Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

A clap switch is easiest to build as a low-voltage ESP32 project: a microphone detects a sharp sound, firmware confirms a two-clap pattern, and the board toggles an LED or isolated relay. A KY-038-style module does not recognize claps by itself; it only reports that sound crossed a threshold, so knocks, speech peaks and music can trigger it too. Build and test the LED version first, then use an enclosed, correctly rated switching device for any lamp.

How the project works

The signal path is:

Clap → microphone module → analog or digital signal → ESP32 filtering and timing → LED or isolated switch → lamp

Digital output is suitable for a quick demonstration. Analog sampling lets the ESP32 track room noise, detect short peaks and accept two claps within a chosen time window, reducing—but not eliminating—false triggers.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Parts and safety boundaries

Prototype parts

  • ESP32 development board
  • Electret microphone amplifier or sound-sensor module
  • LED and suitable current-limiting resistor
  • Jumper wires and breadboard for low-voltage wiring only
  • Optional relay module or logic-level solid-state relay
  • Separate suitable supply if the switching module needs more current than the ESP32 board can provide

For a permanent installation

Use an enclosure, fuse protection, strain relief, covered terminals and a switch rated for the lamp’s voltage, current and load type. Never put exposed mains terminals on a solderless breadboard. Fixed household wiring should be performed by a qualified person. A certified smart plug, smart relay or smart bulb is generally safer for daily use than an exposed hobby circuit.

#1 Best Overall
ESP-WROOM-32 ESP32 ESP-32S Development Board 2.4GHz Dual-Mode WiFi + Bluetooth Dual Cores Microcontroller Processor Integrated with Antenna RF AMP Filter AP STA Compatible with Arduino IDE (3PCS)
  • 2.4GHz Dual Mode WiFi + Bluetooth Development Board
  • Support LWIP protocol, Freertos
  • SupportThree Modes: AP, STA, and AP+STA
  • Ultra-Low power consumption, Compatible with Arduino IDE
  • ESP32 is a safe, reliable, and scalable to a variety of applications

Choose the sensor output

Approach What it does Trade-off
Digital output (DO) Comparator changes state when sound exceeds an adjustable threshold. Very simple, but any loud sound can trigger it and polarity varies by module.
Analog output (AO) Provides a fluctuating sound signal for software peak and timing detection. Needs calibration and threshold tuning, but supports a more selective two-clap command.

KY-038-style boards commonly expose VCC, GND, AO and DO. Their comparator behavior and supply requirements differ among clones; check the documentation for your exact board. See the module description at Faranux.

Pin selection for the ESP32

The example below assumes a classic ESP32 development board:

Rank #2
ELEGOO 3PCS ESP-32 Dev Boards, ESP-WROOM-32, USB-C, WiFi Bluetooth 4.2
  • Dual-Core Performance Up to 240 MHz: Run sensor processing, wireless communication, automation logic and connected-device tasks on a 32-bit dual-core ESP32 platform designed for responsive embedded and IoT projects
  • Built-in Wi-Fi and Bluetooth 4.2: Connect to 2.4 GHz Wi-Fi networks or use Bluetooth Classic and BLE for wireless sensors, smart devices, remote controls, home automation and other connected projects
  • Flexible Power-Saving Modes: ESP32 power-management features support dynamic clock scaling and low-power operating modes, helping developers reduce energy use in compatible sensing, monitoring and connected-device applications, suitable for battery-powered Internet of Things (IoT) devices.
  • USB-C Programming with CP2102: Connect through USB-C for power, sketch uploads and serial monitoring, while GPIO, UART, SPI and I2C interfaces support sensors, displays, motor drivers and other modules (USB-C cable not included)
  • Over-the-Air Update Support: Configure OTA functionality through a compatible ESP-32 software framework to update deployed firmware over Wi-Fi without reconnecting the board by USB for every revision
Function Example pin
Microphone AO GPIO32
LED or relay input GPIO26
Sensor ground GND
Sensor supply 3.3 V, only when the module permits it

GPIO32 is an ADC1 pin on the original ESP32. ADC1 is preferable if Wi-Fi may be enabled because the original chip’s ADC2 has Wi-Fi-related restrictions (Espressif ADC documentation). ESP32-C3, S2, S3 and other variants have different pinouts and capabilities. Verify the exact board before choosing GPIO numbers using the Arduino-ESP32 setup guide and your board’s pinout.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Do not connect a potentially 5 V sensor output to an ESP32 input. Use 3.3 V operation where specified, or add appropriate level shifting. Do not drive an unknown relay coil directly from a GPIO.

Rank #3
ELEGOO ESP-32 Super Starter Kit with Tutorial Compatible with Arduino IDE
  • Powerful ESP-32 Board: Unlock the world of Internet of Things (IoT) and advanced electronics with the heart of this kit: the ESP-32 board. It features a powerful dual-core processor, integrated Wi-Fi and Bluetooth 4.2, making it perfect for building connected, smart devices that communicate with your phone or the cloud. It's fully compatible with the Arduino IDE for easy programming.
  • Super Starter Kit: This kit contains over 35 different modules and electronic components, including sensors, displays, motors, and input devices. From LEDs and buttons to an OLED screen, servo motor, and keypad, you have everything needed to explore a vast range of projects in one box.
  • Step by Step Online Tutorial: Jump right in with our detailed, beginner-friendly tutorial. Access 30+ projects with complete code, clear circuit diagrams, and step-by-step instructions. Learn the fundamentals of electronics, coding, and how to utilize the ESP-32's unique capabilities without any prior experience.
  • Hands-on Learning for All Skill Levels: Perfect for students, makers, engineers, and hobbyists. Start with basic circuits and coding, then progress to intermediate and advanced IoT applications. Build practical projects like weather stations, smart home controllers, remote-controlled devices, and interactive gadgets. The skills you learn are the foundation for real-world innovation.
  • Quality & Great Support: Elegoo is committed to quality. We provide a clear, detailed tutorial guide, refined code, and a well-organized component kit. All modules are carefully selected for reliability and ease of use. Our dedicated technical support team and active online community are ready to help you succeed in your learning journey.

Wire and test the low-voltage version

  1. Connect the microphone module’s ground to ESP32 ground.
  2. Connect its AO pin to GPIO32, and its permitted supply to 3.3 V.
  3. Connect GPIO26 to an LED through a current-limiting resistor. Test this before attaching a relay.
  4. If using a relay module later, follow its voltage specification, driver requirements and input polarity. Some inputs are active-low and some modules need a separate coil supply.

Install the Arduino software

  1. Install Arduino IDE.
  2. Install the ESP32 board package and select the exact board and serial port.
  3. Upload the sketch below.
  4. Open Serial Monitor at 115200 baud.

The Arduino-ESP32 documentation currently identifies Core 3.3.10 with ESP-IDF 5.5; menu names and supported boards can change, so use the current official documentation at arduino-esp32 documentation.

Recommended firmware: analog two-clap toggle

This sketch uses a rolling baseline, a minimum peak separation, a 700 ms recognition window and a short lockout. The values are starting points, not universal clap standards. analogRead() returns a raw ADC conversion; readings depend on the chip, attenuation, microphone gain and installation. The ADC API is documented at Arduino-ESP32 ADC.

Rank #4
ESP-WROOM-32 ESP32 ESP-32S Development Board 2.4GHz Dual-Mode WiFi + Bluetooth Dual Cores Microcontroller Processor Integrated with Antenna RF AMP Filter AP STA Compatible with Arduino IDE (1 PCS)
  • 2.4GHz Dual Mode WiFi + Bluetooth Development Board
  • Support LWIP protocol, Freertos;ESP32 is a safe, reliable, and scalable to a variety of applications
  • SupportThree Modes: AP, STA, and AP+STA
  • Ultra-Low power consumption, Compatible with Arduino IDE
  • 1PCS 30Pin ESP32 Development Board 2.4GHz WiFi Dual Cores Microcontroller Integrated with Antenna RF Low Noise Amplifiers Filters
#include <Arduino.h>

