Thursday, October 15, 2015

Arduino multi-click button

Here is some code that I use to detect button multi click and hold for my arduino project. I'm sure I can make this code tighter so it takes less memory. Any suggestions would be appreciated.

The way the code works is that with each call to checkButton( inputPin )

if the number is greater than 0. Then the result is the number of times the button was clicked ( ie. multi-click)

if the number is less than 0. then the result is the number of times the button was clicked before being held.

here is the code. Enjoy.

======================
boolean last_button_state[2] = {LOW,LOW};
boolean cur_button_state[2] = {LOW,LOW};
unsigned long holdEventTS[2] = {0,0};
unsigned short holdDelay[2] = {0,0};
unsigned char clickCount[2] = {0,0};

int checkButton( int button, int index ){

  unsigned long curEventTS = millis();
  int state = 0;
 
  cur_button_state[index] = debounce ( button, last_button_state[index] );

  if ( holdEventTS[index] > 0 ){
    holdDelay[index] = curEventTS - holdEventTS[index];
  }

  if ( cur_button_state[index] == HIGH && last_button_state[index] == LOW ){    
     holdEventTS[index] = curEventTS;      
     clickCount[index] ++;    
  }else if ( cur_button_state[index] == LOW && last_button_state[index] == HIGH && holdEventTS[index] == 0){  
      state = 99;  
  }
 
  last_button_state[index] = cur_button_state[index];

  if ( cur_button_state[index] == LOW && holdDelay[index] > 250 && clickCount[index] > 0){
    state = clickCount[index];
    holdDelay[index] = clickCount[index] = holdEventTS[index] = 0;  
  }else if ( cur_button_state[index] == HIGH && holdDelay[index] > 1000 ){
    state = -1 * clickCount[index];
    holdDelay[index] = clickCount[index] = holdEventTS[index] = 0;  
  }

  return state;

}

boolean debounce ( int button, int curstate ){

  boolean state = digitalRead ( button );
  if ( state != curstate ){
    delay ( 5 );
    state = digitalRead ( button );  
  }

  return state;
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
}
====================