#include "pitches.h"
#define SPEAKER_PIN 8
float sensorvalue;
const uint8_t buttonPins[] = { 12, 11, 10, 9, 7, 6, 5, 4 };
const int buttonTonesC[] = {
NOTE_C4, NOTE_D4, NOTE_E4, NOTE_F4,
NOTE_G4, NOTE_A4, NOTE_B4, NOTE_C5
};
const int buttonTonesG[] = {
NOTE_G4, NOTE_A4, NOTE_B4, NOTE_C5,
NOTE_D5, NOTE_E5, NOTE_FS5, NOTE_G5
};
const int numTones = sizeof(buttonPins) / sizeof(buttonPins[0]);
void setup() {
sensorvalue = 0;
for (uint8_t i = 0; i < numTones; i++) {
pinMode(buttonPins[i], INPUT_PULLUP);//输入模式,使用上拉电阻
}
pinMode(SPEAKER_PIN, OUTPUT);
}
void loop() {
int pitch = 0;
int switchstate = digitalRead(A0);
sensorvalue = digitalRead(A0);//analogRead(A0);
if (switchstate == LOW) {
for (uint8_t i = 0; i < numTones; i++) {
analogWrite(13, 0);
if (digitalRead(buttonPins[i]) == LOW) {
pitch = buttonTonesC[i];
}
}
} else {
analogWrite(13, 255);
for (uint8_t i = 0; i < numTones; i++) {
if (digitalRead(buttonPins[i]) == LOW) {
pitch = buttonTonesG[i];
}
}
}
if (pitch) {
tone(SPEAKER_PIN, pitch);
} else {
noTone(SPEAKER_PIN);
}
}