forked from raffaelemazziotti/oc_chamber
-
Notifications
You must be signed in to change notification settings - Fork 0
/
libSerial.py
executable file
·88 lines (68 loc) · 2.24 KB
/
libSerial.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
import serial
import sys
import glob
from serial.tools import list_ports
import time
# LOW LEVEL ARDUINO COMMUNICATION
def connect(port=None,baud=9600):
if port is None:
obj = ports()
port = obj[0] # CONNECTS AUTOMATICALLY WITH THE FIRST SERIAL PORT
connection = serial.Serial(port,baud,bytesize=8, parity='N', stopbits=1, timeout=None, rtscts=0) # open serial port
time.sleep(3)
return connection
def disconnect(connection):
connection.close()
def write(connection,string):
connection.write(bytes(string,'UTF-8'))
connection.flush()
def readline(connection):
return connection.readline() # read a '\n' terminated line
def wait(connection,timeout=10):
start_time = time.time()
while connection.in_waiting==0:
if (time.time() - start_time)>=timeout:
return False
time.sleep(.01)
return True
def infWait(connection):
while connection.in_waiting==0:
time.sleep(.01)
def flushInput(connection):
connection.flushInput()
def flushOutput(connection):
connection.flushOutput()
def flush(connection):
connection.flush()
def ports():
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
#===============================================================================
if __name__=="__main__":
con = connect()
#
write(con,bytes('30','UTF-8'))
print('Waiting for incoming data...')
b =wait(con)
if(b):
print(readline(con))
else:
print('Timeout reached: No data to print')
disconnect(con)
#===============================================================================