# CubeMX settings: Serial commands

ARGYNIX Skills (worldskills.blog), lesson "Serial commands: an interrupt-driven UART".
Our own settings sheet for the worked example: four commands over USART2 at 115200 baud,
received byte by byte under interrupt. Board: NUCLEO-F103RB. The code to add is in
`uart_commands_user_code.c`.

Labels are as STM32CubeMX 6 shows them. If one reads a little differently in your version,
look for the same word nearby. Part 6 tells you whether every setting really reached the
code.

## 1. Start from the timers project

Open the project from the timers lesson (`timers_pwm_cubemx.md`): 72 MHz from the
ST-LINK's 8 MHz, SYS Debug Serial Wire, TIM2 PWM on PA0 at 1 kHz (PSC 71, ARR 999),
ADC1_IN1 on PA1, PA5 as GPIO_Output. Save it under a new name (File > Save Project As),
then add the UART.

## 2. Pinout & Configuration

| Where | Setting | Value | Why |
|---|---|---|---|
| Connectivity > USART2 | Mode | Asynchronous | CubeMX puts TX on PA2 and RX on PA3. On the Nucleo these go to the ST-LINK, which shows them on the PC as a virtual COM port. |
| | Hardware Flow Control (RS232) | Disable | |
| USART2 > Parameter Settings | Baud Rate | 115200 Bits/s | |
| | Word Length | 8 Bits (including Parity) | |
| | Parity | None | |
| | Stop Bits | 1 | 8N1, the frame the terminal expects |
| | Data Direction | Receive and Transmit | |
| | Over Sampling | 16 Samples | |
| USART2 > NVIC Settings | USART2 global interrupt | Enabled (ticked) | Without it, `HAL_UART_RxCpltCallback` is never called |

Nothing changes in the Clock Configuration. USART2 is on APB1, at 36 MHz.

## 3. Project Manager, then generate

As before: Toolchain / IDE **STM32CubeIDE**, then **GENERATE CODE**. In STM32CubeIDE,
select the project and press **F5** (Refresh), or import it the first time with
**File > STM32 Project Create/Import > Import STM32 Project**.

## 4. Add the code

Copy the blocks of `uart_commands_user_code.c` into `Core/Src/main.c`, each between its own
`USER CODE BEGIN` and `USER CODE END` comments. If you kept the timers code, replace its
blocks: this program reads the ADC and sets the PWM only when a command asks.

## 5. The terminal

The ST-LINK's virtual COM port appears on the PC as a COM port (Windows: Device Manager,
Ports). Open it at 115200 baud, 8 data bits, no parity, 1 stop bit, and set the line
ending to CR, LF or both. Press the black reset button on the board: you should see
READY.

## 6. Check the generated code

- `MX_USART2_UART_Init()`: `huart2.Init.BaudRate = 115200;`,
  `huart2.Init.WordLength = UART_WORDLENGTH_8B;`, `huart2.Init.Parity = UART_PARITY_NONE;`,
  `huart2.Init.Mode = UART_MODE_TX_RX;`.
- `stm32f1xx_hal_msp.c`, `HAL_UART_MspInit()`: `HAL_NVIC_EnableIRQ(USART2_IRQn);`.
- `stm32f1xx_it.c`: `USART2_IRQHandler()` calls `HAL_UART_IRQHandler(&huart2);`.

## 7. Debug

- **SFRs** view: USART2 > BRR reads 0x138 (312): mantissa 19, fraction 8, so USARTDIV is
  19.5 and the real rate is 36 MHz / (16 x 19.5) = 115 385 baud, +0.16 %.
- A breakpoint inside `HAL_UART_RxCpltCallback`: type one character in the terminal and
  the program stops there with `rx_byte` holding it. Remove the breakpoint before you
  type fast: while the program is stopped, the bytes that follow are lost.
- **Live Expressions**: `rx_head`, `rx_tail` and `line_len` while you type.

## 8. Going further: receive by DMA

For long or fast messages, let the DMA write the bytes into a buffer and wake the program
only when the line goes quiet.

| Where | Setting | Value |
|---|---|---|
| USART2 > DMA Settings | Add | USART2_RX (on this chip, DMA1 channel 6) |
| | Mode | Circular |
| | Increment Address | Memory ticked |
| | Data Width | Byte, Byte |
| USART2 > NVIC Settings | USART2 global interrupt | still Enabled: the "line went quiet" event comes from it |

In the code, the DMA replaces `HAL_UART_Receive_IT` and its callback. The rest (the ring,
the line reader, the commands) stays the same:

```c
/* USER CODE BEGIN PV */
static uint8_t dma_rx[64];  /* the DMA writes here, round and round */
static uint16_t dma_old;    /* how far the program has read */
/* USER CODE END PV */

/* USER CODE BEGIN 0 */
static void ring_put(uint8_t b)
{
  uint16_t next = (uint16_t)((rx_head + 1u) & RX_MASK);
  if (next == rx_tail)
  {
    rx_overflow = 1;
  }
  else
  {
    rx_buf[rx_head] = b;
    rx_head = next;
  }
}

/* The HAL calls this when the line goes quiet, and when the buffer is half and fully
 * written. Size is how far into dma_rx the DMA has written. */
void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
{
  if (huart->Instance == USART2)
  {
    if (Size < dma_old)  /* the DMA went round: read to the end first */
    {
      while (dma_old < sizeof dma_rx)
      {
        ring_put(dma_rx[dma_old++]);
      }
      dma_old = 0;
    }
    while (dma_old < Size)
    {
      ring_put(dma_rx[dma_old++]);
    }
    if (dma_old == sizeof dma_rx)
    {
      dma_old = 0;
    }
  }
}

/* In DMA mode every receive error stops reception. Start again. */
void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart)
{
  if (huart->Instance == USART2)
  {
    rx_error = 1;
    dma_old = 0;
    HAL_UARTEx_ReceiveToIdle_DMA(&huart2, dma_rx, sizeof dma_rx);
  }
}
/* USER CODE END 0 */

/* in USER CODE BEGIN 2, instead of HAL_UART_Receive_IT: */
  HAL_UARTEx_ReceiveToIdle_DMA(&huart2, dma_rx, sizeof dma_rx);
```

Keep the PV and 0 blocks of `uart_commands_user_code.c`, delete its `rx_byte`, its
`HAL_UART_RxCpltCallback` and its `HAL_UART_ErrorCallback`, and add the code above. Test
it with the same list as the interrupt version.

## Sources

Checked on 2026-11-25. st.com did not answer from our network that day, so we read ST's
documents in the copies named here and the HAL in ST's own source code.

- STM32F1 HAL driver V1.1.10 (22 July 2024), ST's source on GitHub:
  `HAL_UART_Receive_IT`, `HAL_UART_RxCpltCallback`, `HAL_UART_ErrorCallback` (an overrun,
  or any error in DMA mode, stops reception), `HAL_UARTEx_ReceiveToIdle_DMA`,
  `HAL_UARTEx_RxEventCallback` (called at idle, half and full), the BRR calculation.
  https://github.com/STMicroelectronics/stm32f1xx-hal-driver
- STM32 Nucleo-64 boards user manual, UM1724 (we read Rev 14): USART2 on PA2 and PA3 goes
  to the ST-LINK for the virtual COM port.
  https://www.st.com/resource/en/user_manual/dm00105823-stm32-nucleo64-boards-mb1136-stmicroelectronics.pdf
- STM32CubeIDE user guide, UM2609 Rev 18, June 2026 (installed with STM32CubeIDE 2.2):
  SFRs, Live Expressions, breakpoints.
  https://www.st.com/resource/en/user_manual/um2609-stm32cubeide-user-guide-stmicroelectronics.pdf
- STM32CubeMX user manual, UM1718 Rev 50, February 2026 (the copy installed with
  STM32CubeMX): NVIC Settings, DMA Settings.
  https://www.st.com/resource/en/user_manual/um1718-stm32cubemx-for-stm32-configuration-and-initialization-c-code-generation-stmicroelectronics.pdf
- RM0008, STM32F10x reference manual: the USART baud rate, one receive register, the
  DMA1 request for USART2_RX.
  https://www.st.com/resource/en/reference_manual/rm0008-stm32f101xx-stm32f102xx-stm32f103xx-stm32f105xx-and-stm32f107xx-advanced-armbased-32bit-mcus-stmicroelectronics.pdf
