#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
const int S0 = 2, S1 = 3, S2 = 4, S3 = 5;
const int SIG_PIN = 6;
const int BUZZER_PIN = 9;
// Added one more note for the 16th button!
int tones[] = {262, 294, 330, 349, 392, 440, 494, 523, 587, 659, 698, 784, 880, 988, 1047, 1109};
String noteNames[] = {"Do3", "Re3", "Mi3", "Fa3", "Sol3", "La3", "Si3", "Do4", "Re4", "Mi4", "Fa4", "Sol4", "La4", "Si4", "Do5", "Re5"};
int stableNote = -1;
//int readCount = 0;
const int STABLE_READS = 5;
void setup() {
lcd.init();
lcd.backlight();
pinMode(S0, OUTPUT);
pinMode(S1, OUTPUT);
pinMode(S2, OUTPUT);
pinMode(S3, OUTPUT);
pinMode(SIG_PIN, INPUT_PULLUP);
pinMode(BUZZER_PIN, OUTPUT);
noTone(BUZZER_PIN);
lcd.setCursor(0, 0);
lcd.print(" Piano Ready! ");
lcd.setCursor(0, 1);
lcd.print(" Press a key ");
}
int scanButtons() {
// Changed from 15 to 16!
for (int i = 0; i < 16; i++) {
digitalWrite(S0, bitRead(i, 0));
digitalWrite(S1, bitRead(i, 1));
digitalWrite(S2, bitRead(i, 2));
digitalWrite(S3, bitRead(i, 3));
delay(1);
if (digitalRead(SIG_PIN) == LOW) {
return i;
}
}
return -1;
}
void loop() {
int detectedNote = scanButtons();
// Count stable readings
static int lastDetected = -1;
static int sameCount = 0;
if (detectedNote == lastDetected) {
sameCount++;
} else {
sameCount = 0;
lastDetected = detectedNote;
}
// Only change state after STABLE_READS consecutive identical readings
if (sameCount >= STABLE_READS && detectedNote != stableNote) {
if (detectedNote != -1) {
// Start note
tone(BUZZER_PIN, tones[detectedNote]);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(noteNames[detectedNote]);
lcd.print(" ");
lcd.print(tones[detectedNote]);
lcd.print("Hz");
lcd.setCursor(0, 1);
lcd.print("BIN:");
for (int b = 3; b >= 0; b--) {
lcd.print(bitRead(detectedNote, b));
}
lcd.print(" CH:");
lcd.print(detectedNote);
} else {
// Stop note
noTone(BUZZER_PIN);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(" Piano Ready! ");
lcd.setCursor(0, 1);
lcd.print(" Press a key ");
}
stableNote = detectedNote;
}
delay(5);
}DO
RE
MI
FA
SOL
LA
SI
DO
RE
MI
FA
SOL
LA
SI
DO