0

对不起我的英语不好。我正在尝试在我的 Arduino 上接收来自 Sim800 的 json 数据。要读取串行端口上的数据,我使用了以下代码:

while(serialSIM800.available()==0); //Wait until the data is received
    String content = "";
  while(serialSIM800.available()>0){ // When data is received
    content = content + char(char (serialSIM800.read()));
    }
Serial.print(content);

但收到不完整的数据。如下:

{"id":"1212","temp":"24","hum","4

为了获得更好的结果,我使用了以下代码:

 byte x;
char data[128];
void sim800Reply() {
  x=0;
  do{   
    while(serialSIM800.available()==0);
    data[x]=serialSIM800.read();
    Serial.print(data[x]);
    x++;
  } while(!(data[x-1]=='K'&&data[x-2]=='O'));
}

数据完全接收。如下:

{"id":"1212","temp":"24","hum","45","date":"11.2018","status":"200"}

OK

但是我觉得这个代码不好,有问题。例如如果没有连接sim800时serialSIM800不可用,下面的代码会导致崩溃while(serialSIM800.available()==0);因为这总是正确的或者如果有错误并且OK没有收到,则以下代码导致崩溃while(!(data[x-1]=='K'&&data[x-2]=='O'));因为这总是正确的。最大数据长度为 120 字节,我应该怎么做才能从 Arduino 串口接收 Json 数据?谢谢你们。

4

2 回答 2

0

最后,我将代码更改如下:

 String dump(bool printData) {
      byte while_cunt = 0;
      while (serialSIM800.available() == 0){
        while_cunt++;
        delay(15); // It can change for a proper delay
        if(while_cunt >=250){  // If the data from serial was not received past 3.75 seconds
          Serial.println("return");
          return "";   // Exit from dump function
        }
      }
      String content = "";
      while (serialSIM800.available() > 0) {
        content += serialSIM800.readString();
      }

      if (printData) {
        Serial.println(content);
      }
      return content;
    }

它可以返回和打印串行数据并且它工作速度很快因为每15毫秒检查一次数据是否已收到,如果在一段时间内(在本例中为3.75秒)没有收到数据,它将处于进程之外并且不会崩溃。此函数的示例:

     serialSIM800.println("AT");
     dump(true); 
// print Received response from sim800

    serialSIM800.println("AT");
    String str =  dump(true); 
    // print Received response from sim800 and Saved in variable named 'str'

    serialSIM800.println("AT");
     String str =  dump(false); 
//Save response  in variable named 'str' without print 
于 2018-11-09T17:47:41.240 回答
0

开始尝试:

if (serialSIM800.available()) {
  String content = serialSIM800.readString();
  Serial.print(content);
}

在 setup() 添加serialSIM800.setTimeut(50);

于 2018-11-08T19:24:05.633 回答