Shares
Monitor Your Home With the Raspberry Pi B+

Monitor Your Home With the Raspberry Pi B+

Last Update: / by Marco Schwartz

There are lots of devices on the market that allow you to monitor your home from a central interface. In this article, we are going to make our own DIY version of such devices. To do so, we will use the latest Raspberry Pi board, the B+ model, and the official Raspberry Pi camera module. We will also perform some measurements from a temperature and humidity sensor. I acquired most of the components that I used for this article from NewarkAt the end of the article, you will be able to build an interface to access the camera and the sensor recordings from a single page. Let’s dive in!

Hardware & Software Requirements

The first thing that you will need for this project is a Raspberry Pi B+. I used a B+ model as it is the latest version available to date. It also has nice features (like 4 USB ports), but of course, you can also use an older version.

You will need the official Raspberry Pi camera module to capture pictures. You will use a DHT11 (or DHT22) sensor to measure the temperature and humidity in your home.

Since we will access the Rapsberry Pi remotely, you will need a simple USB WiFi dongle.

You also need to secure an Adafruit Cobbler kit, a breadboard, and some jumper wires. You will need these to make the connections between the Raspberry Pi, the camera and the sensor.

Below is the list of the required components for this project:

Check if you already have a Linux Distribution installed on your Raspberry Pi. This is to ensure that you have a completely functional Pi. I used Raspbian for this project.

If this is not done yet, you can find an excellent guide on this address:

http://www.raspberrypi.org/help/quick-start-guide/

Connect the Raspberry Pi to your local WiFi network and install a driver for the BCM2835 chip to read the data from the DHT11 sensor.

You can download & install these drivers by following the instructions on this page:

http://www.raspberry-projects.com/pi/programming-in-c/c-libraries/bcm2835-by-mike-mccauley

The whole project is based on Node.js. It will act as a server from which we can access all the functions of our Raspberry Pi.

If it is not done yet, you will have to install Node.js on your Pi. Be wary. You just can’t use apt-get to install the node package module since you might be installing an older version. To install the latest version of Node.js, follow this guide:

http://revryl.com/2014/01/04/nodejs-raspberry-pi/

You will also need to install drivers for the BCM2835 chip. You can download & install these drivers by visiting this page:

http://www.airspayce.com/mikem/bcm2835/

After this, download the files for this project on GitHub:

https://github.com/openhomeautomation/rpi-web-control

To access the Raspberry Pi on your local WiFi network via rapsberrypi.local, we need to install some packages. We do this so that we wouldn’t need to access the Pi via its IP address anymore.

For the rest of the article, you can either log into your Raspberry Pi via SSH or go directly to your Pi and type the following commands:

sudo apt install avahi-daemon netatalk

Hardware Configuration

If you have followed the instructions above, it would be easier to proceed with the assembly of your Pi. Let’s now add the other components.

First, we will connect the camera. Follow the instructions on the Raspberry Pi website for an easy install:

http://www.raspberrypi.org/documentation/usage/camera/README.md

Below is a picture of the camera I used. Next to it is my Raspberry Pi:

Monitor Your Home With the Raspberry Pi B+

Note that I have used a plastic case for my Raspberry Pi. It is not required for this project though.

Moving forward, we will connect the DHT11 sensor to the Raspberry Pi via the Cobbler kit. After you have assembled your kit, connect it to the Raspberry Pi GPIO connector. Connect the other side of the cable to the breadboard via the PCB adapter.

For the DHT11 sensor, look first for the pinout of the sensor:

Monitor Your Home With the Raspberry Pi B+

Connect the VCC pin to the Raspberry Pi 3.3V pin, GND to GND, and DATA to pin number 4 on the GPIO connector. Finally, connect the 4.7K Ohm resistor between the VCC and DATA pins. The picture below shows the final result for the sensor:

Monitor Your Home With the Raspberry Pi B+

Testing the Sensor & the Camera

