Pages: [1]   Go Down
Author Topic: Debounce in Bulk  (Read 1311 times)
0 Members and 1 Guest are viewing this topic.
Global Moderator
Dallas
Offline Offline
Shannon Member
*****
Karma: 212
Posts: 13083
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset


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

Code:
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;
  }
}
« Last Edit: October 05, 2012, 03:58:31 am by Coding Badly » Logged

Offline Offline
Edison Member
*
Karma: 26
Posts: 1339
You do some programming to solve a problem, and some to solve it in a particular language. (CC2)
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

- pedantic mode on -

Code:
#define NUM_PINS 14

- pedantic mode off -

 smiley-razz

Also:

Code:
digitalRead( 2 )

or

Code:
digitalRead(pinNumber[i])

(but some more SRAM bytes...)

?
Logged

Global Moderator
Dallas
Offline Offline
Shannon Member
*****
Karma: 212
Posts: 13083
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Code:
digitalRead( 2 )

...fixed.

Quote
pedantic...

...as you wish.
« Last Edit: October 05, 2012, 03:59:24 am by Coding Badly » Logged

Offline Offline
Edison Member
*
Karma: 26
Posts: 1339
You do some programming to solve a problem, and some to solve it in a particular language. (CC2)
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

_pedantic mode on myself on_

dont' use #defines, use const ints

_pedantic mode on myself off_

 smiley-roll-sweat
Logged

Pages: [1]   Go Up
Jump to: