- Name:
- gosub
- Syntax:
-
GOSUB address
CALL address
Address - is a label which specifies where to gosub to.
- Description:
-
Go to sub procedure at 'address', then 'return' at a later point. The compiler also accepts 'call' as a pseudo for 'gosub'. The gosub ('goto subprocedure') command is a 'temporary' jump to a separate section of code, from which you will later return (via the return command). Every gosub command MUST be matched by a corresponding return command. Do not confuse with the goto command which is a permanent jump to a new program location.
The table shows the maximum number of gosubs available in each microcontroller. Gosubs can normally be nested up to 8 levels deep (ie there is a 8 level stack available in the microcontroller).
gosubs interrupt stack depth All 'M2' parts * 255 1 8 All 'X2' parts 255 1 8 All 'X1' parts 255 1 8 All 'X' parts (obsolete) 255 1 4 All 'M' parts (obsolete) 15 1 4 All 'A' parts (obsolete) 16 0 4 * On 'parallel tasking' M2 parts each task has its own separate 8 deep stack. Sub procedures are commonly used to reduce program space usage by putting repeated sections of code in a single sub-procedure. By passing values to the sub- procedure within variables, you can repeat a section of code from multiple places within the program. See the sample below for more information.
Call a gosub subroutine
Flash an LED multiple times using a gosub subroutine
- Code Example:
-
main: let b2 = 15 ; set b2 value gosub flsh ; call sub-procedure let b2 = 5 ; set b2 value gosub flsh ; call sub-procedure end ; stop accidentally falling into sub flsh: for b0 = 1 to b2 ; define loop for b2 times high B.1 ; switch on output 1 pause 500 ; wait 0.5 seconds low B.1 ; switch off output 1 pause 500 ; wait 0.5 seconds next b0 ; end of loop return ; return from sub-procedure
Copy Code Submit an Example
Submit Your Own Code!
You must be logged in to submit code examples. Login now.