Pages: [1] 2   Go Down
Author Topic: Debouncing  (Read 2346 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 1
Posts: 41
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I want to use a debouncer within an ISR, and this is the code I wrote:

Code:

ISR(PCINT0_vect) {
// Interrupt service request for external interrupt
// Interpret switches position
      static uint8_t prevState = 0x03;
      // Get current state
      uint8_t startState = ((((PINC >> _swA) & 0x01) << 2) | (((PINC >> _swB) & 0x01) << 1) | ((PINC >> _swPb) & 0x01));
      // Simple debouncing. 1 nop = 62.5 ns, 1600 nops approx 100 us
      for (int i=0; i < 1600; i++)
            asm volatile ("NOP");
      // Get current state
      uint8_t stopState = ((((PINC >> _swA) & 0x01) << 2) | (((PINC >> _swB) & 0x01) << 1) | ((PINC >> _swPb) & 0x01));
      // Check if the previous state was stable and different from the previous one
      if ((startState == stopState) && (stopState != prevState)) {
            _buttonDown = (~startState & 0x01); // Update button state
            if ((startState >> 1) == 0x03) { // If in idle state
              // Decode steps pattern
                  if (patternBuffer == patternCW)
                        _counts++;             
              if (patternBuffer == patternCCW)
                        _counts--;             
                  patternBuffer = 0x00; // reset buffer
            }
            else {
                  // Append state to the buffer
                  patternBuffer <<= 2;
                  patternBuffer |= (startState >> 1) ;
            }
            prevState = stopState; // Record state for next change
      }
}

It sounds like there are much better solutions. Does one of you has contructive comments and suggestions?
« Last Edit: August 26, 2010, 05:39:44 am by joker » Logged

Melbourne, Australia
Offline Offline
Full Member
***
Karma: 0
Posts: 219
Have you tried turning it off and on again?
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hey there,

You need to see if you can shorten that interrupt routine- they need to be as short as possible, because other interrupts may be waiting, or even missed- you should just get the data you need and let your main code deal with any data manipulation.  

When you read a port "PORTC", you should instead read "PINC" (see section 13.2.4 of the datasheet)

I think that all the states should be volitile global variables, so that the main code can take some functionality from that interrupt routine.

smiley
Logged

UK
Offline Offline
Faraday Member
**
Karma: 17
Posts: 2884
Gorm deficient
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

There's a very long loop in that routine - I'd really recommend getting rid of it.
Logged

Per Arduino ad Astra

0
Offline Offline
Newbie
*
Karma: 1
Posts: 41
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Oooops about
"When you read a port "PORTC", you should instead read "PINC" (see section 13.2.4 of the datasheet)"

Your are 100% right, I simplified my code for the post, please read PINC instead. In my application PORTs are passed as arguments and the pin reading is slightly less self explicit.

Code:
uint8_t startState = ((((PIN(*_encPort) >> _swA) & 0x01) << 2) | (((PIN(*_encPort) >> _swB) & 0x01) << 1) | ((PIN(*_encPort) >> _swPb) & 0x01));
Logged

Dallas
Offline Offline
Sr. Member
****
Karma: 3
Posts: 337
nephew as a kittens
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

For my code, I just had my interrupt increment an int like so:
Code:
void ISR(){

dummyvar++
}

and then in my code, to check if a button was pressed I just do

Code:
if (dummyvar){
//do stuff
dummyvar=0;
}
Logged

0
Offline Offline
Edison Member
*
Karma: 0
Posts: 1103
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Sorry if I sound unconstructive from time to time - this is due to some needed comic relief :-)

What is bouncing? When a switch is closed, it will shortly reopen after that due to mechanical elasticity, this is the same as if you let go a ball to the floor which will bounce many times until it rests. The length of this bouncing phase differs greatly between switches, not only between brands but also between specimen, and also depends on age  and wear.
A "last bounce" can even happen 100ms after the switch is pressed.

Note that there can be no bouncing when a switch is re-opend, but there  is a similar though much shorter electrical effect.

It is considered good practice in software debouncing not to wait until the bouncing is over, but to immediately act at the first edge because you know that the key has been pressed!

Now after some internal activities are over you are wait.ing again that the key has been pressed. You can be in of three situations:
- The key is still bouncing
- The key is still pressed
- The key is already open

How to handle this depends on whether you look at a rising edge - often leading to an interrupt - or if you are polling looking at the level.

The solution of BetterSense is excellent, if the time of "do stuff" is long enough to have left the bouncing phase.

Generally there will be no advantage whith interupts. At the place where you check the dummyVar-flag you can as well read digitalInput(). (Except the key press is very short and you are in danger to miss it!)

The tricky thing comes when the processing of the keypress event is over. Now you have to look for an open key phase, long enough so it cannot be confused with a bounce spike (those spikes are very short btw and in fact difficult to probe without edge sensitive hardware...)

In cases when you can poll regularly, you can use a state variable openCounts to know that a resonably open time has passed

The Code for this might go (sorry no check, just typed in)
Code:
// poll button
if (digitalRead(buttonPin) {
  if (openCounts>2) {

     // do things

    }
    openCounts= 0;
} else
  openCounts ++;
« Last Edit: August 26, 2010, 05:15:32 pm by mpeuser » Logged

Left Coast, CA (USA)
Offline Offline
Brattain Member
*****
Karma: 361
Posts: 17292
Measurement changes behavior
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Well debouncing a switch contact efficently inside a ISR is kind of tricky, as there could still be a lot of useless interrupts being generated from the switch bounces. If it could be debounced with a external filter components it might make for a simpler more reliable system, just saying....

Lefty
« Last Edit: August 26, 2010, 07:24:03 pm by retrolefty » Logged

0
Offline Offline
Newbie
*
Karma: 1
Posts: 41
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Thanks all for these very helpfull answers.
What I learned from them is that my first intuition which consisted in staying away from interrupts for debouncing was funded.

Just for your records, ALPS data sheets for rotary encoders series EC12 says <= 3 ms. But yes, some switches may bounnnnnnnnnnnnnnnnnnce for a longer time.
Logged

0
Offline Offline
Newbie
*
Karma: 1
Posts: 41
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

After multiples tests, I can say that the push button switch is much more prone to bounces than the A & B contacts from the encoder.
Logged

0
Offline Offline
Edison Member
*
Karma: 0
Posts: 1103
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

This is black art... High quality buttoms http://www.ck-components.com/13328/digitast_9mar10.pdf/differ, in that their bounce time is specified, most likely accomplished by selection....

In mechanical rotary switches the contacts slip in a lateral movement which most likely reduces bouncing conciderably, as many points of contact exist...
« Last Edit: August 27, 2010, 03:20:51 pm by mpeuser » Logged

Melbourne, Australia
Offline Offline
Full Member
***
Karma: 0
Posts: 219
Have you tried turning it off and on again?
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
It is considered good practice in software debouncing not to wait until the bouncing is over, but to immediately act at the first edge because you know that the key has been pressed!

It is considered good practice in electronics to make sure that the circuit is not experiencing Impulse noise and giving a false reading.  You don't know that the first edge is due to the button being pushed: Instead, you should recheck a short time later to see if the input is still high.
Logged

0
Offline Offline
Newbie
*
Karma: 1
Posts: 41
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Generally speaking, debouncing applies to many places, other than switches.
At this stage I may explain (taking the risk to bring some confusion) that my personnal approach to Arduino is to try to challenge it using the minimal number of external components. In the case of the rotary encoder, I did not even use the recommanded filter (RC, 10 k + 10 nF wired to ground)! So that I tried to apply a software only solution to the bouncing problem. And it works fine. I would not obviously recommend that for military/medical devices  smiley-razz)
Back to bouncing in general, I remember very well a very nicely written paper in Measure (the internal newspaper at HP) dealing with pulse recognition from magnetic heads in 10 Mb disk drives (which were as big as washing machines  smiley-grin ): this was the starting point of my interest to signal recognition. Since then I paid strong interest to that, applied to other purposes (I am actually lecturing this science from times to times at university). But the techniques in use for such debouncing techniques require a lot of real time analysis and  high tech ressources. Thus my choice for having a little fun with a minimalist approach (Way back to Occam razor) smiley-wink
Logged

Lancashire, UK
Offline Offline
Edison Member
*
Karma: 9
Posts: 1991
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

I struggled with bounce on a reed switch using interrupts in one of my projects and trying to handle it in software.  I gave up and implemented a hardware solution, works perfectly now smiley-wink  

Logged


0
Offline Offline
Edison Member
*
Karma: 0
Posts: 1103
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
It is considered good practice in electronics to make sure that the circuit is not experiencing Impulse noise and giving a false reading.  You don't know that the first edge is due to the button being pushed: Instead, you should recheck a short time later to see if the input is still high.
You said that just to be funny, right?
If you expect noise or spikes of TTL level in your line, we are no longer talking about "de-bouncing", but about "de-glitching" or how you want to name it. There are of course techniques to address both at the same time.
« Last Edit: August 29, 2010, 03:01:59 pm by mpeuser » Logged

Melbourne, Australia
Offline Offline
Full Member
***
Karma: 0
Posts: 219
Have you tried turning it off and on again?
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

What do you mean by "TTL level"?  Are you trying to return a joke?  Microprocessors are built with CMOS technology.
« Last Edit: August 29, 2010, 07:45:22 pm by InvalidApple » Logged

Pages: [1] 2   Go Up
Jump to: