HOME
Shop
  • English
  • 简体中文
HOME
Shop
  • English
  • 简体中文
  • Product Series

    • FPGA+ARM

      • GM-3568JHF

        • Introduction

          • GM-3568JHF Introduction
        • Quick Start

          • Preface
          • Environment Setup
          • Compilation Notes
          • Flashing Guide
          • Debugging Tools
          • Software Update
          • Viewing System Information
          • Test Commands
          • Application Compilation
          • Source Code Access
        • Peripherals & Interfaces

          • USB
          • Display and Touch
          • Ethernet
          • WIFI
          • Bluetooth
          • TF-Card
          • Audio
          • Serial Port
          • CAN
          • RTC
        • Application Development

          • UART Read/Write Demo
          • Key Detection Demo
          • LED Blink Demo
          • MIPI Screen Detection Demo
          • Read USB Device Information Demo
          • FAN Detection Demo
          • FPGA FSPI Communication Demo
          • FPGA DMA Read/Write Demo
          • GPS Debugging Demo
          • Ethernet Test Demo
          • RS485 Read/Write Demo
          • FPGA I2C Read/Write Demo
          • PN532 NFC Card-Reading Demo
          • TF Card Read/Write Demo
        • QT Development

          • ARM64 Cross-Compiler Environment Setup
          • Adding a QT Program to Boot Auto-Start
        • RKNN_NPU Development

          • RK3568 NPU Overview
          • Development Environment Setup
          • Run the Official YOLOv5 Example
        • FPGA Development

          • ARM and FPGA Communication
          • FPGA Development Manual
        • Others

          • Modifying the Root Filesystem
          • System Auto-Start Services
        • Downloads

          • Downloads
      • MB-E30P

        • Introduction

          • MB-E30P Introduction
        • Quick Start

          • Preface
          • Environment Setup
          • Compilation Instructions
          • Flashing Guide
          • Debugging Tools
          • Software Update
          • Viewing Information
          • Test Commands
          • Application Compilation
          • Source Code Acquisition
        • Peripherals & Interfaces

          • USB
          • Display and Touch
          • Ethernet
          • WIFI
          • Bluetooth
          • TF-Card
          • Audio
          • RTC
        • Application Development

          • Key Detection Demo
          • LED Blink Demo
          • MIPI Screen Detection Demo
          • Read USB Device Information Demo
          • FAN Detection Demo
          • FPGA FSPI Communication Demo
          • FPGA DMA Read/Write Demo
          • Ethernet Test Demo
          • FPGA IIC Read/Write Demo
          • PN532 NFC Card Reading Demo
          • TF Card Read/Write Demo
        • QT Development

          • ARM64 Cross-Compiler Environment Setup
          • Adding a QT Program to the Boot Auto-Start Service
        • RKNN_NPU Development

          • RK3568 NPU Overview
          • Development Environment Setup
          • Run the Official YOLOv5 Example
          • Model Conversion In Detail
          • Run Custom Models on the Board
        • FPGA Development

          • ARM and FPGA Communication
          • FPGA Development Manual
        • Others

          • Modifying the Root Filesystem
          • System Auto-Start Service
        • Downloads

          • Downloads
    • ShimetaPi

      • M4-R1

        • Introduction

          • M4-R1 Introduction
        • Quick Start

          • OpenHarmony Overview
          • Image Burning
          • Application Development Quick Start
          • Device Development Quick Start
        • Application Development

          • ArkUI

            • ArkTS Language Overview
            • UI Components - Row Container Introduction
            • UI Components - Column Container Introduction
            • UI Components - Text Component
            • UI Components - Toggle Component
            • UI Components - Slider Component
            • UI Components - Animation Component & Transition Component
          • Documentation

            • OpenHarmony Official Materials
          • Development Notes

            • Full-SDK Replacement Tutorial
            • Introducing and Using Third-Party Libraries
            • HDC Debugging
            • Restore Factory Mode via Command Line
            • Upgrade App to System Permission
          • First App

            • Build Your First ArkTS Application - HelloWorld
          • Demos

            • Serial-Debug-Assistant Application Demo
            • Writing-Board Application Demo
            • Digital Clock Application Demo
            • Wi-Fi Information Acquisition Application Demo
        • Device Development

          • Ubuntu Development

            • Environment Setup
            • Download Source Code
            • Compile Source Code
          • DevEco Device Tool

            • Tool Introduction
            • Development Environment Construction
            • Import the SDK
            • HUAWEI DevEco Tool Function Introduction
        • Kernel Peripherals & Interfaces

          • Guide
          • Device Tree Introduction
          • NAPI Introduction
          • ArkTS Introduction
          • NAPI Development Hands-on Demo
          • GPIO Introduction
          • I2C Communication
          • SPI Communication
          • PWM Control
          • UART Communication
          • TF Card (MicroSD)
          • Screen (Display)
          • Touch
          • Ethernet
          • M.2 SSD
          • Audio
          • WIFI & BT
          • Camera
        • Downloads

          • Downloads
      • M5-R1

        • Introduction

          • M5-R1 Development Docs
        • Quick Start

          • Image Burning
          • Environment Setup
          • Download Source Code
        • Peripherals & Interfaces

          • Raspberry Pi Interfaces
          • GPIO Interface
          • I2C Interface
          • SPI Communication
          • PWM Control
          • Serial Port Communication
          • TF Card
          • Display
          • Touch
          • Audio
          • RTC
          • Ethernet
          • M.2
          • MINI-PCIE
          • Camera
          • WIFI & BT
        • Downloads

          • Downloads
      • Pico-G1

        • Product Overview

          • Product Introduction
          • SDK Version Information
        • Quick Start

          • Development Environment Setup
          • Image Build
          • Image Flashing
          • System Login
          • Network Configuration
          • File Transfer
          • SDK Directory Structure
          • Deploying Your First Application
          • Deploying Your First Driver
          • Mounting an SD Card
        • Peripherals & Interfaces

          • GPIO Control
          • UART Serial Communication
          • I2C Communication
          • SPI Communication
        • MPP Media Development

          • MPP Media Processing Software
          • Image Processing Chain
          • Video Input
          • Image Encoding
        • NPU & AI

          • NPU Driver and Runtime Library Architecture
          • .xmm Model Loading
          • SVP Video Processing
          • AI Noise Reduction (AI_NR)
        • Application Samples

          • Encryption/Decryption Application
          • ADC Acquisition Application
          • Low-Power Application
          • Audio Processing Application
          • Video Encoding Application
          • Video Input Application
          • Video Graphics Subsystem (VGS) Application
          • 08 Region Overlay Application
          • 09 Intelligent Video Engine Application
          • 10 UVC Webcam Application
          • 11 All-in-One Quickstart Application
          • 12 FPN Correction Application
          • 13 Regional Motion Detection Application
          • 14 MTCNN Face Detection Application
        • Expansion Board Peripheral Examples

          • 00 - Pico Expansion Board Peripheral Examples Overview
          • 01 - OLED Display Application
          • 02 - TFT Display Application
          • 03 - MPU6050 Gyroscope Application
          • 04 - ADC Acquisition Application
          • 05 - Passive Buzzer Application
          • 06 - MQ Gas Sensor Application
          • 07 - GPS Positioning Application
          • 08 - SHT20 Temperature & Humidity Application
          • 09 - Ultrasonic Ranging Application
          • 10 - SpO2 Sensor Application
          • 11 - DC Motor Control Application
          • 12 - Servo Control Application
    • OpenHarmony

      • SC-3568HA

        • Introduction

          • SC-3568HA Overview
        • Quick Start Guide

          • OpenHarmony Overview
          • Image Flashing
          • Setting Up the Development Environment
          • Hello World Application and Deployment
        • Application Development

          • ArkUI

            • Introduction to ArkTS Language
            • Introduction to UI Components and Practical Applications (Part 1)
            • Introduction to UI Components and Practical Applications (Part 2)
            • Introduction to UI Components and Practical Applications (Part 3)
          • Expand

            • Getting Started Guide
            • Referencing and Using Third-Party Libraries
            • Application Compilation and Deployment
            • Command-Line Factory Reset
            • System Debugging -- HDC Debugging
            • APP Stability Testing
            • Chapter 7 Application Testing
        • Device Development

          • Environment Setup
          • Download Source Code
          • Compiling Source Code
        • Peripheral And Interface

          • Raspberry Pi interface
          • GPIO Interface
          • I2C Interface
          • SPI communication
          • PWM (Pulse Width Modulation) control
          • Serial port communication
          • TF Card
          • Display Screen
          • Touch
          • Audio
          • RTC
          • Ethernet
          • M.2
          • MINI-PCIE
          • Camera
          • WIFI&BT
          • Raspberry Pi expansion board
        • Downloads

          • Downloads
      • M-K1HSE

        • Introduction

          • M-K1HSE Introduction
        • Quick Start

          • Development environment construction
          • Source code acquisition
          • Compilation Notes
          • Burning Guide
        • Application Development

          • Application Development Environment Setup
          • First Application - Hello World
        • Peripherals and interfaces

          • 01 Audio
          • 02 RS485
          • 03 Display
        • System customization development

          • System transplant
          • System customization
          • Driver Development
          • System Debugging
          • OTA Update
        • Downloads

          • Downloads
    • HVS Camera

      • Quick Start

        • SDK Overview
        • Downloads
        • Your First C++ Program
        • Python Data Analysis
        • MultiVision Studio
      • Development

        • Programming Guides

          • Open Camera
          • Read Events
          • Recording & Replay
          • Event Processing (Denoising)
          • Display & Visualization
          • Tuning
          • Capture APS Image
        • Toolkit SDK

          • Hybrid Vision Toolkit
          • Quick Start
          • C++ API
          • Python API
        • Algorithm

          • Hybrid Vision Algo
          • Hybrid Vision Algo API
          • Windows Algo SDK
        • Samples Overview
        • Applications
      • Fundamentals

        • Event Camera Fundamentals
        • HVS Hybrid Vision
        • Event Visualization
        • Data Formats Reference
        • Glossary
        • Bias & Tuning
        • Video Tutorials
      • USB Cameras

        • HVS Camera Quick Start
        • Networking Capabilities

          • HVS Camera System Architecture
          • EVS Network Server
          • EVS Time Sync
          • Web Window
        • HVS Camera Compatibility Matrix
        • FAQ & Troubleshooting Guide
        • Products

          • CF-NRS1 (Lingguang No.1 Hybrid Vision Camera)
      • MIPI Modules

        • MIPI Module Quick Start
        • Carrier Boards

          • RDK X5 Carrier Board Adaptation
          • Raspberry Pi Carrier Board Adaptation
          • Digua Pi Carrier Board Adaptation
          • ShimeTai Board Carrier Board Adaptation
        • MIPI Module Compatibility Matrix
        • Products

          • EVS_003 Sensor Module
    • AI-model

      • 1684XB-32T

        • Introduction

          • AIBOX-1684XB-32 Introduction
        • Quick Start

          • First Use
          • Network Configuration
          • Disk Usage
          • Memory Allocation
          • Fan Control Strategy
          • Firmware Upgrade
          • Cross Compilation
          • Model Quantization
        • Application Development

          • Development Overview

            • Sophgo SDK Development
            • Sophgo Demo Introduction
          • Large Language Models

            • Deploying Llama3 Example
            • Sophon LLM_api_server Development
            • Deploying MiniCPM-V-2_6
            • Qwen-2-5-VL Image and Video Recognition Demo
            • Qwen3-chat Demo
            • Qwen3-Qwen Agent-MCP Development
            • Qwen3-langchain-AI Agent
          • Deep Learning

            • ResNet (Image Classification)
            • LPRNet (License Plate Recognition)
            • SAM (General Image Segmentation Foundation Model)
            • YOLOv5 (Object Detection)
            • OpenPose (Human Keypoint Detection)
            • PP-OCR (Optical Character Recognition)
        • Downloads

          • Downloads
      • 1684X-416T

        • Introduction

          • AIBOX-1684X-416 Introduction
        • Demo Quick Guide

          • ShimeTai Intelligent Monitoring Demo Quick Usage Guide
      • RDK-X5

        • Introduction

          • RDK-X5 Hardware Introduction
        • Quick Start

          • RDK-X5 Quick Start
        • Application Development

          • AI Online Model Development

            • Experiment 01 - Access Volcengine Doubao AI
            • Experiment 02 - Image Analysis
            • Experiment 03 - Multimodal Visual Analysis & Localization
            • Experiment 04 - Multimodal Image-Text Comparison
            • Experiment 05 - Multimodal Document/Table Analysis
            • Experiment 06 - Camera-based AI Visual Analysis
          • Large Language Models

            • Experiment 01 - Speech Recognition
            • Experiment 02 - Voice Conversation
            • Experiment 03 - Multimodal Image Analysis - Voice
            • Experiment 04 - Multimodal Image Comparison - Voice
            • Experiment 05 - Multimodal Document Analysis - Voice
            • Experiment 06 - Multimodal Vision Application - Voice
          • ROS2 Basics

            • Experiment 01 - Environment Setup
            • Experiment 02 - Create & Build a Workspace Package
            • Experiment 03 - Run ROS2 Topic Communication Node
            • Experiment 04 - ROS2 Camera Application
          • 40-pin IO Development

            • Experiment 01 - GPIO Output (LED Blink)
            • Experiment 02 - GPIO Input
            • Experiment 03 - Button-controlled LED
            • Experiment 04 - PWM Output
            • Experiment 05 - Serial Output
            • Experiment 06 - I2C Experiment
            • Experiment 07 - SPI Experiment
          • USB Module Usage

            • Experiment 01 - USB Voice Module Usage
            • Experiment 02 - Sound Source Localization Module
          • Machine Vision Practice

            • Experiment 01 - Open USB Camera
            • Experiment 02 - Color Recognition
            • Experiment 03 - Gesture Recognition
            • Experiment 04 - YOLOv5 Object Detection
      • RDK-S100

        • Introduction

          • RDK-S100 Hardware Introduction
        • Quick Start

          • RDK-S100 Quick Start
        • Application Development

          • AI Online Model Development

            • Experiment 01 - Access Volcengine Doubao AI
            • Experiment 02 - Image Analysis
            • Experiment 03 - Multimodal Visual Analysis & Localization
            • Experiment 04 - Multimodal Image-Text Comparison
            • Experiment 05 - Multimodal Document/Table Analysis
            • Experiment 06 - Camera-based AI Visual Analysis
          • Large Language Models

            • Experiment 01 - Speech Recognition
            • Experiment 02 - Voice Conversation
            • Experiment 03 - Multimodal Image Analysis - Voice
            • Experiment 04 - Multimodal Image Comparison - Voice
            • Experiment 05 - Multimodal Document Analysis - Voice
            • Experiment 06 - Multimodal Vision Application - Voice
          • ROS2 Basics

            • Experiment 01 - Environment Setup
            • Experiment 02 - Create & Build a Workspace Package
            • Experiment 03 - Run ROS2 Topic Communication Node
            • Experiment 04 - ROS2 Camera Application
          • 40-pin IO Development

            • Experiment 01 - GPIO Output (LED Blink)
            • Experiment 02 - GPIO Input
            • Experiment 03 - Button-controlled LED
            • Experiment 04 - PWM Output
            • Experiment 05 - Serial Output
            • Experiment 06 - I2C Experiment
            • Experiment 07 - SPI Experiment
          • USB Module Usage

            • Experiment 01 - USB Voice Module Usage
            • Experiment 02 - Sound Source Localization Module
          • Machine Vision Practice

            • Experiment 01 - Open USB Camera
            • Experiment 02 - Image Processing Basics
            • Experiment 03 - Object Detection
            • Experiment 04 - Image Segmentation
      • RK1828

        • Introduction

          • M5-182X-A1 AI Edge Box - Product Introduction
          • M5-182X-A1 Hardware Specifications
          • M5-182X-A1 Usage & Safety
        • Quick Start

          • M5-182X-A1 Image Flashing
          • RK182X Hardware Installation & Verification
          • RK182X Development Environment Quick Setup
          • RK182X SDK Overview
          • RK182X Environment Setup in Detail
          • RK182X Quick Start
          • Vendor SDK Data Extraction Record
        • Development Guide

          • ClawChips Architecture and Principles
          • SKILL User Manual
          • RK182X Series LLM Inference (RK1828 Model)
          • RK182X Series CNN Inference (RK1828 Model)
          • Model Conversion
          • RK182X AI Agent Application Development Guide
          • RK182X Industrial Anomaly Detection Application
        • SDK Reference

          • RKNN3-SDK Overview

            • RKNN3 SDK Overview
          • RKNN3-Toolkit

            • RKNN3 Toolkit Installation and Usage
          • RKLLM

            • RKLLM On-Device LLM Inference
          • RK182X Series NPU Overview and Architecture (RK1828 Model)
          • RK182X INT8 Quantized Inference Deployment
          • RK182X MPP Multimedia Framework
          • MPP Details

            • RK182X Video Decoding
            • RK182X Video Encoding
          • NPU Details

            • RKNN Model Conversion
            • RK182X NPU INT8 Quantized Inference
            • RK182X Multi-Model Parallel Inference
          • RGA Details

            • RK182X RGA 2D Graphics Acceleration
          • VPU Details

            • RK182X VPU Codec
        • Hardware Reference

          • RK182X Series Hardware Architecture Overview (RK1828 Model)
          • RK182X Pin Definitions and Multiplexing Configuration
          • RK182X Pin Definitions
          • RK182X Power Management
          • RK182X Clock and PLL Configuration
          • RK182X Clock and Frequency Configuration
        • Tutorials

          • Hello World
          • Hello RK1828 - The First Program
          • RTSP Streaming
          • RTSP Streaming + AI Analysis
          • ShiMetaPi AI Lobster One-Click Deployment
          • PaddleOCR-VL Text Recognition
          • Qwen3-1.7B LLM Text Chat
          • AI Multi-View Inspection (Qwen3-VL Wrapper)
          • YOLOv5 Object Detection
        • Downloads

          • Downloads
        • FAQ

          • FAQ
    • Core-Board

      • C-3568BQ

        • Introduction

          • C-3568BQ Overview
      • C-3588LQ

        • Introduction

          • C-3588LQ Overview
      • GC-3568JBAF

        • Introduction

          • GC-3568JBAF Overview
      • C-K1BA

        • Introduction

          • C-K1BA Overview
    • Software Platform

      • ShiMetaPi Workbench

        • Introduction

          • Product Overview
          • Core Architecture
          • Feature Entries
          • Supported Hardware
          • Release Notes
        • Quick Start

          • Install & Login
          • Connect the Device
          • Set Up the Environment
          • Connect to AIHub
          • First Inference
        • User Guide

          • Workspace Overview
          • Device Manager
          • Model Market
          • One-Click Deploy
          • Vision — SVP
          • Vision - Custom Models
          • shimeta-py IDE
          • Terminal
          • Agent Debug Assistant
          • Settings and Resources
        • FAQ

          • Installation & Login
          • Device Connection
          • Models & Deployment
          • Vision & Runtime
          • Settings & Other
      • ShimetaPi Repository

        • Introduction

          • ShimetaPi Software Repository
        • Pico G1 (GK7206)

          • Quick Start

            • Installation & First Inference
            • shimeta_infer — Image Inference
            • shimeta_camera — Real-time Camera Inference
            • SVP Scene Detection
            • File Transfer & Built-in Model Reference
            • FAQ
          • HTTP API & Python SDK

            • HTTP API Reference
      • Model Fine-tuning Platform

        • Introduction

          • Model Training Platform
        • Quick Start

          • Register & Login
          • Create Your First Model (30-Minute Quick Experience)
        • Training Guide

          • Data Preparation & Annotation
          • Training Parameter Configuration
          • Start & Monitor Training
          • Model Evaluation & Testing
        • Model Deployment

          • Export Model
          • Deploy to Edge Device

05 - Passive Buzzer Application

This chapter describes the passive buzzer application example on the Pico-G1 expansion board — buzzer. It demonstrates how to generate a software square wave through the GPIO interface to drive a passive buzzer and produce sound. It is a fundamental example for learning GPIO timing control and audio signal generation, showing how to achieve precise timing control with software delays.

The application source code lives in the SDK directory source/app/05_buzzer/, providing a complete GPIO square-wave generation implementation — an important reference for learning audio control and timer programming.

1 Application Overview

1.1 Features

  • GPIO square-wave generation: produces a square-wave signal of precise frequency via software delays
  • Passive buzzer driving: demonstrates the difference between passive and active buzzers and how to use them
  • Adjustable frequency: supports custom sound frequency (2~4kHz recommended)
  • Duration control: supports custom sound duration
  • Simple and efficient: minimal code, suitable for embedded learning and quick applications

1.2 Technical Specifications

ParameterValue
Control pinGPIO5_5
Default frequency2kHz (2000Hz)
Default duration1 second
Recommended frequency2~4kHz (loudest)
GPIO interfaceLinux GPIO character device v1 ABI
ImplementationSoftware square wave (clock_gettime busy-wait)
CPU usage100% of one core while sounding

1.3 Test Case List

indexNameTest commandExpected result (success)Possible causes of failure
1Basic beep./buzzerBuzzer sounds for 1 second (2kHz) then turns off automaticallyWrong GPIO pin configuration, damaged buzzer
2Custom frequencyChange the frequency parameter in codeBuzzer sounds at the new frequencyFrequency outside the audible range
3Custom durationChange the duration parameter in codeBuzzer sounds for the new durationWrong duration parameter
4Multiple beepsCall the beep function in a loopBuzzer produces several beeps ("beep beep beep")Delays too short, causing continuous sound

