-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserialTester.py
More file actions
69 lines (61 loc) · 2.13 KB
/
serialTester.py
File metadata and controls
69 lines (61 loc) · 2.13 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
#!/usr/bin/python
import threading, time, serial, readline
stopFlag = False #Flag to determine when to end program
readAsBytes = False # Flag to read serial data as bytes instead of text
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=None)
#ser.open() Open is called in constructor.
def serialWrite():
global stopFlag
global readAsBytes
while True:
dataToSend = raw_input("Byte Command>>> ")
if dataToSend == "":
continue
if dataToSend == "bytes":
readAsBytes = True
print "Incoming serial data will now be printed as individual bytes"
continue
if dataToSend == "text":
readAsBytes = False
print "Incoming serial data will now be treated as text"
continue
if dataToSend == "exit":
stopFlag = True
print "Exiting serialWrite"
return
bytesToSend = dataToSend.split()
cmdToSend = ""
try:
for x in range(0, len(bytesToSend)):
cmdToSend = cmdToSend + chr(int(bytesToSend[x]));
ser.write(cmdToSend)
except ValueError:
print "Error: Only byte-level commands can be sent. The command must only contain integers from 0-255 separated by whitespace"
def serialRead():
while stopFlag==False:
time.sleep(.1);
if ser.inWaiting() > 0:
if readAsBytes:
dataToRead = ser.read(ser.inWaiting())
dataToPrint = ""
for x in range(0, len(dataToRead)):
dataToPrint = dataToPrint + str(ord(dataToRead[x])) + " "
print dataToPrint
else:
dataToRead = ser.readline()
if dataToRead != "":
print dataToRead
ser.flush()
print "Exiting serialRead"
try:
print "Type 'exit' to close program. Type byte commands delimited by whitespace to send"
writeLoop = threading.Thread(target=serialWrite) #create a separate thread for writing to serial port
readLoop = threading.Thread(target=serialRead) #create a separate thread for reading from serial port
writeLoop.start()
readLoop.start()
writeLoop.join() #wait for this thread to finish
readLoop.join() #wait for this thread to finish
print "Exiting main thread"
ser.close()
except KeyboardInterrupt:
ser.close()