Does your embedded product need faster ADC processing and do you want to implement all that in C++ . In this post I am going to show you how to run ADC of Arduino UNO in interrupted mode. In the next post, we will wrap the code in C++.
But why do we need to run ADC in interrupted mode?
Well, when you use analogRead() to read an ADC value CPU goes to the function & waits until a conversion is completed by the ADC peripheral. So you are actually waiting and wasting the CPU cycles.
How about you tell the ADC peripheral of the MCU to inform you when it finishes a conversion. In this way, CPU can go back to doing other works and return the ADC value once it is ready/converted.
So the optimized way is to enable the ADC interrupt & configure the ADC to run in free-running mode. the following code snippet shows how to configure the ADC registers of atmega328 for this purpose.
Please Note that Arduino UNO's mcu is actually atmega328 And the above C snippet configuring Registers will also get compiled by Arduino IDE.
ADMUX|=(1<<REFS0); //AVCC with external capacitor at AREF pin
ADMUX|=(1<<MUX2)|(1<<MUX0); //0101adc channel 5 selected for adc input
ADCSRA|=(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0); //prescalar 128 selected
ADCSRA|=(1<<ADEN); //adc enabled
ADCSRA|=(1<<ADATE); // ADC Auto Trigger Enable
ADCSRA|=(1<<ADIE); //adc interrupt enable such that interrupt will happen after each conversion
ADCSRA|=(1<<ADSC); //conversion process begins
sei(); //dont forget to enable the global interrupt
Please Note that Arduino UNO's mcu is actually atmega328 And the above C snippet configuring Registers will also get compiled by Arduino IDE.
In this mode after each conversion ADC peripheral will automatically throw an interrupt and at that interrupt service routine CPU will read the adc value from the ADC register. the following code snippet shows how to handle the interrupt handler.
ISR(ADC_vect) //adc interrupt service routine /tasks which will be executed by microprocessor after each conversion
{
adcValue=ADCL; //ADCL data register read
adcValue+=(ADCH<<8); //ADCH data register read
}
We can structure all of the above in a good OOP manner. The steps are described in this link https://whileinthisloop.blogspot.com/2016/05/c-in-arduino-isr-in-class.html
0 comments:
Post a Comment