当前位置:文档之家› 51单片机PWM占空比调整程序

51单片机PWM占空比调整程序

51单片机PWM占空比调整程序
(通过测试,注意:AT89S51单片机,有的单片机P3_7需要改为P3^7)

/*****************************************************************************
* 程序名称:PWM占空比调整演示程序 *
*程序思路说明: *
* 只需要4个按键。 *
*关于频率和占空比的确定,对于12M晶振,输出频率为1KHZ,这样定时中断次数设定为 *
*10,即0.01MS中断一次,则TH0=FF,TL0=F6;由于设定中断时间为0.01ms,这样可以设 *
*定占空比可从1-99%变化。即0.01ms*100=1ms *
******************************************************************************/

#include
#define uchar unsigned char
#define uint unsigned int
uchar timer0_tick,ZKB=1;//timer0_tick计数,ZKB占空比
uchar i=0,n=0,temp=0;
code seven_seg[10]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};//1,2,3, 4, 5, 6, 7, 8, 9
code scan[2]={0xfd,0xfe};
uchar counter[2]={0,0};
sbit AN1=P3^2;//调整个位
sbit AN2=P3^3;//调整十位
sbit AN3=P3^4;//启动按键
sbit AN4=P3^5;//确认按键
void delay(uint z)//软件延时函数
{
uint x,y;
for(x=z;x>0;x--)
for(y=110;y>0;y--);
}
static void timer0_isr(void) interrupt 1 using 0 //中断函数
{
TR0=0;
TL0=0xf6;
TH0=0xff;
TR0=1;
if (ZKB>99) ZKB=1;
if (ZKB<1) ZKB=99;
counter[0]=ZKB%10;
counter[1]=ZKB/10;
n++;
if(n==100)
{
n=0;
i++;
if(i==2) i=0;
P0=seven_seg[counter[i]];
P2=scan[i];
}
timer0_tick++;
if(timer0_tick++==100)
{
timer0_tick=0;

}
if(AN2==0)
{
delay(100);
if(AN2==0)
{
temp=1;
counter[0]++;
if(counter[0]==10)
{
counter[0]=0;
}

}
}
if(AN1==0)
{
delay(100);
if(AN1==0)
{
temp=1;
counter[1]++;
if(counter[1]==10)
{
counter[1]=0;
}

}
}
ZKB=counter[0]+counter[1]*10;
if(AN4==0)
{
delay(5);
if(AN4==0)
temp=0;
}
if(temp==1)
P3_7=0;// P3_7为脉冲输出引脚
else
{
if (timer0_tick<=ZKB) /*当小于占空比值时输出低电平,高于时是高电平,从而实现占空比的调整*/
{
P3_7=1;
}
else
{
P3_7=0;
}

}
}
static void timer0_initialize(void)//中断初始化
{
EA=0;
timer0_tick=0;
TR0=0;
TMOD=0x01;
TL0=0xf6;
TH0=0xff;
PT0=0;
ET0=1;
TR0=1;
EA=1;
}
void main(void)
{
STAR: delay(100);
if(AN3!=0) goto STAR;//按键3启动脉冲
timer0_initialize();
while(1);
}
//按按键3启动脉冲器,初始设置占空比为1%,按键1

调整十位,
//按键2调整个位,一旦调整,输出为0,必须按确认键确认,
//输出正确脉冲.可以占空比1-99%任意调节。


相关主题
文本预览
相关文档 最新文档