蓝桥杯单片机学习 ④使用定时器实现秒表

实验功能:利用定时器实现秒表,通过按键S4启动或暂停,按键S5清零

代码:

#include <STC15F2K60S2.H>
#include "intrins.h"

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

unsigned char t_fen = 0;
unsigned char t_s = 0;
unsigned char t_ms = 0;

unsigned char code SMG_NoDot[18]={
	0xc0,0xf9,0xa4,0xb0,0x99,0x92,//5
	0x82,0xf8,0x80,0x90,0x88,
	0x80,0xc6,0xc0,0x86,0x8e,
	0xbf,0x7f};

void Delay1ms(int x);

void InitHC138(unsigned char n)
{
	switch(n)
	{
		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 ShowSMG(unsigned char value,unsigned char pos)
{
	InitHC138(6);
	P0 = 0x01<<pos;
	InitHC138(7);
	P0 = value;
}

void DisplayInit()
{
	ShowSMG(SMG_NoDot[t_ms % 10],7);Delay1ms(2);
	ShowSMG(SMG_NoDot[t_ms / 10],6);Delay1ms(2);	
	ShowSMG(SMG_NoDot[16],5);Delay1ms(2);
	
	ShowSMG(SMG_NoDot[t_s % 10],4);Delay1ms(2);	
	ShowSMG(SMG_NoDot[t_s / 10],3);Delay1ms(2);
	ShowSMG(SMG_NoDot[16],2);Delay1ms(2);
	
	ShowSMG(SMG_NoDot[t_fen % 10],1);Delay1ms(2);
	ShowSMG(SMG_NoDot[t_fen / 10],0);Delay1ms(2);	
}

void KeyInit()
{
	if(S4 == 0)
	{
		Delay1ms(20);
		if(S4 == 0)
		{
			TR0 = ~TR0;
			while(S4 == 0);
		}
	}
	if(S5 == 0)
	{
		Delay1ms(20);
		if(S5 == 0)
		{
			t_fen = 0;
			t_s = 0;
			t_ms = 0;
			while(S5 == 0);
		}
	}	
}

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

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

void main()
{
	Timer0Init();
	while(1)
	{
		DisplayInit();
		KeyInit();
	}
}

void Delay1ms(int x)		//@11.0592MHz
{
	int y;
	y = x;
	while(x--)
	{
		unsigned char data i, j;

		_nop_();
		_nop_();
		_nop_();
		i = 11;
		j = 190;
		do
		{
			while (--j);
		} while (--i);
	}
	x = y;
}

实验结果:

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值