Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 36 ยท Microcontrollers and Boards

GPIO, PWM, Timers and Interrupts

Understand GPIO modes, pull-ups, logic levels, PWM, hardware timers and interrupts, with an interrupt-driven counter and a debounce simulation.

The pins of a microcontroller are where code meets the physical world. This lesson explains how pins work (GPIO), how timers generate precise signals (PWM), and how interrupts let the chip react instantly to events without constantly checking. These three ideas appear on every board, whether you program in C++, MicroPython or Rust.

GPIO: general-purpose input/output

A GPIO pin can be configured in software:

  • Output (push-pull): the chip drives the pin to the supply voltage or to ground.
  • Input: the chip reads the voltage and decides HIGH or LOW using thresholds.
  • Input with pull-up/pull-down: a built-in resistor (about 10-50 kohm) holds the pin at a default level when nothing drives it.
  • Open-drain: the chip can only pull the pin low; an external pull-up gives the high level. Used by I2C so several devices can share a wire.
  • Alternate function: the pin is handed to a peripheral (UART, SPI, ADC, PWM).

An undriven input "floats" and reads random values, so always use a pull-up or pull-down with buttons and switches.

Logic levels

Chips use 5 V (older AVR boards) or 3.3 V (ESP32, RP2040, most modern chips) logic, and 1.8 V in very low-power parts. Connecting a 5 V output to a 3.3 V input can damage it. Use a level shifter or a resistor divider for one-way signals. Also remember current limits: a GPIO typically supplies 10 to 40 mA at most, and the chip has a total limit. Drive bigger loads through a transistor, as in actuators.

C++
pinMode(2, INPUT_PULLUP);   // button to ground
pinMode(5, OUTPUT);         // LED through a resistor
bool pressed = (digitalRead(2) == LOW);
digitalWrite(5, pressed);

PWM: analog-like output from a digital pin

Pulse-width modulation switches a pin on and off rapidly. Two numbers define it:

  • Frequency: how many cycles per second (500 Hz for LEDs, 20 kHz for quiet motors, 50 Hz for servos).
  • Duty cycle: the percentage of each cycle that the pin is high.

Average voltage = supply * duty. A 3.3 V pin at 25% duty looks like about 0.8 V on average to an LED or motor. The resolution is the number of duty steps: an 8-bit PWM has 256 steps, a 12-bit has 4096.

Python Generating a PWM waveform and measuring its average

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

LED brightness appears non-linear to the eye: perceived brightness follows roughly a power of 2 to 2.8. A gamma table makes fades look smooth:

Python Gamma-corrected LED fade table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Hardware timers

Timers are counters that run independently of the CPU. They count clock ticks and can:

  • Generate PWM waveforms without CPU effort.
  • Trigger an interrupt at precise intervals (every 1 ms, every 100 ms).
  • Measure the time between two events (input capture) such as an echo pulse.
  • Act as a watchdog that resets the chip if software freezes.

The timer period follows from the clock, a prescaler (a divider) and the count limit: period = (prescaler * (limit + 1)) / clock.

Python Choosing prescaler and limit for a timer interrupt

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Interrupts: react now, not eventually

Polling means checking a pin constantly in loop(). If the loop is busy, a short pulse can be missed. An interrupt makes the hardware pause the main program, run a short function (the interrupt service routine, ISR) and then resume. Sources include pin changes (rising, falling, change), timer overflows, UART bytes received and ADC completion.

C++
volatile unsigned long pulses = 0;       // 'volatile': changed inside an ISR

void IRAM_ATTR onPulse() {               // ISR: keep it tiny
  pulses++;
}

void setup() {
  pinMode(4, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(4), onPulse, FALLING);
}

void loop() {
  noInterrupts();                         // copy shared data safely
  unsigned long n = pulses;
  interrupts();
  Serial.println(n);
  delay(1000);
}

Rules for ISRs

  1. Be short: set a flag or increment a counter, nothing more.
  2. No delay(), no Serial.print, no heap allocation inside an ISR.
  3. Mark shared variables volatile so the compiler re-reads them.
  4. Protect multi-byte shared variables while reading them (disable interrupts briefly) so you never read half an update.
  5. On ESP32 put the ISR in IRAM (IRAM_ATTR).

The pattern "ISR sets a flag, the main loop does the work" keeps everything safe. The simulation below counts pulses from a flow meter. The "hardware" fires events at the right moments; the ISR increments the counter; the main loop converts counts into litres per minute.

Python Interrupt-driven pulse counter (flow meter)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Interrupt debouncing

Bouncing buttons can fire an interrupt many times. In the ISR, compare millis() with the time of the previous accepted press, as in this logic:

Python ISR with a time-based debounce guard

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Watchdog timers

A watchdog resets the chip unless the program "feeds" it regularly. If your code hangs, the watchdog expires and reboots the device, which is essential for unattended IoT devices. Feed it only from code that proves the whole program is healthy, not from a timer interrupt that keeps running even when the main program is frozen.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What problem does a pull-up resistor solve on a button input?

    Without a default level, an open input floats and picks up noise.
  2. 2. What does a 25% duty cycle on a 3.3 V PWM pin deliver on average?

    Average voltage equals supply times duty fraction (3.3 x 0.25 = 0.83 V).
  3. 3. Which action is NOT appropriate inside an interrupt service routine?

    ISRs must be very short; blocking calls and heavy I/O can break timing and crash the chip.
  4. 4. Why mark an ISR-shared variable volatile?

    Without volatile, the compiler may keep an old copy in a register and never see the ISR's changes.

Summary

  • GPIO pins can be inputs, outputs, pull-up/down, open-drain or hand over to peripherals; mind logic levels and current limits.
  • PWM uses frequency and duty cycle to deliver average power; timers produce it in hardware.
  • Interrupts react immediately to events; ISRs must be tiny, use volatile shared data and defer work to the main loop.
  • Use a watchdog so unattended devices recover from hangs.

Next: ESP32 and Raspberry Pi