#include "pitches.h"
// 程序包含了一个名为 pitches.h 的头文件,该文件定义了不同音符的频率。
#define SPEAKER_PIN 8
//将数字引脚8定义为连接扬声器的引脚
const uint8_t buttonPins[] = { 12, 11, 10, 9, 7, 6, 5, 4 };
const int buttonTones[] = {
NOTE_C4, NOTE_D4, NOTE_E4, NOTE_F4,
NOTE_G4, NOTE_A4, NOTE_B4, NOTE_C5
};
const int numTones = sizeof(buttonPins) / sizeof(buttonPins[0]);
void setup() {
for (uint8_t i = 0; i < numTones; i++) {
pinMode(buttonPins[i], INPUT_PULLUP); //将其设置为输入模式,并启用内部上拉电阻。
}
pinMode(SPEAKER_PIN, OUTPUT);
}
void loop() {
int pitch = 0;
for (uint8_t i = 0; i < numTones; i++) {
if (digitalRead(buttonPins[i]) == LOW) {
pitch = buttonTones[i];
}
}
if (pitch) {
tone(SPEAKER_PIN, pitch);
// tone() 是一个内置的函数,用于在指定的引脚上产生一个方波信号,从而发出声音。
//函数的语法为:tone(pin, frequency)
} else {
noTone(SPEAKER_PIN);
}
}