Category Archives: Electronics

Any project including electronics.

Raspberry Pi Appliance Timer

Disclaimer:  Working with mains current is dangerous. Use the information provided in this article/post at your own risk. Always turn off power and confirm no voltage is present on the wires you are going to work with, with a volt meter before beginning work with mains power.

This is an On/Off timer based on the Raspberry Pi. After some really high electric bills I decided I needed to do something to help reduce my burden. The first thing that came to mind that likely runs much more than necessary is the electric water heater.  The water heater is designed to constantly retain a certain temperature. However, we only use hot water one to two times daily, once in the morning and again at night.

I needed something that would give me an AM and a PM On/Off schedule. I could have bought a ready made product but I have been looking for a good project for the Raspberry Pi and since it is so much easier to use the Pi for timed projects due to the built in NTP client over the Arduino it was a no brainer.

There are  couple of different ways of writing a script to turn on and off the appliance. One way and probably the easiest is to turn on the GPIO pins based on time and then set a delay for the duration you want it on for followed by turning the GPIO pin back off. Another, the way I did it here, is to turn the GPIO pin on and off based on times rather than setting a delay. I feel like making the on and off based on the clock is more elegant and dependable.

Now, on to the Hardware I used and why.

Raspberry Pi (any model) – $35 – Where to purchase

Raspberry Pi case – $8.99 – Where to purchase – This is for the pi B+ or Pi 2. You will need a different case for the other Pi models.

240 volt to 24 volt AC transformer – $14 – Where to purchase

240 volt contactor – $21 – Where to purchase – Steps 240 volts down to 24 volts for the contactor relay.

NPN transistor – $0.12 – Where to purchase – This switches the 24 volt relay.

24 volt relay – $0.64 – Where to purchase – This switches the contactor.

3 position screw down terminal – $0.20 – Where to purchase – 5 volt and grounds terminal block.

2 position screw down terminal – $0.10 – Where to purchase – 24 volt relay terminal for switching the contactor.

Prototyping board – $0.99 – Where to purchase – To solder our components to.

LED (any color) – $0.05 – Where to purchase – To indicate whether the appliance is switched on or off.

Momentary button – $0.25 – Where to purchase – Manual timed on switch

Enclosure – $10.89 – Where to purchase – This is not the enclosure I used but it is the type you should use. Mine is one I had around from Radio Shack.

Wire – $0.00 – You should be able to find appropriate wire laying around. Cat 5 (Ethernet), Cat 3 (Phone Wire), HVAC Thermostat Wire), all will work well for the contactor control board, but just about any wire larger than 24 gauge will be fine. Just make sure that you have a few different colors so you don’t make mistakes by getting confused about what goes where. I use Cat 5 wire because you can find it everywhere these days and because there are 8 differently color coded wires in it.

Wire nuts – $10.96 – Where to purchase – Use wire nuts appropriate for the size of the wire and amount of current.

Wire Terminals – $2.98 – Where to purchase – Use wire terminals appropriate for the size of your wire and amount of current.

Crude Schematic of Contactor Control Board

Click pictures to show larger view.

These pictures are showing the bottom of the board where the pins come through.

relayBoard

5VrelayPins

 

 

 

 

 

 

Semi complete Project

 

WP_20150806_003 WP_20150814_004[1] WP_20150806_002 WP_20150806_004 WP_20150806_001 WP_20150805_005

 

 

 

 

 

 

 

 

 

 

 

 

 

Make the Contactor Control Board

Since the 24 volt relay is the largest component on the controller board, it should be the component you structure the rest of the components around. I placed the transistor close enough to the relay that I was able to solder it directly to the relay pin. You can use wire to connect each point on the board or make solder traces connecting it all together. You should be able to follow my crude schematic to put together the control board, but if you need further instruction please leave a comment or email me at modsbyus ‘at’ modsbyus.com. I will be more than happy to give further assistance.

 

Putting Together The Mains Components

The 240/24 Volt AC Transformer

This transformer has 4 wires for connecting to the mains. The black and white ones are for 120 volts and the orange and red ones are for 240 volts. Use the pair that is appropriate for your usage. The 24 volt wires are blue and yellow.

The yellow wire is going to connect to the relay terminal on the control board and then you make a connection from the other position on the relay terminal to one side of the contactor. The blue wire goes directly to the other side of the contactor.

The Enclosure

