/*
Arduino Forum
Topics: Count if button pressed while LED is on
Category: Using Arduino
Sub-Category: Programming Questions
Link: https://forum.arduino.cc/t/count-if-button-pressed-while-led-is-on/1155397
*/
#define buttonPin A0
#define ledPin 10
#define DEBOUNCE_PERIOD 10
#define OFF_DELAY_MIN 500
#define OFF_DELAY_MAX 2000
#define ON_DELAY_MIN 500
#define ON_DELAY_MAX 2000
uint8_t count;
bool active;
unsigned long timeDelay;
unsigned long startTime;
void setup() {
Serial.begin(115200);
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
randomSeed(A0);
count = 0;
}
void loop() {
Counter(PullupDebounce(buttonPin));
}
bool PullupDebounce(uint8_t pin) {
static bool prevInput;
static bool state;
static unsigned long startDebounceTime;
unsigned long currTime = millis();
bool input = !digitalRead(pin);
if (input != prevInput) {
startDebounceTime = currTime;
}
prevInput = input;
if (input != state) {
if (currTime - startDebounceTime >= DEBOUNCE_PERIOD) {
state = input;
}
}
return state;
}
void Counter(bool press) {
static bool prevPress;
unsigned long currTime = millis();
if (currTime - startTime >= timeDelay) {
Reset(!active, currTime);
}
if (active & press & !prevPress) {
Reset(false, currTime);
count++;
Serial.println(count);
}
prevPress = press;
}
void Reset(bool initial, unsigned long time) {
startTime = time;
active = initial;
timeDelay = active ? random(ON_DELAY_MIN, ON_DELAY_MAX) : random(OFF_DELAY_MIN, OFF_DELAY_MAX);
digitalWrite(ledPin, active);
}