ESP32 with INMP441 I2S Omnidirectional Microphone Module (Arduino IDE)

In this getting started guide, you’ll learn how to use the INMP441 I2S omnidirectional microphone with the ESP32 using Arduino IDE. We’ll cover how to wire the sensor to the board, and we’ll create three examples to show how the sensor works. We’ll measure the sound intensity (RMS), display the sound wave in the Serial Plotter, and build a clap on/clap off project where you can control an LED (relay, or any ESP32 output) with claps.

ESP32 with INMP441 I2S Omnidirectional Microphone Module Arduino IDE

Table of Contents

In this guide, we’ll cover the following topics:

Introducing the INMP441 Microphone Module

The INMP44 is an omnidirectional MEMS (Micro-Electro-Mechanical System) microphone. It captures sound and outputs 24-bit digital audio data through the I2S interface (a specific communication protocol used for audio transmission).

INMP441 Microphone I2S Module Pinout Top

It provides clear sound with low power consumption and a good signal-to-noise ratio. It is a much better choice compared with analog microphones because it already includes the conversion from audio to a filtered digital signal.

The pins should be soldered as shown in the pictures above and below. When attached to a breadboard, the microphone’s small hole should be facing you.

INMP441 Microphone I2S Module Sensor Back

Key features of the INMP441:

  • Omnidirectional: captures sound from all directions, so there is no need for precise positioning;
  • I2S output: outputs digital audio directly through the I2S interface;
  • Good signal quality and low noise;
  • Ideal for embedded projects: its small size, low power consumption, and digital interface make it a good choice for IoT projects, especially with the ESP32, which supports the I2S interface.

I2S Communication

The INMP441 uses I2S communication (Inter-IC Sound). It is a synchronous serial communication protocol used for transmitting audio data between two digital audio devices.

ESP32 INMP441 Microphone I2S Wiring Circuit

The ESP32 supports I2S via the I2S peripheral using the I2S driver, and it can be configured as an input to read audio data, or as an output to send audio data to play or transfer audio.

For more detailed technical information about I2S communication on the ESP32, check out the ESP-IDF official documentation: Inter-IC Sound (I2S).

INMP441 Pinout

The INMP441 microphone module communicates with the ESP32 using I2S protocol. It comes with the following pins:

  • L/R: selects left or right I2S channel (connected to GND selects left, connected to 3V3 selects right). You can select either one. Then, you just need to modify the code accordingly
  • WS: Word Select (also called LRCLK) – connect to an ESP32 GPIO
  • SCK: Serial Clock (also called BCLK) – connect to an ESP32 GPIO
  • SD: Serial Data, the actual microphone audio – connect to an ESP32 GPIO (input)
  • GND: connect to an ESP32 GND pin
  • VDD: power the module – use 3.3V on the ESP32

Where to buy?

You can check our Maker Advisor Tools Page to compare the INMP441 microphone module price in different stores.

Wiring the INMP441 to the ESP32

In this guide, we’re using an ESP32-S3, and we’ll use the following GPIOs. Adjust if you’re using a board with a different ESP32 chip.

INMP441ESP32-S3
L/RGND
WSGPIO 40
SCKGPIO 42
SDGPIO 41
GNDGND
VDD3V3
ESP32 S3 Wiring to INMP441 Microphone Module

There aren’t predefined I2S GPIOs. You can use any safe-to-use ESP32 GPIOs. Recommended reading:

Preparing Arduino IDE

Before proceeding, make sure you have the Arduino IDE installed and the ESP32 boards. Follow the next tutorial if you haven’t already:

1) INMP441with the ESP32: Sound Intensity (RMS)

In this example, we’ll use the INMP441 microphone with the ESP32 to measure the intensity of sound and display it in the Arduino IDE Serial Plotter.

The microphone is continuously capturing sound and sending audio samples to the ESP32 (via the I2S interface). We can then use these samples to calculate the RMS (Root Mean Square) value, which gives us an indication of the strength of the sound during a short period.

The RMS is calculated as follows:

  • Square each sample
  • Calculate the average of all the squared values
  • Take the square root of the result
RMS Value Formula

The louder the sound, the higher the RMS value.

Code – INMP441 Sound Intensity (RMS)

To get audio data via I2S, we’ll use the ESP-IDF driver/i2s.h in the Arduino IDE. It is included by default in the ESP32 Arduino core. You don’t need to install any external libraries.

