GPIO and PWM: switching and controlling pins
In short: GPIO pins are freely programmable digital inputs and outputs of microcontrollers; with PWM brightness, motors and servos can be controlled without exceeding the pins’ current capacity.
In more detail: GPIO (general purpose input/output) are pins that a program uses as input (read a button) or output (switch an LED). On Raspberry Pi, Pico, Arduino and ESP32 this connects software with the world.
In Depth
Inputs and outputs
- Output:
HIGH(3.3 V/5 V) orLOW(0 V); current per pin limited (Arduino ≈ 20 mA, Pi ≈ 16 mA, mind the total); LED with series resistor, larger loads via transistor/MOSFET/relay driver. - Input: reading a button; an open input floats (reads randomness) → pull-up or pull-down (internally activatable:
INPUT_PULLUP). - Debouncing: mechanical buttons bounce for a few ms → software debouncing/capacitor.
- Interrupts: an edge triggers a function (instead of constant polling).
PWM (pulse-width modulation)
Fast on/off with adjustable duty cycle. The average acts like an analogue voltage: 25 % on → about ¼ brightness/power.
# MicroPython (Raspberry Pi Pico)
from machine import Pin, PWM
led = PWM(Pin(15)); led.freq(1000)
led.duty_u16(32768) # 50 %Uses: dimming LEDs, motor speed, servo (pulses of 1–2 ms every 20 ms for angle), tones (speaker), fan control. Frequency high enough (avoid flicker/whine).
Analogue and levels
- ADC reads voltages (0–3.3 V → 0–1023/4095), e.g. potentiometer, light sensor; Raspberry Pi has no ADC (external needed, MCP3008). Outputting DAC is rare; PWM + filter often suffices.
- 3.3 V vs. 5 V: only tolerant pins/level shifters; 5 V on a 3.3 V GPIO can destroy it.
- Connect GND in common.
- Motors/servos with own power supply and common ground, flyback diode; not directly on the pin.
- Protection: series resistors, ESD caution.
Programming
- Arduino:
pinMode,digitalWrite,digitalRead,analogWrite. - Raspberry Pi:
gpiozero(LED(17).on(),Button(2)),libgpiod; (RPi.GPIOold). Distinguish pin numbering (BCM vs. board). - MicroPython/CircuitPython on Pico/ESP32.
- Linux level:
gpiodtools, device tree. - Projects: button-LED, traffic light, temperature sensor + display (I²C), servo control, retro case with power button, fan curve.
- Safety: never mains voltage directly; relay modules with isolation only with expertise.
See also: I²C, SPI and UART, Raspberry Pi, Arduino and microcontrollers, Electronic components