Build a Apple HomeKit Temperature Sensor (DHT22) Device Using a RaspberryPI and a DHT22

40K3394

Intro: Build a Apple HomeKit Temperature Sensor (DHT22) Device Using a RaspberryPI and a DHT22

I was looking for a low cost temperature / humidity sensor I could use to monitor what is happening in my crawlspace, as I found that this spring it was very wet, and had a lot of damp. So I was looking for a reasonably priced sensor that I could put down there, and monitor remotely. After doing some digging on the net for what was available locally and shown to work with a RaspBerry PI and a NodeMCU ( more on this later ). I decided on a DHT22 Sensor. It was cheap, offered both temperature and humididty and available locally.

Update April 2019 - After several years of using the pigpiod library, I have switched to the bcm2835 library and have published new instructions here. https://github.com/NorthernMan54/homebridge-dht/blob/master/Build.md

Update December 2016 - After running these for a few months, I have found that the accuracy of the humidity sensor varies greatly over time and have stopped trusting these for reasonably accurate humidty information. And am changing all my devices over to the Bosch BME280 Temperature/Humidity/Barometric Pressure sensor. So I have created a new instructable showing how to connect this sensor to the RaspberryPI ( Connect Your RaspberryPI to the BME280 Temperature and NodeMCU/ESP8266 ( Homebridge-MCUIOT ).

STEP 1: Parts List

So I went to my local parts store, and purchased

1 - DHT22 / AM2303 Temperature / Humidity Sensor

1 - 4.7K Resistor

4 Pin Female header ( Sensor side )

5 Pin Female header ( RPI Side )

Heatshrink tubing narrow, and wide

Old serial mouse

To wire the sensor to PI, I used the cable from an old serial mouse I had lying around. Any used cable could be used, as long at it has 3 wires. The one I used had a couple of wires, but I used the Red, Yellow and Black to keep things simple.

STEP 2: Prepare the RPI End of the Cable

I then soldered the pins to my wire. The pins I had were crimp ones, but I couldn't get them to crimp correctly, so I went with solder instead.

After soldering the pins, I then inserted them into the 5 Pin Female header, with the Red in 1, Yellow in 4, and Black in 5.

RPI Connection is wired like this


RPI -> 5 Pin Header -> Description -> Wire Colour

1 -> 1 -> 3.3 VDC Power -> Red

7 -> 4 -> GPIO4 -> Yellow

9 -> 5 -> Ground -> Black

STEP 3: Sensor End of the Cable

At this end we use the 4 Pin female header, the resistor and the heat shrink tubing.

Solder the red and yellow wires each to a pin, and put the resistor between them as well. Also cover these with heat shrink so you don't get a short. Then solder the black wire to a pin as well. Insert the pins into the 4 Pin header as follows

1 - Red

2 - Yellow

3 - Empty

4 - Black

Then cover the wires with the larger heat shrink tubing.

STEP 4: Connecting the Cables

With your RPI powered off, carefully connect the 5 pin female to the GPIO connection, with the Red wire in pin 1 lining up with pin 1 on the GPIO connector. The header should only cover the first 5 odd numbered GPU pins.

For the sensor side, align the pins on the sensor with the header, and ensure that pin 1 of the sensor ( on the left side ), connects with pin 1 of the header ( with the red wire ).

After putting the heat shrink on, I couldn't see the wire colour anymore, so I marked it with a sharpie.

STEP 5: Installing the Homebridge Software

As their are a lot of other guides for setting up a raspberry pi, I'm not going to repeat this here, but am assuming that you have your RPI setup with Raspbian Jessie, with Node.JS installed and homebridge running. Their are a number of homebridge getting started guides around covering this already.

STEP 6: Install Homebridge-dht

1. Install homebridge-dht with the command

sudo npm install -g homebridge-dht

2. Update your config.json file in ~/.homebridge with the following

{    "bridge": {
     "name": "Penny",
     "username": "CC:22:3D:E3:CD:33",
     "port": 51826,
     "pin": "031-45-154"
    },

"description": "HomeBridge",

"platforms": [],

"accessories": [
        { "accessory": "Dht",
        "name": "dht22",
	"name_temperature": "Temperature",
	"name_humidity": "Humidity",
	"service": "dht22" }

]}

STEP 7: Installing PIGPIO

1. Install the pigpiod library via these commands

sudo apt-get update

sudo apt-get install pigpio python-pigpio python3-pigpio

2. Copy dht22 to /usr/local/bin/dht22, and make executable.

With the installation on my RPI, it is located in /usr/lib/node_modules/homebridge-dht. Your installation may place it in a different location. Please check with

ls -l /usr/lib/node_modules/homebridge-dht/dh22

sudo cp /usr/lib/node_modules/homebridge-dht/dht22 /usr/local/bin/dht22

sudo chmod a+x /usr/local/bin/dht22

3. At this point you should be able to test your DHT22 sensor with the command

dht22

And it should respond with

0 18.4 C 51.0 %

STEP 8: Raspberry PI CPU Temperature Monitoring - Optional

This is an optional step, that allows you to remotely monitor the temperature of your raspberry PI CPU as well.

1. Create a file in /usr/local/bin/cputemp containing

#!/bin/bash<br>cpuTemp0=$(cat /sys/class/thermal/thermal_zone0/temp)
cpuTemp1=$(($cpuTemp0/1000))
cpuTemp2=$(($cpuTemp0/100))
cpuTempM=$(($cpuTemp2 % $cpuTemp1))

echo $cpuTemp1" C"

2. Make file executable

chmod a+x /usr/local/bin/cputemp

3. Update your config.json file in ~/.homebridge and replace the accessories section with the following:

"accessories": [
        { "accessory":          "Dht",
          "name":               "cputemp",
          "service":        "Temperature" },
        { "accessory":          "Dht",
        "name":               "Temp/Humidity Sensor",
        "service":            "dht22" }
    ]

STEP 9: Start Homebridge

Start homebridge, and your log file should look like this

[6/21/2016, 9:37:31 PM] Loaded plugin: homebridge-dht
[6/21/2016, 9:37:31 PM] Registering accessory 'homebridge-dht.Dht'

[6/21/2016, 9:37:31 PM] ---

[6/21/2016, 9:37:31 PM] Loaded config.json with 2 accessories and 0 platforms.

[6/21/2016, 9:37:31 PM] ---

[6/21/2016, 9:37:32 PM] Loading 0 platforms...

[6/21/2016, 9:37:32 PM] Loading 2 accessories...

[6/21/2016, 9:37:32 PM] [cputemp] Initializing Dht accessory...

[6/21/2016, 9:37:32 PM] [cputemp] INIT: cputemp

[6/21/2016, 9:37:32 PM] [Temp/Humidity Sensor] Initializing Dht accessory...

[6/21/2016, 9:37:32 PM] [Temp/Humidity Sensor] INIT: Temp/Humidity Sensor

Scan this code with your HomeKit App on your iOS device to pair with Homebridge:

┌────────────┐

│ 031-45-154 │

└────────────┘

[6/21/2016, 9:37:32 PM] Homebridge is running on port 51826.

STEP 10: Testing With Home Kit

Fire up your favourite homekit client, and pair with your new accessory. You should then see the new Temperature/Humidity Sensor.

If you have problems or issues, please raise an issue on GitHub

STEP 11: Bonus Chapter - Dual Sensors

After being asked by several people I thought I would include the notes needed to add a second sensor.

For the wiring, take a look at the at the attached image, this is the one that I shared with Hector305 to connect the second sensor.

And for the updated config file, this is config.json for that.

{ "accessory":   "Dht",

  "name":        "dht22 - indoor",
  "name_temperature": "Indoor Temperature",
  "name_humidity": "Indoor Humdity",
  "gpio":        "4",       
  "service":     "dht22" },
 { "accessory":   "Dht",
  "name":        "dht22 - outdoor",
  "name_temperature": "Outdoor Temperature",
  "name_humidity": "Outdoor Humdity",
  "gpio":        "2",   
  "service":     "dht22" }

57 Comments

if you are using SEN0137 by DFrobot with the DHT22 sensor on board, it alread has the resistor and 3 pins sorted for you. The included coloured wires to raspberry pi pins are
Red > pin 1
Green > pin 7
Black > pin 9

It took me ages to work this out and i only got it right with dumb luck so i hope this helps
Can you help me figure out what is happening?

I have errors in homebridge
[2019-3-3 21:30:01] [dht22] DHT Status: 2, Temperature: 0, Humidity: 0
[2019-3-3 21:30:01] [dht22] Error: dht22 read failed with status 2

Sometimes temperature is read correctly. I'm sure that DHT11 is working fine as from AdaFruit DHT is read correctly if I will check this sensor using this script. From your script I have correct reply only on 5% of request.

Next:

[2019-3-3 21:31:01] [dht22] Error: dht22 read failed with status 2 <-- this reply is more often, due that temperature is not displayed correctly in Home app.
[2019-3-3 21:32:01] [dht22] DHT Status: 0, Temperature: 26, Humidity: 38

hey,

thanks for this tutorial, but I get this err:

Error: spawn EACCES
at _errnoException (util.js:1022:11)
at ChildProcess.spawn (internal/child_process.js:323:11)
at exports.spawn (child_process.js:502:9)
at exports.execFile (child_process.js:212:15)
at DhtAccessory.getDHTTemperature (/usr/local/lib/node_modules/homebridge-dht/index.js:85:5)
at DhtAccessory.getServices (/usr/local/lib/node_modules/homebridge-dht/index.js:213:14)
at Server._createAccessory (/usr/local/lib/node_modules/homebridge/lib/server.js:410:36)
at Server._loadAccessories (/usr/local/lib/node_modules/homebridge/lib/server.js:298:26)
at Server.run (/usr/local/lib/node_modules/homebridge/lib/server.js:87:38)
at module.exports (/usr/local/lib/node_modules/homebridge/lib/cli.js:45:10)

Any ideas. Thank you!
If you google the error message "Error: spawn EACCES", it indicates a permission/access on the DHT22 executable. Try this from the directory with the dht22 command

sudo chmod a+rwx dht22

I'm following all steps but when I call the "dht22" it doesn't work. I've formated my RPI for four times, but the error it is the same. Bellow there are the steps that I reproduced:

1. sudo npm install -g homebridge-dht

2. Update my config.json

3.sudo apt-get update

4.sudo apt-get install pigpio python-pigpio python3-pigpio

6. sudo cp /usr/lib/node_modules/homebridge-dht/dht22 /usr/local/bin/dht22 (I've checked the path as mentioned)

7.sudo chmod a+x /usr/local/bin/dht22

8. dht22 and...

... Doesn't work!

Where is my mistake?

I really appreciate any help.

Best,

Thiago

I think the challenge is with step 6, and that some installs are a little bit different. Do you know which directory homebridge-dht was installed into? dht22 should be there

Step 7 ..... there is a lot missing in the tutorial

Yeah originally I had instructions pointing directly how to download and compile the binary but had to remove that after the website with the source code was no longer available. I made some minor changes to the text now, does it make sense?

Error: dht22 read failed with status 2

It looks like something isn't working here...

The status's are

#define DHT_GOOD 0

#define DHT_BAD_CHECKSUM 1

#define DHT_BAD_DATA 2

#define DHT_TIMEOUT 3

Check your wiring and connection to the DHT.

What I need to copy and rename for what ?

Sorry just saw this message, and I fixed the instructions.

What I need to copy and rename for what ? In the step with DTHXXD Step 7

Sorry just saw this message, and I fixed the instructions.

On step 7 a few sub steps are missing :-( please update!!

I just fixed it, it should be fine now. I had changed the process for making the executable from manual build, to including the executable in the supplied code base.

Hi I'm very new to this and have limited code knowledge. Im stuck on step 6 i got to the step of sudo apt-get install pigpio python-pigpio python3-pigpio and downloaded the DHT22 sample code but I'm stuck on this bit. Apply this patch to test_DHTXXD. This adds units to the response, and adds an error when pigpiod is not running.

diff test_DHTXXD.c orig/test_DHTXXD.c

128c128

< printf("%d %.1f C %.1f %%\n", r.status, r.temperature, r.humidity);

---

> printf("%d %.1f %.1f\n", r.status, r.temperature, r.humidity);

158,160d157

< } else {

< fprintf(stderr, "ERROR: pigpiod not running\n");

< return 1;

Compile with this command

gcc -Wall -pthread -o DHTXXD test_DHTXXD.c DHTXXD.c -lpigpiod_if2

Copy DHTXXD to /usr/local/bin/dht22, and make executable.

At this point you should be able to test your DHT22 sensor with the command

dht22

And it should respond with

0 18.4 C 51.0 %

I would appreciate your input

Regards Aaron

Aaron,

I went back and changed the patch instructions, and hopefully made them easier to follow this time. And I have included the patch file as part of the homebridge plugin, so you will need to run sudo npm install -g homebridge-dht before following the instructions.

Hi, I'm also new to this and am having some trouble with step 6. I completed "sudo apt-get install pigpio python-pigpio python3-pigpio," but now I'm stuck on "Copy, and rename DHTXXD to /usr/local/bin/dht22, and make executable." Where can I find the file "DHTXXD"? I also don't know where to find the DHT22 sample code Aaron is mentioning above, or the patch instructions. I would really appreciate some direction here. Thanks so much, Shaun
More Comments