Multiple buttons connected to an Arduino board

I want to connect four Buttons on my Arduino board, concretely on the digital input pins 2 – 5.
Following /arduino.cc/en/Tutorial/Button I have connected the parts as shown in the upper part of the attached image (next post). However, as soon as one button is closed, the input is distributed to any of the input pins.

I have also tried to connect the parts as shown in the lower part of the attached image (next post). However, as soon as a digital input pin is not attached to ground (if the button is closed) the input value on the pin is completely undetermined (why? I don't understand that)

I hope someone can help me.

Thanks!

You need to use the internal pullups. digitalWrite(pin, HIGH) this turns on the pullups. Do this for each of your pins. Otherwise, the pins are left floating. You can then use the switches to pull the pin to ground. Remove the 5V from the circuit and it should work much better.

Thanks!

I have tried what you said, for the beginning with just one button, connected in the following way:

I removed the 5V as you told, and also the 10K-resistor, because it didn't work with it.

Here is the test code

const int buttonPin = 2; 
const int ledPin =  13;
int buttonState = 0; 

void setup() {
  pinMode(ledPin, OUTPUT);      
  pinMode(buttonPin, INPUT);
  digitalWrite(buttonPin, HIGH);
}

void loop(){
  buttonState = digitalRead(buttonPin);

  if (buttonState == HIGH) {     
    // turn LED on:    
    digitalWrite(ledPin, HIGH);  
  } else {
    digitalWrite(ledPin, LOW); 
  }
}

It works, but it's not very stable:

When the switch changes from closed to open, it seems that takes about ~300 ms till the input on that pin remains stable (I just conclude that from the flickering of the LED).

Very strange: When I put the switch on the table the circuit closes (LED is off).

Slow but steady I despair on that problem :cry:

Don't you mean:

const int buttonPin = 2;
const int ledPin =  13;
int buttonState = 0;

void setup() {
  pinMode(ledPin, OUTPUT);      
  pinMode(buttonPin, INPUT);
  digitalWrite(buttonPin, HIGH);
}

void loop(){
  buttonState = digitalRead(buttonPin);

  if (buttonState == LOW) {    
    // turn LED on:    
    digitalWrite(ledPin, HIGH);  
  } else {
    digitalWrite(ledPin, LOW);
  }
}

more or less the same strange behaviour

When the switch changes from closed to open, it seems that takes about ~300 ms till the input on that pin remains stable (I just conclude that from the flickering of the LED).

What sort of switch is this, it could be that you are suffering with contact bounce if you see instability at change time. Have you got a scope, if not is 300mS a guess because it sounds long for contact bounce.