Static

出自YFRobotwiki
在2017年9月13日 (三) 09:05由Allblue對話 | 貢獻所做的修訂版本

(差異) ←上個修訂 | 最新修訂 (差異) | 下一修訂→ (差異)
跳轉到: 導覽搜尋

靜態變數

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




返回Arduino語法參考列表

更多建議和問題歡迎反饋至 YFRobot論壇