Skip to content

Subroutine ​

Purpose: write steps you reuse once, as a block that different cases run with Call, optionally passing parameters. A subroutine is not a step: it is a part of the script that sits alongside the cases.

Subroutine screen

Click + under SUBROUTINES on the left to add one. With a subroutine selected, its parameters show at the top; click Parameters to edit them:

Subroutine parameters

FieldWhat it sets
NameParameter name, used inside the subroutine as ${addr}
DefaultDefault value (a constant). A parameter with a default can be left out of the Call
DescriptionDescriptive text

JSON ​

Subroutines go in subroutines at the top level of the script:

json
"subroutines": [
  {
    "name": "write_check",
    "params": [
      { "name": "addr", "desc": "register address" },
      { "name": "value", "default": 1, "desc": "value to write" }
    ],
    "steps": [
      { "write": { "function": 6, "address": "${addr}", "value": "${value}" } },
      { "read": { "address": "${addr}", "expected": "${value}" } }
    ]
  }
]
FieldRequiredMeaning
nameYesSubroutine name, up to 63 characters. Must differ from other subroutines and cases
paramsNoParameter list, up to 8. Each has name, default (a constant) and desc
stepsYesList of steps, written as in a case

Variable scope ​

  • A subroutine has its own variables: its parameters and the variables it sets. It cannot see the caller's variables, and its variables are gone when it ends.
  • To hand a result back to the caller, return it with Return and receive it with store on the Call.
  • ${now} shares the same clock as the caller.

Result ​

The results of a subroutine's steps show when you select that subroutine. If a step in the subroutine FAILs, the Call step that ran it is FAIL (a step in write_check failed).

Example ​

The case calls write_check twice: first with addr = 0x0600, value = 42, then with only addr = 0x0601, so value uses its default of 1.

Subroutine example result

Notes ​

  • End Case and Verdict cannot be used in a subroutine (they are not in the Add Step list), and Return can only be used in a subroutine.
  • Subroutines can call other subroutines, up to 32 levels deep, but cannot call themselves directly or indirectly. Loading the script points out the loop.
  • Parameter defaults must be constants, not variables.

Download the sample script ​

Sample script

Before running it, start a Slave window on 127.0.0.1:502 and click Listen, then open the script with Open JSON in Script mode and click Run. See How to use the examples.

Roach Modbus Tool by Mr.Roach