51单片机实现小时钟
文章目录
实验环境
软件: Keil5+Proteus7
元件:
仿真图
代码实现
/*********程序********/
#include <reg52.h>
#include <intrins.h>
#define uchar unsigned char
#define uint unsigned int
#define LBIT P0 //位型接P0
#define LNUM P2 //字型接P2
//存放LED的点阵码数组,对应0~15,HPLV
uchar code ledTab[]={
0x3F,0x06,0x5B,0x4F,0x66,
0x6D,0x7D,0x07,0x7F,0x6F,0x40,
0x77,0x7C,0x39,0x5E,0x79,
0x71,0x76,0x73,0x38,0x3e};
//存放显示位对应的码对应1~8位
uchar code tabIndex[]={
0xFE,0xFD,0xFB,0xF7,0xEF,0xDF,0xBF,0x7F};
uchar Num[8]={
0}; //存放显示的数据
uchar Num0[8]={
0x00,0x01,0x02,0x03,0x04,0x05,0x09,0x0A};
uchar tcnt=0; //定义计数次数
uchar second=45; //定义秒
uchar minute=59; //定义分
uchar hour=23; //定义时
/***********************************
T0中断服务子程序
***********************************/
timer1()interrupt 1 using 1
{
tcnt++;
TH0=(65536-40000)/256; //定时40ms
TL0=(65536-40000)%256;
if(tcnt==60) //调节速度
{
tcnt=0;
second=(second+1)%60;
if(second%10==0&&second/10%10==0){
minute=(minute+1)%60;
if(minute%10==0&&minute/10%10==0)
hour=(hour+1)%24;
}
}
}
/***********************************
函数名称:Delay_us
函数功能:延时us级别
输入参数:要延时的微秒数
输出参数:无
***********************************/
void Delay_us(unsigned int time)
{
while(time--);
}
/********************************************************************
函数名称:dynamicLed
函数功能:实现LED的循环动态显示
输入参数:Counter 表示要点亮的LED的个数取值1~8
Light 灯的亮度的控制,数值越大灯越亮,取值范围0~255
输出参数:无
*********************************************************************/
void dynamicLed(unsigned char Counter,unsigned char Ligh)
{
unsigned char i;
for(i=0;i<Counter;i++)
{
Delay_us(Ligh);//实现灯亮度的调整
LNUM=0x00; //实现单个LED灯的点亮
LBIT=tabIndex[i%8];
LNUM=ledTab[Num[i]%20];
}
}
/********************************************************************
函数名称:saveInt_times
函数功能:保存计数次数
输入参数:int_times表示计数次数
flag为0时,保存成十六进制
为1时,保存成BCD码
输出参数:无
*********************************************************************/
void saveInt_times(bit flag,uchar int_times,uchar minute,uchar hour)
{
if(flag==0)
{
Num[0]=int_times&0x0f;
int_times>>=4;
Num[1]=int_times&0x0f;
}
else
{
Num[0]=int_times%10;
Num[1]=int_times/10%10;
Num[2]=Num0[7];
Num[3]=minute%10;
Num[4]=minute/10%10;
Num[5]=Num0[7];
Num[6]=hour%10;
Num[7]=hour/10%10;
}
}
/********************************************************************
函数名称:init
函数功能:初始化
输入参数:无
输出参数:无
*********************************************************************/
void init()
{
TMOD=TMOD&0x0f|0x10; //T1定时
TH0=(65536-40000)/256; //定时40ms
TL0=(65536-40000)%256;
EA=1; //开总中断
ET0=1; //允许T1中断
TR0=1;
}
/*********主程序********/
void main()
{
init();
//初始化
while(1)
{
saveInt_times(1,second,minute,hour);
dynamicLed(8,100);
}
}