#define BUTTON_PIN 2
#define LED_PIN 4
#define LONG_press_time 2000
//timing
unsigned long lastblink = 0;
const unsigned blinkinterval = 500;
//debounce
unsigned long lastdebounce = 0;
const unsigned long debouncedelay = 50;
int buttonstate = HIGH;
int lastreading = HIGH;
//led
int ledstate = LOW;
//press logics
unsigned long press_start_time = 0;
bool ispressed = false;
bool longpressed = false;
enum SystemState {STATE_BLINKING, STATE_OVERIDE};
SystemState currentstate = STATE_BLINKING;
void setup()
{
pinMode(LED_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP);
}
void loop()
{
int reading = digitalRead(BUTTON_PIN);
unsigned long now = millis();
//debounce
if (reading != lastreading)
{
lastdebounce = now;
}
if ((now - lastdebounce) > debouncedelay)
{
if (buttonstate != reading)
{
buttonstate = reading;
}
}
lastreading = reading;
//press detection
if (buttonstate == LOW && !ispressed)
{
ispressed = true;
press_start_time = now;
longpressed = false;
}
//long pressed detection
if (ispressed && !longpressed)
{
if ((now - press_start_time) > LONG_press_time)
{
longpressed = true;
digitalWrite(LED_PIN, LOW);
currentstate = STATE_OVERIDE;
}
}
//release event
if (buttonstate == HIGH && ispressed )
{
ispressed = false;
//short press detection
if (!longpressed)
{
if (currentstate == STATE_BLINKING)
{
currentstate = STATE_OVERIDE;
}
else
{
currentstate = STATE_BLINKING;
}
}
}
switch (currentstate)
{
case STATE_BLINKING:
if ((now - lastblink) > blinkinterval)
{
lastblink = now;
ledstate = ! ledstate;
digitalWrite(LED_PIN, ledstate);
}
break;
case STATE_OVERIDE:
digitalWrite(LED_PIN, LOW);
break;
}
}