1.4 Directory Structure

source/app/05_buzzer/
├── Makefile              # Build script
├── main.c                # Main program
├── buzzer.c              # Buzzer driver implementation
├── buzzer.h              # Buzzer driver header
├── gpio_hal.c            # GPIO HAL layer implementation
├── gpio_hal.h            # GPIO HAL layer header
└── README.md             # Documentation

2 Hardware Connection

2.1 Pin Definition

SignalOn-board GPIONodeDescription
Control pin (CTRL/SIG)GPIO5_5/dev/gpiochip5 line5Square-wave drive input
VCC3.3V or 5V—Power supply (per the buzzer module rating)
GNDGND—Ground

2.2 Hardware Circuit

Standard passive buzzer wiring:

     Pico-G1              Passive Buzzer Module
  ┌───────────┐         ┌──────────────┐
  │           │         │              │
  │ GPIO5_5 ──┼─────────┤ SIG/CTRL     │
  │           │         │              │
  │    3.3V ──┼─────────┤ VCC          │
  │           │         │              │
  │     GND ──┼─────────┤ GND          │
  │           │         │              │
  └───────────┘         └──────────────┘

Choosing the supply voltage

  • 3.3V supply: safe, low power, suitable for most applications
  • 5V supply: louder, higher power; confirm the module supports it
  • Prefer 3.3V first; try 5V only if the volume is insufficient

