Search code examples
arduinoesp32serial-communicationatmegaarduino-esp32

Problem with serial communication between Arduino Mega2560 and ESP32


Good morning everyone. I am trying to establish serial communication between an arduino mega and an esp32, in both I am using hardware serials. In the arduino the uart3 in the esp the uart2. I have checked the pin connections several times. I also adapted the arduino's tx signal to the esp32 with a level shifter.

Essentially I need to send a string to the esp32. The code of the arduino is as follows:

  String InvioDatiESP() {
  String da_passare = ("hello!!!"); 
  return(da_passare);
  }

  void setup() {
     Serial.begin(9600);
     Serial3.begin(115200);
  }

  void loop() {
     Serial3.println(InvioDatiESP());
     Serial.println(InvioDatiESP());
     delay(1000);  
  }

I create the string in a function since it is a reduced version of the actual code in which the string is to be composed.

The code of Esp32 is as follows:

#define RXp2 16
#define TXp2 17

void setup() {
   Serial.begin(115200);
   Serial2.begin(115200, SERIAL_8N1, RXp2, TXp2);
}

void loop() {
   Serial.println(Serial2.readString());
}

I correctly set the boudrate in both serial ports on the IDE to verify communication.

The thing I notice that makes me doubt that the problem is related only to the ESP32 reading the string is that in the serial port of the ESP32 in the IDE while the program is running, blank lines are printed on the screen exactly every 1000ms, as if the data is received but not interpreted correctly.

How could I solve this in your opinion? Thanks in advance for the answers!


Solution

  • EDIT: Can you try to lower the boudrate? Check to see if with a lower one it will start decoding properly.

    Your problem is not with the code, it's with the hardware. The arduino Mega2560 is using 5V logic level and ESP32 is using 3.3V. You need to do some level shifting to be able to communicate.

    You can take a look at this article to learn more about it.

    Hope it helps.