🛠 Firmware libre sur Blue Pill avec libopencm3 et OpenOCD
Why libopencm3?
libopencm3 is an open-source GCC library for Cortex-M "written completely from scratch from the manufacturer's datasheets" — with no ST code, under the LGPL3 license. The STM32 F1xx family is supported, and the project documents flashing via OpenOCD. It is the ideal option for understanding what the HAL really does, with a lightweight API (rcc, gpio, usart, spi, i2c, adc, can…) and canonical examples: the libopencm3-examples repository contains stm32-maple targets (miniblink, USB CDC-ACM, SPI/I2C demos) that correspond to Blue Pill-class boards.
The miniblink, PC13 version
Adapted from the stm32-maple/miniblink example, taking into account the LED in sink mode (HIGH = off) and the low drive capability of PC13:
#include <libopencm3/stm32/rcc.h>
#include <libopencm3/stm32/gpio.h>
static void gpio_setup(void)
{
/* Active l'horloge du périphérique GPIOC (RCC_APB2ENR |= IOPCEN). */
rcc_periph_clock_enable(RCC_GPIOC);
/* PC13 en sortie push-pull 2 MHz (broche à faible drive). */
gpio_set_mode(GPIOC, GPIO_MODE_OUTPUT_2_MHZ,
GPIO_CNF_OUTPUT_PUSHPULL, GPIO13);
}
int main(void)
{
int i;
gpio_setup;
while (1) {
gpio_set(GPIOC, GPIO13); /* HIGH -> LED ÉTEINTE (sink) */
for (i = 0; i < 800000; i++)
__asm__("nop");
gpio_clear(GPIOC, GPIO13); /* LOW -> LED ALLUMÉE */
for (i = 0; i < 800000; i++)
__asm__("nop");
}
}
Two hardware lessons are encapsulated in this file: you must enable the APB2 clock for the GPIOC port before any access (otherwise writes have no effect), and PC13 must remain a slow control pin — hence the 2 MHz mode.
Compilation chain and flashing
- Compiler:
arm-none-eabi-gcc; build within libopencm3-examples or via a template such as libopencm3-template. - SWD flashing: OpenOCD (method documented by the project) or stlink tools:
st-flash --reset write blink.bin 0x8000000. - Alternative without ST-Link: the ROM serial bootloader (
stm32flash, BOOT0=1, USART1 PA9/PA10 at 115200).
The PlatformIO board definition for genericSTM32F103C8 also lists the frameworks arduino, cmsis, libopencm3, stm32cube and the upload protocols jlink, cmsis-dap, stlink, blackmagic, serial, dfu — proof that this board lends itself to all levels of abstraction.
Other tutorials for this board
- Découvrir la Blue Pill : que trouve-t-on dans la boîte ?
- Premier programme Arduino sur la Blue Pill (core officiel stm32duino)
- Alimenter et flasher la Blue Pill : BOOT0, port série, ST-Link et DFU
- Série, ADC et chasse aux contrefaçons : diagnostiquer sa Blue Pill
- Dompter l'USB natif de la Blue Pill : CDC, DFU et la résistance rebelle
- Passer au niveau supérieur : STM32CubeIDE, HAL et LL sur F103