Copy the following code to the Arduino IDE.

/*
  Rui Santos & Sara Santos - Random Nerd Tutorials
  Complete project details at https://RandomNerdTutorials.com/esp32-inmp441-i2s-microphone-arduino/
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.
  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*/
#include <driver/i2s.h>

// Pin configuration
#define I2S_SCK   42   // BCLK
#define I2S_WS    40   // LRCLK / WS
#define I2S_SD    41   // DOUT from mic

#define I2S_PORT  I2S_NUM_0
#define SAMPLE_RATE 16000
#define BUFFER_LEN  512

int32_t sBuffer[BUFFER_LEN];

void setup() {
  Serial.begin(115200);
  delay(1000);

  Serial.println("INMP441 Microphone");

  // I2S configuration
  i2s_config_t i2s_config = {
    .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_RX),
    .sample_rate = SAMPLE_RATE,
    .bits_per_sample = I2S_BITS_PER_SAMPLE_32BIT,
    .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT,   // L/R = GND
    .communication_format = I2S_COMM_FORMAT_STAND_I2S,
    .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1,
    .dma_buf_count = 8,
    .dma_buf_len = BUFFER_LEN,
    .use_apll = false
  };

  // Pin configuration
  i2s_pin_config_t pin_config = {
    .bck_io_num = I2S_SCK,
    .ws_io_num = I2S_WS,
    .data_out_num = I2S_PIN_NO_CHANGE,
    .data_in_num = I2S_SD
  };

  // Start I2S
  i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL);
  i2s_set_pin(I2S_PORT, &pin_config);
  i2s_zero_dma_buffer(I2S_PORT);

  Serial.println("I2S started.");
  Serial.println("Reading microphone...");
}

void loop() {
  size_t bytes_read = 0;

  // Read microphone data
  i2s_read(I2S_PORT, sBuffer, sizeof(sBuffer), &bytes_read, portMAX_DELAY);

  int samples_read = bytes_read / sizeof(int32_t);
  double sum = 0;

  // Print the samples
  for (int i = 0; i < samples_read; i++) {

    // INMP441 sends 24-bit audio left-aligned in a 32-bit I2S word
    int32_t sample = sBuffer[i] >> 8;
    //Serial.println(sample);
    sum += (double)sample * sample;
  }
    // Calculate RMS
    double rms = sqrt(sum / samples_read);

    // Print RMS
    //Serial.print("RMS: ");
    Serial.println(rms);
}

View raw code

How Does the Code Work?

Continue reading to learn how the code works, or skip to the demonstration section.

I2S Driver

First, we need to include the I2S driver.

#include <driver/i2s.h>

I2S Pins

Define the pins you’re using to connect to the microphone. Modify the following lines if you’re using different pins.

// Pin configuration
#define I2S_SCK   42    // BCLK
#define I2S_WS    40    //  LRCLK / WS
#define I2S_SD    41     //  DOUT from mic

I2S Port and Sample Rate

Select I2S peripheral 0 and define the sampling rate (how many audio samples are captured every second). We’re setting the sampling rate to 16000, which is a common sampling rate for voice and sound applications.

#define I2S_PORT  I2S_NUM_0
#define SAMPLE_RATE 16000

RMS Buffer Size

Then, we define the buffer size for how many audio samples we’ll use to calculate the RMS, and create the actual buffer (sBuffer).

#define BUFFER_LEN  512

int32_t sBuffer[BUFFER_LEN];

Note: the buffer is prepared to receive a 32-bit sample. I2S transfers data in fixed-size time slots. With the INMP441, using a 32-bit slot is the practical choice even though the microphone’s audio resolution is 24 bits. In other words, the INMP441 24 bits of data are placed inside a 32-bit I2S word. Then, we need to extract the bits that contain the data.

setup()

In the setup(), initialize the Serial Monitor at a baud rate of 115200.

void setup() {
  Serial.begin(115200);
  delay(1000);

  Serial.println("INMP441 Microphone");

Configure I2S – Configuration Structures

Then, we can configure the I2S peripheral. Start by creating a structure of type i2s_config_t called i2s_config with the configurations for I2S. Here, we assign the sampling rate, bits per sample, channel (left or right), and other configuration settings.

// I2S configuration
i2s_config_t i2s_config = {
  .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_RX),
  .sample_rate = SAMPLE_RATE,
  .bits_per_sample = I2S_BITS_PER_SAMPLE_32BIT,
  .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT,   // L/R = GND
  .communication_format = I2S_COMM_FORMAT_STAND_I2S,
  .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1,
  .dma_buf_count = 8,
  .dma_buf_len = BUFFER_LEN,
  .use_apll = false
};

