/**
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]);
const int melody[] = {NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4};
const int durations[] = {500,125,125,250,250,250,250,250};
int index;
void setup() {
for (uint8_t i = 0; i < numTones; i++) {
pinMode(buttonPins[i], INPUT_PULLUP);
}
pinMode(SPEAKER_PIN, OUTPUT);
Serial.begin(115200);
}
void loop() {
int pitch = 0;
for (uint8_t i = 0; i < numTones; i++) {
if (digitalRead(buttonPins[i]) == LOW) {
pitch = buttonTones[i];
}
}
if (pitch == NOTE_C4) {
Serial,println("button 0 pushed")
for (int j = 0; j<8; j++) {
tone(SPEAKER_PIN, pitch, melody[j], durations [j]);
delay(200);
}
}else if (pitch == NOTE_D4) {
Serial,println("button 0 pushed")
for (int k = 7; k>= 0; j--) {
tone(SPEAKER_PIN, pitch, melody[k], durations [k]);
delay(250);
}
if (pitch == NOTE_E4) {
Serial,println("button 0 pushed")
for (int i2 = 0; i2<8; 12++) {
index = random(0,8);
tone(SPEAKER_PIN, pitch, melody[j], durations [j]);
delay(250);
}
} else if (pitch) {
tone(SPEAKER_PIN, pitch)
} else{
noTone(SPEAKER_PIN);
}
}