forked from tinygo-org/drivers
-
Notifications
You must be signed in to change notification settings - Fork 1
/
bh1750.go
70 lines (59 loc) · 1.67 KB
/
bh1750.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Package bh1750 provides a driver for the BH1750 digital Ambient Light
//
// Datasheet:
// https://www.mouser.com/ds/2/348/bh1750fvi-e-186247.pdf
//
package bh1750
import (
"time"
"machine"
)
// SamplingMode is the sampling's resolution of the measurement
type SamplingMode byte
// Device wraps an I2C connection to a bh1750 device.
type Device struct {
bus machine.I2C
mode SamplingMode
}
// New creates a new bh1750 connection. The I2C bus must already be
// configured.
//
// This function only creates the Device object, it does not touch the device.
func New(bus machine.I2C) Device {
return Device{
bus: bus,
mode: CONTINUOUS_HIGH_RES_MODE,
}
}
// Configure sets up the device for communication
func (d *Device) Configure() {
d.bus.Tx(Address, []byte{POWER_ON}, nil)
d.SetMode(d.mode)
}
// RawSensorData returns the raw value from the bh1750
func (d *Device) RawSensorData() uint16 {
buf := []byte{1, 0}
d.bus.Tx(Address, nil, buf)
return (uint16(buf[0]) << 8) | uint16(buf[1])
}
// Illuminance returns the adjusted value in mlx (milliLux)
func (d *Device) Illuminance() int32 {
lux := uint32(d.RawSensorData())
var coef uint32
if d.mode == CONTINUOUS_HIGH_RES_MODE || d.mode == ONE_TIME_HIGH_RES_MODE {
coef = HIGH_RES
} else if d.mode == CONTINUOUS_HIGH_RES_MODE_2 || d.mode == ONE_TIME_HIGH_RES_MODE_2 {
coef = HIGH_RES2
} else {
coef = LOW_RES
}
// 100 * coef * lux * (5/6)
// 5/6 = measurement accuracy as per the datasheet
return int32(250 * coef * lux / 3)
}
// SetMode changes the reading mode for the sensor
func (d *Device) SetMode(mode SamplingMode) {
d.mode = mode
d.bus.Tx(Address, []byte{byte(d.mode)}, nil)
time.Sleep(10 * time.Millisecond)
}