Example Code for Arduino-Temperature and Humidity Sensor Reading Test

Last revision 2025/12/18

The project reads the measured values from the AHT20 temperature and humidity sensor and prints them through the serial port. Users can learn how to interface the AHT20 sensor with Arduino, install and use the DFRobot_AHT20 library, and obtain real-time temperature and humidity data.

Hardware Preparation

  • DFRduino UNO R3 (or similar) x 1
  • SEN0528 Gravity: AHT20 Temperature and Humidity Sensor x 1
  • M-M/F-M/F-F Jumper wires

Software Preparation

Wiring Diagram

UNO Board: 3V3 - connect to - AHT20:+

UNO Board: GND - connect to - AHT20:-

UNO Board: SCL - connect to - AHT20:C

UNO Board: SDA - connect to - AHT20:D

Sample Code

The following code will read the measured values from the AHT20 temperature and humidity sensor and print them through the serial port.

    #include "DFRobot_AHT20.h"
    DFRobot_AHT20 aht20;
    void setup(){
      Serial.begin(115200);
      while(!Serial){
      }
      uint8_t status;
      while((status = aht20.begin()) != 0){
        Serial.print("AHT20 sensor initialization failed. error status : ");
        Serial.println(status);
        delay(1000);
      }
    }
    void loop(){
      if(aht20.startMeasurementReady(true)){
        Serial.print("temperature(-40~85 C): ");
        Serial.print(aht20.getTemperature_C());
        Serial.print(" C, ");
        Serial.print(aht20.getTemperature_F());
        Serial.print(" F\t");
        Serial.print("humidity(0~100): ");
        Serial.print(aht20.getHumidity_RH());
        Serial.println(" %RH");
        delay(8000);
      }
    }

Result

The results are as shown in the figure below, the temperature values in ℃ and ℉, and humidity values are displayed in the serial monitor.

Was this article helpful?

TOP