Help with Button Increment Logic please!

Guys, I could use some help with someone could guide me down the correct path.

I am trying to increment or decrement a number when a up/down button is pressed or held. The holding part works beautifully. It will move up by 10 until it gets close to the max which is 200, then increment 1 at a time. the decrement works flawlessly when held too. The problem is when I do a single click it acts strange and jumps up by 21 instead of a single increment.

I am using the clickbutton.h library. Basically long presses are stored as -1 and single clicks as 1. I cannot use if (upButtonClicks == -1 && upButton.depressed == true) because the -1 reverts back to zero after the button updater is called again.

It seems I can get the code to work where it will increment by 10 and stop (wont repeat when held) and single clicks work fine, or the button held works fine and single clicks do not. any guidance is really appreciated.

void wattControl() {
currentMillis2 = millis();
previousMillis2 = 0;

  if (wattLockVar == false) {

    if (upButtonClicks > 0 && watts < maxWatts) {
      watts++;    
    }
    
    if (downButtonClicks > 0 && watts > minWatts) {
      watts--;
    }

    if ((currentMillis2 - previousMillis2) >= 100 && upButton.depressed == true && watts <= (maxWatts - 10) ) {
      watts = watts + 10;
      display.display(); 
      previousMillis2 = currentMillis2;
    }
   if ((currentMillis2 - previousMillis2) >= 100   && upButton.depressed == true && watts > (maxWatts - 10)&& watts < maxWatts ) {
      watts++;
      display.display();
       previousMillis2 = currentMillis2;
    }
    if ((currentMillis2 - previousMillis2) >= 100  && downButton.depressed == true && watts >= (minWatts + 10) ) {
      watts = watts - 10;
       display.display();
     previousMillis2 = currentMillis2;
    }
     if ((currentMillis2 - previousMillis2) >= 100  && downButton.depressed == true && watts < (minWatts + 10)&& watts > minWatts ) {
      watts--;
    display.display();
       previousMillis2 = currentMillis2;
    }
  }
}

Try adding a currentmillis and previousmillis condition to the single click if statements as well. Let the delay be something between 20-50.

You're probably experiencing button bounce, where the button bounces up and down very fast (you can't see this, but the Arduino will easily pick up on it) for a while before settling.

Look up "button debouncing" on how to deal with this.

Hi,

Can you post your complete code please?
How have you go your buttons wired?
Are you using pull-up or pull-down resistors?

Thanks.. Tom.. :slight_smile: