赞
踩
1.新建项目,编写main代码
#include <REGX52.H>
sbit LED=P2^0;
void Delay(unsigned char i) //需要用这个延时函数,以前的延时只是1us
{
while(i--);
}
void main()
{
unsigned char time=0,latency;
while(1)
{
for(time=0;time<100;time++) //改变亮灭时间,由暗到亮
{
for(latency=0;latency<20;latency++) //保持一个状态20次
{
LED=0; //LED亮
Delay(time); //延时时间
LED=1; //LED灭
Delay(100-time); //延时100-time
}
}
for(time=100;time>0;time--) //翻转改变亮灭时间,由亮到暗
{
for(latency=0;latency<20;latency++) //保持一个状态20次
{
LED=0; //LED亮
Delay(time); //延时时间
LED=1; //LED灭
Delay(100-time); //延时100-time
}
}
}
}
至此呼吸灯完毕
1.新建项目,导入Delay、Timer0、Key、数码管相关文件代码
2.将呼吸灯代码修改为以定时器控制
通过设置Compare的值,就可以实现控制直流电机的PWM
#include <REGX52.H>
#include "Nixie.h"
#include "Key.h"
#include "Timer0.h"
sbit LED = P2^0;
unsigned char keynum,speed;
unsigned char Counter, Compare;
void main()
{
Compare = 5;
Timer0Init();
while(1)
{
keynum=Key();
if(keynum==1)
{
Compare=0;
speed=0;
}
if(keynum==2)
{
Compare=50;
speed=2;
}
if(keynum==3)
{
Compare=75;
speed=3;
}
if(keynum==4)
{
Compare=100;
speed=4;
}
Nixie(1,speed);
}
}
void Timer0_Routine() interrupt 1
{
TL0 = 0x9C; //设置定时初值
TH0 = 0xFF; //设置定时初值
Counter++;
Counter%=100;
if(Counter < Compare)
{
LED=0;
}
else
{
LED=1;
}
}
3.将直流电机代入,要注意电机1是转,0是不转
#include <REGX52.H>
#include "Nixie.h"
#include "Key.h"
#include "Timer0.h"
sbit Motor = P1^0;
unsigned char keynum,speed;
unsigned char Counter, Compare;
void main()
{
Compare = 5;
Timer0Init();
while(1)
{
keynum=Key();
if(keynum==1)
{
Compare=0;
speed=0;
}
if(keynum==2)
{
Compare=50;
speed=2;
}
if(keynum==3)
{
Compare=75;
speed=3;
}
if(keynum==4)
{
Compare=100;
speed=4;
}
Nixie(1,speed);
}
}
void Timer0_Routine() interrupt 1
{
TL0 = 0x9C; //设置定时初值
TH0 = 0xFF; //设置定时初值
Counter++;
Counter%=100;
if(Counter < Compare)
{
Motor=1;
}
else
{
Motor=0;
}
}
4.效果展示
直流电机驱动
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。