Arduino 的 for 和 while 循环
Arduino 中的 for 和 while 循环遵循 C 语言语法。
for 循环的语法如下:
语法
for(iterator initialization; stop condition; increment instruction){ //Do something }
示例
for(int i = 0; i< 50; i++){ //Do something }
类似地,while 循环的语法如下:
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
语法
while(condition){ //Do something }
示例
int i = 0 while(i < 50){ //Do something i = i+1; }
以下示例将演示在 Arduino 程序中 for 和 while 循环的工作方式。
示例
void setup() { Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: int i = 0; for(i = 0; i< 10; i++){ Serial.println(i); } while(i < 20){ i = i+1; Serial.println(i); } }
请注意,我们在 for 循环之外定义了整数 i。如果我写成 for(int i = 0; i< 10; i++),则变量 i 的作用域将仅限于 for 循环,而 while 循环将无法访问它。
上述程序的串口监视器输出如下:
输出
正如你所看到的,这两个循环共享变量 i。
为了编写无限循环,你可以对 for 循环使用以下语法:
语法
for(;;){ //Do something continuously }
以及对 while 循环使用以下语法:
语法
while(1){ //Do something continuously }
广告