EDN Access

 

December 4, 1997


Conversion program outputs BCD values

Mike McGlinchy, MDM Designs, San Bruno, CA

A program entitled HEXBCD is an 8051 µC subroutine that converts a 16-bit HEX number in internal RAM locations 33 and 34H into its BCD equivalent (Listing 1). The program places the result in scratchpad registers R1, R2, and R3 . (You can download the file DI-SIG, #2120.)

Many applications require a µC to output BCD values, such as for driving a BCD seven-segment LED decoder. Converting an 8-bit number to BCD is relatively simple; the routine LOW8, which is part of the main HEXBCD program, performs an 8-bit conversion. You can add more registers to expand the overall conversion program beyond 16 bits to handle larger numbers.

The maximum time to perform a 16-bit conversion is 236 instruction cycles. With a 12-MHz crystal and the corresponding 1 µsec/instruction, the maximum time is then 236 µsec. The more 1s that exist in the number, the longer the conversion takes. For example, converting FFFFH (all 1s) to its BCD equivalent (65,535) takes the maximum of 236 µsec. Converting 4104H to BCD takes 113 µsec because this HEX number contains only three 1s.

The program begins by clearing the BCD registers R1, R2, and R3. The program then takes the high byte of the 16-bit HEX number from RAM location 33H and tests each bit for a high. If a bit is high, the program places a corresponding binary-weighted number in temporary-storage registers R4, R5, and R6. For example, if bit 6 (bit 14 overall) of the high byte is high, the program places 16384H in R4, R5, and R6. The program then calls a subroutine, BCDADD, which adds 16384H to the contents of R1, R2, and R3 using the ADDC A,R1 (add register to accumulator with carry) and DA A (decimal adjust accumulator) instructions.

After the program tests and adds the upper 8 bits, the intermediate BCD answer is in locations R1, R2, and R3. The routine LOW8 then does a quick HEX-to-BCD conversion of the lower 8 bits. The program adds this result to the high-byte result by calling BCDADD once more. (DI #2120)


Listing 1 -- HEXBCD conversion program
24D2120L24D2120M

| EDN Access | Feedback | Table of Contents |


Copyright © 1997 EDN Magazine, EDN Access. EDN is a registered trademark of Reed Properties Inc, used under license. EDN is published by Cahners Publishing Company, a unit of Reed Elsevier Inc.