arduino蜂鸣器简单歌曲代码
时间: 2023-09-08 13:09:21 浏览: 284
Arduino项目开发 利用蜂鸣器演奏简单的歌曲.pdf
好的,以下是一个简单的arduino蜂鸣器播放"小星星"的代码:
```
int melody[] = {
NOTE_C4, NOTE_C4, NOTE_G4, NOTE_G4, NOTE_A4, NOTE_A4, NOTE_G4,
NOTE_F4, NOTE_F4, NOTE_E4, NOTE_E4, NOTE_D4, NOTE_D4, NOTE_C4
};
int noteDurations[] = {
4, 4, 4, 4, 4, 4, 2,
4, 4, 4, 4, 4, 4, 2
};
void playTone(int tone, int duration) {
for (long i = 0; i < duration * 1000L; i += tone * 2) {
digitalWrite(8, HIGH);
delayMicroseconds(tone);
digitalWrite(8, LOW);
delayMicroseconds(tone);
}
}
void playNote(int note, int duration) {
int tone = 0;
switch(note) {
case 'C':
tone = 1915;
break;
case 'D':
tone = 1700;
break;
case 'E':
tone = 1519;
break;
case 'F':
tone = 1432;
break;
case 'G':
tone = 1275;
break;
case 'A':
tone = 1136;
break;
case 'B':
tone = 1014;
break;
case 'P':
delay(duration);
return;
default:
break;
}
playTone(tone, duration);
}
void setup() {
pinMode(8, OUTPUT);
}
void loop() {
for (int i = 0; i < 14; i++) {
playNote(melody[i], noteDurations[i]);
delay(noteDurations[i] / 2);
}
delay(1000);
}
```
以上代码会让蜂鸣器播放"小星星",如果需要播放其他歌曲或想要更详细的说明,可以与我进行交互。
阅读全文