forked from hybridgroup/gobot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
motor_driver.go
94 lines (80 loc) · 2.06 KB
/
motor_driver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package megapi
import (
"bytes"
"encoding/binary"
"sync"
"gobot.io/x/gobot"
)
var _ gobot.Driver = (*MotorDriver)(nil)
// MotorDriver represents a motor
type MotorDriver struct {
name string
megaPi *Adaptor
port byte
halted bool
syncRoot *sync.Mutex
}
// NewMotorDriver creates a new MotorDriver at the given port
func NewMotorDriver(megaPi *Adaptor, port byte) *MotorDriver {
return &MotorDriver{
name: "MegaPiMotor",
megaPi: megaPi,
port: port,
halted: true,
syncRoot: &sync.Mutex{},
}
}
// Name returns the name of this motor
func (m *MotorDriver) Name() string {
return m.name
}
// SetName sets the name of this motor
func (m *MotorDriver) SetName(n string) {
m.name = n
}
// Start implements the Driver interface
func (m *MotorDriver) Start() error {
m.syncRoot.Lock()
defer m.syncRoot.Unlock()
m.halted = false
m.speedHelper(0)
return nil
}
// Halt terminates the Driver interface
func (m *MotorDriver) Halt() error {
m.syncRoot.Lock()
defer m.syncRoot.Unlock()
m.halted = true
m.speedHelper(0)
return nil
}
// 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()
}