How can I get the duration of how long a button is unpressed? And when the duration excceds 30 seconds I have to perform an event in arduino. Any help would be appreciated
Asked
Active
Viewed 48 times
-1
-
You don't know how to detect the button release or how to calculate the duration? – hcheung Oct 15 '22 at 11:41
-
All timing questions have something similar to `millis() - starttime` in their core. In your case, you probably update `starttime` whenever the button is pressed. – datafiddler Oct 19 '22 at 08:54
1 Answers
0
I would use a code like this who save the last press time and wait until the 30th milliseconds to execute the code. Let me know if it is working, since I haven't tested it.
#define BUTTON_PIN 4
unsigned long startTime;
unsigned long lastPress;
void setup()
{
Serial.begin(9600);
pinMode(BUTTON_PIN, INPUT_PULLUP);
}
void loop()
{
byte buttonState = digitalRead(BUTTON_PIN);
if (buttonState == HIGH) // save the last time button was pressed in milliseconds
{
lastPress = millis();
}
if ((millis() - lastPress) > 30000)
{
// execute any code you want after 30 seconds
// reset the counter
startTime = 0;
}
}