Skip to content

Instantly share code, notes, and snippets.

@oveddan
Created January 31, 2018 08:41
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save oveddan/402a7e1302462fcc150cbba4d005fa81 to your computer and use it in GitHub Desktop.
Lunar Lander Game Controller Code
#include <Keyboard.h>
#include <Mouse.h>
const int Y_PIN = A0;
const int LEFT_PIN = 2;
const int RIGHT_PIN = 3;
const int START_PIN = 6;
void setup() {
// put your setup code here, to run once:
//pinMode(Y_PIN, INPUT);
pinMode(START_PIN, INPUT);
pinMode(LEFT_PIN, INPUT);
pinMode(RIGHT_PIN, INPUT);
Serial.begin(9600);
Mouse.begin();
Keyboard.begin();
}
int yNeutral = 0;
const int Y_MIN = 20;
int thrustJoystickValue() {
return analogRead(Y_PIN);
}
bool leftButtonPressed() {
return digitalRead(LEFT_PIN) == 1;
}
bool rightButtonPressed() {
return digitalRead(RIGHT_PIN) == 1;
}
bool startButtonPressed() {
return digitalRead(START_PIN) == 1;
}
bool thrustJoystickAboveZero() {
//Serial.print(thrustJoystickValue(), yNeutral);
return thrustJoystickValue() < yNeutral - 100;
}
bool upKeyPressed = false;
void ensureUpKeyPressed() {
if (!upKeyPressed) {
Keyboard.press(KEY_UP_ARROW);
upKeyPressed = true;
}
}
void ensureUpKeyReleased() {
Keyboard.release(KEY_UP_ARROW);
upKeyPressed = false;
}
const int THRUST_PERIOD = 100;
long start = millis();
// simulates pulse width modulation to determine if thrust button should be pressed
bool thrustPulseOn() {
int yRange = yNeutral - 100 - Y_MIN;
float thrustPercentage = 1. - max((thrustJoystickValue() - Y_MIN) / float(yRange), 0);
float percentInThrustPeriod = (millis() - start) % THRUST_PERIOD / float(THRUST_PERIOD);
return thrustPercentage >= percentInThrustPeriod;
}
bool pulsingThrust = false;
bool leftKeyPressed = false;
bool rightKeyPressed = false;
void loop() {
if (startButtonPressed()) {
yNeutral = thrustJoystickValue();
Mouse.click();
Mouse.release();
}
if (thrustJoystickAboveZero() && thrustPulseOn()) {
ensureUpKeyPressed();
} else {
ensureUpKeyReleased();
}
if (leftButtonPressed() && !leftKeyPressed) {
leftKeyPressed = true;
Keyboard.press(KEY_LEFT_ARROW);
} else if (!leftButtonPressed() && leftKeyPressed) {
leftKeyPressed = false;
Keyboard.release(KEY_LEFT_ARROW);
}
if (rightButtonPressed() && !rightKeyPressed) {
rightKeyPressed = true;
Keyboard.press(KEY_RIGHT_ARROW);
} else if (!rightButtonPressed() && rightKeyPressed) {
rightKeyPressed = false;
Keyboard.release(KEY_RIGHT_ARROW);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment