tags:

views:

329

answers:

3

I'm trying to figure out some things with some firmware that was written for us. I'm not all that familiar with C and I think there's some shorthand going on here that I'm just not getting. I don't understand how the code relates to the comments, particularly how you get 70ms from any of that. Can you help translate into English?

// so the button has to be held for 70 ms to be considered being pressed
// and then has to be released for 70ms to be considered un-pressed
State=(State<<1) | !input(USER_BUTTON) | 0xe000;
if(State==0xe000)
{
 Debounced_Button_Pressed =  TRUE;
 time_button_held++;
}
else if (State==0xffff)
{
 Debounced_Button_Pressed =  FALSE;
}

This is within a timer interrupt function and apparently fires every 4.4ms

Thanks.

+2  A: 

Think of the varialbe "State" as 16 bits. The << operator shifts it left by one each time, and the | operator is used to set the least significant bit whenever input(USER_BUTTON) is false (! is the not operator). The checks then just check if the last 13 cases of input were all true or all false.

Matthias Wandel
+13  A: 

Let's take this one step at a time...

State=(State<<1) | !input(USER_BUTTON) | 0xe000;

What this does is:

  • Shift state one to the left (throw out the top bit, move everything over, set the low bit to 0)
  • Set the low bit if the input is 0 (off)
  • Force the top 3 bits on.

So, there are 13 bits here that are not forced on, and they form a sort of history of the last 13 samples of the USER_BUTTON input.

The if statement then just checks whether all 13 of those bits are off (giving 0xe000) or on (giving 0xffff). If off, the button's been pressed for 13 samples; if on, it's been un-pressed for 13 samples.

This then gives a debounce time of 4.4ms * 13 = 57.2ms - a bit off from the comment, or the timer interval's closer to 5.385ms.

bdonlan
Thank you! This is most helpful in figuring it out. Any chance you can take me through a few iterations asssuming State starts at zero and input(USER_BUTTON) is false (for example) doesn't it just get infinitely larger? | means a bitwise OR, right? So when I get out my handy windows programming calculator the results for the first 3 are:E0011E0033E007and we can already see there's no hope of it being 0xffff or 0xe000 ever again. What simple obvious thing am I missing?
Steven
State is likely an unsigned short, meaning it's truncated at 16 bits (4 hex digits) each time.
bdonlan
+2  A: 

He's debouncing a switch by shifting samples of the switch's state into an integer every 4.4ms. He can then tell a valid press from noise by seeing if the contents of that integer match a certain hex value. It looks like he can also tell if it has been released according to his definition by comparing it to a different value.

Stephen Friederichs