You can check other possible configuration values in the ESP-IDF I2S documentation.

Then, create another structure (i2s_pin_config_t) to define the I2S pins we’re using.

// Pin configuration
i2s_pin_config_t pin_config = {
  .bck_io_num = I2S_SCK,
  .ws_io_num = I2S_WS,
  .data_out_num = I2S_PIN_NO_CHANGE,
  .data_in_num = I2S_SD
};

Finally, you can start I2S by calling the following functions with the configuration structures we created previously.

i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL);
i2s_set_pin(I2S_PORT, &pin_config);
i2s_zero_dma_buffer(I2S_PORT);

loop()

In the loop(), we’ll read the microphone data and calculate RMS.

We call the i2s_read() function that reads data from the INMP441 microphone and saves it in the sBuffer. After each successful read, the sBuffer variable will contain 512 audio samples

i2s_read(I2S_PORT, sBuffer, sizeof(sBuffer), &bytes_read, portMAX_DELAY);

Then, we convert bytes_read to samples_read by dividing the number of bytes received by the size of each sample. This tells us exactly how many samples are available in the buffer.

int samples_read = bytes_read / sizeof(int32_t);

The following lines square every sample and add the squared values together.

// Print the samples
for (int i = 0; i < samples_read; i++) {

  // INMP441 sends 24-bit audio left-aligned in a 32-bit I2S word
  int32_t sample = sBuffer[i] >> 8;
  //Serial.println(sample);
  sum += (double)sample * sample;
}

Then, calculate the RMS by dividing by the samples read and take the square root.

// Calculate RMS
double rms = sqrt(sum / samples_read);

Notice the following line of code. The 24-bit microphone data is positioned within that 32-bit value. The >> 8 shifts the value so we get the 24-bit sample shifted 8 bits to the right, aligning the audio data correctly before calculating RMS.

int32_t sample = sBuffer[i] >> 8;

Finally, we print the RMS value. We’re only printing this value to the Serial Monitor (without anything else) so we can use the Serial Plotter to better visualize the results.

Serial.println(rms);

Demonstration

Upload the code to your ESP32 board. Don’t forget to select the right board and COM port. I’m using an ESP32-S3 board.

After uploading the code, open the Serial Plotter. Its icon is right next to the Serial Monitor icon.

Arduino IDE, open the Serial Plotter

A new window will open, displaying the RMS value over time. Clap, speak, or make louder and quieter sounds and see the RMS value changing accordingly.

ESP32 with INMP441: get RMS on Serial Plotter

In this example, the peaks correspond to when I clapped and the second one to when I snapped my fingers.

Now you can check the RMS values for different sound intensities and use them to determine a threshold. Then, you can create a new project that triggers an action when the RMS value exceeds a certain threshold.

2) INMP441 with the ESP32: Visualize the Audio Waveform

In this example, we’ll read the audio data and display the waveform in the Arduino Serial Plotter. This is as easy as getting the I2S audio data and printing it to the Serial Monitor/Plotter.

Copy the following code to the Arduino IDE.

/*
  Rui Santos & Sara Santos - Random Nerd Tutorials
  Complete project details at https://RandomNerdTutorials.com/esp32-inmp441-i2s-microphone-arduino/
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.
  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*/
#include <driver/i2s.h>

// Pin configuration
#define I2S_SCK   42   // BCLK
#define I2S_WS    40   // LRCLK / WS
#define I2S_SD    41   // DOUT from mic

#define I2S_PORT  I2S_NUM_0
#define SAMPLE_RATE 16000
#define BUFFER_LEN  512

int32_t sBuffer[BUFFER_LEN];

void setup() {
  Serial.begin(115200);
  delay(1000);

  Serial.println("INMP441 Microphone");

  // I2S configuration
  i2s_config_t i2s_config = {
    .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_RX),
    .sample_rate = SAMPLE_RATE,
    .bits_per_sample = I2S_BITS_PER_SAMPLE_32BIT,
    .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT,   // L/R = GND
    .communication_format = I2S_COMM_FORMAT_STAND_I2S,
    .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1,
    .dma_buf_count = 8,
    .dma_buf_len = BUFFER_LEN,
    .use_apll = false
  };

  // Pin configuration
  i2s_pin_config_t pin_config = {
    .bck_io_num = I2S_SCK,
    .ws_io_num = I2S_WS,
    .data_out_num = I2S_PIN_NO_CHANGE,
    .data_in_num = I2S_SD
  };

  // Start I2S
  i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL);
  i2s_set_pin(I2S_PORT, &pin_config);
  i2s_zero_dma_buffer(I2S_PORT);

  Serial.println("I2S started.");
  Serial.println("Reading microphone...");
}

