So here is a demo-code that shows how blinking is done non-blocking.
Non-blocking is a must to keep your code responsive to button-presses.
An Arduino Uno or Arduino Mega has a small LED on the board.
This LED is connected to IO-Pin 13
This demo-code makes this onboard-led blink
// demo-Code non-blocking timing
unsigned long MyBlinkTimer = 0; // Timer-variables MUST be of type unsigned long
const byte OnBoard_LED = 13;
byte ledState = LOW;
void setup() {
Serial.begin(115200);
Serial.println("Setup-Start");
pinMode(OnBoard_LED,OUTPUT);
}
void loop() {
// check if 500 milliseconds have passed by since last time
// function TimePeriodIsOver resulted in "true"
if ( TimePeriodIsOver(MyBlinkTimer,500) ) {
// when REALLY 500 milliseconds have passed by
if (ledState == LOW) {
ledState = HIGH; // change to HIGH
}
else { // ledState is HIGH
ledState = LOW; // change to LOW
}
digitalWrite(OnBoard_LED,ledState);
}
}
// 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
}
Here as a WOWKI-Simulation
If you want to learn more about non-blocking timing
best regards Stefan