Skip to content

Instantly share code, notes, and snippets.

@mangtronix
Created January 15, 2019 18:10
Show Gist options
  • Save mangtronix/73fc9d21b99e2f4965035996784a85b5 to your computer and use it in GitHub Desktop.
Save mangtronix/73fc9d21b99e2f4965035996784a85b5 to your computer and use it in GitHub Desktop.
Processing sketch - Demo code to show pressing keys from simulated serial input
// Demo code to show pressing keys from simulated serial input
//
// Click in the window to send some simulated serial data.
// Press the keys on the keyboard to see the output is the same.
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
Robot robot;
void setup() {
size(400, 400);
// Add this to setup
try {
robot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
exit();
}
}
void draw() {}
void mousePressed() {
//Press the space key
// robot.keyPress(KeyEvent.VK_SPACE);
//If we want a delay here, that gets a little bit more complicated...
//robot.keyRelease(KeyEvent.VK_SPACE);
// Demo
println("Sending B");
handleSerialChar('B');
println("");
println("Sending L");
handleSerialChar('L');
println("");
println("Sending R");
handleSerialChar('R');
println("");
}
void keyPressed() {
//Detect space key presses (to show that it works)
if(keyCode == ' ') {
print("Space! - ");
} else if (keyCode == KeyEvent.VK_LEFT) {
print("left - ");
} else if (keyCode == KeyEvent.VK_RIGHT) {
print("right - ");
}
println(keyCode);
}
// Call this with the char from serial readChar
void handleSerialChar(char c) {
if (c == 'B') {
pressShoot();
} else if (c == 'L') {
pressLeft();
} else if (c == 'R') {
pressRight();
}
}
void pressLeft() {
robot.keyPress(KeyEvent.VK_LEFT);
robot.keyRelease(KeyEvent.VK_LEFT);
}
void pressRight() {
robot.keyPress(KeyEvent.VK_RIGHT);
robot.keyRelease(KeyEvent.VK_RIGHT);
}
void pressShoot() {
robot.keyPress(KeyEvent.VK_SPACE);
robot.keyRelease(KeyEvent.VK_SPACE);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment