กลับไปหน้ารวมไฟล์
interfacing-buzzer-with-arduino-48a319-en.md

Acoustic Frequency Basics: Interfacing Buzzer

An LED is binary: ON or OFF. A buzzer is entirely analog. The Interfacing Buzzer with Arduino project introduces the foundational concept of generating an audible "Square Wave" by violently oscillating an Arduino digital pin HIGH and LOW thousands of times a second, physically forcing a piezoelectric crystal to bend and snap, creating sound waves in the air!

button_led_basic_interaction_1772681969235.png

The Physics of the tone() Function

If you just run digitalWrite(BuzzerPin, HIGH), the buzzer might click once and stay silent.

  1. To make a sound, you must vibrate the pin.
  2. The Arduino core team wrote the <tone()> library, which hooks directly into the ATmega Timer 2 hardware interrupt register.
  3. The Syntax: tone(pin, frequency, duration);
    • tone(8, 440, 1000); -> Blast a 440Hz frequency (The musical note 'A4') out of Pin 8 for exactly 1000 milliseconds!
  4. The Arduino processor violently alternates Pin 8 between 5V and GND exactly 440 times per second! The piezo crystal physically flexes 440 times, matching the acoustic resonance of a tuned piano string!

Composing Array-Based Melodies

Playing one note is boring. Creating the Super Mario theme song requires parsing massive arrays.

  • You must declare a massive array of integers representing the sheet music:
int melody[] = { 262, 196, 196, 220, 196, 0, 247, 262 }; // C4, G3, G3, A3, G3, Rest, B3, C4
int noteDurations[] = { 4, 8, 8, 4, 4, 4, 4, 4 };
  • A for loop cycles through the array. It calculates the physical duration (1000ms / noteDurations[i]).
  • Without delay() between the notes, the song will slur together into an indistinguishable, horrible screech. You must insert a mathematical pause (duration * 1.3) between the tone() executions to allow the physical piezo crystal to return to its rest state!

Essential Chiptune Hardware

  • Arduino Uno/Nano (Standard form factor).
  • Passive Piezoelectric Buzzer (Do NOT use an "Active" buzzer. Active buzzers have their own internal oscillator and will only play one horrible, screeching 2kHz note no matter what frequency you send them from the C++ code!).
  • A 100 Ohm Resistor physically wired in series to the buzzer pin to prevent drawing massive current and blowing the Arduino's logic gate during heavy square-wave pulsing.

ข้อมูล Frontmatter ดั้งเดิม

title: "Interfacing Buzzer with Arduino"
description: "Acoustic synthesis! Learn the foundational physics of generating square waves, manipulating the internal 16MHz ATmega timers using the `tone()` function to blast complex, polyphonic chiptune melodies."
category: "Audio & Sound"
difficulty: "Easy"