-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_read_serial.py
More file actions
36 lines (28 loc) · 854 Bytes
/
Copy pathtest_read_serial.py
File metadata and controls
36 lines (28 loc) · 854 Bytes
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
import time
import serial
ser = serial.Serial(
port="/dev/ttyUSB0",
baudrate=19200,
bytesize=8,
parity=serial.PARITY_NONE,
stopbits=1,
timeout=5,
)
print(f"Reading on port {ser.portstr} at {ser.baudrate} baud")
try:
print("StartFing serial read loop. Press Ctrl+C to stop.")
while True:
data = ser.readline()
current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
if data:
try:
decoded_data = data.decode("utf-8").strip()
print(f"[{current_time}] Received: {decoded_data}")
except UnicodeDecodeError:
print(f"[{current_time}] Received (hex): {data.hex()}")
time.sleep(0.1)
except KeyboardInterrupt:
print("\nRead loop stopped by user")
finally:
ser.close()
print("Serial port closed")