Go Down

Topic: Debouncing (Read 2666 times) previous topic - next topic

joker

Aug 26, 2010, 10:22 am Last Edit: Aug 26, 2010, 12:39 pm by joker Reason: 1
I want to use a debouncer within an ISR, and this is the code I wrote:

Code: [Select]

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?

InvalidApple

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.

:)

Groove

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

joker

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: [Select]
uint8_t startState = ((((PIN(*_encPort) >> _swA) & 0x01) << 2) | (((PIN(*_encPort) >> _swB) & 0x01) << 1) | ((PIN(*_encPort) >> _swPb) & 0x01));

BetterSense

For my code, I just had my interrupt increment an int like so:
Code: [Select]

void ISR(){

dummyvar++
}


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

Code: [Select]
if (dummyvar){
//do stuff
dummyvar=0;
}

deSilva

#5
Aug 27, 2010, 12:12 am Last Edit: Aug 27, 2010, 12:15 am by mpeuser Reason: 1
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: [Select]
// poll button
if (digitalRead(buttonPin) {
 if (openCounts>2) {

    // do things

   }
   openCounts= 0;
} else
 openCounts ++;

retrolefty

#6
Aug 27, 2010, 02:23 am Last Edit: Aug 27, 2010, 02:24 am by retrolefty Reason: 1
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

joker

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.

joker

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.

deSilva

#9
Aug 27, 2010, 10:19 pm Last Edit: Aug 27, 2010, 10:20 pm by mpeuser Reason: 1
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...

InvalidApple

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.

joker

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  :P)
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  :D ): 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) ;)

pluggy

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 ;)  

http://pluggy.is-a-geek.com/index.html

deSilva

#13
Aug 29, 2010, 10:01 pm Last Edit: Aug 29, 2010, 10:01 pm by mpeuser Reason: 1
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.

InvalidApple

#14
Aug 30, 2010, 02:01 am Last Edit: Aug 30, 2010, 02:45 am by InvalidApple Reason: 1
What do you mean by "TTL level"?  Are you trying to return a joke?  Microprocessors are built with CMOS technology.

Go Up