const int ledPin = 8;
const int button1 = 5;
int ledState = LOW;
const unsigned long interval = 1000;
unsigned long myBlinkTimer;
int NoOfBlinks = 0;
void setup() {
Serial.begin(115200);
Serial.println("Setup-Start");
Serial.println("press button to start blinking");
pinMode(ledPin, OUTPUT);
pinMode(button1, INPUT_PULLUP);
}
void loop() {
if (NoOfBlinks == 0) { // if no blinking is active variable "NoOfBlinks" contains value 0
if (digitalRead(button1) == LOW) {
Serial.println("Button pressed start blinking");
myBlinkTimer = millis();
NoOfBlinks = 1; // assign value 0 to indicate blinking shall start
}
}
// check if blinking shall be active
if (NoOfBlinks > 0 ) {
// check if it is time to change LED-state
if ( TimePeriodIsOver(myBlinkTimer, interval) ) {
Serial.print("NoOfBlinks:");
Serial.print(NoOfBlinks);
// if the LED is off turn it on and vice-versa:
if (ledState == LOW) {
Serial.println(" LED off switching on");
ledState = HIGH;
}
else {
ledState = LOW;
Serial.println(" LED on switching off");
NoOfBlinks++; // if blink has finished by switching off increment by 1
}
digitalWrite(ledPin, ledState);
}
if (NoOfBlinks > 5) {
Serial.print("NoOfBlinks:");
Serial.print(NoOfBlinks);
Serial.println(" => stop blinking");
Serial.println("press button to start blinking new");
digitalWrite(ledPin, LOW);
NoOfBlinks = 0; // assign value 0 to stop the blinking
}
}
}
// easy to use helper-function for non-blocking timing
boolean TimePeriodIsOver (unsigned long &startOfPeriod, unsigned long TimePeriod) {
unsigned long currentMillis = millis();
if ( currentMillis - startOfPeriod >= TimePeriod ) {
// more time than TimePeriod has elapsed since last time if-condition was true
startOfPeriod = currentMillis; // a new period starts right here so set new starttime
return true;
}
else return false; // actual TimePeriod is NOT yet over
}