clignotante.c

STM32F4DISCOVERY (STM32F407VGT6 Discovery kit) · File : clignotante.c · Language : C · Use case : Faire clignoter la LED utilisateur avec la bibliothèque HAL

The reference blink in bare C with STM32 HAL: the board LED on pin 12 toggles every 500 ms thanks to the 1 ms HAL SysTick. The skeleton is the one generated by STM32CubeIDE, ready to compile.

Hardware

A STM32F407G-DISC1 (Discovery F4, Cortex-M4 @ 168 MHz) with built-in ST-LINK, 3.3 V pins. None: the user LED (LED4 verte, broche PD12 ; les autres LED sont PD13-PD15) is enough. The board is programmed via its USB connector (ST-LINK or bootloader).

Wiring

Nothing to wire: internal LED on GPIOD/GPIO_PIN_12, active HIGH.

How it works

HAL_Init() sets up SysTick (1 ms tick); HAL_GetTick() acts as a non-blocking clock. HAL_GPIO_WritePin drives the push-pull pin. __WFI() sleeps the CPU between ticks.

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

Create the project from the ST-provided .ioc (or an equivalent one), or use the LL library for leaner code.

clignotante.c

// Clignotement LED en STM32 HAL (projet genere par STM32CubeIDE/.ioc).
#include "main.h"

/* Broche de la LED utilisateur de la carte. */
#define LED_PORT  GPIOD
#define LED_PIN   GPIO_PIN_12
/* LED active a l'etat HIGH. */

uint32_t dernierBlink = 0;
uint8_t etat = 0;

int main(void) {
  HAL_Init();            // SysTick 1 ms + priorites NVIC
  SystemClock_Config();  // horloge generee depuis CubeMX

  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();
  __HAL_RCC_GPIOC_CLK_ENABLE();
  __HAL_RCC_GPIOD_CLK_ENABLE();

  GPIO_InitTypeDef g = {0};
  g.Pin = LED_PIN;
  g.Mode = GPIO_MODE_OUTPUT_PP;   // sortie push-pull
  g.Pull = GPIO_NOPULL;
  g.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(LED_PORT, &g);

  for (;;) {
    if (HAL_GetTick() - dernierBlink >= 500) {  // 500 ms
      dernierBlink = HAL_GetTick();
      etat ^= 1;
      HAL_GPIO_WritePin(LED_PORT, LED_PIN, etat ? GPIO_PIN_SET : GPIO_PIN_RESET);
    }
    __WFI();  // attend l'interruption SysTick : consomme moins
  }
}

← Back to the board