Arduino Uno light up led's 1 by 1 by clicking

So I am new to Arduino, so I wanted to try this function.
Basicly as the title states I want it that when I press a button that 1 led turn on and when I press again the next led turn on and the old one goes off. In total I have 3 led’s. I already wrote some code but when I press the button sometimes it takes 4 to 5 clicks eventhough I put a short delay.

EDIT: Posted entire code!

#include <Arduino.h>

const int PIN_LED_RED = 4;
const int PIN_LED_GREEN = 5;
const int PIN_LED_BLUE = 6;
const int PIN_LED_YELLOW = 7;
const int PIN_BUTTON_1 = 8;
const int PIN_BUTTON_2 = 9;

int buttonState_1 = 0;

void setup() {
  Serial.begin(9600);
  pinMode(PIN_LED_RED, OUTPUT);
  pinMode(PIN_LED_GREEN, OUTPUT);
  pinMode(PIN_LED_BLUE, OUTPUT);
  pinMode(PIN_LED_YELLOW, OUTPUT);
  pinMode(PIN_BUTTON_1, INPUT_PULLUP);
  pinMode(PIN_BUTTON_2, INPUT_PULLUP);
}

void loop() {
  buttonState_1 = digitalRead(PIN_BUTTON_1);

  if (buttonState_1 == LOW)
  {
    digitalWrite(PIN_LED_RED, HIGH);
    delay(150);
    digitalWrite(PIN_LED_RED, LOW);
    delay(150);
  }
  while (digitalRead(PIN_BUTTON_1) == LOW)
  {
    digitalWrite(PIN_LED_GREEN, HIGH);
    delay(150);
    digitalWrite(PIN_LED_GREEN, LOW);
  }
}

Kudos for posting code correctly the first time.

'functions weird' is not a problem description. Describe exactly the behavior you are seeing - since the forum cannot.

The problem could well lie in the code not posted. Edit the original post to include the entire sketch.

What do you mean by weird ?

How is your input button wired ?
Is it in a known state at all times or, when the button is not pressed is it floating at an unknown, possibly HIGH, possibly LOW state ?

when I press a button that 1 led turn on and when I press again the next led turn on

You need to detect when the button becomes pressed, not when it is pressed. The StateChangeDetection example in the IDE shows how to do it

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.