முதன்மை உள்ளடக்கத்திற்குச் செல்லவும்

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.

Lesson 1 of 31 hவரைவு

இந்தப் பாடம் மொழிபெயர்க்கப்படும் வரை ஆங்கிலத்தில் உள்ளது.

What the standard asks

Section 6 of the 2026 Electronics standard, Embedded systems programming, is worth 25% of the marks, the joint largest with assembly (WorldSkills Occupational Standards, Electronics, WorldSkills Shanghai 2026, checked 2026-11-25). It asks you to program a microcontroller's peripherals, and to check that the processor and those peripherals really do what your program intends.

It also asks you to use the IDEs that industry uses. We train on two programs from ST: STM32CubeMX sets up the chip and writes the start-up code, and STM32CubeIDE is where you write the rest, build, flash and debug. The toolkit says what each one is for and which versions we checked. Our board is the NUCLEO-F103RB: an STM32F103RB, the chip of many training boards, with an ST-LINK probe built in.

Timers are the peripheral you will use most. Every blink, PWM output, debounce and timeout in a task depends on one. This lesson shows how to work out any timer setting from the clock tree, set it in CubeMX, drive it with the HAL (ST's Hardware Abstraction Layer library), and prove the result on the pin and in the debugger.

The theory

Three numbers set a timer

A timer counts clock pulses. On the STM32 its clock is divided by PSC + 1, then it counts from 0 up to ARR and starts again, so one period is ARR + 1 counts:

f = timer clock ÷ ((PSC + 1) × (ARR + 1))

A compare value, CCR1 for channel 1, sets where in that period the pin changes. That gives the duty.

To design, turn it round: (PSC + 1) × (ARR + 1) = timer clock ÷ f. Try the smallest prescaler first and take the first one whose ARR fits in 16 bits, 65 535 at most. A small prescaler gives a large ARR, and a large ARR gives fine steps of duty. The resolution in bits is log2(ARR + 1).

Both registers hold a count minus one. PSC = 71 divides by 72. ARR = 999 makes a period of 1000 counts.

Where the timer clock comes from

Read the clock tree in CubeMX's Clock Configuration tab from left to right. On a NUCLEO-F103RB, 8 MHz comes in from the ST-LINK. The PLL multiplies it by 9: 72 MHz, the fastest this chip runs. TIM2 to TIM4 sit on the APB1 bus, which may not run faster than 36 MHz, so APB1 is divided by 2.

Now the trap. When the APB1 prescaler is not 1, the timers on APB1 get twice the bus clock: 72 MHz, not 36 MHz (RM0008, the STM32F10x reference manual, clock tree). CubeMX shows it in its own box, the APB1 timer clock. Work out PSC from 36 MHz and your PWM comes out at twice the frequency you planned.

Frequency against resolution

With a 72 MHz timer clock:

NeedPSCARRDuty steps
1 kHz for an LED135 99936 000
20 kHz for a motor, above hearing035993600
50 Hz for a servo7119 99920 000, 1 µs each

At 20 kHz you have 3600 steps, about 11.8 bits. That is the trade: a faster PWM has coarser duty. For a servo the size of a step matters more than their number. PSC = 71 makes one count 1 µs, so a 1.5 ms pulse is CCR1 = 1500.

Duty in PWM mode 1

In PWM mode 1, counting up, the pin is HIGH while the count is below CCR1 (RM0008, PWM mode). So duty = CCR1 ÷ (ARR + 1). With ARR = 999, CCR1 = 250 gives 250 counts HIGH out of 1000: 25.0%. CCR1 = 0 is a true 0%, and any CCR1 above ARR holds the pin HIGH: 100%. No special cases at either end.

CubeMX's Counter Mode Up gives edge-aligned PWM: the count runs up, then jumps back to 0. The Center Aligned modes count up to ARR and back down, so one period is 2 × ARR counts and the pulse sits in the middle of it. Motor drives use it. For the same ARR, the frequency is about half.

Change the duty without a glitch

A new CCR1 written in the middle of a period can spoil that period: a pulse cut short, or an edge missed. The timer can hold the new value in a preload register and copy it across at the next update event, the start of the next period (AN4776, the general-purpose timer cookbook, the preload feature). In CubeMX that is Output compare preload: Enable for CCR1, and auto-reload preload: Enable for ARR.

Then __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_1, value) is safe at any moment. It is a macro that writes CCR1, nothing more (stm32f1xx_hal_tim.h in ST's F1 HAL, version 1.1.10). The HAL init functions that the generated MX_TIM2_Init() calls also set the UG bit once, which loads PSC and ARR before the timer starts.

CubeMX sets the timer up but does not start it. Call HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1) once, in USER CODE 2. Forget it and the pin stays LOW.

