Instrument Technician - Programmable Logic Controllers Part B Notes

Objective One: Math Instructions and PID Control

Rationale

PLCs are essential in industrial automation. Technicians need to understand PLC programming, integration with field instrumentation, and safety concerns for maintenance, troubleshooting, and configuration.

Outcome

Upon completing this module, you will be able to select, configure, troubleshoot, and maintain PLCs.

Prerequisites

Complete module 310403aA, "Programmable Logic Controllers - Part A."

Objectives

  1. Describe PLC ladder logic programs using math instructions and PID control.

  2. Describe PLC programs using subroutines.

Introduction

This module covers math instructions, proportional integral derivative (PID) instructions, generic ladder diagram (LD) instructions, example LD programs, and the use of subroutines.

Math Instructions

  • PLCs use digital signals (binary numbers).

  • Field devices use analog signals (electrical mA).

Math and data comparison instructions enable PLCs to perform operations like a computer. They are often required for controlling a process, especially when working with analog data (integer and real numbers) rather than digital data (logic 1 or logic 0).

Analog Signals

Field input data often comes from analog transmitter signals (4 mA to 20 mA) or pulse-generating devices. PLCs require analog input channels or modules to process analog transmitter signals. Pulse signals may require specialized pulse input channels based on the frequency of the pulse train.

Field output analog data goes to final control elements (FEC) like control valves. The standard analog output signal is 4 mA to 20 mA. PLCs need analog output channels or modules to produce analog output signals.

Analog Modules

Analog input modules connect to devices that provide an electrical signal proportional to the measured variable. For example, a level transmitter provides a milliamp output proportional to the level it detects.

PLCs represent analog signals as binary numbers. Analog input modules have an analog-to-digital converter (ADC) chip that converts the electrical signal to a proportional binary number.

Analog output modules connect to devices that receive an electrical signal and change a manipulated variable in proportion to the signal, such as a milliamp signal to a variable speed drive. Analog output modules have a digital-to-analog converter (DAC) chip that converts a binary number to a proportional electrical signal.

Analog Inputs

Analog input (AI) modules convert an analog input signal into a proportional binary word.

Block Diagram

The PLC side of an AI module has a microcontroller (μCPU) with memory for storing analog input signal values. The μCPU controls the ADC operation by selecting an input and storing the binary word representing that input in memory.

The value stored in the μCPU memory from a 16-bit ADC is a binary number between -32,768 and 32,767 (raw number). Scaling is required to relate this raw binary number to the measured variable. Scaling converts the raw binary number to a real number (percentage or engineering units) that represents the measured variable.

Scaling
  • Scaling is done by the microcontroller (µCPU).

When scaling a channel, choose two points along the operating range and apply low and high values to those points. For example, scaling an analog input channel to represent 4 mA as the low signal and 20 mA as the high signal.

AI Scaling Process

The measured variable (e.g., pressure) is measured by a sensor (PT) and transmitted to the PLC (4 mA to 20 mA signal). It is converted into a binary word (ADC) and then scaled by the AI module's μCPU into a real number.

Scaling is generally done in the AI module. The scaled value is then communicated to the PLC over the backplane to the input image table. With scaling, you change a quantity from one notation (a binary integer value) to another (a real number) in the floating-point data format. The variable tag assigned to that point must be a real data type.

The update speed to the input image table is configurable for microcontroller AI modules. For example, with a real-time sample configured to 100 milliseconds (ms), the AI data is updated ten times a second.

Analog Outputs

Analog output (AO) modules convert a binary word to a proportional analog output signal. Analog outputs control actuators, valves, and motors in industrial environments.

Block Diagram

The PLC side of an AO module also has a μCPU with memory for storing analog output signal values. The μCPU controls the DAC operation and provides it with a binary word to convert to a proportional analog signal.

Processor Output Scan

During the PLC processor output scan, the value for each analog output is communicated over the backplane to the AO module's memory.

AO Scaling Process

The analog output is scaled by the AO module's μCPU into a binary number that the DAC uses.

The DAC converts its input (binary number) to a proportional mA signal. The DAC's output is transmitted to the final control element (FCE) (4 mA to 20 mA signal).

The update speed of the AO module's output signal is configurable for microcontroller-type AO modules. For example, if the requested packet interval is configured to be 50 ms, then its output is updated twenty times a second.

Depending on the requested packet interval value, the output module can receive data multiple times during one program scan.

Comparison Instructions

Comparison instructions compare data from two values or memory locations to make a true or false decision.

Block Diagram

The first input must be a Boolean data type that you insert into an LD program as the first input connects to the LD rung. The enable argument (EN) provides this functionality for LD instructions that require it. Most comparison LD instructions require this.

Common Comparisons

Most PLCs have LD instructions for the following comparisons:

  • equal to (=),

  • less than (<),

  • greater than (>),

  • less than or equal to (<=),

  • greater than or equal to (>=), and

  • not equal to (<>).

When you use these instructions, the data type for both inputs (IN1 and IN2) must be the same. For the greater than instruction (IN1 > IN2), both IN1 and IN2 must be the same data type. If IN1 is 25 (integer [INT] data type) and IN2 is 20 (INT data type), then the greater than instruction evaluates to true (25 is greater than 20). If IN1 is 25.0 (REAL data type) and IN2 is 20 (INT data type), then the greater than instruction is invalid because the data types do not match.

*NOTE: You should not use the equal to instruction with real data type inputs, as real numbers are seldom (if ever) identical. For example, a temperature measurement can never be exactly 50.0°C50.0°C, as that assumes an infinite number of zeros after the decimal place.

Lift Station Example

A lift station pumps waste to a processing plant. When the level in the wet well rises to 6.06.0 metres (m)(m) in automatic mode, the pump starts and draws the level down until the level drops to 0.5m0.5 m.

This control strategy uses two compare instructions:

  1. A greater than instruction to turn the pump on when the level is greater than 6.0m6.0m.2. A less than instruction to turn the pump off when the level is less than 0.5m0.5m.

When the hand-off-auto (HOA) switch is in auto, the LD program in the PLC controls the pump.

With the level at 4.5m4.5 m, the pump off, and the HOA in automatic:

  • Initially, the level is at 4.5m4.5 m and the lift pump (P30) is off; both Latch1 and Latch2 are false. Rung 3 is false because Latch1 and P30 are false.

  • When the level rises above 6.0m6.0 m, the greater than instruction (IN1 > IN2) in rung 1 is now true, so Latch 1 becomes true. This makes rung 3 true, which energizes the motor contactor and starts the lift pump (P30).

  • The pump is on, so the level starts to decrease. When the level drops below 6.0m6.0 m, the greater than instruction (IN1 > IN2) in rung 1 changes to false; therefore, Latch1 is false. However, the pump stays on as P30 and NOT (Latch2) are still true.

  • When the level drops below 0.5m0.5 m, the less than instruction (IN1 < IN2) in rung 2 becomes true, so Latch2 becomes true. This makes rung 3 false, which de-energizes the motor contactor and stops the lift pump.

  • The pump is off, so the level starts to increase. When the level rises above 0.5m0.5 m, the less than instruction (IN1 < IN2) in rung 2 changes to false. However, the pump stays off as P30 and Latch1 are false.

