Problem with my counter

Hi,

I have 4 leds that I want to turn on when I press the button. If I press once, led1 should be on and if I press twice led2 should go on, etc.

But instead of just counting 1 when I press the button it counts really fast. Also when I keep the button pressed it keeps counting. I know it's looping the counter part when I press the button, so something must be wrong there, but I can't figure out what.

if (debounceButton(buttonState) == HIGH && buttonState == LOW) { buttonState == HIGH; counter++; Serial.println(counter); }

What have I missed or am I doing wrong?

const int buttonPin = 8;
int led1 = 2;
int led2 = 3;
int led3 = 4;
int led5 = 5;
boolean buttonState = LOW;
int counter = 0;

void setup() {
  Serial.begin(9600);
  pinMode(buttonPin, INPUT);

  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  
  
}


void loop() {
      if (debounceButton(buttonState) == HIGH && buttonState == LOW) {
          buttonState == HIGH;
          counter++;
          Serial.println(counter);
      }    
      else if (debounceButton(buttonState) == LOW && buttonState == HIGH) { 
        buttonState = LOW; 
      }
      if (counter == 1) {
        digitalWrite(2, HIGH);  
      }
      if (counter == 2) {
        digitalWrite(3, HIGH);
      }
      if (counter == 3) {
        digitalWrite(4, HIGH);
      }
      if (counter == 4) {
        digitalWrite(5, HIGH);
      }
}


boolean debounceButton(boolean state) {
  boolean stateNow = digitalRead(buttonPin);
  if (state != stateNow) {
    delay(20);
    stateNow = digitalRead(buttonPin);
  }
  return stateNow;
}

You need to detect when the button [u]becomes[/u] pressed rather than when it [u]is[/u] pressed. Look at the StateChangeDetection example in the IDE

Incidentally, the code you posted does not compile.

          buttonState == HIGH;

The assignment operator is NOT ==.

How IS your switch wired?

PaulS:           buttonState == HIGH;

The assignment operator is NOT ==.

How IS your switch wired?

That was the problem, should have been = I seriously been looking at it for a long time and didn't see it.

Thank you!