Debounce in Bulk

Debouncing 14 digital pins using only 30 bytes of SRAM…

static const int NUM_PINS = 14;

uint16_t PreviousMillis;

typedef struct
{
  uint8_t stage;
  uint8_t previous;
}
debounce_t;

debounce_t debounce[NUM_PINS];


void setup( void )
{
  for ( uint8_t i=0; i < NUM_PINS; ++i )
  {
    pinMode( i, INPUT_PULLUP );
    debounce[i].stage = 0xFF;
    debounce[i].previous = 0xFF;
  }
}

void loop( void )
{
  uint16_t ThisMillis;
  
  ThisMillis = millis();
  
  if ( ThisMillis - PreviousMillis >= 3 )
  {
    for ( uint8_t i=0; i < NUM_PINS; ++i )
    {
      debounce[i].stage = (debounce[i].stage << 1) | digitalRead( i );
      
      if ( (debounce[i].stage != debounce[i].previous)
          && ((debounce[i].stage == 0x00) || (debounce[i].stage = 0xFF)) )
      {
        // 8 bits * 3 milliseconds per bit = 24 milliseconds at the same state

        // debounce[i].stage is the state of the pushbutton
  
        debounce[i].previous = debounce[i].stage;
      }
    }

    PreviousMillis = ThisMillis;
  }
}
  • pedantic mode on -
#define NUM_PINS 14
  • pedantic mode off -

:P

Also:

digitalRead( 2 )

or

digitalRead(pinNumber[i])

(but some more SRAM bytes...)

?

digitalRead( 2 )

...fixed.

pedantic...

...as you wish.

pedantic mode on myself on

dont' use #defines, use const ints

pedantic mode on myself off

:cold_sweat: