digitalRead on switch seems random

Status
Not open for further replies.

anku

Member
Hello,

a bit of a simple question, but I can't seem to find a solution-- I have a limit switch (NO) connected to pin 14 of my teensy LC:
Code:
#define S_limitSwitch  14  //  A0
. When the switch closes, it connects the pin to ground. The pull up resistor is activated:
Code:
pinMode(S_limitSwitch, INPUT_PULLUP);
. When I do
Code:
Serial.print("S_limitSwitch: ");
Serial.println(digitalRead(S_limitSwitch));
with the switch closed, I get a solid 1 (as supposed), but when it is open, the output is random 0 or 1.
I checked the switch, it works fine. Am I missing something obvious here? Could it be that the cable length of 1m from teensy to the switch causes the problem?

thanks, Philip
 
Disable the internal pullup and use an external 4k7 resistor. Your wire is probably acting like an antenna and the internal pullup is not strong enough.
The resistor goes between pin14 and 3.3V.
 
Disable the internal pullup and use an external 4k7 resistor.
Thank you so much, that (almost) did the trick! However, with an open switch, every 20-100 digitalReads will return a 0. Although that could be fixed in software, do you have any recommendations for further reading on that behaviour (or a keyword to search for)? I'd really like to understand how that happens. Maybe choosing a different resistor value would help :confused:
 
You might be seeing 'Contact Bounce' or chatter:

There are various hardware solutions, but a lot of people use a bounce library that does several reads and only after the button has achieved a steady state is it reported as being changed. I use the Bounce2 library which is a rewrite of the original Bounce library. Both are in the standard Teensy release. I recall having issues with the original Bounce library, but I don't remember what they were.

 
@neurofun A 2k2 resistor definitifely improved the readings. No 100nF capacitors at hand but I ordered some and will add one aswell. Thanks!

@MichaelMeissner Thanks for your suggestions, but the bouncing happens without any contact whatsoever. Since this is a limit switch, bouncing during switching is not really an issue--
 
You might be seeing 'Contact Bounce' or chatter:

There are various hardware solutions, but a lot of people use a bounce library that does several reads and only after the button has achieved a steady state is it reported as being changed. I use the Bounce2 library which is a rewrite of the original Bounce library. Both are in the standard Teensy release. I recall having issues with the original Bounce library, but I don't remember what they were.


Best explanation I've seen in the video. In my case I'd use the output of a TOF timer with the delay of the debouncing time, so that you don't freeze the arduino during the delay.
 
Status
Not open for further replies.
Back
Top