Tuesday, July 16, 2013

JavaScript Powered Arduino with Johnny-Five

ATWOOD'S LAW: Any application that can be written in JavaScript, will eventually be written in JavaScript.

- , July 17, 2007




Other than the near omniscience of , 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 . Through the use of frameworks like Rick Waldron's 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 platform is an 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:



* An Arduino Uno R3 board

* A USB type A cable (the kind often used for printers)

* An electronics breadboard

* Breadboard jumper wires

* A few small LEDs

* A variety of 1/4 watt resistors (330 Ohm, 1K Ohm and 10K Ohm would be a good start)

* A small, bread-board compatible button (a "SPDT, through-hole, momentary push-button")

* Needle-nose pliers

* Safety glasses



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 , 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.



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:



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.



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.



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



If you don't have NodeJS installed yet, you will need to do that now. Head over to 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



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 "nodemodules" folder containing the Johnny-Five installation from npm.



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



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.



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 1off 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.



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:



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:



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.



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:



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 offUSING 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 JavaScriptAtwood's lawcome on, now ). From here, it would be fun to get into measurement through sensors and responding to those measurements. Say, oh, I don't knowa 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:



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.



helps you create your own toys, remote controllers, alarms, detectors, robots, and many other projects with the Arduino device.



In 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.



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



is a Developer Advocate for , 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 , produces screencasts at , tweets as and provides support and assistance for JavaScript, BackboneJS, MarionetteJS and much more around the web.
Full Post

No comments:

Post a Comment