SME
Embedded Systems · Problem type
PWM frequency and duty cycle
Use this for “A 16 MHz timer with prescaler 8 counts to TOP = 1999 and compares at 500. Find the PWM frequency, duty and average voltage at 5 V.”
Diagram
The
count
runs
from
0
to
TOP
and
starts
again;
the
output
is
high
while
the
count
is
below
the
compare
value.
duty
=
compare
TOP + 1
=
500
2,000
=
25%.
The dashed line is the average, Vavg = 1.25 V of 5 V.
This is an example. Type your own values to start a new problem.
fPWM (kHz)
=
fclk (MHz)
×
(
+
1)
duty (%)
=
compare
+
1
Vavg (V)
=
duty (%)
×
VDD (V)
The timer ticks at fclk ÷ N: the clock fclk slowed by the prescaler N, so each step of the drawn count takes N ÷ fclk.
Formulas
fPWM
=
1,000
×
fclk
N
× (TOP + 1)
1
=
1,000
×
16
8 × (1,999 + 1)
duty
=
100
×
compare
TOP + 1
25
=
100
×
500
1,999 + 1
Vavg
=
duty
×
VDD
100
1.25
=
25
×
5
100
Assumptions
•
Fast PWM: the count runs 0 to TOP, so a period is TOP + 1 ticks.
•
The output is high while the count is below the compare value.
•
The average voltage is the duty times the supply, as a low-pass filter or a motor sees it.
Step-by-step
WE KNOW
fclk = 16 MHz, N = 8, TOP = 1,999, compare = 500, VDD = 5 V
FIND
PWM frequency (fPWM), duty cycle (duty), average voltage (Vavg)
Step 1 · Find PWM frequency (fPWM)
Use fPWM = 1,000 × fclk ÷ (N × (TOP + 1))
The clock over the prescaler and the TOP + 1 ticks of a period; 1000 turns MHz into kHz.
fPWM
=
1,000
×
16
8 × (1,999 + 1)
fPWM
=
1,000
×
16
8 × 2,000
fPWM
=
1,000
×
16
16,000
fPWM
=
16,000
16,000
fPWM = 1 kHz
Step 2 · Find duty cycle (duty)
Use duty = 100 × compare ÷ (TOP + 1)
The share of the period the output is high, as a percent.
duty
=
100
×
500
1,999 + 1
duty
=
100
×
500
2,000
duty
=
50,000
2,000
duty = 25%
Step 3 · Find average voltage (Vavg)
Use Vavg = duty × VDD ÷ 100
High for the duty’s share of the time, so the average is that share of VDD.
Vavg
=
25
×
5
100
Vavg
=
125
100
Vavg = 1.25 V
Check
Put the numbers back in. Both sides should match.
1
=
1,000
×
16
8 × (1,999 + 1)
✓
25
=
100
×
500
1,999 + 1
✓
1.25
=
25
×
5
100
✓
Topic check
See what you know: 5 questions on this topic
New questions each time. Pass to mark it complete.
Related lessons
Interrupts and timers
Main lesson
Longest timer period
Use this for “How long can a 16-bit timer at 16 MHz run with prescaler 1024 before it overflows?”
CPU time in an interrupt
Use this for “An interrupt fires at 10 kHz and its ISR takes 20 μs. What share of the CPU does it use?”
What happens on an interrupt
Use this for “A timer matches its compare value. Put in order what the CPU does until the main program resumes.”