DHT11 temperature — Arduino code
The DHT11 measures temperature and humidity together and reports both over a single data wire. It needs the DHT sensor library, which you install once from the Arduino IDE.
What you need
- • Arduino Uno
- • 1 × DHT11 module
- • 3 jumper wires
- • DHT sensor library (Adafruit)
Wiring
- 1VCC or + to 5 V
- 2GND or − to GND
- 3DATA or S to digital pin 2
- 4In the IDE: Tools → Manage Libraries → search "DHT sensor library" → Install.
The code
dht11-temperature.ino
#include <DHT.h>
#define DHTPIN 2
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
dht.begin();
}
void loop() {
float temperature = dht.readTemperature(); // °C
float humidity = dht.readHumidity(); // %
if (isnan(temperature) || isnan(humidity)) {
Serial.println("Sensor not responding");
} else {
Serial.print(temperature);
Serial.print(" C ");
Serial.print(humidity);
Serial.println(" %");
}
delay(2000); // DHT11 needs 2 seconds between reads
}Line by line
- DHT dht(DHTPIN, DHTTYPE);
- Sets up the sensor object for a DHT11 on pin 2.
- dht.begin();
- Starts talking to the sensor once, in setup().
- dht.readTemperature();
- Returns degrees Celsius. Pass true for Fahrenheit.
- isnan(temperature)
- Catches failed reads so a loose wire does not print nonsense.
- delay(2000);
- The DHT11 can only be read about once every two seconds.
When it does not work
- It prints nan or "Sensor not responding"
- Usually the data pin is on the wrong socket or the delay is too short. Check the wire and keep delay(2000).
- How accurate is a DHT11?
- About ±2 °C and ±5 % humidity. For sharper readings use a DHT22, which uses the same code with DHTTYPE DHT22.
Want the theory behind it?