想让蜂鸣器唱歌,但现在我实在是不知道我逻辑在哪出问题了,感觉是定时器这块 求各位赐教
单片机源程序如下:
- #include<reg52.h>
- sbit sound=P1^5;
- unsigned int p, k,j,z;unsigned int c=0;
- unsigned int f=0;
- unsigned int sound_high;unsigned int sound_low;
- unsigned int pace;
- unsigned char code MUSICHIGH[3][8]={{0xff,0xf9,0xf9,0xfa,0xfa,0xfb,0xfb,0xfc},//di
- {0xff,0xfc,0xfc,0xfd,0xfd,0xfd,0xfd,0xfe},
- {0xff,0xfe,0xfe,0xfe,0xfe,0xfe,0xfe,0xff}
- };//三个音阶高电位
- unsigned char code MUSICLOW[3][8]={{0xff,0x21,0xe1,0x8c,0xd8,0x68,0xe9,0x5b},
- {0xff,0x8f,0xef,0x45,0x6c,0xb4,0xf4,0x2e},
- {0xff,0x47,0x78,0xa2,0xb6,0xda,0xfa,0x17}};//三个音阶低电位
- unsigned char code MUSIC[]={1,1,1, 1,1,1, 1,1,2, 5,0,2,
- 3,1,1, 3,1,1, 3,1,2, 1,1,2,
- 1,1,1, 3,1,1, 5,1,2, 5,1,2, 4,1,1, 3,1,1, 2,1,4,
- 2,1,1, 3,1,1, 4,1,2, 4,1,2, 3,1,1, 2,1,1, 3,1,2,
- 1,1,2, 1,1,1, 3,1,1, 2,1,2,
- 5,0,2, 7,0,1, 2,1,1, 1,1,3, 9 };//音符,音阶,节拍
- void init()
- {
- TMOD=0x11; //开两定时器
- TH0=0Xd8;
- TL0=0Xf0;
- EA=1;
- ET0=1;
- }
- void timer0() interrupt 1//节拍
- {
- TH0=0Xd8;
- TL0=0Xf0;
- pace--;
- }
- void delay(unsigned char x)//延迟毫秒
- {
- unsigned int i,h;
- for(i=x;i>0;i--)
- for(h=120;h>0;h--)
- ;
- }
- void sound_delay(unsigned int sound_high,unsigned int sound_low)//产生音调
- {
- TH1=sound_high;
- TL1=sound_low;
- TR1=1;
- while(TF1==0);
- TR1=0;
- TF1=0;
- }
- void main()
- {
-
- c=0;
- init();
- play:
- while(1);
- {
- p=MUSIC[c];
- if(p==9)
- { c=0, delay(1000); goto play;}
-
- else
- {
- j=MUSIC[c++];
- k=MUSIC[c++];//取音符和音高
- sound_high=MUSICHIGH[k][j];
- sound_low=MUSICLOW[k][j];//高低电位取数值
- pace=40*MUSIC[c++];
- TR0=1;
- }
-
- while(pace!=0)
- {
- sound=~sound;
- sound_delay(sound_high,sound_low);
- TR0=0;
- }
- }
- }
-
-
复制代码
|