/**
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]);
int n = 1000;
int hn = n/2;
int qn = n/4;
int qnd = (int)(qn*1.5);
int en = n/8;
int enp = n/8 + 150;
int sn = n/16;
enum notes {D, E, F, G, A, B, C, Dp};
void playNote(int note, int ntype) {
tone(SPEAKER_PIN, note);
delay(ntype);
noTone(SPEAKER_PIN);
if (ntype != enp) {
delay(150);
}
}
void playSong() {
int notesheet[62] = { B, B, C, Dp,
Dp, C, B, A,
G, G, A, B,
B, A, A,
B, B, C, Dp,
Dp, C, B, A,
G, G, A, B,
A, G, G,
A, A, B, G,
A, B, C, B, G,
A, B, C, B, A,
G, A, D,
B, B, C, Dp,
Dp, C, B, A,
G, G, A, B,
A, G, G};
int noteTypes[62] = { qn, qn, qn, qn,
qn, qn, qn, qn,
qn, qn, qn, qn,
qnd, en, hn,
qn, qn, qn, qn,
qn, qn, qn, qn,
qn, qn, qn, qn,
qnd, en, hn,
qn, qn, qn, qn,
qn, enp, en, qn, qn,
qn, enp, en, qn, qn,
qn, qn, hn,
qn, qn, qn, qn,
qn, qn, qn, qn,
qn, qn, qn, qn,
qnd, en, hn};
for (int i = 0; i < 62; i++) {
Serial.println(notesheet[i]);
playNote(buttonTones[notesheet[i]], noteTypes[i]);
}
}
void setup() {
for (uint8_t i = 0; i < numTones; i++) {
pinMode(buttonPins[i], INPUT_PULLUP);
}
pinMode(SPEAKER_PIN, OUTPUT);
}
void loop() {
playSong();
delay(70000);
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);
} else {
noTone(SPEAKER_PIN);
}
}