#include <reg51.h>
sbit K1=P1^4;
sbit K2=P1^5;
sbit K3=P1^6;
sbit K4=P1^7;
sbit K5=P3^2;
sbit K6=P3^3;
sbit K7=P3^4;
sbit Bee=P3^7; //蜂鸣器所在
//定义七个基本音节
unsigned int Music_7[]={262,294,330,349,392,440,494};
//定义高音的七个音节,因为按键不够暂时不用,可以在Proteus仿真中使用
//unsigned int Music_7_H[]={523,587,659,698,784,880,988};
unsigned char th,tl;
void InitTimer0(void)
{
TMOD = 0x01;
TH0 = 0x0F8;
TL0 = 0x18;
EA = 1;
ET0 = 1;
Bee =1; //关闭蜂鸣器,因为这蜂鸣器跟喇叭不同,只要上电就他娘的响
TR0 = 0; //关闭定时器,防止一开机就嗷嗷的响
}
void set_music(unsigned char i)
{
th=(65536-(1000000/Music_7[i]))/256;
tl=(65536-(1000000/Music_7[i]))%256;
TH0=th;
TL0=tl;
}
void delay1s(void) //误差 0us
{
unsigned char b,c;
for(c=180;c>0;c--)
for(b=250;b>0;b--)
;
}
void main(void)
{
InitTimer0();
while(1)
{
if(K1==0)
{
set_music(0);
while(K1==0);
{
TR0=1; //启动定时器开始演奏音乐
delay1s(); //每次触发大概1秒,后续可修改为松手停止响。这里可以换成松手检测就可以了
TR0=0; //关闭定时器,停止音律响
Bee=1; //关闭蜂鸣器,防止一直嗷嗷响,如果用的是喇叭就可以忽略这个。
}
}
if(K2==0)
{
set_music(1);
while(K2==0);
{
TR0=1;
delay1s();
TR0=0;
Bee=1;
}
}
if(K3==0)
{
set_music(2);
while(K3==0);
{
TR0=1;
delay1s();
TR0=0;
Bee=1;
}
}
if(K4==0)
{
set_music(3);
while(K4==0);
{
TR0=1;
delay1s();
TR0=0;
Bee=1;
}
}
if(K5==0)
{
set_music(4);
while(K5==0);
{
TR0=1;
delay1s();
TR0=0;
Bee=1;
}
}
if(K6==0)
{
set_music(5);
while(K6==0);
{
TR0=1;
delay1s();
TR0=0;
Bee=1;
}
}
if(K7==0)
{
set_music(6);
while(K7==0);
{
TR0=1;
delay1s();
TR0=0;
Bee=1;
}
}
}
}
void Timer0Interrupt(void) interrupt 1
{
TH0 = th;
TL0 = tl;
Bee = ~Bee;
}
|