for loop in Arduino programming

for loop in Arduino programming:

for loop in Arduino– in a for loop, the number of iterations can be set to a value exactly. Therefore, we will use the for loop in Arduino to execute a set of instructions (written inside the opening and closing braces) a specified number of times.


general syntax of for loop in Arduino:

As can be seen, three parts must be written in parentheses differently, separated by semicolons. These three parts are optional (they can omit any of them) and are the following:

Initial value of the counter: this part assigns the initial value of an integer variable to be used as a counter in loop iterations. For example, if we write x = 0 there, the variable “x” will be set to zero at the beginning of the loop. From then on, at each repetition of the loop, this variable “x” will go progressively increasing (or decreasing) in value.

Loop end condition: This part specifies a condition (of the style of those used in a “while” loop). Just before each iteration, check that it is true to proceed to execute the group of statements internally. If the condition evaluates to false, the for loop in Arduino is terminated, continuing the program after its closing brace. For example, if there we write x <10, the inner group of instruction will be executed only when the variable “x” is less than 10 (that is, as long as x <10 is true).

Counter increment: in the last of the three parts is where the change of value that the variable will undergo at the beginning of each iteration of the loop is used as a counter. This change is expressed with an assignment. For example, the instruction x = x + 1 will add 1 to the variable “x” before each new iterating the loop, so we would actually be doing a counter that increases one by one with each repetition. This change is made right before checking the end condition of the loop.



for loop Arduino basic Programming Examples 

Example1: how to use for loop in Arduino programming:

Output:

for loop in arduino

If we observe the result shown by the “Serial monitor”, we will see that a list of numbers from 0 to 9 appears. Why? Because when in the sketch it reaches the “for” statement, first the counter is initialized (x = 0) and then check the condition. Since, effectively, x <10, the -only one will be executed in this case– inner instruction, which shows the value of the counter by the “Serial monitor”. Right after, the increment (x = x + 1) is performed, then turning to check the condition. If “x” (which is now 1) continues to meet the condition (yes, because 1 <10), the internal instruction will be executed again, now showing the value “1” in the “Serial monitor”. Right after this the increment will be performed again (being x now therefore 2) and the condition will be checked again, and so on and so on until that there comes a time when the condition turns out to be false (when “x” has increased so much its value that it is equal to or greater than 10), at which time the “for” will be terminated immediately.



It is important to emphasize that the number 10 will not be printed, because, as We have commented, first the counter is increased and then the verification. As soon as we finish executing the last iteration we will have to “x” is worth 9; then it is increased to 10 and then it is checked if 10 is less than 10. As this is false, it leaves the “for”, so when “x” is worth 10 it no longer has the opportunity to be printed. If we had wanted to print 10, we would have to have written as a condition x <= 10, in which case the “for” would have been repeated 11 times.

Obviously, it is not mandatory for the counter initialization to start by 0, nor that the increment is carried out one by one (not even that it is an increment: it can be a decrement, such as x = x-1 or similar).

As mentioned, the three parts within the definition parentheses of the loop are optional. In fact, if all three are omitted (that is, if for (;;)) we would be writing an infinite loop, such as the “loop()” function.

The inner statements of a for loop in Arduino can be as many as they want and of any kind, including, of course, new for loops (whatever called “nested for”).

If a variable is declared inside a for loop in Arduino, it will only exist while this for loop is running.


Example2: how to use the expression  in for loop in Arduino programming:

Output:

for loop in arduino

In the above code, you can see a fairly common way to perform sums of many values ​​(and their mean). Many times we will have the need to calculate these operations, and the mechanics are always the same: in this example, we have used a variable (in this case, called “sum”), which begins with the value 0. In the first repetition of the for loop in Arduino, the value of the first data is assigned to Add; in the second repetition, the second value is added to that “sum” value (so at that time “sum” is worth the sum of the first two values). In the third repetition, the third value is added to that partial sum (so in that moment “sum” is worth the sum of the first three values), in the fourth repetition the fourth value, and so on and on until the for loop in Arduino has just been traversed and all the data has been added one after another until the total sum is reached. Finally, I show the result, and I also show the mean, which is nothing more than that total sum Enter the number of data entered in the sum.


Example3: how to use Array in For loop in Arduino programming:

Another practical and concrete application of the for loop in Arduino is to use it to loop through the elements of an array, one by one. The loop counter is used as the index (the position) of each element of the array: initially, this counter is placed in the first element and increases in each iteration until reaching the latest. For example, assuming we have  declared an array of 5 elements of type “char” called “myarray”, we could do the following to assign a value (the same, in this case) to each of them and then show it on the “Serial monitor” along with its corresponding index:

Output:

for loop in arduino

Observe in the above example that the counter starts from 0 (same as the numbering of the positions of the elements in an array) and that the loop will perform five iterations, with “i” from 0 to 4 (corresponding to the five elements of the array). In each iteration, the value ‘a’ is assigned to the corresponding element (first to 0, then to 1, etc), then the value of “i” (0,1, etc.) is printed, and finally, the value just assigned to that element is printed (which is for all  ‘x’).

On the other hand, since the assignment of type x = x + 1 is very common in the third part of the definition of the for loop (and in general, in all our sketches), the Arduino programmers usually write this specific assignment in an alternative, more compact and faster, through the use of special signs, which belong to a set of symbols called “compound operators” whose function is precisely to facilitate the writing (and reading) of code. These operators are not essential, because what they do can be done with other operators (such as arithmetic: +, -, *, /, etc.) but they are widely used. TO Below is a table of “equivalence” –incomplete– between the use of some of the existing compound operators in the Arduino language and their meaning.


Compound operators in arduino programming:

x++ Equivalent to x = x + 1 (The operator “++” is called the operator “increment”)

x– Equivalent to x = x-1 (The “-” operator is called the “decrement” operator)

x + = 3 Equivalent to x = x + 3

x- = 3 Equivalent to x = x-3

x * = 3 Equivalent to x = x * 3

x / = 3 Equivalent to x = x / 3

Knowing this, now we can write, for example, a “for” loop like this:

for (x = 0; x <10; x ++) {}, which is just a more compact way of saying the same thing than this: for (x = 0; x <10; x = x + 1) {}

break and continue statement in for loop:

The “break” statement and the “continue” statement are closely related to loops (either of type “while” or “for”). Note that none of them incorporates parentheses, but like any other instruction, in our sketches, they must be ending with a semicolon.

The “break” instruction must be written inside the braces that delimit the internal statements of a loop and serve to terminate the loop immediately. It is In other words, this instruction will force the program to continue its execution after the loop closure brace. In case there are several nested loops (some within others), the “break” statement will only exit the innermost loop of them.

The “continue” statement must also be written inside the curly braces that delimit the inner statements of a loop and serve to end the current iteration and start immediately with the next one. That is, this instruction will force the program to “go back up” and begin the evaluation of the next iteration even if there are still instructions pending to be executed in the iteration current. In case there are several nested loops (one inside the other) the instruction “Continue” will only have an effect on the innermost loop of them.



Example4: how to use break statement in For loop in Arduino programming:

Output:

for loop in arduino

In the code above, you can see how the value 4 of “x” is no longer reached print because the break statement interrupts the execution of the entire loop. What after the “for” the “setup ()” function no longer has any more code, nothing else is visible. What would happen if we substitute the break statement for the continue statement, leaving the rest of the above code exactly the same? That we would see a list of numbers from 0 to 9, except precisely 4. This is so because the continue statement interrupts the execution of the iteration in which “x” is equal to 4 (and therefore the corresponding Serial.println () instruction is never executed) but it continues with the next iteration of the loop as normal, in which “x” assigns it the value 5.


Amazon purchase links:

nodemcu
bluetooth hc05
16×2 lcd
Potentiometer
LM7805 Voltage 
PIR Sensor
IR infrared 
rasberry pi
GSM sim900A
Neo 6m GPS module
Mq-2 gas/smoke sensor
LDR pack
WebCam night vision
electronic lock:
Robot Car chassis kit:
Flex sensor
L298N dual H-Bridge motor driver:
Joystick
433Mhz tx and Rx: best offer 
ITDB02 Arduino mega shield 2.1
SainSmart TFT LCD Display for Arduino (7″)
dht11 sensor
GPS module: 
solenoid valve: 
atmega328 microcontroller 
terminal block connector: 
MFRC522 RFID modulel

DISCLAIMER:

Please Note: these are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!



Related Arduino Project

Photodiode, Phototransistor and IR Sensor with Arduino

Photoresistor | LDR Arduino based Projects

 

Recommended For You

About the Author: Fawad

My name is Shahzada Fawad and I am a Programmer. Currently, I am running my own YouTube channel "Expertstech", and managing this Website. My Hobbies are * Watching Movies * Music * Photography * Travelling * gaming and so on...

Leave a Reply

%d bloggers like this: