#include <REGX52.h>
#include "Delay.h"
sbit Buzz = P1^5;
#define SPEED 400 //播放速度,值为四分音符的时长(ms)
//音符与索引对应表,P:休止符,L:低音,M:中音,H:高音,下划线:升半音符号#
#define P 0
#define L1 1
#define L1_ 2
#define L2 3
#define L2_ 4
#define L3 5
#define L4 6
#define L4_ 7
#define L5 8
#define L5_ 9
#define L6 10
#define L6_ 11
#define L7 12
#define M1 13
#define M1_ 14
#define M2 15
#define M2_ 16
#define M3 17
#define M4 18
#define M4_ 19
#define M5 20
#define M5_ 21
#define M6 22
#define M6_ 23
#define M7 24
#define H1 25
#define H1_ 26
#define H2 27
#define H2_ 28
#define H3 29
#define H4 30
#define H4_ 31
#define H5 32
#define H5_ 33
#define H6 34
#define H6_ 35
#define H7 36
unsigned char MusicSelect , FreqSelect;
//索引与频率对照表
code unsigned int FreqTable_H[] = {
0,
0xF8,0xF8,0xF9,0xF9,0xFA,0xFA,0xFA,0xFB,0xFB,0xFB,0xFB,0xFC,
0xFC,0xFC,0xFC,0xFC,0xFD,0xFD,0xFD,0xFD,0xFD,0xFD,0xFD,0xFE,
0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFF,
};//定时器计时高位 休止符(0) 低调(1~12) 中调(13~24) 高调(25~36)
code unsigned int FreqTable_L[] = {
0,
0x8C,0xF3,0x5B,0xB8,0x15,0x67,0xB9,0x04,0x4B,0x90,0xCF,0x10,
0x44,0x79,0xAC,0xDC,0x09,0x34,0x5C,0x82,0xA6,0xC8,0xE8,0x06,
0x22,0x3D,0x56,0x6E,0x85,0x9A,0xAE,0xC1,0xD3,0xE4,0xF4,0x03,
};//定时器计时低位 休止符(0) 低调(1~12) 中调(13~24) 高调(25~36)
/*乐谱好运来*/
code unsigned char Music[] = {
M6,2+1+1,H1,2,H1,2,
M6,4+2,M6,2,
M5,2,M3,2,M5,2,H1,2,
M6,4,0,4,
M6,2,H1,2,H1,2+1,H1,1,
H1,4,M5,4,
M6,2,M5,2,M2,2,M5,2,
M3,4+2,M2,2,
M3,2,M2,2,M1,2,M3,2,
M2,4+2,M3,2,
M6,2,M5,2,M3,2,M6,2,
M6,2,M5,4+2,
M6,2,H1,2,H1,2,M6,1,
H2,2,H2,2,H2,2,H1,2,
M6,4,M5,2,H1,2,
M6,4+4,
M6,4+4, //
M6,4,H3,2+1,H2,1,
H2,4,H1,2,M6,2,
M5,2,H1,2,
M6,4,M6,4,
M6,4,H2,4,
H1,4,M6,2,M5,2,
M2,4,M5,2,M6,2,
M5,2,M3,4+2,
M3,4,M6,2+1,M5,1,M6,4,M6,2,M5,2,
M6,4,H2,2+1,H1,1,
H2,4,H2,4,
H1,2+1,H1,1,H1,2,H2,2,
H3,2,H3,2,H2,2,H1,2,
M5,4,H1,2+1,M6,1,
M6,4,M6,4,
M6,4,M6,4,//
H2,4,H2,4,
H2,4,H2,4,
H3,4,H3,4,
H3,4,H3,4,
M6,4,M6,4,
M6,4,M6,4,
M6,4,M6,4,
M6,4,M6,4,
0,4,M5,2,M5,2,
M6,4,M6,4,
0xFF //停止标志位
};
void Timer0Init()
{
TMOD |= 0x01;
TL0 = 0x18;
TH0 = 0xFC;
TR0 = 1;
ET0 = 1;
EA = 1;
}
void main()
{
Timer0Init();
while(1)
{
if(Music[MusicSelect]!=0xFF) //判断是否等于终止标志位
{
FreqSelect = Music[MusicSelect]; //获取音符对应的频率
MusicSelect++; //MusicSelect++转换至音符长度
delay(SPEED/4*Music[MusicSelect]);//选择音符对应的时间长度(时值)
MusicSelect++; //MusicSelect++转换至下一个音符
TR0 = 0;
delay(5); //音符间短暂停顿
TR0 = 1;
}
else //如果是停止标识符清零重新播放
{
TR0 = 0;
MusicSelect = 0;
}
}
}
void Timer0_Routine() interrupt 1
{
if(FreqSelect) //判断是否为休止符
{
/*取对应频率值的重装载值到定时器*/
TL0 = FreqTable_L[FreqSelect]; //设置定时器初值
TH0 = FreqTable_H[FreqSelect]; //设置定时器初值
Buzz = !Buzz;//翻转蜂鸣器IO口
}
}
不会换歌的可以私信我,我帮你们换歌有空的话