loading

Using software we can take a single button and have it toggle a light on or off, or complete a more complicated function if we so desire. But what if we have two functions but still only one button? Many of us use a button like this, on smartphones for example, everyday; this is called a short press and a long press (press and hold).

The following guide will take you through all the steps needed to create a simple push button that can control the state of two separate LED's.

Step 1: The Theory

First some theory. Using a button to turn on a light is simple, if the button is reading HIGH (when pressed), then we can turn the LED on by writing the output pin it's attached to HIGH as well. Once the button is reading LOW, we can then set the output pin LOW again to turn off the LED. This is what we call momentary.

For this set-up though, we are looking to toggle the LED on or off. This in it'self is a problem for the simple example above, as the loop function in Arduino repeats hundreds of times per second. Even the quickest press could toggle on and off many many times. This first problem we will overcome using a simple boolean or two, explained on the next few pages.

The second problem is the long press function. How do we trigger this function without triggering the short press function first? The answer is simple. The long press function is triggered whilst the button is being pressed, the short press function is triggered once the button is released. This can again be observed on a smart phone by releasing an object on screen just before the long press function activates.

In the next step we will be creating our hardware set-up, feel free to skip this if you are already at this stage...

Step 2: The Hardware

The hardware is very straight forward, so I won't bore you too much.

First are the two LED's. We wire the anodes of each to pins 12 and 13 on the Arduino, the cathodes then go to ground.

The button is connected to 5V output and pin 3 on the Arduino, then grounded with a 10kOhm resistor.

Step 3: The Software in Detail Part 1

Now to detail each step of the code. If you want to go straight to the full code, you'll find that in the step 5

Let's first look at the variables needed for this set-up, starting with the straight forward pin references.

int LED1 = 12;
int LED2 = 13;
int button = 3;

Next we need a few booleans. These will be used to flip the state of the LEDs on or off

boolean LED1State = false;
boolean LED2State = false;

Another two booleans now. The first will be changed dependant on the state of the button; this will allow the code to detect the first loop after the button has been pressed or released. The second will serve two functions, it will allow the code to stop the long press from activating more than once, and will stop the short press function being activated when we release the button after a long press.

boolean buttonActive = false;
boolean longPressActive = false;

Finally the two last variables. The first variable is used to record the time the button is first pressed. The second variable, is the length of time (in milliseconds) you wish to have the button held down for, to activate the long press function. This can be changed to a figure of your choosing.

long buttonTimer = 0;
long longPressTime = 250;

Now for the set-up, this is again very straight forward, we are simply setting the pin modes.

void setup() {

	pinMode(LED1, OUTPUT);
	pinMode(LED2, OUTPUT);
	pinMode(button, INPUT);

}

Step 4: The Software in Detail Part 2

Now for the loop. I'm going to break this down bit by bit, to explain what's going on. The first thing the program will do is read the state of the button. This will give us the code below and and allow us to create functions for both un-pressed and pressed states, remember that the short press function happens upon button release.

if (digitalRead(button) == HIGH) {

	//Button pressed

} else {

	//Button not pressed

}

In the button pressed section, the first thing we will do is test the buttonActive variable, upon set-up this is false. If this is currently false, this means the program is detecting the button being pressed for the first time. This is because after reading false we immediately set it to true, and only releasing the button can set it back to false. We also record the time the button was first pressed.

if (buttonActive == false) {

	buttonActive = true;
	buttonTimer = millis();

}

The next step within the button pressed section, is to test how long we have held the button for. We do this by testing the current time, subtracting the time first pressed in milliseconds and compare that to the length of time we wish until the long press is activated.

We also check that the longPressActive boolean is false, because once we have activated the long press function we will set this boolean to true to stop repeat activation. Once we have held the button for the desired time, we will flip the state of the LED1State boolean which will in turn flip the pin the LED is attached to HIGH or LOW accordingly.

if ((millis() - buttonTimer > longPressTime) && (longPressActive == false)) {

	longPressActive = true;
	LED1State = !LED1State;
	digitalWrite(LED1, LED1State);

}

