#include<reg52.h>
#define uchar unsigned char
#define uint unsigned int
sbit wela=P2^0;
sbit dula=P2^1;
uchar code tablewe[]={
0xfe,0xfd,0xfb,0xf7,0xef,0xdf,0xbf,0x7f};
uchar code tabledu[]={
0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};
uchar Data[8];	 //存储显示值的全局变量
sbit dc1=P1^1;	//定义电机信号输出端口
uchar pwm_on;	//定义速度等级
#define cycle 10	//周期
void delay(uchar t)
{
	while(--t);
}
void delayMS(uchar t)
{
	while(t--)
	{
		delay(245);
		delay(245);
	}
}
void display(uchar f,uchar n);
uchar keyscan();
void init();
void main()
{
	uchar num;
	pwm_on=0;	 //速度等级赋初值
	init();

	Data[0]=0x5e;	//'d'
	Data[1]=0x39;   //'c'
	while(1)
	{
		num=keyscan();
		if(num==1)			//第一个按键,速度等级增加
		{
			if(pwm_on<cycle)
			{
				pwm_on++;
			}
		}
		else if(num==2)		//第二个按键,速度等级减小
		{
			if(pwm_on>0)
			{
				pwm_on--;
			}
		}
		Data[5]=tabledu[pwm_on/10];	  //显示速度等级
		Data[6]=tabledu[pwm_on%10];
	}
}
void init()		   //初始化定时器
{
 	TMOD=0x01;
	EA=1;
	ET0=1;
	TR0=1;
	//PT0=1;	//开优先级(有多个中断时使用)
}
void display(uchar f,uchar n)		//数码管显示函数
{
	static uchar i;		  //定义静态变量
	P0=0;		   //消隐
	dula=1;
	dula=0;

	P0=tablewe[i+f];
	wela=1;
	wela=0;

	P0=Data[i];
	dula=1;
	dula=0;

	i++;
	if(i==n)
		i=0;
}
void timer0() interrupt 1	   //定时器中断
{
    static uchar times;
	TH0=(65536-2000)/256;
	TL0=(65536-2000)%256;
	display(0,8);

	if(times==pwm_on)	 //如果定时的时间等于on的时间,说明作用时间结束,输出低电平
	{
		dc1=0;
	}			  //pwm_on越大,占空比越大,速度越大。
	times++;	  //on的延时时间越长,相应的关的时间越短,从而占空比越大,速度越快。所以调节pwm——on即为调节直流电机转动的占空比
	if(times==cycle)	 //反之,低电平时间结束后返回高电平
	{
		times=0;
		if(pwm_on!=0)		 //如果开启的时间是0,保持原来状态
		{
			dc1=1;
		}
	}
}
uchar keyscan()
{
	uchar value;
	if(P3!=0xff)
	{
		delayMS(10);
		if(P3!=0xff)
		{
			value=P3;
			while(P3!=0xff);
			switch(value)
			{
				case 0xfe:return 1;break;
				case 0xfd:return 2;break;
				case 0xfb:return 3;break;
				case 0xf7:return 4;break;
				case 0xef:return 5;break;
				case 0xdf:return 6;break;
				case 0xbf:return 7;break;
				case 0x7f:return 8;break;
				default :return 0;break;
			}
		}
	}
	return 0;
}

 

posted on 2011-11-18 21:54    阅读(262)  评论(0编辑  收藏  举报