Arduino Lesson 3: For Loops for Simple LED Circuit

In this lesson we will create a circuit and write arduino code to control two LED’s.

Two Diode Circuit

You can jump right to the video, or read through the tutorial.

In the earlier lessons we wrote our first programs and built our first circuit. At this time you should be getting comfortable with how the breadboard works and how to work with variables and digitalWrite commands in the arduino IDE (Integrated Development Environment). Now we are going to build a slightly more complicated circuit for controlling two LEDs. Since we want to control each one individually, you will need to have a separate arduino pin control each LED and each LED should have its own current limiting resistor (330 ohms). You should be able to sketch out your own circuit at this point. This is a diagram of the circuit we will be using. Yours does not have to be exactly like this, but it should have the same function.

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

Notice that in this circuit, the shorter leg of both LED’s needs to be connected to ground. In order to accomplish this we run a wire from the ground pin on the arduino to the top row of the breadboard. This makes the top row “ground”. Now any device that needs to be grounded can just be connected to the top row, since that row of the breadboard is connected all the way across (See LESSON 1). Also note that both LED’s have their own 330 ohm current limiting resistor, and remember that the direction matters on diodes . . . be sure to put them in with the longer leg connected to the more positive part of the circuit . . . in this case, the longer leg should be connected to the resistor (since the resistor connects to the + voltage coming from the arduino pin).

When you get the circuit built, it should look something like this:

Arduino LED Circuit
Photograph of our Arduino Circuit for Controlling Two Diodes.

Now that your circuit is built, we are ready to do some programming.

Our objective in this exercise is to be able to independently control the LED’s.  We will want to blink the red one ten times in a row, and then blink the yellow one once.  A “blink” should be turning LED on, leaving it on for a quarter second, turning it off, and leaving it off for a quarter second. Then that sequence will be repeated. So, we will need to think about the variables we will need. We have two LED’s so we will need to declare two variables to indicate the pins that the LED’s are connected to. In the schematic we connected the red LED to pin 9 and the yellow LED to pin 10. Also, since we will be blinking two LED’s, we will need onTime and offTime variables for each LED.  You should go ahead and open your arduino IDE and set declare your variables. Think about what you are going to name your variables . . . you do not have to use the same names I use. My code looks like this:

Now that your variables are declared, what should you do next? That’s right! You need to work on your void setup(). In your void setup you will need to set your pinModes. Since you are using 2 arduino pins this time, you need to issue two pinMode commads as follows.

Things are moving along and we are now ready to do our main business in the void loop(). Remember our goal is to blink the Red LED ten times, and then blink the yellow LED one time.

 OK, now you are ready to run your code. If you did it correctly,  it should run, and blink the red LED ten times, and then blink the yellow LED one time. If it does not run correctly, you need to debug your code. If it does not work, it is because you made a mistake. Most of the time it is silly typos or forgetting to end lines with a semicolon. Check your work, and you will find your error. Sometimes it helps to have someone else look it over with you.

OK, hopefully you have your code and circuit working now. You can play around with the parameters, and you can see that you can make the LED’s do whatever you want them to.

Now imagine I asked you to make the red LED blink 25 times and then the yellow blink ten times. The problem becomes that it gets very tedious to continue to copy and paste the code, and it eventually becomes impossible to keep track of how many times you have pasted the code in. We need a better way of doing repetitive tasks, like blinking. Luckily there is what is called a “for loop” a for loop will repeat a clause, or a group of commands, or lines of code a specified number of times. The for loop looks like this:

 OK, there is lots going on with this new code, so lets break it down. First,  notice the open and close curly brackets. All of the code or command lines you put between the curly brackets will be the code that is executed in the for loop. You can put as much or as little code as you want in the for loop. Now lets look at the first line that actually initiates the for loop. Inside the parenthesis are the parameters or arguments that define the behavior of the loop. Notice first that we have introduced a new variable, j. Since we do not need this variable in other parts of the program, we make it a “local” variable. That is, we do not declare it at the top of the program, but declare it just when we use it. That is why we have “int j=1”. The int is declaring that we are going to use a new variable called j. Now j=1 is telling the loop to start with a value of j of 1. Then the j<=10 says to continue to loop as long as j is less than or equal to 10. Then after the next semicolon we have j=j+1. This tells the arduino that each time through the loop, increment j by 1. So, inside the parenthesis we are telling the arduino to start looping with j set equal to one, to continue to loop as long as j is less than or equal to 10,  and each time through the loop to add 1 to the value of j.

So, if we want to blink the red LED ten times, it becomes very easy using the following code:

Remember that our goal was to blink the red LED ten times and blink the yelow LED one time.  We need to add a little code so that the LED will blink yellow. This should be done AFTER the for loop.

 WOW, that is a huge improvement over our original code. The for loop makes it much easier to manage things. The one thing that I don’t like about what we did in the code above is that we looped to the constant value of ten. It would be better and smarter to declare a new variable at the top of the program, The new variable could be numRedBlinks. Then in the for loop we would loop until j<=numRedBlinks. Then at the top of the program we could set numRedBlinks to however many times we want the red led to blink.

OK, I have done lots of the work for you in the above example. Now, I want you to write a program where the yellow LED is also controlled inside a for loop. So, you would declare at the top of the program two new variables . . . numRedBlink and numYellowBlink. The program would have a for loop to blink the red LED numRedBlink times, and then blink the yellow LED numYellowBlink times.  Good Luck!

RESOURCES USED IN THIS LESSON:

Arduino Microcontroller: You can get a good deal on the arduino on Amazon. Arduinos are open source and many are cheap chinese knockoffs, so you want to make sure you get an “official” version, which you can at the link above.

Sparkfun Inventor’s Kit: While the bare arduino will get you started, I really suggest getting the Sparkfun Inventor Kit. The projects I will feature in this tutorial set will use the components in this kit, and it is probably cheaper to go ahead and get the kit than to buy the individual components as you go along. The kit is under $100 on Amazon.

32 thoughts on “Arduino Lesson 3: For Loops for Simple LED Circuit”

  1. Great web site great teacher ,i have done the first 5 lessons and i’m very happy. My first working program look like :

    /*This Sketch was write by Daniel P. and inspired by great tutorials with prof. Paul Mc.Whorter
    post at http://www.toptechboy.com
    Turns on and off a LED connected to any digital pin,in my case i use pin 13,
    using the delay() function.

    This example code is in the public domain.

    */
    int red=13; //Declare my red led an integer, int and set to pin 13
    int redOnTime=250; //Declare how long my led will be on and set to 250 millisconds
    int redOffTime=250; //Declare how long my led will be off and set to 250 milliseconds
    int numRedBlink; //Declare a global variable where i store an integer , how many time my led will blinking
    String redMessage=”The Red Led Blinking”; //Declare a string variable

    void setup(){

    pinMode(red,OUTPUT); //Tell Arduino my red led is an OUTPUT
    Serial.begin(9600); //Turn on Serial Port
    }

    void loop(){

    Serial.print(“How Many Times Do You Want The Red Led To Blink ? “);
    while(Serial.available()==0){} //Wait until the user enter an integer
    numRedBlink=Serial.parseInt(); //Assigned a value to numRedBlink
    Serial.println(numRedBlink);
    Serial.println(redMessage);
    for(int j=1;j<=numRedBlink;j++){ //Start my for loop ,where the int j count
    Serial.print(" You are on blink #: ");
    Serial.println(j); //Print the counter
    digitalWrite(red,HIGH); //Turn red led on
    delay(redOnTime); //Keep on my led for redOnTime
    digitalWrite(red,LOW); //Turn red led off
    delay(redOffTime); //Keep off my led for redOffTime
    }
    Serial.println(" ");
    }

    Thanks a lot and keep teaching as.

  2. hello sir..may I ask ,how do we want to stop the loop after one complete cycle? Btw I really appreciate this lesson..Thank You

    1. The void loop continues to loop. It is not something you can stop. If you want to do something only once, put it in the void setup

  3. Hello,

    All worked well with the first part but after the swop to ‘for’ code I’m getting errors. Could you please correct me with what I have done wrong.
    Here is the code…

    int redLEDPin=9; //Declare redLEDPin an int, and set to pin 9
    int yellowLEDPin=10; //Declare yellowLEDPin an int, and set to pin 10
    int redOnTime=100; //Declare redOnTime an int, and set to 250 mseconds
    int redOffTime=900; //Declare redOffTime an int, and set to 250
    int yellowOnTime=900; //Declare yellowOnTime an int, and set to 250
    int yellowOffTime=100; //Declare yellowOffTime an int, and set to 250
    int numRedBlink=5; // number of times to blink red

    void setup() {

    pinMode(redLEDPin, OUTPUT); // Tell Arduino that redLEDPin is an output pin
    pinMode(yellowLEDPin, OUTPUT); //Tell Arduino that yellowLEDPin is an output pin

    }

    void loop () (

    for () (int j=1; j<=numRedBlink; j=j+1 ) { // Start our for loop
    digitalWrite(redLEDPin, HIGH); //Turn red LED on
    delay(redOnTime); //Leave on for redOnTime
    digitalWrite(redLEDPin, LOW); //Turn red LED off
    delay(redOffTime); //Leave off for redOffTime
    }

    digitalWrite(yellowLEDPin, HIGH); //Turn yellow LED on
    delay(yellowOnTime); //Leave on for yellowOnTime
    digitalWrite(yellowLEDPin, LOW); //Turn yellow LED off
    delay(yellowOffTime); //Leave off for yellowOffTime

    )
    Any help will be much appreciated.

    1. Thanks for your reply.
      I corrected it but it still didn’t work. It did correct some of the script but after adding ‘}}’ at the end it now works.
      Here’s the amended script (for anyone who has had similar problems).

      int redLEDPin=9; //Declare redLEDPin an int, and set to pin 9
      int yellowLEDPin=10; //Declare yellowLEDPin an int, and set to pin 10
      int redOnTime=250; //Declare redOnTime an int, and set to 250 mseconds
      int redOffTime=250; //Declare redOffTime an int, and set to 250
      int yellowOnTime=250; //Declare yellowOnTime an int, and set to 250
      int yellowOffTime=250; //Declare yellowOffTime an int, and set to 250

      void setup() {

      pinMode(redLEDPin, OUTPUT); // Tell Arduino that redLEDPin is an output pin
      pinMode(yellowLEDPin, OUTPUT); //Tell Arduino that yellowLEDPin is an output pin
      }

      void loop() {
      for (int j=1; j<=10; j=j+1) {

      //do something cool in this loop

      }

      for (int j=1; j<=10; j=j+1) { // Start our for loop
      digitalWrite(redLEDPin,HIGH); //Turn red LED on
      delay(redOnTime); //Leave on for redOnTime
      digitalWrite(redLEDPin,LOW); //Turn red LED off
      delay(redOffTime); //Leave off for redOffTime
      }}

      I am an absolute beginner and love your tutorials.
      Many thanks for your time and making these lessons public. I am infeed most grateful.

  4. hi i receive this error:
    Arduino: 1.6.1 (Windows 7), Board: “Arduino Uno”

    lesson3.ino:69:1: error: expected unqualified-id before ‘for’

    lesson3.ino:69:15: error: ‘j’ does not name a type

    lesson3.ino:69:22: error: ‘j’ does not name a type

    Error compiling.

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

        1. Hi many apologies. I am totally lost with this code but would like to learn how to make it work. how do I ‘declare’ int counter j?

          1. If you are totally lost, you should probably go back and watch the first two lessons. Make sure to watch the video, as it shows exactly how to do it.

          2. to declare we use int
            so to do a loop, we have to initialize variables first eg int j

            then do

            for(j=0,j<10,j++)
            {

            }
            what it means is j start at 0 then increment till it is less than 10 so altogether loop for 10 times because its start from 0.

        2. Don’t do it that way. If you are declaring a variable dont set it to another variable. If you must set it to something, set it to a constant.

  5. These lessons are superb. Thanks for your time, I am using what I learn from you to help teach my students.

    When technology teaches understanding the world becomes a better place.

  6. Excellent lesson. I had the hardest time wrapping my head around for loops for the longest time, but this made it clear as day. I’m looking forward to sitting through the rest of your videos. Excellent work.

  7. excellent lesson!
    I used to code in BASIC 40 years ago. this example shows the much more efficient looping functionality then the old FOR/NEXT looping in BASIC.
    I like it!
    Thanks
    …..Art

  8. From one teacher to another…Let me say, these are the best lessons on the web for beginning Arduino.

    God Bless you, Brother!

  9. Hello! I have question that i never get a answer to. When you have an LED in your breadboard does it matter where i put the resistor on the LEDs leg? Should it go through the khatod or anode? Some people put it through the khatod other through the anode. So doest it matter which leg? Btw love your videos

  10. Hi, I’m having the same problem as Andy back in August 2015. My for is not changing color and I wonder if tha is causing my error. I am using ver. 1.6.8 with Windows 10.
    Thanks

  11. All was going well with lesson three with this ultra novice. For some reason my for loop doesn’t turn red when typed and I cant get it to work. Also I am not too clear on the curly bracket placement either. I seem to be doing something wrong. Any helpful suggestions?? Really enjoying the lessons so far, but am scared something that looks so easy is causing so much grief with no red colored for when typed. Thanks.

    1. Anybody? I wanna fix this little glitch and keep learning. Thanks and sorry for being so impatient not waiting very long.

      1. I managed to trouble shoot this issue by previous posts and a little bit of experimenting. As suggested at the end of the tutorial I ran another loop (I used I instead of j ) to make the yellow LED behave the same in turn as the red one. It was a very good experience of problem solving and I have a much better understanding loops now.

  12. Thanks a lot that I found you in webpage, otherwise it would be difficult for me to learn operating the arduino. I have received you as my teacher in my heart. Best wishes for you.
    By the way… I actually got to know about arduino when I was finding a way to make an incubator for my little quails. I came to learn that Arduino is a free hardware that can be manipulated to control temperature, humidity and motor.

    Now I am learning programing language and your tutorials are greatly helping me.
    Could you please suggest me any easy way to multi-task in Arduino?
    If I use ‘delay’ in program it seems impossible to execute other works simultaneously. So if I could get a video tutorial/suggestion on multi-tasking in Arduino Uno R3; it would be very helpful for me.

    God Bless You.

  13. can any one tel me why the for loop do not work on my programing. it does not repeat it self. it works like there are no for loop.

  14. for (int j=1; j<=10; j=j+1) { // Start our for loop

    i don't understand , please help me

    i want to led green blink for 10 times and led red for 15 times , please help me

Leave a Reply

Your email address will not be published. Required fields are marked *