Home automation lets you control devices like lights or fans from your Raspberry Pi. Relay modules act like switches that the Pi can turn on or off safely.
0
0
Home automation with relay modules in Raspberry Pi
Introduction
You want to turn your room lights on or off using your Raspberry Pi.
You want to control a fan remotely with a program.
You want to automate watering plants by switching a pump on and off.
You want to build a simple security system that controls alarms or locks.
You want to schedule devices to run at certain times automatically.
Syntax
Raspberry Pi
import RPi.GPIO as GPIO import time relay_pin = 17 GPIO.setmode(GPIO.BCM) GPIO.setup(relay_pin, GPIO.OUT) # To turn relay ON GPIO.output(relay_pin, GPIO.LOW) # To turn relay OFF GPIO.output(relay_pin, GPIO.HIGH)
Relay modules usually work with LOW signal to turn ON and HIGH to turn OFF.
Use GPIO.BCM mode to refer to pins by their Broadcom number.
Examples
This example turns a relay connected to pin 17 ON for 2 seconds, then OFF.
Raspberry Pi
import RPi.GPIO as GPIO relay_pin = 17 GPIO.setmode(GPIO.BCM) GPIO.setup(relay_pin, GPIO.OUT) # Turn relay ON GPIO.output(relay_pin, GPIO.LOW) # Wait 2 seconds import time time.sleep(2) # Turn relay OFF GPIO.output(relay_pin, GPIO.HIGH) GPIO.cleanup()
This code blinks the relay 3 times with 1 second ON and 1 second OFF.
Raspberry Pi
import RPi.GPIO as GPIO import time relay_pin = 27 GPIO.setmode(GPIO.BCM) GPIO.setup(relay_pin, GPIO.OUT) # Toggle relay ON and OFF 3 times for _ in range(3): GPIO.output(relay_pin, GPIO.LOW) time.sleep(1) GPIO.output(relay_pin, GPIO.HIGH) time.sleep(1) GPIO.cleanup()
Sample Program
This program turns a relay connected to pin 22 ON for 3 seconds, then turns it OFF and cleans up the GPIO pins.
Raspberry Pi
import RPi.GPIO as GPIO import time relay_pin = 22 GPIO.setmode(GPIO.BCM) GPIO.setup(relay_pin, GPIO.OUT) print('Turning relay ON') GPIO.output(relay_pin, GPIO.LOW) # Relay ON print('Relay is ON for 3 seconds') time.sleep(3) print('Turning relay OFF') GPIO.output(relay_pin, GPIO.HIGH) # Relay OFF GPIO.cleanup() print('Program finished')
OutputSuccess
Important Notes
Always connect relay modules to a separate power supply if they need more current than the Pi can provide.
Use GPIO.cleanup() at the end to reset pins and avoid warnings next time you run the program.
Check your relay module's datasheet to confirm if LOW or HIGH activates the relay.
Summary
Relay modules let your Raspberry Pi safely control high-power devices.
Use GPIO pins to send LOW or HIGH signals to switch the relay ON or OFF.
Always clean up GPIO pins after your program finishes.