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. jeremy, i need to use both Keypad and client_A function at the same time. Kindly help me through this.

    #include
    #include
    #include
    #include
    #include
    #include
    #include
    #include
    #include “EmonLib.h”

    // Include Emon Library
    EnergyMonitor emon1;

    ////////////////////////////////////////////////////// LCD ///////////////////////////////////////////////////
    LiquidCrystal lcd(A4, A5 ,5, 4, 3, 2);

    ////////////////////////////////////////////////////// ETHER /////////////////////////////////////////////////

    byte mac[] = {
    0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
    IPAddress ip(192,168,1,177); //Client IP
    IPAddress server(192,168,1,170); //Server IP
    EthernetClient client;

    /////////////////////////////////////////////////////// KEYPAD //////////////////////////////////////////////
    const byte ROWS = 2; // Two rows
    const byte COLS = 3; // Three columns
    char keys[ROWS][COLS] = {
    {
    ‘1’,’2′,’3′ }
    ,
    {
    ‘4’,’5′,’6′ }
    ,
    };
    byte rowPins[ROWS] = {
    7, 6}; //Keypad Rows
    byte colPins[COLS] = {
    A3, 9, 8 }; //Keypad Colums
    Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

    ////////////////////////////////////////////////////VARIABLE DECLARATTION//////////////////////////////////////

    int a=0,b=0,c=0,d=0,count=0,count1=0,count2=0,count3=0,k1,bed1,l1,g1;
    int k, bed, l ,g;

    ///////////////////////////////////////////////////////INPUTS/OUTPUTS//////////////////////////////////////////

    int led1 = (13); //Relay 1st Room
    int led2 = (A0); //Relay 2nd Room
    int led3 = (A1); //Relay 3rd Room
    //int led4 = (A3); //Relay 4th Room
    int buttonInt=0;

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////
    /////////////////// SETUP //////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////

    void setup()
    {
    lcd.begin(16, 2);
    //int tickEvent = t.every(2000, Client_A);

    //Timer1.initialize(100000);
    attachInterrupt(buttonInt, keypad, RISING );
    Serial.begin(9600);

    pinMode(led1, OUTPUT);
    pinMode(led2, OUTPUT);
    pinMode(led3, OUTPUT);
    //pinMode(led4, OUTPUT);
    delay (1000);
    lcd.print(“Welcome…”);
    delay(1000);
    lcd.clear();

    lcd.print(“Set Priorities”);
    delay(2000);
    lcd.clear();
    Ethernet.begin(mac, ip);

    if (client.connect(server, 4400))
    {

    lcd.clear();

    Serial.println(“connected”);
    }
    else
    {
    Serial.println(“connection failed”);
    }

    /*lcd.print(“pres 1 fr kitchn”);
    delay(2000);
    lcd.clear();

    lcd.print(“pres 2 fr bed”);
    delay(2000);
    lcd.clear();

    lcd.print(“pres 3 fr longue”);
    delay(2000);
    lcd.clear();

    lcd.print(“pres 4 fr grage”);
    delay(2000);
    lcd.clear();

    */

    }

    char key;

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////// MAIN LOOP ///////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////

    void loop()
    {

    // for (int i=0; i<5000; i++)
    keypad();
    {
    Client_A();
    }
    }
    // keypad function calling

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////// PRIORITIES //////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////

    void keypad()
    {

    key = kpd.getKey();

    if(key!=NO_KEY)
    {

    if(key=='6')
    {
    lcd.clear();
    lcd.print("Again");
    Serial.print("Again");
    a=0;
    b=0;
    c=0;
    d=0;
    count=0;
    count1=0;
    count2=0;
    count3=0;
    }
    else
    if((key=='1') && (b<1) && (c<1) && (d<1) && (a==0) && (count%2==0))
    {
    lcd.clear();
    a=1;
    b=0;
    c=0;
    d=0;
    count++;
    }

    else
    if((key=='2') && (a<1) && (c<1) && (d<1) && (b==0) && (count1%2==0))
    {
    lcd.clear();
    a=0;
    b=1;
    c=0;
    d=0;
    count1++;

    }
    else
    if((key=='3') && (a<1) && (b<1) && (d<1) && (c==0) && (count2%2==0))
    {
    lcd.clear();
    a=0;
    b=0;
    c=1;
    d=0;
    count2++;
    }

    else
    if((key=='4') && (a<1) && (b<1) && (c0 && bed>0 && l>0 && g>0)
    {

    if (led1==HIGH || led2==1023 || led3==1023 || led4==1023)
    {
    switching2();
    }

    if(k==4)
    {
    digitalWrite(led1, HIGH);
    }

    if(bed==4)
    {
    analogWrite(led2, 1023);
    }

    if(l==4)
    {
    analogWrite(led3, 1023);
    }

    if(g==4)
    {
    analogWrite(led4, 1023);
    }
    }
    }

    void switching2()
    {
    if ((led1==HIGH && led2==1023)||(led1==HIGH && led3==1023)||(led1==HIGH && led4==1023)||(led3==1023 && led2==1023)||(led4==1023 && led2==1023)||(led3==HIGH && led4==1023))
    {
    switching3();
    }
    if(k==3)
    {
    digitalWrite(led1, HIGH);
    }

    if(bed==3)
    {
    analogWrite(led2, 1023);
    }

    if(l==3)
    {
    analogWrite(led3, 1023);
    }

    if(g==3)
    {
    analogWrite(led4, 1023);
    }
    }

    void switching3()
    {

    if(led1==HIGH && led2==1023 && led3==1023 || led1==HIGH && led2==1023 && led4==1023 || led2==1023 && led4==1023 && led3==1023 || led1==HIGH && led4==1023 && led3==1023)
    {
    switching4();
    }
    if(k==2)
    {
    digitalWrite(led1, HIGH);
    }

    if(bed==2)
    {
    analogWrite(led2, 1023);
    }

    if(l==2)
    {
    analogWrite(led3, 1023);
    }

    if(g==2)
    {
    analogWrite(led4, 1023);
    }
    }

    void switching4()
    {
    if(k==1)
    {
    digitalWrite(led1, HIGH);
    }

    if(bed==1)
    {
    analogWrite(led2, 1023);
    }

    if(l==1)
    {
    analogWrite(led3, 1023);
    }

    if(g==1)
    {
    analogWrite(led4, 1023);
    }
    }

    void unswitching()
    {
    if(led1==HIGH && led2==1023 && led3==1023 || led1==HIGH && led2==1023 && led4==1023 || led2==1023 && led4==1023 && led3==1023 || led1==HIGH && led4==1023 && led3==1023)
    {
    unswitching2();
    }
    if(k==1)
    {
    digitalWrite(led1, LOW);
    }

    if(bed==1)
    {
    analogWrite(led2, 0);
    }

    if(l==1)
    {
    analogWrite(led3, 0);
    }

    if(g==1)
    {
    analogWrite(led4, 0);
    }
    }

    void unswitching2()
    {

    if(led1==HIGH && led2==1023 || led1==HIGH && led3==1023 || led1==HIGH && led4==1023 || led3==1023 && led2==1023 || led4==1023 && led2==1023 || led3==HIGH && led4==1023)
    {
    unswitching3();
    }
    if(k==2)
    {
    digitalWrite(led1, LOW);
    }

    if(bed==2)
    {
    analogWrite(led2, 0);
    }

    if(l==2)
    {
    analogWrite(led3, 0);
    }

    if(g==2)
    {
    analogWrite(led4, 0);
    }
    }

    void unswitching3()
    {
    if (led1==HIGH || led2==1023 || led3==1023 || led4==1023)
    {
    unswitching4();
    }

    if(k==3)
    {
    digitalWrite(led1, LOW);
    }

    if(bed==3)
    {
    analogWrite(led2, 0);
    }

    if(l==3)
    {
    analogWrite(led3, 0);
    }

    if(g==3)
    {
    analogWrite(led4, 0);
    }
    }

    void unswitching4()
    {
    if(k==4)
    {
    digitalWrite(led1, 0);
    }

    if(bed==4)
    {
    analogWrite(led2, 0);
    }

    if(l==4)
    {
    analogWrite(led3, 0);
    }

    if(g==4)
    {
    analogWrite(led4, 0);
    }
    }*/

    void Client_A()
    {

    double Irms = emon1.calcIrms(1480); //Value of current from current transformer
    char Ir[60];
    delay (1000);
    if (client.available()>0)
    {
    char rec = client.read();
    Serial.print(rec);
    switch (rec)
    {
    case ‘I’:
    client.write(“1–1–“);
    client.flush();
    break;
    case ‘D’:
    dtostrf(Irms, 1, 2, Ir);
    client.write(Ir);
    client.flush ();
    break;
    delay(1000);
    case ‘0’:
    // switching(); //switching starts here
    client.flush ();
    }

    }

    if (!client.connected())
    {
    Serial.println();
    lcd.println(“disconnecting.”);
    client.stop();
    while(true);
    }

    }

    1. I saw the Tutorial 02 for Arduino: Buttons, PWM, and Functions and it was perfect.
      But I still have a problem.
      When I press the button the LED stay´s on, but I want the LED blinking. How can I do that?

    2. I saw the Tutorial 02 for Arduino: Buttons, PWM, and Functions and it was perfect.
      But I still have a problem.
      When I press the button the LED stay´s on, but I want the LED blinking. How can I do that?

  2. Hello Jeremy! Could you please explain why boolean function (boolean debounce(boolean last)) written before void loop? Does it jump out of (void loop) when we push button?

  3. How does the Boolean function make the light stay on and stay off corresponding with the switch as compared to the earlier demonstration. didn’t quite get the boolean function.

  4. Hi Jermy,

    I have a question about the debounce function you made in this tutorial.

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

    debounce is the name of the function?
    current is the output of the function?
    last is the input?

    so in this tutorial last will be changed out with lastButton and current will be replaced by currentButton when you use the function in the program?

    What does actual the return command do?

    thanks for any answer, regards Pelle

  5. Hi Jeremy,

    Thank you for you Arduino tutorials it really help me and it is wonderful. Is it posibble if you could do a tutorial;

    – Use a sensor to create a disco light controller

    Cheers,

  6. Hi Jeremy,

    I have followed Tutorial 2 and seem to have a problem. My code looks to be exactly the same as yours however when I press the pushbutton nothing happens. My only experience is Tutorial 1 so far so might be missing something but can’t seem to find it!

  7. Hello Jeremy.

    Love your tutorials thanks alot for them !

    I have a question about the Debounce code.

    How do you multiply if for more than 1 switch ?

    fx. i have 4 switch and each switch should control an LED. input on 8-9-10-11 and output on 2-3-4-5.

    seems like everything i’ve tried to dublicate and rewrite the code won’t work. Can you offer a helping hand ? Thanks a bunch.

    P.S tried google without much help. Been trying to fix this for 4 hours now , driving me crazy ! :)

  8. Can anyone see the problem with my code? I’ve tried switching pins and everything to see if maybe the arduino was flawed, but the outcome is always the same: as soon as I load up the program, the led turns on. Pressing the button doesn’t do anything for it.

    int switchPin = 8;
    int ledPin = 12;
    boolean lastButton = LOW;
    boolean currentButton = LOW;
    boolean ledOn = false;

    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);
    {
    ledOn=!ledOn;
    }
    lastButton = currentButton;
    digitalWrite(ledPin, ledOn);
    }

  9. Hi Jeremy,

    Thanks so much for producing these tutes. I’ve learned more about button->led control with this one than I have in about a two weeks of painful dead end or carbon copy google directed research. I’m an arduino infant of about 2 months so things are still falling into place for me and this pool of knowledge will definitely help push me forward a little faster.

    I am hoping you might be able to point me in the right direction with something i’m trying to achieve. I’d like to manipulate the PWM to have the LED flash at a defined interval, constantly, after the button changes state and then have the LED return to an always LOW state after the buttons state changes again.

    I have attempted to combine the ever present “button switch” and “blink without delay” codes which are readily available but have had no luck so far in achieving anything more than a solid LOW or HIGH LED state.

    Your code achieves a similar outcome but in a slightly different way to the others i’ve seen in that you’re applying the use of PWM and, from what I understand of your code, may allow for the type of outcome i’m aiming for.

    Do you think you might be able to help out. I’ll hack at your code and see what I can do right away and hope that you’ll respond soon. If I nail it then I’ll post what i’ve done here if that’s all good with you.

    Thanks again.

    1. You should implement a state machine to accomplish this. Use a variable to track button presses. Trigger a timer interrupt every x millisecond and have it toggle the LED depending on the value of that state variable.

  10. I wanna do the same code of switching ON/OFF a led but with a push button, but i want to use several leds and push buttons say 3. So should I do the exact same things 3 times or is there another way to optimize the code? the part the confusing me is the debouncing part, I dunno if I should define 2 more “current” variables for each button of what?!

    Thanks :)

    1. No sara u need not do that , all u need is to get three jumper wires and put them into the arduino pins which u have to assign as input .Then in the code reproduce the condition ex-if (digitalRead(button)==HIGH) and then write the led number one by one . Yes no doubt you have to write this if statement three times . I am not sure but may be u can go for SWITCH statement if u wanna use more then 3 suppose 10 led .I did this code in a different way and it is here, i havent used the debouncing function ,may be this can help u.

      int led =13;
      int sw=2;
      int b=1;

      void setup ()
      {
      pinMode (led, OUTPUT);
      pinMode (sw, INPUT);

      }

      void loop ()
      {
      if (digitalRead(sw)== HIGH)
      {
      if (b==1)
      {
      digitalWrite (led, HIGH);
      b=1-b;
      delay(500);
      }
      else
      {
      digitalWrite (led, LOW);
      b=1;
      delay(500);
      }
      }
      }
      Let me know if i was of any help to u.

  11. Hi Jeremy!
    First of all thank you for the tutorials, they are really awesome!
    I have a doubt concerning the if condition. You say if (lastButton == LOW && currentButton == HIGH), then ledOn !=ledOn. I tried to remove the condition lastButton==LOW to see what could have happened and the debounce stopped working. Point is that I do not understand how checking the lastButton influences the code. I mean, why the currentButton condition is not sufficient? And how is the code behaviour modified by putting both the last and currentButton condition instead of using the only currentButton one?
    Thank you a lot!

  12. Hi jeremy,

    I am building a radiation detector. so using an arduino uno to record the voltage output from two different detectors on a sd card. I need the sd card to record the voltages vs time for each one of the detectors on the same card but on separately. could you help me with the code as i have just started using the system a day ago and an a mechanical engineering student. your help would be very much appreciated as i have very basic programming knowledge. thank you

    yaz

  13. Hey Jeremy great tutorial but my led is not lighting brightly ,its quite dim……Could it be that I have connected it wrongly ?

  14. Hey, I suck at coding. Is there a way I could make this control two or three LEDs independently of each other? Thanks.

  15. Plz Jeremy can u let me know for what that pull down resistor is used .Let me elaborate my doubt.In case button is pressed the input pin 8 will read high and in case button is left pin will read low .then for what purpose 10k resistor is being used.If u r talking abt any excess current then its not possible since when button is left the circuit is open and 0 current will flow .Plz help me out of this as my college teachers are unable to tell this .

  16. But sir when the button is unpressed the circuit is open ,and in digital 1 means high and 0 means low . So when circuit is open cant we just say that the input pin is getting no voltage (0 voltage),and thus the input pin will read low,then the pull down resistor doesnt matter if i am correct

    1. No. An unconnected pin is not the same as a pin that is connected to ground. Voltage is a measure of potential, it is not a measure of whether or not electricity is flowing (that’s current). A digital input reads the potential on the pin. If it does not have a path to ground, it could fluctuate between high and low due to transient noise since there is no reference.

  17. Ok thanks a lot sir. I have one more doubt that what would happen if the 10 k resistor is removed.I dont think there will be any problem in the unpressed state of button if resistor is removed.And in pressed condition the incoming current will have two paths , one two the input pin and other to the ground .I think that half of the current will go into each branch since no resistor is there.Thanks once again.

  18. Sir plz reply . I have one more doubt that what would happen if the 10 k resistor is removed.I dont think there will be any problem in the unpressed state of button if resistor is removed.And in pressed condition the incoming current will have two paths , one two the input pin and other to the ground .I think that half of the current will go into each branch since no resistor is there.Thanks once again.

  19. You should probably use a resistor with an LED on pin 13. I looked at the schematic for the Arduino Uno and the trace runs directly from pin 19 on the microcontroller to the rail contact labeled pin 13. It also runs to the resistor/LED, but the pin 13 you’re connecting to is before the resistor.

  20. The ledPin was not declared in this scope is what it says and I wrote this pinMode(ledPin, OUTPUT); is there a problem ot did I write it wrong

  21. considering that the switchPin goes low after the switch is pressed everytime(it pops up right?). shouldnt the following program be sufficient?

    int switchPin;
    int ledPin;
    boolean ledOn=LOW;
    void setup()
    {
    pinMode(ledPin,OUTPUT);
    pinMode(switchPin,INPUT);
    }

    void loop()
    {
    if(digitalRead(switchPin)==HIGH)
    {
    ledOn=!ledOn;
    }
    digitalWrite(ledPin,ledOn);
    }

    1. Nope. While the switch is held down (even for a moment), the LED will flicker because the if-statement will execute over and over again, thus toggling the LED.

  22. Hi Jeremy,
    Thank you for your Tutorials with out people like your self the world would not move forward !
    Please can you help me ? I have recently brought a Arduino Mega 2560 I am following your tutorials but it appears (as with all the projects iv picked to do) there is some difference needed in the code between the Arduino Uno and the Mega 2560. Things work great on pin 13 but once leaving pin 13 and assigning a new pin all joy ends.
    Please can you spare a minute to point me in the correct directing of how I can change the code to accommodate My Mega 2560 for future projects as well as this Tutorial.
    Best regards
    Sam Lawrece

      1. hi Erik,thanks for the link. I know Alexander when I did a workshop in Bayreuth and he satrted this project. Great idea and we had a lot of fun with this crazy beats. We sent his impulses over to a modified computer game (check out Victor Morales! ! !) where some of his characters where dancing to the groove.

  23. i just need to clarify this concept.

    when the switch is pressed the switchpin gets assigned as assigned high.
    however due to bouncing of the switch,the value of switchpin goes wrong.
    thus we decide to read its value with a delay.

    am i right here?

  24. on writing current = digitalRead(switchpin)…we detect the value of switchpin.

    and then we verify if it has been switched on by : if(last!=current)

    however we read the value again after 5ms.

    i believe this is done because the void loop iterates in a very small time.
    therefore even before the position of the switch is intentionally changed, the value current will get reassigned to a wrong value in the next iteration due bouncing.

    am i correct here?

  25. Hi can you help me with mine I used your code and instead of having the led deafault off it is on and when I click the button it turns off.

  26. Hi
    I have the same problem like eko who posted on december 10, 2013 . instead of having the led deafault off it is on and when I click the button it turns off and blue led on arduino turns off.

    “Hi can you help me with mine I used your code and instead of having the led deafault off it is on and when I click the button it turns off.”

    1. I think that I did not put a high enough resistor so when I hovered my hand over the sensor, it over loaded the circuit and the arduino automatically shut it off. I have an arduino that I suspect is from china but I dont thnk it should make a difference

  27. Hi,

    I also didn’t have the appropriate resistor. Today I will try with the resistor mentioned in the tutorial and I’ll let you know the result. But I think that the only difference will be in the intensity of the LED light.

  28. Newbie here. I can’t seem to get the pull down resistor to work correctly for the first circuit in this tutorial. The code looks OK, but the led turns on when my hand gets anywhere near the wires or the switch itself. I thought I understood that the pull down resistor took care of this specific issue. I have tried up to 40k ohm as a pull down value with essentially no change. Very discouraging to fail on the first very basic circuit. I plan to try even higher resistance tomorrow, but cannot understand why 10k wouldn’t work based upon all that I have read. If anyone can please help me, I’d appreciate it. Thank you.

  29. First of all, your tutorials are awesome. I watched 2nd tutorial but it finished at 18:21 and i could not complete sketch. I would appreciate if you can either provide link to full video or a copy of sketch to control led brightness. Thanks in advance.

      1. Manoj-

        I apologize, but I was incorrect earlier. There actually was a YouTube problem that prevented the video from completing. It has now been resolved.

  30. I just bought your book and am going through chapter 2. I have question about connection between pin#2 and the +5V rail (page 30, also this tutorial). When the button is pressed there is essentially a piece of wire connecting +5V to pin2 which is set to LOW. It seems like a short circuit. There is nothing to limit the current. Could you please explain why it is not burning the microprocessor up.

  31. I am very raw in this kind of industry. Please excuse me if I ask a dumb question.
    I saw earlier in the post that someone ask if it is possible to make the light blink with the LED level.
    So, first click level 51 blink, second click level +51 blink, until 5th click and it will turn off.
    I have tried many ways, but still have no answer. Please help… this is frustrating :(:(

    1. I am just catching up with this.
      You can use the loop like this:

      void loop()
      {
      currentButton = debounce(lastButton);
      if (lastButton == LOW && currentButton == HIGH)
      {
      ledLevel = ledLevel + 51; // increment the ledLevel as normal
      analogWrite(ledPin, 0); // turn the LED off to start the blink
      delay(100); // wait 0.1 of a second so it blinks
      analogWrite(ledPin,ledLevel); // update the LED with the new ledLevel to end the blink
      }
      lastButton = currentButton;

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

      }

      Update the delay value to the length of blink that you prefer.

    1. This was a YouTube video transcoding problem. This problem has been fixed, and the full video should now play. Let me know if you experience further problems.

  32. I have tried three different major web browsers, Firefox 28, IE8, Google Chrome, and in every single one the video is cut short at 18:21 instead of playing to 20:09. Jeremy, I have seen that u had said that this problem was caused by a problem in the web browser, but I have now tried this video in three different browsers & in all three of the video is cut short at the exact same place. I watch videos on YouTube regularly & have never had this problem any place but on your video. How can I watch the rest of the video so I can finish it?

    Danon

  33. for those who dont get the end basically what he is going to do
    if (level>=255)
    level=0;

    analogWrite(led,level);//analog write writes to the ~

  34. Love the tutorials! bought the book and making my way through your lessons.

    but as a newbie i didn’t understand how the global value of currentbutton got set to zero at
    the end if the code says

    lastButton = currentButton;

    1. just got it…….. never mind good sir.. i didn’t realize the code was trying to always go back to a LOW state for both the lastButton and currentButton…… thx and good day :)

  35. great videos Jeremy, keep it up
    Your video in tutorial two cuts of the lats moment of code
    what comes after

    if (ledLevil > 255 lev

    1. This was a YouTube video transcoding problem. This problem has been fixed, and the full video should now play. Let me know if you experience further problems.

  36. Hi Jeremy, Im a technology teacher and we are moving from PBasic STAMP to arduino and your videos have been a godsend, so firstly thank you! I have a problem though due to my lack of knowledge and experience using it. Ive used this video to understand keeping an output on and debounce, but im now trying to modify the sketch youve created to have 2 switches and 2 LEDs – each switch controlling different LED. My idea was that my pupils would create a queueing system for a theme park – a theme park employee would press a button and a red stop light would go on, then press another for a green go light. Ive got myself REALLY confused – can you help me please?

    1. So glad you’ve liked the videos! You might also like my book for your class – a lot of teachers use it: http://www.exploringarduino.com

      You can modify the debounce function to operate on a particular button pin:
      boolean debounce(boolean last, int btn_pin)
      {
      boolean current = digitalRead(btn_pin);
      if (last != current)
      {
      delay(5);
      current = digitalRead(btn_pin);
      }
      return current;
      }

      At the top of your program, you’ll need to define states for each button:
      //Button Debouncing & Knob Tracking Variables
      boolean A_button_last = LOW;
      boolean A_button_current = LOW;
      boolean B_button_last = LOW;
      boolean B_button_current = LOW;

      In your loop, simply add a check for each button:
      //A Button Debouncing
      A_button_current = debounce(A_button_last, A_button_pin);
      if (A_button_current == HIGH && A_button_last == LOW)
      {
      //Do something
      }
      A_button_last = A_button_current;

      //B Button Debouncing
      B_button_current = debounce(B_button_last, B_button_pin);
      if (B_button_current == HIGH && B_button_last == LOW)
      {
      //Do something
      }
      B_button_last = B_button_current;

  37. Hello, Jeremy!
    I’ve watched your tutorial and I almost did what I wanted to but now my main question is how to do this brightness control when holding the button? And my other question is when i do the hold button brightness control how to make the code to change the direction of fading when I release the button and hold it again?

  38. Hi Jeremy. First let me say thanks for your great tutorials. I am newbie with arduino and your video tutorials are very helpfull for me. I’v tried to running my 3 phase inverter circuit with this main_code below and it worked properly.
    float port1 = 11;
    float port2 = 10;
    float port3 = 9;
    int f = 50;
    void setup() {
    Serial.begin(9600);
    pinMode(port1, OUTPUT);
    pinMode(port2, OUTPUT);
    pinMode(port3, OUTPUT);
    }
    void loop() {
    //1st session
    analogWrite(port1, 255);
    analogWrite(port2, 0);
    analogWrite(port3, 255);
    Serial.println(“1 0 1”);
    delay(1/(6*f));
    //2nd session
    analogWrite(port1, 255);
    analogWrite(port2, 0);
    analogWrite(port3, 0);
    Serial.println(“1 0 0”);
    delay(1/(6*f));
    //3rd session
    analogWrite(port1, 255);
    analogWrite(port2, 255);
    analogWrite(port3, 0);
    Serial.println(“1 1 0”);
    delay(1/(6*f));
    //4th session
    analogWrite(port1, 0);
    analogWrite(port2, 255);
    analogWrite(port3, 0);
    Serial.println(“0 1 0”);
    delay(1/(6*f));
    //5th session
    analogWrite(port1, 0);
    analogWrite(port2, 255);
    analogWrite(port3, 255);
    Serial.println(“0 1 1”);
    delay(1/(6*f));
    //6th session
    analogWrite(port1, 0);
    analogWrite(port2, 0);
    analogWrite(port3, 255);
    Serial.println(“0 0 1”);
    delay(1/(6*f));
    }
    The problem came when I tried to apply it with lcd and switch buttons for more frequencies variant (30Hz, 40Hz, and 50Hz). I modified my code and it didn’t work (my induction motor didn’t rotate). This is my modified code :
    #include
    float PWM1 = 11;
    float PWM2 = 10;
    float PWM3 = 9;
    int f = 50;
    const int PIN_A0 = A0;
    const int PIN_A1 = A1;
    const int PIN_A2 = A2;
    const int PIN_RS = 2;
    const int PIN_E = 3;
    const int PIN_DB4 = 4;
    const int PIN_DB5 = 5;
    const int PIN_DB6 = 7;
    const int PIN_DB7 = 8;
    LiquidCrystal lcd(2, 3, 4, 5, 7, 8);
    void setup() {
    pinMode(PWM1, OUTPUT);
    pinMode(PWM2, OUTPUT);
    pinMode(PWM3, OUTPUT);
    pinMode(PIN_A0, INPUT_PULLUP);
    pinMode(PIN_A1, INPUT_PULLUP);
    pinMode(PIN_A2, INPUT_PULLUP);
    lcd.begin(16, 2);
    Serial.begin(9600);
    }
    void loop() {
    int TOMBOL1 = digitalRead(PIN_A0);
    int TOMBOL2 = digitalRead(PIN_A1);
    int TOMBOL3 = digitalRead(PIN_A2);
    if(TOMBOL1 == LOW && TOMBOL2 == HIGH && TOMBOL3 == HIGH){
    lcd.clear();
    lcd.print(“3_PHASE INVERTER”);
    lcd.setCursor(0, 1);
    lcd.print(“Freq = 50Hz”);
    frequency50();
    }
    else if(TOMBOL1 == HIGH && TOMBOL2 == LOW && TOMBOL3 == HIGH){
    lcd.clear();
    lcd.print(“3_PHASE INVERTER”);
    lcd.setCursor(0, 1);
    lcd.print(“Freq = 40Hz”);
    frequency40();
    }
    else if(TOMBOL1 == HIGH && TOMBOL2 == HIGH && TOMBOL3 == LOW){
    lcd.clear();
    lcd.print(“3_PHASE INVERTER”);
    lcd.setCursor(0, 1);
    lcd.print(“Freq = 30Hz”);
    frequency30();
    }
    else{
    lcd.clear();
    lcd.print(“3_PHASE INVERTER”);
    lcd.setCursor(0, 1);
    lcd.print(“Standby Mode”);
    Serial.println(“Standby”);
    delay(1000);
    }
    }
    void frequency50() {
    //1st session (101)
    analogWrite(PWM1, 255);
    analogWrite(PWM2, 0);
    analogWrite(PWM3, 255);
    delay(1/(6*f));
    //2nd session (100)
    analogWrite(PWM1, 255);
    analogWrite(PWM2, 0);
    analogWrite(PWM3, 0);
    delay(1/(6*f));
    //3rd session (110)
    analogWrite(PWM1, 255);
    analogWrite(PWM2, 255);
    analogWrite(PWM3, 0);
    delay(1/(6*f));
    //4th session (010)
    analogWrite(PWM1, 0);
    analogWrite(PWM2, 255);
    analogWrite(PWM3, 0);
    delay(1/(6*f));
    //5th session (011)
    analogWrite(PWM1, 0);
    analogWrite(PWM2, 255);
    analogWrite(PWM3, 255);
    delay(1/(6*f));
    //6th session (001)
    analogWrite(PWM1, 0);
    analogWrite(PWM2, 0);
    analogWrite(PWM3, 255);
    delay(1/(6*f));
    Serial.print(“50Hz”);
    }
    void frequency40() {
    //1st session (101)
    analogWrite(PWM1, 204);
    analogWrite(PWM2, 0);
    analogWrite(PWM3, 204);
    delay(1/(6*f));
    //2nd session (100)
    analogWrite(PWM1, 204);
    analogWrite(PWM2, 0);
    analogWrite(PWM3, 0);
    delay(1/(6*f));
    //3rd session (110)
    analogWrite(PWM1, 204);
    analogWrite(PWM2, 204);
    analogWrite(PWM3, 0);
    delay(1/(6*f));
    //4th session (010)
    analogWrite(PWM1, 0);
    analogWrite(PWM2, 204);
    analogWrite(PWM3, 0);
    delay(1/(6*f));
    //5th session (011)
    analogWrite(PWM1, 0);
    analogWrite(PWM2, 204);
    analogWrite(PWM3, 204);
    delay(1/(6*f));
    //6th session (001)
    analogWrite(PWM1, 0);
    analogWrite(PWM2, 0);
    analogWrite(PWM3, 204);
    delay(1/(6*f));
    Serial.print(“40Hz”);
    }
    void frequency30() {
    //1st session (101)
    analogWrite(PWM1, 153);
    analogWrite(PWM2, 0);
    analogWrite(PWM3, 153);
    delay(1/(6*f));
    //2nd session (100)
    analogWrite(PWM1, 153);
    analogWrite(PWM2, 0);
    analogWrite(PWM3, 0);
    delay(1/(6*f));
    //3rd session (110)
    analogWrite(PWM1, 153);
    analogWrite(PWM2, 153);
    analogWrite(PWM3, 0);
    delay(1/(6*f));
    //4th session (010)
    analogWrite(PWM1, 0);
    analogWrite(PWM2, 153);
    analogWrite(PWM3, 0);
    delay(1/(6*f));
    //5th session (011)
    analogWrite(PWM1, 0);
    analogWrite(PWM2, 153);
    analogWrite(PWM3, 153);
    delay(1/(6*f));
    //6th session (001)
    analogWrite(PWM1, 0);
    analogWrite(PWM2, 0);
    analogWrite(PWM3, 153);
    delay(1/(6*f));
    Serial.print(“30Hz”);
    }
    For more information I’v tried to running my project only with main_code + lcd and it also didn’t work. Shoud I lessen 6th session pwm with processing time for lcd listing? (I used lcd QC1602A v2.0). Please help me solve this problem. Thank you. Regards, Tiara.

  39. Do we have to re-read the switch state if we already got it from the if statement?

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

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