Arduino uno User Manual page 23

Hide thumbs Also See for uno:
Table of Contents

Advertisement

The for statement is used to create program loops. Loops are useful when you want a chunk of
code to be repeated a specified number of times. A variable is used to count the number of times
the code is repeated. Here is an example that flashes an LED attached to pin 2 five times
int i;
void setup()
{
pinMode(2,OUTPUT);
for (i=0;i<5;i++) {
digitalWrite(2,HIGH);
delay(250);
digitalWrite(2,LOW);
delay(250);
}
}
void loop() {}
The variable i is the loop counter. The for() statement has three parts: the initialization, the check
and the increment. Variable i is initialized to zero. The check is to see if i is less then 5. If so, the
commands between the braces are executed. If not, those commands are skipped. After the
check, i is incremented by 1 (the i++ command). While the for statement could read for
(i=1;i==5;i++), it is convention to start the counter variable at zero and use less than for the
condition check.
You can have the loop counter increment by two or by three or by any increment you want. For
example, try this code fragment.
int i;
void setup()
{
Serial.begin(9600);
for (i=0;i<15;i=i+3) {
Serial.println(i);
}
}
void loop() {}
Loops can be nested within loops. This example will flash the LED 10 times because for each of
the five outer loops counted by i, the program goes twice through the inner loop counted by j.
int i,j;
void setup()
{
pinMode(2,OUTPUT);
for (i=0;i<5;i++) {
for(j=0;j<2;j++) {
digitalWrite(2,HIGH);
delay(250);
digitalWrite(2,LOW);
delay(250);
}
}
23

Hide quick links:

Advertisement

Table of Contents
loading
Need help?

Need help?

Do you have a question about the uno and is the answer not in the manual?

Questions and answers

Subscribe to Our Youtube Channel

Table of Contents

Save PDF