Hello,
take a view to CONSTRAIN instruction inside the Arduino reference.
Try this and ckeck it out for your project:
// BLOCK COMMENT
// https://www.learncpp.com/cpp-tutorial/
// https://forum.arduino.cc/t/counter-with-limits/903228
#define ProjectName "Counter with limits"
// CONSTANT DEFINITION
// you may need to change these constants to your hardware and needs
constexpr byte Input_[] {A0, A1};
constexpr unsigned long ScanButtonTime {20};
// VARIABLE DECLARATION AND DEFINTION
enum {OctavaUp , OctavaDown };
unsigned long currentTime;
struct TIMER {
unsigned long duration;
unsigned long stamp;
};
TIMER scanButton{ScanButtonTime, 0};
struct BUTTON {
int name_;
byte pin;
bool state_;
} buttons[] {
{OctavaUp, Input_[OctavaUp], 0},
{OctavaDown, Input_[OctavaDown], 0},
};
int octavas {3};
// FUNCTIONS
bool checkTimer(TIMER & time_) {
if (currentTime - time_.stamp >= time_.duration ) {
time_.stamp = currentTime;
return true;
} else return false;
}
void setup() {
Serial.begin(9600);
Serial.println(F("."));
Serial.print(F("File : ")), Serial.println(__FILE__);
Serial.print(F("Date : ")), Serial.println(__DATE__);
Serial.print(F("Project: ")), Serial.println(ProjectName);
pinMode (LED_BUILTIN, OUTPUT);
for (auto Input : Input_) pinMode(Input, INPUT_PULLUP);
Serial.println(octavas);
}
void loop () {
currentTime = millis();
digitalWrite(LED_BUILTIN, (currentTime / 500) % 2);
if (currentTime - scanButton.stamp >= scanButton.duration) {
scanButton.stamp = currentTime;
for (auto &button_ : buttons) {
bool stateNew = !digitalRead(button_.pin);
if (button_.state_ != stateNew) {
button_.state_ = stateNew;
if (stateNew) {
switch (button_.name_) {
case OctavaUp:
octavas++;
break;
case OctavaDown:
octavas--;
break;
}
octavas = constrain(octavas, 0, 6);
Serial.println(octavas);
}
}
}
}
}
Have a nice day and enjoy coding.