Button Debouncing Error

int input = 7;
int output = 13;
boolean lastButton = LOW;
boolean ledOn = false;

void setup() {
  pinMode(input, INPUT);
  pinMode(output, OUTPUT);

boolean debounce(boolean buttonState)
  boolean current = digitalRead(input);
  if(buttonState != current)
    current = digitalRead(input);
  return current;

void loop() {
  boolean state = debounce(digitalRead(input));
  if(state == HIGH && lastButton == LOW)
    ledOn = true;
    lastButton = HIGH;
    digitalWrite(output, HIGH);
  else if(state == HIGH && ledOn)
    ledOn = false;
    lastButton = LOW;
    digitalWrite(output, LOW);

This is the code I am using to toggle an LED. However, it is not toggling properly (button only sometimes turns on/off), even after implementing a debounce function. Is my implementation incorrect?

Do you have an external pull-up or pull-down resistor on pin 7? If not you will either need to enable the internal pull-up by changing:

  pinMode(input, INPUT);


  pinMode(input, INPUT_PULLUP);

or add an external resistor. See: https://www.arduino.cc/en/Reference/PinMode

How is your button wired? Do you have pull-up or pull-down resistors in place?

5 ms might be a bit short for some buttons to stabilize