现象
在无源蜂鸣器上循环演奏低音“DO、RE、MI、FA、SO、LA、SI”这7个音调。
参考程序
1 主函数
#include
#include "delayms.h"
#include "timer0.h"
sbit Buzzer = P2^5;
//音调与频率对照表,低中高:1,1#,2,2#,3,4,4#,5,5#,6,6#,7
//unsigned int FreqTable[]={
// 63628,63731,63835,63928,64021,64103,64185,64260,64331,64400,64463,64528,
// 64580,64633,64684,64732,64777,64820,64860,64898,64934,64968,65000,65030,
// 65058,65085,65110,65134,65157,65178,65198,65217,65235,65252,65268,65283,
//};
//音调与频率对照表,低中高:1,2,3,4,5,6,7
unsigned int FreqTable[]={
63628,63835,64021,64103,64260,64400,64528,
64580,64684,64777,64820,64898,64968,65030,
65058,65110,65157,65178,65217,65252,65283,
};
unsigned char FreqSelect;
void main()
{
Timer0Init( );
while(1)
{
if(FreqSelect>19)
FreqSelect = 0;
else
FreqSelect++;
delayms(500);
}
}
//定时器中断函数
void timer0_routine() interrupt 1
{
TL0 = FreqTable[FreqSelect]%256;
TH0 = FreqTable[FreqSelect]/256;
Buzzer = !Buzzer;
}
2 延时函数
#ifndef _delayms_h_
#define _delayms_h_
void delayms(unsigned int xms);
#endif
#include
void delayms(unsigned int xms) //@11.0592MHz
{
unsigned char i, j;
while(xms--)
{
_nop_();
i = 2;
j = 199;
do
{
while (--j);
} while (--i);
}
}
3 定时器函数
#ifndef _timer0_h_
#define _timer0_h_
void Timer0Init(void);
#endif
#include
/**
* @brief 定时器0初始化,1毫秒@11.0592MHz
* @param 无
* @retval 无
*/
void Timer0Init(void) //1毫秒@11.0592MHz
{
TMOD &= 0xF0; //设置定时器模式
TMOD |= 0x01; //设置定时器模式
TL0 = 0x66; //设置定时初始值
TH0 = 0xFC; //设置定时初始值
TF0 = 0; //清除TF0标志
TR0 = 1; //定时器0开始计时
ET0 = 1; //打开定时器0中断
EA = 1; //打开总中断开关
PT0 = 0; //设置定时器0中断优先级
}
相关文章