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