Page 1 of 1

UART, RX buffer: shall I "lock" it while I am copying data from it?

Posted: Sat Sep 13, 2025 11:39 pm
by career_changer
Hi guys, I am a beginner in ESP32 programming.

For self-learning purposes, I am planning to write a small program that receives data via UART, and then executes some calculations on the received data. The reception and the calculation with the received data would compose an infinite routine, so consider e.g. a moving average calculator (with a fix moving window size).

I assume that I should avoid calculations directly on the RX buffer data. Instead, I assume that I should copy some part of the RX buffer, i.e., to work with the copy of the recent few bytes received via UART.

To be consistent with the data, I want to assure that the content of the RX buffer does not change while I am copying several bytes from it.

Shall I realize this "protection" by myself, e.g., using mutex in the copy procedure?
Or is this protection already there, working in the UART reception in the background, in the firmware and via the ESP-IDF utilities (the UART-related functions, such as uart_read_bytes().)


Thank you for your help, and sorry if this was a dummy question.

Re: UART, RX buffer: shall I "lock" it while I am copying data from it?

Posted: Sun Sep 14, 2025 10:49 am
by MicroController
uart_read_bytes() is synchronous, thread-safe, and 'atomic' w.r.t. the UART interrupt. So the data you get out of it will not be corrupted by concurrency.

Notice that you provide the buffer where uart_read_bytes() will copy the RX data to. If you don't share that buffer across tasks there will also be no concurrency issue. I.o.w., you cannot access the internal buffers of the UART (driver) directly but will only ever get your own copy in the first place.

Re: UART, RX buffer: shall I "lock" it while I am copying data from it?

Posted: Sun Sep 14, 2025 7:28 pm
by career_changer
Thank you for your professional an informative answer. It sounds great!