📄 c51.txt
字号:
//PWM 调制程序 C51 2008-4-2 18:24:00
/*pwm 调制程序*/
/*说明: key用来控制 脉宽的高电平时间,
可以在P2.0引脚 接一个led做测试*/
#include <reg51.h>
#define CIRCLE 10
void pwmkey(void);
unsigned char count=1,last;
sbit led=P2^7;
sbit key=P0^0;
void main(void)
{
EA=1;
ET0=1;
TH0=(65536-2000)/256;
TL0=(65536-2000)%256;
TR0=1;
count=1;
last=1;
while(1)
{
pwmkey();
}
}
void pwmkey(void)
{
char old=0 ,new=0;
while(1)
{
new=key;
if(new && !old)
last++;
if(last>CIRCLE)
last=1;
old=new;
}
}
void into(void) interrupt 1
{
count++;
if(count>CIRCLE)
{
count=1;
}
if(count<=last)
led=0;
else
led=1;
TH0=(65536-2000)/256;
TL0=(65536-2000)%256;
}
改进型~
增加了防抖动检测。
带宽增长了点。
//PWM 调制程序 C51 2008-4-2 18:24:00
/*pwm 调制程序*/
/*说明: key用来控制 脉宽的高电平时间,
可以在P2.0引脚 接一个led做测试*/
#include <reg51.h>
#define CIRCLE 10
void delayms(uchar); //声明延时函数
#define uchar unsigned char
void pwmkey(void);
unsigned char count=1,last;
sbit led=P2^7;
sbit key=P0^0;
int i,j;
void main(void)
{led=0;
for(i=0;i<=255;i++)
{for(j=0;j<=255;j++);}
led=1;
for(i=0;i<=255;i++)
{for(j=0;j<=255;j++);}
EA=1;
ET0=1;
TH0=(65536-2000)/256;
TL0=(65536-2000)%256;
TR0=1;
count=1;
last=1;
while(1)
{
pwmkey();
}
}
void pwmkey(void)
{
while(1)
{
A:if (key==0)
{delayms(20);
if(key==0)
{last++;
if(last>CIRCLE)
last=1;
b:if (key==1)
{delayms(20);
if (key==1) goto A;
else goto b;}
else goto b;
}
else
{goto A;}
}
}
}
void interr(void) interrupt 1 using 1
{
count++;
if(count>CIRCLE)
{
count=1;
}
if(count<=last)
led=0;
else
led=1;
TH0=(65536-2000)/256;
TL0=(65536-2000)%256;
}
void delayms(uchar j) //延时子程序
{char n,m;
for(n=0;n<j;n++)
{for(m=0;m<120;m++) //延时时间为1ms
{;}
}
}
再改进~~
#include <reg51.h>
#define CIRCLE 10
#define uchar unsigned char
void pwmkey(void);
unsigned char count=1,last;
sbit led=P1^7;
sbit key=P3^3;
int k;
void main(void)
{
EA=1;
ET0=1;
TH0=(65536-2000)/256;
TL0=(65536-2000)%256;
TR0=1;
count=1;
last=0;
while(1)
{
pwmkey();
}
}
void pwmkey(void)
{
while(1)
{
A:if (key==0)
{for(k=1;k<=255*40;k++);
if(key==0)
{last++;
if(last>CIRCLE)
last=0;
b:if (key==1)
{for(k=1;k<=255*40;k++);
if (key==1) goto A;
else goto b;}
else goto b;
}
else
{goto A;}
}
}
}
void interr(void) interrupt 1 using 1
{
count++;
if(count>CIRCLE)
{
count=1;
}
if(count<=last)
led=0;
else
led=1;
TH0=(65536-2000)/256;
TL0=(65536-2000)%256;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -