#include <avr/io.h>
#include <avr/interrupt.h>

unsigned  char led_digit[] = {0x18, 0xBB, 0x2C, 0x29, 0x8B, 0x49, 0x48, 0x3B, 0x08, 0x09};

volatile unsigned int adc_result=0;
volatile  long timer0=0;
volatile unsigned char display_ledA, display_ledB;

void display_sevenLED(int i)
{
 switch(i){
  case 3:
   PORTC = (PORTC | 0xF0) & ~(1<<PC7);
   PORTA = led_digit[ (display_ledA % 100) / 10 ];
   break;

  case 2:
   PORTC = (PORTC | 0xF0) & ~(1<<PC6);
   PORTA = led_digit[ display_ledA % 10];
   break;

  case 1:
   PORTC = (PORTC | 0xF0) & ~(1<<PC5);
   PORTA = led_digit[ (display_ledB % 100) / 10 ];
   break;

  case 0:
   PORTC = (PORTC | 0xF0) & ~(1<<PC4);
   PORTA = led_digit[ display_ledB % 10];
   break;
  
  default:
   break;
 }
}  

SIGNAL(SIG_ADC)
{
 adc_result = ADC;
}

SIGNAL(SIG_OVERFLOW0)
{
 timer0++;

 display_sevenLED(timer0 % 4);
}

void enable_adc_interrupt(unsigned char channel)
{
 // Aref, Channel setting 
 ADMUX = (ADMUX & 0xE0) | (channel & 0x1F);
 // AD enable, Interrupt enable, 1/128
 ADCSRA = (1<<ADEN) | (1<<ADIE) | 7;  
 ADCSRA |= 1<<ADFR | 1<<ADSC; // Free run mode, ADC start
}

//////////////////////////////////////////////////////////////
int main(void)
{
 DDRA = 0xFF;    // seven segment output
 DDRC = 0xF0;    // seven segment selection
 PORTC = 0xF0;
 
 TIMSK |= 1<<TOIE0;  // Timer0 overflow interrupt enable
 TCCR0 = 0x5;   // 128 prescaler
 
 enable_adc_interrupt(0);
 
 sei();     // start global interrupt

 while(1){
  display_ledA = adc_result / 20;
 }
}

