Interrupts and timers
Đã giới thiệu| English | Ý nghĩa |
|---|---|
| interrupt/ˈɪntərʌpt/ | ngắt |
| interrupt service routine/ˈɪntərʌpt ˈsɜːvɪs ruːˈtiːn/ | hàm phục hồi ngắt |
| NVIC | NVIC |
| timer | bộ đếm thời gian |
| prescaler | bộ chia tần |
Sleep until needed
- An interrupt suspends the main program where it stands: hardware pushes the return state, vectors to the interrupt service routine (ISR), which runs and returns. The NVIC ranks priorities.
- A timer is a counter behind a prescaler; it raises an interrupt at its reload value: $f = f_{clock}/(\text{prescaler} \times \text{reload})$.

1 Hz from 84 MHz: prescaler 8400 gives 10 kHz, reload 10 000 gives 1 Hz; both fit 16 bits ✓ and $8400 \times 10\,000 = 84 \times 10^{6}$ ✓ closes the design.
{exercise:uni-ee0841-timer}
From an 84 MHz clock, prescaler 4200 and reload 20 000 give an interrupt at —
Độ khó 1/5 · 100 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
4200 × 20 000 = 84 000 000 = the clock, so exactly 1 Hz; and 20 000 ≤ 65 535 fits a 16-bit reload.
An ISR that forgets to clear its interrupt flag causes —
Độ khó 1/5 · 100 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
The flag still reads pending when the ISR returns, so the CPU vectors straight back in — clear the flag, keep the ISR short.
Interrupt or poll?
- A GPIO interrupt with 12 + 30 + 10 = 52 cycles costs 0.62 µs — against 21 000 laps for the polled wait. But per event: at 1 kHz that is 0.06% of the CPU; at 1 MHz, 62%.
- Past about 1 MHz of events, polling a fast peripheral is cheaper than interrupting.
{exercise:uni-ee0842-latency}
A 52-cycle ISR serviced at 1 MHz of events consumes about —
Độ khó 1/5 · 100 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
52e6 cycles/s against 84e6 available = 62%. The same ISR at 1 kHz costs only 0.06% — rate decides, not the ISR itself.