Custom Game Controller Button Lag - Arduino Pro Micro/Leonardo

Good day everyone! Im very new to Arduino and just got introduced it when I tried building my DIY Steering Wheel.

I came across this free DIY Guide using the Arduino Pro Micro.

All the buttons work, but Im getting really slow response during continuous button inputs, particularly for the paddle shifters.

I'm thinking it is simply bad code?
Would like to ask for help on how I can make button inputs faster.

Also, I think I used an Arduino Leonardo instead of a Pro Micro which this code was designed for. Pro Micro is written on the pcb, but it appears as a Leonardo.

Thanks!

/*

$ lsusb
2341:8037 Arduino SA

idVendor 0x2341 Arduino SA
idProduct 0x8037
iManufacturer 1 Arduino LLC
iProduct 2 Arduino Micro

.build.usb_manufacturer

*/

#include <Joystick.h>
#include "Switch.h"

const uint32_t SAMPLE_TIME_MS = 5;

// Normal buttons
const uint8_t TOTAL_BUTTONS = 14; // 6 left, 6 right, 2 shifter
Switch buttons[TOTAL_BUTTONS];
bool previousButtonState[TOTAL_BUTTONS];
const uint8_t BUTTON_PINS[TOTAL_BUTTONS] = {
2, 3, 4, 5, 6, 7,
21, 20, 19, 18, 15, 14,
8, 16
};

Joystick_ Joystick(
JOYSTICK_DEFAULT_REPORT_ID, JOYSTICK_TYPE_JOYSTICK,
TOTAL_BUTTONS, 0, // Button Count, Hat Switch Count
false, false, false, // no X, Y and Z Axis
false, false, false, // No Rx, Ry, or Rz
false, false, // No rudder or throttle
false, false, false // No accelerator, brake, or steering
);

void setup(void) {
Joystick.begin(false);
// Serial.begin(115200);
for (uint8_t i=0; i < TOTAL_BUTTONS;i++) {
previousButtonState[i] = false;
pinMode(BUTTON_PINS[i], INPUT_PULLUP);
};
// Set shifter GND low
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
digitalWrite(9, LOW);
digitalWrite(10, LOW);
};

void loop(void) {
static uint32_t previousTime = millis();
static uint32_t buttonState = 0;

// Map 14 normal buttons
for (uint8_t i=0; i < TOTAL_BUTTONS; i++) {
buttons[i].update(!digitalRead(BUTTON_PINS[i]));
if (buttons[i].on() != previousButtonState[i]) {
Joystick.setButton(i, buttons[i].on());
}
previousButtonState[i] = buttons[i].on();
// Serial.print(buttons[i].on());
};
// Serial.println();

// Send new state to the host
if (millis() - previousTime > SAMPLE_TIME_MS) {
Joystick.sendState();
previousTime = millis();
};

// delay(SAMPLE_TIME_MS);

};

Try static uint32_t previousTime;

1 Like

Thank you very much for the reply! Just tried this, but unfortunately the lag is still present :frowning:

I could insert some Serial.print telling where in the code the print is done and also millis(), or microseconds. Serial monitor in the Pc...
That way You can see where time us lost/used.