const int buzzerPin = 2;
const int redLedPins[4] = {8, 9, 10, 11};
const int greenLedPins[4] = {4, 5, 6, 7};
const int buttonPin = 12;
#define RED_ON for( auto pin:redLedPins) digitalWrite(pin, HIGH)
#define RED_OFF for( auto pin:redLedPins) digitalWrite(pin, LOW)
#define GREEN_ON for( auto pin:greenLedPins) digitalWrite(pin, HIGH)
#define GREEN_OFF for( auto pin:greenLedPins) digitalWrite(pin, LOW)
bool triggered = false;
unsigned long previousMillisDuration;
const unsigned long duration = 2000; // duration of blinking leds and buzzer
unsigned long previousMillisBlink;
const unsigned long blinkTime = 500; // blinktime for blinking leds
int count;
int lastButtonState;
void setup()
{
Serial.begin(9600);
Serial.println( "Led flasher");
Serial.println( "-----------");
pinMode( buzzerPin, OUTPUT);
for( auto pin:redLedPins)
pinMode( pin, OUTPUT);
for( auto pin:greenLedPins)
pinMode( pin, OUTPUT);
pinMode( buttonPin, INPUT);
// --------------------------------------------------
// STARTUP ROUTINE - All LED's FLASH TWICE
// --------------------------------------------------
for( int i=0; i<2; i++)
{
RED_ON;
GREEN_ON;
delay(500);
RED_OFF;
GREEN_OFF;
delay(500);
}
}
void loop()
{
unsigned long currentMillis = millis();
// --------------------------------------------------
// State Change Detection for trigger input
// --------------------------------------------------
int buttonState = digitalRead( buttonPin);
if( buttonState != lastButtonState)
{
if( buttonState == HIGH) // triggered ?
{
Serial.println( "Trigger");
previousMillisDuration = currentMillis;
triggered = true;
tone( 2, 500);
}
lastButtonState = buttonState;
}
// --------------------------------------------------
// millis-timer
// --------------------------------------------------
if( triggered)
{
if( currentMillis - previousMillisBlink >= blinkTime)
{
previousMillisBlink = currentMillis;
switch( count)
{
case 0:
GREEN_ON;
break;
case 1:
GREEN_OFF;
break;
case 2:
RED_ON;
break;
case 3:
RED_OFF;
break;
}
count++;
if( count >= 4)
count = 0;
}
if( currentMillis - previousMillisDuration >= duration)
{
noTone( 2);
GREEN_OFF;
RED_OFF;
triggered = false;
Serial.println( "Waiting ...");
}
}
}