View previous topic :: View next topic |
Author |
Message |
thefallen66633
Joined: 13 Feb 2014 Posts: 2
|
pic 16f877 push button debounce broblem |
Posted: Thu Feb 13, 2014 3:18 am |
|
|
Hi. I'm new to this forum, and to Pic too. I write a simple program for Pic 16f877. Each time the button is pressed, LED will change status between turning off and blinking. So far, when i first press, it change from off to blinking. However, when i press again, it still blink. I have tried several delay time, and i think it is debounce problem. Please help me. Thank you guys very much. Here is my code.
Code: | #include <16f877.h>
#use delay(clock=4Mhz)
void main(){
int32 count=0;
while(1){
if (input(PIN_A0)==0)
{delay_ms(1000);
count=1;
}
if(count ==0){
output_low(PIN_B1);
}
if(count ==1){
output_high(PIN_B1);
delay_ms(100);
output_low(PIN_B1);
delay_ms(100);}
if (input(PIN_A0)==0)
count=0;
}
}
|
|
|
|
Mike Walne
Joined: 19 Feb 2004 Posts: 1785 Location: Boston Spa UK
|
|
Posted: Thu Feb 13, 2014 4:18 am |
|
|
Your main problem is NOT debounce.
Before you press the button first time:-
1) The code whizzes round very quickly by missing out all the delay_ms(xx). Count remains at zero.
2) The button is being tested every few us.
After the first press:-
3) Code spends most time in one or other of the delay_ms(xx)
4) The button is tested for ~1us every 200ms.
If you hold the button down for say 200ms you will make count = 0.
A few us later you will test the button again and make count = 1.
So your chances of getting back to the initial state are very slim.
It's a timing problem, you have to release the button in a very narrow time window.
You've got several issues:-
a) Whilst blinking, system is locked up in delay_ms(xx), so missing button press.
b) After you make count back to zero, waiting for button release will probably help.
c) You will still need to provide some degree of debounce.
Mike
Hint. Learn to use the code button. |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19538
|
|
Posted: Thu Feb 13, 2014 4:26 am |
|
|
Your delay, is just a delay, not a debounce.....
You need to read the input, pause a short time, and read it _again_. If it is still set, then accept it.
So, something like:
Code: |
#include <16f877.h>
#use delay(clock=4Mhz)
#define KEY PIN_A0
#define LOW 0
#define HIGH 1
void main(void)
{
int8 count=0; //why use an int32?
while(TRUE)
{
if (input(KEY)==LOW)
{
delay_ms(10); //short delay
if (input(KEY)==LOW) //key is still low
output_high(PIN_B1);
}
else
output_low(PIN_B1);
//Now B1 will go on, if the key goes low, and _stays_
//low for 10mSec
}
}
|
|
|
|
thefallen66633
Joined: 13 Feb 2014 Posts: 2
|
|
Posted: Sat Feb 15, 2014 1:47 am |
|
|
I have solved my problem. Thank you all |
|
|
|