STM32CubeMX
This page is the short, concrete workflow for using STM32CubeMX to configure an STM32 project and generate init code without accidentally nuking your work.
Download: https://www.st.com/en/development-tools/stm32cubemx.html
1) Install & open a project
- Install STM32CubeMX from the download page above.
- Open an existing project by opening the
.iocfile (this is the configuration source of truth). - If you are starting new: create a new project and pick the correct MCU/board (ask if unsure).
2) Configure pins & peripherals
- In Pinout & Configuration: enable the peripherals you need (UART/SPI/I2C/CAN/Timers/ADC/etc.).
- Assign pins and resolve conflicts (CubeMX will warn you).
- Configure DMA + NVIC if needed (especially for high-rate IO or RTOS systems).
3) Set up the clocks
- Go to Clock Configuration and set your clock source (HSI/HSE) and PLL to the target system frequency.
- Verify peripheral clocks (UART baud rates and timer frequencies depend on this).
- If USB is used, make sure USB clock requirements are satisfied (CubeMX will usually flag invalid setups).
4) Code generation rules
Do not write custom code in CubeMX-generated files.
CubeMX will overwrite generated files during regeneration. Any custom code placed there will be lost, even if it appears to work temporarily.
Rule:
- Generated code is read-only.
- Your code lives outside of it.
What to do instead:
- Put all application logic in your own source files (
src/, modules, drivers, etc.). - Only use generated code as initialization and hardware configuration.
- Call your own code from the appropriate entry points (e.g. after init in
main()).
Bottom line:
If your code depends on surviving a “Generate Code” click, it’s in the wrong place.
5) Generate code, then build & verify
- Open Project Manager and confirm the project type/toolchain and output path are correct.
- Click Generate Code.
- Immediately review changes (e.g.
git diff). If CubeMX changed a lot more than expected, stop and investigate before committing. - Build the firmware and run a basic smoke test (UART prints, LED blink, peripheral init success, etc.).
```