/*
Wokwi: https://wokwi.com/projects/359089603316967425
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!
Version: V0.21 - 2023-03-13
ec2021
*/
const byte IN4 = 4;
const byte IN5 = 5;
struct pressButtonType {
byte Pin;
unsigned long lastChange;
byte lastState;
byte state;
boolean pressed();
};
boolean pressButtonType::pressed() {
byte 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;
}
signed long count = 0;
pressButtonType but4 = {IN4, 0, HIGH};
pressButtonType but5 = {IN5, 0, HIGH};
void setup() {
Serial.begin(9600);
Serial.println("Start");
pinMode(IN4, INPUT_PULLUP);
pinMode(IN5, INPUT_PULLUP);
}
boolean LeaveWhileLoop;
void loop() {
if (but4.pressed()) {
LeaveWhileLoop = false;
while (!LeaveWhileLoop)
{
if (but4.pressed()){
count++;
if (but5.pressed()) {
Serial.print("Quick count up\t");
Serial.println(count);
delay(100);
} else {
Serial.print("Slow count up\t");
Serial.println(count);
delay(300);
}
}
LeaveWhileLoop = (!but4.pressed() && !but5.pressed());
}
}
if (but5.pressed()) {
LeaveWhileLoop = false;
while (!LeaveWhileLoop)
{
if (but5.pressed()){
count--;
if (but4.pressed()) {
Serial.print("Quick count down\t");
Serial.println(count);
delay(100);
} else {
Serial.print("Slow count down\t");
Serial.println(count);
delay(300);
}
}
LeaveWhileLoop = (!but4.pressed() && !but5.pressed());
}
}
}