Comfort meter (AHT20)
An AHT20 measures temperature and humidity; a green LED means comfortable, red too dry or too damp, yellow too hot or cold.
Sensors · Beginner
In a real product: Indoor air-quality monitor (Smart home): Shows whether a room is comfortable from its temperature and humidity.
Indoors, people are comfortable between about 20 and 25 °C at 30 to 60 % relative humidity. An AHT20 measures both over I²C, and three LEDs say how the room is doing.
What you'll learn
- Reading a sensor whose measurement takes time: the library triggers it and waits for the busy bit to clear
- Classifying readings into ranges, with the most urgent one shown first
- Why a sensor with no registers still needs a protocol: commands in, a status byte and data out
How it works
aht.getEvent() sends the trigger command (0xAC 0x33 0x00) and polls the status byte until the sensor is no longer busy, about 80 ms later. Then it reads six bytes: the status, 20 bits of humidity and 20 of temperature, which the library scales to %RH and °C.
Each second the sketch picks one LED: red when the humidity is outside 30–60 %, yellow when the temperature is outside 20–25 °C, otherwise green.
Try this
- Click the sensor and drag the humidity below 30 %: red. Bring it back and raise the temperature to 28 °C: yellow.
- Print
millis()before and aftergetEvent(): the measurement takes 80 ms. - Add a little hysteresis, so the LEDs do not flicker when a reading sits right on a limit.
sketch.ino
// A comfort meter: an AHT20 measures the room once a second. Red (pin 5): the humidity is outside 30-60 %RH. Yellow
// (pin 6): the temperature is outside 20-25 C. Green (pin 7): comfortable.
#include <Adafruit_AHTX0.h>
Adafruit_AHTX0 aht;
const int RED = 5, YELLOW = 6, GREEN = 7;
void setup() {
Serial.begin(9600);
for (int pin = RED; pin <= GREEN; pin++) pinMode(pin, OUTPUT);
if (!aht.begin()) {
Serial.println("No AHT20 found");
while (true) {}
}
}
void loop() {
sensors_event_t humidity, temp;
aht.getEvent(&humidity, &temp);
float t = temp.temperature, rh = humidity.relative_humidity;
int lit = rh < 30 || rh > 60 ? RED : t < 20 || t > 25 ? YELLOW : GREEN;
for (int pin = RED; pin <= GREEN; pin++) digitalWrite(pin, pin == lit ? HIGH : LOW);
Serial.print(t, 1);
Serial.print(" C, ");
Serial.print(rh, 1);
Serial.println(lit == GREEN ? " %RH: comfortable" : lit == RED ? " %RH: too dry or damp" : " %RH: too hot or cold");
delay(1000);
}