Interfacing the AHT20 sensor

Place code snippets and demo code here
Post Reply
User avatar
cicciocb
Site Admin
Posts: 1899
Joined: Mon Feb 03, 2020 1:15 pm
Location: Toulouse
Has thanked: 407 times
Been thanked: 1269 times
Contact:

Interfacing the AHT20 sensor

Post by cicciocb »

Hi all,
you can find here an example on how handle an AHT20 temperature / humidity sensor with a library written in basic.
This can also be a good demonstration of what can be done with the existing functions without requiring a dedicated driver.
I tried to comment the code so should not be hard to understand how use it.

cicciocb

Code: [Local Link Removed for Guests]

' Example of interfacing with the sensor AHT20
' without using any library but only
' existing 'I2C commands / functions
' datasheet 
' http://www.aosong.com/userfiles/files/media/Data%20Sheet%20AHT20.pdf
'---------------------------------------------------------------------
I2C.SETUP 21, 22  ' set I2C port on pins 21 and 22

te = 0
hu = 0
aht20_init ' init the sensor
while 1
  aht20_read te, hu ' read temperature and humidity
  wlog "hum="; hu, "temp=";te
  pause 500
wend
end

'ATH20 library
sub aht20_init
  'init (reset)
  i2c.begin &h38
  i2c.write &hbe
  i2c.end
  pause 100 ' pause after reset
end sub

sub aht20_read(temp, hum)
  dim arr(6) ' array used for the read

  ' trigger the measurement
  i2c.begin &h38
  i2c.write &hac
  i2c.write &h33
  i2c.write &h00
  i2c.end
  pause 80 ' wait time requested for the read (80msec as per the datasheet)
  
  'read the data
  I2C.REQFROM &h38, 6
  for z=0 to 5
    arr(z) = i2c.read
  next z
  ' arr(0) is the status
  if (arr(0) and 128) then
    wlog "data not available; increase the wait time"
  else
    hum =  ((arr(1) << 12) + (arr(2) << 4) + (arr(3) >> 4)) / 10485.76
    temp = (((arr(3) and &h0f) << 16) + (arr(4) << 8) + arr(5)) / 1048576
    temp = temp * 200 - 50
  end if
end sub
Jan Volk
Posts: 71
Joined: Wed Mar 03, 2021 1:35 pm
Been thanked: 23 times

Re: Interfacing the AHT20 sensor

Post by Jan Volk »

Cicciocb,

Thank you for this code and have already tested it with different boards and different versions and works very stable so far.
It does indeed work with the DHT20 and am very happy with it.
I have two sensors working the same on an ESP32 LOLIN32 Lite and on an ESP32-C3USB and the differences between them are very small and so far no wrong measurements.

Jan
Post Reply