Using the Raspberry Pi to control AC electric power

Notice
VERY IMPORTANT NOTE: THIS IS NOT A HOW-TO ARTICLE. This article explains how the author used a Raspberry Pi to control electric current. However, the author is NOT an electrician, and just because he did something doesn’t mean YOU should, particularly if you are unfamiliar with how to wire electrical devices safely. WIRING A DEVICE IMPROPERLY CAN RESULT IN FIRE, PROPERTY DAMAGE, BODILY INJURY, AND/OR DEATH! So DO NOT just blindly do what the author has done, unless you are certain you know what you are doing and are willing to take full responsibility for your own actions! This article is for INFORMATIONAL PURPOSES AND DISCUSSION ONLY, and is NOT intended to be a guide to building any device!

WE ARE NOT RESPONSIBLE IF YOU ATTEMPT TO BUILD ANYTHING BASED ON WHAT YOU SEE IN THIS ARTICLE AND INJURE YOURSELF OR HAVE PROPERTY DAMAGE AS A RESULT. STOP READING THIS ARTICLE NOW IF YOU ARE UNWILLING TO TAKE FULL RESPONSIBILITY FOR YOUR OWN ACTIONS!!!! AGAIN, THIS IS ONLY TO REPORT ON WHAT THE AUTHOR OF THE ARTICLE DID, AND WE ARE NOT SUGGESTING THAT YOU DO LIKEWISE, PARTICULARLY IF YOU DO NOT FULLY UNDERSTAND AND APPRECIATE THE DANGER OF WORKING WITH LIVE ELECTRIC CURRENT! PLEASE CONSULT WITH A LICENSED ELECTRICIAN BEFORE ATTEMPTING TO BUILD ANYTHING THAT WILL UTILIZE HOUSEHOLD ELECTRICAL CURRENT!

EDIT: This article is getting somewhat dated now, and while the principles shown in this article are still sound, they involve wiring or using devices that directly switch AC power. Also, the quality of the relay boards used is not always great – we have seen several instances of a single relay that simply fails to work correctly on a board of four or eight relays. And many people don’t have the skills to do this, or they are (with some justification) uncomfortable with doing anything that involves AC power. So we’ll just point out that there is another way to do this that doesn’t involve working with AC power directly, and it is explained in an article entitled How to use a Raspberry Pi to trigger wireless remote controlled outlets (and probably other wireless devices). That method has an additional convenience factor, in that the actual switched outlets can be at some distance from the Raspberry Pi. If you know next to nothing about electricity, perhaps consider going that route instead of trying what is shown here.

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):

Pi Power Controller Wiring Diagram SSR

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.

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, but only because there was nothing better available at the time. We no longer recommend this due to the low current-carrying capacity of the relays, and the availability of relay boards better suited for this application. For an example of a better solution, see How we made a Raspberry Pi controlled 8-outlet power box:

Pi Power Controller Wiring Diagram SainSmart

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. However, we no longer recommend these due to the low current rating of the relays, as explained below.

SainSmart 2-Channel 5V Relay Module (NOT tested by us)
SainSmart 2-Channel 5V Relay Module (NOT tested by us)

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 (October 16, 2016): Although the SainSmart boards were designed for use with Arduinos and not Raspberry Pis, there now is a relay board available that was designed for use with the Raspberry Pi. You can read a review of it here: ModMyPi PiOT Relay Board for Raspberry Pi, or you can watch one of these videos:

Or, just visit the manufacturer’s page for the ModMyPi PiOT Relay Board.

EDIT (March 19, 2018): Another board that seems to work quite well with a Raspberry Pi, and that uses relays rated to handle 10 Amps looks like this:

Elegoo 8 Channel DC 5V Relay Module with Optocoupler
Elegoo 8 Channel DC 5V Relay Module with Optocoupler

This unit is sold on Amazon by Elegoo, and the only caveat is that it appears the GPIO pin states are inverted from what you’d expect. So, when a GPIO pin is at logical 0, the relay turns on, and switching it to logical 1 turns the relay off. However the relays have both normally open and normally closed contacts, so you should still be able to control whatever you want to control. If you can wrap your head around that, these work well – all you need to do is connect the Raspberry Pi to the 10 pin strip on the relay board: The Vcc pin on the relay board connects to 5 volts on the Pi (Pin 2), the Gnd pin on the relay board connects to any of the GND pins on the Pi (pin 25, for example), and the other pins (In1 through In8) connect to GPIO pins on the Pi (we suggest using the pins that are color coded green in the pinout diagram on this page).

An example of a power control box built using one of these relay modules can be seen here:  How we made a Raspberry Pi controlled 8-outlet power box

