Problem using multiple pin for digitalRead

hi. i am new to arduino. i want to make the arduino print this on serial monitor:

→ …
→ 1
→ 1
→ …
when i connect pin 5v to pin 2 and pin 3

→ …
→ 0
→ 0
→ …
when i did not connect anything

→ …
→ 1
→ 0
→ …
when i connect pin 5v to pin 2 only

→ …
→ 0
→ 1
→ …
when i connect pin 5v to pin 3 only

this is the code:

#include <SoftwareSerial.h>
int aa = 0;
int ab = 0;

void setup() {
  // initialize the pushbutton pin as an input:
  pinMode(2, INPUT);
  pinMode(3, INPUT);
  Serial.begin(9600);
}

void loop() {
  delay(100);
  aa = digitalRead(2);
  ab = digitalRead(3);

  Serial.println("..................................");
  Serial.println(aa);
  Serial.println(ab);
  Serial.println("..................................");
}

but what happen to me is the serial monitor show me this:

→ …
→ 1
→ 1
→ …

when i connect pin 5v to pin 2 and 3

→ …
→ 1
→ 0
→ …

when i did not connect anything

→ …
→ 1
→ 0
→ …

when i connect pin 5v to pin 2 only

→ …
→ 1
→ 1
→ …

when i connect pin 5v to pin 3 only

sometime when i try to connect this according to method at above, the arduino did not read the pin* and give the aa and ab variable a random number either 0 or 1.

*(but when i test the digital input 1 by 1 and all ok)

Can you help me solve this problem?

i’m using this code on arduino uno and arduino mega 2560.

thank you very much

If nothing is connected to a pin using pinMode(yourPin, INPUT), the pin floats and react on noise on the environment. You either need a pull-down resistor or a pull-up resistor to get the pin in a defined state if nothing is connected. A pull-up resistor is the easiest and can be done in code.

With below code, it will always read HIGH (1) unless you short the pin to GND.

  pinMode(2, INPUT_PULLUP);  // switch on internal pull-up
  pinMode(3, INPUT_PULLUP);  // switch on internal pull-up

Read up on "floating input".

You need to connect pull-down resistors seperately from each digital input to ground. I'd suggest a value of 10kohm.

NOT pull-ups because then an unconnected input will always show a 1.

johnerrington:
NOT pull-ups because then an unconnected input will always show a 1.

So ? ? ?

sterretje: So ? ? ?

So if you ever want to see anything change connecting the pins to 5V ain't going to work ! ! !

Sorry @johnerrington

Based on OP's requirement, you're right.

And thanks at @slipstick for making me read the OP again ;)

:slight_smile: