使用arduino编写蜂鸣器演奏 青花瓷的代码
时间: 2023-06-14 13:08:35 浏览: 1028
以下是使用 Arduino 控制蜂鸣器演奏《青花瓷》的示例代码:
```C++
// 定义蜂鸣器引脚
#define BUZZER_PIN 8
// 定义音符频率
#define NOTE_C4 262
#define NOTE_D4 294
#define NOTE_E4 330
#define NOTE_F4 349
#define NOTE_G4 392
#define NOTE_A4 440
#define NOTE_B4 494
#define NOTE_C5 523
// 定义每个音符的持续时间
#define NOTE_DURATION 500
// 定义演奏的曲目
int melody[] = {
NOTE_G4, NOTE_A4, NOTE_B4, NOTE_C5, NOTE_B4, NOTE_A4, NOTE_G4,
NOTE_E4, NOTE_G4, NOTE_A4, NOTE_B4, NOTE_A4, NOTE_G4,
NOTE_E4, NOTE_G4, NOTE_A4, NOTE_B4, NOTE_C5, NOTE_B4, NOTE_A4, NOTE_G4,
NOTE_A4, NOTE_C5, NOTE_D5, NOTE_B4, NOTE_G4, NOTE_A4,
NOTE_G4, NOTE_A4, NOTE_B4, NOTE_C5, NOTE_B4, NOTE_A4, NOTE_G4,
NOTE_E4, NOTE_G4, NOTE_A4, NOTE_B4, NOTE_A4, NOTE_G4,
NOTE_E4, NOTE_G4, NOTE_A4, NOTE_G4, NOTE_E4, NOTE_D4, NOTE_C4
};
// 定义演奏的曲目对应的节奏
int noteDurations[] = {
NOTE_DURATION, NOTE_DURATION, NOTE_DURATION, NOTE_DURATION, NOTE_DURATION, NOTE_DURATION, NOTE_DURATION,
NOTE_DURATION, NOTE_DURATION, NOTE_DURATION, NOTE_DURATION, NOTE_DURATION, NOTE_DURATION,
NOTE_DURATION, NOTE_DURATION, NOTE_DURATION, NOTE_DURATION, NOTE_DURATION, NOTE_DURATION, NOTE_DURATION, NOTE_DURATION,
NOTE_DURATION, NOTE_DURATION, NOTE_DURATION, NOTE_DURATION, NOTE_DURATION, NOTE_DURATION,
NOTE_DURATION, NOTE_DURATION, NOTE_DURATION, NOTE_DURATION, NOTE_DURATION, NOTE_DURATION, NOTE_DURATION,
NOTE_DURATION, NOTE_DURATION, NOTE_DURATION, NOTE_DURATION, NOTE_DURATION, NOTE_DURATION,
NOTE_DURATION, NOTE_DURATION, NOTE_DURATION, NOTE_DURATION, NOTE_DURATION, NOTE_DURATION, NOTE_DURATION
};
void setup() {
// 初始化串口
Serial.begin(9600);
// 设置蜂鸣器引脚为输出
pinMode(BUZZER_PIN, OUTPUT);
}
void loop() {
// 演奏曲目
for (int i = 0; i < sizeof(melody) / sizeof(int); i++) {
tone(BUZZER_PIN, melody[i], noteDurations[i]);
delay(noteDurations[i] * 1.3); // 延时一段时间以让音符完整演奏
noTone(BUZZER_PIN); // 停止演奏
}
}
```
你可以将以上代码复制到 Arduino IDE 中,然后将 Arduino 板子连接到计算机上,选择正确的板子和端口,编译上传即可。在演奏时,将蜂鸣器连接到 Arduino 板子的 8 号引脚上即可。
阅读全文