Arduino从软件串行接收数据

时间:2018-11-08 19:10:30

标签: json arduino avr sim800 software-serial

对不起,我的英语不好。我正在尝试从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

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

2 个答案:

答案 0 :(得分:0)

开始尝试:

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

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

答案 1 :(得分: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