void loop() {
  size_t bytes_read = 0;

  // Read microphone data
  i2s_read(I2S_PORT, sBuffer, sizeof(sBuffer), &bytes_read, portMAX_DELAY);

  int samples_read = bytes_read / sizeof(int32_t);

  // Print the samples
  for (int i = 0; i < samples_read; i++) {

    // INMP441 sends 24-bit audio left-aligned in a 32-bit I2S word
    int32_t sample = sBuffer[i] >> 8;

    Serial.println(sample);
  }
}

View raw code

How Does the Code Work?

This code works exactly in the same way as the previous one, except that it doesn’t calculate the RMS. Everything else remains the same.

We go through each sample in the audio buffer and print the results. Each sample represents the amplitude of the audio signal at a specific moment.

// Print the samples
for (int i = 0; i < samples_read; i++) {

  // INMP441 sends 24-bit audio left-aligned in a 32-bit I2S word
  int32_t sample = sBuffer[i] >> 8;

  Serial.println(sample);
}

Demonstration

Upload the code to your ESP32 board. Don’t forget to select the right board and COM port. I’m using an ESP32-S3 board.

After uploading the code, open the Serial Plotter. Its icon is right next to the Serial Monitor icon.

Now, you can see the amplitude of the sound wave at a particular moment. You can test this by producing the sound of different vowels, like aaaaaa, eeeeee, iiiii, oooooo, uuuuu, and see how the sound wave changes.

ESP32 with INMP441 Sound Wave Serial Plotter

The different vowels produce different combinations of frequencies, changing the shape of the waveform.

The Serial Plotter might not be the best tool to actually see the waveform shape. You can create a Python code with matplotlib. You can adjust the scale to better see and export a capture of the waveform.

ESP32 with INMP441 Microphone Module - aeiou waveforms

Extra: Visualize the Waveform on Matplotlib (Quick instructions)

1) Install Python (make sure to check Add Python to PATH during installation)

2) Open the Terminal/Command Prompt and run to install the required libraries.

pip install pyserial matplotlib

3) Make sure the code is running on the ESP32. In the Arduino IDE, check the serial port (for example COM5). Close the Arduino IDE window.

4) Create a new Python program. You can use Notepad if you don’t have a Python editor, as long as you save the file with the .py extension.

5) Copy this code into that file (view INMP441-microphone.py file). Modify it with your COM port. Save the code on your Desktop, for example with the name INMP441-microphone.py.

6) In the Terminal window, run:

cd Desktop

And finally, run the Python code.

python INMP441-microphone.py

A Matplotlib window should then open and display the waveform.

ESP32 INMP441 Display waveform Matplotlib

3) Control ESP32 Output with Claps (Clap On/ Clap Off)

Taking into account what you’ve learned so far, it’s now easy to create a simple project where you can control the ESP32 outputs with claps. Here’s an overview of this project:

  • We’ll control one GPIO of the ESP32 with claps – to better visualize the results, we’ll control an LED. Alternatively, you can control a relay, for example, to control a lamp, or window blinds.
  • Clap twice to invert the current LED state.
ESP32 INMP441 Microphone I2S Clap Control Demonstration

When you clap, the amplitude of the sound wave increases, creating a peak. You can clearly see that it stands out from the ambient sound wave. If we detect two peaks above a certain defined threshold within a short period of time, we consider that we have a double clap, and we invert the LED state.

ESP32 with INMP441 double clap detection

Note: this project doesn’t actually detect a clap. It detects two consecutive peaks of the sound wave (above a certain threshold and within a predefined period). It also works with grasping fingers, knocks, etc.

Before proceeding, connect an LED to your ESP32 board. We’re controlling an LED connected to GPIO 38 (we’re using an ESP32-S3 DevkitC). Adjust to use another GPIO if you’re using a different board.

Parts required:

ESP32 with INMP441 Control GPIO with claps - wiring diagram

