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

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.

  • 1,744 views
  • 2 comments
  • 7 respects

Components and supplies

Apps and online services

About this project

Hey there! Good to see you from Part Zero — let's get our hands dirty! If you remember from the previous tutorial, we looked at why JavaScript is a good choice for coding hardware, what advantages it brings, what Nodebots are, and what components you should get to take part in this, especially if you're a new with code and hardware.

In this part, we'll be setting up Node to run our projects on the computer's level, and Yarn as a dependency manager for our projects. In addition, we'll look at the components used, set up StandardFirmata for the Arduino, how to use REPL, and make a simple nodebot. That's enough of the talk, let's get stuck in!

Setting Up Node and Yarn

Before we start our projects, we need to set up Node.JS and Yarn so we can run our code and install dependencies. If you've already done this, skip this step, but if you haven't done this before it's important to get this out of the way first!

To install Node.JS, you can simply download the installer for your operating system of choice from the Node.JS website. This is the easiest way to get Node.JS installed on your machine, and will get you up and running in no time!

Alternatively, if you're on macOS, you can also use Homebrew to install it. If you have Homebrew installed, simply put the following in your CLI.

brew install node

There are many alternative ways to install Node.JS, so take your pick!

Node.JS comes with NPM built in, which can be used for installing and maintaining dependencies. However, I suggest using an alternative from Facebook called Yarn. It's become a very popular dependency manager, and one thing that I love about is its speed. It is much, much faster than NPM, and it gets your dependencies set up quickly and reliably. It also has a neat CLI output that's easy to read!

To install Yarn on Windows, you can download an installer to set it up. On macOS and Linux, you can do the following curl command to install it.

curl -o- -L https://yarnpkg.com/install.sh | bash

Also on macOS, you can install it via Homebrew if you want to.

brew install yarn

Again, there are alternative methods to install Yarn. If you have any trouble, be sure to look at the Install page on the Yarn website.

Important Note: Be sure to have your PATH set up for Yarn so you can use Yarn executables globally! These can be found on the Install page on the Yarn website if you're stuck.

Now we've got our Node.JS runtime set up and have Yarn as a dependency manager, we can now start installing Node Packages and run JavaScript software on our machine! But not so fast, we need to get our Arduino ready to work with our code!

Setting Up StandardFirmata

Because we're using a computer to host the code we're writing, we need to install Firmata to our Arduino in order to interpret the code coming from the computer. This is very easy. Just connect your Arduino Uno to your computer, then open the Arduino IDE. Then select your Uno Board, and make sure the port is connected.

Then, open "File>Examples>Firmata>StandardFirmata". Upload it to your Arduino and then it's ready to receive our JS Code from the computer! Couldn't be simpler.

Making a Simple LED Nodebot

Now we're ready to start making our first Nodebot! The first thing we need to do is put our circuit together — place an LED onto your breadboard, on the right column, and connect a wire from Pin 9 on your Arduino to the Breadboard, with a 330 Ohm Resistor bridging the two columns, connecting the LED to Pin 9. Also, connect a wire from the negative of the LED (the short leg!) to a Ground pin on the Arduino. If you're confused at all, follow the schematic provided!

Important Note: When connecting the LED to Pin 9 and the Resistor, make sure you connect it to the long leg of the LED! This is the positive end of the LED component and needs the incoming current, so make sure you connect it properly!

Now on your computer we'll need to make a new folder called 'basic-nodebot', or whatever you'd like to call it, it's up to you. In your Terminal, go into the directory you just created, and run yarn init -y. This makes a package.json file where we'll store our dependencies, node scripts, and much more. Next, type yarn add johnny-five, and this will install Johnny-Five into our project!

Next, make a file called index.js and open it in your favourite editor (I personally enjoy using Visual Studio Code or Atom). Using the following script, we can store the Johnny-Five library into a variable, and then reference the various Classes in its API when necessary. We need to make a new Board instance, and use an Led class.

var five = require('johnny-five');

// Make variables for objects we'll be using
var board, led, pushButton;

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

// When the board's 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);

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

  // 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.');
  });

});

Now in your CLI, run node index.js. Node.JS will then connect to your Arduino, and your LED will come on!

Congratulations! You've just made your first Nodebot script!

Using Read, Eval, Print, Loop (REPL)

