byte buttonPin = 2, relay = 3, ledRED = 4, ledGRN = 5;
unsigned long debounceTimeout = 50; // debounceTimeout
unsigned long timer = 0; // measures button press time
bool currentButtonState; // current button state (pressed/not pressed)
bool lastButtonRead; // previous button reading
byte functionState = 0; // current system state
byte functionTotal = 2; // total system states
void setup() {
Serial.begin(115200);
pinMode(buttonPin, INPUT_PULLUP); // HIGH when not pressed, tied low
pinMode(ledRED, OUTPUT);
pinMode(ledGRN, OUTPUT);
pinMode(relay, OUTPUT);
Serial.print("Function state: ");
function_state_0(); // initial state
}
void loop() {
readButton();
}
void readButton() {
bool currentButtonRead = digitalRead(buttonPin); // read button pin
if (currentButtonRead != lastButtonRead) { // if button pin reading changes...
timer = millis(); // ...start a timer
lastButtonRead = currentButtonRead; // ... and store current state
}
if ((millis() - timer) > debounceTimeout) { // if button read change was longer than debounceTimeout
if (currentButtonState == HIGH && lastButtonRead == LOW) { // ... and State NOT pressed while Button PRESSED
functionState++; // button was pressed, increment state
if (functionState == functionTotal) // check for function rollover
functionState = 0; // reset on function rollover
switch (functionState) { // call the state function
case 0: function_state_0(); break;
case 1: function_state_1(); break;
}
}
currentButtonState = currentButtonRead; // change the state
}
}
void function_state_0() {
Serial.print(functionState);
digitalWrite(ledRED, HIGH);
digitalWrite(ledGRN, LOW);
digitalWrite(relay, LOW);
}
void function_state_1() {
Serial.print(functionState);
digitalWrite(ledRED, LOW);
digitalWrite(ledGRN, HIGH);
digitalWrite(relay, HIGH);
}