学习笔记——定时器的综合案例解析

目录

  • 一、任务简述
    • 1.1 任务要求
  • 二、实现方法
  • 三、参考代码

一、任务简述

在CT107D单片机上,利用定时器T0、数码管模块和两个独立按键(J5的2-3短接),设计一个秒表,具有清零,暂停,启动功能。

1.1 任务要求

1.显示格式:分-秒-0.05秒
例如:05-14-18 为 5分14秒900毫秒
2.独立按键S4:暂停/启动
独立按键S5:清零
按键均为按下有效。

二、实现方法

确定好函数编写,利用之前学过的知识实现本功能。

三、参考代码

#include "reg52.h"

sbit S4 = P3^3;
sbit S5 = P3^2;

/*void delay(unsigned int nms)
{
	unsigned int i,j;
	for(i = nms; i > 0; i--)
	{
		for(j = 110; j > 0; j--);
	}
}
*/
unsigned char code SEG[18] = {0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x88,0x83,0xc6,0xc0,0x86,0x8e,0xbf,0x7f};
unsigned char t_m = 0;
unsigned char t_s = 0;
unsigned char t_005s = 0;
	
/*void delay(unsigned int nms)   //延时50us误差 0us
{
    unsigned int i, j;
	for(i = nms; i > 0; i--)
        for(j = 110; j > 0; j--);
}
*/
void Select_HC573(unsigned char channel)
{
	switch(channel)
	{
		case 4:
			P2 = (P2 & 0x1f) | 0x80;
		break;
		case 5:
			P2 = (P2 & 0x1f) | 0xa0;
		break;
		case 6:
			P2 = (P2 & 0x1f) | 0xc0;
		break;
		case 7:
			P2 = (P2 & 0x1f) | 0xe0;
		break;
	}
}

void Display_SEG(unsigned char val,unsigned char pos)
{
	Select_HC573(6);
	P0 = 0x01 << pos;
	Select_HC573(7);
	P0 = val;
}
void delay_SEG(unsigned char t)
{
	while(t--);
}
void Timer_action()
{
	Display_SEG(SEG[t_005s % 10],7);
	delay_SEG(500);
	Display_SEG(SEG[t_005s / 10],6);
	delay_SEG(500);
	Display_SEG(SEG[16],5);
	delay_SEG(500);
	
	Display_SEG(SEG[t_s % 10],4);
	delay_SEG(500);
	Display_SEG(SEG[t_s / 10],3);
	delay_SEG(500);
	Display_SEG(SEG[16],2);
	delay_SEG(500);
	
	Display_SEG(SEG[t_m % 10],1);
	delay_SEG(500);
	Display_SEG(SEG[t_m / 10],0);
	delay_SEG(500);
	
}

void Intial_Timer0()
{
	TMOD = 0x01;
	TH0 = (65535 - 50000) / 256;
	TL0 = (65535 - 50000) % 256;
	
	ET0 = 1;
	EA = 1;
	TR0 = 1;	
}

void Service_Timer0() interrupt 1
{
	TH0 = (65535 - 50000) / 256;
	TL0 = (65535 - 50000) % 256;
	
	t_005s++;
	if(t_005s == 20)
	{
		t_s++;
		t_005s = 0;
	}
	if(t_s == 60)
	{
		t_m++;
		t_s = 0;
	}
	if(t_m == 99)
	{
		t_m = 0;
	}
}

void delay_Keys(unsigned char t)
{
	while(t--);
}

void ScanKeys()
{
	if(S4 == 0)
	{
		delay_Keys(100);
		TR0 = ~TR0;
		while(S4 == 0)
		{
			Timer_action();
		}
	}
	if(S5 == 0)
	{
		delay_Keys(100);
		if(S5 == 0)
		{
			t_005s = 0;
			t_s = 0;
			t_m = 0;
			while(S5 == 0)
		{
			Timer_action();
		}
		}
	}
}

void main()
{
	Intial_Timer0();
	while(1)
	{
		Timer_action();
		ScanKeys();
	}
}

你可能感兴趣的:(学习笔记,蓝桥杯,学习,单片机,c语言)