单片机,原来也是音乐家:),如下图的案例,MCU也可以实现播放音乐曲谱哦!
其实用简单的电路+MCU + 蜂鸣器就可以play music了!
#include<reg51.h>
sbit BEEP=P3^7;
unsigned char code SONG_TONE[]={212,212,190,212,159,169,212,212,190,212,142,159,212,212,
106,126,159,169,190,119,119,126,159,142,159,0};
unsigned char code SONG_LONG[]={9,3,12,12,12,24,9,3,12,12,12,24,9,3,12,12,12,12,12,9,3,12,12,12,24,0};
void DelayMS(unsigned int x){
unsigned char t;
while(x--) for(t=0;t<120;t++);
}
//播放函数
void PlayMusic(){
unsigned int i=0,j,k;
while(SONG_LONG!=0||SONG_TONE!=0){
for(j=0;j<SONG_LONG*20;j++){//播放各个音符,SONG_LONG为拍子长度
BEEP=~BEEP;
//SONG_TONE延时表决定了每个音符的频率
for(k=0;k<SONG_TONE/2;k++);
}
DelayMS(10);
i++;
}
}
void main(){
BEEP=0;
while(1)
{
PlayMusic(); //播放生日快乐
DelayMS(1000); //播放完后暂停一段时间
}
}