Using the Raspberry Pi to control AC electric power

We were trying to figure out if a Raspberry Pi could be made to control a device that is powererd by 120 volts AC. Our first idea was to build a device based on this wiring diagram, which would have let us control two electric outlets individually, using GPIO pins 17 and 18 on the Raspberry Pi. We tried using a Solid State Relay rated at 25 Amps rather than the 40 Amp one shown in the diagram, but the wiring of the two devices is the same (click on the diagram to enlarge):

What we found was that the above method worked IF you get good Solid State Relays. Unfortunately, we purchased two of them, and only one of them would work with the Raspberry Pi. While the rated trigger voltage on the label is 3 – 32 volts DC, we found that one of the relays we purchased required something closer to four volts to trigger. We then found other reports where other purchasers of those types of relays have encountered similar issues. Some people could buy several and find they all worked, others were not so fortunate and would have issues like we did.Using the Raspberry Pi to control AC electric power

We returned the bad one for a refund, and searched for another solution. But we do note that some of those Solid State Relays such as the ones shown in the diagram can handle up to 40 Amps, assuming you use a good heat sink, and even the less expensive units we purchased can handle up to 25 Amps with a heat sink, so had we been trying to control a heavy load we might have been willing to order another one and try it. It’s quite possible that these relays would work better with a proper transistor and resistor added to the control circuit (and connecting one leg of the transistor to the +5 Volt supply on the Raspberry Pi), but since we aren’t electronic engineers we did not attempt to design such a circuit.

We then tried this:

The above circuit uses a SainSmart 2 Channel 5V Solid State Relay Module Board. Unlike the Solid State Relays mentioned earlier, these devices do require a +5 volt power connection, but they only require a trigger voltage of 2.5V – 20V. We purchased one of those and tried it, and had no problem triggering it from the Raspberry Pi.

The only downside is that these devices are only rated to handle 2 Amps (Volts x Amps = Watts, so if your voltage is 110 volts then that means you could in theory use up to a 220 watt load. Remember that motors and some other devices can draw many times their rated load for a second or two when starting up). We only wanted to switch power to devices that draw perhaps a couple dozen Watts at most, so the 2 Amp limitation wasn’t an issue. If you need to control something that draws more current, or you want to control a DC load, then perhaps this SainSmart 2-Channel 5V Relay Module for Arduino DSP AVR PIC ARM (pictured at right) that uses mechanical relays would work for you, but we have never attempted to use one of those, so cannot comment on whether or how well those would work. (EDIT December 21, 2013:) We have discovered that the mechanical relay boards are wired a bit differently than the solid state ones, due to differences between the Arduino and the Raspberry Pi, so at a very minimum you would probably want to add something like a ULN2803A or ULN2003A integrated circuit (the first can handle 8 channels, the latter only 7) to shift the levels, and use a separate external power supply to power the relay coils, as shown in this diagram (which shows the 4-channel version of the mechanical relay board) and discussed in this thread (also this thread and this one). Alternately, you could use individual NPN transistors and resistors to shift the levels. We’ve also been made aware of the SupTronics Expansion Board Made for Raspberry Pi that among other things provides an “8-channel darlington Driver chip allowing to control electronic circuits which require more current to drive them”, that might be suitable for driving one of these relay boards — it uses a ULN2803A integrated circuit (see full details here, and please note that we have not tested one of these boards to see if it would work in this application). We are not electronic engineers, but suffice it to say that the Raspberry Pi GPIO pins send +3.3 volts when turned on, whereas the Arduino sinks current to ground when on, and the mechanical relay board was definitely designed to work with the Arduino, not the Raspberry Pi.

EDIT August 26-28, 2013: Someone (not us) posted a link to this article on Reddit, where in the comments it was criticized for showing a regular outlet in a circuit that can only draw 2 Amps. One commenter labeled this “a pretty irresponsible article” and noted that “using a 2 amp rated, but normal looking outlet with nothing to interrupt the circuit if it is overloaded sounds like a terrible idea and risks starting a fire. It is not hard to exceed 2 amps.” But as someone else noted, you can’t readily purchase a special outlet that is intended for use only with smaller loads. We only show the outlet to illustrate how a small device, for example a device powered by a typical “wall wart” power supply that only draws a few watts, could be controlled. The diagrams above are for conceptual and illustrative purposes only – we are NOT actually advising you to build any such circuit or to use that type of outlet, but if you nevertheless attempt to build such a thing and thereby assume all the risks of doing so, we at the very least suggest you affix a conspicuous label showing the maximum amperage and wattage ratings (for example: MAXIMUM RATING 2 AMPS / 220 WATTS PER OUTLET or whatever is appropriate for the circuit you build). It might also be a good idea to put some type of additional protection, such as a 2 amp fuse or circuit breaker, in each leg of the circuit between the hot side of the outlet and the Solid State Relay Module Board. Or you could substitute one of the SainSmart mechanical relay boards, which supposedly will handle up to a 10 amp load, but we have never tried any of those so you are on your own there. But again, this is not and was never intended to be a hardware construction article, so if you attempt to build anything such as this, please be sure you know what you are doing!

