#include "pitches.h"
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define SPEAKER_PIN 8
LiquidCrystal_I2C lcd(0x27, 20, 4);
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 maxNotes = 20;
int recordedNotes[maxNotes];
int recordedCount = 0;
void setup() {
lcd.begin(20, 4);
for (uint8_t i = 0; i < numTones; i++) {
pinMode(buttonPins[i], INPUT_PULLUP);
}
pinMode(SPEAKER_PIN, OUTPUT);
displayRecordedNotes();
}
void loop() {
int pitch = 0;
for (uint8_t i = 0; i < numTones; i++) {
if (digitalRead(buttonPins[i]) == LOW) {
pitch = buttonTones[i];
recordNote(pitch);
displayRecordedNotes();
}
}
if (pitch) {
tone(SPEAKER_PIN, pitch);
delay(250);
noTone(SPEAKER_PIN);
}
}
void recordNote(int pitch) {
if (recordedCount < maxNotes) {
recordedNotes[recordedCount++] = pitch;
} else {
for (int i = 0; i < maxNotes - 1; i++) {
recordedNotes[i] = recordedNotes[i + 1];
}
recordedNotes[maxNotes - 1] = pitch;
}
}
void displayRecordedNotes() {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Music:");
for (int i = 0; i < recordedCount; i++) {
lcd.print(" ");
switch (recordedNotes[i]) {
case NOTE_C4: lcd.print("Do"); break;
case NOTE_D4: lcd.print("Re"); break;
case NOTE_E4: lcd.print("Mi"); break;
case NOTE_F4: lcd.print("Fa"); break;
case NOTE_G4: lcd.print("So"); break;
case NOTE_A4: lcd.print("La"); break;
case NOTE_B4: lcd.print("Ti"); break;
case NOTE_C5: lcd.print("Do"); break;
default: lcd.print("Unknown");
}
}
}
void clearLCD() {
lcd.clear();
}