- Install GCC ARM toolchain.
- Write bare-metal or HAL-based C code.
- Create a linker script.
- Compile using
arm-none-eabi-gcc
. - Convert to binary with
arm-none-eabi-objcopy
. - Flash using
st-flash
orOpenOCD
. - Debug with
GDB
(optional).
1. Set Up the Toolchain
To compile code for STM32, you need an ARM GCC toolchain:
- Download ARM GCC (GNU Arm Embedded Toolchain):
https://developer.arm.com/downloads/-/gnu-rm
Extract and add thebin
folder to your systemPATH
.
2. Write Your Code (Bare-metal or HAL)
Create a main.c
file with your STM32 application logic. Example:
#include "stm32f4xx.h"
void delay(volatile uint32_t s) {
for (; s > 0; s--);
}
int main(void) {
RCC->AHB1ENR |= (1 << 3); // Enable GPIOD clock
GPIOD->MODER |= (1 << 26); // Set PD13 as output
while (1) {
GPIOD->ODR ^= (1 << 13); // Toggle LED
delay(1000000);
}
}
3. Create a Linker Script (STM32F4.ld
)
Define memory sections for your STM32 chip:
ld
MEMORY
{
FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 512K
SRAM (rwx) : ORIGIN = 0x20000000, LENGTH = 128K
}
SECTIONS
{
.text : {
*(.isr_vector)
*(.text)
*(.rodata)
. = ALIGN(4);
} > FLASH
.data : {
*(.data)
. = ALIGN(4);
} > SRAM AT > FLASH
.bss : {
*(.bss)
. = ALIGN(4);
} > SRAM
}
4. Compile Using GCC
Run the following command to compile your main.c
file:
sh
arm-none-eabi-gcc -mcpu=cortex-m4 -mthumb -O2 -T STM32F4.ld -o main.elf main.c -nostartfiles
5. Convert ELF to Binary
To flash the STM32, convert the ELF file to a binary format:
sh
arm-none-eabi-objcopy -O binary main.elf main.bin
6. Flash the Code
You can use st-flash
(from stlink) to upload the binary to your STM32 via ST-Link:
sh
st-flash write main.bin 0x08000000
Alternatively, use OpenOCD:
sh
openocd -f interface/stlink.cfg -f target/stm32f4x.cfg -c "program main.elf verify reset exit"
7. Debugging (Optional)
If you want to debug without an IDE, use GDB with OpenOCD:
sh
openocd -f interface/stlink.cfg -f target/stm32f4x.cfg
Then, in another terminal:
sh
arm-none-eabi-gdb main.elf (gdb) target remote localhost:3333 (gdb) monitor reset halt (gdb) load (gdb) continue
Leave a Reply