Arduino, ESP32 and 3 hardware serial ports

When working with ESP32 WiFi/Bluetooth MCU under Arduino SDK for ESP32, you will notice that Serial work just fine. But Serial1 and Serial2 do not. ESP32 has 3 hardware UARTs that can be mapped to almost any pin. But, Serial1 and Serial2 will not work. In case of ESP32 this just has to be done in a slightly different way:

The trick is to use HardwareSerial library to access UART 1 and 2 instead of Serial1 and Serial2

  • Class HardwareSerial accepts one parameter in constructor, it is a number of UART. Values from 0 (UART 1) to 2 (UART 3)
  • HardwareSerial(0) is the same as Serial so be aware
  • begin method accepts 4 parameters
    • baud speed
    • UART mode
    • RX pin
    • TX pin

The real beauty of this solution is that almost any pin can be used as TX or RX pin for any UART. Most ESP32 dev boards have labels like TX2 or RX2, but you really do not have to exactly those pins. Every other GPIO pin can act as Serial RX, but only the ones between GPIO0 and GPIO31 can be used as TX. Still, that gives plenty of pins to choose from…

2 thoughts on “Arduino, ESP32 and 3 hardware serial ports

  1. I have been trying for a couple of weeks to get the second and third serial ports working. I have tried a lot of different methods but none worked. Your solution worked right off.
    I am using an ESR32 Dev board by Doit with a Nextion screen running off Ubuntu Linux.

    Thanks very much for the solution.

    Ron Hunter

  2. Thank you so much for the explanation of the 3 serial ports. I too am using the Nextion screen.
    good stuff!

    Jim Cullins

Leave a Reply

Your email address will not be published.