Control a Relay From Anywhere Using the Raspberry Pi

article

If you found this article after doing a search on Google, welcome! On this website you will find plenty of content around DIY home automation using open-source hardware. Enjoy the article!

I have been asked a lot about writing tutorials using the Raspberry Pi for home automation, as well as how to access your home automation systems from anywhere. And this is exactly what I will show you in this tutorial: you are going to learn how you can control a relay that is attached to your Raspberry Pi, from any device like your computer or smartphone, and from anywhere in the world.

In this project, we will connect the relay to a simple LED, but of course this LED could be replaced by anything like a lamp, some lights on the ceiling, or the motor of your electric curtains. And to control this relay from anywhere, we are going to run a web server based on Node.js to control the relay from a web browser. Sounds exciting ? Let’s dive in !

Hardware & Software Requirements

For this tutorial, of course you will need a Raspberry Pi board. The version of the board or the model (A or B) doesn’t really matter, but keep in mind that you will have to connect it to your local network, so you will need a WiFi dongle if you are using the A model which doesn’t have an Ethernet port. In this tutorial, I used a Raspberry Pi model B with the WiPi dongle.

For the components, you will need a small 5V relay, a P2N2222A transistor (but any similar NPN transistor will do the job), a 1N4001 diode, a 1K ohm resistor, a 220 ohm resistorone LED, and of course a breadboard and some jumper wires. To connect the Raspberry Pi to the breadboard, I also used the Adafruit cobbler kit, but any cobbler kit for the Raspberry Pi will work fine.

This is the list of the components that have been used in this tutorial:

- Raspberry Pi Model B
- Cobbler kit
- 5V relay
- 2N2222 transistor (or any equivalent NPN transistor)
1N4001 diode
- Red LED
- 1K ohm and 220 ohm resistors
- Breadboard and some jumper wires

On the software side, you will need a fully usable Raspberry Pi. And by usable I mean already configured with the Raspbian Linux distribution installed on it. There are many tutorials on the web that will guide you through the installation of Raspbian on your Pi, but I recommend this one:

http://www.raspberrypi.org/documentation/installation/installing-images/

You also have to check that your Raspberry Pi is connected to the Internet. Again, this will depend on your configuration (Ethernet or WiFi) and your router, but is usually really easy. If you are using the Ethernet connection, simply connect a cable to your router and it should work automatically. If you’re using a WiFi dongle, the easiest solution is to use the GUI that comes with Raspbian to find your wireless network and enter your WEP/WPA password.

The server part is based on Node.js, so you will need to install it on your Pi with:

wget http://node-arm.herokuapp.com/node_latest_armhf.deb
sudo dpkg -i node_latest_armhf.deb

Then, you will need to install the gpio-admin package. To do so, follow these steps in a terminal (if pi is your default username):

git clone git://github.com/quick2wire/quick2wire-gpio-admin.git
cd quick2wire-gpio-admin
make
sudo make install
sudo adduser pi gpio

After that, you’ll need to log out and in again.

Now, you need to download the GitHub repository of the project somewhere on your Pi:

git clone https://github.com/openhomeautomation/pi-node-relay

Finally, you need to go into the folder you just downloaded, and install the node.js module to interface directly with the GPIO pins of the Pi:

sudo npm install pi-gpio express

If it doesn’t work, just restart the Pi and try again the same operation. You are now ready to build the hardware!

Hardware Configuration

There is quite a lot of hardware to connect for this project, so pay attention to this paragraph. First, let’s speak about the relay itself. A relay is an electromagnetic switch. The one I used in this project basically has 2 parts. The first part, the coil, is the low-power part of the circuit, and will be controlled by the Raspberry Pi. The second part of the relay is the switch, which can sustain higher powers. This part is actually mechanical on the relay I used, so you should hear a “click” when the relay is switching to another state. Activating the low-power part by applying 5V on the coil will activate the switch and change the state of the relay. To monitor in which state the relay is, I used one LED on one part of the switch. Of course, the LED can be replaced by any device you want to switch on or off, for example a lamp.

But … there is still a problem. The relay is rated at 5V to switch, and the Raspberry Pi GPIO port can only deliver 3.3V. This is why we need a transistor in between to activate the relay. The transistor is basically a solid-state switch, which will be activated via the digital output of the Raspberry Pi board. When the transistor is on, the 5V pin of the Raspberry Pi board will directly power the relay, thus making the relay switch.

