DHT11 Temperature and Humidity Sensor Example

DHT11 Temperature and Humidity Sensor

DHT11 is a temperature and humidity sensor with a calibrated digital signal output. 
In this example it is used the DHT11 to print on the Serial port the values of temperature in Celsius degrees and humidity of the environment monitored. 
DHT11 sensor

Hardware Required

For more details visit our Store.


DHT11 example circuit 
The DHT11 sensor has four pins. Connect the first pin on left of sensor ('VCC') to  5V of your board, the second pin ('Data') to digital pin 3 and the fourth pin ('GND') to ground. 
When the connecting cable is shorter than 20 metres, a 5K pull-up resistor between the second Pin of sensor and 5V is recommended.


DHT11 exmple schematic


Connect the board to PC and upload the below code using the Arduino IDE.
The sketch includes the library DHT.h. You can download it here.
The code defines the pin 3, used to connect the sensor, as DHTPIN and also it defines the sensor used( in this case DHT11). 
In the setup it is initialized the Serial communication and it is created a table with two column: T(C) to insert the temperature in Celsius degrees and H(%)to insert the humidity. 
The loop checks the values read by sensor and it prints them on Serial Monitor.

The complete code and its detailed description are shown down.

// DHT11 Temperature and Humidity Sensors Example
#include "DHT.h"         //include DHT library
#define DHTPIN 3         //define as DHTPIN the Pin 3 used to connect the Sensor
#define DHTTYPE DHT11   //define the sensor used(DHT11)
DHT dht(DHTPIN, DHTTYPE);//create an instance of DHT
void setup() {
Serial.begin(9600);   //initialize the Serial communication
delay(6000);           //wait 6 seconds
Serial.println("Temperature and Humidity test!");//print on Serial monitor
Serial.println("T(C) \tH(%)");                   //print on Serial monitor
dht.begin();           //initialize the Serial communication
void loop() {
float h = dht.readHumidity();   // reading Humidity
float t = dht.readTemperature(); // read Temperature as Celsius (the default)
// check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t)) {  
  Serial.println("Failed to read from DHT sensor!");
Serial.print(t, 2);   //print the temperature
Serial.println(h, 2); //print the humidity
delay(2000);           //wait 2 seconds