static
Descrição
A palavra-chave
static
é usada para criar variáveis que são visíveis para apenas uma função. No entanto, diferentemente de variáveis locais, que são criadas e destruidas toda vez que uma função é chamada, variáveis static
persistem entre chamadas da função, preservando seu valor.Variáveis declaradas como static são criadas e inicializadas apenas a primeria vez que uma função é chamada.
Código de Exemplo
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 int total;16
17 void setup() {18 Serial.begin(9600);19 }20
21 void loop() {22 // test randomWalk function23 stepsize = 5;24 thisTime = randomWalk(stepsize);25 Serial.println(thisTime);26 delay(10);27 }28
29 int randomWalk(int moveSize) {30 static int place; // variable to store value in random walk - declared static so that it stores31 // values in between function calls, but no other functions can change its value32
33 place = place + (random(-moveSize, moveSize + 1));34
35 if (place < randomWalkLowRange) { // check lower and upper limits36 place = randomWalkLowRange + (randomWalkLowRange - place); // reflect number back in positive direction37 }38 else if (place > randomWalkHighRange) {39 place = randomWalkHighRange - (place - randomWalkHighRange); // reflect number back in negative direction40 }41
42 return place;43 }
Ver também
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.