Help
  • FAQ
    browse most common questions
  • Live Chat
    talk with our online service
  • Email
    contact your dedicated sales:
0

STM32 Buzzer Music Playback Example

Author : AIVON January 12, 2026

Content

 

Introduction

This article demonstrates playing music with a buzzer driven by an STM32 microcontroller using STM32CubeIDE as the development environment.

Buzzer Types

Active buzzer

An active buzzer contains an internal oscillator and sounds when powered. Its output frequency is fixed.

Passive buzzer

A passive buzzer does not contain an oscillator. It requires an external signal at a specific frequency on its pin to produce sound.

This example uses a passive buzzer. Varying the control frequency produces different pitches.

 

Circuit Diagram

From the schematic, the buzzer is connected to PB5. Toggling PB5 at a certain frequency will make the buzzer sound.

Circuit Diagram

 

STM32 Project

Open STM32CubeIDE and create a new STM32 project. For STM32CubeIDE usage, see the reference "STM32 PWM configuration and application".

Configure the clock

Configure the clock

 

Project settings

Project settings

 

Enable PB5

 

Enable PB5

Delay function and timer

Implement a microsecond delay function. Enable timer TIM7 to implement HAL_Delay_us(). For details, see the reference "STM32 HAL custom delay function delay_us()".

Delay function and timer

Save and generate code.

49c2a3be-eb2e-11ee-a297-92fbcf53809c.png

 

Playback Logic

Iterate through the music array to get music[i]. Use music[i] as an index into the tone array to obtain the frequency for that note, i.e. tone[music[i]], then call the sound function to drive the buzzer. The duration of each note is controlled by the time array.

The two elements required to play music on the buzzer are frequency and duration, corresponding to pitch and beat in musical notation.

 


2025 AIVON.COM All Rights Reserved
Intellectual Property Rights | Terms of Service | Privacy Policy | Refund Policy