Go Down

Topic: Project 08 - Question about the variable "currentTime" (Read 1 time) previous topic - next topic

ShannonC

There is a local variable created in the loop ( ) body named currentTime and is used to hold the current time since the Arduino first loaded up.

It is defined like this:

void loop ( ) {
     unsigned long currentTime = millis ( );
     â€¦
}


My question is if the body of the loop gets repeated, why isn't a new local variable created each time? Does the Arduino's IDE or the PC check if there are variables previously created in the last run of loop and if it finds one it doesn't create a new one?

Just had me thinking…

Thanks!

Peter_n

The loop() function is completely finished and started again.
That means that the variable is created every time.

However, you don't have to worry about "creating" a variable, it is simpler than that.
The unsigned long are 4 bytes and are filled with value of millis(). The millis() function is the function that returns the time since startup. Those 4 bytes could be kept in registers, or with 4 bytes on the stack.

So the millis() function is called, and the 4 bytes are kept in registers or in a location on the stack. That's all, there is nothing more to it.

KenF

Although the variable is created every time the loop runs, it is also destroyed as the loop ends (every time).  So it's not an issue.

ShannonC


Go Up