A tick that never blocks

HAL_Init() starts SysTick with an interrupt every millisecond, and HAL_GetTick() returns the count. Compare times; never wait:

if (now - last_led >= 250u) {   /* unsigned: still right when the count wraps */
    last_led += 250u;           /* += keeps the rhythm; last_led = now would drift */
    HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_5);   /* LD2 */
}

HAL_Delay() waits in a loop, and nothing else in the main loop runs meanwhile. Keep it for start-up, if at all.

For your own tick, use a timer. TIM3 with PSC = 71 and ARR = 999 overflows every 1 ms. Tick TIM3 global interrupt in its NVIC Settings, start it with HAL_TIM_Base_Start_IT(&htim3), and the HAL calls HAL_TIM_PeriodElapsedCallback every time. The state machines lesson debounces its buttons in one.

A variable changed in an interrupt and read in the main loop must be volatile. A 32-bit read is one instruction on the Cortex-M3, so the interrupt cannot change it halfway through. Two variables that must agree, or a count that both sides change, still need interrupts off for those few instructions: __disable_irq(), then __enable_irq().

Where your code goes

CubeMX writes main.c with pairs of comments: USER CODE BEGIN 2 and USER CODE END 2, and so on. Only what is between a pair survives the next generate (UM1718, the STM32CubeMX user manual). Never invent a pair of your own: CubeMX keeps only the ones it wrote. In this lesson, variables go in PV, functions in 0, start-up calls in 2, and the loop body in 3, which sits inside while (1).

Worked example

The brief. A NUCLEO-F103RB drives an LED on PA0 with a 1 kHz PWM whose duty follows a knob on PA1. LD2, the green LED on PA5, blinks at 2 Hz. Nothing may block.

  1. The timer. In CubeMX, click PA0: TIM2_CH1 is on its list. Then set TIM2's Channel1 to PWM Generation CH1.
  2. The clock. 72 MHz system clock and APB1 divided by 2, so TIM2 counts at 72 MHz.
  3. PSC and ARR for 1 kHz. 72 MHz ÷ 1 kHz = 72 000 counts in each period.
PSCTimer counts atARR for 1 kHzFits 16 bits?Duty steps
072 MHz71 999No
136 MHz35 999Yes36 000 (15 bits)
711 MHz999Yes1000 (10 bits)

PSC = 1 is the first that fits, and it gives the finest duty. For an LED, 1000 steps of 0.1% are plenty, and PSC = 71 makes one count 1 µs, so CCR1 is the HIGH time in microseconds: easy to check on a scope. We take PSC = 71 and ARR = 999. When a brief asks for the finest duty, take PSC = 1.

  1. Duty from the knob. ADC1 is 12-bit, 0 to 4095. In tenths of a percent, duty = (raw × 1000 + 2047) ÷ 4095, rounded, 0 to 1000. With ARR + 1 = 1000, CCR1 is that number: 25.0% is CCR1 = 250. The code reads ARR from the timer, so the duty stays right if you change the frequency later.
  2. The tick. HAL_GetTick(): read the knob every 10 ms, toggle LD2 every 250 ms.
  3. The code. timers_pwm_user_code.c has four blocks: PV, 0, 2 and 3. Block 2 calibrates the ADC with HAL_ADCEx_Calibration_Start(&hadc1) and starts the PWM with HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1).
  4. Prove it. Start a debug session and add knob_raw and duty_permille to Live Expressions. Turn the knob until duty_permille reads 250. Put a scope or logic analyser on PA0. Expect a period of 1.000 ms, a HIGH time of 250.0 µs and a duty of 25.0%. LD2 should be on for 250 ms and off for 250 ms. Then pause and open the SFRs view: TIM2 shows PSC = 71, ARR = 999 and CCR1 = 250, the numbers you worked out, now in the chip.

If PA0 reads 2 kHz, someone set PSC = 35 for a 36 MHz timer clock that does not exist. If PA0 stays LOW, HAL_TIM_PWM_Start never ran.

Practice task

  1. Build the project from timers_pwm_cubemx.md, add timers_pwm_user_code.c, and debug it on the board. Put a scope or logic analyser on PA0. Fill a table at five knob settings: duty_permille from Live Expressions, the duty measured, the frequency measured.
  2. Change the design to 20 kHz. Work out PSC and ARR before you look at the table above. Change them in CubeMX, generate again, press F5 in CubeIDE, and check that your code survived. Measure. How many duty steps do you have now?
  3. Make a 50 Hz servo signal on PA0 with pulses of 1.0, 1.5 and 2.0 ms. Work out PSC, ARR and the three CCR1 values, set them with __HAL_TIM_SET_COMPARE, and measure each pulse with cursors.
  4. Set PSC = 35, as someone who forgot the doubled timer clock would. Predict the frequency, then measure it.
  5. Time yourself from a one-line brief to a measured, correct output: "2.5 kHz at 30% duty on PA6". PA6 is TIM3_CH1. Target: under 10 minutes, CubeMX included.

Common mistakes

  • No HAL_TIM_PWM_Start. CubeMX sets TIM2 up and leaves it stopped. The pin stays LOW.
  • Forgetting the doubled timer clock on APB1. You work it out for 36 MHz, and the PWM comes out at twice the frequency you planned.
  • Off by one. PSC and ARR are "counts minus one": dividing by 72 is PSC = 71, and 1000 counts is ARR = 999.
  • Your code outside the USER CODE blocks. The next generate deletes it, without a warning.
  • Preload left on Disable. A glitch each time the duty or the period changes.
  • last = now in a non-blocking timer. Each late pass adds to the drift. Use last += interval.
  • SYS Debug left on No Debug. On an F1 the generated code can turn the debug pins off, and the ST-LINK cannot connect after the first flash. Set Serial Wire; to recover, hold the reset button while you connect.
  • Trusting the numbers in the code. Measure the pin.

Self-check

  1. You need 4 kHz PWM from TIM2 at a 72 MHz timer clock, with the finest duty. Give PSC, ARR and the number of duty steps.
  2. With PSC = 71 and ARR = 999, what CCR1 gives 25% duty, and what is the HIGH time? What do CCR1 = 0 and CCR1 = 1000 give?
  3. You flash the program, and PA0 stays LOW although MX_TIM2_Init() ran. What is the most likely cause?
  4. On a 72 MHz STM32F103 you set TIM2 to PSC = 71 and ARR = 999. A friend says the PWM is 500 Hz, because APB1 runs at 36 MHz. Who is right?
  5. You want a 1 ms interrupt from TIM3 at a 72 MHz timer clock. Why does PSC = 0 not work, and which settings do?
  6. You call __HAL_TIM_SET_COMPARE in the middle of a period, with Output compare preload enabled. When does the new duty start, and why does that matter?
  7. A volatile uint32_t counter is changed in an interrupt. Why can the main loop read it without turning interrupts off? When must you turn them off?
Show answers
  1. 72 MHz ÷ 4 kHz = 18 000 counts. PSC = 0 and ARR = 17 999, which fits in 16 bits: 18 000 steps, about 14 bits. A larger PSC would only make the steps coarser.
  2. CCR1 = 250. The pin is HIGH while the count is below 250: 250 counts of 1 µs, so 250 µs of every 1000 µs. CCR1 = 0 gives 0%, the pin never goes HIGH. CCR1 = 1000 is above ARR, so the pin stays HIGH: 100%.
  3. HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1) was never called: CubeMX sets the timer up but does not start it. The next thing to check: PA0 set to TIM2_CH1 in CubeMX.
  4. You are. When the APB1 prescaler is not 1, the timers on APB1 run at twice the bus clock, 72 MHz. 72 MHz ÷ 72 ÷ 1000 = 1 kHz.
  5. 72 MHz ÷ 1 kHz = 72 000 counts, more than a 16-bit ARR holds. PSC = 1 with ARR = 35 999 works, and so does PSC = 71 with ARR = 999.
  6. At the next update event, the start of the next period. The new value waits in the preload register, so no period is cut short and none gets an extra edge.
  7. A 32-bit read is one instruction on the Cortex-M3, so the interrupt cannot change the value halfway through it. Turn interrupts off when both sides change the same variable (a read, an add and a write can be split), or when two variables must agree with each other.

Downloads

  • timers_pwm_cubemx.md: our CubeMX settings for the worked example on a NUCLEO-F103RB: the pins, the 72 MHz clock tree, TIM2 with PSC 71 and ARR 999, the ADC, then what to check in the generated code and in the debugger.
  • timers_pwm_user_code.c: the code for the USER CODE blocks of main.c: the knob read with the ADC, the duty set with __HAL_TIM_SET_COMPARE, and the 2 Hz blink from HAL_GetTick(). 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 project is the same idea on the Uno's ATmega328P. The names change; the maths does not:

IdeaSTM32, this lessonUno, in the Lab
Timer clock72 MHz16 MHz
PrescalerPSC = 71, divide by 72N = 1
Top of the countARR = 999ICR1 = 15 999 (PWM_TOP)
Compare valueCCR1OCR1A
1 ms tickSysTick, HAL_GetTick()Timer2, OCR2A = 249

One difference to notice: in the AVR's fast PWM the pin is HIGH for OCR1A + 1 counts (ATmega328P datasheet, Timer1), so 25% of 16 000 counts is OCR1A = 3999, not 4000.

Open the Timer1 PWM project in ARGYNIX Lab (புதிய தாவலில் திறக்கும்): an Uno with a knob on A0, an LED on D9 and an LED on D13, running timers_pwm_lab.ino, a sketch that also runs on a real Uno. It builds and runs as it opens. Turn the knob: the D9 LED dims and brightens, and the Serial page prints the duty twice a second.

Open the Logic page: D9 shows its duty in percent at the right, and D13 switches every 250 ms. Turn the knob until Serial says 25.0% and check that the Logic page agrees. It shows each pin's share of time HIGH about 60 times a second, so a 1 kHz PWM appears as its duty, not as pulses: measure frequency and edges on a real board.

Then change the code, and predict before you run:

  • PWM_TOP to 799: 20 kHz. The duty still follows the knob, now in steps of 1 in 800.
  • OCR2A = 249 to OCR2A = 124: the tick is now every 0.5 ms. Everything timed by it runs twice as fast: D13 blinks at 4 Hz and Serial prints four times a second.

The Lab runs the Uno's real chip, instruction by instruction, so these registers behave as they would on a real Uno. The STM32 version of this lesson needs a real board: the Lab's Blue Pill does not model TIM2 and the ADC registers. Use the Lab to practise the maths, then do the worked example again on the NUCLEO-F103RB with CubeMX and CubeIDE.

Run it in your browser, then do it again on your own board.

Open in ARGYNIX Lab (புதிய தாவலில் திறக்கும்)

இந்தச் சாதனத்தில் மட்டுமே சேமிக்கப்படும்.

ஆதாரம்: WorldSkills Occupational Standard, Electronics, 2026; st.com; st.com; st.com; github.com; st.com; st.com; st.com; ww1.microchip.com. சரிபார்த்தது 25 நவம்பர், 2026.

அதிகாரபூர்வ தரநிலையிலிருந்து எங்கள் சொந்த வார்த்தைகளில் எழுதப்பட்டது. இது அதிகாரபூர்வ WorldSkills ஆவணம் அல்ல.