ardunio点歌机详细代码
时间: 2023-10-04 21:12:19 浏览: 46
以下是一个基于 Arduino 的点歌机的详细代码:
```
#include <SoftwareSerial.h>
// 定义 LED 灯的引脚
#define LED_PIN 13
// 定义 MP3 模块的引脚
#define TX_PIN 10
#define RX_PIN 11
// 使用软串口与 MP3 模块通信
SoftwareSerial mp3Serial(TX_PIN, RX_PIN);
void setup() {
// 初始化串口
Serial.begin(9600);
mp3Serial.begin(9600);
// 设置 LED 灯引脚为输出模式
pinMode(LED_PIN, OUTPUT);
// 发送指令给 MP3 模块,使其初始化
sendCommand(0x0C);
delay(500);
sendCommand(0x01);
delay(500);
sendCommand(0x06);
}
void loop() {
// 等待串口接收到数据
if (Serial.available() > 0) {
// 读取接收到的数据
String song = Serial.readStringUntil('\n');
// 播放指定的歌曲
playSong(song);
// 点亮 LED 灯
digitalWrite(LED_PIN, HIGH);
delay(1000);
// 熄灭 LED 灯
digitalWrite(LED_PIN, LOW);
}
}
void sendCommand(byte command) {
// 发送命令给 MP3 模块
byte buffer[8] = {0x7E, 0x02, command, 0x00, 0x00, 0x00, 0xEF};
for (int i = 0; i < 8; i++) {
mp3Serial.write(buffer[i]);
}
}
void playSong(String song) {
// 根据歌曲名字播放对应的歌曲
if (song == "song1") {
sendCommand(0x03);
} else if (song == "song2") {
sendCommand(0x04);
} else if (song == "song3") {
sendCommand(0x05);
} else {
Serial.println("Unknown song");
}
}
```
此代码使用了一个软串口库来与 MP3 模块通信,并且使用了一个 LED 灯来指示是否正在播放歌曲。在 `setup()` 函数中,我们发送了一些初始化指令给 MP3 模块。在 `loop()` 函数中,我们等待串口接收到数据,读取接收到的数据并播放对应的歌曲。`sendCommand()` 函数用于向 MP3 模块发送指令,`playSong()` 函数根据歌曲名字播放对应的歌曲。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)