I have just started using Arduino. I am trying a simple project in which, if I press the push button switch the LED on pin 13 lights up and remains lighted until the push button switch is pressed again. When I initially wrote the code for this I was unaware about bouncing of a switch. And hence my code was something like this:
int ledPin = 13;
int switchPin = 8;
boolean ledOn = false;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(switchPin, INPUT);
}
void loop() {
if(currentState == HIGH)
{
ledOn = !ledOn;
}
else
{
ledOn = ledOn;
}
digitalWrite(ledPin, ledOn);
}
After knowing about the bouncing effect I made the following change:
int ledPin = 13;
int switchPin = 8;
boolean ledOn = false;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(switchPin, INPUT);
}
boolean debounce(int z)
{
if(digitalRead(z) != LOW)
{
delay(5);
}
return digitalRead(z);
}
void loop() {
boolean currentState = debounce(switchPin);
if(currentState == HIGH)
{
ledOn = !ledOn;
}
else
{
ledOn = ledOn;
}
digitalWrite(ledPin, ledOn);
}
But the problem still persists. I want to know what is wrong in what I have done and if I can use an alternate way for debouncing the switch.