STM32 LED Blinking with Assembly on Linux
Setting Up Embededd Development Environment
To develop STM32 applications on Linux, configure the ARM GNU toolchain for cross-compilation. Download the latest ARM GNU Toolchain from Arm Developer and extract it to /opt/gcc-arm-none-eabi. Add the binary path to your shell configuration:
export PATH=$PATH:/opt/gcc-arm-none-eabi/bin
Install required dependencies:
sudo apt install -y libncursesw5 python3.8
Verify installation with:
arm-none-eabi-gcc --version
Hardware Connnectivity Seetup
Use USBIPD to access Windows-connected USB devices from WSL. Follow Microsoft's USBIPD documentation to share STM32 debugger interfaces with the Linux environment.
Embedded Debugging Tools
Install OpenOCD for programming and debugging:
sudo apt install openocd
This provides JTAG/SWD communication with STM32 chips through interfaces like ST-Link.
Assembly Implementation
Modify the Reset_Handler in the startup file (startup_stm32f10x_md.s) to initialize GPIO and control LED blinking:
Reset_Handler:
bl init_led
b lights_loop
init_led:
ldr r0, =0x40021018 @ RCC_APB2ENR
ldr r1, [r0]
orr r1, r1, #0x10 @ Enable GPIOC clock
str r1, [r0]
ldr r0, =0x40011004 @ GPIOC_CRH
ldr r1, [r0]
orr r1, r1, #0x100000 @ Configure PC13 as output
str r1, [r0]
bx lr
lights_loop:
bl led_on
bl delay
bl led_off
bl delay
b lights_loop
led_on:
ldr r0, =0x4001100C @ GPIOC_ODR
ldr r1, [r0]
bic r1, r1, #(1<<13) @ Set PC13 low
str r1, [r0]
bx lr
delay:
mov r2, #0x100000
delay_loop:
subs r2, r2, #1
bne delay_loop
bx lr
Linker Script Configuration
Create a linker script (STM32F103RETx_FLASH.ld) to manage memory allocation:
MEMORY {
FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 512K
RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 64K
}
ENTRY(Reset_Handler)
SECTIONS {
.text : {
*startup_stm32f10x_md.o (.text)
} > FLASH
}
Compilation and Flashing
Compile the assembly to object file:
arm-none-eabi-gcc -c -mthumb -mcpu=cortex-m3 -o startup.o startup_stm32f10x_md.s
Link objects into ELF executable:
arm-none-eabi-gcc -o firmware.elf startup.o -T STM32F103RETx_FLASH.ld
Generate binary file:
arm-none-eabi-objcopy -O binary firmware.elf firmware.bin
Flash using OpenOCD:
openocd -f interface/stlink.cfg -f target/stm32f1x.cfg -c "program firmware.bin verify reset exit"