Arduino Lesson 7: Using While Loops

In Lesson 3 we learned how to use for loops. For loops are very powerful and they are sufficient to take care of most of your looping needs. However, there is another type of loop called a ‘while loop’.  The while loop is not better than a for loop, it is just a different way of looping. In most scenarios you could choose to loop with either a for loop or a while loop. In lesson 6 we briefly introduced while loops, and used one to pause the program to wain on user input. In this lesson we will look in more detail at how while loops work. We will continue to work with this circuit, which you first built in lesson 3. If you need help putting it together go back and see Lesson 3.

LED Schematic
This circuit will allow you to independently control two Light Emitting Diodes from the arduino microcontroller

Also, we will continue to expand the code we developed in Lesson 6. At the end of Lesson 6, our code looked something like this:

You can see in the code above, we are prompting the user for data, then waiting, then entering the data for both numRedBlinks and numYellowBlinks. This allows the user to set the number of times the LED’s blink from the serial monitor. The way we actually do the blinking is with the two for loops. There is another way to loop, and that is with ‘while loops’. When you are writing code, often times you can choose a for loop or a while loop. Some people frequently use both types of loops and some have a preference for one or the other and almost always use their preferred type of loop. It is good to know how to use both types, so here we will explore the while loop.

Lets look at how one might work:

 Lets unpack this code and see how it works. First, notice that the while loop will have one or more commands that it executes. It will execute the commands that are between the curly brackets.  It will continue to execute the commands between the curly brackets as long as the ‘condition’ described in the parenthesis of the while loop is true. In the case above, it will continue to execute the commands between the curly brackets as long as j is less than or equal to ten. notice that inside the loop we are incrementing j by 1 each time through the loop. This ensures that it will eventually exit the loop. If we were to forget to increment j, the program would become hung in the loop. This would create what is called an infinite loop, and the program would become hung in the infinite loop.

So, for the code above, we start by making j=1, then each time through the loop we increment j by 1. The program will continue executing this loop until the condition is no longer true . . . for this case, at the point that j=11 the condition would no longer be true, the program would not enter the curly bracket, and would jump to the first line of code after the closing curly bracket.

So, for this lesson what we want to do is replace the for loops in the original code shown at the top of this lesson with while loops. There is one for loop that blinks the red LED and one for loop that blinks the yellow LED. Replace those two for loops with while loops. Lets look at the first for loop again:

Lets do the same function with a while loop. We could replace this code with:

 

22 thoughts on “Arduino Lesson 7: Using While Loops”

  1. Nice Tutorials.I want to know why can’t we just replace ‘for’ with ‘while’ for looping instead of breaking up what is written in the brackets of the ‘for loop’ in lesson 6 while doing a ‘while loop’.

    Thanks

    1. Most of the time you can use either for loops or while loops. When you use a while loop, you have to make sure you provide a condition that will allow the program to exit the loop when you intend it to.

      1. i also have done the same kind of code but getting error as
        “Arduino: 1.6.5 (Windows 8.1), Board: “Arduino Uno”

        Blink.ino: In function ‘void loop()’:
        Blink:25: error: ‘i’ was not declared in this scope
        ‘i’ was not declared in this scope

        This report would have more information with
        “Show verbose output during compilation”
        enabled in File > Preferences.

        plzz help me out faster as soon
        u can mail me alsoo

  2. I originally posted this under lesson 6, sorry for any confusion.

    I’m having the same problems as a couple of others. The 1st while loop prints and waits. Enter a value. The 2nd while loop prints, but does not wait and the program continues to count and print for the 1st while loop. It then prints “the yellow LED is Blinking” then prints the prompt for 1st while loop again.
    I’ve matched whichever Baud rates that I used.
    I’m also using the latest IDE 1.6.5
    I tried your exact sketch , ( copy and paste), with no success
    This is my sketch typed from new;-

    int redLEDPin=9; //redLEDPin set to pin9
    int yellowLEDPin=10; //yellowLEDPin set to pin10
    int redOnTime=250; //redOnTime set to 250ms
    int redOffTime=250; //redOffTime set to 250ms
    int yellowOnTime=250; //yellowOnTime set to 250ms
    int yellowOffTime=250; //yellowOffTime set to 250ms
    int numYellowBlinks; //#times to Blink yellow
    int numRedBlinks; //#times to Blink red
    String redMessage=”The Red LED is Blinking”; //print string
    String yellowMessage=”The Yellow LED is Blinking”; //print string

    void setup() {
    pinMode(redLEDPin, OUTPUT); //redLEDPin an output pin
    pinMode(yellowLEDPin, OUTPUT); //yellowLEDPin an output pin
    Serial.begin(9600); //Set the Baud rate
    }

    void loop() {
    Serial.println(“How many times do you want the Red LED to Blink?”); //print inside “”
    while(Serial.available()==0) { } //prompt user
    numRedBlinks=Serial.parseInt(); //assign value to int

    Serial.println(“How many times do you want the Yellow LED to Blink?”); //print inside “”
    while(Serial.available()==0) { } //prompt user
    numYellowBlinks=Serial.parseInt(); //assign value to int

    Serial.println(redMessage); //print int
    for (int j=1; j<=numRedBlinks; j=j+1) { //start red count
    Serial.print(" You are on Blink number: "); //print inside ""
    Serial.println(j); //print count value
    digitalWrite(redLEDPin, HIGH); //red LED on
    delay(redOnTime); //on for int
    digitalWrite(redLEDPin, LOW); //red LED off
    delay(redOffTime); //off for int
    }
    Serial.println(" "); //print blank line

    Serial.println(yellowMessage); //print int
    for (int j=1; j<=numYellowBlinks; j=j+1) { //start yellow count
    Serial.print(" You are on Blink number: "); //print inside ""
    Serial.println(j); //print count value
    digitalWrite(yellowLEDPin, HIGH); //yellow LED on
    delay(yellowOnTime); //on for int
    digitalWrite(yellowLEDPin, LOW); //yellow LED off
    delay(yellowOffTime); //off for int
    }
    Serial.println(" "); //print blank line
    }
    Thanks for your attention

    1. bro you are using wrong commas “””””” this one is write

      int redLEDPin=9; //redLEDPin set to pin9
      int yellowLEDPin=10; //yellowLEDPin set to pin10
      int redOnTime=500; //redOnTime set to 250ms
      int redOffTime=500; //redOffTime set to 250ms
      int yellowOnTime=500; //yellowOnTime set to 250ms
      int yellowOffTime=500; //yellowOffTime set to 250ms
      int numYellowBlinks; //#times to Blink yellow
      int numRedBlinks; //#times to Blink red
      String redMessage=” Red LED is Blinking”; //print string
      String yellowMessage= “Yellow LED is Blinking”; //print string

      void setup() {
      pinMode(redLEDPin, OUTPUT); //redLEDPin an output pin
      pinMode(yellowLEDPin, OUTPUT); //yellowLEDPin an output pin
      Serial.begin(9600);
      }

      void loop() {
      Serial.println(“How many times do you want the Red LED to Blink?”);
      while(Serial.available()==0) { } //prompt user
      numRedBlinks=Serial.parseInt(); //assign value to int

      Serial.println(“How many times do you want the Yellow LED to Blink?”);
      while(Serial.available()==0) {
      delay(1000);
      Serial.println(“please tell”);

      }
      numYellowBlinks=Serial.parseInt(); //assign value to int

      for (int j=1; j<=numRedBlinks; j=j+1) { //start red count
      Serial.print(" You are on Blink number: "); //print inside ""
      Serial.print(redMessage );
      Serial.println(j); //print count value
      digitalWrite(redLEDPin, HIGH); //red LED on
      delay(redOnTime); //on for int
      digitalWrite(redLEDPin, LOW); //red LED off
      delay(redOffTime); //off for int
      }
      Serial.println(" "); //print blank line

      Serial.println(yellowMessage); //print int
      for (int j=1; j<=numYellowBlinks; j=j+1) {
      Serial.print(" You are on Blink number: "); //print inside ""
      Serial.println(j); //print count value
      digitalWrite(yellowLEDPin, HIGH); //yellow LED on
      delay(yellowOnTime); //on for int
      digitalWrite(yellowLEDPin, LOW); //yellow LED off
      delay(yellowOffTime); //off for int
      }
      Serial.println(" "); //print blank line
      }

  3. See that I did:

    Serial.println(“How Many Times Do You Want the Red LED to Blink? “); //Prompt User for Input
    while (Serial.available()==0){ } //Wait for User Input
    numRedBlinks = Serial.parseInt(); //Read User Input

    Serial.println(“How Many Times Do You Want the Yellow LED to Blink? “); //Prompt User for Input
    while (Serial.available()==1){ } //Wait for Input
    numYellowBlinks = Serial.parseInt(); //Read User Input

  4. I also did this code. Same problem. The >>
    while (Serial.available()==0){ } //Wait for Input
    Is not changing, back to zero and the code moves on to the next line. The next line does not “wait for input” as the values in not zero. By using the >>
    while (Serial.available()==1){ } //Wait for Input
    you invert the state, and cause the second question to remain indefinitely, regardless of the answer., unless you create an escape logic using the answer. Then return the answer value to zero at the end of the execution routine.
    Something like if answer greater then zero escape while loop. Then at the end of the programs clear the answers.

  5. I have seen lesson 1-7 for now, and my code is working now for 3 LED’s .

    Serial In & Output’s for the user off my program:

    int yellowLEDPin=8; //Declaring greenLEDPin as an int, and set it to 8
    int redLEDPin=9; //Declaring redLEDPin as an int, and set it to 9
    int greenLEDPin=10; //Declaring greenLEDPin as an int, and set it to 10
    int yellowOnTime; //This is the yellow LED ontime
    int yellowOffTime; //This is the yellow LED off time
    int redOnTime; //This is the red LED ontime
    int redOffTime; //This is the red LED offtime
    int greenOnTime; //This is the green LED ontime
    int greenOffTime; //This is the green LED off time
    int numYellowBlink; //Number of times to blink green
    int numRedBlink; //Number of times to blink red
    int numGreenBlink; //Number of times to blink green
    String yellowMessage=”The yellow LED is Blinking”; //Declaring a string Variable
    String redMessage=”The red LED is Blinking”; // Declaring a string Variable
    String greenMessage=”The green LED is Blinking”; // Declaring a string Variable

    void setup() {

    Serial.begin(115200);
    String wm1= “Welcome to “; //Declare string varable wm1 and assign a value
    String wm2= “My Program!.”; //Declare string variable wm2 and assign a value
    String wm3; //Declare string variable wm3
    wm3= wm1+wm2; //concatanating wm1 and wm2 into wm3

    Serial.print(wm3);
    Serial.println();
    pinMode(yellowLEDPin, OUTPUT);
    pinMode(redLEDPin, OUTPUT);
    pinMode(greenLEDPin, OUTPUT);

    Serial.println(“- How many times do you want the yellow LED to Blink?”); //Prompt User for Input
    while (Serial.available()==0){ } //Wait for User Input
    numYellowBlink = Serial.parseInt(); //Read User Input

    Serial.println(“- How long do you want the yellow LED is on?”); //Prompt User for Input
    while (Serial.available()==0){ } //Wait for User Input
    yellowOnTime = Serial.parseInt(); //Read User Input

    Serial.println(“- How long do you want the yellow LED is off?”); //Prompt User for Input
    while (Serial.available()==0){ } //Wait for User Input
    yellowOffTime = Serial.parseInt(); //Read User Input

    Serial.println(“- How many times do you want the red LED to Blink?”); //Prompt User for Input
    while (Serial.available()==0){ } //Wait for User Input
    numRedBlink = Serial.parseInt(); //Read User Input

    Serial.println(“- How long do you want the red LED is on?”); //Prompt User for Input
    while (Serial.available()==0) { } //Wait for User Input
    redOnTime = Serial.parseInt(); //Read User input

    Serial.println (“- How long do you want the red LED is off?”); //Prompt User for Input
    while (Serial.available()==0) { } //Wait for User Input
    redOffTime = Serial.parseInt(); //Read User input

    Serial.println(“- How many times do you want the green LED to Blink?”); //Prompt User for Input
    while (Serial.available()==0){ } //Wait for User Input
    numGreenBlink = Serial.parseInt(); //Read User Input

    Serial.println(“- How long do you want the green LED is on?”); //Prompt User for Input
    while (Serial.available()==0) { } //Wait for User Input
    greenOnTime = Serial.parseInt(); //Read User input

    Serial.println(“- How long do you want the green LED is off?”); //Prompt User for Input
    while (Serial.available()==0) { } //Wait for User Input
    greenOffTime = Serial.parseInt(); //ReadUser Input
    }

    void loop() {

    Serial.println(” “);
    Serial.println(yellowMessage);
    int j=1;
    while (j<=numYellowBlink ) { //Start our for loop
    Serial.print(" You are on Blink #: ");
    Serial.println(j);
    digitalWrite(yellowLEDPin, HIGH); //Turn the green LED on
    delay(yellowOnTime);
    digitalWrite(yellowLEDPin, LOW); //Turn the green LED off
    delay(yellowOffTime);
    j=j+1;
    }
    Serial.println(" ");
    Serial.println(redMessage);
    int k=1;
    while (k<=numRedBlink ) { //Start our for loop
    Serial.print(" You are on Blink #: ");
    Serial.println(j);
    digitalWrite(redLEDPin, HIGH); //Turn the red LED on
    delay(redOnTime); //Wait
    digitalWrite(redLEDPin, LOW); //Turn the red LED off
    delay(redOffTime); //Wait
    k=k+1;
    }
    Serial.println(" ");
    Serial.println(greenMessage);
    int i=1;
    while (i<=numGreenBlink ) { //Start our for loop
    Serial.print(" You are on Blink#: ");
    Serial.println(j);
    digitalWrite(greenLEDPin, HIGH); //Turn the green LED on
    delay(greenOnTime); //Wait
    digitalWrite(greenLEDPin, LOW); //Turn the green LED off
    delay(greenOffTime); //Wait
    i=i+1;
    }
    Serial.println(" ");
    }

  6. Your tutorials are the best that I have found yet. Thanks for your work. I have one question. I have religiously entered code as I go along but I want to copy the code as of the end on session 6 so I can be using exactly what you are using as I do 7 etc. When I do that and then upload and try to see it in the monitor I get 4 little symbols — 2 squares, something that looks like a superscript s and something that looks like a “p”. They will not copy so I can’t put them on this screen. What’s happening?

  7. My notes might not be quite as nice as Paul’s but I followed along his lesson and this is my flawlessly working program..
    This is also my first time to ever play with programming and you have made it quite interesting.. Looking forward to learning more .
    Great teacher very easy to follow, Please keep it coming ..

    int greenLEDPin = 8; // green LED dedicated to pin 8
    int redLEDPin = 9; // red LED dedicated to pin 9
    int yellowLEDPin = 10; // yellow LED dedicated to pin 10
    int greenOnTime = 1000; // time that green LED is on
    int greenOffTime = 500; // time that green led is OFF
    int redOnTime = 250; // time that red LED is on
    int redOffTime = 500; // time that red LED is off
    int yellowOnTime = 500; // time that yellow LED is on
    int yellowOffTime = 100; // time that yellow LED is off
    int greenBlinks; // number of times green LED blinks
    int redBlinks; // number of times red LED blinks
    int yellowBlinks; // number of times yellow LED blinks
    String greenMessage=”Green LED is blinking”; // message to display on serial monitor
    String redMessage=”Red LED blinking”; // message to display on serial monitor
    String yellowMessage=”Yellow LED blinking”; // message to display on serial monitor

    void setup() {
    Serial.begin(9600); // open serial port
    pinMode(greenLEDPin, OUTPUT); // setting digital output to green LED
    pinMode(redLEDPin, OUTPUT); // setting digital output to red LED
    pinMode(yellowLEDPin, OUTPUT); // setting digital output to yellow LED
    String wm1=”Welcome to my “; // opening statement to user part 1
    String wm2=”first project”; // opening statement to user part 2
    String wm3; // opening statement to user combined with parts 1 and 2
    wm3= wm1+wm2; // declaring wordmessage1 + wordmessage2 = wordmessage3
    Serial.println(wm3); // sending wordmessage3 to serial monitor
    }

    void loop() {
    Serial.println(“How many times would you like to blink the Green LED? “); // question challenging user
    while(Serial.available( )==0){ } // waiting for user’s response
    greenBlinks=Serial.parseInt( ); // displaying user’s response to challange question
    Serial.println(greenMessage); // declring green section to user

    for ( int j = 1; j <= greenBlinks; j = j + 1 ) { // loop time for green LED
    Serial.print(" you are on blink #; "); // showing the number of blinks on serial monitor
    Serial.print(" "); // text space
    Serial.println(j); // displaying numeric valve
    digitalWrite(greenLEDPin, HIGH); // turn on green LED
    delay(greenOnTime); // time green LED is on
    digitalWrite(greenLEDPin, LOW); // turn off green LED
    delay(greenOffTime); // time green LED is off
    }

    Serial.println("How many times would you like to blink the Red LED? "); // question challenging user
    while(Serial.available( )==0){ } // waiting for user's reponse
    redBlinks=Serial.parseInt( ); // user's response to challange question
    Serial.println(redMessage); // declaring red section to user

    for (int j = 1; j <= redBlinks; j = j + 1) { // loop time for red LED
    Serial.print(" you are on blink #; "); // showing the number of blinks on serial monitor
    Serial.print(" "); // text space
    Serial.println(j); // displaying numeric valve
    digitalWrite(redLEDPin, HIGH); // turn on red LED
    delay(redOnTime); // time red LED is on
    digitalWrite(redLEDPin, LOW); // turn off red LED
    delay(redOffTime); // time red LED is off
    }
    Serial.println("How many times would you like to blink the Yellow LED? "); // question challenging user
    while(Serial.available( )==0){ } // waiting for user's response
    yellowBlinks=Serial.parseInt( ); // user's response to challange question
    Serial.println(yellowMessage); // declaring yellow section to user
    for (int j = 1; j <= yellowBlinks; j = j + 1) { // loop time for yellow LED
    Serial.print(" you are on blink #; "); // showing number of blinks on serial monitor
    Serial.print(" "); // text space
    Serial.println(j); // displaying numeric value
    digitalWrite(yellowLEDPin, HIGH); // turn on yellow LED
    delay(yellowOnTime); // time yellow LED is on
    digitalWrite(yellowLEDPin, LOW); // turn off yellow LED
    delay(yellowOffTime); // time yellow LED is off
    }

  8. I forgot to state the fact that I wrote my from start to finish without copy and paste… Better for learning repetition and fewer mistakes…
    Have a Good day…

  9. Enjoy the lessons but have made an observation on the drawing of lesson three. In this drawing the LED’s are drawn wrong : kathode and anode are reversed.
    For the un-initiated, in electronics, this may cause problems.
    Regards,
    Cees.

  10. I am getting an error in my program but i am not able to recognize it. Can you please help me…. The program is mentioned below.
    int redLED = 9;
    int yellowLED= 10;
    int numRed;
    int numYellow;
    String introduction = “You are going to see the red and yellow LEDs blink!”;
    String yellowIntroduction = “The yellow LED will blink!”;
    String redIntroduction = “The red LED will blink!”;
    void setup() {
    // put your setup code here, to run once:
    Serial.begin(9600);
    pinMode(redLED,OUTPUT);
    pinMode(yellowLED,OUTPUT);
    String message1 = “Hello “;
    String message2 = “Everybody!”;
    String message3 = message1 + message2;
    Serial.println (message3);
    delay(1500);
    }

    void loop() {
    // put your main code here, to run repeatedly:
    Serial.println(introduction);
    delay(2500);
    Serial.println(“How many times do you want the red LED to blink?”);
    while (Serial.available==0){ }
    numRed=Serial.parseInt();
    Serial.println(redIntroduction);
    delay(2000);
    for(int j=1; j “);
    Serial.println(j);
    digitalWrite(redLED,HIGH);
    delay(500);
    digitalWrite(redLED,LOW);
    delay(500);
    }
    delay(1000);
    Serial.println( );
    Serial.println(“How many times do you want the yellow LED to blink?”);
    while (Serial.available==0){ } // the line showing problem…..<——
    numYellow=Serial.parseInt();
    Serial.println(yellowIntroduction);
    delay(2000);
    for(int j=1; j “);
    Serial.println(j);
    digitalWrite(yellowLED,HIGH);
    delay(500);
    digitalWrite(yellowLED,LOW);
    delay(500);}
    }
    The problem is shown in the line with comment. THANKS FOR YOU ATTENTION….

    1. sir
      from the above program i can set the LED`s no of blinking similarly
      may i set the delay time sir?

Comments are closed.