當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Arduino static用法及代碼示例

[變量範圍和限定符]

說明

static 關鍵字用於創建僅對一個函數可見的變量。然而,與每次調用函數時都會創建和銷毀的局部變量不同,靜態變量在函數調用之後仍然存在,在函數調用之間保留它們的數據。

聲明為靜態的變量隻會在第一次調用函數時創建和初始化。

示例代碼

/* 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;

void setup() {
  Serial.begin(9600);
}

void loop() {
  //  test 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 = randomWalkLowRange + (randomWalkLowRange - place);    // reflect number back in positive direction
  }
  else if (place > randomWalkHighRange) {
    place = randomWalkHighRange - (place - randomWalkHighRange);  // reflect number back in negative direction
  }

  return place;
}

相關用法


注:本文由純淨天空篩選整理自arduino.cc大神的英文原創作品 static。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。