Search code examples
c++arduinoarduino-idearduino-esp8266arduino-c++

How can Arduino millis() - millis() equal anything other than 0?


So I know millis() returns the time passed since the program started running, right?

Now I've run into a case where millis() is used in a delay like this:

long dly = millis();
while (millis() - dly < 250) {
yield();        // enough time to send response
}

How can the value of millis() - dly be more than 0? If the point is to yield indefinitely, why would someone use a delay like this?


Solution

  • I am no ardunio coder, but having a look at the code:

    long dly = millis();
    while (millis() - dly < 250) {
    yield();        // enough time to send response
    }
    

    At line 1, you define a variable that holds time passed since start then inside the while loop you retrive the current millis() until it is greater than 250ms.

    Example:

    long dly = millis(); => Say millis = 1250,
    inside while loop => millis will update itself until its 1500
    

    Essentially the code waits 250 miliseconds. Every time while loop runs it will return the current millis, your assumption is that it will return the old value.