Let's Build a Temperature Sensor with a Raspberry Pi Part 1

I had a temperature sensor in my box of things, and I wanted to know the temperature.

This is a two-part project. In this part, I connect a raspberry pi to a temperature & humidity sensor so that I can read the current temperature in my apartment.

In part 2, I set up the pi to emit the temperature and humidity data using BLE. I also made an iPhone app that can read that data.

Hardware

How To Do This

Setup the Raspberry Pi with Raspbian and Node.js.

I setup my raspberry pi zero and installed node.js following the same process in that's in my Raspberry Pi for Developers: Getting Started course

Wire up the pi to the sensor.

The next step was to wire up the temperature sensor to the pi. I used the DHT22 temperature and humidity sensor, which is a super common sensor, so there's a diagram and instructions on adafruit. Here's my setup:

  • Plug the left pin (red pin) into 5v.
  • Plug the right pin (black pin) into ground.
  • Plug the inner left pin (green pin) into a gpio pin, I chose 4. (I origianlly chose 14, but my faulty soldering made that pin unreliable)

Raspberry pi pins

Plug in the pi, and connect to it using ssh.

I used the following link to do this before I plugged in the pi: Prepare SD card for Wifi on Headless Pi.

Here's the official documentation on how to connect to a pi using ssh: https://www.raspberrypi.org/documentation/remote-access/ssh/

Install [node-dht-sensor](https://www.npmjs.com/package/node-dht-sensor)

There's a great library that makes it super easy to connect a raspberry pi to a DHT sensor. Before you can use the node-dht-sensor library, you have to install the bcm2835 c library that gives easy access to the gpio pins for libraries like node-dht-sensor. You can follow the instructions on npm, but here's the code I ran on the pi to install it:

wget http://www.airspayce.com/mikem/bcm2835/bcm2835-1.56.tar.gz
tar zxvf bcm2835-1.56.tar.gz
cd bcm2835-1.56
./configure
make
sudo make check
sudo make install

Code the app.

Now for the fun part. This app could have been written in 4 lines of javascript, so it's really not complex at all. I just npm install node-dht-sensor and wrote the following code.

const sensor = require('node-dht-sensor');

const sensorNumber = 22;
const pinNumber = 4;
sensor.read(sensorNumber, pinNumber, (err, temperature, humidity) => {
  if (err) {
    console.log("AHHHHHHHH error", err);
    return;
  }

  console.log('temp: ' + temperature.toFixed(1) + '°C, ' + 'humidity: ' + humidity.toFixed(1) +  '%');
});

Find an issue with this page? Fix it on GitHub