“For”的版本间的差异

来自YFRobotwiki
跳转至: 导航搜索
第1行: 第1行:
  
<font color="orange" size="+1">'''Description'''</font>
+
<font color="orange" size="+1">''' 描述'''</font>
  
  
The for statement is used to repeat a block of statements enclosed in curly braces. An increment counter is usually used to increment and terminate the loop. The for statement is useful for any repetitive operation, and is often used in combination with arrays to operate on collections of data/pins.
+
for 语句是用于重复执行在大括号内的一段代码。通常使用一个增量计数器来增加计数和终止循环。for语句用于重复性操作非常实用,经常和数组结合被用于操作数据或引脚。
  
There are three parts to the for loop header:
+
 
 +
for 循环语句开头有3个部分:
  
 
<pre style="color:dimgray">
 
<pre style="color:dimgray">

2015年8月18日 (二) 21:50的版本

描述


for 语句是用于重复执行在大括号内的一段代码。通常使用一个增量计数器来增加计数和终止循环。for语句用于重复性操作非常实用,经常和数组结合被用于操作数据或引脚。


for循环语句开头有3个部分:

for (initialization; condition; increment) {

//statement(s);

}


ForLoopIllustrated.png


The initialization happens first and exactly once. Each time through the loop, the condition is tested; if it's true, the statement block, and the increment is executed, then the condition is tested again. When the condition becomes false, the loop ends.


Example


// Dim an LED using a PWM pin
int PWMpin = 10; // LED in series with 470 ohm resistor on pin 10

void setup()
{
  // no setup needed
}

void loop()
{
   for (int i=0; i <= 255; i++){
      analogWrite(PWMpin, i);
      delay(10);
   } 
}


Coding Tips


The C for loop is much more flexible than for loops found in some other computer languages, including BASIC. Any or all of the three header elements may be omitted, although the semicolons are required. Also the statements for initialization, condition, and increment can be any valid C statements with unrelated variables, and use any C datatypes including floats. These types of unusual for statements may provide solutions to some rare programming problems.

For example, using a multiplication in the increment line will generate a logarithmic progression:

for(int x = 2; x < 100; x = x * 1.5){
println(x);
}

Generates: 2,3,4,6,9,13,19,28,42,63,94

Another example, fade an LED up and down with one for loop:

void loop()
{
   int x = 1;
   for (int i = 0; i > -1; i = i + x){
      analogWrite(PWMpin, i);
      if (i == 255) x = -1;             // switch direction at peak
      delay(10);
   } 
}




返回Arduino语法参考列表

更多建议和问题欢迎反馈至 YFRobot论坛