Buzzer tutorial using Arduino | play Birthday tone

Mr.ElectroUino
9


In this tutorial, we have to control buzzer using an Arduino board 
 and play birthday tone.
 A Buzzer or beeper is used for produces sound. Uses of buzzer include security, alarm devices, and mouse click or keystroke sound. We need Arduino to control a frequency of buzzer and produces different sound to change frequency and duration.

Control a buzzer using Arduino uno.

Requirement:-
       1.     Arduino Uno.
       2.     Active Buzzer.
       3.     Breadboard.
       4.     Jumper wire.

Circuit:-












Steps:-

1.     Piezo buzzer having 2 pin, negative and positive.
2.     Connect a jumper wire from positive pin of buzzer to Arduino pin 8.
3.     Then connect a jumper wire from negative pin of buzzer to Arduino GND pin.
4.     Upload the code…..
5.     Keep practices, to change frequency and duration to create a musical tone.

Code:-

int buzzer = 8;
void setup() 
{
    // put your setup code here, to run once:
    pinMode(buzzer, OUTPUT);//sets the digital pin as OUTPUT
}

void loop() 
{  
// put your main code here, to run repeatedly:
  //creating a more notes by changing frequency AND duration

int notes[10]={234,324,432,543,232,267,876,368,123,980}; //an array having different frequency

for(int i = 0; i< 10; i++)
{
    tone(buzzer, notes[i]);
    delay(1000);
  }
    noTone(buzzer);// stops tone
    delay(1000);
}



Control a 3 LEDs, buzzer, and button using Arduino uno and playing birthday tone.

Requirement:-
      1.     Arduino Uno.
      2.     Active Buzzer.
      3.     1 x 220 ohms Resistor. 
      4.     1 x 10k ohms Resistor.
      5.     3 x LEDs 5mm.
      6.     Push button.
      7.     Breadboard.
      8.     Jumper wire.



Circuit:-



Steps:-

1.    Piezo buzzer having 2 pin, negative and positive.
2.    Connect a jumper wire from positive pin of buzzer to Arduino pin 2.
3.    Then connect a jumper wire from negative pin of buzzer to Arduino GND pin.
4.    Attach a 220 ohms resistor to the positive pin (anode) of all LEDs and at the end of the resistor is connected to Arduino digital pin 5, 6 and 7 respectively.


 5.  Connecting Button pin 4 to Arduino pin 5v using a jumper wire.
6.    Attach a 10k ohms resistor to button pin 2 and at the end of the resistor is connected to Arduino pin GND.
7.   Button pin 1 is connected to Arduino digital pin 4 using a jumper wire.
8.    Now circuit is readyyy…….. enjoy it…..

Note:-If you need different tone like birthday tone, then comment it.

Code: -

//constant will be not change
const int speakerPin = 2;
const int led1 = 5;
const int led2 = 6;
const int led3 = 7;
const int button = 12;

int buttonState = 0;
int length = 28; // the number of notes

char notes[] = "GGAGcB GGAGdc GGxecBA yyecdc";
int beats[] = { 2, 2, 8, 8, 8, 16, 1, 2, 2, 8, 8,8, 16, 1, 2,2,8,8,8,8,16, 1,2,2,8,8,8,16 };
int tempo = 150;

void playTone(int tone, int duration)
{
    for (long i = 0; i < duration * 1000L; i += tone * 2) 
       {   
           digitalWrite(speakerPin, HIGH);
           delayMicroseconds(tone);
           digitalWrite(speakerPin, LOW);
           delayMicroseconds(tone);
        }
   }
void playNote(char note, int duration) {
char names[] = {'C', 'D', 'E', 'F', 'G', 'A', 'B',          
                 'c', 'd', 'e', 'f', 'g', 'a', 'b',
                 'x', 'y' };

int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014,
                 956,  834,  765,  593,  468,  346,  224,
                655 , 715 };

int SPEE = 5;

// play the tone corresponding to the note name

