Lesson 6 - While & For Loops





In this lesson, we will be going through a new structure of programming with Arduino, called Loops. A loop is used to repeat a set of code constantly, whilst a condition is true. When the condition becomes false, the Arduino exits the loop and proceeds with the rest of the code. There are 2 different types of loops we are going to be looking at, both are very similar to each other.


While Loop





A while loop will loop continuously, until the condition inside the parenthesis becomes false. Something must change the tested variable, or the while loop will never exit.






For Loop





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.



Program Requirements

1. Blink an LED, using a loop function, 10 times with 1 second intervals

2. After 10 blinks, the LED must completely turn off

3. Then, using and alternative structure, blink a different LED 25 times with half a second intervals

4. Once the 25 blinks have been achieved, this LED must also turn off.



Coding

Firstly, in the global scope we need to declare two variable names for 2 separate LEDs. Using the MFS will allow us to choose between digital pins 10 to 13, as LED output pins. Secondly, we need two numerical integers which we can use to count the blinks of each LED. In the setup, we will need configure each LED pin as an output.


Note: Using the LED pins on the MFS means HIGH = 0 and LOW = 1. The digital logic is reversed because of the internal electrical connections of the MFS.


In the loop, we will begin by ensuring both LEDs are off. This is to avoid any bugs and to ensure our program executes correctly. Then, we will blink the first LED constantly 10 times at 1 second intervals. This instruction set will be within a while loop which has a condition to repeat until the blink count is less than 25. Within the instruction set we will increment the counter using the increment function, so each blink is recorded. Once the counter reaches 10, the Arduino will exit the loop and at this point we will turn this LED off completely.


Now, using a for loop, we will blink the second LED 25 times at half a second intervals. Within the structure parenthesis, we will just include the variable name for the second counter because it has already been initialised in the global scope. The condition is to loop the instruction set while the counter is less than 25 and after each loop increment the counter by 1, positively. After 25 blinks, the for loop will exit and again we will turn this LED off too.





We have followed the program requirements and have completed this. While and For Loops are great structures when programming with Arduino. We will be using more of these over the next few lessons to program at a higher level.



Source Code



We recommend copying the source code to the IDE



Code


By Zaqyas Mahmood, Electronics Engineer