用定时器我会写程序如下,根据PWM_ON的大小控制电压大一,PWM_ON越大电压就越大,CYCLE是电压等级,随便调。
#include<reg52.h>
#include <intrins.h>
#define uint unsigned int
#define uchar unsigned char
uchar CYCLE,PWM_ON,PWM_Z;
sbit pwm1=P1^0; //PWM
void delay(unsigned int t)
{
while(t--);
}
void main()
{
TMOD =0x01;
TH0=(65536-100)/256;
TL0=(65536-100)%256; //定时0.1mS
EA=1;
ET0=1;
TR0=1;
CYCLE = 5; // 时间可以调整 这个是10调整 8位PWM就是256步
while(1)
{
PWM_ON++;
delay(20000);
if(PWM_ON=CYCLE)
PWM_ON=0;
}
void tim(void) interrupt 1
{
static unsigned char count;
TH0=(65536-100)/256;
TL0=(65536-100)%256; //定时0.1mS
if (count==PWM_ON)
{
pwm1 = 0;
}
count++;
if(count == CYCLE)
{
count=0;
if(PWM_ON!=0)
pwm1 = 1;
}
} |