Also, it should go without saying that you should NEVER UNDER ANY CIRCUMSTANCES permanently connect a circuit of this type to your home’s electrical wiring. Don’t even think about it; it’s not safe to do that and probably would violate at least a dozen sections of the electrical codes where you reside. We shouldn’t even have to say this, but apparently the use of a regular outlet in the illustration led a couple of Reddit commenters to think we might actually be advocating something like that. Apparently they completely overlooked the cord and plug in the diagram, which would not be used in any kind of permanent installation. We are NOT advocating permanently connecting a circuit of this type directly to your home’s wiring because that would be an extremely stupid and dangerous thing to do, not to mention illegal!

We notice that the harshest Reddit commenters were apparently too cowardly to leave their most scathing comments in our comment section, where we might have addressed them more directly. Since we are not Reddit users (we read it very occasionally, but don’t post there) we will not further dignify some of their more irrational statements, particularly since the true intent of this article was to explore the methods that can be used to control a circuit of this type. In other words, the focus of this article is the software, not the hardware. But on that topic, for those that are interested in the hardware side of things, we’ll just note that SainSmart also makes these Solid State Relay Module Boards in 4-channel and 8-channel models. If you prefer the boards with mechanical relays rather than the solid state type, those also come in 4-channel and 8-channel models. Again, we simply don’t know if or how well the mechanical relay versions of these boards work with a Raspberry Pi, apart from what we have read in the threads linked above.

We were a little concerned that the power supply used to power the Raspberry might not support the additional load of the control circuits on the solid state relays. According to the description on the SainSmart site, the board we used requires 5 Volts DC at 160mA. According to this page on the Raspberry Pi web site, “Model B owners using networking and high-current USB peripherals will require a supply which can source 700mA (many phone chargers meet this requirement). Model A owners with powered USB devices will be able to get away with a much lower current capacity (300mA feels like a reasonable safety margin).” We aren’t using any USB peripherals at all, let alone high-current ones, and the power supply we are using produces 1000mA (1 Amp), so it would appear that the power consumption is well within the power supply’s capacity. And, we haven’t had any power issues.

NOTE: Devices shown in the diagrams are NOT exactly to scale.

Controlling the device:

Controlling the device is a matter of turning the GPIO pins on or off. We came up with a couple of simple bash scripts to do this:

For GPIO17 (filename /root/gpio17.sh):

#!/bin/bash

if [ -z $1 ]
then
    opt="toggle"
elif [ -n $1 ]
then
    opt=$1
fi

let "sleep = $RANDOM + 10000"
sleep "0.$sleep"

if [ $(pgrep gpio17.sh|wc -w) -gt "2" ]; then
    exit
fi

if [ ! -e "/sys/class/gpio/gpio17/value" ]
then
    echo "17" > /sys/class/gpio/export
    echo "out" > /sys/class/gpio/gpio17/direction
fi

case $opt in
    on)
        echo 1 > /sys/class/gpio/gpio17/value
        ;;
    off)
        echo 0 > /sys/class/gpio/gpio17/value
        ;;
    toggle)
        value=`cat /sys/class/gpio/gpio17/value`
        if [ $value -ne 0 ]
        then
            echo 0 > /sys/class/gpio/gpio17/value
        else
            echo 1 > /sys/class/gpio/gpio17/value
        fi
        ;;
    reboot)
        echo 0 > /sys/class/gpio/gpio17/value
        sleep 30
        echo 1 > /sys/class/gpio/gpio17/value
        ;;
    status)
        exit
        ;;
    *)
        echo "Invalid option - use on, off, toggle, or reboot (toggle is the default)."
        exit
        ;;
esac

sleep 3

And for GPIO18 (filename /root/gpio18.sh):

#!/bin/bash

if [ -z $1 ]
then
    opt="toggle"
elif [ -n $1 ]
then
    opt=$1
fi

let "sleep = $RANDOM + 10000"
sleep "0.$sleep"

if [ $(pgrep gpio18.sh|wc -w) -gt "2" ]; then
    exit
fi

if [ ! -e "/sys/class/gpio/gpio18/value" ]
then
    echo "18" > /sys/class/gpio/export
    echo "out" > /sys/class/gpio/gpio18/direction
fi

