For loop in Arduino

Implementation of For loop in Arduino

  • Under the for loop, the sentences inside the curly brackets are repeated according to the provided condition. 
  • The loop repetitions are incremented or decremented using an increment operator in the for loop.
  • The for statement is frequently used in conjunction with arrays to perform a repeating job or operation on a group of data/pins.
Syntax 

for (initialization; condition; increment)  
{  
\\ statements  
}  
For loop in Arduino
Arduino For loop

For example

for ( i = 0 ; i < = 5 ; i + +)  
  • The above statement will execute the loop six times. The values of i will be from 0 to 5.
Example 1:

int i;  
void setup ( )  
{  
  Serial.begin(9600);  
  for ( i = 0 ; i < 15 ; i ++ )  
  {  
   Serial.println( "Arduino");  
  }  
}  
void loop ( ) {  
 
Expected Output:
Output

Example 2:
  • To use a multiplication increment/decrement.
  • The multiplication increment in the for loop will generate a logarithmic progression.
int x;  
void setup ( )  
{  
  Serial.begin(9600);  
  for (x = 2; x < 200; x = x * 2)   
  {  
  Serial.println(x);  
  }  
}  
void loop ( ) {  
}  

Expected Output:
2
4
8
16
32
64
128

Example 3: 
  • To fade an LED.
  • const int pinPWM = 11; // here, we have initialized the PWM pin.  
void setup ( )  
{  
  Serial.begin(9600);  
}  
void loop ( )  
 {  
  int x = 1;  
  for (int i = 0; i > -1; i = i + x)  
 {  
    analogWrite(pinPWM, i);  
    if (i == 255)  
 {  
      x = -1;  // It will switch the direction at peak  
    }  
    delay(10); // It is delay time of 10 milliseconds  
    // the lesser the time, the more fading effect can be seen clearly  
  }  
}
 
Output:
  • The positive terminal of the LED in series with the resistor will be connected to PIN 11 (PWM pin), and the negative terminal of the LED will be connected to GND.
Example 4:

void setup ( )  
{  
  int i;  
  Serial.begin(9600);  
  for (i = 0; i < 5; i = i + 1)  
  {  
    Serial.println( "Welcome to Arduino" );  
  }  
  Serial.println( " Done");  
}  
void loop ( )   
{   
}  

The above code will print 'Welcome to Arduino' five times. After that the condition becomes false, control comes out of the loop, and 'DONE' is printed.

Post a Comment

Previous Post Next Post