usart-reception.c

STM32F4DISCOVERY (STM32F407VGT6 Discovery kit) · 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 STM32F407G-DISC1 (Discovery F4, Cortex-M4 @ 168 MHz) with built-in ST-LINK, 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 « STM32F407G-DISC1 »: paste the code into main.c, configure the .ioc, Run. The board has 4 LEDs (PD12-PD15) and the USER button on PA0.

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(GPIOD, GPIO_PIN_12);
  } 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