Roger
Roger

Reputation: 2135

Serial Communication between two ESP32

I have found examples of basic arduino to arduino serial communication but have been unable to get those working on ESP32 boards. I am trying to make the same thing work between two ESP32's The two are connected:

esp1   esp2
gnd to gnd
tx2 to rx2
rx2 to tx2

Simple sketches:

//transmit sketch
void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.println("test...");
  delay(1000);
}

//receive sketch
void setup() {
  Serial.begin(9600);
}

void loop() {
  String received = "";
  while (Serial.available())
  {
    received = Serial.read();
    Serial.println(received);
  }
}

What else is required to make this work?

Upvotes: 3

Views: 20220

Answers (2)

Axi
Axi

Reputation: 41

All the following criteria should be meet to make it work:

  1. ESP32 board should not use the serial port you want to use to any embedded feature. So it should be free to use.

  2. Make sure you are using the right pins:

    U Rx Tx
    Serial 40 41
    Serial1 9 10
    Serial2 16 17
  3. Make sure lines are crossed, so Tx is bind to Rx on the other board and vice versa.

  4. Make sure that the speed is the same on both board.

To see the result both ESP32 board should be connected to the PC via USB and a console should attached to the USB ports. You can use putty for this purpose to connect the USB ports. Two instances can be run for the two USB port. Make sure the speed setup in putty is the same as it is in the code. Whatever you type in one console will be transferred and will appear on the other console.

Upload this code to both ESP32 board:

HardwareSerial &hSerial = Serial1; //can be Serial2 as well, just use proper pins

void setup() 
{
  Serial.begin(115200);//open serial via USB to PC on default port
  hSerial.begin(115200);//open the other serial port
}

void loop() 
{  
  if (Serial.available()) //check incoming on default serial (USB) from PC
      { 
        hSerial.write(Serial.read());   // read it from UBS and send it to hSerial 
      }

  if (hSerial.available()) //check incoming on other serial from the other board
      { 
        Serial.write(hSerial.read());   //read it from hSerial and send it to  UBS
      }
}

Upvotes: 3

user7125259
user7125259

Reputation:

I think your code comes from a simpler world in which pins were always fixed and one UART was all you had available. With the ESP32 you should probably look for a solution more along these lines:

#include <HardwareSerial.h>

HardwareSerial Serial2(2); // use uart2

Serial2.begin(19200, SERIAL_8N1, 16, 17); // pins 16 rx2, 17 tx2, 19200 bps, 8 bits no parity 1 stop bit

I hope this helps. If you still have problems after this, they're likely to be either a) the board you're using doesn't use 16 & 17 for rx2 & tx2, or b) you need 10k pull-up (not series) resistors on both lines to stop them "floating" - however some boards take care of the pull-ups for you.

Upvotes: 8

Related Questions