unsigned char tone;
unsigned char op;
本文引用地址:http://m.butianyuan.cn/article/201611/320305.htmsbit led=P1^1;
sbit spk=P1^0;
sbit key1=P3^2; //兩只老虎演奏按鍵
sbit key2=P3^3;//1~i演奏按鍵
unsigned char code shuma[]={
0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0x80,0x90};
//用于使定時(shí)器初值變化以產(chǎn)生相應(yīng)頻率的定時(shí)
unsigned char code yinfu_H[]=
{0xfb,0xfc,0xfc,0xfc,0xfd,0xfd,0xfd,0xfd,0x00};
unsigned char code yinfu_L[]=
{0xe9,0x5c,0xc1,0xef,0x45,0x92,0xd0,0xee,0x00};
void delay(unsigned int N)
{
unsigned int j=N;
while(j--)
{
unsigned char i;
for(i=0;i<250;i++);
}
}
unsigned char code laohu[]=
{1,2,3,1,1,2,3,1,3,4,5,3,4,5,5,6,5,4,3,1,5,6,5,4,3,1,3,1,1,3
,1,1};//兩只老虎樂譜
unsigned char code laohuys[]=
{220,220,220,220,220,220,220,220,220,220,235,220,220,210,150
,150,
170,170,200,200,150,150,170,170,200,200,244,240,250,244,220,
250};
//定時(shí)器初始化
void initTimer(void)
{
TMOD=0x01;
TH0=yinfu_H[tone];
TL0=yinfu_L[tone];
}
//定時(shí)器T0中斷服務(wù)程序
void timer0(void) interrupt 1
{
TH0=yinfu_H[tone];
TL0=yinfu_L[tone];
spk=~spk;//
}
void laohu_yz()//兩只老虎 演奏程序
{
unsigned char i;
for(i=0;i<32;i++)
{
led=1;
tone=laohu[i]-1;
delay(laohuys[i]/1.2);
led=0; //每個(gè)音符閃爍一次
delay(laohuys[i]/1.5);
}
}
void yuep_yz()//1~i音符演奏程序
{
unsigned char i;
for(i=0;i<16;i++)
{
led=1;
if(i<8)
{
tone=i;
}
else
{
tone=15-i;
}
delay(220);
led=0;
delay(180);
}
}
void jianpan()
{
op=P2;
switch(op)
{
case 0xfe:led=0;tone=0;P0=shuma[1];TR0=1;break;
case 0xfd:led=0;tone=1;P0=shuma[2];TR0=1;break;
case 0xfb:led=0;tone=2;P0=shuma[3];TR0=1;break;
case 0xf7:led=0;tone=3;P0=shuma[4];TR0=1;break;
case 0xef:led=0;tone=4;P0=shuma[5];TR0=1;break;
case 0xdf:led=0;tone=5;P0=shuma[6];TR0=1;break;
case 0xbf:led=0;tone=6;P0=shuma[7];TR0=1;break;
case 0x7f:led=0;tone=7;P0=shuma[8];TR0=1;break;
default:break;
}
delay(4);
TR0=0;
led=1;
P0=0xff;
}
//主程序
void main(void)
{
initTimer();
ET0=1;
EA=1;
spk=0;
while(1)
{
if(key1==0)//判斷K1鍵是否按下
{
delay(10);
if(key1==0)
{
TR0=1;
laohu_yz();
spk=0;
}
}
else if(key2==0)//判斷K2鍵是否按下
{
delay(10);
if(key2==0)
{
TR0=1;
yuep_yz();
spk=0;
}
}
jianpan();//鍵盤檢測(cè)
}
}
評(píng)論