bh1750.lua 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. --- 模块功能:BH1750
  2. -- @module BH1750
  3. -- @author Dozingfiretruck
  4. -- @license MIT
  5. -- @copyright OpenLuat.com
  6. -- @release 2021.03.14
  7. module(...,package.seeall)
  8. require"utils"
  9. require"bit"
  10. pm.wake("bh1750")
  11. local i2cid = 2 --i2cid
  12. local BH1750_ADDRESS_AD0_LOW = 0x23 -- address pin low (GND), default for InvenSense evaluation board
  13. local BH1750_ADDRESS_AD0_HIGH = 0x24 -- address pin high (VCC)
  14. local i2cslaveaddr = BH1750_ADDRESS_AD0_LOW
  15. -- bh1750 registers define
  16. local BH1750_POWER_DOWN = 0x00 -- power down
  17. local BH1750_POWER_ON = 0x01 -- power on
  18. local BH1750_RESET = 0x07 -- reset
  19. local BH1750_CON_H_RES_MODE = 0x10 -- Continuously H-Resolution Mode
  20. local BH1750_CON_H_RES_MODE2 = 0x11 -- Continuously H-Resolution Mode2
  21. local BH1750_CON_L_RES_MODE = 0x13 -- Continuously L-Resolution Mode
  22. local BH1750_ONE_H_RES_MODE = 0x20 -- One Time H-Resolution Mode
  23. local BH1750_ONE_H_RES_MODE2 = 0x21 -- One Time H-Resolution Mode2
  24. local BH1750_ONE_L_RES_MODE = 0x23 -- One Time L-Resolution Mode
  25. local function i2c_send(data)
  26. i2c.send(i2cid, i2cslaveaddr, data)
  27. end
  28. local function i2c_recv(num)
  29. local revData = i2c.recv(i2cid, i2cslaveaddr, num)
  30. return revData
  31. end
  32. local function bh1750_power_on()
  33. i2c_send(BH1750_POWER_ON)
  34. end
  35. local function bh1750_power_down()
  36. i2c_send(BH1750_POWER_DOWN)
  37. end
  38. local function bh1750_set_measure_mode(mode,time)
  39. i2c_send(BH1750_RESET)
  40. i2c_send(mode)
  41. sys.wait(time)
  42. end
  43. local function bh1750_read_light()
  44. bh1750_set_measure_mode(BH1750_CON_H_RES_MODE2, 180)
  45. local _,light = pack.unpack(i2c_recv(2),">h")
  46. if light then
  47. light = light / 1.2 * 10
  48. end
  49. return light;
  50. end
  51. local function bh1750_test()
  52. sys.wait(4000)
  53. if i2c.setup(i2cid,i2c.SLOW) ~= i2c.SLOW then
  54. log.error("I2c.init","fail")
  55. return
  56. end
  57. bh1750_power_on()
  58. sys.wait(180)
  59. while true do
  60. log.info("bh1750_read_light", bh1750_read_light())
  61. sys.wait(1000)
  62. end
  63. end
  64. sys.taskInit(bh1750_test)