If you want to measure temperature and humidity and process them using an Arduino, the best way to do that is to use a DHT sensor. You can either use DHT11 or DHT22 depending on your application.





DHT sensors give digital output, so you can connect it to any digital pins on the Arduino.





DHT11 vs DHT22

DHT11 is much cheaper and can measure temperature and humidity every second. But it's accuracy is low at about ±2°C temperature and 5% humidity. It has a measuring range of 0°C to 50°C for temperature and 20% to 80% for humidity.

DHT22, on the other hand, is expensive and can give you a new output only after 2 seconds from the last one. But it's accuracy is high about ±0.5°C temperature and 2-5% humidity. It has a measuring range of -40°C to +125°C for temperature and 0% to 100% for humidity.

Depending on your project you have to choose either a DHT11 or DHT22 sensor. The code for both sensors is pretty much the same.

I am using DHT22 sensor in my project. If there is any difference in the code I will mention it as a comment.



CONNECTING DHT SENSOR TO A ARDUINO DHT sensors come with 4 pins. Vcc, GND, data pin and a no connection pin. You have to connect Vcc to 5v pin, GND to GND pin and data to any digital pin on the Arduino. A pull-up resistor of 5-10K ohm resistance should be connected between the data pin and the digital pin for keeping the data line high.







But some DHT sensors come with breakout boards with three pins and these sensors have the pull-up resistors on their board. So you should not add any external resistance. you can refer to the above pictures to see the difference.









I connected the data pin to pin 7 on the Arduino. If you are using a 4-pin DHT sensor, You should connect the pull-up resistor. Otherwise, it will not work.



SOURCE CODE

Here is the source code for reading temperature and humidity from a DHT22 sensor and to print it on the serial monitor. You have to install both the Adafruit Unified Sensor library and the DHT Sensor library.

You can find it in the library manager in Arduino IDE.