Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 37 ยท Sensors and Actuators

Temperature and Humidity Sensors (DHT and TMP36)

Read temperature and humidity with an Arduino: wire an analog TMP36 and a digital DHT22, convert raw readings to units, and smooth noisy data with averaging.

Almost every Arduino project that touches the real world starts with a sensor. Temperature and humidity are the classic first two: they change slowly, they are cheap to measure, and they teach you the two main ways a sensor can talk to a board. An analog sensor such as the TMP36 changes an output voltage that you measure with analogRead(). A digital sensor such as the DHT11 or DHT22 contains a tiny chip that measures, converts and sends you finished numbers as a stream of pulses.

This site cannot run an Arduino board or the Arduino IDE. The Arduino sketches below are real code but are shown read-only. The runnable examples are plain C programs, labelled as stand-ins, that reproduce the arithmetic and the data decoding so you can experiment with the ideas in your browser.

The analog route: TMP36

The TMP36 has three pins: supply, signal and ground. It outputs 10 mV per degree Celsius with a 500 mV offset, so 25 degrees Celsius gives 750 mV. On a 5 V board with a 10-bit ADC (1024 steps), one step is about 4.88 mV.

C++
const int SENSOR_PIN = A0;

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

void loop() {
  int raw = analogRead(SENSOR_PIN);          // 0..1023
  float volts = raw * (5.0 / 1023.0);        // convert steps to volts
  float celsius = (volts - 0.5) * 100.0;     // 10 mV per degree, 500 mV offset
  Serial.println(celsius);
  delay(1000);
}

Two practical notes. First, the ADC reference defaults to the supply voltage, so a noisy or sagging 5 V rail makes your temperature jump. Second, the formula must match your board: a 3.3 V board has a different step size. The next stand-in lets you try the conversion with different raw values and reference voltages.

C Stand-in: ADC counts to degrees (C)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The same raw count means a different temperature depending on the reference voltage. That is the most common cause of "my sensor reads 10 degrees too cold".

The digital route: DHT11 and DHT22

The DHT11 and DHT22 (also sold as AM2302) measure temperature and relative humidity. They use a single data line and a custom protocol: your board pulls the line low to ask for data, then the sensor answers with 40 bits (5 bytes):

Byte Meaning
0 humidity, high byte
1 humidity, low byte
2 temperature, high byte (top bit = negative)
3 temperature, low byte
4 checksum: low 8 bits of the sum of bytes 0 to 3

On the DHT22 the 16-bit humidity and temperature values are in tenths, so 0x0123 humidity means 29.1 percent. The DHT11 sends whole numbers in the high bytes only and is less accurate (about 2 degrees and 5 percent against 0.5 degrees and 2 to 5 percent for the DHT22). Both need about one to two seconds between reads: ask more often and you get stale data or errors.

You almost never decode the pulses yourself. The usual choice is the DHT sensor library by Adafruit (see installing libraries):

C++
#include <DHT.h>

#define DHTPIN 2
#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);

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

void loop() {
  delay(2000);                       // the sensor is slow
  float h = dht.readHumidity();
  float t = dht.readTemperature();   // Celsius

  if (isnan(h) || isnan(t)) {        // failed read returns NaN
    Serial.println("Sensor read failed");
    return;
  }
  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %  Temperature: ");
  Serial.print(t);
  Serial.println(" C");
}

Always test for isnan(). A loose wire, a missing pull-up resistor (module boards usually include one; bare sensors need 4.7 to 10 kilohms between data and supply) or reading too fast all produce NaN, and printing it is harmless while using it in arithmetic spreads the problem.

Understanding the frame makes the library less magical. The next stand-in decodes five example bytes the way the library does, including the sign bit and the checksum test.

C Stand-in: decode a DHT22 frame (C)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Smoothing noisy readings

Even good sensors jitter. Two cheap tricks cover most needs. A moving average keeps the last N samples and reports their mean; it is easy to understand and costs N numbers of RAM. An exponential filter needs one number: smooth = smooth + alpha * (new - smooth), with alpha between 0 and 1 (small = smoother but slower).

flowchart LR
  A["Sensor"] --> B["Raw sample"]
  B --> C["Filter<br/>(average)"]
  C --> D["Decision or display"]

Raw samples are rarely used directly: filter first, then decide.

C Stand-in: moving average and exponential filter (C)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The spike at 25.0 is spread out and softened by both filters. The price is delay: a filtered value reacts a few samples late, so choose the window to match how fast your quantity really changes.

Practical tips

  • Keep wires short and add a 100 nF capacitor across the sensor supply pins if readings wander.
  • Place a temperature sensor away from the board's voltage regulator, which gets warm, or it reports the board and not the room.
  • Use float sparingly: on 8-bit boards it is slow and uses 4 bytes. Tenths of a degree stored in an int are often enough.
  • Label units in your output (C, %) so a log makes sense six months later.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A TMP36 outputs 750 mV. What temperature is that?

    The TMP36 outputs 10 mV per degree with a 500 mV offset, so (750 - 500) / 10 = 25 degrees Celsius.
  2. 2. What should you do when dht.readTemperature() returns NaN?

    NaN means the read failed. Detect it with isnan() and discard the sample instead of using it in calculations.
  3. 3. Why does a DHT22 frame end with a checksum byte?

    The checksum is the low 8 bits of the sum of the four data bytes. If it does not match, the frame was damaged and should be ignored.
  4. 4. Which filter needs only one variable of memory?

    The exponential filter keeps just the previous smoothed value and blends each new sample into it.

Summary

  • Analog sensors like the TMP36 give a voltage; convert counts to volts with the right reference, then to units.
  • DHT11 and DHT22 send a 40-bit frame: humidity, temperature and a checksum; read them no faster than every 1 to 2 seconds.
  • Always check for failed reads (isnan) and verify checksums.
  • Filter noisy samples with a moving average or an exponential filter, and remember filtering adds delay.

Next: Ultrasonic Distance Sensor (HC-SR04)