BLOG > Tutorial 2 for Arduino: Now with more Blinky Things!

This tutorial was featured on the official Arduino blog on 3/9/2011

That’s right folks, it’s Monday, and the second installment of my arduino tutorial series is here!  I spent the last week in Disney World, but now that I’m back, it’s time to get down to business!  This week, I’ll show you how to read a push button, debounce its input using software, how to create a function in the arduino programming environment, and how to change LED brightness using Pulse Width Modulation (PWM).  If you have no idea what PWM is, or if you are confused about analog and digital signals, go check out my TechBits episode on the topic first!  Don’t forget to go browse the element14 Arduino Group; it’s a great place to post questions, and learn from others!


You can download the files associated with this episode here:

GNU GPL License Distributed under the GNU General Public (Open-Source) License.
Please Attribute and Share-Alike.


187 comments

  1. Hi Jermey,

    The GROUND terminal of my board is not working properly. what actions can be taken to rectify this defect

  2. Hi there Jeremy, I just started reading your book and it’s awesome, but… im having some trouble understanding one thing in these line code:

    currentButton = debounce(lastButton);

    I understand that “currentButton” will be set as “debounce(lastButton)” but what’s is really the function of “lastButton” being on parenthesis as an argument.

      1. Dear Jeremy, referring delay for 5ms to read the “HIGH” state, will that be chances it read “LOW”?

  3. Hi Jeremy, thanks a ton for these posts and the Element 14 sponsored vids on youtube.
    I’m desperately trying to get a button counter to turn on successive banks of LED’s being, rather than stepping up the pulse width to a single LED.
    In my mind it was going to be a “simple” addition of some more pin variables as outputs (not just a single ledPin, but also an ledPin2, ledPin3 etc…. etc… for each “bank” of LED’s being turned on).
    Then I just had to define those integer variables as OUTPUTs, change the incrementation of ledLevel to +1 after each press instead of +51….and put “if” logical checks in the loop to see if the button counter ledLevel was at such and such a count, tun on an additional bank of LED’s…..this time with a digitalWrite to the pin for that bank….instead of the analogWrite used in circuit # 4 of your tutorial 02 here.

    It made perfect sense, it even compiled, but even after trying curly braces in different places to segment the code, I can’t seem to get it to work. The LED banks all just spontaneously turn on, and won’t turn off.

    I’ve seen a lot of button count registers but seem to have a hit a wall with getting the count to equate to a new bank of LED’s switched on with each passing button press….until a final press turns them all off.

    Any ideas?
    Here’s my modified code…from your original…
    /*
    Arduino Tutorials
    Episode 3
    Switch4 Program (pwm)
    Written by: Jeremy Blum
    */

    int switchPin = 2;
    int ledPin = 13;
    int ledPin2 = 12;
    int ledPin3 = 11;

    boolean lastButton = LOW;
    boolean currentButton = LOW;
    int ledLevel = 0;

    void setup()
    {
    pinMode(switchPin, INPUT);
    pinMode(ledPin, OUTPUT);
    pinMode(ledPin2, OUTPUT);
    pinMode(ledPin3, OUTPUT);
    }

    boolean debounce(boolean last)
    {
    boolean current = digitalRead(switchPin);
    if (last != current)
    {
    delay(10);
    current = digitalRead(switchPin);
    }
    return current;
    }

    void loop()
    {
    currentButton = debounce(lastButton);
    if (lastButton == LOW && currentButton == HIGH)
    {
    ledLevel = ledLevel + 1;
    }

    lastButton = currentButton;

    if (ledLevel = 1);
    {
    digitalWrite(ledPin, HIGH);
    }

    if (ledLevel = 2);
    {
    digitalWrite(ledPin2, HIGH);
    }
    if (ledLevel = 3);
    {
    digitalWrite(ledPin3, HIGH);
    }
    if (ledLevel > 3) ledLevel = 0;
    {
    digitalWrite(ledPin, LOW);
    digitalWrite(ledPin2, LOW);
    digitalWrite(ledPin3, LOW);

    }
    }

      1. Still haven’t gotten counter count-up and then reset following the count registry being equal or greater than the limit.

        I plan to retackle it this summer along with better debouncing of switches, which will be important to pair with this project.

        I’ll be sure to post when I do.

  4. Hi Jeremy my Name Is Muriuki Please send me the code for “Tutorial 02 for Arduino: Buttons, PWM, and Functions”

  5. I didnot understand the deboucing code you have written.
    boolean debounce(boolean last). What does this line specify in arduino?
    Also you have declared variables current and last anywhere but used them in debounce code. How is it possible?

    1. FIrstly, current is declared in debounce function only and last is itself an argument of function debounce ,so they can be preety well used in debounce.
      boolean debounce(boolean last) ,this line declares a function boolean ,which has return type boolean i.e, it return either True or False and inside parenthesis argument type is also boolean ,so last can take either True OR False (HIGH or LOW ,0 or 1 all are same).
      About debouncing code ,you better do it practically to understand it completely .Think how it is working according to hardware.still i will try to explain as much possible to make it easy for you.
      setup the hardware,burn the code.done?
      1.as soon as you burn the code ,it starts working .setup function executes only once so the only concern should be what is happening inside loop function .first statement inside loop function is currentbutton=debounce(lastbutton);this calls debounce function and it checks for current state of button with last state ,if there is any change in state of funstion then our program waits for 5ms (time taken by switch to get to the stable state) and then again reads the state of switch and stores it to current ,function returns current to currentbutton inside loop then next statements execute inside loop.currentbutton gets copied to lastbutton.
      2.now loop function again starts over, calls function debounce ,checks for change in switch state.if there is change in state ,then again program waits for 5ms till bouncing of switch stops and it gets stable state.then again current state of switch is read which is returned to currentbutton and again rest of the code inside the loop executes and it goes on same way …..

      Best way is try to understand code while doing it practically on hardware ,press the button keep it pressed look at the code start with loop function and see how debounce funbction return current and now leave the button check again debounce function how it returns current again and how it changes .

  6. Mr jeremy, could you please confirm as to whether the color code for a 220 ohm resistor is red red orange.
    Thank you.

  7. Hey Jeremy ,

    Firstly I would like to thank you for such wonderful lessons on arduino. One thing , as I am very new to electrical engineering stuff, I want to ask why analogWrite in place of digitalWrite while increasing the brightness of the led.

    Also, as I was starting my new project on path planning of a bot , which uses Arduino, I wanted to know about that how can I start with running arduino using Python , because I usually code in python .

  8. Why do you need the ledOn variable in the second program in tutorial 2.
    Can’t we just use lastButton for everything.

  9. Alternative and easier solution for the switch bouncing issue:

    int ledpin=13;
    int switchpin=8;
    int ct=0;
    void setup() {
    pinMode(switchpin,INPUT);
    pinMode(ledpin,OUTPUT);
    }
    void loop() {
    if (digitalRead(switchpin)==HIGH)
    {ct=ct+1;
    delay(200);}
    if((ct!=0) && (ct%2)!=0)
    {digitalWrite(ledpin,HIGH);}
    else
    {digitalWrite(ledpin,LOW);
    }}

  10. Jeremy can you tell me why do we have the last in Boolean debounce(Boolean last); the last variable is not defined anywhere why is it here please tell me I am a beginner

  11. Hi, can somebody answer why do you need the else statement to check what the button was in the previous loop with variable lastButton? This is just turning the lastButton to Low on every loop. it seems to work fine without it, is this for some later logging issue or some kind of continuity issue?
    Thanks

  12. Hi Jeremy, I would like to know the function of the code lastButton = currentButton in the PWM section of the tutorial. Thank You.

  13. I have set up the board, and loaded the program, but is not working as expected. Will you please send me a drawing or illustration of the board and connections? I may be missing somewhere.

  14. Hello Jeremy,
    i just wanted to share that if in the second code you give a delay of few milliseconds at the last, the switch doesn’t bounces or at least appears not to bounce. so i just wanted to know whether it is a appropriate way…..

  15. Hi, Jeremy! I don’t understand why you write “ledOn = false” but no “ledOn = LOW”. I read in the handbook that “digitalWrite” takes only “HIGH/LOW” but not “true/false”. Thank you and sorry for my English!

  16. Hey Jeremy,

    I’m using your code from Switch 3 to try and control LEDs connected to a separate button for each and was wondering if I need to write a separate debounce code for each button (seeing as I need to debounce each button) or is there another way to do this (I’m also trying to add a Keyboard.Write into it as well)?

    I would put my current code up here for help, but no one likes reading a wall of text, so do you know of somewhere I can send it through to or upload it for help?

  17. we can also did it by this way ?
    int btn =8 ;
    const int led = 13;
    boolean btnState = false;
    void setup()
    {
    pinMode(btn,INPUT);
    pinMode(led,OUTPUT);
    }

    void loop()
    {
    if(digitalRead(btn) == HIGH)
    {
    delay(100);
    btnState = !btnState;
    }
    if(btnState)
    {
    digitalWrite(led,HIGH);
    }
    else
    {
    digitalWrite(led,LOW);
    }
    }

  18. Hi Jeremy,

    I would like to request if you can provide a code for this condition:

    i want to complete the cycle – when switch pin is high, the LED output will go on and off for one cycle

    the cycle will repeat only by the next push of the input button

  19. Hi!
    I tested this tutorial made few changes. Added stop button and then i had a problem. How to make Arduino “remember” pwm level what was in use before stop was pressed?
    Thanks.

Leave a Reply to Biindo Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Advertisement