ZBasic Language Reference
25
ZBasic Microcontrollers
that the parameter is passed by reference. Each of these parameter passing conventions has its own
advantages and disadvantages and the full explanation of the difference between these two parameter
passing methods is given in Section 2.14. Suffice to say here that the primary difference is whether or
not the called subroutine is able to change the value of the passed parameter from the perspective of the
caller. Some variable types may be passed by one of the methods but not by the other. Again, see
Section 2.14 for complete details. The default passing convention, if neither ByVal nor ByRef is
specified, is ByRef.
To specify a formal parameter that is an array, simply add a set of parentheses following the parameter
name. For example,
Sub mySub(ByRef data() as Byte)
End Sub
Only one-dimensioned arrays whose lower bound is 1 may be passed as parameters and they must be
passed by reference. The upper bound is indeterminate it is the responsibility of the programmer to
ensure that the subroutine does not access elements beyond the upper bound of the passed array.
Often, programmers will include a parameter that specifies the upper bound so that the code may safely
operate with different sizes of arrays.
Sub mySub(ByRef data() as Byte, ByVal count as Byte)
End Sub
Lastly, the <statements> element in the subroutine definition represents zero or more valid ZBasic
statements that are described in Section 2.5 of this manual.
Example
Private Const redLED as Byte = 25
' define the pin for the red LED
Private Const grnLED as Byte = 26
' define the pin for the green LED
Public Sub Main()
' configure the pins to be outputs, LEDs off
Call PutPin(redLed, zxOutputHigh)
Call PutPin(grnLed, zxOutputHigh)
' 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
|