gobot.io/x/gobot/v2@v2.1.0/drivers/i2c/bh1750_driver.go (about)

     1  package i2c
     2  
     3  import (
     4  	"errors"
     5  	"time"
     6  )
     7  
     8  const bh1750DefaultAddress = 0x23
     9  
    10  const (
    11  	BH1750_POWER_DOWN                 = 0x00
    12  	BH1750_POWER_ON                   = 0x01
    13  	BH1750_RESET                      = 0x07
    14  	BH1750_CONTINUOUS_HIGH_RES_MODE   = 0x10
    15  	BH1750_CONTINUOUS_HIGH_RES_MODE_2 = 0x11
    16  	BH1750_CONTINUOUS_LOW_RES_MODE    = 0x13
    17  	BH1750_ONE_TIME_HIGH_RES_MODE     = 0x20
    18  	BH1750_ONE_TIME_HIGH_RES_MODE_2   = 0x21
    19  	BH1750_ONE_TIME_LOW_RES_MODE      = 0x23
    20  )
    21  
    22  // BH1750Driver is a driver for the BH1750 digital Ambient Light Sensor IC for I²C bus interface.
    23  //
    24  type BH1750Driver struct {
    25  	*Driver
    26  	mode byte
    27  }
    28  
    29  // NewBH1750Driver creates a new driver with specified i2c interface
    30  // Params:
    31  //		c Connector - the Adaptor to use with this Driver
    32  //
    33  // Optional params:
    34  //		i2c.WithBus(int):	bus to use with this driver
    35  //		i2c.WithAddress(int):	address to use with this driver
    36  //
    37  func NewBH1750Driver(c Connector, options ...func(Config)) *BH1750Driver {
    38  	h := &BH1750Driver{
    39  		Driver: NewDriver(c, "BH1750", bh1750DefaultAddress),
    40  		mode:   BH1750_CONTINUOUS_HIGH_RES_MODE,
    41  	}
    42  	h.afterStart = h.initialize
    43  
    44  	for _, option := range options {
    45  		option(h)
    46  	}
    47  
    48  	// TODO: add commands for API
    49  	return h
    50  }
    51  
    52  // RawSensorData returns the raw value from the bh1750
    53  func (h *BH1750Driver) RawSensorData() (level int, err error) {
    54  
    55  	buf := []byte{0, 0}
    56  	bytesRead, err := h.connection.Read(buf)
    57  	if bytesRead != 2 {
    58  		err = errors.New("wrong number of bytes read")
    59  		return
    60  	}
    61  	if err != nil {
    62  		return
    63  	}
    64  	level = int(buf[0])<<8 | int(buf[1])
    65  
    66  	return
    67  }
    68  
    69  // Lux returns the adjusted value from the bh1750
    70  func (h *BH1750Driver) Lux() (lux int, err error) {
    71  
    72  	lux, err = h.RawSensorData()
    73  	lux = int(float64(lux) / 1.2)
    74  
    75  	return
    76  }
    77  
    78  func (h *BH1750Driver) initialize() error {
    79  	err := h.connection.WriteByte(h.mode)
    80  	time.Sleep(10 * time.Microsecond)
    81  	if err != nil {
    82  		return err
    83  	}
    84  	return nil
    85  }