我正在实现Python(2.7.9)作为我的Arduino与操纵杆和几个按钮之间的接口以及我的Linux机器来控制模拟器上的Megaman。操纵杆执行x / y移动,按钮可以触发和跳跃。我的代码接收格式为(X_Y_FIRE_JUMP)的字符串,并解析出值,然后使用PyUserInput库查看它应该在键盘上输入的内容。
虽然发生了一个奇怪的错误:每当我向右移动时,即使没有按任何一个按钮,Megaman也会疯狂地开火。我已经检查了我的串行输出,看看它是否是硬件侧面的,但事实并非如此;收到的串行字符串是干净的,因为它应该看起来像这样的“[X> 510] _ [Y~510] _k_t”。因此,X告诉它向右移动,Y并没有真正做任何事情,k告诉它不要跳跃 告诉它不要开火。当我向右移动时,为什么我仍然会粗略地意外触发 ?
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);
}
答案 0 :(得分:0)
事实证明,错误是由于电阻不良导致Arduino在其模拟端口上产生轻微的过电压,从而造成干扰。由于操纵杆是模拟的,因此只有在特定轴更活跃时才会发生问题,因此只有当角色向右移动时才会发生错误的特殊性。