Static

From Microduino Wiki
Revision as of 02:25, 22 August 2016 by Fengfeng (talk) (Created page with "Static variable(static) Keyword static is used to create variables only visible to a function. However, different from the local variable, after the function is called, t...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Static variable(static)

Keyword static is used to create variables only visible to a function. However, different from the local variable, after the function is called, the static variable still keeps the original data, rather than be created and destroyed each time the function is called.

The static variable is only created and initiated at the first time the function is called.

  • Example
/* RandomWalk
* Paul Badger 2007
* Function RandomWalk moves randomly up and down between the two ends. 
* In a loop, the largest mobile depends on the parameter “stepsize”.
*A static variable moves up and down for a random amount. 
*The technique is also known as “pink noise” or “step tipsy”.
*/
 
#define randomWalkLowRange -20
#define randomWalkHighRange 20
 
int stepsize;
 
INT thisTime;
int total;
 
void setup()
{
     Serial.begin(9600);
}
 
void loop()
{        //  test the function randomWalk
  stepsize = 5;
  thisTime = randomWalk(stepsize);
serial.println(thisTime);
   delay(10);
}
 
int randomWalk(int moveSize){
  static int  place;     // store variables in randomwalk
                         // be declared as static to keep data when functions are called, and can’t be changed by other functions 
  place = place + (random(-moveSize, moveSize + 1));
 
  if (place < randomWalkLowRange){                    //check the upper and lower limitations
    place = place + (randomWalkLowRange - place);     // change the numbers into positive direction
}
  else if(place > randomWalkHighRange){
    place = place - (place - randomWalkHighRange);     // change the numbers into negative direction
}
 
  return place;
}

[Return to Arduino Syntax Manual]