AM2320 I2C Temperature & Humidity Sensor.

Place code snippets and demo code here
Post Reply
AndyGadget
Posts: 222
Joined: Mon Feb 15, 2021 1:44 pm
Has thanked: 120 times
Been thanked: 132 times

AM2320 I2C Temperature & Humidity Sensor.

Post by AndyGadget »

The AM2320 is an advance on the DHT22 / AM2302 devices and adds I2C functionality.

After having trouble with long-term relability of humidity readings on BME280 devices I was looking for an Annex usable temperature / humidity module to do this. I turned to the AM2302 but there is a known bug with the temperature MSB with certain devices / drivers (I've detailed my trials and tribulations with this elsewhere in the forum) and the AM2320 addresses this.

The AM2320 is a bit like a lazy human - You've got to give it a prod to wake it up, give it an instruction and then wait a while for it to do it. After it's done it it goes back to sleep again, but gets grouchy if you tell it to do something again before it's had another nap. Also, if you wait to long after waking it, it will go back to sleep again.

Here's a bit of Annex code to read temperature and humidity from an I2C connected AM2320.
The delays are important!

Code: [Local Link Removed for Guests]

'  I2C operaiton of AM2320 temperature and humidity sensor.
'  Similar to DHT22 / AM2302 but with I2C capability and addresses temperature MSB bug.
'  Single wire operation is not compatible with Annex DHT functions.
'  Device address on I2C bus is &H5C (92 decimal). 
'  Untested on the device for negative temperatures.  (OK in simulation).

i2c.setup 4,5
wlog
wlog "Start"

iobuff.dim (1, 8)    ' Initialise io buffer to accept received data

do
  I2C.BEGIN &h5C    ' First write wakes up AM2320
  z =  i2c.end
  
  I2C.BEGIN &h5C     ' Write to device to start measurement
  I2C.WRITE &h03
  I2C.WRITE &h00
  I2C.WRITE &h04
  if i2c.end <> 0 then    ' Check for acknowledgement of command
    wlog "Device Error"
  endif
  
  pause 2200        ' Delay to allow measurement to complete
  
  I2C.READ_IOBUFF(1), &H5C, 0, 8    ' Check for 8 bytes returned by device
  if iobuff.len(1) = 8 then
    Hum = ((iobuff.read(1,2) * 256) + iobuff.read(1,3)) /10
    
if iobuff.read(1,4) > &H7F then    ' Test for top bit of temperature byte set which indicates negative value    
    Tmp =  -(((iobuff.read(1,4) and &H7F) * 256) + iobuff.read(1,5)) /10    ' Mask top bit and make negative if set.
else
    Tmp = ((iobuff.read(1,4) * 256) + iobuff.read(1,5)) /10 
end if

    wlog Hum, Tmp
  else
    wlog "Invalid device read operation"
  end if
  
  pause 1000    ' Pause to allow device to sleep again
loop
Post Reply