static
Description
The
static
keyword is used to create variables that are visible to only one function. However unlike local variables that get created and destroyed every time a function is called, static variables persist beyond the function call, preserving their data between function calls.Variables declared as static will only be created and initialized the first time a function is called.
Example Code
1/* RandomWalk2 Paul Badger 20073 RandomWalk wanders up and down randomly between two4 endpoints. The maximum move in one loop is governed by5 the parameter "stepsize".6 A static variable is moved up and down a random amount.7 This technique is also known as "pink noise" and "drunken walk".8 */9
10 #define randomWalkLowRange -2011 #define randomWalkHighRange 2012 int stepsize;13
14 int thisTime;15
16 void setup() {17 Serial.begin(9600);18 }19
20 void loop() {21 // test randomWalk function22 stepsize = 5;23 thisTime = randomWalk(stepsize);24 Serial.println(thisTime);25 delay(10);26 }27
28 int randomWalk(int moveSize) {29 static int place; // variable to store value in random walk - declared static so that it stores30 // values in between function calls, but no other functions can change its value31
32 place = place + (random(-moveSize, moveSize + 1));33
34 if (place < randomWalkLowRange) { // check lower and upper limits35 place = randomWalkLowRange + (randomWalkLowRange - place); // reflect number back in positive direction36 }37 else if (place > randomWalkHighRange) {38 place = randomWalkHighRange - (place - randomWalkHighRange); // reflect number back in negative direction39 }40
41 return place;42 }
See also
Suggest changes
The content on docs.arduino.cc is facilitated through a public GitHub repository. If you see anything wrong, you can edit this page here.
License
The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.