How do you calculate the PWM frequency on an STM32 timer? Walk through the formula.
The PWM frequency is determined by three values: the timer input clock, the prescaler register, and the auto-reload register. The formula for edge-aligned (up-counting) mode is:
f_PWM = f_CLK / ((PSC + 1) * (ARR + 1))
The prescaler (PSC) divides the timer input clock — a PSC value of 0 means divide-by-1, a value of 71 means divide-by-72. The auto-reload register (ARR) sets the period — the timer counts from 0 to ARR, then resets, so the total number of counts per period is ARR + 1. The "+1" terms are critical interview details because the counter includes both 0 and the max value. For example, with a 72 MHz timer clock, PSC = 71, and ARR = 999: f_PWM = 72,000,000 / (72 * 1000) = 1,000 Hz.
A common follow-up is "how do you choose PSC and ARR for a target frequency?" The general approach: first decide the desired duty cycle resolution (more ARR steps = finer resolution), then calculate PSC to achieve it. For 1 kHz PWM with 1000 steps of resolution, you need (PSC + 1) * 1000 = 72,000,000 / 1000 = 72,000, so PSC + 1 = 72, giving PSC = 71. Always verify the actual frequency by plugging back into the formula, since integer-only registers may not divide evenly for all targets. For center-aligned mode, the effective frequency is halved because the counter counts up and then back down: f_PWM = f_CLK / ((PSC + 1) * 2 * ARR).
Source: Timers & PWM Q&A
