For some reason this code (which is probably messy as I am using it to learn) does not act in the way I would expect. The goal is to have a joystick button that when pressed sends a pulse on and off continuously. Effectively making a single press of the button into a rapid fire of sorts.
I know how to make it send a pulse and the code below works... BUT it doesn't press the SAME button each time. It presses button 1, then a second later button 2 and so on. I need it to press the same button each time though. I believe it's a problem with the digitalwrite line using index. Can anyone explain how to fix this issue?
#include <Joystick.h>
Joystick_ Joystick;
void setup() {
// Initialize Button Pins
pinMode(3, INPUT_PULLUP);
pinMode(4, INPUT_PULLUP);
pinMode(5, INPUT_PULLUP);
pinMode(6, INPUT_PULLUP);
pinMode(7, INPUT_PULLUP);
pinMode(8, INPUT_PULLUP);
pinMode(9, INPUT_PULLUP);
pinMode(10, INPUT_PULLUP);
pinMode(11, INPUT_PULLUP);
pinMode(12, INPUT_PULLUP);
pinMode(13, INPUT_PULLUP);
// Initialize Joystick Library
Joystick.begin();
}
// Constant that maps the physical pin to the joystick button.
const int pinToButtonMap = 3;
// Last state of the button
int buttonState = HIGH ;
int lastButtonState = LOW ;
int index = 0 ;
int buttonPushCounter = 0 ;
void loop() {
// Read pin values
for (int index = 0; index < 13; index++)
{
if (buttonState != lastButtonState) {
// if the state has changed, increment the counter
if (buttonState == HIGH) {
// if the current state is HIGH then the button went from off to on:
buttonPushCounter++;
delay(1000);
digitalWrite(index, LOW); // unpress button by making the voltage LOW
delay(1000);
buttonPushCounter++;
Joystick.setButton(index, !digitalRead(index + pinToButtonMap));
} else {
if (buttonState == LOW) {
// if the current state is LOW then the button went from on to off:
//YYYYYYYYYYYYYYY turn light on here
buttonPushCounter++;
} } } }
}