2.3 Passive vs. Active Buzzer

Passive buzzer (this module):

  • Has no internal oscillator and must be driven with a square wave
  • Applied DC only makes it click once; it will not sound continuously
  • Frequency is adjustable; pitch follows the frequency
  • Requires a continuous square-wave input to sound continuously

Active buzzer:

  • Has an internal oscillator; sounds as soon as DC is applied
  • Fixed frequency; pitch is not adjustable
  • Simple to control: high = sound, low = stop
  • The square wave from this module can also drive an active buzzer (via the average voltage of the square wave)

How to tell the buzzer types apart

  • Check the label: active buzzers are usually marked "有源" or "Active", passive ones "无源" or "Passive"
  • Check the package: active buzzers are usually slightly taller (internal oscillator circuit), passive ones thinner
  • Test: apply DC — continuous sound means active; a single click means passive

2.4 Pin Multiplexing

Physical address configuration of the GPIO5_5 pin:

  • Register address: iocfg_reg60 @ 0x100C0040
  • Default function: func0 = GPIO
  • Alternate function: func1 = PWM0 (hardware PWM)
  • Current configuration: 0x00001000 (input enable | GPIO function)

GPIO5_5 is already in its GPIO function by default, so the IOCFG register does not need modification. To use hardware PWM, configure it as func1.

