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

138                                Chapter 6 Assembly Language Subroutines
































                        Figure 6.1. Subroutine Calling and Returning

            The BSR and RTS instructions are calling and returning mechanisms, and the
        PSHX and ADDD instructions are the program segment in this subroutine. The X and D
        registers at the time the BSR is executed contain the input parameters, and the D register
        at the time that the RTS is executed contains the output parameter. We pass these
        parameters into the subroutine at the beginning of its execution and out of the subroutine
        at the end of its execution. The value pushed on the stack by the PSHX instruction
        becomes a local variable of this subroutine, a variable used only by this subroutine.
            In this chapter, we discuss the mechanics of writing subroutines and, to a much
        lesser extent, the creative issue of what should be a subroutine and what should not.
        Echoing the theme of Chapter 1, we want to teach you how to correctly implement your
        good ideas, so you'll know how to use the subroutine as a tool to carry out these ideas.
            This chapter is divided into sections that correspond to each capability that you need
        to write good subroutines. We first examine the storage of local variables. This
        discussion gives us an opportunity to become more familiar with the stack, so that the
        later sections are easier to present. We next discuss the passing of parameters and then
        consider calling by value, reference, and name. We then discuss the techniques for calling
        subroutines and returning from them. Finally, we present a few examples that tie
        together the various concepts that have been presented in the earlier sections and present
        some conclusions and recommendations for further reading.
            Upon completion of this chapter, you should be able to pick the correct methods to
        call a subroutine, use local variables in it, and pass parameters to and from it. You
        should know how to test and document a subroutine and test the routine that calls the
        subroutine. With these capabilities, you should be ready to exercise your imagination
        creating your own subroutines for larger programs.


                                           138
   156   157   158   159   160   161   162   163   164   165   166