AM2320.lua 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. require "utils"
  2. module(..., package.seeall)
  3. local i2cslaveaddr = 0x5C -- 8bit地址为0xb8 7bit 为0x5C
  4. local function i2c_open(id)
  5. if i2c.setup(id, i2c.SLOW) ~= i2c.SLOW then
  6. log.error("AM2320", "I2C.init is: fail")
  7. i2c.close(id)
  8. return
  9. else
  10. log.error("AM2320", "I2C.init is: succeed")
  11. end
  12. return i2c.SLOW
  13. end
  14. function read(id)
  15. i2c.send(id, i2cslaveaddr, 0x03)
  16. -- 查询功能码:0x03 查询的寄存器首地址:0 长度:4
  17. i2c.send(id, i2cslaveaddr, {0x03, 0x00, 0x04})
  18. sys.wait(2)
  19. local data = i2c.recv(id, i2cslaveaddr, 8)
  20. -- 传感器返回的8位数据格式:
  21. -- 1 2 3 4 5 6 7 8
  22. -- 0x03 0x04 0x03 0x39 0x01 0x15 0xE1 0XFE
  23. -- 功能码 数据长度 湿度高位 湿度数据 温度高位 温度低位 CRC低 CRC高
  24. if data == nil or data == 0 then
  25. return
  26. end
  27. -- log.info("AM2320", "buf data:", buf)
  28. log.info("AM2320", "HEX data:", data:toHex())
  29. i2c.close(id)
  30. local _, crc = pack.unpack(data, '<H', 7)
  31. data = data:sub(1, 6)
  32. if crc == crypto.crc16_modbus(data, 6) then
  33. local _, hum, tmp = pack.unpack(string.sub(data, 3, -1), '>H2')
  34. -- 正负温度处理
  35. if tmp >= 0x8000 then
  36. tmp = 0x8000 - tmp
  37. end
  38. tmp, hum = tmp / 10, hum / 10
  39. log.info("AM2320", "data(tmp hum):", tmp, hum)
  40. return tmp, hum
  41. end
  42. end
  43. function byte2bin(n)
  44. local t = {}
  45. for i = 7, 0, -1 do
  46. t[#t + 1] = math.floor(n / 2 ^ i)
  47. n = n % 2 ^ i
  48. end
  49. return table.concat(t)
  50. end
  51. sys.taskInit(function()
  52. while true do
  53. sys.wait(5000)
  54. log.info("!!!", "************************START************************")
  55. i2c_open(2)
  56. read(2)
  57. log.info("!!!", "************************END************************")
  58. end
  59. end)