3 Build and Deployment

3.1 Prerequisites

Before building this application, make sure the following preparations are complete:

  1. SDK environment ready: set up the cross-compilation toolchain and SDK by following Development Environment Setup
  2. Hardware connected: the buzzer is correctly wired to GPIO5_5, VCC, and GND

3.2 Building the Application

# Set the toolchain path
export PATH=$PATH:<SDK>/tools/linux/toolchains/arm-gcc12.2.0-linux-uclibceabi/bin

# Enter the example directory
cd <SDK>/source/app/05_buzzer

# Build
make

# Clean
make clean

After a successful build, the executable buzzer is generated in the current directory.

3.3 Deploying to the Board

# Transfer to the development board with SCP
scp buzzer root@<board-IP>:/usr/bin/

# Or download via TFTP
tftp -g -r buzzer <board-IP>

3.4 Running the Application

# Add execute permission
chmod +x /usr/bin/buzzer

# Run the buzzer example
/usr/bin/buzzer

Once started, the buzzer sounds for 1 second (2kHz square wave), turns off automatically, and the program exits.

3.5 Expected Output

Console output

/mnt # ./buzzer
[buzzer] pad 复用:GPIO5_5 -> func0(GPIO)
[buzzer] pad 0x100C0040 -> 0x00001000
[buzzer] GPIO5_5 就绪。
[buzzer] 响 1s(2kHz 方波)...
[buzzer] 已关闭,退出。

