Learn / Pins: in and out · guide 5 of 10

Precise timing and PWM

An LED on Arduino pin D3 fades in and out smoothly, driven by a timer, and you have a 1 ms tick and a timer interrupt you can trust.

Intermediate≈ 60 minBefore this:Blink an LED, Print to your PC over the virtual COM portTopics:TIM

Busy-wait delays drift with the clock and the compiler. You build a real millisecond clock with SysTick, then use timer TIM3 two ways: as an interrupt every 500 ms, and as a PWM generator that dims an external LED on pin PA6 without the CPU touching the pin.

You will learn
  • Set up SysTick for a 1 ms tick and write a delay that does not depend on the compiler
  • Where a timer gets its clock from and how PSC and ARR set its rate
  • Run code from a timer update interrupt, and why the update flag must be cleared before enabling it
  • Generate PWM on a pin with an alternate function and change the duty cycle with CCR1
You need
  • STM32H750B-DK and a USB cable to CN14
  • STM32CubeIDE installed
  • A LED (any colour), a 330 Ω resistor and two jumper wires (a breadboard helps)

On this board

Pulled from the datasheet tables and the board schematic. Click a pin for everything the finder knows about it.

PinBallBoard netUsed here asAFOpen
PA6R3ARD_D3Arduino D3: PWM output to your external LEDAF2 TIM3_CH1
PJ2T6LED1LD7, green user LED (active-low), blinks from the timer interrupt
1

A clock you can trust: SysTick

The Blink guide waited with an empty for loop. How long it waits depends on the clock speed and on how the compiler optimises the loop, so it is only good for a demo. The Cortex-M7 core has a small timer built for this job: SysTick, a 24-bit counter that counts down from a reload value, and when it reaches 0 it can raise an interrupt and start over.

The idea: make it fire exactly every millisecond and count the interrupts in a variable. Then "wait 500 ms" means "wait until the counter has grown by 500".

