|

JavaScript Powered Arduino with Johnny-Five

Atwood’s Law: Any application that can be written in JavaScript, will eventually be written in JavaScript.
- Jeff Atwood, July 17, 2007

Other than the near omniscience of Edsger Dijkstra, I don’t think any prediction of the future of software development has been so dead-on as Atwood’s Law. JavaScript is everywhere: running applications in browsers, running the servers that feed HTML to the browser, and running database engines, to name a few. It should be no surprise, then, that JavaScript can also be used to control off-the-shelf hardware, circuits and other electronics like the Arduino platform. Through the use of frameworks like Rick Waldron’s Johnny-Five for NodeJS, and the “StandardFirmata” software package for Arduino, you can write JavaScript on your computer and use it to control and manipulate nearly any aspect of an Arduino-based hardware setup.

But before you take over the world with your JavaScript powered robots, you’ll need to get a few of the basics out of the way. You’ll need to know how to get an Arduino to communicate with your JavaScript program. You’ll need to know how to build a circuit that works properly. And you’ll need to know how to manipulate that circuit, through the use of Arduino, with your JavaScript code. And before you do any of that, you’ll need a few hardware parts to work with.

Arduino

The Arduino platform is an open-source hardware system, designed to make it easy to prototype electronics systems. But more than just the hardware, the Arduino ecosystem includes an IDE and software libraries, along with builders and suppliers that create their own versions of the hardware, and much more. To say that the Arduino ecosystem is “massive” may be an understatement. But, to say that you must be be able to write C and be a electrical engineer to build Arduino toys is, conversely, an overstatement.

A Shopping List For Your Arduino

If you don’t already have the following items, you should purchase them to follow along in this post:

You can find Arduino and compatible boards at nearly any electronics/hobbyist store. There are also dozens of online retailers and specialty companies that supply parts and components. If you buy a “starter kit” of some sort, you can get most of the items that you need in one purchase. The exceptions to this will be the pliers and safety glasses.

Of course there are plenty of other Arduino board options. If you have an Arduino board that you are comfortable with, you do not need to buy an Uno. You will have to adjust some of the code and hardware pin configurations for your specific board, though.

The Arduino IDE And Firmata

Once you have an Arduino in hand, you will need to install the “StandardFirmata” sketch on it to use the Arduino IDE. Don’t worry, though, this process is mostly painless and it is the only time you will have to look at the Arduino IDE or any C code.

The Arduino IDE, Board, And Serial Port

Head over to Arduino.cc, and download and install the latest version of the Arduino IDE for your operating system. Once you have that open, plug the Arduino Uno in to your computer via a USB cable. If you don’t see any LEDs on the board blink a few times (or more) try connecting to a different USB port or with a different USB cable.

connected-arduino-uno

Next, open the “Tools” menu in the Arduino IDE and select the “Arduino Uno” board type under the “Board” sub-menu, with the serial port that your Uno is connected to. Look for a serial port in the “Serial Port” sub-menu of “Tools” that starts with “tty.usbmodem” followed by a number, like the one in this example:

select-arduino-uno
select-serial-port

This information is needed so that the IDE can import the correct features and default libraries for the build and upload process. Once you have the board type and serial port selected, you don’t need to worry about changing them again, unless you change boards or serial ports. The IDE will remember which settings you selected.

The StandardFirmata Sketch

Having set up the IDE, it’s time to compile some code and upload it to the Arduino! Fortunately you don’t have to write any of the needed code. Go to the “File” menu, and under “Examples” you should see a “Firmata” menu. Choose “StandardFirmata” from this menu. This will open the Arduino sketch for the StandardFirmata protocol.

select-standardfirmata

In the file that just opened, you should see a check-mark and an arrow at the top left. Click the right-arrow to compile and upload the code to your Arduino. You’ll see two LEDs labeled “RX” and “TX” light up while the upload is happening. These are the “receive” and “transmit” LEDs for serial communications. The IDE will give you a message and progress bar for the upload, and another message when the upload is completed.

upload-complete

With that done, you can close the Arduino IDE, never to return again (unless you want to, of course)!

NodeJS and Johnny-Five

Now that your Arduino has the StandardFirmata installed, it’s time to get NodeJS and Johnny-Five up and running.

Install NodeJS

nodejs

If you don’t have NodeJS installed yet, you will need to do that now. Head over to NodeJS.org and click the big “download” button. Run the installer and click “next” through the installation steps, and you’re good to go.

Install Johnny-Five

sgier-johnny-five

Johnny-Five is a library of JavaScript components that know how to talk to an Arduino through the “Firmata” protocol – a standard protocol for computers to communicate with hardware devices. To install it, open a command prompt or terminal window in the folder where you will keep your project code. Run the command npm install johnny-five. This will install the NodeJS package for Johnny-Five, making it available for any NodeJS files in that folder.

Blinky: Your First Johnny-Five Program

In software, there is a standard “hello world” as the first code that written for any language being learned. In hardware, the equivalent is learning how to make an LED blink.

Open your favorite text or code editor, and create a file named “blinky.js” in your project folder. Your folder should look something like this, with the “node_modules” folder containing the Johnny-Five installation from npm.

blinky-folder

In your blinky.js file, add the following code (taken from the Johnny-Five documentation):

var j5 = require("johnny-five");
var board = new j5.Board();

var LEDPIN = 13;
var OUTPUT = 1;

board.on("ready", function(){
  var val = 0;

  // Set pin 13 to OUTPUT mode
  this.pinMode(LEDPIN, OUTPUT);

  // Create a loop to "flash/blink/strobe" an led
  this.loop( 100, function() {
    this.digitalWrite(LEDPIN, (val = val ? 0 : 1));
  });
});

To run this, open a command prompt or terminal window in the project folder, and enter this command:

node blinky.js

You will see some information about finding a serial port, and connecting and running the code that you supplied.

blinky-running

The code, in this case, is the JavaScript equivalent of a C program you would find in any introduction to Arduino article that uses C. It loads the Johnny-Five library and creates a new “Board” object, which is used to control the core communications with the Arduino board. It then waits for the board to be “ready” for input and output. Once that happens, it sets up a specific hardware pin number to be in output mode. This allows your code to “write” values to the pin – to set the amount of electricity flowing through that pin. Then a loop is created that will execute code every 100 milliseconds. The code within this loop changes the value of the specified pin to either 0 or 1… off or on. The result is a small LED next to pin 13 on your Uno board, blinking (as well as the “rx” and “tx” lights blinking).

This works out of the box because most Arduino boards have a built in LED and resistor on pin 13. If you change the LEDPIN to something other than 13, though, you won’t see the LED next to pin 13 blinking anymore.

Reducing The Code With Johnny-Five’s Led Type

It’s important to understand how to write code that works with the loop in Johnny-Five. You will end up using this at some point. But making an LED blink is something that shouldn’t require so much code. Thankfully, Johnny-Five includes an Led object type that can handle this for you.

var j5 = require("johnny-five");
var board = new j5.Board();
var LEDPIN = 13;

board.on("ready", function(){
  var led = new j5.Led(LEDPIN);
  led.strobe();
});

When you run this, you should see the same result as the previous code. The difference is that you no longer have to set up a loop, set the pin mode or write a value out to the pin yourself. All of this has been encapsulated in the Led type provided by Johnny-Five, and the .strobe() method to tell it what to do.

LEDs, BreadBoards And Circuits

Using the Arduino’s built-in LED is nice, but not terribly useful when you won’t be able to see the board in a real project. It’s time to use your own LED and a breadboard to configure a circuit.

Replace The Arduino LED

WARNING: Make sure your Arduino is disconnected from your computer (unplug the USB cable) before you change any hardware configuration. If you don’t, you’ll spark or short something, and reboot your computer at best. You can easily fry your Arduino, or take down half a building’s power if you’re not careful (believe me, I’ve done it).

Take one of the small LEDs from your collection and look at the two metal leads coming out of it. You’ll notice that one of them is longer than the other. This is because LEDs are polarized. That is, they will only work properly if electricity flows through them in the right direction. When you have components with one lead longer than the other, the long lead is always the positive lead – where the electricity enters the component. The short lead, then, is where the electricity exits the component – the negative side.

Take the LED and plug the long lead into pin 13 of the Arduino board. Plug the short lead in to the ground pin (labeled “gnd”) right next to pin 13. This will create a complete circuit from pin 13 to the Arduino ground, allowing electricity to flow.

led-pin-13

Run the blinky.js file without changing any code, and this time you will see your LED blinking on and off. Once you added the LED to pin 13 and connected the other end to ground, the Arduino knew to use your LED instead of the built-in LED.

Get Your Breadboard And Jumper Wires Ready

Find the small plastic board with hundreds of holes in it. Yours may be clear, white, yellow, blue, red or any other color but it will generally look like this:

breadboard

This is called a breadboard and it allows you to very quickly prototype electronic circuits without having to solder anything. You plug wires and components into the holes, and take advantage of the built-in connections between the holes.

The connections run the length for the blue and red line (ground and power) and run across for the remaining rows, like this:

breadboard-connections

Take the LED out of your Arduino board and plug it in to the breadboard, crossing at least one horizontal row. This will keep the circuit from shorting itself when power and ground are connected.

Grab two breadboard jumper wires – the flexible wires with stiff ends – preferably a red one and black one. You’re going to build your first circuit with these and the LED you’ve been using.

Burning Up An LED

WARNING: You may be tempted to run the wires from the “5v” pin of your Arduino to the LED, and back to the Arduino’s “gnd” pin. You really don’t want to do that. But if you power up your Arduino with a circuit like this YOU WILL BURN OUT OR BLOW UP YOUR LED! The Arduino board has a resistor built into it, to protect pin 13 from getting too much power. It limits the amount of current flowing to the LED. Without a resistor in place, the LED gets too much power and pops.

If you’d like to learn more about why a resistor fixes this problem, look up “Ohm’s Law” and “protective resistor”.

Protecting Your LED

To fix your circuit design, and not blow up any more LEDs, you will need to add a resistor. Take a 1K resistor from your supply and bend the leads down in the same direction. Plug the resistor into the breadboard so that one lead is connected to the LED’s positive (long) lead, and the other resistor lead is connected to the red wire (5v) from the Arduino.

led-resistor-circuit

When you plug the Arduino back in to the USB port on your computer, it will shine without blowing up. The resistor has made sure that the amount of electricity flowing through the LED is less than what it takes to blow the LED.

Now replace the 1K resistor with a 10K resistor or a 330 Ohm resistor. The higher the resistance, the less brightly the LED shines. The converse is also true, until you get a resistance so low that it blows the LED.

LEDs and Buttons

Having an LED always on is nice if you want to waste electricity or just show that the circuit has power. But it’s more useful to turn it on and off as needed. To do that, a button can be added to the circuit. It would be easy to add the button inline with the resistor and LED, preventing the circuit from being complete. It would be far more fun, though, to hook the button up to an input pin on the Arduino and write code that listens for the button press to turn the LED on and off.

A Button And A Resistor

Take the red wire out of the breadboard and Arduino, for now. Grab a different color jumper wire and run it from digital pin 6 of the Arduino to the unconnected lead of the resistor on the breadboard. This will allow you to turn the LED on and off by changing the flow of electricity in pin 8 on the Arduino.

Next, take the small button from your components and plug it in to the board somewhere away from the LED and resistor. Get a wire of a different color and connect it from the negative side of the button to digital pin 7 of the Arduino. Now, grab one of your 10K resistors and connect it to the same breadboard line as the wire and negative LED lead. Connect this resistor to the ground line on the breadboard. Grab the red wire you removed earlier and connect the Arduino’s 5v supply to the button’s positive lead.

You should have a button and LED configuration that resembles this:

pull-down-button

This button + resistor configuration is called a pull-down resistor. When the button is pressed, electrons flow in to this wire. When the button is no longer pressed, it is possible for some electrons to remain in the wire causing a false signal to be sent to the Arduino. A pull-down resistor pulls any remaining electrons out of the signal wire by ensuring the signal wire always has a connection to ground.

Code The Button And LED

Back in the blinky.js file, change the code to the following:

var j5 = require("johnny-five");
var board = new j5.Board();
var LEDPIN = 8;
var BTNPIN = 7;
var ledOn = false;

board.on("ready", function(){
  var led = new j5.Led(LEDPIN);
  var btn = new j5.Button(BTNPIN);

  btn.on("hit", function(){
    led.on();
  });  

  btn.on("release", function(){
    led.off();
  });
});

If everything is plugged in correctly, you can start up the blinky.js, and press the button down to see the LED turn on and off!

Now, To Take Over The World!

Alright, you’ve got a button that turns an LED on and off… USING JAVASCRIPT! That’s pretty awesome. And it’s really just the first steps in learning how to manipulate the real world and the physical world with a clever combination of software and hardware.

The Downside Of NodeJS/Johnny-Five

The downside to running a framework like Johnny-Five, is that your Arduino device has to be attached to the computer running your NodeJS/Johnny-Five code. It needs to be available via serial communications so that the Firmata protocol can do it’s job. This means that if you want to create a “production” hardware system that runs independently, you won’t be using Johnny-Five for long.

If you do want to move in to production code for a stand-alone hardware device, you’ll most likely end up writing C or finding a different hardware platform that runs a different language. But Johnny-Five and NodeJS gives you an easy way to get started, rapidly prototype hardware and software systems, and learn about the hardware side of things.

Moving On, Measuring And Responding

As much fun as it is to click that button and see your LED turn on and off, it won’t exactly cause Skynet to be born (though I am convinced that Skynet will be built with JavaScript… Atwood’s law… come on, now…). From here, it would be fun to get into measurement through sensors and responding to those measurements. Say, oh, I don’t know… a food grade thermometer to monitor the temperature of the steak on your grill, and turn on that little red LED when it’s done? Stay tuned — in the next post, we’ll run some legitimate math in the NodeJS app, and show you how to build an Arduino powered BBQ thermometer.

Safari Books Online has the content you need

These books in Safari Books Online will help you enhance your Arduino project:

Getting Started with Arduino gives you lots of ideas for Arduino projects and helps you get started with them right away. From getting organized to putting the final touches on your prototype, all the information you need is right in the book.
Arduino Cookbook, 2nd Edition helps you create your own toys, remote controllers, alarms, detectors, robots, and many other projects with the Arduino device.
In Beginning Arduino teaches by using an amazing set of 50 cool projects. You’ll progress from a complete beginner regarding Arduino programming and electronics knowledge to intermediate skills and the confidence to create your own amazing Arduino projects.
Arduino Robotics will show you how to use your Arduino to control a variety of different robots, while providing step-by-step instructions on the entire robot building process.

About this author

derickbailey Derick Bailey is a Developer Advocate for Kendo UI, a developer, speaker, trainer, screen-caster and much more. He’s been slinging code since the late 80’s and doing it professionally since the mid 90′s. These days, Derick spends his time primarily writing JavaScript with back-end languages of all types, including Ruby, NodeJS, .NET and more. Derick blogs at DerickBailey.LosTechies.com, produces screencasts at WatchMeCode.net, tweets as @derickbailey and provides support and assistance for JavaScript, BackboneJS, MarionetteJS and much more around the web.

About Safari Books Online

Safari Books Online is an online learning library that provides access to thousands of technical, engineering, business, and digital media books and training videos. Get the latest information on topics like Windows 8, Android Development, iOS Development, Cloud Computing, HTML5, and so much more – sometimes even before the book is published or on bookshelves. Learn something new today with a free subscription to Safari Books Online.
|

