首页 > 技术文章 > 51单片机学习笔记:秒表

Brimon-zZY 2020-10-09 17:15 原文

代码适用于清翔51板(STC89C52)

#include<reg52.h>

sbit WE = P2^7;
sbit DU = P2^6;
unsigned int code table[10] = {0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F};
unsigned int code duan[10] = {0,0xFE,0xFD,0xFB,0xF7,0xEF,0xDF,0xBF,0x7F};

//software delay
void softwaredelay()   
{
   unsigned char a,b;
    for(b=102;b>0;b--)
        for(a=3;a>0;a--);
}

void machinedelay()
{
	TR0 = 1;
	TMOD = 0x01;
	TH0 = 0x4B;
	TL0 = 0xFD;
}

void digitaltube(unsigned int du,unsigned int num)
{
	if(num == 0)
	{
		
		P0 = 0xFF;
		WE = 1;
		P0 = duan[du];
		WE = 0;
		
		DU = 1;
		P0 = table[0];
		DU = 0;
	}
	if(num == 1)
	{
		P0 = 0xFF;
		WE = 1;
		P0 = duan[du];
		WE = 0;
		
		DU = 1;
		P0 = table[1];
		DU = 0;
	}
	if(num == 2)
	{
		P0 = 0xFF;
		WE = 1;
		P0 = duan[du];
		WE = 0;
		
		DU = 1;
		P0 = table[2];
		DU = 0;
	}
	if(num == 3)
	{
		P0 = 0xFF;
		WE = 1;
		P0 = duan[du];
		WE = 0;
		
		DU = 1;
		P0 = table[3];
		DU = 0;
	}
	if(num == 4)
	{
		P0 = 0xFF;
		WE = 1;
		P0 = duan[du];
		WE = 0;
		
		DU = 1;
		P0 = table[4];
		DU = 0;
	}
	if(num == 5)
	{
		P0 = 0xFF;
		WE = 1;
		P0 = duan[du];
		WE = 0;
		
		DU = 1;
		P0 = table[5];
		DU = 0;
	}
	if(num ==6)
	{
		P0 = 0xFF;
		WE = 1;
		P0 = duan[du];
		WE = 0;
		
		DU = 1;
		P0 = table[6];
		DU = 0;
	}
	if(num == 7)
	{
		P0 = 0xFF;
		WE = 1;
		P0 = duan[du];
		WE = 0;
		
		DU = 1;
		P0 = table[7];
		DU = 0;
	}
	if(num == 8)
	{
		P0 = 0xFF;
		WE = 1;
		P0 = duan[du];
		WE = 0;
		
		DU = 1;
		P0 = table[8];
		DU = 0;
	}
	if(num == 9)
	{
		P0 = 0xFF;
		WE = 1;
		P0 = duan[du];
		WE = 0;
		
		DU = 1;
		P0 = table[9];
		DU = 0;
	}
}	
void main()
{
	unsigned int sec = 0;//the time
	unsigned int count;//used to control the time
	unsigned int dt1 = sec % 10;
	unsigned int dt2 = (sec / 10) % 10;
	unsigned int dt3 = (sec / 100) % 10;
	unsigned int dt4 = (sec/ 1000) % 10;
	machinedelay();
	while(1)
	{
	unsigned int dt4 = sec % 10;					//the Individual position
	unsigned int dt3 = (sec / 10) % 10;		//the ten position
	unsigned int dt2 = (sec / 100) % 10;	//the Hundred position
	unsigned int dt1 = (sec/ 1000) % 10;	//the Thousand position
		if(TF0 == 1)
		{
			TF0 = 0;
			TH0 = 0x4B;
			TL0= 0xFD;
			count ++;
			if(count == 20)
			{
				count = 0;
				sec ++;
			}
			
			if(sec == 9999)
			{
				sec =0;
			}
		}	
		digitaltube(1 , dt1);
		softwaredelay();
		digitaltube(2 , dt2);
		softwaredelay();
		digitaltube(3 , dt3);
		softwaredelay();
		digitaltube(4 , dt4);
		softwaredelay();
	}
}

 

推荐阅读