PC机向单片机发送命令启动或停止蜂鸣器播放音乐,
当播放音乐时该怎么停止,这时是播放函数运行中,pc输入数据要等到放完才接受,也就是停不下来
是不是应该换个播放函数?该怎么写?
#include<reg52.h>
#include<string.h>
unsigned char Count;
sbit speak = P3^4;
unsigned char code SONG[] ={ //祝你平安
0x26,0x20,0x20,0x20,0x20,0x20,0x26,0x10,0x20,0x10,0x20,0x80,0x26,0x20,0x30,0x20,
0x30,0x20,0x39,0x10,0x30,0x10,0x30,0x80,0x26,0x20,0x20,0x20,0x20,0x20,0x1c,0x20,
0x20,0x80,0x2b,0x20,0x26,0x20,0x20,0x20,0x2b,0x10,0x26,0x10,0x2b,0x80,0x26,0x20,
0x30,0x20,0x30,0x20,0x39,0x10,0x26,0x10,0x26,0x60,0x40,0x10,0x39,0x10,0x26,0x20,
0x30,0x20,0x30,0x20,0x39,0x10,0x26,0x10,0x26,0x80,0x26,0x20,0x2b,0x10,0x2b,0x10,
0x2b,0x20,0x30,0x10,0x39,0x10,0x26,0x10,0x2b,0x10,0x2b,0x20,0x2b,0x40,0x40,0x20,
0x20,0x10,0x20,0x10,0x2b,0x10,0x26,0x30,0x30,0x80,0x18,0x20,0x18,0x20,0x26,0x20,
0x20,0x20,0x20,0x40,0x26,0x20,0x2b,0x20,0x30,0x20,0x30,0x20,0x1c,0x20,0x20,0x20,
0x20,0x80,0x1c,0x20,0x1c,0x20,0x1c,0x20,0x30,0x20,0x30,0x60,0x39,0x10,0x30,0x10,
0x20,0x20,0x2b,0x10,0x26,0x10,0x2b,0x10,0x26,0x10,0x26,0x10,0x2b,0x10,0x2b,0x80,
0x18,0x20,0x18,0x20,0x26,0x20,0x20,0x20,0x20,0x60,0x26,0x10,0x2b,0x20,0x30,0x20,
0x30,0x20,0x1c,0x20,0x20,0x20,0x20,0x80,0x26,0x20,0x30,0x10,0x30,0x10,0x30,0x20,
0x39,0x20,0x26,0x10,0x2b,0x10,0x2b,0x20,0x2b,0x40,0x40,0x10,0x40,0x10,0x20,0x10,
0x20,0x10,0x2b,0x10,0x26,0x30,0x30,0x80,0x00};
void Delay_xMs(unsigned int x)
{
unsigned int i,j;
for( i =0;i < x;i++ )
{
for( j =0;j<3;j++ );
}
}
void Play_Song(unsigned char i)
{
unsigned char Temp1,Temp2;
unsigned int Addr;
Count = 0; //中断计数器清0
Addr = i * 217;
while(1)
{
Temp1 = SONG[Addr++];
if ( Temp1 == 0xFF ) //休止符
{
TR0 = 0;
Delay_xMs(100);
}
else if ( Temp1 == 0x00 ) //歌曲结束符
{
return;
}
else
{
Temp2 = SONG[Addr++];
TR0 = 1;
while(1)
{
speak = ~speak;
Delay_xMs(Temp1);
if ( Temp2 == Count )
{
Count = 0;
break;
}
}
}
}
}
void main (void)
{ char a,b=0;
SCON=0x50;//串行口方式1
PCON=0x00;//T1初始化,
TMOD=0x21;//T1设为方式2 T0设为方式1
TH1=0xFD;//选9600波特,fosc=11.0592MHz
TR1=1;//启动T1
IE = 0x82;
TH0 = 0xD8;
TL0 = 0xEF;
while(1)
{
if(RI)//如果接收到数据,就把接收到的数回发给PC
{ RI=0;//清接收标志
a=SBUF ;//读串行口数据
SBUF=a;//把从PC机发送过来的数据返回给PC机
while(!TI);//没有发送完等待
TI=0;//清发送完中断标志
switch(a)
{
case 0x00 : P0=0xff; break;
case 0x01 : P0=0xAA; break;
case 0x02 : P0=0x00; break;
case 0x03 : Play_Song(0);break; //播放
case 0x04 : P0=0xff;
TR0 = 1;speak=0;
break;
}
}
}
}
void Time0_Int() interrupt 1
{
TH0 = 0xD8;
TL0 = 0xEF;
Count++; //长度加1
}
|