Arduino Make a Led Stay Lit Until Pressed Again
Do you take an awarding where you want multiple buttons for dissimilar user inputs? Maybe you lot have a timer and yous want one button for minutes and another for hours.
Just there is a problem – you but accept room for i push!
In this tutorial, we are going to use Arduino to explore how to make 1 push button have the functionality of two or more.
You Will Need:
(1) Momentary push button
(five) Jumper wires
(1) Solderless breadboard
(2) LEDs
(2) 220 Ohm resistors
Set up The Excursion:
To demonstrate making i button have the functionality of two or more, we will set up a simple circuit with 2 LEDs and a button. Based on how we printing the push, different LEDs will illuminate.
Follow the instructions and schematic beneath to get the circuit ready earlier we dive into the mechanics of the Arduino lawmaking.
- Using a jumper wire, connect any GND pin from the Arduino, to the ground runway on your breadboard.
- Place an LED on your breadboard, brand sure to notation which way the long leg is facing.
- Using a jumper wire, connect pin thirteen from your Arduino to the breadboard in the aforementioned channel where you take the long leg of the LED fastened.
- Now connect one side of the 220 Ohm resistor to the short leg of the LED, and connect the other leg to the ground track on the breadboard. The orientation of the resistor doesn't thing.
- Repeat this using pivot 12, and another LED and resistor.
- Finally, identify your push button on the breadboard. Depending on the fashion of your pushbutton, they often fit well straddling the long trench that goes through the breadboard.
- Connect a jumper wire from one side of the push to pin 2 on the Arduino.
- Connect a jumper wire from the other side of the button to the ground rail on the breadboard.
That's information technology for the excursion setup. At present, when you press the push push (which will electrically connect both sides of the button), pivot 2 to will have footing voltage applied. We will use this ground voltage input to trigger our dissimilar functions.
Examine the Sketch:
There are couple ways to implement the multi-function button press using Arduino.
Ane way is to have the number of presses determine the output. For example, a single click might highlight the "hour" field of an LCD timer and a double click might highlight the "minute" field of the display.
Another way that we can implement multiple functions with one push is for the user to concur downward the push button for different lengths of time with the length of the hold determining the output.
For example, if the user holds the push for half a second and releases, something happens. If she holds it for ii seconds, something unlike happens.
This latter method of using button hold length time to decide separate functions is the strategy we will learn here.
Before I become any farther though, I would similar to thank Steve for creating the base Arduino lawmaking that we will exist using. Steve is a member of the Premium Arduino grade (a couple of months ago, he was new to Arduino).
While creating a home automation project, he was in need of using a unmarried button to do multiple things, and came upward with a very uncomplicated way to brand it happen. Thanks Steve!
Here is the complete sketch, I recommend looking information technology over starting time, and then nosotros will discuss it piece by piece beneath.
/*Using a Single Push, create mutliple options based on how long the push is pressed The circuit: * LED attached from pin xiii to ground through a 220 ohm resistor * LED attached from pivot 12 to footing through a 220 ohm resistor * one side of momentary pushbutton attached to pin 2 * other side of momentary pushbutton attached to Ground * Note 1: on most Arduinos at that place is already an LED on the board attached to pin 13. * Notation 2: In this circuit, when the button is pressed, Ground Voltage is what will be practical. Created DEC 2014 by Scuba Steve Modified JAN 2015 by Michael James Both members of https://www.programmingelectronics.com This lawmaking is in the public domain */ /////////Declare and Initialize Variables//////////////////////////// //Nosotros need to track how long the momentary pushbutton is held in society to execute different commands //This value volition be recorded in seconds float pressLength_milliSeconds = 0; // Ascertain the *minimum* length of fourth dimension, in milli-seconds, that the button must be pressed for a particular choice to occur int optionOne_milliSeconds = 100; int optionTwo_milliSeconds = 2000; //The Pin your button is fastened to int buttonPin = ii; //Pin your LEDs are fastened to int ledPin_Option_1 = thirteen; int ledPin_Option_2 = 12; void setup(){ // Initialize the pushbutton pivot every bit an input pullup // Keep in mind, when pin 2 has footing voltage applied, we know the push button is being pressed pinMode(buttonPin, INPUT_PULLUP); //set the LEDs pins as outputs pinMode(ledPin_Option_1, OUTPUT); pinMode(ledPin_Option_2, OUTPUT); //Start series advice - for debugging purposes but Serial.brainstorm(9600); } // close setup void loop() { //Record *roughly* the tenths of seconds the button in existence held down while (digitalRead(buttonPin) == Low ){ delay(100); //if you want more resolution, lower this number pressLength_milliSeconds = pressLength_milliSeconds + 100; //brandish how long button is has been held Serial.print("ms = "); Serial.println(pressLength_milliSeconds); }//close while //Different if-else conditions are triggered based on the length of the button press //Start with the longest time option start //Pick 2 - Execute the 2nd choice if the button is held for the correct amount of time if (pressLength_milliSeconds >= optionTwo_milliSeconds){ digitalWrite(ledPin_Option_2, HIGH); } //option 1 - Execute the first option if the push is held for the correct amount of fourth dimension else if(pressLength_milliSeconds >= optionOne_milliSeconds){ digitalWrite(ledPin_Option_1, Loftier); }//shut if options //every time through the loop, we need to reset the pressLength_Seconds counter pressLength_milliSeconds = 0; } // shut void loop
Comments:
At the top of the sketch, we find the comments. You should brand it a habit to read the comments in a sketch before jumping into the mechanics of the lawmaking. The comments should lay the groundwork for what is going to happen in the plan and will help you lot translate the intent of the code as you begin to analyze it.
Declare and Initialize Variables:
Later on the comments, we start initializing and declaring variables. Since, we are going to exist tracking time, we need to accept a variable to record the length of time a button is beingness held. We practise that with the pressLength_milliSeconds variable:
//We need to track how long the momentary pushbutton is held in order to execute different commands //This value will be recorded in seconds float pressLength_Seconds = 0;
Now, you might think that the variable name is actually long and abrasive. And I wouldn't especially contend with you – I mean, why would I include milliSeconds in the name of the variable?
The reason I exercise this is because I think including the unit of measurement of measurement in the variable proper noun is helpful when other people are trying to read your code. Writing code that other people can read is not only skilful for other people, merely also future versions of yourself who forget what the heck yous were thinking when you lot wrote the lawmaking! [Cease Rant]
The next matter nosotros demand to set up up are the parameters for when options volition get executed. In this example, I have 2 variables for two options:
// Ascertain the *minimum* length of time, in milli-seconds, that the button must be pressed for a particular option to occur int optionOne_milliSeconds = 100; int optionTwo_milliSeconds = 2000;
Each option is defined by the number of milliseconds that the button must be held for that specific choice to get executed. In order to go my outset option to happen, I accept to concord the button for at least 100 milliseconds which is pretty much a short tap on the button.
If I want the second option to happen, then I have to concord the button for at least 2000 milliseconds aka 2 seconds.
If you wanted more options, you would add together more variables here with their respective agree times.
Our final initializations will be to specify pin numbers for our button and LEDs.
//The Pin your button is fastened to int buttonPin = two; //Pivot your LEDs are fastened to int ledPin_Option_1 = 13; int ledPin_Option_2 = 12;
Setup() the Sketch:
The setup() for this sketch is pretty straight forward (if it'southward not straight frontward to you, make sure to check out our gratuitous 12-part Arduino Grade, after which this setup volition be very familiar to you).
We want to make sure that the pin our push button is continued to is gear up every bit an INPUT_PULLUP:
// Initialize the pushbutton pin as an input pullup // Keep in mind, when pin two has footing voltage practical, nosotros know the button is being pressed pinMode(buttonPin, INPUT_PULLUP);
Nosotros practice this to make sure that the button pin is not floating (if you are wondering what the heck that means, you can read more on that here – but if you simply roll with me until we become through this tutorial, you lot should exist fine ).
Nosotros likewise desire to specify the pins that our LEDs are attached to as OUTPUTs, because we volition be applying voltages to these pins in lodge to illuminate them:
//set the LEDs pins as outputs pinMode(ledPin_Option_1, OUTPUT); pinMode(ledPin_Option_2, OUTPUT);
Finally, information technology never hurts to commencement serial communications for debugging purposes.
//Start serial communication - for debugging purposes but Serial.begin(9600);
With setup() consummate, now we can spring into the main loop of our sketch…
The Principal Loop():
Nosotros know nosotros are going to take to measure the length of time the button is pressed, and and then tape information technology.
To do this, we use a while statement whose condition requires the push button pin to be in a LOW state (recollect, when nosotros push the push, pin 2 will have a ground voltage practical).
//Record *roughly* the tenths of seconds the push button in being held downwards while (digitalRead(buttonPin) == Depression ){
Once the push is pressed and held, the while statement starts executing. The first affair we do in the while statement is to delay 100 milliseconds, and then record that into our time tracking variable:
delay(100); //if you want more resolution, lower this number pressLength_milliSeconds = pressLength_milliSeconds + 100;
Keep in mind the get-go time through the loop, pressLength_milliSeconds will be equal to 0, so we are just adding 100 to the variable.
It tin exist handy to know how long the button has been pressed as you add options. To brand this easy, nosotros want to print the current value of the pressLength_milliSeconds variable to the serial monitor window:
//display how long push button is has been held Series.print("ms = "); Serial.println(pressLength_milliSeconds);
Let'southward ignore the residue of the lawmaking for a 2d, and imagine what happens if we continue holding the button.
The outset time through the while loop, we add 100 milliseconds to the time tracking variable and we impress that value to the serial port. The next fourth dimension through loop, we add another 100 milliseconds to the timer counter variable, and impress this new value to the serial monitor.
As long every bit the button is being held downwardly, and then we go on adding time to the pressLength_milliSeconds variable – this is the crux of the plan.
When we release the push, the while statement stops, considering the condition is no longer met, and nosotros stop adding time to pressLength_milliSeconds.
So allow's pretend nosotros held the button for 3 seconds, and and so let go – what happens?
Well, as we discussed, the while argument ends and the next line of lawmaking we encounter is an if statement.
//Option 2 - Execute the 2nd choice if the button is held for the correct amount of fourth dimension if (pressLength_milliSeconds >= optionTwo_milliSeconds){ digitalWrite(ledPin_Option_2, Loftier); }
The condition of the if statement requires that the time nosotros held the push be longer than or equal to the time we set for option number ii.
If you recall, choice number two was set to occur with at least ii seconds of button press time. Since nosotros held the button for three seconds, this if statement will get executed.
And all we practice is write HIGH voltage to our "option 2" LED, making it illuminate.
What if we had only held the push button for one second – then what would happen?
If this were case, then the offset if argument condition would not have been met, but a subsequent else-if statement merely requires the button agree time be 100 milliseconds or more – so the 2d else-if statement would go executed, which turns on the "option one" LED.
//option 1 - Execute the first pick if the button is held for the correct corporeality of fourth dimension else if(pressLength_milliSeconds >= optionOne_milliSeconds){ digitalWrite(ledPin_Option_1, HIGH); }//close if options
Basically, if we hold the push button a long time, the 2d option gets executed. If we concur the button a brusque time, the outset option gets executed.
If we wanted to add more options, we add the longer agree options at the acme, and the shorter hold options at the lesser.
I wouldn't try to squeeze too many options in a minor span of time or it might bulldoze the end user crazy trying effigy out the timing.
Nor would I try to add more than than iii options for a single button inside a given context, or else you chance making your potential end user desire to beat you upwardly.
To cease up the sketch, nosotros reset our button press timing variable to zero. This ensures that side by side time the button is pressed and held, we volition first from time zero once more.
Try On Your Own Challenge:
- Add another selection, which turns off both LEDs. Try calculation it before the first pick (you lot volition have to adjust the timing) and then later each option.
- How tight can you lot squeeze the selection time together? Experiment and determine what is a good dominion of thumb.
Download:
PDF of this Arduino Tutorial
Source: https://www.programmingelectronics.com/make-one-button-functionality-two-arduino/
0 Response to "Arduino Make a Led Stay Lit Until Pressed Again"
Enviar um comentário