|
楼主 |
发表于 2023-1-8 19:43:03
|
显示全部楼层
对于蜂鸣器演奏音乐比较感兴趣,然后查找了一些相关资料,下面的代码可以运行成功但是可能是频率和延时没调好吧才有了附件中乱响的情况,所以想知道怎么调好顺便可以拓宽一下知识面
- #include <STC15F2K60S2.H>
- #include <intrins.h>
- //di yin
- #define DOL 1908
- #define REL 1701
- #define MIL 1515
- #define FAL 1449
- #define SOL 1275
- #define LAL 1136
- #define SIL 1012
- //zhong yin
- #define DOM 956
- #define REM 852
- #define MIM 759
- #define FAM 716
- #define SOM 638
- #define LAM 568
- #define SIM 506
- //gao yin
- #define DOH 478
- #define REH 426
- #define MIH 379
- #define FAH 358
- #define SOH 319
- #define LAH 284
- #define SIH 254
- #define STOP 65535
- #define B41 400
- #define B31 300
- #define B21 200
- #define B32 150
- #define B11 100
- #define B34 75
- #define B12 50
- #define B14 25
- sbit buzzer=P0^6;
- unsigned char th0;
- unsigned char tl0;
- int code music1[]=
- {
- LAM,B12,DOH,B12,REH,B12,REH,B12,REH,B12,REH,B12,REH,B11,MIH,B12,
- FAH,B12,FAH,B11,MIH,B32,DOH,B11,REH,B11,MIH,B11,MIH,B11,SOH,B11,
- LAH,B12,LAH,B11,DOH,B11,DOH,B11,MIH,B11,REH,B21,DOH,B11,REH,B11,MIH,B21,
-
- DOH,B11,REH,B11,MIH,B11,MIH,B11,SOH,B11,LAH,B12,LAH,B11,DOH,B11,
- DOH,B11,MIH,B11,REH,B21,DOH,B11,SIM,B11,DOH,B21,
- 0,0
- };
- void delay_ms(unsigned int ms)
- {
- unsigned int i,j;
- for(i=0;i<ms;i++)
- for(j=0;j<686;j++)
- {
- _nop_();
- _nop_();
- _nop_();
- _nop_();
- }
- }
- void SetFreq(int time)
- {
- th0=(65536-time)>>8;
- tl0=(65536-time)&0x00ff;
- TH0=th0;
- TL0=tl0;
- }
- void Buzzer(int Tone, int Beat)
- {
- SetFreq(Tone);
- delay_ms(100*Beat);
- }
- void PlayMusic(int* music)
- {
- int tone=0;
- int beat=1;
-
- while(music[beat]>0)
- {
- Buzzer(music[tone],music[beat]);
- Buzzer(STOP,100);
- tone+=2;
- beat+=2;
- }
- }
- void Timer0Init(void)
- {
- AUXR &= 0x7F;
- TMOD &= 0xF0;
- TMOD |= 0x01;
- TL0 = 0;
- TH0 = 0;
- TF0 = 0;
- TR0 = 1;
- }
- void main()
- {
- Timer0Init();
- EA=1;
- ET0=1;
- P2=(P2&0x1f)|0xa0;buzzer=1;P2&=0x1f;
- while(1)
- {
- PlayMusic(music1);
- };
- }
- void Time0_Int() interrupt 1
- {
- TH0=th0;
- TL0=tl0;
-
- P2=(P2&0x1f)|0xa0;buzzer=!buzzer;P2&=0x1f;
- }
复制代码 |
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有账号?立即注册
x
|