# Example-code for timing based on millis() easier to understand through the use of example-numbers / avoiding delay()

**URL:** <https://forum.arduino.cc/t/example-code-for-timing-based-on-millis-easier-to-understand-through-the-use-of-example-numbers-avoiding-delay/974017>\
**Category:** Tutorials\
**Created:** [March 27, 2022, 10:51am UTC](https://forum.arduino.cc/t/example-code-for-timing-based-on-millis-easier-to-understand-through-the-use-of-example-numbers-avoiding-delay/974017 "2022-03-27T10:51:40Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![StefanL38](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/stefanl38/32/713548_2.png) [@StefanL38](https://forum.arduino.cc/u/StefanL38)\
**Post date:** [March 27, 2022, 11:23am UTC](https://forum.arduino.cc/t/example-code-for-timing-based-on-millis-easier-to-understand-through-the-use-of-example-numbers-avoiding-delay/974017/3 "2022-03-27T11:23:20Z")

</div>

easier to use non-blocking timing for constantly repeat something after a certain amount of time

```cpp
const int ledPin = LED_BUILTIN; // the number of the LED pin

int ledState = LOW; // ledState used to set the LED

// 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
}

unsigned long MyTestTimer = 0; // Timer-variables MUST be of type unsigned long

unsigned long myInterval = 1000;

void setup() {
  Serial.begin(115200);
  Serial.println("Setup-Start");
  pinMode(ledPin, OUTPUT);
}

// always put code that builds a senseful unit into its own function
void blinkLED() {
    if (ledState == LOW) {
      Serial.println(" ledState is LOW change it to HIGH");
      ledState = HIGH;
    } 
    else {
      Serial.println("ledState is HIGH change it to LOW");
      ledState = LOW;
    }
    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);  
}

void loop() {

  // once every x milliseconds (value stored in variable myInterval) 
  if ( TimePeriodIsOver(MyTestTimer, myInterval) ) {
    // execute code inside this if-condition
    blinkLED(); 
  }
}
```

---

_[View the full topic](https://forum.arduino.cc/t/example-code-for-timing-based-on-millis-easier-to-understand-through-the-use-of-example-numbers-avoiding-delay/974017)._
