pdf-icon

Arduino入門

2. デバイス&サンプル

Air Quality ブザー

Air Quality ブザーに関する API とサンプルプログラム。

サンプルプログラム

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
#include <M5Unified.h>
#define BUZZER_PIN G9
// 音符の周波数
#define NOTE_C4 262
#define NOTE_D4 294
#define NOTE_E4 330
#define NOTE_F4 349
#define NOTE_G4 392
#define NOTE_A4 440
// メロディと拍(「きらきら星」の最初の14音)
int melody[] = {
NOTE_C4, NOTE_C4, NOTE_G4, NOTE_G4,
NOTE_A4, NOTE_A4, NOTE_G4,
NOTE_F4, NOTE_F4, NOTE_E4, NOTE_E4,
NOTE_D4, NOTE_D4, NOTE_C4
};
int noteDurations[] = {
4,4,4,4,4,4,2,
4,4,4,4,4,4,2
};
void setup() {
// M5Unified を初期化
M5.begin();
// 画面をクリアし、テキストプロパティを設定
M5.Display.clear(TFT_BLACK);
M5.Display.setTextSize(2);
M5.Display.setTextColor(TFT_WHITE, TFT_BLACK);
// 画面に英語のタイトルを表示
M5.Display.setCursor( 20, 20);
M5.Display.print("Playing:");
M5.Display.setCursor( 20, 60);
M5.Display.print("Twinkle Twinkle");
M5.Display.setCursor( 20, 100);
M5.Display.print("Little Star");
pinMode(BUZZER_PIN, OUTPUT);
}
void loop() {
int notes = sizeof(melody) / sizeof(melody[0]);
for (int i = 0; i < notes; i++) {
// 現在の音符を再生
int duration = 1000 / noteDurations[i];
tone(BUZZER_PIN, melody[i], duration);
delay(duration * 1.2);
noTone(BUZZER_PIN);
M5.update();
}
// 演奏終了後、最後の音で止まる。ループ再生する場合はコメントアウトを解除:
// while (true) {
// delay(1000);
// }
}

アップロード後、「きらきら星」がループ再生される次のような効果が表示されます:

On This Page