Depending on the enclosure you choose for your project, mounting will be different. You need to make sure that your Raspberry Pi is mounted in its own case outside of the enclosure for the mains components. The EMD (electro magnetic discharge) from the contactor opening and closing can cause damage to your Raspberry Pi and can also cause unexpected unclean shut downs.  You can put the timed override switch and status LED mounted through the enclosure.

The Raspberry Pi

I highly recommend using a Pi case for your Raspberry Pi. It will protect your Pi from all sorts of damage and it looks nicer.

We are going to use GPIO pins 17, 24, and 27 and 3 ground pins.

17 and one ground pin is wired to the timed override switch.

24 and one ground pin is wired to the LED. The long leg of the LED goes to the GPIO 24 pin.

27 goes to the control position on the 3 position terminal block which is connected to pin 1 of the transistor.

A third ground goes to the ground position of the 3 position terminal block which is connected to pin 2 of the transistor.

You will need a constant 5 volt supply for the relay which goes to the 5VDC position of the 3 position terminal block. You can use a 5 volt pin from the Raspberry Pi but I don’t recommend it for this project. Whenever you turn off a coil or motor it sends back high voltage spikes that can damage your Raspberry Pi. I suggest finding a 5 volt power supply to use. The positive line of the 5 volts goes to the 5VDC position of the 3 position terminal block and the ground or negative of the power supply goes to the ground position of the 3 position terminal block.

 

The Python Program That Runs it

You can download it Download ApplianceTimer.py

?View Code PYTHON
# Raspberry Pi custom appliance timer
 
# import GPIO module
import RPi.GPIO as GPIO
 
 
# set up GPIO pins as outputs
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Button
GPIO.setup(27, GPIO.OUT) # Appliance 5/25 volt relay
GPIO.setup(24, GPIO.OUT)# LED
state = 0
button = GPIO.input(17)
 
 
# import date and time modules
import datetime
import time
 
# Enter the times you want the appliance to turn on and off for
# each day of the week.
 
MonAMOn  = datetime.time(hour=5)
MonAMOff = datetime.time(hour=7)
MonPMOn  = datetime.time(hour=16)
MonPMOff = datetime.time(hour=22)
TueAMOn  = datetime.time(hour=5)
TueAMOff = datetime.time(hour=7)
TuePMOn  = datetime.time(hour=16)
TuePMOff = datetime.time(hour=22)
WedAMOn  = datetime.time(hour=5)
WedAMOff = datetime.time(hour=7)
WedPMOn  = datetime.time(hour=16)
WedPMOff = datetime.time(hour=22)
ThuAMOn  = datetime.time(hour=5)
ThuAMOff = datetime.time(hour=7)
ThuPMOn  = datetime.time(hour=16)
ThuPMOff = datetime.time(hour=22)
FriAMOn  = datetime.time(hour=5)
FriAMOff = datetime.time(hour=7)
FriPMOn  = datetime.time(hour=16)
FriPMOff = datetime.time(hour=22)
SatAMOn  = datetime.time(hour=5)
SatAMOff = datetime.time(hour=7)
SatPMOn  = datetime.time(hour=16)
SatPMOff = datetime.time(hour=22)
SunAMOn  = datetime.time(hour=5)
SunAMOff = datetime.time(hour=7)
SunPMOn  = datetime.time(hour=16)
SunPMOff = datetime.time(hour=22)
 
# Store these times in an array for easy access later.
OnTimeAM = [MonAMOn, TueAMOn, WedAMOn, ThuAMOn, FriAMOn, SatAMOn, SunPMOn]
OnTimePM = [MonPMOn, TuePMOn, WedPMOn, ThuPMOn, FriPMOn, SatPMOn, SunPMOn]
OffTimeAM = [MonAMOff, TueAMOff, WedAMOff, ThuAMOff, FriAMOff, SatAMOff, SunAMOff]
OffTimePM = [MonPMOff, TuePMOff, WedPMOff, ThuPMOff, FriPMOff, SatPMOff, SunAMOff]
 
 
# Start the loop that will run until you stop the program or turn off your Raspberry Pi.
 
