Skip to main content

Reply to "Arduino Uno Question"

Anytime you define a variable inside a function, it is temporary. It disappears when the function is completed. This is called going out of scope. The "now" variable does not remain valid after the "loop" returns (by falling off the end of the curly bracket). It's value is lost. But that's what you want. You don't need that value to remain after it has been evaluated.

The "startTime" however, because it is declared outside of the "loop" function remains valid between executions. Thus, when the "loop" function is executed again, the "startTime" value is still available and valid.

When a variable is declared outside of any function, it's scope is global. That means that it can be accessed by any function in your program. But the use of global variables is discouraged for the same reason. Because it can be modified by any part of your program, it becomes difficult to keep track of where these modifications take place. It is better to use "globals" sparingly and only for limited specific purposes.

In order to keep this explanation simple, I lied about the scope of the "now" variable. It does not remain valid throughout the "loop" function. For that to be true, you would need to declare "now" at the beginning of the function like this:

...
void loop () {
  unsigned long now;
...

The way I did it in the example, it has scope (is valid) only within the current block of code. Since it isn't used anywhere else, that's OK. I don't recall the exact rules on scope but that value generally goes out of scope at the next closing curly bracket -- "}". If you try to use it anywhere else, the compiler will just shake its head. 

Note also that the "now" variable is not really necessary. I used it just to illustrate and to name what that value represents. The code could have been written this way just as well:

...
if (millis() - startTime >= 5000) {
...

There are lots of ways to write a program. Just use what you know and move on. There are constructs in the C++ language that I never use at all. Keep it simple and understandable for the next guy that has to trudge through your horrible code. Programmers expect to make mistakes all the time. It goes with the territory.

For more information on scope, see this section of the Arduino reference material.

Last edited by Consolidated Leo

OGR Publishing, Inc., 1310 Eastside Centre Ct, Suite 6, Mountain Home, AR 72653
800-980-OGRR (6477)
www.ogaugerr.com

×
×
×
×
×