digitalRead always returns HIGH or provides random output at no voltage

Hello,

I was going to do some minor automation. However, when I started my project, I got unexpected results. Then, I decided to test the performance of digital and analog inputs. To do this, I wrote this code (here, only for digital). The results are either always "HIGH" or a random combination of "HIGH" or "low" when no voltage is applied. When I test it at definite 5V or 0V, I get correct results. I already tried to exchange my Atmega 328 for my UNO, but results are still vey non-predictive.

Please suggest something. Already ran out of ideas.

#define LED 11 // the pin for the LED
#define BUTTON 7 // the input pin where the
// pushbutton is connected
int val = 0; // val will be used to store the state
// of the input pin
void setup() {
pinMode(LED, OUTPUT); // tell Arduino LED is an output
pinMode(BUTTON, INPUT);
Serial.begin (9600); // and BUTTON is an input
}
void loop(){
val = digitalRead(BUTTON); // read input value and store it
// check whether the input is HIGH (button pressed)
if (val == HIGH) {
analogWrite(LED, 50); // turn LED ON
Serial.println ("HIGH");
} 
else {
analogWrite(LED, 0);
Serial.println ("low");
}
}

Please edit your post, select the code, and put it between [code] ... [/code] tags.

You can do that by hitting the # button above the posting area.

... a random combination of "HIGH" or "low" when no voltage is applied ...

"No voltage" is not the same as "setting the pin low". If the pins are unconnected they may pick up random readings which would vary as you waved your hand around, for example.

Have a read of this
http://www.thebox.myzen.co.uk/Tutorial/Inputs.html

I don't know if you figured this out already from Grumpy_Mike's posting:

pinMode(BUTTON, INPUT);
digitalWrite (BUTTON, HIGH); // add this to enable internal pullup - will then read high unless button is pressed to connect to Gnd

Thank you for your answers! It really helped!

Now I feel so ashamed for my post [facepalm] :slight_smile:

No problem.