19 Responses to JavaScript Powered Arduino with Johnny-Five

  1. Kevin Hoyt says:

    Nice write-up!

    I generally like to know what is going on at the Arduino level, so I write my own sketches and manage the serial IO. From the Node.js side I like to use Node Serial Port and then a Node Web Socket implementation to keep things near real-time. This way I can push to the Arduino, or stream data from it. Not that you can’t with the Firmata/Johnny-Five setup. Just an alternative for consideration by your readers. I keep a repository of examples for various sensors – most with Node.js code, Arduino code, and HTML/JS/CSS example, and schematic where possible.

    Looking forward to your BBQ follow-up!

  2. Hey Kevin,

    Thanks for the comment! I definitely like the idea of using serial communications with the Arduino running native C code. I haven’t tried that out yet, but will have to do so. I’ve also got a wifi shield and ethernet shield that I use to host a simple HTTP API from some of my arduino projects. Love that we have all these options to fit the project, as needed. :)

    -Derick

    • Kevin Hoyt says:

      So many options!

      And in a variety of forms. I use a pair of XBee’s for a weather station in my back yard, and am working on an RC lawnmower using 2.4GHz RF. Wi-fi shield options are plentiful, and Arduino has even announced their own wi-fi board, the Yun. Yet to be released options are exciting too. The Spark Core and Pinoccio on the wi-fi side, and RFduino and BLEduino on the Bluetooth side just to name a few. Jeez!

      An early front-runner that I like to use in projects is the Electric Imp (wi-fi). It solves a lot of the problems you run into with wi-fi such as how to set SSID and password without reprogramming the board, remote software updates, recovery if the connection is dropped, etc. Topped off with sick battery life – I have a project that has run on an Imp with a 2,000mAh battery for over three months.

      Here’s a project (wall power) running on an Arduino and Imp Shield. Uses a BlinkM MaxM to control an RGB LED strip. What’s better is you get to see it all streamed in real-time via a Dropcam pointed at the project.

      So much fun!

  3. Jasper Brown says:

    I’m sorry to be pedantic, but it’s important for his memory:

    Dijkstra’s first name is Edsger, not Edgar.

  4. Awesome!

    We could write an abstraction on top of Firmata to use http over the wifi. Setting up a basic http server was easy for me when I first started with Arduino about ten months ago, but I never managed to establish a data stream, such as a tcp socket. Instead of tcp we could use serial over bluetooth to communicate with node.js and a javascript serial library.

  5. Rick Waldron says:

    To everyone reading: Please share anything awesome that you build :) http://twitter.com/rwaldron Thanks!

  6. Donald Derek says:

    Amazing article! I have a small comment on your “The Downside Of NodeJS/Johnny-Five” Part
    I don’t think that this is a problem, because you can easily link your Arduino Board to the RaspberryPi for example where you have NodeJs/Jhonny-Five. That’s just a thought, didn’t try it yet but I will soon :)

    • I’ve heard of other people doing this, though I haven’t been able to verify it with yet. Definitely something I want to try, though. I’ve got an rPi sitting in my drawer of electronics, and I haven’t even plugged it in yet!

  7. kyle jeske says:

    I don’t care who you are – that is cool!

    I think I might just do this for the fun of doing it. Great article!

  8. Jon McKay says:

    We’re starting to work with Rick to make Johnny-Five library compatible with our JavaScript-powered, WiFi-enabled development board! You might be interested in checking it out: http://www.technical.io. We’ll be launching on Kickstarter in about a month!

  9. AnonyMole says:

    Note: One must have Python 2.7.x installed.
    Note: One must have a C++ compiler installed (Visual Studio Express 2010 C++ worked fine).

  10. Stefan says:

    I can’t wait to be able to run the javascript (johnny-five, noduino, etc.) right on the Linux side of the house on the new Arduino Yun, which is being released this month!

  11. Anon says:

    Hello, I have an error while executing blinky.js that is, “”$$$$$$$ Board Connecting…
    $$$$$$$ Serial Found possible serial port /dev/cu.usbmodem411
    $$$$$$$ Board -> Serialport connected /dev/cu.usbmodem411
    $$$$$$$ StandardFirmata A timeout occurred while connecting to the Board.
    Please check that you’ve properly loaded StandardFirmata onto the Arduino
    $$$$$$$ Board Closing: firmata, serialport””
    I tried every version of Standardfirmata, but same result. Could you solve this problem?