Hi I'm new to the forum so I hope this is the correct place to post.
What I trying to do is set up an ESP-01 to an Arduino Uno and then read commands over the Serial Port and write those commands to the ESP-01 via a software serial. The issue I seem to be having with my code is the Command seems to be one message behind. For example if I type AT into the serial port I see that monitor reads it and assigned it to command string but it didn't get sent to the ESP. If I hit enter again in the serial monitor then the previous AT command gets sent. And the expected response of OK is received. How do I correct this so that it does lag behind by one command. Thanks
/ Basic serial communication with ESP8266
// Uses serial monitor for communication with ESP8266
//
// Pins
// Arduino pin 2 (RX) to ESP8266 TX
// Arduino pin 3 to voltage divider then to ESP8266 RX
// Connect GND from the Arduiono to GND on the ESP8266
// Pull ESP8266 CH_PD HIGH
//
// When a command is entered in to the serial monitor on the computer
// the Arduino will relay it to the ESP8266
//
#include <SoftwareSerial.h>
SoftwareSerial ESPserial(2, 3); // RX | TX
// Wifi configuration details
String _ssid = "yourSSID";
String mydata;
String message;
String response;
int cnt=0;
void setup()
{
Serial.begin(9600); // communication with the host computer
//while (!Serial) { ; }
// Start the software serial for communication with the ESP8266
ESPserial.begin(9600);
Serial.println("");
Serial.println("Remember to to set Both NL & CR in the serial monitor.");
Serial.println("Ready");
Serial.println("");
delay(1000);
Serial.println("");
}
void loop()
{
// Serial.flush();
//ESPserial.flush();
while(Serial.available()==0)
{
//Do nothing until something enters the buffer
}
if(Serial.available() > 0)
{
String command = Serial.readStringUntil('\n');
Serial.println("Command Sent: " + command);
message = readWifiSerialMessage(command);
delay(1000);
if(message.length() > 0)
{
Serial.println("Response Received:");
Serial.println(message);
Serial.println("---------");
delay(100);
}
}
}
/*
* Name: readWifiSerialMessage
* Description: Function used to read data from ESP8266 Serial.
* Returns: The response from the esp8266 (if there is a reponse)
*/
String readWifiSerialMessage(String command){
char value[100];
int index_count =0;
//Serial.println("Message Received:");
ESPserial.println(command);
// Serial.println();
while(ESPserial.available())
{
value[index_count]=ESPserial.read();
index_count++;
value[index_count] = '\0'; // Null terminate the string
}
String str(value);
str.trim(); //Removes any leading or trailing whitespace
return str;
}