Search code examples
buttonarduinojoystick

ArdunioJoystickLibrary ButtonState Preference


Hello I am currently using MHeironimus's ArduinoJoystickLibrary, I have a 3 button game pad for which I am having issues with. My button on pin 2 is normally on, how do I reverse this in the code so that the state is normally off.

I really have no clue, I just modified the the keyboard + button joystick code to get it to work properly, I basically just need to be able to control each of the buttons initial state, because sometimes the switches/buttons might be reversed.

At first I thought it could be done with this part:

// Last state of the button
int lastButtonState[3] = {0,0,0};

Where I would just change this {0,0,0} to like this {0,1,0} then my button on pin 3 would be normally on or in HIGH. But nope. Basically I just need to be able to control each of the 3 button states on the fly because I never know how a switch/button is going to react from my huge bucket of switches/buttons.

See code below:

#include <Joystick.h>

Joystick_ Joystick(JOYSTICK_DEFAULT_REPORT_ID,JOYSTICK_TYPE_GAMEPAD,
  3, 0,                  // Button Count, Hat Switch Count
  false, false, false,   // X and Y, but no 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() {
  // Initialize Button Pins
  pinMode(2, INPUT_PULLUP);
  pinMode(3, INPUT_PULLUP);
  pinMode(4, INPUT_PULLUP);

  // Initialize Joystick Library
  Joystick.begin();
}

// Constant that maps the phyical pin to the joystick button.
const int pinToButtonMap = 2;

// Last state of the button
int lastButtonState[3] = {0,0,0};

void loop() {

  // Read pin values
  for (int index = 0; index < 3; index++)
  {
    int currentButtonState = !digitalRead(index + pinToButtonMap);
    if (currentButtonState != lastButtonState[index])
    {
      if (index < 4) {
        Joystick.setButton(index, currentButtonState);
        lastButtonState[index] = currentButtonState;
      } else {
        if (currentButtonState) {
          Joystick.setButton(index, currentButtonState);
          lastButtonState[index] = currentButtonState;
        }
      }
    }
  }

  delay(10);
}

Solution

  • Define which buttons you want flipped:

    bool flipButtons[3] = {false, true, false};
    

    and then use use it to flip it, when you read the button state:

    int currentButtonState = !digitalRead(index + pinToButtonMap) ^ flipButtons[index];