I am trying to use an ESP8266 module alongside an Arduino Mega and am having some issues getting the Arduino to communicate properly with the ESP8266. I know it CAN talk to the ESP8266 module as I am getting the serial data passed from the ESP8266 into the serial monitor but what I cannot do is send a command and read the response.
My current test code is as follows (this does not work):
void setupWiFi() {
if (sendData("AT\r\n",1000,false) == "AT") {
if (Serial1.find("OK")) {
Serial.print("ESP8266 pinged successfully...");
} else {
Serial.print("ESP8266 did not ping...");
}
}
}
The sendData routine looks like this (And I'm pretty sure that this works correctly):
String sendData(String command, const int timeout, boolean debug)
{
String response = "";
Serial1.print(command); // send the read character to the esp8266
long int time = millis();
while( (time+timeout) > millis())
{
while(Serial1.available())
{
// The esp has data so display its output to the serial window
char c = Serial1.read(); // read the next character.
response+=c;
}
}
if(debug)
{
Serial.print(response);
}
return response;
}
Any ideas or am I missing something blatantly obvious?
The sendData() function returns whatever response it got within the allotted time period. I would find it difficult to believe that the proper response to the AT command is the string "AT". I would expect the device to return "OK".
This will print:Using the markers, we can see that there are no non-printing characters at the start or end of the string (or String (ugh!)).
And, we know what was printed.
Firstly, thank you for this, it actually is surprising how much help brackets around text is! I also think I may have cracked, albeit in a fairly noobish manner. My code is as follows:
if (sendData("AT\r\n",1000,false).indexOf("OK") > 0) {
Serial.print("ESP8266 pinged okay...");
} else {
Serial.println("Doesn't appear to be any response...");
}
Instead of using Serial1.find, I elected to use the indexOf to see if "OK" even existed within the response and if not, I get a -1 returned and know the AT command failed and the ESP8266 kicked up an ERROR.