for (int i = 0; i < 17; i++) 
{
   if (names[i] == note) 
    {
         int newduration = duration/SPEE;
         playTone(tones[i], newduration);
    }
}
}
void setup() {

pinMode(button, INPUT); //sets a pin as a input
pinMode(speakerPin, OUTPUT);////sets a pin as a Output
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
}
void loop() {
  buttonState = digitalRead(button);

 if (buttonState == HIGH)
  {
 for(int k =0; k< 2; k++ )
{
    digitalWrite(led1, HIGH);
    digitalWrite(led2, HIGH);
    digitalWrite(led3, HIGH);

for (int i = 0; i < length; i++) 
{
   if (notes[i] == ' ') {
     delay(beats[i] * tempo); // rest
   } 
else 
{
     playNote(notes[i], beats[i] * tempo);
 }
   // pause between notes
    delay(tempo);
}
}
}
else
 {
    // turn LED off:
    noTone(speakerPin);
    digitalWrite(led1, LOW);
    digitalWrite(led2, LOW);
    digitalWrite(led3, LOW);
  }
}

Watch this................Tutorail.

Post a Comment

9Comments

  1. please help me!
    Write the Arduino sketch with the following functionality:
    When the Arduino is powered up, the red LED
    connected to pin 9 will be turned on. When the pushbutton
    connected to pin 2 is pressed, the green LED connected to
    pin 10 will be turned on and the red LED will be turned off.
    There will be a message in the Serial Monitor tool “Let’s listen
    to the melody.”, and the melody will be played. The piezo
    buzzer must be connected to pin 8. Pressing the pushbutton
    repeatedly while the melody is playing will have no effect
    unless it has finished playing.
    After the melody is finished playing, the green LED will be
    turned off, the red LED will be turned on again, and there
    will be a message in the next line after the first message in
    the Serial Monitor tool “Hope you enjoy!”. If the pushbutton
    is pressed again, the melody will be played again.
    Use the following specifications in your sketch:

    int melody[] = {_E6, _D6, _C6, _D6, _E6, _E6, _E6, _D6, _D6,
    _D6, _E6, _E6, _E6, _E6, _D6, _C6, _D6, _E6,
    _E6, _E6, _C6, _D6, _D6, _E6, _D6, _C6};
    int noteDurations[] = {4, 4, 4, 4, 4, 4, 2, 4, 4, 2, 4, 4, 2, 4, 4, 4,

    4, 4, 4, 4, 4, 4, 4, 4, 4, 1};

    ReplyDelete
  2. if (notes[i] == ' ') {
    I got error in this line... What to do

    ReplyDelete
    Replies
    1. ⚠️ ERRORES DETECTADOS
      1. ❌ Palabras clave incorrectas (traducciones mal hechas)
      constante int → debe ser const int

      notas de carácter[] → debe ser char notas[]

      para → debe ser for

      ALTO y BAJO → deben ser HIGH y LOW

      configuración vacía() → debe ser void setup()

      bucle vacío() → debe ser void loop()

      retardo() → debe ser delay()

      nombres de caracteres[] → debe ser char nombres[]

      longitud mal escrita, debe ser length

      tiempos[] y ritmos[] no coinciden, mezcla de nombres

      2. ❌ Variable mal definida
      pin del altavoz no debe tener espacios, debe ser speakerPin

      3. ❌ Mal uso de arrays y nombres
      Usas notas[], beats[], tiempos[], ritmos[] sin consistencia.

      ✅ CÓDIGO CORREGIDO Y FUNCIONAL (SONIDO + 3 LEDs + BOTÓN)
      Este código reproduce una melodía al presionar un botón, y enciende 3 LEDs mientras suena la música:

      cpp
      Copiar
      Editar
      // Pines
      const int speakerPin = 2;
      const int led1 = 5;
      const int led2 = 6;
      const int led3 = 7;
      const int boton = 12;

      int buttonState = 0;
      int length = 28;
      int tempo = 150;

      // Notas musicales (melodía)
      char notas[] = "GGAGcB GGAGdc GGxecBA yyecdc";
      int ritmos[] = {2,2,8,8,8,16, 1,2,2,8,8,8,16, 1,2,2,8,8,8,8,16, 1,2,2,8,8,8,16};

      void playTone(int toneVal, int duration) {
      for (long i = 0; i < duration * 1000L; i += toneVal * 2) {
      digitalWrite(speakerPin, HIGH);
      delayMicroseconds(toneVal);
      digitalWrite(speakerPin, LOW);
      delayMicroseconds(toneVal);
      }
      }

      void playNote(char note, int duration) {
      char names[] = {'C', 'D', 'E', 'F', 'G', 'A', 'B',
      'c', 'd', 'e', 'f', 'g', 'a', 'b',
      'x', 'y'};

      int tones[] = {1915,1700,1519,1432,1275,1136,1014,
      956,834,765,593,468,346,224,
      655,715};

      int SPEE = 5;

      for (int i = 0; i < 17; i++) {
      if (names[i] == note) {
      int newduration = duration / SPEE;
      playTone(tones[i], newduration);
      }
      }
      }

      void setup() {
      pinMode(boton, INPUT);
      pinMode(speakerPin, OUTPUT);
      pinMode(led1, OUTPUT);
      pinMode(led2, OUTPUT);
      pinMode(led3, OUTPUT);
      }

      void loop() {
      buttonState = digitalRead(boton);

      if (buttonState == HIGH) {
      // Encender LEDs
      digitalWrite(led1, HIGH);
      digitalWrite(led2, HIGH);
      digitalWrite(led3, HIGH);

      // Reproducir la melodía 2 veces
      for (int k = 0; k < 2; k++) {
      for (int i = 0; i < length; i++) {
      if (notas[i] == ' ') {
      delay(ritmos[i] * tempo); // silencio
      } else {
      playNote(notas[i], ritmos[i] * tempo);
      }
      delay(tempo); // pausa entre notas
      }
      }
      } else {
      // Apagar LEDs y buzzer
      noTone(speakerPin);
      digitalWrite(led1, LOW);
      digitalWrite(led2, LOW);
      digitalWrite(led3, LOW);
      }
      }

      Delete
    2. ✅ FUNCIONAMIENTO DEL CÓDIGO
      Al presionar el botón (pin 12):

      Se encienden los 3 LEDs (en pines 5, 6 y 7).

      El buzzer (pin 2) reproduce una melodía compuesta por una secuencia de notas (notas[]) con ritmos (ritmos[]).

      La melodía se reproduce 2 veces.

      Cuando el botón no está presionado:

      Los LEDs se apagan.

      El buzzer se apaga con noTone().

      🛠 SUGERENCIAS
      Usa resistencias de 220 ohmios en serie con los LEDs.

      El buzzer debe ser activo, si usas uno pasivo, considera tone() en vez de digitalWrite().

      Puedes agregar un display LCD para mostrar la nota que suena.

      Delete
    3. 🔧 PASO A PASO DE CONEXIONES — SIN ERRORES
      🧠 Resumen de pines usados en el código:
      Elemento Pin Arduino Descripción lógica
      Buzzer D2 Emite tonos musicales
      LED1 D5 LED encendido al presionar
      LED2 D6 LED encendido al presionar
      LED3 D7 LED encendido al presionar
      Botón D12 Entrada digital para activar

      🔌 1. CONEXIÓN DEL BUZZER (ALTAVOZ ACTIVO)
      Pin Buzzer Conexión
      Positivo (+) Pin D2 de Arduino
      Negativo (–) GND de Arduino

      🔧 Nota: Si usas buzzer pasivo, deberías usar tone() y noTone() como en el código.

      🔴 2. CONEXIÓN DE LOS LEDS
      Conecta una resistencia de 220 ohmios en serie con cada LED.

      LED1 (Rojo):
      Pin LED Conexión
      Ánodo (+) Pin D5 de Arduino
      Cátodo (–) A GND con resistencia de 220 Ω

      LED2 (Amarillo, por ejemplo):
      | Ánodo (+) | Pin D6 |
      | Cátodo (–) | GND con resistencia |

      LED3 (Verde, por ejemplo):
      | Ánodo (+) | Pin D7 |
      | Cátodo (–) | GND con resistencia |

      🔘 3. CONEXIÓN DEL BOTÓN
      ➤ Botón de 2 pines (común):
      Terminal botón Conexión
      Un lado Pin D12 de Arduino
      Otro lado GND de Arduino

      ➤ Opcional: usar resistencia pull-down de 10kΩ entre pin 12 y GND para evitar falsos pulsos.
      🧪 Verificación rápida de pines según código:
      cpp
      Copiar
      Editar
      const int speakerPin = 2;
      const int led1 = 5;
      const int led2 = 6;
      const int led3 = 7;
      const int boton = 12;
      ✅ Coinciden con las conexiones descritas.

      ⚙️ FUNCIONAMIENTO GENERAL DEL CIRCUITO
      El Arduino inicia y configura los pines.

      Al presionar el botón (pin D12 en HIGH):

      Se encienden los 3 LEDs (D5, D6, D7).

      El buzzer conectado al pin D2 emite una melodía (notas musicales).

      Cuando el botón se suelta:

      Se apagan los LEDs.

      El buzzer se silencia (noTone()).

      🧩 EJEMPLO DE DIAGRAMA FÍSICO (RESUMIDO)
      mathematica
      Copiar
      Editar
      [Arduino UNO]

      D2 → (+) Buzzer | (–) Buzzer → GND
      D5 → Ánodo LED1 | Cátodo → 220Ω → GND
      D6 → Ánodo LED2 | Cátodo → 220Ω → GND
      D7 → Ánodo LED3 | Cátodo → 220Ω → GND
      D12 → 1 pin del botón| Otro pin → GND

      +5V (opcional si quieres alimentar desde protoboard)
      GND → protoboard común 🧠 ¿QUÉ ES UNA RESISTENCIA PULL-DOWN?
      Una resistencia pull-down es una resistencia que se conecta entre el pin de entrada digital de un microcontrolador (como Arduino) y GND (tierra), para garantizar que el pin lea un valor LOW (0 lógico) cuando no hay señal activa conectada.

      🧲 ¿PARA QUÉ SE USA?
      ✅ Evita "lecturas flotantes":
      Cuando no presionas el botón, el pin de entrada queda "flotando", es decir, sin voltaje definido. Esto provoca que el Arduino lea valores aleatorios (ruido) o cambie de estado inesperadamente.

      La resistencia pull-down fuerza el pin a estar en LOW (0) cuando el botón no está presionado, garantizando estabilidad.

      🔄 COMPARACIÓN: SIN vs CON PULL-DOWN
      🔴 SIN PULL-DOWN
      Botón suelto → pin flota → puede leer HIGH o LOW al azar.

      Provoca comportamiento errático o falso.

      ✅ CON PULL-DOWN
      Botón suelto → pin conectado a GND a través de la resistencia → siempre LOW estable.

      Botón presionado → pin se conecta a 5V → HIGH confiable.

      ⚙️ CÓMO SE CONECTA EN TU CIRCUITO (CASO BOTÓN)
      🔘 Componentes:
      Botón de 2 patas

      Resistencia de 10kΩ (valor típico)

      🔌 Conexiones:
      Pin botón Conexión
      1 Pin D12 de Arduino
      2 A +5V directo
      Pin D12 También a resistencia de 10kΩ → GND

      📌 Así, cuando el botón no está presionado, el pin D12 queda conectado a GND a través de la resistencia → se lee como LOW.

      Cuando se presiona, el pin D12 se conecta directamente a 5V → se lee como HIGH.

      Delete
Post a Comment