Bright Idea: Using Raspberry Pi as a Lamp Timer

Connected Home Internet of Things Raspberry Pi Technology
The following is an excerpt from Getting Started with Raspberry Piย by Matt Richardson and Shawn Wallace.ย 

Letโ€™s say youโ€™re leaving for a long vacation early tomorrow morning and you want to ward off would-be burglars from your home. A lamp timer is a good deterrent, but hardware stores are closed for the night and you wonโ€™t have time to get one before your flight in the morning. However, since youโ€™re a Raspberry Pi hobbyist, you have a few supplies lying around, namely:

  • Raspberry Pi board
  • Breadboard
  • Jumper wires, female-to-male.
  • PowerSwitch Tail II relay
  • Hookup wire

With these supplies, you can make your own programmable lamp timer using two powerful Linux tools:ย shell scriptsย andย cron.connectedhome_banner

Scripting Commands

A shell script is a file that contains a series of commands (just like the ones youโ€™ve been using to control and read the pins). Take a look at the shell script below and the explanation of the key lines.

#!/bin/bash # 1

echo Exporting pin $1. # 2

echo $1 > /sys/class/gpio/export # 3

echo Setting direction to out.

echo out > /sys/class/gpio/gpio$1/direction # 4

echo Setting pin high.

echo 1 > /sys/class/gpio/gpio$1/value
1 This line is required for all shell scripts.
2 “$1” refers to the first command line argument.
3 Instead of exporting a specific pin number, the script uses the first command line argument.
4 Notice that the first command line argument replaces the pin number here as well.

Save that as a text file calledย on.shย and make it executable with the chmod command:

root@raspberrypi:/home/pi# chmod +x on.sh

Note

You still need to be executing theses commands as root. Typeย sudo suย if youโ€™re get errors like “Permission denied.”

A command line argument is a way of passing information into a program or script by typing it in after name of the command. When youโ€™re writing a shell script, $1 refers to the first command line argument, $2 refers to the second, and so on. In the case ofย on.shย youโ€™ll type in the pin number that you want to export and turn on. Instead ofย hard codingย pin 25 into the shell script, itโ€™s more universal by referring to the pin that was typed in at the command line. To export pin 25 and turn it on, you can now type:

root@raspberrypi:/home/pi/# ./on.sh 25 1

Exporting pin 25.

Setting direction to out.

Setting pin high.
1 The “./” before the filename indicates that you’re executing the script in the directory you’re in.

If you still have the LED connected to pin 25 from earlier in the chapter, it should turn on. Letโ€™s make another shell script calledย off.shย which will turn the LED off. It will look like this:

#!/bin/bash

echo Setting pin low.

echo 0 > /sys/class/gpio/gpio$1/value

echo Unexporting pin $1

echo $1 > /sys/class/gpio/unexport

Now letโ€™s make it executable and run the script:

root@raspberrypi:/home/pi/temp# chmod +x off.sh

root@raspberrypi:/home/pi/temp# ./off.sh 25

Setting pin low.

Unexporting pin 25

If everything worked, the LED should have turned off.

Connecting a Lamp

Of course, a tiny little LED isnโ€™t going to give off enough light to fool burglars into thinking that youโ€™re home, so letโ€™s hook up a lamp to the Raspberry Pi.

  1. Remove the LED connected to pin 25.
  2. Connect two strands of hookup wire to the breadboard, one that connects to pin 25 of the Raspberry Pi and the other to the ground bus.
  3. The strand of wire that connects to pin 25 should be connected to the “+in” terminal of the PowerSwitch Tail.
  4. The strand of wire that connects to ground should be connected to the “-in” terminal of the PowerSwitch Tail. Compare your circuit toย Figureย 7, โ€œConnecting a PowerSwitch Tail II to the Raspberry Piโ€.
  5. Plug the PowerSwitch Tail into the wall and plug a lamp into the PowerSwitch Tail. Be sure the lampโ€™s switch is in the on position.
  6. Now when you executeย ./on.sh 25, the lamp should turn on and if you executeย ./off.sh 25, the lamp should turn off!

Note

