For

From Microduino Wiki
Revision as of 06:47, 4 August 2016 by Fengfeng (talk) (Created page with "*'''for''' For statement is used to repeat the code within the curly brace, with a incremental counter to count and end the cycle usually. For statement is very effective fo...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
  • for


For statement is used to repeat the code within the curly brace, with a incremental counter to count and end the cycle usually. For statement is very effective for repetition operation. And it is usually used to operate data and pins with arrays.

There are 3 parts in the front of for loop:


for(Initialization;condition;expression){
//statements
}


“Initialization” is only executed once when the loop starts. Each time through the loop, the following conditions will be tested;if the condition remain true, the following statements and expression are executed, and the condition is tested again. When the condition becomes false, the loop ends.

Example


//darken LED with PWM pin
int PWMpin = 10; //connect a LED and 47Ω resistor in series and connected them to 10 pin
 
void setup()
{
//needn’t set up
}
 
void loop()
{
   for (int i=0; i <= 255; i++){
      analogWrite(PWMpin, i);
      delay(10);
}
}

Programming tips The C for loop is much more flexible than for loops found in BASIC and other computer programming languages. Any or all of the three header elements may be ommitted, although the semicolons are required. Also the statement for initialization, condition, and expression can be any valid C statements with unrelated variables, and any C data types including float. These types of unusual for statements may provide solutions to some rare programming programs. For example, use multiplication in expression can get a geometric progression:


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

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

For another example, use for loop to make LED generate the effect of lighting gradually and fading gradually:


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


[Return to Arduino Syntax Manual]