ESP32 | Basics 05 – Serial Communication

01

Overview

Serial communication, known in English as Serial Communication, is a method of transmitting data bit by bit. It is a general term for this type of communication, with specific implementation protocols includingUART, TTL, RS232, RS485, etc.

UART (Universal Asynchronous Receiver/Transmitter) is a general-purpose asynchronous transceiver. The ESP32 integrates three UART controllers:

  • UART0: Typically used for USB CDC debugging output, connected to the onboard USB-to-serial chip, with the default TX pin as GPIO43 and the default RX pin as GPIO44.
  • UART1: Pins can be remapped, commonly used as the first general-purpose serial port, with the default TX pin as GPIO17 and the default RX pin as GPIO18.
  • UART2: Pins are fully configurable, used as the second general-purpose serial port, with no default pins.

02

API Documentation

2.1 Initialization

  • Here we use UART1, where tx is the data transmission pin, rx is the data reception pin, and the baud rate is set to 115200.

import machine
uart = machine.UART(1, tx=machine.Pin(2), rx=machine.Pin(4), baudrate=115200)

2.2 Receiving Data

  • uart.any() checks if there is any data received;

  • uart.read() reads data, allowing you to specify the number of bytes to read; uart.read(1) reads one byte, and if no byte count is specified, it reads all data.

  • uart.readline() reads a line of data from the serial port

  • uart.readinto(buf) reads data into and saves it to a buffer

while uart.any():
    response = uart.read()

2.3 Writing Data

  • Write (send) data to the serial port, returning the length of the data

uart.write("$0,0,1#")

2.4 Deinitialization

uart.deinit()

03

Project Practice

ESP32 | Basics 05 - Serial Communication

ESP32 | Basics 05 - Serial CommunicationProgram Explanation

There is a voice recognition module that uses serial communication for data exchange. First, initialize the pins, connecting RX to pin 16 and TX to pin 17, with a baud rate of 9600. Then, continuously loop to check if there is any data returned in the uart. When I say a voice command, the voice recognition module can recognize it, and a recognition symbol will be printed out.

ESP32 | Basics 05 - Serial CommunicationNote: uart operates in full-duplex mode, maintaining a one-to-one relationship between the device and the serial port. If there are multiple devices and not enough serial pins, you can call the deinit method to unload the existing pin initialization and then reinitialize new pins.

ESP32 | Basics 05 - Serial Communication

Students who need accessories can go to my Taobao store with the same name to purchase.

ESP32 | Basics 05 - Serial CommunicationFollow me for more sharingWeilan Classroom

Leave a Comment