We still need to place one component I haven’t spoken about yet: the diode. The role of this diode will be to protect the low-power circuit when the relay is switching. In case any current is flowing through the input of the relay because of the switching of the high-power part, it will just flow through this diode instead of destroying the transistor or the output of the Raspberry Pi. Just place this diode in parallel of the input part of the relay, with the cathode connected to the positive 5V power supply.

This schematic describes the whole project:

Relay_schem_small

Connecting the Relay to The Network

Now it’s time to connect our project to the local network of your home. Again, make sure that the Raspberry Pi is connected to the local network, for example by pinging your own computer in a terminal. Also, check the IP of your Raspberry Pi, you will need it for later. You can do this by typing ifconfig in a terminal. This is the result for my Pi:

Screen Shot 2013-05-28 at 9.18.49 AM

You will use this address (192.168.0.47) to access the web page later on from your computer. What we have to do now is to build the Node.js script that will create our server on the Raspberry Pi. And from this server, we’ll be able to control the relay from your web browser. The following will simply be a walkthrough of the most important parts of the code. To actually make the project work, please refer to the files inside the GitHub repository of the project.

The most important commands are included into a JavaScript file called app.js. Let’s see the details of this file. It starts by including all the required libraries, to start the web server and to control the GPIO pins:

Then, we create the server itself on port 3700 with:

Now, we need to create the different routes for our server, which will be the URLs that the user can type or get access to from the outside. The first one concerns the interface to control our relay:

The second route will be to send commands to the GPIO pin on which the relay is connected to (pin number 7 using the pi-gpio mapping). This is done by creating a new router:

Inside this function, we first process the incoming request, and print it on the console for debugging purposes:

Then, we apply the command on the GPIO pin accordingly. For example, if the received state is “on”, we apply it to the GPIO pin where the relay is connected:

Finally, we send an answer to the browser, and close the connection:

And we end the script by actually starting the server:

Let’s quickly have a look at the interface itself. Inside the main HTML file, each button that controls the relay is defined by some HTML code. For example, this is the code for the “On” button:

The actual click on each of the buttons is handled by a JavaScript file. Every time a button is pressed, a request is sent to the Node.js server running on the Pi to change the state of the relay accordingly.

It’s now time to test the project. To do so, simply go over to the folder where you downloaded the files from the Github repository for this project and type in a terminal:

node app.js

You should see the following message in your terminal:

Listening on port 3700

You can now go to the web browser of your Pi, and type:

localhost:3700/interface

You should now see the following interface inside your web browser on your Pi:

Screen Shot 2014-07-01 at 12.56.48

Just click on one of the button, it should change the state of the relay accordingly. You can also check that the command was received inside the terminal. You can also do the same from your computer using the address of the Pi. For example, in my case:

192.168.0.47:3700/interface

Congratulations, you can now command your relay directly from your web browser!

Access The Interface From Anywhere

Now this is how to command a relay remotely, from your computer or your phone, from anywhere … in your home. Which is already nice, but I have been asked a lot about how to access this project from anywhere in the world. Wouldn’t it be cool to just access your home automation projects from wherever you are in the world, to check for example the status of your alarm system ? This is actually quite simple (depending on your router), and I will show you how.

Of course I can’t do a tutorial for every router in this world, but I will tell you how I did with mine (which is a router made by my Internet Service Provider). Generally you have to activate a mode named “remote access” on your router. Some routers will even give you an URL so you can access the router, but for mine I had to use the IP address. Be careful, I am not talking about the local IP address of your router (for example 192.168.0.254 for me), but the IP of the router on the web. It is generally easy to find in the interface of your router.

Then, you need to route the port corresponding to your Apache server on the Raspberry Pi (usually 80 if you didn’t change anything), so that every external access to this port goes directly to the Raspberry Pi. Usually, there is a “routing” menu in the interface of your router, where you can specify the external port (put 80), the internal port (3700) and the IP address (the one of the Raspberry Pi). Save the setting, and then it should just work out of the box if you type in the IP address of your router in any browser, wherever you are in the world !

One last word: be careful with this. Right now anyone can access this interface with the right IP address, and now it is just connected to a relay that is actually not connected to anything, but don’t do this if your whole alarm system is connected to the Raspberry Pi ! In this case, you better put a solid login/password system on your server so that only you can access it. I will show you how to do this in an upcoming article.

Update 01/07/14: Many of you had problems with the initial version of the project which was using a combination of HTML, Javascript and PHP. This was mainly due to file permissions inside the Apache web server on the Pi. That’s why I completely re-written the project using modern technologies like Node.js and Express. I also added a nice graphical interface to control the relay. Enjoy!

