结果是我预期的。我正在尝试确保以有用的格式拥有数据,并且代码有效或可以更简单。我的代码中有什么可能正在减慢它的速度。
在我的测试中,以下脚本可以减少很多时间:
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()
填充输入缓冲区(reset_input_buffer()) - 防止过时的数据问题。
增加了一个小延迟(Time.Sleep(0.05)) - 允许时间进行处理。反应验证 - 确保仅处理有效的响应。