gobot.io/x/gobot@v1.16.0/drivers/i2c/bh1750_driver.go (about) 1 package i2c 2 3 import ( 4 "time" 5 "errors" 6 7 "gobot.io/x/gobot" 8 ) 9 10 const bh1750Address = 0x23 11 12 const ( 13 BH1750_POWER_DOWN = 0x00 14 BH1750_POWER_ON = 0x01 15 BH1750_RESET = 0x07 16 BH1750_CONTINUOUS_HIGH_RES_MODE = 0x10 17 BH1750_CONTINUOUS_HIGH_RES_MODE_2 = 0x11 18 BH1750_CONTINUOUS_LOW_RES_MODE = 0x13 19 BH1750_ONE_TIME_HIGH_RES_MODE = 0x20 20 BH1750_ONE_TIME_HIGH_RES_MODE_2 = 0x21 21 BH1750_ONE_TIME_LOW_RES_MODE = 0x23 22 ) 23 24 // BH1750Driver is a driver for the BH1750 digital Ambient Light Sensor IC for I²C bus interface. 25 // 26 type BH1750Driver struct { 27 name string 28 connector Connector 29 connection Connection 30 mode byte 31 Config 32 } 33 34 // NewBH1750Driver creates a new driver with specified i2c interface 35 // Params: 36 // conn Connector - the Adaptor to use with this Driver 37 // 38 // Optional params: 39 // i2c.WithBus(int): bus to use with this driver 40 // i2c.WithAddress(int): address to use with this driver 41 // 42 func NewBH1750Driver(a Connector, options ...func(Config)) *BH1750Driver { 43 m := &BH1750Driver{ 44 name: gobot.DefaultName("BH1750"), 45 connector: a, 46 Config: NewConfig(), 47 mode: BH1750_CONTINUOUS_HIGH_RES_MODE, 48 } 49 50 for _, option := range options { 51 option(m) 52 } 53 54 // TODO: add commands for API 55 return m 56 } 57 58 // Name returns the Name for the Driver 59 func (h *BH1750Driver) Name() string { return h.name } 60 61 // SetName sets the Name for the Driver 62 func (h *BH1750Driver) SetName(n string) { h.name = n } 63 64 // Connection returns the connection for the Driver 65 func (h *BH1750Driver) Connection() gobot.Connection { return h.connector.(gobot.Connection) } 66 67 // Start initialized the bh1750 68 func (h *BH1750Driver) Start() (err error) { 69 bus := h.GetBusOrDefault(h.connector.GetDefaultBus()) 70 address := h.GetAddressOrDefault(bh1750Address) 71 72 h.connection, err = h.connector.GetConnection(address, bus) 73 if err != nil { 74 return err 75 } 76 77 err = h.connection.WriteByte(h.mode) 78 time.Sleep(10 * time.Microsecond) 79 if err != nil { 80 return err 81 } 82 83 return 84 } 85 86 // Halt returns true if devices is halted successfully 87 func (h *BH1750Driver) Halt() (err error) { return } 88 89 // RawSensorData returns the raw value from the bh1750 90 func (h *BH1750Driver) RawSensorData() (level int, err error) { 91 92 buf := []byte{0, 0} 93 bytesRead, err := h.connection.Read(buf) 94 if bytesRead != 2 { 95 err = errors.New("wrong number of bytes read") 96 return 97 } 98 if err != nil { 99 return 100 } 101 level = int(buf[0])<<8 | int(buf[1]) 102 103 return 104 } 105 106 // Lux returns the adjusted value from the bh1750 107 func (h *BH1750Driver) Lux() (lux int, err error) { 108 109 lux, err = h.RawSensorData() 110 lux = int(float64(lux) / 1.2) 111 112 return 113 }