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.

2 thoughts on “Bright Idea: Using Raspberry Pi as a Lamp Timer

  1. Wickham Soap says:

    Great stuff Stett, this is just what I was looking for and it’s a simple way to execute such a job. I did wonder how I was going to program a script to control a relay on a timer basis or more important as a newbie what program language to use. I do have a basic knowledge of shell scripts and as I would like to improve on this, you have answered my biggest question with this beautiful demonstration. Thank you very much. :D

  2. Maximiliano Power says:

    I am just start learning coding but need something like this for my fish house, turn on some lights in the middle of the night. I will try this tutorial 2 years after publication with the RB 3. I will keep you inform. Thank you very much for all this tutorials

Comments are closed.

Discuss this article with the rest of the community on our Discord server!
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

ADVERTISEMENT

Maker Faire Bay Area 2023 - Mare Island, CA

Escape to an island of imagination + innovation as Maker Faire Bay Area returns for its 15th iteration!

Buy Tickets today! SAVE 15% and lock-in your preferred date(s).

FEEDBACK