89 lines
2.0 KiB
Go
89 lines
2.0 KiB
Go
package megapi
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/binary"
|
|
"github.com/hybridgroup/gobot"
|
|
"sync"
|
|
)
|
|
|
|
var _ gobot.Driver = (*MotorDriver)(nil)
|
|
|
|
// MotorDriver represents a motor
|
|
type MotorDriver struct {
|
|
name string
|
|
megaPi *MegaPiAdaptor
|
|
port byte
|
|
halted bool
|
|
syncRoot *sync.Mutex
|
|
}
|
|
|
|
// NewMotorDriver creates a new MotorDriver using the provided name, and at the given port
|
|
func NewMotorDriver(megaPi *MegaPiAdaptor, name string, port byte) *MotorDriver {
|
|
return &MotorDriver{
|
|
name: name,
|
|
megaPi: megaPi,
|
|
port: port,
|
|
halted: true,
|
|
syncRoot: &sync.Mutex{},
|
|
}
|
|
}
|
|
|
|
// Name returns the name of this motor
|
|
func (m *MotorDriver) Name() string {
|
|
return m.name
|
|
}
|
|
|
|
// Start implements the Driver interface
|
|
func (m *MotorDriver) Start() []error {
|
|
m.syncRoot.Lock()
|
|
defer m.syncRoot.Unlock()
|
|
m.halted = false
|
|
m.speedHelper(0)
|
|
return []error{}
|
|
}
|
|
|
|
// Halt terminates the Driver interface
|
|
func (m *MotorDriver) Halt() []error {
|
|
m.syncRoot.Lock()
|
|
defer m.syncRoot.Unlock()
|
|
m.halted = true
|
|
m.speedHelper(0)
|
|
return []error{}
|
|
}
|
|
|
|
// Connection returns the Connection associated with the Driver
|
|
func (m *MotorDriver) Connection() gobot.Connection {
|
|
return gobot.Connection(m.megaPi)
|
|
}
|
|
|
|
// Speed sets the motors speed to the specified value
|
|
func (m *MotorDriver) Speed(speed int16) error {
|
|
m.syncRoot.Lock()
|
|
defer m.syncRoot.Unlock()
|
|
if m.halted {
|
|
return nil
|
|
}
|
|
m.speedHelper(speed)
|
|
return nil
|
|
}
|
|
|
|
// there is some sort of bug on the hardware such that you cannot
|
|
// send the exact same speed to 2 different motors consecutively
|
|
// hence we ensure we always alternate speeds
|
|
func (m *MotorDriver) speedHelper(speed int16) {
|
|
m.sendSpeed(speed - 1)
|
|
m.sendSpeed(speed)
|
|
}
|
|
|
|
// sendSpeed sets the motors speed to the specified value
|
|
func (m *MotorDriver) sendSpeed(speed int16) {
|
|
bufOut := new(bytes.Buffer)
|
|
|
|
// byte sequence: 0xff, 0x55, id, action, device, port
|
|
bufOut.Write([]byte{0xff, 0x55, 0x6, 0x0, 0x2, 0xa, m.port})
|
|
binary.Write(bufOut, binary.LittleEndian, speed)
|
|
bufOut.Write([]byte{0xa})
|
|
m.megaPi.writeBytesChannel <- bufOut.Bytes()
|
|
}
|