-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader.py
59 lines (48 loc) · 1.29 KB
/
reader.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
import serial
import threading
import time
import serial.tools.list_ports
import platform
baud = 9600
ser = None
def find_serial_port():
system = platform.system()
if system == 'Windows':
return find_windows_serial_port()
elif system == 'Linux':
return find_linux_serial_port()
else:
print("Unsupported operating system.")
return None
def find_windows_serial_port():
ports = serial.tools.list_ports.comports()
for port in ports:
if port.device.startswith("COM"):
return port.device
return None
def find_linux_serial_port():
ports = serial.tools.list_ports.comports()
for port in ports:
if "tty" in port.device:
return "/dev/" + port.device
return None
def main():
global ser
port = find_serial_port()
if port is None:
print("No serial port found.")
return
ser = serial.Serial(port, baud, timeout=1)
thread = threading.Thread(target=serial_read, args=(ser,))
thread.start()
while True:
ser.read(ser.inWaiting())
time.sleep(1)
ser.close()
def serial_read(ser):
while True:
data = ser.readline()
if len(data) > 0:
data_str = data.replace(b'\r\n', b'')
print(data_str.decode('utf-8'))
main()