1

/*简易电子时钟,不可调时间,不可定时*/


#include<reg52.h>
#define unit unsigned int      //宏定义,为了方便使用unsigned int
#define uchar unsigned char
sbit wela=P2^7;          //数码管位锁存
sbit dula=P2^6;          //数码管段锁存

uchar code table[]={0x3f,0x06,0x5b,0x4f,0x66,
                0x6d,0x7d,0x07,0x7f,0x6f};        //数字0~9
uchar code table01[]={0xbf,0x86,0xdb,0xcf,0xe6,
                0xed,0xfd,0x87,0xff,0xef};        //数字0.~9.
       
unit miao=0,fen=0,shi=0;
unit n,m,x,y,z;
unit shi01,shi02,fen01,fen02,miao01,miao02;


void write_address(uchar address)      //选择哪个数码管亮
{
    wela=1;
    P0=address;
    wela=0;
}

void write_shu(m)               //设定亮哪个数
{
    dula=1;
    P0=table[m];
    dula=0;
}

void write_shudian(m)           //设定亮哪个数(带点)
{
    dula=1;
    P0=table01[m];
    dula=0;
}

void delay(z)    //延迟函数,可随意设置,不影响时钟时间,以画面不闪烁为宜
{
    for(x=z;x>0;x--)
        for(y=125;y>0;y--);
}

void display(void)
{
    write_address(0xfe);
    write_shu(shi01);
    P0=0xff;
    delay(1);

    write_address(0xfd);
    write_shudian(shi02);
    P0=0xff;
    delay(1);

    write_address(0xfb);
    write_shu(fen01);
    P0=0xff;
    delay(1);    

    write_address(0xf7);
    write_shudian(fen02);
    P0=0xff;
    delay(1);    

    write_address(0xef);
    write_shu(miao01);
    P0=0xff;
    delay(1);    

    write_address(0xdf);
    write_shu(miao02);
    delay(1);    
}

void time_init(void)
{
    TMOD=0x01;                 //选择定计时器T0,工作方式1
    TR0=1;                     //打开TO定时器
    TH0=(65536-46080)/256;     //晶振频率11.0592MHz
    TL0=(65536-46080)%256;     //定时50ms
    ET0=1;                     //打开IE控制寄存器TO开关
    EA=1;                       //打开IE控制寄存器总开关
}

void main(void)
{    
    time_init();
    while(1)           //while循环不可缺少
    {
        if(n==20)
        {
            n=0;
            miao++;
            if(miao==60)
            {
                miao=0;
                fen++;
                if(fen==60)
                {
                    fen=0;
                    shi++;
                    if(shi==24)
                    {
                        shi=0;
                    }
                }
            }
        }    
    shi01=shi/10;           //取整,计算时针的十分位
    shi02=shi%10;           //取余,计算时针的个位
    fen01=fen/10;
    fen02=fen%10;
    miao01=miao/10;
    miao02=miao%10;        
    display();
    }
}    

void timer(void)interrupt 1
{
      TH0=(65536-46080)/256;      //计时器清零
    TL0=(65536-46080)%256;
    n++;    
}

我是敌法师
16 声望9 粉丝