#define BUTTON_PIN 2
#define LED_PIN 4
//timing
unsigned long lastblink = 0;
const unsigned long interval = 500;
//debouce
unsigned long lastdebounce = 0;
const unsigned long debouncedelay = 50;
int buttonstate = HIGH;
int lastbuttonstate = HIGH;
//led
int ledstate = LOW;
enum SYSTEMSTATE
{
STATE_BLINKING,
STATE_OVERIDE
};
SYSTEMSTATE currentstate = STATE_BLINKING;
void setup()
{
pinMode(LED_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP);
}
void loop()
{
int now = millis();
//debounce detect
int reading = digitalRead(BUTTON_PIN);
if ( reading != lastbuttonstate)
{
lastdebounce = now;
}
if ((now - lastdebounce) > debouncedelay)
{
if (buttonstate != reading)
{
buttonstate = reading;
}
}
lastbuttonstate = reading;
switch (currentstate)
{
case STATE_BLINKING:
//TIMER EVENT
if ((now - lastblink) > interval)
{
lastblink = now;
ledstate = ! ledstate;
digitalWrite(LED_PIN, ledstate);
}
//press event
if (buttonstate == LOW)
{
digitalWrite(LED_PIN, LOW);
currentstate = STATE_OVERIDE;
}
break;
case STATE_OVERIDE:
//led force off
digitalWrite(LED_PIN, LOW);
//release event
if(buttonstate == HIGH)
{
currentstate = STATE_BLINKING;
}
break;
}
}