/*
Wokwi: https://wokwi.com/projects/359093488403567617
Demo sketch with two buttons (but4 and but5) connected to Arduino MEGA board that
1. starts counting up (slowly) when solely button but4 is pressed
2. starts counting down (slowly) when solely button but5 is pressed
3. starts counting up (quickly) when but5 is pressed while but4 is hold down
4. starts counting up (quickly) when but4 is pressed while but5 is hold down
To achieve slow counting as in no 1. and 2. the respective buttons have to be pressed. The counting
starts immediately
If the second button is pressed, quick counting starts as in no 3. or no. 4.
If in case of no. 3 or 4 the first button is released while the second is still pressed
the counting stops. When the first button is pressed again, the quick counting resumes.
To leave no. 3 or 4 both buttons have to be released first!
This version makes use of a State Machine ...
Version: V0.3 - 2023-03-13
ec2021
*/
const byte IN4 = 4;
const byte IN5 = 5;
const unsigned long shortWaitTime = 100;
const unsigned long longWaitTime = 300;
struct pressButtonType {
byte Pin;
unsigned long lastChange;
int lastState;
int state;
boolean pressed();
};
boolean pressButtonType::pressed() {
int state = digitalRead(pressButtonType::Pin);
if (state != pressButtonType::lastState) {
pressButtonType::lastChange = millis();
pressButtonType::lastState = state;
}
if (state != pressButtonType::state && millis() - pressButtonType::lastChange > 50) {
pressButtonType::state = state;
};
return !pressButtonType::state;
}
enum CountStates {IDLE, COUNTUP, COUNTDOWN};
CountStates actState = IDLE;
CountStates lastState = IDLE;
signed long count = 0;
pressButtonType but4 = {IN4, 0, HIGH};
pressButtonType but5 = {IN5, 0, HIGH};
void StateMachine(){
static unsigned long lastActionTime = 0;
static unsigned long WaitTime = longWaitTime;
switch (actState) {
case IDLE : if (but4.pressed()){
actState = COUNTUP;
}
if (but5.pressed()){
actState = COUNTDOWN;
}
WaitTime = longWaitTime;
break;
case COUNTUP :
if (but5.pressed()) WaitTime = shortWaitTime;
else WaitTime = longWaitTime;
if (but4.pressed() && millis()-lastActionTime >= WaitTime) {
lastActionTime = millis();
count++;
Serial.println(count);
}
if (!but4.pressed() && !but5.pressed()) actState = IDLE;
break;
case COUNTDOWN :
if (but4.pressed()) WaitTime = shortWaitTime;
else WaitTime = longWaitTime;
if (but5.pressed() && millis()-lastActionTime >= WaitTime) {
lastActionTime = millis();
count--;
Serial.println(count);
}
if (!but4.pressed() && !but5.pressed()) actState = IDLE;
break;
default : actState = IDLE;
break;
}
}
void setup() {
Serial.begin(115200);
Serial.println("Start");
pinMode(but4.Pin, INPUT_PULLUP);
pinMode(but5.Pin, INPUT_PULLUP);
actState = IDLE;
}
void loop() {
StateMachine();
}