How to Control Relay with Raspberry Pi: Simple Guide
To control a relay with a Raspberry Pi, connect the relay module's input pin to a Raspberry Pi GPIO pin and use Python's
RPi.GPIO library to set the pin HIGH or LOW. This switches the relay ON or OFF, allowing you to control external devices safely.Syntax
Use the RPi.GPIO library to set up and control GPIO pins connected to the relay.
GPIO.setmode(GPIO.BCM): Use Broadcom pin numbering.GPIO.setup(pin, GPIO.OUT): Set the GPIO pin as output.GPIO.output(pin, GPIO.HIGH): Turn relay OFF (depends on relay type).GPIO.output(pin, GPIO.LOW): Turn relay ON (depends on relay type).GPIO.cleanup(): Reset GPIO pins after use.
python
import RPi.GPIO as GPIO import time relay_pin = 17 # GPIO pin connected to relay input GPIO.setmode(GPIO.BCM) # Use BCM pin numbering GPIO.setup(relay_pin, GPIO.OUT) # Set pin as output # Turn relay ON GPIO.output(relay_pin, GPIO.LOW) # Relay active low time.sleep(1) # Keep relay ON for 1 second # Turn relay OFF GPIO.output(relay_pin, GPIO.HIGH) GPIO.cleanup() # Reset GPIO
Example
This example turns a relay ON for 2 seconds, then OFF, using GPIO pin 17 on the Raspberry Pi.
python
import RPi.GPIO as GPIO import time relay_pin = 17 GPIO.setmode(GPIO.BCM) GPIO.setup(relay_pin, GPIO.OUT) print("Turning relay ON") GPIO.output(relay_pin, GPIO.LOW) # Relay ON (active low) time.sleep(2) print("Turning relay OFF") GPIO.output(relay_pin, GPIO.HIGH) # Relay OFF GPIO.cleanup()
Output
Turning relay ON
Turning relay OFF
Common Pitfalls
- Wrong GPIO numbering: Use
GPIO.BCMmode for pin numbers matching Raspberry Pi GPIO labels. - Relay logic level: Many relay modules are active low, so
GPIO.LOWturns relay ON andGPIO.HIGHturns it OFF. - Power supply: Ensure relay module has proper power (usually 5V) separate from Raspberry Pi 3.3V GPIO pins.
- No protection: Use a relay module with built-in transistor and diode to protect Raspberry Pi from voltage spikes.
python
import RPi.GPIO as GPIO relay_pin = 17 GPIO.setmode(GPIO.BCM) GPIO.setup(relay_pin, GPIO.OUT) # Wrong way: assuming relay is active high GPIO.output(relay_pin, GPIO.HIGH) # This may turn relay OFF instead of ON # Right way for active low relay GPIO.output(relay_pin, GPIO.LOW) # Turns relay ON GPIO.cleanup()
Quick Reference
| Action | Code | Description |
|---|---|---|
| Set GPIO mode | GPIO.setmode(GPIO.BCM) | Use BCM pin numbering |
| Setup pin | GPIO.setup(pin, GPIO.OUT) | Set pin as output |
| Turn relay ON | GPIO.output(pin, GPIO.LOW) | Activate relay (active low) |
| Turn relay OFF | GPIO.output(pin, GPIO.HIGH) | Deactivate relay |
| Cleanup | GPIO.cleanup() | Reset GPIO pins |
Key Takeaways
Use Raspberry Pi GPIO pins with RPi.GPIO library to control relay input pins.
Most relay modules are active low: setting GPIO LOW turns relay ON.
Always use GPIO.cleanup() to reset pins after your program ends.
Ensure proper power and protection for relay modules to avoid damage.
Double-check GPIO pin numbering mode to match your wiring.