STC89C52做音乐播放器
内部晶振11.0592MHZ
C大调音符对照表
###TH0,TL0初始值
小星星乐谱
硬件电路实现
用于驱动蜂鸣器
###蜂鸣器
实现代码(运用模块化编程)
###主函数
#include <REGX52.H>
#include "Timer0.h"
#include "intrins.h"
#include "Delay.h"
void Timer0_Suspend();
sbit buzzer=P1^5;
//定时器装载值
int Frequency[]={
63777,63872,63969,64054,64140,64216,
64291,64360,64426,64489,64547,64603,
64655,64704,64751,64795,64837,64876,
64913,64948,64981,65012,65042,65070,
65095,65120,65144,65166,65186,65206,
65225,65242,65259,65274,65289,65303,
};
//小星星乐谱编号
int code Indexes[]={
12,4,12,4, //1
19,4,19,4, //5
21,4,21,4, //6
19,8,
17,4,17,4, //4
16,4,16,4, //3
14,4,14,4, //2
12,8,
//1
19,4,19,4,
17,4,17,4,
16,4,16,4,
14,8,
19,4,19,4,
17,4,17,4,
16,4,16,4, //3
14,8, //2
12,4,12,4,//1
19,4,19,4, //5
21,4,21,4, //6
19,8, //5
17,4,17,4, //4
16,4,16,4, //3
14,4,14,4, //2
12,8//1
};
int Selection,Music;
void main()
{
Timer0_Init();
while(1)
{
Selection=Indexes[Music];
Music++;
Delay(125*Indexes[Music]);
Music++;
TR0 =0;
Delay(30);
TR0 =1;
if(Music>=84)
Music=0;
}
}
void Timer0_Suspend() interrupt 1
{
TL0 =Frequency[Selection]%256;
TH0 =Frequency[Selection]/256;
buzzer=~buzzer;
}
###定时器0初始化
#ifndef __TIMER0_H__
#define __TIMER0_H__
void Timer0_Init();
#endif
#include <REGX52.H>
void Timer0_Init() //1毫秒@11.0592MHz
{
TMOD &= 0xF0; //设置定时器模式
TMOD |= 0x01; //设置定时器模式
TL0 = 0x66; //设置定时初值
TH0 = 0xFC; //设置定时初值
TF0 = 0; //清除TF0标志
TR0 = 1; //定时器0开始计时
ET0=1;
EA=1;
PT0=0;
}
###延时函数模块
#ifndef __DELAY_H__
#define __DELAY_H__
void Delay(int Ms);
#endif
void Delay(int Ms) //@11.0592MHz 1ms
{
unsigned char i, j;
for(;Ms>0;Ms--)
{
_nop_();
i = 2;
j = 199;
do
{
while (--j);
} while (--i);
}
}