#include <io.h>
#include <delay.h> 

void main(void)
{      
    unsigned char delayCnt = 0;
    unsigned char digitSelect = 0;
    unsigned char i = 0;
    unsigned long num = 0;   
    unsigned long temp;
    unsigned char sevenSegDigit[8];   
    unsigned char blinkTick = 0;   
    unsigned char enterPressed = 0;
    unsigned char incHandled = 0;
    unsigned char sevenSegNum[10] = {
        0xC0,0xF9,0xA4,0xB0,0x99,
        0x92,0x82,0xF8,0x80,0x90
    };        

    DDRC = 0xFF;
    DDRD = 0xFF;   
    DDRB = 0xFF;
    
    DDRA &= ~((1 << 0) | (1 << 1));
    PORTA |= ((1 << 0) | (1 << 1));
             
    temp = num;
    for(i = 0; i < 8; i++)
    {
        sevenSegDigit[i] = sevenSegNum[temp % 10];
        temp /= 10;
    }
       
    while(1)
    {      
        PORTC = 0xFF;               
        PORTD = 1 << digitSelect;  
        PORTC = sevenSegDigit[digitSelect];
        digitSelect++;
        if(digitSelect >= 8)
        {                  
            digitSelect = 0;
        }   
          
        // Inc  
        if(!PINA.0 && !incHandled)
        {    
            incHandled = 1;                                
            num++;     
            temp = num;
            for(i = 0; i < 8; i++)
            {
                sevenSegDigit[i] = sevenSegNum[temp % 10];
                temp /= 10;
            }
            
        }     
        
        if(PINA.0)
        {     
            incHandled = 0;     
        }
              
        // Enter
        if((PINA & (1 << 1)) == 0)
        {       
            enterPressed = 1;                   
        }      
        
        if(enterPressed)
        {              
            if(++blinkTick >= 100)
            {                  
                blinkTick = 0;
                PORTB = ~PORTB;
                if(PORTB == 0)
                {
                    num--; 
                    if(num == 0)
                    {          
                        enterPressed = 0;    
                    }
                    
                    temp = num;
                    for(i = 0; i < 8; i++)
                    {
                        sevenSegDigit[i] = sevenSegNum[temp % 10];
                        temp /= 10;
                    }                                    
                }   
            }                                        
        }
                   
        delay_ms(5);    
        
    }
}
   