Gas Detection Example

The analog output of the gas detector (AZT101) generates alarms. An output less than 3.0mA3.0 mA indicates a fault in the gas detector that activates an alarm light (AZL101). An output greater than 5.6mA5.6 mA indicates a gas concentration that has surpassed the lower explosive limit (LEL) of 1010% that activates AZL101 and the exhaust fan, AZX101. An output greater than 7.2mA7.2 mA indicates a gas concentration that has surpassed the LEL of 2020%. This activates AZL101, AZX101, and the ESD signal, YZ101.

The set dominant SR latch latches on to the emergency shutdown (ESD) system. To reset the ESD system, you must clear the alarm condition and temporarily activate (pulse) the hand switch (HS101).

The gas detector's analog output (AZT101) is connected to channel 1 of the AI card in slot six. This channel is configured to scale the input signal to a 0 to 20 real number that represents 0 mA to 20 mA.

Rung 1 shows that the alarm light (AZL101) activates if AZT101 is below 3 and either AZX101 or YZ101 are true. Rung 2 shows that the exhaust fan (AZX101) activates if AZT101 is above 5.6 or YZ101 is true. Rung 4 shows that the ESD process shutdown signal (YZ101) activates if AZT101 is above 7.2 and latches on. Rung 3 shows that pushing the reset hand switch (HS101) resets the shutdown signal (YZ101). However, if rung 4 is still true, then the shutdown signal YZ101 is latched on again. Also, YZ101 can be unlatched only if AZT101 has a value below 7.2 and HS101 is pushed.

OUTPUT LATCH Instruction

The LD program uses an OUTPUT LATCH instruction.

The OUTPUT LATCH instruction is also called a SET coil. If the rung that contains an OUTPUT LATCH instruction is true, a logical 1 is stored in the memory location that corresponds to the symbol's address or tag name. If the rung that contains this instruction is false, the OUTPUT LATCH instruction does not change the logical value stored in memory.

OUTPUT UNLATCH instruction

The OUTPUT UNLATCH instruction is also called a RESET coil. If the rung that contains an OUTPUT UNLATCH instruction is true, a logical 0 is stored in the memory location that corresponds to the symbol's address or tag name. If the rung that contains this instruction is false, the OUTPUT LATCH instruction does not change the logical value stored in memory.

*NOTE: The OUTPUT LATCH instruction must always be used with an OUTPUT UNLATCH instruction.

Motor Stop Start Control

Pushing the momentary start button temporarily makes rung 1 true. The OUTPUT LATCH instruction (M1) stores a logical 1 in memory location 0:40.0; this energizes the motor contactor M1 and starts the motor. Releasing the start button makes rung 1 false; this does not change the value stored in memory, so the motor stays on.

The only way to stop the motor is to make rung 2 true. Pushing the momentary stop button makes rung 2 true. The OUTPUT UNLATCH instruction M1 stores a logical 0 in memory location 0:40.0; this de-energizes the motor contactor M1 and stops the motor. Releasing the stop button makes rung 2 false (assuming no thermal overload); this does not change the value stored in memory, so the motor stays off.

A thermal overload (OL1) also makes rung 2 true, which unlatches M1 (stores a logical 0 in memory location 0:40.0). To start the motor after a thermal overload, you must push the start button again.

Math Instructions

Math instructions allow the LD program to solve equations. For example, determining the volume in a cylindrical vessel requires the liquid height to be multiplied by the area of the vessel as the equation shows.

V=(Height)∗(Area)V = (Height) * (Area)

Block Diagram

The first input and output of an LD instruction must be a Boolean data type that is to be inserted into a LD program. The EN input and enable output (ENO) provide this functionality for LD instructions that require it. Most math LD instructions require this.

When you use math instructions, the data type for the inputs must be the same. The LD language used in PLCs typically provide most common math functions, which include the following:

  • addition (+),

  • subtraction (-),

  • multiplication (*),

  • division (/),

  • square root (sqrt),

  • power (pow), and

  • absolute (abs).

Volume Calculation Example

Rung 1 uses a multiplication instruction to multiply the level transmitter's (LT101) scaled input signal by 12.566m212.566 m^2. The output of this instruction is stored as tag Volume. All the variables (LT101, 12.566, and Volume) are real variables. The EN input and ENO output are Boolean arguments that allow you to insert this instruction into an LD program. The level transmitter's 4 mA to 20 mA analog signal is scaled in the analog input module to engineering units such as 0.0m0.0 m to 6.0m6.0 m.

The LD program is executed every scan cycle. If the scan cycle takes 100ms100 ms, then this calculation is done ten times a second, which is excessive and unnecessary. Timer instructions control (set) the timing of the calculation.

Every five seconds, T1.Q goes high for one scan cycle during which time the volume calculation instruction is executed.

Scaling Calculation Example

Analog inputs are typically scaled for use in the LD program by the analog input module. However, some analog input modules may not have this capability; in these situations, you use math blocks to scale.

For example, the raw integer output of the ADC must be scaled to engineering units. To do this requires that you know how the analog input module works. The following points explain the operation of an analog input module.

  • The analog input card uses a 16-bit ADC and has a range of 0 mA to 21 mA.

  • The raw integer output of the ADC for a 0 mA signal is −32768-32 768 and for a 21mA21 mA signal it is 3276732 767.

  • Therefore, the raw integer output of the ADC for a 4mA4 mA signal is −20285-20 285 and for a 20mA20 mA signal it is 2964629 646.

If the analog temperature transmitter range is between −20°C-20°C to 100°C100°C, then the raw integer output form the ADC for −20°C(4mA)-20°C (4 mA) is −20285-20 285; the raw integer output for the ADC for 100°C(20mA)100°C (20 mA) is 2964629 646. To scale the raw integer output of the ADC to engineering units (°C)(°C), requires the following math calculation (input/output [I/O] formula).

