Just want to start things off by saying thanks to this community for sharing knowledge on working with the Arduino. I've learned quite a lot from looking thru topics and examples ever since I obtained an Arduino unit about a year ago.
Anyhow, I'm currently stuck on a problem with a project I'm working on and it deals with a button that's active low (when ON, it's connected to ground). What I'm trying to achieve is this:
-
When the button is released, I want to know how long it's idling for and if it's been idle for more than 2 seconds, I want to set a flag indicating this condition is met (true).
-
When the button is released and the idle time is less than 2 seconds or when the button is pressed, the flag will remain false.
I'm not sure what I'm doing wrong in the code, but it doesn't seem like it's executing the "updateState" call function. Can someone please help? It's much appreciated!
const int buttonPin = 5; //Active low input
int buttonState = 1; // current state of the button
int lastButtonState = 1; // previous state of the button
int startPressed = 0; // the moment the button was pressed
int idleTime = 0; // how long the button was idle
boolean buttonflag = false;
boolean buttontrans = false;
unsigned long beginTimer = 0;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50;
void setup() {
pinMode(buttonPin, INPUT_PULLUP); // initialize the button pin as a input
beginTimer = millis();
Serial.begin(9600); // initialize serial communication
}
void loop() {
buttonState = digitalRead(buttonPin); // read the button input
if ((millis() - lastDebounceTime) > debounceDelay) {
if (buttonState == HIGH && lastButtonState == LOW && buttontrans == false) { // button state changed
buttontrans = true;
updateState();
}
lastDebounceTime = millis();
lastButtonState = buttonState;
}
}
void updateState() {
if (buttontrans == true && buttonState == HIGH) {
startPressed = millis();
idleTime = startPressed - beginTimer;
if (idleTime > 2000 && buttonflag == false) {
buttonflag = true;
Serial.println("Button was pressed for more than 2 seconds");
Serial.println("Buttonflag = ");
Serial.println(buttonflag);
}
}
else {
if (digitalRead(buttonPin) == LOW) {
buttonflag = false;
Serial.println("Button was not pressed for more than 2 seconds");
Serial.println("Buttonflag = ");
Serial.println(buttonflag);
}
}
}