// Blink a led 8 times per second for a minute
//
// This sketch bends the rules, by using millis() and 62 and 63 for the blink.
// Blinking 8 times per second would be a interval of 62.5 ms.
//
// The blinking is almost too fast to be visible in Wokwi.
//
const unsigned long onTime = 62;
const unsigned long offTime = 63;
unsigned long previousMillis;
unsigned long interval = offTime; // start with led off
const int ledPin = 13;
int ledState = LOW; // start with low
const int buttonPin = 2;
bool blinkingEnabled = false; // don't blink to start with.
int count;
const int maxCount = 8 * 60; // 8 blinks per second, 60 seconds
void setup()
{
Serial.begin(115200);
Serial.println( "Press the button to start");
pinMode( ledPin, OUTPUT);
pinMode( buttonPin, INPUT_PULLUP);
}
void loop()
{
unsigned long currentMillis = millis();
if( digitalRead( buttonPin) == LOW)
{
blinkingEnabled = true;
count = 0;
}
if( blinkingEnabled)
{
if( currentMillis - previousMillis >= interval)
{
previousMillis += interval; // clock-accurate millis-timer
if( ledState == HIGH) // led was on ?
{
interval = offTime;
ledState = LOW;
if( count >= maxCount) // blinked all the blinks ?
{
blinkingEnabled = false; // turn of this millis-timer
}
}
else // led was off
{
interval = onTime;
ledState = HIGH;
count++; // count the number the led is turned on
}
digitalWrite( LED_BUILTIN, ledState); // set new led state
}
}
}