Moving on to the button not pressed section of the code. The first thing we will check is if the buttonActive boolean is true. If it is set to true, the code is looping for the first time since the button was released. It will then set the boolean back to false to allow the code above to detect the button being pressed again.

if (buttonActive == true) {

	buttonActive = false;

}

Within the above if statement, as we are detecting the first loop after button release, we are next going to check if long press function was activated, which will give up two possible steps. If long press was activated we will simply set the longPressActive back to false to allow the program to long press once again. If it was not activated, we will flip the state of the second LED like we did with the first.

if (longPressActive == true) {

	longPressActive = false;

} else {

	LED2State = !LED2State;
	digitalWrite(LED2, LED2State);

}

Step 5: The Full Code

Here is the full code ready for upload to your Arduino.

int LED1 = 12;
int LED2 = 13;
int button = 3;

boolean LED1State = false;
boolean LED2State = false;

long buttonTimer = 0;
long longPressTime = 250;

boolean buttonActive = false;
boolean longPressActive = false;

void setup() {

	pinMode(LED1, OUTPUT);
	pinMode(LED2, OUTPUT);
	pinMode(button, INPUT);

}

void loop() {

	if (digitalRead(button) == HIGH) {

		if (buttonActive == false) {

			buttonActive = true;
			buttonTimer = millis();

		}

		if ((millis() - buttonTimer > longPressTime) && (longPressActive == false)) {

			longPressActive = true;
			LED1State = !LED1State;
			digitalWrite(LED1, LED1State);

		}

	} else {

		if (buttonActive == true) {

			if (longPressActive == true) {

				longPressActive = false;

			} else {

				LED2State = !LED2State;
				digitalWrite(LED2, LED2State);

			}

			buttonActive = false;

		}

	}

}

Step 6: Bonus - Two Buttons 6 Functions

What if we have two buttons? Then we have the possibility of 6 functions as follows.

Short Press Button 1
Short Press Button 2
Short Press Button 1 & 2
Long Press Button 1
Long Press Button 2
Long Press Button 1 & 2

The program works in the same way the first code does, with some notable changes.

First there are more LED's, meaning there are more variables, and of course the extra button. But the biggest change comes to the point in which the long press or short press are activated. Once either of these two points are reached, rather than turn an LED on or off, we have three possible actions for each function. Resulting one of six possible LED's turning on or off. To determine which action to take, we check the state of each button and those points, and respond accordingly.

Here is the code

int LED1 = 8;
int LED2 = 9;
int LED3 = 10;
int LED4 = 11;
int LED5 = 12;
int LED6 = 13;

int button1 = 3;
int button2 = 4;

long buttonTimer = 0;
long buttonTime = 250;

boolean buttonActive = false;
boolean longPressActive = false;

boolean button1Active = false;
boolean button2Active = false;

boolean LED1Active = false;
boolean LED2Active = false;
boolean LED3Active = false;
boolean LED4Active = false;
boolean LED5Active = false;
boolean LED6Active = false;

void setup() {

	pinMode(LED1, OUTPUT);
	pinMode(LED2, OUTPUT);
	pinMode(LED3, OUTPUT);
	pinMode(LED4, OUTPUT);
	pinMode(LED5, OUTPUT);
	pinMode(LED6, OUTPUT);
	pinMode(button1, INPUT);
	pinMode(button2, INPUT);

}

