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.
#define randomWalkLowRange -20
#define randomWalkHighRange 20
int stepsize;
int thisTime;
void setup() {
Serial.begin(9600);
}
void loop() {
stepsize = 5;
thisTime = randomWalk(stepsize);
Serial.println(thisTime);
delay(10);
}
int randomWalk(int moveSize) {
static int place;
place = place + (random(-moveSize, moveSize + 1));
if (place < randomWalkLowRange) {
place = randomWalkLowRange + (randomWalkLowRange - place);
} else if (place > randomWalkHighRange) {
place = randomWalkHighRange - (place - randomWalkHighRange);
}
return place;
}
※ ARDUINO BUY RECOMMENDATION
Please note: These are Amazon affiliate links. If you buy the components through these links, We will get a commission at no extra cost to you. We appreciate it.