aboutsummaryrefslogtreecommitdiffstats
path: root/docs/source/arduino/static.rst
blob: 1c0340e2066c73649c38f112e744832a29ad15c0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
.. _arduino-static:

Static
======

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
-------

::

    
    
    /* RandomWalk
    * Paul Badger 2007
    * RandomWalk wanders up and down randomly between two
    * endpoints. The maximum move in one loop is governed by
    * the parameter "stepsize".
    * A static variable is moved up and down a random amount.
    * This technique is also known as "pink noise" and "drunken walk".
    */
    
    #define randomWalkLowRange -20
    #define randomWalkHighRange 20
    int stepsize;
    
    int thisTime;
    int total;
    
    void setup()
    {
      Serial.begin(9600);
    }
    
    void loop()
    {        //  tetst randomWalk function
      stepsize = 5;
      thisTime = randomWalk(stepsize);
      Serial.println(thisTime);
       delay(10);
    }
    
    int randomWalk(int moveSize){
      static int  place;     // variable to store value in random walk - declared static so that it stores
                             // values in between function calls, but no other functions can change its value
    
      place = place + (random(-moveSize, moveSize + 1));
    
      if (place < randomWalkLowRange){                    // check lower and upper limits
        place = place + (randomWalkLowRange - place);     // reflect number back in positive direction
      }
      else if(place > randomWalkHighRange){
        place = place - (place - randomWalkHighRange);     // reflect number back in negative direction
      }
    
      return place;
    }