51单片机蜂鸣器音乐代码
时间: 2023-08-29 07:04:44 浏览: 80
以下是一个简单的51单片机连接蜂鸣器播放音乐的代码示例:
```c
#include <reg51.h>
#define uchar unsigned char
#define uint unsigned int
uchar code music[]={0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88,0x88,0x88,0x88,0x98,0xA8,0x98,0x88};
void delay(uint x) //延时函数
{
uint i;
while(x--)
for(i=0;i<120;i++);
}
void main()
{
uchar i=0;
while(1)
{
P2=0xFE; //输出高电平
P0=music[i++]; //输出音乐频率
delay(100); //延时一段时间
if(i==sizeof(music)) //判断是否播放结束
i=0; //重新播放
}
}
```
这段代码中,使用了一个名为“music”的数组来存储音乐频率,其中0x88代表音调1,0x98代表音调2,0xA8代表音调3,以此类推。同时,使用了一个“delay”函数来实现延时,以控制播放速度。在主函数中,通过循环不断输出音乐频率,实现了蜂鸣器播放音乐的效果。
阅读全文