#include <avr/sleep.h>
#include <avr/interrupt.h>
#include <util/atomic.h>
#include "adc.h"


// used to initialize the ADC unit
void adc_init() {

	// configure all pins on the ADC port as input pins
	ADC_DDR = 0x00;
	
	// set analog reference to external pin
	ADMUX |= (1 << REFS0);
	
	// set the ADC clock prescaler to /64. Or other values. See the datasheet.
	ADCSRA |= ((1 << ADPS2) | (1 << ADPS1));
	//ADCSRA |= ((1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0));
	//ADCSRA |= ((1 << ADPS2) | (1 << ADPS0));

	sei();
}


// used to initiate an ADC conversion on the specified adc port
void adc_start_conversion(uint8_t adc_port) {
	// set adc port
	ADMUX = ((ADMUX & 0xE0) | adc_port);

	// enable ADC unit;
	ADCSRA |= (1 << ADEN);
	// enable ADC interrupt;
	ADCSRA |= (1 << ADIE);
	
	// set the sleep mode to ADC noise reduction mode
	set_sleep_mode(SLEEP_MODE_ADC);
	
	// put the processor to sleep during ADC conversion
	// (ADC conversion begins automatically at this point)
	sleep_mode();
	
}

// ADC conversion complete interrupt
SIGNAL(ADC_vect) {
	uint16_t sample;

	// retrieve the ADC sample
	sample = ADCL;
	sample |= (ADCH << 8);
	
	float t = sample * 0.488 - 50;
	//uint16_t t = sample / 2 - 50;
	
	char result[50];
	//sprintf(result,"%X + %X = %d: %d", ADCL, ADCH, sample, (uint16_t)t);
	sprintf(result,"%X + %X = %d", ADCL, ADCH, sample);
	
	uprint_char('[');
	uprint_str(result);
	uprint_char(']');
	uprint_char('\r');
	uprint_char('\n');

	// disable the ADC unit
	ADCSRA &= ~(1 << ADEN);
}




