I have a program that is supposed to take joystick position readings from an arduino (over serial), and translate them to mouse movements on my computer.
There is only one problem with this...
The string to integer conversion is way too slow, and it takes forever for the movements to register.
I need either a faster way to convert a string to an integer value, or a way to skip the conversion altogether.
This is my current code:
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)
Note: Output from arduino has 3 values: 0:0:0 First number: x Second number: y Third number: joystick button
Perhaps something like this will work? This way you can read more than one line of input for each time you call move()
. Some lines of input will be ignored, but that seems necessary if you're getting input faster than you can use it.
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)