Jump to content
Sign in to follow this  
mityeltu

Switch Debouce Code Design

Recommended Posts

I am in the middle of implementing a circuit that uses multiple switched inputs. What I need/want to know is if there is a better way to debounce and verify switch position. The following is a skeleton of what I am doing with each switch input:

 

if porta0 is high then

wait 50mS

if porta0 is still high

do a bunch of stuff

end if

end if

 

The point of the nested if's is to make sure that the first input was a 'real' input and not just abarrent noise or something. Is there a better way to check for the validity of a switch input or button press?

 

Thanks for the help.

Edited by mityeltu

Share this post


Link to post
Share on other sites

I use this routine , returns 2 for a long press 1 for a normal press else 0

 

 

char chksw(void) // button pressed

 

{

 

static byte was_pressed=0;

 

static int count=0;

 

char event=0;

 

byte now_pressed=porta0;

 

if ((now_pressed) && (was_pressed) )

 

{

 

if (count >3000)

 

event=2;

 

else

 

if (count >300) event=1 ;

 

}

 

else

 

event=0;

 

if (now_pressed)

 

{

 

count++;

 

}

 

else

 

count=0;

 

was_pressed=now_pressed;

 

return event;

 

}

 

Share this post


Link to post
Share on other sites

I generally use a switch statement to build a small (4 state) state machine to do this, but I'm usually debouncing multiple switches in parallel and I don't want to hang around waiting for each switch to settle.

Share this post


Link to post
Share on other sites

It isn't necessary to "debounce" a switch at all, as long as you don't read it too frequently or allow it to create an interrupt. You just have to make sure that you poll the switch input bit(s) at some interval that's longer than the bounce time. If you don't need extremely fast response, 50msec is pretty generous. So you set up a timer to give a repeated overflow, which you can respond to either in an interrupt, if you already have one running at some fixed rate, or if your main() routine features an endless loop, you can just poll the overflow flag there, as long as you clear it once it's found to be set. You might or might not need to compare a "State now" with a "Last state" to detect new switch press/release events.

Share this post


Link to post
Share on other sites

Join the conversation

You are posting as a guest. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...