51单片机入门程序——秒表程序示例

下午自学了一下单片机的前几章的知识,理解了数码管的显示原理以及静态显示和动态扫描的编程方法。其中,比较重要的几个概念有:数码管公共端类型(共阴极、共阳极)、位选(决定多位数码管中哪一位显示)、段选(决定数码管显示的数字),另外还有锁存器(教材P36,可通过控制锁存端来改变数据输出的状态)。

上周单片机实验课的内容是编一个秒表,在4位数码管中分别显示分和秒还有分秒,即最多可显示“9:59.9”。这里我用两个键实现了秒表的启动/暂停和清零功能,代码如下:

#include <reg51.h>
#define uint unsigned int
#define uchar unsigned char
sbit S1 = P1^3;
sbit S2 = P1^1;
sbit S3 = P1^2;
sbit S4 = P1^0;
sbit beep = P2^7;
sbit a = P0^0;
sbit b = P0^1;
sbit c = P0^2;
sbit d = P0^3;
sbit e = P0^4;
sbit f = P0^5;
sbit g = P0^6;
sbit p = P0^7;
sbit key1 = P1^4;
sbit key2 = P1^5;
sbit key3 = P3^6;
sbit key4 = P3^7;
uchar num,kms,sec,min;
uchar code N[10] = {0xc0, 0xf9 ,0xa4, 0xb0, 0x99, 0x92, 0x82, 0xf8, 0x80, 0x90}; //0, 1, 2, 3, ...8, 9
uchar code Z[10] = {0x40, 0x79 ,0x24, 0x30, 0x19, 0x12, 0x02, 0x78, 0x00, 0x10}; //0., 1., 2., ... 8., 9.

void delayms(uint xms)
{
	uint i,j;
	for(i = xms; i > 0; i--)
		for(j = 110; j > 0; j--);
}

void init()
{
	TMOD = 0x01;
	TH0 = 0x3c;
	TL0 = 0xb0;
	S3 = 1;
	S1 = S2 = S4 = 0;
	P0 = N[0];
	delayms(5);

	S3 = 0;
	S1 = S2 = S4 = 1;
	P0 = Z[0];
	delayms(5);

	EA = 1;
	TR0 = 0;
	ET0 = 1;	
	kms = sec = min = 0;
}

void display()
{
	uchar shi, ge;
	if(kms >= 0)
	{
		S4 = 0;
		S1 = S2 = S3 = 1;
		P0 = N[kms];
	}
	delayms(5);
	if(sec >= 0)
	{
		shi = sec/10;
		ge = sec%10;

		S3 = 0;
		S1 = S2 = S4 = 1;
		P0 = Z[ge];
		delayms(5);

		S2 = 0;
		S1 = S3 = S4 = 1;
		P0 = N[shi];
	}
	delayms(5);
	if(min >= 0)
	{
		S1 = 0;
		S2 = S3 = S4 = 1;
		P0 = N[min];
	}
	delayms(5);
}

void keyscan()
{
	if(key1 == 0)
	{
		delayms(10);
		if(key1 == 0)
		{
			while(!key1);
			TR0 = ~TR0;
		}
	}
	if(key2 == 0)
	{
		delayms(10);
		if(key2 == 0)
		{
			min = sec = kms = 0;
			while(!key1);
		}
	}
}

main()
{
	init();
	while(1)
	{
		keyscan();
		display();		
	}
}

void T0_time() interrupt 1
{
	TH0 = 0x3c;
	TL0 = 0xb0;
		num++;
	if(num == 2)
	{
		num = 0;
		kms++;
		if(kms == 10)
		{
			kms = 0;
			sec++;
			if(sec == 60)
			{
				sec = 0;
				min++;
				if(min == 10)
				{
					TR0 = 0;
					min = 9;
					sec = 59;
					kms = 9;
				}
			}
		}
	}
} 

程序通过“Keil uVision4”调试,大家也可以在板子上运行一下试试。

注意:需要根据板子的端口定义相关变量,不要不分青红皂白就直接使用我的程序哈。

最后上个图,第一次做单片机,希望以后还有时间可以做更深入的更好玩的东西。


©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页