您好,欢迎访问三七文档
当前位置:首页 > 行业资料 > 其它行业文档 > ATmega16控制蜂鸣器播放音乐
/*****************************************************编译环境:ICC-AVR芯片型号:ATmega16时钟频率:12.000MHz程序功能:PA0口接蜂鸣器,通过单片机驱动蜂鸣器播放音乐******************************************************/#includeiom16v.h#includemacros.h//计时值=65536-系统时钟/分频系数/音调频率/2//音符计时值频率Hz#defineLL638263//220#defineLL741245//247#defineL142635//262#defineL245128//294#defineL347354//330#defineL448344//349#defineL550230//392#defineL651900//440#defineL753390//494#defineN154064//523#defineN255315//587#defineN356431//659#defineN456940//698#defineN557883//784#defineN658718//880#defineN759463//988#defineH159805//1047#defineH260430//1175#defineH360987//1319#defineH461241//1397#defineH561709//1568#defineH662127//1760#defineH762500//1976#defineHH162669//2093#defineO0//休止符/************************************音乐数据这段是《孤星独吟》,自己对着简谱翻的*************************************/unsignedintsong[]={N6,12,N7,4,H1,8,H2,4,H3,4,/**/H2,32,/**/N7,12,N6,4,N5,8,N3,4,N5,4,/**/N6,32,/**/H1,12,N6,4,N6,8,H3,8,/**/H2,32,/**/N5,12,N6,4,N7,8,H1,4,N7,4,/**/N6,32,/**/H3,24,N6,8,/**/H2,24,H3,4,H2,4,/**/H1,16,H1,4,N6,4,H1,4,H2,4,/**/N7,24,H1,4,H2,4,/**/H3,24,H2,4,H1,4,/**/H2,32,/**/N5,4,N6,4,N7,16,N7,4,N5,4,/**/N6,32,/**/N6,12,N7,4,H1,8,H2,4,H3,4,/**/H2,32,/**/N7,12,N6,4,N5,8,N3,4,N5,4,/**/N6,32,/**/H1,12,N6,4,N6,8,H3,8,/**/H2,32,/**/N5,12,N6,4,N7,8,H1,4,N7,4,/**/N6,32,/**/H3,24,N6,8,/**/H2,24,H3,4,H2,4,/**/H1,16,H1,4,N6,4,H1,4,H2,4,/**/N7,24,H1,4,H2,4,/**/H3,24,H2,4,H1,4,/**/H2,32,/**/N5,4,N6,4,N7,16,N6,4,N5,4,/**/N6,32,/**/H3,24,H2,4,H1,4,/**/H2,32,/**/H1,24,N7,4,N6,4,/**/N7,24,H1,4,H2,4,/**/H3,24,H3,4,N6,4,/**/H2,24,H3,4,H2,4,/**/H1,16,H1,4,N6,4,H1,4,H2,4,/**/N7,32,/**/H3,24,N6,8,/**/H2,24,H3,4,H2,4,/**/H1,16,H1,4,N6,4,H1,4,H2,4,/**/N7,24,H1,4,H2,4,/**/H3,24,H2,4,H1,4,/**/H2,24,H3,4,H2,4,/**/H1,24,N6,8,/**/N7,24,H1,8,/**/N6,32,/**/N6,32,/**/0xFF//音乐结尾符};unsignedintbeat;//beat用以存储音符对应的计数值/****************************函数功能:控制整首乐曲的演奏*****************************/voidMusic(unsignedint*pMusic){while(*pMusic!=0xFF)//0xFF为音乐结尾符{TIMSK=0x04;//Timer1溢出中断使能beat=*pMusic;//取出音符TCNT1H=beat/256;TCNT1L=beat%256;//将音符对应的计数值写入计时器,开始发声pMusic++;//乐谱音符指针+1,取拍数delay_ms((*pMusic)*52);//节拍延时,可以通过这里调整音乐播放速度TIMSK=0x00;//当前音符结束,屏蔽Timer1溢出中断pMusic++;//乐谱音符指针+1,指向下一音符}delay_ms(1000);//曲谱结束,等待}/************************************函数功能:完成单个音符的播放*************************************/#pragmainterrupt_handlertimer1_ovf_isr:iv_TIM1_OVFvoidtimer1_ovf_isr(void){if(beat){PORTA^=BIT(0);//蜂鸣器接入口电平翻转TCNT1H=beat/256;TCNT1L=beat%256;//将音符对应的计数值写入计时器}}voidmain(void){DDRA=0xff;//设置PORTA为输出PORTA=0x00;TCCR1B=0x01;//Timer1开始工作,不分频,分频系数为1SEI();//打开全局中断while(1){Music(song);}}voiddelay_1ms(void){unsignedi;for(i=1;i1714;i++);}voiddelay_ms(unsignedintn){unsignedinti;for(i=0;in;i++){delay_1ms();}}
本文标题:ATmega16控制蜂鸣器播放音乐
链接地址:https://www.777doc.com/doc-2406076 .html