Hi! Hope you're enjoying this blog. I have a new home at www.goldsborough.me. Be sure to also check by there for new posts <3

Wednesday, July 2, 2014

The DHT11 sensor and AVR C

The weather nodes I built involved, besides Manchester Encoding RF signals which I talked about in my last post, reading weather data. For this, I used very nice, cheap and sufficiently precise and reliable sensors known as the DHT11 sensors. This post might also be useful for people using the more reliable and more expensive DHT22s. If you don't have these sensors yet, you can grab one off Amazon for a few Euros, Dollars, Pesos, beans, seashells or whatever you use as currency in your country.

Have a read through the data sheet if you haven't yet: http://goo.gl/RWJ7KV

The only catch with these sensors is that they have their own serial protocol for fetching data. It uses only the data pin which is used for sending and retrieving signals so you have to change the data direction of the pin in between. Anyway, here's the code. It worked the first time I uploaded it. I don't think that has ever happened before haha.

It might be a good idea to note that I'm using Attiny85s @8Mhz clock speed. The data fetching does not use the <util/delay.h> header at all, it works entirely with the internal timers and is only used for my makeshift way of visualizing the data. However, that means that if your microcontroller can't run at 8Mhz you'll have to change the pre-scalers.

The GitHub repository I created: https://github.com/goldsborough/AVR-DHT11

The entire data transmission is 40 bits. The first byte is the integral part of the humidity, the second byte is the decimal part of the humidity. The third byte then is the integral part of the temperature reading and the fourth byte again the decimal part of the temperature. The last byte is the checksum which is basically the lower 8 bits of the sum of the previous four numbers.

I'm not sure the decimal bytes have any use at all because in another datasheet I read that the resolution of the readings is 1, so I think byte 2 (counting from 1, the decimal part of the humidity) and byte 4 (decimal part of the temperature) can be ignored.

Cheers, comment if you have problems or questions.

EDIT: I just noticed that the sensor wasn't responding when I applied power externally to it (It had gotten power from the In-System Programmer). I then remembered that somewhere in the datasheet I had come across this statement: "When power is supplied to the sensor, do not send any instruction to the sensor in within one second in order to pass the unstable status.". Aha! So, if you're turning the sensor on and off externally, add a one or two second delay before reading data.


  1. please post the circuit of the above code

    1. You can find the circuit in the datasheet I linked to above (http://akizukidenshi.com/download/ds/aosong/DHT11.pdf). Page 3 :)