In this short guide, I will share my experience reading temperature and humidity value from a DHT22 sensor that i bought on Adafruit! This sensor needs a 4.7K – 10K resistor, you will use as a pullup from the data pin to VCC that is provided in the linked product.
Schematics:
The shematics are made with awesome tool that is Fritzing.
And photo of my setup with Arduino Yun:
.In order to interact easily with the sensor I strongly recomend you to use this library developped by Adafruit. Put the library files in your source and don’t forget to include the .hpp in your code before using.
Here is the sample code from the DHT library:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
// Example testing sketch for various DHT humidity/temperature sensors // Written by ladyada, public domain #include "DHT.h" #define DHTPIN 2 // what pin we're connected to // Uncomment whatever type you're using! //#define DHTTYPE DHT11 // DHT 11 #define DHTTYPE DHT22 // DHT 22 (AM2302) //#define DHTTYPE DHT21 // DHT 21 (AM2301) // Connect pin 1 (on the left) of the sensor to +5V // Connect pin 2 of the sensor to whatever your DHTPIN is // Connect pin 4 (on the right) of the sensor to GROUND // Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor DHT dht(DHTPIN, DHTTYPE); void setup() { Serial.begin(9600); Serial.println("DHTxx test!"); dht.begin(); } void loop() { // Reading temperature or humidity takes about 250 milliseconds! // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) float h = dht.readHumidity(); float t = dht.readTemperature(); // check if returns are valid, if they are NaN (not a number) then something went wrong! if (isnan(t) || isnan(h)) { Serial.println("Failed to read from DHT"); } else { Serial.print("Humidity: "); Serial.print(h); Serial.print(" %\t"); Serial.print("Temperature: "); Serial.print(t); Serial.println(" *C"); } } |
If you upload and test the code you’ll be able to receive on your Serial port the sensors data. Remember that calling readHumidity() and readTemperature() may be really time consuming.
In order to understand what is going on in the library, I suggest you to read this source code.
Edit: an awesome tutorial by Adafruit itself is already available here.
Leave a Reply