python-serial port

website

conda install pyserial
or
pip3 install pyserial

readline

readline 需要 \n 结尾

import serial

def simulate_DL_RS1A():
try:
# 端口,GNU / Linux上的/ dev / ttyUSB0 等 或 Windows上的 COM3 等
port = "COM2"
# 波特率,标准值之一:50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,19200,38400,57600,115200
baudrate = 19200
# 超时设置,None:永远等待操作,0为立即返回请求结果,其他值为等待超时时间(单位为秒)
timeout = 5
ser = serial.Serial(port, baudrate, timeout=timeout)
# 循环读取数据
while True:
line = ser.readline().decode("gbk")
if line.startswith('M0\r\n'):
result = ser.write("M0,-00.029,+00.043,+00.056,-00.038,+00.037,+00.018,-00.229,+00.030\r\n".encode("gbk"))
pass

# 写数据
result = ser.write("123456".encode("gbk"))
print("字节数:", result)
ser.close() # 关闭串口
except Exception as e:
import traceback
traceback.print_exc()
errMsg = traceback.format_exc()
print("Error: 异常,无法发送邮件: " + errMsg)
except:
import traceback
traceback.print_exc()
errMsg = traceback.format_exc()
print("Error: 未知异常,无法发送邮件: " + errMsg)
pass

read

read(size=1)
Parameters: size – Number of bytes to read.
Returns: Bytes read from the port.
Return type: bytes
Read size bytes from the serial port. If a timeout is set it may return less characters as requested. With no timeout it will block until the requested number of bytes is read.

Changed in version 2.5: Returns an instance of bytes when available (Python 2.6 and newer) and str otherwise.