This is my first post. I have just finished my first project which involves a switch running to pin D4. The other end of the switch is connected to the 3V3 pin. The pin is set up via code as pinMode(D4,INPUT_PULLDOWN) so that when it closes, a 3.3V is applied to the pin and it raises an event “switch closed”. All works well. However, when I attached a 5m wire between the switch and the pin, I started to notice the event “switch closed”, followed by “switch opened” around 0.3 seconds later, even though the switch has not been touched. I suspect that this is interference in the wire. I have read on line that it is possible to supress this with a capacitor. Is this the best solution and could I please have more information on how to do it?
Hey James
I suspect you are right about the interference, a capacitor to ground is the best way to deal with this kind of noise. For DC filtering I usually use a 100uF cap just because in general they work, I have attached a circuit diagram that shows you how to wire it in. If you want to dig a bit deeper this is a type of passive RC filter where the R is the pulldown resistance and C is the capacitor you use.
Thanks Clinton, I have tried this and also a external pull-up resistor rather than the internal pull-down circuit, and the combination works. One question that I have is the size of capacitor please. I used a 1.8k Ohm resistor between 3V3 and D4, and then a 100nF (ie 0.1uF) cap across the switch, which now runs between D4 and GND. This seems to work but it is a different order of magnitude to the one that you recommend. How is this decided please?
100uF is just the value I have found works quite well in most applications. Capacitors will look like an open circuit to the DC and an impedance (like resistance) to AC. The size of the impedance will depend on the frequency and size of the capacitor (I added a picture to show this). So as frequency and capacitor size go up the impedance reduces, by choosing a large cap you get the frequency that the cap looks like a short compared to the resistor at lower hertz.