#include <reg51.h>
typedef unsigned char uint8;
typedef unsigned int uint16;
sbit down = P3^0;
sbit up = P3^1;
uint8 t = 0;
uint8 PWM_T = 0; //占空比控制變
void delay_1ms(uint16 t)
{
uint16 x,y;
for(x=t;x>0;x--)
for(y=120;y>0;y--);
}
/****************************************************
主程序
****************************************************/
void main(void)
{
TMOD = 0x02; //定時器0,工作模式2,8位定時模式
TH0=210; //寫入預置初值(取值1-255,數越大PWM頻率越高)
TL0=210; //寫入預置值 (取值1-255,數越大PWM頻率越高)
TR0=1; //啟動定時器
ET0=1; //允許定時器0中斷
EA=1; //允許總中斷
P1=0xff; //初始化P1,輸出端口
PWM_T=30;
while(1)
{
if(!up)
{
if(PWM_T<250)
{
PWM_T++;
}
delay_1ms(10);
}
if(!down)
{
if(PWM_T>0)
{
PWM_T--;
}
delay_1ms(10);
}
}
}
/****************************************************
/定時器0中斷模擬PWM
****************************************************/
timer0() interrupt 1
{
t++; //每次定時器溢出加1
if(t==250) //PWM周期 100個單位
{
t=0; //使t=0,開始新的PWM周期
P1=0x00; //輸出端口
}
if(PWM_T==t) //按照當前占空比切換輸出為高電平
{
P1=0xff; //
}
}
|