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 sensor'); }
You can now either copy the code inside a file called sensor_test.js, or just get the complete code from the GitHub repository for this project:
https://github.com/openhomeautomation/smart-homes-pi-zero
Next, use Terminal to navigate to the folder where the files are and type the following:
npm install node-dht-sensor
This will install the module to read data from the sensor; it can take a while, so be patient. In case it doesn't work, try using sudo
in front of the command. Next, actually start the software with the following:
sudo node sensor_test.js
This should print the readings of the sensor at regular intervals inside the terminal:
Congratulations, you can now read data from a digital sensor using your Pi Zero board! This is the first step to building sensors for your smart home.