AM2320.lua 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. --- AM2320 温湿度传感器驱动
  2. -- @module AM2320
  3. -- @author 稀饭放姜
  4. -- @license MIT
  5. -- @copyright openLuat.com
  6. -- @release 2017.10.19
  7. require "utils"
  8. module(..., package.seeall)
  9. -- 初始化并打开I2C操作
  10. -- @param I2C 内部ID
  11. -- @return number ,I2C的速率
  12. local function i2c_open(id)
  13. if i2c.setup(id, i2c.SLOW) ~= i2c.SLOW then
  14. log.error("I2C.init is: ", "fail")
  15. i2c.close(id)
  16. return
  17. end
  18. return i2c.SLOW
  19. end
  20. --- 读取AM2320的数据
  21. -- @number id, 端口号0-2
  22. -- @return string,string,第一个参数是温度,第二个是湿度
  23. -- @usage tmp, hum = read()
  24. function read(id)
  25. i2c_open(id)
  26. i2c.send(id, 0x5C, 0x03)
  27. i2c.send(id, 0x5C, {0x03, 0x00, 0x04})
  28. -- sys.wait(2)
  29. local data = i2c.recv(id, 0x5C, 8)
  30. i2c.close(id)
  31. if data == nil or data == 0 then return end
  32. local _, crc = pack.unpack(data, '<H', 7)
  33. data = data:sub(1, 6)
  34. if crc == crypto.crc16_modbus(data, 6) then
  35. local _, hum, tmp = pack.unpack(string.sub(data, 3, -1), '>H2')
  36. if tmp >= 0x8000 then tmp = 0x8000 - tmp end
  37. log.info("AM2320 data: ", tmp, hum)
  38. return tmp, hum
  39. end
  40. end