Hi guys,
I'm working on a project that will use one button to enter and exit a menu using a long button hold but also activate certain things with a short press.
My problem is that when i release the button when entering the menu mode, it also gives a short press, meaning what ever the first function in the menu is, is activated immediately.
When exiting the menu mode everything works fine. I can see what is happening too. The conditions for a short press in menumode are met upon releasing the button. I just can't figure out how to stop it from doing it.
I've tried everything i can think of!
Here is a shortened version of the code that is easier to see what is happening.
#define buttonPin 15 // analog input pin to use as a digital input
#define debounce 20 // ms debounce period to prevent flickering when pressing or releasing the button
#define holdTime 1000 // ms hold period: how long to wait for press+hold event
// Button variables
int buttonVal = 0; // value read from button
int buttonLast = 0; // buffered value of the button's previous state
long btnDnTime; // time the button was pressed down
long btnUpTime; // time the button was released
boolean ignoreUp = false; // whether to ignore the button release because the click+hold was triggered
boolean menuMode = false; // whether menu mode has been activated or not
//=================================================
void setup()
{
// Set button input pin
pinMode(buttonPin, INPUT);
digitalWrite(buttonPin, HIGH );
Serial.begin(9600);
}
//=================================================
void loop()
{
// Read the state of the button
buttonVal = digitalRead(buttonPin);
delay(10);
// Test for button pressed and store the down time
if (buttonVal == LOW && buttonLast == HIGH && (millis() - btnUpTime) > debounce)
{
btnDnTime = millis();
}
// Test for button release and store the up time
if (buttonVal == HIGH && buttonLast == LOW && (millis() - btnDnTime) > debounce)
{
if (ignoreUp == false && menuMode == false) {
Serial.println("Button 1");
}
else ignoreUp = false;
btnUpTime = millis();
}
// Test for button held down for longer than the hold time
if (buttonVal == LOW && menuMode == false && (millis() - btnDnTime) > long(holdTime))
{
Serial.println("Menu Mode");
ignoreUp = true;
btnDnTime = millis();
menuMode = true;
}
if (buttonVal == HIGH && buttonLast == LOW && (millis() - btnDnTime) > debounce)
{
if (ignoreUp == false && menuMode == true){
Serial.println("Button 2");
}
else ignoreUp = false;
btnUpTime = millis();
}
if (buttonVal == LOW && menuMode == true && (millis() - btnDnTime) > long(holdTime))
{
Serial.println("Normal Mode");
ignoreUp = true;
btnDnTime = millis();
menuMode = false;
}
buttonLast = buttonVal;
}
I forget where i found this code so can't give credit to whomever wrote it, but other than this one wee issue, it does exactly what i want!
Thanks