const int speakerPin = 9; // 連接喇叭的腳位
const int joystickX = A0; // 搖桿 X 軸輸入
const int joystickY = A1; // 搖桿 Y 軸輸入
const int centerThreshold = 100; // 中立範圍
void playMelody(int melody[], int noteDurations[], int noteCount) {
for (int i = 0; i < noteCount; i++) {
tone(speakerPin, melody[i], noteDurations[i]);
delay(noteDurations[i] + 50);
}
noTone(speakerPin);
}
// 🎂 生日快樂歌
int melodyHappyBirthday[] = {262, 262, 294, 262, 349, 330, 262, 262, 294, 262, 392, 349};
int noteDurationsHappyBirthday[] = {300, 300, 600, 600, 600, 1200, 300, 300, 600, 600, 600, 1200};
// 🎺 歡樂頌
int melodyOdeToJoy[] = {392, 392, 440, 392, 349, 330, 262, 294, 330, 349, 392, 392, 392};
int noteDurationsOdeToJoy[] = {300, 300, 600, 600, 600, 600, 300, 300, 600, 600, 600, 600, 1200};
// 🎶 愛麗絲
int melodyFurElise[] = {659, 622, 659, 622, 659, 494, 587, 523, 440, 262, 330, 440};
int noteDurationsFurElise[] = {300, 300, 600, 600, 600, 600, 300, 300, 600, 600, 600, 1200};
// ⭐ 小星星
int melodyTwinkleStar[] = {262, 262, 392, 392, 440, 440, 392, 349, 349, 330, 330, 294, 294, 262};
int noteDurationsTwinkleStar[] = {300, 300, 600, 600, 600, 600, 1200, 300, 300, 600, 600, 600, 600, 1200};
void setup() {
pinMode(speakerPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
int xValue = analogRead(joystickX);
int yValue = analogRead(joystickY);
// 根據搖桿方向播放不同旋律
if (yValue < 512 - centerThreshold) {
playMelody(melodyHappyBirthday, noteDurationsHappyBirthday, 12); // 上:生日快樂
} else if (xValue > 512 + centerThreshold) {
playMelody(melodyOdeToJoy, noteDurationsOdeToJoy, 13); // 右:歡樂頌
} else if (yValue > 512 + centerThreshold) {
playMelody(melodyFurElise, noteDurationsFurElise, 12); // 下:愛麗絲
} else if (xValue < 512 - centerThreshold) {
playMelody(melodyTwinkleStar, noteDurationsTwinkleStar, 14); // 左:小星星
} else {
noTone(speakerPin); // 中立位置不發聲
}
Serial.print("X: ");
Serial.print(xValue);
Serial.print(" Y: ");
Serial.println(yValue);
delay(500);
}

留言
張貼留言