PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Thu Mar 05, 2015 6:31 pm |
|
|
There are many ways to debounce a push-button. The program below
shows one way. Every time you push the button, you will increment the
count and it will be displayed in the terminal window (TeraTerm).
Example:
Quote: | 1 2 3 4 5 6 7 8 9 10 11 12 13 |
The push-button must be connected to the PIC with the circuit shown
below. You can use 4.7K pullup (or 10K or some other value).
Code: |
+5v
|
<
> 4.7K
< ___ Push button switch
To | _|_|_
PIC -----------------o o------
pin |
B0 --- GND
-
|
In the test program below, the internal PortB pullups are used, so the
external pull-up is not needed.
Test program:
Code: |
#include <18F4520.h>
#fuses INTRC_IO, BROWNOUT, PUT, NOWDT
#use delay(clock=4M)
#use rs232(baud=9600, UART1, ERRORS)
#define BUTTON_PIN PIN_B0 // This pin must have a pull-up.
#define DEBOUNCE_PERIOD_IN_MS 10
#define DEBOUNCE_COUNT 2
void wait_for_keypress(void);
//====================================
void main()
{
int8 count;
port_b_pullups(TRUE);
count = 0;
while(TRUE)
{
wait_for_keypress();
count++;
printf( "%u ", count);
}
}
//==================================
void wait_for_keypress(void)
{
char count;
// First, wait for the button to be released. With the debounce
// values as given above, the button must be in the "up" state
// for two consecutive readings, spaced 10 ms apart.
count = 0;
while(TRUE)
{
if(input(BUTTON_PIN) == 1)
count++;
else
count = 0;
if(count == DEBOUNCE_COUNT)
break;
delay_ms(DEBOUNCE_PERIOD_IN_MS);
}
// Now that the button is up, wait until the user presses it.
// In order for the keypress to be considered valid, based
// on the debounce values listed at the beginning of the
// program, the button must be held down for two consecutive
// readings, spaced 10 ms apart.
count = 0;
while(TRUE)
{
if(input(BUTTON_PIN) == 0)
count++;
else
count = 0;
if(count == DEBOUNCE_COUNT)
break;
delay_ms(DEBOUNCE_PERIOD_IN_MS);
}
}
|
|
|