This YouTube video shows a guy using a similar relay board to the one shown above, though from a different seller. And, he’s also using different GPIO ports from the ones we would recommend using, just so his ribbon cable connection looks a bit neater. Regardless, the video does show that these types of relay boards can work quite well with a 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, a far better alternative would be to substitute one of the mechanical relay boards with relays rated to handle 10 Amps (and of course, be careful to never connect anything drawing more than 10 Amps to an outlet). 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.

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. Still, it might not hurt to oversize your power supply a bit (use one rated for 2 Amps, for example), particularly if you are using the mechanical relays.

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

EDIT (September 21, 2016): If you do not wish to build your own device OR do not have the knowledge to do it safely, there is a commercial alternative available that may work. We are NOT recommending this, simply because we have neither owned nor tested one, and we do not know if it has received the necessary approvals for various countries, including wherever you may live. We’re simply alerting you that this product exists, but if you choose to buy one we assume no responsibility whatsoever for any outcome of your decision, good or bad.

The product is the IoT Power Relay from Digital Loggers (the same people that make the Atomic Pi) and its advertised features are as follows:

  • Universal control voltage 3-60VDC or 12-120VAC connects to Arduino, Raspberry Pi, PIC or other micro. Or connect directly to a 12V to 48VDC or even 120VAC circuit.

  • High voltage wiring and safety hazards are eliminated.

  • A single input signal switches four outlets: 2 normally on + 2 normally off.
  • Optical isolation, relay hysteresis and de-bounce protection add safety.

  • A large MOV clamps surges for clean  90-140VAC power.

  • The durable SPDT control relay is rated at 30/40A, >400,000 operations at 12A or 2 million+ operations at 5A.

  • A 12A thermal safety circuit breaker switch prevents overloads.

  • Standard 24″ C-13 detachable cord included free, cords up to 25′ are optional.

  • Professionally built and tested. Not a kit.  Be up and running in minutes.

IoT Power Relay from Digital Loggers
IoT Power Relay from Digital Loggers (NOT tested by us)

For those that have wanted a solution that did not require building from scratch, this might be it, at least in countries that use 120VAC as the standard voltage and use the standard USA/Canada style power outlet. We do not know at this time whether the scripts below would need any modifications to work with this device.

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. Note that you MIGHT need to invert the on and off values for certain mechanical relay boards (send 1 for off and 0 for on, etc.):

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

That 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):

[custom-picontrol]
exten => s,1,Set(TIMEOUT_LOOPCOUNT=0)
exten => s,n,Set(INVALID_LOOPCOUNT=0)
exten => s,n,Set(_IVR_CONTEXT_${CONTEXT}=${IVR_CONTEXT})
exten => s,n,Set(_IVR_CONTEXT=${CONTEXT})
exten => s,n,Set(__IVR_RETVM=)
exten => s,n,GotoIf($["${CDR(disposition)}" = "ANSWERED"]?skip)
exten => s,n,Answer
exten => s,n,Wait(1)
exten => s,n(skip),Set(IVR_MSG=custom/please-enter-rpi-pin)
exten => s,n(start),Set(TIMEOUT(digit)=3)
exten => s,n,Set(PIGPIOPIN=Background(${IVR_MSG}))
exten => s,n,ExecIf($["${IVR_MSG}" != ""]?Background(${IVR_MSG}))
exten => s,n,WaitExten(5,)
exten => 4,1(ivrsel-4),Set(PIGPIOPIN=4)
exten => 4,n,Goto(custom-validpipin,s,1)
exten => 17,1(ivrsel-17),Set(PIGPIOPIN=17)
exten => 17,n,Goto(custom-validpipin,s,1)
exten => 18,1(ivrsel-18),Set(PIGPIOPIN=18)
exten => 18,n,Goto(custom-validpipin,s,1)
exten => 22,1(ivrsel-22),Set(PIGPIOPIN=22)
exten => 22,n,Goto(custom-validpipin,s,1)
exten => 23,1(ivrsel-23),Set(PIGPIOPIN=23)
exten => 23,n,Goto(custom-validpipin,s,1)
exten => 24,1(ivrsel-24),Set(PIGPIOPIN=24)
exten => 24,n,Goto(custom-validpipin,s,1)
exten => 25,1(ivrsel-25),Set(PIGPIOPIN=25)
exten => 25,n,Goto(custom-validpipin,s,1)
exten => 27,1(ivrsel-27),Set(PIGPIOPIN=27)
exten => 27,n,Goto(custom-validpipin,s,1)
exten => i,1,Set(INVALID_LOOPCOUNT=$[${INVALID_LOOPCOUNT}+1])
exten => i,n,GotoIf($[${INVALID_LOOPCOUNT} > 3]?final)
exten => i,n,Set(IVR_MSG=custom/sorry-not-valid-rpi-gpio)
exten => i,n,Goto(s,start)
exten => i,n(final),Playback(no-valid-responce-transfering)
exten => i,n,Goto(app-blackhole,hangup,1)
exten => t,1,Set(TIMEOUT_LOOPCOUNT=$[${TIMEOUT_LOOPCOUNT}+1])
exten => t,n,GotoIf($[${TIMEOUT_LOOPCOUNT} > 3]?final)
exten => t,n,Set(IVR_MSG=no-valid-responce-pls-try-again&custom/please-enter-rpi-pin)
exten => t,n,Goto(s,start)
exten => t,n(final),Playback(no-valid-responce-transfering)
exten => t,n,Goto(app-blackhole,hangup,1)
exten => return,1,Set(_IVR_CONTEXT=${CONTEXT})
exten => return,n,Set(_IVR_CONTEXT_${CONTEXT}=${IVR_CONTEXT_${CONTEXT}})
exten => return,n,Set(IVR_MSG=custom/please-enter-rpi-pin)
exten => return,n,Goto(s,start)
exten => h,1,Hangup
exten => hang,1,Playback(vm-goodbye)
exten => hang,n,Hangup

