# main.ino

- Project: [esp32-inmp441-example](https://flashesp.com/explore/MgQhNtyqhiabjpIoApkd6.md) by Mikrobot.pl
- Board: ESP32 Dev Module
- Language: Arduino (C++)
- Web page: https://flashesp.com/explore/MgQhNtyqhiabjpIoApkd6/files/3HXb6OPxBoTTkFUshvqmK

```cpp
#include <WiFi.h>
#include <WebServer.h>
#include <DNSServer.h>
#include "driver/i2s.h"
#include <math.h>

// =======================
// INMP441 I2S PIN CONFIGURATION
// =======================
//
// INMP441 -> ESP32
//
// VDD      -> 3V3
// GND      -> GND
// SCK/BCLK -> GPIO 26
// WS/LRCL  -> GPIO 25
// SD/DOUT  -> GPIO 33
// L/R      -> GPIO 27
//
// L/R decides which stereo channel the microphone uses:
// L/R LOW  = LEFT channel
// L/R HIGH = RIGHT channel
//
// This code sets GPIO 27 either LOW or HIGH automatically.

#define I2S_WS   25
#define I2S_SCK  26
#define I2S_SD   33

#define MIC_LR_PIN 27

// true  = set L/R HIGH  -> RIGHT channel
// false = set L/R LOW   -> LEFT channel
#define MIC_CHANNEL_RIGHT true

#define I2S_PORT I2S_NUM_0

// =======================
// WIFI ACCESS POINT CONFIG
// =======================
const char* ap_ssid = "ESP32-INMP441"; // open AP, no password

IPAddress apIP(192, 168, 4, 1);
IPAddress netMsk(255, 255, 255, 0);

// =======================
// DNS / CAPTIVE PORTAL
// =======================
const byte DNS_PORT = 53;
DNSServer dnsServer;
WebServer server(80);

// =======================
// AUDIO VARIABLES
// =======================
float currentDbLeft = -100.0;
float currentDbRight = -100.0;

int currentLevelLeftPercent = 0;
int currentLevelRightPercent = 0;

// Raw RMS values, useful for debugging
double currentRmsLeft = 0;
double currentRmsRight = 0;

// =======================
// HELPER FUNCTIONS
// =======================
float rmsToDb(double rms) {
  if (rms < 1) {
    return -100.0;
  }

  // INMP441 gives 24-bit audio inside a 32-bit word.
  // 8388608.0 = 2^23, max value for signed 24-bit audio.
  return 20.0 * log10(rms / 8388608.0);
}

int dbToPercent(float db) {
  // Map -60 dBFS ... 0 dBFS to 0 ... 100%
  float mapped = (db + 60.0) * (100.0 / 60.0);

  if (mapped < 0) mapped = 0;
  if (mapped > 100) mapped = 100;

  return (int)mapped;
}

// =======================
// MICROPHONE CHANNEL SELECT
// =======================
void setupMicChannelPin() {
  pinMode(MIC_LR_PIN, OUTPUT);

  if (MIC_CHANNEL_RIGHT) {
    digitalWrite(MIC_LR_PIN, HIGH);
    Serial.println("MIC L/R pin set to HIGH -> RIGHT channel");
  } else {
    digitalWrite(MIC_LR_PIN, LOW);
    Serial.println("MIC L/R pin set to LOW -> LEFT channel");
  }
}

// =======================
// I2S SETUP
// =======================
void setupI2S() {
  i2s_config_t i2s_config = {
    .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_RX),
    .sample_rate = 16000,
    .bits_per_sample = I2S_BITS_PER_SAMPLE_32BIT,

    // Read both stereo channels.
    .channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT,

    .communication_format = (i2s_comm_format_t)(I2S_COMM_FORMAT_I2S | I2S_COMM_FORMAT_I2S_MSB),
    .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1,
    .dma_buf_count = 8,
    .dma_buf_len = 256,
    .use_apll = false,
    .tx_desc_auto_clear = false,
    .fixed_mclk = 0
  };

  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
  };

  esp_err_t err;

  err = i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL);
  if (err != ESP_OK) {
    Serial.print("i2s_driver_install failed. Error: ");
    Serial.println(err);
    return;
  }

  err = i2s_set_pin(I2S_PORT, &pin_config);
  if (err != ESP_OK) {
    Serial.print("i2s_set_pin failed. Error: ");
    Serial.println(err);
    return;
  }

  i2s_zero_dma_buffer(I2S_PORT);

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

// =======================
// AUDIO READING
// =======================
void updateAudioLevel() {
  const int samplesCount = 1024;
  int32_t samples[samplesCount];

  size_t bytesRead = 0;

  esp_err_t result = i2s_read(
    I2S_PORT,
    (void*)samples,
    sizeof(samples),
    &bytesRead,
    20 / portTICK_PERIOD_MS
  );

  if (result != ESP_OK || bytesRead == 0) {
    return;
  }

  int samplesRead = bytesRead / sizeof(int32_t);

  double sumLeft = 0;
  double sumRight = 0;

  int countLeft = 0;
  int countRight = 0;

  // With I2S_CHANNEL_FMT_RIGHT_LEFT, samples usually come alternately:
  // even index = RIGHT
  // odd index  = LEFT
  for (int i = 0; i < samplesRead; i++) {
    // INMP441 gives 24-bit audio in a 32-bit word.
    int32_t sample = samples[i] >> 8;

    if (i % 2 == 0) {
      sumRight += sample;
      countRight++;
    } else {
      sumLeft += sample;
      countLeft++;
    }
  }

  if (countLeft == 0 || countRight == 0) {
    return;
  }

  double meanLeft = sumLeft / countLeft;
  double meanRight = sumRight / countRight;

  double rmsLeftSum = 0;
  double rmsRightSum = 0;

  for (int i = 0; i < samplesRead; i++) {
    int32_t sample = samples[i] >> 8;

    if (i % 2 == 0) {
      double centeredRight = sample - meanRight;
      rmsRightSum += centeredRight * centeredRight;
    } else {
      double centeredLeft = sample - meanLeft;
      rmsLeftSum += centeredLeft * centeredLeft;
    }
  }

  currentRmsLeft = sqrt(rmsLeftSum / countLeft);
  currentRmsRight = sqrt(rmsRightSum / countRight);

  currentDbLeft = rmsToDb(currentRmsLeft);
  currentDbRight = rmsToDb(currentRmsRight);

  currentLevelLeftPercent = dbToPercent(currentDbLeft);
  currentLevelRightPercent = dbToPercent(currentDbRight);
}

// =======================
// HTML PAGE
// =======================
String htmlPage() {
  String html =
    "<!DOCTYPE html><html><head>"
    "<meta charset='UTF-8'>"
    "<meta name='viewport' content='width=device-width, initial-scale=1.0'>"
    "<title>ESP32 INMP441 Stereo Test</title>"
    "<style>"
    "body{font-family:sans-serif;margin:20px;background:#fafafa;}"
    ".card{max-width:560px;padding:20px;background:white;border-radius:12px;box-shadow:0 2px 10px #ccc;}"
    ".channel{margin:18px 0;padding:12px;background:#f1f1f1;border-radius:10px;}"
    ".label{font-size:20px;font-weight:bold;margin-bottom:8px;}"
    ".value{font-size:30px;font-weight:bold;margin:8px 0;}"
    ".barOuter{width:100%;height:28px;background:#ddd;border-radius:20px;overflow:hidden;}"
    ".barInner{height:100%;width:0%;background:#4CAF50;transition:width 0.15s;}"
    ".small{color:#555;font-size:14px;line-height:1.4;}"
    ".active{font-weight:bold;color:#0a7a0a;}"
    ".inactive{font-weight:bold;color:#999;}"
    "code{background:#eee;padding:2px 5px;border-radius:4px;}"
    "</style>"
    "</head><body>";

  html += "<div class='card'>";
  html += "<h2>ESP32 + INMP441</h2>";
  html += "<p>I2S stereo channel monitor: LEFT and RIGHT.</p>";

  html += "<div class='channel'>";
  html += "<div class='label'>LEFT channel <span id='leftStatus' class='inactive'></span></div>";
  html += "<div class='value'><span id='leftPercent'>0</span>%</div>";
  html += "<div class='barOuter'><div class='barInner' id='leftBar'></div></div>";
  html += "<p>dBFS: <b><span id='leftDb'>-100</span></b></p>";
  html += "<p>RMS: <b><span id='leftRms'>0</span></b></p>";
  html += "</div>";

  html += "<div class='channel'>";
  html += "<div class='label'>RIGHT channel <span id='rightStatus' class='inactive'></span></div>";
  html += "<div class='value'><span id='rightPercent'>0</span>%</div>";
  html += "<div class='barOuter'><div class='barInner' id='rightBar'></div></div>";
  html += "<p>dBFS: <b><span id='rightDb'>-100</span></b></p>";
  html += "<p>RMS: <b><span id='rightRms'>0</span></b></p>";
  html += "</div>";

  html += "<hr>";
  html += "<p class='small'>Wi-Fi network: <b>ESP32-INMP441</b></p>";
  html += "<p class='small'>Manual address: <code>http://192.168.4.1</code></p>";
  html += "<p class='small'><b>L/R LOW</b> = LEFT channel. <b>L/R HIGH</b> = RIGHT channel.</p>";
  html += "<p class='small'>In this sketch, the L/R pin is connected to ESP32 GPIO 27 and controlled by code.</p>";
  html += "<p class='small'>This is not a calibrated SPL measurement. It is only a relative digital audio level shown in dBFS.</p>";
  html += "</div>";

  html += "<script>";
  html += "async function update(){";
  html += "try{";
  html += "let r=await fetch('/level');";
  html += "let d=await r.json();";

  html += "document.getElementById('leftPercent').innerText=d.left_percent;";
  html += "document.getElementById('leftDb').innerText=d.left_db.toFixed(1);";
  html += "document.getElementById('leftRms').innerText=Math.round(d.left_rms);";
  html += "document.getElementById('leftBar').style.width=d.left_percent+'%';";

  html += "document.getElementById('rightPercent').innerText=d.right_percent;";
  html += "document.getElementById('rightDb').innerText=d.right_db.toFixed(1);";
  html += "document.getElementById('rightRms').innerText=Math.round(d.right_rms);";
  html += "document.getElementById('rightBar').style.width=d.right_percent+'%';";

  html += "let leftActive=d.left_percent>3;";
  html += "let rightActive=d.right_percent>3;";

  html += "document.getElementById('leftStatus').innerText=leftActive?'ACTIVE':'';";
  html += "document.getElementById('rightStatus').innerText=rightActive?'ACTIVE':'';";

  html += "document.getElementById('leftStatus').className=leftActive?'active':'inactive';";
  html += "document.getElementById('rightStatus').className=rightActive?'active':'inactive';";

  html += "}catch(e){}";
  html += "}";
  html += "setInterval(update,300);";
  html += "update();";
  html += "</script>";

  html += "</body></html>";

  return html;
}

// =======================
// CAPTIVE PORTAL REDIRECT
// =======================
void redirectToRoot() {
  String url = "http://" + apIP.toString() + "/";
  server.sendHeader("Location", url, true);
  server.send(302, "text/plain", "");
}

// =======================
// HTTP HANDLERS
// =======================
void handleRoot() {
  server.send(200, "text/html", htmlPage());
}

void handleLevel() {
  String json = "{";

  json += "\"left_db\":";
  json += String(currentDbLeft, 1);

  json += ",\"right_db\":";
  json += String(currentDbRight, 1);

  json += ",\"left_percent\":";
  json += String(currentLevelLeftPercent);

  json += ",\"right_percent\":";
  json += String(currentLevelRightPercent);

  json += ",\"left_rms\":";
  json += String(currentRmsLeft, 0);

  json += ",\"right_rms\":";
  json += String(currentRmsRight, 0);

  json += "}";

  server.send(200, "application/json", json);
}

void handleNotFound() {
  redirectToRoot();
}

// Captive portal triggers used by Android, iOS, Windows
void handleGenerate204() { handleRoot(); }          // Android
void handleHotspotDetect() { handleRoot(); }        // iOS/macOS
void handleNCsi() { handleRoot(); }                 // Windows

// =======================
// SETUP
// =======================
void setup() {
  Serial.begin(115200);
  delay(100);

  setupMicChannelPin();
  setupI2S();

  WiFi.mode(WIFI_AP);
  WiFi.softAPConfig(apIP, apIP, netMsk);
  WiFi.softAP(ap_ssid);

  Serial.println();
  Serial.print("AP started. SSID: ");
  Serial.println(ap_ssid);
  Serial.print("AP IP address: ");
  Serial.println(apIP);

  dnsServer.start(DNS_PORT, "*", apIP);

  server.on("/", handleRoot);
  server.on("/level", handleLevel);

  server.on("/generate_204", handleGenerate204);
  server.on("/hotspot-detect.html", handleHotspotDetect);
  server.on("/ncsi.txt", handleNCsi);

  server.onNotFound(handleNotFound);

  server.begin();

  Serial.println("Web server + DNS captive portal started.");
  Serial.println("Open WiFi network: ESP32-INMP441");
  Serial.println("Open page: http://192.168.4.1");
}

// =======================
// LOOP
// =======================
void loop() {
  dnsServer.processNextRequest();
  server.handleClient();

  static unsigned long lastAudioRead = 0;

  if (millis() - lastAudioRead > 50) {
    lastAudioRead = millis();

    updateAudioLevel();

    Serial.print("LEFT: ");
    Serial.print(currentLevelLeftPercent);
    Serial.print("%, ");
    Serial.print(currentDbLeft, 1);
    Serial.print(" dBFS, RMS: ");
    Serial.print(currentRmsLeft, 0);

    Serial.print(" | RIGHT: ");
    Serial.print(currentLevelRightPercent);
    Serial.print("%, ");
    Serial.print(currentDbRight, 1);
    Serial.print(" dBFS, RMS: ");
    Serial.println(currentRmsRight, 0);
  }
}
```