Let's kick things up a bit with our LED Nodebot. We'll be using REPL (Read, Eval, Print, Loop), where we can interact with our Nodebot using the CLI. Johnny-Five's REPL is `true` by default, and can be configured. We can use Johnny-Five's REPL utility to access our components via the CLI, interact with the components using their functions, or write entire functions we can fire from the CLI. This is very useful for testing out our scripts and functions to make sure they're working properly!

// When the board's connected, turn on the LED connected to pin 9
board.on('ready', function() {
  // [...] Our Previous Code lives here...
  
 
  this.repl.inject({
    // Control the LED via calling for the object
    led: led,
  });

  // [...] Exit code lives here...  
  
});

Using the script above, we can access our led component by typing led to the cli. When this is fired, it will show the entire LED class' code. Don't let this frighten you, it's perfectly normal! However, try led.on(), and the LED should turn on! Another thing you can try is led.pulse(2000), which will fade the LED in and out in a space of two seconds.

There's a lot we can do with just this, but let's make something with a bit more depth. Let's write a function that we can use in REPL. Using this method, we can add more complex scripting to fire when we call it using REPL.

The first thing to note is we've added a boolean variable in our code, which we'll use to control the state of our Led. This will become more useful later on, but it's worth placing here now. If the lightOn boolean is true, then the LED is on, and it's off if it's false.

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

// When the board's connected, turn on the LED connected to pin 9
board.on('ready', function() {
  // [...] Our Previous Code lives here...
  
 
  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;
      }
    }
  });

  // [...] Exit code lives here...  
  
});

There's two functions here — switchOn() and switchOff(), these will turn on the LED on and off, respectively. Also, the lightOn boolean is used to check if your light is on or off already, so if you try to fire switchOn but lightOn is already true, then it will give a console message saying the LED is already on!

These functions are an example of using whole scripts that we can fire as functions while interacting with the Nodebot over the CLI! With this, we can interact with components and test our functions over the CLI to make sure they work as expected.

Now that we've played around with REPL, we get an idea of how to interact with Johnny-Five using the CLI. Let's add another component to interact with to turn our LED on and off.

Adding a Button to the mix

Let's add a button to our circuit, and we'll make it a button pullup. To put it simply, a pullup is basically when power is sent to a component but can't connect to ground until the circuit is closed. A button or switch is an example of a pullup component. When the button is closed, the current to the button can then connect to ground, completing its loop, so the microcontroller knows the button has been pressed.

// 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;
    }
  });

  // [...] Our REPL and exit code lives here...
});

Using the lightOn boolean, we can toggle if the light is on or off depending on the boolean's value. Every time the button is pressed, the lightOn variable changes from its previous value to a new one. With this, we can turn our LED on and off when necessary using a button and our code.

At this point, you've used a few components and have written JavaScript to control the state of an LED as well as interacting it with the Command Line. That deserves a pat on the back!

Next time...

We'll be covering using modern JavaScript and improving how we can write our code! We'll be taking a dive into Babel, making sure our code is consistent with ESLint, type checking with Flow, and NPM scripts!

Totally can't wait to see the next part of the series?

If you become a Patron, you can access this content a few days before everybody else does! All you need to do is pledge a dollar, and you'll get to see new content before everyone else!

Alternatively, if you're willing to wait a few days later yet still want to donate, here's my PayPal! You can also follow me on Twitter, like my Facebook Page, or subscribe to my mailing list to get updates!

Code

index.jsJavaScript
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.jsonJSON
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"
  }
}

Schematics

Basic Nodebot
The final circuit of the first nodebot!
First nodebot 64druuisgv

Comments

Similar projects you might like

Arduino Uno-Based, Easy-to-Build Pet Feeder

Project tutorial by edr1924

  • 1,865 views
  • 3 comments
  • 19 respects

HOW PIR SENSOR WORK

Project tutorial by DIY Partners

  • 2,492 views
  • 6 comments
  • 21 respects

4-Stroke Digital Clock With Arduino

Project tutorial by LAGSILVA

  • 7,413 views
  • 8 comments
  • 30 respects

RGB Camera Backlight Control with Android Mobile

Project tutorial by DIY Partners

  • 131 views
  • 0 comments
  • 2 respects

"Living Art" Arduino-Controlled Desk Lamp

Project tutorial by Modustrial Maker

  • 1,495 views
  • 0 comments
  • 5 respects
Add projectSign up / Login