We are now going to test the sensor first, and then the camera.

Because we want to build an application based on Node.JS, we will use the Node to interface with the DHT11 sensor. To do so, we will use a specialized Node module that already exists.

You will find everything under a folder called sensors_test inside the code of the project. Below is the complete code for this part:

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

var dht_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 () {
            dht_sensor.read();
        }, 2000);
    }
};

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

The code starts by importing the required module for the DHT sensor. Then, every 2000 ms, we read data from the sensor, and display it inside the terminal using console.log(). The code for this part is available in the GitHub repository of the project:

https://github.com/openhomeautomation/rpi-web-control

It’s now time to test the code. After downloading the code from GitHub, go to the sensors_test folder, and type:

sudo npm install node-dht-sensor

This might take a while, so be patient. After it loads, type:

sudo node sensors_test.js

You should see the values of the temperature and humidity printed in the terminal:

Temperature: 21.00C, humidity: 35.00%

The camera is much easier to test. Simply go to a terminal window and type:

raspistill -o cam.jpg

You can then go to the folder where you executed this command. You should be able to see that a picture was created as cam.jpg.

Monitoring Your Home via WiFi

We are now going to write an application based on Node.js to remotely track the measurements from the sensor and the camera. There are basically three main parts in the code: (1) the server code in Javascript, (2) the HTML page which will contain the interface, and (3) a client-side Javascript file which will link the two.

[Node.js course]

Let’s look at the server-side Javascript code first. It starts by including the required Node modules: (1) the node-dht-sensor module to handle the DHT sensor as before and (2) Express to handle HTTP communications like a web server. Below is the code:

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

We also include the views and public directory. The views directory is where we will store the interface, while the public directory is where we will put both the Javascript code and the recorded pictures:

app.set('views', __dirname + '/views')
app.set('view engine', 'jade')
app.use(express.static(__dirname + '/public'))

We will create a route for the interface, which will allow us to access the our project:

app.get('/interface', function(req, res){
    res.render('interface');
});