After wiring the circuit, copy the following code:

/*
  Rui Santos & Sara Santos - Random Nerd Tutorials
  Complete project details at https://RandomNerdTutorials.com/esp32-inmp441-i2s-microphone-arduino/
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.
  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*/
#include <driver/i2s.h>

// Pin configuration
#define I2S_SCK   42   // BCLK
#define I2S_WS    40   // LRCLK / WS
#define I2S_SD    41   // DOUT from mic

#define I2S_PORT  I2S_NUM_0
#define SAMPLE_RATE 16000
#define BUFFER_LEN  512

int32_t sBuffer[BUFFER_LEN];

// LED
#define LED_PIN 38

// Clap detection
#define CLAP_THRESHOLD 1000000

// Maximum time allowed between the first and second clap
const unsigned long CLAP_GAP = 700;

// Prevent the same clap from being detected multiple times
const unsigned long CLAP_COOLDOWN = 250;

// State variables
bool ledState = false;

int clapCount = 0;

unsigned long firstClapTime = 0;
unsigned long lastClapTime = 0;

void setup() {
  Serial.begin(115200);
  delay(1000);

  Serial.println("INMP441 Microphone");

  // LED setup
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, LOW);

  // I2S configuration
  i2s_config_t i2s_config = {
    .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_RX),
    .sample_rate = SAMPLE_RATE,
    .bits_per_sample = I2S_BITS_PER_SAMPLE_32BIT,
    .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT,   // L/R = GND
    .communication_format = I2S_COMM_FORMAT_STAND_I2S,
    .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1,
    .dma_buf_count = 8,
    .dma_buf_len = BUFFER_LEN,
    .use_apll = false
  };

  // Pin configuration
  i2s_pin_config_t pin_config = {
    .bck_io_num = I2S_SCK,
    .ws_io_num = I2S_WS,
    .data_out_num = I2S_PIN_NO_CHANGE,
    .data_in_num = I2S_SD
  };

  // Start I2S
  i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL);
  i2s_set_pin(I2S_PORT, &pin_config);
  i2s_zero_dma_buffer(I2S_PORT);

  Serial.println("I2S started.");
  Serial.println("Double clap to control LED");
}


void loop() {
  size_t bytes_read = 0;

  // Read microphone data
  i2s_read(I2S_PORT, sBuffer, sizeof(sBuffer), &bytes_read, portMAX_DELAY);

  int samples_read = bytes_read / sizeof(int32_t);

  // Find the loudest sample
  int32_t peak = 0;

  // Print the samples
  for (int i = 0; i < samples_read; i++) {
    int32_t sample = sBuffer[i] >> 8;
    int32_t magnitude = abs(sample);

    if (magnitude > peak) {
      peak = magnitude;
    }
  }

  // Print peak
  Serial.println(peak);

  // Detect a clap
  unsigned long now = millis();

  if (peak > CLAP_THRESHOLD && now - lastClapTime > CLAP_COOLDOWN) {
    lastClapTime = now;

    // First clap
    if (clapCount == 0) {
      clapCount = 1;
      firstClapTime = now;
      Serial.println("First clap detected");
    }

    // Second clap
    else if (now - firstClapTime <= CLAP_GAP) {
      clapCount = 0;

      // Double clap - invert LED state
      ledState = !ledState;
      digitalWrite(LED_PIN, ledState);
      if (ledState) {
        Serial.println("DOUBLE CLAP - LED ON");
      }
      else {
        Serial.println("DOUBLE CLAP - LED OFF");
      }
    }

    // Too much time passed
    else {

      // Treat this clap as the beginning of a new pair
      clapCount = 1;
      firstClapTime = now;
      Serial.println("New first clap");
    }
  }

  // Reset if second clap doesn't arrive in time
  if (clapCount == 1 && now - firstClapTime > CLAP_GAP) {
    clapCount = 0;
  }
}

View raw code

How Does the Code Work?

The initialization of I2S protocol and getting the sound wave works exactly like in the previous projects.

We’ll control GPIO 38. Adjust accordingly in the following line.

// LED
#define LED_PIN 38

We need to define a clap threshold. This is the amplitude above which we’ll consider we have a clap. It must stand out from the amplitude of the ambient sound. You may need to adjust this value for your scenario.

// Clap detection
#define CLAP_THRESHOLD 1000000

We’ll consider we have a double tap if we have two peaks above the threshold that happen with a maximum difference of 700 milliseconds.

const unsigned long CLAP_GAP = 700;

We’ll ignore peaks that occur after 250 milliseconds. This allows us to prevent the same clap from being detected multiple times.

const unsigned long CLAP_COOLDOWN = 250;

We’ll register the time of the first clap, and the time of the last clap. With this, we can determine if we have a double clap. We’ll save the time the claps occurred in the following variables (firstClapTime, lastClapTime). We’ll also register the clap number (first clap or second clap) in the clapCount variable.

int clapCount = 0;

unsigned long firstClapTime = 0;
unsigned long lastClapTime = 0;

In the loop(), we’re continuously getting audio data and saving it in the samples_read buffer variable.

// Read microphone data
i2s_read(I2S_PORT, sBuffer, sizeof(sBuffer), &bytes_read, portMAX_DELAY);

int samples_read = bytes_read / sizeof(int32_t);

In each buffer we get, we check the magnitude (amplitude of the sample) and get the sample peak.

// Find the loudest sample
int32_t peak = 0;

// Print the samples
for (int i = 0; i < samples_read; i++) {
  int32_t sample = sBuffer[i] >> 8;
  int32_t magnitude = abs(sample);

  if (magnitude > peak) {
    peak = magnitude;
  }
}

We save the time of that sample, and then we check the conditions for a double clap. The peak must be greater than the threshold value, and the time between the current and last peak must be above the clap cooldown.

// Detect a clap
unsigned long now = millis();

if (peak > CLAP_THRESHOLD && now - lastClapTime > CLAP_COOLDOWN) {

If those conditions are met, and if we still don’t have a first clap, we consider this one the first clap and save the time it occurred at the firstClapTime variable.

// First clap
if (clapCount == 0) {
  clapCount = 1;
  firstClapTime = now;
  Serial.println("First clap detected");
}

Then, if we detect a second clap (the interval between the first and second tap is smaller than the clap gap), we invert the LED state. We also reset the clapCount to 0 to start searching for new double claps.

// Second clap
else if (now - firstClapTime <= CLAP_GAP) {
  clapCount = 0;

  // Double clap: invert LED state
  ledState = !ledState;

  digitalWrite(LED_PIN, ledState);
  if (ledState) {
    Serial.println("DOUBLE CLAP - turn LED ON");
  }
  else {
    Serial.println("DOUBLE CLAP - turn LED OFF");
  }
}

If too much time has passed since the first clap (above the clap gap), we’ll now consider this second tap as the first one.

// Too much time passed
else {
  // Treat this clap as the beginning of a new pair
  clapCount = 1;
  firstClapTime = now;
  Serial.println("New first clap");
}

Finally, if we don’t have a second clap within the clap gap time, we reset the clapCount to 0 to start searching for new claps.

// Reset if second clap doesn't arrive in time
if (clapCount == 1 && now - firstClapTime > CLAP_GAP) {
  clapCount = 0;
}

Demonstration

Upload the code to the ESP32 board. Make sure you have the right board and COM port selected.

Now, clap twice. The LED should turn ON. Clap twice again and the LED should turn off. You can check the following quick video demonstration.


If the LED is continuously blinking, it means you need to increase the tap threshold in the CLAP_THRESHOLD variable.

#define CLAP_THRESHOLD 1000000

If the LED is not turning ON when you clap, it means you need to decrease the CLAP_THRESHOLD variable.

To choose a more appropriate value for the CLAP_THRESHOLD variable, uncomment the following line that will print the audio amplitude.

//Serial.println(peak);

Check the ambient sound values (when you’re not clapping). Check the values when you clap. The threshold value should be between those two (a little bit less than the peak of the sound wave when you clap).

Wrapping Up

In this guide, you learned how to interface the INMP441 microphone module with the ESP32 using the I2S communication protocol. You learned how to configure the I2S bus and get data via I2S.

With the INMP441, we’re continuously getting audio data and saving it to a buffer. Then, we can use the buffer data to visualize the audio waveform, or make calculations like the RMS.

In audio projects, you may also find it useful to interface an amplifier like the MAX98357 for audio output, also via I2S. We’ll create a tutorial about that module soon, so stay tuned.

We hope you’ve found this guide useful.

We have more ESP32 guides for sensors and modules that you may like:

Learn more about the ESP32 with our resources:



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Enjoyed this project? Stay updated by subscribing our newsletter!

Leave a Comment

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.