import serial ### pip install pyserial
ser = serial.Serial(read_com, com_band, timeout=3) # Open COM3, baud rate 9600, timeout 3 seconds
ser.flushInput() # Clear the buffer
while True:
try:
count = ser.inWaiting() # Get serial buffer data
if count != 0:
recv_bytestream = ser.read(100) ##读取100个字节,格式为bytes
recv_bytestream = ser.read_all() ##Read all the data in a timeout period, the format is bytes
print(time.time(), "recv_bytestream:", recv_bytestream)
# bytes转为字符串方法
recv_str = str(recv_bytestream, 'UTF-8')
print(time.time(), "recv_str:", recv_str)
### 处理数据 ###
except Exception as e:
print("exception:", e)
finally:
time.sleep(0.01) # 延时0.01秒,免得CPU出问题
pass