Files
lilygo-t-deck/examples/NoiseSensor/sound_detector.h
T
Dejvino 72f80bfdd8 Make microphone slot discovery self-healing
The ES7210 power-up transient is loud enough to look like the first
sound. It placed one centred blip right after init and then pinned the
mic pair to whichever slots were loudest at that instant. If that was
the wrong pair, later claps were ignored forever.

Ignore the first 800 ms after starting the codec, and re-evaluate the
mic pair on every clear sound instead of locking once. The pair only
changes after repeating for a few blocks, or immediately when the
current pair is silent while another one is loud. Also enable the
per-second rms/pair debug line so the slot mapping can be verified on
hardware.
2026-11-12 14:10:17 +01:00

67 lines
2.2 KiB
C++

/**
* @file sound_detector.h
* @brief Dual-microphone sound localizer for the T-Deck Plus (ES7210).
*
* Reads the ES7210's four TDM slots and uses the two slots that carry a
* populated MEMS microphone (the board only fits two of the four footprints).
* Balance is taken from the level difference between the pair, so a sound on
* the left or right side moves a radar blip accordingly.
*/
#pragma once
#include <Arduino.h>
#include <driver/i2s.h>
struct SoundReading {
float left; // smoothed level above the noise floor (0..1)
float right; // smoothed level above the noise floor (0..1)
float balance; // -1 = far left, 0 = centre, +1 = far right
float loudness; // 0 = quiet, 1 = loud (dB-mapped)
bool active; // true while a sound is present (with a short hold)
};
class SoundDetector {
public:
// Starts the ES7210 codec and the I2S receive task. Returns false if the
// codec or I2S driver could not be initialised.
bool begin(uint32_t sampleRate = 16000);
// Latest measurement. Safe to call from the main loop.
SoundReading read();
bool available() const { return running_; }
// Ignore microphone input for a while (used so the device's own radar
// ping does not register as a target).
void suppress(uint32_t ms);
private:
static void taskEntry(void *arg);
void taskLoop();
void processBlock(const int16_t *frames, size_t frameCount);
void publish(float left, float right, float balance, float loudness, bool active);
uint32_t sampleRate_ = 16000;
TaskHandle_t task_ = nullptr;
volatile bool running_ = false;
volatile uint32_t suppressUntil_ = 0;
portMUX_TYPE mux_ = portMUX_INITIALIZER_UNLOCKED;
SoundReading reading_ = {};
uint32_t lastActiveMs_ = 0;
float envL_ = 0.0f;
float envR_ = 0.0f;
float floorL_ = 0.01f;
float floorR_ = 0.01f;
// The codec always delivers four TDM slots, but only two microphones are
// fitted. The pair is (re)discovered from the slots that carry signal.
int leftSlot_ = 0;
int rightSlot_ = 1;
int candL_ = -1;
int candR_ = -1;
int candCount_ = 0;
uint32_t warmupUntil_ = 0;
};