MOULDLKnowledge BaseElectrical Knowledge Base3D Model DownloadsMembership
中文版Model Store »
Knowledge Base › Electrical Knowledge Base › What should you watch out for when calling a subroutine from an interrupt routine?
HomeModels
Table of contents

On this page

PLC & Programming (100 articles)

Quick Reference

  • PLC & Programming
  • Electrical & Electronic Basics (monthly)(每月更新中)
  • Electrical Control & Drawings (monthly)(每月更新中)
  • Drives & Actuators (monthly)(每月更新中)
  • Sensors & Detection (monthly)(每月更新中)
  • Industrial Communication & Networks (monthly)(每月更新中)
  • HMI & Host Systems (monthly)(每月更新中)
  • Industrial Robots & Motion Control (monthly)(每月更新中)
  • Mechatronic System Integration (monthly)(每月更新中)
  • Fault Diagnosis & Standards (monthly)(每月更新中)

What should you watch out for when calling a subroutine from an interrupt routine?

Calling subroutines from interrupts is fine — with care: the main program and the interrupt can interleave calls to the same subroutine, and the subroutine's working devices, timers and accumulators become a shared scratchpad both sides scribble on. The rule in one sentence: the interrupt path's subroutines must be purpose-built, or written as re-entrant pure functions. The sections below cover the risk mechanism, the two approaches, data handshakes and a checklist.

1. The risk mechanism: interleaved execution tramples the scratchpad

Shared resourceHow it is trampledTypical symptom
General M/D used inside the subroutineThe main's call is interrupted mid-way; the interrupt's call of the same subroutine overwrites those values; on return the logic is wrongOccasional state corruption, near-impossible to reproduce
Shared timers/countersBoth sides drive the same timer; results unpredictableOccasional timing inaccuracy
Accumulator / scratch variablesThe interrupt rewrites a value the main is computingData jumps, statistics off
Outputs / SET targetsThe interrupt path moves a mechanism's output stateMechanism moves unexpectedly mid-way (dangerous)

Note that on single-core PLCs "simultaneous" means interleaved: the interrupt can insert at any instruction boundary. With dedicated resources, interleaving is harmless; with shared resources, interleaving plants mines.

2. Approach one: purpose-built copies (for complex logic)

Give the interrupt path its own copy of the subroutine (MAIN uses CALC, the interrupt uses CALC_INT), the latter's internal devices fully dedicated (its own M/D blocks, its own timer numbers), zero sharing with the main path. The price is duplicated code; the return is absolute isolation. Use it when interrupt-side logic is non-trivial (sampling, scaling, latching) and the platform's re-entrancy story is unclear — the safest road.

Supporting discipline: the interrupt-only subroutine's device block is marked in the partition table as "interrupt path only", off-limits to ordinary subroutines.

3. Approach two: pure-function style (for calculations)

Make the subroutine "stateless": inputs come only from parameters or designated input areas, results go only to designated output areas, and internal variables are initialised on entry before use — no reliance on leftovers from the last call. Under that style, even interleaved calls are correct provided the read and write areas do not overlap. Fits conversions, comparisons, lookups. The test: run the subroutine twice in a row — same result? Then it is pure and shareable; different (it kept state) and it is not.

TraitPure functionStateful
Internal variables initialised firstYesNo (relies on leftovers)
Uses timers/accumulatorsNeverOften
Run twice, same resultYesMaybe not
Shareable main/interruptYes (non-overlapping areas)No — build a dedicated copy

4. Handshake rules for shared data

For data crossing between interrupt and main, use "double buffer + flag" instead of direct sharing: the interrupt writes results to area A and sets "new data"; the main sees the flag, copies A to B, processes B, clears the flag. The interrupt writes only A, the main reads A and writes B — a single writer means no torn reads. Data flowing the other way (main → interrupt) sets the mirror up reversed. Four instructions of handshake buy out a whole class of "occasional wrong value" mysteries.

5. Checklist before calling a subroutine from an interrupt

CheckPass criterion
Subroutine internal devicesDedicated block, or pure-function style (initialised on entry)
Timer/counter numbersInterrupt path owns an exclusive number block
Variables shared with mainBoth directions via double buffer + flag, no direct co-writing
Output actionsThe interrupt path drives no mechanism outputs (flags only)
Subroutine execution timeCounted in the interrupt budget (≤ 30% of the period)
Nested calls insideEach layer checked to the same standard

6. Common errors

SymptomCauseFix
Main program statistics occasionally shortThe shared subroutine's interrupt call races the accumulator areaDedicated accumulator area + handshake
Timing occasionally offA shared timer number driven from the interrupt pathExclusive timer number block for interrupts
Odd state after the interrupt returnsSubroutine scratch values trampledPure-function style or a dedicated copy
Scan-time spikesInterrupt call chain too deepSlim the interrupt path, defer processing to main

7. Notes

A subroutine has no notion of "thread safety" — it is shared code, and its safety depends entirely on whether you give it exclusive resources. The whole craft of calling subroutines from interrupts is two rules: exclusive resources (dedicated copies or pure functions) and data handshakes (double buffer + flag). With both, interleaving is safe; without, faults appear as "occasional, unreproducible".

8. References

Subroutine calls (CALL etc.) and interrupt behaviour follow the PLC's programming manual; variable access and atomicity across tasks are documented in each platform's runtime notes; interrupt size versus scan impact follows the watchdog documentation; the independence of safety functions from all this follows GB 5226.1 / IEC 60204-1.

9. Cautions

⚠️ Three traps to avoid:
① Reusing the main program's subroutine in the interrupt — shared scratch gets trampled, faults never reproduce;
② A timer inside the interrupt subroutine — the main path's same-numbered timer drifts occasionally;
③ A three-deep call chain in the interrupt — scan-time spikes trip the watchdog.

Before writing the interrupt path, carve the "interrupt-only zone" in the partition table and source every device from it — resources carved up, interleaving is safe.

Related reading

Related 3D models: Ready to build it? Download free 3D models & CAD drawings at MOULDL »
MOULDL · Electrical Knowledge Base · free self-study reference for electrical & automation engineers, 3D CAD models at MOULDL