< return

PiBoy Build Log - Part 1 - DIY Keyboard with Arduino Leonardo Pro Micro

Quick post just for notekeeping mostly, I'm making a PiBoy (who isn't?) and wanted to make a super easy keyboard based input for the gamepad. I bought £5 pro micro and slapped some tactile switches on.

First working version:

Wiring is basic, tactile switch wired one side to ground and one side to pin 2, which is set to UP in this case. Plan is to map out all basic RetroPi inputs in this method.

Running the following code, which has been only slightly modified to default to HIGH and wait for LOW:

#include <Keyboard.h>
// Number of buttons to handle
const int buttonsCount = 4;

// Arduino PINs to use
const int pins[buttonsCount] = {
    2,
    3,
    4,
    5
};

// Keys to send (order has to match the pins array)
const byte keys[buttonsCount] = {
    KEY_UP_ARROW,
    KEY_DOWN_ARROW,
    KEY_LEFT_ARROW,
    KEY_RIGHT_ARROW
};

// Debounce delay
const long debounceDelay = 50;

bool status[buttonsCount] = {LOW};
long lastDebounces[buttonsCount] = {0};

void setup() {
    for (int i = 0; i < buttonsCount; ++i) {
        pinMode(pins[i], INPUT);
        digitalWrite(pins[i], HIGH);
    }

    Keyboard.begin();
}

void loop() {
    for (int i = 0; i < buttonsCount; ++i) {
        const int pinStatus = digitalRead(pins[i]);
        if (pinStatus != status[i] && millis() - debounceDelay > lastDebounces[i]) {
            status[i] = pinStatus;
            if (pinStatus == LOW) {
                Keyboard.press(keys[i]);
            } else {
                Keyboard.release(keys[i]);
            }
            lastDebounces[i] = millis();
        }
    }
}

code credit: https://github.com/Kernald/gameduino

login