I've been trying to get an Arduino and ESP8266 to communicate with each other over serial. The ESP8266 uses the Serial
class for communications, while the Arduino uses SoftwareSerial
.
The problem is that when I try to send data from the Arduino to the ESP8266, only the first character of the string sent gets received by the ESP8266. For example, if I send a string "leather", the ESP8266 only receives an 'l'. Both devices are operating at 38400 baud, although I have tried 9600 baud with similar results (apparently SoftwareSerial
is more reliable at lower baud rates).
Here is the relevant code that's running on both devices:
Arduino code:
#include <stdlib.h>
#include <SoftwareSerial.h>
#define COMMAND_TILT 'c'
#define SOFTWARE_SERIAL_BAUD_RATE 38400
#define ESP_RX 8
#define ESP_TX 9
SoftwareSerial esp(ESP_RX, ESP_TX);
void setup()
{
...
esp.begin(SOFTWARE_SERIAL_BAUD_RATE);
...
}
void loop()
{
if (esp.available() > 0) {
String data;
while (esp.available() > 0) {
data += (char) esp.read();
}
char command = data.charAt(0);
data.remove(0, 1);
int value = data.toInt();
char buf[STR_BUF_LEN];
switch (command) {
case COMMAND_TILT:
...
sprintf(buf, "%c%d", COMMAND_TILT, value);
esp.write(buf);
break;
...
}
}
delay(100);
}
...
ESP8266 code:
#define SERIAL_BAUD_RATE 38400
void setup()
{
...
Serial.begin(SERIAL_BAUD_RATE);
...
}
void loop()
{
...
if (Serial.available() > 0) {
String data;
while (Serial.available() > 0) {
data += (char) Serial.read();
}
char command = data.charAt(0);
data.remove(0, 1);
// problem: now, data.c_str() is blank when it should contain an integer in string format
...
delay(100);
}
}
...
If it helps to know, I'm running an MQTT client on the ESP8266 and controlling some steppers and relays on the Arduino.
write()
calls and still get it in one piece on the Arduino side. But even if I send the data in one buffer the other way around, the ESP only gets the first character. For any gaps in data, shouldn't theSerial.available()
calls take care of things? Or do you mean something else entirely?Serial.available()
returns the count of bytes in RX buffer. but at 9600 baud the bytes are coming very slow