Posted on 3 Comments

Buzzer on Raspberry Pi playing a melody

raspberry pi buzzer melody

In this tutorial we learn how a buzzer can play music notes. See how easy it is to play a basic melody with a Python script running on your Raspberry Pi. When you have completed this tutorial, you will be able to generate different tones with a buzzer. You will also have the Python code to let your buzzer play a basic melody.

Prepare your Pi

First, you need to have a Raspberry Pi running on the latest version of Raspberry Pi OS. This version includes “Thonny”. We’ll use this user-friendly IDE to write our Python code. If you’re not familiar with Python or with Thonny or GPIO-pins, I suggest to have a look at our tutorials “How to write your first Python program on the Raspberry Pi” and/or “How to use the Raspberry Pi GPIO pins” to have a quick introduction. For a basic understanding about the active buzzer and how to connect it to your Pi, have a look at our tutorial “Buzzer on Raspberry Pi generating beeps”.

Prepare the extra hardware

Next, you’ll need some extra hardware:

  • a breadboard (we are using a 400 points breadboard)
  • a 5V active buzzer
  • Dupont jumper wires
  • NPN transistor
  • a T-cobbler (optional)
  • a 40 pin GPIO cable (optional)

If you miss any hardware, don’t hesitate to visit our shop. We have a nice kit which contains all the things you need tot start. Raspberry Pi GPIO kit

About music notes

music notes buzzer

In Wikipedia we can learn that a music note is the pitch and duration of a sound. Each pitch is an element of a pitch class and has a well defined frequency. This frequency can be calculated. But we won’t handle these topics in this tutorial. We just keep in mind we need the frequency and the duration for each note we want to play on the buzzer. We’ll use these two elements in our script

For more information on music notes, visit this Wikipedia page.

For the frequencies of the pitches, have a look at this tuning table.

Set up the hardware part

Be careful ! Before starting to connect wires on the GPIO pins of your Raspberry Pi, make sure you properly shut down the Pi and removed the power cable from the board!

We use the same hardware configuration as the one we used in our tutorial “Buzzer on Raspberry Pi generating beeps”.

Raspberry Pi active buzzer transistor
  • connect the 40 pin cable on the GPIO pins of your Pi (if necessary, remove the cover of your Pi first)
  • plug the cobbler onto the breadboard as shown in the figure above or below
  • plug the other end of the 40 pin cable in the T-cobbler
  • place the buzzer on the breadboard, the long leg is the positive leg, make sure to place it near the border of the breadboard
  • place the NPN transistor: on our image, the current flows from the right pin (3) to left pin (1), the middle pin (2) is the gate.
  • connect transistor pin (3) to a 5V pin of the Pi (red wire)
  • connect transistor pin (2) to pin 23 (yellow wire)
  • make sure the long leg (+) of the buzzer is placed in the same breadboard row as transistor pin (1)
  • connect the short leg (-) of the buzzer to a GPIO GND pin (black wire)
Raspberry Pi active buzzer transistor

Write the code

The aim of this tutorial is to write a simple Python script that allows the buzzer to play a simple melody. To write the code, we use the Thonny IDE. You can find Thonny under the application menu of your Raspberry Pi.

Write or paste following code in the IDE:

import RPi.GPIO as GPIO
import time
def buzz(noteFreq, duration):
    halveWaveTime = 1 / (noteFreq * 2 )
    waves = int(duration * noteFreq)
    for i in range(waves):
       GPIO.output(BUZZER, True)
       GPIO.output(BUZZER, False)
def play():
    for n in notes:
        buzz(n, duration[t])
        time.sleep(duration[t] *0.1)
#buzz(262, 0.5)

Some explanations about the code:

  • GPIO.setmode(GPIO.BCM): The GPIO.BCM option means that we are referring to the pins by the “Broadcom SOC channel” number, these are the numbers after “GPIO”
  • GPIO.setwarnings(False): We use this line of code to avoid warning messages in the case we don’t end the GPIO connection properly while interrupting the program
  • GPIO.setup(BUZZER, GPIO.OUT): We define the BUZZER pin (=23) as an output pin
  • def buzz(noteFreq, duration): Here we define the “buzz” function with the arguments “noteFreq” and “duration”
  • Be careful, Python is whitespace-sensitive. Don’t remove the “tab” before the next lines of code
  • halveWaveTime = 1 / (noteFreq * 2 ): Calculating the time for halve of the wave of the given frequency
  • int(duration * noteFreq): Calculating the amount of waves to buzz
  • for i in range(waves):: A loop that will iterate until the number of waves has been reached
  • def play():: Defining the “play” function
  • notes=[…]: An array with all the frequencies of the music notes to play (Hz)
  • duration=[…]: An array with all the durations of the music notes to play (seconds)
  • for n in notes:: What follows will be repeated for each element of the array “notes”
  • buzz(n, duration[t]): Calling the “buzz” function with the elements of both arrays
  • time.sleep(duration[t] *0.1): Wait a short moment between playing each music note
  • #buzz(262, 0.5): This line has been commented. Uncomment to just play one music note
  • play(): By calling the “play” function, the melody will be played.

Run the Python script

Before running the program you’ll have to give it a name and save it.

raspberry pi python script buzzer melody

Once saved, click on the Run button. You will hear a well-known melody.

Congratulations! With this setup you can now play a melody with a simple active buzzer on your Raspberry Pi. Feel free to change or add the “notes” and “duration” arrays for different melodies. Have fun with it!

How useful was this post?

Click on a star to rate it!

Average rating 4.1 / 5. Vote count: 7

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

3 thoughts on “Buzzer on Raspberry Pi playing a melody

  1. I copied and pasted the code and checked, to be right.
    When I run the code, no output sound from the buzzer is coming.
    The only thing I did not do is, the npn transister is not connected.
    I did the connection as the one with out transistor.
    The beep code works fine with this connection.
    IS the transister, a must or optional ?

    1. It is very likely you use a 5V-buzzer. So, to be able to get the buzzer working properly, you will need 5V. As the GPIO I/O-pins voltage is 3.3V, it is necessary to work with a transistor for this project.

  2. Very nice and clear example for the code, it works.

    BTW: we just connect one passive buzzer to one GPIO pin (One GND), no extra transistor needed for exercise.

Leave a Reply

Your email address will not be published. Required fields are marked *

How useful was this post?

Click on a star to rate it!

Average rating 4.1 / 5. Vote count: 7

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

find out more products

Be the first to be informed about our latest tutorials and products by subscribing to our Newsletter respects your privacy. Read our privacy policy on how we handle your personal information.