1. Using subroutines

1. Using subroutines

Subroutines help you divide the functions of a program. Use theCALL command in the calling program to execute the subroutine. When CALLM calls a subroutine and executes it, the subroutine executes all instructions until it ends. Then, the system returns control to the next instruction at the location where the subroutine was called.

Subroutines are used to segment and block programs into smaller, more manageable blocks. You can take advantage of this when debugging and maintaining programs. By using smaller program blocks, it is easy to debug and troubleshoot these areas and the entire program. Only calling program blocks when needed can make more efficient use of PLC, as all program blocks may not need to perform each scan.

Try to make subroutines use only their parameters and local variables, in order to facilitate the porting of subroutines to other projects and achieve functional reuse.

Attention

Program parameters and local variables occupy stack space, and stack resources are very limited, so they are only suitable for small-scale use.

These two types of software components only exist during the program execution cycle, and SamSoar2022 cannot monitor their values.

To use subroutines in a program, the following three tasks must be performed:

  • Create Subroutine

  • Define its parameters in the parameter table of the subroutine (if any)

  • Call a subroutine using the CALLM instruction from the corresponding POU (from the main program, another subroutine, or interrupt program)

When another POU calls a subroutine, the CPU saves the entire logical stack, sets the top of the stack to one, sets all other stack positions to zero, and transfers control to the called subroutine. After this subroutine is completed, the CPU restores the stack to the value saved at the time of the call and returns control to the POU of the calling subroutine.