What the standard asks
Section 6, Embedded systems programming, is worth 25% of the marks (WorldSkills Occupational Standards, Electronics, WorldSkills Shanghai 2026, checked 2026-11-25). It names power management features such as the watchdog timer, and code that stores data and controls equipment. A controller that works for ten minutes on the bench is not enough. It must stay right when buttons are pressed in the wrong order, when the power fails during a save, and when something hangs.
The section page showed HAL_IWDG_Refresh and named state machines. This lesson builds one complete controller on a NUCLEO-F103RB, a pump with a dry-run guard, and explains the decision behind each part. STM32CubeMX sets up the pins, a 1 ms timer, the watchdog and the serial port. Your code goes in the USER CODE blocks of main.c, and STM32CubeIDE builds, flashes and debugs it, as in the timers lesson.
The theory
The state machine, on paper first
A state machine is a few states, the events that move between them, and what happens on each move. Write it as a table before any code. Each row becomes a test later.
| State | Event | Only if | Next state | Action |
|---|---|---|---|---|
| IDLE | short press | tank not full | RUNNING | pump on |
| IDLE | long press | IDLE | next run limit, saved | |
| RUNNING | short press, or tank full | IDLE | pump off | |
| RUNNING | run time reaches the limit | FAULT | pump off | |
| FAULT | long press | IDLE | ||
| start | the watchdog caused the reset | FAULT | pump off |
Three rules keep it honest:
- One place switches the outputs. In the download,
enter()is the only function that touches the pump. The pump cannot be left on in a state that should have it off. - Outputs follow the state. The status LED is worked out from the state on every pass, never toggled blindly, so it cannot get out of step.
- Nothing blocks. Each pass of the loop reads the time and the events and makes at most one move. A timeout is a comparison, never a delay.
Events from a noisy world
A button's contacts bounce for a few milliseconds as they close and open. The download debounces with an integrator in a 1 ms timer interrupt: TIM3 with PSC = 71 and ARR = 999, as in the timers lesson, started with HAL_TIM_Base_Start_IT(&htim3). The HAL then calls HAL_TIM_PeriodElapsedCallback every millisecond. In it, a count moves one step toward the raw input, and the stable state changes only when the count reaches 0 or 20. The input must agree for 20 ms in total. Bounce never gets that far; a real press always does.
From the stable button come two events:
- Short press: released before 2 s. It is only known on the release.
- Long press: still held at 2 s. It fires once, while the button is held, so the person sees the result without letting go.
Timeouts that survive the wrap
HAL_GetTick() counts milliseconds in an unsigned 32-bit number. With it, now - state_since >= limit is right even when the counter wraps, which happens after 2³² ms, about 49.7 days. A controller in a plant can run that long. now >= state_since + limit goes wrong at the wrap.
The watchdog
The STM32F103's independent watchdog (IWDG) resets the chip if the program does not feed it in time. It counts down on its own clock, the LSI oscillator, so it still works if the main clock fails. Once started, it cannot be stopped: only a reset ends it (stm32f1xx_hal_iwdg.c in ST's F1 HAL). CubeMX starts it in MX_IWDG_Init(), before USER CODE 2, so from that line on your program must feed it in time.
Its time comes from two numbers you set in CubeMX:
timeout = prescaler × (reload + 1) ÷ LSI frequency
The download sets prescaler 8 and reload 1249: 8 × 1250 ÷ 40 kHz = 250 ms. But 40 kHz is only typical. The datasheet promises the LSI between 30 and 60 kHz, so the real timeout is anywhere from 167 ms to 333 ms. Plan with the shortest.
Use it well:
- Feed it in one place, with
HAL_IWDG_Refresh(&hiwdg)in USER CODE 3, at the point the loop reaches only when a whole pass has run. Feeding it inHAL_TIM_PeriodElapsedCallbackis useless: the timer interrupt keeps running while the main loop is stuck. - Choose the time from your longest pass. Here that is a flash save:
HAL_FLASHEx_Erasereturns only when the page is erased, after 20 to 40 ms. The shortest real timeout, 167 ms, is four times that, and a hang still ends within a third of a second. - Know why you started. The reset flags in the RCC_CSR register say what caused the last reset, and a watchdog reset sets IWDGRSTF. In USER CODE 1, the first lines of
main(), the download reads that flag with__HAL_RCC_GET_FLAG(RCC_FLAG_IWDGRST)and keeps the answer, then clears every flag with__HAL_RCC_CLEAR_RESET_FLAGS(). The flags stay set through later resets until software clears them, or the power goes off. Without the clear, each press of the reset button after one watchdog reset looks like another one. Then start safe: pump off, FAULT, and a person must clear it. A pump that restarts by itself after a crash is how equipment gets damaged. - Freeze it under the debugger. The IWDG keeps counting while a breakpoint holds the core, so the chip resets under you.
__HAL_DBGMCU_FREEZE_IWDG()in USER CODE SysInit stops it while the core is halted, and changes nothing when the program runs on its own. CubeIDE's debug configuration has the same choice: Suspend watchdog counters while halted (UM2609, the STM32CubeIDE user guide).
Settings that survive
The STM32F103 has no EEPROM. Settings go in a page of flash that your program does not use. The STM32F103RB has 128 KB of flash in 1 KB pages, so its last page starts at 0x0801FC00. Three facts decide how you save (the STM32F103 datasheet, and stm32f1xx_hal_flash.c):
- Erase, then write. Flash is erased a whole page at a time, and an erased page reads 0xFFFF in every half-word. You can write a half-word only where the page is erased.
- Erasing is slow. A page erase takes 20 to 40 ms. Writing a half-word takes about 50 µs.
- Erasing wears it. A page is rated for 10 000 erase cycles.
Saved once a second, the page wears out in 10 000 s: under 3 hours. Saved only when a person changes the setting, a few times a year, it outlives the product. So save on a change, never on a timer. The download goes one step further: it compares the new settings with the saved ones, and erases only when they differ.
The HAL calls, in order: HAL_FLASH_Unlock(); HAL_FLASHEx_Erase() with FLASH_TYPEERASE_PAGES, the page address and one page; HAL_FLASH_Program(FLASH_TYPEPROGRAM_HALFWORD, address, value) for each half-word; then HAL_FLASH_Lock(). Each returns HAL_OK or an error. Check it.
Check what you read back, too. A new chip's page reads 0xFFFF, and a power cut in the middle of a save can leave the page erased, or only half written. The download stores a version number and a check word with the setting: the two added up, then inverted. If either is wrong, it loads a safe default instead of, say, run limit number 65 535. A save cut off before the check word leaves 0xFFFF there, which never matches, so that fails safe as well.
If a value must change often, do not erase every time. Write each new copy in the next empty slot of the page, and erase only when the page is full. A 1 KB page holds 170 copies of 6 bytes, so it wears 170 times more slowly. ST's EEPROM emulation example for this board, in STM32CubeF1, works this way.
Last, keep your program out of that page. CubeIDE's Build Analyzer shows where the program ends: it must end well below 0x0801FC00. For a product, also take that page out of the FLASH region in the linker script (the .ld file in the project), so the linker stops you first.
Worked example
The brief. A NUCLEO-F103RB runs a pump. A short press of B1, the blue button, starts or stops it. A level switch on PA10 stops it when the tank is full. If it runs for longer than the run limit without filling, it stops with a fault that only a long press clears. A long press when idle moves the run limit on through 30, 60 and 120 s, and the choice is saved. LD2 shows the state, and the terminal shows each change. A hang must end in a safe restart.
- The table. The one in the theory, written before any code.
- CubeMX. From
pump_controller_cubemx.md: PC13 and PA10 as inputs, PA10 with its pull-up; PA8 (the pump) and PA5 (LD2) as outputs that start Low; TIM3 with PSC 71, ARR 999 and TIM3 global interrupt ticked; IWDG Activated, with prescaler 8 and reload 1249; USART2 at 115 200 baud for the log. The Timebase Source stays SysTick, because the program writes its ownHAL_TIM_PeriodElapsedCallback. - The code.
pump_controller_user_code.cfills nine blocks. Block 1 reads the reset cause beforeHAL_Init(). SysInit freezes the watchdog under the debugger. Block 2 loads the settings, starts TIM3 withHAL_TIM_Base_Start_IT(&htim3), and enters IDLE, or FAULT after a watchdog reset. Block 3 runs the state machine once a millisecond, then callsHAL_IWDG_Refresh(&hiwdg). - Quick limits. Set
QUICK_LIMITSto 1, so the limits are 5, 10 and 20 s and a fault shows quickly. Debug it, press Resume (F8) when it stops atmain(), and open the virtual COM port at 115 200 baud.
Now test the controller against its table, one row at a time. Work out each time before you press anything:
| Time | You do | Terminal | Pump (PA8) | LD2 (PA5) | Row tested |
|---|---|---|---|---|---|
| 0 ms | power on | 0 ms: IDLE | off | off | start, not a watchdog reset |
| 0.5 to 0.7 s | short press | 720 ms: RUNNING | on | on | IDLE, short press |
| 0.7 to 5.7 s | wait | 5720 ms: FAULT | off | blinks at 4 Hz | RUNNING, limit reached |
| from 6.0 s | hold B1 | 8020 ms: IDLE | off | off | FAULT, long press |
| 8.6 to 8.8 s | short press | 8820 ms: RUNNING | on | on | IDLE, short press |
| 9.3 s | level switch to full | 9320 ms: IDLE | off | off | RUNNING, tank full |
Read the times the way an Expert would. RUNNING comes at 720 ms: the release at 0.7 s plus 20 ms of debounce, because a short press is only known when it ends. FAULT comes exactly 5000 ms later. IDLE comes at 8020 ms: the press at 6.0 s, 20 ms of debounce, then 2000 ms of hold. The level switch stops the pump 20 ms after it closes. Your numbers may be a millisecond or two later: SysTick and TIM3 tick separately, and the start-up code takes a moment.
Then test the rows a hurried tester skips:
- Tank full, then a short press in IDLE. Nothing happens: the "only if" of the first row.
- A long press in IDLE. The run limit moves on, and LD2 flashes once, twice or three times to show which. Press the black reset button: the new limit is still there. Pause the debugger and open the Memory view at 0x0801FC00: the three saved half-words are the version (1), the limit's number and the check.
- The watchdog. Set
TEST_WATCHDOGto 1, build, and start it with Run › Run As › STM32 C/C++ Application, so no debugger holds the core. Start the pump and hold B1 for 2 s. The program hangs on purpose. About a quarter of a second later the board restarts: the terminal shows FAULT, and the pump is off. That proves the watchdog and the safe start together. - The reset button after it. Clear the fault with a long press, then press the black reset button. The board must start in IDLE. If it starts in FAULT again, the reset flags were never cleared.
Practice task
- Write the state table first for a brief of your own: a garage door with OPENING, OPEN, CLOSING, CLOSED and STOPPED, a limit switch at each end, one button and a 20 s motor timeout.
- Set it up in CubeMX: the button, the two limit switches, two motor outputs that start Low, TIM3 for the 1 ms tick, the IWDG and USART2. Code it in the style of the download: one
enter()switches the outputs, the outputs follow the state, and there is noHAL_Delay()anywhere. - Test every row of your table. Print each change of state on the terminal with its time, and tick the row.
- Add the watchdog. Make the program hang on purpose, and prove the board restarts in a safe state. Then press the reset button and prove it starts normally.
- Save one setting in flash with a version and a check. Then cut the power in the middle of a save: put a breakpoint on the line after
HAL_FLASHEx_Erase, let the program stop there, and pull out the USB cable. Prove the program starts with the default.
Give yourself 90 minutes for the whole brief, CubeMX included, then mark it with the checklist on the section page.
Common mistakes
- Coding before the table exists. The Expert finds the missing rows for you.
- Switching outputs in many places. One forgotten line leaves the pump running in IDLE.
- A
HAL_Delay()inside a state. The buttons and the level switch go unread while it waits. - Feeding the watchdog in an interrupt callback, or in several places. It then never catches the hang it is there for.
- A watchdog time worked out at 40 kHz only. At 60 kHz it is a third shorter. If that is shorter than your longest pass, the board resets during normal work, such as a flash save.
- Reset flags read but never cleared. After one watchdog reset, every later start looks like another.
- Saving to flash on a timer, or on every pass. 10 000 erases are gone in hours.
- Trusting flash without a version and a check. An empty page gives you 65 535.
- A settings page your program grows into. The next save erases your own code. Check the Build Analyzer.
- Debugging with the watchdog running. Without the freeze, the board resets each time a breakpoint stops it.
Self-check
- You press B1 for 1.5 s and let go. Which event does the download make, and when?
- Why is
now - state_since >= limitright afterHAL_GetTick()wraps, butnow >= state_since + limitis not? After how long does it wrap? - Why is feeding the watchdog inside
HAL_TIM_PeriodElapsedCallbackuseless? - Your loop's longest pass is a 40 ms display update. A friend sets the IWDG to prescaler 4 and reload 499. Is that safe? What would you choose?
- A setting is saved to flash once a second. About how long until the page wears out, and what is the fix?
- The power fails just after
HAL_FLASHEx_Erase, before the new values are written. What does the download load at the next start, and why? - After one watchdog test, your board starts in FAULT every time you press the reset button, though nothing hangs. What is missing?
- Why does the download start in FAULT after a watchdog reset?
Show answers
- A short press. It is made on the release, 20 ms after the contacts open (the debounce), because only then is it known that the press ended before 2 s.
- Unsigned subtraction gives the time passed even across the wrap, because the result wraps too.
state_since + limitcan wrap to a small number, sonow >=comes true at once, long before the time is up. A 32-bit millisecond counter wraps after 2³² ms, about 49.7 days. - The timer interrupt keeps running even when the main loop is stuck, so the watchdog is fed for ever and never resets the hung program. Feed it only where the main loop proves it has finished a pass.
- No. 4 × 500 ÷ 40 kHz = 50 ms with a typical LSI, but at 60 kHz it is 33 ms, shorter than the 40 ms pass: some boards would reset during every display update. Choose a time whose shortest value is well above 40 ms, such as prescaler 8 and reload 1249: 167 ms at the shortest. Better still, split the display update into shorter steps.
- 10 000 erase cycles at one a second: 10 000 s, under 3 hours. Save only when the value changes, and compare it with the saved copy first. If it really must change often, write each copy into the next empty slot of the page, and erase only when the page is full.
- The default, the shortest run limit. An erased page reads 0xFFFF everywhere, so the version does not match and the download refuses the page. The setting is lost, but the pump starts with a safe limit.
__HAL_RCC_CLEAR_RESET_FLAGS(), or the line that calls it never runs. The reset flags in RCC_CSR stay set through later resets until software clears them, so IWDGRSTF from the test is still there at every start.- A watchdog reset means something hung. Starting in FAULT keeps the pump off until a person has looked, instead of restarting a machine that may have caused the problem.
Downloads
- pump_controller_cubemx.md: our CubeMX settings for the pump controller on a NUCLEO-F103RB: the pins, TIM3 for the 1 ms tick, the IWDG at 250 ms and USART2 for the log, then what to check in the generated code, and how to test the watchdog and the saved setting.
- pump_controller_user_code.c: the code for the USER CODE blocks of
main.c: the state machine, the debounce in the TIM3 callback, short and long presses, the reset cause, the watchdog, and the run limit in flash with a version and a check.QUICK_LIMITSandTEST_WATCHDOGswitch on the quick tests. We built it against ST's F1 HAL with no errors and no warnings.
Practise in ARGYNIX Lab
The Lab runs Arduino-style code on an Uno or a Blue Pill, so this is the same controller on the Uno: the same table, the same debounce, the same enter().
Open the pump controller in ARGYNIX Lab (opens in a new tab): an Uno with a button on D2, a level switch on D3, the pump (a green LED) on D7 and the status LED (red) on D13, running pump_controller_lab.ino, a sketch that also runs on a real Uno. In the Lab the run limits are 5, 10 and 20 s, as with QUICK_LIMITS, and the watchdog and the saved setting are left out, because the Lab's Uno does not model them.
Run the worked example's table. Click the button briefly: RUNNING, and the green LED lights. Wait 5 s: FAULT, and the red LED blinks. Hold the button for 2 s: IDLE. Start again and slide the level switch over: IDLE at once. Each change of state is on the Serial page with its time, and the Logic page shows D7 and D13 change with it.
Then test the rows people skip: the level switch on full, then a short press; a long press in IDLE, counting the flashes. Last, break a rule on purpose: delete || full from the RUNNING case and watch the pump run into a full tank. Put it back. The watchdog, the reset flags and the flash are the STM32 part: test them on the NUCLEO-F103RB with the main download.
Run it in your browser, then do it again on your own board.
Open in ARGYNIX Lab (opens in a new tab)