void loop() {

	if (digitalRead(button1) == HIGH) {

		if (buttonActive == false) {

			buttonActive = true;
			buttonTimer = millis();

		}

    		button1Active = true;

	}

	if (digitalRead(button2) == HIGH) {

		if (buttonActive == false) {

			buttonActive = true;
			buttonTimer = millis();

		}

		button2Active = true;

	}

	if ((buttonActive == true) && (millis() - buttonTimer > buttonTime) && (longPressActive == false)) {

		longPressActive = true;

		if ((button1Active == true) && (button2Active == true)) {

			LED4Active = !LED4Active;
			digitalWrite(LED4, LED4Active);

		} else if((button1Active == true) && (button2Active == false)) {

			LED5Active = !LED5Active;
			digitalWrite(LED5, LED5Active);

		} else {

			LED6Active = !LED6Active;
			digitalWrite(LED6, LED6Active);

		}
	}

	if ((buttonActive == true) && (digitalRead(button1) == LOW) && (digitalRead(button2) == LOW)) {

		if (longPressActive == true) {

			longPressActive = false;

		} else {

			if ((button1Active == true) && (button2Active == true)) {

				LED1Active = !LED1Active;
				digitalWrite(LED1, LED1Active);

			} else if ((button1Active == true) && (button2Active == false)) {

				LED2Active = !LED2Active;
				digitalWrite(LED2, LED2Active);

			} else {

				LED3Active = !LED3Active;
				digitalWrite(LED3, LED3Active);

			}

		}

		buttonActive = false;
		button1Active = false;
		button2Active = false;

	}

}

From here we could even add a third button for a possible 14 LEDs, or four button for 30 LEDs. Maybe another time though :)

