Skip to content

Instantly share code, notes, and snippets.

@Flowdeeps
Created April 12, 2019 23:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Flowdeeps/e072cf5dfd1473139d85a0c63cfd0bb0 to your computer and use it in GitHub Desktop.
Save Flowdeeps/e072cf5dfd1473139d85a0c63cfd0bb0 to your computer and use it in GitHub Desktop.
// Update this to reflect the amount of LEDs and buttons you want to control
const int LEDCount = 3;
// This array is for tracking all of the values for each LED and button pair
// The first value is the LED pin
// The second value is the button pin
// The third value is the "last button state" which is set LOW by default in setup
// but is also set here as to echo that default state
// The fourth value is "current button state" also set low by default in this array's objects
// Finally the last value represent the millis() at the time the button was pressed so that
// the debounce timer can be calculated per button
// You will need to add an object per pair {LED, BUTTON, BUTTON_LAST_STATE, BUTTON_CURRENT_STATE, LED_STATE, MILLIS_WHEN_BUTTON_WAS_PRESSED}
int pinsAndButts[LEDCount][6] = {
{12, 9, LOW, LOW, LOW, 0},
{11, 8, LOW, LOW, LOW, 0},
{10, 7, LOW, LOW, LOW, 0}
};
// Debounce timer value
unsigned long debounceDelay = 50;
void setup() {
// this setup loop is for setting the initial state of all the buttons and LEDs
for (int ledPinPair = 0; ledPinPair < LEDCount; ledPinPair++) {
int LEDPin = pinsAndButts[ledPinPair][0];
int buttonPin = pinsAndButts[ledPinPair][1];
pinMode(LEDPin, OUTPUT);
pinMode(buttonPin, INPUT);
digitalWrite(LEDPin, LOW);
digitalWrite(buttonPin, LOW);
}
}
void loop() {
for (int readingPin = 0; readingPin < LEDCount; readingPin++){
int LEDPin = pinsAndButts[readingPin][0];
int buttonPin = pinsAndButts[readingPin][1];
int readingPinVal = digitalRead(buttonPin);
int buttLastState = pinsAndButts[readingPin][2];
pinsAndButts[readingPin][3] = readingPinVal;
int buttCurrState = readingPinVal;
int LEDState = pinsAndButts[readingPin][4];
unsigned long lastDebounceTime = pinsAndButts[readingPin][5];
if (readingPinVal != buttLastState) {
pinsAndButts[readingPin][5] = millis();
};
if ((millis() - lastDebounceTime) > debounceDelay) {
if (readingPinVal != buttLastState) {
pinsAndButts[readingPin][2] = readingPinVal;
if (buttLastState == HIGH) {
pinsAndButts[readingPin][4] = !pinsAndButts[readingPin][4];
}
}
}
pinsAndButts[readingPin][2] = buttCurrState;
digitalWrite(LEDPin, LEDState);
}
delay(10);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment