Repository navigation
Expand file tree
/
Copy pathRobotAPI_class.py
More file actions
1261 lines (1092 loc) · 42.2 KB
/
Copy pathRobotAPI_class.py
File metadata and controls
1261 lines (1092 loc) · 42.2 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
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
# Python API for robot control.
import math
import time
from time import sleep
from pySerialTransfer import pySerialTransfer as txfer
class RobotAPI:
# Constants: Address
ADDR_PC = 100
ADDR_MEGA = 200
# Constants: Function Code
FC_PING = 1
FC_TORQUE_ON = 2
FC_TORQUE_OFF = 3
FC_TORQUE_STATUS = 4
FC_READ_ANGLE = 5
FC_WRITE_ANGLE = 6
FC_PEN_SERVO = 7
FC_READ_STATE = 8
FC_WRITE_STATE = 9
FC_READ_ROBOT_STATE = 10
FC_WRITE_ROBOT_STATE = 11
FC_RW_ROBOT_STATE = 12
# Other
RS485_TO = 0.1
# The constructor
def __init__(self, port: str, baud_rate: int, robot_type: str, RS485_timeout: float=0.1):
try:
self.link = txfer.SerialTransfer(port, baud_rate)
if self.link.open():
print("Serial port opened successfully.")
else:
print("Failed to open serial port.")
except Exception as e:
print(f"Error opening serial port: {e}")
self.link = None
self.rob = robot_type
# The destructor
def __del__(self):
if hasattr(self, 'link') and self.link is not None:
try:
self.link.close()
print("Serial port closed successfully.")
except Exception as e:
print(f"Error closing serial port: {e}")
def pingTest(self, motorID: int):
"""
Description: This function sends a ping command
to the specified motor and waits for a response.
Input:
motorID: The ID of the motor to ping
Output:
True if the motor responds to the ping command
False if the motor does not respond to the ping command
"""
# Packet to send
from_addr = self.ADDR_PC
to_addr = self.ADDR_MEGA
FC1 = self.FC_PING
FC2 = 0
data = motorID
# Packet
send_array = [from_addr, to_addr, FC1, FC2, data]
try:
# Load the Tx buffer with the packet
send_size = self.link.tx_obj(send_array)
# Send the packet
self.link.send(send_size)
# Wait for the packet to be sent
sleep(0.001)
# Record the time the packet was sent
send_time = time.time()
# Wait for response with timeout
while not self.link.available():
if (time.time() - send_time) > self.RS485_TO:
print("Timeout waiting for response")
return False
sleep(0.001)
# Process response
if self.link.status == txfer.NEW_DATA:
response = self.link.rx_obj(
obj_type=list, obj_byte_size=self.link.bytesRead, list_format="i"
)
from_addr = response[0]
to_addr = response[1]
FC1 = response[2]
FC2 = response[3]
if (
from_addr == self.ADDR_MEGA
and to_addr == self.ADDR_PC
and FC1 == 0
and FC2 == self.FC_PING
):
return response[4]
else:
print(
f"Error: Invalid response from {from_addr} to {to_addr} with FC1={FC1} and FC2={FC2}"
)
return False
else:
print("Data receipt error. Status:", self.link.status)
return False
except Exception as e:
print("Error:", e)
return False
def setTorqueON(self, motorID: int):
"""
Description: This function enables the motor control
of the specified motor and waits for a response.
Input:
motorID: The ID of the motor to enable torque
Output:
True if the torque is enabled
False if failed to enabled the torque
"""
# Packet to send
from_addr = self.ADDR_PC
to_addr = self.ADDR_MEGA
FC1 = self.FC_TORQUE_ON
FC2 = 0
data = motorID
# Packet
send_array = [from_addr, to_addr, FC1, FC2, data]
try:
# Load the Tx buffer with the packet
send_size = self.link.tx_obj(send_array)
# Send the packet
self.link.send(send_size)
# Wait for the packet to be sent
sleep(0.001)
# Record the time the packet was sent
send_time = time.time()
# Wait for response with timeout
while not self.link.available():
if (time.time() - send_time) > self.RS485_TO:
print("Timeout waiting for response")
return False
sleep(0.001)
# Process response
if self.link.status == txfer.NEW_DATA:
response = self.link.rx_obj(
obj_type=list, obj_byte_size=self.link.bytesRead, list_format="i"
)
from_addr = response[0]
to_addr = response[1]
FC1 = response[2]
FC2 = response[3]
if (
from_addr == self.ADDR_MEGA
and to_addr == self.ADDR_PC
and FC1 == 0
and FC2 == self.FC_TORQUE_ON
):
return response[4]
else:
print(
f"Error: Invalid response from {from_addr} to {to_addr} with FC1={FC1} and FC2={FC2}"
)
return False
else:
print("Data receipt error. Status:", self.link.status)
return False
except Exception as e:
print("Error:", e)
return False
def setTorqueOFF(self, motorID: int):
"""
Description: This function disables the motor control
of the specified motor and waits for a response.
Input:
motorID: The ID of the motor to disable torque
Output:
True if the torque is disabled
False if failed to disable the torque
"""
# Packet to send
from_addr = self.ADDR_PC
to_addr = self.ADDR_MEGA
FC1 = self.FC_TORQUE_OFF
FC2 = 0
data = motorID
send_array = [from_addr, to_addr, FC1, FC2, data]
try:
# Load the Tx buffer with the packet
send_size = self.link.tx_obj(send_array)
# Send the packet
self.link.send(send_size)
# Wait for the packet to be sent
sleep(0.001)
# Record the time the packet was sent
send_time = time.time()
# Wait for response with timeout
while not self.link.available():
if (time.time() - send_time) > self.RS485_TO:
print("Timeout waiting for response")
return False
sleep(0.001)
# Process response
if self.link.status == txfer.NEW_DATA:
# Process the response if needed
response = self.link.rx_obj(
obj_type=list, obj_byte_size=self.link.bytesRead, list_format="i"
)
from_addr = response[0]
to_addr = response[1]
FC1 = response[2]
FC2 = response[3]
if (
from_addr == self.ADDR_MEGA
and to_addr == self.ADDR_PC
and FC1 == 0
and FC2 == self.FC_TORQUE_OFF
):
return response[4]
else:
print(
f"Err: Invalid response from {from_addr} to {to_addr} with FC1={FC1} and FC2={FC2}"
)
return False
else:
print("Data receipt error. Status:", self.link.status)
return False
except Exception as e:
print("Error:", e)
return False
def getTorqueStatus(self, motorID: int):
"""
Description: This function checks the torque enabled/disabled status.
Input:
motorID: The ID of the motor to check the torque status
Output:
1 if the motor torque is enabled
0 if the motor torque is disabled
-1 if failed to get the torque status
"""
# Packet to send
from_addr = self.ADDR_PC
to_addr = self.ADDR_MEGA
FC1 = self.FC_TORQUE_STATUS
FC2 = 0
data = motorID
send_array = [from_addr, to_addr, FC1, FC2, data]
try:
# Load the Tx buffer with the packet
send_size = self.link.tx_obj(send_array)
# Send the packet
self.link.send(send_size)
# Wait for the packet to be sent
sleep(0.001)
# Record the time the packet was sent
send_time = time.time()
# Wait for response with timeout
while not self.link.available():
if (time.time() - send_time) > self.RS485_TO:
print("Timeout waiting for response")
return -1
sleep(0.001)
# Process response
if self.link.status == txfer.NEW_DATA:
response = self.link.rx_obj(
obj_type=list, obj_byte_size=self.link.bytesRead, list_format="i"
)
from_addr = response[0]
to_addr = response[1]
FC1 = response[2]
FC2 = response[3]
if (
from_addr == self.ADDR_MEGA
and to_addr == self.ADDR_PC
and FC1 == 0
and FC2 == self.FC_TORQUE_STATUS
):
return response[4]
else:
print(
f"Error: Invalid response from {from_addr} to {to_addr} with FC1={FC1} and FC2={FC2}"
)
return -1
else:
print("Data receipt error. Status:", self.link.status)
return -1
except Exception as e:
print("Error:", e)
return -1
def _clip(self, value: int, min_value: int, max_value: int):
"""
Clips the input value to the specified range.
Parameters:
value (int): The input value to be clipped.
min_value (int): The minimum value of the range.
max_value (int): The maximum value of the range.
Returns:
int: The clipped value.
"""
op = max(min_value, min(value, max_value))
if op != value:
print(f"Warning: Value {value} to be sent to the robot clipped to {op}")
return op
def _mapAngleToRobot(
self, robot: str, motorID: int, angle: float, unit: str = "rad"
):
"""
Description:
This function maps the angle in radians to a 10-bit value.
The home (zero) position and the joint limits are preset
according to the motor ID and the robot type.
Input:
robot: '2R' or '5bar'
motorID: The ID of the motor
angle: The angle in radians.
unit: The unit of the angle. Default is 'rad'. Use 'deg' for degrees.
Output:
10-bit value of the angle to be communicated to the robot
-1: invalid robot type or unit
"""
# base motor ID = 1, elbow motor ID = 2.
# home at centre position for both the motors
home_2R = [512, 512]
# base motor ID 1 limits: + - 90 degrees, i.e., 307 counts
# elbow motor ID 2 limits: + - 144 degrees, i.e., 490 counts
limits_2R = [[512 - 307, 512 + 307], [512 - 490, 512 + 490]]
# left motor ID = 1, right motor ID = 2.
# home at 45 degrees away from the centre position for both the motors
# home_5bar = [512 - 153, 512 + 153]
home_5bar = [512, 512]
# left motor ID 1 limits: + 45 degrees and -90 degrees
# right motor ID 2 limits: + 90 degrees and -45 degrees
limits_5bar = [[512 - 307, 512 + 153], [512 - 153, 512 + 307]]
# scaling factor
if not isinstance(unit, str):
raise TypeError("Error: unit input should be a string")
else:
if unit == "rad":
scl = -(180 / math.pi) * (1023 / 300)
elif unit == "deg":
scl = -1023 / 300
else:
print(
"Error: Invalid unit entered. Please enter either 'rad' or 'deg' only"
)
return -1
# check if the robot input is a string
if not isinstance(robot, str):
raise TypeError("Error: robot input should be a string")
else:
# if the robot is 2R
if robot == "2R":
# check if the motor ID is 1 or 2
if motorID == 1:
# map the angle to the 10-bit value
angle_10bit = int(scl * angle + home_2R[0])
angle_10bit = self._clip(
angle_10bit, limits_2R[0][0], limits_2R[0][1]
)
elif motorID == 2:
# map the angle to the 10-bit value
angle_10bit = int(scl * angle + home_2R[1])
angle_10bit = self._clip(
angle_10bit, limits_2R[1][0], limits_2R[1][1]
)
elif robot == "5bar":
# check if the motor ID is 1 or 2
if motorID == 1:
# map the angle to the 10-bit value
angle_10bit = int(scl * angle + home_5bar[0])
angle_10bit = self._clip(
angle_10bit, limits_5bar[0][0], limits_5bar[0][1]
)
elif motorID == 2:
# map the angle to the 10-bit value
angle_10bit = int(scl * angle + home_5bar[1])
angle_10bit = self._clip(
angle_10bit, limits_5bar[1][0], limits_5bar[1][1]
)
else:
print(
"Error: Invalid robot type entered. Please enter either '2R' or '5bar' only"
)
return -1
return angle_10bit
def _mapAngleFromRobot(
self, robot: str, motorID: int, angle_10bit: int, unit: str = "rad"
):
"""
Description:
This function maps the 10-bit motor angle to the robot angle in radians.
The home (zero) position and the joint limits are preset
according to the motor ID and the robot type.
Input:
robot: '2R' or '5bar'
motorID: The ID of the motor
angle: The angle in radians.
unit: The unit of the output angle. Default is 'rad'. Use 'deg' for degrees.
Output:
The robot angle
-1: invalid robot type or unit
"""
# base motor ID = 1, elbow motor ID = 2.
# home at centre position for both the motors
home_2R = [512, 512]
# base motor ID 1 limits: + - 90 degrees, i.e., 307 counts
# elbow motor ID 2 limits: + - 144 degrees, i.e., 490 counts
limits_2R = [[512 - 307, 512 + 307], [512 - 490, 512 + 490]]
# left motor ID = 1, right motor ID = 2.
# home at 45 degrees away from the centre position for both the motors
# home_5bar = [512 - 153, 512 + 153]
home_5bar = [512 , 512]
# left motor ID 1 limits: + 45 degrees and -90 degrees
# right motor ID 2 limits: + 90 degrees and -45 degrees
limits_5bar = [[512 - 307, 512 + 153], [512 - 153, 512 + 307]]
# scaling factor
if not isinstance(unit, str):
raise TypeError("Error: unit input should be a string")
else:
if unit == "rad":
scl = -1 / ((180 / math.pi) * (1023 / 300))
elif unit == "deg":
scl = -1 / (1023 / 300)
else:
print(
"Error: Invalid unit entered. Please enter either 'rad' or 'deg' only"
)
return -1
# check if the robot input is a string
if not isinstance(robot, str):
raise TypeError("Error: robot input should be a string")
else:
# if the robot is 2R
if robot == "2R":
# check if the motor ID is 1 or 2
if motorID == 1:
# map the angle to the 16-bit value
angle = scl * (angle_10bit - home_2R[0])
elif motorID == 2:
# map the angle to the 16-bit value
angle = scl * (angle_10bit - home_2R[1])
elif robot == "5bar":
# check if the motor ID is 1 or 2
if motorID == 1:
# map the angle to the 16-bit value
angle = scl * (angle_10bit - home_5bar[0])
elif motorID == 2:
angle = scl * (angle_10bit - home_5bar[1])
else:
print(
"Error: Invalid robot type entered. Please enter either '2R' or '5bar' only"
)
return -1
return round(angle, 3)
def getJointAngle(self, motorID: int, unit: str = "rad"):
"""
Description: This function reads the motor joint angle
Input:
motorID: The ID of the motor
unit: optional input. Default is 'rad'. Use 'deg' for degrees.
Output:
joint angle
Nan if failed to get the joint angle
"""
# Packet to send
from_addr = self.ADDR_PC
to_addr = self.ADDR_MEGA
FC1 = self.FC_READ_ANGLE
FC2 = 0
data = motorID
send_array = [from_addr, to_addr, FC1, FC2, data]
try:
# Load the Tx buffer with the packet
send_size = self.link.tx_obj(send_array)
# Send the packet
self.link.send(send_size)
# Wait for the packet to be sent
sleep(0.001)
# Record the time the packet was sent
send_time = time.time()
# Wait for response with timeout
while not self.link.available():
if (time.time() - send_time) > self.RS485_TO:
print("Timeout waiting for response")
return -1
sleep(0.001)
# Process response
if self.link.status == txfer.NEW_DATA:
response = self.link.rx_obj(
obj_type=list, obj_byte_size=self.link.bytesRead, list_format="i"
)
from_addr = response[0]
to_addr = response[1]
FC1 = response[2]
FC2 = response[3]
if (
from_addr == self.ADDR_MEGA
and to_addr == self.ADDR_PC
and FC1 == 0
and FC2 == self.FC_READ_ANGLE
):
angle = self._mapAngleFromRobot(
self.rob, motorID, response[4], unit
)
return angle
else:
print(
f"Error: Invalid response from {from_addr} to {to_addr} with FC1={FC1} and FC2={FC2}"
)
return -1
else:
print("Data receipt error. Status:", self.link.status)
return -1
except Exception as e:
print("Error:", e)
return -1
def setJointAngle(
self,
motorID: int,
angle: float,
unit: str = "rad",
):
"""
Description:
This function sets the motor joint angle.
The motor torque is enabled automatically.
Input:
motorID: The ID of the motor
angle: The angle
unit: optional input. Default is 'rad'. Use 'deg' for degrees.
Output:
success/failure
"""
# Packet to send
from_addr = self.ADDR_PC
to_addr = self.ADDR_MEGA
FC1 = self.FC_WRITE_ANGLE
FC2 = 0
motorAngle = self._mapAngleToRobot(self.rob, motorID, angle, unit)
send_array = [from_addr, to_addr, FC1, FC2, motorID, motorAngle]
try:
# Load the Tx buffer with the packet
send_size = self.link.tx_obj(send_array)
# Send the packet
self.link.send(send_size)
# Wait for the packet to be sent
sleep(0.001)
# Record the time the packet was sent
send_time = time.time()
# Wait for response with timeout
while not self.link.available():
if (time.time() - send_time) > self.RS485_TO:
print("Timeout waiting for response")
return -1
sleep(0.001)
# Process response
if self.link.status == txfer.NEW_DATA:
response = self.link.rx_obj(
obj_type=list, obj_byte_size=self.link.bytesRead, list_format="i"
)
from_addr = response[0]
to_addr = response[1]
FC1 = response[2]
FC2 = response[3]
if (
from_addr == self.ADDR_MEGA
and to_addr == self.ADDR_PC
and FC1 == 0
and FC2 == self.FC_WRITE_ANGLE
):
# Read the acknowledgement
ack = response[4]
return ack
else:
print(
f"Error: Invalid response from {from_addr} to {to_addr} with FC1={FC1} and FC2={FC2}"
)
return -1
else:
print("Data receipt error. Status:", self.link.status)
return -1
except Exception as e:
print("Error:", e)
return -1
def penDown(self, angle=30):
"""
Description:
Pen down
Input:
angle in degrees: 30-Deg for 2R, 90-Deg for 5-bar
Output:
No feedback available from the servo motor. Inspect visually.
"""
# Packet to send
from_addr = self.ADDR_PC
to_addr = self.ADDR_MEGA
FC1 = self.FC_PEN_SERVO
FC2 = 0
data = angle
send_array = [from_addr, to_addr, FC1, FC2, data]
try:
# Load Tx buffer
send_size = self.link.tx_obj(send_array)
self.link.send(send_size)
sleep(0.001) # allow transmission
send_time = time.time()
# Wait for response with timeout
while not self.link.available():
if (time.time() - send_time) > self.RS485_TO:
print("Timeout waiting for response")
return False
sleep(0.001)
# Process response
if self.link.status == txfer.NEW_DATA:
response = self.link.rx_obj(
obj_type=list,
obj_byte_size=self.link.bytesRead,
list_format="i"
)
from_addr, to_addr, FC1, FC2, data = response[:5]
if (
from_addr == self.ADDR_MEGA
and to_addr == self.ADDR_PC
and FC1 == 0
and FC2 == self.FC_PEN_SERVO
):
return data
else:
print(
f"Error: Invalid response from {from_addr} "
f"to {to_addr} with FC1={FC1} and FC2={FC2}"
)
return False
else:
print("Data receipt error. Status:", self.link.status)
return False
except Exception as e:
print("Error:", e)
return False
def penUp(self):
"""
Description:
Pen up (lifted in air)
Input: -NA-
Output:
No feedback available from the servo motor. Inspect visually.
"""
# Packet to send
from_addr = self.ADDR_PC
to_addr = self.ADDR_MEGA
FC1 = self.FC_PEN_SERVO
FC2 = 0
data = 0 # pen up => move servo to 0 degrees
send_array = [from_addr, to_addr, FC1, FC2, data]
try:
# Load the Tx buffer with the packet
send_size = self.link.tx_obj(send_array)
# Send the packet
self.link.send(send_size)
# Wait for the packet to be sent
sleep(0.001)
# Record the time the packet was sent
send_time = time.time()
# Wait for response with timeout
while not self.link.available():
if (time.time() - send_time) > self.RS485_TO:
print("Timeout waiting for response")
return False
sleep(0.001)
# Process response
if self.link.status == txfer.NEW_DATA:
response = self.link.rx_obj(
obj_type=list,
obj_byte_size=self.link.bytesRead,
list_format="i"
)
from_addr, to_addr, FC1, FC2, data = response[:5]
if (
from_addr == self.ADDR_MEGA
and to_addr == self.ADDR_PC
and FC1 == 0
and FC2 == self.FC_PEN_SERVO
):
return data
else:
print(
f"Error: Invalid response from {from_addr} "
f"to {to_addr} with FC1={FC1} and FC2={FC2}"
)
return False
else:
print("Data receipt error. Status:", self.link.status)
return False
except Exception as e:
print("Error:", e)
return False
def _mapAngVelFromMotor(self, val_10bit: int):
"""
Description:
This function maps the 10-bit motor speed to the angular velocity in rad/s.
Angular velocity mapping to/from robot is independent of the robot type and motor ID.
Input:
val_10bit: The 10-bit motor speed value.
Output:
The angular velocity in rad/s with sign.
"""
# Present speed can be positive or negative like angular velocity.
# AX-12A: 0-1023 is CCW, 1024-2047 is CW rotation
# See https://emanual.robotis.com/docs/en/dxl/ax/ax-12a/#present-speed
# Output in rad/s with sign.
scl = -1 * (114 / 1023) * (2 * math.pi / 60)
if val_10bit > 1023:
op = -(val_10bit - 1024) * scl
op = round(op, 3)
return op
else:
op = val_10bit * scl
op = round(op, 3)
return op
def getJointState(self, motorID: int):
"""
Description: This function reads the motor joint angle and joint velocity
Input:
motorID: The ID of the motor
Output:
[joint angle (rad), joint velocity (rad/s)]
-1 if failed to get the state
"""
# Packet to send
from_addr = self.ADDR_PC
to_addr = self.ADDR_MEGA
FC1 = self.FC_READ_STATE
FC2 = 0
send_array = [from_addr, to_addr, FC1, FC2, motorID]
try:
# Load the Tx buffer with the packet
send_size = self.link.tx_obj(send_array)
# Send the packet
self.link.send(send_size)
# Wait for the packet to be sent
sleep(0.001)
# Record the time the packet was sent
send_time = time.time()
# Wait for response with timeout
while not self.link.available():
if (time.time() - send_time) > self.RS485_TO:
print("Timeout waiting for response")
return -1
sleep(0.001)
# Process response
if self.link.status == txfer.NEW_DATA:
response = self.link.rx_obj(
obj_type=list, obj_byte_size=self.link.bytesRead, list_format="i"
)
from_addr = response[0]
to_addr = response[1]
FC1 = response[2]
FC2 = response[3]
if (
from_addr == self.ADDR_MEGA
and to_addr == self.ADDR_PC
and FC1 == 0
and FC2 == self.FC_READ_STATE
):
angle = self._mapAngleFromRobot(self.robot, motorID, response[4])
velocity = self._mapAngVelFromMotor(response[5])
return [angle, velocity]
else:
print(
f"Error: Invalid response from {from_addr} to {to_addr} with FC1={FC1} and FC2={FC2}"
)
return -1
else:
print("Data receipt error. Status:", self.link.status)
return -1
except Exception as e:
print("Error:", e)
return -1
def _mapAngVelToMotor(self, vel: float):
"""
Description:
This function maps the angular velocity in rad/s to the 10-bit motor speed.
Only magnitude matters. The sign is skipped.
The motor will reach to the next position with 'vel' rad/s angular speed.
Angular velocity mapping to/from robot is independent of the robot type and motor ID.
Input:
vel: The angular velocity in rad/s.
The sign doesn't matter as its magnitude is used.
Output:
The 10-bit motor speed value.
"""
# See https://emanual.robotis.com/docs/en/dxl/ax/ax-12a/#moving-speed
# Input in rad/s with sign.
scl = (1023 / 114) * (60 / (2 * math.pi))
# Only magnitude matters. The sign is skipped.
spd = abs(vel)
# Zero speed is not allowed. Zero speed means full 1023 speed. So scale it a bit and add a constant.
if spd < 0.1:
spd = spd * 1.5 + 0.1
# Convert to 10-bit value.
op = int(spd * scl)
# Clip the value to the range [0, 1023].
op = self._clip(op, 0, 1023)
return op
def setJointState(self, motorID: int, state: list):
"""
Description:
This function sets the motor joint angle and joint velocity.
The motor torque is enabled automatically.
Input:
motorID: The ID of the motor
state: [joint angle (rad), joint velocity (rad/s)]
Output:
success/failure
"""
# If the list is longer than 2, ignore the rest of the values
if len(state) > 2:
print(
"Warning: The state list is longer than 2. Ignoring the rest of the values"
)
# Packet to send
from_addr = self.ADDR_PC
to_addr = self.ADDR_MEGA
FC1 = self.FC_WRITE_STATE
FC2 = 0
motorAngle = self._mapAngleToRobot(self.rob, motorID, state[0])
motorSpeed = self._mapAngVelToMotor(state[1])
send_array = [from_addr, to_addr, FC1, FC2, motorID, motorAngle, motorSpeed]
try:
# Load the Tx buffer with the packet
send_size = self.link.tx_obj(send_array)
# Send the packet
self.link.send(send_size)
# Wait for the packet to be sent
sleep(0.001)
# Record the time the packet was sent
send_time = time.time()
# Wait for response with timeout
while not self.link.available():
if (time.time() - send_time) > self.RS485_TO:
print("Timeout waiting for response")
return -1
sleep(0.001)
# Process response
if self.link.status == txfer.NEW_DATA:
response = self.link.rx_obj(
obj_type=list, obj_byte_size=self.link.bytesRead, list_format="i"
)
from_addr = response[0]
to_addr = response[1]
FC1 = response[2]
FC2 = response[3]
if (
from_addr == self.ADDR_MEGA
and to_addr == self.ADDR_PC
and FC1 == 0
and FC2 == self.FC_WRITE_STATE
):
# Read the acknowledgement
ack = response[4]
return ack
else:
print(
f"Error: Invalid response from {from_addr} to {to_addr} with FC1={FC1} and FC2={FC2}"
)
return -1
else:
print("Data receipt error. Status:", self.link.status)
return -1
except Exception as e:
print("Error:", e)