Chapter 2. API Reference
Running UART Communication Serial communication is controlled by each UART controller’s finite state
machine (FSM).
The process of sending data involves the following steps:
1. Write data into Tx FIFO buffer
2. FSM serializes the data
3. FSM sends the data out
The process of receiving data is similar, but the steps are reversed:
1. FSM processes an incoming serial stream and parallelizes it
2. FSM writes the data into Rx FIFO buffer
3. Read the data from Rx FIFO buffer
Therefore, an application will be limited to writing and reading data from a respective buffer using
uart_write_bytes() and uart_read_bytes() respectively, and the FSM will do the rest.
Transmitting After preparing the data for transmission, call the function uart_write_bytes() and pass the
data buffer’s address and data length to it. The function will copy the data to the Tx ring buffer (either immediately
or after enough space is available), and then exit. When there is free space in the Tx FIFO buffer, an interrupt service
routine (ISR) moves the data from the Tx ring buffer to the Tx FIFO buffer in the background. The code below
demonstrates the use of this function.
// Write data to UART.
char* test_str = "This is a test string.\n";
uart_write_bytes(uart_num, (const char*)test_str, strlen(test_str));
The function uart_write_bytes_with_break() is similar to uart_write_bytes() but adds a serial
break signal at the end of the transmission. A‘serial break signal’means holding the Tx line low for a period longer
than one data frame.
// Write data to UART, end with a break signal.
uart_write_bytes_with_break(uart_num, "test break\n",strlen("test break\n"), 100);
Another function for writing data to the Tx FIFO buffer is uart_tx_chars(). Unlike
uart_write_bytes(), this function will not block until space is available. Instead, it will write all data
which can immediately fit into the hardware Tx FIFO, and then return the number of bytes that were written.
There is a ‘companion’function uart_wait_tx_done() that monitors the status of the Tx FIFO buffer and
returns once it is empty.
// Wait for packet to be sent
const uart_port_t uart_num = UART_NUM_1;
ESP_ERROR_CHECK(uart_wait_tx_done(uart_num, 100)); // wait timeout is 100 RTOS␣
,→ticks (TickType_t)
Receiving Once the data is received by the UART and saved in the Rx FIFO buffer, it needs to be retrieved using
the function uart_read_bytes(). Before reading data, you can check the number of bytes available in the
Rx FIFO buffer by calling uart_get_buffered_data_len(). An example of using these functions is given
below.
// Read data from UART.
const uart_port_t uart_num = UART_NUM_1;
uint8_t data[128];
int length = 0;
ESP_ERROR_CHECK(uart_get_buffered_data_len(uart_num, (size_t*)&length));
length = uart_read_bytes(uart_num, data, length, 100);
If the data in the Rx FIFO buffer is no longer needed, you can clear the buffer by calling uart_flush().
Espressif Systems 460
Submit Document Feedback
Release v4.4