读取10s数据,然后关闭串口
#读取10s串口数据后关闭这个串口 import time def read_serial(port, baudrate, duration): try: # 初始化串口 ser = serial.Serial(port, baudrate) print(f"Opened serial port {port} at {baudrate} baud.") # 记录开始时间 start_time = time.time() # 持续读取数据直到指定的时间(10秒)到达 while time.time() - start_time < duration: # 从串口读取一行数据 #line = ser.readline().decode('utf-8') line = ser.readline().decode('utf-8').strip() if line: print(f"Received data: {line}") print(f"Reading data for {duration} seconds completed.") except serial.SerialException as e: print(f"Error opening or using serial port: {e}") finally: # 关闭串口 if ser.is_open: ser.close() print(f"Closed serial port {port}.") # 设置串口参数 port = 'COM3' # 根据实际情况更改为您的串口端口,例如'/dev/ttyUSB0'或'/dev/ttyS0'等 baudrate = 115200 # 设置波特率 duration = 10 # 持续时间为10秒 # 调用函数读取串口数据 read_serial(port, baudrate, duration)
标签:读取,python,串口,time,duration,serial,port,ser From: https://www.cnblogs.com/lpj1393822011/p/18383695