What the standard asks
Section 6, Embedded systems programming, is worth 25% of the marks (WorldSkills Occupational Standards, Electronics, WorldSkills Shanghai 2026, checked 2026-11-25). It asks you to connect a microcontroller to outside devices, and to write code that reads data and controls equipment. A serial command interface does both: a PC, a panel or another board sends a line, and your board acts and answers.
The section page sent text with HAL_UART_Transmit. Sending is the easy half. This lesson is about receiving: never losing a byte, never blocking, and never trusting what arrives. You set the UART up in STM32CubeMX and receive with the HAL's interrupt functions, on a NUCLEO-F103RB. Its USART2 reaches your PC through the ST-LINK's USB cable as a virtual COM port, so you need no adapter (UM1724, the Nucleo-64 user manual).
The theory
How long a byte takes
A UART frame in 8N1 is 10 bits: a start bit, 8 data bits and a stop bit. At 115 200 baud a byte takes 10 ÷ 115 200 = 86.8 µs, so up to 11 520 bytes arrive each second.
The STM32F103's USART holds one received byte in its data register while the next one comes in through its shift register (RM0008, USART). If the program has not read the first byte when the second is complete, the overrun flag ORE is set and a byte is lost. At 115 200 baud that leaves 86.8 µs. A main loop that polls the USART itself, or waits in HAL_UART_Receive, and ever does anything longer will lose bytes.
An interrupt fixes this. The receive interrupt runs within microseconds of each byte, whatever the main loop is doing.
The baud rate is a divider too
USART2 sits on APB1, at 36 MHz. It divides that clock by 16 × USARTDIV, and its BRR register holds USARTDIV in sixteenths. For 115 200 baud, 36 MHz ÷ (16 × 115 200) = 19.53. The HAL rounds it to 19 and 8/16 = 19.5, and writes BRR = 0x138 (stm32f1xx_hal_uart.h, UART_BRR_SAMPLING16). The real rate is 36 MHz ÷ (16 × 19.5) = 115 385 baud, +0.16%: far inside what a receiver accepts. You can read BRR yourself in CubeIDE's SFRs view. The code or board lesson shows when a baud error is too big.
The ring buffer
The receive callback stores each byte in a ring buffer and returns. The main loop takes bytes out when it is ready.
- One writer for each index. The callback writes only
rx_head; the main loop writes onlyrx_tail. They never write the same variable, so no lock is needed. - Empty and full. Empty when head equals tail. Full when head + 1 equals tail: one slot always stays empty, so full and empty never look the same.
- A power-of-two size. With 64 bytes the index wraps with
& 63, one instruction, instead of a division. - Indexes read in one go. A 16-bit variable is read in one instruction on the Cortex-M3, so the interrupt cannot change it halfway through a read.
How big? Big enough for what arrives while the main loop is busy. 64 bytes hold 63 × 86.8 µs = 5.5 ms of non-stop input at 115 200 baud. If your longest pass of the loop is 2 ms, that is plenty. If one function blocks for 20 ms, it is not: make that function shorter, or the buffer bigger.
From bytes to lines
A command ends with a line ending, and terminals disagree about it. Some send LF, PuTTY sends CR when you press Enter, and many test scripts send both. Accept CR, LF or both, and treat an empty line as nothing, so the LF after a CR is not a second command.
Set a length limit. Refuse a line that is too long as a whole, with an error. Never cut it short and run what is left: PWM 100 cut to 6 characters is PWM 10, a different valid command.
Parse, check, answer
- Make the line upper case once, so
led onandLED ONare the same. - Compare whole commands with
strcmp, not the first few letters. - Read numbers with
strtoland its end pointer.atoi("4O")(with a letter O) returns 4 and says nothing.strtoltells you where it stopped, so you can refuse anything after the number. - Check the range before you act. A duty of 140% is an error, not 100%.
- Answer every command, starting with
OKorERR. A person sees at once what happened, and a test script can check it.
Receiving with the HAL
In CubeMX, set USART2 to Asynchronous at 115 200 baud, 8N1, and tick USART2 global interrupt in its NVIC Settings. Then three HAL functions do the work (ST's F1 HAL, version 1.1.10, stm32f1xx_hal_uart.c):
HAL_UART_Receive_IT(&huart2, &rx_byte, 1)asks for one byte under interrupt, and returns at once.- When the byte has arrived, the HAL calls
HAL_UART_RxCpltCallback(huart). Put the byte in the ring there, and ask for the next byte at once, inside the callback. - When a byte arrives with a framing, noise or overrun error, the HAL calls
HAL_UART_ErrorCallback(huart). After an overrun it may also have stopped receiving. Start receiving again in that callback, or the board goes deaf after one bad byte. If reception is still running, the call just returnsHAL_BUSYand changes nothing.
The HAL's own callbacks are weak: they do nothing, and a function you write with exactly the same name replaces them. One callback serves every UART, so check huart->Instance == USART2 first. The callback runs inside the interrupt, so keep it to a few lines.
HAL_UART_Transmit blocks until the last byte has gone: a 20-character reply takes 1.7 ms at 115 200 baud. That is fine for short replies. Long reports need HAL_UART_Transmit_IT or DMA, or they hold up everything else.
DMA, for long or fast input
The DMA can move the bytes into memory with no work from the CPU. HAL_UARTEx_ReceiveToIdle_DMA(&huart2, buffer, size), with the DMA in circular mode, fills the buffer round and round. The HAL calls HAL_UARTEx_RxEventCallback(huart, Size) when the line goes quiet, and when the buffer is half and fully written. Size says how far into the buffer the DMA has written. The CubeMX sheet in the downloads has the settings and the code. Learn the interrupt version first: it is the one you can debug in a hurry.
Worked example
The brief. A NUCLEO-F103RB takes four commands at 115 200 baud on its virtual COM port: LED ON and LED OFF (LD2, on PA5), PWM n (0 to 100% on PA0) and ADC? (the knob on PA1, raw and in millivolts). Every reply starts with OK or ERR.
- CubeMX. Start from the timers project: TIM2 PWM on PA0 at 1 kHz (PSC 71, ARR 999), ADC1_IN1 on PA1, PA5 as an output. Add USART2: Asynchronous, 115 200, 8N1, with USART2 global interrupt ticked.
- Receive. In USER CODE 2,
HAL_UART_Receive_IT(&huart2, &rx_byte, 1)asks for the first byte. The receive callback stores each byte in a 64-byte ring and asks for the next one. - Lines. Up to 31 characters, made upper case, ended by CR or LF.
- PWM. duty = CCR1 ÷ (ARR + 1), so
PWM 40writes CCR1 = 40 × 1000 ÷ 100 = 400 with__HAL_TIM_SET_COMPARE: exactly 40.0%. - ADC. The 12-bit ADC gives 0 to 4095 for 0 to 3.3 V. mV = (raw × 3300 + 2048) ÷ 4096, in 32-bit maths. Adding 2048 rounds to the nearest millivolt.
- Test every line of the brief, and the wrong inputs too. Lines starting with
>are what you type:
READY
> led on
OK LED ON
> PWM 40
OK PWM 40
> pwm 140
ERR PWM needs a number from 0 to 100
> ADC?
OK ADC 2048 1650 mV
> hello
ERR unknown command
With the knob at half travel, raw is about 2048, and 2048 × 3300 ÷ 4096 = 1650 mV. Check it with your meter on PA1. Then paste a line of 40 characters: the answer is ERR line too long, and the next command still works.
Finally set the terminal to 9600 baud and type. The board answers ERR framing or overrun: check the baud rate, but at 115 200 baud, so your terminal shows rubbish or nothing. Go back to 115 200: the first answer may be an ERR, because the line still holds the rubbish bytes, and every command after it must work. A board that goes deaf here fails the brief.
- Debug. Put a breakpoint in
HAL_UART_RxCpltCallbackand type one character: the program stops there, with the character inrx_byte. Then open the SFRs view and read USART2's BRR: 0x138.
Practice task
- Build the project from
uart_commands_cubemx.md, adduart_commands_user_code.c, run the test list above and tick each line. - Add
BLINK n: LD2 blinks n times a second, 0 to 10, without blocking. UseHAL_GetTick()as in the timers lesson. - Add
STATUS?, which answers in one line: the LED, the PWM duty and the ADC reading. - Before you write the code, write a test list: every command, a value just inside and just outside each range, a wrong word, an empty line, a line too long. Swap lists with a partner and run theirs on your board.
- Delete the
HAL_UART_Receive_ITcall inside the receive callback, build, and type a command. Predict what happens before you try it, then put the line back. - When the interrupt version passes every test, move the receive to DMA with part 8 of the CubeMX sheet, and run the same test list again.
Common mistakes
- Doing the work in the callback. It runs inside the interrupt, so parsing or printing there holds up every interrupt of the same or lower priority. The callback stores the byte; the main loop does the rest.
- Not asking the HAL for the next byte in the receive callback, or after an error. The board takes one byte, then never another.
- USART2 global interrupt not ticked in CubeMX.
HAL_UART_Receive_ITreturnsHAL_OK, and the callback never runs. - A callback with a slightly different name or arguments. It compiles, and the HAL's empty weak version runs instead. Copy the name from stm32f1xx_hal_uart.h.
- No length check. A long line runs past the end of the array and overwrites other variables.
atoifor numbers. It cannot tell you that "4O" was not a number.- Blocking sends inside a timed loop. Each 20-character reply costs 1.7 ms at 115 200 baud.
- A breakpoint left in the receive callback. While the program is stopped, the bytes that follow are lost.
- Testing only the commands that work. An Expert tries the wrong ones too.
Self-check
- How long does one 8N1 byte take at 115 200 baud, and how many bytes can arrive in a second?
- A main loop polls USART2 itself and sometimes runs a 2 ms task. At 115 200 baud, why does it lose bytes, and what fixes it?
- A 64-byte ring buffer has head = 10 and tail = 11. Is it empty or full, and how many bytes are waiting?
- Why does the receive callback write only
rx_head, and the main loop onlyrx_tail? - What is wrong with keeping the first 31 characters of a 40-character line and running them?
PWM 33arrives. What CCR1 does the download write at 1 kHz (ARR = 999), and at 25 kHz (PSC = 0, ARR = 2879)? What is the real duty each time?- Your board takes the first character you type, then nothing more. What is the most likely cause? And if instead it works for an hour and then goes deaf, what do you check?
Show answers
- 10 bits ÷ 115 200 baud = 86.8 µs a byte, so 11 520 bytes a second.
- The STM32F103's USART holds one received byte while the next comes in, so each byte must be read within 86.8 µs. In 2 ms about 23 bytes arrive, so nearly all of them are lost to overrun. Receive under interrupt into a ring buffer, so each byte is taken within microseconds.
- Full. Head + 1 = 11 = tail, the full condition, so 63 bytes are waiting: one slot is always left empty.
- With one writer for each index, the callback and the main loop never write the same variable, so no lock and no disabling of interrupts is needed. Each index is read in one instruction, so a read cannot be torn.
- The cut line can be a different valid command (
PWM 100cut short isPWM 10), and the board acts on something nobody sent. Refuse the whole line with an error. - At 1 kHz: (33 × 1000 + 50) ÷ 100 = 330, exactly 33.0%. At 25 kHz: 33 × 2880 ÷ 100 = 950.4, which the integer maths rounds to 950: 950 ÷ 2880 = 32.99%. Say so in your report if the brief asks for exact percentages.
- The first: the receive callback does not call
HAL_UART_Receive_ITagain, so only one byte was ever asked for. The second: an error, most likely an overrun, stopped reception, andHAL_UART_ErrorCallbackdoes not start it again.
Downloads
- uart_commands_cubemx.md: our CubeMX settings for the worked example on a NUCLEO-F103RB: USART2 with its interrupt, the terminal, what to check in the generated code and the SFRs view, and the settings and code for receiving by DMA.
- uart_commands_user_code.c: the code for the USER CODE blocks of
main.c: the receive and error callbacks, the ring buffer, the line reader, the four commands and their checks. We built it against ST's F1 HAL with no errors and no warnings.
Practise in ARGYNIX Lab
The Lab runs Arduino-style code on an Uno or a Blue Pill, so this project is the same idea on the Uno: the same ring buffer, line reader, commands and replies. Only the receive differs. The sketch has its own receive interrupt for the ATmega328P's USART0, and never uses Serial, because the core's receive interrupt and yours cannot both exist. The Uno's numbers differ too: its ADC is 10-bit with a 5 V reference, so half travel reads 512 and 2500 mV, and its Timer0 has 256 steps, so PWM 40 gives (101 + 1) ÷ 256 = 39.8%.
Open the serial command project in ARGYNIX Lab (புதிய தாவலில் திறக்கும்): an Uno with a knob on A0, an LED on D6 and an LED on D13, running uart_commands_lab.ino, a sketch that also runs on a real Uno. It opens running, and the Serial page shows READY.
Type in the box under the Serial page and press Send. The line ending is set to Newline. Run the test list from the worked example: led on, PWM 40, pwm 140, ADC?, hello. Turn the knob and send ADC? again. After PWM 40, open the Logic page: D6 reads about 40%.
Then try to break it. Send a line of 40 characters, then a good command: it must still work. Send PWM 4O with a letter O, and PWM with nothing after it: each must get an ERR. Set the line ending to "No ending" and send a command: nothing happens, because the board waits for the end of the line. Then add BLINK n from the practice task to the sketch and test the idea here. The Lab does not check the baud rate, and the HAL callbacks are the STM32 part, so do the 9600 baud test and the callback tests on the NUCLEO-F103RB.
Run it in your browser, then do it again on your own board.
Open in ARGYNIX Lab (புதிய தாவலில் திறக்கும்)