Go Down

Topic: Debounce in Bulk (Read 4030 times)previous topic - next topic

Oct 05, 2012, 10:22 amLast 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;  }}`

marcello.romani

#1
Oct 05, 2012, 10:30 am
- pedantic mode on -

Code: [Select]
`#define NUM_PINS 14`

- pedantic mode off -

Also:

Code: [Select]
`digitalRead( 2 )`

or

Code: [Select]
`digitalRead(pinNumber[i])`

(but some more SRAM bytes...)

?

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

...fixed.

Quote
pedantic...

...as you wish.

marcello.romani

#3
Oct 05, 2012, 11:44 am
_pedantic mode on myself on_

dont' use #defines, use const ints

_pedantic mode on myself off_

Go Up