51单片机定时器之秒表计时+按键修改时间

代码如下(示例):

#include <reg51.h>
#define uchar unsigned char
#define uint unsigned int
code uchar num[]=
{0xC0,0xF9,0x64,0x70,0x59,0x52,0x42,0xF8,0x40,0x50};
uchar oldkey=0xff;
void delay(uint i)
{
	  while(i--); 
} 
sbit SMG_0 = P1^3;
sbit SMG_1 = P1^2;
sbit SMG_2 = P1^4;
sbit SMG_3 = P1^1;
sbit led=P2^1;
sbit key1 = P3^7;
sbit key2 = P3^6;
sbit key3 = P3^5;
sbit key4 = P3^4;
uchar kk;
unsigned char ReadKey(void)	
{
	unsigned char lkey=0;
	if((P3&0xfc)!=0xfc){
		delay(10);
		if(oldkey!=(P3&0xfc)){
			oldkey=P3&0xfc;
			if(key1==0)
				lkey=1;
			else if(key2==0)
				lkey=2;
				else if(key3==0)
				lkey=3;
			else if(key4==0)
				lkey=4;
		}
	}
	else{
		oldkey=0xfc;
	}
	return lkey;
}
void display(uchar a,uchar b)
{
uchar aa=0,bb=0,cc=0,dd=0;
P0=0XFF;
	
SMG_0 = 1;
SMG_1 = 1;
SMG_2 = 1;
SMG_3 = 0;
aa=a%10;	
P0=num[aa];                      
delay(250);                                             

SMG_0 = 1;
SMG_1 = 1;
SMG_2 = 0;
SMG_3 = 1;
bb=a/10;
P0=num[bb];
delay(250); 
	
SMG_0 = 1;
SMG_1 = 0;
SMG_2 = 1;
SMG_3 = 1;
cc=b%10;	
P0=num[cc];                     
delay(250);                         

SMG_0 = 0;
SMG_1 = 1;
SMG_2 = 1;
SMG_3 = 1; 
dd=b/10;	
P0=num[dd];                     
delay(250);                         

}
void main()
{
	uchar ms=59;
	uchar min=59;
	uchar hour=23;
	TMOD=0x01;
	TH0=(65536-10000)/256;
	TL0=(65535-10000)%256;
	EA=1;
	ET0=1;
	TR0=1;

	while(1)
	{	
		switch(ReadKey()){			
		case 1:min++;
		break;
		case 2:min--;	
		break;
		case 3:hour++;
		break;
		case 4:hour--;	
		break;
		}		
		if(min>59)
		{
			min=0;
			hour++;
		}
		if(hour>23)
		{
			hour=0;
			min=0;			
		}
		
		if(kk==100)		
		{ 
			kk=0;
			led=!led;			
			ms++;					
			if(ms>60)
		   {
			  ms=0;
			  min++;
			  if(min>59)
			  {
				 min=0;
				 hour++;
			  }
		   }
	  }		
   
display(min,hour);

}

}	

void timer0() interrupt 1
{
	TH0=(65536-10000)/256;
	TL0=(65535-10000)%256;
     kk++;
}
  • 3
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值