Processing to Arduino with Keyboard
我决定构建一个远程呈现机器人,它可以通过键盘(使用 WASD)通过串口进行控制。我一直在等待我的零件到货,所以我开始做一些处理测试并使用 WASD 键点亮 LED。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | import processing.serial.*; import cc.arduino.*; Serial myPort; Arduino arduino; void setup () { println(Arduino.list()); arduino = new Arduino(this, Arduino.list() [1], 57600); arduino.pinMode(12, Arduino.OUTPUT); arduino.pinMode(11, Arduino.OUTPUT); arduino.pinMode(9, Arduino.OUTPUT); arduino.pinMode(10, Arduino.OUTPUT); } void draw() { if (keyPressed == true) { if (key == 'w' || key == 'W') { arduino.digitalWrite (12, Arduino.HIGH); } if (key == 's' || key == 'S') { arduino.digitalWrite (11, Arduino.HIGH); } if (key == 'a' || key == 'A') { arduino.digitalWrite (9, Arduino.HIGH); } if (key == 'd' || key == 'D') { arduino.digitalWrite (10, Arduino.HIGH); } else { arduino.digitalWrite (12, Arduino.LOW); arduino.digitalWrite (11, Arduino.LOW); arduino.digitalWrite (9, Arduino.LOW); arduino.digitalWrite (10, Arduino.LOW); } } } |
除了按\\'D\\'键外,一切正常。每当我按下它(或最后一个 if 中使用的任何其他字母)时,LED 都会亮起,但在我松开按键时不会熄灭。我试过改变 LED 引脚,"if"语句的顺序,但最后一个总是有同样的问题。 Arduino 正在运行 StandardFirmata 草图。我使用的是 Arduino Uno、Win 7 x64 和 Processing 1.5.1,因为 2.0.2 给了我一个错误。任何帮助都会很棒。
谢谢
您的"else"语句似乎位于错误的"if"块下。根据您的目标,您应该拥有它,以便如果未按下某个键,您正在将 Arduino.LOW 写入引脚 9-12。基本上,只需移动一个括号:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | void draw() { if (keyPressed == true) { if (key == 'w' || key == 'W') { arduino.digitalWrite (12, Arduino.HIGH); } if (key == 's' || key == 'S') { arduino.digitalWrite (11, Arduino.HIGH); } if (key == 'a' || key == 'A') { arduino.digitalWrite (9, Arduino.HIGH); } if (key == 'd' || key == 'D') { arduino.digitalWrite (10, Arduino.HIGH); } } else { arduino.digitalWrite (12, Arduino.LOW); arduino.digitalWrite (11, Arduino.LOW); arduino.digitalWrite (9, Arduino.LOW); arduino.digitalWrite (10, Arduino.LOW); } } |