/**
Mini piano for Arduino.
You can control the colorful buttons with your keyboard:
After starting the simulation, click anywhere in the diagram to focus it.
Then press any key between 1 and 8 to play the piano (1 is the lowest note,
8 is the highest).
Copyright (C) 2021, Uri Shaked. Released under the MIT License.
*/
/* 这段程序是一个基于 Arduino 的音乐播放器。
它通过按下按钮来选择音调,并通过蜂鸣器播放指定的乐曲《大海》。
*/
#include "pitches.h" // 引入共享的音调定义文件
#define SPEAKER_PIN 8 // 定义蜂鸣器连接的引脚
#define SWITCH_PIN 3 // 定义开关连接的引脚
const uint8_t buttonPins[] = { 12, 11, 10, 9, 7, 6, 5, 4 }; // 定义琴键连接的引脚数组
const int buttonTones[] = {
NOTE_C4, NOTE_D4, NOTE_E4, NOTE_F4, NOTE_G5, NOTE_A5, NOTE_B4, NOTE_C5
}; // 定义琴键对应的音调数组
const int numTones = sizeof(buttonPins) / sizeof(buttonPins[0]); // 计算琴键数量
// 定义乐曲《大海》的音符名称数组
const char* notes[] = {
"C4", "E4", "G4", "E4", "C4", "E4", "G4", "E4",
"C4", "E4", "G4", "F4", "E4", "F4", "G4",
"C5", "A4", "G4", "F4", "E4", "D4", "E4", "F4", "G4", "A4",
"C5", "A4", "G4", "F4", "E4", "D4", "E4", "F4", "G4", "A4",
"G4", "E4", "C4", "D4", "E4", "F4", "G4",
"G4", "E4", "C4", "D4", "E4", "F4", "G4"
};
// 定义乐曲《大海》的音调数组
const int tones[] = {
262, 330, 392, 330, 262, 330, 392, 330,
262, 330, 392, 349, 330, 349, 392,
523, 440, 392, 349, 330, 294, 330, 349, 392, 440,
523, 440, 392, 349, 330, 294, 330, 349, 392, 440,
392, 330, 262, 294, 330, 349, 392,
392, 330, 262, 294, 330, 349, 392
};
// 定义乐曲《大海》的每个音符的时长数组(以毫秒为单位)
const int durations[] = {
300, 300, 300, 300, 300, 300, 300, 300,
300, 300, 300, 300, 300, 300, 600,
300, 300, 300, 300, 300, 300, 300, 300, 300, 600,
300, 300, 300, 300, 300, 300, 300, 300, 300, 600,
300, 300, 300, 300, 300, 300, 600,
300, 300, 300, 300, 300, 300, 600
};
bool musicPlaying = true; // 音乐播放状态
void setup() {
for (uint8_t i = 0; i < numTones; i++) {
pinMode(buttonPins[i], INPUT_PULLUP); // 将琴键引脚设置为输入模式,使用内部上拉电阻
}
pinMode(SPEAKER_PIN, OUTPUT); // 将蜂鸣器引脚设置为输出模式
pinMode(SWITCH_PIN, INPUT_PULLUP); // 将开关引脚设置为输入模式,使用内部上拉电阻
}
void loop() {
int pitch = 0;
// 检测开关按钮是否按下,控制音乐的播放与停止
if (digitalRead(SWITCH_PIN) == LOW) {
musicPlaying = !musicPlaying; // 切换音乐播放状态
delay(200); // 延迟一段时间防止按键抖动
}
if (musicPlaying) {
for (uint8_t i = 0; i < numTones; i++) {
if (digitalRead(buttonPins[i]) == LOW) { // 检测是否有琴键按钮按下
pitch = buttonTones[i]; // 获取对应的音调值
}
}
if (pitch) {
tone(SPEAKER_PIN, pitch); // 播放所选音调
} else {
noTone(SPEAKER_PIN); // 停止播放音调
}
// 播放乐曲《大海》
for (int i = 0; i < sizeof(notes) / sizeof(notes[0]); i++) {
tone(SPEAKER_PIN, tones[i], durations[i]); // 播放当前音符及其时长
delay(durations[i] + 50); // 延迟一段时间后播放下一个音符
}
} else {
noTone(SPEAKER_PIN); // 停止播放音调
}
}