while True:
    button = GPIO.input(17)
    #print('ttt')
    global state
    if button == 0:
        #print('button', button)
        state = 1
        #print('state', state)
    if state == 1:
        time.sleep(0.5)
        GPIO.output(24, True)
        GPIO.output(27, True)
        time.sleep(3600) #3600
        state = 0
        GPIO.output(24, False)
        GPIO.output(27, False)
 
 
 
    # get the current time in hours, minutes and seconds
    currTime = datetime.datetime.now()
    #print(currTime)
    # get the current day of the week (0=Monday, 1=Tuesday, 2=Wednesday...)
    currDay = datetime.date.today().weekday()
 
        #Check to see if it's time to run the appliance for the AM hours
    while (currTime.hour >= OnTimeAM[currDay].hour and currTime.hour <= OffTimeAM[currDay].hour): # set the GPIO pin to HIGH GPIO.output(24, True) GPIO.output(27, True) time.sleep(60) currTime = datetime.datetime.now() currDay = datetime.date.today().weekday() else: if (currTime.hour >= OffTimeAM[currDay].hour - 1):
            GPIO.output(24, False)
            GPIO.output(27, False)
 
 
 
    #Check to see if it's time to run the appliance for the PM hours
    while (currTime.hour >= OnTimePM[currDay].hour and currTime.hour <= OffTimePM[currDay].hour): GPIO.output(24, True) GPIO.output(27, True) time.sleep(60) currDay = datetime.date.today().weekday() currTime = datetime.datetime.now() else: if (currTime.hour >= OffTimePM[currDay].hour - 1):
            GPIO.output(24, False)
            GPIO.output(27, False)

Disconnected Testing

You should run a dry test without the mains connected to the contactor. You don’t want to damage anything or hurt yourself. As long as you can push the override switch and it stays on for the expected amount of time and it comes on and goes off properly for a specified time period then you are good to go.

Bringing it All Together

Its time to hook up the mains (240 or 110 Volts) to the contactor. The feed lines go to one side and the lines to your appliance go to the other side. Use the pictures above as a reference. As always you should follow all safety procedures for dealing with main current and if you don’t know what you are doing then you have no business messing with it. YOU CAN KILL YOURSELF OR OTHERS!

Live Testing

After hooking in the mains and your appliance its time to give it a real test. Set and AM and a PM time for short durations during a time you can monitor it. Turn everything on, boot up the PI, test out the override switch and the timed functions.

Set it and Forget it

The easiest way I have found to set a python script to start when you boot the Pi is to set it as a Cron job using Webmin.

HARDWARE_HACKS has a great tutorial on how to setup Webmin. Follow that then return here for the Cron Job how to.

If you have Webmin setup and you are logged in click on System then Scheduled Cron Jobs

CronJobs

 

 

 

 

 

Now click on Create a New Scheduled Cron Job.

It should look like this. The only difference is that for the Command that you put in the path for your python script.

python /home/pi/Desktop/RevisedWHTimer.py

CreateCronJob

 

 

 

 

 

 

Now Just

sudo reboot

and you are all done! It should come on and go off based on the schedule you set.

Special Note:

The Raspberry Pi does not do well with improper shutdowns. It will cause system corruption. For the sake of all the hard work you just went through, run this on a UPS or some type of reliable battery system.

Getting Started with the Raspberry Pi

I Got My Raspberry Pi, Now What?

This is a great platform to work with. You have many options when choosing a micro computer. The Raspberry Pi has a large community that makes it easy to work with this hardware. If you have trouble with the hardware or with the scripting or programming for the Pi you can head over to the Raspberry Pi Forum where there is always someone happy to help without being rude and condescending. Unlike most other forums I have encountered, the atmosphere there is refreshing and full of welcome.

What you Need

  • Raspberry Pi
  • Class 10 Micro SD Card (Others will work but this is recommended.)
  • 5 Volt 2 Amp with a Micro USB 5pin Male
  • A computer
  • A Micro SD Adapter and maybe a USB to SD Adapter as well depending on your needs.
  • SD Formatter – Get it at sdcard.org
  • Win32 Disk Imager – Get it at sourceforge.net
  • Raspbian (The Operating System) – Get it at raspberrypi.org
  • Adafruit Pi Finder – Get it at GitHub
  • WinRAR – Get it at win-rar.com
  • Putty – Get it at chiark.greenend.org.uk
  • AngryIPScanner – Get it at angryip.org (Optional)
  • A Ethernet connection to your network (internet access)

Install WINRAR

You will need this or some other archive tool to extract everything you have downloaded. I suggest that you extract everything to a familiar place like your Desktop to make it easy to find. You should create a folder to extract the Adafruit Pi Finder to since there are a lot of files.

 

Preparing the SD Card

Open SD Formatter

SDFormatter

SDFormatterOptions

 

 

 

 

 

 

 

It should find your SD card automatically but you need to verify that the drive letter shown is in fact the drive letter of your SD card. If you format the wrong drive you will erase EVERYTHING. Go to your explorer and verify drive letters there.

Choose the Option button and select Format Size Adjustment to ON. Then click OK then Format. Say OK to the two warnings to Format your SD card.

