Skip to content

Instantly share code, notes, and snippets.

@joegaffey
Created August 11, 2018 20:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joegaffey/39d116885e449d0b24ce3adfc5e1f06c to your computer and use it in GitHub Desktop.
Save joegaffey/39d116885e449d0b24ce3adfc5e1f06c to your computer and use it in GitHub Desktop.
// Simple gamepad example that demonstraits how to read five Arduino
// digital pins and map them to the Arduino Joystick library.
//
// The digital pins are grounded when they are pressed.
//
// NOTE: This sketch file is for use with Arduino Leonardo and
// Arduino Micro only.
//
// Modified version of original code by Matthew Heironimus
// 2018-08-11
//--------------------------------------------------------------------
#include <Joystick.h>
Joystick_ Joystick;
void setup() {
// Initialize Button Pins
pinMode(2, INPUT_PULLUP);
pinMode(3, INPUT_PULLUP);
pinMode(4, INPUT_PULLUP);
pinMode(5, INPUT_PULLUP);
pinMode(6, INPUT_PULLUP);
pinMode(7, INPUT_PULLUP);
pinMode(8, INPUT_PULLUP);
pinMode(9, INPUT_PULLUP);
pinMode(10, INPUT_PULLUP);
pinMode(16, INPUT_PULLUP);
pinMode(20, INPUT_PULLUP);
pinMode(21, INPUT_PULLUP);
// Initialize Joystick Library
Joystick.begin();
Joystick.setXAxisRange(-1, 1);
Joystick.setYAxisRange(-1, 1);
}
// Last state of the buttons
int lastButtonState[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int pins[12] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 20, 21};
void loop() {
// Read pin values
for (int index = 0; index < 12; index++)
{
int currentButtonState = !digitalRead(pins[index]);
if (currentButtonState != lastButtonState[index])
{
switch (pins[index]) {
case 2: // UP
if (currentButtonState == 1) {
Joystick.setYAxis(-1);
} else {
Joystick.setYAxis(0);
}
break;
case 3: // RIGHT
if (currentButtonState == 1) {
Joystick.setXAxis(1);
} else {
Joystick.setXAxis(0);
}
break;
case 4: // DOWN
if (currentButtonState == 1) {
Joystick.setYAxis(1);
} else {
Joystick.setYAxis(0);
}
break;
case 5: // LEFT
if (currentButtonState == 1) {
Joystick.setXAxis(-1);
} else {
Joystick.setXAxis(0);
}
break;
case 6:
Joystick.setButton(0, currentButtonState);
break;
case 7:
Joystick.setButton(1, currentButtonState);
break;
case 8:
Joystick.setButton(2, currentButtonState);
break;
case 9:
Joystick.setButton(3, currentButtonState);
break;
case 10:
Joystick.setButton(4, currentButtonState);
break;
case 16:
Joystick.setButton(5, currentButtonState);
break;
case 20:
Joystick.setButton(8, currentButtonState);
break;
case 21: {
Joystick.setButton(9, currentButtonState);
break;
}
}
lastButtonState[index] = currentButtonState;
}
}
delay(10);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment