Issue with communication between arduino mega and nodemcu esp 8266

To be clear:

Serial.write(1) ;  // writes the value 0x01
Serial.print(1); // writes the value 1 as the ASCII representation = 0x31
Serial.print('1')';  //  writes the single character '1' = 0x31
Serial.print("1"); // writes the 1 char array which is also 0x31

On the receiving side, you always read an int so make sure you test properly

if (Serial.read() == 1);  // matches Serial.write(1)
if (Serial.read() == '1'); // matches Serial.print(1), Serial.print('1') or Serial.print("1")
if (Serial.read() == "1");  // never works since "1" is a string

You also have to be aware that the Mega runs at 5V and the ESP2866 runs at 3.3V so you should not be wiring the Rx/Tx lines directly.

2 Likes