【发布时间】:2015-12-25 01:49:08
【问题描述】:
我将 Python (2.7.9) 实现为带有操纵杆和几个按钮的 Arduino 与我的 Linux 机器之间的接口,以在模拟器上控制 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);
}
【问题讨论】:
-
为什么按钮是analogRead而不是digitalRead?你如何检查你的串行输出?
-
@Ôrel 我正在使用模拟读取,因为我的按钮很奇怪而且会时断时续。在尝试 GetXY 函数的第一行检查串行输出。
-
我的意思是,你如何确定输出是好的,根据我们的代码,你应该在一秒钟内收到几行。你检查每一个收到的行吗?。
-
@Ôrel 我在测试期间打开了一个串行监视器,我可以看到发生了什么。在 Python 代码输入的串行字符串上触发命令的部分没有任何变化,但是无论哪种方式,当我向右(并且仅向右)行走时,我都会像疯了一样开火,这对我来说真的没有意义。
-
您是否尝试过使用 PyKeyboard 编写一个简单的 prog 并在不读取输入的情况下执行多个操作以查看问题出在哪里?
标签: python c interface keyboard arduino