-
Notifications
You must be signed in to change notification settings - Fork 0
/
motor.go
100 lines (86 loc) · 1.78 KB
/
motor.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
95
96
97
98
99
100
package motor
import (
"tinygo.org/x/drivers"
)
type Direction uint8
type Motor uint8
const (
Address = 0x10
Forward Direction = 0x00
Backward Direction = 0x01
MotorRight Motor = 0x02
MotorLeft Motor = 0x00
)
type Device struct {
bus drivers.I2C
buf []byte
Address uint8
speed uint8
}
func New(i2c drivers.I2C) *Device {
return &Device{
bus: i2c,
buf: make([]byte, 5),
Address: Address,
speed: 50,
}
}
func (d *Device) Configure() {
d.buf[0] = 0x00
d.buf[1] = uint8(Forward)
d.buf[2] = 20
d.buf[3] = uint8(Forward)
d.buf[4] = 20
}
func (d *Device) SetSpeed(speed uint8) {
d.speed = speed
}
func (d *Device) Forward() {
d.buf[1] = uint8(Forward)
d.buf[2] = d.speed
d.buf[3] = uint8(Forward)
d.buf[4] = d.speed
d.bus.Tx(uint16(d.Address), d.buf, nil)
}
func (d *Device) Backward() {
d.buf[1] = uint8(Backward)
d.buf[2] = d.speed
d.buf[3] = uint8(Backward)
d.buf[4] = d.speed
d.bus.Tx(uint16(d.Address), d.buf, nil)
}
func (d *Device) SpinRight() {
d.buf[1] = uint8(Forward)
d.buf[2] = d.speed
d.buf[3] = uint8(Backward)
d.buf[4] = d.speed
d.bus.Tx(uint16(d.Address), d.buf, nil)
}
func (d *Device) SpinLeft() {
d.buf[1] = uint8(Backward)
d.buf[2] = d.speed
d.buf[3] = uint8(Forward)
d.buf[4] = d.speed
d.bus.Tx(uint16(d.Address), d.buf, nil)
}
func (d *Device) Right() {
d.buf[1] = uint8(Forward)
d.buf[2] = d.speed
d.buf[3] = uint8(Forward)
d.buf[4] = 20
d.bus.Tx(uint16(d.Address), d.buf, nil)
}
func (d *Device) Left() {
d.buf[1] = uint8(Forward)
d.buf[2] = 20
d.buf[3] = uint8(Forward)
d.buf[4] = d.speed
d.bus.Tx(uint16(d.Address), d.buf, nil)
}
func (d *Device) Stop() {
d.buf[1] = uint8(Forward)
d.buf[2] = 20
d.buf[3] = uint8(Forward)
d.buf[4] = 20
d.bus.Tx(uint16(d.Address), d.buf, nil)
}