arduino蜂鸣器音乐代码大全
时间: 2023-09-18 10:01:39 浏览: 1219
arduino蜂鸣器音乐代码.doc
以下是几个常见的Arduino蜂鸣器音乐代码示例:
1. 播放简单的音阶:
```
int buzzerPin = 9;
void setup() {
pinMode(buzzerPin, OUTPUT);
}
void loop() {
// 音阶数组
int melody[] = {262, 294, 330, 349, 392, 440, 494, 523};
// 音符持续时间
int noteDuration = 250;
// 播放音阶
for (int i = 0; i < 8; i++) {
tone(buzzerPin, melody[i], noteDuration);
delay(noteDuration);
noTone(buzzerPin);
delay(50);
}
}
```
2. 播放Happy Birthday歌曲:
```
int buzzerPin = 9;
void setup() {
pinMode(buzzerPin, OUTPUT);
}
void loop() {
int melody[] = {NOTE_E4, NOTE_E4, NOTE_F4, NOTE_E4, NOTE_G4, NOTE_E4, NOTE_E4, NOTE_F4, NOTE_E4, NOTE_A4, NOTE_E4, NOTE_E4, NOTE_E5, NOTE_E4, NOTE_D5, NOTE_B4, NOTE_G4, NOTE_G4, NOTE_F4, NOTE_E4, NOTE_C5, NOTE_C5, NOTE_B4, NOTE_G4, NOTE_A4, 0, NOTE_A4, NOTE_A4, NOTE_G4, NOTE_E4, NOTE_G4, NOTE_E4, NOTE_C5, NOTE_B4, 0};
int noteDuration[] = {4, 4, 8, 8, 4, 4, 4, 4, 4, 4, 2, 4, 4, 8, 8, 4, 4, 4, 4, 4, 4, 2, 4, 4, 8, 8, 4, 4, 4, 4, 4, 4, 2};
for (int i = 0; i < 31; i++) {
if (melody[i] == 0) {
delay(noteDuration[i]);
} else {
tone(buzzerPin, melody[i], noteDuration[i] * 100);
delay(noteDuration[i] * 110);
noTone(buzzerPin);
delay(20);
}
}
}
```
3. 播放Super Mario游戏主题曲:
```
int buzzerPin = 9;
void setup() {
pinMode(buzzerPin, OUTPUT);
}
void loop() {
int melody[] = {NOTE_E7, NOTE_E7, 0, NOTE_E7, 0, NOTE_C7, NOTE_E7, 0, NOTE_G7, 0, 0, 0, NOTE_G6, 0, 0, 0, NOTE_C7, 0, 0, NOTE_G6, 0, 0, NOTE_E6, 0, 0, NOTE_A6, 0, NOTE_B6, 0, NOTE_AS6, NOTE_A6, 0, NOTE_G6, NOTE_E7, NOTE_G7, NOTE_A7, 0, NOTE_F7, NOTE_G7, 0, NOTE_E7, 0, NOTE_C7, NOTE_D7, NOTE_B6, 0, 0, NOTE_C7, 0, 0, NOTE_G6, 0, 0, NOTE_E6, 0, 0, NOTE_A6, 0, NOTE_B6, 0, NOTE_AS6, NOTE_A6, 0, NOTE_G6, NOTE_E7, NOTE_G7, NOTE_A7, 0, NOTE_F7, NOTE_G7, 0, NOTE_E7, 0, NOTE_C7, NOTE_D7, NOTE_B6, 0, 0};
int noteDuration[] = {12, 12, 12, 12, 12, 12, 6, 12, 12, 6, 12, 12, 12, 12, 12, 12, 12, 6, 6, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 6, 6, 12, 12, 12, 12, 6, 6, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 6};
for (int i = 0; i < 90; i++)
{
if (melody[i] == 0) {
delay(noteDuration[i]);
} else {
tone(buzzerPin, melody[i], noteDuration[i] * 100);
delay(noteDuration[i] * 110);
noTone(buzzerPin);
delay(20);
}
}
}
```
这些代码提供了一些基本的Arduino蜂鸣器音乐代码示例,您可以根据自己的需求进行修改和扩展。
阅读全文