🛠 STM32CubeF4 et HAL : blink + UART printf générés pour la Nucleo-F401RE

STM32 Nucleo-64 famille F4 — phare : Nucleo-F401RE · intermediaire · Schéma : IMG-stm32f4-nucleo-intermediaire-4-stm32f4nuc-cubemx-hal-blink-uart.svg — flux de travail STM32CubeF4 : CubeMX configurant USART2 et la broche PA5, génération du code HAL, compilation puis flash via ST-LINK

Goals

Leave the Arduino abstraction for a session and build a STM32Cube HAL project for the Nucleo-F401RE. STM32CubeF4 is ST's official firmware package — CMSIS + HAL/LL drivers + board BSP + middleware + ready-made example projects — and it explicitly ships projects for the STM32F401RE-Nucleo. Code generation happens in STM32CubeMX ; flashing goes through the on-board ST-LINK with STM32CubeProgrammer.

Hardware

Steps

git clone --recursive https://github.com/STMicroelectronics/STM32CubeF4

  1. Clone the package recursively — it is a submodule aggregate:
  2. In CubeMX, select the Nucleo-F401RE board, enable USART2 (PA2/PA3, the ST-LINK VCP) in Asynchronous mode.
  3. Generate the code, then wire the blink + printf loop below into main.c.
  4. Build and flash over ST-LINK ; open the ST-LINK COM port at 115200.

Code

/* main.c — Nucleo-F401RE, STM32Cube HAL: LD2 blink on PA5 + USART2 (ST-LINK VCP) */
#include "stm32f4xx_hal.h"
extern UART_HandleTypeDef huart2;   // generated by CubeMX (PA2/PA3 -> ST-LINK VCP)
static GPIO_InitTypeDef gpio = {0};

int main(void)
{
  HAL_Init;                   /* SysTick @1 ms, NVIC defaults        */
  SystemClock_Config;         /* generated: HSI/PLL -> 84 MHz SYSCLK  */

  __HAL_RCC_GPIOA_CLK_ENABLE;
  gpio.Pin   = GPIO_PIN_5;      /* LD2 (green user LED) = PA5           */
  gpio.Mode  = GPIO_MODE_OUTPUT_PP;
  gpio.Pull  = GPIO_NOPULL;
  gpio.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOA, &gpio);

  char msg[48]; uint32_t n = 0;
  while (1) {
    HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_5);
    HAL_Delay(250);
    int len = snprintf(msg, sizeof msg,
                       "hello from Nucleo-F401RE #%lu\r\n", (unsigned long)++n);
    HAL_UART_Transmit(&huart2, (uint8_t *)msg, len, HAL_MAX_DELAY);
    HAL_Delay(750);
  }
}

Expected result

LD2 blinks at 2 Hz and the ST-LINK COM port prints a numbered hello once per second. The generated SystemClock_Config runs the F401 at its default 84 MHz SYSCLK derived from HSI through the PLL. From here, the Projects/STM32F401RE-Nucleo tree in the repo is your cookbook: GPIO, ADC, USART, USB and SDIO examples maintained by ST.

Common mistakes

Autres tutoriels pour cette carte

Exemples de code pour cette carte

← Retour à la fiche 🛠 Tous les tutoriels