-
Notifications
You must be signed in to change notification settings - Fork 1
/
ArduinoCarArm.py
217 lines (189 loc) · 5.68 KB
/
ArduinoCarArm.py
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
import sys
import glob
import atexit
import serial
import serial.tools.list_ports
from pynput.keyboard import Key, Controller, Listener
import threading
import time
### global constants ###
move_step = 5
switcher = {
#Car
'MOT_A_SPD': 'a',
'MOT_B_SPD': 'c',
'FORWARD_CMD': 'f',
'BACK_CMD': 'b',
'LEFT_CMD': 'l',
'RIGHT_CMD': 'r',
'STOP_CMD': 's',
'BRAKE_CMD': 'v',
#Arm
'BASE_CMD': 'x',
'SHOULDER_CMD':'u',
'ELBOW_CMD': 'e',
'GRIPPER_CMD': 'g',
'GRIPPER_OC': 'o'
}
### global variables ###
_base_deg = 100
_shoulder_deg = 100
_elbow_deg = 100
_gripper_deg = 100
ser = None
kill = False
buff = ''
dest = None
lock1 = threading.Lock()
lock2 = threading.Lock()
### method ###
def cmd_handler(arg1, arg2=None):
ser.write(switcher[arg1].encode())
if arg2:
ser.write(str(arg2).encode())
ser.write('\n'.encode())
#Courtesy by Thomas @ https://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python
def get_serial_ports():
""" Lists serial port names
:raises EnvironmentError:
On unsupported or unknown platforms
:returns:
A list of the serial ports available on the system
"""
if sys.platform.startswith('win'):
ports = ['COM%s' % (i + 1) for i in range(256)]
elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
# this excludes your current terminal "/dev/tty"
ports = glob.glob('/dev/tty[A-Za-z]*')
elif sys.platform.startswith('darwin'):
ports = glob.glob('/dev/tty.*')
else:
raise EnvironmentError('Unsupported platform')
result = []
for port in ports:
try:
s = serial.Serial(port)
s.close()
result.append(port)
except (OSError, serial.SerialException):
pass
return result
def get_ports_routine():
while input("Scan ports?(y/n):") == 'y':
print("Available serial ports:{}".format(get_serial_ports()))
def connect_routine():
global ser
port = input("Port(tty***/COM***):")
baud = input("Baudrate:")
try:
ser = serial.Serial(port, baud, timeout=30)
except ValueError:
if input("Baudrate should be an integer. Continue?(y/n):") != 'y':
access_kill(True)
except serial.SerialException:
if input("Connect error. Continue?(y/n):") != 'y':
access_kill(True)
def access_kill(write=None):
global kill
lock2.acquire()
if write != None:
kill = write
_return = kill
lock2.release()
return _return
def on_press(key):
global _base_deg, _shoulder_deg, _elbow_deg, dest, buff
if not ser or not ser.is_open:
return False
if key == Key.esc:
return True
if dest != None:
if key == Key.enter:
if dest == 'A':
cmd_handler('MOT_A_SPD', buff)
else:
cmd_handler('MOT_B_SPD', buff)
print('Send "{}" to motor {}.'.format(str(buff), dest))
dest = None
buff = ''
else:
buff += str(key)[1]
else:
if key == Key.up:
cmd_handler('FORWARD_CMD')
print('Forward')
elif key == Key.down:
cmd_handler('BACK_CMD')
print('Backward')
elif key == Key.left:
cmd_handler('LEFT_CMD')
print('Turn left')
elif key == Key.right:
cmd_handler('RIGHT_CMD')
print('Turn right')
elif str(key)[1] == '.':
cmd_handler('STOP_CMD')
print("STOP")
elif str(key)[1] == 'a':
_base_deg -= move_step
cmd_handler('BASE_CMD', _base_deg)
elif str(key)[1] == 'd':
_base_deg += move_step
cmd_handler('BASE_CMD', _base_deg)
elif str(key)[1] == 'w':
_shoulder_deg += move_step
cmd_handler('SHOULDER_CMD', _shoulder_deg)
elif str(key)[1] == 's':
_shoulder_deg -= move_step
cmd_handler('SHOULDER_CMD', _shoulder_deg)
elif str(key)[1] == 'q':
_elbow_deg -= move_step
cmd_handler('ELBOW_CMD', _elbow_deg)
elif str(key)[1] == 'e':
_elbow_deg += move_step
cmd_handler('ELBOW_CMD', _elbow_deg)
elif str(key)[1] == 'o':
cmd_handler('GRIPPER_OC')
elif str(key)[1] == 'f':
dest = 'A'
print('Motor A:')
elif str(key)[1] == 'g':
dest = 'B'
print('Motor B:')
elif str(key)[1] == 'x':
access_kill(True)
return False # Stop listener
def on_release(key):
if not ser or not ser.is_open:
return False
if key == Key.up:
cmd_handler('STOP_CMD')
elif key == Key.down:
cmd_handler('STOP_CMD')
elif key == Key.left:
cmd_handler('STOP_CMD')
elif key == Key.right:
cmd_handler('STOP_CMD')
#atexit.register(cleanup)
#
#Main program start here
#
def main():
typer = Controller()
while not access_kill():
get_ports_routine()
connect_routine()
try:
with Listener(on_press = on_press, on_release = on_release) as listener:
while not access_kill():
typer.press(Key.esc)
if not listener.is_alive():
break
time.sleep(1)
listener.join()
except:
pass
if ser:
ser.close()
if __name__ == '__main__':
main()