【发布时间】:2022-01-26 00:40:55
【问题描述】:
我有一个程序应该从 arduino(通过串行)获取操纵杆位置读数,并将它们转换为我计算机上的鼠标移动。
这只有一个问题...
字符串到整数的转换太慢了,而且动作要花很长时间才能注册。
我需要一种更快的方法来将字符串转换为整数值,或者完全跳过转换。
这是我当前的代码:
import serial
import pyautogui
import time
ser = serial.Serial('COM3', 9600, timeout=1)
while True:
time.sleep(0.0001)
ser_bytes = ser.readline()
decoded_bytes = ser_bytes[0:len(ser_bytes)-2].decode("utf-8")
pos = decoded_bytes.split(':')
xpos = int(pos[0])
ypos = int(pos[1])
print("x:", xpos, " y:", ypos)
pyautogui.move(xpos, ypos)
注意:arduino 的输出具有 3 值: 0:0:0 第一个数字:x 第二个数字:y 第三个数字:摇杆按钮
【问题讨论】:
-
为什么不删除 time.sleep()?
-
sleep()和ser.readline()和print(...)语句可能比 int() 语句昂贵得多。 -
print 语句仅用于调试,但 sleep() 语句是为了避免程序不断崩溃的错误,而 ser.readline() 语句很关键,因为它从arduino。
-
你确定字符串到整数的转换实际上是瓶颈吗?您如何验证这一点?
-
我已经通过取出代码片段验证了这一点,主要瓶颈是字符串到整数的转换,另一个大瓶颈是 time.sleep() 语句,但这应该会变慢将代码缩减非常少,以避免串行通信错误。