-
Notifications
You must be signed in to change notification settings - Fork 0
/
roomba.go
158 lines (132 loc) · 2.24 KB
/
roomba.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
//
// Laser Range Finder
// roomba.go
//
// Cole Smith - [email protected]
// Eric Lin - [email protected]
// LICENSE: Apache 2.0
//
package roombaControl
import (
"fmt"
"github.com/tarm/serial"
"log"
"strconv"
"time"
)
const (
SERIAL_INTERFACE = "ttyAMA0"
BAUD = 115200
SPEED = 200
)
var (
ser *serial.Port
)
func init() {
// Open Connection to Serial Port
c := &serial.Config{Name: SERIAL_INTERFACE, Baud: BAUD}
var err error
ser, err = serial.OpenPort(c)
if err != nil {
fmt.Println(err)
log.Fatal(err)
}
// Motor Priming
ModeStart()
ModeSafe()
Stop()
fmt.Println("Roomba is ready")
}
//
// Mode Set Functions
//
func ModeStart() {
fmt.Println("Starting...")
write(128)
}
func ModeSafe() {
fmt.Println("In safe mode")
write(131)
}
func ModeDriveDirect() {
fmt.Println("In drive direct mode")
write(145)
}
//
// Utility Functions
//
func toHex(val int) (int, int) {
eqBitVal := 0
if val >= 0 {
eqBitVal = val
} else {
eqBitVal = (1 << 16) + val
}
return (eqBitVal >> 8) & 0xFF, eqBitVal & 0xFF
}
func toBytes(val int) []byte {
return []byte(strconv.Itoa(val))
}
func write(val int) {
_, err := ser.Write(toBytes(val))
if err != nil {
fmt.Println("Write Error: %v", err)
}
time.Sleep(25 * time.Millisecond)
}
func read() []byte {
buf := make([]byte, 128)
n, err := ser.Read(buf)
if err != nil {
fmt.Println("Read Error: %v", err)
}
return buf[n:]
}
//
// Sensor Functions
//
// TODO: Implement if needed
func GetStasis() {}
func GetBumps() {}
//
// Drive Functions
//
func drive(velocity, angle int) {
velHigh, velLow := toHex(velocity)
radHigh, radLow := toHex(angle)
write(137)
write(velHigh)
write(velLow)
write(radHigh)
write(radLow)
}
func Forward() {
fmt.Println("Forward...")
drive(SPEED, 0)
}
func Backward() {
fmt.Println("Backward...")
drive(SPEED*-1, 0)
}
func Stop() {
fmt.Println("Stopping...")
velHigh, velLow := toHex(0)
radHigh, radLow := toHex(0)
write(137)
write(velHigh)
write(velLow)
write(radHigh)
write(radLow)
}
func Turn() {
fmt.Println("Turning...")
drive(SPEED, -1)
// 0.54 is ~ 90 degrees
time.Sleep(54 * time.Millisecond)
}
func TurnLeft() {
fmt.Println("Turning...")
drive(SPEED, 1)
// 0.54 is ~ 90 degrees
time.Sleep(54 * time.Millisecond)
}