main.lua 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 TSL2561()
  47. init(0x39) -- 初始化
  48. send(0x80, 0x03) -- 启动
  49. send(0x81, 0x02) -- 积分时间
  50. sys.wait(300)
  51. while true do
  52. local s = ""
  53. for i=0, 3 do
  54. send(140+i)
  55. s = s..read(1)
  56. sys.wait(200)
  57. end
  58. _, ch0, ch1 = pack.unpack(s, "<HH")
  59. log.info("Full Spectrum(IR + Visible)", ch0)
  60. log.info("Infrared Value", ch1)
  61. log.info("Visible Value", ch0-ch1)
  62. end
  63. end
  64. sys.taskInit(function()
  65. sys.wait(3000)
  66. TSL2561()
  67. end)
  68. sys.init(0, 0)
  69. sys.run()