Last active
January 31, 2018 00:31
-
-
Save oshoham/d60aa7594115b4ba8b722f6d539c183f to your computer and use it in GitHub Desktop.
Lunar Lander Controller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Author: Oren Shoham | |
* Written on 1/30/2018 for Tom Igoe's Tangible Interaction Workshop class at NYU ITP. | |
* | |
* References: | |
* https://github.com/PaulStoffregen/Encoder/blob/master/examples/Basic/Basic.pde | |
* https://www.arduino.cc/en/Tutorial/KeyboardAndMouseControl | |
*/ | |
#include <Encoder.h> | |
#include <Keyboard.h> | |
#include <Mouse.h> | |
const int toggleSwitchPin = 5; | |
const int rotaryEncoderSwitchPin = 6; | |
const long turnTime = 150; | |
Encoder myEnc(2, 3); | |
long oldEncoderPosition = -999; | |
bool thrustEngaged = false; | |
bool turningLeft = false; | |
bool turningRight = false; | |
long startedTurningLeftTime = 0; | |
long startedTurningRightTime = 0; | |
void setup() { | |
pinMode(toggleSwitchPin, INPUT); | |
pinMode(rotaryEncoderSwitchPin, INPUT); | |
Keyboard.begin(); | |
Mouse.begin(); | |
} | |
void loop() { | |
// keyboard up arrow | |
int toggleSwitchValue = digitalRead(toggleSwitchPin); | |
if (toggleSwitchValue == HIGH) { | |
if (!thrustEngaged) { | |
Keyboard.press(KEY_UP_ARROW); | |
thrustEngaged = true; | |
} | |
} else { | |
if (thrustEngaged) { | |
Keyboard.release(KEY_UP_ARROW); | |
thrustEngaged = false; | |
} | |
} | |
// mouse click | |
int rotaryEncoderSwitchValue = digitalRead(rotaryEncoderSwitchPin); | |
if (rotaryEncoderSwitchValue == HIGH) { | |
if (!Mouse.isPressed(MOUSE_LEFT)) { | |
Mouse.press(MOUSE_LEFT); | |
} | |
} else { | |
if (Mouse.isPressed(MOUSE_LEFT)) { | |
Mouse.release(MOUSE_LEFT); | |
} | |
} | |
// keyboard left and right arrows | |
long newEncoderPosition = myEnc.read(); | |
if (newEncoderPosition != oldEncoderPosition) { | |
if (newEncoderPosition > oldEncoderPosition) { | |
if (!turningLeft) { | |
Keyboard.press(KEY_LEFT_ARROW); | |
turningLeft = true; | |
startedTurningLeftTime = millis(); | |
} | |
} else { | |
if (!turningRight) { | |
Keyboard.press(KEY_RIGHT_ARROW); | |
turningRight = true; | |
startedTurningRightTime = millis(); | |
} | |
} | |
oldEncoderPosition = newEncoderPosition; | |
} else { | |
if (turningLeft && millis() - startedTurningLeftTime > turnTime) { | |
Keyboard.release(KEY_LEFT_ARROW); | |
turningLeft = false; | |
} | |
if (turningRight && millis() - startedTurningRightTime > turnTime) { | |
Keyboard.release(KEY_RIGHT_ARROW); | |
turningRight = false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment