/*
Arduino Forum
Topics: Sharing Switch Control Code
Category: Using Arduino
Sub-Category: Programming Questions
Link: https://forum.arduino.cc/t/sharing-switch-control-code/1159151/5
*/
#define DEBOUNCE_PERIOD 10 // 10 milliseconds
#define buttonPin 2
#define togglePin 5
#define statePin 13
bool buttonState;
bool toggle;
bool InstantDebounce();
void setup() {
Serial.begin(115200);
pinMode(buttonPin, INPUT_PULLUP);
pinMode(statePin, OUTPUT);
pinMode(togglePin, OUTPUT);
buttonState = HIGH;
toggle = HIGH;
}
void loop() {
if (InstantDebounce()) toggle = !toggle;
digitalWrite(statePin, buttonState);
digitalWrite(togglePin, toggle);
}
bool InstantDebounce() {
static bool input;
static bool debouncing;
static unsigned long startDebounceTime;
bool prevInput = input;
input = digitalRead(buttonPin);
if (input != prevInput) {
startDebounceTime = millis();
}
if (debouncing) {
if (millis() - startDebounceTime >= DEBOUNCE_PERIOD) {
debouncing = false;
}
} else {
if (input != buttonState) {
buttonState = input;
debouncing = true;
return buttonState == LOW; // When pressed, state = LOW if pin mode = INPUT_PULLUP, and state = HIGH if pin mode = INPUT.
}
}
return LOW;
}STATE
TOGGLE
BUTTON DEBOUNCEWITH INSTANT MODE