/*
 * adc.c
 *
 * Created: 20.02.2019 20:46:32
 *  Author: jens
 */ 

#include <stddef.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include "adc.h"
#include "message.h"

static volatile int16_t adc_value[16];
static volatile size_t adc_ch = 0;
static Fifo *g_pFifo = NULL;

ISR(ADC_vect)
{
	int16_t value_low = (int16_t)ADCL;
	int16_t value_high = (int16_t)ADCH;
	ADCSRA |= (1<<ADIF);
	int16_t value = value_high << 8 | value_low;
	adc_value[adc_ch] = value;

	Msg_t msg = {AdcComplete, adc_getChannel()};
	fifo_push(g_pFifo, &msg);
}

void adc_init(Fifo *pFifo)
{
	g_pFifo = pFifo;
	PRR &= ~(1 << PRADC);
	ADCSRA |= (1 << ADEN) | 7;
}

void adc_start_conversion(size_t ch)
{
	ADMUX = (ADMUX & 0xF0) | (ch & 0x0F) | (1 << REFS0);
	ADCSRA |= (1 << ADSC) | (1 << ADIE);
	adc_ch = ch & 0x0F;
}

int adc_is_fininshed()
{
	return (int)(0 == (ADCSRA & (1 << ADSC)));
}

size_t adc_getChannel()
{
	return adc_ch;
}

int16_t adc_getData()
{
	return adc_value[adc_ch];
}

