Example Code for Arduino-I2C Communication
Last revision 2026/01/18
This article offers a comprehensive guide to implementing Arduino-I2C communication with the AHT20 sensor, using the DFRobot Beetle RP2040. It covers hardware and software preparation, wiring instructions, and sample code for reading temperature and humidity data from the sensor via the serial port.
Hardware Preparation
- DFRobot Beetle RP2040, 1, Purchase Link
- USB Type-C Cable, 1
- AHT20 Temperature and Humidity Sensor (SEN0527), 1, Purchase Link (replace with actual SKU)
Software Preparation
- Arduino IDE: Download Link
- Raspberry Pi Pico/RP2040 SDK: Installed via Arduino Boards Manager (see Getting Started)
- DFRobot_AHT20 Library: Download Link
Wiring Diagram

- AHT20: pin SDA (connect to) BeetleRP2040: pin GP4
- AHT20: pin SCL (connect to) BeetleRP2040: pin GP5
- AHT20: pin GND (connect to) BeetleRP2040: pin GND
- AHT20: pin VCC (connect to) BeetleRP2040: pin 3V3
Other Preparation Work
- Open Arduino IDE.
- Select "DFRobot Beetle RP2040" as the development board.
- Connect the Beetle RP2040 to your computer.
- Wire the AHT20 sensor to I2C0 (GP4/SDA0, GP5/SCL0) as per the diagram.
- Install the DFRobot_AHT20 library via Arduino Library Manager.
Sample Code
Function: read the temperature and humidity values from the AHT20 temperature and humidity sensor and print them in the serial port.
#include "DFRobot_AHT20.h"
DFRobot_AHT20 aht20;
void setup(){
Serial.begin(9600);
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
Open the serial monitor of Arduino IDE, set the baud rate to 9600, and the window prints the temperature and humidity information read by the sensor.

Additional Information
- I2C0 uses pins GP4 (SDA0) and GP5 (SCL0) for communication.
- The AHT20 sensor has a default I2C address of 0x38.
Was this article helpful?
