Start programming with Node Js and Johnny-Five: IoT and robotics based on Arduino, Raspberry Pi, Orange Pi

Johnny-Five is an open source Javascript library that allows the rapid and easy development of connected objects or small robotic projects (articulated arm, radio-controlled car …). In the previous tutorial, we saw how to replace the GPIO of the Orange Pi which fishing by its lack of libraries by an Arduino Pro Micro 5V / 16MHz. We used Node-RED to drive the Arduino GPIO. In this tutorial, we will begin javascript programming with the Johnny-Five package.

Project display

We will use an Arduino Nano v3 5V/16MHz to replace the GPIO of Orange Pi Lite. The Arduino will work with firmware Firmata. A led is connected to pin D9. A button will start / stop the flashing of the LED. Finally a BMP180 will explain how to use the I2C bus. For this tutorial, you can use any Orange Pi model (here an Orange Pi Lite – WiFi – 512MB) running under Armbian. You can also run it on a Raspberry Pi (the GPIO of Pi will not be used).

orange pi lite nodejs johnny-five arduino firmata bmp180 i2c led strobe

Equipment used

For this tutorial, I used an Orange Pi but you can also use a Raspberry Pi or a Linux PC

Circuit

Arduino firmata nodejs johnny-five led bmp180

Install Firmata firmware on the Arduino

The Firmata firmware provides access to all Arduino features via the serial port (using a USB cable). Connect the card to the computer and open the Arduino IDE. In the examples menu you will find a submenu named Firmata. Select the firmware that fits your need. The most common is to use the standard firmware. There is also a Plus version for communicating with peripheral devices via serial link UART, USART or SoftwareSerial. Simply upload the firmware to the card. It’s ready ! To customize the firmware, read this article.

ide arduino install firmata

Installing Node.js on Armbian or Raspbian

Node.js is a runtime engine that allows Javascript scripts to run on a computer or mini-PC (Raspberry Pi, Orange Pi …). It is a multiplatform engine, meaning that code written on an environment can work identically (provided that the hardware resources also exist) on another environment. Node.js is available for Windows, MacOS, Linux (x86 and ARM).

nodejs download macos windows linux arm

First, make sure that Node.js is not already installed on your distribution

# node -v && npm -v
v5.12.0
3.8.6

If you get an error message, install Node.js 4.x (sufficient) as well as Python and Build

curl -sL https://deb.nodesource.com/setup_4.x | sudo bash -
sudo apt-get install -y build-essential python-dev nodejs

Installing the Johnny-Five package (J5)

johnny five johnny5 j5

Johnny-Five is a very popular open source project for the programming of connected objects or robotics in Javascript (official page). The name was inspired by the character of the film Short Circuit of which here is a small excerpt for the pleasure of re-discovering

It is available as a Node-RED plugin. (Arduino Uno, SparkFun RedBoard, Arduino Leonardo, Arduino Mega, Arduino Fio, Arduino Micro, Arduino Mini, Arduino Nano, Arduino Pro Mini, BotBoarduino, ChipKit Uno32, Spider Robot Controller, DFRobot Romeo, Teensy 3, Intel Galileo Gen 2, Intel Galileo Gen 2, Intel Edison Arduino, Intel Edison Mini, etc.). Npm, the Node.js package manager was installed at the same time. Run the following command to install the Johnny-Five package for Node.js

npm install -g johnny-five
Note. Here we will use an Arduino/Firmata as a GPIO. If you want to use the Raspberry Pi GPIO, you will need to install the io-plugin package. The complete list is here.

A simple program to start: flashing a Led

Let’s start with a simple program to understand the working principle of Javascript and the Johnny-Five bookstore. Place yourself at the root of the SD card, create a new directory (for example nodebot) and then a new file (strobe.js for example)

cd ../..
mkdir nodebot && cd nodebot;
nano strobe.js

In Javascript, we use the require command to load dependencies. We define an object (here five) which will call the API Johnny-Five (J5).

var five = require("johnny-five"),

The first thing to do is to create a map. By default, Jonny-Five will scan the USB ports for a compatible card. In this case, there is only a simple declaration to be made

board = new five.Board();

You can have several cards attached to your Orange Pi (or Raspberry Pi). In this case you can specify the USB port, or the COM port under Windows. You can also define other parameters such as speed (baudrate), pinmode, configure the I2C bus … Everything is detailed here.

It is mandatory to wait until the card is ready before driving the led. The state is retrieved by listening to the javascript ready event. You can then call a function (s) or put code in the function.

board.on("ready", function() {
  // Code ou appel d'une autre fonction
  // Code or call other function
});

Here we will execute the code directly in the function. The LED is attached to the pin and then the pro

Then we have to define the object we want to use. Here, we will attach a Led on pin 13 of the Arduino (initialization) and then call the method strobe () which will make it flash at a frequency of 250ms.

var led = new five.Led(13);
led.strobe(250);

Finally, the led will be stopped properly when the program is stopped. To stop a script, simply type CTRL + C twice or enter .exit in the console (which is not always possible if there are many log messages). To do this, we will connect a processing by listening to the exit event. To stop the strobe, the stop() method is called. But stop simply stops all methods running by leaving the actuators in their current state. You should call led.off() to be sure to turn off the led.

board.on("exit", function(){
  led.stop();  
  led.off();
});

Paste the complete code of the project then save with CTRL + X then Y.

var five = require("johnny-five"),
board = new five.Board();   // Cree un carte J5 - create J5 board

