// Define note frequencies (using the #define statements you provided)
#define NOTE_C4 262
#define NOTE_D4 294
#define NOTE_E4 330
#define NOTE_F4 349
#define NOTE_G4 392
#define NOTE_A4 440
#define NOTE_B4 494
#define NOTE_C5 523
#define NOTE_D5 587
// Pin where the piezo buzzer is connected
const int piezoPin = 11;
int tempo = 100; // Tempo of the song
// Define melody: notes followed by their duration (1 = whole note, 2 = half note, etc.)
int melody[] = {
NOTE_C4, 4, // Do (C4)
NOTE_D4, 4, // Re (D4)
NOTE_E4, 4, // Mi (E4)
NOTE_F4, 4, // Fa (F4)
NOTE_G4, 4, // Sol (G4)
NOTE_A4, 4, // La (A4)
NOTE_B4, 4, // Ti (B4)
NOTE_C5, 4, // High Do (C5)
};
// Calculate the duration of a whole note in ms
int wholenote = (60000 * 4) / tempo;
void setup() {
Serial.begin(9600); // Start serial communication at 9600 baud
}
void loop() {
if (Serial.available() > 0) {
char note = Serial.read(); // Read the input from the serial monitor
// Calculate the index in the melody array based on the input
int index = (note - '1') * 2; // Since each note has a frequency and duration
// Check if the input is valid (1-9)
if (index >= 0 && index < sizeof(melody) / sizeof(melody[0])) {
int frequency = melody[index]; // Get the frequency
int duration = melody[index + 1]; // Get the duration
// Calculate the note duration based on the tempo
int noteDuration = (wholenote) / duration;
// Play the note using tone() for the calculated duration
tone(piezoPin, frequency, noteDuration * 0.9); // 90% of the duration is used for the note
delay(noteDuration); // Wait for the note to finish
noTone(piezoPin); // Stop the tone after the note is played
}
}
}