Page 223 - Programming Microcontrollers in C
P. 223

208    Chapter 4  Small 8-Bit Systems

                       return result;
                   }
                              Listing 4-8: First BCD Conversion

                              This small function takes an 8-bit character n that is less than 99
                          and converts the number into one 8-bit result. The upper nibble is the
                          number of tens in the number and the lower nibble is the number of
                          units. A hexadecimal number 0xff is returned if the number is greater
                          than 99. Note that the calculation requires an integer divide opera­
                          tion and a modulus operation which is equivalent to a divide operation.
                          The code to execute the divide and modulus operations must be asso­
                          ciated with this function to complete its task.
                              Another approach is shown below. This approach avoids any exter­
                          nal function calls and actually requires less total code than the version in
                          Listing 4-8, even though the C code is somewhat longer. In this case, the
                          while loop essentially divides the input number by 10 and places the
                          result in the most significant nibble of the result. After the tens have been
                          removed from the number, all that is left is the units. This value—the
                          number of units—is ORed on the result before it is returned.
                   /* convert a binary number less than 100 to BCD */


                   unsigned char convert_bcd(unsigned char n)
                   {
                       unsigned int result;


                       if(n>99) return 0xff;
                       result=0;
                       while((n-10)>=0)
                          result+=0x10;
                       n+=10;
                       result += n;
                       return result;
                   }
                              Listing 4-9: Second BCD Conversion

                              The function shown below was originally written for use on a
                          M68HC05, but was later used on a M68HC11 as well. A two-digit
                          number must be sent to a seven-segment LED display. The number
                          to be shown is contained in the memory locations for tens and units.
   218   219   220   221   222   223   224   225   226   227   228