Ejemplo 1: Happy Birthday melody
Teniendo en cuenta que en unos días es el Cumple del que escribe os dejamos una versión del ejemplo 3 del control del «buzzer». Afortunadamente no utiliza librería alguna por lo tras la instalación de la versión correcta de ESP32 … tu relojito empezará a cantar.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
#define BUZZER 3 // Define the buzzer pin // Notes frequencies (in Hz) #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_AS4 466 // Add A#4 (A-sharp) frequency #define NOTE_B4 494 #define NOTE_C5 523 // Happy Birthday melody int melody[] = { NOTE_C4, NOTE_C4, NOTE_D4, NOTE_C4, NOTE_F4, NOTE_E4, // Happy birthday to you NOTE_C4, NOTE_C4, NOTE_D4, NOTE_C4, NOTE_G4, NOTE_F4, // Happy birthday to you NOTE_C4, NOTE_C4, NOTE_C5, NOTE_A4, NOTE_F4, NOTE_E4, NOTE_D4, // Happy birthday dear [Name] NOTE_AS4, NOTE_AS4, NOTE_A4, NOTE_F4, NOTE_G4, NOTE_F4 // Happy birthday to you }; // Note durations: 4 = quarter note, 8 = eighth note, etc. int noteDurations[] = { 4, 8, 4, 4, 4, 2, 4, 8, 4, 4, 4, 2, 4, 8, 4, 4, 4, 8, 4, 4, 8, 4, 4, 4, 2 }; void setup() { pinMode(BUZZER, OUTPUT); // Set the buzzer pin as an output digitalWrite(BUZZER, LOW); // Ensure the buzzer is off initially } void loop() { // Play the Happy Birthday melody for (int i = 0; i < sizeof(melody) / sizeof(melody[0]); i++) { int duration = 1000 / noteDurations[i]; // Calculate the note duration tone(BUZZER, melody[i], duration); // Play the note delay(duration * 1.3); // Wait for the note to finish with a slight pause noTone(BUZZER); // Stop the tone } delay(2000); // Wait for 2 seconds before repeating the melody } |
Y aquí el resultado final… tan solo con sonido, evidentemente.
4268
