basic resistor question; why need a resistor to ground when making a reading?

Just a simple question.

When I make a digital or analogue reading from a capacitor or switch, i need to place a resistor between the cable that goes to the input reading socket (say 2, or A0) on the arduino and the ground.

If i don’t do this, the reading is erratic and almost random. What’s going on? Is my arduino on the blink or is this always necessary?

(I attach a fritzing diagram to illustrate).

Many thanks.

Is that a switch or a potentiometer?

With the switch open (and no pull-up or pull-down resistor) there is no connection to the analog input. The input is "floating" and undefined. You may just read noise.

DC current doesn't flow through a capacitor, so again the input is floating as far as DC is concerned. A capacitor will tend to smooth-out the noise. If the capacitor is charged (say, to some voltage between 0 and 5V), the charge should hold for a rather long time (depending on the capacitor value) because of the very-high input impedance on the Arduino.

Like DVDdoug said.

In newbie terms, you use the resistor to make it clear to the pin, what voltage it is at.

Either you connect the pin to 5V on the board or to ground with the resistor. This means, that you either "pull it up" to 5V or "pull it down" to ground level. It overrules all the random noise, and you will not have weird readings from a floating pin.

In your setup (I guess it is a potentiometer), you have the two outer legs to 5V and GND, and read from the middle leg. This is a voltage divider, and you do not need the resistor.

Let us say, that you have a button connected to a pin, and a pull up resistor to 5V. The Arduino will read the pin as HIGH. When you push the button, you connect directly to GND. This is a much more direct way for the electrons, and the pin will now read as LOW.

If you want to read an analog sensor, and it is not in itself a part of a voltage divider, you will have to make it part of a voltage divider with the help of a suitable resistor.

Many thanks for both replies.

As you can tell, i am pretty new, so i am not so sure what component i put in the diagram, (it was meant to ba a potentiometer) but i think you were able to answer the question regardless.

Thanks for taking the time to explain and for your clear explanations.

Think of an input pin as a perfect voltage sensor, drawing no current and very sensitive to nearby fields and stray ions floating in the air and you won't be far wrong. CMOS inputs go to the gates of MOSFETs, and gates are isolated by an ultra-thin layer of silicon oxide (quartz/glass) so the only current that flows is a truly minute leakage current (pico amps perhaps).

Everything else the input "connects" to is a reversed-biased pn-junction, which at room temperature are effective isolation too.