[custom-validpipin]
exten => s,1,Set(TIMEOUT_LOOPCOUNT=0)
exten => s,n,Set(INVALID_LOOPCOUNT=0)
exten => s,n,Set(_IVR_CONTEXT_${CONTEXT}=${IVR_CONTEXT})
exten => s,n,Set(_IVR_CONTEXT=${CONTEXT})
exten => s,n,Set(__IVR_RETVM=)
exten => s,n,GotoIf($["${CDR(disposition)}" = "ANSWERED"]?skip)
exten => s,n,Answer
exten => s,n,Wait(1)
exten => s,n(skip),Set(IVR_MSG=custom/rpi-gpio-pin-state-selection)
exten => s,n(start),Set(TIMEOUT(digit)=3)
exten => s,n,ExecIf($["${IVR_MSG}" != ""]?Background(${IVR_MSG}))
exten => s,n,WaitExten(5,)
exten => 0,1(ivrsel-0),Set(PIPINSTATE=off)
exten => 0,n,Goto(custom-pincontrol,s,1)
exten => 1,1(ivrsel-1),Set(PIPINSTATE=on)
exten => 1,n,Goto(custom-pincontrol,s,1)
exten => 2,1(ivrsel-1),Set(PIPINSTATE=toggle)
exten => 2,n,Goto(custom-pincontrol,s,1)
exten => 3,1(ivrsel-1),Set(PIPINSTATE=reboot)
exten => 3,n,Goto(custom-pincontrol,s,1)
exten => 4,1(ivrsel-1),Set(PIPINSTATE=status)
exten => 4,n,Goto(custom-pincontrol,s,1)
exten => i,1,Set(INVALID_LOOPCOUNT=$[${INVALID_LOOPCOUNT}+1])
exten => i,n,GotoIf($[${INVALID_LOOPCOUNT} > 3]?final)
exten => i,n,Set(IVR_MSG=no-valid-responce-pls-try-again)
exten => i,n,Goto(s,start)
exten => i,n(final),Playback(no-valid-responce-transfering)
exten => i,n,Goto(app-blackhole,hangup,1)
exten => t,1,Set(TIMEOUT_LOOPCOUNT=$[${TIMEOUT_LOOPCOUNT}+1])
exten => t,n,GotoIf($[${TIMEOUT_LOOPCOUNT} > 3]?final)
exten => t,n,Set(IVR_MSG=no-valid-responce-pls-try-again&custom/rpi-gpio-pin-state-selection)
exten => t,n,Goto(s,start)
exten => t,n(final),Playback(no-valid-responce-transfering)
exten => t,n,Goto(app-blackhole,hangup,1)
exten => return,1,Set(_IVR_CONTEXT=${CONTEXT})
exten => return,n,Set(_IVR_CONTEXT_${CONTEXT}=${IVR_CONTEXT_${CONTEXT}})
exten => return,n,Set(IVR_MSG=custom/rpi-gpio-pin-state-selection)
exten => return,n,Goto(s,start)
exten => h,1,Hangup
exten => hang,1,Playback(vm-goodbye)
exten => hang,n,Hangup