Actual behavior

The buzzer produces a single continuous tone ("beeep—") that stops after 1 second.

Fixed and variable parts

  • Fixed part: the sound duration and frequency (matches the fixed code)
  • Variable part: none (this program's output is entirely fixed)

4 Internal Execution Logic

4.1 Application Architecture

This application uses a layered design consisting of a hardware abstraction layer, a driver layer, and an application layer:

// Application layer (main.c)
int main(int argc, char *argv[])
{
    // 1. Initialize the buzzer
    buzzer_init();

    // 2. Beep for 1 second (2kHz)
    buzzer_beep(1000, 2000);

    // 3. Turn the buzzer off
    buzzer_off();
    buzzer_deinit();

    return 0;
}

4.2 Buzzer Driver Implementation

The buzzer driver implements software square-wave generation:

// Buzzer initialization
int buzzer_init(void)
{
    // Configure GPIO5_5 as output
    if (gpio_set_direction(BUZZER_GPIO_CHIP, BUZZER_GPIO_LINE, GPIO_OUTPUT) < 0) {
        return -1;
    }

    // Initial state is low
    gpio_set_value(BUZZER_GPIO_CHIP, BUZZER_GPIO_LINE, 0);

    return 0;
}

// Beep function
void buzzer_beep(int duration_ms, int frequency_hz)
{
    if (frequency_hz <= 0 || duration_ms <= 0)
        return;

    // Compute the half-period duration (microseconds)
    int half_period_us = 1000000 / (2 * frequency_hz);
    int cycles = (duration_ms * 1000) / (2 * half_period_us);

    struct timespec start, current;
    clock_gettime(CLOCK_MONOTONIC, &start);

    int state = 0;
    for (int i = 0; i < cycles; i++) {
        // Toggle the GPIO state
        state = !state;
        gpio_set_value(BUZZER_GPIO_CHIP, BUZZER_GPIO_LINE, state);

        // Delay precisely for half a period
        clock_gettime(CLOCK_MONOTONIC, &current);
        long elapsed_us = (current.tv_sec - start.tv_sec) * 1000000 +
                         (current.tv_nsec - start.tv_nsec) / 1000;
        long target_us = (2 * i + 1) * half_period_us;
        long delay_us = target_us - elapsed_us;

        if (delay_us > 0) {
            usleep(delay_us);
        }
    }

    // Return to low
    gpio_set_value(BUZZER_GPIO_CHIP, BUZZER_GPIO_LINE, 0);
}

// Turn the buzzer off
void buzzer_off(void)
{
    gpio_set_value(BUZZER_GPIO_CHIP, BUZZER_GPIO_LINE, 0);
}

// Buzzer cleanup
void buzzer_deinit(void)
{
    buzzer_off();
}

4.3 Software Square-Wave Principle

The software square wave is realized by toggling the GPIO at timed intervals:

Key points:

  1. Frequency control: different frequencies are achieved by controlling the half-period duration
  2. Duty cycle: 50% (high and low times are equal)
  3. Precision guarantee: clock_gettime() provides accurate timestamps

4.4 Precise Delay Implementation

Precise delays using clock_gettime() and usleep():

// Read the monotonic clock (unaffected by system time adjustments)
clock_gettime(CLOCK_MONOTONIC, &current);

// Compute the elapsed time (microseconds)
long elapsed_us = (current.tv_sec - start.tv_sec) * 1000000 +
                 (current.tv_nsec - start.tv_nsec) / 1000;

// Compute the target time
long target_us = (2 * i + 1) * half_period_us;

// Compute the remaining delay
long delay_us = target_us - elapsed_us;

// Perform the delay
if (delay_us > 0) {
    usleep(delay_us);
}

Why use the monotonic clock

  • CLOCK_MONOTONIC: unaffected by system time adjustments, keeping timing accurate
  • CLOCK_REALTIME: affected by system time adjustments, not suitable for timing applications

5 Key Programming Points

5.1 GPIO Output Operations

Control flow:

  1. Configure the GPIO direction as output
  2. Set the initial value low
  3. Toggle the GPIO state periodically
  4. Return it low when finished

Notes:

  • Delay precisely after every toggle
  • Use clock_gettime() to guarantee time precision
  • Avoid overly long delays that would distort the frequency

5.2 Frequency and Pitch

Different frequencies correspond to different musical pitches:

FrequencyPitchNote nameDescription
261HzDo (C4)Middle CReference tone, low
294HzRe (D4)——
330HzMi (E4)——
349HzFa (F4)——
392HzSol (G4)——
440HzLa (A4)Concert ATuning reference
494HzSi (B4)——
523HzDo (C5)High COne octave higher
1000~2000Hz——Common buzzer range
2000~4000Hz——Loudest range

Recommended frequencies

  • 2000Hz: moderate loudness, sensitive to the human ear
  • 2700Hz: louder, a common alarm frequency
  • 4000Hz: very loud, but possibly harsh

5.3 Duration and Rhythm Control

Combine different durations to create rhythms:

// Short "beep"
buzzer_beep(100, 2700);
usleep(100000);  // 100ms interval

// Long "beeeep"
buzzer_beep(500, 2700);
usleep(200000);  // 200ms interval

// Double "beep-beep"
buzzer_beep(100, 2700);
usleep(50000);   // 50ms interval
buzzer_beep(100, 2700);
usleep(200000);

5.4 CPU Usage Issue

Drawbacks of the software square wave:

  • Occupies 100% of a single CPU core while sounding
  • Cannot run complex multitasking at the same time
  • Higher power consumption

Solutions:

  1. Hardware PWM: use the PWM0 function of GPIO5_5 for near-zero CPU usage
  2. Multithreading: run the square-wave generation in a separate thread
  3. Dedicated audio chip: use an external audio driver chip

6 Code Customization

6.1 Changing the Frequency and Duration

Edit the call parameters in main.c:

// buzzer_beep(duration_ms, frequency_hz);
buzzer_beep(1000, 2000);   // 1 second, 2kHz
buzzer_beep(500, 2700);    // 0.5 second, 2.7kHz
buzzer_beep(100, 4000);    // 0.1 second, 4kHz (short chirp)

6.2 Multiple-Beep Effects

Call it in a loop inside main():

// "Beep beep beep" effect
for (int i = 0; i < 3; i++) {
    buzzer_beep(100, 2700);
    usleep(100000);  // 100ms interval
}

// "Beep—beep—beep" effect (SOS rhythm)
for (int i = 0; i < 3; i++) {
    buzzer_beep(200, 2700);
    usleep(100000);
}
usleep(200000);
for (int i = 0; i < 3; i++) {
    buzzer_beep(500, 2700);
    usleep(200000);
}
usleep(200000);
for (int i = 0; i < 3; i++) {
    buzzer_beep(200, 2700);
    usleep(100000);
}

6.3 Playing a Simple Melody

Implement a simple song player:

// Simple scale
#define NOTE_C4  262
#define NOTE_D4  294
#define NOTE_E4  330
#define NOTE_F4  349
#define NOTE_G4  392
#define NOTE_A4  440
#define NOTE_B4  494
#define NOTE_C5  523

// Note structure
struct note {
    int frequency;
    int duration;
};

// "Twinkle Twinkle Little Star" melody
struct note twinkle_star[] = {
    {NOTE_C4, 500}, {NOTE_C4, 500}, {NOTE_G4, 500}, {NOTE_G4, 500},
    {NOTE_A4, 500}, {NOTE_A4, 500}, {NOTE_G4, 1000},
    {NOTE_F4, 500}, {NOTE_F4, 500}, {NOTE_E4, 500}, {NOTE_E4, 500},
    {NOTE_D4, 500}, {NOTE_D4, 500}, {NOTE_C4, 1000},
};

void play_melody(struct note *melody, int length)
{
    for (int i = 0; i < length; i++) {
        buzzer_beep(melody[i].duration, melody[i].frequency);
        usleep(melody[i].duration * 1000);
    }
}

int main()
{
    buzzer_init();
    play_melody(twinkle_star, sizeof(twinkle_star)/sizeof(twinkle_star[0]));
    buzzer_deinit();
    return 0;
}

7 Troubleshooting

ProblemPossible causeSolution
Buzzer silentWrong buzzer type, wrong wiring, wrong GPIO configurationConfirm it is a passive buzzer, check wiring, verify GPIO output
Only a single clickIt is an active buzzer being driven with a square waveHold the pin high continuously instead of using a square wave
Sound too quietFrequency off the resonance point, insufficient supply voltageAdjust the frequency to 2700~4000Hz, raise the supply voltage
Muffled soundFrequency too lowRaise the frequency above 2000Hz
Harsh soundFrequency too highLower the frequency to the 2000~3000Hz range
Inaccurate frequencyImprecise delaysUse hardware PWM or improve the delay algorithm

8 Advanced Extensions

8.1 Using Hardware PWM

Switch to hardware PWM for near-zero CPU usage:

# List the PWM controllers
ls /sys/class/pwm/

# Export the PWM channel
echo 0 > /sys/class/pwm/pwmchip0/export

# Configure the PWM parameters
echo 2000000 > /sys/class/pwm/pwmchip0/pwm0/period    # 2kHz period (500ns)
echo 1000000 > /sys/class/pwm/pwmchip0/pwm0/duty_cycle # 50% duty cycle
echo 1 > /sys/class/pwm/pwmchip0/pwm0/enable         # Enable PWM

# Disable PWM
echo 0 > /sys/class/pwm/pwmchip0/pwm0/enable

Advantages of hardware PWM

  • Near-zero CPU usage
  • Precise frequency with no jitter
  • Other tasks can run at the same time

8.2 Multithreaded Implementation

Run the square-wave generation in a separate thread:

#include <pthread.h>

struct buzzer_params {
    int duration_ms;
    int frequency_hz;
};

void *buzzer_thread(void *arg)
{
    struct buzzer_params *params = (struct buzzer_params *)arg;
    buzzer_beep(params->duration_ms, params->frequency_hz);
    free(params);
    return NULL;
}

// Asynchronous beep
void buzzer_beep_async(int duration_ms, int frequency_hz)
{
    pthread_t thread;
    struct buzzer_params *params = malloc(sizeof(struct buzzer_params));
    params->duration_ms = duration_ms;
    params->frequency_hz = frequency_hz;

    pthread_create(&thread, NULL, buzzer_thread, params);
    pthread_detach(thread);
}

8.3 Volume Control

Achieve volume control by changing the duty cycle:

void buzzer_beep_volume(int duration_ms, int frequency_hz, int volume_percent)
{
    if (volume_percent < 0 || volume_percent > 100)
        volume_percent = 50;

    int half_period_us = 1000000 / (2 * frequency_hz);
    int on_us = half_period_us * volume_percent / 100;
    int off_us = half_period_us * 2 - on_us;

    for (int i = 0; i < duration_ms * frequency_hz; i++) {
        gpio_set_value(BUZZER_GPIO_CHIP, BUZZER_GPIO_LINE, 1);
        usleep(on_us);
        gpio_set_value(BUZZER_GPIO_CHIP, BUZZER_GPIO_LINE, 0);
        usleep(off_us);
    }
}

Duty cycle vs. volume

  • 50% duty cycle: maximum volume
  • 25% duty cycle: half the volume
  • The relationship is nonlinear; the actual effect depends on the buzzer's characteristics

9 References

  • GPIO Interface in Detail
  • Motor Control Application
  • Development Environment Setup
Edit this page on GitHub
Prev
04 - ADC Acquisition Application
Next
06 - MQ Gas Sensor Application