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

     1  package i2c
     2  
     3  const hmc6352DefaultAddress = 0x21
     4  
     5  // HMC6352Driver is a Driver for a HMC6352 digital compass
     6  type HMC6352Driver struct {
     7  	*Driver
     8  }
     9  
    10  // NewHMC6352Driver creates a new driver with specified i2c interface
    11  // Params:
    12  //		c Connector - the Adaptor to use with this Driver
    13  //
    14  // Optional params:
    15  //		i2c.WithBus(int):	bus to use with this driver
    16  //		i2c.WithAddress(int):	address to use with this driver
    17  //
    18  func NewHMC6352Driver(c Connector, options ...func(Config)) *HMC6352Driver {
    19  	h := &HMC6352Driver{
    20  		Driver: NewDriver(c, "HMC6352", hmc6352DefaultAddress),
    21  	}
    22  	h.afterStart = h.initialize
    23  
    24  	for _, option := range options {
    25  		option(h)
    26  	}
    27  
    28  	return h
    29  }
    30  
    31  // Heading returns the current heading
    32  func (h *HMC6352Driver) Heading() (heading uint16, err error) {
    33  	if _, err = h.connection.Write([]byte("A")); err != nil {
    34  		return
    35  	}
    36  	buf := []byte{0, 0}
    37  	bytesRead, err := h.connection.Read(buf)
    38  	if err != nil {
    39  		return
    40  	}
    41  	if bytesRead == 2 {
    42  		heading = (uint16(buf[1]) + uint16(buf[0])*256) / 10
    43  		return
    44  	}
    45  
    46  	err = ErrNotEnoughBytes
    47  	return
    48  }
    49  
    50  func (h *HMC6352Driver) initialize() error {
    51  	if _, err := h.connection.Write([]byte("A")); err != nil {
    52  		return err
    53  	}
    54  	return nil
    55  }