ESP32 AHT20 Temperature and Humidity Sensor
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.
Jump to Code Examples
Quick Links
AHT20 Price
About AHT20 Temperature and Humidity Sensor
The AHT series comprises digital temperature and humidity sensors manufactured by Aosong Electronics Co., Ltd., also known as AOSONG. The AHT20 is an upgraded version in the AHT series, offering improved performance and precision compared to its predecessor, the AHT10. The AHT20 sensor provides enhanced accuracy in temperature and humidity measurements, making it an ideal choice for a wider range of applications requiring reliable environmental monitoring. Learn more about the AHT20 sensor in the series. Also check the previous, cheaper version - AHT10 Sensor.AHT20 Sensor Technical Specifications
Below you can see the AHT20 Temperature and Humidity Sensor Technical Specifications. The sensor is compatible with the ESP32, operating within a voltage range suitable for microcontrollers. For precise details about its features, specifications, and usage, refer to the sensor’s datasheet.
- Protocol: I2C
- Interface: I2C
- Accuracy: ±2% RH, ±0.3 °C
- Operating Range: -40°C to 85°C, 0–100% RH
- Voltage: 2.0V to 5.5V (typical 3.3V)
AHT20 Sensor Pinout
Below you can see the pinout for the AHT20 Temperature and Humidity Sensor. 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.
AHT20 Wiring with ESP32
Below you can see the wiring for the AHT20 Temperature and Humidity Sensor with the ESP32. Connect the VCC pin of the sensor to the 3.3V pin on the ESP32 or external power supply for power and the GND pin of the sensor to the GND pin of the ESP32. Depending on the communication protocol of the sensor (e.g., I2C, SPI, UART, or analog), connect the appropriate data and clock or signal pins to compatible GPIO pins on the ESP32, as shown below in the wiring diagram.
SDA
, SCL
, VCC
and GND
pins to the ESP32. Make sure to configure the I2C pins accordingly.Code Examples
Below you can find code examples of AHT20 Temperature and Humidity Sensor with ESP32 in several frameworks:
ESP32 AHT20 Arduino IDE Code Example
Fill in your main
Arduino IDE sketch file with the following code to use the AHT20 Temperature and Humidity Sensor:
#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
if (!aht.begin(Adafruit_AHT10::AHTX0_SENSOR)) { // Specify AHT20 variant
Serial.println("Failed to find AHT20 sensor! Check wiring.");
while (1);
}
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 code uses the Adafruit_AHT10
library to interface with the AHT20 sensor. It begins by including the required libraries, #include <Wire.h>
for I2C communication and #include <Adafruit_AHT10.h>
for the sensor-specific functionality.
An instance of the AHT20 sensor is created using Adafruit_AHT10 aht;
. In the setup()
function, the serial communication is initialized with Serial.begin(115200)
, and the sensor is initialized using aht.begin()
. If the sensor is not detected, an error message is printed, and the program enters an infinite loop.
The loop()
function reads the temperature and humidity data from the sensor using aht.getEvent(&humidity, &temp)
. The temperature is accessed via temp.temperature
, and the humidity via humidity.relative_humidity
. These values are printed to the Serial Monitor using Serial.print()
. A delay of 2 seconds is added between readings using delay(2000)
.
Connect your ESP32 to your computer via a USB cable, Ensure the correct Board and Port are selected under Tools, Click the "Upload" button in the Arduino IDE to compile and upload the code to your ESP32.
ESP32 AHT20 ESP-IDF Code ExampleExample in Espressif IoT Framework (ESP-IDF)
If you're using ESP-IDF to work with the AHT20 Temperature and Humidity Sensor, here's how you can set it up and read data from the sensor. Fill in this code in the main
ESP-IDF file:
#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()
.
Update the I2C pins (I2C_MASTER_SDA_IO
and I2C_MASTER_SCL_IO
) to match your ESP32 hardware setup, Use idf.py build to compile the project, Use idf.py flash to upload the code to your ESP32.
ESP32 AHT20 ESPHome Code Example
Fill in this configuration in your ESPHome YAML configuration file (example.yml
) to integrate the AHT20 Temperature and Humidity Sensor
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.
Upload this code to your ESP32 using the ESPHome dashboard or the esphome run
command.
ESP32 AHT20 PlatformIO Code Example
For PlatformIO, make sure to configure the platformio.ini
file with the appropriate environment and libraries, and then proceed with the code.
Configure platformio.ini
First, your platformio.ini
should look like below. You might need to include some libraries as shown. Make sure to change the board to your ESP32:
[env:esp32]
platform = espressif32
board = esp32dev
framework = arduino
monitor_speed = 115200
lib_deps =
adafruit/Adafruit AHTX0 @ ^2.0.0
arduino-libraries/Wire
ESP32 AHT20 PlatformIO Example Code
Write this code in your PlatformIO project under the src/main.cpp
file to use the AHT20 Temperature and Humidity Sensor:
#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
.
Upload the code to your ESP32 using the PlatformIO "Upload" button in your IDE or the pio run --target upload
command.
ESP32 AHT20 MicroPython Code Example
Fill in this script in your MicroPython main.py file (main.py
) to integrate the AHT20 Temperature and Humidity Sensor with your ESP32.
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)
.
Upload this code to your ESP32 using a MicroPython-compatible IDE, such as Thonny, uPyCraft, or tools like ampy
.
Conclusion
We went through technical specifications of AHT20 Temperature and Humidity Sensor, its pinout, connection with ESP32 and AHT20 Temperature and Humidity Sensor code examples with Arduino IDE, ESP-IDF, ESPHome and PlatformIO.