bh1750.lua 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. -- ***************************************************************************
  2. -- BH1750 module for ESP8266 with nodeMCU
  3. -- BH1750 compatible tested 2015-1-22
  4. --
  5. -- Written by xiaohu
  6. --
  7. -- MIT license, http://opensource.org/licenses/MIT
  8. -- ***************************************************************************
  9. local moduleName = ...
  10. local M = {}
  11. _G[moduleName] = M
  12. --I2C slave address of GY-30
  13. local GY_30_address = 0x23
  14. -- i2c interface ID
  15. local id = 0
  16. --LUX
  17. local l
  18. --CMD
  19. local CMD = 0x10
  20. local init = false
  21. --Make it more faster
  22. local i2c = i2c
  23. function M.init(sda, scl)
  24. i2c.setup(id, sda, scl, i2c.SLOW)
  25. --print("i2c ok..")
  26. init = true
  27. end
  28. local function read_data(ADDR, commands, length)
  29. i2c.start(id)
  30. i2c.address(id, ADDR, i2c.TRANSMITTER)
  31. i2c.write(id, commands)
  32. i2c.stop(id)
  33. i2c.start(id)
  34. i2c.address(id, ADDR,i2c.RECEIVER)
  35. tmr.delay(200000)
  36. local c = i2c.read(id, length)
  37. i2c.stop(id)
  38. return c
  39. end
  40. local function read_lux()
  41. local dataT = read_data(GY_30_address, CMD, 2)
  42. --Make it more faster
  43. local UT = dataT:byte(1) * 256 + dataT:byte(2)
  44. l = (UT*1000/12)
  45. return(l)
  46. end
  47. function M.read()
  48. if (not init) then
  49. print("init() must be called before read.")
  50. else
  51. read_lux()
  52. end
  53. end
  54. function M.getlux()
  55. return l
  56. end
  57. return M