Button Debounce

Hey I'm new to the forum and just got my first Ardunio today.

Could anyone tell me why my Button Debounce program is not working?

int led1 = 13;
int switch1 = 52;

boolean track1 = LOW;
boolean ledtrack = LOW;
boolean bcurrent = LOW;



void setup() {
  
  pinMode(switch1, INPUT);
  pinMode(led1, OUTPUT);
}
  boolean bounce(){
    bcurrent = digitalRead(switch1);
    if (bcurrent != LOW)
    {
      delay(5);
      bcurrent = digitalRead(switch1);
    }
    return bcurrent;
  
}

void loop() 
{

  track1 = bounce();
  
  if (track1 == HIGH)
    {
      ledtrack = !ledtrack;
      digitalWrite(led1, ledtrack);
      bcurrent = LOW;
    }
  
  
}

Please explain what you mean when you say that it is not working. How is the button wired ?

I do wish that people would use consistent data types in programs even when some are interchangeable. The bounce() function returns a boolean and you then test to see whether what is returned is HIGH. It would be easier to say
if (bounce())to test whether the value returned is true. Changing the name of the function to say pressed() would make the program easier to understand too.

This is ehh...Ok, there is a better way, but for now, its ok.

bcurrent = digitalRead(switch1);
if (bcurrent != LOW)
{
delay(5);
bcurrent = digitalRead(switch1);
}
return bcurrent;

This however is not.

if (track1 == HIGH)
{
ledtrack = !ledtrack;
digitalWrite(led1, ledtrack);
bcurrent = LOW;
}

Assuming you want to make a latch, press once do something, press again undo, or do something else, then this part he is wrong.

You don't want to see if it is HIGH all the time, you want to see if it transitions from HIGH to LOW and if that is true AND it is high, then the IF statement is true. Also "bcurrent = LOW;" isn't doing anything.

I think I might have broken the board =(

It started to act funny so I loaded the blink example script and the led pin seems to be OK. After I loaded a simple push to turn on the LED script that was working before. Its not working the way it should at all. The LED will come on as long as something is plugged into the digital pin I'm using for the switch even if the other end of the wire isn't connected to anything at all.

I have checked all the connections 4 or 5 times. The simple code I used was from a website and it was working before.

Have I broken it?

Please post a schematic and pictures.

Sounds like you don't have a pulling (pull up or pull down) resistor, so the pin is basically floating until the button is pressed.

HazardsMind:
Please post a schematic and pictures.

Sounds like you don't have a pulling (pull up or pull down) resistor, so the pin is basically floating until the button is pressed.

That's fixed it thanks. Hopefully I can get back to fixing the code now tomorrow.

Great.