| Posted: 12:03pm 04 Oct 2023 |
|
|
|
I think the others have slightly higher accuracy than the AHT10, but haven't looked into the datasheets very closely.
To avoid a delay between initiating a read and outputting the data many sensors do it back to front. When you query them they output data from the previous read then get new data and save it for the next read.
The AHT10 has separate initiate and read commands so can work either way.
The Sub in this program avoids the 75mS pause by using the reverse method.
> LIST 'Read AHT10 using System I2C
Dim Integer dat(6), addr = &H38, bytes5, n Dim Float humid, temp
Print "rel. humidity temp" I2C write addr, 0, 3, 172, 51, 0 'trigger first measurement Pause 75 'wait for data
Sub AHT10 I2C read addr, 1, 6, dat() 'read 6 data bytes bytes5 = 0
For n=1 To 5 bytes5 = bytes5 + (dat(6-n)<<8*(n-1)) 'Assemble 40 bit word Next
humid = bytes5 / &H10000000000 * 100 'extract humidity temp = (bytes5 And &Hfffff) / &H100000 * 200 - 50 'extract temperature humid = CInt(humid) 'round humid temp = CInt(temp * 10) * 0.1 'round temp
I2C write addr, 0, 3, 172, 51, 0 'trigger measurement for next read End Sub
Do AHT10 Print humid;" %",, temp;" C" Pause 2000 ' read every 2S Loop
End >
Edit. The AHT10 provides 20 bits each for humidity and temperature, which greatly exceeds the accuracy of it. This streamlined version uses 8 bits for humidity and 12 bits for temperature.
'Read AHT10 using System I2C
Dim Integer dat(4), addr = &H38 Dim Float humid, temp
Print "rel. humidity temp" I2C write addr, 0, 3, 172, 51, 0 'trigger first measurement Pause 75 'wait for data
Sub AHT10 I2C read addr, 1, 5, dat() 'read first 5 data bytes - last one not needed humid = Cint(dat(1) * 0.390625) temp = Cint((((dat(3) And 15) << 8) + dat(4)) * 0.48828125 - 500) * 0.1
I2C write addr, 0, 3, 172, 51, 0 'trigger measurement for next read End Sub
Do AHT10 Print humid;" %",, temp;" C" Pause 2000 ' read every 2S Loop
End
> RUN rel. humidity temp 63 % 14 C 63 % 14.1 C 63 % 14 C 63 % 14 C >
Edit 2 Was curious to know what the first byte - the "State" byte (= &H1C) was for. The data sheet doesn't say so ran a loop continually reading the device and printing dat(0) and the timer. Between initiating a read and getting new data dat(0) = &H9C then changes to &H1C. This takes about 42mS on my unit so the recommended pause of 75mS is longer than needed. If you want the shortest possible read time keep reading until dat(0) changes then you have new data.
Sub AHT10 I2C write AHaddr, 0, 3, 172, 51, 0 'trigger measurement for next read Timer =0:Do :I2C read AHaddr,1,5,dat():Loop Until dat(0)=28:Print Timer,, humid = Cint(dat(1) * 0.390625) temp = Cint((((dat(3) And 15) << 8) + dat(4)) * 0.48828125 - 500) * 0.1 'read first 5 data bytes - last one not needed. End Sub
Timer rel. humidity temp 41.548 71 % 13 C 41.655 71 % 13 C 41.694 71 % 13.1 C 41.682 76 % 13.1 C 41.724 77 % 13.1 C 41.562 77 % 13.1 C 41.679 77 % 13.1 C
Edited 2023-10-16 14:28 by phil99 |