Skip to content
3way_button.ino 2.09 KiB
Newer Older
//include the third party library to manage HID
#include "HID-Project.h"

//declare understandable var to recognise button in the code,
//the values are the pin number of the Arduino on which the 2 sides of the 3 way buttons are plugged in
const int Button1 = 4;
const int Button2 = 7;

//manage the last button status
int lastButtonStatus[32];

void setup() {
  //define the pin 4 and 7 as inputs
  pinMode(Button1, INPUT_PULLUP);
  pinMode(Button2, INPUT_PULLUP);

  //initialise the last status for 32 possible button (no use for now but will be usefull later
  // in the final button box code
  for (int i = 0 ; i < 31 ; i++)
  {
    lastButtonStatus[i] = HIGH;
  }

  //initialise the gamepad
  Gamepad.begin();
}


//function that will be executed again and again and again...
void loop() {
  //to keep the loop clean and understandable
  //Button management externalised to another function
  ButtonCheck(Button1, 1);
  ButtonCheck(Button2, 2);
}


// function that check the button state
// the parameters are
// inputNB => the pin nb of the button of the push button
// gamepadButtonNb => which gamepad number will be pressed when the push button is pressed
void ButtonCheck(int inputNb, int gamepadButtonNb) {
  //we check and store the button status
  int ButtonVal = digitalRead(inputNb);

  // if the button state have changed, it means the user pressed or released the physical button
  if (ButtonVal != lastButtonStatus[inputNb]) {

    // if the status is LOW, it means the user pressed the physical push button
    // remember, the INPUT_PULLUP invert the value
    if (ButtonVal == LOW) {
      //don't forget to update the last status of the button
      lastButtonStatus[inputNb] = LOW;

      //and then we "press" the gamepad button
      Gamepad.press(gamepadButtonNb);
      Gamepad.write();
    }
    else { // if the input is HIGH, it means the user released the physical push button
      //don't forget to update the last status of the button
      lastButtonStatus[inputNb] = HIGH;

      //and then we "release" the gamepad button
      Gamepad.release(gamepadButtonNb);
      Gamepad.write();
    }
  }
}