5 ADCC Spike Detection

This example presents a solution that will generate an interrupt when a spike is detected in the value that is being read. A sharp increase or decrease is necessary to generate the interrupt, a slow increase or decrease will not trigger it. The code was tested with a potentiometer that can be turned quickly between its maximum and minimum values.

The main clock is configured to run from HFINTOSC with 1 MHz with a prescaler of 4 for a clock frequency of 250 kHz. The RA0 pin is configured as analog input.

The ADCC is enabled, Continuous mode is enabled, and the result is right-justified. The clock is given by the main clock of the microcontroller, divided by two times the value found in the ADC Clock Selection (ADCLK) register plus one, 128 in this case. This gives a sampling frequency of 169 Hz for the ADCC which is small enough that the interrupt can be triggered by turning the potentiometer quickly.

The ADCC is configured to run in the Average mode with 16 samples per conversion and a right shift of 16, selected by setting the ADC Accumulated Calculation Right Shift Select (ADCRS) bits in the ADCON2 register to 4. In order to ensure a correct average, it is recommended to have the same number of samples as the bits shifted to the right. The A/D Accumulator Clear Command (ADACLR) bit in the ADCON2 register is set. This Command bit clears the Overflow Status bit, the accumulator and the count register after each conversion and is necessary for the correct triggering of the threshold interrupt. When the accumulator overflows and the Overflow Status bit is set, a threshold interrupt is generated. This condition can be checked in the interrupt handler or the ADACLR bit can be set to prevent triggers from overflows.

The error calculation is configured as the first derivative of a single measurement (e.g. the error is the difference between this conversion and the last conversion) and the threshold interrupt is configured to trigger if the error is higher than the upper threshold of 35 or smaller than the lower threshold of -35.

Finally, the ADCC threshold interrupt, peripheral and global interrupts are enabled.

As in the previous examples, the sample capacitor is discharged by connecting it to Ground and then the conversion is started.

The interrupt handler returns the value of the error which is found in the ADERRH and ADERRL registers and this can be checked with the debugger.

To achieve the functionality described by the use case, the following actions will have to be performed:

  • System clock initialization
  • Port initialization
  • ADCC initialization
  • Interrupt initialization
  • Discharge sample capacitor
  • Starting the conversion
  • ADCC threshold interrupt handling