Franc Gossin Blog: Single-chip microcomputer | Use buzzer play music

Franc Gossin Blog by Franc Gossin is licensed under CC BY-NC-ND 4.0

2024-11-08

Single-chip microcomputer | Use buzzer play music

The buzzer in the microcomputer can be controlled by setting its value repeatedly. However if we want to make it beep in a certain frequency, we need to do something more.

Here are some examples:

Für Elise

哈基米音乐


First, the value of frequency is measured by Herz (Hz). We denote the frequency of the buzzer as f. From the definition of frequency we have
$f={{1}\over {T}}$
where λ is the wave length of the sound wave. So we need to know the connection between λ and the change in the buzzer's input current.
We can see that in the picture, there are two change occurring within a period. So within a second, there would have to be ${{2} \over {T}} = 2f$ changes. For example, if we want to use buzzer simulate the note A at 440 Hz, there have to be 880 times of changes. So, it would take ${1} \over {880}$ second for every change.
So the code would be like:
#include <reg52.h>
#define uint unsigned int
#define uchar unsigned char
sbit BEEP = P2^5;
void delay(uint tus) {
while (tus--);
}
int play(int i, int ws){
while (i--) {
BEEP = !BEEP;
delay(ws);
}
i=0;
return 0;
}
void note(float s, float p)
float i = 50000/p;
play((int)s*p*0.22,(int)i);
}

When we want to  make the buzzer beep at a $f$ Hz for t seconds, call the note() function. The bigger the first parameter is, the longer this sound would last. And the higher value of the second parameter, the higher pitch it would be.



No comments:

Post a Comment