forked from KurtE/Phantom_Phoenix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
phoenix_driver_ax12.cpp
1219 lines (1026 loc) · 39.2 KB
/
phoenix_driver_ax12.cpp
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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//====================================================================
//Project Lynxmotion Phoenix
//
// Servo Driver - This version is setup to use AX-12 type servos using the
// Arbotix AX12 and bioloid libraries (which may have been updated)
//====================================================================
#if ARDUINO>99
#include <Arduino.h> // Arduino 1.0
#else
#include <Wprogram.h> // Arduino 0022
#include <avr\pgmspace.h>
#endif
#include "Hex_Globals.h"
#include "ServoDriver.h"
#ifdef USE_PYPOSE_HEADER
#define EXPORT_POSE_LIST
#include "PyPoseGen.h"
#endif
#ifdef c4DOF
#define NUMSERVOSPERLEG 4
#else
#define NUMSERVOSPERLEG 3
#endif
#define NUMSERVOS (NUMSERVOSPERLEG*6)
#ifdef USE_AX12_DRIVER
#include <ax12.h>
#define USE_BIOLOIDEX // Use the Bioloid code to control the AX12 servos...
#define USE_AX12_SPEED_CONTROL // Experiment to see if the speed control works well enough...
boolean g_fAXSpeedControl; // flag to know which way we are doing output...
#include "BioloidEx.h"
#ifdef USE_AX12_SPEED_CONTROL
// Current positions in AX coordinates
word g_awCurAXPos[NUMSERVOS];
word g_awGoalAXPos[NUMSERVOS];
#endif
#ifdef DBGSerial
//#define DEBUG
// Only allow debug stuff to be turned on if we have a debug serial port to output to...
//#define DEBUG_SERVOS
#endif
#ifdef DEBUG_SERVOS
#define ServosEnabled (g_fEnableServos)
#else
#define ServosEnabled (true) // always true compiler should remove if...
#endif
//=============================================================================
// Global - Local to this file only...
//=============================================================================
static const byte cPinTable[] PROGMEM = {
cRRCoxaPin, cRMCoxaPin, cRFCoxaPin, cLRCoxaPin, cLMCoxaPin, cLFCoxaPin,
cRRFemurPin, cRMFemurPin, cRFFemurPin, cLRFemurPin, cLMFemurPin, cLFFemurPin,
cRRTibiaPin, cRMTibiaPin, cRFTibiaPin, cLRTibiaPin, cLMTibiaPin, cLFTibiaPin
#ifdef c4DOF
,cRRTarsPin, cRMTarsPin, cRFTarsPin, cLRTarsPin, cLMTarsPin, cLFTarsPin
#endif
};
#define FIRSTCOXAPIN 0
#define FIRSTFEMURPIN 6
#define FIRSTTIBIAPIN 12
#define FIRSTTARSPIN 18
// Not sure yet if I will use the controller class or not, but...
BioloidControllerEx bioloid = BioloidControllerEx(1000000);
boolean g_fServosFree; // Are the servos in a free state?
//============================================================================================
// Lets try rolling our own GPSequence code here...
#define GPSEQ_EEPROM_START 0x40 // Reserve the first 64 bytes of EEPROM for other stuff...
#define GPSEQ_EEPROM_START_DATA 0x50 // Reserved room for up to 8 in header...
#define GPSEQ_EEPROM_SIZE 0x800 // I think we have 2K
#define GPSEQ_EEPROM_MAX_SEQ 5 // For now this is probably the the max we can probably hold...
// Not sure if pragma needed or not...
#pragma pack(1)
typedef struct {
byte bSeqNum; // the sequence number, used to verify
byte bCntServos; // count of servos
byte bCntSteps; // How many steps there are
byte bCntPoses; // How many poses
}
EEPromPoseHeader;
typedef struct {
byte bPoseNum; // which pose to use
word wTime; // Time to do pose
}
EEPROMPoseSeq; // This is a sequence entry
// Pose is just an array of words...
// A sequence is stored as:
//<header> <sequences><poses>
// Some forward references
extern void MakeSureServosAreOn(void);
extern void DoPyPose(byte *psz);
extern void EEPROMReadData(word wStart, uint8_t *pv, byte cnt);
extern void EEPROMWriteData(word wStart, uint8_t *pv, byte cnt);
//--------------------------------------------------------------------
//Init
//--------------------------------------------------------------------
void ServoDriver::Init(void) {
// First lets get the actual servo positions for all of our servos...
pinMode(0, OUTPUT);
g_fServosFree = true;
bioloid.poseSize = 18;
bioloid.readPose();
#ifdef cVoltagePin
for (byte i=0; i < 8; i++)
GetBatteryVoltage(); // init the voltage pin
#endif
g_fAXSpeedControl = false;
#ifdef OPT_GPPLAYER
_fGPEnabled = true; // assume we support it.
#endif
}
//--------------------------------------------------------------------
//GetBatteryVoltage - Maybe should try to minimize when this is called
// as it uses the serial port... Maybe only when we are not interpolating
// or if maybe some minimum time has elapsed...
//--------------------------------------------------------------------
#ifdef cVoltagePin
word g_awVoltages[8]={
0,0,0,0,0,0,0,0};
word g_wVoltageSum = 0;
byte g_iVoltages = 0;
word ServoDriver::GetBatteryVoltage(void) {
g_iVoltages = (++g_iVoltages)&0x7; // setup index to our array...
g_wVoltageSum -= g_awVoltages[g_iVoltages];
g_awVoltages[g_iVoltages] = analogRead(cVoltagePin);
g_wVoltageSum += g_awVoltages[g_iVoltages];
return ((long)((long)g_wVoltageSum*125*(CVADR1+CVADR2))/(long)(2048*(long)CVADR2));
}
#else
#define VOLTAGE_REPEAT_MAX 3
#define VOLTAGE_MAX_TIME_BETWEEN_CALLS 500 // call at least twice a second...
word g_wLastVoltage = 0xffff; // save the last voltage we retrieved...
unsigned long g_ulTimeLastBatteryVoltage;
word ServoDriver::GetBatteryVoltage(void) {
if (bioloid.interpolating && (g_wLastVoltage != 0xffff) && ((millis()-g_ulTimeLastBatteryVoltage) < VOLTAGE_MAX_TIME_BETWEEN_CALLS))
return g_wLastVoltage;
register uint8_t bLoopCnt = VOLTAGE_REPEAT_MAX;
do {
register word wVoltage = ax12GetRegister (1, AX_PRESENT_VOLTAGE, 1);
if (wVoltage != 0xffff) {
g_ulTimeLastBatteryVoltage = millis();
g_wLastVoltage = wVoltage * 10;
return g_wLastVoltage;
}
}
while (--bLoopCnt);
return 0;
}
#endif
//--------------------------------------------------------------------
//[GP PLAYER]
//--------------------------------------------------------------------
#ifdef OPT_GPPLAYER
EEPromPoseHeader g_eepph; // current header
byte g_bSeqStepNum;
word g_wSeqHeaderStart;
boolean g_fSeqProgmem;
transition_t *g_ptransCur; // pointer to our current transisiton...
boolean fRobotUpsideDownGPStart; // state when we start sequence
#ifdef USE_PYPOSE_HEADER
#define CNT_PYPOSE_SEGS (sizeof(PoseList)/sizeof(PoseList[0]))
#else
#define CNT_PYPOSE_SEGS 0
#endif
//--------------------------------------------------------------------
//[FIsGPSeqDefined]
//--------------------------------------------------------------------
boolean ServoDriver::FIsGPSeqDefined(uint8_t iSeq)
{
#ifdef USE_PYPOSE_HEADER
if (iSeq < CNT_PYPOSE_SEGS) {
g_fSeqProgmem = true;
g_ptransCur = (transition_t *)pgm_read_word(&PoseList[iSeq]);
// First entry in this table has the count of poses.
g_eepph.bCntSteps = (byte)pgm_read_word(&(g_ptransCur->time));
g_eepph.bCntServos = 18;
return true; // say that we are valid...
}
g_fSeqProgmem = false;
#endif
iSeq -= CNT_PYPOSE_SEGS; // update count to subtract off fixed ones.
if (iSeq >= GPSEQ_EEPROM_MAX_SEQ)
return false;
// Now read in the header pointer...
EEPROMReadData(GPSEQ_EEPROM_START+iSeq*sizeof(word), (uint8_t*)&g_wSeqHeaderStart, sizeof(g_wSeqHeaderStart));
if ((g_wSeqHeaderStart < GPSEQ_EEPROM_START_DATA) || (g_wSeqHeaderStart >= GPSEQ_EEPROM_SIZE))
return false; // pointer does not look right.
// Now Read in the actual header
EEPROMReadData(g_wSeqHeaderStart, (uint8_t*)&g_eepph, sizeof(g_eepph));
if ((g_eepph.bSeqNum != iSeq) || (g_eepph.bCntServos != 18) ||
((g_wSeqHeaderStart + sizeof(g_eepph) + (g_eepph.bCntSteps * sizeof(EEPROMPoseSeq)) + (g_eepph.bCntPoses * sizeof(word) * 18)) >= GPSEQ_EEPROM_SIZE))
return false;
return true; // Looks like it is valid
}
//--------------------------------------------------------------------
// Setup to start sequence number...
//--------------------------------------------------------------------
void ServoDriver::GPStartSeq(uint8_t iSeq)
{
if ((iSeq == 0xff) && _fGPActive) {
// Caller is asking us to abort...
// I think I can simply clear our active flag and it will cleanup...
// May need to find a way to clear the interpolating...
_fGPActive = false;
return;
}
// Use our Validate function to get the initial stuff set up...
if (!FIsGPSeqDefined(iSeq))
return;
_fGPActive = true;
_iSeq = iSeq;
g_bSeqStepNum = 0xff; // Say that we are not in a step yet...
_sGPSM = 100; // assume we are running at standard speed
fRobotUpsideDownGPStart = g_fRobotUpsideDown;
}
//--------------------------------------------------------------------
//[GP PLAYER]
//--------------------------------------------------------------------
static const byte cPinIndexTranslateUpsideDownTable[] PROGMEM = {
0x80+1, 0x80+0, 3, 2, 5, 4, 0x80+7, 0x80+6, 9, 8, 11, 10, 0x80+13, 0x80+12, 15, 14, 17, 16};
void ServoDriver::GPPlayer(void)
{
EEPROMPoseSeq eepps;
byte bServo;
word wPosePos;
byte bServoIndexUpsideDown;
if (_fGPActive) {
// See if we are still interpolating the last step
if ((g_bSeqStepNum != 0xff) && (bioloid.interpolating)) {
bioloid.interpolateStep(false);
return;
}
if (_sGPSM >= 0) {
if (++g_bSeqStepNum >= g_eepph.bCntSteps) {
_fGPActive = false; // we are done
return;
}
}
else {
// Run in reverse
if ((g_bSeqStepNum == 0xff) || g_bSeqStepNum == 0) {
_fGPActive = false; // we are done
return;
}
g_bSeqStepNum--;
}
#ifdef USE_PYPOSE_HEADER
if (g_fSeqProgmem) {
if (_sGPSM >= 0)
g_ptransCur++; // lets point to the next step entry.
else
g_ptransCur--; // lets point to the next step entry.
word *pwPose = (word*)pgm_read_word(&(g_ptransCur->pose));
int poseSize = pgm_read_word_near(pwPose); // number of servos in this pose
if (!fRobotUpsideDownGPStart) {
for(bServo=0; bServo<poseSize; bServo++) {
bioloid.setNextPoseByIndex(bServo, pgm_read_word_near(pwPose+1+bServo)); // set a servo value by index for next pose
}
}
else {
// Upside down
for(bServo=0; bServo<poseSize; bServo++) {
bServoIndexUpsideDown = pgm_read_byte(&cPinIndexTranslateUpsideDownTable[bServo]);
if (bServoIndexUpsideDown & 0x80)
bioloid.setNextPoseByIndex(bServoIndexUpsideDown&0x7f, 1023-pgm_read_word_near(pwPose+1+bServo));
else
bioloid.setNextPoseByIndex(bServoIndexUpsideDown, pgm_read_word_near(pwPose+1+bServo));
}
}
// interpolate - Note: we want to take the Speed multipler into account here.
bioloid.interpolateSetup(((long)pgm_read_word(&(g_ptransCur->time))*100)/abs(_sGPSM));
return;
}
#endif
// Lets get the sequence information
EEPROMReadData(g_wSeqHeaderStart + sizeof(g_eepph) + (g_bSeqStepNum*sizeof(EEPROMPoseSeq)), (uint8_t*)&eepps, sizeof(eepps));
// Now lets setup to read in the pose information
word wEEPromPoseLoc = g_wSeqHeaderStart + sizeof(g_eepph) + (g_eepph.bCntPoses*sizeof(EEPROMPoseSeq)) + (eepps.bPoseNum * sizeof(word) * 18); // should not hard code 18
for (bServo=0; bServo < 18; bServo++) {
EEPROMReadData(wEEPromPoseLoc, (uint8_t*)&wPosePos, sizeof(wPosePos));
if (!fRobotUpsideDownGPStart) {
bioloid.setNextPoseByIndex(bServo, wPosePos); // set a servo value by index for next pose
}
else {
bServoIndexUpsideDown = pgm_read_byte(&cPinIndexTranslateUpsideDownTable[bServo]);
if (bServoIndexUpsideDown & 0x80)
bioloid.setNextPoseByIndex(bServoIndexUpsideDown&0x7f, 1023-wPosePos);
else
bioloid.setNextPoseByIndex(bServoIndexUpsideDown, wPosePos);
}
// bioloid.setNextPose(bServo+1,wPosePos);
wEEPromPoseLoc += sizeof(word);
}
// interpolate
bioloid.interpolateSetup((((long)eepps.wTime)*100)/abs(_sGPSM));
}
}
//------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------
uint8_t ServoDriver::GPNumSteps(void) // How many steps does the current sequence have
{
return _fGPActive ? g_eepph.bCntSteps : 0;
}
//------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------
uint8_t ServoDriver::GPCurStep(void) // Return which step currently on...
{
return _fGPActive ? g_bSeqStepNum + 1 : 0xff;
}
//------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------
void ServoDriver::GPSetSpeedMultiplyer(short sm) // Set the Speed multiplier (100 is default)
{
_sGPSM = sm;
}
#endif // OPT_GPPLAYER
//------------------------------------------------------------------------------------------
//[BeginServoUpdate] Does whatever preperation that is needed to starrt a move of our servos
//------------------------------------------------------------------------------------------
void ServoDriver::BeginServoUpdate(void) // Start the update
{
MakeSureServosAreOn();
if (ServosEnabled) {
DebugToggle(A4);
if (g_fAXSpeedControl) {
#ifdef USE_AX12_SPEED_CONTROL
// If we are trying our own Servo control need to save away the new positions...
for (byte i=0; i < NUMSERVOS; i++) {
g_awCurAXPos[i] = g_awGoalAXPos[i];
}
#endif
}
else
bioloid.interpolateStep(true); // Make sure we call at least once
}
}
//------------------------------------------------------------------------------------------
//[OutputServoInfoForLeg] Do the output to the SSC-32 for the servos associated with
// the Leg number passed in.
//------------------------------------------------------------------------------------------
#define cPwmMult 128
#define cPwmDiv 375
#define cPFConst 512 // half of our 1024 range
#ifdef c4DOF
void ServoDriver::OutputServoInfoForLeg(byte LegIndex, short sCoxaAngle1, short sFemurAngle1, short sTibiaAngle1, short sTarsAngle1)
#else
void ServoDriver::OutputServoInfoForLeg(byte LegIndex, short sCoxaAngle1, short sFemurAngle1, short sTibiaAngle1)
#endif
{
word wCoxaSSCV; // Coxa value in SSC units
word wFemurSSCV; //
word wTibiaSSCV; //
#ifdef c4DOF
word wTarsSSCV; //
#endif
//Update Right Legs
g_InputController.AllowControllerInterrupts(false); // If on xbee on hserial tell hserial to not processess...
if (LegIndex < 3) {
wCoxaSSCV = (((long)(-sCoxaAngle1))* cPwmMult) / cPwmDiv +cPFConst;
wFemurSSCV = (((long)(-sFemurAngle1))* cPwmMult) / cPwmDiv +cPFConst;
wTibiaSSCV = (((long)(-sTibiaAngle1))* cPwmMult) / cPwmDiv +cPFConst;
#ifdef c4DOF
wTarsSSCV = (((long)(-sTarsAngle1))* cPwmMult) / cPwmDiv +cPFConst;
#endif
}
else {
wCoxaSSCV = (((long)(sCoxaAngle1))* cPwmMult) / cPwmDiv +cPFConst;
wFemurSSCV = (((long)((long)(sFemurAngle1))* cPwmMult) / cPwmDiv +cPFConst);
wTibiaSSCV = (((long)(sTibiaAngle1))* cPwmMult) / cPwmDiv +cPFConst;
#ifdef c4DOF
wTarsSSCV = (((long)(sTarsAngle1))* cPwmMult) / cPwmDiv +cPFConst;
#endif
}
if (ServosEnabled) {
if (g_fAXSpeedControl) {
#ifdef USE_AX12_SPEED_CONTROL
// Save away the new positions...
g_awGoalAXPos[FIRSTCOXAPIN+LegIndex] = wCoxaSSCV; // What order should we store these values?
g_awGoalAXPos[FIRSTFEMURPIN+LegIndex] = wFemurSSCV;
g_awGoalAXPos[FIRSTTIBIAPIN+LegIndex] = wTibiaSSCV;
#ifdef c4DOF
g_awGoalAXTarsPos[FIRSTTARSPIN+LegIndex] = wTarsSSCV;
#endif
#endif
}
else {
bioloid.setNextPose(pgm_read_byte(&cPinTable[FIRSTCOXAPIN+LegIndex]), wCoxaSSCV);
bioloid.setNextPose(pgm_read_byte(&cPinTable[FIRSTFEMURPIN+LegIndex]), wFemurSSCV);
bioloid.setNextPose(pgm_read_byte(&cPinTable[FIRSTTIBIAPIN+LegIndex]), wTibiaSSCV);
#ifdef c4DOF
if ((byte)pgm_read_byte(&cTarsLength[LegIndex])) // We allow mix of 3 and 4 DOF legs...
bioloid.setNextPose(pgm_read_byte(&cPinTable[FIRSTTARSPIN+LegIndex]), wTarsSSCV);
#endif
}
}
#ifdef DEBUG_SERVOS
if (g_fDebugOutput) {
DBGSerial.print(LegIndex, DEC);
DBGSerial.print("(");
DBGSerial.print(sCoxaAngle1, DEC);
DBGSerial.print("=");
DBGSerial.print(wCoxaSSCV, DEC);
DBGSerial.print("),(");
DBGSerial.print(sFemurAngle1, DEC);
DBGSerial.print("=");
DBGSerial.print(wFemurSSCV, DEC);
DBGSerial.print("),(");
DBGSerial.print("(");
DBGSerial.print(sTibiaAngle1, DEC);
DBGSerial.print("=");
DBGSerial.print(wTibiaSSCV, DEC);
DBGSerial.print(") :");
}
#endif
g_InputController.AllowControllerInterrupts(true); // Ok for hserial again...
}
//==============================================================================
// Calculate servo speeds to achieve desired pose timing
// We make the following assumptions:
// AX-12 speed is 59rpm @ 12V which corresponds to 0.170s/60deg
// The AX-12 manual states this as the 'no load speed' at 12V
// The Moving Speed control table entry states that 0x3FF = 114rpm
// and according to Robotis this means 0x212 = 59rpm and anything greater 0x212 is also 59rpm
#ifdef USE_AX12_SPEED_CONTROL
word CalculateAX12MoveSpeed(word wCurPos, word wGoalPos, word wTime)
{
word wTravel;
uint32_t factor;
word wSpeed;
// find the amount of travel for each servo
if( wGoalPos > wCurPos) {
wTravel = wGoalPos - wCurPos;
}
else {
wTravel = wCurPos - wGoalPos;
}
// now we can calculate the desired moving speed
// for 59pm the factor is 847.46 which we round to 848
// we need to use a temporary 32bit integer to prevent overflow
factor = (uint32_t) 848 * wTravel;
wSpeed = (uint16_t) ( factor / wTime );
// if the desired speed exceeds the maximum, we need to adjust
if (wSpeed > 1023) wSpeed = 1023;
// we also use a minimum speed of 26 (5% of 530 the max value for 59RPM)
if (wSpeed < 26) wSpeed = 26;
return wSpeed;
}
#endif
//--------------------------------------------------------------------
//[CommitServoDriver Updates the positions of the servos - This outputs
// as much of the command as we can without committing it. This
// allows us to once the previous update was completed to quickly
// get the next command to start
//--------------------------------------------------------------------
void ServoDriver::CommitServoDriver(word wMoveTime)
{
#ifdef cSSC_BINARYMODE
byte abOut[3];
#endif
g_InputController.AllowControllerInterrupts(false); // If on xbee on hserial tell hserial to not processess...
if (ServosEnabled) {
if (g_fAXSpeedControl) {
#ifdef USE_AX12_SPEED_CONTROL
// Need to first output the header for the Sync Write
int length = 4 + (NUMSERVOS * 5); // 5 = id + pos(2byte) + speed(2 bytes)
int checksum = 254 + length + AX_SYNC_WRITE + 4 + AX_GOAL_POSITION_L;
word wSpeed;
setTXall();
ax12write(0xFF);
ax12write(0xFF);
ax12write(0xFE);
ax12write(length);
ax12write(AX_SYNC_WRITE);
ax12write(AX_GOAL_POSITION_L);
ax12write(4); // number of bytes per servo (plus the ID...)
for (int i = 0; i < NUMSERVOS; i++) {
wSpeed = CalculateAX12MoveSpeed(g_awCurAXPos[i], g_awGoalAXPos[i], wMoveTime); // What order should we store these values?
byte id = pgm_read_byte(&cPinTable[i]);
checksum += id + (g_awGoalAXPos[i]&0xff) + (g_awGoalAXPos[i]>>8) + (wSpeed>>8) + (wSpeed & 0xff);
ax12write(id);
ax12write(g_awGoalAXPos[i]&0xff);
ax12write(g_awGoalAXPos[i]>>8);
ax12write(wSpeed&0xff);
ax12write(wSpeed>>8);
}
ax12write(0xff - (checksum % 256));
setRX(0);
#endif
}
else {
bioloid.interpolateSetup(wMoveTime);
}
}
#ifdef DEBUG_SERVOS
if (g_fDebugOutput)
DBGSerial.println(wMoveTime, DEC);
#endif
g_InputController.AllowControllerInterrupts(true);
}
//--------------------------------------------------------------------
//[FREE SERVOS] Frees all the servos
//--------------------------------------------------------------------
void ServoDriver::FreeServos(void)
{
if (ServosEnabled) {
g_InputController.AllowControllerInterrupts(false); // If on xbee on hserial tell hserial to not processess...
for (byte i = 0; i < NUMSERVOS; i++) {
Relax(pgm_read_byte(&cPinTable[i]));
}
g_InputController.AllowControllerInterrupts(true);
g_fServosFree = true;
}
}
//--------------------------------------------------------------------
//[FREE SERVOS] Frees all the servos
//--------------------------------------------------------------------
void MakeSureServosAreOn(void)
{
if (ServosEnabled) {
if (!g_fServosFree)
return; // we are not free
g_InputController.AllowControllerInterrupts(false); // If on xbee on hserial tell hserial to not processess...
if (g_fAXSpeedControl) {
for(int i=0;i<NUMSERVOS;i++){
g_awGoalAXPos[i] = ax12GetRegister(pgm_read_byte(&cPinTable[i]),AX_PRESENT_POSITION_L,2);
delay(25);
}
}
else {
bioloid.readPose();
}
for (byte i = 0; i < NUMSERVOS; i++) {
TorqueOn(pgm_read_byte(&cPinTable[i]));
}
g_InputController.AllowControllerInterrupts(true);
g_fServosFree = false;
}
}
//==============================================================================
// BackgroundProcess - Allows us to have some background processing for those
// servo drivers that need us to do things like polling...
//==============================================================================
void ServoDriver::BackgroundProcess(void)
{
if (g_fAXSpeedControl)
return; // nothing to do in this mode...
if (ServosEnabled) {
DebugToggle(A3);
bioloid.interpolateStep(false); // Do our background stuff...
}
}
#ifdef OPT_TERMINAL_MONITOR
//==============================================================================
// ShowTerminalCommandList: Allow the Terminal monitor to call the servo driver
// to allow it to display any additional commands it may have.
//==============================================================================
void ServoDriver::ShowTerminalCommandList(void)
{
DBGSerial.println(F("M - Toggle Motors on or off"));
DBGSerial.println(F("F<frame length> - FL in ms")); // BUGBUG::
DBGSerial.println(F("A - Toggle AX12 speed control"));
DBGSerial.println(F("T - Test Servos"));
#ifdef OPT_PYPOSE
DBGSerial.println(F("P<DL PC> - Pypose"));
#endif
#ifdef OPT_FIND_SERVO_OFFSETS
DBGSerial.println(F("O - Enter Servo offset mode"));
#endif
#ifdef OPT_SSC_FORWARDER
DBGSerial.println(F("S - SSC Forwarder"));
#endif
}
//==============================================================================
// ProcessTerminalCommand: The terminal monitor will call this to see if the
// command the user entered was one added by the servo driver.
//==============================================================================
boolean ServoDriver::ProcessTerminalCommand(byte *psz, byte bLen)
{
if ((bLen == 1) && ((*psz == 'm') || (*psz == 'M'))) {
g_fEnableServos = !g_fEnableServos;
if (g_fEnableServos)
DBGSerial.println(F("Motors are on"));
else
DBGSerial.println(F("Motors are off"));
return true;
}
if ((bLen == 1) && ((*psz == 't') || (*psz == 'T'))) {
// Test to see if all servos are responding...
for(int i=1;i<=NUMSERVOS;i++){
word w;
w = ax12GetRegister(i,AX_PRESENT_POSITION_L,2);
DBGSerial.print(i,DEC);
DBGSerial.print(F("="));
DBGSerial.println(w, DEC);
delay(25);
}
}
if ((bLen == 1) && ((*psz == 'a') || (*psz == 'A'))) {
g_fAXSpeedControl = !g_fAXSpeedControl;
if (g_fAXSpeedControl)
DBGSerial.println(F("AX12 Speed Control"));
else
DBGSerial.println(F("Bioloid Speed"));
}
if ((bLen >= 1) && ((*psz == 'f') || (*psz == 'F'))) {
psz++; // need to get beyond the first character
while (*psz == ' ')
psz++; // ignore leading blanks...
byte bFrame = 0;
while ((*psz >= '0') && (*psz <= '9')) { // Get the frame count...
bFrame = bFrame*10 + *psz++ - '0';
}
if (bFrame != 0) {
DBGSerial.print(F("New Servo Cycles per second: "));
DBGSerial.println(1000/bFrame, DEC);
extern BioloidControllerEx bioloid;
bioloid.frameLength = bFrame;
}
}
#ifdef OPT_FIND_SERVO_OFFSETS
else if ((bLen == 1) && ((*psz == 'o') || (*psz == 'O'))) {
FindServoOffsets();
}
#endif
#ifdef OPT_SSC_FORWARDER
else if ((bLen == 1) && ((*psz == 's') || (*psz == 'S'))) {
SSCForwarder();
}
#endif
#ifdef OPT_PYPOSE
else if ((*psz == 'p') || (*psz == 'P')) {
DoPyPose(++psz);
}
#endif
}
#endif
//==============================================================================
// SSC Forwarder - used to allow things like Lynxterm to talk to the SSC-32
// through the Arduino... Will see if it is fast enough...
//==============================================================================
#ifdef OPT_SSC_FORWARDER
void SSCForwarder(void)
{
}
#endif // OPT_SSC_FORWARDER
//==============================================================================
// FindServoOffsets - Find the zero points for each of our servos...
// Will use the new servo function to set the actual pwm rate and see
// how well that works...
//==============================================================================
#ifdef OPT_FIND_SERVO_OFFSETS
void FindServoOffsets()
{
}
#endif // OPT_FIND_SERVO_OFFSETS
//==============================================================================
// EEPromReadData - Quick and dirty function to read multiple bytes in from
// eeprom...
//==============================================================================
void EEPROMReadData(word wStart, uint8_t *pv, byte cnt) {
while (cnt--) {
*pv++ = EEPROM.read(wStart++);
}
}
//==============================================================================
// DoPyPose - This is based off of the Pypose sketch...
// ArbotiX Test Program for use with PyPose 0013
// Copyright (c) 2008-2010 Michael E. Ferguson. All right reserved.
//
// The code was put onto a memory diet and extended by me...
//==============================================================================
#ifdef OPT_PYPOSE
// Some defines for different modes and commands
#define ARB_SIZE_POSE 7 // also initializes
#define ARB_LOAD_POSE 8
#define ARB_LOAD_SEQ 9
#define ARB_PLAY_SEQ 10
#define ARB_LOOP_SEQ 11
#define ARB_SAVE_EEPROM_SEQ 12
#define ARB_TEST 25
// Global to this function...
byte g_bPoseSize = 18; // assume poses are for 18 servos.
short g_poses[540]; // enough for 30 steps...
typedef struct{
byte pose; // index of pose to transition to
word time; // time for transition
}
sp_trans_t;
sp_trans_t g_sequence[30]; // sequence
byte g_bParams[90]; // parameters
// Some forward referencs
extern boolean PyPoseSaveToEEPROM(byte);
void DoPyPose(byte *psz)
{
int mode = 0; // where we are in the frame
byte id = 0; // id of this frame
byte length = 0; // length of this frame
byte ins = 0; // instruction of this frame
byte index = 0; // index in param buffer
word wPoseIndex;
int checksum; // checksum
// pose and sequence storage
// Put on diet - convert int to short plus convert poses from 2 dimensions to 1 dimension...
//
byte seqPos; // step in current sequence
word wMY;
// See if the user gave us a string to process. If so it should be the XBEE DL to talk to.
// BUGBUG:: if using our XBEE stuff could default to debug terminal...
#ifdef USEXBEE
#ifdef DBGSerial
wMY = GetXBeeHVal('M', 'Y');
DBGSerial.print(F("My: "));
DBGSerial.println(wMY, HEX);
wMY = GetXBeeHVal('D', 'L'); // I know reused variable...
DBGSerial.print(F("PC DL: "));
DBGSerial.println(wMY, HEX);
DBGSerial.println(F("Exit Terminal and Start Pypose"));
DBGSerial.println(F("$TEXTM$")); // add some support in VB side to convert to text mode...
#endif
// Now lets reset our xbee...
APISendXBeeGetCmd('F','R'); // Send a Forced reset...
delay(2000);
while(Serial.read() != -1)
;
if (psz) {
word wDL;
for (wDL=0; *psz; psz++) {
if ((*psz >= '0') && (*psz <= '9'))
wDL = (wDL << 4) + *psz - '0';
if ((*psz >= 'a') && (*psz <= 'f'))
wDL = (wDL << 4) + *psz - 'a' + 10;
if ((*psz >= 'A') && (*psz <= 'F'))
wDL = (wDL << 4) + *psz - 'A' + 10;
}
if (wDL) {
Serial.print("+++");
delay (1000);
while ((checksum=Serial.read()) != -1) {
//Serial.write((byte)checksum);
}
// Now lets set the DL and exit command mode...
Serial.print("ATDL ");
Serial.print(wDL, HEX);
Serial.println(",ATCN");
}
}
delay(10);
while ((checksum=Serial.read()) != -1) {
//Serial.write((byte)checksum);
}
#endif
// process messages
for (;;) {
while(Serial.available() > 0){
// We need to 0xFF at start of packet
if(mode == 0){ // start of new packet
if(Serial.read() == 0xff){
mode = 2;
digitalWrite(0,HIGH-digitalRead(0));
}
//}else if(mode == 1){ // another start byte
// if(Serial.read() == 0xff)
// mode = 2;
// else
// mode = 0;
}
else if(mode == 2){ // next byte is index of servo
id = Serial.read();
if(id != 0xff)
mode = 3;
}
else if(mode == 3){ // next byte is length
length = Serial.read();
checksum = id + length;
mode = 4;
}
else if(mode == 4){ // next byte is instruction
ins = Serial.read();
checksum += ins;
index = 0;
mode = 5;
}
else if(mode == 5){ // read data in
g_bParams[index] = Serial.read();
checksum += (int) g_bParams[index];
index++;
if(index + 1 == length){ // we've read params & checksum
mode = 0;
if((checksum%256) != 255){
// return a packet: FF FF id Len Err params=None check
Serial.write((byte)0xff);
Serial.write((byte)0xff);
Serial.write((byte)id);
Serial.write((byte)2);
Serial.write((byte)64);
Serial.write((byte)(255-((66+id)%256)));
}
else{
if(id == 253){
// return a packet: FF FF id Len Err params=None check
Serial.write((byte)0xff);
Serial.write((byte)0xff);
Serial.write((byte)id);
Serial.write((byte)2);
Serial.write((byte)0);
Serial.write((byte)(255-((2+id)%256)));
// special ArbotiX instructions
// Pose Size = 7, followed by single param: size of pose
// Load Pose = 8, followed by index, then pose positions (# of param = 2*pose_size)
// Load Seq = 9, followed by index/times (# of parameters = 3*seq_size)
// Play Seq = A, no params
if(ins == ARB_SIZE_POSE){
g_bPoseSize = bioloid.poseSize = g_bParams[0];
bioloid.readPose();
//Serial.println(bioloid.poseSize);
}
else if(ins == ARB_LOAD_POSE){
int i;
//Serial.print("New Pose:");
wPoseIndex = g_bParams[0] * g_bPoseSize;
for(i=0; i<bioloid.poseSize; i++){
g_poses[wPoseIndex+i] = g_bParams[(2*i)+1]+(g_bParams[(2*i)+2]<<8);
//Serial.print(g_poses[g_bParams[0]][i]);
//Serial.print(",");
}
//Serial.println("");
}
else if(ins == ARB_LOAD_SEQ){
int i;
for(i=0;i<(length-2)/3;i++){
g_sequence[i].pose = g_bParams[(i*3)];
g_sequence[i].time = g_bParams[(i*3)+1] + (g_bParams[(i*3)+2]<<8);
//Serial.print("New Transition:");
//Serial.print((int)g_sequence[i].pose);
//Serial.print(" in ");
//Serial.println(g_sequence[i].time);
}
}
else if(ins == ARB_PLAY_SEQ){
seqPos = 0;
while(g_sequence[seqPos].pose != 0xff){
int i;
int p = g_sequence[seqPos].pose;
wPoseIndex = p * g_bPoseSize;
// are we HALT?
if(Serial.read() == 'H') return;
// load pose
for(i=0; i<bioloid.poseSize; i++){
bioloid.setNextPose(i+1,g_poses[wPoseIndex+i]);
}
// interpolate
bioloid.interpolateSetup(g_sequence[seqPos].time);
while(bioloid.interpolating)
bioloid.interpolateStep();
// next transition
seqPos++;
}
}
else if(ins == ARB_LOOP_SEQ){
while(1){
seqPos = 0;
while(g_sequence[seqPos].pose != 0xff){
int i;
int p = g_sequence[seqPos].pose;
wPoseIndex = p * g_bPoseSize;
// are we HALT?
if(Serial.read() == 'H') return;
// load pose
for(i=0; i<bioloid.poseSize; i++){
bioloid.setNextPose(i+1,g_poses[wPoseIndex+i]);
}
// interpolate
bioloid.interpolateSetup(g_sequence[seqPos].time);
while(bioloid.interpolating)
bioloid.interpolateStep();