Controlling GPIO Outputs with Python — LED, Relay, and Buzzer
raspberry pigpiopythonelectronics
The Raspberry Pi GPIO lets you control real-world hardware from Python. Three essential output patterns.
Setup
pip install gpiozero # usually pre-installed
Blink an LED
Wiring: Pin 17 > 330 ohm resistor > LED > GND
from gpiozero import LED
from time import sleep
led = LED(17)
while True:
led.on()
sleep(1)
led.off()
sleep(1)
Control a Relay
from gpiozero import OutputDevice
from time import sleep
relay = OutputDevice(18, active_high=False) # most relay modules are active-low
relay.on() # closes relay
sleep(5)
relay.off() # opens relay
Caution: Relays switch mains voltage. Use proper housing and fusing.
Piezo Buzzer
Wiring: Pin 20 > Buzzer positive, GND > Buzzer negative
from gpiozero import Buzzer
from time import sleep
buzzer = Buzzer(20)
for _ in range(3):
buzzer.on()
sleep(0.2)
buzzer.off()
sleep(0.1)
Running at Boot
Create a systemd service in /etc/systemd/system/myscript.service to auto-start GPIO scripts on boot.