Notice I am a pretty experienced programmer, but I do not have much experience with micro controllers, GPIO, python, electricity and the like. Take care in reading up on these topics for your own safety and the safety of your equipment.
I am doing this exercise because I think it is fun and I think I will learn a lot from it. By no means I think this is a cost effective way to create a switch. If you want that simply buy a zwave switch and controller and integrate that with openhab or other home automation software.
- Raspberry pi 3
- Four relay
- Adafruit T-cobbler (optional)
- Sd card class 10 https://www.raspberrypi.org/documentation/installation/sd-cards.md
Setup the raspberry pi
Install Raspbian as described in https://www.raspberrypi.org/downloads/raspbian/ or openhabian. I installed raspbian already but if had to start over again I would probably start with openhabian, http://docs.openhab.org/installation/openhabian.html#raspberry-pi. python3 and pip3 are installed by default on raspbian.
Install GPIO for python
To install the gpio support for python run the following in the terminal:
sudo apt-get install python3-rpi.gpio
sudo pip-3.2 install RPi.GPIO
Useful reading for starting out GPIO on the raspberry pi: https://www.raspberrypi.org/documentation/usage/gpio-plus-and-raspi2/
Wiring up the pi and the relay
Before I am going to write a script that simply turns on a switch on the relay and puts it back off. First I have to start with setting up the wiring. I myself use a T-cobbler from Adafruit, this is very easy because the pins on the raspberry pi are not numbered and the cobbler does. When you do not use the cobbler than you have to use a schema like this
Photo of simple setup
Photo of setup with cobbler
The first cable comes from the 5v on the pi to the vcc on the relay. The second cable connects one of the grounds of the pi with the ground of the relay. The third cable goes from the BCM pin 17 to the IN1 pin of the relay.
Writing the python script
Create a file somewhere called gpio.py.
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) pin_number = 17 print('Setting up pin ' + str(pin_number)) GPIO.setup(pin_number, GPIO.OUT) GPIO.output(pin_number, GPIO.LOW) time.sleep(1) GPIO.output(pin_number, GPIO.HIGH) print('Cleaning up pin ' + str(pin_number)) GPIO.cleanup(pin_number)
Run this script by executing:
sudo python3 gpio101.py
In part 2 I will add buttons and will handle GPIO input