/*
Arduino Mini Piano
https://gist.github.com/mikeputnam/2820675
*/
#include "pitches.h"
const int NUM_BTNS = 8;
const int BTN_PINS[] = {10, 9, 8, 7, 6, 5, 4, 3};
const int BUZZ_PIN = 2;
// globals to hold button states
int btnState[NUM_BTNS];
int oldBtnState[NUM_BTNS];
// function returns which button was pressed, 0 if none, -1 if released
int checkButtons() {
int btnPressed = 0;
for (int i = 0; i < NUM_BTNS; i++) {
// check each button
btnState[i] = digitalRead(BTN_PINS[i]);
if (btnState[i] != oldBtnState[i]) { // if it changed
oldBtnState[i] = btnState[i]; // remember state for next time
if (btnState[i] == LOW) { // was just pressed
btnPressed = i + 1;
Serial.print("Button ");
Serial.print(btnPressed);
Serial.println(" pressed");
} else { // was just released
btnPressed = -1;
//Serial.print("Button ");
//Serial.print(btnPressed);
//Serial.println(" released");
}
delay(20); // debounce
}
}
return btnPressed;
}
void setup() {
Serial.begin(115200);
for (int i = 0; i < NUM_BTNS; i++) {
pinMode(BTN_PINS[i], INPUT_PULLUP);
}
pinMode(BUZZ_PIN, OUTPUT);
}
void loop() {
int btnNumber = checkButtons();
if (btnNumber) {
if (btnNumber == 1) {
tone(BUZZ_PIN, NOTE_C4);
} else if (btnNumber == 2) {
tone(BUZZ_PIN, NOTE_D4);
} else if (btnNumber == 3) {
tone(BUZZ_PIN, NOTE_E4);
} else if (btnNumber == 4) {
tone(BUZZ_PIN, NOTE_F4);
} else if (btnNumber == 5) {
tone(BUZZ_PIN, NOTE_G4);
} else if (btnNumber == 6) {
tone(BUZZ_PIN, NOTE_A4);
} else if (btnNumber == 7) {
tone(BUZZ_PIN, NOTE_B4);
} else if (btnNumber == 8) {
tone(BUZZ_PIN, NOTE_C5);
} else if (btnNumber == -1) {
noTone(BUZZ_PIN);
}
}
}