无源蜂鸣器播放小星星
#define L1 63628 #define L1_S 63731 #define L2 63835 #define L2_S 63928 #define L3 64021 #define L4 64103 #define L4_S 64185 #define L5 64260 #define L5_S 64331 #define L6 64400 #define L6_S 64463 #define L7 64528 #define M1 64580 #define M1_S 64633 #define M2 64684 #define M2_S 64732 #define M3 64777 #define M4 64820 #define M4_S 64860 #define M5 64898 #define M5_S 64934 #define M6 64968 #define M6_S 65000 #define M7 65030 #define H1 65058 #define H1_S 65085 #define H2 65110 #define H2_S 65134 #define H3 65157 #define H4 65178 #define H4_S 65198 #define H5 65217 #define H5_S 65235 #define H6 65252 #define H6_S 65268 #define H7 65283 #define SPEED 500 #include <REGX52.H> #include "Timer0.h" #include "SKey.h" #include "Nixie.h" #include "Delay.h" void sing(unsigned int t , unsigned int speed); sbit BEEP = P2^5; unsigned char KeyN = 0; unsigned int MIndex = 0; unsigned int YYF; unsigned int SPE; unsigned char RELOAD[] = {0x00,0x00}; unsigned int code MUSIC[] = { M1,4, M1,4, M5,4, M5,4, M6,4, M6,4, M5,4+4, M4,4, M4,4, M3,4, M3,4, M2,4, M2,4, M1,4+4, M5,4, M5,4, M4,4, M4,4, M3,4, M3,4, M2,4+4, M5,4, M5,4, M4,4, M4,4, M3,4, M3,4, M2,4+4, M1,4, M1,4, M5,4, M5,4, M6,4, M6,4, M5,4+4, M4,4, M4,4, M3,4, M3,4, M2,4, M2,4, M1,4+4, 0xFF}; void main(){ Timer0Init(); while(1){ YYF = MUSIC[MIndex]; MIndex++; SPE = MUSIC[MIndex]; if(YYF==0xFF || SPE==0xFF){ MIndex = 0; continue; } sing(YYF,SPE); MIndex++; } } void sing(unsigned int t , unsigned int speed){ RELOAD[0] = t%256; RELOAD[1] = t/256; Delay(speed/4 * SPEED); RELOAD[0] = 0x00; RELOAD[1] = 0x00; Delay(5); //停止定时器 // TR0 = 0; } void Timer0_Routine() interrupt 1 { if(RELOAD[0] != 0x00){ TL0 = RELOAD[0]; //设置定时初值 TH0 = RELOAD[1]; //设置定时初值 BEEP = !BEEP; }else{ TL0 = 0xF5; //设置定时初值 TH0 = 0xFF; //设置定时初值 } }
1、采用51单片机的Timer0定时器根据改变周期来给蜂鸣器振荡电压。
2、不同的声调有不同的振动频率。将振动频率转换为计数器的重载值,实现播放音符。
3、根据每个小节的每个音符的持续时间来确定播放速度。
void main(){ Timer0Init(); while(1){
YYF = MUSIC[MIndex]; MIndex++; SPE = MUSIC[MIndex]; if(YYF==0xFF || SPE==0xFF){ MIndex = 0; continue;}sing(YYF,SPE); MIndex++; }
}
void sing(unsigned int t , unsigned int speed){ RELOAD[0] = t%256; RELOAD[1] = t/256; Delay(speed/4 * SPEED); RELOAD[0] = 0x00; RELOAD[1] = 0x00; Delay(5); //停止定时器 // TR0 = 0;
}
void Timer0_Routine() interrupt 1{ if(RELOAD[0] != 0x00){TL0 = RELOAD[0];//设置定时初值TH0 = RELOAD[1];//设置定时初值BEEP = !BEEP;}else{TL0 = 0xF5;//设置定时初值TH0 = 0xFF;//设置定时初值} }