Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Lunar Lander Controller
/*
* 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