PLC Subroutine

Subroutines improve Ladder Logic code re-usability and readability.  They do this by allowing you to break apart your code into manageable pieces.  Subroutines can then be used multiple times inside a program and easily brought into new programs.

2 routines envolved:

  • Calling Routine: the routine requesting a Subroutine to run.  It can be the main program, or another subroutine.
  • Subroutine: the routine being called

Subroutines act as a separate Ladder Logic that can be called whenever needed.  Many times you’ll need to provide it data from the calling routine.  To do this, you setup input Tags for the Subroutine that will receive data from the Calling Routine.  Wherever you call the Subroutine you match up the Tags you want to pass from the Calling Routine to the Tags in the Subroutine that will receive the data.  Passing a Tag can be done in 1 of 2 ways.

Pass by Value: is a 1 way street for data to go From the Calling Tag to the Subroutine Tag.  The Calling Tag will be unaffected by the pass.

Pass by Reference: is a 2 way street.  The Calling Tag passes the Subroutine Tag it’s value.  When the Subroutine Returns, the Subroutine Tag passes the Calling Tag it’s value.

Example:

Here’s the order what happens in a subroutine:

  1. The Rungs of a Calling Routine run until it reaches a Subroutine Call
  2. Data is passed from Calling Routine Tags to Subroutine Tags (optional)
  3. Subroutine runs until it reaches a Return statement
  4. Data passed by reference is passed from Subroutine Tags to Calling Routine Tags (optional)
  5. The Calling Routine continues with the rung that follows the Subroutine Call.

Inside the Subroutine you must have at least 1 Return statement.  This tells the Subroutine to return to the Calling Routine.  It is possible to have more than one Return statement, if you need more than one thing to trigger a return.

Often it is possible to use Tags inside the Subroutine that come from the Main Program without passing them. This is using Global Tags.  While this is allowed, they will make your Subroutine less re-usable.  If you want to bring the Subroutine into another project it will be necessarily that the project has all the Global Tags used in your Subroutine(s).

A word of caution:  PLC makers describe a range of functionality as Subroutines, while often missing key elements.  On our sister site PLCCompare.com you can find our assessments of which PLC lines provide true Subroutines.