SysTick counts processor clock cycles. For a period of N cycles the reload value is N − 1 (the manual's own example: every 100 clock pulses, reload = 99). One millisecond is SystemCoreClock / 1000 cycles: after reset the core runs from the 64 MHz internal oscillator, so that is 64 000 and the reload is 63 999. The reload register holds at most 24 bits (16 777 215), which is more than enough for a 1 ms tick.

The programming manual gives the start-up order: reload value, clear current value, then control register. The control register has three bits you need: CLKSOURCE (1 = processor clock), TICKINT (raise the interrupt) and ENABLE. The handler's name, SysTick_Handler, comes from the startup file.

#include "stm32h7xx.h"   /* with STM32H750xx defined by the project */

static volatile uint32_t ms_ticks;               /* milliseconds since start */

void SysTick_Handler(void)                       /* name comes from the startup file */
{
    ms_ticks++;
}

static void systick_init(void)
{
    /* order from the Programming Manual (4.4.5): reload, clear current, control */
    SysTick->LOAD = SystemCoreClock / 1000U - 1U;     /* N cycles = reload N-1 */
    SysTick->VAL  = 0U;
    SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk        /* count processor clock cycles */
                  | SysTick_CTRL_TICKINT_Msk          /* interrupt when it reaches 0 */
                  | SysTick_CTRL_ENABLE_Msk;
    /* Shortcut that does the same and also sets the lowest priority:
       SysTick_Config(SystemCoreClock / 1000U); */
}

static void delay_ms(uint32_t ms)
{
    uint32_t start = ms_ticks;
    while ((uint32_t)(ms_ticks - start) < ms) {
        __WFI();                                  /* sleep until the next interrupt */
    }
}

int main(void)
{
    RCC->AHB4ENR |= RCC_AHB4ENR_GPIOJEN;
    (void)RCC->AHB4ENR;
    GPIOJ->MODER = (GPIOJ->MODER & ~GPIO_MODER_MODE2_Msk)
                 | (1U << GPIO_MODER_MODE2_Pos);

    systick_init();
    for (;;) {                                    /* short flash, long pause: exact timing */
        GPIOJ->BSRR = GPIO_BSRR_BR2;              /* LD7 on (active-low) */
        delay_ms(100);
        GPIOJ->BSRR = GPIO_BSRR_BS2;              /* LD7 off */
        delay_ms(900);
    }
}

Tip. A reload value of 0 does nothing, because the interrupt and COUNTFLAG happen when the counter goes from 1 to 0. Counting from N − 1 down to 0 takes exactly N clock cycles, hence the N − 1 rule.

2

A general-purpose timer and its clock

SysTick is one fixed timer. The chip also has many programmable timer peripherals. We use TIM3, a general-purpose timer: a 16-bit counter that counts up from 0 to the value in the auto-reload register TIM3_ARR, and then starts again from 0. That wrap-around is the update event (see ARR and CCR). Three registers set the rhythm:

  • TIMx_PSC (prescaler): divides the input clock by PSC + 1.
  • TIMx_ARR: the counter counts 0 … ARR, so one period is ARR + 1 ticks.
  • So: update rate = timer clock / ((PSC + 1) × (ARR + 1)).

(The counter of TIM3 and TIM4 is 16 bits wide, so ARR must be at most 65 535. TIM2 and TIM5 have 32 bits.)

What is the timer clock? Like every peripheral, TIM3 needs its bus clock switched on first: TIM3EN in RCC_APB1LENR. Its input frequency comes from Table 57 in the RCC chapter: when the APB1 prescaler is 1 (the reset value) and bit TIMPRE is 0 (also the reset value), the timer clock equals the AHB clock, 64 MHz after reset. If your clock setup divides APB1 by 2 or more, the timer clock is twice the APB1 clock. Check this in your clock tree before computing PSC and ARR.

Example for an update every 500 ms at 64 MHz: PSC = 6399 gives a 10 kHz counter (64 000 000 / 6400), and ARR = 4999 gives 5000 ticks = 0.5 s.

3

A timer interrupt: blink LD7 every 500 ms

Let us make the timer call you. The setup order matters here, because of how the timer buffers its settings: PSC and ARR are preloaded, which means a new value only reaches the working copy at the next update event. So after writing them, force one update event yourself with UG in TIMx_EGR.

That forced update also sets the update flag UIF in TIMx_SR. If you enable the update interrupt first, the CPU jumps into your handler once at start-up for no reason. So: write PSC and ARR, set UG, clear UIF, only then set UIE in TIMx_DIER, enable the interrupt in the NVIC and finally start the counter with CEN in TIMx_CR1.

In the handler, clear UIF again. The status flags of this timer are "write 0 to clear" (the manual calls this rc_w0), so you write the complement: TIM3->SR = ~TIM_SR_UIF clears UIF and leaves the other flags alone.

void TIM3_IRQHandler(void)                    /* name comes from the startup file */
{
    if (TIM3->SR & TIM_SR_UIF) {
        TIM3->SR = ~TIM_SR_UIF;                   /* rc_w0: write 0 to clear UIF only */
        if (GPIOJ->ODR & GPIO_ODR_OD2) GPIOJ->BSRR = GPIO_BSRR_BR2;   /* toggle LD7 */
        else                           GPIOJ->BSRR = GPIO_BSRR_BS2;
    }
}

static void tim3_update_irq_init(void)
{
    RCC->APB1LENR |= RCC_APB1LENR_TIM3EN;
    (void)RCC->APB1LENR;

    TIM3->PSC = 6399U;                            /* 64 MHz / 6400 = 10 kHz */
    TIM3->ARR = 4999U;                            /* 5000 ticks = 500 ms */
    TIM3->EGR = TIM_EGR_UG;                       /* copy PSC and ARR to the working registers now ... */
    TIM3->SR  = ~TIM_SR_UIF;                      /* ... and forget the update flag that caused */

    TIM3->DIER = TIM_DIER_UIE;                    /* update interrupt on */
    NVIC_SetPriority(TIM3_IRQn, 5);
    NVIC_EnableIRQ(TIM3_IRQn);

    TIM3->CR1 = TIM_CR1_CEN;                      /* go */
}

Tip. Call tim3_update_irq_init() from main() after systick_init(), then loop on __WFI(). LD7 now blinks without your main loop doing anything: that is the point of an interrupt.

4

Wire the external LED

Now the same timer will drive a pin directly. The two user LEDs LD6 and LD7 cannot be dimmed this way: their pins (PI13 and PJ2) have no timer output, you can see that in the alternate-function table of the datasheet. So we use an external LED on an Arduino header pin.

Pin D3 of the Arduino header is PA6, and PA6 can be the output of TIM3 channel 1 (TIM3_CH1) with alternate function number 2. The datasheet also shows other pins with a timer channel (for example D5 = PA8 with TIM1_CH1), so you could choose differently.

Wire: D3 → 330 Ω resistor → LED anode (long leg); LED cathode (short leg) → GND on the header. This LED is wired the opposite way from the on-board ones: it lights when the pin is high. The resistor limits the current to roughly (3.3 V − about 2 V across a red LED) / 330 Ω ≈ 4 mA, well below the 20 mA the datasheet allows a pin to sink. Note the caution in the user manual: the I/Os of this header are 3.3 V, not the 5 V of a classic Arduino Uno.

5

PWM: the timer drives the pin

A pin can only be fully on or fully off, so how do you dim an LED? You switch it on and off so fast that the eye only sees the average. That is PWM: a fixed period and a variable duty cycle, the fraction of the period that the pin is high.

The timer does it in hardware. In PWM mode 1 a channel's output is high while the counter is below the compare value CCR1, and low from there until the counter wraps:

  • Period = (PSC + 1) × (ARR + 1) / timer clock. With PSC = 63 and ARR = 999, the counter ticks at 1 MHz and wraps every 1000 ticks, so the PWM frequency is 1 kHz. That is far above what the eye notices as flicker.
  • Duty = CCR1 / (ARR + 1). With ARR = 999: CCR1 = 250 means 25 %, 1000 means always high, 0 means always low. You get 1000 brightness steps.

What you have to set, in order:

  1. Clocks for port A and TIM3, then PA6 in alternate-function mode (MODER = 10) with AF2 in GPIOx_AFRL (pin 6 is in the low register).
  2. PSC, ARR, and a first CCR1.
  3. In TIMx_CCMR1: OC1M = 110 (PWM mode 1), and OC1PE = 1 so a new CCR1 waits until the period ends (no glitch mid-period).
  4. In TIMx_CCER: CC1E = 1 connects the channel to the pin. Without it the pin stays silent.
  5. UG to load everything, then CEN.

After that the CPU does nothing for the pin. Changing brightness is a single write to CCR1.

static void pwm_init(void)
{
    /* clocks: port A and TIM3 */
    RCC->AHB4ENR  |= RCC_AHB4ENR_GPIOAEN;
    RCC->APB1LENR |= RCC_APB1LENR_TIM3EN;
    (void)RCC->APB1LENR;

    /* PA6 = TIM3_CH1: alternate function mode, AF2 (pins 0..7 are in AFRL = AFR[0]) */
    GPIOA->MODER  = (GPIOA->MODER & ~GPIO_MODER_MODE6_Msk) | (2U << GPIO_MODER_MODE6_Pos);
    GPIOA->AFR[0] = (GPIOA->AFR[0] & ~GPIO_AFRL_AFSEL6_Msk) | (2U << GPIO_AFRL_AFSEL6_Pos);

    TIM3->CR1  = 0U;                              /* stopped */
    TIM3->DIER = 0U;                              /* update interrupt of step 3 off */
    TIM3->PSC  = 63U;                             /* 64 MHz / 64 = 1 MHz counter clock */
    TIM3->ARR  = 999U;                            /* 1000 ticks = 1 kHz PWM */
    TIM3->CCR1 = 250U;                            /* 25 % duty */

    /* channel 1 is an output (CC1S = 00, reset value); PWM mode 1 = OC1M 110; preload on */
    TIM3->CCMR1 = (TIM3->CCMR1 & ~TIM_CCMR1_OC1M_Msk)
                | TIM_CCMR1_OC1M_1 | TIM_CCMR1_OC1M_2
                | TIM_CCMR1_OC1PE;
    TIM3->CCER |= TIM_CCER_CC1E;                  /* connect the channel to the pin */

    TIM3->CR1 = TIM_CR1_ARPE;                     /* buffer ARR too */
    TIM3->EGR = TIM_EGR_UG;                       /* load PSC, ARR and CCR1 into the working registers */
    TIM3->CR1 |= TIM_CR1_CEN;                     /* start */
}

Tip. Start with the 25 % duty: the LED is clearly dimmer than at 100 %. If it is on at full brightness or off, jump to the pitfalls below.

6

Make the LED breathe

Now put SysTick and PWM together. Every 10 ms, take one step along a triangle that goes 0 → 100 → 0, and set CCR1 from it. 200 steps × 10 ms makes a 2 s breathing cycle.

One more observation: the eye does not see brightness linearly. A duty of 50 % looks a lot brighter than half of full brightness. Squaring the triangle value (the t * t / 10 below, which still runs from 0 to 1000) makes the fade look much more even. Try a plain linear version and compare.

Notice that the CPU only writes one register every 10 ms. The waveform on the pin keeps running between the writes, because the timer generates it.

int main(void)
{
    uint32_t phase = 0U;                          /* 0..199 */

    systick_init();                               /* from step 1 */
    pwm_init();

    for (;;) {
        uint32_t t = (phase < 100U) ? phase : 200U - phase;   /* triangle 0..100..0 */
        TIM3->CCR1 = t * t / 10U;                              /* 0..1000, squared = looks even */
        phase = (phase + 1U) % 200U;
        delay_ms(10);
    }
}
7

Make it yours

Things to try once it works:

  • Move the PWM to another pin: D5 is PA8 with TIM1_CH1 (the advanced timer TIM1 needs one extra step, the main output enable bit MOE in TIM1_BDTR, see its chapter).
  • Change the PWM frequency to 100 Hz and watch the LED flicker. Where does it become visible?
  • Run the update interrupt of step 3 and the PWM of step 5 on different timers (TIM4 for the interrupt) and see both at once.
  • Replace the triangle with a lookup table of 64 sine values for a smoother breathing effect.

Common mistakes

  • Doing the timer maths with the wrong clock. The timer clock is not always the APB1 clock: with an APB1 prescaler above 1 it is twice that. Read Table 57 and your own clock tree.
  • Enabling the update interrupt before clearing UIF after the forced UG: the handler runs once straight away.
  • Forgetting to clear UIF in the handler: the interrupt fires again and again and your main loop starves.
  • PWM pin silent: CC1E not set, wrong AF number, or the pin still in analog mode (MODER reset value is 11).
  • Writing a CCR1 bigger than ARR: the output stays high all the time (100 %). That is documented, not a bug.
  • Expecting HAL_Delay to work inside an interrupt of higher priority than SysTick: the tick can never advance and the program hangs. Give SysTick the highest priority or avoid delays in handlers.
  • Connecting the LED the wrong way round (nothing lights) or without a resistor (stresses the pin and the LED).

Check yourself

Try to answer before opening. If you get stuck, the pages linked above have the answer.

The timer clock is 200 MHz. Which PSC and ARR give a 1 kHz PWM with 1000 duty steps?

PSC = 199 makes a 1 MHz counter (200 MHz / 200). ARR = 999 gives 1000 ticks per period, so 1 MHz / 1000 = 1 kHz, and CCR1 runs from 0 to 1000.

Why does the code write TIM3->EGR = TIM_EGR_UG before starting the timer?

PSC, ARR and (with the preload bit) CCR1 only reach the working registers at an update event. Without it the counter would start with the old values and the first period would be wrong.

Could you dim LD7 (PJ2) with PWM instead of an external LED?

Not from a timer. The datasheet lists only LCD_R3 and EVENTOUT as alternate functions of PJ2, so no timer channel can drive that pin. You would have to toggle it from software or from a timer interrupt, which costs CPU time and is much less precise.

Reading list

Every page this guide sent you to, by document. Reading them in order is a good revision.

PM0253PM0253 Cortex-M7 programming manualp.42p.184p.212p.213p.214p.216
RM0433RM0433 reference manual (STM32H742/743/753/750)p.349p.457p.461p.540p.542p.543p.544p.750p.1633p.1635p.1654p.1676p.1676p.1682p.1683p.1684p.1686p.1692p.1694p.1695p.1695
UM2488UM2488 STM32H745I/H750B-DK Discovery kit user manualp.17
MB1381MB1381 Discovery board schematic (H750XB variant)sheet 3sheet 16
DS12556STM32H750xB datasheetp.53p.94

Search next

Each of these opens the finder with pins, registers, schematic hits and document pages for the term.

Where to go next