Sub topic 9
Celsius and Fahrenheit
This chapter assumes you can already read a DHT sensor with the Adafruit library and check results with isnan. It covers two things: how the library handles units, and how to keep unit handling from causing subtle bugs in your sketch.
What the sensor actually reports
A DHT sensor measures temperature in Celsius. The sensor sends raw bytes over its single data wire, and the library decodes them into degrees Celsius. Fahrenheit is a conversion done in software afterwards. The sensor has no Fahrenheit mode.
This affects how you design the sketch. Treat Celsius as the internal unit and convert to Fahrenheit only when you show a value to a person. Calibration offsets, the dew point formula, and threshold checks are all simpler and less error-prone if they use a single unit.
| Quantity | Celsius | Fahrenheit |
|---|---|---|
| Water freezes | 0 | 32 |
| Typical room | 20 | 68 |
| Body temperature | 37 | 98.6 |
| Water boils | 100 | 212 |
| Where the scales meet | -40 | -40 |
| DHT22 range | -40 to 80 | -40 to 176 |
| DHT11 range | 0 to 50 | 32 to 122 |
Asking the library for Fahrenheit
readTemperature() takes an optional first argument. Pass true to get Fahrenheit:
float temperatureC = dht.readTemperature(); // Celsius (default)
float temperatureF = dht.readTemperature(true); // FahrenheitBoth calls return NaN when the read fails, so the isnan check from the error-handling chapter applies to each one.
Why two calls do not mean two sensor reads
The library remembers the last result and the time it was taken. If you call a read function again within the minimum interval of about two seconds, it returns the stored data instead of talking to the sensor. Calling readTemperature() and then readTemperature(true) back to back therefore does not hit the sensor twice. Both values come from the same measurement.
This is convenient, but it hides a weakness. If the first read fails and returns NaN, the second call usually fails too, so you cannot treat the second call as a retry. A failed read needs a pause of at least the sampling interval before you try again.
Converting yourself
Reading Celsius once and converting is usually cleaner than requesting both units. The formulas are:
- Fahrenheit = Celsius × 9 / 5 + 32
- Celsius = (Fahrenheit − 32) × 5 / 9
The library provides these as dht.convertCtoF() and dht.convertFtoC(). Writing your own is easy and avoids depending on the library for simple arithmetic. It also lets you use the same functions with values that did not come from the sensor, such as a threshold typed by the user.
float celsiusToFahrenheit(float c) {
return c * 9.0 / 5.0 + 32.0;
}
float fahrenheitToCelsius(float f) {
return (f - 32.0) * 5.0 / 9.0;
}The integer division trap
The most common unit bug on Arduino is writing the ratio as 9 / 5. Both operands are int, so C++ computes integer division and the result is 1, not 1.8. Your Fahrenheit value then equals Celsius plus 32, which looks plausible at a glance and is wrong.
float wrong = c * (9 / 5) + 32; // 9 / 5 is 1, so this is c + 32
float right = c * 9.0 / 5.0 + 32.0; // floating-point math
float alsoRight = c * 1.8 + 32.0;Use a decimal point on at least one operand of every division. For (f - 32.0) * 5.0 / 9.0, the 5.0 and 9.0 matter just as much.
A complete sketch that shows both units
This sketch reads once in Celsius, validates the result, and prints both units. It uses the same pin and sensor type as the earlier chapters.
#include <DHT.h>
#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
float celsiusToFahrenheit(float c) {
return c * 9.0 / 5.0 + 32.0;
}
void setup() {
Serial.begin(9600);
dht.begin();
}
void loop() {
delay(2000);
float temperatureC = dht.readTemperature();
if (isnan(temperatureC)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
float temperatureF = celsiusToFahrenheit(temperatureC);
Serial.print(temperatureC, 1);
Serial.print(F(" C = "));
Serial.print(temperatureF, 1);
Serial.println(F(" F"));
}The second argument to Serial.print, as in Serial.print(temperatureC, 1), sets the number of decimal places. Without it, a float prints two decimals. For a DHT22 with ±0.5 °C accuracy, one decimal is already more precision than the sensor can justify.
Resolution and what the units imply
Converting does not add information. A Fahrenheit degree is smaller than a Celsius degree, so Fahrenheit numbers look finer-grained, but the sensor's precision stays the same.
- A DHT22 reports in steps of 0.1 °C, which is 0.18 °F. Its accuracy is about ±0.5 °C, which is ±0.9 °F.
- A DHT11 effectively reports whole degrees Celsius. After conversion, consecutive values differ by 1.8 °F, so you will see values like 71.6, 73.4, and 75.2. Those jumps are normal and are not noise.
- A DHT11's accuracy of about ±2 °C is ±3.6 °F. Printing
73.40suggests a precision the sensor does not have.
Print as many decimals as the sensor supports and no more. One decimal is a good default for the DHT22 and zero or one for the DHT11.
Converting differences is different
The + 32 in the formula is an offset between the two scales' zero points. It applies to absolute temperatures and does not apply to differences between temperatures. A change of 1 °C is a change of 1.8 °F, with no 32 involved.
This matters for the calibration offsets covered in a later chapter. Suppose your reference thermometer shows your sensor reading 0.5 °C too high. The Celsius correction is -0.5. If you wanted to apply that correction to a Fahrenheit value, the correction would be -0.9, not -0.5 * 9 / 5 + 32. The simplest way to avoid the mistake is to apply every offset in Celsius, before any conversion.
const float TEMP_OFFSET_C = -0.5;
float rawC = dht.readTemperature();
float correctedC = rawC + TEMP_OFFSET_C;
float correctedF = celsiusToFahrenheit(correctedC);The same applies to hysteresis bands and alarm margins. A thermostat that switches at 24 °C with a 0.5 °C band has a Fahrenheit band of 0.9 °F.
Units and derived values
Two calculations from the next chapter depend on units, so settle the rules now.
computeHeatIndex(temperature, humidity, isFahrenheit)hasisFahrenheitdefaulting totrue. If you pass a Celsius value withoutfalseas the third argument, the library treats it as Fahrenheit and returns a wrong result, with no error. Always pass the flag explicitly.- The dew point function you saw earlier takes Celsius. Feeding it Fahrenheit produces a meaningless number.
A helper that makes the unit part of the name prevents most of these mistakes:
float heatIndexC(DHT &sensor, float tempC, float humidity) {
return sensor.computeHeatIndex(tempC, humidity, false);
}Letting the user choose a unit
If your project has a button or a serial command to switch units, keep a single flag and branch only at the display step. Do not store two copies of every value.
bool showFahrenheit = false;
void printTemperature(float tempC) {
if (showFahrenheit) {
Serial.print(tempC * 9.0 / 5.0 + 32.0, 1);
Serial.println(F(" F"));
} else {
Serial.print(tempC, 1);
Serial.println(F(" C"));
}
}Flipping showFahrenheit changes only what is displayed. The logging format, thresholds, and calibration stay in Celsius, so data files remain comparable across runs.
Common errors
- Using
9 / 5instead of9.0 / 5.0, which silently gives a factor of 1. - Treating the second
readTemperaturecall as a retry after a failure. - Passing Celsius to
computeHeatIndexwithoutfalse. - Applying a Celsius calibration offset to a Fahrenheit value, or converting an offset with
+ 32. - Printing a DHT11 value with two decimals and reading meaning into the digits.
- Logging a mix of units in one file because the display unit changed mid-run.
Exercise
A DHT22 read returns 25.0 in Celsius. Your sketch contains the line float f = c * (9 / 5) + 32;. What value does f hold, what is the correct value, and how do you fix the line?
Show answer
9 / 5 is integer division and equals 1, so f is 25.0 1 + 32 = 57.0. The correct value is 25.0 1.8 + 32 = 77.0. Fix it by using floating-point constants: float f = c * 9.0 / 5.0 + 32.0;.
Exercise
Your reference thermometer shows that your sensor reads 0.5 °C too high. You want to correct a Fahrenheit value tempF directly. What number do you subtract, and why is the formula -0.5 * 9 / 5 + 32 wrong?
Show answer
Subtract 0.9. A 0.5 °C difference is 0.5 × 1.8 = 0.9 °F. The + 32 converts between the scales' zero points, so it only applies to absolute temperatures and not to differences. The simpler approach is to correct in Celsius first and convert afterwards.