ESP32 Capacitive Touch Lamp Switch with Relay

Build an ESP32 capacitive touch lamp switch using the built-in touch pin, a metal plate and a relay module. Tap to toggle, long press for off. Wiring table, diagram and full code.

  • DifficultyEasy
  • Build time1–2 hours
  • Board / MCUESP32 DevKit
  • Parts7 items
  • CodeArduino C++

Need it ready-made? Buy Ready Project

This ESP32 touch lamp switch turns any metal surface into a light switch. Tap a small metal plate and the lamp turns on, tap it again and it turns off. There is no separate touch sensor module: the ESP32 has capacitive touch sensing built into some of its pins, so the only parts you need are the board, a relay module and a piece of metal.

It is a small beginner project that teaches how the ESP32 touch pins work, how to calibrate them, and how to debounce a touch input so the lamp does not flicker.

ESP32 capacitive touch lamp switch wiring with touch plate, relay module and lamp

How the ESP32 Touch Lamp Switch Works

  • Capacitive sensing: GPIO4 is touch pad T0. The ESP32 measures how much charge the pin and the wire attached to it can hold. When your finger touches the plate, your body adds capacitance and the reading from touchRead() drops noticeably on the original ESP32.
  • Auto calibration: at power-up the sketch takes 20 readings with nobody touching the plate and stores the average as the baseline. A touch is counted when the reading falls 30% below that baseline, so it works with different plate sizes and wire lengths.
  • Debounce: a touch must stay stable for 60 ms before it counts, which filters out electrical noise.
  • Tap and long press: a short tap toggles the lamp when you lift your finger. Holding the plate for 1.5 seconds always turns the lamp OFF.
  • Relay output: GPIO26 drives the relay module, and the relay contacts switch the lamp. The on-board blue LED on GPIO2 shows whether the lamp is on.

Components Required

  • ESP32 DevKit V1 (ESP32-WROOM-32) – 1
  • 1-channel 5 V relay module (opto-isolated, contacts rated 10 A 250 V) – 1
  • Metal touch plate: a coin, a small aluminium or copper sheet, or a steel bolt head – 1
  • Insulated hook-up wire (keep the touch wire under about 30 cm)
  • 5 V USB adapter and USB cable
  • Table lamp with a bulb, and a closed plastic enclosure for the relay
  • Jumper wires and a breadboard

Wiring Table

PartESP32 pinNotes
Touch plateGPIO4 (T0)Single insulated wire, solder it to the plate
Relay module INGPIO26Lamp control signal
Relay module VCCVIN (5V)5 V from USB
Relay module GNDGNDCommon ground
Relay COMLamp live wire (from mains)Switched side
Relay NOLamp live wire (to lamp)Lamp ON when relay is ON
On-board LEDGPIO2Already on the board, no wiring needed

Most cheap relay modules switch ON when the input is LOW, and the sketch is set for that (RELAY_ACTIVE_LOW = true). If your module switches ON with a HIGH input, change it to false. If the relay does not click reliably with the 3.3 V signal, use a module marked as 3.3 V compatible.

Connection Diagram

The illustration at the top shows the general layout. The pin-accurate drawing below matches the wiring table exactly.

ESP32 Capacitive Touch Lamp Switch – Pin-Accurate Wiring ESP32 DevKit GPIO4 (T0) Metal touch plate (insulated wire, keep under 30 cm) GPIO26 Relay module IN VIN (5V) Relay module VCC GND Relay module GND GPIO2 On-board LED (already fitted, shows lamp state) Relay COM and NO are wired in series with the lamp live wire. Mains wiring must be enclosed and done by a qualified person. Power the ESP32 from USB 5 V so the VIN pin can feed the relay module.
Pin-accurate connection diagram for the ESP32 capacitive touch lamp switch.

Arduino Code

In the Arduino IDE install the ESP32 board package by Espressif, select ESP32 Dev Module and upload the sketch. No extra libraries are needed. Keep your hands away from the touch plate for the first second after power-up while it calibrates.

/*
  ESP32 Capacitive Touch Lamp Switch with Relay
  ---------------------------------------------
  Touch a metal plate wired to GPIO4 (touch pad T0) to toggle a lamp
  through a relay module. A short tap toggles the lamp, a long press
  (over 1.5 s) turns it OFF. The on-board LED (GPIO2) mirrors the lamp state.
  No extra touch sensor module is needed: the ESP32 has capacitive touch built in.

  Board: ESP32 Dev Module (ESP32 Arduino core 2.x or 3.x)
*/

const int TOUCH_PIN = 4;     // T0 = GPIO4, connect to the metal touch plate
const int RELAY_PIN = 26;    // relay module IN
const int LED_PIN   = 2;     // on-board blue LED

