LM75B.lua 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. module(..., package.seeall)
  2. require "utils"
  3. local i2cslaveaddr = 0x48
  4. local function read_am2320(id)
  5. i2c.close(id)
  6. if i2c.setup(id, i2c.SLOW, i2cslaveaddr) ~= i2c.SLOW then
  7. log.error("I2C.init is: fail ", id, i2cslaveaddr)
  8. i2c.close(id)
  9. return
  10. else
  11. local buf = i2c.read(2, 0x00, 2)
  12. log.info("LM75B", "HEX data:", buf:toHex())
  13. -- 传感器返回数据格式:
  14. -- 1 2 3 4 5 6 7 8
  15. -- 符号位 [ 温度数据(单位 0.5摄氏度)]
  16. if buf == nil or buf == 0 then
  17. return
  18. end
  19. local data = byte2bin(string.byte(buf)) .. byte2bin(string.byte(buf, 2))
  20. log.info("LM75", "DATA(full)", data)
  21. -- log.error("LM75"," buf LEN",string.len(buf))
  22. -- 提取符号位
  23. zero_tem = data:sub(1, 1)
  24. data = data:sub(2, 9)
  25. log.info("LM75", "DATA(2-9)", data)
  26. local _, tmp = pack.unpack(data, 'b8')
  27. if zero_tem == "0" then
  28. log.info("LM75B", "温度+", tmp / 2)
  29. else
  30. log.info("LM75B", "温度-", 128-tmp / 2)
  31. end
  32. return
  33. end
  34. end
  35. function byte2bin(n)
  36. local t = {}
  37. for i = 7, 0, -1 do
  38. t[#t + 1] = math.floor(n / 2 ^ i)
  39. n = n % 2 ^ i
  40. end
  41. return table.concat(t)
  42. end
  43. sys.taskInit(function()
  44. while true do
  45. sys.wait(5000)
  46. log.info("!!!", "************************START************************")
  47. read_am2320(2)
  48. log.info("!!!", "************************END************************")
  49. end
  50. end)