基于51单片机的数码管时钟设计——按键修改时间

视频演示

哔哩哔哩视频演示

Proteus 仿真图

基于51单片机的数码管时钟设计——按键修改时间_第1张图片

代码:

#include

typedef unsigned char uchar;
typedef unsigned int uint;

//按键定义
sbit key_stop = P3^0;
sbit key_star = P3^1;
sbit key_fen = P3^2;
sbit key_shi = P3^3;

//0~9的十六进制数码
uchar code num[10] = {0xC0, 0xF9, 0xA4, 0xB0, 0x99, 0x92, 0x82, 0xF8, 0x80, 0x90};  // 0~9

//秒、分、时标志
uchar miao = 0, fen = 0, shi = 0;  

//秒、分、时高位低位
uchar miao_L, miao_H, fen_L, fen_H, shi_L, shi_H; 

//计数
uint counter = 0;  


void delay(uint x){  //延时函数
	while(x--)
		;
}//delay

void key_delay(int xms){  //按键延时函数 x ms
	unsigned int i, j;
	for(i=0; i<xms; ++i)
		for(j=0; j<110; ++j)
			;
}//key_delay

void T0_Init(){  //定时器初始化
	
	TMOD = 0x01; 
	TH0 = 0x3c;  
	TL0 = 0xb0;	 
    EA = 1;  //开总中断
	ET0 = 1;     
	TR0 = 1;    
}//T0_Init

void display(){  //显示函数
	
	P2 = 0x20;  
	P0 = 0xbf;	
	delay(50);
		
	P2 = 0x04; 
	P0 = 0xbf;
	delay(50);

	P2 = 0x80;  // 1000 0000
	P0 = num[miao_L];  
	delay(50);

	P2 = 0x40;	// 0100 0000
	P0 = num[miao_H]; 
	delay(50);

	P2 = 0x10;	// 0001 0000
	P0 = num[fen_L];  
	delay(50);

	P2 = 0x08;	// 0000 1000
	P0 = num[fen_H];  
	delay(50);

	P2 = 0x02;	// 0000 0010
	P0 = num[shi_L];  
	delay(50);
	
	P2 = 0x01;	// 0000 0001
	P0 = num[shi_H]; 
	delay(50);

}//display

void keyscan(){  //按键函数

	if(key_stop == 0){
		key_delay(20);
		if(key_stop == 0){
			EA = 0;  //关总中断,即停止
			while(!key_stop);
		}
	}//key_stop
	
	if(key_star == 0){
		key_delay(20);
		if(key_star == 0){
			EA = 1;  //开总中断
			while(!key_star);
		}
	}//key_star	
	
	if(key_fen == 0){
		key_delay(20);
		if(key_fen == 0){
			fen++;
			while(!key_fen);
		}
	}//key_fen++
	
	if(key_shi == 0){
		key_delay(20);
		if(key_shi == 0){
			shi++;
			while(!key_shi);
		}
	}//key_shi++
}

void main(){

	T0_Init(); 
	
	while(1){

		display();
		
        keyscan();		
   }

}//main

void timer0_Init() interrupt 1{  //中断函数 
 	 
	 counter++;

	 if(counter == 20){
	 	counter = 0;  
	 	miao++;	//i = 100 

		if(miao == 60){
			miao = 0;  
			fen++;

			if(fen == 60){
				fen = 0;  
				shi++;

				if(shi == 24){
					shi = 0;
					fen = 0;
					miao = 0;
				}
			}
		}

		miao_L = miao%10;  
		miao_H = miao/10; 

		fen_L = fen%10; 
		fen_H = fen/10;  

		shi_L = shi%10;  
		shi_H = shi/10;

	 }
 }//timer0_Init

完整工程

时钟——两组实验.zip

你可能感兴趣的:(51单片机,单片机,时钟,定时器,按键)