51单片机:独立键盘实现音乐简谱

#include 

#define KEYPORT P1

sbit beep = P2^7;

unsigned char High;
unsigned char Low;

unsigned char code freq[][2]=
{ 
    0xD8,0xF7,//00440HZ 1 //音乐简谱(1~7)  
    0xBD,0xF8,//00494HZ 2  
    0x87,0xF9,//00554HZ 3  
    0xE4,0xF9,//00587HZ 4    
    0x90,0xFA,//00659HZ 5     
    0x29,0xFB,//00740HZ 6     
    0xB1,0xFB,//00831HZ 7      
    0xEF,0xFB,//00880HZ 1
};

void timer0_init(void)
{
	EA = 1;
	TMOD |= 0x01;
	TH0 = 0;
	TL0 = 0;
	ET0 = 1;
	TR0 = 0;
}

void timer0_isr(void) interrupt 1
{
	TH0 = High;
	TL0 = Low;
	beep = ~beep;
	
}
	
	
void main()
{
	unsigned char num = 0;

	timer0_init();
	
	while(1)
	{
		switch(KEYPORT)
		{
		  case 0xfe: num = 1;break;
      case 0xfd: num = 2;break;
		  case 0xfb: num = 3;break;
		  case 0xf7: num = 4;break;
		  case 0xef: num = 5;break;
		  case 0xdf: num = 6;break;
		  case 0xbf: num = 7;break;
		  case 0x7f: num = 8;break;
      default :num = 0;break;

	  } 
	  if(num)
	  {
		  High = freq[num - 1][1]; //针对不同的按键赋值不同的音乐简谱频率(赋定时器初值并打开定时器)
		  Low = freq[num - 1][0];
		  TR0 = 1;
	  }
	  else
	  {	 
			TR0 = 0; //无定时器按下,关闭定时器
	  }
  }
}

    

你可能感兴趣的:(51单片机)