Skip to content

Instantly share code, notes, and snippets.

@njtbot
Created September 30, 2013 14:56
Show Gist options
  • Save njtbot/6765019 to your computer and use it in GitHub Desktop.
Save njtbot/6765019 to your computer and use it in GitHub Desktop.
Basic rounding scheme to avoid sampling/rounding errors. From PIC24 but pseudo-code enough to be ported.
void SampleADC() {
/* Wait till interrupt says samples are ready */
while (!AD1CON1bits.DONE);
/* Assign buffer values to temp variables for processing */
tempPot = ADC1BUF0;
/* Set threshold values to avoid fluctuating rounding errors */
int potThresh = 25;
/* Calculate 1024 scaled value for current volume */
cv = currentPot * 32;
/* Check threshold ranges and update if necessary */
if ((tempPot <= (cv - potThresh)) && (currentPot != 0)) {
/* Volume has changed one step lower */
currentPot--;
} else if ((tempPot >= (cv + potThresh)) && (currentPot != 31)) {
/* Volume has changed one step higher */
currentPot++;
} else {
/* No change in volume */
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment