  #include <avr/io.h>
  #include <util/delay.h>
  
  #define F_CPU  1000000
  #define SEG1_LATCH   PB0
  #define SEG2_LATCH   PB1
  #define POWER_LATCH  PB6
  #define LED_LATCH    PB7

  unsigned char font[] = {
	  0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07,
	  0x7f, 0x6f, 0x77, 0x7c, 0x58, 0x5e, 0x79, 0x71
  };

  // initialize adc
  void adc_init()
  {
	  // AREF = AVcc
	  ADMUX = (1<<REFS0);

	  // ADC Enable and prescaler of 128
	  // 16000000/128 = 125000
	  ADCSRA = (1<<ADEN)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0);
  }

  // read adc value
  uint16_t adc_read(uint8_t ch)
  {
	  // select the corresponding channel 0~7
	  // ANDing with '7' will always keep the value
	  // of 'ch' between 0 and 7
	  ch &= 0b00000111;  // AND operation with 7
	  // clears the bottom 3 bits before ORing
	  ADMUX = (ADMUX & 0xF8)|ch;

	  // start single conversion
	  // write '1' to ADSC
	  ADCSRA |= (1<<ADSC);

	  // wait for conversion to complete
	  // ADSC becomes '0' again
	  // till then, run loop continuously
	  while(ADCSRA & (1<<ADSC));

	  return (ADC);
  }
  
    void init_board() {
	    DDRD = 0xff;
	    PORTD = 0xff;
	    DDRB = 0xc3;

	    PORTB |= (1<<SEG1_LATCH);
	    PORTB &= ~(1<<SEG1_LATCH);
	    PORTB |= (1<<SEG2_LATCH);
	    PORTB &= ~(1<<SEG2_LATCH);
	    PORTB |= (1<<POWER_LATCH);
	    PORTB &= ~(1<<POWER_LATCH);
	    PORTB |= (1<<LED_LATCH);
	    PORTB &= ~(1<<LED_LATCH);
    }


  int main()
  {
	  uint16_t adc_result3;
      init_board();
	  adc_init();

	  _delay_ms(50);

	  while(1)
	  {
		  // read adc value at PC1
		  adc_result3 = adc_read(3)/10.3;
		  PORTD = ~font[adc_result3/10];
		  PORTB = 0x02;
		  PORTB = 0;
		  PORTD = ~font[adc_result3%10];
		  PORTB = 0x01;
		  PORTB = 0;
		  _delay_ms(50);
	  }
  }

