Measuring how long a button was pressed

How can I measure the time between when a button was pressed and when it was released? I have all the code working for button pressing etc., but I want a certain action when the button is held for 3 seconds.

Thanks!

When the button goes HIGH/LOW record what millis() is.
When the button goes LOW/HIGH record what millis() is.
Then take the difference between the two recorded values.

Show us what you have.
Attach your code using the </> icon on the left side of the posting menu.
Put your sketch between the code tags [code]Paste your sketch here[/code]

.

So . . . . the button is going to have to be pressed for precisely 3 seconds? Like, 3.000 seconds precise? :slight_smile:

unsigned long buttonPressedAt = 0;
const int BUTTON = 3;
bool buttonReleased = false;
byte buttonPrevState = 0;

void setup() {
 pinMode(BUTTON,INPUT);
}

void loop() {
  int state = digitalRead(BUTTON);
  
  if (state != buttonPrevState) {
    if (state == HIGH) {
      buttonReleased = false;
      buttonPressedAt = millis();
    }
    else {
      buttonReleased = true;
    }
    buttonPrevState=state;
  }

  if (buttonReleased == true) {
    after3Sec();
    buttonReleased=false;
    buttonPressedAt = 0;
  }
}

void after3Sec() {
  long diff = millis()-buttonPressedAt;
  if (diff>3000) {
    //do action for 3 sec button press
  }
}

Not tested, modified the code for your requirement.

Wrote this for another post, check this post cant solve this one out! - #11 by sarouje - Programming Questions - Arduino Forum

INTP:
Like, 3.000 seconds precise? :slight_smile:

correction, 3000 milli sec :slight_smile: