Page 92 - Introduction to Microcontrollers Architecture, Programming, and Interfacing of The Motorola 68HC12
P. 92

3.3 Relative Addressing And Position Independence                     69













             Figure 3.9. Program Segment Using BRA, Illustrating Position Independence

            The example in Figure 3.10 constantly flips bits in location 1. It might be used in
        Chapter 12; location I is an output port, and this program segment outputs a square
        wave on all the bits. The two's-complement offset is negative because the branch is
        backwards. Observe that, after BRA L is fetched, the program counter is on location
        $816; the offset $FB is -5, so the program counter becomes $811 after it is executed.
            Many programmers have difficulty with relative branch instructions that branch
        backwards. We recommend using sixteen's complement arithmetic to determine the
        negative branch instruction displacement. The sixteen's complement is to hexadecimal
        numbers as the two's complement is to binary numbers. To illustrate this technique, the
        displacement used in the branch instruction, the last instruction in the program in Figure
        3.10, can be determined as follows. When the branch is executed, the program counter
        has the value $816, and we want to jump back to location $811. The difference, $816 -
        $811, is $05, so the displacement should be -$05. A safe way to calculate the
        displacement is to convert to binary, negate, then convert to hexadecimal. Because $5 is
        00000101, the two's complement negative is 11111011. In hexadecimal, this is $FB.
        That is not hard to see, but binary arithmetic gets rather tedious. A faster way takes the
        sixteen's complement of the hexadecimal number. Just subtract each digit from $F (15),
        digit by digit, then add 1 to the whole thing. Then -$05 is ($F - 0),($F - 5) + 1 or
        $FA + 1, which is $FB. That's pretty easy, isn't it!
            If the relative offset is outside the 8-bit range, one uses the long branch equivalent,
        LBRA L, which uses a 16-bit two's-complement relative offset.
            Program counter relative addressing can be used to read (constant) data that should be
        stored with the program. Relative addressing can be implemented using a 5-bit, 9-bit, or
         16-bit signed relative offset. Nine-bit offset relative addressing is denoted by the "<"
        before and ", PCR" after the offset and 16-bit offset by ">" symbol before and ", PCR"
        after the offset, (This mode's machine code uses a post byte as it is an index option.)














               Figure 3.10. Program Segment to Put a Square Wave on an Output Port
   87   88   89   90   91   92   93   94   95   96   97