GPIO, timers, interrupts and PWM
UAT 204 Microcontrollers and Embedded Systems
Lesson
By the end of this module you will be able to
- Configure GPIO pins as inputs or outputs with pull-up or pull-down
- Calculate timer prescaler and auto-reload values to generate PWM at a required frequency
- Generate servo and ESC pulse widths following ArduPilot's default ranges
- Compare polling with interrupts and debounce a button
Why this matters
Everything an MCU does with the outside world starts at its pins: reading buttons and sensor signals, driving LEDs, and commanding servos or ESCs with pulses accurate to microseconds. Counting time with the CPU is inaccurate and wastes time needed for other work, so MCUs have timers that generate pulses by themselves, and interrupts that wake the CPU when something happens.
GPIO
A GPIO (general-purpose input/output) pin can be set as an input or output. An unconnected input “floats” and reads random values, so it needs a pull-up (to the positive supply) or pull-down (to ground), usually available inside the chip. A button to ground with a pull-up reads 1 when released and 0 when pressed.
Timers and PWM
A timer counts the clock after dividing it by a prescaler (PSC), then counts up to the auto-reload (ARR) value and restarts. According to ST’s timer cookbook (AN4776), the cycle frequency is . The CCR value sets where the pin switches from high to low, and so sets the pulse width.
PWM servos and ESCs read the pulse width as the command. ArduPilot’s output defaults are SERVOx_MIN 1100, SERVOx_TRIM 1500 and SERVOx_MAX 1900 µs; the pulse frequency depends on the device, so check the documentation of the servo or ESC used.
Example 1 Finding PSC and ARR
Assume the timer clock is 84 MHz, we want to count in 1 µs steps, and a 20 ms period (an example).
f_tim = 84_000_000
tick_hz = 1_000_000 # count in 1 µs steps
psc = f_tim // tick_hz - 1
period_us = 20_000
arr = period_us - 1
f_pwm = f_tim / ((psc + 1) * (arr + 1))
print(f"PSC = {psc}, ARR = {arr}, f_PWM = {f_pwm:.1f} Hz")
for pulse_us in (1100, 1500, 1900):
print(f"pulse {pulse_us} µs -> CCR = {pulse_us}, duty = {pulse_us / (arr + 1):.2%}")
PSC = 83, ARR = 19999, f_PWM = 50.0 Hz
pulse 1100 µs -> CCR = 1100, duty = 5.50%
pulse 1500 µs -> CCR = 1500, duty = 7.50%
pulse 1900 µs -> CCR = 1900, duty = 9.50%
With the timer counting in 1 µs steps, CCR equals the pulse width in microseconds, which keeps code readable. With a different clock, recalculate PSC, and ARR must not exceed the counter size (such as 65,535 for a 16-bit timer).
Polling and interrupts
- Polling: the main program checks the status repeatedly. Simple, but it wastes CPU and can miss short events
- Interrupts: the hardware pauses the main program to call an ISR (interrupt service routine), then resumes. The ISR must be as short as possible: set a flag and let the main program do the heavy work
Mechanical buttons have contacts that bounce briefly when pressed, appearing as several presses. They must be debounced, accepting a new value only once it has been stable long enough.
Example 2 Debouncing a button
Read the pin every 1 ms (1 = released, with a pull-up) and accept a new value once stable for 5 ms.
samples = [1] * 5 + [0, 1, 0, 1, 1, 0, 0, 1, 0] + [0] * 20 + [1, 0, 1] + [1] * 15
raw_presses = sum(1 for a, b in zip(samples, samples[1:]) if a == 1 and b == 0)
stable, candidate, count, presses = 1, 1, 0, 0
for s in samples:
count = count + 1 if s == candidate else 1
candidate = s
if count >= 5 and candidate != stable:
stable = candidate
presses += stable == 0
print(f"raw falling edges: {raw_presses}, debounced presses: {presses}")
raw falling edges: 5, debounced presses: 1
One real press with bouncing contacts shows several falling edges; after debouncing there is one. The 5 ms is an example value; choose it from the characteristics of the button used.
Handing events from an ISR to the main program
A single flag only says “something happened”. If events arrive faster than the main program can take them (for example because it is busy printing text), you must decide what happens to the excess. There are two main policies.
- Latest value The ISR always overwrites with the newest data. The main program handles only the latest value and counts how many it skipped (missed). It suits values where a controller needs only the newest one.
- Bounded FIFO queue (often built as a ring buffer) keeps events in order. When it is full you choose to reject the new item (drop-newest) or overwrite the oldest (drop-oldest), and count the losses (overflow). It suits data logging, where history matters.
Either way, the data an ISR passes on usually has several fields, such as a tick number and a time. If the main program reads two fields while the ISR writes in between, the pair will not match. volatile stops the compiler from skipping reads, but it does not make a two-field read one unit. The common fix is to disable interrupts briefly while copying the pair and then restore the previous state at once (on a Cortex-M core this uses the interrupt mask). Heavy work happens outside that window.
Example 3 Latest value versus a queue when the main program stalls for 70 ms
A timer produces a tick every 10 ms, from tick 1 at 10 ms to tick 10 at 100 ms. The main program runs at 25, 95 and 105 ms (it is stuck between 25 and 95 ms). Compare the latest-value policy with a four-slot drop-newest queue. Age is the time from the tick being produced to the main program picking it up.
from collections import deque
TICK_MS = 10
arrivals = [(n, n * TICK_MS) for n in range(1, 11)] # tick n arrives at n * 10 ms
main_runs = [25, 95, 105] # main loop is blocked from 25 ms to 95 ms
def latest_value():
seen, last, missed, log = [], 0, 0, []
for t_run in main_runs:
ready = [n for n, t in arrivals if t <= t_run and n > last]
if ready:
newest = ready[-1]
missed += len(ready) - 1
log.append((t_run, newest, t_run - newest * TICK_MS))
last = newest
return log, missed
def fifo(depth=4):
q, overflow, log, idx = deque(), 0, [], 0
for t_run in main_runs:
while idx < len(arrivals) and arrivals[idx][1] <= t_run:
if len(q) < depth:
q.append(arrivals[idx])
else:
overflow += 1
idx += 1
if q:
n, t = q.popleft()
log.append((t_run, n, t_run - t))
return log, overflow, list(q)
log, missed = latest_value()
print("latest-value:", [f"run@{r} tick={n} age={a}ms" for r, n, a in log], f"missed={missed}")
log, overflow, left = fifo()
print("fifo(4): ", [f"run@{r} tick={n} age={a}ms" for r, n, a in log], f"overflow={overflow}", "left=", [n for n, _ in left])
latest-value: ['run@25 tick=2 age=5ms', 'run@95 tick=9 age=5ms', 'run@105 tick=10 age=5ms'] missed=7
fifo(4): ['run@25 tick=1 age=15ms', 'run@95 tick=2 age=75ms', 'run@105 tick=3 age=75ms'] overflow=4 left= [4, 5, 10]
Latest value always gives fresh data (age 5 ms) but skips 7 ticks. The queue never skips in order, but once it is full it rejects 4 ticks, and the data it delivers is as old as 75 ms. A bigger queue does not fix a slow main program; it only makes the delivered data older. A controller should therefore use the latest value with a maximum age, while a logger uses the queue and records the overflow count.
Module lab
Lab: driving a servo and reading a button with interrupts
- Connect a button to a GPIO pin with the internal pull-up, read it by polling, and count presses without debouncing.
- Switch to an interrupt that sets a
volatileflag and debounce in the main loop, comparing the count with step 1. - Use the Pico 2 PWM to generate 1100, 1500 and 1900 µs pulses at the frequency given in the servo’s documentation, and measure them with an oscilloscope or logic analyzer.
- Connect a servo (separate power, common ground) and command it with all three pulses.
- Calculate PSC and ARR for the Pico 2 clock using the same approach as Example 1.
- Repeat Example 3 with a different stall time and queue size, and record how missed, overflow and age change.
Common mistakes
Watch out
- Leaving inputs floating without a pull-up or pull-down
- Setting ARR beyond the counter size
- Doing heavy work in an ISR, such as printing or waiting
- Not debouncing buttons
- Powering a servo from the MCU’s supply pin until the supply sags
Summary
- GPIO inputs need a pull-up or pull-down
- PWM frequency is , and CCR sets the pulse width
- ArduPilot’s default pulses are 1100–1900 µs with 1500 µs centre
- Interrupts respond to events at once; ISRs must be short, and buttons must be debounced
Check your understanding
- With MHz, PSC = 47 and ARR = 999, what is the PWM frequency?
- In question 1, what is the duty cycle if CCR = 250?
- To count in 1 µs steps from a 150 MHz clock, what PSC is needed?
- What is ArduPilot’s default centre pulse (
SERVOx_TRIM)? - Why should an ISR be as short as possible?
Answers
- Hz
- 1500 µs
- While in the ISR, other work and same-level interrupts must wait; too long and the system misses its timing
Key formulas
| Timer PWM frequency | |
| Duty cycle |
Key references
- STMicroelectronics. (2026). How to use general-purpose timer peripheral on STM32 MCUs (Application note AN4776, Rev 4; formerly the General-purpose timer cookbook for STM32 microcontrollers). link
- Raspberry Pi Ltd. RP2350 datasheet. link
- White, E. (2024). Making embedded systems: Design patterns for great software (2nd ed.). O'Reilly Media.
- ArduPilot Dev Team. ESC calibration. ArduPilot Copter documentation. link
Further reading
Study the assigned knowledge units in advance, review media and take the module quiz
สถาปัตยกรรมไมโครคอนโทรลเลอร์
Basic level: Arduino/ESP32, signals and timing
Timer interrupt and delivering ticks
Event queue from an ISR
Preparing real-board experiments: UNO, ESP32 and STM32
In class / field
Lab or field practice from worksheets with a safety checklist
Learning evidence: Checked worksheets and quiz results