This is the code I used in Drake Startup Box Youtube video
#include <Joystick.h>
Joystick_ Joystick(JOYSTICK_DEFAULT_REPORT_ID,JOYSTICK_TYPE_GAMEPAD,
3, 0, // Button Count, Hat Switch Count
false, false, false, // No Axis
false, false, false, // No Rx, Ry, or Rz
false, false, // No rudder or throttle
false, false, false); // No accelerator, brake, or steering
int buttonVal = 0; // This is the current value of the push button
int lastButtonVal = 0; // This is the previous value of the push button
int randomDrake = 0; // Random value to decide what actually happens
int buttonPin = 2; // Define here the PIN where the button is connected on your Arduino
void setup() {
pinMode(buttonPin, INPUT_PULLUP); // Initializes the right PIN to act as input using pullup resistor => button pressed is 0 and relesed is 1.
Joystick.begin(); // Starts the joystick library
}
void loop() {
buttonVal = !digitalRead(buttonPin); // Reads if the button is pressed and switches it around for the variable => if button is pressed, variable will be 1. This is required because the pullup resistor is used.
// This will run if there is a change in button's state, aka it's pressed or depressed. If the button's state doesn't change, no change is communicated to PC.
if ((buttonVal != lastButtonVal) && (lastButtonVal == 0)) { // This one is when button is not pressed previously and is now pressed.
randomDrake = random(10); // Random value and write it to the variable randomDrake
randomizerDrake(); // Starts funcion
} else if ((buttonVal != lastButtonVal) && (lastButtonVal == 1)) { // This one is when button is pressed previously and is now released.
randomizerDrake(); // Starts funcion but doesn't create new random value before it, making sure the right button is depressed.
}
delay(10); // Wait 10 milliseconds
}
// This function will send a button press or release to computer, depending on randomDrake variable's value
void randomizerDrake() {
if (randomDrake < 6) {
Joystick.setButton(0,buttonVal); // Press or depress button 1, first value inside brackets is the button number, second value is the state to be sent to computer 0 = not pressed, 1 = pressed
} else if ((randomDrake >= 6) && (randomDrake <= 8)) {
Joystick.setButton(1,buttonVal); // Press or depress button 2
} else if (randomDrake == 9) {
Joystick.setButton(2,buttonVal); // Press or depress button 3
}
lastButtonVal = buttonVal; // This will change the previous button value to make sure the if loop doesn't run if there isn't a change in the physical button's state
}