Advertisement
  1. Code
  2. JavaScript
  3. Node

Visualizing Real-Time Arduino Sensor Data With Johnny-Five and PubNub EON.js

Scroll to top
Sponsored Content

This sponsored post features a product relevant to our readers while meeting our editorial guidelines for being objective and educational.

In my previous article, I showed you how to prototype an Internet of Things system using Johnny-Five and PubNub. In that tutorial, you learned how to create a web-controlled LED, à la Philips HUE.

This time, I would like to show you how to read data from sensors attached to an Arduino and plot a graph on the web!

In this exercise, you are going to:

  1. build a circuit with a temperature sensor, and read the values from the sensor
  2. read the data and plot them
An image of the finished productAn image of the finished productAn image of the finished product

Prerequisites

You need an Arduino (Genuino) Uno board and basic knowledge of how to set up the Arduino for Johnny-Five. It is a good idea to review the Setting Up Arduino section in the step-by-step tutorial, but you do not need to install StandardFirmata because you are going to install something else this time.

Also, make sure that Node.js is running on your computer.

Easy and Simple Data Visualization With EON

Project EON is an open-source JavaScript framework for charting and mapping, created by PubNub.

Since the charting and graphing component of EON is based on C3.js, which is a wrapper for D3.js, EON allows you to build real-time graphs easily without knowing how to use the far more complicated D3 library.

The basic steps to visualize the sensor data are as simple as the following:

Publish data from a source:

1
PUBNUB.publish({
2
3
  channel:  'my-graph',
4
5
  message:  {'eon': 
6
7
  {'My data 1': 39, 'My data 2': 23}}
8
9
});
10
11
12
13
2. Embed a graph on web:
14
15
16
17
eon.chart({
18
19
  channel: 'my-graph',
20
21
  generate: {
22
23
    bindto: '#myGraph'
24
25
  }
26
27
});

I will walk through the details of how to use EON, as we work on both a hardware and a software exercise here. So let's begin!

Wiring Up the Circuit With a Temperature Sensor

Let's build a circuit for the temperature sensor first! The generic sensor and parts should be pretty inexpensive.

Hardware You Need:

  • 1 Arduino Uno
  • 1 DS18B20 1-Wire digital temperature sensor
  • 1 resistor (4.7kO)
  • 3 male/male jumper wires
  • 1 breadboard
The hardware that youll needThe hardware that youll needThe hardware that youll need

About the DS18B20 Digital Temperature Sensor

A typical DS18B20 digital temperature sensor measures from -55°C to 125°C (Celsius) with ±0.5°C accuracy over much of the range. A built-in analog-to-digital converter (ADC) converts this analog temperature measurement into a digital value with up to 12 bits of precision.

Loading Arduino With ConfigurableFirmata

The DS18B20 sensor communicates over a proprietary 1-Wire bus. When you are using devices with the special protocol, Johnny-Five requires the 1-Wire specific module, which utilizes the ConfigurableFirmata sketch.

So let's load your Arduino up with ConfigurableFirmata before wiring the sensor:

  1. Connect your Arduino to your computer with a USB cable.
  2. On Arduino IDE, go to Sketch > Include Library > Manage Libraries.
  3. Search for "ConfigurableFirmata".
  4. Click the result, select the latest version, and click Install.
  5. Go to File > Examples > ConfigurableFirmata.
  6. Upload the code to the board.
Selecting the library from the Arduino IDESelecting the library from the Arduino IDESelecting the library from the Arduino IDE
Selecting ConfigurableFirmataSelecting ConfigurableFirmataSelecting ConfigurableFirmata

Assembling a Circuit

Now, let’s wire them up. The circuit is pretty simple—just make sure that you use a 4.7kO resistor when you are powering the sensor up with the 5V source from the Arduino.

A sketch of the diagram for how well put this togetherA sketch of the diagram for how well put this togetherA sketch of the diagram for how well put this together
The assembled circuitThe assembled circuitThe assembled circuit

Reading the Temperature From the Sensor

Let's move on to the software side. Reading the digital values from the sensor is super easy when you are using Johnny-Five.

Make sure Node.js is installed on your computer. In an appropriate dev directory, install Johnny-Five using the npm package manager.

$ npm install johnny-five

Create a file, temperature.js, and use the code below to print out the values:

