const int buzzerPin = 8; //ブザー
const int playButtonPin = 11; //再生ボタン
const int nextButtonPin = 10; //トラック移動ボタン
bool isPlaying = false; //演奏状態か
int currentTrack = 0; //現在のトラック番号
const int totalTracks = 3; // トラック数 3曲
const int tracksLeght = 15;
/*
melodyは周波数
durationは長さ
例:
きらきら星はbpm100としたとき1分に100拍なので60÷100=0.6
入力の単位がmSecなので600を入れた
*/
// トラック0:ドレミファ
int melody0[] = {262, 294, 330, 349};
int duration0[] = {300, 300, 300, 300};
// トラック1:ソラシド
int melody1[] = {392, 440, 494, 523};
int duration1[] = {300, 300, 300, 300};
// トラック2:きらきら星
int melody2[] = {
262, 262, 392, 392, 440, 440, 392,
349, 349, 330, 330, 294, 294, 262
};
int duration2[] = {
600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 1200
};
// メロディと長さの配列をまとめて扱えるようにポインタでまとめる
int* melodies[] = {melody0, melody1, melody2};
int* durations[] = {duration0, duration1, duration2};
int melodyLengths[] = {
sizeof(melody0) / sizeof(int),
sizeof(melody1) / sizeof(int),
sizeof(melody2) / sizeof(int)
};
void setup() {
pinMode(buzzerPin, OUTPUT);
pinMode(playButtonPin, INPUT_PULLUP);
pinMode(nextButtonPin, INPUT_PULLUP);
}
void loop() {
//状態を記録する
static bool lastPlayButton = HIGH;//初回だけ初期化
static bool lastNextButton = HIGH;//初回だけ初期化
bool playButton = digitalRead(playButtonPin);
//再生ボタンが押されたら
if (lastPlayButton == HIGH && playButton == LOW) {
isPlaying = !isPlaying;//演奏状態を逆に
}
lastPlayButton = playButton;//状態の記録を更新
bool nextButton = digitalRead(nextButtonPin);
//トラック移動が押されたら
if (lastNextButton == HIGH && nextButton == LOW) {
currentTrack = (currentTrack + 1) % totalTracks;//ループするようにトラック番号+1
isPlaying = false;//演奏停止
noTone(buzzerPin);
}
lastNextButton = nextButton;//状態の記録を更新
if (isPlaying) {//演奏してたら
playTrack(currentTrack);//currentTrack番を再生
isPlaying = false; // 1回再生したら停止
//再生終わったら次のトラック流してもいいけどボタンで移動できたか分かりづらいので今回はなし
}
}
/*
音楽再生用の関数
引数:int track (トラック番号)
返り値:なし
*/
void playTrack(int track) {
int* melody = melodies[track];
int* duration = durations[track];
int length = melodyLengths[track];
for (int i = 0; i < length; i++) {
/*
// 再生ボタンの状態を毎回確認
if (digitalRead(playButtonPin) == LOW) {
isPlaying = false; // 再生状態フラグを下げる
noTone(buzzerPin); // 音を止める
break; // ループから抜ける
}
*/
tone(buzzerPin, melody[i]);
delay(duration[i]);
noTone(buzzerPin);
delay(50);
}
}