SME
Embedded Systems
Interrupts and timers
Use this for “Set a 16 MHz timer to interrupt every 1 ms with prescaler 64.”
Diagram
The
timer
counts
up
at
fₜ
and
resets
after
it
matches
the
compare
value,
raising
the
interrupt
(IRQ).
fₜ
=
fclk
N
=
16
MHz
64
=
250
kHz.
250 ticks of 4 μs make P = 1 ms; compare = 250 − 1 = 249.
It fits a 8-bit timer (below 256).
This is an example. Type your own values to start a new problem.
fₜ (kHz)
=
fclk (MHz)
÷
N
compare
=
P (ms)
×
fₜ (kHz)
−
1
ticks
Ticks a period
calculated
n
Timer bits
example
Formulas
fₜ
=
1,000
×
fclk
N
250
=
1,000
×
16
64
ticks
=
P
×
fₜ
250 = 1 × 250
compare = ticks − 1
249 = 250 − 1
Assumptions
•
The timer counts from 0 and clears on a compare match (CTC mode).
•
Each match raises the interrupt, so the count runs compare + 1 ticks a period.
•
The compare register holds whole numbers from 0 to 2ⁿ − 1 for an n-bit timer.
Step-by-step
WE KNOW
fclk = 16 MHz, N = 64, P = 1 ms, n = 8
FIND
timer clock (fₜ), ticks a period (ticks), compare value (compare)
Step 1 · Find timer clock (fₜ)
Use fₜ = 1,000 × fclk ÷ N
The prescaler divides the clock; 1000 turns MHz into kHz.
fₜ
=
1,000
×
16
64
fₜ
=
16,000
64
fₜ = 250 kHz
Step 2 · Find ticks a period (ticks)
Use ticks = P × fₜ
Ticks are the period times the tick rate (ms × kHz is a plain number).
ticks = 1 × 250
ticks = 250
Step 3 · Find compare value (compare)
Use compare = ticks − 1
The count starts at 0, so the last count is one less.
compare = 250 − 1
compare = 249
Check
Put the numbers back in. Both sides should match.
250
=
1,000
×
16
64
✓
250 = 1 × 250 ✓
249 = 250 − 1 ✓
Topic check
See what you know: 5 questions on this topic
New questions each time. Pass to mark it complete.
More problem types
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.”
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.”