We will include the Raspberry Pi version of the aREST API (http://arest.io/) for us to control the Raspberry Pi via HTTP:

var piREST = require('pi-arest')(app);

We also give an ID and a name to your Pi:

piREST.set_id('1');
piREST.set_name('my_RPi');

Finally, we call the app.listen() function to start our application:

var server = app.listen(3000, function() {
    console.log('Listening on port %d', server.address().port);
});

The interface itself is written in Jade (http://jade-lang.com/). This will give us an HTML file as a result. The file is stored in the view directory inside the application. We add some title, some containers for the sensor measurements, and a field for the picture which will be recorded by the camera:

doctype
html
  head
    title Raspberry Pi Interface
    script(src="/js/jquery-2.0.3.min.js")
    script(src="/js/interface.js")
    link(rel='stylesheet', href='/css/style.css')
  body
    header
      div.mainContainer
        h1 Raspberry Pi Interface
        h2 Sensor Readings
        p Temperature: 
          span#temperature 0
          span  C
        p Humidity: 
          span#humidity 0
          span  %

        h2 Camera
        img#camera(src='')

As you can see on the code, we will include a Javascript file and a jQuery inside the Jade template. The script file will call the Raspberry Pi aREST API every 2000 ms to refresh the measurements of the DHT11 sensor:

setInterval(function() {

  // Update temperature
  $.get("/temperature", function(data) {
    $("#temperature").html(data.temperature);
  });

  // Update humidity
  $.get("/humidity", function(data) {
    $("#humidity").html(data.humidity);
  });
  
}, 2000);

And every 10 seconds, the camera will take a picture:

setInterval(function() {

  // Take picture
  $.get("/camera/snapshot");
  
}, 10000);

This picture inside the interface will refresh every second:

setInterval(function() {

  // Reload picture
  d = new Date();
  $("#camera").attr("src","pictures/image.jpg?" + d.getTime());
  
}, 1000);

It is now time to test the interface. Go to the pi_node folder and type:

sudo npm install node-dht-sensor express pi-arest jade

Wait a bit; it can take a while.

Then, type:

sudo node pi_node.js

Finally, go to your favorite web browser and type:

http://raspberrypi.local:3000/interface

On your Pi, you can just type:

http://localhost:3000/interface

You should see the interface of the project displaying the following:

Monitor Your Home With the Raspberry Pi B+

Be patient in waiting for the measurements and the picture to appear on the display. Remember, there is a 2-second delay for the sensor measurements and a 10-second delay for the picture.

Also, note that the Node.js module for the camera module is not perfect. In my system, I had a delay between the moment the picture was taken and the moment it appeared on the display.

Congratulations, you can now remotely access measurements from your Raspberry Pi and the camera!

How to Go Further

We built a Node.js-based application to automatically access the measurements coming from sensors. We also used a Node.js module to access the camera module of the Raspberry Pi. Finally, we displayed everything on a nice web interface.

You can go further with this project by including more sensors to the project. For example, you can add light level sensors and motion sensors. It is then quite easy to display the state of these sensors in the Node.js application. We will expand this project in the future so it uses Socket.IO for it to be remotely controlled from anywhere in the world.

If you liked what you read in this article, note that you can also find several projects using the Raspberry Pi for home automation purposes in my Home Automation with the Raspberry Pi book.

Again, I wanted to mention that I acquired most of the components that I used for this article from Newark, that I really recommend to get your Raspberry Pi and other related components.

Did you build similar projects in your home using the Raspberry Pi? If you have already tried building this project, please feel free to share your experiences in the comments!

Want to learn more? Get my free eBook about the Raspberry Pi!
The Raspberry Pi is a powerful board that can be used for all sorts of projects. Download today my free eBook "Build a Simple Thermostat with the Raspberry Pi". Simply click on the button below!

Leave a Comment

Please enter your name.
Please enter your email.
Please enter your comment.
Asmau Bilbis 4 years ago
After running sudo node sensors_test.js i get temp:0 humidity:0 and it goes on non stop
Reply
Please enter your name.
Please enter your email.
Please enter your comment.
Marco Schwartz Asmau Bilbis 4 years ago
This seems to me like you have a connection problem between the sensor & the Pi. Check the cables & the pin on which the sensor is connected to.
Leo Li 4 years ago
Hi Thanks so much for sharing this interesting topic. Seems I am having issue to install node-dht-sensor as after I enter npm install node-dht-sensor it goes:ACTION Regenerating Makefilemake: Warning: File '../../../../.node-gyp/0.12.6/common.gypi' has modification time 4989761 s in the future..and keeps going. End less... is this normal? I installed bcm2835 Lib via: http://www.airspayce.com/mi...Many thanks,
Reply
Please enter your name.
Please enter your email.
Please enter your comment.
Marco Schwartz Leo Li 4 years ago
You're welcome :) I didn't notice warnings during the compilation of the library, but I guess that's ok.
pipi 4 years ago
hello Marco,I tried sensor_test.js and it burnt my dht11 :( before running the program it was ok but when I ran it it heated and burntI don't know why :'(
Reply
Please enter your name.
Please enter your email.
Please enter your comment.
Marco Schwartz pipi 4 years ago
Sounds like a wiring problem or a problem with the DHT sensor, I don't see how the code could burn a sensor.
Lazy Colonel 5 years ago
Hello,Thanks for this amazing tutorialBut I have a question.. Can we use gauges for temperature or humidity? Does it require a lot of changes?
Reply
Please enter your name.
Please enter your email.
Please enter your comment.
Marco Schwartz Lazy Colonel 4 years ago
Hey, thanks! No it will be nearly the same, just look online and you should find some nice jQuery gauges :)
pellson60 5 years ago
I have this error massage in browser and terminal.In the terminal temp. and humidity value ar printed every two second. It looks like the program is running ok. I use a Raspberry Pi 2.Error: Cannot find module 'jade' at Function.Module._resolveFilename (module.js:336:15) at Function.Module._load (module.js:278:25) at Module.require (module.js:365:17) at require (module.js:384:17) at new View (/home/pi/rpi-web-control-master/pi_node/node_modules/express/lib/view.js:50:49) at EventEmitter.app.render (/home/pi/rpi-web-control-master/pi_node/node_modules/express/lib/application.js:545:12) at ServerResponse.res.render (/home/pi/rpi-web-control-master/pi_node/node_modules/express/lib/response.js:938:7) at /home/pi/rpi-web-control-master/pi_node/pi_node.js:13:9 at Layer.handle [as handle_request] (/home/pi/rpi-web-control-master/pi_node/node_modules/express/lib/router/layer.js:82:5) at next (/home/pi/rpi-web-control-master/pi_node/node_modules/express/lib/router/route.js:110:13)
Reply
Please enter your name.
Please enter your email.
Please enter your comment.
Marco Schwartz pellson60 5 years ago
Just add sudo npm install jade from the folder where your app.js is located :)
Fred 5 years ago
Hi Marco,I want to combine this with another tutorial, which controls LED. I simply add the none overlapped codes together in app.js, interface.js and interface.html. But these to tutorials are different in data query. This one uses piREST variables, but LED uses another way, using var queryData = url.parse(request.url, true).query.....It turns out that, the sensor and camera work well, but the switches don't work. I can't control my LEDs. I can only control them after deleting var piREST = require('pi-arest')(app); piREST.set_id('1'); piREST.set_name('my_RPi'); and the "//make measurements from sensors" part. Of course, in this way, I can't read data from my sensor and camera, but I can control my LEDs.Can you help me with this? What I need to modify for the LED part or Sensor and camera part? So I can control LEDs as well as reading the data.Look forward to your reply!! Many thanks.
Reply
Please enter your name.
Please enter your email.
Please enter your comment.
Marco Schwartz Fred 5 years ago
Hi Fred! Well, you should be able to do everything from within pi-aREST. From the interface.js file you can just call the route "/digital/5/1" to control GPIO pin 5 for example. You can also learn more on:http://arest.io/pi/Good luck with your project!
Alex 5 years ago
Hello Marco,Interesting tutorial - many thanks for that.However, I am stuck at rendering HTML. When I go to localhost:3000/interface, all I get is{"id":"1","name":"my_RPi","hardware":"rpi","connected":true}Any idea what I should double check?Many thanksAlex
Reply
Please enter your name.
Please enter your email.
Please enter your comment.
Bart Vijgen Alex 5 years ago
i have same problem. hope you get an answer. i reinstalled everything on diferent sd card and same problem
Marco Schwartz Alex 5 years ago
Hi Alex, thanks! Strange indeed. Well there is no HTML in the project but Jade, which is in charge of generating the interface. Try to check if you have the latest files from the GitHub repository of the project & that you have Jade installed.
KPSNP-NJ 5 years ago
I am sorry to bother you again. We got past the last error (thanks for your quick reply on the missing code) but now have a new error when trying to contact the sensor. See below. Any ideas for what to do about [email protected] ~/rpi-web-control $ ls -ltotal 12drwxr-xr-x 4 pi pi 4096 Jan 3 21:36 pi_node-rw-r--r-- 1 pi pi 68 Jan 3 21:36 README.mddrwxr-xr-x 2 pi pi 4096 Jan 3 21:36 [email protected] ~/rpi-web-control $ sudo node sensors_testmodule.js:340 throw err; ^Error: Cannot find module '/home/pi/rpi-web-control/sensors_test' at Function.Module._resolveFilename (module.js:338:15) at Function.Module._load (module.js:280:25) at Function.Module.runMain (module.js:497:10) at startup (node.js:119:16) at node.js:929:3
Reply
Please enter your name.
Please enter your email.
Please enter your comment.
KPSNP-NJ KPSNP-NJ 5 years ago
I solved this myself. I did "cd sensors_test" and then did the command "sudo node sensors_test.js" and it worked. It apparently only works when you run it from the directory where the program is stored.Will this matter for future use?
Marco Schwartz KPSNP-NJ 5 years ago
sensors_test is a folder, you need to go inside it and enter the same command :)
KPSNP-NJ 5 years ago
I just tried to build the sensor code on a new Raspberry pi but got a make error as shown below. Any ideas why?# sudo npm install node-dht-sensor/> [email protected] install /home/pi/node_modules/node-dht-sensor> node-gyp rebuildmake: Entering directory '/home/pi/node_modules/node-dht-sensor/build' CXX(target) Release/obj.target/node-dht-sensor/...../node-dht-sensor.cpp:21:21: fatal error: bcm2835.h: No such file or directorycompilation terminated.node-dht-sensor.target.mk:80: recipe for target 'Release/obj.target/node-dht-sensor/... failedmake: *** [Release/obj.target/node-dht-sensor/...] Error 1make: Leaving directory '/home/pi/node_modules/node-dht-sensor/build'gyp ERR! build error gyp ERR! stack Error: `make` failed with exit code: 2gyp ERR! stack at ChildProcess.onExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:267:23)gyp ERR! stack at ChildProcess.emit (events.js:98:17)gyp ERR! stack at Process.ChildProcess._handle.onexit (child_process.js:820:12)gyp ERR! System Linux 3.12.35+gyp ERR! command "node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"gyp ERR! cwd /home/pi/node_modules/node-dht-sensorgyp ERR! node -v v0.10.35gyp ERR! node-gyp -v v1.0.1gyp ERR! not oknpm ERR! [email protected] install: `node-gyp rebuild`npm ERR! Exit status 1npm ERR! npm ERR! Failed at the [email protected] install script.npm ERR! This is most likely a problem with the node-dht-sensor package,npm ERR! not with npm itself.npm ERR! Tell the author that this fails on your system:npm ERR! node-gyp rebuildnpm ERR! You can get their info via:npm ERR! npm owner ls node-dht-sensornpm ERR! There is likely additional logging output above.npm ERR! System Linux 3.12.35+npm ERR! command "/usr/local/bin/node" "/usr/local/bin/npm" "install" "node-dht-sensor"npm ERR! cwd /home/pi/rpi-web-control/sensors_testnpm ERR! node -v v0.10.35npm ERR! npm -v 1.4.28npm ERR! code ELIFECYCLEnpm ERR! not ok code [email protected]:/home/pi/rpi-web-control/sensors_test#
Reply
Please enter your name.
Please enter your email.
Please enter your comment.
Marco Schwartz KPSNP-NJ 5 years ago
This is because you don't have the library for the BCM2835 chip. You can download it & follow the instructions from: http://www.airspayce.com/mi...I also added the link into the article.
Doug 5 years ago
This fails on my system: node-gyp rebuild Can you help with this? I cloned files twice with no luck or is this for B+ only ? I'm using B
Reply
Please enter your name.
Please enter your email.
Please enter your comment.
Marco Schwartz Doug 5 years ago
No, this should works for B (and A/A+ as well). Make sure that all the packages on your Raspberry Pi are up to date, and to start every command with sudo.
Bart Vijgen 5 years ago
Hi. Seems my webserver is not working properly. when i run sudo node pi_node.js. i get readings on console. But when i access file by http, i get{"id":"1","name":"my_RPi","hardware":"rpi","variables":{"temperature":"20.00","humidity":"37.00"},"connected":true}I dont know where to look.
Reply
Please enter your name.
Please enter your email.
Please enter your comment.
Marco Schwartz Bart Vijgen 5 years ago
The answer from the web server looks good! What is the problem exactly, the interface is not working?