Monday, May 15, 2017

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.
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 more Serial port, you just create another instance of HardwareSerial such as: HardwareSerial Serial1(1) or HardwareSerial Serial2(2) and then use them as usual.
We will make a simple demo that print string “hello ESP32” every 1 second on Terminal. This demo is easy. To monitor “printed” data just go to Tools > Serial Monitor
4. Result


Figure: ESP32 using Serial to print debug information

0 comments: