usart-reception.c
The circular DMA fills the UART buffer without ever interrupting the CPU: the main loop slices the stream into lines and runs commands ("led" toggles the user LED). The reference pattern for a responsive mini serial protocol.
Hardware
A Nucleo H7 board (STM32H743ZI, Cortex-M7 @ 480 MHz) programmed via ST-LINK (USB), 3.3 V pins. Serial terminal (115200 8N1) sending text lines.
Wiring
No wiring: USART2 is tied to the board USB converter. Enable the USART2 RX DMA in CubeMX.
How it works
Receive_DMA sets a permanent hardware transfer; __HAL_DMA_GET_COUNTER reports the write position. The loop compares with its own cursor and splits on \r/\n.
Running it
STM32CubeIDE project based on the Nucleo-H743ZI: drop the code into main.c, declare peripherals in the .ioc, then Run over ST-LINK. The ST-LINK serial monitor shows printf at 115200.
Variants
Add typed commands (LED, ADC, PWM) AT-style, or handle lines in the HAL_UARTEx_RxEventCallback with half/full DMA.
usart-reception.c
// Reception serie non bloquante : DMA circulaire + recherche de lignes.
#include "main.h"
#include <string.h>
#include <stdio.h>
extern UART_HandleTypeDef huart2;
extern DMA_HandleTypeDef hdma_usart2_rx;
#define TAILLE 64
uint8_t tampon[TAILLE];
uint16_t dernierIndice = 0;
static void traiterLigne(const char *ligne) {
if (strcmp(ligne, "led") == 0) {
HAL_GPIO_TogglePin(GPIOB, GPIO_PIN_0);
} else {
printf("recu: %s\r\n", ligne);
}
}
int main(void) {
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_USART2_UART_Init();
MX_DMA_Init();
HAL_UART_Receive_DMA(&huart2, tampon, TAILLE); // ne bloque jamais
for (;;) {
// Le DMA remplit le tampon en tournant ; on lit ce qui a avance.
uint16_t indice = TAILLE - __HAL_DMA_GET_COUNTER(huart2.hdmarx);
while (dernierIndice != indice) {
uint8_t c = tampon[dernierIndice];
dernierIndice = (dernierIndice + 1) % TAILLE;
static char ligne[TAILLE];
static int n = 0;
if (c == '\r' || c == '\n') {
if (n) { ligne[n] = 0; traiterLigne(ligne); n = 0; }
} else if (n < TAILLE - 1) {
ligne[n++] = (char)c;
}
}
}
}