case $opt in
    on)
        echo 1 > /sys/class/gpio/gpio18/value
        ;;
    off)
        echo 0 > /sys/class/gpio/gpio18/value
        ;;
    toggle)
        value=`cat /sys/class/gpio/gpio18/value`
        if [ $value -ne 0 ]
        then
            echo 0 > /sys/class/gpio/gpio18/value
        else
            echo 1 > /sys/class/gpio/gpio18/value
        fi
        ;;
    reboot)
        echo 0 > /sys/class/gpio/gpio18/value
        sleep 30
        echo 1 > /sys/class/gpio/gpio18/value
        ;;
    status)
        exit
        ;;
    *)
        echo "Invalid option - use on, off, toggle, or reboot (toggle is the default)."
        exit
        ;;
esac

sleep 3

Be sure to make the scripts executable. If you want to control any of the other GPIO pins, just copy the text of either of the above scripts into a text editor (one that will not change the line endings) and then do a global search and replace for the pin number – for example, if you use the script for pin 18, and you want to control pin 4, just replace all occurrences of “18” with “4”, and then save the script as /root/gpio4.sh and make it executable. Besides 4, 17, and 18, other GPIO pin numbers you can use are 22, 23, 24, 25, and 27 – that’s on a Revision 2 board, but if you happen to have a Revision 1 board then substitute 21 for 27. And if you think the GPIO pin numbering on a Raspberry Pi makes absolutely no sense at all, you are not alone, since the GPIO pin numbers are not in any logical sequence, and bear no relationship whatsoever to the actual positions of the pins on the board. The best thing you can do is look at a chart such as this one to help you keep track of which pin is which.

(Strictly speaking, you may be able to control certain other pins on the Raspberry Pi as well, but the eight GPIO pins mentioned in the previous paragraph should be your first choices for any projects of this type, and controlling any of the others is beyond the scope of this article. Also, note that the wiring diagrams above show Revision 2 boards, which have slightly different pinouts from Revision 1 boards, although none of the pins actually used for wiring in those diagrams are different between revisions. This article assumes you have a Revision 2 board, so if you have Revision 1, substitute any references to pin 27 with pin 21).

The scripts accept four arguments – on, off, toggle, or reboot (actually it also accepts a fifth, status, but that is for a special purpose and it not really intended for use directly from a command prompt). toggle is the default if no argument is specified.

There is a small section at the top of each script that may confuse some readers:

let "sleep = $RANDOM + 10000"
sleep "0.$sleep"

if [ $(pgrep gpio17.sh|wc -w) -gt "2" ]; then
    exit
fi

Using the Raspberry Pi to control AC electric power SchematicThat section delays a random amount of time (0.1 to 0.42767 seconds), then checks to see if the script is already running, without writing anything to the Raspberry Pi’s SD card (which could shorten the card’s lifespan if done too frequently). If the script is already running it bails out. While it is unlikely that a user would attempt to start the same script twice, this pretty much guards against it. That’s also the point of the “sleep 3″ at the end of the script, which keeps devices from being toggled on or off too quickly. If you know of a better way to do this, feel free to modify the script, and also to post your suggested modifications in the comments (but, please do not suggest reading man pages. If that is all you can be bothered to offer, please just move along).

The reason we used two scripts for the two pins, rather than just one with an added option to specify which pin to control, is so that you could control the two different pins simultaneously without being denied access to one because the script is already running on the other.

The options should be pretty obvious:

on – turn the pin on
off – turn the pin off
toggle – if the pin is currently off, turn it on, and vice versa (this is the default if no option is specified)
reboot – turn the pin off for 30 seconds, then turn it on

The hidden one, status, is a do-nothing command that only makes sure that the pin is initialized, but does not change its state. It is meant to be used when you are calling this script from Asterisk. Yes, you can do that, once the above scripts are enabled and you know they are working properly!

Controlling the device from Asterisk/FreePBX:

This section assumes that the Raspberry Pi is running Asterisk for Raspberry Pi (RasPBX), though it should work with any other FreePBX-based distribution that runs on the Raspberry Pi. To allow Asterisk to control the GPIO pins, you could add the following lines to /etc/asterisk/extensions-custom.conf (note this requires a few custom recordings and a bit of additional configuration, which will be discussed in a moment):

 

For more detail: Using the Raspberry Pi to control AC electric power


About The Author

Ibrar Ayyub

I am an experienced technical writer holding a Master's degree in computer science from BZU Multan, Pakistan University. With a background spanning various industries, particularly in home automation and engineering, I have honed my skills in crafting clear and concise content. Proficient in leveraging infographics and diagrams, I strive to simplify complex concepts for readers. My strength lies in thorough research and presenting information in a structured and logical format.

Follow Us:
LinkedinTwitter

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top