A touch button can appear to work, then quietly learn a held finger as its new “untouched” value. This experiment makes that software mistake visible. Build one copper pad, track slow baseline changes only when the evidence looks idle, and freeze the baseline while a possible or confirmed touch is present.
Units used below are volts (V), ohms (Ω), watts (W), millimetres (mm), centimetres (cm), milliseconds (ms, one thousandth of a second) and hertz (Hz, cycles per second).
The hardware is an Espressif ESP32-DevKitC V4 with ESP32-WROOM-32E, running official MicroPython1.26.0. We use the original ESP32 capacitive-touch peripheral on GPIO27, also called TOUCH7. GPIO means general-purpose input/output. This is a relative capacitive interface, not an analog-to-digital converter (ADC) voltage measurement: the program never creates an ADC object or converts its counts into volts or picofarads.
Use the classic ESP32 interpretation
Capacitance describes how conductors separated by an insulating region store electric charge. A nearby finger, the lead, board ground, enclosure and surrounding objects all affect the touch pad’s coupling. MicroPython returns relative touch counts; on the original ESP32, the count becomes smaller when the pin or attached electrode is touched.
That direction is not portable to every chip with ESP32 in its name. The documented ESP32-S2 and ESP32-S3 touch readings move in the opposite direction. A C3 or another board is not silently supported by this lesson. Confirm the WROOM-32E marking, DevKitC revision and firmware before applying this policy.
The currently retrieved WROOM-32E/32UE datasheet is version2.1, specifying a3.0–3.6V module supply with3.3V nominal. The development board’s normal USB connector supplies its regulator; USB means Universal Serial Bus. Do not interpret a5V board-power connector as permission to apply5V to GPIO27 or the electrode.
One electrode, a short lead and a series resistor
- Exact ESP32-DevKitC V4/WROOM-32E; a data-capable USB cable; official MicroPython1.26.0.
- A510Ω,1%,0.125W or higher resistor close to the board’s GPIO27 header connection.
- A roughly15mm×15mm copper-foil pad fixed to a nonconductive backing, with a short lead of roughly5cm or less.
- A fixed cover coupon, for example0.5mm PET plastic, over the electrode; PET means polyethylene terephthalate. Record its actual material/thickness and keep that geometry fixed.
- A stable bench arrangement with the board and lead immobilized. The computer’s console records observations; no relay, motor or human-protection function is connected.

Connect GPIO27→510Ω→pad and use the board’s existing ground reference. Do not add a digital pullup or wire the electrode directly to ground. The pad is one sensing net. Espressif’s current hardware guideline recommends a chip-side series resistor in the470Ω–2kΩ range, preferably510Ω, with the final choice dependent on product testing. The resistor is not a calibrated sensitivity adjustment and its presence is not a system-level protection certificate.
Pad area, cover, lead length, board grounding and the operator’s surroundings can all change the raw count. Treat our dimensions as a reproducible starting fixture, not a universal touch-button recipe. Moving the lead can matter as much as changing a threshold. Keep the electrode away from other wires during the initial comparison and record any intentional geometry change.
A baseline needs an explicit condition
A baseline is the reference count representing the declared untouched condition. Startup asks the operator to keep the pad and lead untouched, allows500ms, then collects32 readings with10ms delays. The allowance is an application choice, not a guaranteed sensor warm-up time. A stable finger held on the pad during startup can still produce a stable but wrong baseline; software variance checks cannot prove the operator removed it.
The calibration requires32 positive integer counts, a mean of at least20counts, and an observed maximum-minus-minimum span no greater than10% of that mean. The minimum is a numeric-resolution policy and the span rule is an experimental quality check. They are not Espressif touch-accuracy specifications. Failed recalibration revokes the old reference rather than silently returning to it.
Once calibrated, the policy uses the previous sample’s baseline b to calculate enter=0.75b and release=0.88b. With a synthetic baseline of1000counts, those are750 and880. Three consecutive samples at or below the entry threshold confirm a press. Three consecutive samples at or above the release threshold confirm release. Hysteresis means the two transition boundaries differ, reducing rapid back-and-forth decisions near one threshold.
Freeze before confirmation, not only after it

