// C++ code
//
#define greenLED 8
#define redLED 9
#define yellowLED 10
#define ButtonPin 3
// random set of times
int timesOn[] = {100, 250, 400, 500};
// random set of delays
int delayTimes[] = {250, 500, 1000, 1500};
// we need volatile variables in order to be
// able to be accessed/changed during the ISR
volatile boolean redLEDLit = false;
volatile boolean isWinner = false;
void setup()
{
pinMode(greenLED, OUTPUT);
pinMode(redLED, OUTPUT);
pinMode(yellowLED, OUTPUT);
// creating interrupt
attachInterrupt(0, checkWinner, FALLING);
turnOffLEDs();
Serial.begin(9600);
}
void loop()
{
int LEDtoLight = random(1,4);
int periodLEDisLit = timesOn[random(4)];
lightLED(LEDtoLight, periodLEDisLit);
turnOffLEDs();
int delayTime = delayTimes[random(4)];
delay(delayTime);
if (isWinner) {
isWinner = false;
winner();
}
}
void lightLED(int led, int duration)
{
switch (led) {
case 1: //green
digitalWrite(greenLED, HIGH);
break;
case 2: // red
digitalWrite(redLED, HIGH);
break;
case 3: // yellow
digitalWrite(yellowLED, HIGH);
break;
default:
break;
}
delay(duration);
redLEDLit = false;
}
void turnOffLEDs()
{
digitalWrite(greenLED, LOW);
digitalWrite(redLED, LOW);
digitalWrite(yellowLED, LOW);
}
void winner()
{
for (int i=0; i<3; i++) {
digitalWrite(greenLED, HIGH);
digitalWrite(redLED, HIGH);
digitalWrite(yellowLED, HIGH);
delay(250);
digitalWrite(greenLED, LOW);
digitalWrite(redLED, LOW);
digitalWrite(yellowLED, LOW);
delay(250);
}
delay(3000);
}
// ISR
void checkWinner()
{
if (redLEDLit) {
Serial.println("win");
isWinner = true;
}
}