Unexpected delay while reading digital pin state

Hi everyone,

I'm relatively new to using Arduino, but not to computer programming in general. It's most likely something basic, but I wasn't able to find much on the issue, or at least nothing that helped my case (it may have been my phrasing). The following is my code reduced down to just the parts that give me the trouble:

void setup() {
 pinMode(6,INPUT);
 pinMode(13,OUTPUT);
}

void loop() {
    if (digitalRead(6)==HIGH) 
      digitalWrite(13,HIGH);
    else
      digitalWrite(13,LOW);
}

I would expect that the when pin 6 is connected to 5V that the LED on pin 13 would turn on, and when pin 6 is then disconnected, the LED would turn off. However, even though the LED turns on immediately, there is a 2-5 second delay before it turns off again once the 5V has been disconnected from pin 6. I suppose that this is sort of like pressing a button, in which case this might have to do with debouncing? Thanks for your help.

When you say the 5V is disconnected from pin 6, is pin 6 then connected to ground or left floating? If you leave it floating (nothing connected to it) then it can read any random thing and will usually read whatever voltage was last applied for at least a little while.

Facepalms* Okay that was very silly of me. No, it wasn't connecting to ground afterwards. That would explain it and yes, now it's working correctly. Thank you!

Ususally, you would put a resistor between the pin and ground in this situation, to hold the pin low unless it's switched to 5V. 10K is a typical value for this 'pulldown' resistor.

Or, you can do it the other way - connect the resistor from the input pin to +5V, (a 'pullup' resistor), then switch it to GND when 'active'.
In this case, you can even eliminate the external resistor in most cases. There are built in internal 'pullup' resistors in the chip, which can be enabled like this:-

pinMode(6, INPUT_PULLUP);

Now the pin will not 'float' when left unconnected. It will be high, and will go low when you switch it to GND.
Then you would turn the LED on/off in your code like this:-

if (digitalRead(6)==LOW)
      digitalWrite(13, HIGH);
else
      digitalWrite(13, LOW);

Ah, so in that case, the LED would turn on when I connect the pin to ground and pull back up to high otherwise.

Some typical arrangements to follow:

.

carljmont:
Ah, so in that case, the LED would turn on when I connect the pin to ground and pull back up to high otherwise.

Yep, you've got it. If you were using a pushbutton, it would connect between the pin and ground.
Larry's diagram will help. (I described the situation with S3 in his diagram.)