Sub topic 3
Celsius and Fahrenheit
This chapter assumes you can upload a sketch, use the Serial Monitor, wire a DHT22 with the Adafruit DHT library installed, and use float variables and simple functions.
Celsius and Fahrenheit
The DHT library returns Celsius by default. Pass true to get Fahrenheit:
float tempC = dht.readTemperature();
float tempF = dht.readTemperature(true);Store one unit in your code and convert only when you display a value. To convert Celsius to Fahrenheit, use F = C × 9/5 + 32.
Computing heat index and dew point
Heat index is the temperature people feel at a given humidity. Dew point is the temperature at which water vapor condenses. The library computes heat index. Dew point needs the Magnus approximation:
float dewPointC(float tempC, float humidityPercent) {
const float a = 17.62;
const float b = 243.12;
float gamma = log(humidityPercent / 100.0) + (a * tempC) / (b + tempC);
return (b * gamma) / (a - gamma);
}Pass false as the third argument to computeHeatIndex when your temperature is in Celsius.
Accuracy limits and calibration offsets
The DHT22 is specified at about ±0.5 °C and ±2 % relative humidity. The DHT11 is specified at about ±2 °C and ±5 %. To correct a constant error, compare the sensor with a reference thermometer and store the difference as an offset:
const float TEMP_OFFSET_C = -0.5;
const float HUMIDITY_OFFSET = 1.0;
float calibratedTemp(float rawC) {
return rawC + TEMP_OFFSET_C;
}
float calibratedHumidity(float rawPercent) {
return constrain(rawPercent + HUMIDITY_OFFSET, 0.0, 100.0);
}Reading without blocking the sketch
delay() stops the whole sketch. Use millis() to read the sensor on a schedule while the rest of loop() keeps running:
#include <DHT.h>
#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
const unsigned long READ_INTERVAL_MS = 2000;
unsigned long lastReadMs = 0;
void setup() {
Serial.begin(9600);
dht.begin();
}
void loop() {
unsigned long now = millis();
if (now - lastReadMs >= READ_INTERVAL_MS) {
lastReadMs = now;
float humidity = dht.readHumidity();
float tempC = dht.readTemperature();
if (!isnan(humidity) && !isnan(tempC)) {
Serial.print(tempC);
Serial.print(',');
Serial.println(humidity);
}
}
}The output is comma-separated, so you can paste it into a spreadsheet or log file.
When to choose an I2C sensor instead
I2C is a two-wire bus that several sensors can share. Sensors such as the SHT31 are often more accurate than the DHT22, and their reads do not depend on single-wire timing. Choose a DHT sensor for low-cost, simple projects. Choose an I2C sensor when you need better accuracy or several sensors on one bus.
Exercise
Exercise
Your sketch reads a DHT22 every 2 seconds. The reading is 25.0 °C, and a reference thermometer shows 24.4 °C. What offset should you store in TEMPOFFSETC, and what does calibratedTemp return for a new raw reading of 30.0 °C?
Show answer
The offset is 24.4 − 25.0 = −0.6, so TEMPOFFSETC = -0.6. calibratedTemp(30.0) returns 30.0 + (−0.6) = 29.4 °C.