Digital input acting strange

I'm trying out various things with my new Arduino Mega to get acquainted with it. I've hooked up a pushbutton to pin 31 and sent the value of the pin periodically to the Arduino serial monitor. When the switch is open, instead of sending all 1's or all 0's, it sends alternating 1's and 0's. When I close the switch, it sends all 0's. Why not read all 1's when the switch is open?

Here's the test code I'm running:

int digitalSensor = 31; int digitalValue = 0;

void setup() { Serial.begin( 115200 ); pinMode( digitalSensor, INPUT ); }

void loop() { digitalValue = digitalRead( digitalSensor ); Serial.print( "digital value = " ); Serial.println( digitalValue, DEC ); delay( 200 ); }

The reason for this is probably obvious to you guys, but to me it's a mystery. Can you please enlighten me?

Thanks, Dave

You need to either have external pull-up or pull-down resistor on the pin or activate the internal software pull-up resistor. A 'floating digital input pin is just reading noise and will not give a reliable default reading.

Add the following to your setup portion in your sketch.

pinMode(digitalSensor, INPUT); // set pin to input digitalWrite(digitalSensor, HIGH); // turn on pullup resistors


Thank you very much. That did the trick. I especially appreciate the link to the educational resource.