简体中文
English
简体中文
日本語

Arduino 上手教程

2. 设备开发 & 案例程序

5. 扩展模块

6. 应用案例

PaperMono Mic 麦克风

PaperMono Mic 相关 API 与案例程序。

案例程序

编译要求

  • M5Stack 板管理版本 >= 3.3.9
  • 开发板选项 = M5PaperMono
  • M5Unified 库版本 >= 0.2.20
  • M5GFX 库版本 >= 0.2.27
  • M5IOE1 库版本 >= 1.0.9
cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
#include <Arduino.h>
#include <M5IOE1.h>
#include <M5Unified.h>
#include <driver/gpio.h>
#include <math.h>

namespace {

constexpr uint32_t kSampleRateHz = 16000;
constexpr size_t kSampleCount = 1600;
constexpr uint32_t kUpdateIntervalMs = 1000;
constexpr size_t kHistoryLength = 60;

constexpr int kPdmClockPin = 45;
constexpr int kPdmDataPin = 46;
constexpr auto kPdmPowerPin = M5IOE1_PIN_12;

constexpr int kGraphLeft = 42;
constexpr int kGraphTop = 245;
constexpr int kGraphWidth = 396;
constexpr int kGraphHeight = 430;

M5IOE1 ioe1;
M5Canvas canvas(&M5.Display);
int16_t samples[kSampleCount];
float levelHistory[kHistoryLength] = {};
size_t historyCount = 0;
uint32_t nextUpdateMs = 0;

struct VolumeReading {
    float rms;
    float peak;
    float dbfs;
    float percent;
};

[[noreturn]] void stopWithError(const char* message)
{
    Serial.println(message);
    canvas.fillSprite(TFT_WHITE);
    canvas.setTextColor(TFT_BLACK, TFT_WHITE);
    canvas.setTextDatum(middle_center);
    canvas.setFont(&fonts::FreeSansBold18pt7b);
    canvas.drawString("MIC ERROR", 240, 330);
    canvas.setFont(&fonts::FreeSans12pt7b);
    canvas.drawString(message, 240, 410);
    M5.Display.setEpdMode(epd_mode_t::epd_fastest);
    canvas.pushSprite(0, 0);
    while (true) {
        delay(1000);
    }
}

bool waitForRecording(uint32_t timeoutMs)
{
    const uint32_t startedAt = millis();
    while (M5.Mic.isRecording()) {
        if (millis() - startedAt >= timeoutMs) {
            return false;
        }
        delay(1);
    }
    return true;
}

VolumeReading analyzeSamples()
{
    int64_t sum = 0;
    for (size_t i = 0; i < kSampleCount; ++i) {
        sum += samples[i];
    }
    const double mean = static_cast<double>(sum) / kSampleCount;

    double squareSum = 0.0;
    double peak = 0.0;
    for (size_t i = 0; i < kSampleCount; ++i) {
        const double centered = static_cast<double>(samples[i]) - mean;
        squareSum += centered * centered;
        peak = max(peak, fabs(centered));
    }

    const float rms = sqrt(squareSum / kSampleCount);
    const float dbfs = rms > 0.0f ? 20.0f * log10f(rms / 32768.0f) : -96.0f;
    const float percent = constrain((dbfs + 60.0f) * (100.0f / 60.0f), 0.0f, 100.0f);
    return {rms, static_cast<float>(peak), dbfs, percent};
}

void appendHistory(float value)
{
    if (historyCount < kHistoryLength) {
        levelHistory[historyCount++] = value;
        return;
    }

    memmove(levelHistory, levelHistory + 1,
            (kHistoryLength - 1) * sizeof(levelHistory[0]));
    levelHistory[kHistoryLength - 1] = value;
}

void drawGrid()
{
    canvas.drawRect(kGraphLeft, kGraphTop, kGraphWidth, kGraphHeight, TFT_BLACK);
    canvas.setFont(&fonts::FreeSans9pt7b);
    canvas.setTextDatum(middle_right);

    for (int percent = 0; percent <= 100; percent += 25) {
        const int y = kGraphTop + kGraphHeight -
                      (percent * kGraphHeight / 100);
        const uint16_t color = percent == 0 ? TFT_BLACK : TFT_LIGHTGREY;
        canvas.drawFastHLine(kGraphLeft, y, kGraphWidth, color);
        canvas.drawString(String(percent), kGraphLeft - 7, y);
    }

    canvas.setTextDatum(top_center);
    canvas.drawString("60 seconds", kGraphLeft + kGraphWidth / 2,
                      kGraphTop + kGraphHeight + 18);
}

void drawScreen(const VolumeReading& reading)
{
    canvas.fillSprite(TFT_WHITE);
    canvas.setTextColor(TFT_BLACK, TFT_WHITE);
    canvas.setTextDatum(top_center);

    canvas.setFont(&fonts::FreeSansBold24pt7b);
    canvas.drawString("PaperMono MIC", 240, 24);
    canvas.setFont(&fonts::FreeSans12pt7b);
    canvas.drawString("Volume amplitude", 240, 92);

    canvas.setFont(&fonts::FreeSansBold18pt7b);
    canvas.setTextDatum(middle_center);
    canvas.drawString(String(reading.percent, 1) + "%", 110, 180);
    canvas.drawString(String(reading.dbfs, 1) + " dBFS", 350, 180);

    canvas.setFont(&fonts::FreeSans9pt7b);
    canvas.drawString("RMS " + String(reading.rms, 0), 110, 220);
    canvas.drawString("PEAK " + String(reading.peak, 0), 350, 220);

    drawGrid();

    if (historyCount > 0) {
        const int plotLeft = kGraphLeft + 1;
        const int plotRight = kGraphLeft + kGraphWidth - 2;
        const int plotBottom = kGraphTop + kGraphHeight - 1;
        const int plotHeight = kGraphHeight - 2;
        int previousX = plotRight -
                        static_cast<int>((historyCount - 1) *
                                         (plotRight - plotLeft) /
                                         (kHistoryLength - 1));
        int previousY = plotBottom -
                        static_cast<int>(levelHistory[0] * plotHeight / 100.0f);

        for (size_t i = 1; i < historyCount; ++i) {
            const int x = plotRight -
                          static_cast<int>((historyCount - 1 - i) *
                                           (plotRight - plotLeft) /
                                           (kHistoryLength - 1));
            const int y = plotBottom -
                          static_cast<int>(levelHistory[i] * plotHeight / 100.0f);
            canvas.drawLine(previousX, previousY, x, y, TFT_BLACK);
            canvas.fillCircle(x, y, 3, TFT_BLACK);
            previousX = x;
            previousY = y;
        }
        canvas.fillCircle(previousX, previousY, 4, TFT_BLACK);
    }

    M5.Display.setEpdMode(epd_mode_t::epd_fastest);
    canvas.pushSprite(0, 0);
}

void initializeMicrophone()
{
    const m5ioe1_err_t ioeError = ioe1.begin(
        &M5.In_I2C, M5IOE1_DEFAULT_ADDR_2, M5IOE1_I2C_FREQ_100K);
    if (ioeError != M5IOE1_OK) {
        stopWithError("M5IOE1 initialization failed");
    }

    ioe1.pinMode(kPdmPowerPin, OUTPUT);
    if (ioe1.setDriveMode(kPdmPowerPin, M5IOE1_DRIVE_PUSHPULL) != M5IOE1_OK) {
        stopWithError("PDM power pin setup failed");
    }
    m5ioe1_err_t powerError = M5IOE1_OK;
    ioe1.digitalWriteWithRes(kPdmPowerPin, HIGH, &powerError);
    if (powerError != M5IOE1_OK) {
        stopWithError("PDM microphone power failed");
    }
    delay(20);

    gpio_reset_pin(static_cast<gpio_num_t>(kPdmDataPin));
    gpio_set_direction(static_cast<gpio_num_t>(kPdmDataPin), GPIO_MODE_INPUT);
    gpio_set_pull_mode(static_cast<gpio_num_t>(kPdmDataPin), GPIO_FLOATING);
    gpio_reset_pin(static_cast<gpio_num_t>(kPdmClockPin));

    M5.Speaker.end();
    M5.Mic.end();
    auto micConfig = M5.Mic.config();
    micConfig.pin_mck = I2S_PIN_NO_CHANGE;
    micConfig.pin_bck = I2S_PIN_NO_CHANGE;
    micConfig.pin_ws = kPdmClockPin;
    micConfig.pin_data_in = kPdmDataPin;
    micConfig.i2s_port = I2S_NUM_0;
    micConfig.input_channel = m5::input_channel_t::input_only_right;
    micConfig.sample_rate = kSampleRateHz;
    micConfig.over_sampling = 1;
    micConfig.magnification = 2;
    micConfig.dma_buf_len = 128;
    micConfig.dma_buf_count = 8;
    M5.Mic.config(micConfig);

    if (!M5.Mic.begin()) {
        stopWithError("PDM microphone begin failed");
    }
    Serial.println("PDM microphone: ready");
}

}  // namespace

void setup()
{
    Serial.begin(115200);
    delay(100);
    Serial.println("PaperMono microphone amplitude demo");

    auto config = M5.config();
    config.clear_display = false;
    config.internal_rtc = false;
    config.internal_imu = false;
    config.internal_mic = false;
    M5.begin(config);

    M5.Display.setRotation(0);
    M5.Display.setBrightness(160);
    M5.Display.setEpdMode(epd_mode_t::epd_fastest);
    canvas.setColorDepth(16);
    if (!canvas.createSprite(M5.Display.width(), M5.Display.height())) {
        while (true) {
            Serial.println("Display canvas allocation failed");
            delay(1000);
        }
    }

    initializeMicrophone();
    nextUpdateMs = millis();
}

void loop()
{
    M5.update();
    const uint32_t now = millis();
    if (static_cast<int32_t>(now - nextUpdateMs) < 0) {
        delay(5);
        return;
    }
    nextUpdateMs = now + kUpdateIntervalMs;

    if (!M5.Mic.record(samples, kSampleCount, kSampleRateHz, false) ||
        !waitForRecording(250)) {
        Serial.println("Microphone sample failed");
        return;
    }

    const VolumeReading reading = analyzeSamples();
    appendHistory(reading.percent);
    Serial.printf("MIC rms=%.1f peak=%.1f dbfs=%.1f level=%.1f%%\n",
                  reading.rms, reading.peak, reading.dbfs, reading.percent);
    drawScreen(reading);
}

程序通过 M5IOE1 打开 PDM 麦克风电源,以 16 kHz 采样率每秒采集 1600 个样本,去除直流偏置后计算 RMS、峰值、dBFS 和音量百分比。屏幕会显示当前数值和最近 60 秒的音量变化曲线,数据同时输出到串口监视器。

API

PaperMono 麦克风部分使用了 M5Unified 库中的 Mic_Class,更多相关的API可以参考下方文档:

Page Tools
PDF
On This Page