Microchip Technology DM164130-9 User Manual

Page of 101
Lessons
 2012 Microchip Technology Inc.
DS41628B-page 83
EQUATION 3-5:
3.12.7
C language
3.12.7.1 BOTH
Pointers in ‘C’ are constructed by using the INDF/FSR pair on the PIC16/PIC18 to 
achieve the effect.
EXAMPLE 3-44: 
Similar to the assembly version, the main loop starts by resetting the pointer by pointing 
(referencing) to the first byte in the queue. Then, an ADC reading is taken and saved 
in the queue. LATC is then assigned the average of the queue. Remember that ‘queue’ 
is eight bytes wide, so it can hold eight samples of the ADC result (two LSbs of the 
result are not saved).
EXAMPLE 3-45: 
The average function has the pointer to queue as a parameter. The _sum is a global 
variable which retains its value outside of this function. The current value in the running 
sum is subtracted. The asterisk means that its value is being used (dereferencing). A 
new ADC value is taken and added back into the running sum and the queue. The aver-
age reading is then returned to the main loop to be shifted onto the LED display. 
There is a great deal of information about pointers for the ‘C’ language on the web. It 
is recommended that the reader look there for additional information. 
Before Rotate right: b'00001010'= d'10'
After Rotate right:  b'00000101'= d'5'
while (1) {
     ptr_queue = &queue;                    //point to the first byte in this array  
                                            (RESET the pointer)
     for (i = NUM_READINGS; i != 0; i--){
         LATC = (average(ptr_queue) >> 4 ); //only want the 4 MSbs for 4 LEDs
         ptr_queue++;
}
unsigned char average(unsigned char *ptr) {
    unsigned char adc_value;
    _sum -= *ptr;               //subtract the current value out of the sum
    adc_value = adc();
    *ptr = adc_value;           //assign ADC value to the queue
    _sum += adc_value;          //add to the sum
    return (_sum/NUM_READINGS); //compute the average
}