IAE Academy

FOR CORE AND IT JOBS · CHAPTER 3 OF 7

GPIO, timers and PWM

This chapter explains how a microcontroller pin is driven and read, how a hardware timer turns a clock into exact delays, and how the same timer produces PWM and measures incoming signals. Most embedded control programs are built from these pieces.

Updated 30 Oct 2026

What you will be able to do

You will configure a pin as an output or an input and read a push button without false presses. You will compute a timer's period from its clock and prescaler, and choose a compare value for an exact delay. You will set the frequency and duty cycle of a PWM signal, and turn two captured counter values into a frequency or a pulse width.

Before you start

  1. Chapter 2, Embedded C: registers, bits and memory

  2. Ohm's law: I = V/R

  3. Frequency and period: T = 1/f

  4. The average of a repeating signal: area over one period divided by the period

  5. Binary and hexadecimal counting, powers of 2, and the remainder a mod m

Pins and buttons

A general-purpose I/O pin connects one bit of a few registers to the outside world. On a typical 8-bit microcontroller each register has one bit per pin, and bit 0, the least significant bit, belongs to pin 0 of the port. A direction bit makes the pin an output or an input; which value means output differs between parts. On a part where 1 means output, with DIR_REG and OUT_REG pointers to the volatile direction and output registers as in Chapter 2, *DIR_REG |= 0x08u; makes pin 3 an output and *OUT_REG |= 0x08u; drives it high.

Direction

Output bit

What the pin does

output

1

driven to the supply voltage

output

0

driven to 0 V

input

does not drive the pin

copies the pin voltage into its bit of the input register

input, pull-up enabled

does not drive the pin

reads 1 unless something pulls it low

An input connected to nothing is floating: its voltage drifts and the bit can read either value. A pull-up resistor fixes this for a button. One end of the resistor goes to the supply, the other to the pin, and the button connects the pin to ground. Many parts have a pull-up inside, switched on by an enable bit. Released, almost no current flows, so the pin sits at the supply and reads 1; pressed, it is tied to 0 V and reads 0.

CURRENT THROUGH A PRESSED BUTTON

Ohm's law across the resistor, while the button is closed and its own resistance is negligible. is the current in A, the supply in V, the pull-up resistance in Ω. A larger wastes less current while the button is held.

WATCH OUT FOR

Reading a pressed button as 1. The test: with a pull-up, the idle level is 1, so a press is a falling level. Check the idle value first.

A mechanical contact does not close cleanly. It bounces, opening and closing for a few milliseconds, and a program that reads fast enough sees several presses. Software debouncing samples the pin every and accepts a press only after pressed samples in a row. One released sample resets the count.

DEBOUNCE CONFIRMATION TIME

Holds once the contact has settled closed: the next sample comes within and more follow, so the press is accepted within . The samples span , so choose longer than the bounce time : no closed stretch inside the bounce is that long. is a whole number; , , in s.

The function below must run every 5 ms, from the periodic timer tick built in the next section. The hardware can call a function each time that tick's flag rises: this call is an interrupt, and it pauses the main loop until the function returns. PIN_REG points to the volatile input register; the main loop reads pressed_count, so it is volatile too. With , a press is accepted within 20 ms of the contact settling, and any closed stretch shorter than 15 ms is rejected.

#include <stdint.h>
#define BTN_MASK 0x01u
volatile uint8_t pressed_count = 0u;   /* read by the main loop */

void sample_button(void) {             /* timer interrupt, every 5 ms */
    if ((*PIN_REG & BTN_MASK) == 0u) { /* 0 means pressed */
        if (pressed_count < 4u) { pressed_count++; }
    } else {
        pressed_count = 0u;            /* a released sample restarts */
    }
}

The button counts as pressed while pressed_count equals 4.

Timers and delays

A hardware timer is a counter that adds 1 on every tick of its clock while your program does other work. The system clock is often too fast for a short counter, so a prescaler divides it first. The counter is bits wide: on the tick after its largest value, , it overflows to 0 and sets a flag bit. A compare register holds a chosen value: when the counter reaches it, a compare match sets another flag and can clear the counter.

COUNTER TICK AND OVERFLOW PERIOD

Holds for a timer that counts up from 0 and overflows after ticks. is the clock into the prescaler in Hz, the prescaler division (a pure number), the counter width in bits, the counting rate in Hz, the time from 0 to overflow in s. Each tick lasts .

For an exact time you want a period other than ticks. In clear-on-compare mode the counter counts 0, 1, …, and returns to 0 on the next tick, so successive compare matches are ticks, or , apart. Call the wanted match rate , in Hz. Setting and solving gives . The hardware then raises the flag once per period however long your code takes: a periodic tick.

COMPARE VALUE FOR A GIVEN TICK RATE

Holds in clear-on-compare mode when the result is a whole number no larger than . is the compare value (a whole number), the match rate in Hz, and as above. Choose so that fits. If the result is not whole, round and accept a small error in .

WATCH OUT FOR

Off-by-one in . Test it with : the counter sits at 0 and one tick passes per period, so the period is tick, not 0.

For a single delay, write 0 to the counter, clear the flag and wait for it once. That first wait can be a tick or two short: the prescaler may be part-way through a tick, and some parts raise the flag on reaching rather than on the return to 0. The periods after it are exact.

WORKED EXAMPLE

An 8-bit timer has MHz and a prescaler of 64. Find the compare value for a 1 ms periodic tick (1 kHz) in clear-on-compare mode.

Solution
  1. The counting rate is kHz, so one tick lasts 4 µs.

  2. One period of 1 ms holds ticks.

  3. The period has states, so and .

  4. Check: , so it fits in 8 bits. A prescaler of 8 would need 2000 ticks, too many for 8 bits.

Answer: N = 249 (0xF9), giving a compare match every 1 ms.

PWM and input capture

Pulse-width modulation switches a pin between high and low at a fixed frequency and varies the time spent high. The duty cycle is the fraction of each period the pin is high. A timer produces it directly: the counter runs from 0 to a top value, the pin is high while the counter is below the compare value, and low for the rest. Top sets the frequency. Compare sets the duty cycle. Parts differ by one count in where the output flips, so check yours.

AVERAGE VOLTAGE OF PWM

Holds for a waveform that is when high and 0 V when low. A load sees as a steady voltage only if it responds much more slowly than one period. is the high time in s, the period in s, the duty cycle between 0 and 1. The area under one period, , divided by gives the average.

PWM FREQUENCY AND COMPARE VALUE

Holds for a counter running 0 to with the pin high while the count is below , where . and are integers; in Hz, and as before. With an 8-bit and , from 0 to 255 gives 256 duty values, from 0 to 255/256.

WORKED EXAMPLE

An 8-bit timer with MHz, and drives a pin between 0 V and 5 V. Find , the for a duty of about 30 %, and the average voltage you really get.

Solution
  1. One period is ticks, so Hz.

  2. A duty of 0.30 needs . The compare value is an integer, so choose the nearest, 77 (0x4D).

  3. The real duty is .

  4. The average is V.

Answer: f_pwm = 7812.5 Hz, CMP = 77, V_avg ≈ 1.50 V.

Input capture runs the idea backwards. At a chosen edge on a pin, the hardware copies the counter into a capture register at once, without waiting for software. Two captures on successive rising edges bracket one period of the signal; for a pulse width, capture a rising edge and then the next falling edge. Subtract the two counts and keep only the remainder modulo , as unsigned -bit arithmetic does. If the counter wrapped once between the edges, that remainder is still the right count.

PERIOD AND FREQUENCY FROM TWO CAPTURES

Holds when less than one full counter cycle, ticks, passes between the two edges. , are the captured counts, the ticks between them, the time between the edges in s (the period, or the pulse width for a rising then a falling edge), the frequency in Hz.

WATCH OUT FOR

Where int is 32 bits, C converts uint16_t values to int before subtracting, so c2 - c1 with 0x0300 and 0xFF00 gives −64512. The test: write (uint16_t)(c2 - c1), which gives 0x0400 = 1024 on any compiler.

Check yourself

CHECK YOURSELF 1

A button connects a pin to ground. The pin has a pull-up resistor of 33 kΩ to a supply of 3.3 V. The button resistance is negligible. Find the current through the resistor while the button is held down, in µA.

Answer and solution

Answer: (accepted range )

  1. While the button is closed, the full supply voltage is across the pull-up resistor.

  2. .

  3. A = 100 µA.

CHECK YOURSELF 2

A button contact bounces for up to 12 ms. A program samples the pin every 5 ms and accepts a press only after pressed samples in a row. You need the samples to span longer than the bounce time, that is . What is the smallest that works?

  1. (A)

    2

  2. (B)

    3

  3. (C)

    4

  4. (D)

    5

Answer and solution

Answer: (C)

  1. The samples span , and this must exceed 12 ms.

  2. For : ms, which is not longer than 12 ms.

  3. For : ms, which is longer than 12 ms.

  4. So the smallest is 4.

CHECK YOURSELF 3

A 16-bit timer has MHz and a prescaler of 8. It runs in clear-on-compare mode and must raise a compare match 2000 times per second. Find the compare value .

Answer and solution

Answer: (accepted range )

  1. .

  2. .

  3. .

  4. Check: 749 is below , so it fits in 16 bits.

CHECK YOURSELF 4One or more options are correct

An 8-bit timer has and drives a pin between 0 V and 3.3 V. The pin is high while the count is below , and . Which statements are correct?

  1. (A)

    The duty cycle is 0.25.

  2. (B)

    Changing CMP changes the PWM frequency.

  3. (C)

    The average voltage is 0.825 V.

  4. (D)

    Raising the prescaler raises the PWM frequency.

Answer and solution

Answer: (A), (C)

  1. , so A is correct.

  2. has no in it, so B is wrong.

  3. V, so C is correct.

  4. A larger lowers , so D is wrong.