How to make sound with a buzzer?

Introduction

A buzzer is an electromechanical or piezoelectric component that produces a characteristic sound—a beep—when voltage is applied to it.
It consists of a diaphragm that reacts to the piezoelectric effect.

It can be controlled by the Raspberry Pi board using a square wave signal that represents the frequency of the note.

Here is the electronic schematic to connect the buzzer to the Raspberry Pi board:

Programming

For programming the buzzer, we offer you two programs: one to produce a beep, and the other to play a melody from the buzzer.

Here is the program to produce multiple beeps from the buzzer:

import RPi.GPIO as GPIO
import time

# Buzzer pin configuration
buzzer_pin = 17  # Replace with the GPIO pin number your buzzer is connected to

# Initial GPIO setup
GPIO.setmode(GPIO.BCM)
GPIO.setup(buzzer_pin, GPIO.OUT)

try:
    while True:
        print("Beep!")
        GPIO.output(buzzer_pin, GPIO.HIGH)  # Turn the buzzer on
        time.sleep(0.1)  # Keep the buzzer on for 0.1 seconds
        GPIO.output(buzzer_pin, GPIO.LOW)  # Turn the buzzer off
        time.sleep(0.5)  # Wait 0.5 seconds before the next beep

except KeyboardInterrupt:
    pass

finally:
    # Clean up GPIO resources
    GPIO.cleanup()

Here is the program to play a melody using the buzzer:

import RPi.GPIO as GPIO
import time

# Buzzer pin configuration
buzzer_pin = 17  # Replace with the GPIO pin number your buzzer is connected to

# Initial GPIO setup
GPIO.setmode(GPIO.BCM)
GPIO.setup(buzzer_pin, GPIO.OUT)

# Dictionary of note frequencies
notes = {
    'C': 261.63,
    'D': 293.66,
    'E': 329.63,
    'F': 349.23,
    'G': 392.00,
    'A': 440.00,
    'B': 493.88,
    'C_high': 523.25,
}

# Function to play a note
def play_note(note, duration):
    if note == ' ':
        time.sleep(duration)
    else:
        GPIO.output(buzzer_pin, GPIO.HIGH)
        time.sleep(duration)
        GPIO.output(buzzer_pin, GPIO.LOW)

# Function to play a melody
def play_melody(melody):
    for note, duration in melody:
        play_note(note, duration)

try:
    # Play the melody
    example_melody = [
        ('E', 0.5),
        ('D', 0.5),
        ('C', 0.5),
        ('D', 0.5),
        ('E', 0.5),
        ('E', 0.5),
        ('E', 0.5),
        ('D', 0.5),
        ('D', 0.5),
        ('D', 0.5),
        ('E', 0.5),
        ('E', 0.5),
        ('E', 0.5),
        ('E', 0.5),
        ('D', 0.5),
        ('C', 0.5),
        ('D', 0.5),
        ('E', 0.5),
        ('E', 0.5),
        ('E', 0.5),
        ('E', 0.5),
        ('D', 0.5),
        ('D', 0.5),
        ('E', 0.5),
        ('D', 0.5),
        ('C', 0.5),
    ]

    play_melody(example_melody)

except KeyboardInterrupt:
    pass

finally:
    # Clean up GPIO resources
    GPIO.cleanup()