Saturday, February 23, 2013

Initializing the ADC on an ATMega328



Decent tutorial on AVRFreaks, however his micro gets put into free-run a different way. I used ADATE instead, which is in ADCSRA.
void initADC0()
{
ADCSRA |= (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0);  // set prescale to 128; (table 23-5)
ADMUX |= (1 << REFS0);    // reference to vcc (table 23-3)
//ADCSRA |= (1 << ADFR);    // put into free-running mode. (not in 328??)
ADMUX |= (1 << ADLAR);    // put into 8-bit mode.

ADCSRA |= (1 << ADEN); 
ADCSRA |= (1 << ADSC);  // start taking measurements
ADCSRA |= (1 << ADATE); // Auto-trigger
ADCSRA |= (1 << ADIE);  // Enable ADC Interrupt
}
Then the interrupt handler is just:

ISR(ADC_vect)
{
ADCRead = ADCH;
}


Make sure interrupts are actually on! (use sei();)

ADCRead is a static, not sure if that's the best idea. But it makes the getter easy:

uint8_t getADC()
{
return ADCRead;
}


The only thing I'm not sure about is how often ISR gets called. It kind of seems like it would get called a lot.

No comments:

Post a Comment