How to play a melody with a piezo buzzer and PIC16F877A microcontroller?
This example demonstrates how to play a simple melody using the PIC microcontroller and piezo buzzer. The circuit was assembled on the solderless breadboard and tested on the PIC-01 Development Board. For programming, the CCS C was employed.Buzzer’s input is simply connected to the D0 pin of the microcontroller.
Drawing 1. (large view)

Because buzzers have a narrow bandwidth, the quality of sound is rather poor, and some frequencies sounds louder whereas other are attenuated. But, some quite simple melodies can be played, like this first notes of Beethoven’s “For Elise”..
/*************************************************
buzzer.c
*************************************************/
#include <16f877a.h>
#fuses xt, nowdt, noprotect, nolvp, noput
#use delay (clock=4000000)
int i,j;
play(pitch, note){
for(j=0;j<note;j++){
for(i=0;i<15;i++){
delay_us(pitch);
output_high(pin_d0);
delay_us(pitch);
output_low(pin_d0);
}
}
}
main()
{
const int pitch_C6=478;
const int pitch_Db6=451;
const int pitch_D6=426;
const int pitch_Eb6=402;
const int pitch_E6=379;
const int pitch_F6=358;
const int pitch_Gb6=338;
const int pitch_G6=319;
const int pitch_Ab6=301;
const int pitch_A6=284;
const int pitch_Bb6=268;
const int pitch_B6=253;
const int pitch_C7=238;
const int pitch_Db7=226;
const int pitch_D7=212;
const int pitch_Eb7=200;
const int pitch_E7=189;
const int pitch_F7=179;
const int pitch_Gb7=169;
const int pitch_G7=159;
const int pitch_Ab7=150;
const int pitch_A7=142;
const int pitch_Bb7=134;
const int pitch_B7=126;
const int pitch_C8=119;
const int pitch_Db8=113;
const int pitch_D8=106;
const int pitch_Eb8=100;
const int pitch_E8=95;
const int quarter_note=50;
const int half_note=100;
play(pitch_E8, quarter_note);
play(pitch_Eb8, quarter_note);
play(pitch_E8, quarter_note);
play(pitch_Eb8, quarter_note);
play(pitch_E8, quarter_note);
play(pitch_B7, quarter_note);
play(pitch_D8, quarter_note);
play(pitch_C8, quarter_note);
play(pitch_A7, half_note);
play(pitch_C7, quarter_note);
play(pitch_E7, quarter_note);
play(pitch_A7, quarter_note);
play(pitch_B7, half_note);
play(pitch_E7, quarter_note);
play(pitch_A7, quarter_note);
play(pitch_Bb7, quarter_note);
play(pitch_C8, half_note);
}
play(pitch, note) functions pulses the microcontroller’s output D0 in certain frequency for some certain time. Frequencies of piano scale can be found on the Internet.
Statement const int pitch_C6=478; is basicly the half of the period (1/f)/2 which corresponds to the frequency of sound (C6 here). It is not very accurate, because some time microcontroller uses for execution, but more imortant are intervals – the diffrences in pitch between notes.
Source code for PIC-01 Development Board and hex files:
buzzer.c (.zip)
buzzer.hex (.zip)