51单片机蜂鸣器实现《卡农》代码,连接一个蜂鸣器到P2.5口
时间: 2023-11-13 15:03:30 浏览: 93
以下是51单片机实现《卡农》的蜂鸣器代码,使用定时器0实现:
```c
#include <reg51.h>
#define uchar unsigned char
#define uint unsigned int
uchar code music[]={0x1c,0x1c,0x1f,0x1c,0x1c,0x1f,0x1c,0x1c,0x1f,0x1c,0x1c,0x1f,0x1c,0x1c,0x1f,0x1c,
0x1c,0x1e,0x1c,0x1c,0x1e,0x1c,0x1c,0x1e,0x1c,0x1c,0x1e,0x1c,0x1c,0x1e,0x1c,0x1c,
0x1d,0x1c,0x1c,0x1d,0x1c,0x1c,0x1d,0x1c,0x1c,0x1d,0x1c,0x1c,0x1d,0x1c,0x1c,0x1c,
0x1c,0x1c,0x1f,0x1c,0x1c,0x1f,0x1c,0x1c,0x1f,0x1c,0x1c,0x1f,0x1c,0x1c,0x1f,0x1c,0x1c,
0x1e,0x1c,0x1c,0x1e,0x1c,0x1c,0x1e,0x1c,0x1c,0x1e,0x1c,0x1c,0x1e,0x1c,0x1c,0x1c,0x1c,
0x1d,0x1c,0x1c,0x1d,0x1c,0x1c,0x1d,0x1c,0x1c,0x1d,0x1c,0x1c,0x1d,0x1c,0x1c,0x1c,0x1c,
0x1c,0x1c,0x1f,0x1c,0x1c,0x1f,0x1c,0x1c,0x1f,0x1c,0x1c,0x1f,0x1c,0x1c,0x1f,0x1c,0x1c,
0x1e,0x1c,0x1c,0x1e,0x1c,0x1c,0x1e,0x1c,0x1c,0x1e,0x1c,0x1c,0x1e,0x1c,0x1c,0x1c,0x1c}; //乐谱数组
uchar cnt; //计数变量
void delay(uint z) //延时函数
{
uint x,y;
for(x=z;x>0;x--)
for(y=114;y>0;y--);
}
void timer0() interrupt 1 //定时器0中断
{
TH0=(65536-1000)/256; //重新加载初值
TL0=(65536-1000)%256;
cnt++; //计数器自增
if(cnt>=sizeof(music)) //计数器达到乐谱数组长度时清零
cnt=0;
P2=music[cnt]; //输出下一个音符
}
void main()
{
TMOD=0x01; //定时器0,工作方式1
TH0=(65536-1000)/256; //给定初值
TL0=(65536-1000)%256;
TR0=1; //启动定时器0
ET0=1; //使能定时器0中断
EA=1; //使能总中断
while(1);
}
```
将蜂鸣器连接到P2.5口。