4.1 Initialize the ADC
This subsection showcases how to initialize the ADC module to run in Single Conversion mode. The ADC input pin needs to have the digital input buffer and the pull-up resistor disabled, to have the highest possible input impedance.
The ADC Single Conversion uses the Config A setup explained in Hardware Configuration.
To select the ADC channel AIN3, PD3, use the code below:
ADC0.MUXPOS = ADC_MUXPOS_AIN3_gc;
The ADC Clock Prescaler can be used to divide the clock frequency. In this example, the clock is divided by 4.
ADC0.CTRLC |= ADC_PRESC_DIV4_gc;
VREF.ADC0REF = VREF_REFSEL_2V048_gc; /* Internal 2.048V reference */
The ADC resolution is set by the RESSEL bit in the ADC0.CTRLA register. The ADC is enabled by setting the ENABLE bit in the ADC0.CTRLA register.
This translates into the following code:
ADC0.CTRLA = ADC_ENABLE_bm /* ADC Enable: enabled */
| ADC_RESSEL_12BIT_gc; /* 12-bit mode */
The ADC conversion is started by setting the STCONV bit in the ADC0.COMMAND register.
This translates into the following code:
ADC0.COMMAND = ADC_STCONV_bm;
When the conversion finishes, the RESRDY bit in ADC0.INTFLAGS gets set by the hardware. The user must wait for that bit to be set before reading the ADC result.
The user must clear the RESRDY bit by reading the ADC0.RES register before starting another conversion:
/* Clear the interrupt flag by reading the result */
return ADC0.RES;
The conversion result can be read from the ADC0.RES register:
adcVal = ADC0.RES;