simple test sending text messages between the Mega and ESP8266 at 115200baud
connecting Mega hardware Serial1 (pins 18 TX1 and 19 RX1) to ModeMCU ESP-12E using SoftwareSerial pins D5 (RX) and D6 (TX)
Mega code
// Arduino Mega serial1 test
// mega pin 18 is Tx
// pin 19 is Rx
// for loopback test connect pin 18 to pin 19
// for RS232 shield connect pin 18 to Tx and pin 19 to Rx
// for loopback test connect 9 pin D connector pins 2 and 3
unsigned long time;
void setup() {
Serial.begin(115200); // initialise serial monitor port
Serial1.begin(115200); // initialise Serial1
Serial.write("Arduino Mega Serial1 test - for loopback test connect pin 18 to pin 19\n");
}
void loop() {
if (Serial1.available()) // read from Serial1 output to Serial
Serial.write(Serial1.read());
if (Serial.available()) { // read from Serial outut to Serial1
int inByte = Serial.read();
//Serial.write(inByte); // local echo if required
Serial1.write(inByte);
}
}
ESP8266 code
// ESP8266 SoftwareSerial
// https://circuits4you.com/2016/12/14/software-serial-esp8266/
#include <SoftwareSerial.h>
// pins Rx GPIO14 (D5) and Tx GPIO 12 (D6)
SoftwareSerial swSer(14, 12);
void setup() {
Serial.begin(115200); //Initialize hardware serial with baudrate of 115200
swSer.begin(115200); //Initialize software serial with baudrate of 115200
Serial.println("\nESP8266 Software serial test started");
}
void loop() {
while (swSer.available() > 0) { //wait for data at software serial
Serial.write(swSer.read()); //Send data recived from software serial to hardware serial
}
while (Serial.available() > 0) { //wait for data at hardware serial
swSer.write(Serial.read()); //send data recived from hardware serial to software serial
}
}
mega Serial monitor output as text is entered in ESP8266 serial monitor
06:05:01.387 -> Arduino Mega Serial1 test - for loopback test connect pin 18 to pin 19
06:05:49.661 -> esp8266 test 1 hello
06:06:07.058 -> esp8266 test 2 12345678901234567890
06:06:24.805 -> esp8266 test 3 abcdefghijklmnop
ESP8266 Serial monitor output as text is entered in Mega serial monitor
06:04:56.924 -> ESP8266 Software serial test started
06:05:14.329 -> mega test1 hello
06:05:23.875 -> mega test 2 1234567890
06:05:36.124 -> mega test 3 abcdefghij
remember to have a voltage divider on the Mega TX1 pin18 (5V logic) to ESP8266 Rx pin D5 (3.3V logic), e.g.
