cht8305c.lua 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. --[[
  2. @module cht8305c
  3. @summary cht8305c 温湿度传感器
  4. @version 1.0
  5. @date 2023.07.21
  6. @author wendal
  7. @usage
  8. --注意:因使用了sys.wait()所有api需要在协程中使用
  9. -- 用法实例
  10. local cht8305c = require "cht8305c"
  11. i2cid = 0
  12. i2c_speed = i2c.FAST
  13. sys.taskInit(function()
  14. i2c.setup(i2cid,i2c_speed)
  15. cht8305c.init(i2cid)--初始化,传入i2c_id
  16. while 1 do
  17. local data = cht8305c.get_data()
  18. if data and data.RH then
  19. local tmp = string.format("RH: %.2f T: %.2f ℃", data.RH*100, data.T)
  20. log.info("cht8305c", tmp)
  21. else
  22. log.info("cht8305c", "读取失败")
  23. end
  24. sys.wait(1000)
  25. end
  26. end)
  27. ]]
  28. local cht8305c = {}
  29. local sys = require "sys"
  30. local i2cid
  31. local cht8305c_addr = 0x40
  32. --[[
  33. cht8305c初始化
  34. @api cht8305c.init(i2c_id)
  35. @number 所在的i2c总线id
  36. @return bool 成功返回true
  37. @usage
  38. cht8305c.init(0)
  39. ]]
  40. function cht8305c.init(i2c_id)
  41. i2cid = i2c_id
  42. sys.wait(20)
  43. local Manufacture = i2c.readReg(i2cid, cht8305c_addr, 0xFE, 2)
  44. -- log.info("cht8305c", "Manufacture", Manufacture and Manufacture:toHex() or "??")
  45. if Manufacture and Manufacture:byte() == 0x59 then
  46. log.info("cht8305c init_ok")
  47. return true
  48. else
  49. log.info("cht8305c init_fail")
  50. end
  51. end
  52. --[[
  53. 获取cht8305c数据
  54. @api cht8305c.get_data()
  55. @return table cht8305c数据
  56. ]]
  57. function cht8305c.get_data()
  58. local data={RH=nil,T=nil}
  59. i2c.send(i2cid, cht8305c_addr, string.char(0))
  60. sys.wait(22)
  61. local tmp = i2c.recv(i2cid, cht8305c_addr, 4)
  62. -- log.info("CHT8305C", tmp and tmp:toHex() or "??")
  63. if tmp and #tmp == 4 then
  64. local _, temp, hum = pack.unpack(tmp, ">HH")
  65. data.T = (165 * temp) / 65535.0 - 40
  66. data.RH = hum / 65535.0
  67. -- log.info("CHT8305C", temp, hum)
  68. end
  69. return data
  70. end
  71. return cht8305c