board.on("ready", function() {
  // Cree une Led sur la broche 13 - Create an Led on pin 13
  var led = new five.Led(13);
  
  // Fait clignoter la led (on/off) avec une frequence de 100ms
  // Strobe the pin on/off, defaults to 100ms phases
  led.strobe(250);
  
  // Arrête le clignotement et éteint la led à l'arrêt (.exit)
  // Stop strobe and power off the led on .exit 
  board.on("exit", function(){
    led.stop();  
    led.off();
  });
});

Start the script with the node strobe.js  or node strobe  command. Johnny-Five searches for the Arduino card and then flashes the LED until the script is stopped with the key combination CTRL + C (2 times) or the .exit command

root@orangepilite:~/nodebot# node strobe
1489998297086 Device(s) /dev/ttyUSB0  
1489998297172 Connected /dev/ttyUSB0  
1489998298753 Repl Initialized  
>>

Start/stop the flashing of the led with a button

Let’s go a little further now. We will add a button to stop / start the flashing of the LED. It’s the Button class that handles the buttons in Johnny-Five. The complete documentation can be found here.

At the beginning of the program, we will add a variable to store the state of the led.

var ledStatus = false;

Several parameters are available to define a button. At least, the pin on which the button is connected must be indicated:

  • pin: pin
  • invert: the button logic is reversed
  • isPullup: initializes the button with a reset.
  • holdtime: time in milliseconds during which the button must be held down to trigger a “hold”
var button = new five.Button({
  pin:9,
  isPullup: true
});

You can intercept 3 events on a button:

  • hold: the button has been held for at least the time previously indicated
  • press or down: the button has just been pressed
  • up or release: button just released

Here we will intercept the event press, which will call the function strobeLed () as soon as the button

button.on("press", function(){
  strobeLed();
});

The strobeLed() function tests the state of the statusLed variable to start the blinking or to stop it.

function strobeLed(){
  if ( ledStatus == false ) {
    console.log("Start Strobe Led");
    ledStatus = true;
    led.strobe(250);
  } else {
    console.log("Stop Strobe Led");
    ledStatus = false;
    led.stop();
    led.off();
  }
}

Retrieve measurements from a BMP180 on the I2C bus,

We saw in the previous tutorial that the Multi class is in charge of the sensors returning several measurements. This is the case of the BMP180, which is used to measure atmospheric pressure and temperature.

We will create a BMP180 object that will be updated every 5 seconds (5000 ms)

var bmp180 = new five.Multi({
  controller: "BMP180",
  freq: 5000
});

Here, we will simply send to the console the measurements at each change of value (which should happen every 5 seconds).

bmp180.on("change", function() {
  console.log("Temperature BMP180   ", this.thermometer.celsius);
  console.log("Atm. Pressure BMP180 ", this.barometer.pressure);
});

We’ll see in a future tutorial how to send them to a Blynk server for example.

Complete code for the Johnny-Five project

Here is the complete code of the project that you simply paste into a new file.

var five = require("johnny-five"),
board = new five.Board();
var ledStatus = false;

board.on("ready", function() {
  // Cree une Led attachee a la broche 13 - Create an Led on pin 13
  var led = new five.Led(13);
  // Cree un bouton attache a la broche 9 - Create a button on pin 9
  var button = new five.Button({
    pin:9,
    isPullup: true
  });
  // Cree un objet multi pour le BMP180 - Create a multi object for the BMP180 sensor
  var bmp180 = new five.Multi({
    controller: "BMP180",
    freq: 5000
  });
  
  // Affiche les mesures du BMP180 dans la console - display BMP180 value on the console
  bmp180.on("change", function() {
    console.log("Temperature BMP180   ", this.thermometer.celsius);
    console.log("Atm. Pressure BMP180 ", this.barometer.pressure);
  });
  
  // Bouton appuye, demarre ou stop le strobe - Button pressed, start or stop strobe
  button.on("press", function(){
    strobeLed();
  });
  
  // arrete proprement la led a l'arret du script - clean stop the strobe when script stop
  board.on("exit", function(){
    led.stop();
    led.off();
  });
  
  // fonction qui demarre ou arrete le strobe en fonction de l'etat precedent
  // Function that start or stop the strobe depending the previous state 
  function strobeLed(){
    if ( ledStatus == false ) {
      console.log("Start Strobe Led");
      ledStatus = true;
      led.strobe(250);
    } else {
      console.log("Stop Strobe Led");
      ledStatus = false;
      led.stop();
      led.off();
    }
  }
});

Save the script (strobe2.js for example) and run it with the node strobe2.js  command. As soon as Johnny-Five has started communication with the Arduino / Firmata, you will start receiving measurements from the BMP180 and you will be able to control the LED.

# node strobe.js 
1490018472982 Device(s) /dev/ttyUSB0  
1490018473105 Connected /dev/ttyUSB0  
1490018474708 Repl Initialized  
>> Temperature BMP180    21.5
Atm. Pressure BMP180  97.483
Start Strobe Led
Temperature BMP180    21.6
Atm. Pressure BMP180  97.483

You now have a little glimpse of the power of Johnny-Five and javascript, a very powerful language and very simple to handle. The Arduino/Firmata – Johnny-Five duo makes the Orange Pi as interesting as the Raspberry Pi, but it’s always frustrating not to be able to use the raspi-io libraries.

Subscribe to the weekly newsletter

No spam and no other use will be made of your email. You can unsubscribe anytime.

  • Nimra Nimo

    can we read data from arduino sdcard using johney five?

    • Hi Nimo. I just checked and that does not seem possible. It’s a great idea, you should make a request to the development team. As the arduino is used by a “simple” gpio, developers may not see the point. What would you like to do with it?

DIY Projects