Exercise 12 - Connecting a temperature and relative humidity sensor
1. INTRODUCTION
This sensor is very basic and slow, but is great for hobbyists who want to do some basic data logging. The DHT sensors are made of two parts, a capacitive humidity sensor and a thermistor.
In addition, a very basic chip inside does some analog to digital conversion and spits out a digital signal with the temperature and humidity. See more in adafruit.
2. HOW TO CONNECT?
Materials:
· Arduino UNO board
· Protoboard
· Some wire Jumpers
· Temperature and relative humidity sensor
· 10K ohms resitor
Looking the holes of the sensor, the left terminal and one side of 10k resistor go to 5V, the other side goes to pin 4, also connect second terminal of the sensor to this pin. The last pin is connected to ground.
EXERCISE_A (Testing the sensor)
|
3. PROGRAMMING
To use this sensor, it’s necessary to install DHT adafruit library in Arduino folder like in CONNECTING_A_LCD_(I2C)_SCREEN.
#include "DHT.h"
#define DHTPIN 4 // Arduino pin4, connected to pin2 in sensor
Read comments are always important, in this case for example you should uncomment the #define of sensor that you are going to use.
// There are DHT type sensors. Uncomment the sensor which you will go use
#define DHTTYPE DHT11 // DHT 11
//#define DHTTYPE DHT22 // DHT 22 (AM2302)
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
// Pin 1 Sensor to +5V de Arduino
// Pin 2 Sensor to HDTPIN (in this sketch pin 4)
// Pin 4 Sensor to GROUND in Arduino
// 10k resistor from pin2 of sensor to 5V in Arduino
// Initialize sensor
DHT dht(DHTPIN,DHTTYPE);
void setup(){
Serial.begin(9600);
Serial.println("Sensor test");
dht.begin();
}
On loop. First, program trying to read humidity and temperature with readHumidity() and readTemperature()functions. The read value is store in h and t variables.
void loop(){
// Wait to do meassure
delay(2000);
// Each read of sensor spends 250 milliseconds
// Read the humidity value
float h=dht.readHumidity();
// Read the temperature value in celsius (if you want Fahrenheit put TRUE into brackets)
float t=dht.readTemperature();
If read can’t be realizing program prints “Sensor read failed!”
// Validate if the sensor is sending meassures
if(isnan(h)||isnan(t)){
Serial.println("Sensor read failed!");
return;
}
To finalize, the results are printed in serial monitor.
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("temperature: ");
Serial.print(t);
Serial.println(" *C ");
}