#include <LiquidCrystal_I2C.h>
// 定义LCD显示屏(如果有)
LiquidCrystal_I2C lcd(0x27, 16, 2); // 使用I2C适配器,地址和尺寸根据具体LCD而定
const int numKeys = 8; // 假设有8个按键
const int keys[numKeys] = {2, 3, 4, 5, 6, 7, 8, 9}; // 每个按键连接到的Arduino引脚
// 音符频率数组
const int noteFreq[numKeys] = {262, 294, 330, 349, 392, 440, 494, 523}; // 对应每个按键的音符频率
const int buzzerPin = 10; // 蜂鸣器连接的引脚
const int ledPin = 13; // 用于指示录音状态的LED连接的引脚
const int recordButtonPin = 11; // 录音按钮连接的引脚
const int playButtonPin = 12; // 播放按钮连接的引脚
// 录音和回放相关变量
int recordedNotes[50]; // 最多记录50个音符
int recordedCount = 0; // 记录的音符数量
bool recording = false; // 是否正在录音
void setup() {
pinMode(buzzerPin, OUTPUT);
pinMode(ledPin, OUTPUT);
pinMode(recordButtonPin, INPUT);
pinMode(playButtonPin, INPUT);
// 初始化LCD显示屏(如果有)
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Electronic Piano");
}
void loop() {
// 检测录音按钮状态
if (digitalRead(recordButtonPin) == HIGH) {
delay(50); // 延时去抖动
toggleRecording(); // 切换录音状态
while (digitalRead(recordButtonPin) == HIGH) {} // 等待按钮释放
}
// 检测播放按钮状态
if (digitalRead(playButtonPin) == HIGH) {
delay(50); // 延时去抖动
playbackRecordedNotes(); // 播放录音
while (digitalRead(playButtonPin) == HIGH) {} // 等待按钮释放
}
// 检测每个按键状态
for (int i = 0; i < numKeys; i++) {
if (digitalRead(keys[i]) == HIGH) { // 按钮按下
keyPressed(i);
// 如果正在录音,记录音符
if (recording) {
recordNote(i);
}
delay(100); // 延时避免重复触发
}
}
}
// 播放音符函数
void playNote(int noteIndex) {
tone(buzzerPin, noteFreq[noteIndex], 200); // 在引脚10上播放音符,持续时间200毫秒
}
// 记录音符函数
void recordNote(int noteIndex) {
if (recordedCount < 50) { // 限制最多记录50个音符
recordedNotes[recordedCount++] = noteIndex;
digitalWrite(ledPin, HIGH); // 点亮录音指示灯
}
}
// 开始/停止录音函数
void toggleRecording() {
recording = !recording;
if (!recording) {
digitalWrite(ledPin, LOW); // 关闭录音指示灯
}
}
// 回放录音函数
void playbackRecordedNotes() {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Playback...");
for (int i = 0; i < recordedCount; i++) {
playNote(recordedNotes[i]);
delay(300); // 每个音符之间的间隔300毫秒
}
delay(1000); // 播放结束后等待1秒
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Electronic Piano");
}
// 按钮按下时的处理函数
void keyPressed(int keyIndex) {
lcd.setCursor(0, 1);
lcd.print("Key pressed: ");
lcd.print(keyIndex + 1);
playNote(keyIndex); // 播放音符
if (recording) {
recordNote(keyIndex); // 如果正在录音,记录音符
}
}