I always wanted to see how could a Raspberry PI could control a lamp and contribute to the IOT and home automation.
For a prof-of-concept (To learn how to use a relay before using in more high voltages), we’re going to need:
- Raspberry PI
- Relay (I’m using Sainsmart 2-channel 5v relay – or a clone)
- batteries to power the LED – separate power for RPi and LED – 4x AA
- 220ohm resistor
This is going to be a three part tutorial:
- This one is part one – connecting and testing the relay
- In Part two we’re creating a webpage using Flask to control the relay and the lamp
- In Part three we use our voice to control the lamp.
A relay is switch operated electrically. They can be really really useful for some projects. It can be connected to a range of microcontrollers . The one I’m going to use is a SRD-05VDC-SL-C with 2 channels. It can drive great loads, such as 7A/240VAC,10A/125VAC,10A/28VDC.
This relay has 2 channels. We can connect there devices in one of two ways:
- Always on until we activate the channel (light turns off) – (NC – normally close)
- Always off until we activate the channel (light turns on) – (NO – normally open)
The pinout in the relay:
- NO – Normally Open (connects when INT1 – if channel 1 – is set to 0v) – active low
- COM – Common PIN (Source PIN – starts connected to NC and connects to NO when 0v applied)
- NC – Normally Close (connected – disconnects when INT1 is set to 0v) – active low
The pinout for connection to the Raspberry PI
|IN2||Control PIN for relay channel 2|
|IN1||Control PIN for relay channel 1 – PIN 16 – BCM23|
This particular relay will activate when the voltage on the control PIN will be below 2.0v (GND) . This relay is active low.
Here’s a great article from Make: Magazine on relays ! I recommend you to read it
First, let’s install the necessary libraries
sudo apt-get install python-rpi.gpio
Create the python file to use the relay
import RPi.GPIO as GPIO import time relay_pin = 23 GPIO.setmode(GPIO.BCM) GPIO.setup(relay_pin,GPIO.OUT) try: while True: #set low print ("Setting low - LED ON") GPIO.output (relay_pin,GPIO.LOW) time.sleep(2) #set high print ("Setting high - LED OFF") GPIO.output (relay_pin, GPIO.HIGH) time.sleep(2) except KeyboardInterrupt: GPIO.cleanup() print ("Bye")
To run it:
python relay.py (press ctrl+c to interrupt)
Now that it works, let’s create a web interface to control the lamp using our browser (our our smartphone).
We’ll be using Flask for it. Head to part two of the tutorial