gpt4 book ai didi

python - Arduino 加速计到 Python 输出

转载 作者:行者123 更新时间:2023-12-01 06:21:00 27 4
gpt4 key购买 nike

我正在尝试获取我的arduino代码,让它输出一个字符,然后让我的python代码接受该字符并执行一个功能(按上、下、左或右)。现在我的arduino代码正在给我一个我想要的字母的输出,当我运行python时我看到了这个输出,但是python仍然没有像我需要的那样按下按钮。任何帮助都会很棒!

Arduino 代码:


int xmin=250,xmax=330;
int ymin=264,ymax=330;
int zmin=268,zmax=400;
int n=0, nx=0, ny=0, nz=0, a=0;
int x,y,z;
String cad="";

void setup() {
Serial.begin(115200);
}


void loop() {


nx=1;ny=1;nz=1;a=1;
x=analogRead(1);
y=analogRead(2);
z=analogRead(3);
x=9-map(x,xmin,xmax,0,9);
y=map(y,ymin,ymax,0,9);
z=map(z,zmin,zmax,0,9);


if (x<3) nx=0;
if (x>5) nx=2;
if (y<3) ny=0;
if (y>5) ny=2;
if (z<3) nz=0;
if (z>5) nz=2;


a=1+9*nz+nx+3*ny;

if (a==25){
Serial.write('A'); //Release
}
else if (a==18){
Serial.write('B'); //Duck
}
else if (a==26){
Serial.write('C'); //Move right
}
else if (a==10){
Serial.write('D'); //Left
}
else if (a==22){
Serial.write('D');
}
else if (a==16){
Serial.write('E'); //Jump
}
delay(200);

}

Python 代码:

import serial
import time
import pyautogui


str_up="up"
str_down="down"
str_left="left"
str_right="right"


ArduinoSerial = serial.Serial(port='/dev/tty.usbmodem14501', baudrate=115200)
time.sleep(2)

while 1:
incoming = str (ArduinoSerial.read(1)) #Read one byte from serial port
print(incoming)

if 'D' == incoming:
pyautogui.keyDown(str_left) # Press left and ...
pyautogui.keyUp(str_left) # release
elif 'A' in incoming:
pyautogui.keyUp(str_right) ## release and ...
pyautogui.keyUp(str_right) # release
elif 'C' == incoming:
pyautogui.keyDown(str_right) # Press right and ...
pyautogui.keyUp(str_right) # release
elif 'B' == incoming:
pyautogui.keyDown(str_down) ## Press down and ...
pyautogui.keyUp(str_down) # release
elif 'E' == incoming:
pyautogui.keyDown(str_up) ## Press up and ...
pyautogui.keyUp(str_up) # release


ArduinoSerial.reset_input_buffer() # Flush the serial port

最佳答案

根据文档:https://pyautogui.readthedocs.io/en/latest/keyboard.html#the-press-keydown-and-keyup-functions您可以使用“press('up')”方法代替 keyDown 和 keyUp。也许注册太快了?您可以尝试在两者之间等待一段时间。

示例:

>>> pyautogui.keyDown('shift')  # hold down the shift key
>>> pyautogui.press('left') # press the left arrow key
>>> pyautogui.press('left') # press the left arrow key
>>> pyautogui.press('left') # press the left arrow key
>>> pyautogui.keyUp('shift') # release the shift key

关于python - Arduino 加速计到 Python 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60356258/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com