上面的脚本应该将用户输入作为字符串接收。该字符串将类似于“120,50”,其中 120 是 x 坐标,50 是 y 坐标。我编写了一个名为“judge”的函数,它将接受用户输入,将其分成两部分(x 和 y),然后检查 x 或 y 是大于 127 还是小于 -127。如果是这种情况,它应该在 x/y 值中加上或减去 127。这样做是为了获得差异。然后它添加最初获得差异所需的 127(或减去)。在这个计算之后,这些值被发送到一个 arduino,鼠标相应地移动。
主机上的 main.py
import serial, serial.tools.list_ports
import win32api
from time import sleep
# print list of available comports
ports = list(serial.tools.list_ports.comports())
for _ in ports:
print(_)
# establish connection with given comport
comport = input("Enter comport: COM")
ser = serial.Serial(f"COM{comport}", 115200)
# send coordinates in bytes
def write_read(x):
ser.write(x.encode("utf-8"))
def judge(num, append_string_x, append_string_y):
x, y = num.split(",")
if int(x) > 127:
append_string_x = str(int(x) - 127)
# ADD 127 AFTER SENDING
write_read("127,0")
sleep(0.01) # Sleep is used to circumvent a bug I found
elif int(x) < -127:
append_string_x = str(int(x) + 127)
# SUBTRACT 127 AFTER SEND
write_read("-127,0")
sleep(0.01) # Sleep is used to circumvent a bug I found
else:
append_string_x = str(x)
if int(y) > 127:
append_string_y = str(int(y) - 127)
# ADD 127 AFTER SENDING
write_read("0,127")
sleep(0.01) # Sleep is used to circumvent a bug I found
elif int(y) < -127:
append_string_y = str(int(y) + 127)
# SUBTRACT 127 AFTER SENDING
write_read("0,-127")
sleep(0.01) # Sleep is used to circumvent a bug I found
else:
append_string_y = str(y)
x_y = f"{append_string_x},{append_string_y}"
write_read(x_y)
sleep(0.01) # Sleep is used to circumvent a bug I found
# main while loop
while True:
num = input("Enter a number: ")
judge(num, append_string_x="", append_string_y="")
arduino 上的 main.c
#include "HID-Project.h"
void setup() {
Serial.begin(115200);
Serial.setTimeout(1); // This shit almost gave me a heart attack
Mouse.begin();
}
void loop()
{
if(Serial.available() > 0)
{
String str = Serial.readStringUntil(',');
int dx = str.toInt();
int dy = Serial.parseInt();
mouse_move(dx, dy);
}
}
void mouse_move(int dx, int dy)
{
Mouse.move(dx, dy);
}
没有 sleep(0.01)
调用 main.py的行为
当 main.py 中不包含 sleep(0.01) 调用时,为什么会有 y 轴移动?
编辑:如果有帮助,我正在使用 Arduino Micro atmega32u4。