2. 選單命令「File/New」
檢視預設的程式框架
void setup() {
// put your setup code here, to run once:
}
void loop() {
// put your main code here, to run repeatedly:
}
Arduino程式基本架構
2
3. 選單命令File> New
編輯以下程式碼
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println("setup");
}
void loop() {
// put your main code here, to run repeatedly:
Serial.println("loop");
delay(2500);
}
Lab 測試Arduino程式運行 1/2
3
18. 有效範圍(scope)
全域變數(global variable),宣告在#include指令之後,提供整份
Arduino程式使用
區域變數(local variable),宣告在程式區塊中,只能在所宣告的程式
區塊中使用;每次執行時變數會被動態創建(create)和銷毁(destroy)
int gPWMval; //整個程式檔都可使用gPWMval變數
void setup() {
//...
}
void loop() {
int i, j; //在loop程式區塊中可使用變數i與j
//...
for (int k = 0; k < 100; k++){ //變數k只能在for程式區塊中使用
//...
}
}
變數 3/4
18
19. 靜態變數 (static variable)
在區域變數宣告前加上static關鍵字
程式執行期間變數內容會保留
void walk(int steps){
static int a; //每次執行walk()函式,變數a會保留上一次執行結果
int b; //每次執行walk()函式,變數b會重置
a = a + steps;
b = b + steps;
}
變數 4/4
19
20. int a = 0; //全域變數
void setup() {
Serial.begin(9600);
a = a + 1;
Serial.print("a = ");
Serial.println(a);
func1();
func2();
a = a + 1;
Serial.print("a = ");
Serial.println(a);
func1();
func1();
func2();
func2();
}
void loop() {
}
Lab 測試變數Scope 1/2
20
21. void func1() {
int b = 0;
b = a + b;
Serial.print("b in func1 = ");
Serial.println(b);
}
void func2(){
static int b = 0;
b = a + b;
Serial.print("b in func2 = ");
Serial.println(b);
}
Lab 測試變數Scope 2/2
21
50. void setup() {
Serial.begin(9600);
}
void loop() {
int i = 0;
while (i <= 255){
Serial.println(i);
delay(500);
i += 5;
}
Serial.print("Finally, i = ");
Serial.println(i);
}
Lab while迴圈敘述
50
51. do … while迴圏
do {
// statement block
} while (condition);
⾄少會執行⼀次
範例
#define pwmPin 3
...
int i = 0;
do {
analogWrite(pwmPin, i);
delay(10);
i++;
} while (i <= 255);
do迴圈敘述
條件運算式
重複作業區塊
true
false
結束
51
52. void setup() {
Serial.begin(9600);
}
void loop() {
int i = 0;
do {
Serial.println(i);
delay(500);
i += 5;
} while (i <= 255);
Serial.print("Finally, i = ");
Serial.println(i);
}
Lab do迴圈敘述
52