remove: 移除多余的mind目录
[LuatOS.git] / script / libs / bh1750.lua
blobb021d2137ebc2e5c2f4f7f27bedb6d1f06488bd1
1 --[[
2 @module bh1750
3 @summary bh1750 数字型光强度传感器
4 @version 1.0
5 @date 2022.03.15
6 @author Dozingfiretruck
7 @usage
8 --注意:因使用了sys.wait()所有api需要在协程中使用
9 -- 用法实例
10 local bh1750 = require "bh1750"
11 i2cid = 0
12 i2c_speed = i2c.FAST
13 sys.taskInit(function()
14 i2c.setup(i2cid,i2c_speed)
15 bh1750.init(i2cid)--初始化,传入i2c_id
16 while 1 do
17 local bh1750_data = bh1750.read_light()
18 log.info("bh1750_read_light", bh1750_data)
19 sys.wait(1000)
20 end
21 end)
24 local bh1750 = {}
26 local sys = require "sys"
28 local i2cid
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)
48 end
50 local function i2c_recv(num)
51 local revData = i2c.recv(i2cid, i2cslaveaddr, num)
52 return revData
53 end
55 function bh1750.power_on()
56 i2c_send(BH1750_POWER_ON)
57 end
59 function bh1750.power_down()
60 i2c_send(BH1750_POWER_DOWN)
61 end
63 local function bh1750_set_measure_mode(mode,time)
64 i2c_send(BH1750_RESET)
65 i2c_send(mode)
66 sys.wait(time)
67 end
69 --[[
70 bh1750初始化
71 @api bh1750.init(i2c_id)
72 @number 所在的i2c总线id
73 @return bool 成功返回true
74 @usage
75 bh1750.init(0)
77 function bh1750.init(i2c_id)
78 i2cid = i2c_id
79 bh1750.power_on()
80 log.info("bh1750 init_ok")
81 return true
82 end
84 --[[
85 获取bh1750数据
86 @api bh1750.read_light()
87 @return number 光照强度数据, 若读取失败会返回nil
88 @usage
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")
96 if light then
97 return light / 1.2
98 end
99 end
101 return bh1750