- C 99.5%
- CMake 0.2%
- Assembly 0.2%
- Linker Script 0.1%
Measured on this image, -Os saves 544 B of Flash over -O2 (7392 B vs 7936 B) and 988 B over the debug build, for 8 B less .bss. Nothing in the control loop is latency critical, so size optimisation is the right default for a 24 KiB part. README records the three builds side by side. |
||
|---|---|---|
| .vscode | ||
| cmake | ||
| Drivers | ||
| inc | ||
| linker | ||
| src | ||
| startup | ||
| .clangd | ||
| .gitignore | ||
| CMakeLists.txt | ||
| CMakePresets.json | ||
| CONVERT.md | ||
| OPERATION.md | ||
| README.md | ||
ro_controller — XL32F001 firmware
Firmware for the XL32F001 (Cortex-M0+, 24 MHz, 24 KiB Flash /
3 KiB RAM), built with VS Code + CMake + Ninja + arm-none-eabi-gcc +
OpenOCD + Cortex-Debug. No Keil, no PlatformIO, no STM32CubeIDE.
This project derives from xl32f001-vscode-cmake-template. The vendor
driver, GCC startup file and linker script are inherited from that
template and have already been validated; the application layer is ours.
The current image runs a boot sequence and then a 10 ms control loop. At reset it initialises the HAL and clock, holds the two switch outputs (PB4, PB5) low, lights the signal LED PB0 and waits 10 seconds so a debugger can attach while PA2/PB6 are still SWD. It then initialises the ADC, hands PA2/PB6 to USART1 as the master link, and runs the IDLE / OPERATING / FLUSHING state machine. The machine is armed at boot, so it starts the pump once the tank reads empty. See OPERATION.md for the protocol, thresholds and state machine.
Requirements
arm-none-eabi-gcc(for example Ubuntu:sudo apt install gcc-arm-none-eabi)- CMake 3.22 or newer, and Ninja
- OpenOCD and an SWD probe (ST-Link, DAPLink, or J-Link) for flashing
- VS Code extensions: CMake Tools, clangd, Cortex-Debug (VS Code
suggests them from
.vscode/extensions.json)
Build and flash
From VS Code
- Open this folder in VS Code.
- CMake Tools asks for a kit/preset: pick the debug preset.
- Build with the CMake Tools build button, or the task CMake: configure + build.
- Before the first flash, run Flash: OpenOCD, probe only (check the chip answers before flashing).
- Flash with the task Flash: OpenOCD + ST-Link (try stm32f0x target first).
- PB0 lights for 10 seconds while PB4/PB5 stay low; then PB0 goes off as USART1 takes over PA2/PB6. Reset the board to get the SWD window back.
From a terminal
cmake --preset debug
cmake --build --preset debug
For a build that runs unattended, use the release profile instead:
cmake --preset release
cmake --build --preset release
To flash:
openocd -f interface/stlink.cfg -f target/stm32f0x.cfg \
-c "program build/ro_controller.elf verify reset exit"
To only check that the probe and target answer:
openocd -f interface/stlink.cfg -f target/stm32f0x.cfg \
-c "init; halt; flash probe 0; exit"
Build profiles
Two presets, same sources, separate build trees:
| Preset | Directory | Flags | Use |
|---|---|---|---|
debug |
build/ |
-g -Og |
day-to-day development, gdb |
release |
build-release/ |
-Os -DNDEBUG |
long-running units and soak tests |
release uses -Os rather than CMake's -O3/-O2 defaults. Measured on
this image:
| Profile | .text |
Flash | RAM |
|---|---|---|---|
debug (-Og) |
8168 B | 8380 B | 1376 B |
-O2 |
7724 B | 7936 B | 1376 B |
release (-Os) |
7180 B | 7392 B | 1368 B |
Flash is the scarce resource on a 24 KiB part and nothing in the control
loop has a deadline a size-optimised build could miss: the loop has a
10 ms budget and uses a fraction of it, dominated by one ~9 µs ADC
conversion. -Os is 544 B smaller than -O2 and 988 B smaller than the
debug build, with identical behaviour — the only compile-time difference
that reaches the firmware is that standard assert() disappears, and the
HAL's assert_param() is already compiled out via USE_FULL_ASSERT.
Build outputs
Everything lands in the preset's directory (build/ or build-release/):
ro_controller.elf— the debug/flash imagero_controller.bin,ro_controller.hex— generated next to the.elfro_controller.map— linker mapcompile_commands.json— used by clangd for IntelliSense
Both directories are gitignored; they are safe to delete and rebuild.
Soak testing
For a multi-day run, flash the release image and leave the master polling:
cmake --build --preset release, then flashbuild-release/ro_controller.elfwith the same OpenOCD command.- Power-cycle after flashing so the unit starts from the state a real installation sees (boot window, ADC init, link up, armed).
- Watch the 1 s ADC poll in MQTT, plus a counters read
(
5A 7E 00 00 00 00 00 AFonro/cmd) every few minutes.
What "checks out" looks like over days:
statecycles idle → operating → flushing → idle with the tank, and the outputs in the status frame match the state.flagsstays free ofADC_FAULT(0x02),LINK_ERROR(0x04) andCONFIG_REJECT(0x08).LINK_ERRORonly clears on an explicitRESET, so a single glitch stays visible for the whole run rather than being lost.- Counters frame (
A6 00 …): byte 4 ring overruns and byte 5 UART errors stay 0, byte 6 frame errors stays 0. All three saturate at 255, so a saturated value means "many", not "exactly 255". Therxcount in bytes 2–3 wraps every 65536 bytes; that is a liveness indicator, not an exact tally. - PB0 stays off: it only lights during the boot window.
Timing arithmetic is wrap-safe ((int32_t)(now - start) for the flush
timer, (uint32_t)(now - last) for the frame timeout), so the 49.7-day
SysTick rollover at 1 kHz does not disturb an unattended unit.
Project layout
src/ all user C sources (main, User_Control, User_Link, User_USART,
User_ADC,
PY32 project files)
inc/ all user headers, plus py32f002b_hal_conf.h (HAL config)
Drivers/ vendor CMSIS + PY32F002B HAL, verbatim — do not edit
startup/ GCC startup file and vector table
linker/ flash.ld (24 KiB Flash / 3 KiB RAM) — inherited from the template
cmake/ arm-none-eabi toolchain file
.vscode/ build/flash tasks, Cortex-Debug launch, clangd settings
CMakeLists.txt, CMakePresets.json
OPERATION.md describes the runtime state machine, configuration and
serial protocol in detail.
The rule for adding code is simply:
- a new
.cfile goes insrc/and is added to theadd_executablelist inCMakeLists.txt; - a new
.hfile goes ininc/, which is already on the include path.
Hardware setup
| Signal | Pin | Notes |
|---|---|---|
| Switch A (pump) | PB4 | Push-pull output, active high, low at boot |
| Switch B (flush) | PB5 | Push-pull output, active high, low at boot |
| Signal LED | PB0 | Push-pull output, active high |
| ADC1_IN0 | PB1 | Analog input, VCCA = VCC = 5 V |
| USART1 RX | PA2 | AF1 — shared with SWCLK |
| USART1 TX | PB6 | AF1 — shared with SWDIO |
| SWD | PA2 / PB6 | Available for 10 s after reset, then taken by USART1 |
The clock is HSI 24 MHz as system clock, with APB divided by 2, so PCLK
is 12 MHz. HAL_Delay() uses the 1 ms SysTick set up by HAL_Init().
PB4 was USART1 TX and PB5 was USART1 RX in the template; this project uses both as plain GPIOs for the two switch outputs. PB0 is the signal LED.
Boot sequence
main() runs a fixed blocking sequence:
HAL_Init()andUser_System_Clock_Init().User_Control_Init()configures PB4/PB5 as outputs low.User_Signal_Init()configures PB0 and drives it on.HAL_Delay(10000)keeps PB0 on for the SWD window — PA2/PB6 are still SWCLK/SWDIO, so a debugger can attach or the board can be reflashed. The switch outputs stay low.- PB0 is driven off, the ADC is initialised, and
User_Link_Init()hands PA2/PB6 to USART1. If the link cannot be brought up, PB0 blinks at 5 Hz and the firmware stops: there is nothing to serve without it.
Because the SWD pins disappear after step 4, flashing and debugging must
happen inside the 10 s window — press reset, then attach. The window is
USER_SWD_WINDOW_MS in src/main.c.
Master link
src/User_USART.c / inc/User_USART.h own the transport: USART1 at
115200 8N1 on PA2 (RX) and PB6 (TX), both AF1. Receive is interrupt
driven into a 64-byte ring buffer; transmit is blocking, about 0.75 ms
for a frame. The ring is what makes the blocking transmit safe — bytes
keep landing in it while a reply goes out.
src/User_Link.c / inc/User_Link.h own the framing: fixed 8-byte
frames, CRC-8, resynchronisation on the magic byte, a 100 ms frame
timeout, and the SET_CONFIG, RESET, FORCE_STATE and DEBUG
commands. Every valid request gets exactly one reply; a frame with a bad
CRC is ignored so a corrupt request can never provoke a corrupt reply.
The full protocol is in OPERATION.md.
The daisy-chain is main → User_Link → User_USART. Framing runs in
the main loop, so nothing but the byte ring is shared with an interrupt.
ADC module
src/User_ADC.c / inc/User_ADC.h configure ADC1 for PB1 / ADC_IN0:
- synchronous PCLK/2 = 6 MHz ADC clock
- 12-bit, right-aligned, single channel, software trigger
- 41.5-cycle sampling time
- offset + capacitance calibration during init
- VCCA is tied to VCC = 5 V, so
USER_ADC_VREF_MVis 5000 andmV = raw * 5000 / 4095
User_ADC_Init() configures and calibrates the ADC but leaves it
disabled. User_ADC_Read(&raw) performs one blocking conversion
(HAL_ADC_Start → HAL_ADC_PollForConversion → HAL_ADC_GetValue →
HAL_ADC_Stop, 10 ms timeout) and stores the raw 12-bit value.
User_Control_Tick() calls User_ADC_Read() once per 10 ms tick.
Note: the generic "2.4 V to 3.6 V ADC supply" comment in the HAL driver is inherited from STM32; this board follows its own XL32F001 doc, where VCCA is derived directly from VCC = 5 V.
The HAL configuration header
inc/py32f002b_hal_conf.h is not application code. It is the HAL's
configuration header (the PY32F002B equivalent of ST's
stm32f0xx_hal_conf.h), and it must keep that exact name and stay on the
include path; inc/ is already there.
Every HAL driver reaches it through the umbrella header, and py32f0xx.h
includes that umbrella because USE_HAL_DRIVER is defined in
CMakeLists.txt:
py32f0xx_hal.h -> py32f002b_hal_conf.h -> the enabled py32f002b_hal_*.h
The HAL_<X>_MODULE_ENABLED switches near the top choose which peripheral
drivers are pulled in. The rest of the file holds the clock constants
(HSE_VALUE, HSI_VALUE, ...) and USE_FULL_ASSERT.
To disable a module, comment out its switch and remove its driver
.c from CMakeLists.txt: the driver gets its types from the umbrella
and will not compile once its header is no longer included.
The project compiles the full set of HAL drivers the template shipped
with; --gc-sections drops the unused ones at link time.
The #include "py32f002b_hal_*.h" lines at the bottom are module
selection, not direct dependencies of this file. Because they are
side-effect includes, clangd's unused-include check is disabled for this
file in .clangd; deleting them, as its warning suggests, would break
the HAL.
Tooling notes
- IntelliSense comes from clangd, reading
build/compile_commands.json. The Microsoft C/C++ extension's IntelliSense is disabled in.vscode/settings.json, because the two engines fight over the same files. Keep it disabled. - The CMake preset is called
debugand uses Ninja pluscmake/arm-none-eabi.cmake. To configure by hand, pass-DCMAKE_TOOLCHAIN_FILE=cmake/arm-none-eabi.cmake. - The build uses
-Og -g3 -Wall -Wextrawith-ffunction-sections -fdata-sectionsand--gc-sections, so unused HAL functions are dropped at link time. .binand.hexare produced by a post-build step, so they always match the.elf.
Troubleshooting
- Build fails with "arm-none-eabi-gcc not found": install the
toolchain and make sure it is on
PATHbefore opening VS Code, or CMake Tools will cache a host compiler. - Linker error "section will not fit": your code outgrew 24 KiB Flash / 3 KiB RAM, or your chip is smaller than the linker script assumes. Check the memory-size item under CHECK in CONVERT.md before editing the script.
- Warnings about
_close,_fstat,_isatty,_lseek,_readnot implemented: expected. They come fromnosys.specs. If you addprintflater, implement_write()(as the template did inUser_USART.c) or nothing will appear. - Build succeeds, but PB0 does nothing at boot: check the PB0 wiring
and LED polarity (the firmware drives it active high), and that the
probe actually flashed (compare the
.elftimestamp with the flash log). See the hardware notes in CONVERT.md. - PB0 stays on forever:
main()is stuck before the end of the 10 s window — SysTick is not running at 24 MHz, soHAL_Delay()never returns. See the clock assumptions in CONVERT.md. - PB0 blinks at 5 Hz after boot:
HAL_UART_Init()failed. That is almost always a clock problem, not a wiring one — the pin configuration is set up by the same call. - The debugger cannot attach: the 10 s SWD window has expired and USART1 owns PA2/PB6. Press reset and attach within 10 s.
Background and hardware caveats
The template was converted from a Keil project that targeted a PY32F002B-class part; no XL32F001 datasheet was available. The vendor driver, startup file and linker script are known good, but some chip-level assumptions (trim addresses, pinout, register map, option bytes) are still inherited from PY32F002B.
CONVERT.md records:
- what the original project did and what was removed (the 433 receiver, and now the USART helper module);
- how to restore the 433 receiver later;
- the original pin map and clock setup;
- where every file came from, and what was translated rather than copied;
- the CHECK list — every XL32F001 assumption worth verifying against your datasheet and board;
- hardware bring-up troubleshooting;
- the build verification snapshot from the template.
It is conversion history; where it disagrees with the current code, the code and this README win.