Section 3.4 Capacitive touchpads
Most touchscreens and touch-sensitive electronic devices use a technique known as "capacitive touch sensing". You may have used a touch lamp or other touch-sensitive electronic devices.
Subsection 3.4.1 What is a capacitor?
A capacitor is a device that stores electrical charge. You could think of it like a teeny-tiny rechargable battery that can be charged and discharged thousands or millions of times per second.
You may have learned in physics about a "parallel-plate capacitor", which is just two plates of metal separated by an air gap or insulator. If you apply a voltage across the plates, positive charges will be pushed on to one plate and negative charges onto the other until the electric field builds up and the potential difference between the plates equals the applied voltage. The bigger the plates, or the smaller the gap, the more charge you can push onto the plates with a given voltage. This is called *capacitance*. Capacitance is measured in coulombs per volt (amount of charge stored per unit voltage), and is renamed the Farad (in honor of scientist Michael Faraday 1 ).
Now if two metal objects separated by an insulator form a capacitor, then it shouldn't suprise you that *any* two conductive objects have some capacitance. Two wires running next to each other on a circuit board have some capacitance, overhead electrical cables have some capacitance with the ground (that's part of why they're so high up), and my body has some capacitance with the wiring in my house (thankfully not enough to have any biological impact). And, particular to our application, a microcontroller input/output pin has some capacitance to the ground pin, simply because they are two metal objects separated by an insulator. When a conductive object (such as your body) touches the input/output pin, this changes the overall capacitance of the system. If we had a way to measure that change in capacitance, then we could make touch-sensitive objects without needing switches.
Subsection 3.4.2 Measuring capacitance with a microcontroller
When a charged capacitor is connected to a resistor, the charges on the capacitor leave and flow through the resistor.
In the simulation below, close the switch and observe what happens. Then try adjusting the capacitance using the slider on the right, and reset the simulation. How does the voltage change over time? How does the capacitance affect the behavior of the circuit?
Subsection 3.4.3 Using capacitive touch pads on the ESP32
from machine import TouchPad, Pin t = TouchPad(Pin(14)) touchReading = t.read()
The first line is the usual ``import`` statement to load the needed library objects. The second line sets up the touch pad and saves it in the variable ``t``. The final line tells the microprocessor to read the touch pad and return the value.