ESP32 AHT20 Temperature and Humidity Sensor
Overview
The AHT20 datasheet provides comprehensive technical details about the AHT20 digital temperature and humidity sensor, a highly accurate and reliable component designed for industrial-grade applications. This document includes information on the sensor's specifications, electrical characteristics, communication protocols, and recommended usage guidelines, ensuring users can integrate it seamlessly into their projects.
About AHT20 Temperature and Humidity Sensor
The AHT series, developed by AOSONG (Aosong Electronics Co., Ltd.), consists of high-precision digital temperature and humidity sensors.
⚡ Key Features
- Upgraded Performance – The AHT20 offers higher accuracy and improved reliability compared to the AHT10.
- Reliable Environmental Monitoring – Ideal for weather stations, indoor climate control, and industrial applications.
- Compact & Efficient – Digital output with I²C interface for seamless integration.
🔗 Learn more about the AHT20 sensor.
🔗 Check out the AHT10 sensor for a more affordable option.
Where to Buy
Prices are subject to change. We earn from qualifying purchases as an Amazon Associate.
Technical Specifications
Pinout Configuration
The VCC
pin is used to supply power to the sensor, and it typically requires 3.3V or 5V (refer to the datasheet for specific voltage requirements). The GND
pin is the ground connection and must be connected to the ground of your ESP32.
The AHT20 pinout is simple and follows the I2C communication protocol:
- SDA (Data Line): Used for transferring data between the sensor and the microcontroller (ESP32).
- SCL (Clock Line): Provides the clock signal for synchronizing data transfer.
- GND (Ground): Connect to the ground of the ESP32 to complete the circuit.
- VCC (Power): Connect to the 3.3V or 5V power supply on the ESP32 to power the sensor.
Troubleshooting Guide
Common Issues
⚠️ Sensor Initialization Failure on ESP32
Issue: When connecting the AHT20 sensor to an ESP32, the sensor fails to initialize, resulting in errors such as: AHT20 sensor initialization failed. error status : 2
.
Possible causes include incorrect wiring, improper I2C configuration, or insufficient power supply.
Solution: Verify that the AHT20's SCL and SDA pins are correctly connected to the ESP32's I2C pins (commonly GPIO 21 for SDA and GPIO 22 for SCL). Ensure that the sensor is powered appropriately, either through the 3.3V or 5V pin, depending on the sensor's voltage requirements. Additionally, confirm that the I2C bus is properly initialized in the code with the correct pins and that no other devices on the bus share the same address. (forum.arduino.cc)
🔄 Communication Failure with ESPHome
Issue: When integrating the AHT20 sensor with ESPHome, the following error appears in the logs: [E][aht10:080]: Communication with AHT10 failed!
, leading to the sensor not providing temperature and humidity data.
Possible causes include incorrect sensor variant specification or compatibility issues with the ESPHome version.
Solution: Ensure that the sensor variant is correctly specified in the ESPHome configuration. For the AHT20 sensor, the configuration should include variant: AHT20
. Additionally, updating ESPHome to the latest version may resolve compatibility issues. If the problem persists, consider testing the sensor with a different microcontroller or using alternative libraries to rule out hardware-related issues. (github.com)
🌡️ Temperature Readings Increasing Over Time
Issue: The AHT20 sensor reports temperature readings that gradually increase over time, deviating from actual ambient conditions.
Possible causes include self-heating effects due to the sensor's proximity to heat-generating components or insufficient ventilation.
Solution: Position the sensor away from heat sources such as microcontrollers, voltage regulators, or other components that may emit heat. Implement proper ventilation around the sensor to allow for accurate ambient temperature measurements. Using longer connecting wires can help distance the sensor from potential heat sources. Additionally, consider placing the sensor in a well-ventilated enclosure to minimize the impact of external heat. (community.home-assistant.io)
🔍 Device Address Detected but Read Failed on ESP32
Issue: On a ESP32, the I2C bus detects the AHT20 sensor's address, but attempts to read data result in errors such as: Error: Read failed
.
Possible causes include incorrect I2C bus configuration, insufficient pull-up resistors, or conflicts with other I2C devices.
Solution: Verify that the I2C interface is enabled on the ESP32 and that the correct I2C bus is being used. Ensure that appropriate pull-up resistors (typically 4.7kΩ) are present on the SDA and SCL lines. Check for address conflicts with other devices on the I2C bus and ensure that each device has a unique address.
Debugging Tips
🔍 Serial Monitor
Use the Serial Monitor to check for error messages and verify the sensor's output. Add debug prints in your code to track the sensor's state.
⚡ Voltage Checks
Use a multimeter to verify voltage levels and check for continuity in your connections. Ensure the power supply is stable and within the sensor's requirements.
Additional Resources
Code Examples
Arduino Example
#include <Wire.h>
#include <Adafruit_AHTX0.h> // Correct library for AHT20
// Create an instance of the AHT20 sensor
Adafruit_AHTX0 aht; // Use AHTX0 instead of AHT10
void setup() {
// Initialize Serial Monitor
Serial.begin(115200);
Serial.println("AHT20 Sensor Example");
// Initialize I2C communication
if (!aht.begin()) { // No parameter needed
Serial.println("Failed to find AHT20 sensor! Check wiring.");
while (1);
}
Serial.println("AHT20 sensor initialized.");
}
void loop() {
// Get sensor data
sensors_event_t humidity, temp;
aht.getEvent(&humidity, &temp); // Retrieve sensor readings
// Print temperature and humidity
Serial.print("Temperature: ");
Serial.print(temp.temperature);
Serial.println(" °C");
Serial.print("Humidity: ");
Serial.print(humidity.relative_humidity);
Serial.println(" %");
// Delay between readings
delay(2000);
}
This Arduino sketch interfaces with the AHT20 Temperature and Humidity Sensor using the Adafruit AHTX0 library over I2C.
Required Library #
To use this code, ensure you have installed the Adafruit AHTX0 library. You can install it via the Arduino Library Manager:
- Open Arduino IDE.
- Navigate to Sketch → Include Library → Manage Libraries.
- Search for 'Adafruit AHTX0' and install it.
Alternatively, you can download it from the official Adafruit GitHub repository:
🔗 Adafruit AHTX0 Library
ESP-IDF Example
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/i2c.h"
#define I2C_MASTER_NUM I2C_NUM_0 // I2C port number
#define I2C_MASTER_SDA_IO 21 // GPIO for SDA
#define I2C_MASTER_SCL_IO 22 // GPIO for SCL
#define I2C_MASTER_FREQ_HZ 100000 // I2C clock frequency
#define AHT20_ADDR 0x38 // I2C address of the AHT20 sensor
#define AHT20_CMD_TRIGGER 0xAC // Command to trigger measurement
#define AHT20_CMD_SOFTRESET 0xBA // Command to reset the sensor
#define AHT20_CMD_INIT 0xBE // Command to initialize the sensor
// Function to initialize I2C
void i2c_master_init() {
i2c_config_t conf = {
.mode = I2C_MODE_MASTER,
.sda_io_num = I2C_MASTER_SDA_IO,
.scl_io_num = I2C_MASTER_SCL_IO,
.sda_pullup_en = GPIO_PULLUP_ENABLE,
.scl_pullup_en = GPIO_PULLUP_ENABLE,
.master.clk_speed = I2C_MASTER_FREQ_HZ,
};
i2c_param_config(I2C_MASTER_NUM, &conf);
i2c_driver_install(I2C_MASTER_NUM, conf.mode, 0, 0, 0);
}
// Function to write data to the AHT20
esp_err_t aht20_write_command(uint8_t cmd) {
i2c_cmd_handle_t handle = i2c_cmd_link_create();
i2c_master_start(handle);
i2c_master_write_byte(handle, (AHT20_ADDR << 1) | I2C_MASTER_WRITE, true);
i2c_master_write_byte(handle, cmd, true);
i2c_master_stop(handle);
esp_err_t ret = i2c_master_cmd_begin(I2C_MASTER_NUM, handle, pdMS_TO_TICKS(1000));
i2c_cmd_link_delete(handle);
return ret;
}
// Function to read data from the AHT20
esp_err_t aht20_read_data(uint8_t data, size_t length) {
i2c_cmd_handle_t handle = i2c_cmd_link_create();
i2c_master_start(handle);
i2c_master_write_byte(handle, (AHT20_ADDR << 1) | I2C_MASTER_READ, true);
i2c_master_read(handle, data, length, I2C_MASTER_LAST_NACK);
i2c_master_stop(handle);
esp_err_t ret = i2c_master_cmd_begin(I2C_MASTER_NUM, handle, pdMS_TO_TICKS(1000));
i2c_cmd_link_delete(handle);
return ret;
}
// Function to reset and initialize the AHT20
void aht20_init() {
aht20_write_command(AHT20_CMD_SOFTRESET);
vTaskDelay(pdMS_TO_TICKS(20)); // Wait after reset
aht20_write_command(AHT20_CMD_INIT);
vTaskDelay(pdMS_TO_TICKS(20)); // Wait for initialization
}
// Function to get temperature and humidity
void aht20_get_temp_humidity(float temperature, float humidity) {
uint8_t data[6];
aht20_write_command(AHT20_CMD_TRIGGER);
vTaskDelay(pdMS_TO_TICKS(80)); // Wait for the measurement
if (aht20_read_data(data, 6) == ESP_OK) {
uint32_t raw_humidity = ((data[1] << 16) | (data[2] << 8) | data[3]) >> 4;
uint32_t raw_temperature = ((data[3] & 0x0F) << 16) | (data[4] << 8) | data[5];
humidity = ((float)raw_humidity / 1048576.0) 100.0;
temperature = ((float)raw_temperature / 1048576.0) 200.0 - 50.0;
} else {
humidity = -1.0;
*temperature = -1.0;
}
}
// Main application
void app_main() {
float temperature = 0.0, humidity = 0.0;
i2c_master_init();
aht20_init();
while (1) {
aht20_get_temp_humidity(&temperature, &humidity);
printf("Temperature: %.2f °C, Humidity: %.2f %%", temperature, humidity);
vTaskDelay(pdMS_TO_TICKS(2000));
}
}
The code initializes the I2C communication using i2c_master_init()
and sets up the AHT20 sensor with aht20_init()
. The aht20_write_command()
function sends commands to the sensor for initialization and measurements, while aht20_read_data()
reads the response, including raw temperature and humidity data. The aht20_get_temp_humidity()
function processes the raw data to compute the actual temperature and humidity values. The main function app_main()
initializes the sensor, enters a loop, and retrieves and displays the sensor data every 2 seconds using printf()
.
ESPHome Example
sensor:
- platform: aht10
variant: AHT20
temperature:
name: "Living Room Temperature"
humidity:
name: "Living Room Humidity"
update_interval: 60s
This code snippet configures an AHT20 temperature and humidity sensor in an ESPHome YAML file. The sensor
block defines the platform as aht10
, specifying that the device is compatible with the AHT10/AHT20 series of sensors. The variant
field explicitly declares the sensor model as AHT20
.
Two sensors are set up: temperature
and humidity
. Each sensor has a unique name
for identification in the ESPHome dashboard or Home Assistant, such as Living Room Temperature
and Living Room Humidity
. These names are used when displaying or logging the sensor readings.
The update_interval
is set to 60s
, which means the sensor will provide updated temperature and humidity readings every 60 seconds.
PlatformIO Example
platformio.ini
[env:esp32]
platform = espressif32
board = esp32dev
framework = arduino
monitor_speed = 115200
lib_deps =
adafruit/Adafruit AHTX0 @ ^2.0.0
arduino-libraries/Wire
PlatformIO Example Code
#include <Wire.h>
#include "Adafruit_AHT10.h"
// Create an instance of the AHT20 sensor
Adafruit_AHT10 aht;
void setup() {
// Initialize Serial Monitor
Serial.begin(115200);
Serial.println("AHT20 Sensor Example");
// Initialize I2C communication and sensor
if (!aht.begin(Adafruit_AHT10::AHTX0_SENSOR)) { // Specify AHT20 variant
Serial.println("Failed to find AHT20 sensor! Check wiring.");
while (1); // Infinite loop if initialization fails
}
Serial.println("AHT20 sensor initialized.");
}
void loop() {
// Read temperature and humidity from the sensor
sensors_event_t humidity, temp;
aht.getEvent(&humidity, &temp); // Populate the event objects
// Print temperature and humidity to Serial Monitor
Serial.print("Temperature: ");
Serial.print(temp.temperature);
Serial.println(" °C");
Serial.print("Humidity: ");
Serial.print(humidity.relative_humidity);
Serial.println(" %");
// Delay between readings
delay(2000);
}
The platformio.ini
file configures the project for the ESP32 using the Arduino framework. The environment is set to [env:esp32]
, with platform = espressif32
for the ESP32 platform and board = esp32dev
specifying a generic ESP32 development board. The framework is set to arduino
, and the baud rate for the serial monitor is configured with monitor_speed = 115200
.
MicroPython Example
import machine
import time
from ahtx0 import AHT20
# Initialize I2C
i2c = machine.I2C(0, scl=machine.Pin(22), sda=machine.Pin(21))
# Initialize AHT20 sensor
sensor = AHT20(i2c)
# Main loop
while True:
try:
# Read temperature and humidity
temperature = sensor.temperature
humidity = sensor.humidity
# Print readings
print("Temperature: {:.2f} °C".format(temperature))
print("Humidity: {:.2f} %".format(humidity))
# Wait for 2 seconds
time.sleep(2)
except Exception as e:
print("Error reading
The code initializes I2C communication using machine.I2C
with GPIO22 for SCL and GPIO21 for SDA. The AHT20 sensor is initialized with the AHT20
class. In the main loop, the temperature and humidity are read using sensor.temperature
and sensor.humidity
, and the values are printed to the console using print()
. A delay of 2 seconds is added between readings using time.sleep(2)
.
Conclusion
The ESP32 AHT20 Temperature and Humidity Sensor is a powerful environment sensor that offers excellent performance and reliability. With support for multiple development platforms including Arduino, ESP-IDF, ESPHome, PlatformIO, and MicroPython, it's a versatile choice for your IoT projects.
For optimal performance, ensure proper wiring and follow the recommended configuration for your chosen development platform.
Always verify power supply requirements and pin connections before powering up your project to avoid potential damage.