定时器计时,并在数码管实时显示时间

/****************************************************************************

  用定时器计时,并将实时秒数显示到数码管上面,本例仅支持0-99显示

*****************************************************************************/

#include <reg52.h>

#define uchar unsigned char

#define uint unsigned int

uint code a[]= {0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};

sbit WE = P2^7;

sbit DU = P2^6;

void delay(uint i);

void display(uchar i);

void delay(uint i)  //普通延时函数

{

    uint x,y;

    for(x = 0;x < i;x++)

        for(y = 0;y < 114;y++);

}

void display(uchar i)

{

    uchar one,two;

    one = i / 10; //十位数的数值

    two = i % 10; //个位数的数值

    P0 = 0xff;    //防止重影,消影手段

    WE= 1; //位选打开

    P0 = 0xfe;

    WE = 0;

   

    DU = 1;   //段选打开

    P0 = a[one];//第一个数码管显示十位数

    DU = 0;

    delay(5);

    P0 = 0xff;

    WE = 1;

    P0 = 0xfd;

    WE = 0;

   

    DU = 1;

    P0 = a[two];//第二个数码管显示个位数

    DU = 0;

    delay(5);

}

void main()

{

    TR1= 1;  //打开定时计数器1

    TMOD = 0x10; //工作方式设置为定时器

    TH1 = 0x4b; //装入初值,根据单片机的晶振和你打算计算的时间有关

    TL1 = 0xfc;   //单片机晶振为11.0592,计时50ms;装入0x4bfc;

    while(1){

        uchar m,b;

        if(TF1 == 1){ //检测TF1位是否为1,是则说明定时器已装满一次

            TH1 = 0x4b; //重新装入初值

            TL1 = 0xfc;

            TF1 = 0;  //将TF1位重新置0

            m++;       //装满次数,即50ms的次数

        }

        if(m == 20){    //当20次装满50ms时,则过了1s

            m = 0;      //将次数置0,继续计时下一秒

            b++;        //程序执行的总时间,总秒数

        }

        display(b);    

    }

   

}

猜你喜欢

转载自blog.csdn.net/Xiao_peng117/article/details/78786701