30 of 208
ZBasic Language Reference 22 ZX Microcontroller Family ' alternately blink the LEDs Do ' turn on the red LED Call Blink(redLed) ' turn on the green LED Call Blink(grnLed) Loop End Sub Private Sub Blink(ByVal pin as Byte) ' turn on the LED connected to the specified pin for one half second Call PutPin(pin, zxOutputLow) Call Delay(0.5) Call PutPin(pin, zxOutputHigh) End Sub In this program, we have factored out the code that turns an LED on and off into a subroutine named Blink(). In the definition of Blink(), pin is called the formal parameter. In Main() where Blink() is invoked, the parameters redLed and grnLed are the actual parameters. By factoring out the code that was common to blinking the two LEDs we have simplified the program. The details of how an LED is blinked are encapsulated in the definition of Blink(). No longer does the Main() subroutine need to know how to blink an LED; it just calls the subroutine to handle all of the details of blinking an LED connected to a specific pin and provides the necessary data for Blink() to do the work. In this case, all that is needed is a pin number. If we wished to do so, we could add another parameter to the blink subroutine to specify how long we want the LED illuminated. Private Sub Blink(ByVal pin as Byte, ByVal duration as Single) ' turn on the LED connected to the specified pin for the time given Call PutPin(pin, zxOutputLow) Call Delay(duration) Call PutPin(pin, zxOutputHigh) End Sub With this definition, we would need to add a second actual parameter in each call. For example, Call Blink(redLed, 0.5) It is recommended that you invoke subroutines as shown using the Call keyword as shown. However, for compatibility with other Basic dialects it is also possible, although not recommended, to invoke a subroutine by using its name as if it were a statement. If this is done, the actual parameters are not allowed to have enclosing parentheses as illustrated below. Blink redLed, 0.5 One powerful aspect of subroutines is that variables and constants may be defined within a subroutine itself. When this is done, the variable or constant is private to the subroutine and cannot be directly accessed from any other routine. Although it is common to place such definitions near the beginning of the subroutine, the definitions may occur anywhere in the subroutine as long as they occur before their first use. Note that the normal execution sequence of a subroutine may be altered by using the Exit Sub statement. When this statement is executed, it causes control to return to the caller immediately bypassing the remaining statements in the subroutine.