gpt4 book ai didi

python - 使用 Python 作为界面时的奇怪控件

转载 作者:行者123 更新时间:2023-11-30 17:10:35 25 4
gpt4 key购买 nike

我正在实现 Python (2.7.9) 作为带有操纵杆和几个按钮的 Arduino 与 Linux 机器之间的接口(interface),以在模拟器上控制 Megaman。操纵杆进行 x/y 运动,按钮进行触发和跳跃。我的代码接收格式为 (X_Y_FIRE_JUMP) 的字符串,并解析出这些值,然后使用 PyUserInput 查看应该在键盘上输入的内容。图书馆。

但是,一个奇怪的错误正在发生:每当我向右移动时,即使没有按下任何一个按钮,洛克人也会疯狂地开火。我检查了我的串行输出,看看这是否是硬件方面的,但事实并非如此;接收到的串行字符串是干净的,因为它应该看起来像这样“[X>510]_[Y~510]_k_t”。所以,X 告诉它向右移动,Y 并没有真正做任何事情,k 告诉它不要跳跃,t 告诉它不要开火。为什么我在向右移动时仍然会发生粗略的意外射击?

Python 代码:

import serial
from pykeyboard import PyKeyboard


control = PyKeyboard()


def getxy():
while True:
try:
ab = arduino.readline()
a, b, c, d = ab.split("_")
a = int(a)
a = a - 512
# This is pure jiggery-pokery and apple sauce. The joystick controller is
# totally kaput (#german) and I didn't want to mess with the wiring (damn
# color wires. Don't touch this, it will hurt your family.)
b = int(b)
b = (b - 512) * -1
return a, b, c, d
except Exception:
continue
break


def procxy():
x, y, s, j = getxy()
mov = ""
if (x > 100):
mov = mov + "r"
if (x < -100):
mov = mov + "l"
if (y > 100):
mov = mov + "u"
if (y < -100):
mov = mov + "d"
if ("f" in s):
mov = mov + "f"
if ("j" in j):
mov = mov + "j"
return mov


def doshot(instr):
if ("f" in instr):
control.press_key('z')
if ("f" not in instr):
control.release_key('z')


def dojump(instr):
if ("j" in instr):
control.press_key('s')
if ("j" not in instr):
control.release_key('s')


def domove():
movstr = procxy()
doshot(movstr)
dojump(movstr)
while ("r" in movstr):
control.press_key(control.right_key)
movstr = procxy()
doshot(movstr)
dojump(movstr)
control.release_key(control.right_key)
while ("l" in movstr):
control.press_key(control.left_key)
movstr = procxy()
doshot(movstr)
dojump(movstr)
control.release_key(control.left_key)


try:
arduino = serial.Serial('/dev/ttyACM1', 9600)
except:
print ("Failed to connect on /dev/ttyACM0")
while True:
x, y, s, j = getxy()
domove()
print ("X = {0}\nY = {1}".format(x, y))

Arduino C 代码:

int y = 0;
int x = 0;
int fire = 0;
int jump = 0;
void setup(){
Serial.begin(9600);
}

void loop(){
y = analogRead(A0);
x = analogRead(A1);
fire = analogRead(A2);
jump = analogRead(A3);
String out = "";
out.concat(x);
out.concat("_");
out.concat(y);
if(fire > 900)
{
out.concat("_");
out.concat("f");
}
else
{
out.concat("_");
out.concat("t");
}
if (jump > 900)
{
out.concat("_");
out.concat("j");
}
else
{
out.concat("_");
out.concat("k");
}
out.concat("\n");
Serial.print(out);
}

最佳答案

事实证明,该错误是由于电阻不良导致 Arduino 的模拟端口出现轻微过压,从而造成干扰。由于操纵杆是模拟的,因此只有当该特定轴更加活跃时才会发生问题,因此只有当角色向右移动时才会发生该错误的特殊性。

关于python - 使用 Python 作为界面时的奇怪控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32812498/

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