7.1 Initialize the ADC

This subsection presents how to initialize the ADC module to use the Sample Accumulator feature. This application uses the Config A setup explained in Hardware Configuration. In this mode, the ADC can add up to 128 samples in the accumulator register, thus filtering the signal and reducing the noise, which is useful when reading analog sensor data, where a smooth signal is required. By using a hardware accumulator instead of adding those readings in software, it reduces the CPU load.

To activate this mode, the Sample Accumulation Number in the ADC0.CTRLB register must be set, in addition to the normal ADC initialization.

Figure 7-1. ADC0.CTRLB - Set the SAMPNUM Bit

This translates into the following code:

ADC0.CTRLB = ADC_SAMPNUM_ACC64_gc; 

The samples will be added up in the ADC0.RES register. The ADC_RESRDY flag is set after the number of samples specified in ADC0.CTRLB is acquired.

The user can read that value and divide it by the number of samples to get the average value. If there are more than 16 accumulated samples, the result will be truncated down in hardware to a 16-bit variable, and it needs to be divided by 16:

adcVal = ADC0_read(); /* Clear the interrupt flag by reading the result */
adcVal = adcVal >> ADC_SHIFT_DIV16; /* divide by No of samples or 16, if No. samples > 16 */