<p>This is good tutorial. I have only one question: what kind of resistor I have to connect with LED? I tried this circle in https://circuits.io but does not work :( I will try live :)</p>
<p>his diagrams are wrong. button(s) is/are always stuck on HIGH with this setup.</p><p>You need to swap the resistor and the 5v wire on the bottom of the button(s)</p>
<p>The resistor you use depends on the voltage drop off, source voltage and led current. For example</p><p>(SourceVoltage-LEDVoltage)/Current = Ohm</p><p>(5V-3.4V)/0.005A = 320 Ohm resistor</p><p>I hope that makes sense</p>
<p>How would dimming be added to this sketch?</p><p>Say i wanted to dim what ever LED was high from a different button?</p>
<p>my class (library) based on others') detects click, double-click, long press &amp; release and very long press. see: <a href="http://pastebin.com/87cCn6h9" rel="nofollow"> http://pastebin.com/87cCn6h9</a></p><p>the same code reproduced below for your convenience:</p><p>// for types of button presses for the Arduino: click, double-click, long press (and release), very long press </p><p>// might work with other controllers. modified from: http://pastebin.com/gQLTrHVF</p><p>/*</p><p> i had to make a few changes (update it?) to make the code work. main changes:</p><p> 1. REMOVED: #include &quot;WProgram.h&quot; (no longer required).</p><p> 2. CHANGED: bpUP TO bp.</p><p> 3. ADDED: event listeners for ALL four types of presses in the sample code.</p><p> 4. CHANGED: time intervals for single, double, long clicks and for long press. these feel more intuitive to me.</p><p> 5. CHANGED: event OnLongPress is raised ONLY after the button is released. this, again, feels more intuitive. code is tested and at http://pastebin.com/87cCn6h9</p><p>*/</p><p>//</p><p>// jb_exe</p><p>// Class from the code of JEFF'S ARDUINO BLOG</p><p>// http://jmsarduino.blogspot.com/2009/10/4-way-button-click-double-click-hold.html</p><p>// </p><p>// the modified version at http://pastebin.com/gQLTrHVF</p><p>// further modified by mahesh [at] tinymogul.com</p><p>// How to use me :</p><p>// &quot;FWB_Project.pde&quot;</p><p>// #include &quot;FWB.h&quot;</p><p>// #define BP 0 //the pin where your button is connected</p><p>//</p><p>// FWB bp;</p><p>//</p><p>// void OnClick(int pin) {</p><p>// //Your code here</p><p>// }</p><p>//</p><p>// void OnDblClick(int pin) {</p><p>// //Your code here</p><p>// }</p><p>//</p><p>// void OnLongPress(int pin) {</p><p>// //Your code here</p><p>// }</p><p>//</p><p>// void OnVLongPress(int pin) {</p><p>// //Your code here</p><p>// }</p><p>//</p><p>// void setup()</p><p>// {</p><p>// // errors in code fixed here. empty event handlers added.</p><p>// bp.Configure(BP);</p><p>// bp.OnClick = OnClick;</p><p>// bp.OnDblClick = OnDblClick;</p><p>// bp.OnLongPress = OnLongPress;</p><p>// bp.OnVLongPress = OnVLongPress;</p><p>// }</p><p>//</p><p>// void loop()</p><p>// {</p><p>// // Test button state</p><p>// bp.CheckBP();</p><p>// }</p><p>#define PULL_UP 1</p><p>#define PULL_DOWN 0</p><p>class FWB</p><p>{</p><p>private:</p><p> int _pin;</p><p> boolean _pullMode;</p><p> // Properties //</p><p> ////////////////</p><p> // Debounce period to prevent flickering when pressing or releasing the button (in ms)</p><p> int Debounce;</p><p> // Max period between clicks for a double click event (in ms)</p><p> int DblClickDelay;</p><p> // Hold period for a long press event (in ms)</p><p> int LongPressDelay;</p><p> // Hold period for a very long press event (in ms)</p><p> int VLongPressDelay;</p><p> // Variables //</p><p> ///////////////</p><p> // Value read from button</p><p> boolean _state;</p><p> // Last value of button state</p><p> boolean _lastState;</p><p> // whether we're waiting for a double click (down)</p><p> boolean _dblClickWaiting;</p><p> // whether to register a double click on next release, or whether to wait and click</p><p> boolean _dblClickOnNextUp;</p><p> // whether it's OK to do a single click</p><p> boolean _singleClickOK;</p><p> // time the button was pressed down</p><p> long _downTime;</p><p> // time the button was released</p><p> long _upTime;</p><p> // whether to ignore the button release because the click+hold was triggered</p><p> boolean _ignoreUP;</p><p> // when held, whether to wait for the up event</p><p> boolean _waitForUP;</p><p> // whether or not the hold event happened already</p><p> boolean _longPressHappened;</p><p> // whether or not the long hold event happened already</p><p> boolean _vLongPressHappened;</p><p> public:</p><p> void (*OnClick)(int pin);</p><p> void (*OnDblClick)(int pin);</p><p> void (*OnLongPress)(int pin);</p><p> void (*OnVLongPress)(int pin);</p><p> FWB()</p><p> {</p><p> // Initialization of properties</p><p> Debounce = 20;</p><p> DblClickDelay = 250;</p><p> LongPressDelay = 750;</p><p> // LongPressDelay = 1000; </p><p> VLongPressDelay = 3500;</p><p> // VLongPressDelay = 3000;</p><p> // Initialization of variables</p><p> _state = true;</p><p> _lastState = true;</p><p> _dblClickWaiting = false;</p><p> _dblClickOnNextUp = false;</p><p> _singleClickOK = false; //Default = true</p><p> _downTime = -1;</p><p> _upTime = -1;</p><p> _ignoreUP = false;</p><p> _waitForUP = false;</p><p> _longPressHappened = false;</p><p> _vLongPressHappened = false;</p><p> }</p><p> void Configure(int pin, int pullMode = PULL_DOWN)</p><p> {</p><p> _pin = pin;</p><p> _pullMode = pullMode;</p><p> pinMode(_pin, INPUT);</p><p> }</p><p> void CheckBP(void)</p><p> {</p><p> int resultEvent = 0;</p><p> long millisRes = millis();</p><p> _state = digitalRead(_pin) == HIGH;</p><p> // Button pressed down</p><p> if (_state != _pullMode &amp;&amp; _lastState == _pullMode &amp;&amp; (millisRes - _upTime) &gt; Debounce)</p><p> {</p><p> //Serial.println(&quot;button down&quot;);</p><p> _downTime = millisRes;</p><p> _ignoreUP = false;</p><p> _waitForUP = false;</p><p> _singleClickOK = true;</p><p> _longPressHappened = false;</p><p> _vLongPressHappened = false;</p><p> if ((millisRes - _upTime) &lt; DblClickDelay &amp;&amp; _dblClickOnNextUp == false &amp;&amp; _dblClickWaiting == true)</p><p> _dblClickOnNextUp = true;</p><p> else</p><p> _dblClickOnNextUp = false;</p><p> _dblClickWaiting = false;</p><p> }</p><p> // Button released</p><p> else if (_state == _pullMode &amp;&amp; _lastState != _pullMode &amp;&amp; (millisRes - _downTime) &gt; Debounce)</p><p> {</p><p> //Serial.println(&quot;button up&quot;);</p><p> if (_ignoreUP == false) //Replace &quot;(!_ignoreUP)&quot; by &quot;(not _ignoreUP)&quot;</p><p> {</p><p> _upTime = millisRes;</p><p> if (_dblClickOnNextUp == false) _dblClickWaiting = true;</p><p> else</p><p> {</p><p> resultEvent = 2;</p><p> _dblClickOnNextUp = false;</p><p> _dblClickWaiting = false;</p><p> _singleClickOK = false;</p><p> }</p><p> }</p><p> }</p><p> // Test for normal click event: DblClickDelay expired</p><p> if (_state == _pullMode &amp;&amp; (millisRes - _upTime) &gt;= DblClickDelay &amp;&amp; _dblClickWaiting == true &amp;&amp; _dblClickOnNextUp == false &amp;&amp; _singleClickOK == true &amp;&amp; resultEvent != 2)</p><p> {</p><p> resultEvent = 1;</p><p> _dblClickWaiting = false;</p><p> }</p><p> // added code: raise OnLongPress event when only when the button is released</p><p> if (_state == _pullMode &amp;&amp; _longPressHappened &amp;&amp; !_vLongPressHappened) {</p><p> resultEvent = 3;</p><p> _longPressHappened = false;</p><p> }</p><p> // Test for hold</p><p> if (_state != _pullMode &amp;&amp; (millisRes - _downTime) &gt;= LongPressDelay)</p><p> {</p><p> // Trigger &quot;normal&quot; hold</p><p> if (_longPressHappened == false)</p><p> {</p><p> // resultEvent = 3;</p><p> _waitForUP = true;</p><p> _ignoreUP = true;</p><p> _dblClickOnNextUp = false;</p><p> _dblClickWaiting = false;</p><p> //_downTime = millis();</p><p> _longPressHappened = true;</p><p> }</p><p> // Trigger &quot;long&quot; hold</p><p> if ((millisRes - _downTime) &gt;= VLongPressDelay)</p><p> {</p><p> if (_vLongPressHappened == false)</p><p> {</p><p> resultEvent = 4;</p><p> _vLongPressHappened = true;</p><p> //_longPressHappened = false;</p><p> }</p><p> }</p><p> }</p><p> _lastState = _state;</p><p> //if (resultEvent!=0)</p><p> // Serial.println((String)&quot;resultEvent: &quot; + (String) resultEvent);</p><p> if (resultEvent == 1 &amp;&amp; OnClick) OnClick(_pin);</p><p> if (resultEvent == 2 &amp;&amp; OnDblClick) OnDblClick(_pin);</p><p> if (resultEvent == 3 &amp;&amp; OnLongPress) OnLongPress(_pin);</p><p> if (resultEvent == 4 &amp;&amp; OnVLongPress) OnVLongPress(_pin);</p><p> // if (resultEvent != 0)</p><p> // Usb.println(resultEvent);</p><p> }</p><p>};</p>
<p>THANKYOU!</p>
<p>You're welcome. I presume you were able to use this for a project</p>
<p>Hi, here is the application. one button at front and one at back uses this long / short press concept.</p><p>https://www.instructables.com/id/Sparrow-My-Assistant/</p>
<p>Yes. i was able to grasp half of concept. but was in hurry, saved to understand it properly. :)</p>
<p>modified it and used it for nested menu</p>
Great, thanks, i will give a try over the weekend.
This is very cool! Thanks for the ible
Glad you like it.

About This Instructable

31,767views

61favorites

License:

More by xn1ch1:Using Microsoft Visual Basic to Upload Files to an FTP Server Arduino - Dual Function Button - Long Press/Short Press (Without Delay) + Bonus 
Add instructable to: