মূল বিষয়বস্তুতে যান
Learn/Sensing the world/Temperature and humidity (DHT11/22)
Sensing the world · Lesson
10 min read

Temperature and humidity (DHT11/22)

Read a digital sensor with a library and handle failed readings.

What You Will Learn

  • Use the DHT library
  • Check for NaN
  • Respect the sensor's sampling rate

The DHT11 and DHT22 send temperature and humidity over one data wire using their own timing protocol. The DHT library handles the details.

Arduino C++
#include <DHT.h>
DHT dht(4, DHT11);

void setup() { Serial.begin(9600); dht.begin(); }

void loop() {
  float t = dht.readTemperature();
  if (isnan(t)) { Serial.println("read failed"); }
  else { Serial.println(t); }
  delay(2000);
}
DHT11DHT22
Temperature0–50 °C, ±2 °C−40–80 °C, ±0.5 °C
Humidity20–90 %, ±5 %0–100 %, ±2 %
Max rate1 reading/s1 reading / 2 s
LCD thermometerarduino-uno
Open in Lab
UNOATmega328P: The 8-bit AVR microcontroller that runs your sketch (16 MHz, 32 KB flash, 2 KB RAM).ATmega328PUSB-B: USB connection for uploading sketches and for the Serial Monitor. Also powers the board (5 V).DC jack: Barrel jack for 7–12 V from a battery pack or adapter (centre positive).ATmega16U2: Converts USB to serial for uploads and Serial.print().RESET: Restarts your sketch from the beginning (setup() runs again).L (D13): Built-in LED connected to pin 13 (LED_BUILTIN).ON: Power indicator.5 V regulator: Turns 7–12 V from VIN/jack into a steady 5 V.16 MHz: Clock source: the microcontroller runs 16 million cycles per second.ICSP: In-circuit programming header (SPI). Used to burn a bootloader; not needed for normal uploads.27°C · 60%GNDVCCSDASCL
Note: Change temperature and humidity on the sensor. Disconnect its VCC wire to see how failures show up (NaN).

Check Your Understanding

Test what you learned in this lesson

1dht.readTemperature() returned NaN. What's the most likely cause?