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

6





                      Assembly Language


                               Subroutines










         Subroutines are fantastic tools that will exercise your creativity. Have you ever wished
         you had an instruction that executed a floating-point multiply? The 6812 does not have
         such powerful instructions, but you can write a subroutine to execute the floating-point
         multiplication operation. The instruction that calls the subroutine now behaves pretty
         much like the instruction that you wish you had. Subroutines can call other subroutines
         as you build larger instructions out of simpler ones. In a sense, your final program is
        just a single instruction built out of simpler instructions. This idea leads to a
         methodology of writing programs called top-down design. Thus, creative new
         instructions are usually implemented as subroutines where the code is written only once.
         In fact, macros are commonly used just to call subroutines. In this chapter, we
        concentrate on the use of subroutines to implement larger instructions and to introduce
        programming methodologies.
            To preview some of the ideas of this chapter, consider the following simple
         subroutine, which adds the contents of the X register to accumulator D.
        SUB:    PSHX              ; Push copy of X onto stack
                ADDD 2, SP+       ; Add copy into D; pop copy off stack
                RTS
        It can be called by the instruction
                BSR    SUB
        Recall from Chapter 2 that the BSR instruction, besides branching to location SUB,
        pushes the return address onto the hardware stack, low byte first, while the instruction
        RTS at the end of the subroutine pulls the top two bytes of the stack into the program
        counter, high byte first. See Figure 6.1. In this figure, H:L denotes the return address and
        the contents of X is denoted XH:XL. Notice particularly that the instruction
                ADDD 2,SP+

        in the subroutine above not only adds the copy of the contents of X into D but also pops
        the copy off the stack so that the return address will be pulled into the program counter
        by the RTS instruction.

                                           137
   155   156   157   158   159   160   161   162   163   164   165