Simple Relay Interface with Raspberry Pi
I had a few 5v relays lying around and decided to connect one up to my room lighting and control it via my Raspberry Pi.
Connection to Appliance
In my case it is my main room lighting. This is quite straightforward, unscrew the cover plate of the light switch and swap the wires into the relay module (be careful not to shock yourself; I’m not responsible for any injury or death during this process). Look up some wiring diagrams if you’re unsure.
COM should be written on one terminal of the light switch, connect accordingly to the relay board. Mine is a two way switch and therefore has 2 other terminals which connect randomly to NC(normally closed) & NO(Normally Open).
If your switch is one-way, connect the wire to the NO terminal of the relay board and leave the NC alone.
For other electrical appliances, you just need to splice the neutral wire and reconnect to COM and NO.
Connection to Raspberry Pi
Locate the VCC,GND and IN pins on your relay board.
Connect accorindly to the raspberry pi or any other board with IO pins (such as arduino)
- VCC goes to 5v
- GND to Ground
- IN to any gpio pin of your choice
Python Scripts to control relay
I have two python scripts, one for switch the relay on and the other off. You’ll understand why later. Also, the relay board I’m using is a low-on/high-off board, meaning it turns on when there is a low signal and off to a high signal (a bit counterintuitive but it was the only type I had)
#RelayOn
import RPi.GPIO as gpio
gpio.setwarnings(False)
gpio.setmode(gpio.BCM)
relaypin = 17 #change this to your pin number.
gpio.setup(relaypin, gpio.OUT)
gpio.output(relayping, False) #set to True if your relay board is high-on/low-off
#RelayOff
import RPi.GPIO as gpio
gpio.setwarnings(False)
gpio.setmode(gpio.BCM)
relaypin = 17 #change this to your pin number
gpio.setup(relaypin, gpio.OUT)
gpio.output(relaypin, True) #set to False if your relay board is high-on/low-off
Run the scripts and verify if the relay is turning on/off properly.
Remote SSH command
Now what is left is to run the python scripts remotely; for that I’m using a secure shell connection(SSH).
For convenience, I’m using MacroDroid on my phone with a tasker plugin (this also allows me to do cool stuff like turn off the lights when I open the Netflix app).
If you too will be using MacroDroid:
#1.Set your preferred trigger (I’m using a widget) #2. From the action list select “locale or tasker plugin” then configure the plugin to send an ssh command to your pi to run the python scripts. (Change the path to your python script)
Now the scripts can be remotely run and you
should be able to turn the relay on or off :)
Demo
FIN