Why does this button function always return 1 when nothing is pressed?

This function was supposed to return the number of which ever button is pressed( i have 4 buttons connected to pins 2,3,4,5).

This is the function.

int getButtonPressedFunc()
{
boolean pressed = false;
while(pressed == false)
{
button1Value = digitalRead(button1Pin);
button2Value = digitalRead(button2Pin);
button3Value = digitalRead(button3Pin);
button4Value = digitalRead(button4Pin);

if (button2Value !=0)
{
pressed = true;
return 2;
}
if (button3Value !=0)
{
pressed = true;
return 3;
}
if (button4Value !=0)
{
pressed = true;
return 4;
}
if (button1Value !=0)
{
pressed = true;
return 1;
}

}
}

Hello
Welcome to the Arduino fora.
Before you do anything else please take a moment to read General guidance and
How to use this forum
Especially item #7 on posting code.

We need to see ALL your code, not just a bit of it. We also need to know how the buttons are wired.

I suspect you have not used pull down resistors or not wired your buttons correctly.

How are the buttons wired and what pinMode() have you used for their pins ?

You should post your entire code, however, you don't need to set pressed equal to true since you are returning anyway. What you have is equivalent to this:

int getButtonPressedFunc()
{
  while(1)
  {
    button1Value = digitalRead(button1Pin);
    button2Value = digitalRead(button2Pin);
    button3Value = digitalRead(button3Pin);
    button4Value = digitalRead(button4Pin);

    if (button2Value == HIGH)
    {
      return 2;
    }
    if (button3Value == HIGH)
    {
      return 3;
    }
    if (button4Value == HIGH)
    {
      return 4;
    }
    if (button1Value == HIGH)
    {
      return 1;
    }
   
  }  
}

Also, how are your button inputs configured and how are your buttons wired?

Bored today...

int getButtonPressedFunc()
{
  uint8_t pins[] = {button1Pin, button2Pin, button3Pin, button4Pin};
  uint8_t i = 0;
  while (1)
  {
    if (digitalRead(pins[i]) != 0) return i + 1;
    i++;
    if ( i > sizeof(pins[]) / sizeof(pins[0]) ) i = 0;
  }
}

aarg:
Bored today...

Even more bored than aarg...

int getButtonPressedFunc()
{
  const uint8_t pins[] = {button1Pin, button2Pin, button3Pin, button4Pin};
  const uint8_t NUMPINS = sizeof(pins[]) / sizeof(pins[0]);
  const uint8_t PRESSED = HIGH;

  uint8_t i = 0;
  while (1)
  {
    if (digitalRead(pins[i]) == PRESSED) return i + 1;
    i++;
    i %= NUMPINS;
  }
}
  const uint8_t NUMPINS = sizeof(pins[]) / sizeof(pins[0]);
expected primary-expression before ']' token

Even more bored than aarg...

Not possible:

int getButtonPressedFunc()
{
  const uint8_t pins[] = {button1Pin, button2Pin, button3Pin, button4Pin};
  const uint8_t NUMPINS = sizeof(pins) / sizeof(pins[0]);
  int i = 0;
  while (not digitalRead(pins[i % NUMPINS])) i++;
  return (i % NUMPINS) + 1;
}

aarg:
Not possible:

:grin: :grin: :grin: