Counting Functions

Hi All,

My question pertains to "counting functions", sorry I don't exactly know what to call it, but say I am trying to keep track of how many times something happens and want to keep a running tally throughout the time that the system is running, how do I do that?


I want to control a stepper motor that controls temperature based on user input and a sensors readings...the system has a limit, how far the motor can rotate, so through out the use of the device, I want to know when the motor is reaching its limit or the max number the user can increase the input to.

Basically when I get to the end of the loop, how can I carry a value back to the beginning, a value that will most likely change every time through the loop?

There are two basic ways to preserve the value of a variable across function calls:

  1. declare it globally, i.e. outside any function (usually you see global variables declared at the beginning of the file, before setup());
  2. declare it static within the function that is called repeatedly (e.g. within loop(), static int rotation).

The main difference is that in 1 the variable will be globally accessible, which is usually considered bad practice (any function can modify it, so you don't know which function is responsible if something goes wrong).