How do I control GPIO with Python?


Using Python, you can easily control GPIO (General Purpose Input/Output) pins to manage components like LEDs, motors, or sensors. Here’s a step-by-step guide for the Raspberry Pi (also applicable to Arduino with MicroPython).
1. Prerequisites
✅ Raspberry Pi (running Raspberry Pi OS)
✅ Python 3 (pre-installed)
✅ GPIO library (e.g., RPi.GPIO
or gpiozero
)
✅ Electronic components (e.g., LED, resistor, button)
2. Installing GPIO Libraries
A. RPi.GPIO (classic, low-level)
bash
sudo apt update && sudo apt install python3-rpi.gpio
B. gpiozero (simpler, modern)
bash
sudo apt install python3-gpiozero
(Recommended for beginners!)
3. GPIO Pinout
The Raspberry Pi has 40 GPIO pins (GPIO2, GPIO3, etc.).
Use
pinout
in the terminal or refer to Pinout.xyz.
https://pinout.xyz/resources/raspberry-pi-pinout.png
4. Example 1: Blinking an LED (using gpiozero
)
Circuit Setup
LED+ → GPIO17 (Pin 11)
LED- → GND (Pin 9) with a 220Ω resistor
Python Code (led_blink.py
)
python
from gpiozero import LED
from time import sleep
led = LED(17) # GPIO17 (Pin 11)
while True:
led.on()
sleep(1)
led.off()
sleep(1)
Run with:
bash
python3 led_blink.py
(Press CTRL + C
to stop.)
5. Example 2: Reading a Button (using RPi.GPIO
)
Circuit Setup
Button → GPIO2 (Pin 3) and 3.3V (Pin 1)
Pull-down resistor (or software pull-down)
Python Code (button_read.py
)
python
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM) # Use GPIO numbering (not physical pins)
GPIO.setup(2, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # Button on GPIO2
try:
while True:
if GPIO.input(2) == GPIO.HIGH:
print("Button pressed!")
time.sleep(0.1)
except KeyboardInterrupt:
GPIO.cleanup() # Reset GPIO pins
Run with:
bash
python3 button_read.py
6. Example 3: PWM (Motor/Brightness Control)
Circuit Setup
- LED on GPIO18 (Pin 12) with a resistor
Python Code (pwm_led.py
)
python
from gpiozero import PWMLED
from time import sleep
led = PWMLED(18) # GPIO18 (PWM-capable)
while True:
led.value = 0.5 # 50% brightness
sleep(1)
led.value = 0.1 # 10% brightness
sleep(1)
7. Key Commands Overview
Function | RPi.GPIO | gpiozero |
Set pin mode | GPIO.setup(pin, GPIO.OUT) | led = LED(pin) |
Digital read | GPIO.input(pin) | button.is_pressed |
Digital write | GPIO.output(pin, HIGH) | led.on() / led.off() |
PWM | pwm = GPIO.PWM(pin, freq) | led = PWMLED(pin) |
Cleanup | GPIO.cleanup() | Automatic |
8. Tips & Troubleshooting
🔹 Permission issues? Use sudo
or add the user to the gpio
group:
bash
sudo usermod -aG gpio $USER
🔹 Wrong pins? Use GPIO.setmode(GPIO.BCM)
for GPIO numbering.
🔹 Button debouncing? Use hardware debouncing (capacitor) or software delay.
Conclusion
With Python and gpiozero
/RPi.GPIO
, GPIO control is easy to implement—whether for LEDs, motors, or sensors.
Subscribe to my newsletter
Read articles from ampheo directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
