Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
GameBoy mod input for Teensy 3.1
// Set Board type to "Teensy 3.1"
// Set USB type to "Keyboard + Mouse + Joystick"
#define JOY_MIN 0
#define JOY_DEF 512
#define JOY_MAX 1023
#define JOY_INDEX_LEFT 0
#define JOY_INDEX_UP 1
#define JOY_INDEX_RIGHT 2
#define JOY_INDEX_DOWN 3
#define HOLD_KEY_MENU KEY_F1
#define HOLD_KEY_EXIT KEY_ESC
#define MASK_MENU_PIN_STATE B11000000
#define MASK_EXIT_PIN_STATE B11110000
#define HOLD_MILLIS_MENU 2000
#define HOLD_MILLIS_EXIT 2000
#define HOLD_MILLIS_AUTORELEASE 2500
const int pins[] = { 0,1,3,5,7,9,10,12,-1 }; // must terminate with -1
unsigned long hold_started;
unsigned char hold_processed;
void setup() {
hold_started = 0;
hold_processed = 0;
for (int i = 0; pins[i] != -1; i++) {
if (pins[i] != -1) {
pinMode(pins[i], INPUT_PULLUP);
}
}
Joystick.useManualSend(true);
}
void loop() {
Joystick.X(JOY_DEF);
Joystick.Y(JOY_DEF);
unsigned int pinState = 0;
for (int i = 0; pins[i] != -1; i++) {
unsigned char pressed = !digitalRead(pins[i]);
pinState |= (pressed << i);
if (i < 4) {
if (i == JOY_INDEX_LEFT && pressed) {
Joystick.X(JOY_MIN);
} else if (i == JOY_INDEX_UP && pressed) {
Joystick.Y(JOY_MIN);
}
if (i == JOY_INDEX_RIGHT && pressed) {
Joystick.X(JOY_MAX);
} else if (i == JOY_INDEX_DOWN && pressed) {
Joystick.Y(JOY_MAX);
}
} else {
Joystick.button(i - 3, pressed);
}
}
if ((pinState & MASK_EXIT_PIN_STATE) == MASK_EXIT_PIN_STATE) {
if (hold_started) {
if (millis() - hold_started > HOLD_MILLIS_EXIT && !hold_processed) {
Keyboard.press(HOLD_KEY_EXIT);
hold_processed = 1;
}
} else {
hold_processed = 0;
hold_started = millis();
}
} else if ((pinState & MASK_MENU_PIN_STATE) == MASK_MENU_PIN_STATE) {
if (hold_started) {
if (millis() - hold_started > HOLD_MILLIS_MENU && !hold_processed) {
Keyboard.press(HOLD_KEY_MENU);
hold_processed = 1;
}
} else {
hold_processed = 0;
hold_started = millis();
}
} else if (hold_started) {
Keyboard.releaseAll();
hold_started = 0;
hold_processed = 0;
}
if (!hold_processed) {
Joystick.send_now();
} else if (millis() - hold_started > HOLD_MILLIS_AUTORELEASE) {
Keyboard.releaseAll();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment