您好,欢迎访问三七文档
#includereg52.hsbitspeaker=P2^0;unsignedchartimer0h,timer0l,time;sbitIN1=P0^0;//intput1sbitIN2=P0^1;//intput2sbitIN3=P0^2;//intput3sbitIN4=P0^3;//intput4sbitIN5=P0^4;//intput5sbitIN6=P0^5;//intput6sbitIN7=P0^6;//intput7sbitIN8=P0^7;//intput8sbitIN15=P1^4;//intput15sbitIN16=P1^5;//intput16sbitIN10=P3^1;//intput10sbitIN11=P3^4;//intput11sbitIN12=P3^5;//intput12sbitIN13=P3^6;//intput13sbitIN14=P3^7;//intput14sbitIN9=P3^0;//intput9//输出sbitOut7=P2^1;//output7sbitOut6=P2^2;//output6sbitOut5=P2^3;//output5sbitOut4=P2^4;//output4sbitOut3=P2^5;//output3sbitOut2=P2^6;//output2sbitOut1=P2^7;//output1//--------------------------------------//单片机晶振采用11.0592MHz//频率-半周期数据表高八位本软件共保存了四个八度的28个频率数据codeunsignedcharFREQH[]={0xF2,0xF3,0xF5,0xF5,0xF6,0xF7,0xF8,//低音12345670xF9,0xF9,0xFA,0xFA,0xFB,0xFB,0xFC,0xFC,//1,2,3,4,5,6,7,i0xFC,0xFD,0xFD,0xFD,0xFD,0xFE,//高音2345670xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFF};//超高音1234567//频率-半周期数据表低八位codeunsignedcharFREQL[]={0x42,0xC1,0x17,0xB6,0xD0,0xD1,0xB6,//低音12345670x21,0xE1,0x8C,0xD8,0x68,0xE9,0x5B,0x8F,//1,2,3,4,5,6,7,i0xEE,0x44,0x6B,0xB4,0xF4,0x2D,//高音2345670x47,0x77,0xA2,0xB6,0xDA,0xFA,0x16};//超高音1234567//--------------------------------------//世上只有妈妈好数据表要想演奏不同的乐曲,只需要修改这个数据表codeunsignedcharsszymmh[]={6,2,3,5,2,1,3,2,2,5,2,2,1,3,2,6,2,1,5,2,1,//一个音符有三个数字。前为第几个音、中为第几个八度、后为时长(以半拍为单位)。//6,2,3代表:6,中音,3个半拍;//5,2,1代表:5,中音,1个半拍;//3,2,2代表:3,中音,2个半拍;//5,2,2代表:5,中音,2个半拍;//1,3,2代表:1,高音,2个半拍;//6,2,4,3,2,2,5,2,1,6,2,1,5,2,2,3,2,2,1,2,1,6,1,1,5,2,1,3,2,1,2,2,4,2,2,3,3,2,1,5,2,2,5,2,1,6,2,1,3,2,2,2,2,2,1,2,4,5,2,3,3,2,1,2,2,1,1,2,1,6,1,1,1,2,1,5,1,6,0,0,0};//--------------------------------------voidt0int()interrupt1//T0中断程序,控制发音的音调{TR0=0;//先关闭T0speaker=!speaker;//输出方波,发音TH0=timer0h;//下次的中断时间,这个时间,控制音调高低TL0=timer0l;TR0=1;//启动T0}//--------------------------------------voiddelay(unsignedchart)//延时程序,控制发音的时间长度{unsignedchart1;unsignedlongt2;for(t1=0;t1t;t1++)//双重循环,共延时t个半拍for(t2=0;t27000;t2++);//延时期间,可进入T0中断去发音TR0=0;//关闭T0,停止发音}//--------------------------------------voidsong()//演奏一个音符{TH0=timer0h;//控制音调TL0=timer0l;TR0=1;//启动T0,由T0输出方波去发音delay(time);//控制时间长度}voidmain(void){unsignedchark,i;TMOD=1;//置T0定时工作方式1ET0=1;//开T0中断EA=1;//开CPU中断while(1){i=0;time=1;while(time){k=sszymmh[i]+7*sszymmh[i+1]-1;//第i个是音符,第i+1个是第几个八度timer0h=FREQH[k];//从数据表中读出频率数值timer0l=FREQL[k];//实际上,是定时的时间长度time=sszymmh[i+2];//读出时间长度数值i+=3;song();//发出一个音符Out1=~Out1;Out2=~Out2;Out3=~Out3;Out4=~Out4;Out5=~Out5;Out6=~Out6;Out7=~Out7;}}}
本文标题:单片机音乐代码
链接地址:https://www.777doc.com/doc-7345765 .html