Go Down

Topic: Debounce in Bulk (Read 1 time) previous topic - next topic

Coding Badly

Oct 05, 2012, 10:22 am Last Edit: Oct 05, 2012, 10:58 am by Coding Badly Reason: 1

Debouncing 14 digital pins using only 30 bytes of SRAM...

Code: [Select]
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;
 }
}

tuxduino

- pedantic mode on -

Code: [Select]

#define NUM_PINS 14


- pedantic mode off -

:P

Also:

Code: [Select]

digitalRead( 2 )


or

Code: [Select]

digitalRead(pinNumber[i])


(but some more SRAM bytes...)

?

Coding Badly

#2
Oct 05, 2012, 10:54 am Last Edit: Oct 05, 2012, 10:59 am by Coding Badly Reason: 1
Code: [Select]
digitalRead( 2 )

...fixed.

Quote
pedantic...


...as you wish.

tuxduino

_pedantic mode on myself on_

dont' use #defines, use const ints

_pedantic mode on myself off_

:smiley-roll-sweat:

Go Up