2014-04-27 18:54:41 -07:00
|
|
|
package i2c
|
|
|
|
|
2022-12-10 13:10:23 +01:00
|
|
|
const hmc6352DefaultAddress = 0x21
|
2015-07-03 18:57:29 -07:00
|
|
|
|
2016-12-20 18:59:26 +01:00
|
|
|
// HMC6352Driver is a Driver for a HMC6352 digital compass
|
2014-04-27 18:54:41 -07:00
|
|
|
type HMC6352Driver struct {
|
2022-12-10 13:10:23 +01:00
|
|
|
*Driver
|
2014-04-27 18:54:41 -07:00
|
|
|
}
|
|
|
|
|
2016-09-25 14:08:18 +02:00
|
|
|
// NewHMC6352Driver creates a new driver with specified i2c interface
|
2017-02-09 16:47:11 +01:00
|
|
|
// Params:
|
2022-12-10 13:10:23 +01:00
|
|
|
// c Connector - the Adaptor to use with this Driver
|
2017-02-09 16:47:11 +01:00
|
|
|
//
|
|
|
|
// Optional params:
|
2017-02-10 11:08:32 +01:00
|
|
|
// i2c.WithBus(int): bus to use with this driver
|
|
|
|
// i2c.WithAddress(int): address to use with this driver
|
2017-02-09 16:47:11 +01:00
|
|
|
//
|
2022-12-10 13:10:23 +01:00
|
|
|
func NewHMC6352Driver(c Connector, options ...func(Config)) *HMC6352Driver {
|
|
|
|
h := &HMC6352Driver{
|
|
|
|
Driver: NewDriver(c, "HMC6352", hmc6352DefaultAddress),
|
2014-04-27 18:54:41 -07:00
|
|
|
}
|
2022-12-10 13:10:23 +01:00
|
|
|
h.afterStart = h.initialize
|
2017-02-09 11:23:36 +01:00
|
|
|
|
|
|
|
for _, option := range options {
|
2022-12-10 13:10:23 +01:00
|
|
|
option(h)
|
2017-02-09 11:23:36 +01:00
|
|
|
}
|
|
|
|
|
2022-12-10 13:10:23 +01:00
|
|
|
return h
|
2014-04-27 18:54:41 -07:00
|
|
|
}
|
|
|
|
|
2014-11-19 16:56:48 -08:00
|
|
|
// Heading returns the current heading
|
|
|
|
func (h *HMC6352Driver) Heading() (heading uint16, err error) {
|
2017-02-06 00:19:42 +01:00
|
|
|
if _, err = h.connection.Write([]byte("A")); err != nil {
|
2014-11-19 16:56:48 -08:00
|
|
|
return
|
|
|
|
}
|
2017-02-06 00:19:42 +01:00
|
|
|
buf := []byte{0, 0}
|
|
|
|
bytesRead, err := h.connection.Read(buf)
|
2014-11-19 16:56:48 -08:00
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
2017-02-06 00:19:42 +01:00
|
|
|
if bytesRead == 2 {
|
|
|
|
heading = (uint16(buf[1]) + uint16(buf[0])*256) / 10
|
2014-11-19 16:56:48 -08:00
|
|
|
return
|
|
|
|
}
|
2017-02-10 11:44:36 +01:00
|
|
|
|
|
|
|
err = ErrNotEnoughBytes
|
2014-11-19 16:56:48 -08:00
|
|
|
return
|
2014-04-27 18:54:41 -07:00
|
|
|
}
|
2022-12-10 13:10:23 +01:00
|
|
|
|
|
|
|
func (h *HMC6352Driver) initialize() error {
|
|
|
|
if _, err := h.connection.Write([]byte("A")); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|