Limit switch fades light when off

Hi. I have a limit switch thats supposed to turn an led when clicked. It works when it is clicked but when I release it, it does not turn off immediately. It fades for about 1-2 seconds when released.

Limit switch COM >>>> 5v pin
Limit switch NO >>>> I/O 4
Led pin 13

Code:

int V;

void setup(){
pinMode(4,INPUT);
pinMode(13,OUTPUT);

}

void loop(){
V=digitalRead(4);
digitalWrite(13, V);

}

Your help would be very appreciated.:grinning::grinning::grinning:

Hello
How do you have the switch connectet to the Arduino?
Post a schematic to see what happens.

Did you use a pull down resistor with your switch?
If not, then it's most likely a 'floating' switchpin.

A resistor is not needed if you change

pinMode(4,INPUT);

to

pinMode(4,INPUT_PULLUP);

And connect the switch between pin and ground.
Logic is now inverted.
You can fix that this way

V = !digitalRead(4);

Leo..

Thank you for all your reply. I will do what you suggest then get back with an update.:grinning::grinning::grinning:

UPDATE: Now it does not turn on even if the switch is closed. How do I fix it? I changed the

INPUT

to

INPUT_PULLUP

Did you also connect the switch between pin and ground (not between pin and 5volt).
Leo..

No. No ground connection.

There are two ways to make a switch work.

  1. connect the switch between pin and VCC (5volt), and use a physical (10k) resistor from pin to ground (pinMode(pin, INPUT).

  2. connect the switch between pin and ground, and make use of the internal pull up inside the processor (pinMode(pin, INPUT_PULLUP).
    Leo..

Will that resolve the fading?

I tried to do it like this:

void loop(){
if(digitalRead(4)==HIGH){
digitalWrite(4,HIGH);
}

if(digitalRead(4)==LOW){
digitalWrite(4,LOW);
}
}

The fading stopped but there is still a 1-2 second/s delay for the LED to go to LOW when the switch is released.

Also when I connect it to pin 13 directly the delay disappears.

Forget the switch, just try with a jumper wire, this will check if its code, or the switch.

I solved it. I using the pullup method and It should be connected to common ground not 5v

Anyways, thanks a lot.:grinning::grinning:

You were told 3 times to do this! Please be more carefull when reading responses!

This could of been resolved 4 Hours ago! :wink:

Anyway, Glad you got it working.

I'm sorry for not reading your responses carefully. I am really thankful for your help.:slightly_smiling_face::slightly_smiling_face::slightly_smiling_face: