Arduino Basics Handling Multiple States

Поделиться
HTML-код
  • Опубликовано: 6 фев 2025
  • Handling multiple states is one of the keystones of programming. In this example we use one button to cycle through 3 LEDs. This gives us a 4 states (all off, red,green,yellow). By passing the state between variables we can cycles through them with ease. This example uses the button debouncing code that was described in this video:
    • How to debounce a butt...
    ~-~~-~~~-~~-~
    May I suggest: "10 PCB's for two bucks!"
    • 10 PCB's for two bucks!
    ~-~~-~~~-~~-~

Комментарии • 152

  • @jlr3636
    @jlr3636 6 лет назад +5

    Thanks for the clear and concise video. After reading the remarks I’m amazed at the lazy people. You took the time to produce the video, purchased the equipment to produce the video, and put out a video to help other people learn something you already knew. All anyone needs to do is take their own time to re-wright the code as is shown, they MIGHT learn something by doing it themselves. And they MIGHT actually have to take their own time to watch multiple videos from multiple sources and learn how to combine them to produce what they want. They might learn something to help themselves or I guess they could just go to the store and purchase the item (already built) that they are trying to build. “Life is hard, then you die”. Thanks for your time !

    • @learnelectronics
      @learnelectronics  6 лет назад +2

      THANKS

    • @alloycrow917
      @alloycrow917 5 лет назад

      I agree, This has been the best explained video I have seen in regards to both code and hardware setup.
      and the code is not even that long for him to post it, millenials and their instant gratification...

    • @KOAlleyCat
      @KOAlleyCat Год назад

      Yeah, man. That’s exactly how I learn. When I first read the comments I just assumed he didn’t even visually show the code. Then I came to the 3:14 minute mark and the code is right there in front of their faces! Is writing it down really that difficult to some people? 😂

  • @tomassasovsky4412
    @tomassasovsky4412 5 лет назад +48

    #define button 3 //Push button on D3
    #define redLED 5 //red LED on D5
    #define greenLED 6 //green LED on D6
    #define yellowLED 7 //yellow LED on D7
    int state = 0;
    //integer to hold current state
    int old = 0;
    //integer to hold last state
    int buttonPoll = 0;
    //integer to hold button state
    void setup() {
    pinMode(button, INPUT_PULLUP);
    //button as input
    pinMode(redLED, OUTPUT);
    //LEDs as output
    pinMode(greenLED, OUTPUT);
    pinMode(yellowLED, OUTPUT);
    digitalWrite(redLED, LOW);
    //set initial state as off
    digitalWrite(greenLED, LOW);
    //set initial state as off
    digitalWrite(yellowLED, LOW);
    //set initial state as off
    }
    void loop() {

    buttonPoll = digitalRead(button);
    if(buttonPoll == 1){
    delay(50);
    buttonPoll = digitalRead(button);
    if(buttonPoll == 0){
    state = old + 1;
    }}
    else{
    delay(100);
    }
    switch(state){
    case 1:
    digitalWrite(redLED, HIGH);
    digitalWrite(greenLED, LOW);
    digitalWrite(yellowLED, LOW);
    old = state;
    break;
    case 2:
    digitalWrite(redLED, LOW);
    digitalWrite(greenLED, HIGH);
    digitalWrite(yellowLED, LOW);
    old = state;
    break;
    case 3:
    digitalWrite(redLED, LOW);
    digitalWrite(greenLED, LOW);
    digitalWrite(yellowLED, HIGH);
    old = state;
    break;
    default:
    digitalWrite(redLED, LOW);
    digitalWrite(greenLED, LOW);
    digitalWrite(yellowLED, LOW);
    old = 0;
    break;
    }
    }

    • @mrgraememell4526
      @mrgraememell4526 7 месяцев назад

      Very useful tutorial. One change in the in default case - the yellowLED should be set to LOW

    • @tomassasovsky4412
      @tomassasovsky4412 7 месяцев назад

      @@mrgraememell4526 thanks for the code review, man! I just edited the original comment. awesome to see this is still being used

  • @droid1008
    @droid1008 2 года назад +2

    Exactly the explanation I've needed for the past few months to continue with my project!
    Thank you immensely for making this simple.

  • @seditiousmonkeyart
    @seditiousmonkeyart 6 лет назад +6

    Best and simplest explanation and demonstration of debouncing I have found. Thank you for making and sharing this with us. looking forward to more.

  • @casperjuniorviriri7177
    @casperjuniorviriri7177 7 лет назад +2

    This tutorial actually works the best, for a day i wrote the same code over and over again and it wasn't working, jus to realise i was typing "state = old = 1" when it should've been "state = old + 1)....Just goes to show how the smallest mistake can make code non functional.

    • @chbonnici
      @chbonnici 6 лет назад

      Dear Casper please can you send me the code to my email : chbonnici@gmail.com . I checked over and over the code but still cannot get it working and when I compile it compiles OK. Unbelievable but true.

  • @alloycrow917
    @alloycrow917 5 лет назад +7

    Man, best and most organized code. Keep those tutorials coming!! Cheers.

    • @lukass1604
      @lukass1604 4 года назад

      Coming form a programing background, the code isn't clean at all lol

    • @fish9468
      @fish9468 4 года назад

      @@lukass1604 coming from an asskisser background, only assembly is clean B) libtard owned

  • @nathanharding7737
    @nathanharding7737 5 лет назад +6

    Thank you for the awesome video! Also, thank you for not posting the code. This forced me to write/debug my own code, and in the process learn a lot.

  • @Timothy_Osman
    @Timothy_Osman 29 дней назад

    The nano is such an incredible microcontroller i cant say that enough

  • @scottneels2628
    @scottneels2628 3 года назад +1

    Perfect, Thanks for this. I've been trying to get clear on state changes and this finally made it click for me. Go well!

  • @JoxMiguel
    @JoxMiguel 3 года назад

    Muchas Gracias! justo lo que estaba buscando para mi proyecto, Saludos desde México!

  • @chbonnici
    @chbonnici 6 лет назад +3

    Thank you I solved the problem one missing = ALL works perfect. Great explanation

  • @karlcheng_5210
    @karlcheng_5210 3 года назад

    thank you very much!!!! I did search and learn for this effect around few days! And watched your video unexpectedly! I must say I am very new in arduino, however you teach me something in a short term! VERY appreciate!

  • @markdropesr.182
    @markdropesr.182 2 года назад

    Thank you this is what I was looking for to work with my smart car.

  • @tmburns4
    @tmburns4 4 года назад

    Great video, super informative. One request: when showing code on the screen, please zoom in on it so it is more readable on RUclips. Some of us are already watching on small screens. Thank you!

  • @ericr1954
    @ericr1954 4 года назад

    Thank you! Extremely organized and easy to follow code, great work.

  • @RealGenX
    @RealGenX 3 года назад

    Thanks a bunch for this, I’m new to programming and this will definitely help me on a relay project I’m working on!

  • @TheFairytail4ever
    @TheFairytail4ever 4 года назад +1

    This debouncing routine helps me a lot m8 :D cheers!

  • @Arthurk346
    @Arthurk346 5 лет назад +1

    i wish the day i ordered RGB LED's with common anode never existed... but it worked somehow. thanks!

  • @howlround
    @howlround 2 года назад

    You always have the perfect video. Great stuff. Thanks!

  • @dr.mailman
    @dr.mailman Год назад +1

    Thanks, this might have been exactly what I was looking for. Im inexperienced with electronics and was looking for a way to switch states on a timer but I am experienced with coding so this gave me the push in the direction to writing the code to do what Im looking for.

  • @errolsternberg8185
    @errolsternberg8185 4 года назад

    Thank you now i finally understand the button state and why it is done.

  • @tj9382
    @tj9382 4 года назад

    Very nice neat setup and good code layout.

  • @johneagle4384
    @johneagle4384 3 года назад

    Very clear explanation!

  • @TJenga
    @TJenga 2 года назад

    This is almost exactly what I’m trying to do. Now I need to figure out how to add a second button to switch between a different set of lights and continue using button one to switch states. Any hope on you making that video before I figure it out on my own? 😅

  • @s001software9
    @s001software9 4 года назад

    Exactly what I was looking for!! Thank You!

  • @bens423
    @bens423 4 года назад

    This is the video i searched for

  • @RSchef
    @RSchef 9 месяцев назад

    Important concept!

  • @gary1679
    @gary1679 3 года назад

    Finally, I found this video!!!!!!!!!!!!!!!

  • @naboulsikhalid7763
    @naboulsikhalid7763 5 лет назад

    very instructive, clear cristal. wonderfull tutorial. it helped me with a project. thank you for sharing your knowledge.

  • @ricardocruz9066
    @ricardocruz9066 7 лет назад

    I congratulate you, very good job . Hey you can perform an exercise in which you have two buttons and two led to turn on the first and turn off the second at the same time.

  • @habibhabibov4610
    @habibhabibov4610 Год назад

    Hi you are the best really thank you 👏👏👏💪

  • @ADhiman1991
    @ADhiman1991 7 лет назад +2

    Thank you ,this is what i was looking for.

  • @HackTechMW
    @HackTechMW 3 года назад

    Thanks man this is all I wanted😊😊

  • @grudge579
    @grudge579 5 лет назад

    Lovely work. Thanks for the video, it is going to be used for my robot's sensor calibration

  • @pdxfunk
    @pdxfunk 4 года назад

    Super helpful, thank you! Was looking for just this.

  • @karlcheng_5210
    @karlcheng_5210 3 года назад

    is it possible to change the case statement be blink and fade without delay?

  • @RAILWAY_FILMS
    @RAILWAY_FILMS 7 лет назад

    I really enjoyed your video. You do a great job of explaining this sort of thing. Thanks.

  • @v0llk0rnbr0t20
    @v0llk0rnbr0t20 3 года назад

    Yes, this is exactly what I need!!!

  • @melaniewilson-bruneau9079
    @melaniewilson-bruneau9079 3 года назад

    Hello, what would you change to get the following:
    1st button press = LED1
    2nd button press = LED2
    3rd button press = LED1 & LED2
    4th (1st) button press = LED1 (start over again)

  • @aarondsouza1024
    @aarondsouza1024 3 года назад

    That was amazing it helped me out so much thank you very much

  • @mohd.rizanabdulrahim6539
    @mohd.rizanabdulrahim6539 3 года назад

    Ur code is perfect. If I press on and set a timer for e.g. 30 sec, and then it off automatically after 30 sec, what is the code for each case?

  • @sam-lg
    @sam-lg 4 года назад

    This really useful project 👌

  • @Dunalduck
    @Dunalduck 6 лет назад

    Thank you, for a beginner this was great video

  • @faroff4435
    @faroff4435 3 года назад

    You could do the same but with 3 buttons and change state as it is pressed, button1- led1, button2- led2 ... what would be the modification?

  • @buzzbuddi6846
    @buzzbuddi6846 3 года назад

    Hi, how to add timer function?
    I wanna all leds turn on for one second only.

  • @boopeshkumarprabhakaran
    @boopeshkumarprabhakaran 3 года назад

    hi how to make arduino remember the last active led when power failure?

  • @damianrecinski7329
    @damianrecinski7329 4 года назад

    What if button has been pressed and released during 100ms delay? It would not be detected. Another error: if button would be released after checking `if (buttonPoll == 0)` and before `if (buttonPoll == 1)`, then release would not be detected again

  • @umiturgutaswwsa
    @umiturgutaswwsa 3 года назад

    Can anyone help me about my problem?My setup just runs the code on the default mode.I cant switch on states.

  • @topten7064
    @topten7064 5 лет назад +1

    You are really great

  • @BellaSkinUS
    @BellaSkinUS 7 лет назад

    I like it. I would like to know how to add some blinking to the LED's , let's say when red is is on will stay ON for 2 seconds and off for 1 sec, and green ON for 3 seconds and OFF for 0.5 sec, and yellow ON for 4 sec and OFF for 1.5 sec. Every time we push the button each led will have that blinking cycle and finally all of them OFF at the 4th push on the button. Thanks

    • @learnelectronics
      @learnelectronics  7 лет назад

      +Hernan Melgar Personal support is available to patrons. www.patreon.com/learnelectronics

  • @Kinko01765
    @Kinko01765 6 лет назад

    Thank you !!!!!! This video is helping me a lot .

  • @joverstreet24
    @joverstreet24 5 лет назад

    Excellent tutorial.

  • @OutOfNameIdeas2
    @OutOfNameIdeas2 3 года назад

    I need to make this work with the button being on 1v and not 5v. Is this possible? It doesn't work for me.

  • @musaaftabi6269
    @musaaftabi6269 4 года назад

    hello
    i make a project with arduino uno and IRremote and stepper motor .the remote control turn the motor shaft to the right and left. i need a little help with the codes. is it possible to define just one button of remote control to turn the shaft to right and left ???
    how to write the code ?
    i can send the codes i wrote if its needed.

  • @goatelope7539
    @goatelope7539 4 года назад

    Thats awesome!!! To use the same button state code to change color patterns on a neopixel strip, Instead of commanding different pins, i could paste in the rainbow/animation code, right? or is it more complicated than that? I'm new and getting into Cosplay and lighting projects. Thank you

  • @everythingcool491
    @everythingcool491 4 года назад

    Hi, thanskfor the tutorial, ive followed it to a tee, but it never lights up the first LED,?

  • @DeepSpaceAlien
    @DeepSpaceAlien 5 лет назад +1

    How can you add delays between the leds going on or off in 1 case

  • @qzorn4440
    @qzorn4440 3 года назад

    nice video, i have an Arduino Pro Micro setup for keyboard emulation and it works great on the bench. however, when it is hooked up on a machine with a DC motor and not connected to the arduino, and with the one pro input connected to common to act as a switch input. the F11 keyboard command keeps strobing. any ideas before making my changes? thanks a lot...:)

  • @pacmangsxr750
    @pacmangsxr750 Год назад

    Thank you

  • @alejandraurena3533
    @alejandraurena3533 4 года назад

    Thank you! This really helped me

  • @marcodoria5635
    @marcodoria5635 5 лет назад

    Obrigado por ajudar um amigo brasileiro!

  • @chagadunudev9583
    @chagadunudev9583 3 года назад

    Thanks heaps!!!!

  • @reubeyonduty
    @reubeyonduty 6 лет назад

    Ok, I set this up with a button and changed a few things... Instead of turning one led on at a time, I have them all turn on one at a time then shut off. That was easy enough to do. Now, I want to make that exact thing happen with an rc transmitter and receiver. I have the pwm signals on the channel 2 stick set so that 1 is neutral, you push it up, it reads a 0, if you push it down it reads a 2. So in theory I want to push up on the joystick, it turns on the first led, push up again it turns on the second, and push up a 3rd time it turns on the last led. Push up a 4th time it shuts them all off. If I push down on the joystick its puts power to an output pin. Take you finger off the joystick power stops. Can you help me. Ive been trying to do this for days! TIA, any help would be appreciated!

  • @rahmatramadhana93
    @rahmatramadhana93 4 года назад

    why not always in case 1? will change to case 2 randomly evaery time

  • @dekaezyofficial9740
    @dekaezyofficial9740 7 лет назад

    thank you for sharing, i have tested your sketch and succeeded, but there is a little problem, yellow led flame is not like bright red and green light, i have replaced the led with new one and change output pin, but it did not work, am i miss something?

  • @leonbakeroot3291
    @leonbakeroot3291 4 года назад

    How can I put different delays on each LED and still have it to go to the next button if I press?

  • @hansifansi
    @hansifansi 6 лет назад +1

    Thank you for you video. This helped me a lot. I have a few questions. 1. Is it possible to add a function that makes a long press of the button the code to jump to defult? And 2. Is it possible to add a second button and for both buttons to control their own switch cases (button 1 for case 1,2 and 3, and button 2 for case 4, 5 and 6)?

  • @bagusadikin7416
    @bagusadikin7416 5 лет назад

    thanks really helpful, and i was thinking can we use Interrupts function to replace the button? to replace it HIGH and LOW signal?

  • @AmateurInventor
    @AmateurInventor 5 лет назад

    Good job buddy

  • @akokJ619
    @akokJ619 3 года назад

    for some reason say if I hae 6 leds and 2 toggle switch and I want to divide 3 leds each for each switch, I put the same code but it doesn't work for one set. Please help me out

    • @scottneels2628
      @scottneels2628 3 года назад

      Toggle switches are not momentary so you have no rising edge like what happens when he lifts his finger off the button.

  • @Design.Studio-DS
    @Design.Studio-DS 7 лет назад

    Very useful tutorial. its perfect. but i would like to know how to do something after press the button. i mean, if i need to flash RED bulb with 1 sec delay after first press and so on.. i tried to do it. but if i do so, next bulb not response after second press of the button. could you please explain me how to use this type code for handle multiple programs just using one button press. if it is possible, it will be able to use as a menu selector & will be v.usefull to automation.

  • @xsoul6838
    @xsoul6838 6 лет назад +2

    i need button
    Handling Multiple States with if else ?

  • @santoshbabu517
    @santoshbabu517 4 года назад

    can we turn back LED on to the stste in which it was after poer failure

  • @MattG101680
    @MattG101680 4 года назад

    Hey, Im trying to program a switch like this to just toggle between basically 2 lights, how would you code it to just be 2 lights and not have a full off except when first powered up?

  • @jimmywang7862
    @jimmywang7862 6 лет назад

    nice tutorial just what i was looking for. I do have on question in fact, can i place the digitalwrite in each case with other codes like analog write?

  • @noureldinabdelrhman2860
    @noureldinabdelrhman2860 4 года назад

    thank you so much

  • @DocAlexLego
    @DocAlexLego 5 лет назад

    I may use this for a Star Trek Phaser Type 2 Cobra Head Display where Each LED must stay on like this
    -=OFF
    *=ON
    **------
    ********
    This requires multiplex and I'm hoping if this can work by telling the arudino to keep the last LED on and then light the other and so on - if I hold the other button it resets the phaser or move down if I press it.
    But will these States work in the multiplex format?

  • @antoniogutierrez3254
    @antoniogutierrez3254 6 лет назад +1

    Hello, amazing project, how must i change the code if i want to use a Hall effect sensor instead of a button to have the same beheavour of the leds? thank you very much!

    • @bagusadikin7416
      @bagusadikin7416 5 лет назад

      have you already made it work? im intended too, to use digital Interupts to replace the button so the LED can be controlled by a signal or sensor

  • @ssdwang7338
    @ssdwang7338 4 года назад

    how to change it to serial?

  • @jamesanderton903
    @jamesanderton903 6 лет назад

    Thanks, well explained.

  • @electron4me
    @electron4me 3 года назад

    Good Afternoon.
    Thank you for a great tutorial.
    I'm wondering if you could advise me how to tailor it to my requirements? I'm using an hall switch to switch the states.
    the important pins in my example are one and two in each case. This case is turning on and off an electromagnet but has it is
    case one is turning the magnet on and case 2 off. What I'm looking for is case 1 to turn on and then turn off before case 2 happens and then the same in case two. I've been on it all day and cant get it to do this. I'd really be grateful for some advice.
    Many thanks.
    switch (state) {
    case 1:
    digitalWrite(magnet_pin_one, HIGH);
    digitalWrite(magnet_pin_two, LOW);
    digitalWrite(dial_pin_three, LOW);
    digitalWrite(dial_pin_four, HIGH);
    old = state;
    break;
    case 2:

    digitalWrite(magnet_pin_one, HIGH);
    digitalWrite(magnet_pin_two, LOW);
    digitalWrite(dial_pin_three, HIGH);
    digitalWrite(dial_pin_four, LOW);
    old = state;

  • @RCBros2000
    @RCBros2000 5 лет назад

    im using this to run an LED tracer loop with different settings. i noticed with this code it will only change modes if i press the button between the time the last led goes off and the first led fires. is there any way around this?

  • @WiktorErikAndersson
    @WiktorErikAndersson 4 года назад

    I have a problem.. I wrote a code using this format! Works great but.. in case 2 I want to ad a delay that will turn of one LED after 3 sec! And I know how to do that but the arduino loops that delay 3 times for some reason! Any idea?

    • @PrashantPatil-zg4cz
      @PrashantPatil-zg4cz 3 года назад

      If we use delay cmd then its not switching to next case.

  • @patracy
    @patracy 5 лет назад

    Thanks for the basics of this. How would I define this to cycle backwards in the same pattern but reverse instead of off. Is that just basically adding more cases that invert the pattern until we wrap up at the first state?

  • @VictorRodriguez-cg1kg
    @VictorRodriguez-cg1kg 4 года назад

    Hi, hope you can help me out. Basically I want to do the following: I want to control two LEDs separately using one single push button, example if push the button once LED 1 will lit up and immediately turn off (momentarily) and if I push the button again now LED 2 will lit up and turn off immediately, the cycle should repeat. Thanks.

    • @learnelectronics
      @learnelectronics  4 года назад

      Look at this video: ruclips.net/video/PKwE10Aigac/видео.html
      You will have to adjust the code to make it momentary but it will do what you want.

    • @VictorRodriguez-cg1kg
      @VictorRodriguez-cg1kg 4 года назад

      @@learnelectronics thank you

  • @Ifa-097
    @Ifa-097 6 лет назад

    i have problem with case 3, after case 3 running, lamp red is on, actually i not push button

  • @deanbrothersfilms
    @deanbrothersfilms 4 года назад

    Would it be possible to swap out the button with a mini photocell so different levels of brightness would switch on one of the 3 lights?

  • @sintamaritobrbakkara3072
    @sintamaritobrbakkara3072 4 года назад

    are there the coding in pdf?

  • @georgechambers3197
    @georgechambers3197 7 лет назад +2

    This is a very good explanation of states. Would it be possible to have the code and a wiring diagram with these videos? I've programmed in C a lot but it was many years ago. Thanks for the video.

  • @cghkjhjkhjhvfghc
    @cghkjhjkhjhvfghc 7 лет назад +3

    nice thanks..100th thumbs up.

  • @mohitarora8754
    @mohitarora8754 6 лет назад

    If you press three times continuously then third LED will Glow or not??

  • @kushalgarg3366
    @kushalgarg3366 6 лет назад

    Can anyone give me an explanation of why we put a delay of 100 ms in the else part of after the debouncing routine?

  • @santoshbabu517
    @santoshbabu517 4 года назад

    can i have the code to test

  • @chbonnici
    @chbonnici 6 лет назад

    How to introduce a timer of 10sec so when button is pressed the led switch of after 10 sec without loosing the sequence

  • @juangil6925
    @juangil6925 6 лет назад

    Hi. Very/extremely useful. My respects. Thank you for sharing!.
    2 questions, if you could please advise me. If I need to go back from case 3 to 1, instead of going OFF all 3 lights, I guess I should make a case 4 with Case 1 statements, and at the end, write OLD = 1, and then, it should keep cycling, right?. Second question... to apply this for a servo, I guess that I should load SERVO library, and state the angle I want for the position of servo ( servo.write(angle) ), and I should be able to cycle trough different pre-programmed positions with the click of the button. (ej_ 0, 90, 180, 0, 90, 180..). Off course, after selecting the angle outputs to the proper/same PWM Output.. Do you think it might work? I have the project on mind, and getting all components in a week, so, I am gathering all information I can, before I can do some testing.
    Juan

    • @learnelectronics
      @learnelectronics  6 лет назад

      Yes you are on the right track in both cases. You will definitely need the servo library for your second question.

    • @juangil6925
      @juangil6925 6 лет назад

      I will work on this base once I get all the components. Thanks for sharing!!

  • @TheFlybyman
    @TheFlybyman 6 лет назад

    Thanks !!!!!!!!

  • @shayaflynn8695
    @shayaflynn8695 7 лет назад

    Can you do delay on the cases??

  • @brunocolman53
    @brunocolman53 4 года назад

    could you make me available or code please?

  • @MrDickales
    @MrDickales 5 лет назад

    I typed your code exactly but consistently get "expected unqualified-id before '/' token....am i missing something?

    • @Emilsteixner
      @Emilsteixner 5 лет назад

      i had that too... i just deleted it but now i get: expected primary-expression before ',' token

  • @weerobot
    @weerobot Год назад

    Cool...