Demo 2: How to use multiple Serial ports on Arduino ESP32

1. Introduction
Arduino ESP32 use Serial port to flash software and print information on Terminal. ESP32 supports 3 Serial ports so you need not to use SoftwareSerial as in general Arduino. In this tutorial we only care about using How to use multiple Serial port on Arduino ESP32 to print the debug information to Terminal.
2. Hardware
You do not need any extra hardware. Just connect RX pin G16 with TX pin G17.
3. Software
We use "HardwareSerial" class for Serial communication. It has some important interfaces:
- HardwareSerial(int uart_nr): this is the constructor of HardwareSerial where uart_nr is 0, 1 or 2 so we have maximum 3 Serial ports.

- void begin(unsigned long baud, uint32_t config=SERIAL_8N1, int8_t rxPin=-1, int8_t txPin=-1): initialize Serial port with baudrate, Serial mode (default is SERIAL_8N1), rxPin and txPin (if you leave these parameters empty library will use default pins).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
void HardwareSerial::begin(unsigned long baud, uint32_t config, int8_t rxPin, int8_t txPin)
{
    if(_uart_nr == 0 && rxPin < 0 && txPin < 0) {
        rxPin = 3;
        txPin = 1;
    }
    if(_uart_nr == 1 && rxPin < 0 && txPin < 0) {
        rxPin = 9;
        txPin = 10;
    }
    if(_uart_nr == 2 && rxPin < 0 && txPin < 0) {
        rxPin = 16;
        txPin = 17;
    }
    _uart = uartBegin(_uart_nr, baud, config, rxPin, txPin, 256, false);
}
- available(): Get the number of bytes (characters) available for reading from the serial port.
- print(): Prints data to the serial port as human-readable ASCII text.
- println(): Prints data to the serial port as human-readable ASCII text followed by a carriage return character (ASCII 13, or '\r') and a newline character (ASCII 10, or '\n').
- read(): Reads incoming serial data on Rx pin.
- readStringUntil(): reads characters from the serial buffer into a string until facing terminator character.
- Because Arduino library created a default instance HardwareSerial Serial(0), so you can use created Serial object directly (in example below) without create an instance by yourself.
- In order to use multiple Serial ports, you just use default instances of HardwareSerial such as: Serial1 or Serial2 and then use them as usual.
We will make a simple demo that The Hardware Serial2 will get the data from Serial and the Serial will print the data that Serial2 got. Go to Tools > Serial Monitor. Type something in the text box and see the data will be printed on Terminal.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#include <HardwareSerial.h>

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  // set the data rate for the HardwareSerial port
  Serial2.begin(115200);
}

void loop() {
  if (Serial2.available()) {
    Serial.write(Serial2.read());
  }
  if (Serial.available()) {
    Serial2.write(Serial.read());
  }
}

Post a Comment

1 Comments