This section is worth 25% of the marks, the joint largest. An embedded system is a small computer built into a product to control it, such as the controller inside a washing machine. Its brain is usually a microcontroller (MCU): a processor, memory and input and output blocks on one chip. Here you write the C code that makes it work. We train on STM32 chips from ST, with ST's own tools: STM32CubeMX to set up the chip, STM32CubeIDE to write, build, flash and debug, and ST's HAL library in between.
What the standard asks
You will need to:
- Understand embedded systems and how microcontrollers connect to the world around them.
- Program the common peripherals of a microcontroller, and connect them to outside devices. A peripheral is a hardware block inside the chip, such as a timer or a serial port.
- Use power management features, such as the watchdog timer.
- Use the IDEs (integrated development environments: the editor, compiler and debugger in one program) that industry uses.
- Write, analyse, review and update C code that stores and reads data and controls equipment.
- Find and fix syntax errors, then build the code again.
- Check whether the processor and its peripherals really do what your program intends.
- Use standard C functions and functions you are given.
- Write your own functions for set tasks.
Why it matters on the competition floor
Code is usually checked by what it does. Does the display show the right value? Does the output switch at the right time? Does it still work when the button is pressed twice quickly? Code that almost works often earns little. Test every requirement, one by one, before time ends.
You may be given a library of functions. Read its header file first: the names, the arguments, the units and what each function returns. Five minutes of reading can save an hour of guessing.
The workstation will have its own versions of CubeMX and CubeIDE. Ask which ones, and practise in them: menus move between versions.
Topics, from Foundation to World
- Foundation. C for microcontrollers: fixed-size types (
uint8_t,uint16_t,int32_t), operators, functions and header files. - Foundation. Bits and registers: set, clear, toggle and test a bit, in binary and hex, and read a register in the debugger.
- Foundation. GPIO (general-purpose input and output pins): LEDs, buttons, pull-up resistors and debouncing.
- Foundation. The toolchain: STM32CubeMX for the pins, the clock tree, the peripherals and the generated code; STM32CubeIDE to build, flash (load the program into the chip) over the ST-LINK, and debug.
- State. Timers and PWM (pulse-width modulation: switching a pin fast to control brightness, speed or position), and timing without blocking delays.
- State. The ADC (analog-to-digital converter): read a sensor and scale the reading to volts and real units.
- State. UART serial: send text to a PC terminal and read simple commands.
- State. Interrupts: an interrupt runs your code when an event happens. The NVIC settings in CubeMX, the HAL's callbacks, shared variables, and short callbacks.
- National. I2C and SPI: talk to sensors, displays and memory chips using their datasheets.
- National. State machines: organise a program into clear modes, without blocking.
- National. Debugging: breakpoints, Live Expressions, the register view (SFRs), stepping, and a logic analyser on the bus.
- World. The watchdog, low-power modes, saving data in flash, reading a new library fast, and working at register level on an unfamiliar chip.
Key ideas to master
From CubeMX to the board. Since STM32CubeIDE 2.0 (November 2025), STM32CubeMX is a separate program. A project takes the same path every time. The toolkit says which versions we checked.
- In STM32CubeMX, start a new project from the chip (the MCU Selector) or from the board.
- In Pinout & Configuration, set System Core › SYS › Debug to Serial Wire first. Then click each pin to give it its job, and turn on each peripheral with its Parameter Settings and, if it needs an interrupt, its NVIC Settings.
- In Clock Configuration, follow the clock from left to right, to the system clock and to each bus. A box in red is a clock above its limit: fix it before you go on.
- In Project Manager, choose STM32CubeIDE as the Toolchain / IDE, then click GENERATE CODE.
- In STM32CubeIDE, the first time: File › STM32 Project Create/Import › Import STM32 Project. After each new generate: select the project in the Project Explorer and press F5 (Refresh).
- Write your code in the USER CODE blocks of
Core/Src/main.c, then Project › Build Project. Aim for no errors and no warnings. - Run › Debug As › STM32 C/C++ Application flashes the board over the ST-LINK and stops at
main(). Run › Run As › STM32 C/C++ Application flashes it and lets it run, with no debugger.
Your code goes in the USER CODE blocks. CubeMX writes main.c with pairs of comments, such as /* USER CODE BEGIN 2 */ and /* USER CODE END 2 */. Code between a pair survives the next generate. Code anywhere else is written over, without a warning (UM1718, the STM32CubeMX user manual). Never make a pair of your own: CubeMX keeps only the ones it wrote.
Bit operations. Most hardware is controlled by setting bits in registers. Learn these four by heart:
- Set bit 5:
REG |= (1u << 5); - Clear bit 5:
REG &= ~(1u << 5); - Toggle bit 5:
REG ^= (1u << 5); - Test bit 5:
if (REG & (1u << 5))
The HAL writes the registers for you, but the debugger shows you the registers themselves, so learn to read them. The STM32F103's registers and their bits are in RM0008, its reference manual.
The first program. In CubeMX, set PA5 to GPIO_Output: on a NUCLEO-F103RB that is LD2, the green LED. Then blink it from the main loop:
/* USER CODE BEGIN 3 */
HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_5); /* LD2 */
HAL_Delay(500);
/* USER CODE END 3 */
Block 3 sits inside the while (1) loop that CubeMX writes.
Reading a button. Set the pin to GPIO_Input in CubeMX, with Pull-up in its GPIO settings, and wire the button from the pin to ground. The pin reads GPIO_PIN_SET when released and GPIO_PIN_RESET when pressed. B1, the blue button on a Nucleo, works the same way on PC13, with its pull-up on the board.
if (HAL_GPIO_ReadPin(GPIOC, GPIO_PIN_13) == GPIO_PIN_RESET) {
/* pressed */
}
A real button bounces: its contacts open and close many times in the first few milliseconds. Read it again after about 20 ms, or sample it in a timer, before you trust it.
Interrupts and volatile. Tick the peripheral's interrupt in its NVIC Settings in CubeMX. CubeMX writes the interrupt handler, and the HAL then calls a callback: a function you write, with exactly the name the HAL gives it. A variable changed inside a callback must be volatile. This tells the compiler to read it from memory every time. Without it, the main loop may never see the change. The callback runs inside the interrupt, so keep it short: set a flag, and do the real work in the main loop.
/* USER CODE BEGIN PV */
volatile uint8_t tick = 0;
/* USER CODE END PV */
/* USER CODE BEGIN 0 */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
if (htim->Instance == TIM3) { /* once a second: PSC 7199, ARR 9999 at 72 MHz */
tick = 1;
}
}
/* USER CODE END 0 */
/* USER CODE BEGIN 2 */
HAL_TIM_Base_Start_IT(&htim3); /* CubeMX sets TIM3 up but does not start it */
/* USER CODE END 2 */
Do not block. HAL_Delay(500) stops everything for half a second, and a button press in that time can be missed. Use the millisecond counter instead:
/* USER CODE BEGIN 2 */
uint32_t last = HAL_GetTick();
/* USER CODE END 2 */
/* USER CODE BEGIN 3 */
if (HAL_GetTick() - last >= 500u) { /* 500 ms passed? */
last += 500u;
HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_5);
}
/* other work runs here without waiting */
/* USER CODE END 3 */
The subtraction still works when the counter rolls over, because the values are unsigned.
ADC and UART. STM32CubeMX generates the setup code for you. Here hadc1 and huart2 are the handles it creates when you turn on ADC1 and USART2.
char msg[32];
HAL_ADC_Start(&hadc1);
if (HAL_ADC_PollForConversion(&hadc1, 10) == HAL_OK) {
uint32_t raw = HAL_ADC_GetValue(&hadc1); /* 0 to 4095 on a 12-bit ADC */
int n = snprintf(msg, sizeof msg, "raw=%lu\r\n", (unsigned long)raw);
HAL_UART_Transmit(&huart2, (uint8_t *)msg, (uint16_t)n, 100);
}
HAL_ADC_Stop(&hadc1);
snprintf comes from stdio.h: put #include <stdio.h> in the USER CODE Includes block.
Scaling without overflow. On the STM32 an int is 32 bits, so 4095 × 3300 fits easily. Microvolts do not: 4095 × 3 300 000 is about 13.5 billion, and 32 bits hold only 4.29 billion. Know the size of every type you use, and do a big multiply in 64 bits:
uint32_t adc_to_mv(uint32_t raw) /* 12-bit ADC, 3.3 V reference */
{
return (raw * 3300u + 2048u) / 4096u; /* rounded */
}
uint32_t adc_to_uv(uint32_t raw)
{
return (uint32_t)(((uint64_t)raw * 3300000u + 2048u) / 4096u);
}
If you learned on an Arduino Uno, note the change: its int is only 16 bits, and here it is 32.
Watchdog. A watchdog is a timer that resets the chip if the program stops "feeding" it in time. It rescues a program that has hung. On the STM32F103 it is the independent watchdog, IWDG: tick System Core › IWDG › Activated in CubeMX, and set its prescaler and reload. Prescaler 32 and reload 1249 give 32 × 1250 ÷ 40 kHz = 1 s with a typical LSI, its clock. CubeMX starts it in MX_IWDG_Init(). Feed it only from the place where you know the program is healthy:
/* USER CODE BEGIN 3 */
do_work();
HAL_IWDG_Refresh(&hiwdg); /* feed the watchdog */
/* USER CODE END 3 */
The LSI is only promised between 30 and 60 kHz (STM32F103 datasheet), so that 1 s can be anywhere from 0.67 s to 1.33 s. The state machines lesson builds a whole controller around it.
Fixing build errors. Read the first error first; later errors are often caused by it. In CubeIDE the Problems view lists them: double-click one to go to its line, and also look at the line just above it. Common causes: a missing semicolon or brace, a misspelled name, or a missing #include. A warning about an "implicit declaration" means the compiler has not seen that function's declaration. Treat warnings as problems to fix.
Prove it works. Do not trust your eyes alone. Debug it: stop at a breakpoint, step, and read variables. Live Expressions shows variables while the program runs, and the SFRs view shows the registers the HAL wrote. Print values over UART. Look at the real pin with a scope or logic analyser and check the timing.
Practise with cheap equipment
You need an STM32 board with an ST-LINK probe. Our lessons use a NUCLEO-F103RB: its ST-LINK flashes and debugs the chip over one USB cable, and also passes USART2 to your PC as a virtual COM port, so you need no USB-to-serial adapter. A Blue Pill (STM32F103C8) is cheaper, but needs a separate ST-LINK probe. Add a breadboard, LEDs, buttons, a potentiometer, and later an I2C sensor.
ARGYNIX Lab (https://lab.argynix.com (opens in a new tab)) runs Arduino-style code on an Uno or a Blue Pill in your browser, and each lesson's Lab part shows the same idea there. Use it when you are away from your bench, then do the task again on a real board in CubeMX and CubeIDE, because the competition uses real hardware.
- Blink, then blink without blocking. Then blink two LEDs at different rates.
- Button counter. Count presses with debouncing and print the count over UART.
- Dimmer. Read a potentiometer with the ADC, print the value in millivolts, and use it to set a PWM duty cycle.
- Sensor from the datasheet. Read an I2C temperature sensor with
HAL_I2C_Mem_Readand its datasheet, without a ready-made library. - Traffic light. A state machine with a pedestrian button.
- Watchdog test. Make your program hang on purpose, watch the watchdog reset it, and detect the reset from the reset flags when it starts again.
- Port it. Make a working task run on a different STM32 board. Change the pins and the clock in CubeMX, and as little code as you can.
- Timed task. Write a one-page specification for a friend's task, then swap. 60 minutes, one attempt, CubeMX included.
Common mistakes
- A variable shared with an interrupt callback that is not
volatile. - Long work inside a callback, such as printing text. It runs inside the interrupt.
- A callback with a slightly wrong name. It compiles, and the HAL's empty version runs instead.
- Overflow in calculations: a multiply too big for its type.
- Code written outside the USER CODE blocks, then lost at the next generate.
- A peripheral set up in CubeMX but never started, such as a timer without
HAL_TIM_PWM_StartorHAL_TIM_Base_Start_IT. HAL_Delayeverywhere, so button presses are missed.- A wrong clock setting, so the UART prints rubbish because the baud rate (the serial speed) is wrong.
- Using a supplied function without reading what it returns. Most HAL functions return
HAL_OKor an error. - SYS Debug left on No Debug in CubeMX. On an STM32F1 the generated code can then turn the debug pins off, and the ST-LINK cannot connect after the first flash. To recover, hold the reset button while you connect.
How this section is marked
ARGYNIX practice marking guide, written by us; not the official WorldSkills marking scheme. The official marking scheme belongs to WorldSkills and is set for each competition. We do not copy it, and we do not claim to know it. Use this guide to mark your own practice work. For how a skill is marked in general, read how a skill is marked. For what this section covers, read the official standard (opens in a new tab).
Where its marks come from. Its marks usually come from programming tasks set from a written specification, often on hardware the competition supplies, sometimes with a library of functions you must use being checked.
Measurement marks. These check whether the program does what the specification says: the right output, at the right time, with the right value, every time it is tested.
Judgement marks. Where they are used, these look at the code itself: whether it is clear, well organised and easy for another programmer to follow.
A practice checklist. Mark a program you wrote from a one-page specification in 90 minutes. Write the specification with four requirements, or swap with a friend. The checklist below is out of 15 marks.
| # | Aspect | Type | Marks |
|---|---|---|---|
| 1 | The code builds with no errors and no warnings | M | 1 |
| 2 | Requirement 1 works exactly as written | M | 2 |
| 3 | Requirement 2 works exactly as written | M | 2 |
| 4 | Requirement 3 works exactly as written | M | 2 |
| 5 | Requirement 4 works exactly as written | M | 2 |
| 6 | Button presses never missed or counted twice, tested 20 times fast | M | 1 |
| 7 | No blocking delay where the specification needs a quick response | M | 1 |
| 8 | Values sent over UART are right, with their units | M | 1 |
| 9 | Supplied functions used correctly, with their return values checked | M | 1 |
| 10 | Readable code: clear names, short functions, comments where they help | J | 2 |
| Total | 15 |
Mark your own work. Give a measurement (M) aspect its full marks or nothing: it was done or it was not. Score a judgement (J) aspect from 0 to 3, the way Experts do: 0 is below industry standard, 1 meets it, 2 is better than it, and 3 is excellent. Then take that share of its marks: a score of 2 on a 1.5-mark aspect earns 1 mark.
Use your score. Test like an Expert: one requirement at a time, with the specification in your hand, and tick each one only when you have seen it work. Mark the same kind of task every two weeks and write the score in your training log.
Check yourself
- What does
GPIOA->ODR &= ~(1u << 3);do? - Why must a flag set inside a HAL callback be declared
volatile? - A 12-bit ADC with a 3.3 V reference reads 2048. What is the input voltage?
- Your UART prints rubbish characters. Give two likely causes.
- What does a watchdog timer do, and where in your program should you feed it?
- You changed one pin in CubeMX and generated the code again. Half your program has gone. Why, and how do you stop it happening again?
Show answers
- It clears bit 3 of GPIOA's output data register, so pin PA3 goes low if it is an output. The other bits do not change.
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_3, GPIO_PIN_RESET)does the same with a single write to the BSRR register. - So the compiler reads it from memory every time. Otherwise the main loop may keep an old copy and never see the change.
- 2048 × 3.3 V ÷ 4096 = 1.65 V.
- Any two of: different baud rates at each end; a wrong clock setting in the microcontroller; wrong frame settings (data bits, parity, stop bits); no common ground between the boards.
- It resets the microcontroller if the program does not feed it in time, so a hung program restarts. Feed it in the main loop, with
HAL_IWDG_Refresh(&hiwdg)in USER CODE 3, at a point the program only reaches when it is working normally. - That code was outside the USER CODE blocks, and CubeMX wrote over it. Put all your code between the
USER CODE BEGINandUSER CODE ENDcomments that CubeMX made, and generate once after each big change to check that it survives.
Materials
Equipment
- An STM32 board with an ST-LINK probe. Our lessons use the NUCLEO-F103RB, which has one built in.
- A breadboard, LEDs, buttons, a potentiometer and an I2C sensor.
- A logic analyser, if you can get one.
- A USB-to-serial adapter, for a board with no virtual COM port.
Software
- STM32CubeMX, to set up the chip and generate the code.
- STM32CubeIDE, to write, build, flash and debug. Both are free from ST, and the toolkit says which versions we checked.
- A serial terminal.
- ARGYNIX Lab (opens in a new tab), to practise the same ideas in the browser when you are away from your bench.
Printable checklist: before you say a program is done
- It builds with no errors and no warnings.
- Every requirement tested, one by one, against the specification.
- Buttons tested fast and many times.
- Timing checked on a scope or logic analyser, not by eye.
- My code is inside the USER CODE blocks, and survives a new generate.
- SYS Debug is set to Serial Wire in CubeMX.
- The project saved with a version in its name.
Print this page to take this checklist, the practice marking checklist and the self-check to your bench.
Free resources
- STM32CubeF1 on GitHub, STMicroelectronics (opens in a new tab): the HAL drivers and many example projects for STM32F1 chips, with a set for the NUCLEO-F103RB.
- STM32F1 HAL driver on GitHub, STMicroelectronics (opens in a new tab): the HAL's own source. Each driver file starts with a part called "How to use this driver".
- UM1850, the STM32F1 HAL and low-layer drivers, STMicroelectronics (opens in a new tab): every HAL function, its arguments and what it returns.
- UM1718, the STM32CubeMX user manual, STMicroelectronics (opens in a new tab): pins, clocks, peripherals and code generation.
- UM2609, the STM32CubeIDE user guide, STMicroelectronics (opens in a new tab): building, debugging, Live Expressions, the SFRs view and the Build Analyzer.
- RM0008, the STM32F10x reference manual, STMicroelectronics (opens in a new tab): every register of the chip, bit by bit.
- Embedded Systems: Shape the World, Jonathan Valvano and Ramesh Yerraballi, University of Texas at Austin (opens in a new tab): a free online textbook on embedded C for ARM Cortex-M chips.
- Embedded System Design with ARM, NPTEL (opens in a new tab): a free Indian course with hands-on ARM microcontroller work.
Lessons in this section
Each lesson goes further than this page, with a worked example, a practice task and a self-check. Take them in order.
0 of 3 lessons done
Timers and PWM on the STM32
Work out a timer's prescaler and period for any PWM frequency from the clock tree, set it in STM32CubeMX, change the duty with the HAL without a glitch, and prove it on the pin and in the debugger.
1 hSerial commands: an interrupt-driven UART
Set up a UART in STM32CubeMX, receive every byte under interrupt with the HAL into a ring buffer, build the bytes into lines, and parse commands that are checked and always answered.
1 hFirmware that does not hang: state machines, the watchdog and saved settings
Build a controller as a state machine with debounced events and timeouts, let the STM32's independent watchdog rescue a hang and start safe after it, and save settings in flash that survive power cuts and wear.
1 h