-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexampleRS232text.py
More file actions
66 lines (62 loc) · 1.89 KB
/
exampleRS232text.py
File metadata and controls
66 lines (62 loc) · 1.89 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
import serial
import time
from typing import Optional
def send_text_command(port: str, baud: int, command: str, seol: str = "\r", timeout: float = 1.0, read_size: int = 1024) -> Optional[str]:
"""
Open serial port, send `command` as text (with `seol` appended), read response and return it decoded.
Returns None on error.
"""
ser = None
try:
ser = serial.Serial(
port=port,
baudrate=baud,
bytesize=serial.EIGHTBITS,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
timeout=timeout,
xonxoff=False,
rtscts=False,
dsrdtr=False
)
# assert control lines if desired
try:
ser.setDTR(False)
ser.setRTS(False)
except Exception:
pass
time.sleep(0.2) # small settle
text = f"{command}{seol}"
print(f"Sending: {text!r}")
ser.write(text.encode("ascii"))
#ser.write(text.encode("utf-8"))
time.sleep(0.2)
resp = ser.read(read_size)
if not resp:
print("A")
return ""
try:
print("B")
#return resp.decode("utf-8", errors="ignore")
return resp.decode("ascii", errors="ignore")
except Exception:
print("C")
#return resp.decode("latin1", errors="ignore")
return resp.decode("ascii", errors="ignore")
except Exception as e:
print("Serial error:", e)
return None
finally:
if ser and ser.is_open:
try:
ser.close()
except Exception:
pass
if __name__ == "__main__":
# adjust port/baud to your device
port = "/dev/tty722540"
# baud = 115200
baud = 9600
reply = send_text_command(port, baud, "*IDN?", seol="")
print("Reply:", reply)
# ...existing code...