[custom-pincontrol]
exten => s,1,Noop(GPIO pin selected is ${PIGPIOPIN} and pin state is ${PIPINSTATE})
exten => s,n,System(sudo /root/gpio${PIGPIOPIN}.sh ${PIPINSTATE})
exten => s,n,Playback(custom/pin)
exten => s,n,SayNumber(${PIGPIOPIN})
exten => s,n,Playback(en/ha/is)
exten => s,n,ExecIf($["${SHELL(cat /sys/class/gpio/gpio${PIGPIOPIN}/value):0:1}" = "0"]?Playback(en/ha/off):Playback(en/ha/on))
exten => s,n,Goto(app-blackhole,hangup,1)
exten => h,1,Hangup

The [custom-picontrol] context above actually allows you to enter any of the possible GPIO pins (available to the user) on the Raspberry Pi, but in our example we’re only using pins 17 and 18, so if you don’t plan on using any other GPIO pins, you may want to remove all the lines that start with exten => N, where N is any number other than 17 or 18. The first two contexts are based on FreePBX IVR logic, except that instead of using the selection to transfer to an extension or other destination, the choices made are stored in variables for use by the [custom-pincontrol] context.

In order for this to work, there are a few extra steps you must take. First, you must give Asterisk permission to run the scripts. Run the visudo command as root, and use it to add these lines to the end of /etc/sudoers:

asterisk ALL = NOPASSWD: /root/gpio17.sh
asterisk ALL = NOPASSWD: /root/gpio18.sh

If you want to allow Asterisk to control all the GPIO pins rather than just 17 and 18, here’s a complete list of the lines to add to /etc/sudoers. Note that you must create the additional scripts and make them executable:

asterisk ALL = NOPASSWD: /root/gpio4.sh
asterisk ALL = NOPASSWD: /root/gpio17.sh
asterisk ALL = NOPASSWD: /root/gpio18.sh
asterisk ALL = NOPASSWD: /root/gpio22.sh
asterisk ALL = NOPASSWD: /root/gpio23.sh
asterisk ALL = NOPASSWD: /root/gpio24.sh
asterisk ALL = NOPASSWD: /root/gpio25.sh
asterisk ALL = NOPASSWD: /root/gpio27.sh

You must also create some system recordings and place them in the /var/lib/asterisk/sounds/custom directory. These can be added using the FreePBX System Recordings module, which is actually the preferred way because it will make sure all the permissions are set correctly. These are the four new recordings you need, and the suggested scripts:

please-enter-rpi-pin.wav: “Please enter the Raspberry Pi GPIO pin number you wish to control:”
rpi-gpio-pin-state-selection.wav: “Press zero to turn the GPIO pin off, one to turn it on, two to set it to the opposite of its current state, three to initiate a reboot sequence, or four to hear the current status of the pin.”
sorry-not-valid-rpi-gpio.wav: “I’m sorry, that is not a valid Raspberry Pi GPIO pin number. Please try again.”
pin.wav: “Pin”

If you are handy with an audio editor such as Audacity, you can probably slice the word Pin off of one of the existing recordings that start with the word “Pin” (found in /var/lib/asterisk/sounds/en for English-language speakers). For the others, you can record them yourself, or you could perhaps use text-to-speech software to generate them. There’s also the option of using flite text-to-speech synthesis if it is installed on your system, but you’ll need to modify the contexts accordingly (we don’t care for the sound of flite, so you are on your own with that).

Finally, you must go into FreePBX and under Admin/Custom Destinations, add a Custom Destination called “Raspberry Pi control”, then give it this destination:

custom-picontrol,s,1

Then go into Applications/Misc Applications and add a new Misc Application called “Raspberry Pi Control” or whatever you want. Give it an extension number you want to use when controlling pins on your Raspberry Pi – we used 774 (“RPI” on a standard touch-tone keypad). For the destination, select “Custom Destinations” and “Raspberry Pi control”, then apply the changes and you should be all set.

Other ways to control the pins:

There are many other ways you can control the pins. You can even do it from another computer on your network. For example, we have set up SSH Passwordless Logins from another computer on our local network. Having done that, we can create scripts on that computer that look like this (note you do NOT put these on the Raspberry Pi!):

In ~/gpio17.sh place these two lines:

#!/bin/bash
ssh root@IP_address_of_Raspberry_Pi "/root/gpio17.sh $1"

In ~/gpio18.sh place these two lines:

#!/bin/bash
ssh root@IP_address_of_Raspberry_Pi "/root/gpio18.sh $1"

Replace IP_address_of_Raspberry_Pi with the IP address of your Raspberry Pi – of course, this works best if the Raspberry Pi is always on the same IP address.

Now we can run the bash scripts from a another system, just as if we were logged into the Raspberry Pi. But the beauty of this is that you can call those scripts from other software on the system. Let’s say the other system is a home theater PC, and it has a ~/.lircrc file to accept commands from the remote. You could possibly add lines like this (note these are dependent on the remote you are using, and are just examples):

