Skip to content

Instantly share code, notes, and snippets.

@wojtekka
Created April 15, 2019 19:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wojtekka/78d9939536c5d6a4c506031820fac49b to your computer and use it in GitHub Desktop.
Save wojtekka/78d9939536c5d6a4c506031820fac49b to your computer and use it in GitHub Desktop.
Simple code to read AM2320 connected to Raspberry Pi in Python without external libraries
# AM2320 connected to Raspberry Pi pin 3 (SDA) and 5 (SCL)
# Public domain
import sys
import fcntl
import time
import struct
I2C_SLAVE = 0x0703
AM2320_ADDR = 0x5c
def crc_am2320(buf):
crc = 0xffff
for c in buf:
if sys.version_info < (3, 0):
crc ^= ord(c)
else:
crc ^= c
for i in range(8):
if crc & 1:
crc >>= 1
crc ^= 0xa001
else:
crc >>= 1
return crc
def read_am2320(f, addr, count, tries=3):
fcntl.ioctl(f.fileno(), I2C_SLAVE, AM2320_ADDR)
buf = None
while tries > 0:
try:
f.write(struct.pack("BBB", 3, addr, count))
time.sleep(0.002)
buf = f.read(4 + count)
if len(buf) != 4 + count:
raise IOError
received_crc, = struct.unpack("<H", buf[-2:])
if received_crc != crc_am2320(buf[:-2]):
raise IOError
return buf[2:-2]
except IOError:
buf = None
time.sleep(0.002)
tries -= 1
continue
return None
if len(sys.argv) != 2:
print("usage: %s I2CDEVICE" % sys.argv[0])
exit(1)
f = open(sys.argv[1], "rb+", 0)
buf = read_am2320(f, 0, 4)
if not buf:
print("Unable to communicate")
exit(1)
humid_tenths, temp_tenths = struct.unpack(">HH", buf)
print("t=%.1f rh=%.1f" % (temp_tenths / 10.0, humid_tenths / 10.0))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment