需要快速将字符串转换为 int python

Need to convert strint to int quickly python

我有一个程序应该从 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 第三个数字:摇杆按钮

也许这样的事情会奏效?这样你每次调用 move() 就可以读取一行以上的输入。某些输入行将被忽略,但如果您获得输入的速度快于您使用它的速度,这似乎是必要的。

import serial
import pyautogui
import time

ser = serial.Serial('COM3', 9600, timeout=1)
while True:
    time_to_move = time.time() + 0.001
    while True:
        ser_bytes = ser.readline()
        if time.time() >= time_to_move:
            break
    x_bytes, y_bytes = ser_bytes[:-2].split(b':')
    x, y = int(x_bytes), int(y_bytes)
    pyautogui.move(x, y)