Reader small image

You're reading from  Building Smart Homes with Raspberry Pi Zero

Product typeBook
Published inOct 2016
PublisherPackt
ISBN-139781786466952
Edition1st Edition
Right arrow
Author (1)
Marco Schwartz
Marco Schwartz
author image
Marco Schwartz

Marco Schwartz is an electrical engineer, entrepreneur, and blogger. He has a master's degree in electrical engineering and computer science from Supélec, France, and a master's degree in micro engineering from the Ecole Polytechnique Fédérale de Lausanne (EPFL), Switzerland. He has more than five years' experience working in the domain of electrical engineering. Marco's interests center around electronics, home automation, the Arduino and Raspberry Pi platforms, open source hardware projects, and 3D printing. He has several websites about the Arduino, including the Open Home Automation website, which is dedicated to building home automation systems using open source hardware. Marco has written another book on home automation and the Arduino, called Home Automation With Arduino: Automate Your Home Using Open-source Hardware. He has also written a book on how to build Internet of Things projects with the Arduino, called Internet of Things with the Arduino Yun, by Packt Publishing.
Read more about Marco Schwartz

Right arrow

Chapter 2. Measure Data Using Your Raspberry Pi Zero Board

In the first chapter of this book, we worked on setting up your Raspberry Pi board so you can use it in your projects and realize all the projects you'll find in this book.

In this chapter, we are going to make our first project using the Zero board: measuring data using your board. We are going to learn how to connect a very simple temperature and humidity digital sensor to your Pi, and how to write software to read data from it.

From there, we'll look at some very basic applications using this sensor that can be really useful inside a smart home: how to log data on the Pi itself, how to access the measurements remotely, and finally, how to display past data on a nice plot.

Hardware and software requirements


We have already discussed most of the requirements for this project in the first chapter of this book. Here, you will simply need an additional component: a DHT11 sensor (https://www.adafruit.com/products/386). The following image shows the sensor:

You can of course use other similar sensors, for example the DHT22, which is more precise. To use a DHT22, you will only need to change one thing inside the code we'll see later.

You will also need a 4.7k Ohm resistor to make the sensor work, as well as jumper wires and a breadboard.

Hardware configuration

Let's now look at how to configure the hardware for this project; basically, how to connect the sensor to the Pi Zero board.

The following figure is a schematic to help you out:

As it's the first project we are actually building using the Raspberry Pi Zero, there is something important I wanted to point out here. To connect the board to components like this sensor here, we have two options. You can either use jumper...

Reading data from the sensor


As the first project of this chapter, we are simply going to see how to read data from the sensor. As for all the projects in this book, we'll use Node.js, which is a great framework for building projects on your Raspberry Pi Zero.

I will now go through the main parts of this first piece of code. It starts by including the DHT sensor module for Node.js:

var sensorLib = require('node-dht-sensor');

Then, we create an object to read data from the sensor and initialize it when we start the software:

var sensor = {
    initialize: function () {
        return sensorLib.initialize(11, 4);
    },
    read: function () {
        var readout = sensorLib.read();
        console.log('Temperature: ' + readout.temperature.toFixed(2) + 'C, ' +
            'humidity: ' + readout.humidity.toFixed(2) + '%');
        setTimeout(function () {
            sensor.read();
        }, 2000);
    }
};

if (sensor.initialize()) {
    sensor.read();
} else {
    console.warn('Failed to initialize...

Storing sensor data


Displaying the current measurements from the sensor is nice, but what is even better is to actually store that data inside a database. In this section, we are going to see how easy it is to do this with Node.js.

As a database, we'll simply use NeDB here, which is a really simple database for Node.js that is completely stored in memory, but you can also save the entire database in a file.

The code is actually very similar to what we saw in the previous section. However, here, we'll first import the database module, and then insert data inside the database when a measurement is done:

var Datastore = require('nedb')
  , db = new Datastore({ filename: 'path/to/datafile', autoload: true });
sdfsd
var readout = sensorLib.read();

// Log
var data = {
    humidity: readout.humidity.toFixed(2),
    temperature: readout.temperature.toFixed(2),
    date: new Date()
};
db.insert(data, function (err, newDoc) {
    console.log(newDoc);
});

// Repeat
setTimeout(function () {
    sensor...

Accessing the data remotely


In the previous projects of this chapter, we learned how to measure and store data on your Pi. However, in a smart home, the best is to be able to access data remotely, for example, from your smartphone or computer. We will see many similar examples in later chapters of this book, but in this chapter, I just wanted to give you a glimpse of what is possible.

The module we are going to use here is Express, a server framework that is really easy to use with Node.js. Express works by defining routes, which is what will be served to the client if a request is made on a specific URL.

First, we'll import Express and define a main route that will send back the temperature and humidity measurements:

var express = require('express');
var app = express();

app.get('/', function (req, res) {

  var readout = sensor.read();
  answer = 'Temperature: ' + readout.temperature.toFixed(2);
  answer += ' Humidity: ' + readout.humidity.toFixed(2);
  res.send(answer);

});

Finally, we...

Plotting the stored data


In the final project of this chapter, we are going to learn how to plot the data that was measured by the Raspberry Pi Zero board. We are actually going to combine what we did in the other projects of this chapter and add the plotting part on top of that.

As the code is quite similar to what we have already seen, I will only highlight the main changes here. First, we need to define a route for the data:

app.get('/data', function (req, res) {

  db.find({}, function (err, docs) {

    res.json(docs); 

  });

});

This will make sure that, when it is queried on this route, the server will return all the measurements stored so far inside the database.

Then, to display the plot of all the measurements, we are going to use a JavaScript called HighCharts. You can find more information about HighCharts here:

http://www.highcharts.com/

We'll include it inside an HTML file that we will place inside a folder called public, so our app can access it. This file will basically import...

Summary


In this chapter, we saw how to perform a basic task with the Raspberry Pi Zero board: measuring data. We saw how to measure data from a digital sensor, and then store this data, access it remotely, and finally even plot the data on a graph.

You can of course already use what you learned in this project and adapt it to your own projects. You can, for example, have the project measure from more sensors at the same time, for example, from a barometric pressure sensor or from a light-level sensor.

In the next chapter, we are going to apply what we have learned in this chapter to build another project with the Pi Zero: building your own home thermostat.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Building Smart Homes with Raspberry Pi Zero
Published in: Oct 2016Publisher: PacktISBN-13: 9781786466952
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Marco Schwartz

Marco Schwartz is an electrical engineer, entrepreneur, and blogger. He has a master's degree in electrical engineering and computer science from Supélec, France, and a master's degree in micro engineering from the Ecole Polytechnique Fédérale de Lausanne (EPFL), Switzerland. He has more than five years' experience working in the domain of electrical engineering. Marco's interests center around electronics, home automation, the Arduino and Raspberry Pi platforms, open source hardware projects, and 3D printing. He has several websites about the Arduino, including the Open Home Automation website, which is dedicated to building home automation systems using open source hardware. Marco has written another book on home automation and the Arduino, called Home Automation With Arduino: Automate Your Home Using Open-source Hardware. He has also written a book on how to build Internet of Things projects with the Arduino, called Internet of Things with the Arduino Yun, by Packt Publishing.
Read more about Marco Schwartz