简体   繁体   中英

Arduino Uno r3 with wifi error when uploading string to database

Im having trouble transmitting a string from my uno, to an ESP8266 and then onto a database. Instead of displaying "Low" and directed in the uno program, its displaying each character of low on the table on my webpage instead of the whole world. (see attached image).

Code for Arduino Uno:

// send as 
String test = "Low";
void setup() 
{
    Serial.begin(115200);  
    // wait for the serial port to connect. Required for Leonardo/Micro native USB port only
    while (!Serial) {  ;  }
}


void loop() 
{
  Serial.print(test);

}

Code for onboard ESP8266:

#ifdef ESP32
  #include <WiFi.h>
  #include <HTTPClient.h>
#else
  #include <ESP8266WiFi.h>
  #include <ESP8266HTTPClient.h>
  #include <WiFiClient.h>
#endif

#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

char c []= "";
// Replace with your network credentials
const char* ssid     = "*****";
const char* password = "****";

// REPLACE with your Domain name and URL path or IP address with path
const char* serverName = "******";

// Keep this API Key value to be compatible with the PHP code provided in the project page. 
// If you change the apiKeyValue value, the PHP file /post-esp-data.php also needs to have the same key 
String apiKeyValue = "****";

String humidityValue;

void setup() {
  Serial.begin(115200);

  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) { 
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
}

void loop() {

  if(Serial.available())
  {
    char c = Serial.read();
    delay(100);
    humidityValue = c;
    Serial.print(humidityValue);
   }

  //Check WiFi connection status
  if(WiFi.status()== WL_CONNECTED){
    HTTPClient http;
    http.begin(serverName);
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");
    String httpRequestData = "api_key=" + apiKeyValue + "&humidity=" +    humidityValue + "";
    int httpResponseCode = http.POST(httpRequestData);
    delay(1000);
    http.end();    
  }
  delay(1000);
}

在此处输入图片说明

You are only reading one character at a time:

 char c = Serial.read();

char is one character, not a whole string.

You could read a whole string, but then you will just get whatever happens to have already arrived, which might be timing dependent. You are sending LowLowLowLowLow... so there is no way for the receiver to know where the string ends.

Maybe send "Low\\n" instead, then in the receiver side, keep reading characters until you see the '\\n' and then process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM