usart-reception.c

STM32 Nucleo-64 F4 family — flagship: Nucleo-F401RE · File : usart-reception.c · Language : C · Use case : Recevoir des commandes série par interruption et DMA circulaire

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 F4 board (STM32F401RE/F411RE, Cortex-M4) 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

Create a STM32CubeIDE project (pick Nucleo-F401RE or F411RE), paste the code into main.c, configure peripherals in the .ioc, then Run. The ST-LINK serial terminal 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(GPIOA, GPIO_PIN_5);
  } 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;
      }
    }
  }
}

← Back to the board