Thank so much for that - new to Arduino and was going all around the houses just to get it to perform a repeated action with a stepper - this video made it so simple
Man you're the best . I went through the comments and you're helping all the beginners. I also had a little problem . Whenever I release the buttons , some extra A's are being printed.
Hey thanks, I like helping people out, happy to help. Sorry for the delay, I responded to your other comment. Let me know if that helps. If it's happening when you release, try putting a short delay after the release is detected maybe something like delay(100) or try increasing if it doesn't help. If you get to over 250 then it's likely something else unless you're really slowly letting the button go.
I don't typically post the code in the video because I'd prefer that people write the code as they follow along so they can better learn the code rather than copying and pasting. That being said, I do generally always post the code in my website, I just don't link it for the reason mentioned. Here is the code if you'd like to copy/paste it, thanks for watching and commenting. robotresearchlab.com/2021/01/05/how-to-program-a-push-button-with-arduino/
For beginners, it helps to add the actual sketch to the video notes. Even at full screen, your screenshots are too blurry to see the small punctuation marks clearly (and a pain in the **** to transcribe by pausing the video every two seconds)
Sorry about that, it's recorded in 1080p and looked good from my view. In any case I do have a write up with the code. I don't always pay the code for the smaller projects because I like to have people follow along and understand the code. Here's a link to the post with the source code. robotresearchlab.com/2021/01/05/how-to-program-a-push-button-with-arduino/ Sorry again and thanks for the feedback.
Sorry for the late reply, the simplest way to do this would be to copy and paste the code but have currentState be each separate button, so you'd have the code as it is in the video, then something like this currentState = digitalRead(BUTTON_PIN_2); if (currentState == pressed) { // Do something here while(digitalRead(BUTTON_PIN_2) == pressed) { // Do nothing while button is pressed } } This isn't the best way but it's the easiest to describe in text. A better way would be to create a function that reads a button based on the pin value passed in, then you're code would look something like this (this is much cleaner and repeatable without copying and pasting a lot of code, it's just a simple if statement copied and pasted. if (buttonPressed(BUTTON_PIN)) { // Do something here } if (buttonPressed(BUTTON_PIN_2) { // Do something here } But you'd have a custom function called buttonPressed() which would return true/false based on the button pin state. That would look like this bool buttonPressed(char buttonPin) { if (digitalRead(buttonPin) == pressed) { // Do something here while(digitalRead(buttonPin) == pressed) { // Do nothing while button is pressed } return true; } else { return false; } }
Can you make a video where you explain how you could do the same, but instead of printing somethign on your computer, you display it on another apparat, aso another peace of hardware, that just does thing when a button is pressed (could also be a light turning on/off or smth easier than displaying text)
I could do that, but unfortunately, I haven't had any time to make new videos for quite some time now. It would be easy to change this, though, just change the Serial.println() code to do something else instead, like digitalWrite(LED_BUILTIN, HIGH) to turn on the onboard LED. If you want to be able to toggle the LED it would require a couple more lines of code but it's the same concept. If you need some more information than that, I can help but, I unfortunately won't be able to create a video though.
Sure thing, here they are: Arduino Board: www.amazon.com/gp/product/B01EWOE0UU Wires: www.amazon.com/gp/product/B005TZJ0AM Breadboard: www.amazon.com/gp/product/B077PK858F (These are unavailable but there are many other options, don't pay more than $10 for a set of 10-12 of the mini boards) Breadboard alternative: www.amazon.com/gp/product/B07DL13RZH (This gives you multiple options for different sized projects) Buttons: www.amazon.com/gp/product/B07WF76VHT (The ones I have are unavailable but I wouldn't recommend the ones I have, I would get these since they're made for breadboards) But actually, If you're just getting started I would recommend this starter kit, for less than $20 you get everything you need to do many different projects. It includes everything you would need to build the project in the video as well. www.amazon.com/gp/product/B01DGD2GAO
Debounce is slightly different, it's to counteract the fast on/off that can happen when pressing or releasing a button (called hysteresis). Basically with hysteresis, when you press the button it can make the microcontroller think you pressed the button multiple times. These buttons don't seem to have that issue so luckily I didn't need to go down that rabbit hole with this video. But I do plan to cover this in a future video. Thanks for the feedback and sub, I hope to get more videos out soon, nicer weather means more work outside so we'll see.... Thank again!
@@shukrantpatil I don't have any videos on debounce yet, the easiest (yet hacky) solution to resolve this would be to put a short delay after a press is detected. This way any hysteresis occurring during the press will be ignored during the delay.
Just in case you are still watching comments 4 years after uploading this video, I have a request; I am just beginning my Arduino journey and my first project is to program a Flight Simulator controller. The device I have built includes a DPST toggle switch with an [ON] OFF [ON] configuration to control flaps. This is equivalent to 2 pushbuttons in the same switch. Move the toggle up - the flaps move up. Move the toggle down - the flaps move down. I would like my serial monitor to print a line with "UP" or "DOWN" when the toggle is moved in the corresponding direction. Any advice would be amazing and greatly appreciated.
Thanks for the feedback. Debounce is on my list but unfortunately I haven't had time for videos lately (been saying that for way too long). The easiest way to hack around that would be to put a quick delay after the button press is detected (that way multiple presses within a certain time won't trigger the code multiple times). Probably something like `delay(100)` would work as a guess. There's also button libraries that handle debounce but I'd suggest you read through the code in the library so you understand how they're doing it and it doesn't work against you. Thanks again.
Thank you for a relatively simple explanation of this code... Now what would I do different if I were using this code to cause the computer to see a button pressed on a joystick? I race online and have built a 32 button box for controlling different functions. However I need to add three toggle switches and I have spent hours trying to find a code I could edit to make it work using a different Arduino Pro micro, hopefully if you can answer my question about the joystick I can finish that project.
Great Help, and Really well explained. Thank You!! I have tried it and it fixed a problem that has been driving me mad. Please can you tell me how I can multiply this exact code to control multiple buttons?
Hey, I'm glad it helped, if you want to reuse code for different objects, the best way is to create a function. Functions allow you to reuse code with slight changes so it works for multiple situations. In this example code I simply moved the code from the loop() into its own function. bool isButtonPressed(int buttonPin) { // Read button bool currentState = digitalRead(buttonPin); if (currentState == pressed) { Serial.print("Button on pin "); Serial.print(buttonPin); Serial.println(" pressed"); while(digitalRead(buttonPin) == pressed) { // Do nothing while the button is pressed } return pressed; } } Now, this code can be used for a button on any pin by simply supplying the pin number, an example would be the following. void loop() { // Check if the button on pin one is pressed isButtonPressed(1); // Check if the button on pin 4 is pressed isButtonPressed(4) } Now, because I added a "return type" (bool isButtonPressed), the bool means our function returns a bool (true/false). So, you can actually remove the Serial statements so all the code does is respond back with whether the button was pressed, and now you can do different things for each button, see below. void loop() { bool btnState = false; // Check if the button on pin one is pressed btnState = isButtonPressed(1); if (btnState == pressed) { // Do something for this button } // Check if the button on pin 4 is pressed // You can also use a shorter version of code that does the same thing if (isButtonPressed(4) == pressed) { // Do something for this button } } Thanks for watching and for the feedback, I hope this helps. DISCLAIMER: This code was written in the comment so it hasn't been tested.
I would like to know how you can take one momentary button and get 2 functions from it with a short and long press. The first short press will make an LED blink untill the button is pressed short again to stop it blinking. The second function of long press will sound a horn as long as the button is pressed and stop when the button is released.
Sorry for the delay. This is a great question and an interesting problem. I hadn't responded as I wanted to do a video on it but I'm so swamped I haven't had a chance. So, I've never done one but I think I'm going to try and do a live stream tomorrow and get this done. I've generally stayed away from live stream because my edited videos are already long so a live stream is going to be longer... we'll see how it goes, hopefully you still need this but if not, it's a learning experience for me anyway and maybe it will help someone else.
Here you go, let me know if you like it or dislike it, what I could do better. I hope this helps, thanks for watching. ua-cam.com/video/HhhEHECKywM/v-deo.html
can you make a video that will play a 30 second audio then fade on 6 led lights, then turn off after 10 or 15 seconds with a push button using an arduino nano?
Hey there! this is very useful video, thanks for it! Have you made any video explaining how to write a code for multiple buttons build in a matrix? Happy to give more details if my question is not clear enough ;)
No, I have not made any videos using multiple buttons or buttons in a matrix. Unfortunately I haven't had time to make any new videos for a while but I will add this to my list.
Will you please make a video for me wherein I will be using four switches, each one will be doing different jobs. For example: Switch 1 when pressed will switch ON light. Repressed will switch OFF. Switch 2 will start fan when pressed again switch off fan. Like wise for other switches. Use of Arduino Uno, Switch and Relays requested. Thanks in advance.
Hey, thanks for watching and commenting. I haven't had time lately to create a new video so I probably won't get to this soon. I'd like to use your idea for a video that shows how to create a function but what I would suggest is get one button working, then copy and paste the code three more times and change the values for each button. It really should be put in a function so you don't copy/paste but if you don't know how then it's easier to just copy/paste. If you need help you can contact me through my website, it'll send me a personal email and then when I respond you can attach your code so I can take a look at any problems you're having. robotresearchlab.com/contact-me/
@@MarkoCR221L There are many ways to do this, personally I would copy all of the code inside of the loop() function and put it in a new function so the code can be reused rather than copy and paste the same code over and over. I added a parameter to the custom function that accepts the pin the button is on, now this function will work for any pin that you tell it has a button on it. I also added a return bool value, if the button is pressed it returns true, if it isn't then it returns false. This might be confusing since "pressed" is set to false so you can certainly change the function to return whatever pressed is set to instead, I'll show that code after this code below. void loop() { if (buttonPressed(BUTTON1_PIN)) { // Do something here for button 1 Serial.print("Hello from button on pin "); Serial.println(BUTTON1_PIN) } if (buttonPressed(BUTTON2_PIN)) { // Do something here for button 2 Serial.print("You pressed the button on pin "); Serial.println(BUTTON1_PIN) } } bool buttonPressed(char btnPin) { // Read button bool currentState = digitalRead(btnPin); if (currentState == pressed) { while(digitalRead(btnPin) == pressed) { // Do nothing while button is pressed } // Return that the button was pressed return true; } // Return that the button was not pressed return false; } Now, as mentioned, you could alter that code so it returns whatever "pressed" is set to by changing the return values from 'true' and 'false' to return pressed; // Return a value of pressed and return !pressed; // Return a value of NOT pressed This option is a little cleaner because now, if you change the value of pressed because maybe you're using a pull down resistor, the function will still work, you'd just simply change the value of pressed to 'true' instead of 'false'. I hope this helps.
Not necessarily, if you put this same code in an interrupt it would still halt the program because the chip would be performing the interrupt function. Interrupts are typically used in cases where you don't want to keep checking the state of a pin, you can have code automatically execute when a pin goes high, low, or just changes in either direction. In order to allow the code to do something else, you'd have to modify the code to remove the while loop. Something like Check if the button is pressed, if it is, check to see if it was pressed the last time you checked. If it was pressed the last time then we can assume they're still holding the button down so don't execute the code again, only execute the code when the button is currently pressed but wasn't pressed the last time we checked. I hope that makes sense, if not let me know and I'll try to explain better, I might have responded to another comment with actual code so you can check the other comments (since there shouldn't be that many unfortunately lol).
Hey, sorry for the delay, the code is going to depend on whether you want to do other things while also checking for the button being held for 5 seconds. If you just want it to check for five seconds after the button is pressed and do nothing else you just use a while loop for 5 seconds after the button is pressed, leaving the loop only if five seconds has passed or if the button is released. Here is some un-tested code that should get you started. Keep in mind, checking if the button is pressed assumes BUTTON_PIN is set and that a digitalRead() HIGH means pressed. This code should allow you to hold the button and it will execute the print statement for every 5 seconds the button is held. ---------------------------------- void loop() { checkButton() } void checkButton() { static bool lastButtonState = false; static unsigned long lastPressedTime = 0; // If the button is pressed if (digitalRead(BUTTON_PIN)) { if (lastButtonState == false) { // The button was just pressed, record the state and time lastButtonState = true; lastPressedTime = millis(); } else { // The button was already pressed, check the time if (millis() - lastPressedTime > 5000) { // Button was pressed for five seconds!!! Serial.println("Hello") // Reset the time last pressed so it only executes every 5 seconds lastPressedTime = millis() } } } else { // Button isn't pressed so update the lastButtonState lastButtonState = false } }
You "should" use resistors but you don't necessarily have to. The reason the resistor is there is because the pin readings can fluctuate if left "floating". The resistor forces the reading to be either high or low when there is no direct input source. So, yes it can work without the resistor but you may get bad readings, also, Arduino has built in pull up resistors in the chips so you can use the internal resistors (but they are only pull up resistors so you'd need to make your button a pull down, or pull to ground instead of pull to 5V).
Hey buddy any advice, i want to control my claw machine with my keyboard. Any ideas where to start? I want to be able to moved the claw and drop it as well.
Hmmm, I don't have any videos on this sort of thing, I actually don't even have any on Servos which is probably something I should have covered. In any case, to answer your question: 1. Start by simply trying to manage user inputs, for that I would start here www.arduino.cc/reference/en/language/functions/communication/serial/read/ 2. Now, I would modify that code to make a motor movement instead of printing out what was entered. You'll either need a series of if, else-if, and else statements or a switch statement 3. Once you have all that down I would start to define keys for each individual servo. I'm assuming you probably have three much like a human arm (shoulder rotation, elbow bending, and wrist bending) 4. You could modify the code to accept three values and move each servo to the value passed in As a bonus, since this is all done by reading character inputs you could easily modify this to work with bluetooth as an enhancement. I should have a video on adding bluetooth, but it essentially does the same thing except you can add buttons to a phone app and press the buttons on your phone to control the arm instead of having to send one character at a time (the button sends the character for you automatically).
@@melannieworld Unfortunately I don't have much time for robotics lately, I've got a lot of personal tasks to complete before I can get back to making videos and helping directly. If you contact me through my website, it will send me an email and I can try to help you through emails. robotresearchlab.com/contact-me/
Just to clarify, you want an LED that has a variable resistor and a button? Like a wall switch where you can set the brightness but control on/off with a button?
I'm not sure what you mean, I'll need some more information. What are the "rules" to determine increase vs decrease? Is it something like the button goes up and when it reaches the max it starts decreasing, or is there a certain button press sequence to increase vs decrease? Like, press twice quickly to increase or press once to decrease or something like that.
If you want it to open a link on your computer, that would be a tricky one, the easiest solution I can think of is to use the Arduino to execute a macro (or script) on your computer (you would need to use an Arduino Pro board). It is a little more involved than something that can be explained over a comment. Interesting idea though, maybe I'll create a video for it... not that it would probably be watched by a lot of people, it's a pretty specific use case lol. I'll add it to my list of ideas though, thanks for watching.
Is there a reason you used const Char instead of const int? Im trying to use the same type of button to start my code, pretty much once the button is pressed it will run through my code once. Great video and tutorial thank you by the way.
It won't make any functional difference. I use 'char' when assigning pins just because char values go from -128 to 127 Since it's only one byte it takes up less space than an int which is two bytes. Int types range from -32,768 to 32,767 Technically it takes slightly longer to process variables that are larger but the difference between char and int is very minimal, mostly it's about saving space but again, I wouldn't worry about that unless it became an issue.
Hey man, I'm working on a school project. My goal is to have 2 push buttons and each will control a separate LED, when one button is pushed the corresponding LED will extinguish while the other one flashes. I have it working but I need the serial monitor to say every time I press a button. My problem is when I use the "while" statement it stops my other LED from blinking while the button is pressed. Do you think a "do-while" statement could resolve my issue? any suggestions are welcome. Awesome video!
The best way that I can think to resolve this issue is to use an interrupt triggered by the timer, it basically allows a function to be run regardless of the code currently being run, it would switch over to the led function and then come back to the main code. I don't have any videos on timer interrupts but this article blog.wokwi.com/5-ways-to-blink-an-led-with-arduino/#blinking-with-timers- should help you out. If you just need the one to keep blinking all the time you can use the code as is. If you need it to blink under certain situations you'll need to modify the blink interrupt routine code so that there is a boolean such as "enabled" or "shouldBlink" so it knows whether or not the LED should be blinking. Then just add an if statement like this. ISR(TIMER1_OVF_vect) { if (shouldBlink) { digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); } Lastly, for the record, you really shouldn't read a digital pin if the pinMode is set to OUTPUT, it probably won't give you any issues but to be safe or if you are having issues you might want to add a pinMode() statement to change it to OUTPUT when its digitalWrite and INPUT when it's digitalRead.
For that you'd have to add some more variables but it's doable. You would want a variable that holds the value of when the button was last pressed (let's call the variable lastBtnPressMillis) and you'll need one to know if there is a pending action (let's make that a bool and call it pendingBtnAction). It will either need to be a global variable or a static variable, if you can't figure out static variables just go with global for now. So, when the button is pressed, set the lastBtnPressMillis to the current time (lastBtnPressMillis = millis()) and set pendingBtnAction to true. Then you'll have to add a check for that variable in the button function, maybe something like this if (pendingBtnAction && millis() - lastBtnPressMillis > 10000) { // turn off your OLED here // Reset the pending action flag until the next btn press pendingBtnAction = false; } These aren't the easiest things to discuss via comments and I don't have the time to make videos lately so let me know if any of this isn't clear. This is by no means the only solution, this is just off the top of my head how I would do it.
@@RobotResearchLab thank you very much. i just solved the problem with the command from ssd1306 lib. display.ssd1306_command(SSD1306_DISPLAYOFF); and if i want to turn on the oled display, display.ssd1306_command(SSD1306_DISPLAYON);
@@RobotResearchLab I’ve tried loads of different ways of trying to add multiple buttons and give each button a name to be recognised on pc but i can’t seem to get it to work any tips or videos you have done
@@RobotResearchLab yes basically but I’m also adding a joystick using potentiometers but I havnt got that far yet lol thort I’d master the button coding first lmao
@@johnmasters2099 This should be as easy as just using the Keyboard and Mouse libraries included with the Arduino core libraries. I personally haven't used them BUT I do know that only certain boards will work. Essentially I'd suggest the Arduino Pro Micro (or third party version) as it'll be the cheapest of the boards that have this ability. For how to do this, again, I haven't done it myself but looking over this article looks promising. maker.pro/arduino/projects/how-to-turn-an-arduino-into-a-keystroke-automation-tool
hey bro. i need a help. i have this project where we have two buttons and we have to code one button to play music and the other button to pause the music. we have the code for the music(we going to rickroll the teacher lmao), but he dont know how to do the code for the the buttons to play and pause. hope u see this and help us out. we need to submit on thursday 11th aug
I can definitely try to help you out, especially if it's to rickroll someone, that's a noble cause ha ha. If you contact me through robotresearchlab.com/contact-me/ it will forward to my email and I can reply back to you personally (just be sure to provide your real email address so I can get back to you).
hi im trying to make a button box for a sim racing setup and i have no experience at all do you think you could help me i have a arduino pro micro and 9 2 pins button
Sure, you can contact me through this form and it will send me an email. Then I can respond back to you via email instead of trying to help through YT comments. robotresearchlab.com/contact-me/
This video is really helpful, but there is a problem with my code. I am trying to make a servo motor move when I press the button, but whenever I verify the code I get the error message "a function-definition is not allowed here before '{' token". Here is my code const char BUTTON_PIN = 8; bool pressed = false; void setup() { Serial.begin(115200); pinMode(BUTTON_PIN, INPUT_PULLUP); } void loop() { bool currentState = digitalRead(BUTTON_PIN); if (currentState == pressed) { #include Servo servo; void setup() { servo.attach(9); servo.write(0); delay(2000); } void loop() { servo.write(90); delay(1000); servo.write(0); delay(1000); } } } I am also pretty new to programing with arduino so I don't know that much about it. If you know how to fix the problem that would be amazing.
Sorry I didn't see this comment, I'm not getting notified of every comment by UA-cam. Anyway, hopefully you've figured out the issue by now but it's an issue with your curly braces. You have a function declaration (void loop()) inside an if statement. Function declaration must be outside of all code blocks. Also, you can't have two functions named void loop(). It looks like you just accidentally copied the loop function into your if statement.
Using an analog pin? Are you using analogRead() instead of digitalRead(). You can use analog pins as digital pins, they are in fact digital pins but have the added feature of a DAC which converts digital to analog but you certainly don't have to use that. If you are using analogRead then ANY value that is not 0 will return a true when you do "if (analogRead(pin) == true)". If you're using an analog pin as a digital pin just simply use digitalRead(pin) and it should work the same. Let me know if this helps or you need more help.
You can either go to Tools-->Serial Monitor or click the magnifying glass in the upper right toolbar. It's a built in tool for monitoring serial inputs.
@@RobotResearchLab Super helpful tutorial and I managed to get this to print to serial. But is there a way to actually get this to type "Hello" in Notepad?
@@theyutethatdoot7895 In order to do this there are a few things that need to be done ahead of time. In its simplest solution, if you had Notepad open and the cursor was in the application ready to type then you could use something like an Arduino Pro Micro which can act as a keyboard or mouse for any PC. Then you would have to use the Keyboard library to send the text to the computer and it would basically be as if you were typing. It's possible that you could pair an Arduino sketch with a script on your PC so that when the Arduino is detected, it opens Notepad and starts typing but that would be pretty involved and require a video to explain. First and foremost though, you would need an Arduino that has a chip capable of supporting keyboard and mouse functions (Pro Micro is probably the cheapest/most easy to find and non-Arduino brands will work as long as they market as a Pro Micro board).
@@Qwzdf Just a heads up, if you want to control keys on a computer you need a specific Arduino board for that. Here is a list of supported boards, I always used a Pro Micro (generic brands work too, doesn't have to be Arduino brand) www.arduino.cc/reference/en/libraries/keyboard/
Good evening, I am a student and am working on my final project. I want to ask what if the "Push the Button" 5 seconds turns on then turns off again. Thank you please help
Sorry for the late reply, do you still need help on this? If so, I need some more information as I'm not understanding your question exactly. Do you want to push a button for 5 seconds in order to trigger some action or push the button and have it wait five seconds before doing something... or something different than that?
Sure, I'll try to explain in a comment, hopefully it translates. What you'd want to do is, in the if statement for the button (if currentState == pressed) you want to add to a variable that will count the number of times the button is pressed. So, for starters you'll need to add a variable in the global variables (let's call that btnCounter). Then each time the button is pressed, increment that counter. Then add an if statement to increment your value if the btnCounter is equal to 6... then reset the button counter. Here's an example 1. Add a variable up top like: char btnCounter = 0; 2. Modify the if statement to keep track of button counts and add an if statement to increment your variable if (currentState == pressed) { btnCounter++; // Increment the button counter by one if (btnCounter == 6) { aNumber = aNumber + 1; // Could also use aNumber++; btnCounter = 0; // Reset the button counter } ... Other code from the video (Serial print and while loop) here } You could simplify it even more so you don't need to reset the counter by using `if (btnCounter % 6 == 0)` but don't worry about that until you understand the code above.
@@RobotResearchLab Ah that's great thank you, appreciate it. One more thing. Could I use another button which would make the number go down. And everytime it was pushed 6 times it would decrease by 1? Basically the same but opposite
@@tdb1940 Yeah, definitely. For that you would need a whole other if statement to handle the other button (the one that handles going down). Everything else would be the same only you might want to change btnCounter to something like btnUpCounter so then you can add another for btnDownCounter. Then when the up button is pressed it would add to btnUpCounter (like the code I showed in the previous comment) and you'd have another so when the down button is pressed it adds to btnDownCounter and when that reaches 6 you decrease your value by one and reset the btnDownCounter. So, essentially you'd have something like this: if (btnUpCurrentState == pressed) { btnUpCounter++; // Increment the up button counter by one if (btnUpCounter == 6) { aNumber = aNumber + 1; // Could also use aNumber++; btnUpCounter = 0; // Reset the button counter } ... Other code from the video (Serial print and while loop) here } if (btnDownCurrentState == pressed) { btnDownCounter++; // Increment the down button counter by one if (btnDownCounter == 6) { aNumber = aNumber - 1; // Could also use aNumber--; btnDownCounter = 0; // Reset the button counter } ... Other code from the video (Serial print and while loop) here } Does that make sense? (you'd also have to change "currentState" to btnUpCurrentState and add one for btnDownCurrentState since you'll have two buttons.)
@@RobotResearchLab essentially I have a scenario where i need to create a monitoring system for a theme park ride which will count the people coming in. 6 people maximum is allowed on the ride. Ride takes 30 seconds and goes automatically. Every 6 people is 1 minute queue time.
Hi I used nema17 stepper motor+driver l298n+UNO R3 in a mechanical system, the code written below provides the movements I want, but when a push button is pressed, I need to add what code to the text below and connect the button to which inputs on the uno r3. It would be greatly appreciated if you could help me. Like Pushpull, when the button is pressed, I want the motor to proceed a certain step counterclockwise and stop and continue the same operation from where it left off when the button is pressed, but somehow I couldn't. */ #include const int stepsPerRevolution = 150; // change this to fit the number of steps per revolution // for your engine // initialize the stepper library on pins 8 through 11: Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11); void setup() { // set the speed at 90 pm: myStepper.setSpeed(60); // initialize the serial port: Serial.begin(9600); } void loop() { // step one revolution in one direction: Serial.println("counterclockwise"); myStepper.step(stepsPerRevolution); delay(500);
I'm not sure I fully understand what you want to do. If you want to move to a certain position after the button is pressed then you would first need to add the code (if statement) to detect if your button is pressed. Then from there you would put the movement code inside the if statement so that if the button is pressed, the motor moves to the position you want. If you can try to do as much as possible and then send me the code you came up with I can try to help some more.
@@RobotResearchLab sure, this isn't all my code, but essentially this is the part of the code that I just can't get to work; in this instance of code it will only print "OFF". My main code is part of a function() and when I call it to setup() it doesn't work, I've been thinking that I need something like "while(Serial.available()==0);" but in terms for push-buttons, not sure tho #define SWITCH0 12 //push-button #0 pin void setup() { Serial.begin(115200); int sw0; //reading for push-button #0 sw0 = digitalRead(SWITCH0); if(sw0 == LOW) Serial.print("ON"); else Serial.print("OFF"); } void loop() {}
@@325.minutes Ahh, okay. Yeah, the setup() function only gets called once so, I misunderstood your initial question. It works anywhere but setup only gets called once so it's only going to check the button state once in this case. What are you trying to do with your button? That will determine whether you want it in the setup() or loop()
@@RobotResearchLab currently I'm working on a project that is essentially a restaurant menu that has multiple functions(), and I'm using the buttons as inputs to order items off the menu (in a binary configuration), I guess there's no specific preference as why the code should be in setup() or loop() (that I could think of at least) but I guess I was just wondering How I would be able to get it to work in setup()
@@325.minutes Typically the use case for having something like this in the setup() function is if you want to turn your project on but you don't want it to start the main code until you push a button. An example would be a Line Follow competition, you would generally turn your robot on but wait for the judge to say GO! before starting the line follow. In this case you might add a loop in the setup that keeps checking the button, once the button is pressed it would go on to the loop() function to start the line follow process. If you want a menu then I would suggest putting it in the loop, that's actually not a bad idea for a video and that would be super quick to make which is good given my limited time lately ha ha. The reason I would suggest using the loop() is because, unless you only want to check that button state once, it's more difficult to use the setup function. In any case, here is how you would put the button in the setup() as an example, to wait and only enter the loop() once the button is pressed. I haven't tested this code but, as long as you have a button that is tied to GND it should work. This will only print once though, then it will go on to the loop(). If you want it to keep checking the button you'd have to wrap all that code in a while(true) loop, but that's what the loop() function is so you might as well just use that. This also doesn't wait for the button to go HIGH before continuing so, as is, if you moved this code to the loop() function, it would keep printing while the button is pressed. You'd have to add in the code to wait for it to be let go if you wanted that. I hope this helps. const char BUTTON_PIN = 2; void setup() { // Pull the button HIGH pinMode(BUTTON_PIN, INPUT_PULLUP); // While the buton is HIGH (not pressed) while(digitalRead(BUTTON_PIN) == HIGH) { // This will loop until the button is pressed (sending it LOW) } // This will only print when the button is pressed Serial.println("Yo"); }
i never made anything like this i follow all the steps and im good, let me explain i had an handbrake to games working with magnets but it was really unreliable and it broke, so im just trying to re-use it has a button but after i did all this i try to select the input to a game to work has handbrake but it doesnt detect any the button.. idk if you understand what im trying to say before the arduino showed has a controller and now shows unspecified btw my arduino is a PRO MICRO, do i sellect the board micro or pro/pro mini
so i got it i just had to download a joystick example and input this #include "Joystick.h" im sorry for all the spam but its my first time working with any hardware at all, you helped me a lot i subbed and suddently i gained a new hobby
ola. pelo que me deu a entender pecebes de arduino e gostas de jogar. eu comprei recentemente uma button box para simulador. acontece que eu jogo ACC na xbox. no acc nao da para escolher as teclas do teclado e ja veem definidas como por exemplo para aumentar o ABS e Shift+a . e nao sei fazer. Podes me ajudar? abraco
I was not aware the code wasn't readable but I've received comments from others as well so I will try to remember to increase the font size in future videos... when I can get back to making them, thanks for commenting and providing feedback.
@@johnalbu2319 Ha ha, that makes a little more sense. TBH I have received similar comments, I'm not sure if they were watching on a TV. I did check out my video and it could definitely benefit from larger font. I usually review my videos full screen on a laptop so that could also be why it looks okay to me. In any case, I will be trying to remember to increase the font for future videos... whenever I get time to get back to them. Thanks again for the feedback, and also for the clarification 😄
The intent was for you to follow along since it's such a small code sketch but I've posted the code on my site here robotresearchlab.com/2021/01/05/how-to-program-a-push-button-with-arduino/
@@RobotResearchLab Actually I am working on interlock system for that I need 4 push button and when one push button pressed it should be high and others status must be low even pressed but I tried for one push button it didn't work.
@@RobotResearchLab Its Great! I am just intrested into programming - I am currently learning python know some basics and got this video in my recommended and though that it was cool to see that you can get output on things that you do daily using code. I like robotics and never knew anything about Arduino and think this would be great for me to buy as I did similar projects like solar pannel movement when I was younger.
A while loop is "basically" stopping the program but a delay IS stopping the program. The video shows how a printout will repeatedly print while the button is being held down and that's exactly what I'm avoiding with the loop, if I change to a delay then this doesn't solve the problem. Also, you can do other things in the while loop so that your code continues while holding the button but just doesn't activate the button code repeatedly. As an example, check this recent live stream out ua-cam.com/video/HhhEHECKywM/v-deo.html, I use the while loop and still execute code while the button is being held down. I personally try to avoid delays because they do in fact stop the code completely and you can't do anything else during the delay. In some cases a delay is fine, just as in your case, it may be fine but in this particular video, as mentioned, I'm trying to avoid repeatedly triggering the button code when the button is held but also allowing the program to pick up button clicks that are extremely close together.
This is exactly what I've been looking for, you earned a sub, but most importantly you earned my absolute respect 💯
Thank so much for that - new to Arduino and was going all around the houses just to get it to perform a repeated action with a stepper - this video made it so simple
Thank you for your feedback, I'm glad it helped.
Man you're the best . I went through the comments and you're helping all the beginners. I also had a little problem . Whenever I release the buttons , some extra A's are being printed.
Hey thanks, I like helping people out, happy to help. Sorry for the delay, I responded to your other comment. Let me know if that helps. If it's happening when you release, try putting a short delay after the release is detected maybe something like delay(100) or try increasing if it doesn't help. If you get to over 250 then it's likely something else unless you're really slowly letting the button go.
next time teach us switch w/ led activation. thanks
Never knew about the "while" command, Thanks !
DUDE WHY CAN'T YOU JUST PUT THE STINKING CODE IN THE DISCRIPTION?
I don't typically post the code in the video because I'd prefer that people write the code as they follow along so they can better learn the code rather than copying and pasting. That being said, I do generally always post the code in my website, I just don't link it for the reason mentioned. Here is the code if you'd like to copy/paste it, thanks for watching and commenting. robotresearchlab.com/2021/01/05/how-to-program-a-push-button-with-arduino/
you are absolutely underrated. Thank you so much for all of this helpful content
Thank you for the feedback, I'm glad I could help.
For beginners, it helps to add the actual sketch to the video notes. Even at full screen, your screenshots are too blurry to see the small punctuation marks clearly (and a pain in the **** to transcribe by pausing the video every two seconds)
Sorry about that, it's recorded in 1080p and looked good from my view. In any case I do have a write up with the code. I don't always pay the code for the smaller projects because I like to have people follow along and understand the code.
Here's a link to the post with the source code. robotresearchlab.com/2021/01/05/how-to-program-a-push-button-with-arduino/
Sorry again and thanks for the feedback.
Hi, how can I program 6 buttons so that I can use them as inputs in video games?
Sorry for the late reply, the simplest way to do this would be to copy and paste the code but have currentState be each separate button, so you'd have the code as it is in the video, then something like this
currentState = digitalRead(BUTTON_PIN_2);
if (currentState == pressed) {
// Do something here
while(digitalRead(BUTTON_PIN_2) == pressed) {
// Do nothing while button is pressed
}
}
This isn't the best way but it's the easiest to describe in text. A better way would be to create a function that reads a button based on the pin value passed in, then you're code would look something like this (this is much cleaner and repeatable without copying and pasting a lot of code, it's just a simple if statement copied and pasted.
if (buttonPressed(BUTTON_PIN)) {
// Do something here
}
if (buttonPressed(BUTTON_PIN_2) {
// Do something here
}
But you'd have a custom function called buttonPressed() which would return true/false based on the button pin state. That would look like this
bool buttonPressed(char buttonPin) {
if (digitalRead(buttonPin) == pressed) {
// Do something here
while(digitalRead(buttonPin) == pressed) {
// Do nothing while button is pressed
}
return true;
} else {
return false;
}
}
Man, ty looking for an expectation for exatly this kind of setup thank you very much!
Can you make a video where you explain how you could do the same, but instead of printing somethign on your computer, you display it on another apparat, aso another peace of hardware, that just does thing when a button is pressed (could also be a light turning on/off or smth easier than displaying text)
I could do that, but unfortunately, I haven't had any time to make new videos for quite some time now. It would be easy to change this, though, just change the Serial.println() code to do something else instead, like digitalWrite(LED_BUILTIN, HIGH) to turn on the onboard LED. If you want to be able to toggle the LED it would require a couple more lines of code but it's the same concept.
If you need some more information than that, I can help but, I unfortunately won't be able to create a video though.
can you give some amazon links for the things you used
Sure thing, here they are:
Arduino Board: www.amazon.com/gp/product/B01EWOE0UU
Wires: www.amazon.com/gp/product/B005TZJ0AM
Breadboard: www.amazon.com/gp/product/B077PK858F (These are unavailable but there are many other options, don't pay more than $10 for a set of 10-12 of the mini boards)
Breadboard alternative: www.amazon.com/gp/product/B07DL13RZH (This gives you multiple options for different sized projects)
Buttons: www.amazon.com/gp/product/B07WF76VHT (The ones I have are unavailable but I wouldn't recommend the ones I have, I would get these since they're made for breadboards)
But actually, If you're just getting started I would recommend this starter kit, for less than $20 you get everything you need to do many different projects. It includes everything you would need to build the project in the video as well. www.amazon.com/gp/product/B01DGD2GAO
@@RobotResearchLab thanks!
I think there is something called a "debounce" maybe that would also help the pressing to be more ok, awesome vid, just subbed
Debounce is slightly different, it's to counteract the fast on/off that can happen when pressing or releasing a button (called hysteresis). Basically with hysteresis, when you press the button it can make the microcontroller think you pressed the button multiple times. These buttons don't seem to have that issue so luckily I didn't need to go down that rabbit hole with this video. But I do plan to cover this in a future video. Thanks for the feedback and sub, I hope to get more videos out soon, nicer weather means more work outside so we'll see.... Thank again!
@@RobotResearchLab this is probably what's happening with my buttons
@@shukrantpatil I don't have any videos on debounce yet, the easiest (yet hacky) solution to resolve this would be to put a short delay after a press is detected. This way any hysteresis occurring during the press will be ignored during the delay.
This was great. Helped my project a lot, thanks
Thank you for the feedback, it's great to hear it helped.
Just in case you are still watching comments 4 years after uploading this video, I have a request; I am just beginning my Arduino journey and my first project is to program a Flight Simulator controller. The device I have built includes a DPST toggle switch with an [ON] OFF [ON] configuration to control flaps. This is equivalent to 2 pushbuttons in the same switch. Move the toggle up - the flaps move up. Move the toggle down - the flaps move down. I would like my serial monitor to print a line with "UP" or "DOWN" when the toggle is moved in the corresponding direction. Any advice would be amazing and greatly appreciated.
Worked well, thanks! I need to debounce next as this is for a midi controller and it's bouncing like mad!! Subbed 👍❤️😎
Thanks for the feedback. Debounce is on my list but unfortunately I haven't had time for videos lately (been saying that for way too long).
The easiest way to hack around that would be to put a quick delay after the button press is detected (that way multiple presses within a certain time won't trigger the code multiple times). Probably something like `delay(100)` would work as a guess. There's also button libraries that handle debounce but I'd suggest you read through the code in the library so you understand how they're doing it and it doesn't work against you.
Thanks again.
Thank you for a relatively simple explanation of this code... Now what would I do different if I were using this code to cause the computer to see a button pressed on a joystick?
I race online and have built a 32 button box for controlling different functions. However I need to add three toggle switches and I have spent hours trying to find a code I could edit to make it work using a different Arduino Pro micro, hopefully if you can answer my question about the joystick I can finish that project.
Great Help, and Really well explained. Thank You!!
I have tried it and it fixed a problem that has been driving me mad.
Please can you tell me how I can multiply this exact code to control multiple buttons?
Hey, I'm glad it helped, if you want to reuse code for different objects, the best way is to create a function. Functions allow you to reuse code with slight changes so it works for multiple situations.
In this example code I simply moved the code from the loop() into its own function.
bool isButtonPressed(int buttonPin) {
// Read button
bool currentState = digitalRead(buttonPin);
if (currentState == pressed) {
Serial.print("Button on pin ");
Serial.print(buttonPin);
Serial.println(" pressed");
while(digitalRead(buttonPin) == pressed) {
// Do nothing while the button is pressed
}
return pressed;
}
}
Now, this code can be used for a button on any pin by simply supplying the pin number, an example would be the following.
void loop() {
// Check if the button on pin one is pressed
isButtonPressed(1);
// Check if the button on pin 4 is pressed
isButtonPressed(4)
}
Now, because I added a "return type" (bool isButtonPressed), the bool means our function returns a bool (true/false). So, you can actually remove the Serial statements so all the code does is respond back with whether the button was pressed, and now you can do different things for each button, see below.
void loop() {
bool btnState = false;
// Check if the button on pin one is pressed
btnState = isButtonPressed(1);
if (btnState == pressed) {
// Do something for this button
}
// Check if the button on pin 4 is pressed
// You can also use a shorter version of code that does the same thing
if (isButtonPressed(4) == pressed) {
// Do something for this button
}
}
Thanks for watching and for the feedback, I hope this helps.
DISCLAIMER: This code was written in the comment so it hasn't been tested.
@@RobotResearchLab Wow that's AMAZING!!! thank you so much.
I' can't wait to get stuck into this.😃
thanks you realy helped my project
you have definetly earned a sub
I would like to know how you can take one momentary button and get 2 functions from it with a short and long press. The first short press will make an LED blink untill the button is pressed short again to stop it blinking. The second function of long press will sound a horn as long as the button is pressed and stop when the button is released.
Sorry for the delay. This is a great question and an interesting problem. I hadn't responded as I wanted to do a video on it but I'm so swamped I haven't had a chance. So, I've never done one but I think I'm going to try and do a live stream tomorrow and get this done.
I've generally stayed away from live stream because my edited videos are already long so a live stream is going to be longer... we'll see how it goes, hopefully you still need this but if not, it's a learning experience for me anyway and maybe it will help someone else.
@@RobotResearchLab can i watch the livestream afterwards or only during? I still need this but i won't be able to follow the livestream tomorrow
@@joscornelissen5626 you can watch it after, it will be saved just like a normal video.
Here you go, let me know if you like it or dislike it, what I could do better. I hope this helps, thanks for watching. ua-cam.com/video/HhhEHECKywM/v-deo.html
Hello, I'm working on a graduation project. He talks about tracking down children, women and the elderly by parents.
Strange.... I'm not sure how to respond to this.
can you make a video that will play a 30 second audio then fade on 6 led lights, then turn off after 10 or 15 seconds with a push button using an arduino nano?
great tutorial video with really good explanations!!
Thank you
Hey there! this is very useful video, thanks for it!
Have you made any video explaining how to write a code for multiple buttons build in a matrix? Happy to give more details if my question is not clear enough ;)
No, I have not made any videos using multiple buttons or buttons in a matrix. Unfortunately I haven't had time to make any new videos for a while but I will add this to my list.
Will you please make a video for me wherein I will be using four switches, each one will be doing different jobs. For example: Switch 1 when pressed will switch ON light. Repressed will switch OFF. Switch 2 will start fan when pressed again switch off fan. Like wise for other switches. Use of Arduino Uno, Switch and Relays requested. Thanks in advance.
Hey, thanks for watching and commenting. I haven't had time lately to create a new video so I probably won't get to this soon. I'd like to use your idea for a video that shows how to create a function but what I would suggest is get one button working, then copy and paste the code three more times and change the values for each button. It really should be put in a function so you don't copy/paste but if you don't know how then it's easier to just copy/paste.
If you need help you can contact me through my website, it'll send me a personal email and then when I respond you can attach your code so I can take a look at any problems you're having. robotresearchlab.com/contact-me/
@@RobotResearchLab Many thanks for considering my request. Good day.
@@RobotResearchLab Which part of the code do i copy because i wanna add multipule buttons
@@MarkoCR221L There are many ways to do this, personally I would copy all of the code inside of the loop() function and put it in a new function so the code can be reused rather than copy and paste the same code over and over. I added a parameter to the custom function that accepts the pin the button is on, now this function will work for any pin that you tell it has a button on it. I also added a return bool value, if the button is pressed it returns true, if it isn't then it returns false. This might be confusing since "pressed" is set to false so you can certainly change the function to return whatever pressed is set to instead, I'll show that code after this code below.
void loop() {
if (buttonPressed(BUTTON1_PIN)) {
// Do something here for button 1
Serial.print("Hello from button on pin ");
Serial.println(BUTTON1_PIN)
}
if (buttonPressed(BUTTON2_PIN)) {
// Do something here for button 2
Serial.print("You pressed the button on pin ");
Serial.println(BUTTON1_PIN)
}
}
bool buttonPressed(char btnPin) {
// Read button
bool currentState = digitalRead(btnPin);
if (currentState == pressed) {
while(digitalRead(btnPin) == pressed) {
// Do nothing while button is pressed
}
// Return that the button was pressed
return true;
}
// Return that the button was not pressed
return false;
}
Now, as mentioned, you could alter that code so it returns whatever "pressed" is set to by changing the return values from 'true' and 'false' to
return pressed; // Return a value of pressed
and
return !pressed; // Return a value of NOT pressed
This option is a little cleaner because now, if you change the value of pressed because maybe you're using a pull down resistor, the function will still work, you'd just simply change the value of pressed to 'true' instead of 'false'.
I hope this helps.
@@RobotResearchLab thanks mate
Is "hysteresis" the same as "debouncing" a button?
a really good tutorial thx man
When you press the button nothing else can work in the sketch? it halts the loop? is this where interrupts are needed?
Not necessarily, if you put this same code in an interrupt it would still halt the program because the chip would be performing the interrupt function. Interrupts are typically used in cases where you don't want to keep checking the state of a pin, you can have code automatically execute when a pin goes high, low, or just changes in either direction.
In order to allow the code to do something else, you'd have to modify the code to remove the while loop. Something like
Check if the button is pressed, if it is, check to see if it was pressed the last time you checked. If it was pressed the last time then we can assume they're still holding the button down so don't execute the code again, only execute the code when the button is currently pressed but wasn't pressed the last time we checked.
I hope that makes sense, if not let me know and I'll try to explain better, I might have responded to another comment with actual code so you can check the other comments (since there shouldn't be that many unfortunately lol).
Hey nice video 😁. I want to ask you, do you know the code when i pressed the button for 5 second and then it will print "Hello" ?. Thank you
Hey, sorry for the delay, the code is going to depend on whether you want to do other things while also checking for the button being held for 5 seconds.
If you just want it to check for five seconds after the button is pressed and do nothing else you just use a while loop for 5 seconds after the button is pressed, leaving the loop only if five seconds has passed or if the button is released. Here is some un-tested code that should get you started. Keep in mind, checking if the button is pressed assumes BUTTON_PIN is set and that a digitalRead() HIGH means pressed. This code should allow you to hold the button and it will execute the print statement for every 5 seconds the button is held.
----------------------------------
void loop() {
checkButton()
}
void checkButton() {
static bool lastButtonState = false;
static unsigned long lastPressedTime = 0;
// If the button is pressed
if (digitalRead(BUTTON_PIN)) {
if (lastButtonState == false) {
// The button was just pressed, record the state and time
lastButtonState = true;
lastPressedTime = millis();
} else {
// The button was already pressed, check the time
if (millis() - lastPressedTime > 5000) {
// Button was pressed for five seconds!!!
Serial.println("Hello")
// Reset the time last pressed so it only executes every 5 seconds
lastPressedTime = millis()
}
}
} else {
// Button isn't pressed so update the lastButtonState
lastButtonState = false
}
}
Is it important to use resistors?
You "should" use resistors but you don't necessarily have to. The reason the resistor is there is because the pin readings can fluctuate if left "floating". The resistor forces the reading to be either high or low when there is no direct input source. So, yes it can work without the resistor but you may get bad readings, also, Arduino has built in pull up resistors in the chips so you can use the internal resistors (but they are only pull up resistors so you'd need to make your button a pull down, or pull to ground instead of pull to 5V).
Hey buddy any advice, i want to control my claw machine with my keyboard. Any ideas where to start? I want to be able to moved the claw and drop it as well.
Hmmm, I don't have any videos on this sort of thing, I actually don't even have any on Servos which is probably something I should have covered. In any case, to answer your question:
1. Start by simply trying to manage user inputs, for that I would start here www.arduino.cc/reference/en/language/functions/communication/serial/read/
2. Now, I would modify that code to make a motor movement instead of printing out what was entered. You'll either need a series of if, else-if, and else statements or a switch statement
3. Once you have all that down I would start to define keys for each individual servo. I'm assuming you probably have three much like a human arm (shoulder rotation, elbow bending, and wrist bending)
4. You could modify the code to accept three values and move each servo to the value passed in
As a bonus, since this is all done by reading character inputs you could easily modify this to work with bluetooth as an enhancement. I should have a video on adding bluetooth, but it essentially does the same thing except you can add buttons to a phone app and press the buttons on your phone to control the arm instead of having to send one character at a time (the button sends the character for you automatically).
@@RobotResearchLab , any idea how much you would charge me to get it setup?
@@melannieworld Unfortunately I don't have much time for robotics lately, I've got a lot of personal tasks to complete before I can get back to making videos and helping directly. If you contact me through my website, it will send me an email and I can try to help you through emails. robotresearchlab.com/contact-me/
Thank you so much this has been very informative
Thank you for the feedback
How to put push button in water level sensor?
What are you trying to have the push button do for the water level sensor, take a reading, print something, etc?
my project did 200% progress with this viedeo
I love it, awesome to hear, thank you.
How to connect switch with variable resistor to control light altered (switch-on/off,variable -as dimmer)
Just to clarify, you want an LED that has a variable resistor and a button? Like a wall switch where you can set the brightness but control on/off with a button?
nice upload Robot Research Lab. I killed the thumbs up on your video. Maintain up the really good work.
Ha ha, thanks, I'm hoping to have new content at some point here, summers make it hard, thanks for the feedback and support, much appreciated.
Thankyou bro....but verious type of action ( e.g: set , increase and decrease action) by used same push button in Arduino program.
I'm not sure what you mean, I'll need some more information. What are the "rules" to determine increase vs decrease?
Is it something like the button goes up and when it reaches the max it starts decreasing, or is there a certain button press sequence to increase vs decrease? Like, press twice quickly to increase or press once to decrease or something like that.
how can i impliment a link so when i press the button it opens for example UA-cam?
If you want it to open a link on your computer, that would be a tricky one, the easiest solution I can think of is to use the Arduino to execute a macro (or script) on your computer (you would need to use an Arduino Pro board). It is a little more involved than something that can be explained over a comment. Interesting idea though, maybe I'll create a video for it... not that it would probably be watched by a lot of people, it's a pretty specific use case lol. I'll add it to my list of ideas though, thanks for watching.
@@RobotResearchLab Thank you men, I also think it would be a great idea. I'll sub rn so I don't miss it
Is there a reason you used const Char instead of const int? Im trying to use the same type of button to start my code, pretty much once the button is pressed it will run through my code once. Great video and tutorial thank you by the way.
It won't make any functional difference. I use 'char' when assigning pins just because char values go from -128 to 127 Since it's only one byte it takes up less space than an int which is two bytes. Int types range from -32,768 to 32,767
Technically it takes slightly longer to process variables that are larger but the difference between char and int is very minimal, mostly it's about saving space but again, I wouldn't worry about that unless it became an issue.
@@RobotResearchLab Thanks! Makes sense. Im using pin 51 as i have a CNC shield in so all the others are taken.
Hey man, I'm working on a school project. My goal is to have 2 push buttons and each will control a separate LED, when one button is pushed the corresponding LED will extinguish while the other one flashes. I have it working but I need the serial monitor to say every time I press a button. My problem is when I use the "while" statement it stops my other LED from blinking while the button is pressed. Do you think a "do-while" statement could resolve my issue? any suggestions are welcome. Awesome video!
The best way that I can think to resolve this issue is to use an interrupt triggered by the timer, it basically allows a function to be run regardless of the code currently being run, it would switch over to the led function and then come back to the main code.
I don't have any videos on timer interrupts but this article blog.wokwi.com/5-ways-to-blink-an-led-with-arduino/#blinking-with-timers- should help you out. If you just need the one to keep blinking all the time you can use the code as is. If you need it to blink under certain situations you'll need to modify the blink interrupt routine code so that there is a boolean such as "enabled" or "shouldBlink" so it knows whether or not the LED should be blinking. Then just add an if statement like this.
ISR(TIMER1_OVF_vect) {
if (shouldBlink) {
digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
}
Lastly, for the record, you really shouldn't read a digital pin if the pinMode is set to OUTPUT, it probably won't give you any issues but to be safe or if you are having issues you might want to add a pinMode() statement to change it to OUTPUT when its digitalWrite and INPUT when it's digitalRead.
and what if i want that the oled Display turned off (after 10 sec.) after pushing the button. Any idea?
For that you'd have to add some more variables but it's doable. You would want a variable that holds the value of when the button was last pressed (let's call the variable lastBtnPressMillis) and you'll need one to know if there is a pending action (let's make that a bool and call it pendingBtnAction). It will either need to be a global variable or a static variable, if you can't figure out static variables just go with global for now. So, when the button is pressed, set the lastBtnPressMillis to the current time (lastBtnPressMillis = millis()) and set pendingBtnAction to true. Then you'll have to add a check for that variable in the button function, maybe something like this
if (pendingBtnAction && millis() - lastBtnPressMillis > 10000) {
// turn off your OLED here
// Reset the pending action flag until the next btn press
pendingBtnAction = false;
}
These aren't the easiest things to discuss via comments and I don't have the time to make videos lately so let me know if any of this isn't clear. This is by no means the only solution, this is just off the top of my head how I would do it.
@@RobotResearchLab thank you very much. i just solved the problem with the command from ssd1306 lib. display.ssd1306_command(SSD1306_DISPLAYOFF); and if i want to turn on the oled display, display.ssd1306_command(SSD1306_DISPLAYON);
Thank you really helpful now I’ve just gotta work out how to do this with many buttons and make it so a game can understand it haha
Let me know if you run into troubles, maybe I can make a video about it... I'll eventually get time to make more videos ha ha.
@@RobotResearchLab I’ve tried loads of different ways of trying to add multiple buttons and give each button a name to be recognised on pc but i can’t seem to get it to work any tips or videos you have done
@@johnmasters2099 Oh okay, you're trying to make a game controller that can enter keys on a PC (basically a keyboard)?
@@RobotResearchLab yes basically but I’m also adding a joystick using potentiometers but I havnt got that far yet lol thort I’d master the button coding first lmao
@@johnmasters2099 This should be as easy as just using the Keyboard and Mouse libraries included with the Arduino core libraries. I personally haven't used them BUT I do know that only certain boards will work. Essentially I'd suggest the Arduino Pro Micro (or third party version) as it'll be the cheapest of the boards that have this ability. For how to do this, again, I haven't done it myself but looking over this article looks promising. maker.pro/arduino/projects/how-to-turn-an-arduino-into-a-keystroke-automation-tool
👌👌👌
hey bro. i need a help. i have this project where we have two buttons and we have to code one button to play music and the other button to pause the music. we have the code for the music(we going to rickroll the teacher lmao), but he dont know how to do the code for the the buttons to play and pause. hope u see this and help us out. we need to submit on thursday 11th aug
I can definitely try to help you out, especially if it's to rickroll someone, that's a noble cause ha ha. If you contact me through robotresearchlab.com/contact-me/ it will forward to my email and I can reply back to you personally (just be sure to provide your real email address so I can get back to you).
hi im trying to make a button box for a sim racing setup and i have no experience at all do you think you could help me i have a arduino pro micro and 9 2 pins button
Sure, you can contact me through this form and it will send me an email. Then I can respond back to you via email instead of trying to help through YT comments. robotresearchlab.com/contact-me/
This video is really helpful, but there is a problem with my code. I am trying to make a servo motor move when I press the button, but whenever I verify the code I get the error message "a function-definition is not allowed here before '{' token". Here is my code
const char BUTTON_PIN = 8;
bool pressed = false;
void setup() {
Serial.begin(115200);
pinMode(BUTTON_PIN, INPUT_PULLUP);
}
void loop() {
bool currentState = digitalRead(BUTTON_PIN);
if (currentState == pressed) {
#include
Servo servo;
void setup() {
servo.attach(9);
servo.write(0);
delay(2000);
}
void loop() {
servo.write(90);
delay(1000);
servo.write(0);
delay(1000);
}
}
}
I am also pretty new to programing with arduino so I don't know that much about it. If you know how to fix the problem that would be amazing.
Sorry I didn't see this comment, I'm not getting notified of every comment by UA-cam.
Anyway, hopefully you've figured out the issue by now but it's an issue with your curly braces. You have a function declaration (void loop()) inside an if statement. Function declaration must be outside of all code blocks. Also, you can't have two functions named void loop(). It looks like you just accidentally copied the loop function into your if statement.
Thanks, I did end up fixing the issue, great video by the way.
I used this code using analog for push button. I couldn't get past the while loop. Is there any solution?
Using an analog pin? Are you using analogRead() instead of digitalRead(). You can use analog pins as digital pins, they are in fact digital pins but have the added feature of a DAC which converts digital to analog but you certainly don't have to use that. If you are using analogRead then ANY value that is not 0 will return a true when you do "if (analogRead(pin) == true)".
If you're using an analog pin as a digital pin just simply use digitalRead(pin) and it should work the same.
Let me know if this helps or you need more help.
what are you printing the text to?
I try doing this in notepad but it doesn't work.
You can either go to Tools-->Serial Monitor or click the magnifying glass in the upper right toolbar. It's a built in tool for monitoring serial inputs.
@@RobotResearchLab Thanks for the reply, I managed to figure it out shortly after.
@@RobotResearchLab Super helpful tutorial and I managed to get this to print to serial. But is there a way to actually get this to type "Hello" in Notepad?
@@theyutethatdoot7895 In order to do this there are a few things that need to be done ahead of time. In its simplest solution, if you had Notepad open and the cursor was in the application ready to type then you could use something like an Arduino Pro Micro which can act as a keyboard or mouse for any PC. Then you would have to use the Keyboard library to send the text to the computer and it would basically be as if you were typing.
It's possible that you could pair an Arduino sketch with a script on your PC so that when the Arduino is detected, it opens Notepad and starts typing but that would be pretty involved and require a video to explain.
First and foremost though, you would need an Arduino that has a chip capable of supporting keyboard and mouse functions (Pro Micro is probably the cheapest/most easy to find and non-Arduino brands will work as long as they market as a Pro Micro board).
@@RobotResearchLab Thank you for the thorough reply. I'll try the Arduino Pro Micro since I have all the other components on hand. Again, thank you!
ayyyyyy I was 1000 th sub still working with the code since I messed something up xD
Ha ha, thanks. Let me know if you need help with something.
@@RobotResearchLab actually Im trying to program a button to act as a keyboard key right now and havent been able to find any tutorials
@@Qwzdf Ah, so like a macro to make your Arduino button simulate a keyboard button (or sequence)? If so, what board are you using?
@@RobotResearchLab yes, Im using uno 3
@@Qwzdf Just a heads up, if you want to control keys on a computer you need a specific Arduino board for that. Here is a list of supported boards, I always used a Pro Micro (generic brands work too, doesn't have to be Arduino brand)
www.arduino.cc/reference/en/libraries/keyboard/
Good evening, I am a student and am working on my final project. I want to ask what if the "Push the Button" 5 seconds turns on then turns off again. Thank you please help
Sorry for the late reply, do you still need help on this? If so, I need some more information as I'm not understanding your question exactly. Do you want to push a button for 5 seconds in order to trigger some action or push the button and have it wait five seconds before doing something... or something different than that?
Do you know how I could do it so when the button is pressed 6 times, a number is then +1?
Sure, I'll try to explain in a comment, hopefully it translates.
What you'd want to do is, in the if statement for the button (if currentState == pressed) you want to add to a variable that will count the number of times the button is pressed. So, for starters you'll need to add a variable in the global variables (let's call that btnCounter). Then each time the button is pressed, increment that counter. Then add an if statement to increment your value if the btnCounter is equal to 6... then reset the button counter. Here's an example
1. Add a variable up top like:
char btnCounter = 0;
2. Modify the if statement to keep track of button counts and add an if statement to increment your variable
if (currentState == pressed) {
btnCounter++; // Increment the button counter by one
if (btnCounter == 6) {
aNumber = aNumber + 1; // Could also use aNumber++;
btnCounter = 0; // Reset the button counter
}
... Other code from the video (Serial print and while loop) here
}
You could simplify it even more so you don't need to reset the counter by using `if (btnCounter % 6 == 0)` but don't worry about that until you understand the code above.
@@RobotResearchLab Ah that's great thank you, appreciate it. One more thing. Could I use another button which would make the number go down. And everytime it was pushed 6 times it would decrease by 1? Basically the same but opposite
@@tdb1940 Yeah, definitely. For that you would need a whole other if statement to handle the other button (the one that handles going down). Everything else would be the same only you might want to change btnCounter to something like btnUpCounter so then you can add another for btnDownCounter. Then when the up button is pressed it would add to btnUpCounter (like the code I showed in the previous comment) and you'd have another so when the down button is pressed it adds to btnDownCounter and when that reaches 6 you decrease your value by one and reset the btnDownCounter. So, essentially you'd have something like this:
if (btnUpCurrentState == pressed) {
btnUpCounter++; // Increment the up button counter by one
if (btnUpCounter == 6) {
aNumber = aNumber + 1; // Could also use aNumber++;
btnUpCounter = 0; // Reset the button counter
}
... Other code from the video (Serial print and while loop) here
}
if (btnDownCurrentState == pressed) {
btnDownCounter++; // Increment the down button counter by one
if (btnDownCounter == 6) {
aNumber = aNumber - 1; // Could also use aNumber--;
btnDownCounter = 0; // Reset the button counter
}
... Other code from the video (Serial print and while loop) here
}
Does that make sense? (you'd also have to change "currentState" to btnUpCurrentState and add one for btnDownCurrentState since you'll have two buttons.)
@@RobotResearchLab This is my code at the moment but it doesn't seem to be working?
const char btnUpCounter = 2;
const char btnDownCounter = 3;
void setup() {
Serial.begin(9600);
pinMode(btnUpCounter, INPUT_PULLUP);
pinMode(btnDownCounter, INPUT_PULLUP);
}
void loop() {
if(btnUpCounter == false){
btnUpCounter++; // increment the up button counter by one
if(btnUpCounter == 6){
aNumber = aNumber + 1;
btnDownCounter = 0; // resets the button counter
}
digitalRead(btnUpCounter)
if(digitalRead(btnUpCounter == false) {
Serial.println("Hello");
while(digitalRead(btnUpCounter) == false) {
}
if(btnDownCounter == false){
btnDownCounter++; // increment the down button counter by one
if(btnDownCouter == 6) {
aNumber = aNumber -1;
btnDownCounter = 0; // reset button counter
digitalRead(btnDownCounter)
if(digitalRead(btnDownCounter == false) {
Serial.println("Hello");
while(digitalRead(btnDownCounter) == false) {
}
}
}
}
@@RobotResearchLab essentially I have a scenario where i need to create a monitoring system for a theme park ride which will count the people coming in. 6 people maximum is allowed on the ride. Ride takes 30 seconds and goes automatically. Every 6 people is 1 minute queue time.
Hi I used nema17 stepper motor+driver l298n+UNO R3 in a mechanical system, the code written below provides the movements I want, but when a push button is pressed, I need to add what code to the text below and connect the button to which inputs on the uno r3. It would be greatly appreciated if you could help me. Like Pushpull, when the button is pressed, I want the motor to proceed a certain step counterclockwise and stop and continue the same operation from where it left off when the button is pressed, but somehow I couldn't. */ #include const int stepsPerRevolution = 150; // change this to fit the number of steps per revolution // for your engine // initialize the stepper library on pins 8 through 11: Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11); void setup() { // set the speed at 90 pm: myStepper.setSpeed(60); // initialize the serial port: Serial.begin(9600); } void loop() { // step one revolution in one direction: Serial.println("counterclockwise"); myStepper.step(stepsPerRevolution); delay(500);
I'm not sure I fully understand what you want to do. If you want to move to a certain position after the button is pressed then you would first need to add the code (if statement) to detect if your button is pressed. Then from there you would put the movement code inside the if statement so that if the button is pressed, the motor moves to the position you want.
If you can try to do as much as possible and then send me the code you came up with I can try to help some more.
Do push buttons only work in void loop? Because I can’t seem to get it to work in setup, help would be appropriate!
No, buttons work anywhere in the code, can you provide more details, maybe some of the code so I can take a look?
@@RobotResearchLab sure, this isn't all my code, but essentially this is the part of the code that I just can't get to work; in this instance of code it will only print "OFF".
My main code is part of a function() and when I call it to setup() it doesn't work, I've been thinking that I need something like "while(Serial.available()==0);" but in terms for push-buttons, not sure tho
#define SWITCH0 12 //push-button #0 pin
void setup() {
Serial.begin(115200);
int sw0; //reading for push-button #0
sw0 = digitalRead(SWITCH0);
if(sw0 == LOW)
Serial.print("ON");
else
Serial.print("OFF");
}
void loop() {}
@@325.minutes Ahh, okay. Yeah, the setup() function only gets called once so, I misunderstood your initial question. It works anywhere but setup only gets called once so it's only going to check the button state once in this case.
What are you trying to do with your button? That will determine whether you want it in the setup() or loop()
@@RobotResearchLab currently I'm working on a project that is essentially a restaurant menu that has multiple functions(), and I'm using the buttons as inputs to order items off the menu (in a binary configuration), I guess there's no specific preference as why the code should be in setup() or loop() (that I could think of at least) but I guess I was just wondering How I would be able to get it to work in setup()
@@325.minutes Typically the use case for having something like this in the setup() function is if you want to turn your project on but you don't want it to start the main code until you push a button. An example would be a Line Follow competition, you would generally turn your robot on but wait for the judge to say GO! before starting the line follow. In this case you might add a loop in the setup that keeps checking the button, once the button is pressed it would go on to the loop() function to start the line follow process.
If you want a menu then I would suggest putting it in the loop, that's actually not a bad idea for a video and that would be super quick to make which is good given my limited time lately ha ha. The reason I would suggest using the loop() is because, unless you only want to check that button state once, it's more difficult to use the setup function.
In any case, here is how you would put the button in the setup() as an example, to wait and only enter the loop() once the button is pressed. I haven't tested this code but, as long as you have a button that is tied to GND it should work. This will only print once though, then it will go on to the loop(). If you want it to keep checking the button you'd have to wrap all that code in a while(true) loop, but that's what the loop() function is so you might as well just use that. This also doesn't wait for the button to go HIGH before continuing so, as is, if you moved this code to the loop() function, it would keep printing while the button is pressed. You'd have to add in the code to wait for it to be let go if you wanted that. I hope this helps.
const char BUTTON_PIN = 2;
void setup() {
// Pull the button HIGH
pinMode(BUTTON_PIN, INPUT_PULLUP);
// While the buton is HIGH (not pressed)
while(digitalRead(BUTTON_PIN) == HIGH) {
// This will loop until the button is pressed (sending it LOW)
}
// This will only print when the button is pressed
Serial.println("Yo");
}
i never made anything like this i follow all the steps and im good, let me explain i had an handbrake to games working with magnets but it was really unreliable and it broke, so im just trying to re-use it has a button but after i did all this i try to select the input to a game to work has handbrake but it doesnt detect any the button.. idk if you understand what im trying to say before the arduino showed has a controller and now shows unspecified btw my arduino is a PRO MICRO, do i sellect the board micro or pro/pro mini
so i got it i just had to download a joystick example and input this #include "Joystick.h"
im sorry for all the spam but its my first time working with any hardware at all, you helped me a lot i subbed and suddently i gained a new hobby
@@Sim-po1mc No problem at all, sorry I didn't get to your comment in time but I'm glad you ended up figuring it out. Thanks for the feedback.
ola. pelo que me deu a entender pecebes de arduino e gostas de jogar. eu comprei recentemente uma button box para simulador. acontece que eu jogo ACC na xbox. no acc nao da para escolher as teclas do teclado e ja veem definidas como por exemplo para aumentar o ABS e Shift+a . e nao sei fazer. Podes me ajudar? abraco
Author should use CTRL + to increase font size for his videos.
I was not aware the code wasn't readable but I've received comments from others as well so I will try to remember to increase the font size in future videos... when I can get back to making them, thanks for commenting and providing feedback.
@@RobotResearchLab - I should clarify that I was watching on UA-cam.
On a TV
@@johnalbu2319 Ha ha, that makes a little more sense. TBH I have received similar comments, I'm not sure if they were watching on a TV. I did check out my video and it could definitely benefit from larger font. I usually review my videos full screen on a laptop so that could also be why it looks okay to me.
In any case, I will be trying to remember to increase the font for future videos... whenever I get time to get back to them.
Thanks again for the feedback, and also for the clarification 😄
That's a very small breadboard
Thx bro please give us the code link
The intent was for you to follow along since it's such a small code sketch but I've posted the code on my site here robotresearchlab.com/2021/01/05/how-to-program-a-push-button-with-arduino/
@@RobotResearchLab okay thx 😜
it doesn't work for me
I'd love to help, but I need more information, what issue are you seeing? (Doesn't compile, doesn't print, etc)
@@RobotResearchLab Actually I am working on interlock system for that I need 4 push button and when one push button pressed it should be high and others status must be low even pressed but I tried for one push button it didn't work.
@@sc-ty1ei Can you provide your code in my contact form? www.robotresearchlab.com/contact
doesn't work
Can you provide me with some more information? I'd be glad to help.
If you send me a message through this link, it will go to my email and I can respond directly from there. robotresearchlab.com/contact-me/
wow
Thanks? I'm not sure if this is a good wow or bad wow ha ha. If good, then thank you. If bad then please let me know what I can improve, thanks again.
@@RobotResearchLab Its Great! I am just intrested into programming - I am currently learning python know some basics and got this video in my recommended and though that it was cool to see that you can get output on things that you do daily using code. I like robotics and never knew anything about Arduino and think this would be great for me to buy as I did similar projects like solar pannel movement when I was younger.
your basicaly stopping the while loop, this will be not good for almost any project you will put it in. you should change that to a deley instead
A while loop is "basically" stopping the program but a delay IS stopping the program. The video shows how a printout will repeatedly print while the button is being held down and that's exactly what I'm avoiding with the loop, if I change to a delay then this doesn't solve the problem. Also, you can do other things in the while loop so that your code continues while holding the button but just doesn't activate the button code repeatedly.
As an example, check this recent live stream out ua-cam.com/video/HhhEHECKywM/v-deo.html, I use the while loop and still execute code while the button is being held down. I personally try to avoid delays because they do in fact stop the code completely and you can't do anything else during the delay. In some cases a delay is fine, just as in your case, it may be fine but in this particular video, as mentioned, I'm trying to avoid repeatedly triggering the button code when the button is held but also allowing the program to pick up button clicks that are extremely close together.