Search code examples
cmicrocontroller8051keil

8051 microcontroller lcd countdown timer


Currently i faced some problem on my lcd screen. I'm try to do a countdown timer but when i set Hour = 0, Min = 1, the sec hit 0 and my hour turn to some unknown character and min = 59, sec = 59. I'm i missing out something?

void Timer1(void) interrupt 3
{
    TF1 = 0;
    TH1 = 0xB1;
    TL1 = 0XE0;
    cd_msec--;

    if(cd_msec == 0)
    {
        cd_msec = 99;
        cd_sec--;
    }
    if(cd_sec == 0)
    {
        cd_sec = 59;
        cd_min--;
    }
    if(cd_min == 0) 
    {
        cd_min = 59;
        cd_hour--;
    }
    if(cd_hour == 0)
    {
        cd_hour = 0;
    }
    if(cd_hour == 0 && cd_min == 0)
    {
        cd_hour = 0;
        cd_min = 0;
    }
    if(cd_hour == 0 && cd_min == 0 && cd_sec == 0)
    {
        cd_hour = 0;
        cd_min = 0;
        cd_sec = 0;
        cd_msec = 0;
    }     

}

Solution

  • I agree with @nielsen that the logic is wrong. You may consider following approach to update all the variables properly at every millisecond tick.

    Also, I have assigned milli_sec to 999 considering that you will manage to get a 16 bit variable for it.

    if (milli_sec > 0)
    {
        milli_sec--
    } else {
        if (second > 0) {
            milli_sec = 999;
            second--;
        } else {
            if (minute > 0) {
                milli_sec = 999;
                second = 59
                minute--
            } else {
                if (hour > 0) {
                    milli_sec = 999;
                    second = 59;
                    minute = 59;
                    hour--
                }
                else {
                    //COUNTDOWN REACHED TO 0
                    //hour,minute,second,milli_second is zero
                }
    
            }
        }
    }