安装方式
pip install pyserial
python串口收发数据简单DEMO
import serial
import time
from datetime import datetime
import threading
# 开启com12口,波特率115200,超时15s
ser = serial.Serial("COM12", 115200, timeout=15)
ser.flushInput()
def timestamp_convert_realtime(ts):
return str(datetime.fromtimestamp(float(ts)))
def receive_serial_data():
while True:
# 获取串口缓冲区数据
count = ser.inWaiting()
if count != 0:
# 读出串口数据
recv = ser.readline().decode()
print(timestamp_convert_realtime(time.time()), " ", recv)
# print(recv)
time.sleep(0.1)
def send_serial_data():
ser.write("ls /usrdata\n".encode('utf-8'))
if __name__ == '__main__':
t1 = threading.Thread(target=receive_serial_data)
t1.start()
send_serial_data()
参考链接
仓库地址:https://github.com/pyserial/pyserial
官方文档:https://pyserial.readthedocs.io/en/latest/index.html