will be read-only starting December 31st, 2018. For more info please look at this Forum Post

The capacitance of a capacitor between an analog input pin and ground can be measured quite accurately by charging the capacitor, then letting it discharge through a known resistance. This sketch does this.

The voltage of the discharging capacitor is described by

U = U_0 * e^(-t/RC)

The function fit_exp fits the above curve to a series of voltage measurements and returns the value for RC, from which C is calculated. Actually fitting the curve instead of waiting for the voltage to drop below a threshold makes the method accurate and independent of the charge voltage U_0.

Capacitor between analog pin and ground, discharging

The sketch uses the tricks described here to make analogRead faster. As one measurement is known to take 16 microseconds, there's no need to record the time for each voltage sample.

In the sketch, the time constant -RC returned by fit_exp is in microseconds, so using a 100k resistor gives C = -RC/10 pF.

If the measured capacitance is very large, additional delays might be needed. The time it takes to charge the capacitor could be used to determine the need for this.

This was originally written to measure soil moisture in flower pots. Below is a test measurement of a soil filled glass jar approx. 10cm in diameter and height. Tinfoil wrapped around the jar was connected to a ground pin. Analog pin was connected to an insulated metal bolt which was inserted in the soil in the middle of the jar. Gradually adding water shows that the moisture content is readable from the capacitance.

Soil capacitance varies with moisture content