阅读串行端口并将数据存储在字典中

问题描述 投票:0回答:1
样本数据out: {'001':'0300','002':'0700','003':'3000','004':'004':'0',005':005':'1',006':006':'0',','' 007':'1','008':'08','009':'2','010':'050','011':'050', '012':'3','013':'0','014':'30'}

结果是我预期的。我正在尝试确保以有用的格式拥有数据,并且代码有效或可以更简单。我的代码中有什么可能正在减慢它的速度。
	

在我的测试中,以下脚本可以减少很多时间:

import serial import time def Read_Radio(): ser = serial.Serial( port='COM4', baudrate=38400, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=0.2 # Reduced timeout for faster response ) def send_command(ser, command): ser.reset_input_buffer() # Flush buffer before sending ser.write(command.encode()) # Send command time.sleep(0.05) # Small delay to allow device processing response = ser.readline().decode().strip() # Strip spaces/newlines return response menu_data = {} try: for m in range(1, 15): # Limited to 15 for testing. ID = f"{m:03}" command = f"EX{ID};" response = send_command(ser, command) if response: # Check if response is valid raw = response.lstrip("EX").rstrip(";") if len(raw) >= 3: P1, P2 = raw[:3], raw[3:] menu_data[P1] = P2 except Exception as e: print(f"An error occurred: {e}") finally: print(menu_data) ser.close() Read_Radio()

python serial-port evaluate
1个回答
0
投票
取消超时(0.2秒) - 避免不必要的等待。

填充输入缓冲区(reset_input_buffer()) - 防止过时的数据问题。

增加了一个小延迟(Time.Sleep(0.05)) - 允许时间进行处理。
反应验证 - 确保仅处理有效的响应。
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.