AM2320.lua 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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
  41. --
  42. --
  43. function sht30read(id)
  44. local te,hu
  45. i2c_open(id)
  46. i2c.send(id,0x44,{0x2c,0x06})
  47. local sht30_data = i2c.recv(id,0x44,6)
  48. if sht30_data == nil then sht30_data = 0 end
  49. log.info("SHT30 HEX DATA:",string.toHex(sht30_data," "))
  50. i2c.close(id)
  51. if sht30_data ~= 0 then
  52. local _,h_H,h_L,h_crc,t_H,t_L,t_crc = pack.unpack(sht30_data,'b6')
  53. if h_H == nil then return end
  54. te = ((1750*(h_H*256+h_L)/65535-450))
  55. hu = ((1000*(t_H*256+t_L)/65535))
  56. log.warn("SHT30 temp,humi:",te,hu)
  57. return te,hu
  58. end
  59. end