PubNubTomomi Imura
Published © GPL3+

Getting Started with Johnny Five for IoT (Part 2)

Tomomi Imura, developer evangelist at PubNub, walks through connecting the circuit built in part 1 to a remote user interface using PubNub.

BeginnerProtip4,698
Getting Started with Johnny Five for IoT (Part 2)

Things used in this project

Story

Read more

Schematics

LED - Hello world

Code

remote-blink.js

JavaScript
Node.js / Johnny-Five code
var five = require('johnny-five');
var board = new five.Board();

var pubnub = require('pubnub').init({
  publish_key: 'pub-c-0b43969b-...', // Use your pub key
  subscribe_key: 'sub-c-cb24903e-...' // Use your sub key
});

var channel = 'led';
 
board.on('ready', function() {
  var led = new five.Led(13); // pin 13

  pubnub.subscribe({
    channel: channel,
    message: function(m) {
      if(m.blink === true) {
        led.blink(500);
      } else {
        led.stop();
        led.off();
      }
    },
    error: function(err) {console.log(err);}
  });
  
});

Remote control UI: index.html

HTML
Remote control UI (Front-end code)
<h1>Prototyping IoT Demo UI</h1>

<p>The simplified version of this code (the one used in my Johnny-Five tutorial video on Arduino.cc is available at: <a href="http://codepen.io/girliemac/pen/ZWMqmZ">http://codepen.io/girliemac/pen/ZWMqmZ</a>)

<button class="button-blue">Blink LED</button>

<script src="//cdn.pubnub.com/pubnub-3.14.5.min.js"></script>

Remote control UI: app.js

JavaScript
Remote Control UI (Front-end code)
// Use the same keys that you are going to use for Arduino code with Johnny-Five

var pubnub = PUBNUB.init({
  publish_key: 'pub-c-0b43969b-...', // Use your pub key
  subscribe_key: 'sub-c-cb24903e-...' // Use your sub key
});

// Use the same channel name
var channel = 'led';

var button = document.querySelector('button');

var blinkState = true;

/***
Subscribe data from all subscibers of the channel to set the button state correctly
***/
pubnub.subscribe({
  channel: channel,
  message: function(m) {
    blinkState = m.blink; // the raw data
    blinkState = !blinkState; // toggle it to lable the button
    button.textContent = (blinkState) ? 'Blink LED' : 'Stop LED'; 
    console.log(blinkState);
  }
});

/*
Upon a button click, publish the data.
Arduino will subscribe it and blink LED
*/
button.addEventListener('click', function(e) {
  pubnub.publish({
    channel: channel, 
    message: {blink: blinkState},
    callback: function(m) {
      console.log(m);
    }
  });
  
});

Credits

PubNub
2 projects • 10 followers
Realtime Apps Made Simple! The global data stream network for IoT, Mobile, and Web applications
Tomomi Imura
5 projects • 26 followers
An open web and open technology advocate. A front-end developer. Self-claimed designer. Cat sitter. Pokémon trainer.

Comments