SERIAL之 READLINE READ_UNTIL比较

本文介绍了一种使用Python进行串口通信的方法,通过测试readline和read_until函数在不同timeout设置下的表现,对比了阻塞型和非阻塞型读取方式的差异。
部署运行你感兴趣的模型镜像

READLINE

  • 阻塞型,除非设置了timeout

READ_UNTIL

  • 非阻塞型,最好设置timeout
# test serial timeout, readline and read_until
import time
import serial
import serial.tools.list_ports

def get_time_stamp():
   ct = time.time()
   local_time = time.localtime(ct)
   data_head = time.strftime("%Y-%m-%d %H:%M:%S", local_time)
   data_secs = (ct - int(ct)) * 1000
   time_stamp = "%s.%03d" % (data_head, data_secs)
   return time_stamp


port_list = list(serial.tools.list_ports.comports())
#print(port_list)
if len(port_list) == 0:
   print('无可用串口')
else:
   for i in range(0,len(port_list)):
       #help(port_list[i])
       #print(port_list[i].__dict__)
       #print(port_list[i])
       port_name = port_list[i].device

tout = 0.1
#print(port_name)
#print(type(port_name))

###############################test readline function##########################################
try:
   serial_timeout = serial.Serial(port_name,115200,timeout=tout)
except Exception as e:
   print('rasie exception:',e)
   
try:
   serial_timeout.open()
except:
   print(port_name,' has opened! ')
   
print('start test readline.........',get_time_stamp())

#write serial
try:
   serial_timeout.write(b'II\n')
except Exception as e:
   print(e)
#read serial
try:
   serial_timeout.readline()
except Exception as e:
   print(e)
   
#serial_timeout.close()
print('stop test readline.........',get_time_stamp())


###############################test readline function##########################################

#serial_timeout = serial.Serial(port_name,115200,timeout=tout)

try:
   serial_timeout = serial.Serial(port_name,115200,timeout=tout)
except Exception as e:
   print('rasie exception:',e)
   
   
try:
   serial_timeout.open()
except:
   print(port_name,' has opened! ')
   
print('start test read_until.........',get_time_stamp())

#write serial
try:
   serial_timeout.write(b'II\n')
except Exception as e:
   print(e)
#read serial
try:
   serial_timeout.read_until(b'\n\n')
except Exception as e:
   print(e)
   
serial_timeout.close()
print('stop test read_until.........',get_time_stamp())

   
   
输出结果:

timeout = 0.1
在这里插入图片描述
timeout = 10
在这里插入图片描述

您可能感兴趣的与本文相关的镜像

Python3.10

Python3.10

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

import serial import time import sys # 创建并打开串口 serial_port = serial.Serial() def Writes(data): try: serial_port.write(data) serial_port.flush() except serial.SerialException as e: print(f"Serial write error: {e}") return -2 except Exception as e: print(f"Unexpected error: {e}") return -1 return 0 def main(): try: # 设置串口参数 serial_port.baudrate = 9600 # 波特率 serial_port.port = "/dev/ttyUSB0" # 串口设备 serial_port.bytesize = serial.EIGHTBITS # 数据位 serial_port.stopbits = serial.STOPBITS_ONE # 停止位 serial_port.parity = serial.PARITY_NONE # 校验位 serial_port.timeout = 1 # 读超时(秒) serial_port.xonxoff = False # 软件流控制 serial_port.rtscts = False # 硬件(RTS/CTS)流控制 serial_port.dsrdtr = False # 硬件(DSR/DTR)流控制 # 打开串口 serial_port.open() buff=bytearray(5) buff[0]=0xFE buff[1]=4 buff[2]=5 buff[3]=8 buff[4]=0xFF i=0 while(i!=5): Writes(buff[i]) i=i+1 # 读取串口返回的数据 try: # 读取直到遇到换行符或超时 read_data = serial_port.readline().decode('utf-8').strip() print(f"Received: {read_data}") except UnicodeDecodeError: print("Warning: Could not decode received data as UTF-8") # 可以尝试其他编码或直接读取字节 serial_port.reset_input_buffer() # 关闭串口 serial_port.close() except serial.SerialException as e: print(f"Serial port error: {e}") return 1 except Exception as e: print(f"Error: {e}") return 1 return 0 if __name__ == "__main__": sys.exit(main())帮我分析这段代码有什么问题
11-19
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值