Good day everyone. I faced a problem when writing my code, here is what I want my code to do:
- Timer Overflow interrupt start the ADC Conversion
- ADC Conversion starts
- ADC value is recorded
I was hoping each whole process to take probably less than 1ms, therefore i used prescaler of 16 for ADC conversion and 32 for timer
volatile int adc_pin = 15; // A0 = 14 (pins_arduino.h)
volatile int adc_value;
volatile bool adc_busy;
volatile bool adc_done;
volatile bool trig_conv=0;
volatile unsigned short starttime;
volatile unsigned short endtime;
volatile unsigned short trigtime;
void setup() {
Serial.begin (115200);
Serial.println("ADC with interrupt");
//ADC Registers
ADCSRA = bit(ADEN) // Turn ADC on
| bit(ADIE) // Enable interrupt
| bit(ADPS2); // Prescaler of 16
//(1/(16000000/16))*13.5 = 0.0000135s=0.0135ms
ADMUX = bit(REFS0) // AVCC
| ((adc_pin - 14) & 0x07); // Arduino Uno to ADC pin
//Timer Registers
TIMSK2 = (TIMSK2 & B11111110) | 0x01; //Enable timer overflow (last bit)
TCCR2B = (TCCR2B & B11111000) | 0x04; //011,Divisor of 32 - (1/(16000000/32))*255 = 0.00051
}
ISR(TIMER2_OVF_vect){
TCNT2=0;
trig_conv=1;
//TCCR2B=0;
//TIMSK2=0;
}
// ADC complete ISR
ISR(ADC_vect) {
adc_value = ADC;
endtime=micros();//record the time once the ADC conversion is completed
adc_done = true;
adc_busy = false;
}
void loop() {
if (adc_done)
{
// do something with the reading, for example, print it
Serial.print("end :");
Serial.println (endtime);
adc_done = false;
}
// Start new conversion
//if (!adc_busy) {
//adc_busy = true;
// start the conversion
if(trig_conv){
ADCSRA = (ADCSRA & B10111111)|0x40;//ADSC
trig_conv=0;
//}
starttime=micros();
Serial.print("start :");
Serial.println(starttime);
}
/*
if(trig_conv)
{
starttime=micros();
Serial.print("time: ");
Serial.println(starttime);
trig_conv=0;
//TCCR2B=0;
}
*/
}
Here is my question: By right the codes should be running in a loop, that whenever the timer overflows, ADC conversion starts and ends and wait for the next timer overflow, but when I serial print it out, the time showed has a delay in between, do any of you know the reasons and how to solve it? here is the picture of the serial monitor