Files
lilygo-t-deck/examples/NoiseSensor/sound_detector.h
T
Dejvino 2ba92a65d1 Drive radar blips from the T-Deck Plus dual microphones
Add a SoundDetector that reads the ES7210 as a 4-slot TDM stream
(slot 0 = MIC1/left, slot 2 = MIC3/right), tracks a per-channel RMS
envelope with an adaptive noise floor, and publishes a stereo balance
plus a dB-mapped loudness.

The radar sketch now slides a single reused blip left/right from the
balance and moves it nearer as the loudness rises, instead of firing a
hardcoded demo blip. The device's own ping/click mutes the detector for
200 ms so it cannot hear itself.

The trackball stays detached: GPIO0 is unavailable while the ES7210
microphones are running.
2026-11-12 08:20:38 +01:00

58 lines
1.8 KiB
C++

/**
* @file sound_detector.h
* @brief Dual-microphone sound localizer for the T-Deck Plus (ES7210).
*
* Reads the two populated MEMS microphones as a 4-slot TDM stream:
* slot 0 = MIC1 (left), slot 2 = MIC3 (right)
* and exposes a smoothed left/right level, a stereo balance and a loudness
* value suitable for placing a radar blip.
*/
#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;
};