
Arduino入門


#include "M5Chain.h"
#define RXD_PIN GPIO_NUM_5 // 48 for the other side of Chain DualKey
#define TXD_PIN GPIO_NUM_6 // 47 for the other side of Chain DualKey
Chain M5Chain;
device_info_t devices[8];
device_list_t device_list = {0, devices};
uint16_t device_count = 0;
#define START_KEY_PIN GPIO_NUM_0
#define STOP_KEY_PIN GPIO_NUM_17
uint8_t mic_id = 0;
bool mic_found = false;
bool print_adc = false;
bool start_key_last = HIGH;
bool stop_key_last = HIGH;
void setup() {
Serial.begin(115200);
delay(1000);
Serial.println("===========================");
Serial.println("M5Stack Chain MIC Test");
pinMode(START_KEY_PIN, INPUT_PULLUP);
pinMode(STOP_KEY_PIN, INPUT_PULLUP);
M5Chain.begin(&Serial2, 115200, RXD_PIN, TXD_PIN);
while (!M5Chain.isDeviceConnected()) {
Serial.println("No device connected");
delay(1000);
}
if (M5Chain.getDeviceNum(&device_count) != CHAIN_OK || device_count == 0) {
Serial.println("Failed to get device count");
return;
}
device_list.count = device_count < 8 ? device_count : 8;
if (!M5Chain.getDeviceList(&device_list)) {
Serial.println("Failed to get device list");
return;
}
for (uint16_t i = 0; i < device_list.count; i++) {
if (device_list.devices[i].device_type == CHAIN_MIC_TYPE_CODE) {
mic_id = device_list.devices[i].id;
mic_found = true;
Serial.printf("ID[%d] is Chain MIC\n", mic_id);
break;
}
}
if (!mic_found) {
Serial.println("Chain MIC not found");
return;
}
Serial.println("Press KEY1 to start ADC output");
Serial.println("Press KEY2 to stop ADC output");
}
void loop() {
const bool start_key = digitalRead(START_KEY_PIN);
const bool stop_key = digitalRead(STOP_KEY_PIN);
if (start_key == LOW && start_key_last == HIGH) {
print_adc = true;
Serial.println("ADC_PRINT_START");
}
if (stop_key == LOW && stop_key_last == HIGH) {
print_adc = false;
Serial.println("ADC_PRINT_STOP");
}
start_key_last = start_key;
stop_key_last = stop_key;
if (!mic_found || !print_adc) {
delay(10);
return;
}
uint16_t adc = 0;
if (M5Chain.getMIC12BitAdc(mic_id, &adc) == CHAIN_OK) {
Serial.print("MIC ADC=");
Serial.println(adc);
} else {
Serial.println("MIC ADC read failed");
}
delay(100);
}Chain Bridge コネクタを使用して、メインコントローラである Chain DualKey と Chain MIC を接続します。接続時は方向に注意し、三角形の矢印がメインコントローラ Chain DualKey から外側へ向くようにしてください(下図参照):
この例では、Chain DualKey の GPIO5 を RX、GPIO6 を TX、KEY1(GPIO0)を開始ボタン、KEY2(GPIO17)を停止ボタンとして使用します。Chain MIC を Chain DualKey の反対側のインターフェースに接続する場合は、実際の配線に応じてプログラムの RXD_PIN と TXD_PIN を変更してください。
上記のプログラムをコンパイルして Chain DualKey に書き込み、Arduino IDE 右上のボタンをクリックしてシリアルモニタを開きます。KEY1 を押すと Chain MIC の 12 ビット ADC 値(範囲 0 ~ 4095)の出力が開始され、100 ms ごとに 1 回出力されます。KEY2 を押すと出力が停止します。シリアル出力の ADC_PRINT_START または ADC_PRINT_STOP でボタンの状態を確認できます。
サンプルの動作結果は次のとおりです: