讀取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)