begin
 prog = irexec
 button = KEY_RED
 config = ~/gpio17.sh &
 repeat = 0
endbegin
 prog = irexec
 button = KEY_BLUE
 config = ~/gpio18.sh &
 repeat = 0
end

Now every time you press the red button on the remote, GPIO17 on the Raspberry Pi would toggle to the opposite of its current state (since no option is specified). And if you pressed the blue button, GPIO18 would toggle. So you could use a remote on a different system to send commands to the Raspberry Pi to power a device on or off. Or you could create a script or program that switches things on or off at certain times. We’ve actually done this so we know it works!

There is software available that allows you to use a web interface to control the GPIO pins, such as BerryIO and WebIOPi. It seems that the possibilities are endless. I could envision building something like an automatic lawn watering system controller that could go out and download the weather report, and then decide to water or not water based on the probability of significant amounts of rain. That’s just one example of the sort of thing you could do if you have the ability and the expertise.

Again, should you foolishly ignore our advice to not try building anything like this unless you know how to protect yourself when working with household electrical current, PLEASE remember to use extreme caution! We would really hate to see anyone kill or injure themselves, or set their house on fire (but we will not be responsible if you do that, because we’ve warned you every way we can think of!).

 

27 thoughts on “Using the Raspberry Pi to control AC electric power

  1. Pingback: raspberry pi control ac power relay control | asterisk의 모든것
  2. Not working for me, always says ’18 is ON’ can’t change it.

    Also how I direct an external call to feature code 774 ?

    Thanks

    1. Did you add all the line

      asterisk ALL = NOPASSWD: /root/gpio18.sh

      to the end of /etc/sudoers ? If you did, try rebooting the raspberry Pi. What happens when you go to a Linux command prompt and run these three lines?

      sudo echo “18” > /sys/class/gpio/export
      sudo echo “out” > /sys/class/gpio/gpio18/direction
      sudo echo 1 > /sys/class/gpio/gpio18/value

      After doing that check the status, it should say pin 18 is on. If that works that way then there’s a permissions issue; for some reason the addition to /etc/sudoers isn’t being recognized. Or maybe you left something out when you copied the configuration.

      As for directing an external call, simply send it to the custom destination you created (“Raspberry Pi control”), It should appear as a destination in your inbound routes or a selection from your IVR, etc.

      1. Many thanks for the reply. Yes I have added asterisk ALL = NOPASSWD: /root/gpio18.sh to etc/sudoers and followed all instructions to the letter.

        sudo echo “18″ > /sys/class/gpio/export showed :-

        sudo: parse error in /etc/sudoers.d/sudoers near line 26
        sudo: no valid sudoers sources found, quitting
        sudo: unable to initialize policy plugin

        sudo echo 1 > /sys/class/gpio/gpio18/value showed :-

        -bash: /sys/class/gpio/gpio18/value: No such file or directory

        sudo echo 1 > /sys/class/gpio/gpio18/value showed :-

        -bash: /sys/class/gpio/gpio18/value: No such file or directory

        It would appear that it’s not finding the gpio19.sh script in root ?

        Thanks

        Dave.

        1. Is there actually a file named /etc/sudoers.d/sudoers on your system, and if so, did you change or modify it in any way? It seems to be saying there is something wrong with that file at or near line 26. The other problems stem from the fact that you are not executing the commands as root – in some cases if you don’t have permission to access a file or device, Linux will not even acknowledge its existence to you, presumably for security reasons.

          Try running something like
          sudo ls /root
          Chances are you will still get the same error about the error in /etc/sudoers.d/sudoers and until you get that fixed, none of this will work.

          In RasPBX it appears there is no such file (the /etc/sudoers.d/ directory exists, but it only has a README file in it) so we’re not sure why you have one or what is supposed to be in it.

          Also, when editing configuration files, be aware that if you take the file to a Window-based machine, edit it there, and then save it back you will most likely change the line endings and corrupt the file. Linux configuration files should only be edited on a Linux machine, or in a text editor capable of saving the file with Linux standard line endings.

          1. sudo is /root showed:-

            root@raspbx:~# sudo ls /root
            sudo: parse error in /etc/sudoers.d/sudoers near line 26
            sudo: no valid sudoers sources found, quitting
            sudo: unable to initialize policy plugin

            I always edit with Programmers Notepad and save as pure text (most of the time!)

            Yes, /etc/sudoers.d contains a readme and sudoers

            #
            # This file MUST be edited with the ‘visudo’ command as root.
            #
            # Please consider adding local content in /etc/sudoers.d/ instead of
            # directly modifying this file.
            #
            # See the man page for details on how to write a sudoers file.
            #
            Defaults env_reset
            Defaults mail_badpass
            Defaults secure_path=”/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin”

            # Host alias specification

            # User alias specification

            # Cmnd alias specification

            # User privilege specification
            root ALL=(ALL:ALL) ALL

            # Allow members of group sudo to execute any command
            %sudo ALL=(ALL:ALL) ALL

            # See sudoers(5) for more information on “#include” directives:

            #includedir /etc/sudoers.d

            asterisk ALL = NOPASSWD: /root/gpio17.sh
            asterisk ALL = NOPASSWD: /root/gpio18.sh

          2. One thing I just spotted, on line 24 is the ‘%’ before sudo ALL=(ALL:ALL) ALL supposed to be there ?

          3. Apparently we have reached the quote level limit on replies here, but anyway,

            Yes, the line

            %sudo ALL=(ALL:ALL) ALL

            is correct, including the %

            Note the comment at the top:

            # This file MUST be edited with the ‘visudo’ command as root.

            Try running that command and them re-saving the file. If that doesn’t work, run it again but this time delete the lines you added, then save the file. Then try the sudo ls /root command again. If it works this time, stop using Programmers Notepad to edit Linux system files, and use visudo to add those lines back in.

            Sure hope you have a root login on that system because if you don’t you are probably screwed, because sooner or later you will need to either login as root or use sudo to perform some vital system task, and if you’re corrupted sudo’s configuration file to where it won’t work at all, that’s a bad thing.

            We have successfully edited the sudoers file using nano rather than visudo, so there probably isn’t anything magical about that program (other than that it might eliminate a require to reboot the system before the added lines are recognized, not 100% sure about that), but if you changed the file on a Windows box it’s extremely likely you have changed the line endings from Linux type to Windows type (by forgetting to select Unix line endings before saving the file) and that’s how it got messed up.

  3. I Think I go it, Looks like it needed a space after the comment #includedir /etc/sudoers.d

    sudo is root now shows ‘:-

    oot@raspbx:~# sudo ls /root
    debug,error,notice,verbose gpio18.sh nano.save.1
    gpio17.sh nano.save sudoers
    root@raspbx:~#

    Thanks, I’ll try again…

  4. And the three original queries now show :-

    root@raspbx:~# sudo echo “18” > /sys/class/gpio/export
    echo: write error: Device or resource busy

    root@raspbx:~# sudo echo “out” > /sys/class/gpio/gpio18/direction

    root@raspbx:~# sudo echo 1 > /sys/class/gpio/gpio18/value

    1. So, it worked?

      When you saw:

      root@raspbx:~# sudo echo “18″ > /sys/class/gpio/export
      echo: write error: Device or resource busy

      That may have been because GPIO pin 18 had already been initialized. You only have to do that once after a reboot.

      Or it may be in some weird state that necessitates a reboot. Note that the scripts test to see if the pin has previously been initialized and if so they don’t attempt to do it again.

      Anyway, if you followed the rest of the instructions, I think you will find that it works, now that you have resolved the sudo issue. But, if you edited any of the configuration files in Windows, be sure to load them back into your editor and change the line endings to Unix and then save them back, otherwise they will not work.

  5. Nope, Still not working 17 and 18 still stay ‘ON’ from the voice prompts even when I press 0 to turn them off. Also I’m unable to toggle. I think, not sure there must be a problem in the scripts as the rest appears to working ?. Fine what you said about editing files I used nano BTW.

    1. We’re stumped then. However, once the pin is initialized and set for output, you should be able to do

      sudo echo 1 > /sys/class/gpio/gpio18/value

      to turn the pin on and

      sudo echo 0 > /sys/class/gpio/gpio18/value

      to turn the pin off

      Remember that you can look at the value of /sys/class/gpio/gpio18/value to see its current state at any time. If those commands aren’t changing the pin values then the scripts will never work because that is basically all they do. We can’t imagine that different Raspberry Pi models would implement this differently, but suppose that anything is possible.

      1. hello, i have the same problem , have you could , resolve this problem?
        root@odroid:/sys/class/gpio# echo 199 >> /sys/class/gpio/export
        bash: echo: write error: Device or resource busy

  6. I’m stumped too now, Indeed I can toggle a pin on and off (tested with multi meter)with sudo echo 1 > /sys/class/gpio/gpio18/value BUT still not working with the rest, oh well I give up for now. I’ll have another go in a day or two …

  7. I get the same problem as Dave, I can turn things on and off but not through asterisk, no matter what it says the pin is ON and it never changes the state the pin is in. I did see your comment concerning editing files in windows. I copied and pasted all your examples in notepad and transferred them over. I suppose I can delete them and try manually writing them.

  8. Ok I did solve the problem by deleting the files I made with notepad and rewriting them by touch /root/gpio17.sh and the editing them with nano, then with winSCP I changed the permissions of those files to allow all to execute them. I might have my wiring done wrong but when asterisks says the pin is off it is really on and vice versa. But at least I got that far and now I know not to use notepad to edit files for Linux.

  9. Hi Admin,

    I can find the Misc Applications in my raspbx, NO Misc Applications under Application

    Thanks,

  10. Good day> i have set up everything according to the above tutorial. Everything is working as it should. Thank you. I would however like to be able to add a time limit to the on/of i.e it switches the relay on for five seconds and than off again. This is for access control so i dont really want the gut unlocked until i send another code.

  11. The SSR-40DA is rated at 3-32V, 6-25 mA. If you use the 3.3V from the Rasperry Pi you will need to provide about 25 mA, which is too much for the Pi GPIO pins. At this area it might work or not, and that is not a fault of the SSR.
    It is anyway a good idea to have a transistor connected to 5V between the GPIO and the SSR, so the current is provided by the Pi’s power supply directly, not from the GPIO.

  12. Hi eveyone !

    I found this page really interesting and full knownledge ! Thank you !

    I’m setting up a media center based on RPi and Hifiberry under OpenELEC with Kodi.
    I want my mixtable and 5.1 speakers to stop and start based on Kodi activity (play, resume and idle time).
    So I bought the 2 solid state relay interface from Sainsmart (still waiting for shipping…).
    By the time it’s delivered, I wrote a script based on the one on this article to drive the GPIOs (i.e. the relays), but pushed a bit further on parameterizing some stuff.

    I created a github repo for the occasion : .
    Feel free to use, comment or even contribute !

  13. Thank you for this, just what i’m looking for to do some simple home automation tasks with RASPBX
    It worked very nearly first time. One suggestion might be to explain to Linux newbies like me how to actually make
    the shell scripts bootable with
    chmod +x gpio17.sh
    etc.
    and to use ./ when testing them from the console.

    The relay modules that you call SainSmart are very cheap on ebay, and work directly from the RPi 3.3v GPIO pins and 5v supply. The only issue is inversion, the relay is energised when the pin is LOW so I am going to have to modify the recordings and/or the code to suit.

    In fact, all I need is four separate contexts, on and off for each relay, with four corresponding extension numbers without any toggle and just a simple confirmation voice prompt.
    I’ll see what I can do.

  14. hi , we’re newbie in this field. we used a solid state relay and we cant get a refund for that so continued with solid state relay . we used npn transistor to trigger iit but our problem is we dont know where to connect the npn transistor on our circuit. pls help.

    1. Lee27, this page shows basic info including how to calculate the value of the resistors. Note that if your relay is intended to be controlled by 5 volts then you probably don’t need resistor R1, but you would still need resistor R2:

      https://einhugur.com/blog/index.php/xojo-gpio/putting-the-gpio-pin-behind-transistor-to-get-more-current/

      If you were using a mechanical relay with a coil then you’d also need a diode for kickback protection, as shown in this article:

      https://www.petervis.com/Raspberry_PI/Driving_Relays_with_CMOS_and_TTL_Outputs/Driving_Relays_with_CMOS_and_TTL_Outputs.html

      If you prefer to watch a couple of videos, start here: https://www.youtube.com/watch?v=Dn2NEZC5dEM

      There are many other pages on the subject, just put something like “Raspberry Pi GPIO NPN transistor” (without the quotes) into a search engine to see more.

  15. I set up a box to control 8 power outlets using the 8 Channel DC 5V Relay Module as shown above. I wrote a bash script to control the outlets that some might like:

    #! /bin/bash
    cd /home/pi
    
    # Read outlet names from files
    outlet=1
    until [ $outlet -gt 8 ]; do
    outletname[$outlet]=`cat "outletname$outlet"`
    let outlet+=1
    done
    
    while :
    do
        echo ""
        echo "PowerPi Control"
        echo ""
        #display status of outlets
        outlet=1
        until [    $outlet -gt 8 ]; do
            if [ "$outlet" -eq 1 ]; then
                [ ! -e "/sys/class/gpio/gpio4/value" ] && value=-1 || value=`cat /sys/class/gpio/gpio4/value`
            fi
            if [ "$outlet" -eq 2 ]; then
                [ ! -e "/sys/class/gpio/gpio17/value" ] && value=-1 || value=`cat /sys/class/gpio/gpio17/value`
            fi
            if [ "$outlet" -eq 3 ]; then
                [ ! -e "/sys/class/gpio/gpio18/value" ] && value=-1 || value=`cat /sys/class/gpio/gpio18/value`
            fi
            if [ "$outlet" -eq 4 ]; then
                [ ! -e "/sys/class/gpio/gpio27/value" ] && value=-1 || value=`cat /sys/class/gpio/gpio27/value`
            fi
            if [ "$outlet" -eq 5 ]; then
                [ ! -e "/sys/class/gpio/gpio22/value" ] && value=-1 || value=`cat /sys/class/gpio/gpio22/value`
            fi
            if [ "$outlet" -eq 6 ]; then
                [ ! -e "/sys/class/gpio/gpio23/value" ] && value=-1 || value=`cat /sys/class/gpio/gpio23/value`
            fi
            if [ "$outlet" -eq 7 ]; then
                [ ! -e "/sys/class/gpio/gpio24/value" ] && value=-1 || value=`cat /sys/class/gpio/gpio24/value`
            fi
            if [ "$outlet" -eq 8 ]; then
                [ ! -e "/sys/class/gpio/gpio25/value" ] && value=-1 || value=`cat /sys/class/gpio/gpio25/value`
            fi
            [ "$value" -eq -1 ] && echo "Outlet $outlet (${outletname[$outlet]}) is currently OFF (UNINITIALIZED)"
            [ "$value" -eq 0 ] && echo "Outlet $outlet (${outletname[$outlet]}) is currently ON"
            [ "$value" -eq 1 ] && echo "Outlet $outlet (${outletname[$outlet]}) is currently OFF"
            let outlet+=1
        done
        echo ""
        echo "Enter action to take (On, Off, Reboot, Toggle, or Rename) followed by outlet number, for example OFF 1 or ON 2.    You can also enter QUIT or EXIT:"
        read action outlet
        action=${action,,}
        [[ "${action}" == "exit" ]] && exit
        [[ "${action}" == "quit" ]] && exit
        if [[ "${action}" == "rename" ]]; then
            echo "Current name for outlet $outlet is ${outletname[$outlet]}"
            read -p "Enter new outlet name, or Enter to leave unchanged: " outletname
            [[ ! -z "${outletname// }" ]] && echo "Outlet $outlet name changed to $outletname" && outletname[$outlet]=$outletname && echo $outletname > "outletname$outlet"
        elif [[ "${action}" =~ ^(on|off|reboot|toggle)$ ]]; then
            if [ "$outlet" -ge 1 -a "$outlet" -le 8 ]; then
                # Valid outlet number, select correct gpio pin number
                [ "$outlet" -eq 1 ] && gpio=4
                [ "$outlet" -eq 2 ] && gpio=17
                [ "$outlet" -eq 3 ] && gpio=18
                [ "$outlet" -eq 4 ] && gpio=27
                [ "$outlet" -eq 5 ] && gpio=22
                [ "$outlet" -eq 6 ] && gpio=23
                [ "$outlet" -eq 7 ] && gpio=24
                [ "$outlet" -eq 8 ] && gpio=25
                echo "Valid action: $action $outlet (controlling GPIO pin $gpio)"
                [ "$action" == "reboot" ] && echo "Please wait 30 seconds for reboot cycle to complete..."
                `sudo /root/gpio$gpio.sh $action`
            else
                echo "Invalid outlet number!!!"
            fi
        else
            echo "Invalid action!!!"
        fi
    done
    

    The outlet names are stored in individual files named outletname1 through outletname8. If you use different GPIO pinis than I did, or mapped them to different outlets you will need to adjust the script accordingly. Note that after a reboot, the outlets will remain off but the GPIO pins will stay uninitialized until you actually send a command, and that is because if you try to initialize the pins at startup the relays will click as each pin is initialized. It doesn’t hurt anything to leave them uninitialized until you want to turn an outlet on.

    I just wanted something simple that interacted with the GPIO pins directly and that did not require any added libraries, Python scripts, or anything like that. I’m sure this script could be improved by someone competent in bash, but it’s short enough and it works fine on an original first edition Raspberry Pi, and now I can ssh in and remotely control whatever is connected to those eight outlets. If you do build something like this, be sure to use a power cable heavy enough to support the load you will be connecting.

  16. I’m actually using the IoT Power Relay for a different reason. I am controlling it from my Denon receiver to power on an external amp for an 11.2 setup. I hadn’t thought about being able to drive it with a Pi, it would be a relatively clean and safe option for a prewired relay power-strip. It is unfortunately only one channel, but it does indeed provide another choice.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Recent Posts

Recent Comments

Archives

Categories

Meta

GiottoPress by Enrique Chavez