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