Buttons pressed

Hi all,

I wrote a simple script to check if there are buttons pressed. I added a pull down resistor between output of my tactile button and ground. The output of the buttons go to A0, A1, A2, ..., A6. At the input pin of the buttons I put 5V. My script does something very weird. When I press the button it keeps spamming the message "Button pressed". But when I uncomment the third line in this piece of code it suddenly works (which means it only prints "Button pressed" once for every time I press the button).

void checkButtons()
{
  Serial.println(buttonsPressed[0]);
  for(int i = 0; i < AMOUNT_BUTTONS; i++)
  {
    if(digitalRead(A0 + i) == HIGH)
    {
      if(buttonsHeld[i] == false)
      {
        buttonsHeld[i] = true;
        buttonsPressed[i] = true;
        Serial.println("Button pressed");
      }
      else
      {
        buttonsPressed[i] = false;
      }
    }
    else
    {
      buttonsHeld[i] = false;
      buttonsPressed[i] = false;
    }
  }
}

Nowhere other than in this piece of the code are buttonsPressed[] and buttonsHeld[] changed, printed or whatever. Except for the setup which sets all the values to false.

What the hell is happening here?

You need to post the complete program.

...R

Alright here it is. But it doesn't really add anything.

#define AMOUNT_BUTTONS 6

bool buttonsHeld[AMOUNT_BUTTONS], buttonsPressed[AMOUNT_BUTTONS];

void setup()
{
  Serial.begin(9600);

  delay(100);

  for(int i = 0; i < AMOUNT_BUTTONS; i++)
  {
    pinMode(A0 + i, INPUT);
    buttonsPressed[i] = false;
    buttonsHeld[i] = false;
  }
}

void loop()
{
  checkButtons();
}

void checkButtons()
{
  //  Serial.println(buttonsPressed[0]);
  for(int i = 0; i < AMOUNT_BUTTONS; i++)
  {
    if(digitalRead(A0 + i) == HIGH)
    {
      if(buttonsHeld[i] == false)
      {
        buttonsHeld[i] = true;
        buttonsPressed[i] = true;
        Serial.println("Button pressed");
      }
      else
      {
        buttonsPressed[i] = false;
      }
    }
    else
    {
      buttonsHeld[i] = false;
      buttonsPressed[i] = false;
    }
  }
}

Anteino:
Alright here it is. But it doesn't really add anything.

It adds a very important extra - now I know there is nothing else important. You would be surprised what gets left out.

I added a pull down resistor between output of my tactile button and ground.

That does not sound correct. I suspect the input is floating.

Either put a pull-up resistor on the pin (or better still use pinMode(pin, INPUT_PULLUP) ) and use the switch to pull it to GND. Or use a pull-down resistor on the pin and use the switch to pull it to 5v. The former is better as it is less likely to give rise to a short circuit is something comes adrift.

...R

Wait what, the arduino has onboard pullups? After all these years and I never knew. I feel like such an idiot right now :cry: