Build Project

Home Automation

ESP32 Sound-Triggered Relay Demo

Build an ESP32 sound-triggered relay demo with an INMP441 I2S microphone, peak detection, and a low-voltage relay load. Not speech recognition.

IntermediateAges 13+90-120 minUnder 30 USDParent Safe
Illustrative sound relay scene; follow the supported STEMMA/INMP441 wiring diagram, not rendered hardware pin positions
Jump to a section

What You Will Build

An offline loud-sound detector that toggles the supported active-HIGH relay and a GPIO25 LED indicator. It compares INMP441 sample peaks with a configurable threshold; it does not recognize words. A quiet interval and cooldown separate triggers, but room echoes and noise can still affect detection.

Before You Start

Classic ESP32-WROOM-32/32E DevKit with the named GPIOs exposed and unused; Arduino IDE 2.x and esp32 by Espressif Systems 3.x. Other ESP32 families need their own pin map. Serial Monitor: 115200 baud.

The complete example supports the Adafruit STEMMA Non-Latching Mini Relay (product 4409), with red Vin, black GND and white Signal leads. It is active HIGH and accepts a 3.3 V signal. Use a regulated external 5 V supply rated at least 100 mA for this relay alone (about 50 mA energized per manufacturer). Do not substitute a latching relay or an unidentified active-LOW board. The generic page photo does not identify this supported model.

Use an INMP441 standard I2S breakout at 3.3 V, with its L/R pin tied to GND for the left slot. Confirm its labels and onboard decoupling; a PDM microphone is not a substitute. Use only a separate 3 V battery supply, one ordinary red LED and a 330 ohm series resistor as the contact-side load. No mains, motors, heaters or unattended operation are covered. The contact-side battery circuit needs no connection to ESP32 ground.

Verification: documentation/API and code-path review only; not compiled for ESP32 or tested on hardware in this update.

Parts

  • Classic ESP32-WROOM DevKit and USB data cableBoard pins must match the table.
  • INMP441 I2S microphone breakout3.3 V power; L/R to GND; not a PDM microphone.
  • Adafruit STEMMA Non-Latching Mini Relay 4409 and 3-pin JST-PH cableDocumented active-HIGH, 3.3 V signal input.
  • External regulated 5 V supplyAt least 100 mA for the relay alone; negative shares ESP32 ground; do not connect +5 V to USB-powered DevKit rail.
  • 10 kΩ resistorRelay Signal pull-down to GND.
  • Two ordinary red LEDs, 220 ohm and 330 ohm resistorsGPIO25 indicator uses 220 ohms; separate battery load uses 330 ohms.
  • Separate 3 V battery holder, breadboard and jumper wiresBattery powers only the switched LED load.

Wiring

This is a logical connection diagram, not physical pin placement. The microphone uses ESP32 3.3 V; the supported relay uses external 5 V. Both control grounds are shared. The LED contact load has its own 3 V battery.

Logical INMP441 sound relay circuit: GPIO14 SCK, GPIO15 WS, GPIO32 SD with 100 kiloohm pull-down, microphone at 3.3 V and L/R to GND; supported STEMMA relay Signal on GPIO26 with 10 kiloohm pull-down; external 5 V control power; GPIO25 LED and separate 3 V switched LED

Open wiring diagram full size

  1. 1

    Disconnect USB, the external relay supply and the load battery before wiring.

  2. 2

    Connect microphone VDD/VCC to 3.3 V, GND and L/R to ESP32 GND. Connect SCK/BCLK to GPIO14, WS/LRCLK to GPIO15 and SD/DOUT to GPIO32. Add a 100 kΩ SD-to-GND pull-down if the breakout does not already provide one, following the microphone datasheet.

  3. 3

    Connect GPIO25 through 220 ohms to the indicator LED anode; its cathode goes to ESP32 GND.

  4. 4

    Connect the supported relay red Vin lead to regulated external +5 V; connect its black GND lead to that supply negative and ESP32 GND. Do not join external +5 V to the USB-powered DevKit 5 V pin.

  5. 5

    Connect the relay white Signal lead to GPIO26. Add a 10 kΩ resistor between Signal and control-side GND to hold the command LOW while GPIO26 is not driven.

  6. 6

    Wire the separate 3 V battery positive to COM. Wire NO through a 330 ohm resistor to the red LED anode; LED cathode returns to battery negative. Leave NC unused.

  7. 7

    Initially leave the load battery disconnected. Upload the example, open Serial Monitor at 115200 baud and check the relay command and contact operation.

  8. 8

    Disconnect all supplies before adding the battery. Reconnect and confirm that the LED lights only when the relay is commanded ON.

Wiring Reference

SignalESP32 PinDirectionNotes
INMP441 SCK / WSGPIO14 / GPIO15OutputStandard I2S bit/frame clocks
INMP441 SDGPIO32InputLeft slot; 100 kΩ to GND if absent on breakout
INMP441 VDD; L/R3.3 V; GNDPower / selection3.3 V breakout; select left channel
STEMMA white SignalGPIO26OutputHIGH=ON; LOW=OFF; 10 kΩ to control GND
STEMMA red Vin / black GNDExternal +5 V / supply − and ESP32 GNDPowerExternal +5 V must not join USB power rail
Indicator LEDGPIO25 → 220 ohms → anode; cathode → GNDOutputHIGH lights indicator
Separate switched LED3 V battery + → COM → NO → 330 ohms → LED → battery −Contact circuitNC unused; independent of control supply

Libraries and Setup

  • esp32 by Espressif Systems 3.xESP_I2S.h is included in the core. API signatures reviewed against 3.0.7 and current official documentation; not a compilation or latest-release claim.
  • Arduino IDE setupChoose the exact WROOM board (or ESP32 Dev Module for a generic WROOM DevKit), select port and use Serial Monitor at 115200 baud. No third-party microphone library.

Configure the Example

CLAP_THRESHOLD=50000 and QUIET_THRESHOLD=15000 are starting values in shifted PCM counts, not measured noise levels or decibels. Record quiet-room peaks and deliberate sounds, then choose a trigger above normal noise and a lower quiet threshold. Keep 0 < QUIET_THRESHOLD < CLAP_THRESHOLD.

The example needs 200 ms below the quiet threshold to rearm and at least 750 ms between accepted triggers. These are software settings, not proof of one trigger per real clap. Keep the microphone away from the relay click. Startup discards 300 ms of microphone data before measuring.

Control and Recovery Behavior

ConditionResult
Reset / startupRelay and indicator commanded OFF; Signal pull-down holds LOW while GPIO is not driven.
Quiet for 200 msDetector can rearm; no toggle yet.
Armed peak above CLAP_THRESHOLD after cooldownToggle relay and indicator once; disarm until a new quiet interval.
Continuous loud inputRemain disarmed; do not repeatedly toggle from the same sustained sound.
I2S initialization failure or incomplete readLatch OFF with an error message; correct the cause and reset.
Silent or disconnected microphone that still returns complete readsZero samples are not a reliable fault diagnosis; do not use this demonstration for safety control.

Code

Install the libraries above and match the configuration and wiring before uploading.

esp32_sound_relay.ino
#include <Arduino.h>
#include <ESP_I2S.h>

I2SClass microphone;
constexpr uint8_t RELAY_PIN = 26;  // STEMMA 4409: active HIGH only
constexpr uint8_t LED_PIN = 25;
constexpr int32_t CLAP_THRESHOLD = 50000;
constexpr int32_t QUIET_THRESHOLD = 15000;
constexpr uint32_t QUIET_MS = 200;
constexpr uint32_t COOLDOWN_MS = 750;
static_assert(QUIET_THRESHOLD > 0 && QUIET_THRESHOLD < CLAP_THRESHOLD,
              "Quiet threshold must be positive and below trigger threshold");
bool relayOn = false;
bool audioReady = false;
bool armed = false;
uint32_t lastAboveQuiet = 0;
uint32_t lastTrigger = 0;
uint32_t lastReport = 0;
int32_t reportPeak = 0;

void setRelay(bool on) {
  relayOn = on;
  digitalWrite(RELAY_PIN, on ? HIGH : LOW);
  digitalWrite(LED_PIN, on ? HIGH : LOW);
}

void stopOnAudioError() {
  setRelay(false);
  audioReady = false;
  Serial.println("I2S error: relay OFF. Check wiring/settings, then reset.");
}

void setup() {
  pinMode(RELAY_PIN, OUTPUT);
  pinMode(LED_PIN, OUTPUT);
  setRelay(false);
  Serial.begin(115200);
  microphone.setPins(14, 15, -1, 32); // BCLK, WS, no TX data, RX data
  microphone.setTimeout(100);
  if (!microphone.begin(I2S_MODE_STD, 16000, I2S_DATA_BIT_WIDTH_32BIT,
                        I2S_SLOT_MODE_MONO, I2S_STD_SLOT_LEFT)) {
    stopOnAudioError();
    return;
  }
  // Drain startup data while the INMP441 settles; keep the output OFF.
  int32_t discard[256];
  const uint32_t started = millis();
  while (millis() - started < 300) {
    if (microphone.readBytes(reinterpret_cast<char *>(discard), sizeof(discard))
        != sizeof(discard)) {
      stopOnAudioError();
      return;
    }
  }
  lastAboveQuiet = lastTrigger = lastReport = millis();
  audioReady = true;
  Serial.println("Ready: wait for quiet, then make a loud sound. Relay OFF.");
}

void loop() {
  if (!audioReady) {
    delay(100);
    return; // Error remains latched; reset after correcting the cause.
  }
  int32_t samples[256];
  const size_t count = microphone.readBytes(
      reinterpret_cast<char *>(samples), sizeof(samples));
  if (count != sizeof(samples)) {
    stopOnAudioError();
    return;
  }
  int32_t peak = 0;
  for (size_t i = 0; i < 256; ++i) {
    // 24-bit signed I2S audio is in the high bits of a 32-bit slot.
    const int32_t value = samples[i] / 256;
    const int32_t magnitude = value < 0 ? -value : value;
    if (magnitude > peak) peak = magnitude;
  }
  const uint32_t now = millis();
  if (peak >= QUIET_THRESHOLD) lastAboveQuiet = now;
  else if (now - lastAboveQuiet >= QUIET_MS) armed = true;

  if (armed && peak > CLAP_THRESHOLD && now - lastTrigger >= COOLDOWN_MS) {
    setRelay(!relayOn);
    armed = false;
    lastTrigger = now;
    Serial.printf("Relay: %s\n", relayOn ? "ON" : "OFF");
  }
  if (peak > reportPeak) reportPeak = peak;
  if (now - lastReport >= 100) {
    Serial.printf("Peak: %ld\n", static_cast<long>(reportPeak));
    reportPeak = 0;
    lastReport = now;
  }
}

How the Code Works

The modern ESP_I2S API receives left-slot, 32-bit standard-I2S frames at 16 kHz. INMP441 audio is 24-bit signed data; division by 256 produces a bounded value for peak comparison without overflowing when taking its magnitude. The sketch continuously drains samples, prints the largest peak seen in each reporting interval, and rearms only after quiet.

setRelay() gives the documented active-HIGH relay and GPIO25 indicator the same command. Initialization/read errors latch both OFF; full-length zero readings cannot prove the microphone is healthy. Hardware contact state is not sensed by the program.

Expected Output

Serial Monitor at 115200 baud first says the relay is OFF, then reports Peak values approximately every 100 ms. After a quiet interval, an accepted loud sound prints Relay: ON and lights the GPIO25 indicator; the separate battery LED should also light through COM/NO. A later accepted sound prints Relay: OFF and both LEDs go dark. Actual peaks and detection reliability depend on the room and hardware; no acoustic measurements are claimed.

Troubleshooting

  • ESP_I2S.h not found Install/select esp32 by Espressif Systems 3.x. Do not mix this sketch with the legacy driver/i2s.h example.
  • I2S error and relay stays OFF Check supported board/core, VDD/GND, clock/data pins and breakout identity. Correct the issue, then reset; the error deliberately remains latched.
  • Peaks remain zero or very small Check 3.3 V power, L/R=GND, GPIO32 data and SD pull-down. Confirm this is an INMP441 standard-I2S breakout. Complete zero-valued reads alone cannot diagnose a failed microphone.
  • Unwanted or missed triggers Record your own quiet and deliberate-sound peaks; adjust both thresholds. Move microphone away from relay clicks and echoes. If the room never becomes quiet enough, it will not rearm.
  • Indicator toggles but relay or load does not Disconnect load power. Verify STEMMA 4409, external 5 V and shared control ground, then trace the separate battery COM/NO LED circuit. Do not substitute an unknown active-LOW module.
  • ESP32 resets when switching Check the relay external supply and ground connections. Keep +5 V separate from the USB-powered board rail and keep microphone wiring short.

Checks to Perform on Your Build

  • With the battery load disconnected, confirm an OFF command at startup.
  • Observe your own quiet-room and loud-sound peak ranges before choosing thresholds.
  • Confirm that continuous sound does not repeatedly toggle; allow a quiet interval between events.
  • Disconnect all power before attaching the specified low-voltage LED load; compare its state with Serial and the GPIO25 indicator.
  • These are reader checks to perform, not hardware tests reported as completed.

Practical Design Notes

Sound peaks do not identify words or reliably distinguish claps from dropped objects or relay clicks. Thresholds, quiet rearming and cooldown improve this demonstration but do not guarantee recognition. The relay contact state is not fed back; OFF is a software command, not proof of isolation or a fail-safe state.

Upgrade Ideas

  • Add a physical override button and explicit default-OFF behavior.
  • Add an OLED showing relay command and peak level.
  • Experiment with a two-event timing pattern after understanding false triggers.
  • Use a dedicated speech-recognition implementation before describing a project as responding to spoken commands.

FAQs

Is this speech recognition?

No. It compares loud-sound peaks with thresholds and cannot identify words.

Can I use a generic active-LOW relay board?

Not unchanged. This complete example is for STEMMA 4409. Verify a different module schematic, thresholds, supply and OFF state before designing an interface.

Does OFF guarantee that a load is safe?

No. The program commands OFF but cannot sense a welded contact, a failed driver or microphone health. Use only the stated battery LED demonstration.

Review, Testing, and References

Author: Abdul Mubeen and the ESP32 Engine editorial team. Last updated: 2026-10-08. Reviewed: wiring logic, Arduino code structure, beginner safety, and learning sequence.

Educational level: Intermediate. Estimated completion time: 90-120 min. This project is for learning and prototyping; production or unattended hardware needs additional engineering review.