gobot.io/x/gobot@v1.16.0/drivers/i2c/lidarlite_driver.go (about) 1 package i2c 2 3 import ( 4 "gobot.io/x/gobot" 5 6 "time" 7 ) 8 9 const lidarliteAddress = 0x62 10 11 // LIDARLiteDriver is the Gobot driver for the LIDARLite I2C LIDAR device. 12 type LIDARLiteDriver struct { 13 name string 14 connector Connector 15 connection Connection 16 Config 17 } 18 19 // NewLIDARLiteDriver creates a new driver for the LIDARLite I2C LIDAR device. 20 // 21 // Params: 22 // conn Connector - the Adaptor to use with this Driver 23 // 24 // Optional params: 25 // i2c.WithBus(int): bus to use with this driver 26 // i2c.WithAddress(int): address to use with this driver 27 // 28 func NewLIDARLiteDriver(a Connector, options ...func(Config)) *LIDARLiteDriver { 29 l := &LIDARLiteDriver{ 30 name: gobot.DefaultName("LIDARLite"), 31 connector: a, 32 Config: NewConfig(), 33 } 34 35 for _, option := range options { 36 option(l) 37 } 38 39 // TODO: add commands to API 40 return l 41 } 42 43 // Name returns the Name for the Driver 44 func (h *LIDARLiteDriver) Name() string { return h.name } 45 46 // SetName sets the Name for the Driver 47 func (h *LIDARLiteDriver) SetName(n string) { h.name = n } 48 49 // Connection returns the connection for the Driver 50 func (h *LIDARLiteDriver) Connection() gobot.Connection { return h.connector.(gobot.Connection) } 51 52 // Start initialized the LIDAR 53 func (h *LIDARLiteDriver) Start() (err error) { 54 bus := h.GetBusOrDefault(h.connector.GetDefaultBus()) 55 address := h.GetAddressOrDefault(lidarliteAddress) 56 57 h.connection, err = h.connector.GetConnection(address, bus) 58 if err != nil { 59 return err 60 } 61 return 62 } 63 64 // Halt returns true if devices is halted successfully 65 func (h *LIDARLiteDriver) Halt() (err error) { return } 66 67 // Distance returns the current distance in cm 68 func (h *LIDARLiteDriver) Distance() (distance int, err error) { 69 if _, err = h.connection.Write([]byte{0x00, 0x04}); err != nil { 70 return 71 } 72 time.Sleep(20 * time.Millisecond) 73 74 if _, err = h.connection.Write([]byte{0x0F}); err != nil { 75 return 76 } 77 78 upper := []byte{0} 79 bytesRead, err := h.connection.Read(upper) 80 if err != nil { 81 return 82 } 83 84 if bytesRead != 1 { 85 err = ErrNotEnoughBytes 86 return 87 } 88 89 if _, err = h.connection.Write([]byte{0x10}); err != nil { 90 return 91 } 92 93 lower := []byte{0} 94 bytesRead, err = h.connection.Read(lower) 95 if err != nil { 96 return 97 } 98 99 if bytesRead != 1 { 100 err = ErrNotEnoughBytes 101 return 102 } 103 104 distance = ((int(upper[0]) & 0xff) << 8) | (int(lower[0]) & 0xff) 105 106 return 107 }