Debouncing a pushbutton switch by making a change in the code.

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.

Miraj_Shah:

  else

{
  ledOn = ledOn;
 }

That’s a pretty useless part of code…

Miraj_Shah:
I want to know what is wrong in what I have done

That is a really crude debounce. But my guess it 5ms is just not long enough.

Miraj_Shah:
and if I can use an alternate way for debouncing the switch.

Yes, grab one of the many many libraries. I use Bounce2. Code becomes as simple as (assuming button between GND and pin):

#include <Bounce2.h>

const byte LedPin = 13;
const byte ButtonPin = 8;

Bounce button;

void setup() {
  pinMode(ledPin, OUTPUT);
  button.attach(ButtonPin, NPUT_PULLUP);
}


void loop() {
  button.update();
  if(button.fell()){
    togglePin(LedPin);
  }
}

void inline togglePin(byte pin){
  digitalWrite(pin, !digitalRead(pin));
}

The demo Several Things at a Time includes a simple and effective debounce system by having a short interval between successive button reads.

…R