Arduino缺少数据Serial.println()

时间:2019-08-30 11:01:28

标签: c++ tcp arduino esp8266 arduino-c++

我正在使用通过SoftwareSerial连接到Arduino Uno的ESP8266向模块DHT22捕获的温度值的API发出发布请求。 我在通过TCP连接发送数据时遇到问题,我认为它来自数据的构造方式(可变的postRequest)。

void httppost(){
  String postRequest = String("POST " + uri + " HTTP/1.1\r\n" +
      "Host: " + server + ":" + port + "\r\n" + 
      "Accept: *" + "/" + "*\r\n" + 
      "Content-Length: " + data.length() + "\r\n" + 
      "Content-Type: application/x-www-form-urlencoded\r\n" + 
      "\r\n" + data + "\r\n");
  Serial.println(postRequest);
  delay(3000);
  Serial.flush();
  String tcpStart = "AT+CIPSTART=\"TCP\",\"" + server + "\",\"" + port + "\"";
  String sendCmd = "AT+CIPSEND=" + String(postRequest.length());
  esp.println(tcpStart); //start TCP connection
  delay(3000);
  if(esp.find("OK")){
    Serial.println("TCP connection OK");
    esp.println(sendCmd); //send the data over TCP connection
    delay(3000);
    if(esp.find(">")){
      Serial.println("Sending data");
      esp.println(postRequest);
      delay(3000);
      if(esp.find("SEND OK")){
        Serial.println("Packet sent");
        while(esp.available()){ //number of bytes/char available for reading
          char tmpResp = esp.read(); //read one char at the time
          Serial.print(tmpResp);
          if (tmpResp == '\0') continue; //terminate the while when end of the data
        }
        esp.println("AT+CIPCLOSE"); //close TCP connection
      }else{
        Serial.println("--> An error occured while sending packet");
      }
    }else{
        Serial.println("--> ESP8266 is not listening for incoming data");
    }
  }else{
    Serial.println("--> Cannot initiate TCP connection");
  }
}
  Serial.flush();

我总是得到输出:“-> ESP8266没有监听传入的数据”。 另一件事让我觉得问题出在postRequest变量上,这是因为当我尝试将变量打印到Serial.monitor时,字符串中缺少一些行。 我已经尝试添加Serial.flush()来解决此问题,但会出现延迟,但这都不是解决方案。

0 个答案:

没有答案