51单片机蜂鸣器实现《卡农》代码
时间: 2023-10-29 12:06:01 浏览: 108
以下是51单片机蜂鸣器实现《卡农》的代码,需要连接一个蜂鸣器到P2.3口:
```
#include <reg52.h>
#define uchar unsigned char
#define uint unsigned int
uchar code music[] = {0x51,0x5e,0x61,0x5e,0x63,0x64,0x63,0x5e,0x61,0x5e,0x51,0x5e,0x61,0x5e,0x61,0x5e,
0x63,0x64,0x63,0x5e,0x61,0x5e,0x51,0x5e,0x61,0x5e,0x63,0x64,0x63,0x5e,0x61,0x5e,
0x51,0x5e,0x61,0x5e,0x61,0x5e,0x63,0x64,0x63,0x5e,0x61,0x5e,0x51,0x5e,0x61,0x5e,
0x63,0x64,0x63,0x5e,0x61,0x5e,0x51,0x5e,0x61,0x5e,0x63,0x64,0x63,0x5e,0x61,0x5e,
0x51,0x5e,0x61,0x5e,0x61,0x5e,0x63,0x64,0x63,0x5e,0x61,0x5e,0x51,0x5e,0x61,0x5e,
0x63,0x64,0x63,0x5e,0x61,0x5e,0x51,0x5e,0x61,0x5e,0x63,0x64,0x63,0x5e,0x61,0x5e,
0x51,0x5e,0x61,0x5e,0x61,0x5e,0x63,0x64,0x63,0x5e,0x61,0x5e,0x51,0x5e,0x61,0x5e,
0x63,0x64,0x63,0x5e,0x61,0x5e,0x51,0x5e,0x61,0x5e,0x63,0x64,0x63,0x5e,0x61,0x5e};
uchar i = 0;
void delay(uint xms)
{
uint i,j;
for(i=xms;i>0;i--)
{
for(j=110;j>0;j--);
}
}
void main()
{
while(1)
{
P2 = 0xff; //蜂鸣器不响
delay(1000); //延时
P2 = 0x00; //蜂鸣器响
delay(1000); //延时
P2 = 0xff; //蜂鸣器不响
delay(1000); //延时
for (i=0; i<90; i++) //播放音乐
{
P2 = music[i];
delay(15);
}
}
}
```
代码中的 `music` 数组存储了《卡农》的乐谱,使用 `P2` 控制蜂鸣器的状态来播放音乐。需要注意的是,由于蜂鸣器的频率是固定的,所以播放的音乐有可能与原曲有些出入。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)