// Most cheap relay modules turn ON when IN is LOW. Set to false if yours turns ON with HIGH.
const bool RELAY_ACTIVE_LOW = true;

const unsigned long DEBOUNCE_MS   = 60;    // touch must be stable this long
const unsigned long LONG_PRESS_MS = 1500;  // hold this long to force OFF

uint32_t baseline = 0;       // untouched reading, measured at start-up
uint32_t threshold = 0;      // readings past this count as a touch
bool lampOn = false;
bool touched = false;        // debounced touch state
bool longDone = false;       // long press already handled
unsigned long changeStart = 0;
unsigned long pressStart = 0;

void setLamp(bool on) {
  lampOn = on;
  digitalWrite(RELAY_PIN, (on ^ RELAY_ACTIVE_LOW) ? HIGH : LOW);
  digitalWrite(LED_PIN, on ? HIGH : LOW);
  Serial.printf("Lamp %s\n", on ? "ON" : "OFF");
}

// Average several readings to reduce noise
uint32_t readTouch() {
  uint32_t sum = 0;
  for (int i = 0; i < 8; i++) sum += touchRead(TOUCH_PIN);
  return sum / 8;
}

// On the original ESP32 a touch makes the reading DROP.
// (On ESP32-S2/S3 it RISES, so this check handles both.)
bool isTouched(uint32_t v) {
  if (threshold < baseline) return v < threshold;
  return v > threshold;
}

void setup() {
  Serial.begin(115200);
  pinMode(RELAY_PIN, OUTPUT);
  pinMode(LED_PIN, OUTPUT);
  setLamp(false);

  delay(500);                       // keep hands off the plate during calibration
  uint32_t sum = 0;
  for (int i = 0; i < 20; i++) { sum += readTouch(); delay(20); }
  baseline = sum / 20;
#if CONFIG_IDF_TARGET_ESP32
  threshold = baseline * 70 / 100;  // ESP32: touched when reading falls 30%
#else
  threshold = baseline * 130 / 100; // ESP32-S2/S3: touched when reading rises 30%
#endif
  Serial.printf("Touch baseline %u, threshold %u\n", baseline, threshold);
}

void loop() {
  uint32_t v = readTouch();
  bool raw = isTouched(v);
  unsigned long now = millis();

  // Debounce: accept a new state only after it stays the same for DEBOUNCE_MS
  if (raw != touched) {
    if (changeStart == 0) changeStart = now;
    if (now - changeStart >= DEBOUNCE_MS) {
      touched = raw;
      changeStart = 0;
      if (touched) {                // finger just landed
        pressStart = now;
        longDone = false;
      } else if (!longDone) {       // finger lifted after a short tap
        setLamp(!lampOn);
      }
    }
  } else {
    changeStart = 0;
  }

  // Long press: force the lamp OFF once
  if (touched && !longDone && now - pressStart >= LONG_PRESS_MS) {
    longDone = true;
    setLamp(false);
  }

  delay(10);
}

Setup and Testing

  • Upload the sketch and open the Serial Monitor at 115200 baud. It prints the baseline and threshold values.
  • Tap the plate and check that the Serial Monitor shows Lamp ON and Lamp OFF, and that the blue LED follows.
  • Test the relay with a low-voltage load or listen for the click before connecting the real lamp.
  • If touches are missed, change 70 to 80 in the threshold line. If it triggers by itself, change it to 60.

Troubleshooting

ProblemFix
Lamp toggles on its ownShorten the touch wire, keep it away from the mains wires, and lower the threshold percentage.
Touch is not detectedMake sure the wire is on GPIO4, not another pin, and that you did not touch the plate during calibration.
Relay works the opposite wayChange RELAY_ACTIVE_LOW in the sketch.
Relay clicks but the lamp does not lightCheck that you used the COM and NO terminals, not NC.
Readings are always 0 or very lowThe plate may be touching a grounded metal case. Insulate it from other metal.

Safety Note

The lamp runs on 230 V mains. Keep the relay and all mains wiring inside a closed box, use a relay rated for the load, and get help from a qualified electrician. The touch plate is connected only to the low-voltage ESP32, never to the mains side.

Ideas to Extend

  • Use two more touch pins for brightness up and down with a MOSFET LED driver instead of a relay.
  • Add Wi-Fi and a web page so the lamp can also be switched from your phone.
  • Hide the touch plate under a thin wooden or plastic table top for an invisible switch.
  • Add an auto-off timer that turns the lamp off after 30 minutes.

1 thought on “ESP32 Capacitive Touch Lamp Switch with Relay”

Leave a Comment