在 Arduino 中定義新函式


在 Arduino 中定義新函式相當於在 C 中定義函式。

語法為 -

語法

return_type function_name(arg_type arg)

唯一區別在於,如果在 C 中的函式的定義之前呼叫該函式,則需要在頂部宣告該函式。然而,在 Arduino 中不存在這種約束。以下程式碼對此進行了演示 -

示例

void setup() {
   Serial.begin(9600);
   Serial.println();
}
void loop() {
   // put your main code here, to run repeatedly:
   for (int i = 0; i < 10; i++) {
      long int w = square(i);
      Serial.println(w);
      delay(1000);
   }
}
long int square(int a) {
   return (a * a);
}

序列監視器的輸出如下所示 -

輸出

如你所見,即使在定義之前呼叫該函式,Arduino 也不會丟擲錯誤。執行完全符合預期。

更新於:2021-03-24

201 個瀏覽量

開啟你的 職業生涯

完成課程,獲得認證

上手操作
廣告
© . All rights reserved.