On GoSub
Syntax
On Index Variable GoSub Label1 {,...Labeln }
Overview
Cause the program to Call a subroutine based on an index value. A subsequent Return will continue the program immediately following the On GoSub command.
Parameters
Index Variable is a constant, variable, or expression, that specifies the label to call. Label1...Labeln are valid labels that specify where to call. A maximum of 256 labels may be placed after the GoSub.
Example
Device = 18F26K40 ' Use an 18F device
Declare Xtal = 20 ' Tell the compiler the device is operating at 20MHz
Declare Hserial_Baud = 9600 ' Choose the Baud rate for HRsoutLn
Dim bIndex as Byte
Do ' Create an infinite loop
For bIndex = 0 to 2 ' Create a loop to call all the labels
' Call the label depending on the value of Index
On bIndex GoSub Label_0, Label_1, Label_2
DelayMs 500 ' Wait 500ms after the subroutine has returned
Next
Loop ' Do it forever
Label_0:
HRsoutLn "Label 0" ' Display the Label name
Return
Label_1:
HRsoutLn "Label 1" ' Display the Label name
Return
Label_2:
HRsoutLn "Label 2" ' Display the Label name
Return
The above example, a loop is formed that will load the variable Index with values 0 to 2. The On GoSub command will then use that value to call each subroutine in turn. Each subroutine will Return to the DelayMs command, ready for the next scan of the loop.
Notes
On GoSub is useful when you want to organise a structure such as: -
If Var1 = 0 Then GoSub Label_0 ' Var1 = 0: call label "Label_0"
If Var1 = 1 Then GoSub Label_1 ' Var1 = 1: call label "Label_1"
If Var1 = 2 Then GoSub Label_2 ' Var1 = 2: call label "Label_2"
You can use On GoSub to organise this into a single statement: -
On Var1 GoSub Label_0, Label_1, Label_2
This works exactly the same as the above If...Then example. If the value is not in range (in this case if Var1 is greater than 2), On GoSub does nothing. The program continues with the next instruction..
On GoSub is only supported with 18F devices because they are the only PICmicro™ devices that allow code access to their return stack, which is required for the computed Return address.
The list of subroutines within the On Gosub can also be procedure calls, but they are not allowed to contain parameters:
On Var1 GoSub Proc0(), Proc1(), Proc2()

