gobot.io/x/gobot@v1.16.0/drivers/i2c/hmc6352_driver.go (about)

     1  package i2c
     2  
     3  import "gobot.io/x/gobot"
     4  
     5  const hmc6352Address = 0x21
     6  
     7  // HMC6352Driver is a Driver for a HMC6352 digital compass
     8  type HMC6352Driver struct {
     9  	name       string
    10  	connector  Connector
    11  	connection Connection
    12  	Config
    13  }
    14  
    15  // NewHMC6352Driver creates a new driver with specified i2c interface
    16  // Params:
    17  //		conn 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 NewHMC6352Driver(a Connector, options ...func(Config)) *HMC6352Driver {
    24  	hmc := &HMC6352Driver{
    25  		name:      gobot.DefaultName("HMC6352"),
    26  		connector: a,
    27  		Config:    NewConfig(),
    28  	}
    29  
    30  	for _, option := range options {
    31  		option(hmc)
    32  	}
    33  
    34  	return hmc
    35  }
    36  
    37  // Name returns the name for this Driver
    38  func (h *HMC6352Driver) Name() string { return h.name }
    39  
    40  // SetName sets the name for this Driver
    41  func (h *HMC6352Driver) SetName(n string) { h.name = n }
    42  
    43  // Connection returns the connection for this Driver
    44  func (h *HMC6352Driver) Connection() gobot.Connection { return h.connector.(gobot.Connection) }
    45  
    46  // Start initializes the hmc6352
    47  func (h *HMC6352Driver) Start() (err error) {
    48  	bus := h.GetBusOrDefault(h.connector.GetDefaultBus())
    49  	address := h.GetAddressOrDefault(hmc6352Address)
    50  
    51  	h.connection, err = h.connector.GetConnection(address, bus)
    52  	if err != nil {
    53  		return err
    54  	}
    55  
    56  	if _, err := h.connection.Write([]byte("A")); err != nil {
    57  		return err
    58  	}
    59  	return
    60  }
    61  
    62  // Halt returns true if devices is halted successfully
    63  func (h *HMC6352Driver) Halt() (err error) { return }
    64  
    65  // Heading returns the current heading
    66  func (h *HMC6352Driver) Heading() (heading uint16, err error) {
    67  	if _, err = h.connection.Write([]byte("A")); err != nil {
    68  		return
    69  	}
    70  	buf := []byte{0, 0}
    71  	bytesRead, err := h.connection.Read(buf)
    72  	if err != nil {
    73  		return
    74  	}
    75  	if bytesRead == 2 {
    76  		heading = (uint16(buf[1]) + uint16(buf[0])*256) / 10
    77  		return
    78  	}
    79  
    80  	err = ErrNotEnoughBytes
    81  	return
    82  }