Inside the PowerSwitch Tail there are a few electronic components that help you control high voltage devices like a lamp or blender by using a low voltage signal such as the one from the Raspberry Pi. The “click” you hear from the PowerSwitch Tail when itโ€™s turned on or off is the relay, the core component of the circuit inside. A relay acts like a switch for the high voltage device that can be turned on or off depending on whether the low voltage control signal from the Raspberry Pi is on or off.

Figureย 7.ย Connecting a PowerSwitch Tail II to the Raspberry Pi

Connecting a PowerSwitch Tail II to the Raspberry Pi

Scheduling Commands with cron

So now youโ€™ve packaged up a few different commands into two simple commands that can turn a pin on or off. And with the lamp connected to the Raspberry Pi through the PowerSwitch Tail, you can turn the lamp on or off with a single command. Now you can useย cronย to schedule the light to turn on and off at different times of day.ย cronย is Linuxโ€™s job scheduler. With it, you can set commands to execute on specific times and dates, or you can have jobs run on a particular period (for example, once an hour). Youโ€™re going to schedule two jobs; one of them will turn the light on at 8:00pm and the other will turn the light off at 2:00 am.

Note

As with other time-dependent programs, youโ€™ll want to make sure youโ€™ve got the correct date and time set up on your Raspberry Pi, as described inย ???.

To add these jobs, youโ€™ll have to edit the cron table (a list of commands that Linux executes at specified times):

root@raspberrypi:/home/pi/# crontab -e

This will launch a text editor to change rootโ€™s cron table. To change to the root user typeย sudo su. At the top of the file, youโ€™ll see some information about how to modify the cron table. Use your arrow keys to get to the bottom of the file and add these two entries at the end of the file.

0 20 * * * /home/pi/on.sh 25

0 2 * * * /home/pi/off.sh 25

Note

cronย will ignore any lines that start with the hash mark. If you want to temporarily disable a line without deleting it or add a comment to the file, put a hash mark in front of the line.

Typeย Control-Xย to exit, typeย yย to save the file when it prompts you, and hit enter to accept the default file name. When the file is saved and youโ€™re back at the command line, it should sayย installing new crontabย to indicate that the changes youโ€™ve made are going to be executed byย cron

More About Cron

Cron will let you schedule jobs for specific dates and times or on intervals. There are five time fields (or six if you want to schedule by year), each separated by a space followed by another space then the command to execute. Asterisks indicate that the job should execute each period. For example:

Tableย 1.ย Cron Entry for Turning Light On at 8:00pm Every Day

0 20 * * * /home/pi/on.sh 25
Minute (:00) Hour (8pm) Every Day Every Month Every Day of Week path to command

Letโ€™s say you only wanted the lamp to turn on every weekday. Hereโ€™s what the crontab entry would look like:

Tableย 2.ย Cron Entry for Turning Light On at 8:00pm Every Weekday

0 20 * * 1-5 /home/pi/on.sh 25
Minute (:00) Hour (8pm) Every Day Every Month Monday to Friday path to command

Letโ€™s say you have a shell script that checks if you have new mail and emails you if you do. Hereโ€™s how youโ€™d get that script to run every five minutes:

Tableย 3.ย Cron Entry for Checking for Mail Every Five Minutes

*/5 * * * * /home/pi/checkMail.sh
Every five minutes Every Hour Every Day Every Month Every Day of Week path to command

The */5 indicates a period of every five minutes.

As you can see,ย cronย is a powerful tool thatโ€™s at your disposal for scheduling jobs for specific dates or times and scheduling jobs to happen on a specific interval.

Going Further

eLinuxโ€™s Raspberry Pi GPIO Reference Page
This is the most comprehensive reference guide to the Raspberry Piโ€™s GPIO pins.
Adafruit: MCP230xx GPIO Expander on the Raspberry Pi
If you donโ€™t have enough pins to work with, Adafruit offers this guide to using the MCP23008 chip for 8 extra GPIO pins and the MCP23017 for 16 extra GPIO pins.
Tagged

Stett Holbrook is editor of the Bohemian, an alternative weekly in Santa Rosa, California. He is a former senior editor at Maker Media.

He is also the co-creator of Food Forward, a documentary TV series for PBS about the innovators and pioneers changing our food system.

View more articles by Stett Holbrook
Discuss this article with the rest of the community on our Discord server!

ADVERTISEMENT

FEEDBACK