ADC produces wrong values when program is halted while debugging

Question: While debugging a project with ADC, I place a breakpoint after the ADC result is read. The ADC produces wrong results. What is the reason for this behavior and what is the solution?

 

Answer:

When the program is halted on a breakpoint, only the CPU halts.  The analog and digital hardware of the ADC keep running in the background accumulating data over several ADC cycles.  This corrupts the ADC data.  To overcome this problem, several solutions may be used.  Set the breakpoint dynamically, ie, add the breakpoint while the project is running.  Set the breakpoint after dropping one ADC sample.  This way the corrupt ADC result will be dropped and the result available on the breakpoint will be a good one.  Run the ADC in single sample mode instead of continuous sampling.

More details on this can be found in the blog article: Wrong ADC values while debugging