Page 213 - Programming Microcontrollers in C
P. 213

198    Chapter 4  Small 8-Bit Systems

                   adc_data[j]=(read_adc(j)+adc_data[j])/2;

                              Hidden in this code is the fact that both  read_adc and
                          adc_data are unsigned results. When two unsigned numbers are
                          added together, the most significant bit of each can be 1 so there can
                          be a carry or overflow when the addition takes place. Problems from
                          this carry can be avoided in this case by merely using a long or
                          double precision add routine in adding the two numbers. Then,
                          when the result is divided by 2, if a bit is carried into the upper byte
                          of the result it will be shifted back into the lower byte. The result of
                          this operation is correct and will fit into a single unsigned int.
                              The compiled version of the above program with read_adc()
                          merged into it follows:
                                     #include “hc05b6.h”


                       0050 0008         unsigned adc_data[8];
                                     unsigned read_adc(int);

                                     void main(void)
                                     {
                   0058                  unsigned int j;

                   0100 3F 09 CLR $09               AD_CTST=0;
                   0102 1A 09 BSET 5,$09               AD_CTST.ADON=1;


                   0104 3F 58 CLR $58               for(j=0;j<8;j++)
                   0106 B6 58 LDA $58
                   0108 A1 08 CMP #$08
                   010A 24 36 BCC $0142
                                                {
                   010C CD 01 43 JSR $0143  adc_data[j]=(read_adc(j)+
                                                adc_data[j])/2;
                   010F BE 58 LDX $58
                   0111 EB 50 ADD $50,X
                   0113 AE 02 LDX #$02
                   0115 CD 01 57 JSR $0157
                   0118 9F        TXA
                   0119 BE 58 LDX $58
                   011B E7 50 STA $50,X
   208   209   210   211   212   213   214   215   216   217   218