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. A simple schematic of the connections would be nice. To you it is easy. I sort of found the connections to the button confusing they way you presented them.

    1. Thanks for the feedback! I’m going to upload schematics, and include schematic screenshots with the new videos so that this is more clear. You’ll see it in the new video later today.

  2. I have been in the electronics field for over 40 years but for the last 6 I have been a supervisor and therefore not up to speed on the latest things. Your sight is great for those that want to learn about what is going on today not 5 years ago. Thanks for your willingness to give of your time and expertise. You also do a great job as an instructor because you cover all points and explain as you go. This is not only good for the newcomer but for those of us that have not been directly involved with design but just repair.

  3. Craig is right on the money. I’m also an old-timer and now I know what all this Arduino stuff is about. Thanks,

  4. Awesome! I recently got an arduino uno for xmas, and these tutorials have been really helpful, so thanks dude!

  5. Hey Jeremy,

    Awesome tutorials, I’ve been looking for something like this for a long time! Now I can actually start playing around with the Arduino Uno :-D

    Thank you all the way from the Canary Islands

  6. Hey Man,

    Love the tutorials, I just finished #1 and am looking to do #2 next.

    Did you know that the product you link to in the parts list for “Pushbutton” is only available in a minimum order quantity of 10,000! Do you have an alternate?

    -Eric

  7. Hey Jeremy,

    Thanks for the great site! I am learning arduino so I can bring some products to the market and your tutorials have been my guiding light.

    Quick issue (and if you don’t have time for this I completely understand)

    In tutorial #2 I have been over the video many times and keep getting a compile error. ‘ledLevel was not declared in this scope.’

    probably a syntax error, but I have no idea what is going wrong. So, I was wondering if 1) you would look at my code and point me to the error, 2) if you would post the text of the codes in your videos so I can work through syntax without bothering you!

    Thanks again,

    Wake Gregg

    int switchPin = 8;
    int ledPin = 11;
    boolean lastButton =LOW;
    boolean currentButton = LOW;
    int ledLevel = 0;

    void setup ()
    {
    pinMode (switchPin, INPUT);
    pinMode (ledPin, OUTPUT);
    }
    boolean debounce (boolean last)
    {
    boolean current = digitalRead (switchPin);
    if (last != current)
    {
    delay(5);
    current = digitalRead(switchPin);
    }
    return current;
    }
    void loop ()
    {
    currentButton = debounce(lastButton);
    if (lastButton ==LOW && currentButton == HIGH)
    {
    ledLevel = ledLevel + 51;
    }
    lastButton = currentButton;

    if (ledLevel > 255) LedLevel = 0;
    analogWrite (ledPin, ledLevel);
    }

    1. I do post all the code. There is a link to download in the post above. See if that works for you. Let me know if you are still having problems.

    2. Jeremy – Fantastic Job! These tutorials are great.
      Portland’s Electric Bike Shop – this language is case-sensitive, so the line

      if (ledLevel > 255) LedLevel = 0;

      is a problem. It should be “ledLevel = 0;” not “LedLevel = 0”

      Hope that helped.
      Mark Petersen

    3. I have found your mystake:

      In your last block you write:
      }
      lastButton = currentButton;
      if (ledLevel > 255) LedLevel = 0;
      analogWrite (ledPin, ledLevel);
      }

      If you can see you wite LedLevel (first L in uppercase) and ledLevel (first l in lowercase), I am not an expert but i have heard that the program is case sensitive.

      Hello from Cartagena, Colombia

  8. Hey dude, great vids, thanks!

    Just to expand on the latching/debounced button thing, how hard would it be to have multiple buttons/LED’s doing this independently? I’m new to this coding stuff and can’t seem to figure out where to start with what I want to do. I can set up multiple buttons controlling multiple LED’s momentarily, and I can do the latching thing like you did in this video with one button/switch, but I can’t work out how to combine it all.

    Cheers

  9. Hey,

    thank you for your great tutorials!
    But there is one thing i dont understand.
    You are using a 1k or 10k ohm resistor, to connect the button to the ground. But why the current runs to the ground through the resistor and not to the digital-arduino-pin?

    1. When the button is unpressed, the arduino pin is connected to gnd through the resistor, so it reads a logic 0. When the button is pressed, current can flow from two possible places, the 5V rail, or gnd through the resistor. The arduino detects a logic 1 when the button is pressed because the current from the 5V rail far outweighs the current that goes to ground, do to the pull down resistor.

      1. Hey, very interesting explanation. I did not get though the last sentence: “…5V rail far outweighs the current that goes to ground, do to the pull down resistor.” Did you mean “due to the pull down resistor”? I am not quite sure that I understand this sentence.
        Best regards,
        Galina

  10. Hi, thanks for ur tutorials. I just wanted to ask what was actually that java com 23 that u used in putting the signals of 1, 0 ,1 etc….

  11. Thanks a ton for this arduino video tutorial series!! These videos have really been helpful for a beginner like me to understand what’s going on. In this video you are using resistors, but I don’t really understand why. Can you link me to a video that provides an explanation of what resistors are used for and when to use them? That would be really helpful. Thanks!

  12. J,

    Cool site and great videos. I’m a ME but I like to tinker with some electrons and code. Thanks for all this cool stuff.

    -SB

  13. I have a problem :( i used yours code – after mine failed (allready @ example 1).. i connected completely the same (used 10k resistor) … hm, the problem is, the led diode is on after i upload code on arduino… then i push the button and it doesn’t happen anything or the led becomes lit a bit stronger! Sometimes LED also blinks without doing anything (i have a feeling like it’s a short circuit or something isn’t connected well) – but i checked it several times, so i’m rly not sure what did i do wrong

  14. @Rock ..!!

    Please check whether the the legs of the switch which you are using are not already short. Actually in the 4 legged switch which JEREMY used in his tutorial – 2 legs are already shorted.

    Solution to your problem – Make the connections on the diagonally opposite legs of the switch ..!!

  15. Great site. Going Biomedical and we are learning Processing and the Arduino. WIll be going throught all youor tutorial. Great teaching method and preparation for all these Tutorial. Old timer as well back to school

  16. Thanks for the code Jeremy, it worked great though I had to make a few changes for it to work in my circuit. By the way, your website videos don’t work that well, there seems to be a buffering problem. The ones on You Tube worked just fine.

  17. GREAT JOB Jeremy.

    I am new to the ARDUINO and learning alot from your videos.

    Thanks for taking tie to teach others like myself.

  18. Hi Jeremy, thanks for the great video!
    I have a question for you or the other readers:

    I want to ad 2 buttons to the circuit. In total 3 buttons.
    They are the input in Pin 14, 15 and 16
    Connected to pins 0, 1 and 2 is a light circuit.

    I want pin 0 to give 5V if I press the button connected to pin 14,
    pin 1 give 5V if I press button connected to 15
    pin 2 give 5V if I press button connected to 16

    I used te code from your movie and coppied it to add more inputs and outputs.
    But it doesn’t work… What am I doing wrong?

    This is the code:

    // INPUTS
    int switch01_Pin = 14;
    int switch02_Pin = 15;
    int switch03_Pin = 16;

    // OUTPUTS
    int wire01_Pin = 0;
    int wire02_Pin = 1;
    int wire03_Pin = 2;

    // VARIABLES
    boolean lastButton = LOW;
    boolean currentButton = LOW;
    boolean wire01_On = false;
    boolean wire02_On = false;
    boolean wire03_On = false;

    // VOID SETUP
    void setup ()
    {
    pinMode(switch01_Pin, INPUT);
    pinMode(switch02_Pin, INPUT);
    pinMode(switch03_Pin, INPUT);
    pinMode(wire01_Pin, OUTPUT);
    pinMode(wire02_Pin, OUTPUT);
    pinMode(wire03_Pin, OUTPUT);
    }
    boolean debounce(boolean last)
    {
    boolean current = digitalRead(switch01_Pin);
    if (last != current);
    boolean current = digitalRead(switch02_Pin);
    if (last != current);
    boolean current = digitalRead(switch03_Pin);
    if (last != current);
    {
    delay(5);
    current = digitalRead(switch01_Pin);
    delay(5);
    current = digitalRead(switch02_Pin);
    delay(5);
    current = digitalRead(switch03_Pin);
    }
    return current;
    }

    // VOID LOOP
    void loop ()
    {
    currentButton = debounce(lastButton);
    if (lastButton == LOW && currentButton == HIGH);
    {
    wire01_ON = !wire01_On;
    wire02_ON = !wire02_On;
    wire03_ON = !wire03_On;
    }
    lastButton = currentButton;
    digitalWrite(wire01_Pin, wire01_On);
    digitalWrite(wire02_Pin, wire02_On);
    digitalWrite(wire03_Pin, wire03_On);
    }

    Thank you for your help!

  19. you didn’t modify the debounce function correctly. By putting “;” after the if statements, you’re making them do nothing. You need to put the content for each if statement within {} like I did in the video.

  20. Yeah! You are right! I remember changing this afterwards, because I thought I forgot them…

    I have thee feeling that there is still something not correct in my code:

    currentButton = debounce(lastButton);
    if (lastButton == LOW && currentButton == HIGH);
    {
    wire01_On = !wire01_On;
    wire02_On = !wire02_On;
    wire03_On = !wire03_On;
    }
    lastButton = currentButton;

    I am debouncing one switch, then toggling all three wires. Is that correct? I want wire01 on or off if I press switch01, wire02 by switch02 and wire03 by switch03. How do I debounce the three switches?

    Thanks!

    1. You need to debounce each one. You could modify the debounce function so that it takes the switch as an argument too, like this:
      boolean debounce(boolean last, int switch)
      {
      boolean current = digitalRead(switch);
      if (last != current)
      {
      delay(5);
      current = digitalRead(switch);
      }
      return current;
      }

      That way, you can call it for each switch, by changing the second argument.

  21. Hi dude,

    I am a serious beginner, so you could expect a very beginner questions from me…what is it when you change from digital input to analog input. what are the differences between those two?

  22. I’m trying something similar to your PWM control of an led, but with a solid state relay hooked up to a standard incandescent household light bulb (57W) that uses AC. Instead of a button, I tried to just show each dimming level for 5 seconds. It doesn’t work out too well, but instead seems to flicker on and off a few times per seconds (as far as my eye can tell). Is it just a bad idea to use PWM to control an AC device? My ultimate goal is to have a toaster oven that is PID temperature controlled so maybe PWM would have better success with a heating element since temperature changes relatively slowly? This is my test code:

    int relayPin = 11;
    int pwmLevel = 0;

    void setup()
    {
    pinMode(relayPin, OUTPUT);
    }

    void loop()
    {
    pwmLevel = pwmLevel + 51;
    if (pwmLevel > 255)
    {
    pwmLevel = 0;
    }
    analogWrite(relayPin, pwmLevel);
    delay(5000);
    }

    1. You shouldn’t try to control an AC line with PWM. It’s not the same as a DC signal, and it won’t work as you expect. Controlling the heating element directly makes more sense.

  23. Currently working on to power the led and manually controlling the led with variable resistor. That part was easy. Im trying to enhance the circuit by adding two pushbuttons which function is to make the led either go dimmer or brighter. any suggestion on the codes and connection?

    1. Hook them up to the arduino, use my debounce code, and poll both buttons in your loop. Adjust variables that control brightness based on button state.

  24. Is there a way to attach multiple LEDs to a single PWM, say if I want to control more LEDs than ports I have? I’m assuming some sort of external chip that could toggle between them.

  25. Is there a particular shift register chip you recommend? I found the 74HCT595 through Google.

    Also, if you have the time I’d love to see a tutorial using one of the chips to control multiple multicolored LEDs!

    Thanks

  26. I’m completely new to any sort of coding that isn’t on a TI-84 or modding Pokemon games. With your videos I’ve learned all the basics of Arduino in a couple hours. THANKS A TON!! a quick question though, the different I.D’s you make for the commands (e.g ledPin, or buttonPin etc.) do those actually matter? can i just make it like “lolPin” and “thatreallylongnamedPin”? if the DO matter, how would i use more than one of the same thing? Thanks again.

    – Turner

  27. Hey Jeremy
    Great work.. Thank you
    I am doing a similar project to this one but using 2 buttons to control led brightness- 1 for up 1 for down.. I am wondering how to debounce more than 1 button in the code – I cannot seem to get it to work…
    Using your code Switch 4 to do this..
    Your help is greatly appreciated,
    Regards
    Rob H

  28. Hi Jeremy I`m having a problem with the following;
    when creating a log file code:

    ile logFile = SD.open(“LOG.csv”, FILE_WRITE);

    if (logFile) {
    logFile.println(“, , ,”);
    String header = “ID, X, Y, Z”;
    logFile.println(header);
    logFile.close();
    Serial.println(header);

    when I verify de entire code appears expected unqualified-id before if, but in your example and many others it is written the same way a nothing happens, why is this ocurring in my sketch?

  29. I got a question… is it possible to use arduino as an interface in sending a signal from lets say VFD display back to PC??

  30. I’m stuck in the second tutorial. I started with basic.
    In basic you have the “gosub” routine.
    I do not therefore see how the “return function” is made up to.
    Does “return current” back to where it started with the name “current”?
    And something comes back into the variable/boolean current?
    And what value is therefore back in place?

    I watched the tutorial over and over again …
    Am I that stupid or…BASICally confused.
    I even looked at the examples on the Arduino webpage.

    In basic this would look like just return.

    I do not doubt your program, but from my BASIC eyes view,
    should it not be return currentButton???
    Because the line says: currentButton = debounce(lastButton);

    Can you help me out and clearify this for me?
    From which point your calling the gosub routine??

    I’m almost bold for plugging all my hairs out.

  31. Following Jeremy Blum’s second tutorial into Arduino
    https://www.jeremyblum.com/2011/01/10/arduino-tutorial-2-now-with-more-blinky-things/

    I’m having a strange blinking behavior on the third example of this tutorial video [LED on-off toogle with debouncer]:
    First I notticed that the moment the script gets loaded into the Arduino, the on-board LED lights up in some blinky pattern that I supposed was some visual confirmation… but the I noticed that some blinking also goes on the plugged LED at a different timing/pattern. I thought that this was because the script used pin 13, so I changed the additional LED to pin 12 and modified the script accordingly and this time set my camera to catch the event but again I’m having blinking in several LEDs.
    Is it only me? The script works well as expected but I want to understand why is this happening because I don’t want this to be a weird bug when I get into more complex scripts.

    I uploaded the video of this to Youtube so you can see what I am talking about.

  32. Hi , i wanted to transfer the push button value to another arduino through xbee by the following code .but it sends 1 when it is pressed only,and keep on sending 0’scan you tell me the solution of this that one time it sends 1 and other time it sends 0.Here is my code..

    #define INPIN 2

    int state = LOW;

    void setup() {
    Serial.begin(9600);

    pinMode(INPIN, INPUT);
    }

    void loop() {
    delay(10);
    int sensorValue = digitalRead(INPIN);
    if(state != sensorValue) {
    state = sensorValue;

    Serial.println(sensorValue, DEC);
    }
    }

  33. Excellent tutorials, thank you very much for putting in the time to explain this material. There’s an amazing amount of education material on the Arduino, and a lot of it is really poorly done. Yours however is excellent.

    I’d love another 10 videos.

    Thanks,

    Greg

  34. hey jeremy, cool video and great tutorials on youtube. i have a project on using a microcontroller for a boost converter and i chose the arduino. can u help me with the codes and schematics

  35. Hey Jeremy.
    Thanks for your awesome tutorials. If you didn’t give me the code I could never figure out how to write the sourcecode. I mean I understand how the code works but I don’t know how to code my new projects properly.I have some experiences using C and C++, but still having a hard time to create the code. Is there any source to help me with programming?

  36. Hey Jeremy,
    I was going through your code and was thinking it over, but for some reason, I cannot figure out how the loop method works when you are making the LED go on and off for each press of the button. In the loop, you have the if statement:
    if (lastbutton == LOW and currentButton == HIGH)
    ledOn = !ledOn;

    Regarding that statement, won’t the situation where lastButton ==HIGH and currentButton == LOW occur when the when the led was on and now is off. Then, ledOn would not change and the LED light would remain constant. Obviously, I am missing something and I would appreciate if you could tell me what I am missing.

    Thanks a lot,
    Matt

  37. Where does the value for’last’ come from when it is used in the line reading (during the debounce part around minute 12 or 13 of the video):

    boolean debounce (boolean last)

    I see where current is defined as = to digitalRead(switchPin) but am unclear how last is defined? So when it says:
    if (last !=current)

    I’m not sure where the value of last comes from to be compared with.
    Thanks,
    Ryan

  38. hi ,im ron from singapore. i am having a problem in my program. i need to use push button to control my servo motor .what i need to acheive , i press my push button once and it need turn 45 degree and second button need turn 90 degree and press third time move 180 degree but i can’t acheive it.
    this is my program please help me ! im in trouble haha.
    #include

    const int servoPin = 8; // The number of the Servo pin

    const int buttonPin = 9; // The number of the Pushbutton pin

    int buttonState = 0; // Variable for reading the pushbutton status

    int directionState = 0; // Variable for reading direction of the servo

    Servo myservo; // Create servo object to control a servo

    int pos = 0; // Variable to store the servo position

    void setup()

    {

    myservo.attach(8); // attaches the servo on pin 8 to the servo

    pinMode(buttonPin, INPUT); // initialize the pushbutton pin as an input

    }

    void loop() {

    buttonState = digitalRead(buttonPin);

    if (directionState == 0){

    if (buttonState == HIGH) {

    directionState = 0;// The direction for the servo is clockwise

    for(pos = 0; pos =1; pos=pos+1)

    {

    myservo.write(pos);

    delay(15);

    }

    }

    }

    }

  39. Hi Jeremy,

    Great tutorials – thanks for putting them together :)

    Quick question about switch3.pde: Why is the digitalWrite to the LED pin outside of the ‘if’? Don’t you only want the LED pin written to if the switch has been pressed? Thought it worth asking you as I’m a complete novice and perhaps I’m missing something.

    Thanks!

  40. Hi.
    i want to make a card(tag)reader and connected it to internet to identify person and involving paypal account . can i use Ardunio and Arduino shild together.or what Arduino you prefer to use.

    thank you

    1. You should be able to do that using the system I show in my RFID tutorial. You’ll need a desktop program (maybe python) to interact with it and connect to the paypal API

  41. Pingback: [Sciguy14] Arduino Tutorial 10: Interrupts and Hardware Debouncing | Ayarafun
  42. Pingback: Learn arduino - From noob to Ninja - video series
  43. Pingback: Binary and Logic

Leave a Reply to Mason 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