Arduino Tutorial 28: Using a Pushbutton as a Toggle Switch

  Рет қаралды 299,870

Paul McWhorter

Paul McWhorter

Күн бұрын

Пікірлер: 1 100
@northadventure5654
@northadventure5654 5 жыл бұрын
please don't stop after lesson 68! this is so awesome! You are a very good teacher, and there is no one out there like you :D
@tatereinke5166
@tatereinke5166 5 жыл бұрын
North Adventure on video away from greatness
@srinivasyalala1767
@srinivasyalala1767 5 жыл бұрын
Are there videos till 68? I see those videos are as Private (from 43 to 68) and cannot watch them. Please confirm.
@parulpari7346
@parulpari7346 4 жыл бұрын
Yeah
@vitustillebeck4965
@vitustillebeck4965 4 жыл бұрын
He hearted the comment. must mean he just might.
@jaythebay8425
@jaythebay8425 2 жыл бұрын
I agree
@johnvincentjimar8257
@johnvincentjimar8257 2 жыл бұрын
You sir, are the Organic Chemistry Tutor of Arduino. I always go to your videos if I want to continue in learning arduino. Great teacher, love to see more of your videos.
@sebastiannunez4878
@sebastiannunez4878 2 жыл бұрын
lmao this is so accurate
@destinyokwong2099
@destinyokwong2099 Ай бұрын
Soo accurate 😂😂
@jasonengblom2993
@jasonengblom2993 5 жыл бұрын
Loving the series. Drinking beer though, kids and wife are asleep and I'm geeking out in the garage.
@JoeMakaFloe
@JoeMakaFloe 4 жыл бұрын
Sounds like a nice life
@karlgross877
@karlgross877 4 жыл бұрын
I've finished 28 lessons in 4 days and have completed all the homework and lessons including this one. I retired from teaching jr high coding and robotics. We never got into programming Arduino and I always wanted to, so I bought an Ellego and Vilros kit and when they arrived, I started on your lessons and I am having a blast.
@aisssboudi
@aisssboudi 8 ай бұрын
Wow how 😮😮
@erwinvelasquez9018
@erwinvelasquez9018 3 жыл бұрын
As a professional programmer, I thought I could do this on my 1st trial. I finally got it to work (after trying hundreds of times, with sips of coffee, and believing holding my breath will help) when I found out that delaying the loop was my only solution. I had doubts that what I did wasn't the best way of doing it. And then I saw it at 18:42 that explained what I was missing. And now I can't sleep because of the coffee :) Nevertheless, I finally felt the true satisfaction of saying "BOOOOOM!"
@enriqueeenriquez2180
@enriqueeenriquez2180 2 жыл бұрын
i forgot to mention in my previous comment, that your code is simple, elegant and clever and very important, validated. You kept the button pressed on to ensure it will not change, simple but effective validation.. WELL DONE!!!!
@paulmcwhorter
@paulmcwhorter 2 жыл бұрын
I appreciate that!
@hughpatterson1480
@hughpatterson1480 3 жыл бұрын
I started out wanting to get a Technicians license for Ham Radio. Flash forward two years later and I have an extra class license, I went back to school to become certified in IoT, just so I could build my own SDR radio. I now teach Arduino and and Raspberry Pi classes to teenagers. I built an electronics lab in my house as well. I decided to work through all your videos because I recommend them to anyone wishing to learn this type of material. My teaching has greatly improved due to your videos. I am so glad that you explain the math and get students to try things on their own. I came up with a similar sketch (although I prefer to call it code) when trying to do it on my own. I'm currently working on a self driving robot car based on the Arduino platform. I could do this stuff all day and night! Thanks for the great lessons!
@stevenfinken5835
@stevenfinken5835 3 жыл бұрын
I have been watching the series (old as well as the new and improved) repeatedly. Here is the thing for me. If you listen once, you heard it...if you follow along...you copied it...if you do it on your own after the previous, you remembered it...but, if you can create from what you have done previously, you have gained experience and knowledge, therefore...you have learned. I have LEARNED things by reviewing and practicing via your lessons. The things I have taken from your lessons is far more than I learned from dozens of books. For this I thank you, and ask that you continue to keep it simple and speak in "English" vs. speaking in trueNerd (bumpy text used there just for you). Keep up the good work!
@travisrichardson5366
@travisrichardson5366 5 жыл бұрын
Have to admit, this one stumped me. Thanks for walking us through it.
@muhammadtamim451
@muhammadtamim451 3 жыл бұрын
I tried to think in different strategies to make a toggle switch, such as, if it was possible to count the number of pressing the button, then it was possible to switch between the even and odd numbers. However, at last I went through this excellent lecture and learned how to make toggle switch! Thank you!
@muhammadtamim451
@muhammadtamim451 3 жыл бұрын
int buttonPin=2; int LEDPin=4; int dt=300; int buttonState=1; int j=0; void setup() { pinMode(buttonPin,INPUT); pinMode(LEDPin,OUTPUT); } void loop() { buttonState=digitalRead(buttonPin); if(buttonState==0) { j=j+1; } if(j==1) { delay(dt); digitalWrite(LEDPin,HIGH); } if(j==2) { delay(dt); digitalWrite(LEDPin,LOW); j=0; } }
@muhammadtamim451
@muhammadtamim451 3 жыл бұрын
al'hamdulillāh it's working!
@wannabefunnyman
@wannabefunnyman Жыл бұрын
I have to admit that this one completely kicked my butt. I completely overthought it.
@destinyokwong2099
@destinyokwong2099 Ай бұрын
Same 😂
@sourishthakral
@sourishthakral Жыл бұрын
Hello Mr. Paul, I am a student in middle school but I have to really admit ur lessons are superb & the best thing I have seen that you are also teaching the lessons of raspberry pi & raspberry pi pico. but the main motive of commenting you now is that I've already figured out how to make the pushbutton a toggle one, you just have to write this code :- if (digitalRead(buttonPin)==0){ while (digitalRead(buttonPin)==0){} digitalWrite(LEDPin, HIGH); } else if (digitalRead(buttonPin)==1){ while (digitalRead(buttonPin)==1){} digitalWrite(LEDPin, LOW); } This code will definately work.
@samueltheprogrammer6145
@samueltheprogrammer6145 Жыл бұрын
I don't think this code will work for a Toggle Switch, let me explain why. When you press the button the Arduino terminator will go into the if statement "if (digitalRead(buttonPin)==0)" and then the Arduino terminator goes into the while loop "while (digitalRead(buttonPin)==0)" and stays in there until we stop pressing the button, after we are done with pressing the button the Arduino terminator goes to the following line of code which is turning on the LED and then the Arduino terminator gets out of the if statement and then it goes into the else if statement because we are not pressing the button, and then the Arduino terminator goes into the while loop and stays in there until we press the button and then it gets out of the while loop, and the Arduino terminator turns off the LED and then it gets out of the if else statement, and this is where the problem is, sins we are pressing the button now the Arduino terminator will go into if (digitalRead(buttonPin)==0) again and goes into the while loop and after we stop pressing the button we will turn on the LED again. I hope now you can see what the problem is. The problem is that the LED will always be on when you are not pressing the button, which to me is not a Toggle Switch. I hope that makes sense to you. Samuel
@kageshirou
@kageshirou 3 жыл бұрын
I've been looking at the code over and over again and it's amazing how efficient the code is. It's quite confusing at first but I am starting to understand why it works. Many thanks for showing how to use a pushbutton as a toggle switch!
@sumerukoirala
@sumerukoirala 2 ай бұрын
I managed to do the same thing on my own but my initial design was wrong: I did the switch on the 1-to-0 transition instead of the 0-to-1 transition. Using that transition made it easy to work with the one-push toggle scenario, but it made it harder to solve for the "hold" button scenario. Watching this video, all I did was tweak the condition in the first "if" statement and now it works flawlessly. While I have you here Paul, I just wanted to say the following: After many years of sustaining soccer-related injuries, I decided to call it quits and pursue something that wouldn't give me knee problems and concussions. I'm glad I discovered your videos! I love and appreciate your approach of diving into theories before "putting hands to keyboard". Being able to apply the concepts I learned back in high-school has brought back a lot of good memories from then, and reminded me why I loved Physics and Math back then. Things were quite different, of course. We didn't have breadboards at the time. We had perfboards, and needed to skin off the coating on copper wires to set up our circuits(not fun!). We also didn't have arduino, so I relied on my friend (a python wiz) to set up the software from scratch. To this day, I have no idea how he did it. We've certainly come a long way since then. All this to say: thank you, Paul! edit: I also agree with your take on coffee (iced, black, and no sugar)
@Puckatr0n
@Puckatr0n 2 жыл бұрын
I attempted this on my own, and got as far as assigning an independent tracker - in my case I used a boolean. What I did not think of was using && , so I kept falling down, cycling through random states. I also did not think of placing a small delay in the loop to make things a little cleaner; that was a very useful lesson. I then watched through and, although I wasn't able to work through it alone, the lesson afterwards made a lot more sense for having at least tried! Thanks Paul!
@thefierceninja2557
@thefierceninja2557 3 жыл бұрын
Honestly, toggle switches are the bane of my existence as I have always had issues with making them in both programs and videogames, and it's really annoying too because I have made very complex logic systems and made flight control chips using logic gates in games like Scrap Mechanic but I couldn't make a toggle switch, but now I finally found a way that works for all scenarios thanks to this video. Amazing teaching Paul!
@libbytardalo2071
@libbytardalo2071 4 жыл бұрын
I was lost. You had to 'baby step' me through this one and that's okay. I'm here to learn. And you sir, are a teacher.
@TheRaptor1967
@TheRaptor1967 4 жыл бұрын
Nailed it! Gotta admit, took me a 'while'. 4 whiles to be exact. //Toggle Button using SPMA bushbutton switch int LEDPin=8, buttonPin=12; void setup() { pinMode(LEDPin,OUTPUT); pinMode(buttonPin,INPUT); } void loop() { while (digitalRead(buttonPin)==0) {} //wait until button is pressed. (ButtonPressed == 1) digitalWrite(LEDPin,HIGH); //Turn the LED ON. while (digitalRead(buttonPin)==1) {} //Do nothing (wait for them to release the button} //When we get here, the button has been pressed and released. Next do almost the same as above to turn the LED OFF. while (digitalRead(buttonPin)==0) {} //Wait until button is pressed again. (ButtonPressed == 1) digitalWrite(LEDPin,LOW); //Turn the LED OFF. while (digitalRead(buttonPin)==1) {} //Do nothing (wait for them to release the button} } I switched around the + and - on the switch circuit so that open button = 0 and pressed button = 1 (just more logical to me). I also didn't need to add any delays to my switch as it operated perfectly. Addendum: If I press the switch kinda sideways, then yes. It misbehaves a little. Its a cheap switch, so if I'm not careful the switch suffers from the jitters, but I can live with that for the purposes of learning. Also playing with the code above can get you the result on release, but I prefer to have a result on the press of a button (example keyboard).
@mikemanny1533
@mikemanny1533 4 жыл бұрын
Hi, Paul...got to be honest with you, I couldn't work this one out by myself! The problemo was a tad confusing to solve, Old Bean, and after many cups of tea and a whole lotta head scratching and coding errors, I gave up and admitted defeat. The answer to the problem was even harder than I had imagined, so it was a good job that you went on to explain how to overcome this particular problem. Thanks again from across the pond....hope all's well over there with you and family, what with all this Coronavirus malarky. Stay in...stay safe...and stay "switched on".....pardon the pun. Regards....the Grumpy Limey.
@nahuel3256
@nahuel3256 4 жыл бұрын
I was not able to do it by myself, but I saw the light when you mentioned that we should consider the previous logic state and the actual logic state of the button!!! That was a great insight!! Your videos are fabulous!!!
@Rabidius
@Rabidius 2 жыл бұрын
I was able to use your tutorial to turn an ultrasonic sensor into a switch whenever it read a value under a certain number. Thank you so much for making the tutorials you do, you explain them very well and cover a lot of very useful things!
@souljr.
@souljr. 9 ай бұрын
I was definitely mistaken by the appeared simplicity of the homework. I then fell into my bad habit trap of overthinking the absolute hell out the problem. Gave up and felt quite silly when I came and saw the answer. I'm happy you gave us this assignment, it seems to have gotten most people thinking quite critically! You are truly one of the most amazing teachers I've ever had the pleasure of studying under (even though not in a typical sense).
@alanoestacado
@alanoestacado 5 жыл бұрын
Hey Paul, I'm really enjoying your new Arduino series. Please keep the lessons coming. I can tell you are a great teacher and wished you had been my high school science teacher many years ago. I often feel like I am back in high school science class during the sessions. This was the most challenging exercise to date. Took me a couple of tries to dust off enough brain cells to reach a solution. I always try to complete the lesson before watching your solution. BTW, I am using parts of your series as inspiration in teaching my six year old grandson about electronics. He loves working with the Arduino.
@evanbudd649
@evanbudd649 3 жыл бұрын
It took me longer than I thought it would. I had to leave it alone for a while and come back to it. I remembered dealing with "lead edge" and "lag edge" signals when troubleshooting a different problem which led me to a similar solution, but as others have said, yours was more efficient. Awesome challenge! I was tempted to give up because it seemed like the solution should be so obvious. Glad I worked it out myself. Thanks for the great videos.
@paulmcwhorter
@paulmcwhorter 3 жыл бұрын
This is a classic programming problem, and one much harder than you would expect. Glad you understand it now
@nortetrading3136
@nortetrading3136 5 жыл бұрын
18:04 is the funniest part on this series yet! Thanks Paul!
@russellford366
@russellford366 2 жыл бұрын
Anyone else get preoccupied with code that they have written and never think of all the new things you're going to need for the new one? I'm going to start erasing all of what i've written before starting one of these "projects". Awesome job Paul!!! I'm trying to change my career path and these videos as well as this arduino are making learning to code SO much easier!!!!!
@patrickdelvisohopkins
@patrickdelvisohopkins 4 жыл бұрын
Hi Paul! Your Arduino tutorials are amazing. Your teaching approach is "most excellent" and inspirational! I tried this tutorial and solved it with a while loop and two if statements. It was a great feeling to achieve this on my own. Keep up the good work, sir! Thanks again!
@laxmanrao4554
@laxmanrao4554 4 жыл бұрын
Many thanks again Paul. I am just loving these awesome lessons! ❤️ I made an addition to the task for myself. Led will be on on every 3rd release of push button. Codes below: Variables int ledPin=2; int buttonPin=4; int buttonOld=1; int buttonNew; int ledState=0; int dt=500; Void setup(){ Serial.begin(9600); pinMode(ledPin,OUTPUT); pinMode(buttonPin, INPUT); // I AM POWERING THE BUTTONPIN USING A 5V VOLTAGE OUTPUT SLOT IN ARDUINO. void loop(){ buttonNew=digitalRead(buttonPin); Serial.println(buttonNew); if(buttonOld==1 && buttonNew==0){ if(ledState==0){ digitalWrite(ledPin,LOW); ledState=1; buttonOld=buttonNew; } } if(buttonOld==0 && buttonNew==1){ if(ledState==1){ digitalWrite(ledPin,LOW); ledState=2; buttonOld=buttonNew; } } if(buttonOld==1 && buttonNew==0){ if(ledState==2){ digitalWrite(ledPin,LOW); ledState=3; buttonOld=buttonNew; } } if(buttonOld==0 && buttonNew==1){ if(ledState==3){ digitalWrite(ledPin,LOW); ledState=4; buttonOld=buttonNew; } } if(buttonOld==1 && buttonNew==0){ if(ledState==4){ digitalWrite(ledPin,LOW); ledState=5; buttonOld=buttonNew; } } if(buttonOld==0 && buttonNew==1){ if(ledState==5){ digitalWrite(ledPin, HIGH); delay(dt); ledState=0; } buttonOld=buttonNew; }
@Caisstuff
@Caisstuff 4 жыл бұрын
I've been binge-watching these tutorials lately, ever since 2015, I've been trying to figure language out but couldn't at least until now, You made this very easy, and I'm finally understanding how it works, most importantly remembering it, it's hard to remember some things when you have a learning disability, so tysm for making this easy.
@tretty07
@tretty07 4 жыл бұрын
I couldn't figure out the coding on my own and had to see your code, then I had to watch the video 3 times to understand when the condition, "if(buttonOld ==0 && buttonNew==1)" became true, then the light literally turned on and I was able to understand. I am learning so much from you, keep up these most excellent tutorial videos.
@rebeccahare897
@rebeccahare897 4 жыл бұрын
Great video series, thanks very much Paul. I came at this problem in a slightly different way: since the LED modes are binary (at least in this scenario), if you do a button counter (i++ [or j++]), you can then write an "if" statement to check if it is an even number - LOW if even, HIGH if odd. This also gives an advantage of being able to count the number of times the LED has been on & times button has been pressed (if you add a Serial.print!).
@426F6F
@426F6F Жыл бұрын
That's pretty much how mine worked too, but instead, I made 'x += 1;'. When x == 1, the light turns on, then after the next iteration when 'x==2', the light turns off and in the same block I put 'x = 0;' to reset it. It was a pretty simple way to code it.
@yusielrodriguez4153
@yusielrodriguez4153 9 ай бұрын
This one, took me more time than I am used to solving the assignments. But finally, with logic, I could achieve it. I AM A LEGEND AGAIN. Thank you, teacher, for bringing this type of enriching content
@paulmcwhorter
@paulmcwhorter 8 ай бұрын
LEGEND!
@Ikke-xd4nl
@Ikke-xd4nl 4 жыл бұрын
Got this exercise suprisingly quick tbh but did it in a different way, I read the value of the buttonPin and when it's pressed I use a while loop to wait until the button is released again to then switch the state of the LED. This uses less variables (no old/new) and makes it a bit easier to understand in my opinion. Still very interesting to see how you did it! Discovering multiple ways to solve a problem is the best way to learn and really get a solid understanding of solving problems on your own. I only recently got a kit and even though I have some programming experience in Python I'm quite new to electronics and racing through the vids right now.
@msmnutech2814
@msmnutech2814 4 жыл бұрын
I'm similar to you. Programming experience with little to no electronics experience. I also solved it the same way as you did. Check it button pushed, if it is, set the LED on, then wait for it to be released. When released, wait for it to be pushed again, when its pushed a second time, set the LED off and wait for it to be released again. when its released, let the program end so you start at the top again. I'm enjoying the combination of electronics and programming.
@lvessen
@lvessen 2 жыл бұрын
Thanks, this worked for me too.
@manuellomote
@manuellomote Жыл бұрын
Your comment has everything I was going to say 😊
@dcplett1
@dcplett1 9 ай бұрын
This is my first comment, firstly have never enjoyed such Epic content like what you are creating here. I have never gotten so excited to learn before! I was up till 1am trying to figure this one out. Ended up going to bed thinking about this toggle switch. When I woke up this morning I just lay in bed thinking of what it could be. I grabbed a pen and paper and started writing out the code, I had in my head. I managed to get it to work perfectly using while and if statements. Thank you for these videos!
@paulmcwhorter
@paulmcwhorter 9 ай бұрын
Glad you enjoy it!
@prankshot7971
@prankshot7971 5 жыл бұрын
I tried many ways but never succeeded ..after watching this video i am feeling confident.. thanks so much
@edwardowen8668
@edwardowen8668 Жыл бұрын
Just wanted to share how I made a toggle switch, minimal code: int swPin=8; int LEDPin=10; int LEDstate=0; int j; void setup() { // put your setup code here, to run once: pinMode(8,INPUT); pinMode(10, OUTPUT); Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: int swVal; swVal=digitalRead(8); if (swVal==HIGH){ LEDstate=abs(LEDstate-1); digitalWrite(10,LEDstate); Serial.println(LEDstate); delay(500); } } Using the ABS function returns either 1 or 0, opposite of the previous state. Thanks for all the great lessons.
@itimariu
@itimariu 3 ай бұрын
This is fine, but it has a bug. Keep your hand on the button to see what is the issue :)
@itimariu
@itimariu 3 ай бұрын
int isOn = 0; void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(8,OUTPUT); pinMode(13, INPUT); } void loop() { while(digitalRead(13) == 1); while (digitalRead(13) == 0); if (isOn == 1) isOn = 0; else isOn = 1; if (isOn) digitalWrite(8, HIGH); else digitalWrite(8, LOW); }
@yp4577
@yp4577 4 жыл бұрын
These lessons are great! You are such an amazing teacher. Having said that, I will have to reread some of the code written to follow along exactly how the commands make up a toggle switch. As you can probably deduce from that, I was NOT able to come up with the solution all by myself.
@jjedwards1
@jjedwards1 Жыл бұрын
That took me a long time to wrap my head around. I tried numerous things with counters and switch values but need to see your example and then "draw it out" several times to see why it worked. Very elegant in the end. Thanks
@quaternion-pi
@quaternion-pi 5 жыл бұрын
As always- excellent, practical explanation - including debouncing the switch. My solution used logical not (!) on LEDState in the if statements.
@phuctrong6851
@phuctrong6851 5 ай бұрын
It is not a simple project at all like you said, but it was very interesting. I'm kinda embarrassed to say this but I had to spend 2 hours trying to work it all out because I didn't wanna rely on the answer. I used the voltage measure at the LED as the bright stage so that's why I declared an extra readled as an input. Thank you for providing such helpful videos about Arduino like this. Wish you all the best! P/s: Btw here's the code that I did: int readPin=9; int led=7; int vol; int ledvol; int readled=6; int i=1; void setup(){ Serial.begin(2000000); pinMode(readPin,INPUT); pinMode(led,OUTPUT); pinMode(readled,INPUT); } void loop(){ vol=digitalRead(readPin); ledvol=digitalRead(readled); Serial.println(ledvol); if(vol==1){ i=1; } if(vol==0){ if(ledvol==1&&i==1){ digitalWrite(led,LOW); i++; } if(ledvol==0&&i==1){ digitalWrite(led,HIGH); i++; } } }
@allensun
@allensun 4 жыл бұрын
Thanks for the tutorial! I was able to figure it out beforehand, however I used a slightly different approach. In my code, when digitalRead() detects a "0", I enter a while loop which continually performs more digitalReads() until it detects a "1". This indicates the button was released, so I proceed to do an LED state change which was quite similar to your implementation (though I used a boolean variable for LEDState rather than an integer).
@karanjaspreetsingh3807
@karanjaspreetsingh3807 3 жыл бұрын
I too did the same way
@tacowithgiantbeansallover
@tacowithgiantbeansallover 3 жыл бұрын
SAME
@echanical2156
@echanical2156 2 жыл бұрын
If you use a while loop, your program will stuck in there until you release the button. It can't be used in programs with multiple things running simultaneously.
@FarmBoyTech
@FarmBoyTech 2 жыл бұрын
Did u do this without delay ?
@jonnycorleone13
@jonnycorleone13 10 ай бұрын
I did it! Used a while loop white the button is pressed, and changed a boolean inside the while loop with an if, else if statement!! Thank you so much for your lessons Sir!
@jamess009
@jamess009 4 жыл бұрын
After hours of banging my head against a wall I finally managed to get it working, with a bit of help from google i admit. I did it a bit differently, I made a counter and each time you press the button it adds 1. Then if the count is at an odd number the led is off, if its an even number it turns on
@GLH8
@GLH8 3 жыл бұрын
I did this, but it made it flash whenever you held the button down.
@anandg825
@anandg825 Жыл бұрын
I don't think any other code has such ingenuity with fewer statements but works without any glitches and oscillation, especially at the release of the switch. Moreover, the way you explained with the dots on graph is amazing. No one can match you. Thanks Mr.Paul.
@kenmeyer100
@kenmeyer100 3 жыл бұрын
After banging my head against a wall for a microsecond, I got my version running before watching the video. (my secret: I did hold my breath)
@rodrigooballe
@rodrigooballe 4 ай бұрын
I'm back: It's been 4 months since I had been able to be for these wonderful classes and one of the reasons was because I had actually stuck in this example, this extra time I have dedicated to study a little math and take a look at one or another Arduino book while I fed my brain with other classes of the Incomparable Master Paul McWhorter, The result has been wonderful, you teacher really do magic in the heads of those who really want to learn. And even though the code had come out to me, I finally discovered that there is not only one way to do it, well like all code.
@paulmcwhorter
@paulmcwhorter 4 ай бұрын
Welcome back!
@vladstrulev
@vladstrulev 5 жыл бұрын
Thank you very much. Great. I've learned to do it with millis(), not delay()
@rogthedodge99
@rogthedodge99 4 жыл бұрын
Only did it with help from the internet! I managed to fathom out a toggle variable, button didn't track the button state. Not many of us would have realised that an 'Else' was required, as youv'e not shown this before. Made me think though. Keep up the good work.
@oleksandr_honcharov
@oleksandr_honcharov 4 жыл бұрын
Hi, Paul🙂 Interesting tutorial, thank you very much as always) I did it like that before watching how you did it. const int redPin = 12; const int buttonPin = 10; int buttonRead; int redLEDState = LOW; void setup() { Serial.begin(9600); pinMode(redPin, OUTPUT); pinMode(buttonPin, INPUT); buttonRead = digitalRead(buttonPin); } void loop() { digitalWrite(redPin, redLEDState); int newRead = digitalRead(buttonPin); if (buttonRead != newRead && newRead == 1) { redLEDState = !redLEDState; } buttonRead = newRead; Serial.println(buttonRead); }
@nahuel3256
@nahuel3256 4 жыл бұрын
this is very elegant
@michaeltanner4404
@michaeltanner4404 2 жыл бұрын
@@nahuel3256 It is, with one exception. He's declaring a new newRead variable with every loop. I don't think the Arduino does garbage collection, so he has a memory leak. Better to declare newRead as a global and just assign it a new value every pass through the loop. Other than that, it's definitely less code than my attempt :)
@Dragonsecho3
@Dragonsecho3 4 жыл бұрын
I've looked up other arduino help before, and it's patchy at best. You lay it out and actually explain the content. You've answered questions I've long had that no one else has come close to answering. Thank you
@axelbrendel4091
@axelbrendel4091 3 жыл бұрын
My sentiments exactly!
@jitunehete
@jitunehete 5 жыл бұрын
Sir please make lesson on SPI interface. . Thanks in advance..
@RobsFatboy
@RobsFatboy 4 жыл бұрын
Completed the task. Prior programming novice level helps. Drank lots of HOT coffee with creamer and sweetener. Not to mention 23 years in the service as an electronic technician. I definitely need the refresher. Great job keep the tutorials coming.
@evreid6800
@evreid6800 4 жыл бұрын
This one stumped me. I tried to get the program to look at LEDPin and ButtonPin. I got it to come in and stay on but not turn off
@shatann
@shatann 4 жыл бұрын
I had the same problem. Turned out to be the wiring. I only had pin12 going to the switch, but you also need the 5V.
@wonderwang1585
@wonderwang1585 4 жыл бұрын
I have the same problem with yours. Push buttom, it is on; push button again, it still on.
@bifomo8327
@bifomo8327 3 жыл бұрын
Paul, I'm retired and my wife says I look like you (you poor fellow)! I'm using your series to get back to speed after a break of a couple of years, and I find it hugely helpful. I wanted to tell you that I did solve this one but with a different approach that requires a bit more code but fewer variables. It takes as a given that the LED will go on, then off, then on, etc. I'll paste it below. Many thanks for making this series available. Best regards, Dave Borch int inpin=7; int outpin=4; int state; int delaytime=50; void setup() { pinMode(inpin,INPUT); pinMode(outpin,OUTPUT); } void loop() { state=digitalRead(inpin); while(state==1){ digitalWrite(outpin,LOW); state=digitalRead(inpin); delay(delaytime); } while(state==0){ digitalWrite(outpin,LOW); state=digitalRead(inpin); delay(delaytime); } while(state==1){ digitalWrite(outpin,HIGH); state=digitalRead(inpin); delay(delaytime); } while(state==0){ digitalWrite(outpin,HIGH); state=digitalRead(inpin); delay(delaytime); } }
@daveflatters4981
@daveflatters4981 3 жыл бұрын
I got it myself by using 3 if statements and an On variable with 3 states 0, 1, & 2. If button = 0 & On = 0 turn led HIGH & On = 1 If button = 1 & On = 1 turn led HIGH & On = 2 If button = 0 & On = 2 turn led LOW & On = 0
@thegringobaker
@thegringobaker Жыл бұрын
I learned a valuable lesson in this one....count your curly brackets. I followed along as you coded (I had tried it on my own and wasnt'y successful) so I was amazed when it didn't work. I checked my coding looking for my inevitable typos, I checked and rechecked my wiring, I even asked my software engineer son what I did wrong...but it wasn't until I had you in one window, and my code in another that I saw an extra bracket. BOOM...it worked!
@paulmcwhorter
@paulmcwhorter Жыл бұрын
Excellent!
@AnshishRay
@AnshishRay 4 жыл бұрын
cant do it by myself! :(
@ShaneRoseRamos
@ShaneRoseRamos 7 ай бұрын
Same!
@danielbrown9813
@danielbrown9813 2 жыл бұрын
man, all i had was "okay, when it goes from 0 to 1 it's gotta do somethin" but had no real idea how to make that 'somethin' happen til seeing it and now it's so obvious. Thanks for the great content!
@Ben-fy3dl
@Ben-fy3dl 4 жыл бұрын
Damn this pushbutton toggle is logic intensive. I need more brainpower lol
@patrickdoherty3371
@patrickdoherty3371 2 жыл бұрын
Love how you instruct! Repetitive programming is the best way to learn. I've replayed and re-programmed many of your lectures! Thanks!
@danbishop4035
@danbishop4035 4 жыл бұрын
Another great video...my mother passed away a couple of years ago and she had this old flashlight that she always used. Her old flashlight will soon get an upgrade to an Arduino nano, as many LEDs as I can fit into the lens area and a variant of this toggle code. Also thanks to your Fusion 360 tutorials I'll be 3D printing and insert to fill the void of the battery compartment which will hold the nano and the batteries. Thanks for the inspiration!
@Sam-rz5hw
@Sam-rz5hw 3 жыл бұрын
IT WORKED! THANKS A LOT SIR! // PULL DOWN RESISTOR int readPin = 2; int outPin = 3; int delayTime = 500; int signal = 0; void setup() { pinMode(readPin, INPUT); pinMode(outPin, OUTPUT); Serial.begin(9600); } void loop() { while (digitalRead(readPin) == 0) { digitalWrite(outPin, signal); } while (digitalRead(readPin) == 1) { digitalWrite(outPin, signal); } signal = !signal; digitalWrite(outPin, signal); delay(delayTime); }
@jimfisher5099
@jimfisher5099 4 жыл бұрын
I will admit, it took all day tinkering with it, but I got it to work this evening!! Now, my reward it watching this video before I go to bed...
@paulrockwell9914
@paulrockwell9914 3 жыл бұрын
Echoing the "great job" on this lesson. I had solved this on my own, but my solution was bit more complex. I detected the button press, then waited for the button release before toggling the LED. Your analysis and solution made me realize all I had to focus on is detecting when the button was released if it was already pressed.
@nicholasknapik1423
@nicholasknapik1423 2 жыл бұрын
Network admin and beginner tinkerer here. Found your tutorial Playlist when searching for teaching that wasn't filled with fluff. These videos are great. I could likely skip around and go ahead but I'm enjoying the fundamentals you teach on every component. Thank you. Looking forward to getting to display screens.
@Mr_Jonathan_Greer
@Mr_Jonathan_Greer 5 ай бұрын
I didn't figure this one out on my own, and when I saw your code, I still had to sit and work through it a while to understand what's going on, but I eventually got it! Thanks so much!
@DGworksIvan
@DGworksIvan 3 жыл бұрын
the line if(buttonOld==0 && buttonNew==1) made me so confused, I rewatch the video 3 times and started analyze the logic of the code, since if(buttonOld==1 && buttonNew==0) made way more sense to me! What made it more confusing is the program works both ways. Then i studied with 100% concentration, serial printed all values to analyze if i missed something....BOOM! the code works both ways, however the trigger time is different! It has been so long I lost the joy of studying and figuring stuff by myself. Thanks Mr. McWhorter, your lesson is way too good to be free on internet.
@jordynvanevenhoven6305
@jordynvanevenhoven6305 2 жыл бұрын
I never thought that I'd learn so much from such a simple task! I figured it out my own way after a bit of head scratching but still thoroughly enjoyed how you broke it down and explained it. Love your videos and plan on using what I learn in my club, my future classes, and hopefully even one day on the job.
@paulmcwhorter
@paulmcwhorter 2 жыл бұрын
Fantastic!
@kevinroden5503
@kevinroden5503 8 ай бұрын
My new friend Gemini and I made the toggle switch slightly differently. Your excellent tutorials make it a lot easier to understand, and correct, the AI suggestions.
@agustinruiz2081
@agustinruiz2081 2 жыл бұрын
I was not able to figure out myself before to watch the video, my approach was far away and I become crazy :). Honestly, I had to watch the video a few time to understand the approach and finally I got it. Thank you very much!
@paulmcwhorter
@paulmcwhorter 2 жыл бұрын
Excellent!
@dannycollins5698
@dannycollins5698 Жыл бұрын
I didn't get it without you. The answer was harder than I thought! I did give it multiple tries before watching you. I got close using a while loop.
@gordonblackie8503
@gordonblackie8503 3 жыл бұрын
Have been struggling to learn Arduino and am often left wandering what the presenter is saying. THANK YOU FOR SLOWING DOWN! Several key points regarding writing code that I have missed, suddenly became clear from watching you type them in real time rather than saying here's the code copy and paste it. I will be looking at more of your tutorials as I go.
@IvanLopez-kw2hv
@IvanLopez-kw2hv 2 жыл бұрын
Hi Paul, this is a great tutorial. Thanks very much. About this problem, I have to admit that it was the first really challenging one for me. It took me one full day after many attempts trying to find out the logic behind and drawing several flow charts unsuccessfully . Finally came up with a solution directly in the programming window, kind of similar to yours. I introduced a variable that changes to 0 or to 1 in case the actual reading value is 0 or 1, by comparison to that variable (I guess like the previous state). So here is my coding (starting with A=1): buttonRead=digitalRead(buttonPin) if (buttonRead==A) { A=1;} else { A=0;} if (A==0){ digitalWrite (LEDPin,HIGH); } if (A==1){ digitalWrite (LEDPin,LOW); } delay(d);
@vitustillebeck4965
@vitustillebeck4965 4 жыл бұрын
I did it! After 30 minuts of trying. I'm 13 and really want to work in the coding and hardware industry. Thank you for making it possible.
@jakerice1593
@jakerice1593 2 жыл бұрын
I'm loving the videos so far! for anyone watching this in the future, there are actually a few ways to code this. The most efficient I've found, was to just use while-loop-waits, much like waiting for user input.
@adityashauryavardhansingh1491
@adityashauryavardhansingh1491 2 жыл бұрын
int readpin = 4; int ledpin = 8; int v; int i = 1; void setup() { // put your setup code here, to run once: pinMode(readpin, INPUT); pinMode(ledpin, OUTPUT); Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: v = digitalRead(readpin); while (true) { if (v==0) { if (i % 2 != 0) { digitalWrite(ledpin, HIGH); } else { digitalWrite(ledpin, LOW); } i++; } v = digitalRead(readpin); Serial.println(v); delay(140); } } It was working but maybe it was not that efficient method. Thank you, Paul sir for this great lecture and I really appreciated it.
@paulmcwhorter
@paulmcwhorter 2 жыл бұрын
Good!
@bearpapa1606
@bearpapa1606 3 жыл бұрын
I was able to do it myself. But after I watched the first 2 mins of your video, I realise that only trigger the "toggle function" after one let go of the button is a better way to do it. So I rewrite my code again, and it took me an hour to make it work. But I did have fun doing it. I think I did it in a totally different way than yours. I've learned a lot here. Thanks for all the effort that you put into all these videos.
@coconutyesse
@coconutyesse Жыл бұрын
Yes. I did it after I checked the strategy drawing. It is the most important part before the coding. Thanks for this great lesson!
@user-su5sq5ib3i
@user-su5sq5ib3i Жыл бұрын
Had to go back to this just to marvel at how powerful yet simple, brilliant!
@stevensaunders1502
@stevensaunders1502 3 жыл бұрын
Hi Paul, absolutly brilliant tutorials. I love the in depth, how things work stuff, so informative. I managed to get the result but in a completely different way. No outside help but I have done some java coding in the past which I think helps. int LEDPin = 12; int buttonRead = 10; int buttonVal; int dt = 150; int toggleBit = 0; void setup() { // put your setup code here, to run once: pinMode (LEDPin, OUTPUT); pinMode (buttonRead, INPUT); Serial.begin (9600); } void loop() { // put your main code here, to run repeatedly: buttonVal = digitalRead(buttonRead); delay(dt); //Button not pressed. Do nothing and wait till it is pressed. while (buttonVal == 1) { buttonVal = digitalRead(buttonRead); Serial.print("Toggle = "); Serial.println(toggleBit); } //It's pressed but still do nothing!!!!!!! while (buttonVal == 0) { buttonVal = digitalRead(buttonRead); Serial.println("Button Pressed..."); } // Now it's released check the tracking ToggleBit value. If it's a 1 change to 0, if 0 then change to 1. if (toggleBit == 1) { toggleBit = 0; } else { toggleBit = 1; } //If the button has been released and the toggleBit is 0, turn the LED off. if (buttonVal == 1 && toggleBit == 0) { digitalWrite(LEDPin, LOW); } //If the button has been released and the toggleBit is 1, turn the LED on. while (buttonVal == 1 && toggleBit == 1) { digitalWrite(LEDPin, HIGH); Serial.print("Toggle = "); Serial.println(toggleBit); buttonVal = digitalRead(buttonRead); } } Hope putting my sketch is ok?
@adamcurtice3584
@adamcurtice3584 2 жыл бұрын
I got my solution for this on my first try. I added an additional digital input to monitor the state of the LED. I then used 2 If statements to compare LED states when the switch was pressed. Whatever state the LED was in when the switch was pressed was toggled to the next. Other than some debounce issues with the switch it all worked great. Thanks for the challenge.
@filipstojanovicmechanicale9265
@filipstojanovicmechanicale9265 4 жыл бұрын
I must admit.. this was the first asignment that i couldnt do by myself, i was trying for couple days and i watched video to see it done. Little demotivational but we are not giving up here!
@zudzifudushzy
@zudzifudushzy 2 жыл бұрын
Hi Paul! Thanks again for this awesome lesson! I'm quite proud of myself that I where able to do the homework from Ep. 27 in like 15 minutes :D I used a different approach to the problem, but I worked :) This is what I came up with: int LEDPin = 8; int ButtonPin = 12; int ButtonRead; int dt = 50; int lastState = 1; void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(LEDPin, OUTPUT); pinMode(ButtonPin, INPUT); } void loop() { // put your main code here, to run repeatedly: ButtonRead = digitalRead(ButtonPin); Serial.println(ButtonRead); if (ButtonRead == 0 && lastState == 1) { lastState = 0; do { ButtonRead = digitalRead(ButtonPin); } while (ButtonRead == 0); } else if (ButtonRead == 0 && lastState == 0) { lastState = 1; do { ButtonRead = digitalRead(ButtonPin); } while (ButtonRead == 0); } if (lastState == 0) { digitalWrite(LEDPin, HIGH); } else if (lastState == 1) { digitalWrite(LEDPin, LOW); }; delay(dt); }
@ovi_4
@ovi_4 4 жыл бұрын
Ahhhh, I was thinking of the need to use new and old state variables and I have used them but did not realize that you have to actually ,,manually,, change the LEDstate after the IF statement and then manually change it again after the else statement. So my LED switched on at the first push but that was it. I could no longer switch it OFF after that. I must have tried about a dozen different combinations and lots of ,, head scratches,,. Oh...what a bummer...:))) But you know what I'm absolutely hucked on your teaching style. You are a true native teacher. Thank you very much and please, please do not stop the series. It is....well... it goes without saying one of the best teachings I've ever encountered here on youtube. Once again, Thank You, Sir.
@chrisgosling5408
@chrisgosling5408 2 жыл бұрын
This one is a real step up in the coding, If i don't get it after a while I work through with Paul and then stop before boom to run the program myself and then train on the debugging which is just as important as the coding skill, after all we all make mistakes!
@lukeshields8984
@lukeshields8984 3 жыл бұрын
Im going to be honest and say that the task you set i couldn't do but understood once you explained it and done the demo in the video and now fully understand.
@waynenicolson5864
@waynenicolson5864 3 жыл бұрын
Hi Paul, I battled for a good while with this one, then admitted defeat. I watched the video and apart from learning your method, I picked up the (bread crumb) tip and that helped me get my method to work. I used two "while loops" each, one for each "LEDState" and they each had an "if" statement in them. The "if" statements would switch the LED on or off, with the button press, and set the "LEDState" causing the program to exit the "while loop" and then enter the other one. Hope that makes sense. Thanks for another good lesson.
@mdhmthrvnn
@mdhmthrvnn 4 жыл бұрын
Thank you Paul, for your wonderful lessons! Here's another way to derive the same results using fewer variables - the general idea is when someone pushes the button, change the inputs (signal) going to the LED, if it remains unpressed, then do not change the inputs (signal) going to the LED int buttonPin=12; int ledPin=22; int Signal=0; int readValue; void setup() { pinMode(buttonPin,INPUT); pinMode(ledPin,OUTPUT); } void loop() { readValue=digitalRead(buttonPin); if(readValue==0) { Signal=1-Signal; digitalWrite(ledPin,Signal); } if(readValue==1) { digitalWrite(ledPin,Signal); } }
@michaeltanner4404
@michaeltanner4404 2 жыл бұрын
This doesn't work if you hold the button down. If you do, you constantly change the Signal value, which will cause the LED to flicker on and off. It will happen very quickly though, so you may not see it, but it's happening.
@user-zu1ix3yq2w
@user-zu1ix3yq2w 4 жыл бұрын
I did this on my own, but the explanation on graph paper was incredibly insightful.
@shehabsayed5605
@shehabsayed5605 4 жыл бұрын
u should rename this tutorial from learning Arduino to learning and see how proper problem solving, explanation, motivation learning, and draw a smile on our faces works, love u, watching u from Egypt
@wayneswan3092
@wayneswan3092 3 жыл бұрын
There were multiple other sources I was able to look over to set up toggle button. However, as always, yours has proven to be most educational! After going through it with you on this video, however, I have since been able to set up multiple void loops to manipulate 4 RGB-LEDs in various ways, that I was then able to toggle through at the touch of a button. This has been my primary goal since I started playing with Arduino using LEDs. Next I'll be investing in other RGB LED cables and other fun light toys to program to dance to my own liking. Thank you Paul!
@srikannandairy
@srikannandairy 5 жыл бұрын
I tried myself, it is working. It's great on your part to insist on writing the code by myself.
@JohnHarrisonHomes
@JohnHarrisonHomes 5 ай бұрын
I took a different approach. I tried to do something along the lines you did with multiple special variables to record button state, but couldn't figure it out. After two days, finally got it working by using four different while loops. The button press kicks the program from one while loop to the next. And the loops change the LED state. The advantage of mine is it turns the LED on or off immediately when the button is pressed without needing to release the button first. I'm really glad I figured it out before watching this! I was close to giving up.
@samuelstuff4557
@samuelstuff4557 2 жыл бұрын
I love his teaching style because he understands we aren’t as smart as him
@AhmadFirdausIdris_AFNAN
@AhmadFirdausIdris_AFNAN 3 жыл бұрын
pressing the button will reset the buttonOld=0, releasing it will set buttonNew=1. enjoying the series. tqvm Paul.
@kojitw
@kojitw 3 жыл бұрын
finally got it to working after several hours. forgot the "==" sign, didn't connect the pin correctly, there are many things that can go wrong, but I am glad to have made it. thanks, Paul!
@EthanElkorr
@EthanElkorr Жыл бұрын
was not able to figure it out my self but followed along and now I understand how to. Love your Tutorials!!!
@CascadePacificNW
@CascadePacificNW 4 жыл бұрын
I can't believe it but I actually figured it out!!!!!!! Thanks to your teaching style I'm actually learning how this stuff really works and was able to make an educated guess. Its different than how you did it but it worked. void loop() { Serial.println(readVal); readVal=digitalRead(readPin); delay(23); if (readVal==0) { digitalWrite(led,LOW); Serial.println(readVal); readVal=digitalRead(readPin); delay(23); } if (readVal==0) { digitalWrite(led,HIGH); Serial.println(readVal); readVal=digitalRead(readPin); delay(23); } }
@MichaelShoobert
@MichaelShoobert 11 ай бұрын
yes I do the lessons and the home work. I have been working on your lessons now for 3 months. I don't watch them like a Net flicks series. I move on to the next lesson after I understand the current lesson I am on, I play with the program to get a better understanding how it works and how to better apply the program under different conditions.
@sajalsangal1436
@sajalsangal1436 4 жыл бұрын
This is my code , I used a while loop inside if and multiple delays because pushbutton doesn't give out values smoothly as you also mentioned . //This is a toggle switch(pull down resistor) , if button is pressed once the led glows, if button is pressed again it turns off int pushbutton = 2; //input pin from pushbutton , input values are 0 or 1 int buttoninput; int led = 13; int dt = 500; //different delay needed so value doesn't turn quickly int dt1 = 250; void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(pushbutton,INPUT); pinMode(led,OUTPUT); } void loop() { // put your main code here, to run repeatedly: delay(dt); buttoninput = digitalRead(pushbutton); Serial.println(buttoninput); if ( buttoninput == 1) //works if button is pressed { delay(dt); buttoninput = digitalRead(pushbutton); //taking value again because button is released while ( buttoninput == 0) //stay in loop as long as button is not pressed again { delay(dt1); buttoninput = digitalRead(pushbutton); digitalWrite(led,HIGH); } } digitalWrite(led,LOW); } I think yours works faster than mine but in mine we don't have to keep track a lot and works just fine :D
Arduino Tutorial 29: Using Push Buttons to Create Dimmable LED
41:38
Paul McWhorter
Рет қаралды 146 М.
OCCUPIED #shortssprintbrasil
0:37
Natan por Aí
Рет қаралды 131 МЛН
Arduino Tutorial 34: Simplest Way to Use a Pushbutton Switch
10:26
Paul McWhorter
Рет қаралды 103 М.
How to Control a 12V Motor with Arduino: Easy Wiring & Code Examples
44:13
Arduino Tutorial 30: Understanding and Using Servos in Projects
18:05
Paul McWhorter
Рет қаралды 252 М.
Arduino Tutorial 14: Dimmable LED Project
29:47
Paul McWhorter
Рет қаралды 256 М.
Arduino Tutorial 6: Build an LED Binary Counter
37:50
Paul McWhorter
Рет қаралды 465 М.
OCCUPIED #shortssprintbrasil
0:37
Natan por Aí
Рет қаралды 131 МЛН