蓝桥杯单片机CT107D_15_蜂鸣器播放音乐

#include     
#include     
//晶振为12MHZ      
//频率常数即音乐术语中的音调,而节拍常数即音乐术语中的多少拍;     

sbit Beep =  P0^6;
unsigned char p,m;   //m为频率常数变量    
unsigned char i=0;   
   
unsigned char n=0;  //n为节拍常数变量    
unsigned char code music_tab[] ={
        		
//格式为: 频率常数, 节拍常数, 频率常数, 节拍常数,
0x0F,0x01, 0x15,0x02, 0x16,0x02, 0x17,0x66, 0x18,0x03,
0x17,0x02, 0x15,0x02, 0x16,0x01, 0x15,0x02, 0x10,0x02,
0x15,0x00, 0x0F,0x01, 0x15,0x02, 0x16,0x02, 0x17,0x02,
0x17,0x03, 0x18,0x03, 0x19,0x02, 0x15,0x02, 0x18,0x66,
0x17,0x03, 0x19,0x02, 0x16,0x03, 0x17,0x03, 0x16,0x00,
0x17,0x01, 0x19,0x02, 0x1B,0x02, 0x1B,0x70, 0x1A,0x03,
0x1A,0x01, 0x19,0x02, 0x19,0x03, 0x1A,0x03, 0x1B,0x02,
0x1A,0x0D, 0x19,0x03, 0x17,0x00, 0x18,0x66, 0x18,0x03,
0x19,0x02, 0x1A,0x02, 0x19,0x0C, 0x18,0x0D, 0x17,0x03,
0x16,0x01, 0x11,0x02, 0x11,0x03, 0x10,0x03, 0x0F,0x0C,
0x10,0x02, 0x15,0x00, 0x1F,0x01, 0x1A,0x01, 0x18,0x66,
0x19,0x03, 0x1A,0x01, 0x1B,0x02, 0x1B,0x03, 0x1B,0x03,
0x1B,0x0C, 0x1A,0x0D, 0x19,0x03, 0x17,0x00, 0x1F,0x01,
0x1A,0x01, 0x18,0x66, 0x19,0x03, 0x1A,0x01, 0x10,0x02,
0x10,0x03, 0x10,0x03, 0x1A,0x0C, 0x18,0x0D, 0x17,0x03,
0x16,0x00, 0x0F,0x01, 0x15,0x02, 0x16,0x02, 0x17,0x70,
0x18,0x03, 0x17,0x02, 0x15,0x03, 0x15,0x03, 0x16,0x66,
0x16,0x03, 0x16,0x02, 0x16,0x03, 0x15,0x03, 0x10,0x02,
0x10,0x01, 0x11,0x01, 0x11,0x66, 0x10,0x03, 0x0F,0x0C,
0x1A,0x02, 0x19,0x02, 0x16,0x03, 0x16,0x03, 0x18,0x66,
0x18,0x03, 0x18,0x02, 0x17,0x03, 0x16,0x03, 0x19,0x00,
0x00,0x00    
};   
   
void int0()  interrupt 1   //采用中断0 控制节拍    
{
       TH0=0xd8;       //定时10ms
   TL0=0xef;   
   n--;   
}   
   
void delay (unsigned char m)   //控制频率延时    
{
        
 unsigned i=3*m;   
 while(--i);   
}   
   
void delayms(unsigned char a)  //豪秒延时子程序    
{
        
  while(--a);                  //采用while(--a) 不要采用while(a--); 各位可编译一下看看汇编结果就知道了!    
}   
   
void main()   
{
      
  P2 = (P2 & 0x1f) | 0xa0; 
  TMOD&=0x0f;   
  TMOD|=0x01;   
  TH0=0xd8;
  TL0=0xef;   
  EA = 1;
  ET0 = 1; 
  TR0 = 1;  
play:   
   while(1)   
    {
        
    a: p=music_tab[i];   
       if(p==0x00)       
			{
     i=0, delayms(1000); goto play;}     //如果碰到结束符,延时1秒,回到开始再来一遍    
       else if(p==0xff)  
	   		{
     i=i+1;delayms(100),TR0=0; goto a;}  //若碰到休止符,延时100ms,继续取下一音符    
       else         
			{
     m=music_tab[i++], n=music_tab[i++];}  //取频率常数 和 节拍常数    
       TR0=1;                                             //开定时器1    
       while(n!=0) Beep=~Beep,delay(m);                         //等待节拍完成, 通过P1口输出音频(可多声道哦!)    
       TR0=0;                                             //关定时器1    
    }   
}  

你可能感兴趣的:(蓝桥杯单片机,单片机,c语言)