Install the OS to the SD Card

Open Win32 Disk Imager.

Win32DiskImager

 

 

 

Browse to and select the img file you extracted from the file you downloaded from raspberrypi.org.

Click on Write and wait for it to complete. After its finished safely eject the SD card and insert it into the Pi.

First Boot

Plug in your Ethernet (internet) cable to the Pi then the power cable.

Wait a moment for the Pi to boot, then open the Adafruit Pi Finder by double clicking the PiBootstrap.exe file. Then click on Find My Pi!.

PiFinder PiFinderAfterFind

 

 

 

 

 

 

 

Once it finds your Pi open Putty and type in the IP address of your Pi. I don’t suggest using this tool for anything other than finding the IP address of your Pi. Terminal works most of the time but its frustrating when it doesn’t. The webide is still in beta and has some bugs in the installation.

Putty

PuttySession

 

 

 

 

 

 

 

 

The default username is ‘pi’ and the default password is ‘raspberry’. You will not see any characters being printed on the screen when you are inputting the password, this is normal.

Now run

sudo raspi-config

This will take to a window like this.

raspi-config

 

 

 

 

 

 

There is no mouse support in this menu. Use the Up,Down,Left,Right,TAB, and Enter keys of your keyboard to navigate.

Press enter on the first option to Expand Filesystem.

After that has finished you will be returned to this menu. Now choose Change User Password. You don’t want your project bamboozled by the internet bullies.

If you wish to automatically go straight to the desktop or to Scratch then make your selection in Enable Boot to Desktop/Scratch.

Next, Set your timezone and keyboard options in Internationalisation Options.

Now If you have the Raspberry Pi Camera module choose Enable Camera. If you are going to use a webcam there is no need to do this step.

If you wish to get the full potential out of your Pi then go to Overclock and choose the option you want for your Pi.

We’re getting close to the end now.

Go to Advanced Options.

Raspi-config_Advanced

 

 

 

 

 

 

Here you are going to set options that are specific to you individual needs. To have continued access using SSH (Putty) you need to enable SSH. Without SSH you must have an HDMI display hooked up to your PI. After each edit in this menu you will likely be returned to the main menu, just go back to Advance options to get back and finsh your optional configurations. Once you are done and back to the main menu select Finish. You should be prompted to reboot. Go ahead and do that now.

Once your Pi has rebooted restart your Putty session and log in.

Now is a good time to make sure that your Raspberry Pi is up to date.

 

 

sudo apt-get update

Then

sudo apt-get upgrade

This will take a while. Once it is done reboot your Pi again.

sudo reboot

Once your Pi has rebooted restart your Putty session and log in again.

Static Network Config (OPTIONAL)

You may wish to configure a static IP configuration on your Pi to make it easier to find and work on in the future.

First you need to determine a suitable IP address to use. If you know how to find this out by logging into your router then do that.

Otherwise….

Install and open Angry IP Scanner and click on Start.

This will return a list of all the IP addresses on your network, active and inactive.

Typically your router will only give out up to 50 addresses by DHCP. The rest can be used for static assignment. You need to choose an inactive IP outside of you DHCP range. This can be determined by examining the results of the IP Scanner results. Usually your DHCP will either start at 2 and end somewhere around 50 or start around 100 and go to 150 or 200. If your results have IP addresses in the lower range then use something above 100. Otherwise use something between 2 and 49. Examples: 192.168.1.2, 192.168.0.180, ect..

Now that you know what IP address you are going to use.
Go back to your Putty session and type in

route -n

This will give an output something like this.
Putty-route-n
This shows us the Gateway, and netmask. Take note of these.

Example:  Netmask:255.255.255.0 Gateway:192.168.16.1

So now you have an IP address, Gateway address, and a  Netmask.

Now we have the information we need to configure a static IP address.
Now type in

sudo nano /etc/network/interfaces

You will see something like this.

Putty-interfaces

 

 

 

 

 

 

 

Change it to look like this using your IP information.

auto lo

iface lo inet loopback
iface eth0 inet static
address 192.168.16.28
netmask 255.255.255.0
network 192.168.16.0
broadcast 192.168.16.255
gateway 192.168.16.1
nameserver 192.168.16.1

allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface default inet dhcp

Putty-interfaces-Static

 

 

 

 

 

 

Then hit Ctrl+o to save it and Ctrl+x to exit

Now reboot

sudo reboot

If you would like to be able to log into your Pi’s desktop remotely See my Post Raspberry Pi VNC Server Setup.