Odd Pin Behaviour

Hi guys,

Firstly, I appreciate all help in advance! I’ve got a little programming experience but barely any of Arduino!

I’ve written a very simple program in preparation for exploring the syntax for serial communication, but I have a problem with my code, which is running on an Arduino Uno.

Pins 2-6 are connected to resistors, and then LEDs, and pins 9-12 are connected to momentary push-to-make switches, the other pins of which are connected to +5V. The Arduino itself is powered by the USB connection.

Here’s the code:

const int firstSwitch = 9;
const int secondSwitch = 10;
const int thirdSwitch = 11;
const int fourthSwitch = 12;

const int yellowLED = 2;
const int greenLED = 3;
const int blueLED = 4;
const int redLED = 5;

void setup() {
  Serial.begin(9600);
  for(int x = 2 ;x < 6; x++) {
    pinMode(x,OUTPUT);
  }
  for(int x = 9; x < 13; x++) {
    pinMode(x,INPUT);
  }
  for(int x = 2; x < 6; x++) {
    digitalWrite(x,LOW);
  }
}

void loop() {
  if (digitalRead(firstSwitch) == HIGH) {
    digitalWrite(yellowLED,HIGH);
    Serial.print("HIGH ");
  } else {
    digitalWrite(yellowLED,LOW);
    Serial.print("LOW ");
  }
  if (digitalRead(secondSwitch) == HIGH) {
    digitalWrite(greenLED,HIGH);
    Serial.print("HIGH ");
  } else {
    digitalWrite(greenLED,LOW);
    Serial.print("LOW ");
  }
  if (digitalRead(thirdSwitch) == HIGH) {
    digitalWrite(blueLED,HIGH);
    Serial.print("HIGH ");
  } else {
    digitalWrite(blueLED,LOW);
    Serial.print("LOW ");
  }
  if (digitalRead(fourthSwitch) == HIGH) {
    digitalWrite(redLED,HIGH);
    Serial.println("HIGH");
  } else {
    digitalWrite(redLED,LOW);
    Serial.println("LOW");
  }
}

I can’t figure out why, but all my LEDs light up and the Serial Monitor shows all the input pins as high, regardless of whether the switches are open or closed. I’m almost certain that there’s not a problem with the circuit!

Any help is much appreciated!

Try this:
Change this line
pinMode(x,INPUT);
to
pinMode(x,INPUT_PULLUP); // enable internal pullup

Change these lines:
if (digitalRead(firstSwitch) == HIGH) {
to
if (digitalRead(firstSwitch) == LOW) {

Wire these:

pins 9-12 are connected to momentary push-to-make switches

to connect the pin to Gnd when pressed.

Change your

Thank you so much! This has really been baffling me :slight_smile: It works perfectly now!

Struan_DW:
I'm almost certain that there's not a problem with the circuit!

It's a problem with your circuit. :stuck_out_tongue:

Also read the part about debouncing.