arduino点歌机代码
时间: 2023-09-07 17:14:05 浏览: 38
以下是一个简单的 Arduino 点歌机代码,基于数字钢琴的原理实现,可以通过串口接收来指定播放的曲目和音符:
```c++
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
// 数字钢琴按键对应的频率
int pianoNotes[] = {262, 294, 330, 349, 392, 440, 494, 523};
String pianoKeys[] = {"1", "2", "3", "4", "5", "6", "7", "8"};
String song1[] = {"1", "1", "5", "5", "6", "6", "5", "4", "4", "3", "3", "2", "2", "1"};
String song2[] = {"1", "2", "3", "1", "1", "2", "3", "1", "3", "4", "5", "3", "4", "5", "5", "6", "6", "7", "5", "6", "7", "7", "1", "7", "1", "5", "4", "3", "2", "1"};
int song1Length = sizeof(song1) / sizeof(song1[0]);
int song2Length = sizeof(song2) / sizeof(song2[0]);
void setup() {
Serial.begin(9600);
mySerial.begin(9600);
}
void loop() {
if (mySerial.available()) {
String command = mySerial.readString();
for (int i = 0; i < song1Length; i++) {
if (command == song1[i]) {
playPiano(pianoNotes[i]);
break;
}
}
for (int i = 0; i < song2Length; i++) {
if (command == song2[i]) {
playPiano(pianoNotes[i]);
break;
}
}
}
}
void playPiano(int note) {
tone(9, note, 500);
delay(500);
noTone(9);
}
```
在这个代码中,我们需要使用一个软串口(SoftwareSerial)来实现与外部设备(如手机或电脑)的通信。在 setup() 函数中,我们初始化了串口并设置了钢琴按键对应的频率和钢琴按键的编号。在 loop() 函数中,我们使用了 if 语句来判断接收到的命令是否是钢琴按键的编号,如果是,则调用 playPiano() 函数来播放相应的音符。在 playPiano() 函数中,我们使用了 tone() 函数来播放声音,并使用了 delay() 函数来控制音符的持续时间。
在测试代码时,可以使用串口调试助手或其他串口通信软件来向 Arduino 发送钢琴按键的编号,Arduino 会播放相应的音符。如果你想要实现一个按键式的点歌机,可以使用按钮来触发钢琴音符的播放。