Serial communication - Arduino Mega and ESP32

I have an Arduino Mega and an ESP32 that I want to connect by serial communication. The thing is, pins 0 and 1 for RX/TX from Mega are not available because they are covered by a screen shield. So, I decided to use pins 18 and 19 for RX/TX, but with the classic code it doesn't work. How to define that I use pins 18 and 19 instead of 0 and 1? I mention that when connecting to pins 0 and 1, the communication works. I'll attach the code for both boards.
Arduino Mega:

void setup() {
  Serial.begin(9600);
}
void loop() {
  Serial.println("Hello");
  delay(1000);
}

ESP32:

#define RX 16
#define TX 17
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial2.begin(9600, SERIAL_8N1, RX, TX);
}
void loop() {
    Serial.println("Message Received: ");
    Serial.println(Serial2.readString());
}

Do you know how many hardware serial ports the Arduino MEGA has? Why not use an alternate MEGA hardware serial port?

You didn't even attempt a websearch.
I did.
Use Multiple Serial Ports on the Arduino Mega | Arduino Documentation

Mega 2560 Rev3 | Arduino Documentation

Serial1

You should use a voltage divider for the Mega-TX ESP-RX connection to lower the 5V to 3.3V.

Caution:
Use level shifter to connect MEGA and ESP32 as --

1. Connect MEGA and ESP32 using UART2 Ports as per Fig-1 using level shifter.


ESP32-UART-Pins
Figure-1:

2. Upload the following sketches:
MEGA Sketch:

//MEGA
void setup() 
{
  Serial.begin(9600);
  Serial2.begin(9600);  //RX2 = 17, TX2 = 16
}
void loop() 
{
  Serial2.println("Hello"); //sending to ESP32
  delay(1000);
}

ESP32 Sketch:

#define RX2 16
#define TX2 17

void setup()
{
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial2.begin(9600, SERIAL_8N1, RX2, TX2);
}

void loop()
{
  byte n = Serial2.available();
  if (n != 0)
  {
    Serial.println("Message Received: ");
    Serial.println(Serial2.readString());
  }
}

an aletrnative to a level shifter is a potential divider - see Mega_with_ESP-01

basically I have problem with the read.String() that cannot read the data transfer from mega 2560 to esp32 through serial communication2. I hope someone can give to me the solution about my problem

how have you connected the Mega to the ESP32? remember the Mega uses 5V logic the ESP32 3.3V
upload your code (using code tags </>)

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.