Using a standalone ATmega328p. I want to have the ADC to be triggered each time TIMER1's COMPARE B value is reached. When the ADC is done, I want to use an interrupt to grab the data and to set an LED on PORTD to OFF. Then, using Timer1's COMPARE A interrupt, I want to set the LED PORTD to ON. By manipulating the OCR1A value I hope to control the PWM of the LED. I am putting TIMER1 in CTC mode with ICR1 setting the TOP value. Does this approach sound reasonable? Here is the code I have so far. It appears to do what I want although I am not using the ADC output yet.
#include <avr/pgmspace.h>
#include <avr/interrupt.h>
void setup() {
PRR |= (1<<PRTWI)|(1<<PRTIM0)|(1<<PRTIM2)|(1<<PRSPI)|(1<<PRUSART0);
DDRB = 0xFC;
DDRD = 0xFF;
DDRC = 0x3E;
cli(); // disable global interrupts to allow for a clean initial state
//************* Set Modes
TCCR1A = 0;
TCCR1B =0;
OCR1B =0;
OCR1A = 0;
// **************
TCNT1 =0; // Wise to force the count in range
ICR1 = 300; // output compare register used for timer1 A compare
OCR1A=50;
OCR1B = 0; // everytime COMPARE match B, ADC auto triggers
// ctc, IR1 sets top
TCCR1B |= (1 << WGM12)|(1<<WGM13);
TCCR1B &= ~(1<<CS12)&~(1<<CS10);
TCCR1B |= (1<<CS11);
TIMSK1 |= (1<<OCIE1A)|(1<<OCIE1B); // Timer/Counter1 Interrupt Mask Register
// set up sampling of analog pin 0
// ADEN: Enable ADC
// ADATE Auto Triggering of the ADC is enabled. The ADC will start
// a conversion on a positive edge of the selected trigger signal.
// ADIE ADC conversion complete interrupt enable
ADCSRA |= (1 << ADEN)|(1<<ADATE)|(1<<ADIE);
//set reference voltage
ADMUX &= ~(1 << REFS0) & ~(1 << REFS1);
// Right adjust for reading 10 bit value
ADMUX &= ~(1<<ADLAR);
// 0000 selects ADC0 channel
ADCSRA &= ~(1<<ADPS2);
ADCSRA |= (1<<ADPS1)|(1<<ADPS0);
ADMUX &= ~(1<<MUX3) & ~(1<<MUX2) & ~(1<<MUX1) & ~(1<<MUX0);
// auto trigger on compare match B.
ADCSRB |= (1 << ADTS2)|(1 << ADTS0);
sei(); //enable interrupts
ADCSRA |=(1<<ADSC); // must start first conversion
}
ISR(TIMER1_COMPA_vect) {
PORTD=0b11111110;
}
ISR(ADC_vect) {
PORTD=0b11111111;
}
void loop() {
// here I will manipulate OCR1A to change the PWM of the LED on PORTD bit 0
}