基于51单片机的音乐盒设计
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
基于51单片机的音乐盒设计
题目要求:
1. 查阅资料,了解单片机控制单音喇叭发声原理;
2. 设计基于单片机的电子音乐盒;
3.通过按钮可选择不同的音乐,切换3首音乐;
运行仿真图:
程序完整代码:
#include
sbit fx_buzzer=P3^7; //蜂鸣器音乐输出,可根据需要自行修改
sbit music_1 = P2^0; //第一首音乐
sbit music_2 = P2^1; //第二首音乐
sbit music_3 = P2^2; //第二首音乐
unsigned int tone; //简谱音调计数
unsigned char fx_timeh,fx_timel,music,speed; //fx_timeh:TH0初值,fx_timel:TL0初值; music =1播放,=0停止
unsigned char code fx_tone0[]={ //音调对应定时器初值
0xFC,0x8E, 0xFC,0xED, 0xFD,0x43, //中音
0xFD,0x6A, 0xFD,0xB3, 0xFD,0xF3, 0xFE,0x2D,
0xFE,0x47, 0xFE,0x76, 0xFE,0xA1, //高音
0xFE,0xC7, 0xFE,0xD9, 0xFE,0xF9, 0xFF,0x16
};
unsigned char code songbie[]={//送别
0x54,0x32,0x52,0x88,0x64,0x84,0x58,0x54,0x12,0x22,0x34,0x22,0x12,0x2c,0x04, 0x54,0x32,0x52,0x86,0x72,0x64,0x84,0x58,0x54,0x22,0x32,0x46,0x72,0x1c,
0x64,0x8c,0x74,0x62,0x72,0x88,0x62,0x72,0x82,0x62,0x52,0x32,0x12,0x2f,
0x54,0x32,0x52,0x86,0x72,0x64,0x84,0x58,0x54,0x22,0x32,0x46,0x72,0x1c,
0x64,0x8c,0x74,0x62,0x72,0x88,0x62,0x72,0x82,0x62,0x52,0x32,0x12,0x2f,
0x54,0x32,0x52,0x86,0x72,0x64,0x84,0x58,0x54,0x22,0x32,0x46,0x72,0x1c,
0xff};
unsigned char code qnzl[]={ //千年之恋
0x12,0x22,0x34,0x84,0x74,0x54,0x38,0x42,0x32,0x22,
0x42,0x34,0x84,0x72,0x82,0x94,0xA8,0x08,0x32,0x31,
0x21,0x32,0x52,0x32,0x31,0x21,0x32,0x62,0x32,0x31,
0x21,0x32,0x82,0x71,0x81,0x71,0x51,0x32,0x22,0x32,
0x31,0x21,0x32,0x52,0x32,0x31,0x21,0x32,0x62,0x32,
0x31,0x21,0x32,0x83,0x82,0x71,0x72,0x02,0x63,0xA1,
0xA2,0x62,0x92,0x82,0x52,0x31,0x51,0x63,0x51,0x63,
0x51,0x63,0x51,0x62,0x82,0x7C,0x02,0x61,0x71,0x82,
0x71,0x62,0xA2,0x71,0x76,0x61,0x71,0x82,0x71,0x62,
0x52,0x31,0x36,0x61,0x71,0x82,0x71,0x62,0xA3,0x73,
0x62,0x53,0x42,0x63,0x83,0x83,0x91,0x91,0x61,0x71,
0x82,0x71,0x62,0x0A2,0x71,0x76,0x61,0x71,0x82,0x71,
0x62,0x52,0x31,0x36,0x61,0x71,0x82,0x71,0x62,0xA3,
0x73,0x62,0x53,0x42,0x82,0x88,0x02,0x74,0x93,0x89,
0xff};
unsigned char code laohu[]={ //两只老虎
0x14,0x14,0x24,0x34,0x14,0x14,0x24,0x34,0x14,
0x34,0x44,0x58,0x34,0x44,0x58,
0x53,0x61,0x53,0x41,0x34,0x14,
0x53,0x61,0x53,0x41,0x34,0x14,
0x14,0x54,0x18,
0x14,0x54,0x18,
0xFF};
unsigned char keyValue; //存储按下的键值
void init() //初始化函数
{
EA=1;//开总中断
TMOD=0x10;//定时器0工作在方式1
TH1=0;
TL1=0;
ET1=1;
music=1; //默认播放
tone=0;
speed=20; //播放速度
}
void fx_delay(unsigned char i) //音长延时函数
{
unsigned int j,k;
for(i;i>0;i--)
for(k=speed;k>0;k--)
for(j=625;j>0;j--);
}
void play(unsigned char *temp) //音阶播放函数
{
if(speed<1) speed=1; //速度范围设定
if(speed>60) speed=60;
while(1)
{
if(!music) break;
if(music==2) {tone=0;music=1;break;} //配合按钮换歌
if(temp[tone]==0xff){tone=0;break;};
if(temp[tone]/16!=0) //取高4位的音阶判断
{
fx_timeh=fx_tone0[temp[tone]/16*2-2];
fx_timel=fx_tone0[temp[tone]/16*2-1];
TR1=1;
}
fx_delay(temp[tone]%16); //取数的低4位
TR1=0;
tone++;
}
TR1=0;
}