
Arduino Quick Start
APIs and example programs related to the microphone of CoreP4X.
3.3.10-aM5CoreP4X0.3.10.3.1CoreP4X uses the ES7210 audio ADC and dual MEMS microphones, and supports AEC echo cancellation input. The microphone I2S data line is G5, and it shares MCLK G2 / BCLK G6 / LRCK G4 with the speaker.
#include <M5Unified.h>
#include <atomic>
static constexpr size_t SAMPLE_COUNT = 512;
static constexpr uint32_t SAMPLE_RATE = 16000;
static int16_t samples[SAMPLE_COUNT];
static std::atomic<bool> ready {false};
static bool micReady = false;
static void onRecordRelease(void*, void*, size_t)
{
ready.store(true, std::memory_order_release);
}
void setup()
{
auto cfg = M5.config();
cfg.serial_baudrate = 115200;
M5.begin(cfg);
M5.Display.setRotation(0);
M5.Display.setBrightness(128);
M5.Display.fillScreen(TFT_BLACK);
M5.Display.setTextDatum(top_center);
M5.Display.setTextColor(TFT_WHITE, TFT_BLACK);
M5.Display.setFont(&fonts::FreeSansBold24pt7b);
M5.Display.drawString("CoreP4X Mic", 240, 32);
M5.Speaker.end();
M5.Mic.setBufferReleaseCallback(nullptr, onRecordRelease);
micReady = M5.Mic.begin();
if (!micReady) {
M5.Display.setTextColor(TFT_RED, TFT_BLACK);
M5.Display.setFont(&fonts::FreeSans18pt7b);
M5.Display.drawString("Mic init failed", 240, 190);
Serial.println("Mic init failed");
}
}
void loop()
{
if (!micReady || !M5.Mic.isEnabled()) {
delay(500);
return;
}
if (!ready.load(std::memory_order_acquire)) {
if (M5.Mic.record(samples, SAMPLE_COUNT, SAMPLE_RATE)) {
while (!ready.load(std::memory_order_acquire)) {
delay(1);
}
ready.store(false, std::memory_order_release);
int peak = 0;
for (const int16_t sample : samples) {
const int value = abs(sample);
if (value > peak) { peak = value; }
}
const int barWidth = map(peak, 0, 32767, 0, 360);
M5.Display.setTextDatum(middle_center);
M5.Display.setFont(&fonts::FreeSans18pt7b);
M5.Display.setTextColor(TFT_WHITE, TFT_BLACK);
M5.Display.drawString("Input level", 240, 130);
M5.Display.fillRect(60, 174, 360, 40, TFT_DARKGREY);
M5.Display.fillRect(60, 174, barWidth, 40, TFT_GREEN);
M5.Display.fillRect(0, 268, 480, 52, TFT_BLACK);
char peakText[24];
snprintf(peakText, sizeof(peakText), "Peak: %d", peak);
M5.Display.drawString(peakText, 240, 294);
Serial.printf("mic peak: %d\n", peak);
}
}
delay(5);
}After uploading, the screen displays a microphone peak bar; when speaking into the microphone or playing sound, the green bar changes with the volume, and the serial monitor also outputs the peak value.
The microphone section of CoreP4X uses the Mic_Class in the M5Unified library. For more APIs, refer to: