// ESP32-S3 microphone streamer for Waveshare ESP32-S3-Touch-AMOLED-1.8 // // Captures the onboard analog mic through the ES8311 ADC at 16 kHz / 16-bit, // and streams raw PCM over UDP to scripts/mic_recv.py on the LAN. // // Audio path (from the Waveshare BSP): // mic -> ES8311 ADC (I2C 0x18) -> I2S0 RX (DSIN=10, SCLK=9, LCLK=45, MCLK=16) // I2C bus: SDA=15, SCL=14. Speaker PA enable = GPIO46. // // Packet: "MIC1" + uint32 seq + N mono int16 samples (20 ms = 320 samples). #include #include #include #include #include #include #include #include #include #include "secrets.h" #include "display.h" #include "imu.h" #include "battery.h" #include "render_schedule.h" #include #include #define PIN_I2C_SCL 14 #define PIN_I2C_SDA 15 #define PIN_I2S_MCLK 16 #define PIN_I2S_SCLK 9 #define PIN_I2S_LCLK 45 #define PIN_I2S_DOUT 8 #define PIN_I2S_DSIN 10 #define PIN_PA 46 static const uint32_t SAMPLE_RATE = 16000; static const int FRAME_SAMPLES = 320; // 20 ms static const int CHANNELS = 2; // ES8311 drives stereo slots static const uint16_t UDP_PORT = PEER_PORT + 6; // 5007 // Speech gating: adaptive noise floor + hysteresis, with pre-roll so onsets // are not clipped. Idle frames are not transmitted at all. static const int PREROLL_FRAMES = 10; // 200 ms of history static const int HANGOVER_FRAMES = 25; // 500 ms after speech stops static const float TRIGGER_RATIO = 4.0f; // +12 dB over the noise floor static const float NOISE_EMA = 0.005f; // slow floor tracking // ES8311 PGA. At +24 dB the mic sat ~-50 dBFS with the speaker at desk // distance, which is fine near-field but thin across a room. Raised to the // +30 dB maximum for far-field use: claps at close range will clip again, and // that is the intended trade. static const float MIC_PGA_DB = 30.0f; // +30 dB of analog PGA alone was not enough at room distance - transcripts // degraded ("Telemica the Ozzo") - so the rest of the gain is applied per frame // in software. Fast to duck, slow to boost, so it does not pump on speech. static const float AGC_TARGET_RMS = 2500.0f; // ~-22 dBFS static const float AGC_MAX_GAIN = 32.0f; static const float AGC_MIN_RMS = 6.0f; // below this it is silence static float s_agc = 1.0f; static i2c_master_bus_handle_t s_bus; static i2s_chan_handle_t s_tx, s_rx; static esp_codec_dev_handle_t s_mic; static WebSocketsClient s_ws; static uint32_t s_rx_dropped_bytes = 0; static bool IRAM_ATTR rx_overflow(i2s_chan_handle_t, i2s_event_data_t *event, void *) { __atomic_fetch_add(&s_rx_dropped_bytes, static_cast(event->size), __ATOMIC_RELAXED); return false; } // Extract capitalised tokens that are not the first word of a sentence. // Runs entirely on-device: no model, no heap, a few hundred microseconds. // Whisper preserves case for names it recognises, so this is a serviceable // proper-noun filter for display purposes. static void extract_proper_nouns(const char *text, char *out, size_t outsz) { static const char *kStop[] = { "I", "I'm", "I'll", "I've", "I'd", "Okay", "Ok", "Oh", "Ah", "And", "But", "So", "The", "A", "An", "Yeah", "Yes", "No", "Well", "Then", "If", "It", "That", "This", "We", "You", "They", "He", "She", "What", "When", "Where", "Who", "Why", "How", "Let", "Please", "Hey", "Hi", "Hello", "Thanks", "Thank", "Sorry", "Just", "Now", "There", "Here", }; out[0] = 0; size_t used = 0; bool sentence_start = true; for (const char *p = text; *p;) { while (*p == ' ') p++; if (!*p) break; const char *w = p; while (*p && *p != ' ') p++; size_t len = (size_t)(p - w); bool end = false; while (len > 0 && (w[len - 1] == '.' || w[len - 1] == ',' || w[len - 1] == '!' || w[len - 1] == '?' || w[len - 1] == '\'' || w[len - 1] == '"')) { if (w[len - 1] == '.' || w[len - 1] == '!' || w[len - 1] == '?') end = true; len--; } bool cap = len >= 2 && w[0] >= 'A' && w[0] <= 'Z'; if (cap && !sentence_start) { char tok[40]; size_t n = len < sizeof(tok) - 1 ? len : sizeof(tok) - 1; memcpy(tok, w, n); tok[n] = 0; bool stop = false; for (size_t i = 0; i < sizeof(kStop) / sizeof(kStop[0]); i++) if (strcasecmp(tok, kStop[i]) == 0) { stop = true; break; } bool dup = false; for (size_t i = 0; i + n <= used && !dup; i++) if (strncasecmp(out + i, tok, n) == 0 && (out[i + n] == 0 || out[i + n] == ' ')) dup = true; if (!stop && !dup && used + n + 2 < outsz) { if (used) out[used++] = ' '; memcpy(out + used, tok, n); used += n; out[used] = 0; } } sentence_start = end; } } static void json_str(const char *buf, const char *key, char *out, size_t outsz) { out[0] = 0; char pat[32]; snprintf(pat, sizeof(pat), "\"%s\"", key); const char *p = strstr(buf, pat); if (!p) return; p = strchr(p + strlen(pat), ':'); if (!p) return; p++; while (*p == ' ') p++; if (*p != '"') return; p++; size_t i = 0; while (*p && *p != '"' && i < outsz - 1) out[i++] = *p++; out[i] = 0; } // Reads a JSON string array into `items`. Returns the element count, or -1 if // the key is absent entirely (so an explicitly empty array is distinguishable // from "server said nothing" and does not trigger the local fallback). static int json_str_array(const char *buf, const char *key, char items[][40], int max) { char pat[32]; snprintf(pat, sizeof(pat), "\"%s\"", key); const char *p = strstr(buf, pat); if (!p) return -1; p = strchr(p + strlen(pat), '['); if (!p) return -1; p++; int n = 0; while (*p && *p != ']' && n < max) { if (*p == '"') { p++; const char *start = p; while (*p && *p != '"') p++; size_t len = (size_t)(p - start); if (len) { if (len > 39) len = 39; memcpy(items[n], start, len); items[n][len] = 0; n++; } if (*p) p++; } else { p++; } } return n; } static void ws_event(WStype_t type, uint8_t *payload, size_t len) { if (type == WStype_CONNECTED) { Serial.println("WS connected"); return; } if (type == WStype_DISCONNECTED) { Serial.println("WS disconnected"); return; } if (type == WStype_PONG) { Serial.println("WS heartbeat pong"); return; } if (type != WStype_TEXT) return; static char buf[768]; size_t n = len < sizeof(buf) - 1 ? len : sizeof(buf) - 1; memcpy(buf, payload, n); buf[n] = 0; static char txt[160], pn[96]; json_str(buf, "text", txt, sizeof(txt)); if (!txt[0]) return; // Prefer the server's NER, one line per entity. An explicitly empty array // means "no entities", which must not fall back to the local heuristic - // that is how "New Year" kept reappearing after being filtered server-side. static char items[8][40]; int cnt = json_str_array(buf, "proper_nouns", items, 8); if (cnt > 0) { // push in reverse so the first entity ends up on top for (int i = cnt - 1; i >= 0; i--) display_set_utterance(txt, items[i]); } else if (cnt < 0) { extract_proper_nouns(txt, pn, sizeof(pn)); display_set_utterance(txt, pn); } display_set_processing(false); // transcript arrived: end the end-of-utterance cue Serial.printf("WS_UTT text=%s | n=%d first=%s\n", txt, cnt, cnt > 0 ? items[0] : "-"); } static bool init_i2c() { i2c_master_bus_config_t bus_cfg = {}; bus_cfg.i2c_port = I2C_NUM_0; bus_cfg.sda_io_num = (gpio_num_t)PIN_I2C_SDA; bus_cfg.scl_io_num = (gpio_num_t)PIN_I2C_SCL; bus_cfg.clk_source = I2C_CLK_SRC_DEFAULT; bus_cfg.glitch_ignore_cnt = 7; bus_cfg.flags.enable_internal_pullup = true; if (i2c_new_master_bus(&bus_cfg, &s_bus) != ESP_OK) { Serial.println("ERR i2c_new_master_bus"); return false; } return true; } // The 1.8in AMOLED has no free GPIO for panel/touch reset - those lines hang off // the TCA9554 expander, which is why the Waveshare BSP declares BSP_LCD_RST as // NC. Pulse every output low then release, before touching the codec or panel. static bool expander_release() { i2c_device_config_t dev = {}; dev.dev_addr_length = I2C_ADDR_BIT_LEN_7; dev.device_address = 0x20; dev.scl_speed_hz = 100000; i2c_master_dev_handle_t h = nullptr; if (i2c_master_bus_add_device(s_bus, &dev, &h) != ESP_OK) { Serial.println("ERR expander add_device"); return false; } auto wr = [&](uint8_t reg, uint8_t val) { uint8_t buf[2] = {reg, val}; return i2c_master_transmit(h, buf, 2, 100) == ESP_OK; }; bool ok = wr(0x03, 0x00); // all pins outputs ok = wr(0x01, 0x00) && ok; // assert resets delay(30); ok = wr(0x01, 0xFF) && ok; // release delay(60); Serial.printf("EXPANDER ok=%d\n", ok); i2c_master_bus_rm_device(h); return ok; } static bool init_codec() { // This appliance never plays audio. Keep the active-high speaker PA shut // down even across codec reinitialization; ADC mode does not own its GPIO. pinMode(PIN_PA, OUTPUT); digitalWrite(PIN_PA, LOW); if (!s_bus) { Serial.println("ERR i2c bus missing"); return false; } // ---- I2S duplex (both channels so MCLK/BCLK are generated) i2s_chan_config_t chan_cfg = I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_0, I2S_ROLE_MASTER); chan_cfg.auto_clear = true; // 320 ms of DMA headroom for full-screen flushes and short network stalls. // The default ~90 ms ring overflows while the display is being updated. chan_cfg.dma_desc_num = 16; chan_cfg.dma_frame_num = FRAME_SAMPLES; if (i2s_new_channel(&chan_cfg, &s_tx, &s_rx) != ESP_OK) { Serial.println("ERR i2s_new_channel"); return false; } i2s_std_config_t std_cfg = {}; std_cfg.clk_cfg = I2S_STD_CLK_DEFAULT_CONFIG(SAMPLE_RATE); std_cfg.clk_cfg.mclk_multiple = I2S_MCLK_MULTIPLE_256; std_cfg.slot_cfg = I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_16BIT, I2S_SLOT_MODE_STEREO); std_cfg.gpio_cfg.mclk = (gpio_num_t)PIN_I2S_MCLK; std_cfg.gpio_cfg.bclk = (gpio_num_t)PIN_I2S_SCLK; std_cfg.gpio_cfg.ws = (gpio_num_t)PIN_I2S_LCLK; std_cfg.gpio_cfg.dout = (gpio_num_t)PIN_I2S_DOUT; std_cfg.gpio_cfg.din = (gpio_num_t)PIN_I2S_DSIN; if (i2s_channel_init_std_mode(s_tx, &std_cfg) != ESP_OK || i2s_channel_init_std_mode(s_rx, &std_cfg) != ESP_OK) { Serial.println("ERR i2s_channel_init_std_mode"); return false; } i2s_event_callbacks_t callbacks = {}; callbacks.on_recv_q_ovf = rx_overflow; if (i2s_channel_register_event_callback(s_rx, &callbacks, nullptr) != ESP_OK) { Serial.println("ERR I2S overflow callback"); return false; } i2s_channel_enable(s_tx); i2s_channel_enable(s_rx); // ---- codec plumbing audio_codec_i2s_cfg_t i2s_if_cfg = {}; i2s_if_cfg.port = I2S_NUM_0; i2s_if_cfg.tx_handle = s_tx; i2s_if_cfg.rx_handle = s_rx; const audio_codec_data_if_t *data_if = audio_codec_new_i2s_data(&i2s_if_cfg); if (!data_if) { Serial.println("ERR audio_codec_new_i2s_data"); return false; } audio_codec_i2c_cfg_t i2c_if_cfg = {}; i2c_if_cfg.port = I2C_NUM_0; i2c_if_cfg.addr = ES8311_CODEC_DEFAULT_ADDR; // 0x30 (8-bit form) i2c_if_cfg.bus_handle = s_bus; const audio_codec_ctrl_if_t *ctrl_if = audio_codec_new_i2c_ctrl(&i2c_if_cfg); if (!ctrl_if) { Serial.println("ERR audio_codec_new_i2c_ctrl"); return false; } const audio_codec_gpio_if_t *gpio_if = audio_codec_new_gpio(); if (!gpio_if) { Serial.println("ERR audio_codec_new_gpio"); return false; } es8311_codec_cfg_t es_cfg = {}; es_cfg.ctrl_if = ctrl_if; es_cfg.gpio_if = gpio_if; es_cfg.codec_mode = ESP_CODEC_DEV_WORK_MODE_ADC; es_cfg.pa_pin = -1; // no playback; the physical PA stays explicitly off es_cfg.pa_reverted = false; es_cfg.master_mode = false; // ESP32 is I2S master, codec is slave es_cfg.use_mclk = true; es_cfg.digital_mic = false; // analog mic into the ADC es_cfg.hw_gain.pa_voltage = 5.0; es_cfg.hw_gain.codec_dac_voltage = 3.3; const audio_codec_if_t *codec_if = es8311_codec_new(&es_cfg); if (!codec_if) { Serial.println("ERR es8311_codec_new"); return false; } esp_codec_dev_cfg_t dev_cfg = {}; dev_cfg.dev_type = ESP_CODEC_DEV_TYPE_IN; dev_cfg.codec_if = codec_if; dev_cfg.data_if = data_if; s_mic = esp_codec_dev_new(&dev_cfg); if (!s_mic) { Serial.println("ERR esp_codec_dev_new"); return false; } esp_codec_dev_sample_info_t fs = {}; fs.bits_per_sample = 16; fs.channel = CHANNELS; fs.sample_rate = SAMPLE_RATE; fs.mclk_multiple = 256; int ret = esp_codec_dev_open(s_mic, &fs); Serial.printf("CODEC open ret=%d\n", ret); if (ret != ESP_CODEC_DEV_OK) return false; Serial.printf("POWER codec=ADC speaker_pa_gpio=%d\n", digitalRead(PIN_PA)); // Analog PGA; see MIC_PGA_DB for the measurement behind this value. esp_codec_dev_set_in_gain(s_mic, MIC_PGA_DB); Serial.printf("CODEC pga_db=%.0f\n", MIC_PGA_DB); return true; } void setup() { Serial.begin(115200); delay(2500); Serial.println(); Serial.println("=== ESP32-S3 mic streamer ==="); WiFi.mode(WIFI_STA); WiFi.begin(WIFI_SSID, WIFI_PASS); int tries = 0; while (WiFi.status() != WL_CONNECTED && tries++ < 40) delay(500); if (WiFi.status() != WL_CONNECTED) { Serial.println("ERR wifi connect"); return; } const bool modem_sleep = WiFi.setSleep(WIFI_PS_MIN_MODEM) && WiFi.getSleep() == WIFI_PS_MIN_MODEM; Serial.printf("POWER wifi_sleep=MIN_MODEM ok=%d\n", modem_sleep); WiFi.setTxPower(WIFI_POWER_19_5dBm); Serial.printf("WIFI ip=%s rssi=%d ch=%d\n", WiFi.localIP().toString().c_str(), WiFi.RSSI(), WiFi.channel()); if (!init_i2c()) { Serial.println("=== I2C_FAILED ==="); return; } expander_release(); if (!init_codec()) { Serial.println("=== CODEC_FAILED ==="); return; } imu_init(s_bus); // optional: a missing IMU must not stop audio capture battery_init(s_bus); // read-only; missing PMU data must not stop capture bool ui = display_init(); Serial.printf("DISPLAY ok=%d\n", ui); s_ws.beginSSL(ASR_HOST, 443, "/?token=" ASR_TOKEN); s_ws.onEvent(ws_event); s_ws.setReconnectInterval(5000); // Detect a stale link even when idle, including with modem sleep enabled. s_ws.enableHeartbeat(15000, 3000, 2); Serial.printf("WS connecting to wss://%s\n", ASR_HOST); WiFiUDP udp; (void)udp; const int in_bytes = FRAME_SAMPLES * CHANNELS * sizeof(int16_t); const int out_bytes = FRAME_SAMPLES * sizeof(int16_t); int16_t *inbuf = (int16_t *)heap_caps_malloc(in_bytes, MALLOC_CAP_INTERNAL); int16_t *frame = (int16_t *)heap_caps_malloc(out_bytes, MALLOC_CAP_INTERNAL); if (!inbuf || !frame) { Serial.println("=== ALLOC_FAILED ==="); return; } // pre-roll ring: the last PREROLL_FRAMES captured frames, always current int16_t *pre = (int16_t *)heap_caps_malloc(PREROLL_FRAMES * out_bytes, MALLOC_CAP_INTERNAL); if (!pre) { Serial.println("=== ALLOC_FAILED ==="); return; } uint8_t pkt[12 + FRAME_SAMPLES * 2]; memcpy(pkt, "MIC3", 4); uint32_t seq = 0; uint32_t frame_no = 0; // absolute frame index (for the timeline) int64_t t_start = esp_timer_get_time(); int64_t next_log = t_start + 1000000; uint32_t sent = 0; uint32_t window_frames = 0; int64_t window_start = t_start, draw_us = 0, draw_max_us = 0; uint32_t last_dropped = __atomic_load_n(&s_rx_dropped_bytes, __ATOMIC_RELAXED); RenderSchedule render_schedule; bool in_speech = false; bool wave_activity = false; int16_t wave_samples[FRAME_SAMPLES] = {}; int hangover = 0; float noise = -1.0f; uint32_t proc_deadline = 0; auto send_frame = [&](const int16_t *pcm, uint32_t idx, uint32_t *s) { if (s_ws.isConnected()) { uint32_t sample_pos = idx * FRAME_SAMPLES; memcpy(&pkt[4], &seq, 4); memcpy(&pkt[8], &sample_pos, 4); memcpy(&pkt[12], pcm, out_bytes); s_ws.sendBIN(pkt, 12 + out_bytes); seq++; } (*s)++; }; Serial.println("STREAMING"); while (true) { s_ws.loop(); int ret = esp_codec_dev_read(s_mic, inbuf, in_bytes); if (ret != ESP_CODEC_DEV_OK) { Serial.printf("ERR read ret=%d\n", ret); delay(10); continue; } int32_t peak = 0; int64_t acc = 0; for (int i = 0; i < FRAME_SAMPLES; i++) { int16_t s = inbuf[i * CHANNELS]; frame[i] = s; int32_t a = s < 0 ? -s : s; if (a > peak) peak = a; acc += (int64_t)s * s; } float rms = sqrtf((float)acc / FRAME_SAMPLES); if (noise < 0.0f) { // Skip the codec-open click (first ~100 ms) before seeding the floor. if (frame_no >= 5) noise = rms; } float threshold = (noise > 0.0f ? noise : 0.0f) * TRIGGER_RATIO; if (threshold < 40.0f) threshold = 40.0f; bool voiced = (noise > 0.0f) && (rms > threshold); // AGC adapts only while speech is present. Adapting during silence // amplified the noise floor up to the target and ate the headroom // speech needed - measured at 2 m as agc=29.6 with vad=0. if (voiced && rms > AGC_MIN_RMS) { float want = AGC_TARGET_RMS / rms; if (want > AGC_MAX_GAIN) want = AGC_MAX_GAIN; if (want < 1.0f) want = 1.0f; if (want < s_agc) s_agc = want; // duck immediately else s_agc = s_agc * 0.98f + want * 0.02f; // boost slowly } if (s_agc > 1.001f) { for (int i = 0; i < FRAME_SAMPLES; i++) { int32_t v = (int32_t)(frame[i] * s_agc); if (v > 32767) v = 32767; if (v < -32768) v = -32768; frame[i] = (int16_t)v; } peak = 0; for (int i = 0; i < FRAME_SAMPLES; i++) { int32_t a = frame[i] < 0 ? -frame[i] : frame[i]; if (a > peak) peak = a; } } // Latch above-noise audio between UI polls; quiet room noise must not // keep repainting the screen or be magnified into a moving trace. if (voiced) { wave_activity = true; memcpy(wave_samples, frame, out_bytes); } // keep the pre-roll ring current (post-AGC, matching what is sent) memcpy(pre + (frame_no % PREROLL_FRAMES) * FRAME_SAMPLES, frame, out_bytes); if (voiced) { if (!in_speech) { // flush the pre-roll so the onset is intact int first = (int)frame_no - PREROLL_FRAMES + 1; for (int k = 0; k < PREROLL_FRAMES; k++) { int idx = first + k; if (idx < 0) continue; send_frame(pre + (idx % PREROLL_FRAMES) * FRAME_SAMPLES, (uint32_t)idx, &sent); } in_speech = true; Serial.printf("VAD start frame=%u noise=%.0f rms=%.0f\n", (unsigned)frame_no, noise, rms); } hangover = HANGOVER_FRAMES; send_frame(frame, frame_no, &sent); } else if (in_speech) { send_frame(frame, frame_no, &sent); if (--hangover <= 0) { in_speech = false; // Tell the service the utterance ended, so it flushes now instead // of waiting for a gap in sample_pos to prove it. if (s_ws.isConnected()) s_ws.sendTXT("eou"); display_set_processing(true); proc_deadline = millis() + 4000; // clear the cue if nothing returns Serial.printf("VAD stop frame=%u duty=%.1f%%\n", (unsigned)frame_no, 100.0 * sent / (float)(frame_no + 1)); } } else if (noise > 0.0f) { // Adapt fast right after boot, slowly once settled. Guarded on // noise > 0 so the codec-open click can never seed the estimate. float a = (frame_no < 100) ? 0.05f : NOISE_EMA; noise = (1.0f - a) * noise + a * rms; } frame_no++; window_frames++; // Poll orientation independently of the slower UI refresh. Audio stays // at 50 frames/s; buffered samples are drained after each screen flush. const unsigned rotation = imu_rotation(); if (ui && render_schedule.due(millis(), wave_activity || in_speech || proc_deadline != 0, rotation)) { const int64_t draw_start = esp_timer_get_time(); display_set_rotation(rotation); const int percent = battery_percent(); display_set_battery(percent, battery_charging()); display_update(wave_activity ? wave_samples : frame, FRAME_SAMPLES, in_speech, wave_activity); wave_activity = false; const int64_t elapsed = esp_timer_get_time() - draw_start; draw_us += elapsed; if (elapsed > draw_max_us) draw_max_us = elapsed; } if (proc_deadline && (int32_t)(millis() - proc_deadline) > 0) { proc_deadline = 0; display_set_processing(false); } int64_t now = esp_timer_get_time(); if (now >= next_log) { Serial.printf("STAT frame=%u sent_s=%u peak=%ld rms=%.0f noise=%.0f vad=%d agc=%.1f\n", (unsigned)frame_no, (unsigned)sent, (long)peak, rms, noise, in_speech ? 1 : 0, s_agc); const uint32_t dropped = __atomic_load_n(&s_rx_dropped_bytes, __ATOMIC_RELAXED); Serial.printf("PERF fps=%.1f draw_ms=%.1f draw_max_ms=%.1f rx_drop_ms=%.1f\n", window_frames * 1000000.0 / (now - window_start), draw_us / 1000.0, draw_max_us / 1000.0, static_cast(dropped - last_dropped) * 1000.0 / (SAMPLE_RATE * CHANNELS * sizeof(int16_t))); last_dropped = dropped; window_start = now; window_frames = 0; draw_us = 0; draw_max_us = 0; sent = 0; next_log = now + 1000000; } int64_t due = t_start + (int64_t)frame_no * 20000; int64_t delta = due - esp_timer_get_time(); if (delta > 2000) delay(delta / 1000); } } void loop() { delay(1000); }