why not use one of the hardware serial ports for communication with the ESP-01?
e.g. Serial1 on pins 18 and 19 and move whatever is currently using pins 18 and 19 to pins 28 and 29
also the mega uses 5V logic and the ESP-01 3.3V logic - you should use a potential divider on the Mega serial TX to ESP-01 Rx line
Simple example of ESP-01 communicating with a Mega
ESP-01transmits a 010101 pattern over Serial
// ESP8266 - transmit 0101010 in timing loop - read new loop time from keyboard
// Serial 0101010 output will be sent to mega to blink LED
void setup() {
Serial.begin(115200);
}
void loop() {
static long timer=millis();
// send 010101 etc every time interval
static int onoff=0, timeonoff=1000;
if((millis()-timer)>timeonoff) {
timer=millis();
Serial.print(onoff);
onoff=!onoff; // invert value 0 or 1
}
// if text available read next time value
if(Serial.available()==0) return; // wait for serial input
timeonoff=Serial.parseInt(); // read time value
//Serial.println(timeonoff);
delay(10);
while(Serial.available()) Serial.read(); // flush input
}
Mega code receives 01010 pattern over Serial1 to switch LCD OFF/ON
a new blink period in mSec entered on keyboard is transmitted over Serial1 from Mega to ESP-01
// Mega - read Serial1 0101010 input from ESP8266 to blink LED
// ESP-01 transmits 0 or 1 to Serial1 to switch LED OFF/ON
// enter new blink period in mSec on keyboard, e.g. 500 for 0.5sec
void setup() {
Serial.begin(115200);
Serial.println("\nMega to ESP-01 Serial1 test");
Serial.println("ESP-01 transmits 0 or 1 to Serial1 to switch LED OFF/ON");
Serial.println("enter new blink period in mSec on keyboard, e.g. 500 for 0.5sec");
Serial1.begin(115200);
pinMode(LED_BUILTIN, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
// if text available read next time value and send to ESP8266 over Serial1
if (Serial.available() > 0) { // wait for serial input
int timeonoff = Serial.parseInt(); // read time value
Serial1.println(timeonoff); // send to ESP8266
Serial.print("\n\Period in mSec sent to ESP-01 ");
Serial.println(timeonoff);
delay(10);
while (Serial.available()) Serial.read(); // flush input
}
if (Serial1.available() > 0) { // wait for Serial1 input
char ch = Serial1.read(); // should 0 or 1 to blient LED
Serial.print(ch);
if (ch == '0') digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
else digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
}
}
mega serial monitor displays
Mega to ESP-01 Serial1 test
ESP-01 transmits 0 or 1 to Serial1 to switch LED OFF/ON
enter new blink period in mSec on keyboard, e.g. 500 for 0.5sec
01010101010101010101010101
Period in mSec sent to ESP-01 200
010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101Period in mSec sent to ESP-01 5000
1010
Period in mSec sent to ESP-01 500
photo
