Page 211 - Programming Microcontrollers in C
P. 211

196    Chapter 4  Small 8-Bit Systems

                          The following function will provide a reading of a single channel of
                          the ADC input:
                   unsigned int read_adc(int k)
                   {
                       AD_CTST &=~0X7;
                       AD_CTST |=k;
                       while(AD_CTST.COCO==0)
                          ; /* wait here til COCO is set */
                       return AD_DATA;
                   }
                              The argument k is the channel that is to be read, and k can have
                          a value of 0 to 7 to read the external channels.
                              The first two lines of code in the above function will place the
                          channel number to be read in the channel bits of AD_CTST. These
                          bits must be cleared by an instruction sequence that will not alter the
                          upper bits of AD_CTST because the ADON bit is in the upper portion
                          of AD_CTST. This bit cannot be reset while the ADC operation is
                          continuing. The first line of code clears the least significant three
                          bits, and the second line places the channel number in these bits.
                              Writing to AD_CTSTwill cause the ADC conversion to start. There­
                          fore, all that must be done is to wait until the conversion is completed
                          to read the data into the program. The code

                   while(AD_CTST.COCO==0)
                       ; /* wait here til COCO is set */
                          will keep control of the microcontroller in that instruction sequence
                          until the COCO bit, which is the conversion completion bit, is set. At
                          that time the value found in AD_DATA will be the result of the latest
                          conversion.
                              Often, the ADC results must be subjected to some processing to
                          remove unwanted characteristics of the signal being measured. Here
                          is a case where careful use of assembly language procedures can
                          make a big difference in the execution speed as well as the amount of
                          code needed. An example that is often used is to average the past
                          values of the data. A reasonably simple approach is to allow the lat­
                          est ADC reading to have a 50% weight and all of the past readings to
                          have a 50% weight. The following example code will accomplish
                          this task in three different ways:
   206   207   208   209   210   211   212   213   214   215   216