今回は M5Atom Lite からマイクの値を取得して,グラフを描いたり,音の大きさに応じてLEDの明るさを変えてみました.
#M5Atom でマイクテスト#Arduino pic.twitter.com/tnW9e3tNhK
— botamochi (@botamochi6277) May 12, 2021
使用したマイクは Amazon で買ったよくあるマイクとアンプがセットになったモジュールです.
このモジュールはアンプで増幅した信号をアナログ信号として出力します.無音の時にはVccの半分(Vcc が 3.3 V なら 1.615 V)の信号が出てきます.
配線は次の通りです.ポテンショメータの値をとる時と同じような配線になります.
M5Atom | Mic | |
---|---|---|
3.3V | — | VCC |
GND | — | GND |
G33 | — | OUT |
使用したコードはこちらになります.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @file M5AtomMic.ino | |
* @author botamochi6277 | |
* @brief Analog Microphone Test fot M5Atom Series | |
* @version 0.1 | |
* @date 2021-05-07 | |
* | |
* | |
* @licence MIT LICENCE | |
* | |
*/ | |
#include "M5Atom.h" | |
int const ANALOG_PIN = 33; | |
// buffer for moving avarage filter | |
int const NUM_BUFFER = 5; | |
int buffer[NUM_BUFFER]; | |
void setup() | |
{ | |
M5.begin(true, false, true); | |
pinMode(ANALOG_PIN, INPUT); | |
M5.IMU.Init(); | |
} | |
void loop() | |
{ | |
M5.update(); | |
int value = analogRead(ANALOG_PIN); // 0–4096 | |
int v = abs(value – 2048); | |
v = map(v, 0, 2048, 0, 255); | |
pushBack(buffer, v); // update buffer values | |
int magnitude = average(buffer); | |
// CHSV (uint8_t ih, uint8_t is, uint8_t iv) | |
CHSV color = CHSV(127, 255, magnitude); | |
M5.dis.clear(); | |
if (magnitude > 32) | |
{ | |
M5.dis.drawpix(0, color); | |
} | |
Serial.print(value); | |
Serial.print(","); | |
Serial.println(magnitude); | |
delay(50); | |
} | |
int average(int *values) | |
{ | |
int sum = 0; | |
for (int i = 0; i < NUM_BUFFER; i++) | |
{ | |
sum += values[i]; | |
} | |
return sum / NUM_BUFFER; | |
} | |
int pushBack(int *values, int new_value) | |
{ | |
for (int i = NUM_BUFFER – 1; i > 0; i–) | |
{ | |
values[i] = values[i – 1]; | |
} | |
values[0] = new_value; | |
} |
コードの中身としては次のようになっています.
analogRead()
でマイクの値を読み取る (M5Atom のチップのESP32の場合は0–4096の値が返ってきます)map()
でLEDの光の強度magnitude
に変換(0–255)magnitude
を移動平均フィルタで平滑化- FastLED の
CHSV
クラスを使ってLEDに渡す色を設定 - 結果をシリアル通信で送信
コメント