Repository navigation
Expand file tree
/
Copy pathmalgdb.ino
More file actions
executable file
·629 lines (525 loc) · 15.6 KB
/
Copy pathmalgdb.ino
File metadata and controls
executable file
·629 lines (525 loc) · 15.6 KB
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
/*
ASCII Serial Commands
FORWARD = 'f', [0-255][0-255] (speed for each wheel)
BACKWARD = 'b', [0-255][0-255] (speed for each wheel)
LEFT = 'l', [0-255][0-255] (speed for each wheel)
RIGHT = 'r', [0-255][0-255] (speed for each wheel)
FORWARDTIMED = 't' [0-255][0-255] (speed for each wheel) [0-255][0-255] DWORD milliseconds
BACKWARDTIMED = 'u' [0-255][0-255] (speed for each wheel) [0-255][0-255] DWORD milliseconds
LEFTTIMED = 'z'. [0-255][0-255] (speed for each wheel) [0-255][0-255] DWORD milliseconds
RIGHTTIMED = 'e'. [0-255] (speed) [0-255][0-255] DWORD milliseconds
CAM = 'v', [0-255] (servo angle)
CAM RELEASE = 'w' (servo release)
CAM HORIZ SET = 'm' [0-255] (write horizontal position to eeprom)
STOP = 's' (DC motors stop)
HARD_STOP = 'h' (DC motors stop with brake)
GET VERSION = 'y'
GET FIRMWARE = 'x'
FWD FLOOD LIGHT = 'q', [0-255] (intensity)
REAR FLOOD LIGHT = 'o', [0-255] (intensity)
SPOT LIGHT = 'p', [0-255] (intensity)
ODOMETRY_START = 'i' (start recording encoder and gyro, zero values)
ODOMETRY_STOP = 'j' (stop recording encoder and gyro, and report)
ODOMETRY_REPORT = 'k' (report current encoder and gyro counts, then zero counts)
PING = 'c' (heartbeat)
EEPROM_CLEAR = '8' (set entire eeprom bank to 0)
EEPROM_READ = '9' (read camhoriz position)
SEND_SLAVEI2C_BYTE = 'a' [0-255] (send specified byte to I2C slave, optional peripheral)
ENCB_HIGH = 'Q' (optional spare encoder pin HIGH)
ENCB_LOW = 'W' (optional spare encoder pin LOW)
*/
/*
* gyro function
*
* config:
* read z only, 380Mz rate, 250 degrees-per-second resolution
* write to 32 value FIFO buffer, stream overwrite continuously
*
* when motors stopped, calibrate zero every 2 seconds
*
* angle reading is cummulative, as gyro produces rate data (degrees per second)
* if active (not stopped, and readangle boolean true),
* check if fifo threshold reached every loop, if so read up to threshold and add to angle
*
* if info requested or stop detected, print angle to serial, start from 0 again
*
*
*/
#include <Wire.h>
#include <Servo.h>
#include <EEPROM.h>
#define GYROaddr 0x6b
#define SLAVEI2C 0x08
#define WHIGH 0 // 0 = default, reverse 0/1 if wheels wired backwards
#define WLOW 1 // 1 = default, reverse 0/1 if wheels wired backwards
// hbridge
const int pwmA = 3; // pwm
const int in1 = 2;
const int in2 = 4;
const int pwmB = 11; // pwm
const int in3 = 7;
const int in4 = 8;
// lights
const int spotPin = 6; // pwm
const int floodPWMPin = 5; // pwm
const int fwdFloodPin = 12;
const int rearFloodPin = 9;
// servo
const int servoPin = 10; // pwm
Servo camservo;
const int eepromAddress = 0;
// encoder
const int encA = A0;
const int ENCB = A1; // typically unused, available for other uses
// spare 13, A2, A3, A1
// timers
unsigned long time = 0;
unsigned long lastcmd = 0;
const unsigned long hostTimeout = 10000; // stop motors if no steady ping from host
unsigned long stoptime = 0;
// command byte buffer
const int MAX_BUFFER = 32;
int buffer[MAX_BUFFER];
int commandSize = 0;
//pins 5,6 timer 0 factor: 62500/1 >> 64
// 62500/8 >> 8
// 62500/256 >> 0.25
const double timemult = 64;
// gyro
boolean readAngle = false;
double angle = 0;
// const double calibrationComp = 1.047; // 1.047; // 1.094;
const unsigned long gyroZeroInterval = 2000;
unsigned long lastGyroZero = 0;
int zOff = 0;
const double gyroSampleRate = 0.00263157; // 380hz, milliseconds
// const double gyroSampleRate = 0.00526315; // 190hz, milliseconds
int gyroZ[32]; // max FIFO buffer size
int gyrosamples = 0;
// double driftDegPerSec = 0;
boolean gyroFifoReadAfterStop = false;
// end of gyro
// encoder
volatile boolean encoderPinAtZero = false;
volatile int encoderTicks = 0;
const int TICKSPERREV = 180; // 180 for older version of SPG30E-60K, 420 for newer
volatile boolean readEncoder = false;
volatile unsigned long lastEncoderTick = 0;
volatile boolean stopdetected = false;
// end of encoder
// stop detect control
int directioncmd = 0; // 0=stop, 1=forward, 2=backward, 3=left, 4=right
boolean stopped = true;
boolean stopPending = false;
unsigned long stopCommand = 0;
const unsigned long allowforstop = 1000;
const long STOPTHRESHOLD = 25; // milliseconds, 25 for older version of SPG30E-60K, 11 for newer
void setup() {
// horiz servo
int m = (int) EEPROM.read(eepromAddress);
if (m < 30 || m > 100) { // not within range where it looks like its been set properly before
m = 70; //default
EEPROM.write(eepromAddress, m);
}
camservo.attach(servoPin);
camservo.write(m);
delay(500);
camservo.detach();
pinMode(pwmA, OUTPUT);
pinMode(pwmB, OUTPUT);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(in3, OUTPUT);
pinMode(in4, OUTPUT);
pinMode(rearFloodPin, OUTPUT);
pinMode(spotPin, OUTPUT);
pinMode(fwdFloodPin, OUTPUT);
pinMode(encA, INPUT);
pinMode(ENCB, OUTPUT); // only if ENCB not used as 2nd encoder pin
encBdefault();
//pwm frequencies setup (from http://playground.arduino.cc/Code/PwmFrequency)
TCCR2B = TCCR2B & 0b11111000 | 0x07; // 31250hz/1024=30 Hz pin 3, 11 wheels
// TCCR2B = TCCR2B & 0b11111000 | 0x04; // 31250hz/64=488Hz pin 3, 11 wheels
// TCCR2B = TCCR2B & 0b11111000 | 0x02; // 31250hz/8=3906Hz pin 3, 11 wheels
// TCCR2B = TCCR2B & 0b11111000 | 0x01; // 31250hz pin 3, 11 wheels (usually arduino default)
TCCR0B = TCCR0B & 0b11111000 | 0x01; // pins 5, 6 62500/1 = 62kHz lights
// motors fwd, off
analogWrite(pwmA, 0);
analogWrite(pwmB, 0);
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);
Wire.begin();
Wire.setClock(400000L);
// gyro setup
gyroWrite(0x24, 64); // CTRL_REG5 01000000 FIFO enable
gyroWrite(0x2E, 64); // FIFO_CTRL_REG 01000000 FIFO stream mode
gyroWrite(0x20, 172); // CTRL_REG1 10 10 1 1 0 0 380Hz ODR, 50Hz LPF2, pwr normal, z, x, y
// gyroWrite(0x20, 108); // CTRL_REG1 01 10 1 1 0 0 190Hz ODR, 50Hz LPF2, pwr normal, z, x, y
// encoder read interrupt setup
cli(); // switch interrupts off while messing with their settings
PCICR =0x02; // Enable PCINT1 interrupt
PCMSK1 = 0b00000001; // mask A0
sei(); // switch back on
Serial.begin(115200);
Serial.println("<reset>");
}
void loop(){
time = millis() / timemult;
if (readAngle && !stopped) { // && time - gyroReadFifoInterval > lastGyroFifoRead) {
if (getGyroFIFOcontents()) {
boolean checkstop = false;
if (stopPending && (directioncmd ==3 || directioncmd==4) && time- lastcmd > 0) checkstop = true; //was time-lastcmd>80
int callstopdetect = 0;
for (int i=0; i<gyrosamples; i++ ){
int z = gyroZ[i]+zOff;
double degPerSec = (double) z * 250/0x7fff * -1; // using 250dps default scale, negate because typically mounted upside down
// degPerSec -= driftDegPerSec;
angle += degPerSec * gyroSampleRate;
if (checkstop) {
if (abs(z) < 75) { // magic stop constant (was 150 for max2100 gyro)
callstopdetect ++;
}
}
}
if (callstopdetect > 0) stopDetect(); // was 0
}
}
// periodically determine gyro zero offset when stopped
if (time - gyroZeroInterval > lastGyroZero && time >= gyroZeroInterval) {
if (stopped) {
if (getGyroFIFOcontents()) {
int zavg = 0;
for (int i=0; i<gyrosamples; i++) {
zavg += gyroZ[i];
}
zavg /= gyrosamples;
zOff = 0 - zavg;
// driftDegPerSec = (double) zavg * 250/0x7fff * -1;
// TODO: testing only, nuke!
// Serial.print("<zOff: ");
// Serial.print(zOff);
// Serial.println(">");
}
}
lastGyroZero = time;
}
// allow for slow down to complete stop, timed
if (stopPending && time - allowforstop > stopCommand && readAngle && readEncoder) {
Serial.println("<stopdetectfail>"); // TODO: testing only
stopDetect();
}
if (stopdetected) { // used by interrupt only
stopdetected = false;
if (readEncoder && stopPending && (directioncmd==1 || directioncmd==2) ) {
stopDetect();
}
}
if (stoptime != 0 && time > stoptime) {
stop();
stoptime = 0;
}
// manage serial input
if( Serial.available() > 0) {
lastcmd = time;
manageCommand();
}
else if (time - hostTimeout > lastcmd ){
//if no comm with host, stop motors
allOff();
lastcmd = time;
}
}
//
// buffer and/or execute commands from host controller
//
void manageCommand() {
int input = Serial.read();
if((input == 13) || (input == 10)){
if(commandSize > 0){
parseCommand();
commandSize = 0;
}
}
else {
buffer[commandSize++] = input;
}
}
void allOff() {
analogWrite(floodPWMPin, 0);
analogWrite(spotPin, 0);
analogWrite(pwmA, 0);
analogWrite(pwmB, 0);
camservo.detach();
encBdefault();
}
void parseCommand(){
if (buffer[0] == 'q'){ // forward floodlight
analogWrite(floodPWMPin, buffer[1]);
digitalWrite(fwdFloodPin, LOW);
digitalWrite(rearFloodPin, HIGH);
}
else if (buffer[0] == 'o'){ // floodlight
analogWrite(floodPWMPin, buffer[1]);
digitalWrite(fwdFloodPin, HIGH);
digitalWrite(rearFloodPin, LOW);
}
else if (buffer[0] == 'p'){ // spotlight
analogWrite(spotPin, buffer[1]);
}
else if(buffer[0] == 'v') { // camera to position
camservo.attach(servoPin);
camservo.write(buffer[1]);
}
else if(buffer[0]== 'w') camservo.detach();
else if (buffer[0] == 'm') { // camera horiz position to eeprom
EEPROM.write(eepromAddress, buffer[1]);
}
// always set speed on each move command
else if(buffer[0] == 'f' || buffer[0] == 'b' || buffer[0] == 'l' || buffer[0] == 'r'
|| buffer[0] == 'z' || buffer[0] == 'e' || buffer[0] == 't' || buffer[0] == 'u') {
analogWrite(pwmA, buffer[1]);
analogWrite(pwmB, buffer[2]);
if (buffer[0] == 'f') { // forward
digitalWrite(in1, WLOW);
digitalWrite(in2, WHIGH);
digitalWrite(in3, WHIGH);
digitalWrite(in4, WLOW);
stopPending = false;
stopped = false;
directioncmd =1;
}
else if (buffer[0] == 'b') { // backward
digitalWrite(in1, WHIGH);
digitalWrite(in2, WLOW);
digitalWrite(in3, WLOW);
digitalWrite(in4, WHIGH);
stopPending = false;
stopped = false;
directioncmd = 2;
}
else if (buffer[0] == 'l') { // left
digitalWrite(in1, WHIGH);
digitalWrite(in2, WLOW);
digitalWrite(in3, WHIGH);
digitalWrite(in4, WLOW);
stopPending = false;
stopped = false;
directioncmd=3;
}
else if (buffer[0] == 'r') { // right
digitalWrite(in1, WLOW);
digitalWrite(in2, WHIGH);
digitalWrite(in3, WLOW);
digitalWrite(in4, WHIGH);
stopPending = false;
stopped = false;
directioncmd=4;
}
else if (buffer[0] == 'z') { // lefttimed
digitalWrite(in1, WHIGH);
digitalWrite(in2, WLOW);
digitalWrite(in3, WHIGH);
digitalWrite(in4, WLOW);
stopPending = false;
stopped = false;
directioncmd=3;
// unsigned long delay = buffer[3]<<8 | buffer[4];
// if (delay > 1000) { delay = 1000; }
// stoptime = time + delay;
stoptime = time + (buffer[3]<<8 | buffer[4]);
}
else if (buffer[0] == 'e') { // righttimed
digitalWrite(in1, WLOW);
digitalWrite(in2, WHIGH);
digitalWrite(in3, WLOW);
digitalWrite(in4, WHIGH);
stopPending = false;
stopped = false;
directioncmd=4;
// unsigned long delay = buffer[3]<<8 | buffer[4];
// if (delay > 1000) { delay = 1000; }
// stoptime = time + delay;
stoptime = time + (buffer[3]<<8 | buffer[4]);
}
else if (buffer[0] == 't') { // forwardtimed
digitalWrite(in1, WLOW);
digitalWrite(in2, WHIGH);
digitalWrite(in3, WHIGH);
digitalWrite(in4, WLOW);
stopPending = false;
stopped = false;
directioncmd=1;
stoptime = time + (buffer[3]<<8 | buffer[4]);
}
else if (buffer[0] == 'u') { // backwardtimed
digitalWrite(in1, WHIGH);
digitalWrite(in2, WLOW);
digitalWrite(in3, WLOW);
digitalWrite(in4, WHIGH);
stopPending = false;
stopped = false;
directioncmd=2;
stoptime = time + (buffer[3]<<8 | buffer[4]);
}
}
else if (buffer[0] == 's') { // stop
stop();
}
else if (buffer[0] == 'h') { // hard stop
hardstop();
}
else if(buffer[0] == 'x') Serial.println("<id::malgdb>");
else if(buffer[0] == 'y') version();
else if (buffer[0] == 'c') Serial.println(""); // ping, single character to make it quick
else if (buffer[0] == 'i') { // gyro and encoder start
encoderPinAtZero = false;
encoderTicks = 0;
readEncoder = true;
readAngle = true;
angle = 0;
stopdetected = false;
stopPending = false;
stopped = true;
directioncmd = 0;
}
else if (buffer[0] == 'j') { // gyro and encoder stop and report
printMoved();
readEncoder = false;
encoderPinAtZero = false;
readAngle = false;
}
else if (buffer[0] == 'k') { // ODOMETRY_REPORT
printMoved();
}
else if (buffer[0] == '8') { // clear eeprom
for (int i = 0; i < 512; i++)
EEPROM.write(i, 0);
Serial.println("<eeprom erased>");
}
else if (buffer[0] == '9') { // read eeprom
int i = EEPROM.read(eepromAddress);
Serial.print("<horiz_eeprom: ");
Serial.print(i);
Serial.println(">");
}
else if (buffer[0] == 'a') {
// I2c.write(SLAVEI2C, 0x00, buffer[1]); // TODO: fix
}
else if (buffer[0] == 'Q') {
digitalWrite(ENCB, HIGH);
}
else if (buffer[0] == 'W') {
digitalWrite(ENCB, LOW);
}
/* end of command buffer[0] list */
}
boolean getGyroFIFOcontents() {
// FIFO_SRC_REG 2F
// WTM OVRN EMPTY FSS4 FSS3 FSS2 FSS1 FSS0
byte a = gyroRead(0x2F);
gyrosamples = a & B00011111; // 31 max
int ovr = bitRead(a,6);
gyrosamples += ovr; // add OVR bit
// TODO: testing
// note: always triggered after starting from full stop
if (ovr==1 && readAngle && gyroFifoReadAfterStop) Serial.println("<gyroOVR>"); // && !stopped
if (!stopped) gyroFifoReadAfterStop = true;
if (gyrosamples == 0) return false;
// read Z only
int i = 0;
for (int n=0; n < gyrosamples; n++ ) {
Wire.beginTransmission(GYROaddr);
Wire.write(0x2C | (1 << 7)); // shift required to read multiple vals
Wire.endTransmission();
Wire.requestFrom(GYROaddr, 2);
int za =0;
int zb = 0;
while (Wire.available()) {
za= Wire.read();
zb=Wire.read();
}
gyroZ[n] = zb<<8 | za;
}
// if (ovr==1 && readAngle) return false; // TODO: testing
return true;
}
void printMoved() {
double revs = 0;
if (directioncmd ==1 || directioncmd == 2) {
revs = (double) encoderTicks/TICKSPERREV;
if (directioncmd==2) revs *= -1;
}
encoderTicks = 0;
double a = angle; // * calibrationComp;
angle = 0;
Serial.print("<moved ");
Serial.print(revs);
Serial.print(" ");
Serial.print(a);
Serial.println(">");
}
void stop() {
analogWrite(pwmA, 0);
analogWrite(pwmB, 0);
if (!stopped) {
stopCommand = time;
stopPending = true;
stoptime = 0;
}
}
void hardstop() {
digitalWrite(in1, 0);
digitalWrite(in2, 0);
digitalWrite(in3, 0);
digitalWrite(in4, 0);
if (!stopped) {
stopCommand = time;
stopPending = true;
}
}
void stopDetect() {
printMoved();
Serial.println("<stop>");
stopPending = false;
stopped = true;
directioncmd = 0;
lastGyroZero = time; // in case still moving a bit...
gyroFifoReadAfterStop = false;
}
ISR(PCINT1_vect) {
if (!readEncoder) return;
int m = digitalRead(encA);
if (m == LOW) encoderPinAtZero = true;
else {
if (encoderPinAtZero) { // tick
encoderPinAtZero = false;
encoderTicks ++;
unsigned long t = millis()/timemult;
if (t - lastEncoderTick > STOPTHRESHOLD) { stopdetected = true; } // was 25
lastEncoderTick = t;
}
}
}
void gyroWrite(int addr, int value) {
Wire.beginTransmission(GYROaddr);
Wire.write(addr);
Wire.write(value);
Wire.endTransmission();
}
byte gyroRead(int addr) {
Wire.beginTransmission(GYROaddr);
Wire.write(addr);
Wire.endTransmission();
Wire.requestFrom(GYROaddr, 1);
byte a = Wire.read();
return a;
}
// disable this function if ENCB used as 2nd encoder pin
void encBdefault() {
digitalWrite(ENCB, HIGH);
}
void version() {
Serial.println("<version:1.17>");
}