As usual, all the links in this article are affiliate links, so if you use them to order your parts it is a good way to support this website, and I thank you in advance ! All the files and schematics can be found in the Github repository for this project. And this is already the end of this article, I hope you enjoyed it, and if you did, don’t hesitate to comment and share!

How to Go Further

There are many things you can do to improve this project with what you just learnt. You can connect more relays to the project, and command them all from the same interface. You can also install several Raspberry Pi’s in your home to command them all separately. You might also use what you learned in this project to read data from the GPIO pins (for example from a light or motion sensor), and display this data on the web interface we created in the project. Finally, if you built an exciting project based on this tutorial, please share in the comments!

Receive the latest news about home automation
Over 1000 home automation enthusiasts already joined our list !

Do you want to receive the latest news about open-source hardware and home automation ? Then join our mailing list today by entering your name and email below. It is 100% free and you can unsubscribe at any time if you're not satisfied.

  • Allen

    Nicely done! I just ran across your site while looking for home automation (specifically irrigation) systems. I haven’t had a chance to fully read or practice what you’ve shown here, but I wanted to thank you for taking the time to put it together.. I’ve already picked up information on the GPIO I wasn’t sure about.

    • http://www.marcoschwartz.com Marco Schwartz

      Hi Allen, thanks a lot for your message ! Don’t hesitate to drop more comments or to send us a message directly if you have a specific question about home automation & open-source hardware.

      • das

        HI Marco ,
        I love the rasppi ( for my xbmc) and general small PC browsing .

        However, it seems quite tedious to get one output done when compared to an arduino or to use its extra computational power in controlled ways like say a YUN .
        Yet it seems to have enough horse power to do this ..

        Why is it not possible to have a linux program do all the setup with one apget and then a script that pretty much is like arduino language ? Ultimately, we want to read or write the outputs in standardised ways (99%) of the time when using it as a controller .

        Any thoughts ?

        • http://www.marcoschwartz.com Marco Schwartz

          Hello Das, that’s a good comment. I am actually working on something similar (like I did with Arduino in the aREST project https://github.com/marcoschwartz/aREST).

  • Mohammed S.B

    Hi Marco , you are amazing .I’m so happy that I found someone like me ;)
    I did all your steps and It work fine ,BUT last one when I tried to access “remote_relay.php” it didn’t show up “Server error” :’( but to the “index” is fine ..what may cause this problem !!

    I love you Marco P:

    • http://www.marcoschwartz.com Marco Schwartz

      Hi Mohammed, thanks for your message ! Are you sure that the Apache server is running correctly on the Raspberry Pi ? You can check that by trying some basic PHP code directly on the Pi (and be sure the files are in the right folder)

  • Lance

    Hi,

    Its awesome man thanks a lot. I can switch on and off from terminal or SSH remotely BUT, website does not switch it. Apache 2 is running fine, I can see the page and when I hit a button it submits link: http://192.168.2.87/remote_relay.php?total=on but nothing happens:-(

    Please let me know if you have any ideas, much appreciated.

    • http://www.marcoschwartz.com Marco Schwartz

      I had a deeper look on the issue, it might be that you don’t have the right permissions on the Pi. In the terminal on the Raspberry Pi, do this for all the files of the tutorial:

      chmod 777 name_of_the_file

      It should solve the problems.

      • Lance

        Hi Marco,

        Thanks SO much for your reply.
        Unfortunately it did not work…
        Here are the new file permissions so you know I did it right:
        -rwxrwxrwx 1 root root 177 Jun 30 11:46 index.html
        -rwxrwxrwx 1 root root 719 Jun 30 12:55 remote_relay.php
        -rwxrwxrwx 1 root root 604 Jun 30 12:56 script.js

        I restarted apache2 and then restarted the PI just to make sure.

        Any help very much apprciated!

        Regrads
        Lance Smit

        • http://www.marcoschwartz.com Marco Schwartz

          Hi Lance,

          I have the following :

          -rwxrwxrwx 1 root root 725 May 28 07:23 remote_relay.php
          -rw-r–r– 1 root root 177 May 22 09:10 index.html

          I propose to move the discussion into the forum, start a thread there and let’s dive deeper into the problem !

          • Reginald Jaynes

            I tried to access the web site on the raspberry pi as described above xxx.xxx.xxx.xxx/remote_relay.php,
            and my web browser only opens the file for editing. It never runs it. I changed all permitions, and this did not help.

            -Reggie

          • http://www.marcoschwartz.com Marco Schwartz

            Hi Reggie, are you sure that you are accessing the server on the right port ? I have the same error when I access my Pi using another port.

          • Reginald Jaynes

            Hi, thanks for the rapid reply.
            I am using chrome, web browser. The internet says default port is 80.
            I am able to access the default index.html and it runs its web page
            both on local ip address, and with router forwarding from exteral
            ip address. (it displays, ‘It works!’ This is the default web page for this server. …)

            I tried adding your HTML code from above to my index.html file, and
            now it does display the buttons, but they are not hot.

            It still will not run the php file, when I type xxx.xxx.xxx.xxx/remote_relay.php
            Are there setting on apache that change the port, or is it the browser
            that you believe may be configured incorrectly?

            thanks again
            -Reggie

          • Reginald Jaynes

            Hi,

            I fixed the problem. For some reason when I downloaded the php
            and js files, I somehow coppied the HTML contents of the git-hub
            web site in to both files. when I ran the php, it was displaying the
            get-hub.html website page.

            I copied and pasted the proper programs into the proper files,
            and now it seems to work perfectly,

            thanks,
            -Reggie

          • Valter P

            Hi Marco,

            great job!

            I have the same problem as Lance. I can see the page but when I hit a button, nothing happens.

  • Miha

    Hi Marco!

    I am making a remote garage door opener using your tutorial, I just need to buy the parts :) I was wondering what would the code look like if I want to switch the relay for just a second? Should I use the sleep() function in the exec part of the code?

    Something like this?


    exec("gpio -g mode 4 out");
    $state = $_GET["total"];

    if ($state == "on"){
    exec("gpio -g write 4 1")
    sleep(1);
    exec("gpio -g write 4 1")
    }

    I will make a mobile web page with one button that turns on a relay for a second (or maybe less, I have to find out how long it needs to be on, currently I just know that it doesn’t do nothing if it is switched on very quick) and then turns it off. With this, it opens/closes/stops the door depending on the current state.

    • http://www.marcoschwartz.com Marco Schwartz

      Hey, sounds like a great project! You’re right about the sleep() function, but it should be:

      exec(“gpio -g write 4 1″)
      sleep(1);
      exec(“gpio -g write 4 0″)

      As you need to put the relay to its previous state after the sleep(). Keep us updated about the project, for example by using our forum !

      • Miha

        Thanks for your reply Marco!

        I will post the full description of the project on your forum when I’ll finish it :)

        I have stumbled on the same problem as Lance above….the relay switches on and off from SSH, but from the website…it doesn’t… :/ all files are chmodded to 777 but still nothing happens…

        PHP works, phpinfo(); shows that it does.

        Any ideas?

      • http://surrounded.la Sean Ward

        can you please explain how to do exactly this, but using the new node based version. All I need is for a button press to turn on the gpio pin then wait(sleep) 5 seconds and then turn it back off.

        I am using it to access a gate to a parking garage and just need this to simulate a physical button press of the remote which is connected to the relay and activated when the relay is switched on. Only need it to stay on for 5 seconds then return to idle(off) state.

        attempted to insert the “sleep(5)” line into the app.js script, but was unsuccesful.

        any help would be greatly appreciated.

        • http://www.marcoschwartz.com Marco Schwartz

          Hello Sean, delays in JavaScript can be a bit confusing at the first glance. I would use a ‘setTimeOut’ function. Have a look here: http://www.w3schools.com/js/js_timing.asp

  • Pingback: DIY Stripboard/Veroboard Enclosure for Raspberry Pi (Part 2)

  • Lars

    Hi Marco,

    Thank you for a great guide!

    I have adopted your work and expanded the setup to 4 relays :-) and it is working. I only have one small bug, that is haunting me.

    When the Pi is rebooting, my three extra relays are switching to high state(on). As soon as I click any button the web, all three changes to low state (off). But the first relay stays on low (off) during reboot. And that of course is the relay on gpio 4.

    I have read your guide over and over again, but I can’t figure out what I have missed. Do you have any ideas ?

  • Lars

    Hi Marco,

    Thank you very much for a great guide!

    I have copied all your tricks, and managed to expand this setup to 4 relays.
    Using 2 relay boards ( http://dx.com/p/arduino-2-channel-relay-shield-module-red-144140 )
    I got the webpage and jscript to click all the relays.

    Only one little thing is haunting me now. I have read your guide over and over, but I can´t figure out where I went wrong. My issue is that when rebooting the Pi, all my 3 extra relays is changing to high state (on), the first relay (ours if you wish) is staying low. And as soon as I click any button on the web (say switching relay 1 to high – on) the three other relays is changing to low (off) and keep this state until I click the button on the web for that particular relay.

    Do you have any clue what I have missed ?

  • Pingback: เปิดปิดรีเลย์จากที่ไหนก็ได้ในโลกโดยผ่านเว็บ | Raspberry Pi Thailand

  • Lars

    Hi Marco,

    No need to put this post on your web, just a little information.

    I think I have discovered why my relays are in the high state when rebooting, acordin to this link:
    http://www.raspberrypi.org/phpBB3/viewtopic.php?f=44&t=35321

    There is chenges in the state of the pins of the Pi, from the dirrent revision, and “of course” I had decided to use some of the pins, with the high state after reboot.

    Also, a little input to your great guide, maybe add PPTP (easy, but not that secure) ot OpenVPN to the PI, so that using this remote control from the web, can be done using a VPN tunnel instead of having a website wiith full access to the entire world.

    Best reagrds

    Lars

    • http://www.marcoschwartz.com Marco Schwartz

      Hi Lars,

      Thanks for that information ! I am sure it can benefit other readers of this post.

      I also thought about a part on how to access the Pi via a VPN connection, I will definitely add that in the next revision of the article !

  • zaktt

    Hi, i was wondering how i would add more then just one on and off buttons to work as i am trying to control up to 5 different lights for my home automation project

    • http://www.marcoschwartz.com Marco Schwartz

      Hi zaktt, if you have multiple relays to command you can just add more buttons to the interface, and make sure that clicking on a given button triggers the right gpio command. For example, you can add another PHP variable $relay to store which relay has to be activated.

  • Johnathan Lau

    Thanks for the detailed write up ! This helped me improve my door lock system! ;)

  • Darren

    Hi, great tutorial got it working as you described. Just 2 questions, I don’t quite understand how to add another button and would it be possible to control my rf sockets.

    I use “sudo python ./src/strogonanoff_sender.py –channel 1 –button 3 –gpio 8 on” working from terminal. But cant get it to work on this. Thanks for the tutorial

    • Darren

      Done it, more luck than judgement I think. Will post my results on here later for future reference.

  • nick

    Hi marco

    could you send me a the code to add more relays on as i can add buttons but they all work on the same relay cant work out what else to change

    thanks

    • http://www.marcoschwartz.com Marco Schwartz

      Hey Nick,

      Please open a topic on the forum, it will be a great place to discuss that !

  • http://domgarofalo.com Dom

    Lars, Were you able to get this work with your garage? I am considering the same thing.

  • dom

    Marcos, how would I read the status of a magnetic switch hooked up to the pi used to tell if the door is open or closed using PHP? Thanks!

  • Daniel Fay

    I was wondering how you chose the Transistor. I need to turn on a 12v circuit. Do you know if i’d need a different transistor?

    • http://www.marcoschwartz.com Marco Schwartz

      You probably don’t have to use another transistor. I use the 2N2222 transistor a lot, and it supports 12V in this case without problems. The characteristics to look at are really the maximum collector current and power that the transistor can support (in this case 800 mA and 500 mW, so you’re probably safe).

  • mas

    hye marco i wanna ask something. what i should do if i want my dc motor start when i press start button in my android apps that i build myself. i dunno how to make them communicate. but i use jabber/xmpp as im server.pls help meee

    • http://www.marcoschwartz.com Marco Schwartz

      I don’t have much experience with Android, so please use the forum for that question!

  • Arnie

    Great article. When do you expect to have a version with login/pw protection?
    Also, I am wondering how hard it would be to code a watchdog timer into the ON button so that it will automatically turn off after a preset period (e.g. 2 minutes). Off course the OFF button would still turn things off any time.
    I am a newbie to RPi and programming.
    Thanks….Arnie W8DU

    • http://www.marcoschwartz.com Marco Schwartz

      Hey Arnie,

      I am currently developing a better graphical interface for doing home automation on the Pi, so that will include login/pw protection as well. Also, a timer won’t be that difficult to implement using the time functions of PHP (http://php.net/manual/en/function.time.php).

  • Josh

    Great tutorial! I’m trying to do something similar to this but I want to turn a garage heater on remotely. It’s a 31.3 amp electric heater and I’m not really sure what would need to change to make that work. Any recommendations for component changes to make that work?

    • http://www.marcoschwartz.com Marco Schwartz

      Hey Josh, the main idea is the same but you have to be careful about these 31.3 amps. Basically the main change you have to do is carefully choosing the relay so it can handle such high current & power. Also make sure that you have big enough cables to connect the relay to your heater (the breadboard would just burn instantly!)

  • Gianfranco

    hello I have a question: in your scheme (I mean the connections on the design of the breadboard and the Raspberry) did you miss a link that goes from 5V of RPi to the negative diode (and the coil of the relay)? or I’m wrong?

    Anyway, good job and thank you!

    • http://www.marcoschwartz.com Marco Schwartz

      Hello, you’re totally right. It was correct in the schematic but not in the picture, so I just left the schematic for now as it is more clear anyway. Thanks for noticing !

      • Gianfranco

        Don’t worry, we work for same objective!

  • rudy fuller

    Hi I had similar problems with php script not starting….(voltage in gpio 4 stays round 2.2 volts and does not go to 0 when scriot initiates)

    Run below commands again and check…

    sudo /etc/init.d/apache2 stop
    sudo apt-get remove –purge apache2 php5
    sudo apt-get remove –purge libapache2-mod-php5
    sudo apt-get install php5 apache2 libapache2-mod-php5
    sudo /etc/init.d/apache2 start
    sudo a2enmod php5
    sudo /etc/init.d/apache2 force-reload

  • alcachi

    Hi Marco,
    Great article, I will try to replicate it in my new RPi. What do you think about using node.js instead of Apache?

    • http://www.marcoschwartz.com Marco Schwartz

      Hi Alcachi,

      I haven’t use that yet, but I guess it would work without problems !

  • Henrique

    Ausgezeichnet =D a really beautiful project!!
    However, it could become even nicier if controlled by an Android apk… I plan to do it (I hope I can) as part of my final graduation work, do you have any suggestions where to dig?

    • http://www.marcoschwartz.com Marco Schwartz

      Hello Henrique,

      I don’t know much about Android apps, but there are lots of tutorials out there to interface the Raspberry Pi with Android so I am sure you will find something for your project!

  • tarun

    hi Schwartz,
    Iam trying to connect an RFID reader to a raspberry pi and the gpio pins to the door latch to build a door lock system,
    can i use the same circuit and code? the door latch rating is 12V,so is the circuit designed above capable of turning on 12V door latch ?can i use the same 5V relay or any higher rated relay ?also the resistors and transistor??please reply soon.
    anyways ur work has helped me a lot..thanks…

    • http://www.marcoschwartz.com Marco Schwartz

      Hello Tarun,

      Yes basically it will be the same principle. The relay I used in that tutorial can drive up to 30V in DC, so you should be fine with that one.

      • tarun

        but will the value of resistor and transistor be same to drive a 12 v door latch??

  • Darren

    Is there a way to show the state of a gpio pin on the webpage alongside the on/off buttons?

    • http://www.marcoschwartz.com Marco Schwartz

      Hello Darren, definitely that should be easy to do, you could for example use an XML file to represent the state of the GPIO pins you are interested in & display it on the webpage.

  • darren

    Sorry if I sound like a noob (which I am) but would you mind giving me a little more info or maybe even an example. I dont get any problems with electronics but get stuck on code…

    Thanks for your time and a great tutorial.

  • Carlos
    • http://www.marcoschwartz.com Marco Schwartz

      Hello Carlos,

      I am not sure I totally get what you want to achieve, but there would be no problem connecting 12V directly to the relay I used in the project (most relays like this supports up to 50 V DC). Please send me an email if you need additional help !

  • Solarflor

    Ciao Marco,
    molto molto interessante (very interesting)

    To be honest I have a different need. I would like to drive a relay via web using my rasp but the relay and the rasp are in two different area. I mean I would like to use the rasp I have in a room to drive the relay that is in another room.
    Ciao

    • http://www.marcoschwartz.com Marco Schwartz

      Thanks ! What you mentioned is definitely possible by either using a long cable (bad solution) or connect the relay to an Arduino board and interact with the Pi wirelessly (for example, check my tutorials with the CC3000 chip)

  • Christo

    Hi Marco, I don’t know if I misread it but can you please post the link to your other article about setting up a solid login/password system on your server. I will appreciate it thanks.

    • http://www.marcoschwartz.com Marco Schwartz

      Hello Christo,

      It’s in my plans to modify the article to integrate such a secure login. Please stay tuned.

  • Sal

    Hi,
    It is very useful tutorial and i’ll be using it for my project. I want to control a SainSmart 16-Channel 12V Relay Module. Do you think it is possible to control all 16? I was thinking to buy Gertboard but not sure if it could control all 16.
    http://www.sainsmart.com/16-channel-12v-relay-module-for-pic-arm-avr-dsp-arduino-msp430-ttl-logic.html

    • http://www.marcoschwartz.com Marco Schwartz

      Hello Sal,

      There is no problem, the tutorial will definitely work using the relay module you mentioned as it uses digital communications to interface with all the relays connected on the module.

  • ANIKET

    hi i am making the project home automation using raspberry pi for that i want the web page code in html format so can you send the code

    • http://www.marcoschwartz.com Marco Schwartz

      Hello Aniket,

      The code is available on the GitHub repository (https://github.com/openhomeautomation/)

      • http://domgarofalo.com Dom Garofalo

        Marco,

        I want to add an rfid module to my Raspberry Pi so that when I am a few feet from the garage door it will open the door. Is there an rfid module that you could recommend?

        Thanks!

  • http://anoopk.name Anoop K

    Nice article! Thank you very much.

  • Uv

    Hi Marco, wonderful project. I am getting everything right, my relay is also switching through the rpi terminal. But when I create the php and js files and i access it through my computer I get the on off buttons, but when i click on them nothing happens. Could you pls help me with what might be the problem. Thanks :)

    • http://www.marcoschwartz.com Marco Schwartz

      That seems like a file permissions issues. Make sure to chmod 777 all the files on the RPI, and make sure the permissions are set to the user of the Apache server (like www).

  • Pingback: Remotely Control a relay from anywhere using Internet by the Raspberry Pi | Microcontroller Lab

  • https://www.facebook.com/adam.sjostrand.5 Adam S

    Hey, thanks this was very helpfull. But I have a question, how should I do if I would like to add buttons for multible relays? Example a 8 channel relayboard.

    • http://www.marcoschwartz.com Marco Schwartz

      That would be no problem, the project can be extended to any number of relays.

      • Andrew L

        You want to be wary of the maximum load the 5v output of the pi can drive. Each relay you attach will require some of the total capacity of the 5v output. Overload it with too many relays, or attempt to turn on to many at the same time, and you’ll damage the pi.

        • http://www.marcoschwartz.com Marco Schwartz

          Hello Andrew, very good comment indeed. Note that it is also possible to power the relays with an external 5V source to avoid this problem.

  • Ravi

    Thanks for your excellent tutorial. I have made the circuit and the relay is working perfect when checked directly but I am not able to get it working on the net. When I check /var/www ls, it lists only the index file. I tried wget command to download the .php and .js files from github, while being in /var/www, but I get an error 404. Kindly tell me how to resolve this. Thanks

    • http://www.marcoschwartz.com Marco Schwartz

      Hello Ravi, I invite you to test the new version of the tutorial that now uses Node.JS

  • Meo

    It was a nice tutorial. I just came across raspberry pi and honestly I still don’t know anything about it yet. With regards with your internet setup wherein you mention that you can control the devices anywhere… I just wanna ask if you consider about the IP address of the router being dynamic or static, Because if it is static, its not a problem but if it is dynamic, the IP address of your router will change… have you consider this scenario?

    Thanks for the information.

    • http://www.marcoschwartz.com Marco Schwartz

      Good point, I indeed consider the IP address to be static. I haven’t consider the dynamic IP case yet, but I might add that in a future revision of the article.

  • Jo Stuzzi

    Hi Marco,

    Excellent solution. Unfortunately I am a novice within linux OS. I recieve the following error when I enter the command git clone https://github.com/openhomeautomation/pi-node-relay

    git: ‘clone https://github.com/openhomeautomation/pi-node-relay’ is not a git command. See ‘git –help’.

    Are you able to assist ? Thanks

  • Raj Badri

    i am following all your instructions but when i try to run “npm install pi-gpio” in the directory pi-node-relay. the command exits with a error log : npm ERR! Error : failed to fetch from registry: pi-gpio

    please help

    thanks
    Raj

    • http://www.marcoschwartz.com Marco Schwartz

      Hello Raj,

      Make sure that your Internet connection is working on the Raspberry Pi, that might be the source of your error. The command is correct, see: https://www.npmjs.org/package/pi-gpio

  • Rameez Afzal-Ahmed

    Hi There Marco,

    I have been following this tutorial and the previous version of it. I was wondering if you still have the previous tutorial as I had started that already. Could you provide me a link to the previous tutorial and the resources for this also.

    Thanks

  • Ron

    Hi Marco, great project!

    I am running the latest Raspbian (Wheezy) and have followed your
    installation instructions with a microscope.

    I am receiving the following error when starting the nodejs server.js :

    pi@raspberrypi ~/pi-node-relay $ nodejs server.js
    Server has started.

    events.js:48
    throw arguments[1]; // Unhandled ‘error’ event
    ^
    Error: listen EACCES
    at errnoException (net.js:670:11)
    at Array.0 (net.js:756:28)
    at EventEmitter._tickCallback (node.js:190:39)

    Any ideas? Thanks!

    Ron

    • http://www.marcoschwartz.com Marco Schwartz

      Hello Ron, thanks for trying the tutorial. That’s probably coming from an older version of nodejs. Follow the new instructions I put in the tutorial, it should install the latest versions of Node & NPM.

      • Ron

        Great! Got it to work with the new set of instructions, thanks again for sharing!

        • Ron

          Hi Marco, I defined an additional variable i.e.: var queryData2, inserted new id’s in interface.js with no success. What additional changes are required to control 2 or more GPIO pins in app.js? Thanks, Ron

          • http://www.marcoschwartz.com Marco Schwartz

            Hi Ron, to do so you would need to add another button(s) in the interface.html file, and then add more code in the interface.js file to link the buttons with a change on the GPIO pins.

          • Ron

            Hi Marco, added ‘state2′ data variables inside interface.js and app.js
            with success! Regards, Ron

  • Johne416

    Amazing YouTube movies posted at this website, I am going to subscribe for daily updates, as I dont want to fail to take this series. deebccafcade

  • Johnc665

    I think you have noted some very interesting points , appreciate it for the post. cegcdfeedeek

  • ivan

    when i want to install Gpio express(sudo pm install pi-gpio express).
    and it gives me this error:
    sudo: pm: command not found.
    I don’t now what to do i have searched the internet and found nothing.
    Any help?

    • http://www.marcoschwartz.com Marco Schwartz

      Hello Ivan, good point, that was a mistake in the article, now it is fixed. Thanks for noticing!

      • ivan

        sorry for bothering you again im new to raspberry pi.
        i start the web server with node app.js in the folder pi node realy, it sais listening to port 3700 and i go to the ip addr and sais: connot GET /

        • ivan

          any help??

        • http://www.marcoschwartz.com Marco Schwartz

          Hello Ivan, make sure to add /interface after the IP address and port, or it would make the error you mentioned.

      • Mike

        Hi Marco – thanks for all this. I have a similar problem to Ivan above.

        When I enter sudo npm install pi-gpio express as suggested I get the reply “sudo: npm: command not found”

        I’m a real novice and so I’m not sure what is going wrong. I’ve spent a lot of time attempting to find a solution on the web, but with no luck. Any ideas you can provide would me much appreciated.

        Thanks
        Mike

        • http://www.marcoschwartz.com Marco Schwartz

          Hello Mike, you have to be sure to install node & npm using the commands I indicate in the article, and not using the usual apt-get. Hope that helps!

  • DK

    Hi Marco, thank you for the tutorial, everything works fine. I’m new to raspberry pi and programming itself. So, I have two questions:

    1) Is it possible to run this project automatically at Raspbian startup?

    2) For my goal I need one button which sending “on” while pressed and “off” – while not pressed. How to change the code to do it?

    Many thanks!

  • Jo Stuzzi

    Hi Marco,

    I have managed to get the web interface working. I’m not electronically competent but have managed to wire up the Raspberry pi to a 16 Relay board. When I click either on or off it switches the relay on and cant switch it off. Could this be due the way I have wired the GPIO to the relay board ? Again excuse the ignorance thanks.

    Thanks

    • Jo Stuzzi

      Please ignore I figured it out :D

      Quick question though, others have asked whether it is possible to control more than one relay which is possible. Can you please an example/syntax of the files that need to be modified as I am finding it difficult to find how to pass the relevant pin, mapped to GPIO within the interfaces.html and related files. Keep up the fantastic work !!!!

      • Jo Stuzzi

        Sorry ignore previous one I worked it out in /js/interface.js” thanks

      • Ron

        Hi Jo, i’d like to control 2 or more GPIO pins.
        I defined an additional variable i.e.: var queryData2, inserted new id’s in js/interface.js and added new buttons inside interface.html with no success.

        What additional changes are required to control 2 or more GPIO pins in app.js? Thanks!

  • Jo Stuzzi

    Hi Marco,

    I finally was able to modify your code and connect a 6 relay board which I have integrated in my home automation system. I use the system to control speaker zones in my house where I have wired 1 relay per channel (left and right).

    I have noticed that it’s a bit hit and miss when I call two relays to switch on or off simultaneously, where one will switch on and not the other …. I suspect this is a timing issue. Do you able to provide syntax for the app.js file to insert a delay of 1 sec between relay calls… what would be great is to include syntax that checks if the relay is in status OPEN or CLOSED status after the call is made.

    Thanks Jo