#define ledRed 7
#define ledGrn 8
#define ledBlue 9
#define btn 2
int btnReading = 0 ; // variable used to read the button state
int clicksCounter = 0; // variable used to count the number of clicks on the button
unsigned long start = 0; // variable to be used to make use of millis instead of delay
void setup() {
// put your setup code here, to run once:
pinMode(ledRed, OUTPUT);
pinMode(ledGrn, OUTPUT);
pinMode(ledBlue, OUTPUT);
pinMode(btn, INPUT);
Serial.begin(9600);
}
void blinkingLeds() {
//if the time passed is less than a second
if (millis() - start < 1000) {
digitalWrite(ledRed, HIGH);
digitalWrite(ledBlue, LOW);
}
//if the time passed is more than 1 second and less than 2 seconds
else if (millis() - start < 2 * 1000) {
digitalWrite(ledGrn, HIGH);
digitalWrite(ledRed, LOW);
}
//if the time passed is more than 2 seconds and less than 3 seconds
else if (millis() - start < 3 * 1000) {
digitalWrite(ledBlue, HIGH);
digitalWrite(ledGrn, LOW);
}
// if more than 3 seconds has passed restart the start variable (to start from the first led again)
else {
start = millis();
}
}
void loop() {
//read button state
btnReading = digitalRead(btn);
// a small debounce delay is used for the mechanical issues that comes from clicking the button
delay(50);
// detect if button is pressed
if ( btnReading == 1) {
//increase counter by 1
clicksCounter++;
//stay in a loop until button is released to detect a the release of button press (press and release)
while(digitalRead(btn));
delay(50);
}
//check if couter is odd
if (clicksCounter % 2 != 0) {
Serial.print(" Counter: ");
Serial.print(clicksCounter);
//start blinking
blinkingLeds();
}
else {
// if counter is even, turn off all leds
digitalWrite(ledRed, LOW);
digitalWrite(ledGrn, LOW);
digitalWrite(ledBlue, LOW);
}
}