🛠 STM32Cube HAL et BSP officiel : LED, bouton et accéléromètre avec détection automatique

STM32F4DISCOVERY (STM32F407VGT6 Discovery kit) · intermediaire · Schéma : arborescence du paquet STM32CubeF4 mise en évidence — Drivers/BSP/STM32F4-Discovery, Drivers/BSP/Components (lis302dl, lis3dsh) et Projects/STM32F4-Discovery — avec la carte STM32F4DISCOVERY et sa puce accéléromètre reliée au bus SPI1 (PA5/PA6/PA7, CS PE3).

Objective

Program the STM32F4DISCOVERY "from the source": the official STM32CubeF4 firmware contains a dedicated BSP (Board Support Package) for this board, located in Drivers/BSP/STM32F4-Discovery, with complete examples in Projects/STM32F4-Discovery/. You will use the BSP_LED_*, BSP_PB_*, and BSP_ACCELERO_* APIs — and above all, understand the automatic accelerometer detection, a hardware peculiarity of this board.

Hardware and Project

The Hardware Trap: Two Accelerometers Depending on the Revision

The board was produced with two different MEMS on the same SPI1 bus: the LIS302DL on early boards, and the LIS3DSH on later ones (SCK PA5, MISO PA6, MOSI PA7, CS PE3, interrupts PE0/PE1). Code that assumes a single component fails silently on the other revision. The BSP solves this problem by reading the chip ID: use BSP_ACCELERO_Init and do not hardcode the component.

Complete Code

#include "stm32f4_discovery.h"
#include "stm32f4_discovery_accelerometer.h"

int main(void)
{
  int16_t xyz[3] = {0, 0, 0};

  HAL_Init;            /* SysTick/NVIC par defaut */
  SystemClock_Config;  /* 168 MHz depuis le quartz HSE 8 MHz */

  BSP_LED_Init(LED3);    /* LED3 = PD13 (orange) ; LED4/5/6 = PD12/14/15 */
  BSP_PB_Init(BUTTON_KEY, BUTTON_MODE_GPIO);  /* USER = PA0 */
  BSP_ACCELERO_Init;   /* auto-detecte LIS302DL vs LIS3DSH via chip ID */

  while (1)
  {
    BSP_LED_Toggle(LED3);
    BSP_ACCELERO_GetXYZ(xyz);   /* axes normalises entre revisions */
    if (BSP_PB_GetState(BUTTON_KEY) == GPIO_PIN_SET)
      BSP_LED_On(LED4);
    else
      BSP_LED_Off(LED4);
    HAL_Delay(100);
  }
}

What the BSP Hides from You (Useful to Know)

Expected Verification

The orange LED blinks at 5 Hz; the green LED stays on while USER is pressed. When tilting the board, the xyz values change (to be observed in the debugger, as the ST-LINK console is not wired on stock boards).

Common Errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials