The tests carried out so far with the 5 units purchased show very high reliability and precision, much higher than the popular DHT11.
This is the code I have written.
Code: [Local Link Removed for Guests]
' AHT21 temperature/humidity sensor
address = &H38 ' I2C device address
ioBuff.dim(0,3) = &HE1, &H08, &H00 ' Calibrate command
ioBuff.dim(1,3) = &HAC, &H33, &H00 ' Measure command
ioBuff.dim(2,6) ' Read results
I2C.setup 4, 5 ' SDA->GPIO4 (D2) SCL->GPIO5 (D1)
'Reset
I2C.begin address
I2C.write &HBA
I2C.end
' Calibrate
I2C.write_ioBuff(0), address, address
pause 500
I2C.read_ioBuff(2), address, address, 1
if ioBuff.read(2, 0) <> 24 then
wlog "Device error"
END
else
wlog "Calibrated device" + chr$(13)
gosub measure
endif
timer0 5000, measure ' time between measurements
wait
END
measure:
I2C.write_ioBuff(1), address, address
pause 100
I2C.read_ioBuff(2), address, address, 6
' Humidity
byte0 = ioBuff.read(2, 1) << 16
byte1 = ioBuff.read(2, 2) << 8
byte2 = ioBuff.read(2, 3)
value = (byte0 OR Byte1 OR byte2) >> 4
value = value * 100 / 1048576
message$ = "Sensor2: H= " + str$(value, "%2.2f")+ "%, "
' Temperature
byte3 = (ioBuff.read(2, 3) AND &H0F) << 16
byte4 = ioBuff.read(2, 4) << 8
byte5 = ioBuff.read(2, 5)
value = (byte3 OR byte4) OR byte5
value = ((value*200) / 1048576) - 50
message$ = message$ + "T= " + str$(value, "%2.2f") + "º"
wlog message$ + chr$(13)
return