I'm a beginner and I wrote this for debouncing
int led=13,switchp=5;
boolean prevbtn=LOW,ledst=LOW;
void setup()
{
pinMode(led,OUTPUT);
pinMode(switchp,INPUT);
}
void loop()
{
int readsw=digitalRead(switchp);
if(readsw!=prevb)
{
delay(50);
reads=digitalRead(switchp);
}
if(readsw==HIGH && prevb==LOW)
{
ledst=!ledst;
prevbtn=HIGH;
}
else
prevbtn=digitalRead(switchp);
digitalWrite(led,ledst);
}
The switch still bounces...may I know why ?
Won't even compile without adding these 2 lines before setup()
byte prevb;
byte reads;
How do you know it still bounces?
For simple switch bounce code, read the switch every 50-100 ms, if there was a state change, do your something based on the current state.
Do not use delay() as sketch progress is frozen in time for that period.
.
This simple debounce works for me, connect button between pin 5 and GND:
const byte btn = 5,
ledPin = 13;
unsigned long timeStart; // unsigned long
unsigned long dbTime = 250; // debounce time, long for testing,
// 10 - 20 typical
bool btnState = false, debouncedState = false;
void setup()
{
pinMode(btn,INPUT_PULLUP);
pinMode(ledPin,OUTPUT);
}
void loop()
{
// debounce+++++++++++++++++++++
if(digitalRead(btn) != btnState) // they are different!
{
btnState = !btnState; // make them equal
timeStart = millis(); // restart timer
}
if(millis() - timeStart > dbTime) // if not changed for dbTime,
debouncedState = !btnState; // btnState is valid, use it
// end debounce+++++++++++++++++
digitalWrite(ledPin,debouncedState);
}
By looking at your code, you are simply toggling the LED state.
You can use this code for debouncing, I have used it many times in my other projects and it works flawlessly. It only sense button press & would not trigger on release.
const byte PIN_SWITCH = 5;
const byte PIN_LED = 13;
byte lastSwitchState = 0;
void setup(){
pinMode(PIN_SWITCH, INPUT);
pinMode(PIN_LED, OUTPUT);
}
void loop(){
int currentSwitchState = digitalRead(PIN_SWITCH);
if(currentSwitchState > lastSwitchState){
toggleLED();
}
lastSwitchState = currentSwitchState;
}
void toggleLED(){
digitalWrite(PIN_LED, !digitalRead(PIN_LED));
}
Also, use a .1uF electrolytic cap across the switch for smooth operation.
Thanks for the help everybody....
This fixed it
Delta_G:
If you're debouncing a button then you should only read it once and do all the logic with one reading. Try setting it to equal readsw every time instead of reading it again.