const int buzzerPin = 8;
const int buttonPin = 2;
unsigned long lastDebounceTime = 0;
const unsigned long debounceDelay = 50;
int noteIndex = 0;
bool buttonPressed = false;
// 定義音符頻率
#define NOTE_C5 523
#define NOTE_D5 587
#define NOTE_E5 659
#define NOTE_F5 698
#define NOTE_G5 784
// 🎵 Jingle Bells(簡化延長版)
int melody[] = {
NOTE_E5, NOTE_E5, NOTE_E5, NOTE_E5, NOTE_E5, NOTE_E5,
NOTE_E5, NOTE_G5, NOTE_C5, NOTE_D5, NOTE_E5,
NOTE_F5, NOTE_F5, NOTE_F5, NOTE_F5, NOTE_F5, NOTE_E5, NOTE_E5,
NOTE_E5, NOTE_E5, NOTE_D5, NOTE_D5, NOTE_E5, NOTE_D5, NOTE_G5
};
int durations[] = {
4, 4, 2, 4, 4, 2,
4, 4, 4, 4, 1,
4, 4, 2, 4, 4, 2, 4,
4, 4, 4, 4, 4, 4, 1
};
void setup() {
pinMode(buzzerPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
}
void loop() {
static bool lastButtonState = HIGH;
bool reading = digitalRead(buttonPin);
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading == LOW && !buttonPressed) {
buttonPressed = true;
playNextNote();
}
}
if (reading == HIGH) {
buttonPressed = false;
}
lastButtonState = reading;
}
void playNextNote() {
int length = sizeof(melody) / sizeof(melody[0]);
int duration = 1000 / durations[noteIndex];
tone(buzzerPin, melody[noteIndex], duration);
delay(duration * 1.3);
noTone(buzzerPin);
noteIndex++;
if (noteIndex >= length) {
noteIndex = 0; // 從頭開始
}
}
留言
張貼留言