0

我正在使用通过 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(), 延迟来解决这个问题,但这些都不是解决方案。

4

0 回答 0