[Solved] Digital read value floating between 1 and 0

Hi,
I’m trying to set up a simple circuit with a button so that I can read the state of the button using a digital I/O port. I followed this official Arduino tutorial. I believed I had set up the electronics correctly and I copied the code directly from the tutorial. Despite this the LED that was supposed to respond to the input value fluctuated between on and off randomly leading me to believe that the pull down resistor was not working and the value off the pin was floating. To test this theory I printed the input value of the port using Serial.println() in the following code.

const int pinButton = 2;

void setup() {
  pinMode(pinButton, INPUT);
  Serial.begin(19200);
  Serial.println("hi");
}

void loop() {
  int stateButton = digitalRead(pinButton);

  Serial.println(stateButton);
  delay(20);
}

The results looked like this:

hi
0
0
0
1
1
0
0
1
1
1
0
0
1
1
0
0

For reference my hardware was set up like this:

Am I missing something obvious? I apologize if I broke any posting rules or this is the wrong category.

The circuit is not properly wired on the breadboard, if the image can be trusted.

Central holes are connected vertically (five at a time) on the breadboard. Look at the diagram on the page you linked.

In addition there are two possible orientations for the switch, one of which is wrong.

Thank you, this was my problem.
It seems obvious in hindsight, I appreciate you pointing out the mistake.

Change that to INPUT_PULLUP, wire the button to connect the pin to Gnd when pressed. Ditch the resistor.

Please post a schematic. Fritzing pictures are not a schematic.

I can see how using the internal pullup would be more efficient and easier to wire. Are there any potential downsides to this method?

None whatsoever.
Save on parts, wires, and no direct connection to 5V to drag down the power supply to Gnd accidentally.

This is certainly a simple enough example where a schematic is not needed.
Especially as it shows the incorrect usage of the breadboard.

Thanks,
I’m planning to set up multiple buttons so this should save me a good amount of work.

Yes, you can connect the Gnds of all the buttons together and just run 1 wire back to the Arduino Gnd.

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