The baseline is already held during TOUCH_CANDIDATE. It is also held in the intermediate region between the entry and release thresholds, reported as BASELINE_HOLD. That prevents the first few possible-touch readings from moving the reference before the three-sample decision completes. A confirmed touch and its release-confirmation samples also leave the baseline unchanged.
Only an idle reading above the release boundary updates the reference: bnext=b+(raw−b)/256. This is an exponential moving average, a filter that moves a small fraction toward each new value. For synthetic b=1000 and raw=1010, the next baseline is1000.0390625. It is not reset to1010 or averaged with a held-touch count.
With exactly20ms sample spacing,256samples would be about5.12seconds, approximately the filter’s response scale. Our loop also reads and prints, so it is not a precision50Hz scheduler. The three-sample decision spans two nominal intervals, about40ms plus sampling phase and processing time; no measured latency is promised.
The adaptive baseline is limited to±20% of the initial session reference. Exceeding that range latches FAULT and requires a new declared-untouched calibration. This bounds software adaptation; it cannot distinguish every environmental change from a real touch. A large downward environmental change may look like an indefinitely held touch, while a slow approach can remain below the experiment’s detection contrast. Those are limitations to observe, not reasons to label the interface universally reliable.
Unknown must stay different from released
A zero, negative, noninteger or out-of-domain count is not treated as “not touched.” Read exceptions and invalid values latch FAULT, with touch=None and no trusted baseline in the report. Repeated plausible readings do not automatically clear that state. Recovery is a deliberate new run/calibration with the electrode untouched and the fixture checked.
Do not report a press event on every low reading. The program emits PRESSED once when confirmation completes, and RELEASED once at release. It also records raw count, baseline before/after the decision, thresholds used and whether adaptation was held. A quiet console is not evidence of a healthy peripheral; preserve explicit state reports when reviewing the experiment.
Complete MicroPython program
The MicroPython application programming interface (API) supplies TouchPad, Pin and timed delays. Save the complete file as touch_baseline.py on the named ESP32. With the pad untouched, run import touch_baseline; touch_baseline.main() from the USB console. Stop with Ctrl+C before changing the circuit or deliberately starting a fresh calibration.
Download full code (ZIP; file: tricky-circuit-batch-006/code/esp32-touch-baseline.py) · Blank baseline worksheet (ZIP; file: tricky-circuit-batch-006/code/esp32-touch-baseline-observations-blank.csv)
"""Classic ESP32-WROOM-32E touch7/GPIO27; MicroPython1.26.0.
Relative touch counts are not ADC voltage readings or calibrated capacitance.
"""
def raw_ok(raw):
return type(raw) is int and 1 <= raw <= 65535
class TouchPolicy:
def __init__(self):
self.baseline = None
self.reference = None
self.touched = False
self.enter_count = self.release_count = 0
self.error = None
def fail(self, reason):
self.error = str(reason)
return {"state": "FAULT", "touch": None, "baseline": None, "error": self.error}
def calibrate(self, samples):
self.error = "calibration not completed"
self.baseline = self.reference = None
self.touched = False
self.enter_count = self.release_count = 0
if len(samples) != 32 or not all(raw_ok(n) for n in samples):
raise ValueError("need32 valid untouched readings")
mean = sum(samples) / 32
if mean < 20 or max(samples) - min(samples) > mean * 0.10:
raise ValueError("untouched baseline too small or unstable")
self.baseline = self.reference = mean
self.touched = False
self.enter_count = self.release_count = 0
self.error = None
return {"state": "CALIBRATED", "baseline": mean,
"condition": "operator declared pad untouched; not independently proved"}
def step(self, raw):
if self.error is not None:
return self.fail(self.error)
if self.baseline is None:
return self.fail("calibration required")
if not raw_ok(raw):
return self.fail("invalid touch count")
b = self.baseline
enter, release = 0.75 * b, 0.88 * b
event = None
state, held = "IDLE", True
if self.touched:
self.release_count = self.release_count + 1 if raw >= release else 0
if self.release_count >= 3:
self.touched = False
self.release_count = 0
event, state = "RELEASED", "IDLE"
else:
state = "RELEASE_CANDIDATE" if self.release_count else "TOUCHED"
else:
self.enter_count = self.enter_count + 1 if raw <= enter else 0
if self.enter_count >= 3:
self.touched = True
self.enter_count = 0
event, state = "PRESSED", "TOUCHED"
elif self.enter_count:
state = "TOUCH_CANDIDATE"
elif raw <= release:
state = "BASELINE_HOLD"
else:
candidate = b + (raw - b) / 256
if not self.reference * 0.8 <= candidate <= self.reference * 1.2:
return self.fail("adaptive baseline exceeded20% session range")
self.baseline = candidate
held = False
return {"state": state, "touch": self.touched, "event": event,
"raw": raw, "baseline_before": b, "baseline": self.baseline, "baseline_held": held,
"enter_threshold": enter, "release_threshold": release}
def run(reader, sleep_ms, emit=print, samples=None):
policy = TouchPolicy()
try:
emit({"state": "CALIBRATING", "instruction": "keep pad and lead untouched"})
sleep_ms(500) # Setup allowance; not a proven physical stability time.
initial = []
for _ in range(32):
initial.append(reader())
sleep_ms(10)
emit(policy.calibrate(initial))
count = 0
while samples is None or count < samples:
result = policy.step(reader())
emit(result)
if result["state"] == "FAULT":
break
count += 1
sleep_ms(20) # Read/printing time is additional; not a precise scheduler.
except (OSError, ValueError) as error:
emit(policy.fail(error))
return policy
def main():
from machine import Pin, TouchPad
from time import sleep_ms
try:
sensor = TouchPad(Pin(27)) # Classic ESP32 TOUCH7; not an ADC object.
run(sensor.read, sleep_ms)
except (OSError, ValueError) as error:
print({"state": "INITIALIZATION_FAULT", "touch": None, "error": str(error)})
except KeyboardInterrupt:
print({"state": "STOPPED", "instruction": "remove touch before a new run/calibration"})
if __name__ == "__main__":
main()
Repeat the experiment in controlled stages
- Disconnect power and inspect the exact module, GPIO27 connection, resistor and pad. Fix the pad, lead and cover. Power through the development board’s normal USB connector only, and record the board/module/firmware identity.
- Start untouched. Record the initial32-reading baseline quality and several idle reports. If calibration fails, inspect the setup and repeat rather than silently relaxing every numeric rule.
- Touch the covered pad briefly and release. Inspect candidate states and the single press/release events. Then hold the touch for30seconds: the reported baseline should remain unchanged throughout candidates and touch. That is a software prediction to check, not an author-supplied result.
- After release, keep the pad untouched and introduce one controlled slow change, such as repositioning a nearby unconnected object. Record raw count and slow adaptation. Moving the electrode lead itself is a separate trial with a fresh calibration.
- Try a different cover thickness or pad area in a separately labelled setup. Recalibrate and repeat. Do not compare only absolute raw numbers from different fixtures as if they were universal capacitance units.
- For invalid counts and read-failure recovery, run the host injections. For a physical connection fault, switch power off before disconnecting the pad; an open pad lead may still produce plausible counts, so record the actual result instead of claiming guaranteed fault detection.
Espressif’s hardware guidance identifies a conducted-susceptibility limitation for this touch peripheral, and the current chip errata includes a deep-sleep touch/power-domain issue. This program stays awake and polls; it does not use deep sleep, touch wakeup or a claimed workaround for those power modes. Record the actual chip revision when extending it, and review the relevant errata before changing power-domain behavior.
Challenge: why not keep averaging while the pad is held?
A long held touch would gradually pull the reference toward the touch value. Its threshold would then move, potentially ending a real held-touch state in software. Here candidate, hold and touch states freeze adaptation; later physical trials must still determine whether the chosen contrast and drift rules suit the fixture.
Checks and primary sources
Host tests execute the actual baseline, hysteresis, adaptation and application functions. They verify entry/release confirmation, candidate resets,20000held-touch samples without baseline movement, bounce, fault latching, explicit recovery, failed-recalibration revocation and session-drift limits. Injected read failures at startup and mid-run remain unknown. The tests have no electrode, interference, enclosure or person in the loop.
- MicroPython1.26 capacitive-touch reference: original ESP32 reading direction and supported pins.
- Espressif touch hardware guidance: GPIO27/TOUCH7, series-resistor range and application limitations.
- WROOM-32E/32UE datasheet version2.1 and DevKitC V4 board guide.
- Current ESP32 errata summary; silicon identification and power-mode applicability remain part of any later hardware extension.
The interactive lessons cover capacitance and digital state foundations. This project adds a baseline policy that exposes uncertain evidence, rather than converting every changing raw number into a confident button event.



