2

I am new to arduino coding. I am reading data from serial port and storing it in char array. I want to send that data to the local server but it is not getting converted to string

Code :

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
ESP8266WebServer server;
char* ssid = "Office RTPL";
char* password = "********";
char data[64];
char data1[64];
String str;
void setup()

{
  // put your setup code here, to run once:
  WiFi.begin(ssid,password);
  Serial.begin(115200);
  while(WiFi.status()!= WL_CONNECTED)
  {
    Serial.print(".");
    delay(500);
  }
  Serial.println("");
  Serial.print("IP Address: ");
  Serial.print(WiFi.localIP());
  server.on("/",[](){server.send(200,"text/plain","Data Test");});
  server.on("/toggle",serialData);
  server.begin();
}
void loop() 
{
  // put your main code here, to run repeatedly:
  server.handleClient();
 ;
}
void serialData()
{
  if(Serial.available() > 0)
      {

        server.send(200,"text/plain","Data");
         for(int n=0; n<64; n++)
         {
           data[n] = (Serial.read());

         } 
         String str (data);
         server.send(200,"text/plain",str);


  else 
        {
        String no_data = "No Serial Data";
        server.send(200,"text/plain",no_data);
        delay(5000);
        }


}

Please help

1

As I mention in my answer about serial communication:

Before reading, always make sure data is available. For example, this is wrong:

if (Serial.available ())
  {
      char a = Serial.read ();
      char b = Serial.read ();  // may not be available
  }

The Serial.available test only ensures you have one byte available, however the code tries to read two. It may work, if there are two bytes in the buffer, if not you will get -1 returned which will look like 'ÿ' if printed.

In your code:

if(Serial.available() > 0)
    {
    server.send(200,"text/plain","Data");
     for(int n=0; n<64; n++)
     {
       data[n] = (Serial.read());

So you know that one byte is available, but you are reading 64. No, that won't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.