/**
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.
*/
#include "pitches.h"
#define SPEAKER_PIN 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);
}
//琴键是input_pullup 模式,for循环设置好
pinMode(SPEAKER_PIN, OUTPUT);
} //初始化函数中设置每个接口的信息模式- 输入还是输出
void loop() {
int pitch=0;//定义一个当前音调的变量 pitch
for (uint8_t i = 0; i <numTones ; i++) { //遍历所有琴键去搜索谁、哪个被摁下去(是低电平)
if (digitalRead(buttonPins[i]) == LOW){ //数字化读出当前i号接口成员的电平
pitch = buttonTones[i]; //赋值当前音调pitch为低电平的那个琴键对应的音调值(音调数组里面相应的成员);
}
}
if (pitch) {
tone(SPEAKER_PIN,pitch);
//在SPEAKER_PIN这个蜂鸣器接口上播放当前音调pitch
} else {
noTone(SPEAKER_PIN);
//pitch为空的话,就静音。
}
}