Hi. How can I set one action when I press a button and another when I press two times the same button without doing the first one action? My actual code is something like this:
estadoBotonselect = digitalRead(boton_select); //estadoBotonselect is 0 in this time
if (estadoBotonselect != estadoanteriorselect){//estadoBotonselect change
if(estadoBotonselect == LOW){//estadoBoton pushed
d++;//increment one push
if (i==2||i==3){//other part of the program
lcd.setCursor(13,0);//...
lcd.print("OK");//....
delay(1000);//....LCD print "OK" one second
lcd.setCursor(13,0);//...
lcd.print(" ");//...
}
if(d==2){//...boton second push
lcd.clear();//...
d=0;//go 0 push and go to a part of the program
menu();//...
}
}
estadoanteriorselect = estadoBotonselect;//botton go normally}
It is going to be a long answer and has no already-made code so here it goes:
You need to be able to define and detect "buttons clicked" and "buttons double clicked" as status of your button. So maybe define a few time constants such as time between button down and button up as t_press. If user spends longer time than this t_press with button down, you consider it as buttons hold status. Then define a t_dc as time between two sequential buttons released events. If the user spends shorter time than t_dc, do double click. I personally think that doing one action with click and another with hold is easier to program, just in case you can't have a second button.
First, you have to decide what is a reasonable amount of time to wait after the first press for the second press. Once you do that, you can utilize millis() to keep track of the last time you detected a press:
static int numPresses = 0;
if (switch is pressed)
{
numPresses++;
lastSwitchPressed = millis(); // set the time that we last detected a switch press to now
}
You can then perform an action based on the number of presses and the time since the last press:
if (numPresses == 2)
{
// perform action for double click
numPresses = 0;
}
// only 1 press has occurred and we have waited long enough for the second press to come
else if (numPresses == 1 && millis() - lastSwitchPressed > someInterval)
{
// perform action for single click
numPresses = 0;
}
Keep in mind that these two block of code need to run independently of each other, and as often as possible.