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

#define FOSC 8000000
#define BAUD 9600
#define MYUBRR FOSC/16/BAUD-1

#define sbi(var, mask)   ((var) |= (uint8_t)(1 << mask))
#define cbi(var, mask)   ((var) &= (uint8_t)~(1 << mask))

#define STATUS_LED 5

#define HEX__(n) 0x##n##UL
#define B8__(x) ((x&0x0000000FLU)?1:0)  \
  +((x&0x000000F0LU)?2:0)  \
  +((x&0x00000F00LU)?4:0)  \
  +((x&0x0000F000LU)?8:0)  \
  +((x&0x000F0000LU)?16:0) \
  +((x&0x00F00000LU)?32:0) \
  +((x&0x0F000000LU)?64:0) \
  +((x&0xF0000000LU)?128:0)
#define B8(d) ((unsigned char)B8__(HEX__(d)))

void ioinit(void);  

static int uart_putchar(uint8_t c, FILE *stream);
uint8_t uart_getchar(void);

static FILE mystdout = FDEV_SETUP_STREAM(uart_putchar, NULL, _FDEV_SETUP_WRITE);

void delay_ms(uint16_t x);

void ioinit (void)
{
      //1 = output, 0 = input
  //  DDRB = B8(11101111); //PB4 = MISO 
  //  DDRC =B8(11011111); //
  // DDRD = B8(11111110); //PORTD (RX on PD0)
  
    //USART Baud rate: 9600
    UBRRH = MYUBRR >> 8;
    UBRRL = MYUBRR;
    UCSRB = (1<<RXEN)|(1<<TXEN);
    UCSRC = (1<<URSEL)|(3<<UCSZ0);
    
    stdout = &mystdout; //Required for printf init
}

static int uart_putchar(uint8_t c, FILE *stream)
{
    if (c == '\n') uart_putchar('\r', stream);
  
    loop_until_bit_is_set(UCSRA, UDRE);
    UDR = c;
    
    return 0;
}

uint8_t uart_getchar(void)
{
    while( !(UCSRA & (1<<RXC)) );
    return(UDR);
}

//General short delays
void delay_ms(uint16_t x)
{
  uint8_t y, z;
  for ( ; x > 0 ; x--){
    for ( y = 0 ; y < 80 ; y++){
      for ( z = 0 ; z < 40 ; z++){
        asm volatile ("nop");
      }
    }
  }
}

void adc_init(void)
{
  ADMUX = 0; // channel 0
  ADCSRA = _BV(ADEN) | _BV(ADPS2);
}

void start_conversion(void)
{
  ADCSRA |= _BV(ADSC);
}

int conversion_not_over(void)
{
  return !(ADCSRA & _BV(ADSC));
}

void clear_adif(void)
{
  ADCSRA |= _BV(ADIF);
}

int main (void)
{
	uint8_t x = 0;
	
    ioinit(); //Setup IO pins and defaults
    //    adc_init();


    unsigned char channel=0; // measure ADC0
    int analog_result, adlow,adhigh;


    ADMUX=(0<<REFS1)|(1<<REFS0)|(channel & 0x0f);
    // ADCSR: ADC Control and Status Register
    // ADPS2..ADPS0: ADC frequency Prescaler Select Bits
    // ADEN: Analog Digital Converter Enable, set this before setting ADSC
    ADCSR=(1<<ADEN)|(1<<ADPS2);


  while(1) {


    //  start conversion
    ADCSR|= (1<<ADSC);
    while(bit_is_set(ADCSR,ADSC)); // wait for result
    adlow=ADCL; // read low first !!
    adhigh=ADCH;
    analog_result=((adhigh<<8)|(adlow & 0xFF));

      printf("Test:: %d\n", analog_result);
			delay_ms(500);

  }
   
    return(0);
}