const int MIC_PIN = 32;
const int OUTPUT_PIN = 26;
const bool OUTPUT_ACTIVE_HIGH = true;
const unsigned long SAMPLE_INTERVAL_US = 1000;
const unsigned long CLAP_MIN_GAP_MS = 80;
const unsigned long CLAP_MAX_GAP_MS = 700;
const unsigned long EVENT_LOCKOUT_MS = 180;
const int CALIBRATION_SAMPLES = 1500;
const float BASELINE_ALPHA = 0.01f;
const int MIN_PEAK_ABOVE_BASELINE = 180;

float baseline = 0;
unsigned long lastSampleUs = 0, lastPeakMs = 0, firstClapMs = 0, lockoutUntilMs = 0;
bool outputState = false;

void writeOutput(bool state) {
  outputState = state;
  bool level = OUTPUT_ACTIVE_HIGH ? state : !state;
  digitalWrite(OUTPUT_PIN, level ? HIGH : LOW);
}

void calibrateBaseline() {
  long total = 0;
  for (int i = 0; i < CALIBRATION_SAMPLES; i++) {
    total += analogRead(MIC_PIN);
    delayMicroseconds(1000);
  }
  baseline = (float)total / CALIBRATION_SAMPLES;
  Serial.print("Baseline: "); Serial.println(baseline);
}

void registerClap(unsigned long now) {
  if (now < lockoutUntilMs) return;
  if (firstClapMs == 0) {
    firstClapMs = now; lastPeakMs = now;
    Serial.println("First clap detected");
    return;
  }
  unsigned long gap = now - lastPeakMs;
  if (gap < CLAP_MIN_GAP_MS) return;
  if (gap <= CLAP_MAX_GAP_MS) {
    writeOutput(!outputState);
    Serial.println("Two-clap command accepted");
    firstClapMs = 0; lastPeakMs = 0; lockoutUntilMs = now + EVENT_LOCKOUT_MS;
    return;
  }
  firstClapMs = now; lastPeakMs = now;
  Serial.println("New clap window started");
}

void setup() {
  Serial.begin(115200);
  pinMode(OUTPUT_PIN, OUTPUT);
  writeOutput(false);
  analogReadResolution(12);
  delay(500);
  Serial.println("Calibrating. Keep the room quiet...");
  calibrateBaseline();
  lastSampleUs = micros();
}

void loop() {
  unsigned long nowMs = millis();
  if (firstClapMs != 0 && nowMs - firstClapMs > CLAP_MAX_GAP_MS) {
    firstClapMs = 0; lastPeakMs = 0;
  }
  unsigned long nowUs = micros();
  if ((unsigned long)(nowUs - lastSampleUs) < SAMPLE_INTERVAL_US) return;
  lastSampleUs = nowUs;
  int sample = analogRead(MIC_PIN);
  baseline += BASELINE_ALPHA * (sample - baseline);
  int deviation = abs(sample - (int)baseline);
  Serial.print("sample="); Serial.print(sample);
  Serial.print(" baseline="); Serial.print((int)baseline);
  Serial.print(" deviation="); Serial.println(deviation);
  if (deviation >= MIN_PEAK_ABOVE_BASELINE) {
    registerClap(nowMs);
    delay(20);
  }
}

Calibrate for your room

  1. Keep the room quiet during startup calibration.
  2. Watch the baseline and deviation values in Serial Monitor.
  3. Clap at the intended distance and note the peak deviation.
  4. Raise MIN_PEAK_ABOVE_BASELINE until speech and ordinary background noise stop triggering; lower it gradually if claps are missed.
  5. Recalibrate after moving the microphone, changing its enclosure or changing gain.
  6. Test speech, television, a door closing, a knock, music, applause, one clap and two claps at different distances.

Microphone gain, supply voltage, room acoustics, orientation and ADC behavior all affect the useful threshold. A 700 ms interval is a configurable design choice.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Simple digital-output demonstration

Use this only when you want the shortest possible test. Adjust the module’s potentiometer so ordinary room noise does not hold the output active.

Best Value
HiLetgo ESP-WROOM-32 ESP32 ESP-32S Development Board 2.4GHz Dual-Mode WiFi + Bluetooth Dual Cores Microcontroller Processor Integrated with Antenna RF AMP Filter AP STA for Arduino IDE
  • 2.4GHz Dual Mode WiFi + Bluetooth Development Board
  • Ultra-Low power consumption, works perfectly with the Arduino IDE
  • Support LWIP protocol, Freertos
  • SupportThree Modes: AP, STA, and AP+STA
  • ESP32 is a safe, reliable, and scalable to a variety of applications
#include <Arduino.h>
const int SOUND_PIN = 27;
const int OUTPUT_PIN = 26;
const bool SOUND_ACTIVE_HIGH = true;
const bool OUTPUT_ACTIVE_HIGH = true;
bool lightState = false;
unsigned long lastTrigger = 0;
const unsigned long DEBOUNCE_MS = 350;
void setLight(bool state) {
  lightState = state;
  bool level = OUTPUT_ACTIVE_HIGH ? state : !state;
  digitalWrite(OUTPUT_PIN, level ? HIGH : LOW);
}
void setup() {
  Serial.begin(115200);
  pinMode(SOUND_PIN, INPUT);
  pinMode(OUTPUT_PIN, OUTPUT);
  setLight(false);
}
void loop() {
  int raw = digitalRead(SOUND_PIN);
  bool detected = SOUND_ACTIVE_HIGH ? raw == HIGH : raw == LOW;
  unsigned long now = millis();
  if (detected && now - lastTrigger >= DEBOUNCE_MS) {
    setLight(!lightState);
    lastTrigger = now;
    Serial.println(lightState ? "Light ON" : "Light OFF");
  }
}

A permanently high or low input usually means wrong polarity, unsuitable supply voltage, excessive sensitivity or a wiring error.

Relay integration

  • Confirm whether the input is active-high or active-low and set OUTPUT_ACTIVE_HIGH accordingly.
  • Check whether the board expects 5 V logic, a 5 V coil or a separate supply.
  • Share a low-voltage ground only when the module’s design requires a common reference.
  • For a bare relay coil, use a transistor driver and flyback diode; do not use a GPIO as the coil driver.
  • Keep microphone wiring away from relay and switching wiring.

A mechanical relay can switch AC or DC only within its verified ratings and installation conditions. Solid-state relays are silent but have leakage and heat, and AC and DC versions are not interchangeable.

Troubleshooting by symptom

It triggers constantly

  • Raise the threshold, reduce microphone gain or move the sensor away from fans, televisions and the relay.
  • Use two-clap recognition and retain the lockout period.
  • Check for comparator pulses generated by one acoustic event.

Claps are missed

  • Lower the threshold and recalibrate at the actual operating distance.
  • Face the microphone toward the user and check that the enclosure is not muffling it.
  • Adjust CLAP_MAX_GAP_MS for the desired rhythm.

The relay does not switch

  • Check input polarity, GPIO availability, supply voltage and whether a driver is present.
  • Verify the coil has adequate current and that any required grounds are connected.

The ESP32 resets when the relay clicks

  • Use a properly rated separate relay supply, shorter wiring and adequate decoupling.
  • Look for supply sag, inductive noise and poor grounding.

Wi-Fi breaks analog readings

On the original ESP32, move the microphone to a suitable ADC1 pin rather than casually using ADC2. Other ESP32 families require their own pin and ADC checks.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When another control method is better

Option Best fit Limitation
Physical button Predictable local control and fallback operation Requires reaching the button.
PIR or mmWave sensor Automatic lighting based on presence Behavior depends on placement and motion.
Wi-Fi, MQTT or Home Assistant Remote control and status feedback Adds network configuration and security concerns.
Voice assistant Natural-language control May rely on a cloud service, ecosystem or privacy settings.
Certified smart plug, relay or bulb Everyday household reliability and enclosure Less educational than building the mains circuit yourself.

Local ESP32 processing avoids sending audio to a cloud service, but a clap switch still responds to unintended sounds and is not automatically energy-efficient. A physical override is worthwhile for accessibility and recovery.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.