main.lua 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. PROJECT = "sensor"
  2. VERSION = "1.0.0"
  3. require "log"
  4. require "sys"
  5. require "misc"
  6. -- i2c ID
  7. i2cid = 2
  8. -- i2c 速率
  9. speed = 100000
  10. -- 初始化
  11. function init(address)
  12. if i2c.setup(i2cid, speed, -1, 1) ~= speed then
  13. log.error("i2c", "setup fail", addr)
  14. return
  15. end
  16. addr = address
  17. end
  18. -- 发送数据
  19. function send(...)
  20. -- sys.wait(10)
  21. if not addr then
  22. log.info("i2c", "addr err")
  23. return
  24. end
  25. local t = {...}
  26. if i2c.send(i2cid, addr, t) ~= #t then
  27. log.error("i2c", "send fail", #t)
  28. return
  29. end
  30. return true
  31. end
  32. -- 读取数据
  33. function read(n)
  34. sys.wait(10)
  35. if not addr then
  36. log.info("i2c", "addr err")
  37. return "\x00"
  38. end
  39. val = i2c.recv(i2cid, addr, n)
  40. if val and #val>0 then
  41. return val
  42. end
  43. return "\x00"
  44. end
  45. --处理接收到数据
  46. function trans(dat)
  47. n = tonumber(dat:toHex(), 16)
  48. log.info("raw",dat:toHex())
  49. if not n then return end
  50. temp = n / 8
  51. if (temp >= 8192) then
  52. temp = temp - 8192
  53. end
  54. t = temp * 0.0625
  55. return t
  56. end
  57. function LM92()
  58. init(0x48)
  59. send(0x01)
  60. read(2)
  61. send(0x01, 0x10)
  62. send(0x00)
  63. read(2)
  64. sys.wait(300)
  65. while true do
  66. send(0)
  67. log.info("raw data", trans(read(2)))
  68. sys.wait(800)
  69. end
  70. end
  71. sys.taskInit(function()
  72. LM92()
  73. end)
  74. sys.init(0, 0)
  75. sys.run()