2016-02-25 90 views
0

所以我有我的arduino和esp8266 wifi模块。一切正确连接,并发送数据到arduino让我通过AT命令控制连接。 我skletch看起来是这样的:arduino和esp8266 - 如何获得AT命令响应变量

void setup() 
{ 
    Serial.begin(9600); 
    Serial1.begin(9600); 
} 

void loop() 
{ 

    if (Serial.available() > 0) { 
    char ch = Serial.read(); 
    Serial1.print(ch); 
    } 
    if (Serial1.available() > 0) { 
    char ch = Serial1.read(); 
    Serial.print(ch); 
} 

上面的代码让我发送命令,看到ESP响应。尽管有不同的响应时间和不同的答案,但我需要将响应存储在变量中,以便WiFi模块能够创建这样的响应。不幸的是,我不能这样做,因为Serial1.read()只能从Serial1.available()缓冲区中获取一个字符而不是完整的缓冲区。

我想这样的做法:

if (Serial1.available() > 0) { 
     while (Serial1.available() > 0) { 
     char ch = Serial1.read(); 
     Serial.print(ch); 
     response = response.concat(ch); 
     } 
    } else { 
     String response = ""; 
    } 

所以只要疗法EIS在它被发送到concatens最后一个字符与自身反应变量的缓冲区的东西。稍后可以通过indefOf命令搜索“OK”标记或“ERROR”。但是,这并不按预期工作:(例如,可能会打印我的变量8次(不知道为什么)。 我需要wifi模块的完整响应,例如,如果正确命令来自我的arduino板WiFi网络,如果我按上的Arduino到网络按钮,但还发送一些数据的任何想法,将不胜感激

Kalreg

+1

我想推荐你在网上搜索“为什么不在arduino中使用字符串”。如果您不知道为什么以及如何正确使用它,字符串可能会导致问题。如果你继续使用它们,那么至少知道陷阱是什么。尝试实现char数组(C字符串)。 –

回答

1

试试这个相当:。

String response = ""; // No need to recreate the String each time no data is available 
char ch; // No need to recreate the variable in a loop 

while (Serial1.available() > 0) { 
    ch = Serial1.read(); 
    response = response.concat(ch); 
} 

// Now do whatever you want with the string by first checking if it is empty or not. Then do something with it 

还记得清除缓冲区,然后再发送像我之前提问中所建议的命令:how to get AT response from ESP8266 connected to arduino

+0

我试过你的建议,但仍然无法弄清楚什么是错的。我熟悉javascript和php,并且所有那些char,long和String在简单c中的东西都让我发疯。请看我的代码: 'void setup() {Serial.begin(9600); Serial1.begin(115200); Serial1.read(); Serial1.println(“AT”); } void loop() { String response =“”; while(Serial1.available()> 0){char {ch} = Serial1.read(); response + = ch; (response.length()> 0)Serial.println(“{”+ response +“}”);如果(response.length()> 0) } }' 效应初探是: '{A} 横置 { Ø} [KP }' 我期望: '{AT OK}' – Kalreg

+0

不使用串。尝试使用初始长度为200bytes的缓冲区。首先用0x00填充它,然后保持一个索引和索引,填充缓冲区。 –

+0

你没有按照建议去做。你的实现是不同的。不要回避学习如何正确做事。我们并不建议你无缘无故停止使用字符串。有一个原因,这是一个非常好的理由。 –