Push Button Twice Help

Hi, I am struggling trying to figure out how to code something I otherwise thought would have been quite simple. I have a button connected to Pin 2 of the Arduino

I am trying to program it so that the button is pressed twice within 500 milliseconds an LED will light for one second and then the code will reset back to how it was before the button was pressed.

However, I cannot figure out how to do this. It doesn't appear to be as simple as modifying the code from pushing the button to make the led light while it is pressed.

Does anyone have any ideas of how I can do this?

Thanks :slight_smile:

  1. Keep a counter of how many times the button has been pressed
  2. Record a time using the millis() function of when the button was last pressed
  3. Compare this value against the current time to see if it is a second press or not

When you detect the button state going from "not pressed" to "pressed"...

IF the current_time - last_pressed_time < 50
ignore then button press (see debounce)

ELSE IF the current_time - last_pressed_time < 500
increment button_counter
record the last_pressed_time

ELSE
set the button_counter = 1
record the last_pressed_time

In loop...
IF the current_time - last_pressed_time >= 500 && button_counter > 0
handle the number of button presses indicated by button_counter
set button_counter = 0

Take a look at the StateChangeDetection example in the IDE

your requirements were a bit challenging. need to track time of button press, button cnts and then time LED is turned on

consider

// turn LED on for 1 second if button pressed twice w/in 500 msec

#define ON  LOW
#define OFF HIGH

byte butPin = A1;
byte ledPin = 10;

byte butLst;
byte but;

int  butCnt = 0;

unsigned long msec;
unsigned long butMsec;
unsigned long ledMsec;


// -----------------------------------------------------------------------------
void loop (void)
{
    msec = millis ();
    but  = digitalRead (butPin);

    if (butLst != but)  {
        butLst = but;

        if (LOW == but) {   // button pressed
            butCnt++;

            if (msec - butMsec < 500 && 2 <= butCnt)  {
                ledMsec = msec;
                digitalWrite (ledPin, ON);
            }

            butMsec = msec;
            if (1 < butCnt)
                butCnt  = 0;
        }

        delay (10);         // debounce
    }

    if (ledMsec && msec - butMsec > 1000)
        digitalWrite (ledPin, OFF);
        
}

// -----------------------------------------------------------------------------
void setup (void)
{
    digitalWrite (ledPin, OFF);
    pinMode      (ledPin, OUTPUT);

    pinMode      (butPin, INPUT_PULLUP);
    butLst      = digitalRead (butPin);
}

Thanks everyone for the help! I have managed to get it working, I appreciate it :slight_smile: