Skip to content

Instantly share code, notes, and snippets.

@lee2sman
Last active November 18, 2016 23:24
Show Gist options
  • Save lee2sman/a0dd16e2a8d71643ffc5fb2b5006e5f7 to your computer and use it in GitHub Desktop.
Save lee2sman/a0dd16e2a8d71643ffc5fb2b5006e5f7 to your computer and use it in GitHub Desktop.
for use in GameLab to translate joystick/button presses to keypresses via Arduino Leonardo
// Reads arduino digital pins and maps them to USB Joystick library
// NOTE: This sketch file is for use with Arduino Leonardo and Arduino Micro only.
// MODIFIED by Lee2sman 2016-11-18
// REQUIRES ArduinoJoystickLibrary by Matthew Heironimus
// Download at https://github.com/MHeironimus/ArduinoJoystickLibrary/tree/version-1.0
// This uses the Joystick (not Joystick2 or Joystick3) library. Unzip, drop it in your arduino / libraries folder
// Then flash to your Leonardo or Micro board. Use Enjoy2 (Mac) or Joy2Key (PC) to map it to button presses for a game.
// --------------------------------------------------------------------
#include <Joystick.h>
void setup() {
// Initialize Button Pins
pinMode(9, INPUT_PULLUP); // Button1
pinMode(10, INPUT_PULLUP); // Button2
pinMode(11, INPUT_PULLUP); // Button3
pinMode(6, INPUT_PULLUP); // Button4
pinMode(7, INPUT_PULLUP); // Button5
pinMode(8, INPUT_PULLUP); // Button6
//JOYSTICK
pinMode(3, INPUT_PULLUP); //UP
pinMode(5, INPUT_PULLUP); //LEFT
pinMode(2, INPUT_PULLUP); // DOWN
pinMode(4, INPUT_PULLUP); //RIGHT
// Initialize Joystick Library
Joystick.begin();
Serial.begin(9600);
}
// Constant that maps the phyical pin to the joystick button.
const int pinToButtonMap =9;
// Last state of the button
int lastButtonState[13] = {0,0,0,0,0,0,0,0,0,0,0,0,0};
void loop() {
// Read pin values
for (int index = 0; index < 13; index++)
{
int currentButtonState = !digitalRead(index);
if (currentButtonState != lastButtonState[index])
{
Serial.println("got one");
Joystick.setButton(index, currentButtonState);
lastButtonState[index] = currentButtonState;
}
}
delay(50);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment