Iain
Published © MIT

JavaScript with Hardware [Part One]: Making a Simple Nodebot

Part One in a series of JavaScript and Hardware. In this part, Iain shows how to get Node and Yarn set up and making our first Nodebot.

BeginnerProtip2 hours9,404
JavaScript with Hardware [Part One]: Making a Simple Nodebot

Things used in this project

Story

Read more

Schematics

Basic Nodebot

The final circuit of the first nodebot!

Code

index.js

JavaScript
The entire script used for the Nodebot in this tutorial
var five = require('johnny-five');
// Make variables for objects we will be using
var board, led, pushButton;

// Set `lightOn` to true as a default since our LED will be on
var lightOn = true;

// Make a new Board Instance
board = new five.Board();

// When the board is connected, turn on the LED connected to pin 9
board.on('ready', function() {
  console.log('[johnny-five] Board is ready.');

  // Make a new Led object and connect it to pin 9
  led = new five.Led(9);

  // Make a new Button object assigned to pin 7
  // We also need to say it is a pullup resistor!
  var pushButton = new five.Button({
    pin: 7,
    isPullup: true,
  });

  // Switch it on!
  led.on();

  // If the button is pressed, toggle the LED on or off
  pushButton.on('down', function() {
    if (lightOn) {
      led.off();
      lightOn = false;
    } else {
      led.on();
      lightOn = true;
    }
  });

  // REPL object so we can interact with our LED
  this.repl.inject({
    // Control the LED via calling for the object
    led: led,
    // switchOn and switchOff functions to turn LED on and off using REPL
    switchOn: function() {
      if (lightOn) {
        console.log('[johnny-five] LED is already on!');
      } else {
        led.on();
        lightOn = true;
      }
    },
    switchOff: function() {
      if (!lightOn) {
        console.log('[johnny-five] LED is already off!');
      } else {
        led.stop().off();
        lightOn = false;
      }
    }
  });

  // When the board is closing, stop any LED animations and turn it off
  this.on('exit', function() {
    led.stop().off();
    console.log('[johnny-five] Bye Bye.');
  });

});

package.json

JSON
The package file for the Nodebot in this tutorial.
{
  "name": "basic-nodebot",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "johnny-five": "^0.13.0"
  }
}

Credits

Iain

Iain

5 projects • 71 followers
Hello! I'm Iain, a digital creator. I like making projects with code, art, and robots. Follow me for awesome projects and fun tidbits!

Comments