3 @summary bh1750 数字型光强度传感器
6 @author Dozingfiretruck
8 --注意:因使用了sys.wait()所有api需要在协程中使用
10 local bh1750 = require "bh1750"
13 sys.taskInit(function()
14 i2c.setup(i2cid,i2c_speed)
15 bh1750.init(i2cid)--初始化,传入i2c_id
17 local bh1750_data = bh1750.read_light()
18 log.info("bh1750_read_light", bh1750_data)
26 local sys
= require
"sys"
30 local BH1750_ADDRESS_AD0_LOW
= 0x23 -- address pin low (GND), default for InvenSense evaluation board
31 local BH1750_ADDRESS_AD0_HIGH
= 0x24 -- address pin high (VCC)
33 local i2cslaveaddr
= BH1750_ADDRESS_AD0_LOW
35 -- bh1750 registers define
36 local BH1750_POWER_DOWN
= 0x00 -- power down
37 local BH1750_POWER_ON
= 0x01 -- power on
38 local BH1750_RESET
= 0x07 -- reset
39 local BH1750_CON_H_RES_MODE
= 0x10 -- Continuously H-Resolution Mode
40 local BH1750_CON_H_RES_MODE2
= 0x11 -- Continuously H-Resolution Mode2
41 local BH1750_CON_L_RES_MODE
= 0x13 -- Continuously L-Resolution Mode
42 local BH1750_ONE_H_RES_MODE
= 0x20 -- One Time H-Resolution Mode
43 local BH1750_ONE_H_RES_MODE2
= 0x21 -- One Time H-Resolution Mode2
44 local BH1750_ONE_L_RES_MODE
= 0x23 -- One Time L-Resolution Mode
46 local function i2c_send(data
)
47 i2c
.send(i2cid
, i2cslaveaddr
, data
)
50 local function i2c_recv(num
)
51 local revData
= i2c
.recv(i2cid
, i2cslaveaddr
, num
)
55 function bh1750
.power_on()
56 i2c_send(BH1750_POWER_ON
)
59 function bh1750
.power_down()
60 i2c_send(BH1750_POWER_DOWN
)
63 local function bh1750_set_measure_mode(mode
,time
)
64 i2c_send(BH1750_RESET
)
71 @api bh1750.init(i2c_id)
77 function bh1750
.init(i2c_id
)
80 log.info("bh1750 init_ok")
86 @api bh1750.read_light()
87 @return number 光照强度数据, 若读取失败会返回nil
89 local bh1750_data = bh1750.read_light()
90 log.info("bh1750_read_light", bh1750_data)
92 function bh1750
.read_light()
93 bh1750_set_measure_mode(BH1750_CON_H_RES_MODE
, 180)
94 -- local _,light = pack.unpack(i2c_recv(2),">h") -- 极端情况下数据溢出导致的光照出现负值, 如string.toHex(i2c_recv(2)) == "FFFF"
95 local _
,light
= pack
.unpack(i2c_recv(2),">H")