|
用timer0模拟输出占空比和频率可调的方波出现问题!
[复制链接]
频率24MHZ
#include
sbit OUT=P1^0;
sbit K1=P2^0; //增加占空比
sbit K2=P2^1; //减少占空比
sbit K3=P2^2; //增频率
sbit K4=P2^3; //减频率
unsigned int t_Z=0x32; //占空比初值 10%--90%
unsigned int t_T=0x3E8; //频率初值 100--2000
//初始状态1000HZ,50%占空比
unsigned char h_h=0xFC; //高电平初值
unsigned char h_l=0x17;
unsigned char l_h=0xFC; //低电平初值
unsigned char l_l=0x17;
void
delay(unsigned int time)
{
while(time--);
}
void
init_timer()
{
TMOD = 0x01;
TH0 = 0xFC;
TL0 = 0x17;
EA = 1;
ET0 = 1;
TR0 = 1;
}
void
caculate()
{
unsigned int result;
/*计算高点平初值*/
result=(200*t_Z)/t_T;
result=result*100;
result=~result;
h_h=(result>>8)&0xff;
h_l=result&0xff;
/*计算低电平初值*/
result=(200*(100-t_Z))/t_T;
result=result*100;
result=~result;
l_h=(result>>8)&0xff;
l_l=result&0xff;
}
void
main()
{
init_timer();
while(1)
{
if(K1==0)
{
delay(10000);
if(K1==0)
if(t_Z!=0x5A)
t_Z+=0xa;
}
if(K2==0)
{
delay(10000);
if(K2==0)
if(t_Z!=0x0a)
t_Z-=0x0a;
}
if(K3==0)
{
delay(10000);
if(K3==0)
if(t_T<0x07D0)
t_T+=0x14;
}
if(K4==0)
{
delay(10000);
if(K4==0)
if(t_T>0x64)
t_T-=0x14;
}
caculate();
}
}
void
ISR_timer0() interrupt 1 using 3
{
if(OUT==1)
{
TH0=l_h; //low value
TL0=l_l;
}
else
{
TH0=h_h; //high value
TL0=h_l;
}
OUT=~OUT;
}
4个按键来控制占空比和频率,改变频率没有什么问题,但是增大或者减小占空比时出现频率也变化,请教各位是caculate中重新计算初值的问题还是方法问题呢?(本身计算是有问题的,为了方便我就有点拼凑的感觉把值计算出来的呵呵)
|
|