easier to use non-blocking timing for constantly repeat something after a certain amount of time
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();
}
}