#include <Arduino.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include "pitches.h"
// OLED display settings
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define OLED_RESET -1 // Reset pin (not used in this case)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
// Pin definitions for buttons and buzzer
const int buttonPins[13] = { 12, 14, 27, 26, 25, 33, 19, 18, 5, 17, 16, 4, 0 }; // Button pins for notes C4 to B4
const int buzzerPin = 13; // Pin connected to the buzzer
// Note definitions for each button
int noteFrequencies[13] = { NOTE_C4, NOTE_CS4, NOTE_D4, NOTE_DS4, NOTE_E4, NOTE_F4, NOTE_FS4, NOTE_G4, NOTE_GS4, NOTE_A4, NOTE_AS4, NOTE_B4, NOTE_C5 };
const char *noteNames[13] = { "C4", "C#4", "D4", "D#4", "E4", "F4", "F#4", "G4", "G#4", "A4", "A#4", "B4", "C5" }; // Note names for display
void setup() {
// Initialize button pins as inputs
for (int i = 0; i < 13; i++) {
pinMode(buttonPins[i], INPUT_PULLUP); // Use internal pull-up resistors
}
pinMode(buzzerPin, OUTPUT); // Initialize buzzer pin as output
// Initialize OLED display
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;); // Loop forever if allocation fails
}
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.print("Piano Ready");
display.display();
}
void loop() {
for (int i = 0; i < 13; i++) {
if (digitalRead(buttonPins[i]) == LOW) { // Check if button is pressed (active low)
tone(buzzerPin, noteFrequencies[i]); // Play the corresponding note
// Display the note name on the OLED
display.clearDisplay();
display.setCursor(0, 10);
display.setTextSize(2); // Larger text for better visibility
display.print("Playing:");
display.println();
display.setCursor(0, 30);
display.print(noteNames[i]); // Show the note name (e.g., "C4")
display.display();
delay(200); // Short delay to allow note to play
noTone(buzzerPin); // Stop the tone
// Restore "Piano Ready" message after playing the note
display.clearDisplay();
display.setTextSize(1);
display.setCursor(0, 0);
display.print("Piano Ready");
display.display();
}
}
}