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

     1  package i2c
     2  
     3  import (
     4  	"time"
     5  )
     6  
     7  const lidarliteDefaultAddress = 0x62
     8  
     9  // LIDARLiteDriver is the Gobot driver for the LIDARLite I2C LIDAR device.
    10  type LIDARLiteDriver struct {
    11  	*Driver
    12  }
    13  
    14  // NewLIDARLiteDriver creates a new driver for the LIDARLite I2C LIDAR device.
    15  //
    16  // Params:
    17  //		c Connector - the Adaptor to use with this Driver
    18  //
    19  // Optional params:
    20  //		i2c.WithBus(int):	bus to use with this driver
    21  //		i2c.WithAddress(int):	address to use with this driver
    22  //
    23  func NewLIDARLiteDriver(c Connector, options ...func(Config)) *LIDARLiteDriver {
    24  	l := &LIDARLiteDriver{
    25  		Driver: NewDriver(c, "LIDARLite", lidarliteDefaultAddress),
    26  	}
    27  
    28  	for _, option := range options {
    29  		option(l)
    30  	}
    31  
    32  	// TODO: add commands to API
    33  	return l
    34  }
    35  
    36  // Distance returns the current distance in cm
    37  func (h *LIDARLiteDriver) Distance() (distance int, err error) {
    38  	if _, err = h.connection.Write([]byte{0x00, 0x04}); err != nil {
    39  		return
    40  	}
    41  	time.Sleep(20 * time.Millisecond)
    42  
    43  	if _, err = h.connection.Write([]byte{0x0F}); err != nil {
    44  		return
    45  	}
    46  
    47  	upper := []byte{0}
    48  	bytesRead, err := h.connection.Read(upper)
    49  	if err != nil {
    50  		return
    51  	}
    52  
    53  	if bytesRead != 1 {
    54  		err = ErrNotEnoughBytes
    55  		return
    56  	}
    57  
    58  	if _, err = h.connection.Write([]byte{0x10}); err != nil {
    59  		return
    60  	}
    61  
    62  	lower := []byte{0}
    63  	bytesRead, err = h.connection.Read(lower)
    64  	if err != nil {
    65  		return
    66  	}
    67  
    68  	if bytesRead != 1 {
    69  		err = ErrNotEnoughBytes
    70  		return
    71  	}
    72  
    73  	distance = ((int(upper[0]) & 0xff) << 8) | (int(lower[0]) & 0xff)
    74  
    75  	return
    76  }