Control a Relay From Anywhere Using the Raspberry Pi

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 small app based on Node.js to control the relay from any 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:

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:


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

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


Connecting the Relay to The Cloud

Now it’s time to connect our project to the cloud. Again, make sure that the Raspberry Pi is connected to your local network & to the web, for example by trying to ping a web page from a terminal.

What we have to do now is to build the Node.js script that will connect the Raspberry Pi to the aREST.io cloud platform, which is a tool that I created specifically to control boards like the Raspberry Pi remotely. And from this cloud server, we’ll be able to control the relay from your web browser. Here is the complete code for this part:

// Modules
var express = require('express');
var app = express();
var piREST = require('pi-arest')(app);

// Set unique ID

// Connect to cloud.aREST.io

// Start server
var server = app.listen(3000, function() {
    console.log('Listening on port %d', server.address().port);

Let’s now see the details of this file. It starts by including all the required libraries:

var express = require('express');
var app = express();
var piREST = require('pi-arest')(app);

Then, we’ll set a unique ID and a name to your board. Make sure to change at least the ID here, so you are sure that only you can access the device:


After that, we connect the Raspberry Pi to the cloud server with:


Finally, we start the server on the Pi:

var server = app.listen(3000, function() {
    console.log('Listening on port %d', server.address().port);

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:

sudo npm install pi-arest express

After that, type:

sudo node app.js

You should see the following message in your terminal:

Listening on port 3000
Connected to aREST.io

You can now go to any web browser, and type:


You should immediately hear the relay turning on. You can of course do the same with a 0 at the end to turn the relay off again. Congratulations, you can now command your relay directly from any web browser!

Access The Interface From Anywhere

You can now control the relay from anywhere, but only by typing commands in your web browser. That’s nice, but it would be much better if you could do the same from a web-based dashboard, right. Well, that’s what I did inside the aREST framework, and I created a way to easily create a dashboard for devices connected to aREST.io.

The first step is to visit the aREST dashboard website:


Create an account there, and then create a new dashboard, for example called Raspberry Pi:

Screen Shot 2015-12-09 at 08.22.58

After that, open this dashboard, and you will be able to create a new element:

Screen Shot 2015-12-09 at 08.23.06

Here, give a name to your dashboard element, and enter the ID you assigned to the device in the ‘device ID’ input. Also set the element type to ‘Digital’, on pin 7, and with an On/Off switch. This should be the result:

Screen Shot 2015-12-09 at 08.24.16


As you can see, the application automatically detected that your Raspberry Pi was online. You can now try the buttons: it should automatically turn the relay on or off. This dashboard is of course accessible from anywhere on the planet, so you can now control your relay from anywhere using this nice graphical interface!

Update 9/12/15: Many of you had problems with the initial versions of the project which were using a combination of custom HTML & JavaScript code. That’s why I completely re-written the project using my own aREST framework, which made the project much easier to build. You can now build your own graphical interface without any code, and control your Raspberry Pi from anywhere. Enjoy!

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!

Enjoyed what you read in this article? You can find much more information about how to use the Raspberry Pi for home automation in our Home Automation with the Raspberry Pi book.

Like What You've Read?
If yes, join over 2,000 people who receive exclusive information about open-source home automation & the IoT. You will also receive my free eBook "Build a Simple Thermostat with the Raspberry Pi". Simply click on the button below!
Get Started!
  • 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.

    • 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 ?

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

    • 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


    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: but nothing happens:-(

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

    • 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!

        Lance Smit

        • 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.


          • 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

          • Reginald Jaynes


            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,


          • 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")
    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.

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

      exec(“gpio -g write 4 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?

      • 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.

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

    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


    • 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

    • 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


    • Hey Nick,

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

  • 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?

    • 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

    • 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

    • 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?

  • 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!

    • 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?

    • 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?

    • 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…

    • 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?

    • 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
    • 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.

    • 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.

    • Hello Christo,

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

  • Sal

    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.

    • 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.


    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

  • 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 🙂

    • 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()

  • 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.

    • 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.

        • 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

    • 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.

    • 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


  • 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.


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

    [email protected] ~/pi-node-relay $ nodejs server.js
    Server has started.

    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!


    • 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

          • 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?

    • 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??

        • 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.


        • 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.


    • Jo Stuzzi

      Please ignore I figured it out 😀

      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

  • Gadget .

    Hi Marco.

    Excellent article and setup. Worked first time when setup in the standard formation. I have a question regarding “Adding More Buttons” to control more of the “PI’s” outputs, and I have already modified the “interface.html” file to have the following in it: id=”01″, id=”02″, id=”03″, id=”04″ etc. Which looks great on the pc as well as the phone. PI Remote

    And also modified the “interface.js” file to include the lines: clicked_id == “01”, clicked_id == “02”, clicked_id == “03”, clicked_id == “04” etc.

    These can’t surely be the only two files linked to the GPIO’s outputs. I mean I can see there is a “State On Received” and “State Off Received” with the PI plugged into a monitor, but how do I know that id=”03″, id=”04″, id=”05″ etc is switching on/off the correct GPIO output if the only two files being edited are interface files which don’t have a reference to the GPIO pins? Does the “jquery-2.0.3.min.js” file (or to wherever it processes to) have to be modified for this layout to work properly?

    Could you maybe give some light to my dilemma or propose something that would get all 8 outputs working?

    Most appreciated.

    • Hello, to add more buttons you don’t need to modify the jquery file, this is Javascript library that should not be modified. For now the tutorial is not adapted to add more than two buttons as it quickly becomes impractical, but I will soon modify it so you can use an arbitrary number of buttons.

      • Joe Majoros

        Have you modified the code yet? I’m really struggling with :(… Thanks

        • Hi Joe, what is your struggle exactly? I tested the code again and it works fine here.

          • Joe Majoros

            Hi Marco, thanks for getting back to me :)… I’m trying to add 5 relays to your code… so i want 5 separate gpio’s add to your relay switch. Which files do i need to modify and how? I’m ok with basic html php stuff but rubbish with java 🙁 Thanks in advance!

          • Sure! To integrate 5 relays you will need to modify the HTML interface itself (add more buttons) and then the interface.js file that contains all the detail about how the clicks on the buttons are handled.

  • Ajay Gupta

    Hello Marco,

    I have been searching the net on Home Automation but found your article most detailed and interesting on Pi projects, Thanks for doing such a wonderful job.

    I have a Pi B+ and EIGHT
    or 3.3V SIGNAL) for RASPBERRY PI ARDUINO AVR PIC 8051 board

    I need your guidance to connect and configure the eight relay board to operate all 8 relays independently.
    Can you please help with your knowledge and guidance.


    • Hello Ajay, for your project I really recommend checking the datasheet of this ULN2803, as this board is outside the scope of the article (here we are controlling the relay directly)

      • Ajay Gupta

        Thanks a ton for the response,

      • Ajay Gupta

        Hello Marco,
        Thanks a ton for the response, I have already worked on the datasheet of ULN2803,
        “The ULN2801A-ULN2805Aeach contains eight Darlington
        transistors with common emitters and integral suppression diodes for inductive
        loads. Each Darlington features a peak load current rating of 600mA (500mA
        continuous) and can withstand at least 50V in the off state. Outputs may be
        paralleled for higher current capability.”.

        Can you help me identify the 8 GPIO pins in B+ model, to connect the same with the relay board.



        • Hello Ajay, for that I recommend checking out the B+ GPIO header documentation, you will find tons of them on the web.

  • John Cotton

    Marco, Is there a specific folder that the pi-node-relay folder needs to be in? The listening on port 3700 works but I can not see anything in a browser. Regards, John

  • Parth Bhat

    My friend we can even use the arduino for the same
    Instead we could push raspberry pi to an extent were arduino don’t go and can utilise the raspberry pi.
    Likly I’ve made a whole Home automation project controlling 9 switches and even TV and Setopbox with just arduino

    Why can’t we use raspberry pi for more powerful things like voice control like Jarvis but more interactive….
    Think on itt

    But it was a great tutorial no doubt

    Parth Y. Temkar

  • Kris Page

    When I disconnect my SSH connection, node app.js stops running. Is there a way to run an script at bootup that executes the node app.js command in the pi-node-relay folder? I’ve tried adding it to the rc.local file but it wont run properly without being in the pi-node-relay folder first.

    Thanks you for the effort in this great write-up!


    • Kris Page

      Ended up using a linux function called “screen” that works great.
      sudo apt-get install screen

      Once inside pi-node-relay folder, command is:
      screen node app.js

      At this point you can exit out of SSH and server will continue to listen for input.

      I am new to the Pi, Sorry if this is common knowledge.

    • Hi Kris, thanks for the comment! Sure, there are several ways to do that. One is to use the forever package for Node.js:


      • Kris Page

        Hi Marco! I dusted off the old Pi that had this node.js code on it for a new (small) project. In addition to powering a relay, I’d like to be able to play music simultaneously. Can code be written into node.js that will start omxplayer at the same time that a relay is powered? Thanks again for any insight you can provide!

        • Hello Kris, I guess that’s doable 🙂 Check out this to launch system commands from Node.js:


          • Kris Page

            You’re quick Marco! I discovered “child process” prior to your suggestion and got most of it to work.

            var spawn=require(‘child_process’).spawn, child=null;

            In my setup it runs fine as a result of button “2” being pressed:

            if (queryData.state == ‘2’) {
            gpio.open(7, “output”, function(err) {
            gpio.write(7, 0, function() {
            child=spawn(‘omxplayer’, [‘Bills.mp2’], function(){console.log(‘end’);}, {timeout:6000});

            However, if I put a “quit omxplayer” command in button “1” to turn it off, it ends the entire node.js session:

            if (queryData.state == ‘1’) {
            gpio.open(7, “output”, function(err) {
            gpio.write(7, 1, function() {
            omx.quit() ;

            Any ideas of what I’m missing to keep the session running so that I can toggle back and forth between button “1” and button “2” continuously?


  • Uroš Vrtar

    Hi, I would like for my relay to switch off after few seconds after the button ON is pressed. Is it possible to implement some kind of timer in JS for that?

    Thanks for the reply


    • Geert Van Moer

      Can anyone help me with this problem on and off the same error

      [email protected] ~/quick2wire-gpio-admin/pi-node-relay $ node app.js

      Listening on port 3700

      express deprecated res.sendfile: Use res.sendFile instead app.js:18:12

      State on received.

      Error when trying to open pin 7

      gpio-admin: failed to change group ownership of /sys/devices/virtual/gpio/gpio4/direction: No such file or directory

      I have tried most things I could find in goole and forums and after installing and reinstalling no succes.

      Raspberry model PI 2

      • Hey Geert! It seems you don’t have the rights correctly set for the GPIO library. Try again the command:

        sudo adduser pi gpio

  • Pingback: Fix Node.js Error Listen Eacces Windows XP, Vista, 7, 8 [Solved]()

  • Pingback: Fix Nodejs Error Listen Eacces Windows XP, Vista, 7, 8 [Solved]()

  • Shua Senior

    can you post a top down photo of your breadboard?

  • lin

    Hi, Macro. Thanks for your tutorial! everything works fine. however, for the last step – ngrok, when I turn it on and type the URL given in my mobile device, it says ‘404 NOT FOUND’. Do you have any idea what I’m doing wrong?

    • Thanks! Is the Ngrok service running correctly on your Pi? Make sure it is and take the address from there. Also make sure you are redirecting towards the right port.

    • Clint

      hey lin, did you ever figure this out? Mine is doing the same thing

  • Dave Ja Vu

    Superb tutorial from start to finish – really good to follow. Have got it set up and working perfectly, but of course now have a cheeky request!

    I am very new to node / js so, be gentle 😉 I would like to alter the code so a keydown / keyup event will trigger the relay, so relay is only on when key is held down and turns off when key is released.

    Been trying for a while to work this out and but am completely stumped tbh so any tips / pointers greatly appreciated.

    Many thanks.

  • Clint

    Marco, is there any reason this should be really laggy? Sometimes it’s very responsive, and sometimes it takes a long time or doesn’t trigger at all.

    Also, I keep trying ngrok and getting a 404. I’m on port 3700 and I know the requests are getting in because they show up in the ngrok window. Just to be clear, I have to have the app.js and ngrok running in two separate terminals right?

    • jusbaker

      I’m having the same problem. Please reply.

      • Clint

        Which problem? The lagginess or the 404 error? I haven’t been able to solve either yet.

        • jusbaker

          the 404 error, I just ended up writing new code and coming up with a different way to do most of this stuff. I’m still working out the kinks, but once I get it done I can upload it somewhere. Could be a couple days/weeks though.

          • Clint

            I added my fix above, no need to write new code.

    • Hi Clint, no it should not … maybe an issue from your WiFi adapter? Try using Ethernet as well.

      For Ngrok, sure you’re right they need to run in two different terminals. Ngrok should run even you don’t have any web server running on your Pi. I would try with a simpler example (just a basic Node.js server) and see if that works 🙂

      • Clint

        Yeah, who knows with this Comcast connection I have either, It fluctuates bandwith all the time. I’ll see what I can do for the Node.js server. It has to be something simple, ngrok doesn’t have much to it. It almost seems like port 3700 doesn’t have anything on it, although when I run the code it definitely says “listening on port 3700”. I might try to modify the node.js code to just try another port and hit that with ngrok.

  • Kiran Gore

    Sir I complied every thing, you told and also updated web interface for all input output and working grate with local network except NGROK getting error “404 not found” error image attached here

    Please Help
    if any one want source code for new web page I will upload for you

    Thank you

    • Clint

      I’m having the exact same issue. Seems to be happening to a few of us in the last couple weeks.

      • Jessie

        Now I am having the same problem. I have try out both URL given in the terminal, but it display 404 not found.

        • Clint

          Got it! So when you run the app.js it doesn’t run on standard port 3700, it runs on 3700/interface. SO, when you type in the link that ngrok provides, put “/interface” onto the end of the link.

  • Jessie

    Hi Marco, I have follow the steps you show us as above until I have faced a problem where the terminal didn’t shows “Listening on port 3700” after I key-in “node app.js” in terminal. The below picture shows the result in the terminal.

    Another question I would like to ask is about the code: “On”, is this coding has to be key-in in app.js file?

    Lastly, is that “Node.js” file is equivalent to “app.js” file? Because I can’t find any file name “Node.js” file in my downloaded pi-node-relay folder.

    I am apologize for my weak English and I am a new user to pi and networking. Sorry, if I have ask any basic knowledge or silly question here.
    Hope sir or anyone can help me. Thank you.

    • Clint

      You’re not in the “pi-node-relay” folder to run the application

      try “cd pi-node-relay” before you type in “node app.js”

      I could be wrong but I think it may be that simple.

      • Guest

        😀 Thank you Clink, now my localhost part is success. I able to control my relay via localhost. Now I can go one step further by proceed it to Access The Interface From Anywhere. After I have download the linux/Arm files from https://ngrok.com, I moves the files in a new created folder name “Ngrok” and put it in pi, then I access it by clicking right of the Ngrok folder and open in terminal. But, when I keyin “./ngrok3700”, it didn’t works. Does Anyone has ideas can suggest to me?

        Thank you for the effort to help me out 🙂

        • Clint

          Put a space between “./ngrok” and “3700” written like “./ngrok 3700”

      • Jessie

        Thank you Clint, this method really works. My localhost is working fine. Now I am facing the same problem with you, the URL didn’t works, it shows 404 not found. If you had figure out any solution, can you post it here? Thank you very much…

    • Hello Jessie, it seems you are just not in the right folder 🙂 Make sure to download all the code from the GitHub repository and then run node app.js in the folder where the app.js file is located and it should work.

      • Guest

        Thank you sir for your suggestion, now my localhost works fine. When I access via internet by using Ngrok, it display 404 not found. How can I solve this problem? Please suggest any ideas…

        • Kiran Gore

          Most of us facing same issue wait for some time to fix it

      • Jessie

        Hi Marco, this is the result after running Ngrok in terminal. Any idea to solve this problem? Thank you…

        • Kiran Gore

          Jessie create file of named “favicon.ico” in views folder to remove this error

        • Clint

          You need to add “/interface” to the end of the link.

          Try “http://6elc8f5.ngrok.com/interface”

      • Jessie

        Hi Marco, thank you for your replied. My localhost worked fine and now I faced another problem when I runs Ngrok. It shows 404 not found when I copy the given URL and paste it on my web browser, it didn’t work. Now I am using Ethernet cable connection, so I don’t think is line lagging problem causes the page not found. Any idea to solve this problem? Thank you.

  • Darshan Bagul

    Hello, can the same project be done using Django and python instead of Node.js?? If yes, what all tools will I need for the same?

    • I don’t personally know Django, but it should be possible as well 🙂

      • Darshan Bagul

        Thanks a lot Marco, for your reply! I’ll try Django and may be share my experience 🙂
        Also, if instead of an LED, I want to take it a step further, by being able to configure devices that work on 240 V, how should I go about it? Can you please suggest and help me! Thanks!
        One more, can the wired connections be replaced by wireless transmissions cheaply? I mean there are wifi switches available like WeMo, INSTEON, but they cost 20-30 times more than a simple cheap relay!!! Any alternatives you could think of? Thanks! 🙂

  • Kiran Gore

    any one known how to start app.js on system start every time

  • Swapneel Golapkar

    I am having 100 switches in my home across 5 rooms, how can I connect them through 1 rasberry pi ?
    Plz suggest I am a naive developer for this project, I will start with small 2 to three switches, but would like to automate my entire home, thanks for your valuable guidance.


  • Mark


    This is a great project which I have successfully managed to get to work on a Pi B, Now I am trying to do the same with a Pi 2 and am running to the following issue = Error when trying to open pin 7 gpio-admin: failed to change group ownership of /sys/devices/virtual/gpio/gpio4/direction: No such file or directory

    Please could someone advise me what to do. I have read that the directory may have changed location but am unable to locate it.


    • Kiran Gore

      To access GPIO you need administrative permission try by using sudo command

  • nathan

    GET / 404 Not Found anyhelp

    • Clint

      when you plug in the link on your browser, make sure to do “/interface” to the end of the ngrok link

  • how can i switch on and off a 12v circuit if relay is 12v and pi is 5v

  • Rohan

    Your tutorial’s are really amazing…
    I have a doubt regarding my project suppose i want to implement an irrigation system,an led on raspberry pi and access them through a web server but with a different web page to make it more innovative, how will i do that and i want to display a graph using an ultrasonic sensor on a web page and get a notification on an android application i design.
    Please help me out sir asap.

    • Thanks Rohan! Your project sounds exciting, I really recommend you to check all the tutorials on this website and you will sure find how to make it!

  • Jack Hughes

    Great write up. I would like to achieve the remote control of an output gpio pin, but as well as this, control a pcd8544 LCD screen.In otherwords, while GPIO is 1 (high) the LCD displays one message. While the GPIO is 0 (low) then the LCD would display another message.
    Any thanks would be greatly appreciated!

  • Geert Van Moer

    Can anyone help me with this problem on and off the same error

    [email protected] ~/quick2wire-gpio-admin/pi-node-relay $ node app.js

    Listening on port 3700

    express deprecated res.sendfile: Use res.sendFile instead app.js:18:12

    State on received.

    Error when trying to open pin 7

    gpio-admin: failed to change group ownership of /sys/devices/virtual/gpio/gpio4/direction: No such file or directory

    I have tried most things I could find in goole and forums and after installing and reinstalling no succes.

    Raspberry model PI 2

    • Ratmir

      Got the same problem, on a model B+. It means the quick2wire gpio-admin library isn’t working, and the pi’s pins can not be configured and/or set.

      However, on the original raspberry pi, we got the above working like a charm… So I’m guessing that the models with more pins (2, B+, others?) are not supported by quick2wire gpio-admin.

      Perhaps somebody can confirm or deny this?

      • Geert Van Moer

        Hi Ratmir

        problem solved, everything works fine now

        Thanks to Andrew 🙂

        https://github.com/quick2wire/quick2wire-gpio-admin/issues/5 and


        • Ronald Golec

          Hello Geert,

          I followed the github fix you posted and SUCCESSFULLY rectified my group ownership issue after upgrading and currently running version 3.18.5, model B+. Thank you for posting!

          However… the LED’s that I have connected to GPIO pins 36, 38 and 40 do not respond to the buttons I press on the server web page anymore. They all functioned perfectly prior to the upgrade.

          I’m receiving the following normal messages as I did prior to the upgrade:

          “Listening on port 3600”
          “GPIO Pin 36: on received”
          “GPIO Pin 38: on received”
          “GPIO Pin 40: on received”

          But my LED’s do not respond accordingly as before.

          Any suggestions? Thank you!

        • Ronald Golec

          Hello Geert,

          I followed the github fix you posted and SUCCESSFULLY rectified my group ownership issue after upgrading. I’m currently running version 3.18.5, model B+.

          “Listening on port 9200”
          “GPIO Pin 36: on received”

          My LED flashes once and turns off when pressing ‘ON’ in the server page.

          I am receiving the following error in the Terminal:

          express deprecated res.sendfile: Use res.sendFile instead app.js:18:12

          Any suggestions? Thank you!

  • igm4ever

    Hi Marco,

    I’d like to do the same thing but with variable voltages, so as to control dimmable lights, how hard would it be to expand this? I have very basic coding knowledge

    • With the right hardware that would be easy I guess, you would need to look at PWM output on the Raspberry Pi to control the intensity of the lights.

  • Lynda Barry

    I just finished installing the revised software (I’ve previously used the HTML/JS/PHP version) and connected to a relay board that was working fine with the earlier program. When trying to operate the relay I get the following output in the terminal window:

    State on received
    Error when trying to open pin 7
    gpio-admin: failed to change group ownership of /sys/devices/virtual/gpio/gpio 4
    direction: no such file or directory

    Can anyone offer any suggestions to fix this error?

    • Ronald Golec

      Hello Lynda,

      I followed the github fix you posted and SUCCESSFULLY rectified my group ownership issue after upgrading and currently running version 3.18.5, model B+. Thank you for posting!

      However… the LED’s that I have connected to GPIO pins 36, 38 and 40 do not respond to the buttons I press on the server web page anymore. They all functioned perfectly prior to the upgrade.

      I’m receiving the following normal messages as I did prior to the upgrade:

      “Listening on port 3600”


      “GPIO Pin 36: on received”

      “GPIO Pin 38: on received”

      “GPIO Pin 40: on received”

      But my LED’s do not respond accordingly as before.

      Any suggestions? Thank you!

  • Ronald Golec

    Hi Marco,

    I upgraded my RPi to version 3.18.5 on my model B+.

    I now receive the following in Terminal:

    “Listening on port 9200”
    “State undefined received.”
    “GPIO Pin 36: on received”

    The led on GPIO pin 36 flashes once and quickly turns OFF when pressing ‘ON’ in the server page.

    Any suggestions? Thank you!

  • TJ Gilbert

    I saw another user post this same question but it did not get a response. Could someone help me out?

    State on received
    Error when trying to open pin 7
    gpio-admin: failed to change group ownership of /sys/devices/virtual/gpio/gpio 4
    direction: no such file or directory

    Can anyone offer any suggestions to fix this error?

  • Rob McGeown

    I’m struggling with the “failed to change group ownership” error. I’ve changed the path in gpio-admin.c as suggested in the listed solutions but no luck…

  • Lynda Barry

    I just reinstalled the packages for the relay operation from github following the listed procedure. I can launch app.js and get the expected response but when I try to access interface.html I get the following error message:

    Error: ENOENT: no such file or directory, stat ‘/piRelay/views/interface.html’ at Error (native)

    I’m not sure how to resolve this problem.

    • Strange, the file is definitely inside the folder. Make sure that it is really there on the folder on your Pi.

      • Lynda Barry

        That’s one of the things that I checked, and app.js and the ‘views’ folder are definitely inside pi-node-relay. I’m going to try changing the path statement in this section:

        // Set views

        app.use(express.static(path.join(__dirname, ‘public’)));

        app.use(express.static(path.join(__dirname, ‘views’)));

        // Serve files

        app.get(‘/interface’, function(request, response){


        Would this work?

        // Set views

        app.use(express.static(path.join(__dirname, ‘public’)));

        app.use(express.static(path.join(__dirname, ‘piRelay’)));

        app.use(express.static(path.join(__dirname, ‘views’)));

        // Serve files

        app.get(‘/interface’, function(request, response){


  • Lynda Barry

    So, I decided to start over again to try and resolve some issues I’ve been having. I followed steps above and installed node, but when I run this command sudo dpkg -i node_latest_armhf.deb I get the following error message.

    dpkg: regarding node_latest_armhf.deb containing node:
    nodejs-legacy conflicts with node
    node (version 4.2.1-1) is to be installed.
    node provides node and is to be installed.

    dpkg: error processing archive node_latest_armhf.deb (–install) :
    conflicting packages – not installing node
    Errors were encountered while processing:

    I have no idea why this has happened (I’ve tried starting from scratch twice now) – does anyone have any ideas what is going on and how I can fix it?

    • Claudio

      you solved?
      i have the same error 🙁

      • Lynda Barry

        No, not solved yet. I don’t know how to fix the problem and I have been too busy to try anything different.

      • Lynda Barry

        I finally found some help and a solution. Had to remove the pre-installed version of node.js as well as a package that depends on it.

        sudo dpkg -r nodejs-legacy
        sudo dpkg -r nodered

        After that sudo dpkg -i node_latest_armhf.deb works.

  • Lynda Barry

    Okay, I finally got past the node.js installation problem. Had to uninstall nodejs-legacy and nodered before the latest node.js would install. I’ve got all the relevant packages installed correctly now, but I must be doing something wrong with renaming and changing id for my board in app.js. After changing from the default values listed in the tutorial all I get when trying to operate the relay is {“message”: “Requested device not found”.} In the cloud.arest.io dashboard that I created it shows the device as “offline”.

    Any suggestions of how to fix this issue will be greatly appreciated.

  • Ryangodammit lᴉɐɯƎ

    I just built this project and had it running ok once, listening at least, not controlling yet. But after a reboot of the pi, when I try and run the app it says it can’t find the module ‘boom’. Any ideas what this might be?

    • Ryangodammit lᴉɐɯƎ

      Hi Marco,

      I seem to have that problem sorted now and it all seems to be working fine.
      I have been trying to add it to the rc.local file so that it always starts up at boot, but can’t get it to run that way. I’ve tried it as a straight program and also using the forever function to run it, but neither seem to do anything. Have you had it work this way?

  • Ryangodammit lᴉɐɯƎ

    I seem to be having the same problem some else here was having. When I push the on button, the relay very quickly switches on then off, but doesn’t stay on. How do I fix this?

  • malini

    I’m using a raspberry pi 2 model B. I’ve followed all the steps and when i type the url https://cloud.arest.io/digital/7/1 i get the message “requested device not found”. Please help.

    • You need to insert the name of your device first 🙂 For example http://cloud.arest.io/3g83df/id

      • malini

        is this for a static ip address for the pi? because i’m using a dynamic one for my pi.

        • This will work in both cases – it uses communication via MQTT between the Pi & the aREST cloud server. For the device name, you can use whatever you wish 🙂

          • malini

            Thank you 🙂
            But now i’m facing another problem. When i run app.js, it shows listening on port 3000, but now it doesnt show connected to arest.io (though the first time i ran, it did show). Where is the problem? I cant figure out. Please help.

          • malini

            Thank you 🙂

          • malini

            Hey Marco, I have one final problem here. While using the dashboard, when i press on, the relay just stays on for 2-3 seconds and then it switches off. Why is this happening?
            And sometimes, the relay automatically switches on even if i havent pressed the on button. Please help.

          • Hey! Strange, seems like the board or at least the software is resetting somehow. Can you tell me what shows up in the console?

          • malini

            Do you mean this by the console? I’m still struggling with the same problem.

          • I replied to your email 🙂

  • kd4hls

    hi, great instructions..eg. got it working!
    im using this to open some gates, but i need the relay to stay on for a second or two.

  • Edward Morra

    My project is to make a button in my iphone app Simple Remote that issues an http command like and turn on a relay to lower my projector screen.

    I have installed Raspian Jesse Lite on a Pi B,SSH into it and followed the guide for installing aRest for Pi https://arest.io/pi/. I also installed rpi.gpio and wiringPi so I could test the relay from the Pi B command line with ‘gpio -1 mode 12 out’ and ‘gpio -1 write 12 1’ to turn the relay on, which works well.

    I then issue ‘node app.js &’ at the Pi B command line and point a browser on my laptop to it returns the expected default result {“id”:”34f5eQ”,”name”:”my_new_Pi”,”hardware”:”rpi”,”variables”:{“temperature”:24,”humidity”:40},”connected”:true}

    When I try i get the expected {“id”:”34f5eQ”,”name”:”my_new_Pi”,”hardware”:”rpi”,”connected”:true,”message”:”Pin 12 set to 1″}. However the Pi B command line spits out ‘[Error: Pin has not been exported for write] Written to pin’ and the relay does not turn on. I have tried multiple different pins such as, all with the same error.

    How do I declare that pin twelve is to be written to (ie., is an Out pin) to make this work?

    code versions are node -v 4.2.1, gpio -v 2.32.

    Thank you in advance for any helpful comments.

    • Did you start the node.js command with sudo ? That’s usually the main problem

      • Edward Morra

        Thanks Marco, I am excited that it now works! I ssh into the pi, issue ‘sudo screen node app.js’ and logout. I can now operate my screen from my iPhone with the Simple Remote app.

        The next test is to see if this works after a power failure to the pi. Thanks for making this project possible!

  • Miguel Garcia

    Hi Marco Schwartz

    I’m appreciating very much this project but, as I’m a novice, I need you help with the following:

    At a certain point it is said:

    What we have to do now is to build the Node.js script that will connect the Raspberry Pi to the aREST.io cloud platform, which is a tool that I created specifically to control boards like the Raspberry Pi remotely.

    Question is:

    How do I create this script ?

    Is it to put inside a plain text file (created with Leafpad, for example) ?

    If yes, in which directory do I put it ?

    Can you please explain in details.

    If any other one can help me, please do it

    Thanks in advance

  • Miguel Garcia

    Hi Marco Schwartz

    and “Internet of Things with the Raspberry Pi ” on Amazon.
    So, first of all, congratulations on them as, at a first glance, they seam to be
    very interesting.

    As before I bought them I was about to go ahead with this project but, as I’m a linux novice,
    I need you help with the following:

    At a certain point it is said:

    What we have to do now is to build the Node.js script that will connect the Raspberry Pi to the aREST.io cloud platform, which is a tool that I created specifically to control boards like the Raspberry Pi remotely.

    Question is:

    How do I create this script ?

    Is it to put inside a plain text file (created with Leafpad, for example) ?

    If yes, in which directory do I put it ?

    Can you please explain in details.

    If any other one can help me, please do it

    Thanks in advance

    • Thanks! I already answered to your question by email 🙂

  • Malik Adeel

    Hi marco i was follwing the tutorial but the problem is in the second command when i try to run “sudo dpkg -i node_latest_armhf.deb” it gives error :
    error processing archive node_latest_armhf.deb
    codejs-legacy conflicts with node
    Thankx in advance

    • Hi Malik! It seems like you already have Node.js installed 🙂 Check this by typing node -v in a terminal

  • Chandler

    When I type sudo npm install pi-arest express it says /usr/local/bin/node: /usr/lib/arm-linux-gnueabihf/libstdc++.so.6: version ‘GLIBCXX_3.4.20’ not found (required by /usr/local/bin/node) and /usr/local/bin/node: /lib/arm-linux-gnueabihf/libc.so.6: version ‘GLIBC_2.16’ not found (required by /usr/local/bin/node)

  • Deven Swiergiel

    Hey Marco,

    I loved Thai tutorial!! It was very well explained and easy to follow!! I’m a third year computer science major starting to get into robotics and electronics. Anyway the relay I purchased has inverse logic, that is it has High is actually == Low. This means that every time I load the dashboard once the Pi is found, it sets the relays to low or 0, but with my relay that actually turns it on. I tried modifying your code to change it but can’t seem to find the right functions to change. Im still new to some of this stuff so I was wondering if you could guide me in the right direction!

    Thanks a ton!!


    • Hey Deven, you’re welcome! Glad to hear you enjoyed the tutorial 🙂

      • Deven Swiergiel

        I did! But do you think you could tell me where and how I could go about modifying the code to invert the signals to the relay?

  • Juan Lugmania

    Hi, Please can you help me with this problem

    [email protected]:~ $ node app.js
    Camera module off
    Litening on port 3000
    Connected to aREST.io
    [Error: Pin has not been exported for write]
    [Error: Pin has not been exported for write]
    [Error: Pin has not been exported for write]

    • Hi! Just run the Node.js file as sudo 🙂

      • Juan Lugmania

        Waaaooo !!! Viel Danke !!! Grüsse