Control an LED from the Internet with Raspberry Pi – Node.js – Ably.io

Overview

In this post we will remotely toggle an LED connected to a Raspberry Pi. Remember if you can toggle an LED you can control anything.

You don’t need experience in any of these technologies to complete this tutorial. I will supply all code.

We will program the Pi in JavaScript running on Nodejs. This code code will listen for commands from our web page.

We will program our webpage in html and JavaScript running in the browser. This code will send commands to our Pi to toggle the LED on and off. We will be using Microsoft Azure to host our web page for free. Or if you have you own web space – you can use that.

We will use Ably.io to stream the commands from our web page to our Raspberry Pi in what seems to be real-time – Ably is fast. We can also stream data from our Pi back to our web page. You will need to create an Ably account – It’s free for the basic stuff we will be doing and you don’t need a credit card to sign up.

We will use the node GPIO package onoff to toggle the pins on our PI thus turning our LED on and off.

Parts

I do not derive any income from these links. Find cheapest price with good reviews. Also look around for other Pi packages. Some will come with an SD card included – some even with an Operating System installed.

Raspberry Pi (2 or 3)

Micro SD Card

LED, Resistor & Breadboard

SD Reader/Writer

Installing Noobs and Nodejs on your Raspberry Pi

There is a tutorial (how I learned to set up Nodejs) at this link. No sense repeating it here as Dave does a great job. You can skip parts –  Prepare Remote Desktop and Create Windows File Share – if you like but they are worthwhile steps.

Install onoff

At your terminal window type
~$ npm install onoff

onoff

Install Ably

At your terminal window type
~$ npm install ably

ably

Wire up the Pi

Connect the black wire to ground on your Pi and the shorter lead on your LED
Connect the red wire to GPIO 27 on your Pi and to one end of your resistor
Connect the other end of the resistor to the longer lead on your LED
Note there are plenty of tutorials out there that will show you how to calculate the proper size resistor for your LED. You can also live without the resistor for some quick tests, on and off just don’t leave the LED on very long without a resistor.

rasbperry-pi-3-led-ably

The Code

We can now write the code we need to toggle our LED. This will consist of two parts –

  •  JavaScript – running in nodejs on our Pi – which listens for commands and toggles the LED
  • Html page with JavaScript which will send the commands

Pi JavaScript (Listener)

Every new Ably.io account come with a Sandbox key and channel by default. We will be using both here.

  • Choose Pi icon (upper left) -> Programming -> Geany
  • Type or copy/paste code below with your Sandbox key included
  • Save the file as listener.js in  /home/pi directory
var Ably = require("ably");
//Note make sure you change to Your Sandbox Key below
var realtime = new Ably.Realtime({ key: 'Sandbox key here' });

var GPIO = require('onoff').Gpio,
led = new GPIO(27, 'out');

var channel = realtime.channels.get("Sandbox");
//listen for messages from our web page and set
//GPIO pin 27 to 1 (on) or 0 (off).
channel.subscribe(function(msg) {
  var message = JSON.stringify(msg.data.lightstate);

  if (message == "\"on\"") {
    led.writeSync(1);
  }
  else if (message == "\"off\"") {
    led.writeSync(0);
  }
});

Test

Let’s do some testing before we move on to writing the Html/Javascript code to send messages.

Open a terminal window and type the following to run our listener.js file

listener

If you don’t have any file errors your cursor will move to the next line and wait for commands. If you do have errors in the file your Pi will tell you. Fix them and try again…

Now that our listener is running we can write some commands to test

Open a second terminal window and type the following commands

ablytest

Fun stuff… Your LED should have toggled on and off. If not the fun actually begins – debugging.

  • Check your LED connections. Are you using the right pins?
  • Check each line of code. Is it exact? Case counts – ‘Sandbox’ != ‘sandbox’…

Html Page(Sender)

Next we’ll create a web page to allow us to toggle our LED from anywhere we have an internet connection.

You can write this code on your main computer or on your Pi. Notepad works just fine as an editor or if you have an Html editor you can use that.

  • Copy/Paste the code below into Notepad
  • Update your Sandbox key
  • Save the file as LightToggle.html
  • Add some css after your get it working to pretty it up
  • You might your Ably key in a separate js file to hide it a bit
<!DOCTYPE html>
<html lang="en">

<body>
<button type="button" onclick="toggleLight(this)" id="on">On</button>
<button type="button" onclick="toggleLight(this)" id="off">Off</button>
</body>

<!-- Include the latest Ably Library  -->
<script src="https://cdn.ably.io/lib/ably.min.js"></script>
<script type="text/javascript">

    /* Publish a message when the button is pressed */

    function toggleLight(elem) {
        var state;
        var realtime = new Ably.Realtime({ key: 'Your Sandbox Key Here' });
        var channel = realtime.channels.get("Sandbox");
        if(elem.id=="on")
            state="on";
        else if(elem.id=="off")
            state="off"

        channel.publish("update", { "lightstate": state });
    }

</script>
</html>

Create a Web Site

  • Browse to this link to create Azure account. You do not need to be a student to create a free account.
  • Once you have an account – create a web site.
    azure-web-app-steps
  • Upload the html file to your page
    • Browse to: https://{sitename}.scm.azurewebsites.net/DebugConsole
    • Navigate to: site/wwwroot
    • Upload the html file
  • Browse to: http://{sitename}.azurewebsites.net/LightToggle.html
  • Enjoy

Hiding your Ably Key in a JavaScript file

    • Update your html file to the following
      <!DOCTYPE html>
      <html lang="en">
      
      <body>
      <button type="button" onclick="toggleLight(this)" id="on">On</button>
      <button type="button" onclick="toggleLight(this)" id="off">Off</button>
      </body>
      
      <!-- Include the latest Ably Library  -->
      <script src="https://cdn.ably.io/lib/ably.min.js"></script>
      
      <!-- Include the SandboxKey file  -->
      <script src="SandboxKey.js"></script>
      <script type="text/javascript">
      
          /* Publish a message when the button is pressed */
      
          function toggleLight(elem) {
              var state;
      
              if(elem.id=="on")
                  state="on";
              else if(elem.id=="off")
                  state="off"
      
              channel.publish("update", { "lightstate": state });
          }
      
      </script>
      </html>
      
  • Create a file in notepad called SandboxKey.js
  • Add the following
    var realtime = new Ably.Realtime({ key: 'Your Sandbox Key' });
    var channel = realtime.channels.get("Sandbox");
    
  • Upload both files to the same location on your web server
Advertisements

One thought on “Control an LED from the Internet with Raspberry Pi – Node.js – Ably.io

  1. Pingback: RealTimeWeekly | RealTimeWeekly #159

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s