x(Span<em>OUT)+(LRV</em>OUT)x (Span<em>{OUT}) + (LRV</em>{OUT})

  • $[ADCoutput - (-20,285)] / (49,931) * (120°C) + (-20°C)</p></li><li><p>TT101−(−20,285)=TT101Raw/49,931=TT101Frac∗120=TT101Span+(−20)=TTDegC</p></li></ul><h5id="7eca1296−e8cc−4b40−a78a−876b4273786e"data−toc−id="7eca1296−e8cc−4b40−a78a−876b4273786e"collapsed="false"seolevelmigrated="true">TemperatureControl</h5><p>Rung1usesasubtractinstructiontosubtractthetemperaturetransmitter′ssignal(TT101)from</p></li><li><p>TT101 - (-20,285) = TT101 Raw / 49,931 = TT101 Frac * 120 = TT101Span + (-20) = TTDegC</p></li></ul><h5 id="7eca1296-e8cc-4b40-a78a-876b4273786e" data-toc-id="7eca1296-e8cc-4b40-a78a-876b4273786e" collapsed="false" seolevelmigrated="true">Temperature Control</h5><p>Rung 1 uses a subtract instruction to subtract the temperature transmitter's signal (TT101) from-20 285.TheoutputofthisinstructionisstoredastagTT101Raw(realnumber).</p><p>Rung2usesadivideinstructiontodivideTT101Rawby. The output of this instruction is stored as tag TT101Raw (real number).</p><p>Rung 2 uses a divide instruction to divide TT101Raw by49 931.TheoutputofthisinstructionisstoredastagTT101Frac(realnumber).</p><p>Rung3usesamultiplicationinstructiontomultiplyTT101Fracby. The output of this instruction is stored as tag TT101Frac (real number).</p><p>Rung 3 uses a multiplication instruction to multiply TT101Frac by120.0.TheoutputofthisinstructionisstoredastagTT101Span(realnumber).</p><p>Rung4usesanadditioninstructiontoadd. The output of this instruction is stored as tag TT101Span (real number).</p><p>Rung 4 uses an addition instruction to add-20.0toTT101Span.TheoutputofthisinstructionisstoredastagTT101DegC(realnumber).</p><p>Rung5setstagLowtotrueifthetemperatureisbelowto TT101Span. The output of this instruction is stored as tag TT101 DegC (real number).</p><p>Rung 5 sets tag Low to true if the temperature is below47°C.</p><p>Rung6setstagHightotrueifthetemperatureisabove.</p><p>Rung 6 sets tag High to true if the temperature is above53°C.</p><p>Rung7turnsontheheateriftagLowissettotrueandturnsofftheheaterifTagHighistrue.</p><p>∗NOTE:Theon/offswitch(TS)mustalsobeclosed.</p><p>TheLDprogramusedfourmathinstructionstoperformtherequiredoperations.Programmablelogiccontrollermanufacturersgenerallyprovideamathinstructionthatcanperformmultiplemathstepsinasingleinstruction.Thisinstructionhasaprogrammablepop−upwindowinwhichthecalculationissetoutinmuchthesamewayyouuseacalculator.</p><h4id="eb9685e4−3715−401a−86c5−ad07c740f4f6"data−toc−id="eb9685e4−3715−401a−86c5−ad07c740f4f6"collapsed="false"seolevelmigrated="true">ProportionalIntegralDerivativeInstruction</h4><p>Proportionalintegralderivative(PID)controlisfeedbackcontrolthatusesaPIDcontrolalgorithm.Inafeedbackcontrolsystem,theprocessvariable(PV)iscomparedtothesetpoint(SP)thatdeterminesanerror(e).ThePIDalgorithmactstoreducethemagnitudeoftheerrorbycalculatingacontrolleroutput(CO)signalwhichinturnaffectsthevalueofthePV.</p><ul><li><p>PIDControlAlgorithm:SP−e−PID−CO−PV</p></li></ul><p>TheSPisanoperator−generatedvaluethatindicatesthedesiredvalueatwhichtheoperatorwantsthePVtobe.ThePVisameasuredsignalthatmustbecommunicatedtothecontroller.TheCOisasignalfromthecontrollerthatmustbecommunicatedtothefinalcontrolelement(FCE).</p><p>YoucanprogramaPLCtoperformfeedbackcontrolwithoutusinganyspecializedinstructions;however,PLCvendorsprovideaPIDinstructionforthispurpose.ComplexinstructionssuchasthisarenotinIEC1131−3and,therefore,arevendor−specific.</p><h5id="363e041c−f15e−4c69−91f2−1fe6e2a5eac7"data−toc−id="363e041c−f15e−4c69−91f2−1fe6e2a5eac7"collapsed="false"seolevelmigrated="true">Arguments</h5><ul><li><p>TheENandENOargumentsallowtheinstructiontobeinsertedintoanLDrung.TheinstructionexecutesifENistrue;theENOargumentissettoequaltheENargument.</p></li><li><p>Theinstructionneedstobegivenatagname(forthisexampleTIC101).Whenthistagnameiscreatedinthetagbaseeditor,itmustbeofdatatypePID.</p></li><li><p>Thephysicaladdressortagfortheprocessvariable(PV)needstobespecified.</p></li><li><p>Thephysicaladdressortagforthecontroller′soutput(CO)needstobespecified.</p></li><li><p>Theconfigurationbuttonwhenactivatedbringsupapop−upwindowtoallowforconfigurationoftheoperationoftheinstructionforaspecificapplication.</p></li></ul><p>APIDinstructiongenerallyrequiresoperatorinteraction.Forexample,theoperatormaywishtodooneofthefollowing:</p><ul><li><p>TochangetheSP.</p></li><li><p>ToputthePIDinstructioninmanualmode,sothatheorshecanmanuallyadjusttheoutputsignaltotheFCE.</p></li><li><p>ToputthePIDinstructioninautomaticmode,sothattheinstruction′scalculatedoutputgoestotheFCE.</p></li><li><p>TochangethetuningparametersthataffecttheautomaticoperationofthePIDinstruction.</p></li></ul><h5id="e610eca8−faec−431f−989c−30bc5c081e63"data−toc−id="e610eca8−faec−431f−989c−30bc5c081e63"collapsed="false"seolevelmigrated="true">LegacySetup</h5><p>ThePIDinstructionisprogrammedusingthephysicaladdressfortheseinputsandoutputs.</p><ul><li><p>ThePIDinstructionisgivenatagname(TIC101)thatiscreatedintheeditorofthetagbase.</p></li><li><p>ThePIDinstruction′sPVisprogrammedforaphysicaladdress<1:50>towhichtheanaloginputchannelthePVsignal(TT101)isconnected.</p></li><li><p>ThePIDinstruction′sSPisprogrammedforaphysicaladdress<1:51>,theanaloginputchanneltowhichthemanualSPadjustdeviceisconnected.</p></li><li><p>ThePIDinstruction′sTiebackisprogrammedforaphysicaladdress<1:52>,theanaloginputchanneltowhichthemanualoutputadjustdeviceisconnected.</p></li><li><p>ThePIDinstruction′smodeisprogrammedforaphysicaladdress<1:30.00>,thedigitalinputbittowhichtheauto/manualswitchisconnected.</p></li><li><p>ThePIDinstruction′sCOisprogrammedforaphysicaladdress<0:61>,theanalogoutputchanneltowhichtheFCE(TY101)isconnected.</p></li></ul><p>Wheninautomatic,thePIDinstructioncalculatesthevalueofCOfromitsPVandSPinputs.Wheninmanual,theoperator−adjustedinput(Tieback)isusedastheCOoftheinstruction.ThedashedarrowindicatesthatthisvalueisalsousedbythePIDinstructiontoprovidebumplesstransfer.</p><h5id="5da36908−9ee3−4af2−a854−eb787fb49d3d"data−toc−id="5da36908−9ee3−4af2−a854−eb787fb49d3d"collapsed="false"seolevelmigrated="true">ModernSetup</h5><p>ThePIDinstructionissetupusingonlythephysicaladdressforthePVinputandCOoutput.</p><ul><li><p>ThePIDinstructionisgivenatagname(TIC101)whichiscreatedintheeditorofthetagbase.</p></li><li><p>ThePIDinstruction′sPVisprogrammedforaphysicaladdress<1:50>towhichtheanaloginputchannelthePVsignal(TT101)isconnected.</p></li><li><p>ThePIDinstruction′sCOisprogrammedforaphysicaladdress<0:61>towhichtheanalogoutputchanneltheFCE(TY101)isconnected.</p></li></ul><p>WhenaPIDinstructionisgivenatagname(TIC101inthisexample),amemorymapiscreatedthatcanbeaccessedfromanHMI(operatorstationortouchpanel)throughacommunicationnetwork(Ethernet/IPinthisexample).TheHMIwritestoandreadsfromthememoryofthePIDinstruction.</p><ul><li><p>BywritingtotagTIC101.SP,thePIDinstruction′sSPargumentcanbechanged.</p></li><li><p>BywritingtotagTIC101.SWN,thePIDinstruction′smode(auto/manual)canbechanged.</p></li><li><p>BywritingtotagTIC101.OUT,thePIDinstruction′sCOargumentcanbechanged.</p></li></ul><p>ThevalueofthePV,SP,andCOaredisplayedontheHMIfortheoperatortosee.Thesevaluesarereadfromtheappropriatememorylocation.Inaddition,theHMIallowspersonneltochangeotherinternaltagsassociatedwiththePIDinstruction,suchasitstuningparameters.Inthisexample,TIC101.KPistheproportionalgainparameter,TIC101.KIistheintegralgainparameter,andTIC101.KDisthederivativegainparameter.</p><h4id="10b5e207−6b1a−4b16−a26f−5936d8d8b668"data−toc−id="10b5e207−6b1a−4b16−a26f−5936d8d8b668"collapsed="false"seolevelmigrated="true">InstructionConfiguration</h4><p>AfteraPIDinstructionisinsertedintoanLD,givenatagnameanditsI/Opoint′ssetup,youuseitsconfigurationtabs(pop−upwindows)tofinishitsconfiguration.ThissetsupthePIDinstructionforitsspecificapplication.WhenyouuseanHMI,alltheseparametersarechangeablefromtheHMI.</p><p>OnceyouhaveinsertedthePIDinstructioninanLDprogramtoconfigure,youmustchangeparametersin:</p><ul><li><p>PIDConfiguration</p></li><li><p>tuning,</p></li><li><p>algorithmconfiguration,</p></li><li><p>alarms,and</p></li><li><p>scaling.</p></li></ul><h5id="f7d94cb2−37cc−4ace−b7a2−da575f8ac436"data−toc−id="f7d94cb2−37cc−4ace−b7a2−da575f8ac436"collapsed="false"seolevelmigrated="true">TuningTab</h5><p>Thetuningtaborwindowallowsyoutoentertheinitialtuningparametersfortheinstruction,suchasproportionalgain,integralgain,andderivativegain.Thevalueforthesetpointandmode(autoormanual)ofoperationistypicallyadjustablewithinthistab.</p><h5id="cee262d4−05bb−4bb5−9beb−3e423a6b1631"data−toc−id="cee262d4−05bb−4bb5−9beb−3e423a6b1631"collapsed="false"seolevelmigrated="true">AlgorithmConfiguration</h5><p>ThealgorithmconfigurationtaborwindowallowsyoutoconfigurethePIDoperation.Someoftheoptionsinclude:</p><ul><li><p>thePIDequationtype(interacting,non−interacting,orparallel),</p></li><li><p>thecontroller′saction(directorreverse),</p></li><li><p>thederivativeactionoftheerrororPV,</p></li><li><p>theSPtrackingofthePVinmanualmode,</p></li><li><p>thehighandlowlimitforthecontroller′soutput(tominimizeresetwindup)</p></li><li><p>thecascadeoperation,and</p></li><li><p>theloopupdatetime.</p></li></ul><p>Theloopupdatetimeishowoftenthisinstructionisexecuted.Youmustaccuratelysetthisfortheintegralandderivativeactiontoperformcorrectly.</p><h5id="2bee1627−8c94−424e−8da4−959198fd4d74"data−toc−id="2bee1627−8c94−424e−8da4−959198fd4d74"collapsed="false"seolevelmigrated="true">Alarms</h5><p>Thealarmtaborwindowallowsyoutoconfigurethetypicalalarmsusedwithfeedbackcontrol,suchasPVhighandlowalarmsandPVdeviationfortheSPalarms.TheHMIcanaccessthesealarmsbytheirtagname.Forexample,TIC101.PVHisthetagnameforthePVhighalarmforaPIDinstructionwiththetagnameTIC101.YoucanalsoprogramthePLCtoenergizeanoutputusingthealarmstagnameintheLDprogram.</p><h5id="8251a12b−d983−4067−b0bd−77090a1d095d"data−toc−id="8251a12b−d983−4067−b0bd−77090a1d095d"collapsed="false"seolevelmigrated="true">Scaling</h5><p>Thescalingtaborwindowscalestheprocessvariable,controlleroutput,andtiebackvariabletomatchthePIDinstruction′sinternalcalculationrequirements.Howyoudothisdependsonhowtheanaloginputmoduleandanalogoutputmoduleareconfigured.</p><p>LegacyPIDinstructionstypicallyrequirethatthePV,CO,andtiebackvariablesbescaledtoanunsigned12−bitintegervalue(0to4095).ThiswasrequiredbecausethePIDcalculationwasdesignedtooperateasa12−bitmachine.MostPIDinstructionsnowoperateusingfractionalrealnumbersand,therefore,requirescalingtoconverttoandfromthisfractionalformat.Forexample,foratemperaturecontrolloop:</p><ul><li><p>the16−bitanaloginputchannelforthePVissetupwithscalingtomatchitsengineeringrange(.</p><p>Rung 7 turns on the heater if tag Low is set to true and turns off the heater if Tag High is true.</p><p>*NOTE: The on/off switch (TS) must also be closed.</p><p>The LD program used four math instructions to perform the required operations. Programmable logic controller manufacturers generally provide a math instruction that can perform multiple math steps in a single instruction. This instruction has a programmable pop-up window in which the calculation is set out in much the same way you use a calculator.</p><h4 id="eb9685e4-3715-401a-86c5-ad07c740f4f6" data-toc-id="eb9685e4-3715-401a-86c5-ad07c740f4f6" collapsed="false" seolevelmigrated="true">Proportional Integral Derivative Instruction</h4><p>Proportional integral derivative (PID) control is feedback control that uses a PID control algorithm. In a feedback control system, the process variable (PV) is compared to the setpoint (SP) that determines an error (e). The PID algorithm acts to reduce the magnitude of the error by calculating a controller output (CO) signal which in turn affects the value of the PV.</p><ul><li><p>PID Control Algorithm: SP - e - PID - CO - PV</p></li></ul><p>The SP is an operator-generated value that indicates the desired value at which the operator wants the PV to be. The PV is a measured signal that must be communicated to the controller. The CO is a signal from the controller that must be communicated to the final control element (FCE).</p><p>You can program a PLC to perform feedback control without using any specialized instructions; however, PLC vendors provide a PID instruction for this purpose. Complex instructions such as this are not in IEC1131-3 and, therefore, are vendor-specific.</p><h5 id="363e041c-f15e-4c69-91f2-1fe6e2a5eac7" data-toc-id="363e041c-f15e-4c69-91f2-1fe6e2a5eac7" collapsed="false" seolevelmigrated="true">Arguments</h5><ul><li><p>The EN and ENO arguments allow the instruction to be inserted into an LD rung. The instruction executes if EN is true; the ENO argument is set to equal the EN argument.</p></li><li><p>The instruction needs to be given a tag name (for this example TIC101). When this tag name is created in the tag base editor, it must be of data type PID.</p></li><li><p>The physical address or tag for the process variable (PV) needs to be specified.</p></li><li><p>The physical address or tag for the controller's output (CO) needs to be specified.</p></li><li><p>The configuration button when activated brings up a pop-up window to allow for configuration of the operation of the instruction for a specific application.</p></li></ul><p>A PID instruction generally requires operator interaction. For example, the operator may wish to do one of the following:</p><ul><li><p>To change the SP.</p></li><li><p>To put the PID instruction in manual mode, so that he or she can manually adjust the output signal to the FCE.</p></li><li><p>To put the PID instruction in automatic mode, so that the instruction's calculated output goes to the FCE.</p></li><li><p>To change the tuning parameters that affect the automatic operation of the PID instruction.</p></li></ul><h5 id="e610eca8-faec-431f-989c-30bc5c081e63" data-toc-id="e610eca8-faec-431f-989c-30bc5c081e63" collapsed="false" seolevelmigrated="true">Legacy Setup</h5><p>The PID instruction is programmed using the physical address for these inputs and outputs.</p><ul><li><p>The PID instruction is given a tag name (TIC101) that is created in the editor of the tag base.</p></li><li><p>The PID instruction's PV is programmed for a physical address <1:50> to which the analog input channel the PV signal (TT101) is connected.</p></li><li><p>The PID instruction's SP is programmed for a physical address <1:51>, the analog input channel to which the manual SP adjust device is connected.</p></li><li><p>The PID instruction's Tieback is programmed for a physical address <1:52>, the analog input channel to which the manual output adjust device is connected.</p></li><li><p>The PID instruction's mode is programmed for a physical address <1:30.00>, the digital input bit to which the auto/manual switch is connected.</p></li><li><p>The PID instruction's CO is programmed for a physical address <0:61>, the analog output channel to which the FCE (TY101) is connected.</p></li></ul><p>When in automatic, the PID instruction calculates the value of CO from its PV and SP inputs. When in manual, the operator-adjusted input (Tieback) is used as the CO of the instruction. The dashed arrow indicates that this value is also used by the PID instruction to provide bumpless transfer.</p><h5 id="5da36908-9ee3-4af2-a854-eb787fb49d3d" data-toc-id="5da36908-9ee3-4af2-a854-eb787fb49d3d" collapsed="false" seolevelmigrated="true">Modern Setup</h5><p>The PID instruction is setup using only the physical address for the PV input and CO output.</p><ul><li><p>The PID instruction is given a tag name (TIC101) which is created in the editor of the tag base.</p></li><li><p>The PID instruction's PV is programmed for a physical address <1:50> to which the analog input channel the PV signal (TT101) is connected.</p></li><li><p>The PID instruction's CO is programmed for a physical address <0:61> to which the analog output channel the FCE (TY101) is connected.</p></li></ul><p>When a PID instruction is given a tag name (TIC101 in this example), a memory map is created that can be accessed from an HMI (operator station or touch panel) through a communication network (Ethernet/IP in this example). The HMI writes to and reads from the memory of the PID instruction.</p><ul><li><p>By writing to tag TIC101.SP, the PID instruction's SP argument can be changed.</p></li><li><p>By writing to tag TIC101.SWN, the PID instruction's mode (auto/manual) can be changed.</p></li><li><p>By writing to tag TIC101.OUT, the PID instruction's CO argument can be changed.</p></li></ul><p>The value of the PV, SP, and CO are displayed on the HMI for the operator to see. These values are read from the appropriate memory location. In addition, the HMI allows personnel to change other internal tags associated with the PID instruction, such as its tuning parameters. In this example, TIC101.KP is the proportional gain parameter, TIC101.KI is the integral gain parameter, and TIC101.KD is the derivative gain parameter.</p><h4 id="10b5e207-6b1a-4b16-a26f-5936d8d8b668" data-toc-id="10b5e207-6b1a-4b16-a26f-5936d8d8b668" collapsed="false" seolevelmigrated="true">Instruction Configuration</h4><p>After a PID instruction is inserted into an LD, given a tag name and its I/O point's setup, you use its configuration tabs (pop-up windows) to finish its configuration. This sets up the PID instruction for its specific application. When you use an HMI, all these parameters are changeable from the HMI.</p><p>Once you have inserted the PID instruction in an LD program to configure, you must change parameters in:</p><ul><li><p>PID Configuration</p></li><li><p>tuning,</p></li><li><p>algorithm configuration,</p></li><li><p>alarms, and</p></li><li><p>scaling.</p></li></ul><h5 id="f7d94cb2-37cc-4ace-b7a2-da575f8ac436" data-toc-id="f7d94cb2-37cc-4ace-b7a2-da575f8ac436" collapsed="false" seolevelmigrated="true">Tuning Tab</h5><p>The tuning tab or window allows you to enter the initial tuning parameters for the instruction, such as proportional gain, integral gain, and derivative gain. The value for the setpoint and mode (auto or manual) of operation is typically adjustable within this tab.</p><h5 id="cee262d4-05bb-4bb5-9beb-3e423a6b1631" data-toc-id="cee262d4-05bb-4bb5-9beb-3e423a6b1631" collapsed="false" seolevelmigrated="true">Algorithm Configuration</h5><p>The algorithm configuration tab or window allows you to configure the PID operation. Some of the options include:</p><ul><li><p>the PID equation type (interacting, non-interacting, or parallel),</p></li><li><p>the controller's action (direct or reverse),</p></li><li><p>the derivative action of the error or PV,</p></li><li><p>the SP tracking of the PV in manual mode,</p></li><li><p>the high and low limit for the controller's output (to minimize reset windup)</p></li><li><p>the cascade operation, and</p></li><li><p>the loop update time.</p></li></ul><p>The loop update time is how often this instruction is executed. You must accurately set this for the integral and derivative action to perform correctly.</p><h5 id="2bee1627-8c94-424e-8da4-959198fd4d74" data-toc-id="2bee1627-8c94-424e-8da4-959198fd4d74" collapsed="false" seolevelmigrated="true">Alarms</h5><p>The alarm tab or window allows you to configure the typical alarms used with feedback control, such as PV high and low alarms and PV deviation for the SP alarms. The HMI can access these alarms by their tag name. For example, TIC101.PVH is the tag name for the PV high alarm for a PID instruction with the tag name TIC101. You can also program the PLC to energize an output using the alarms tag name in the LD program.</p><h5 id="8251a12b-d983-4067-b0bd-77090a1d095d" data-toc-id="8251a12b-d983-4067-b0bd-77090a1d095d" collapsed="false" seolevelmigrated="true">Scaling</h5><p>The scaling tab or window scales the process variable, controller output, and tieback variable to match the PID instruction's internal calculation requirements. How you do this depends on how the analog input module and analog output module are configured.</p><p>Legacy PID instructions typically require that the PV, CO, and tieback variables be scaled to an unsigned 12-bit integer value (0 to 4095). This was required because the PID calculation was designed to operate as a 12-bit machine. Most PID instructions now operate using fractional real numbers and, therefore, require scaling to convert to and from this fractional format. For example, for a temperature control loop:</p><ul><li><p>the 16-bit analog input channel for the PV is setup with scaling to match its engineering range (-50°Ctoto150°C),</p></li><li><p>the16−bitanalogoutputchannelfortheCOissetupwithoutscaling,and</p></li><li><p>notiebacksignalisused.</p></li></ul><p>BecausetheanaloginputchannelscalesthePVtoengineeringunits(realnumber),thePIDinstructionneedsthelowerandupperrangevaluestoconvertthePVtoafractionalnumber.ThisrequiresyoutoconfigurethePIDinstructionPVparameterasfollows.</p><ul><li><p>ThePVunscaledmaximum(max)andengineeringunitmaximumaresettothesamevalueof),</p></li><li><p>the 16-bit analog output channel for the CO is setup without scaling, and</p></li><li><p>no tieback signal is used.</p></li></ul><p>Because the analog input channel scales the PV to engineering units (real number), the PID instruction needs the lower and upper range values to convert the PV to a fractional number. This requires you to configure the PID instruction PV parameter as follows.</p><ul><li><p>The PV unscaled maximum (max) and engineering unit maximum are set to the same value of150°C.</p></li><li><p>ThePVunscaledminimum(min)andengineeringunitminimumaresettothesamevalueof.</p></li><li><p>The PV unscaled minimum (min) and engineering unit minimum are set to the same value of-50°C.</p></li></ul><p>BecausetheanalogoutputchanneldoesnotscaletheCOtoengineeringunits,thePIDinstructionneedsthelowerandupperrangesignedintegervaluesthatcorrespondto4mAand20mA.Ifthe16−bitanalogoutputcardissetupfor0mAto21mA(.</p></li></ul><p>Because the analog output channel does not scale the CO to engineering units, the PID instruction needs the lower and upper range signed integer values that correspond to 4mA and 20mA. If the 16-bit analog output card is setup for 0mA to 21mA (0 mA is -32 768andand21mA is +32 767),thentherequiredscalingis:</p><ul><li><p>theCOmin(0), then the required scaling is:</p><ul><li><p>the CO min (0% or fractional 0.00) is set to-20 285 (4 mA),and</p></li><li><p>theCOmax(100, and</p></li><li><p>the CO max (100% or fractional 1.00) is set to+29 646 (20 mA).</p></li></ul><p>∗PIDInstruction:LoopUpdateTimemustmatchExecutionTime.AIandAOofPIDmustbeexecutedorupdated10xfasterthanPIDinstruction.</p><h5id="21fa631a−6834−4e40−8c70−ba2969d30c09"data−toc−id="21fa631a−6834−4e40−8c70−ba2969d30c09"collapsed="false"seolevelmigrated="true">InstructioninPeriodicTask</h5><p>Periodictasksareseparateprogramsthatrunatpredefinedintervals.</p><p>Aperiodictaskhasanexecutiontimeunlikeacontinuoustask.ThePLCcontrollerexecutesacontinuoustaskduringeveryscancycle.</p><p>Forexample,ifthescancycletakes.</p></li></ul><p>*PID Instruction: Loop Update Time must match Execution Time. AI and AO of PID must be executed or updated 10x faster than PID instruction.</p><h5 id="21fa631a-6834-4e40-8c70-ba2969d30c09" data-toc-id="21fa631a-6834-4e40-8c70-ba2969d30c09" collapsed="false" seolevelmigrated="true">Instruction in Periodic Task</h5><p>Periodic tasks are separate programs that run at predefined intervals.</p><p>A periodic task has an execution time unlike a continuous task. The PLC controller executes a continuous task during every scan cycle.</p><p>For example, if the scan cycle takes125 msandtheperiodictaskexecutiontimeisand the periodic task execution time is250 ms,thenthecontinuoustask(LDprogram)isexecutedevery, then the continuous task (LD program) is executed every125 ms,whiletheperiodictaskisexecutedevery, while the periodic task is executed every250 ms.Aperiodictask(LDprogram)isexecutedonitsconfiguredtime.Thistimeintervalismoreprecisethanwhenyouuseatimerinacontinuoustaskprogram.ThePIDinstructionisexecutedonlywhentheperiodictaskisexecuted.</p><p>∗Periodictaskconfiguredtimeismoreprecisethanatimerinacontinuoustaskprogram.</p><h3id="32fc5c7f−0f43−4e79−953f−fb3fc9a4d2f0"data−toc−id="32fc5c7f−0f43−4e79−953f−fb3fc9a4d2f0"collapsed="false"seolevelmigrated="true">ObjectiveTwo:Subroutines</h3><p>Subroutinesareself−containedprogramsthatperformaspecificoperationwithablockofprogramlogic.Whenasubroutineiscalled,controlistransferredtothesubroutinefromitsmasterroutine.Attheconclusionofthesubroutine,controlrevertsbacktothemasterroutine.Subroutineshelporganizecomplexprogramsortorepeatanoperationseveraltimeswithinoneroutine.</p><p>TheinstructionsthatthePLCvendorsusetojumptoandfromsubroutinesvarieswidely.It′simportanttoinformyourselfontheoperationforyourspecificPLC.ThismoduleusesthefollowingLDblockinstructions:</p><ul><li><p>jumptosubroutine(JSR),</p></li><li><p>subroutine(SBR),and</p></li><li><p>return(RET).</p></li></ul><p>Theseinstructionsareusedtojumptoasubroutine,passdatatothesubroutine,executethesubroutine,andreturnresultstothemasterroutine.</p><p>∗Subroutinesorganizecomplexprogramsorhelptorepeatanoperationseveraltimeswithinoneroutine.</p><p>Forexample,ifrung2ofthemasterroutineistrue,thenthejumptosubroutine(JSR)instructionjumpstothesubroutinewiththatname.Theexecutionofrung3inthesubroutinereturnsprogramexecutionbacktothemasterroutine.Themasterroutineisexecuted,startingattherungaftertheJSRinstruction(rung3).Whenthesubroutineisbeingexecuted,alldatainthemasterroutineremainsthesameasitwasonleavingunlessthesubroutinechangessomeofit.WhentherungthatcontainstheJSRinstructiongoesfalse,alllocaloutputsinthesubroutineareheldintheirlaststate.</p><p>Subroutinesarenotinthemasterormainroutinebutarecreatedasaseparateroutineandgivenauniquename.</p><h4id="af697ee2−c148−42b8−a210−47eb9896d121"data−toc−id="af697ee2−c148−42b8−a210−47eb9896d121"collapsed="false"seolevelmigrated="true">JumptoSubroutineInstruction</h4><p>Ifrung2ofthemasterroutineistrue,theJSRinstructionjumpstothenamedsubroutine.Rung3inthesubroutinereturnsprogramexecutiontothemasterroutine,whichresumesattherungaftertheJSRinstruction(rung3).Datainthemasterroutineremainsunchangedunlessalteredbythesubroutine.WhentheJSRinstruction′srunggoesfalse,subroutinelocaloutputsholdtheirlaststate.</p><h4id="b901361f−785e−4693−a4cc−1a3fdf5c7824"data−toc−id="b901361f−785e−4693−a4cc−1a3fdf5c7824"collapsed="false"seolevelmigrated="true">SubroutineInstruction</h4><p>Firstrungofthesubroutinemustcontainthesubroutine(SBR)instructionthatassignsitslocaltagstothevalueofthepassedinputparameters</p><h4id="425d3d14−eb39−4c10−b616−980ddadb390d"data−toc−id="425d3d14−eb39−4c10−b616−980ddadb390d"collapsed="false"seolevelmigrated="true">ReturnInstruction</h4><p>Lastrungofthesubroutineoftenhasareturn(RET)instruction,returnsexecutionbacktothemainprogramandpassesthevalueoftagResultasitsfirstreturnparameter</p><h4id="dbc94ae3−6c0c−4c6c−aa25−23135eb8584d"data−toc−id="dbc94ae3−6c0c−4c6c−aa25−23135eb8584d"collapsed="false"seolevelmigrated="true">SubroutineInstructionsExample</h4><p>Forthisexample,assumethevalueofInput1(taginmainroutine)is25andthevalueofInput2(taginmainroutine)is15.</p><ul><li><p>TheJSRinstructioninRung1ofthemainprogramcallsthesubroutineRoutineAandpassesthevalueofitstwoinputparameters(Input1andInput2).</p></li><li><p>Thefirstrungofthesubroutine(Rung1)mustcontainthesubroutine(SBR)instructionthatassignsitslocaltags(valueAandvalueB)tothevalueofthepassedinputparameters.Therefore,valueA=25(valueofInput1)andvalueB=15(valueofInput2).</p></li><li><p>Rung2stores15inthetagResult(calculates25−15).</p></li><li><p>IfinstructionAistrue,thenrung3,whichhasareturn(RET)instruction,returnsexecutionbacktothemainprogramandpassesthevalueoftagResultasitsfirstreturnparameterRETPar.</p></li><li><p>ThereturnedparameterisassignedtothetagOutputinthemainroutineandthenthenextrungofthemainroutineisexecuted.ThevalueassignedtoOutputis15.</p></li></ul><p>IfinstructionAisfalse,thenrung3ofthesubroutineisnotexecuted.Therefore,rung4isexecuted,whichstores40inthetagResult(calculates25+15).IfinstructionBinrung5istrue,thenthesubroutinepasses40backtothemainroutine.Inthiscase,thevalueassignedtooutputis40.</p><p>IfbothinstructionAandinstructionBarefalse,thenrung6isexecuted;thispasses50backtothemainroutine.Inthiscase,thevalueassignedtooutputis50.</p><h5id="7ac89647−c460−4364−b1b6−d87d433299f8"data−toc−id="7ac89647−c460−4364−b1b6−d87d433299f8"collapsed="false"seolevelmigrated="true">Restrictions</h5><p>Therearenorestrictionsonthenumberofinputoroutputparametersthatsubroutineinstructionscanconfigure.However,youmustfollowthefollowingpointswhenusingsubroutines.</p><ul><li><p>Thedatatypefortheinputparameterspassedtoasubroutinemustmatchthedatatypeforthecorrespondingtaginthesubroutine.</p></li><li><p>Thedatatypeforthereturnparameterspassedtothemainroutinemustmatchthedatatypeforthecorrespondingtaginthemainroutine.</p></li><li><p>Theorderoftheparameters(toptobottom)intheinstructiondetermineswhichvalueisassignedtoit.</p></li></ul><h4id="ce5527e7−aec5−4245−a33b−dc86b5a4a8e5"data−toc−id="ce5527e7−aec5−4245−a33b−dc86b5a4a8e5"collapsed="false"seolevelmigrated="true">NestedSubroutines</h4><p>Nestedsubroutinesallowyoutodirectprogramflowfromthemainroutinetoasubroutineandthentoanothersubroutine(nestedsubroutine).Nestedsubroutinescanmakecomplexprogrammingeasier.</p><ul><li><p>Theprogramexecutionisdirectedtoasubroutineifrung2ofthemainprogramistrue.</p></li><li><p>Thesubroutinedirectsprogramexecutiontoanestedsubroutineifrung3ofthesubroutineistrue.</p></li><li><p>Rung3ofthenestedsubroutinedirectsprogramexecutionbacktorung4ofthesubroutine.</p></li><li><p>Rung4ofthesubroutinedirectsprogramexecutionbacktoRung3ofthemainroutine.</p></li></ul><h4id="bb5c0566−ecff−4523−ae57−a3f917af901a"data−toc−id="bb5c0566−ecff−4523−ae57−a3f917af901a"collapsed="false"seolevelmigrated="true">RepetitiveCalculationExample</h4><p>TheanaloginputsTT101andTT102arenotscaledbytheAImodule.ThescalingisdoneinasubroutinecalledConvert,ratherthaninthemainroutinebecausethisisarepetitiveblockoflogic.</p><p>TheAImodulehasa16−bitADCthatproducesasignedintegeroutputbetween−32,768and32,767froma0mAto21mAinputsignal.A4mAsignalproducesa−20,285output,whilea20mAsignalproducesa29,646output.Theengineeringrangeforthetemperaturetransmittersis. A periodic task (LD program) is executed on its configured time. This time interval is more precise than when you use a timer in a continuous task program. The PID instruction is executed only when the periodic task is executed.</p><p>*Periodic task configured time is more precise than a timer in a continuous task program.</p><h3 id="32fc5c7f-0f43-4e79-953f-fb3fc9a4d2f0" data-toc-id="32fc5c7f-0f43-4e79-953f-fb3fc9a4d2f0" collapsed="false" seolevelmigrated="true">Objective Two: Subroutines</h3><p>Subroutines are self-contained programs that perform a specific operation with a block of program logic. When a subroutine is called, control is transferred to the subroutine from its master routine. At the conclusion of the subroutine, control reverts back to the master routine. Subroutines help organize complex programs or to repeat an operation several times within one routine.</p><p>The instructions that the PLC vendors use to jump to and from subroutines varies widely. It's important to inform yourself on the operation for your specific PLC. This module uses the following LD block instructions:</p><ul><li><p>jump to subroutine (JSR),</p></li><li><p>subroutine (SBR), and</p></li><li><p>return (RET).</p></li></ul><p>These instructions are used to jump to a subroutine, pass data to the subroutine, execute the subroutine, and return results to the master routine.</p><p>*Subroutines organize complex programs or help to repeat an operation several times within one routine.</p><p>For example, if rung 2 of the master routine is true, then the jump to subroutine (JSR) instruction jumps to the subroutine with that name. The execution of rung 3 in the subroutine returns program execution back to the master routine. The master routine is executed, starting at the rung after the JSR instruction (rung 3). When the subroutine is being executed, all data in the master routine remains the same as it was on leaving unless the subroutine changes some of it. When the rung that contains the JSR instruction goes false, all local outputs in the subroutine are held in their last state.</p><p>Subroutines are not in the master or main routine but are created as a separate routine and given a unique name.</p><h4 id="af697ee2-c148-42b8-a210-47eb9896d121" data-toc-id="af697ee2-c148-42b8-a210-47eb9896d121" collapsed="false" seolevelmigrated="true">Jump to Subroutine Instruction</h4><p>If rung 2 of the master routine is true, the JSR instruction jumps to the named subroutine. Rung 3 in the subroutine returns program execution to the master routine, which resumes at the rung after the JSR instruction (rung 3). Data in the master routine remains unchanged unless altered by the subroutine. When the JSR instruction's rung goes false, subroutine local outputs hold their last state.</p><h4 id="b901361f-785e-4693-a4cc-1a3fdf5c7824" data-toc-id="b901361f-785e-4693-a4cc-1a3fdf5c7824" collapsed="false" seolevelmigrated="true">Subroutine Instruction</h4><p>First rung of the subroutine must contain the subroutine (SBR) instruction that assigns its local tags to the value of the passed input parameters</p><h4 id="425d3d14-eb39-4c10-b616-980ddadb390d" data-toc-id="425d3d14-eb39-4c10-b616-980ddadb390d" collapsed="false" seolevelmigrated="true">Return Instruction</h4><p>Last rung of the subroutine often has a return (RET) instruction, returns execution back to the main program and passes the value of tag Result as its first return parameter</p><h4 id="dbc94ae3-6c0c-4c6c-aa25-23135eb8584d" data-toc-id="dbc94ae3-6c0c-4c6c-aa25-23135eb8584d" collapsed="false" seolevelmigrated="true">Subroutine Instructions Example</h4><p>For this example, assume the value of Input1 (tag in main routine) is 25 and the value of Input2 (tag in main routine) is 15.</p><ul><li><p>The JSR instruction in Rung 1 of the main program calls the subroutine Routine A and passes the value of its two input parameters (Input1 and Input2).</p></li><li><p>The first rung of the subroutine (Rung 1) must contain the subroutine (SBR) instruction that assigns its local tags (valueA and valueB) to the value of the passed input parameters. Therefore, valueA = 25 (value of Input1) and valueB = 15 (value of Input2).</p></li><li><p>Rung 2 stores 15 in the tag Result (calculates 25-15).</p></li><li><p>If instruction A is true, then rung 3, which has a return (RET) instruction, returns execution back to the main program and passes the value of tag Result as its first return parameter RET_Par.</p></li><li><p>The returned parameter is assigned to the tag Output in the main routine and then the next rung of the main routine is executed. The value assigned to Output is 15.</p></li></ul><p>If instruction A is false, then rung 3 of the subroutine is not executed. Therefore, rung 4 is executed, which stores 40 in the tag Result (calculates 25+ 15). If instruction B in rung 5 is true, then the subroutine passes 40 back to the main routine. In this case, the value assigned to output is 40.</p><p>If both instruction A and instruction B are false, then rung 6 is executed; this passes 50 back to the main routine. In this case, the value assigned to output is 50.</p><h5 id="7ac89647-c460-4364-b1b6-d87d433299f8" data-toc-id="7ac89647-c460-4364-b1b6-d87d433299f8" collapsed="false" seolevelmigrated="true">Restrictions</h5><p>There are no restrictions on the number of input or output parameters that subroutine instructions can configure. However, you must follow the following points when using subroutines.</p><ul><li><p>The data type for the input parameters passed to a subroutine must match the data type for the corresponding tag in the subroutine.</p></li><li><p>The data type for the return parameters passed to the main routine must match the data type for the corresponding tag in the main routine.</p></li><li><p>The order of the parameters (top to bottom) in the instruction determines which value is assigned to it.</p></li></ul><h4 id="ce5527e7-aec5-4245-a33b-dc86b5a4a8e5" data-toc-id="ce5527e7-aec5-4245-a33b-dc86b5a4a8e5" collapsed="false" seolevelmigrated="true">Nested Subroutines</h4><p>Nested subroutines allow you to direct program flow from the main routine to a subroutine and then to another subroutine (nested subroutine). Nested subroutines can make complex programming easier.</p><ul><li><p>The program execution is directed to a subroutine if rung 2 of the main program is true.</p></li><li><p>The subroutine directs program execution to a nested subroutine if rung 3 of the subroutine is true.</p></li><li><p>Rung 3 of the nested subroutine directs program execution back to rung 4 of the subroutine.</p></li><li><p>Rung 4 of the subroutine directs program execution back to Rung 3 of the main routine.</p></li></ul><h4 id="bb5c0566-ecff-4523-ae57-a3f917af901a" data-toc-id="bb5c0566-ecff-4523-ae57-a3f917af901a" collapsed="false" seolevelmigrated="true">Repetitive Calculation Example</h4><p>The analog inputs TT101 and TT102 are not scaled by the AI module. The scaling is done in a subroutine called Convert, rather than in the main routine because this is a repetitive block of logic.</p><p>The AI module has a 16-bit ADC that produces a signed integer output between -32,768 and 32,767 from a 0 mA to 21 mA input signal. A 4 mA signal produces a -20,285 output, while a 20 mA signal produces a 29,646 output. The engineering range for the temperature transmitters is-50°Ctoto150°C.</p><p>IftherawADCvaluefromTT101is1543,itstemperatureinengineeringunitsis.</p><p>If the raw ADC value from TT101 is 1543, its temperature in engineering units is37.4°C.IftherawADCvaluefromTT102is8250,itstemperatureinengineeringunitsis. If the raw ADC value from TT102 is 8250, its temperature in engineering units is64.3°C$$.

    • The JSR instruction in rung 1 of the main program calls the subroutine Convert and passes the value in address <1:50>, which is 1543 for its first input parameter IN_Par.

    • The first rung of the subroutine (rung 1) must contain the SBR instruction that assigns its local tag InRaw to the value of the passed input parameter IN_Par. Therefore, InRaw has a value of 1543.

    • Rung 2 of the subroutine uses the I/O formula to calculate the temperature in engineering units and assigns it to the local tag OutScale. Therefore, OutScale has a value of 37.4.

    • Rung 3 of the subroutine has the RET instruction that returns execution back to the main program and passes the value of tag OutScale as its first return parameter RET_Par.

    • The returned parameter is assigned to the tag TT101 in the main routine and then the next rung of the