Arduino Leonardo 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 collected from the sensor.

Hardware Required

  • Arduino Board
  • DHT11 Sensor
  • Wires
  • Breadboard
  • 1 resistor of 4.7KΩ


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.




The sketch includes the library DHT.h, if there isn't in your IDE 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(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

This is how the DHT11 example is shown on the new Arduino Studio. Check it out!