1. 程式人生 > >微控制器==獨立按鍵+蜂鳴器(10)

微控制器==獨立按鍵+蜂鳴器(10)

#include <reg52.h>

#define KEYPORT P2

sbit beep = P1^7;

#define SEGPORT P0

unsigned char High;
unsigned char Low;
unsigned char code freq[][2]={ 
  0xD8,0xF7,//00440HZ 1   
  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 }; unsigned char code SONG_TONE[]={212,212,190,212,159,169,212,212,190,212,142,159, 212,212,106,126,159,169,190,119,119,126,159,142,159,0}; unsigned char code SONG_LONG[]={9,3,12,12,12,24,9,3,12,12,12,24, 9
,3,12,12,12,12,12,9,3,12,12,12,24,0}; void DelayMS(unsigned int x) { unsigned char t; while(x--)for(t=0;t<120;t++); } void PlayMusic() { unsigned int i=0,j,k; while(SONG_LONG[i]!=0||SONG_TONE[i]!=0) { for(j=0;j<SONG_LONG[i]*20;j++) { beep = ~ beep; for
(k=0;k<SONG_TONE[i]/3;k++); } DelayMS(10); i++; } } 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; } PlayMusic(); } }