Lesson 6: ToneMelody

 

Lesson 6: ToneMelody

Lesson: ToneMelody

Objective: At the end of this lesson, you will be able to play a melody using a piezo buzzer with an Arduino board.

Materials Required:

  • Arduino board
  • Piezo buzzer
  • Jumper wires
  • USB cable

Circuit Connections:

  1. Connect the positive terminal of the piezo buzzer to digital pin 8 on the Arduino board.
  2. Connect the negative terminal of the piezo buzzer to the ground (GND) pin on the Arduino board.


Arduino Code:

#include "pitches.h"

// Melody notes
int melody[] = {
  NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};

// Note durations
int noteDurations[] = {
  4, 8, 8, 4, 4, 4, 4, 4
};

void setup() {
  // No setup required
}

void loop() {
  for (int i = 0; i < sizeof(melody) / sizeof(melody[0]); i++) {
    int noteDuration = 1000 / noteDurations[i];
    tone(8, melody[i], noteDuration);
    int pauseBetweenNotes = noteDuration * 1.30;
    delay(pauseBetweenNotes);
    noTone(8);
  }
}

Experiment Steps:

  1. Set up the circuit connections as described above.
  2. Connect the Arduino board to your computer using a USB cable.
  3. Open the Arduino IDE software and create a new sketch.
  4. Copy the provided code into the Arduino IDE.
  5. Ensure you have the "pitches.h" library installed. If not, go to "Sketch" -> "Include Library" -> "pitches" to install it.
  6. Click the "Upload" button to upload the code to the Arduino board.
  7. Listen to the melody played by the piezo buzzer.

Explanation: The Arduino code above uses the "pitches.h" library to play a melody using a piezo buzzer. The melody is represented by an array of note frequencies stored in the melody array. The corresponding note durations are stored in the noteDurations array.

Inside the loop() function, a for loop is used to iterate through each note of the melody. The tone() function is used to play each note on the piezo buzzer connected to digital pin 8. The duration of each note is calculated based on the note duration value and used as the second parameter of the tone() function. After playing a note, a pause between notes is introduced using the delay() function. Finally, the noTone() function is used to stop the piezo buzzer from playing.

By uploading the code to the Arduino board and connecting a piezo buzzer, you will be able to hear the melody being played.

Challenge: Can you modify the code to play a different melody? Try changing the notes and note durations in the melody and noteDurations arrays to create your own tune.

Here is the link to test and simulate the project

Comments

Popular Posts