What can I use to perform a function in the loop if none of the other conditions in the loop and their code have been executed after a certain amount of time? Can it be done with a delay, or is there some other function?
The setTimeout method allows us to run a function once after the interval of the time. Here we have defined a function to log something in the browser console after 2 seconds. const timerId = setTimeout(() => { console. log('Will be called after 2 seconds'); }, 2000);
I don't think it's possible to implement since the Arduino does not have an internal clock.
EDIT : It is possible to use the millis() function to calculate an amount of time since the start of the board:
unsigned long previousMillis = 0; // last time update
long interval = 2000; // interval at which to do something (milliseconds)
void setup(){
}
void loop(){
unsigned long currentMillis = millis();
if(currentMillis - previousMillis > interval) {
previousMillis = currentMillis;
// do something
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With