1
var five = require('johnny-five');
2
3
4
5
five.Board().on('ready', function() {
6
7
  var temperature = new five.Thermometer({
8
9
    controller: 'DS18B20',
10
11
    pin: 2
12
13
  });
14
15
16
17
  temperature.on('data', function() {
18
19
    console.log(this.celsius + '°C', this.fahrenheit + '°F');
20
21
  });
22
23
});

Run the code from a console with node temperature.js. Once the hardware board is ready, you should see the temperature values printed out on the console like this:

The temperature values printed out in the consoleThe temperature values printed out in the consoleThe temperature values printed out in the console

Now, let's publish the data from the temperature sensor and plot the values in a graph!

Sending the Temperature Data From the Sensor to PubNub

First, you need to install the pubnub Node.js module using npm:

$ npm install pubnub

PubNub Data Stream Network (DSN) provides the global infrastructure and allows you to build and scale real-time apps and IoT devices quite easily. In my previous article, you used PubNub to receive data from a web browser, but this time, you are using PubNub to publish the sensor data to be read in the browser.

Initializing PubNub

Once you install the pubnub module, you need to initialize it with your API keys.

1
var pubnub = require('pubnub')({
2
3
  publish_key: 'pub-c-156a...',
4
5
  subscribe_key: 'sub-c-f762f...'
6
7
});
8

Also let's create a channel name.

1
var channel = 'temperature-ds18b20';

When you plot a graph, you will need to grab the published data from the same channel name.

Publishing Data to PubNub

Once you obtain temperature data on the data event with Johnny-Five that you have created in the previous section of the tutorial, keep the data as a variable, instead of just console.log.

1
var temp = 0;
2
3
4
5
temperature.on('data', function() {
6
7
  temp = this.celsius;
8
9
});

You can publish every piece of data to PubNub, but the sensor may fire the event too frequently. So let's send the data every three seconds.

1
setInterval(publish, 3000);

In the publish function, use the PubNub publish() method to send the data in object (or JSON).

1
function publish() {
2
3
  var data = {
4
5
    'temperature': temp,
6
7
  };
8
9
  pubnub.publish({
10
11
    channel: channel,
12
13
    message: data,
14
15
  });
16
17
}

The entire code for the Arduino is available in this GitHub repo.

Plotting a Bar Graph From the Sensor Data

Now forget about Arduino. You will now create a separate web page to draw a graph.

First, include eon.css in your HTML file:

1
<link type="text/css" rel="stylesheet" href="//pubnub.github.io/eon/v/eon/0.0.9/eon.css">

Then include pubnub.js:

1
<script src="//cdn.pubnub.com/pubnub-3.10.2.js"></script>

Then create an empty element with some ID:

1
<div id="chart"></div>

This is where the graph will be generated in your page. Now, you need to initialize PubNub, just like you did in the node.js file earlier for Arduino:

1
var pubnub = PUBNUB.init({
2
3
  publish_key: 'pub-c-156a...',
4
5
  subscribe_key: 'sub-c-f762f...'
6
7
});

Then, generate a simple bar graph using EON's chart(), as soon as it receives the data from PubNub. You can receive the data sent from the temperature sensor by using the same channel name, temperature-ds18b20:

1
eon.chart({
2
3
  pubnub: pubnub,
4
5
  {
6
7
    channel: 'temperature-ds18b20',
8
9
    generate: {
10
11
      bindto: '#chart'
12
13
    }
14
15
  },
16
17
  transform: function(m) {
18
19
    return { eon: {
20
21
      temperature: m.temperature
22
23
    }}
24
25
  }
26
27
});
28

The transform() function tailors the raw data sent from the sensor to fit in the schema that EON can understand.

Run both the HTML and the Node.js code for Arduino.

Voilà, you've got a real-time data visualization in your browser!

An animation of the real-time data visualization in the browserAn animation of the real-time data visualization in the browserAn animation of the real-time data visualization in the browser

You can customize the graph more with optional C3.js parameters, such as line colors and width!

For example, to change the bar color to purple like this gif animation above, you can add the color of the data parameter:

1
...
2
3
  generate: {
4
5
    bindto: '#chart,

6


7
    data: {

8


9
      type: 'line', 

10


11
      colors: {

12


13
        temperature: '#663399'

14


15
      }

16


17
    },

You can use the axis parameter to label and format the x-axis and y-axis, too.

If you want a different kind of graph, try changing the ‘line’, which is a default value for type, to ‘spline’, and see what happens.

For the complete code, please refer the GitHub repo. There are a few more examples if you would like to try different sensors such as an ambient light sensor, and different types of charts.

I hope you enjoyed the tutorial!

References

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.