Skip to content

Instantly share code, notes, and snippets.

@qubyte
Last active July 4, 2021 13:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qubyte/6d31ccd49fa88dd664e91293a0eba027 to your computer and use it in GitHub Desktop.
Save qubyte/6d31ccd49fa88dd664e91293a0eba027 to your computer and use it in GitHub Desktop.
Arduino Leonardo code to behave as a keyboard with pins set to MAME-ish key bindings.
#include <Keyboard.h>
// MAMEish. An array of pin-key pairs.
struct { int pin; int key; } pinsToKeys[] = {
{ 2, KEY_LEFT_ARROW },
{ 3, KEY_UP_ARROW },
{ 4, KEY_RIGHT_ARROW },
{ 5, KEY_DOWN_ARROW },
{ 6, KEY_LEFT_CTRL }, // Fire 1
{ 7, KEY_LEFT_ALT }, // Fire 2
{ 8, ' ' }, // Fire 3
{ 9, 'a' }, // Fire 4
{ 10, 's' }, // Fire 5
{ 11, 'q' }, // Fire 6
{ A0, '1' }, // start
{ A1, KEY_ESC } // select
};
void setup() {
// Set all used pins to handle input from
// arcade buttons.
for (auto const &pinToKey : pinsToKeys) {
pinMode(pinToKey.pin, INPUT_PULLUP);
}
// Initialize keyboard.
Keyboard.begin();
}
void loop() {
// For each pin-key pair, check the state
// of the pin and set the associated key
// state to match.
for (auto const &pinToKey : pinsToKeys) {
if (digitalRead(pinToKey.pin) == LOW) {
Keyboard.press(pinToKey.key);
} else {
Keyboard.release(pinToKey.key);
}
}
}
@qubyte
Copy link
Author

qubyte commented Jul 4, 2021

It's been a while since I wrote this, but I don't see anything wrong with your code. The analogue pins of a Leonardo can all be assigned as digital inputs too. I'd be careful of using pin 13 though. It's a little different to the other digital pins (I forget why exactly but I think it's to do with the LED).

You'll need to wire each pin to an arcade switch, and the other pin of each switch to a ground pin on the Leonardo. You can safely wire all the ground pins to a single ground of the arduino.

After programming the Leonardo, you should only need to use a USB lead to plug it into a computer. It should be recognised as a keyboard.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment