NJ/NX-series Instructions Reference Manual EN 201811 W502I-E3-24

W502-E1-24 0718, NX, NJ, Manual, W502I-E3-24

OMRON

Instructions Reference Manual - Omron

Keep this manual in a safe place where it will be available for reference during operation. This manual is intended for the following personnel, who must also have knowledge of electrical sys- tems (an electrical engineer or the equivalent).

PDF preview unavailable. Download the PDF instead.

NJNX-series Instructions Reference Manual
Machine Automation Controller
NJ/NX-series
Instructions Reference Manual
NX701-1 NX102-1 NX102-90 NX1P2-1 NX1P2-90 NJ501- NJ301-1 NJ101-10 NJ101-90
W502I-E3-24

NOTE
All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, mechanical, electronic, photocopying, recording, or otherwise, without the prior written permission of OMRON. No patent liability is assumed with respect to the use of the information contained herein. Moreover, because OMRON is constantly striving to improve its high-quality products, the information contained in this manual is subject to change without notice. Every precaution has been taken in the preparation of this manual. Nevertheless, OMRON assumes no responsibility for errors or omissions. Neither is any liability assumed for damages resulting from the use of the information contained in this publication.
Trademarks
· Sysmac and SYSMAC are trademarks or registered trademarks of OMRON Corporation in Japan and other countries for OMRON factory automation products.
· Microsoft, Windows, Windows Vista, Excel, and Visual Basic are either registered trademarks or trademarks of Microsoft Corporation in the United States and other countries.
· EtherCAT® is registered trademark and patented technology, licensed by Beckhoff Automation GmbH, Germany. · ODVA, CIP, CompoNet, DeviceNet, and EtherNet/IP are trademarks of ODVA.
· The SD and SDHC logos are trademarks of SD-3C, LLC.
Other company names and product names in this document are the trademarks or registered trademarks of their respective companies.
Copyrights
Microsoft product screen shots reprinted with permission from Microsoft Corporation.

Introduction

Introduction

Thank you for purchasing an NJ/NX-series CPU Unit. This manual contains information that is necessary to use the NJ/NX-series CPU Unit. Please read this manual and make sure you understand the functionality and performance of the NJ/NX-series CPU Unit before you attempt to use it in a control system. Keep this manual in a safe place where it will be available for reference during operation.

Intended Audience
This manual is intended for the following personnel, who must also have knowledge of electrical systems (an electrical engineer or the equivalent). · Personnel in charge of introducing FA systems. · Personnel in charge of designing FA systems. · Personnel in charge of installing and maintaining FA systems. · Personnel in charge of managing FA systems and facilities.
For programming, this manual is intended for personnel who understand the programming language specifications in international standard IEC 61131-3 or Japanese standard JIS B 3503.

Applicable Products
This manual covers the following products. · NX-series CPU Units
· NX701-17 · NX701-16 · NX102-12 · NX102-11 · NX102-10 · NX102-90 · NX1P2-11 · NX1P2-111 · NX1P2-10 · NX1P2-101 · NX1P2-90 · NX1P2-901
· NJ-series CPU Units · NJ501-5 · NJ501-4 · NJ501-3 · NJ301-12 · NJ301-11 · NJ101-10 · NJ101-90

Part of the specifications and restrictions for the CPU Units are given in other manuals. Refer to Relevant Manuals on page 2 and Related Manuals on page 28.

NJ/NX-series Instructions Reference Manual (W502)

1

Relevant Manuals

Relevant Manuals

The following table provides the relevant manuals for the NJ/NX-series CPU Units. Read all of the manuals that are relevant to your system configuration and application before you use the NJ/NX-series CPU Unit.
Most operations are performed from the Sysmac Studio Automation Software. Refer to the Sysmac Studio Version 1 Operation Manual (Cat. No. W504) for information on the Sysmac Studio.

Basic information

Manual

Purpose of use

NJ/NX-series Troubleshooting Manual NJ/NY-series NC Integrated Controller User's Manual NJ-series NJ Robotics CPU Unit User's Manual NJ-series SECS/GEM CPU Units User's Manual NJ/NX-series Database Connection CPU Units User's Manual NX-series CPU Unit FINS Function User's Manual NJ/NX-series CPU Unit OPC UA User's Manual NJ/NX-series CPU Unit Built-in EtherNet/IP Port User's Manual NJ/NX-series CPU Unit Built-in EtherCAT Port User's Manual NJ/NX-series Motion Control Instructions Reference Manual NJ/NX-series CPU Unit Motion Control User's Manual NJ/NX-series Instructions Reference Manual NX-series NX1P2 CPU Unit Built-in I/O and Option Board User's Manual NJ/NX-series CPU Unit Software User's Manual NJ-series CPU Unit Hardware User's Manual NX-series NX1P2 CPU Unit Hardware User's Manual
NX-series NX102 CPU Unit
Hardware User's Manual NX-series CPU Unit Hardware User's Manual

Introduction to NX701 CPU Units



Introduction to NX102 CPU Units



Introduction to NX1P2 CPU Units



Introduction to NJ-series Controllers



Setting devices and hardware



Using motion control



Using EtherCAT



Using EtherNet/IP



Software settings



Using motion control



Using EtherCAT



Using EtherNet/IP



Using OPC UA



Using FINS



Using the database connection service



Using the GEM Services



Using robot control



Using numerical control



Using the NX1P2 CPU Unit functions



2

NJ/NX-series Instructions Reference Manual (W502)

Basic information

Manual

Relevant Manuals

Purpose of use

NJ/NX-series Troubleshooting Manual NJ/NY-series NC Integrated Controller User's Manual NJ-series NJ Robotics CPU Unit User's Manual NJ-series SECS/GEM CPU Units User's Manual NJ/NX-series Database Connection CPU Units User's Manual NX-series CPU Unit FINS Function User's Manual NJ/NX-series CPU Unit OPC UA User's Manual NJ/NX-series CPU Unit Built-in EtherNet/IP Port User's Manual NJ/NX-series CPU Unit Built-in EtherCAT Port User's Manual NJ/NX-series Motion Control Instructions Reference Manual NJ/NX-series CPU Unit Motion Control User's Manual NJ/NX-series Instructions Reference Manual NX-series NX1P2 CPU Unit Built-in I/O and Option Board User's Manual NJ/NX-series CPU Unit Software User's Manual NJ-series CPU Unit Hardware User's Manual NX-series NX1P2 CPU Unit Hardware User's Manual
NX-series NX102 CPU Unit
Hardware User's Manual NX-series CPU Unit Hardware User's Manual

Writing the user program





Using motion control



Using EtherCAT



Using EtherNet/IP



Using OPC UA



Using FINS



Using the database connection service



Using the GEM Services



Using robot control



Using numerical control



Programming error processing



Using the NX1P2 CPU Unit functions



Testing operation and debugging



Using motion control



Using EtherCAT



Using EtherNet/IP



Using OPC UA



Using FINS



Using the database connection service



Using the GEM Services



Using robot control



Using numerical control



Using the NX1P2 CPU Unit functions



Learning about error management and corrections *1



Maintenance

Using motion control Using EtherCAT



 

Using EtherNet/IP



*1 Refer to the NJ/NX-series Troubleshooting Manual (Cat. No. W503) for the error management concepts and the error items. However, refer to the manuals that are indicated with triangles() for details on errors corresponding to the products with the manuals that are indicated with triangles().

NJ/NX-series Instructions Reference Manual (W502)

3

Manual Structure
Manual Structure
Page Structure
The following page structure is used in this manual.

Ladder Diagram Instructions

Level-2 heading

2
Ladder Diagram Instructions

Level-2 heading
Level-1 section number
Gives the number of the section.

Instruction LD and LDN AND and ANDN OR and ORN Out and OutNot

Name
Load/ Load NOT
AND/ AND NOT
OR/ OR NOT
Output/ Output NOT

Page 2-14 2-16 2-18 2-20

Manual name

NJ-series Instructions Reference Manual (W502)

2-13

This page is for illustration only. It may not literally appear in this manual.

4

NJ/NX-series Instructions Reference Manual (W502)

Manual Structure

Level-3 heading
Manual name

2 Instruction Descriptions

OR and ORN

Ladder Diagram Instructions

OR and ORN

OR: ORN:

Takes the logical OR of the value of a BOOL variable and the execution condition.
Takes the logical OR of the inverse of the value of a BOOL variable and the execution condition.

Instruction

Name

FB/FUN

Graphic expression

ST expression

OR

OR

---

Variable

Variable

VVaarriiaabbllee

result:=vBool1 OR vBool2;
2

Upward differentiation

DDoowwnnwwaarrdd ddiiffffeerreennttiiaattiioonn

ORN

OR NOT ---

Variable

Variable
Upward differentiation

Variable
Downward differentiation

result:=vBool1 OR NOT vBool2;

Variables
None

Function

OR
The OR instruction takes the logical OR of the value of a specified BOOL variable and the execution condition and outputs it to the next instruction. Use the OR instruction for a NO bit connected in parallel with the previous instruction. Use the OR instruction to configure a logical OR between an NO bit and one of the following: a LD or LDN instruction connected directly to the bus bar, or the logic block starting with a LD or LDN instruction and ending with the instruction immediately before the OR instruction.

ORN

The ORN instruction takes the logical OR of the inverse of the value of a specified BOOL variable and the execution condition and outputs it to the next instruction. Use the ORN instruction for a NC bit connected in parallel with the previous instruction. Use the ORN instruction to configure a logical OR between an NC bit and one of the following: a LD or LDN instruction connected directly to the bus bar, or the logic block starting with a LD or LDN instruction and ending with the instruction immediately before the ORN instruction.
The following figure shows a programming example of the OR instruction. It takes the logical OR of variable A and variable B and outputs it to variable C.

LD instruction

A

C

B Out instruction

OR instruction

NJ-series Instructions Reference Manual (W502)

2-17

This page is for illustration only. It may not literally appear in this manual.

Level-1 heading Level-2 heading Level-3 heading
Give the current headings.
Level-1 section number
Gives the number of the section.

Special Information
Special information in this manual is classified as follows:
Precautions for Correct Use Precautions on what to do and what not to do to ensure proper operation and performance.
Additional Information Additional information to read as required. This information is provided to increase understanding or make operation easier.
Note References are provided to more detailed or related information.

Version Information Information on differences in specifications and functionality for CPU Units with different unit versions and for different versions of the Sysmac Studio are given.

NJ/NX-series Instructions Reference Manual (W502)

5

Manual Structure

6

NJ/NX-series Instructions Reference Manual (W502)

Sections in this Manual
1 Instruction Set 2 Instruction Descriptions A Appendices I Index

Sections in this Manual
1 2 A I

NJ/NX-series Instructions Reference Manual (W502)

7

Sections in this Manual

8

NJ/NX-series Instructions Reference Manual (W502)

CONTENTS

CONTENTS

Introduction............................................................................................................... 1 Relevant Manuals ..................................................................................................... 2 Manual Structure ...................................................................................................... 4 Sections in this Manual............................................................................................ 7 Terms and Conditions Agreement ........................................................................ 17 Safety Precautions ................................................................................................. 19 Precautions for Safe Use ....................................................................................... 20 Precautions for Correct Use .................................................................................. 21 Regulations and Standards ................................................................................... 22 Versions................................................................................................................... 24 Related Manuals ..................................................................................................... 28 Revision History ..................................................................................................... 31

Section 1

Instruction Set
Instruction Set ........................................................................................................... 1-2

Section 2

Instruction Descriptions
Using this Section ...................................................................................................... 2-3
Ladder Diagram Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-15
LD and LDN ............................................................................................................. 2-16 AND and ANDN ....................................................................................................... 2-18 OR and ORN ........................................................................................................... 2-20 Out and OutNot ....................................................................................................... 2-22
ST Statement Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-25
IF ............................................................................................................................. 2-26 CASE ....................................................................................................................... 2-30 WHILE ..................................................................................................................... 2-34 REPEAT .................................................................................................................. 2-36 EXIT ........................................................................................................................ 2-38 RETURN ................................................................................................................. 2-41 FOR ......................................................................................................................... 2-42
Sequence Input Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-43
R_TRIG (Up) and F_TRIG (Down) .......................................................................... 2-44 TestABit and TestABitN ........................................................................................... 2-47
Sequence Output Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-49
RS ........................................................................................................................... 2-50 SR ........................................................................................................................... 2-53 Set and Reset .......................................................................................................... 2-56 SetBits and ResetBits .............................................................................................. 2-59 SetABit and ResetABit ............................................................................................ 2-61

NJ/NX-series Instructions Reference Manual (W502)

9

CONTENTS

OutABit .................................................................................................................... 2-63
Sequence Control Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-65
End .......................................................................................................................... 2-66 RETURN ................................................................................................................. 2-67 MC and MCR ........................................................................................................... 2-68 JMP ......................................................................................................................... 2-80 FOR and NEXT ....................................................................................................... 2-82 BREAK .................................................................................................................... 2-89
Comparison Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-91
EQ (=) ...................................................................................................................... 2-92 NE (<>) .................................................................................................................... 2-94 LT (<), LE (<=), GT (>), and GE (>=) ...................................................................... 2-97 EQascii .................................................................................................................. 2-100 NEascii .................................................................................................................. 2-102 LTascii, LEascii, GTascii, and GEascii .................................................................. 2-104 Cmp ....................................................................................................................... 2-107 ZoneCmp ............................................................................................................... 2-109 TableCmp .............................................................................................................. 2-111 AryCmpEQ and AryCmpNE .................................................................................. 2-114 AryCmpLT, AryCmpLE, AryCmpGT, and AryCmpGE ........................................... 2-116 AryCmpEQV and AryCmpNEV ............................................................................. 2-119 AryCmpLTV, AryCmpLEV, AryCmpGTV, and AryCmpGEV ................................. 2-121
Timer Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-125
TON ....................................................................................................................... 2-126 TOF ....................................................................................................................... 2-132 TP .......................................................................................................................... 2-135 AccumulationTimer ................................................................................................ 2-138 Timer ..................................................................................................................... 2-141
Counter Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-145
CTD ....................................................................................................................... 2-146 CTD_** .................................................................................................................. 2-148 CTU ....................................................................................................................... 2-150 CTU_** .................................................................................................................. 2-152 CTUD .................................................................................................................... 2-155 CTUD_** ................................................................................................................ 2-159
Math Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-165
ADD (+) ................................................................................................................. 2-166 AddOU (+OU) ........................................................................................................ 2-170 SUB (-) .................................................................................................................. 2-174 SubOU (-OU) ......................................................................................................... 2-177 MUL (*) .................................................................................................................. 2-181 MulOU (*OU) ......................................................................................................... 2-185 DIV (/) .................................................................................................................... 2-189 MOD ...................................................................................................................... 2-192 ABS ....................................................................................................................... 2-194 RadToDeg and DegToRad .................................................................................... 2-196 SIN, COS, and TAN .............................................................................................. 2-198 ASIN, ACOS, and ATAN ....................................................................................... 2-201 SQRT .................................................................................................................... 2-204 LN and LOG .......................................................................................................... 2-206 EXP ....................................................................................................................... 2-209 EXPT (**) ............................................................................................................... 2-211 Inc and Dec ........................................................................................................... 2-217 Rand ...................................................................................................................... 2-219 AryAdd ................................................................................................................... 2-221 AryAddV ................................................................................................................ 2-223 ArySub ................................................................................................................... 2-225 ArySubV ................................................................................................................ 2-227

10

NJ/NX-series Instructions Reference Manual (W502)

CONTENTS

AryMean ................................................................................................................ 2-229 ArySD .................................................................................................................... 2-231 ModReal ................................................................................................................ 2-233 Fraction ................................................................................................................. 2-235 CheckReal ............................................................................................................. 2-237
BCD Conversion Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-241
**_BCD_TO_*** ..................................................................................................... 2-242 **_TO_BCD_*** ..................................................................................................... 2-245 BCD_TO_** ........................................................................................................... 2-247 BCDsToBin ............................................................................................................ 2-250 BinToBCDs_** ....................................................................................................... 2-253 AryToBCD ............................................................................................................. 2-256 AryToBin ................................................................................................................ 2-258
Data Type Conversion Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-261
**_TO_*** (Integer-to-Integer Conversion Group) ................................................. 2-262 **_TO_*** (Integer-to-Bit String Conversion Group) .............................................. 2-265 **_TO_*** (Integer-to-Real Number Conversion Group) ....................................... 2-268 **_TO_*** (Bit String-to-Integer Conversion Group) .............................................. 2-270 **_TO_*** (Bit String-to-Bit String Conversion Group) .......................................... 2-272 **_TO_*** (Bit String-to-Real Number Conversion Group) .................................... 2-274 **_TO_*** (Real Number-to-Integer Conversion Group) ....................................... 2-276 **_TO_*** (Real Number-to-Bit String Conversion Group) .................................... 2-279 **_TO_*** (Real Number-to-Real Number Conversion Group) ............................. 2-281 **_TO_STRING (Integer-to-Text String Conversion Group) ................................. 2-283 **_TO_STRING (Bit String-to-Text String Conversion Group) .............................. 2-285 **_TO_STRING (Real Number-to-Text String Conversion Group) ....................... 2-287 RealToFormatString .............................................................................................. 2-289 LrealToFormatString ............................................................................................. 2-294 STRING_TO_** (Text String-to-Integer Conversion Group) ................................. 2-299 STRING_TO_** (Text String-to-Bit String Conversion Group) .............................. 2-301 STRING_TO_** (Text String-to-Real Number Conversion Group) ....................... 2-303 TO_** (Integer Conversion Group) ........................................................................ 2-306 TO_** (Bit String Conversion Group) .................................................................... 2-308 TO_** (Real Number Conversion Group) .............................................................. 2-310 EnumToNum ......................................................................................................... 2-312 NumToEnum ......................................................................................................... 2-314 TRUNC, Round, and RoundUp ............................................................................. 2-316
Bit String Processing Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-319
AND (&), OR, and XOR ......................................................................................... 2-320 XORN .................................................................................................................... 2-323 NOT ....................................................................................................................... 2-325 AryAnd, AryOr, AryXor, and AryXorN .................................................................... 2-327
Selection Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-331
SEL ........................................................................................................................ 2-332 MUX ...................................................................................................................... 2-334 LIMIT ..................................................................................................................... 2-337 Band ...................................................................................................................... 2-339 Zone ...................................................................................................................... 2-342 MAX and MIN ........................................................................................................ 2-345 AryMax and AryMin ............................................................................................... 2-347 ArySearch .............................................................................................................. 2-350
Data Movement Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-353
MOVE .................................................................................................................... 2-354 MoveBit ................................................................................................................. 2-357 MoveDigit .............................................................................................................. 2-359 TransBits ............................................................................................................... 2-361 MemCopy .............................................................................................................. 2-363 SetBlock ................................................................................................................ 2-365

NJ/NX-series Instructions Reference Manual (W502)

11

CONTENTS

Exchange .............................................................................................................. 2-367 AryExchange ......................................................................................................... 2-369 AryMove ................................................................................................................ 2-371 Clear ...................................................................................................................... 2-373 Copy**ToNum (Bit String to Signed Integer) ......................................................... 2-375 Copy**To*** (Bit String to Real Number) ............................................................... 2-377 CopyNumTo** (Signed Integer to Bit String) ......................................................... 2-379 CopyNumTo** (Signed Integer to Real Number) .................................................. 2-381 Copy**To*** (Real Number to Bit String) ............................................................... 2-383 Copy**ToNum (Real Number to Signed Integer) .................................................. 2-385
Shift Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-387
AryShiftReg ........................................................................................................... 2-388 AryShiftRegLR ....................................................................................................... 2-390 ArySHL and ArySHR ............................................................................................. 2-393 SHL and SHR ........................................................................................................ 2-396 NSHLC and NSHRC ............................................................................................. 2-398 ROL and ROR ....................................................................................................... 2-400
Conversion Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-403
Swap ..................................................................................................................... 2-404 Neg ........................................................................................................................ 2-405 Decoder ................................................................................................................. 2-407 Encoder ................................................................................................................. 2-410 BitCnt ..................................................................................................................... 2-412 ColmToLine_** ...................................................................................................... 2-413 LineToColm ........................................................................................................... 2-415 Gray ....................................................................................................................... 2-417 UTF8ToSJIS .......................................................................................................... 2-422 SJISToUTF8 .......................................................................................................... 2-424 PWLApprox and PWLApproxNoLineChk .............................................................. 2-426 PWLLineChk ......................................................................................................... 2-432 MovingAverage ..................................................................................................... 2-435 DispartReal ............................................................................................................ 2-441 UniteReal ............................................................................................................... 2-444 NumToDecString and NumToHexString ............................................................... 2-446 HexStringToNum_** .............................................................................................. 2-449 FixNumToString .................................................................................................... 2-451 StringToFixNum .................................................................................................... 2-453 DtToString ............................................................................................................. 2-456 DateToString ......................................................................................................... 2-458 TodToString ........................................................................................................... 2-459 GrayToBin_** and BinToGray_** .......................................................................... 2-461 StringToAry ........................................................................................................... 2-463 AryToString ........................................................................................................... 2-465 DispartDigit ............................................................................................................ 2-467 UniteDigit_** .......................................................................................................... 2-469 Dispart8Bit ............................................................................................................. 2-471 Unite8Bit_** ........................................................................................................... 2-473 ToAryByte .............................................................................................................. 2-475 AryByteTo .............................................................................................................. 2-480 SizeOfAry .............................................................................................................. 2-485 PackWord .............................................................................................................. 2-487 PackDword ............................................................................................................ 2-489 LOWER_BOUND / UPPER_BOUND .................................................................... 2-491
Stack and Table Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-497
StackPush ............................................................................................................. 2-498 StackFIFO and StackLIFO .................................................................................... 2-507 StackIns ................................................................................................................. 2-510 StackDel ................................................................................................................ 2-512 RecSearch ............................................................................................................. 2-514

12

NJ/NX-series Instructions Reference Manual (W502)

CONTENTS

RecRangeSearch .................................................................................................. 2-519 RecSort ................................................................................................................. 2-524 RecNum ................................................................................................................ 2-530 RecMax and RecMin ............................................................................................. 2-532
FCS Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-537
StringSum .............................................................................................................. 2-538 StringLRC .............................................................................................................. 2-540 StringCRCCCITT ................................................................................................... 2-542 StringCRC16 ......................................................................................................... 2-544 AryLRC_** ............................................................................................................. 2-546 AryCRCCCITT ....................................................................................................... 2-548 AryCRC16 ............................................................................................................. 2-550
Text String Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-553
CONCAT ............................................................................................................... 2-554 LEFT and RIGHT .................................................................................................. 2-556 MID ........................................................................................................................ 2-558 FIND ...................................................................................................................... 2-560 LEN ....................................................................................................................... 2-562 REPLACE .............................................................................................................. 2-563 DELETE ................................................................................................................ 2-565 INSERT ................................................................................................................. 2-567 GetByteLen ........................................................................................................... 2-569 ClearString ............................................................................................................ 2-571 ToUCase and ToLCase ......................................................................................... 2-573 TrimL and TrimR ................................................................................................... 2-575 AddDelimiter .......................................................................................................... 2-577 SubDelimiter .......................................................................................................... 2-588
Time and Time of Day Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-599
ADD_TIME ............................................................................................................ 2-600 ADD_TOD_TIME ................................................................................................... 2-602 ADD_DT_TIME ..................................................................................................... 2-604 SUB_TIME ............................................................................................................ 2-606 SUB_TOD_TIME ................................................................................................... 2-608 SUB_TOD_TOD .................................................................................................... 2-610 SUB_DATE_DATE ................................................................................................ 2-611 SUB_DT_DT ......................................................................................................... 2-612 SUB_DT_TIME ...................................................................................................... 2-614 MULTIME .............................................................................................................. 2-616 DIVTIME ................................................................................................................ 2-618 CONCAT_DATE_TOD .......................................................................................... 2-620 DT_TO_TOD ......................................................................................................... 2-622 DT_TO_DATE ....................................................................................................... 2-624 SetTime ................................................................................................................. 2-626 GetTime ................................................................................................................. 2-628 DtToSec ................................................................................................................ 2-630 DateToSec ............................................................................................................ 2-632 TodToSec .............................................................................................................. 2-633 SecToDt ................................................................................................................ 2-634 SecToDate ............................................................................................................ 2-636 SecToTod .............................................................................................................. 2-638 TimeToNanoSec ................................................................................................... 2-640 TimeToSec ............................................................................................................ 2-641 NanoSecToTime ................................................................................................... 2-642 SecToTime ............................................................................................................ 2-643 ChkLeapYear ........................................................................................................ 2-645 GetDaysOfMonth ................................................................................................... 2-646 DaysToMonth ........................................................................................................ 2-648 GetDayOfWeek ..................................................................................................... 2-650 GetWeekOfYear .................................................................................................... 2-652

NJ/NX-series Instructions Reference Manual (W502)

13

CONTENTS

DtToDateStruct ...................................................................................................... 2-654 DateStructToDt ...................................................................................................... 2-656 TruncTime ............................................................................................................. 2-658 TruncDt .................................................................................................................. 2-662 TruncTod ............................................................................................................... 2-666
Analog Control Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-671
PIDAT .................................................................................................................... 2-672 PIDAT_HeatCool ................................................................................................... 2-697 TimeProportionalOut ............................................................................................. 2-735 LimitAlarm_** ......................................................................................................... 2-752 LimitAlarmDv_** .................................................................................................... 2-756 LimitAlarmDvStbySeq_** ....................................................................................... 2-761 ScaleTrans ............................................................................................................ 2-776 AC_StepProgram .................................................................................................. 2-779
System Control Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-805
TraceSamp ............................................................................................................ 2-806 TraceTrig ............................................................................................................... 2-809 GetTraceStatus ..................................................................................................... 2-812 SetAlarm ................................................................................................................ 2-816 ResetAlarm ............................................................................................................ 2-821 GetAlarm ............................................................................................................... 2-823 ResetPLCError ...................................................................................................... 2-825 GetPLCError .......................................................................................................... 2-828 ResetCJBError ...................................................................................................... 2-830 GetCJBError .......................................................................................................... 2-832 GetEIPError ........................................................................................................... 2-834 ResetMCError ....................................................................................................... 2-836 GetMCError ........................................................................................................... 2-841 ResetECError ........................................................................................................ 2-843 GetECError ............................................................................................................ 2-845 ResetNXBError ...................................................................................................... 2-848 GetNXBError ......................................................................................................... 2-850 GetNXUnitError ..................................................................................................... 2-852 SetInfo ................................................................................................................... 2-860 ResetUnit ............................................................................................................... 2-862 GetNTPStatus ....................................................................................................... 2-866 RestartNXUnit ....................................................................................................... 2-868 NX_ChangeWriteMode ......................................................................................... 2-874 NX_SaveParam ..................................................................................................... 2-879 NX_ReadTotalPowerOnTime ................................................................................ 2-885 PLC_ReadTotalPowerOnTime .............................................................................. 2-893
Program Control Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-897
PrgStart ................................................................................................................. 2-898 PrgStop ................................................................................................................. 2-907 PrgStatus ............................................................................................................... 2-927
EtherCAT Communications Instructions . . . . . . . . . . . . . . . . . . . . . . . . .2-933
EC_CoESDOWrite ................................................................................................ 2-934 EC_CoESDORead ................................................................................................ 2-937 EC_StartMon ......................................................................................................... 2-942 EC_StopMon ......................................................................................................... 2-948 EC_SaveMon ........................................................................................................ 2-950 EC_CopyMon ........................................................................................................ 2-952 EC_DisconnectSlave ............................................................................................. 2-954 EC_ConnectSlave ................................................................................................. 2-961 EC_ChangeEnableSetting .................................................................................... 2-963 NX_WriteObj ......................................................................................................... 2-980 NX_ReadObj ......................................................................................................... 2-995
IO-Link Communications Instruction . . . . . . . . . . . . . . . . . . . . . . . . . . .2-1005

14

NJ/NX-series Instructions Reference Manual (W502)

CONTENTS

IOL_ReadObj ...................................................................................................... 2-1006 IOL_WriteObj ....................................................................................................... 2-1015
EtherNet/IP Communications Instructions . . . . . . . . . . . . . . . . . . . . . . 2-1025
CIPOpen .............................................................................................................. 2-1026 CIPOpenWithDataSize ........................................................................................ 2-1035 CIPRead .............................................................................................................. 2-1039 CIPWrite .............................................................................................................. 2-1045 CIPSend .............................................................................................................. 2-1051 CIPClose ............................................................................................................. 2-1056 CIPUCMMRead ................................................................................................... 2-1059 CIPUCMMWrite ................................................................................................... 2-1064 CIPUCMMSend ................................................................................................... 2-1071 SktUDPCreate ..................................................................................................... 2-1081 SktUDPRcv ......................................................................................................... 2-1089 SktUDPSend ....................................................................................................... 2-1092 SktTCPAccept ..................................................................................................... 2-1095 SktTCPConnect ................................................................................................... 2-1098 SktTCPRcv .......................................................................................................... 2-1107 SktTCPSend ........................................................................................................ 2-1110 SktGetTCPStatus ................................................................................................ 2-1113 SktClose .............................................................................................................. 2-1116 SktClearBuf ......................................................................................................... 2-1119 SktSetOption ....................................................................................................... 2-1122 ModbusTCPCmd ................................................................................................. 2-1127 ModbusTCPRead ................................................................................................ 2-1135 ModbusTCPWrite ................................................................................................ 2-1143 ChangeIPAdr ....................................................................................................... 2-1151 ChangeFTPAccount ............................................................................................ 2-1159 ChangeNTPServerAdr ........................................................................................ 2-1163 FTPGetFileList .................................................................................................... 2-1167 FTPGetFile .......................................................................................................... 2-1184 FTPPutFile .......................................................................................................... 2-1193 FTPRemoveFile .................................................................................................. 2-1204 FTPRemoveDir .................................................................................................... 2-1214
Serial Communications Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1219
ExecPMCR .......................................................................................................... 2-1220 SerialSend ........................................................................................................... 2-1233 SerialRcv and SerialRcvNoClear ........................................................................ 2-1244 SendCmd ............................................................................................................ 2-1259 NX_SerialSend .................................................................................................... 2-1272 NX_SerialRcv ...................................................................................................... 2-1285 NX_ModbusRtuCmd ........................................................................................... 2-1299 NX_ModbusRtuRead .......................................................................................... 2-1310 NX_ModbusRtuWrite ........................................................................................... 2-1322 NX_SerialSigCtl ................................................................................................... 2-1334 NX_SerialSigRead .............................................................................................. 2-1343 NX_SerialStatusRead ......................................................................................... 2-1348 NX_SerialBufClear .............................................................................................. 2-1353 NX_SerialStartMon .............................................................................................. 2-1363 NX_SerialStopMon .............................................................................................. 2-1368
SD Memory Card Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1373
FileWriteVar ......................................................................................................... 2-1374 FileReadVar ........................................................................................................ 2-1379 FileOpen .............................................................................................................. 2-1384 FileClose ............................................................................................................. 2-1388 FileSeek .............................................................................................................. 2-1391 FileRead .............................................................................................................. 2-1395 FileWrite .............................................................................................................. 2-1403 FileGets ............................................................................................................... 2-1411

NJ/NX-series Instructions Reference Manual (W502)

15

CONTENTS
FilePuts ............................................................................................................... 2-1419 FileCopy .............................................................................................................. 2-1428 FileRemove ......................................................................................................... 2-1437 FileRename ......................................................................................................... 2-1442 DirCreate ............................................................................................................. 2-1447 DirRemove .......................................................................................................... 2-1450 BackupToMemoryCard ....................................................................................... 2-1453
Time Stamp Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-1469
NX_DOutTimeStamp ........................................................................................... 2-1470 NX_AryDOutTimeStamp ..................................................................................... 2-1476
Other Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-1485
ReadNbit_** ......................................................................................................... 2-1486 WriteNbit_** ......................................................................................................... 2-1488 ChkRange ........................................................................................................... 2-1490 GetMyTaskStatus ................................................................................................ 2-1492 GetMyTaskInterval .............................................................................................. 2-1495 Task_IsActive ...................................................................................................... 2-1498 Lock and Unlock .................................................................................................. 2-1500 ActEventTask ...................................................................................................... 2-1507 Get**Clk ............................................................................................................... 2-1513 Get**Cnt .............................................................................................................. 2-1514
Appendices
A-1 Error Codes That You Can Check with ErrorID ....................................................................A-2 A-2 Error Codes ............................................................................................................................A-22 A-3 Instructions You Cannot Use in Event Tasks .....................................................................A-23 A-4 Instructions Related to NX Message Communications Errors..........................................A-25 A-5 SDO Abort Codes ..................................................................................................................A-26 A-6 Version Information...............................................................................................................A-27
Index

16

NJ/NX-series Instructions Reference Manual (W502)

Terms and Conditions Agreement
Terms and Conditions Agreement
Warranty, Limitations of Liability
Warranties
 Exclusive Warranty
Omron's exclusive warranty is that the Products will be free from defects in materials and workmanship for a period of twelve months from the date of sale by Omron (or such other period expressed in writing by Omron). Omron disclaims all other warranties, express or implied.
 Limitations
OMRON MAKES NO WARRANTY OR REPRESENTATION, EXPRESS OR IMPLIED, ABOUT NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OF THE PRODUCTS. BUYER ACKNOWLEDGES THAT IT ALONE HAS DETERMINED THAT THE PRODUCTS WILL SUITABLY MEET THE REQUIREMENTS OF THEIR INTENDED USE. Omron further disclaims all warranties and responsibility of any type for claims or expenses based on infringement by the Products or otherwise of any intellectual property right.
 Buyer Remedy
Omron's sole obligation hereunder shall be, at Omron's election, to (i) replace (in the form originally shipped with Buyer responsible for labor charges for removal or replacement thereof) the non-complying Product, (ii) repair the non-complying Product, or (iii) repay or credit Buyer an amount equal to the purchase price of the non-complying Product; provided that in no event shall Omron be responsible for warranty, repair, indemnity or any other claims or expenses regarding the Products unless Omron's analysis confirms that the Products were properly handled, stored, installed and maintained and not subject to contamination, abuse, misuse or inappropriate modification. Return of any Products by Buyer must be approved in writing by Omron before shipment. Omron Companies shall not be liable for the suitability or unsuitability or the results from the use of Products in combination with any electrical or electronic components, circuits, system assemblies or any other materials or substances or environments. Any advice, recommendations or information given orally or in writing, are not to be construed as an amendment or addition to the above warranty.
See http://www.omron.com/global/ or contact your Omron representative for published information.
Limitation on Liability; Etc
OMRON COMPANIES SHALL NOT BE LIABLE FOR SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, LOSS OF PROFITS OR PRODUCTION OR COMMERCIAL LOSS IN ANY WAY CONNECTED WITH THE PRODUCTS, WHETHER SUCH CLAIM IS BASED IN CONTRACT, WARRANTY, NEGLIGENCE OR STRICT LIABILITY. Further, in no event shall liability of Omron Companies exceed the individual price of the Product on which liability is asserted.

NJ/NX-series Instructions Reference Manual (W502)

17

Terms and Conditions Agreement
Application Considerations
Suitability of Use
Omron Companies shall not be responsible for conformity with any standards, codes or regulations which apply to the combination of the Product in the Buyer's application or use of the Product. At Buyer's request, Omron will provide applicable third party certification documents identifying ratings and limitations of use which apply to the Product. This information by itself is not sufficient for a complete determination of the suitability of the Product in combination with the end product, machine, system, or other application or use. Buyer shall be solely responsible for determining appropriateness of the particular Product with respect to Buyer's application, product or system. Buyer shall take application responsibility in all cases. NEVER USE THE PRODUCT FOR AN APPLICATION INVOLVING SERIOUS RISK TO LIFE OR PROPERTY OR IN LARGE QUANTITIES WITHOUT ENSURING THAT THE SYSTEM AS A WHOLE HAS BEEN DESIGNED TO ADDRESS THE RISKS, AND THAT THE OMRON PRODUCT(S) IS PROPERLY RATED AND INSTALLED FOR THE INTENDED USE WITHIN THE OVERALL EQUIPMENT OR SYSTEM.
Programmable Products
Omron Companies shall not be responsible for the user's programming of a programmable Product, or any consequence thereof.
Disclaimers
Performance Data
Data presented in Omron Company websites, catalogs and other materials is provided as a guide for the user in determining suitability and does not constitute a warranty. It may represent the result of Omron's test conditions, and the user must correlate it to actual application requirements. Actual performance is subject to the Omron's Warranty and Limitations of Liability.
Change in Specifications
Product specifications and accessories may be changed at any time based on improvements and other reasons. It is our practice to change part numbers when published ratings or features are changed, or when significant construction changes are made. However, some specifications of the Product may be changed without any notice. When in doubt, special part numbers may be assigned to fix or establish key specifications for your application. Please consult with your Omron's representative at any time to confirm actual specifications of purchased Product.
Errors and Omissions
Information presented by Omron Companies has been checked and is believed to be accurate; however, no responsibility is assumed for clerical, typographical or proofreading errors or omissions.

18

NJ/NX-series Instructions Reference Manual (W502)

Safety Precautions
Safety Precautions
Refer to the following manuals for safety precautions. · NX-series CPU Unit Hardware User's Manual (Cat. No. W535) · NX-series NX102 CPU Unit Hardware User's Manual (Cat. No. W593) · NX-series NX1P2 CPU Unit Hardware User's Manual (Cat. No. W578) · NJ-series CPU Unit Hardware User's Manual (Cat No. W500)

NJ/NX-series Instructions Reference Manual (W502)

19

Precautions for Safe Use
Precautions for Safe Use
Refer to the following manuals for precautions for safe use. · NX-series CPU Unit Hardware User's Manual (Cat. No. W535) · NX-series NX102 CPU Unit Hardware User's Manual (Cat. No. W593) · NX-series NX1P2 CPU Unit Hardware User's Manual (Cat. No. W578) · NJ-series CPU Unit Hardware User's Manual (Cat No. W500)

20

NJ/NX-series Instructions Reference Manual (W502)

Precautions for Correct Use
Precautions for Correct Use
Refer to the following manuals for precautions for correct use. · NX-series CPU Unit Hardware User's Manual (Cat. No. W535) · NX-series NX102 CPU Unit Hardware User's Manual (Cat. No. W593) · NX-series NX1P2 CPU Unit Hardware User's Manual (Cat. No. W578) · NJ-series CPU Unit Hardware User's Manual (Cat No. W500)

NJ/NX-series Instructions Reference Manual (W502)

21

Regulations and Standards
Regulations and Standards
Conformance to EU Directives
Applicable Directives
· EMC Directives · Low Voltage Directive
Concepts
 EMC Directive
OMRON devices that comply with EU Directives also conform to the related EMC standards so that they can be more easily built into other devices or the overall machine. The actual products have been checked for conformity to EMC standards.* Whether the products conform to the standards in the system used by the customer, however, must be checked by the customer. EMC-related performance of the OMRON devices that comply with EU Directives will vary depending on the configuration, wiring, and other conditions of the equipment or control panel on which the OMRON devices are installed. The customer must, therefore, perform the final check to confirm that devices and the overall machine conform to EMC standards. * Applicable EMC (Electromagnetic Compatibility) standards are as follows: EMS (Electromagnetic Susceptibility): EN 61131-2 EMI (Electromagnetic Interference): EN 61131-2 (Radiated emission: 10-m regulations)
 Low Voltage Directive
Always ensure that devices operating at voltages of 50 to 1,000 VAC and 75 to 1,500 VDC meet the required safety standards. The applicable directive is EN61010-2-201.
 Conformance to EU Directives
The NJ/NX-series Controllers comply with EU Directives. To ensure that the machine or device in which the NJ/NX-series Controller is used complies with EU Directives, the Controller must be installed as follows: · The NJ/NX-series Controller must be installed within a control panel. · You must use the power supply in SELV specifications for the DC power supplies connected to
DC Power Supply Units and I/O Units. · NJ/NX-series Controllers that comply with EU Directives also conform to the Common Emission
Standard (EN 61000-6-4). Radiated emission characteristics (10-m regulations) may vary depending on the configuration of the control panel used, other devices connected to the control panel, wiring, and other conditions. You must therefore confirm that the overall machine or equipment complies with EU Directives.

22

NJ/NX-series Instructions Reference Manual (W502)

Regulations and Standards
Conformance to KC Certification
Observe the following precaution if you use NX-series Units in Korea.

Class A Device (Broadcasting Communications Device for Office Use)
This device obtained EMC registration for office use (Class A), and it is intended to be used in places other than homes.
Sellers and/or users need to take note of this.

Conformance to Shipbuilding Standards
The NJ/NX-series Controllers comply with the following shipbuilding standards. Applicability to the shipbuilding standards is based on certain usage conditions. It may not be possible to use the product in some locations. Contact your OMRON representative before attempting to use a Controller on a ship.

Usage Conditions for NK and LR Shipbuilding Standards
· The NJ/NX-series Controller must be installed within a control panel. · Gaps in the door to the control panel must be completely filled or covered with gaskets or other
material. · The following noise filter must be connected to the power supply line.
Noise Filter

Manufacturer Cosel Co., Ltd.

Model TAH-06-683

Software Licenses and Copyrights
This product incorporates certain third party software. The license and copyright information associated with this software is available at http://www.fa.omron.co.jp/nj_info_e/.

NJ/NX-series Instructions Reference Manual (W502)

23

Versions

Versions

Hardware revisions and unit versions are used to manage the hardware and software in NJ/NX-series Units and EtherCAT slaves. The hardware revision or unit version is updated each time there is a change in hardware or software specifications. Even when two Units or EtherCAT slaves have the same model number, they will have functional or performance differences if they have different hardware revision or unit versions.
Checking Versions
You can check versions in the ID information indications or with the Sysmac Studio.
Checking Unit Versions on ID Information Indications
The unit version is given on the ID information indication on the side of the product. The ID information on an NX-series NX701- CPU Unit is shown below.

ID information indication Lot number Serial number

Unit version

LOT No. DDMYY PORT1 : PORT2 :

xxxx

Ver.1. HW Rev.

MAC address

Hardware revision

Note The hardware revision is not displayed for the Unit that the hardware revision is in blank.

The ID information on an NX-series NX102- CPU Unit is shown below.

Unit version Hardware revision

Lot number Serial number

Ver. . HW Rev.

LOT No. DDMYY PORT1 PORT2

xxxx

ID information indication

MAC address

Note The hardware revision is not displayed for the Unit that the hardware revision is in blank.

24

NJ/NX-series Instructions Reference Manual (W502)

Versions

The ID information on an NX-series NX1P2- CPU Unit is shown below.

MAC address

Unit version ID information indication

PORT1 :

PORT2 :

Ver.1.

HW Rev.

LOT No. DDMYY xxxx

Hardware revision

Lot number Serial number Note The hardware revision is not displayed for the Unit that the hardware revision is in blank.

The ID information on the NJ-series NJ501- CPU Unit is shown below.

ID information indication Unit model

Unit version

Hardware revision

NJ501 -

Ver.1.

PORT1 MAC ADDRESS: PORT2 MAC ADDRESS:

Lot No. DDMYY xxxx

HW Rev.

Lot number Serial number MAC address Note The hardware revision is not displayed for the Unit that the hardware revision is in blank.

Checking Unit Versions with the Sysmac Studio
You can use the Sysmac Studio to check unit versions. The procedure is different for Units and for EtherCAT slaves.

 Checking the Unit Version of an NX-series CPU Unit
You can use the Production Information while the Sysmac Studio is online to check the unit version of a Unit. You can do this for the following Units.

Unit model NX701- NX102- NX1P2-

Available unit to check the unit version CPU Unit CPU Unit, NX Unit on CPU Rack CPU Unit, NX Unit on CPU Rack, and Option Boards

NJ/NX-series Instructions Reference Manual (W502)

25

Versions
1 Right-click CPU Rack under Configurations and Setup - CPU/Expansion Racks in the
Multiview Explorer and select Production Information. The Production Information Dialog Box is displayed.
 Checking the Unit Version of an NJ-series CPU Unit
You can use the Production Information while the Sysmac Studio is online to check the unit version of a Unit. You can do this for the CPU Unit, CJ-series Special I/O Units, and CJ-series CPU Bus Units. You cannot check the unit versions of CJ-series Basic I/O Units with the Sysmac Studio. Use the following procedure to check the unit version.
1 Double-click CPU/Expansion Racks under Configurations and Setup in the Multiview
Explorer. Or, right-click CPU/Expansion Racks under Configurations and Setup and select Edit from the menu. The Unit Editor is displayed.
2 Right-click any open space in the Unit Editor and select Production Information.
The Production Information Dialog Box is displayed.
 Changing Information Displayed in Production Information Dialog Box
1 Click the Show Detail or Show Outline Button at the lower right of the Production Information
Dialog Box. The view will change between the production information details and outline.

Outline View

Detail View

The information that is displayed is different for the Outline View and Detail View. The Detail View displays the unit version, hardware version, and software versions. The Outline View displays only the unit version.

Note The hardware revision is separated by "/" and displayed on the right of the hardware version. The hardware revision is not displayed for the Unit that the hardware revision is in blank.

 Checking the Unit Version of an EtherCAT Slave
You can use the Production Information while the Sysmac Studio is online to check the unit version of an EtherCAT slave. Use the following procedure to check the unit version.
1 Double-click EtherCAT under Configurations and Setup in the Multiview Explorer. Or, right-
click EtherCAT under Configurations and Setup and select Edit from the menu.
The EtherCAT Tab Page is displayed.

26

NJ/NX-series Instructions Reference Manual (W502)

Versions
2 Right-click the master on the EtherCAT Tab Page and select Display Production Information.
The Production Information Dialog Box is displayed. The unit version is displayed after "Rev."
 Changing Information Displayed in Production Information Dialog Box
1 Click the Show Detail or Show Outline Button at the lower right of the Production Information
Dialog Box. The view will change between the production information details and outline.

Outline View

Detail View

Unit Versions of CPU Units and Sysmac Studio Versions
The functions that are supported depend on the unit version of the NJ/NX-series CPU Unit. The version of Sysmac Studio that supports the functions that were added for an upgrade is also required to use those functions.
Refer to the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) for the relationship between the unit versions of the CPU Units and the Sysmac Studio versions, and for the functions that are supported by each unit version.

NJ/NX-series Instructions Reference Manual (W502)

27

Related Manuals

Related Manuals

The followings are the manuals related to this manual. Use these manuals for reference.

Manual name NX-series CPU Unit Hardware User's Manual
NX-series NX102 CPU Unit Hardware User's Manual
NX-series NX1P2 CPU Unit Hardware User's Manual
NJ-series CPU Unit Hardware User's Manual
NJ/NX-series CPU Unit Software User's Manual
NX-series NX1P2 CPU Unit Built-in I/O and Option Board User's Manual

Cat. No. Model numbers W535 NX701-

W593 NX102-

W578 NX1P2-

W500

NJ501- NJ301- NJ101-

W501

NX701- NX102- NX1P2- NJ501- NJ301- NJ101-

W579 NX1P2-

Application Learning the basic specifications of the NX701 CPU Units, including introductory information, designing, installation, and maintenance. Mainly hardware information is provided.
Learning the basic specifications of the NX102 CPU Units, including introductory information, designing, installation, and maintenance. Mainly hardware information is provided.
Learning the basic specifications of the NX1P2 CPU Units, including introductory information, designing, installation, and maintenance. Mainly hardware information is provided.
Learning the basic specifications of the NJ-series CPU Units, including introductory information, designing, installation, and maintenance. Mainly hardware information is provided.
Learning how to program and set up an NJ/NX-series CPU Unit. Mainly software information is provided.
Learning about the details of functions only for an NXseries NX1P2 CPU Unit and an introduction of functions for an NJ/NX-series CPU Unit.

Description An introduction to the entire NX701 system is provided along with the following information on the CPU Unit.
· Features and system configuration · Introduction · Part names and functions · General specifications · Installation and wiring · Maintenance and inspection An introduction to the entire NX102 system is provided along with the following information on the CPU Unit.
· Features and system configuration · Introduction · Part names and functions · General specifications · Installation and wiring · Maintenance and inspection An introduction to the entire NX1P2 system is provided along with the following information on the CPU Unit.
· Features and system configuration · Introduction · Part names and functions · General specifications · Installation and wiring · Maintenance and inspection An introduction to the entire NJ-series system is provided along with the following information on the CPU Unit.
· Features and system configuration · Introduction · Part names and functions · General specifications · Installation and wiring · Maintenance and inspection The following information is provided on an NJ/NXseries CPU Unit.
· CPU Unit operation · CPU Unit features · Initial settings · Programming based on IEC 61131-3 language
specifications Of the functions for an NX1P2 CPU Unit, the following information is provided.
· Built-in I/O · Serial Communications Option Boards · Analog I/O Option Boards
An introduction of following functions for an NJ/NXseries CPU Unit is also provided.
· Motion control functions · EtherNet/IP communications functions · EtherCAT communications functions

28

NJ/NX-series Instructions Reference Manual (W502)

Related Manuals

Manual name NJ/NX-series Instructions Reference Manual
NJ/NX-series CPU Unit Motion Control User's Manual
NJ/NX-series Motion Control Instructions Reference Manual
NJ/NX-series CPU Unit Built-in EtherCAT® Port User's Manual
NJ/NX-series CPU Unit Built-in EtherNet/IPTM Port User's Manual
NJ/NX-series CPU Unit OPC UA User's Manual NX-series CPU Unit FINS Function User's Manual NJ/NX-series Database Connection CPU Units User's Manual
NJ-series SECS/GEM CPU Unit User's Manual NJ-series NJ Robotics CPU Unit User's Manual NJ/NY-series NC Integrated Controller User's Manual NJ/NY-series G code Instructions Reference Manual NJ/NX-series Troubleshooting Manual
Sysmac Studio Version 1 Operation Manual
CNC Operator Operation Manual

Cat. No. W502
W507
W508
W505
W506
W588 W596

Model numbers
NX701- NX102- NX1P2- NJ501- NJ301- NJ101-
NX701- NX102- NX1P2- NJ501- NJ301- NJ101-
NX701- NX102- NX1P2- NJ501- NJ301- NJ101-
NX701- NX102- NX1P2- NJ501- NJ301- NJ101-
NX701- NX102- NX1P2- NJ501- NJ301- NJ101-
NX102- NJ501-100
NX701-20 NX102-

W527
W528 W539 O030 O031 W503
W504 O032

NX701-20 NX102-20 NJ501-20 NJ101-20 NJ501-1340
NJ501-4
NJ501-5300 NY532-5400
NJ501-5300 NY532-5400
NX701- NX102- NX1P2- NJ501- NJ301- NJ101- SYSMACSE2
SYSMACRTNC0D

Application Learning detailed specifications on the basic instructions of an NJ/NX-series CPU Unit.
Learning about motion control settings and programming concepts.
Learning about the specifications of the motion control instructions that are provided by OMRON.
Using the built-in EtherCAT port on an NJ/NX-series CPU Unit.
Using the built-in EtherNet/IP port on an NJ/NXseries CPU Unit.
Using OPC UA.
Using the FINS function on the NX-series CPU Unit.
Using the database connection service with NJ/NXseries Controllers
Using the GEM Services with NJ-series Controllers Controlling robots with NJseries CPU Units. Performing numerical control with NJ/NY-series Controllers. Learning about the specifications of the G code/M code instructions. Learning about the errors that may be detected in an NJ/NX-series Controller.
Learning about the operating procedures and functions of the Sysmac Studio. Learning an introduction of the CNC Operator and how to use it.

Description The instructions in the instruction set (IEC 61131-3 specifications) are described.
The settings and operation of the CPU Unit and programming concepts for motion control are described.
The motion control instructions are described.
Information on the built-in EtherCAT port is provided. This manual provides an introduction and provides information on the configuration, features, and setup.
Information on the built-in EtherNet/IP port is provided. Information is provided on the basic setup, tag data links, and other features.
An introduction to the OPC UA is provided. An introduction to the FINS function on the NXseries CPU Unit is provided.
Describes the database connection service.
Information is provided on the GEM Services. Describes the functionality to control robots. Describes the functionality to perform the numerical control. The G code/M code instructions are described.
Concepts on managing errors that may be detected in an NJ/NX-series Controller and information on individual errors are described.
Describes the operating procedures of the Sysmac Studio. An introduction of the CNC Operator, installation procedures, basic operations, connection operations, and operating procedures for main functions are described.

NJ/NX-series Instructions Reference Manual (W502)

29

Related Manuals

Manual name NX-series EtherCAT® Coupler Unit User's Manual NX-series Data Reference Manual NX-series NX Units User's Manuals
CJ-series Special Unit Manuals for NJ-series CPU Unit
CX-Protocol Operation Manual

Cat. No. W519
W525
W521
W522 W566 W523
W524
W540 W565 W567 W490
W491 W492 W498
W493 W494 W495 W497 Z317 W344

Model numbers NX-ECC
NX-
NX-ID NX-IA NX-OC NX-OD NX-MD NX-AD NX-DA NX-TS NX-HB NX-PD1 NX-PF0 NX-PC0 NX-TBX01 NX-EC0 NX-ECS NX-PG0
NX-CIF NX-RS NX-ILM
CJ1W-AD CJ1W-DA CJ1W-MAD42 CJ1W-TC CJ1W-CT021 CJ1W-PDC15 CJ1W-PH41U CJ1W-AD04U CJ1W-CRM21 CJ1W-SCU CJ1W-EIP21 CJ1W-DRM21 CJ1W-V680
-

Application Learning how to use an NXseries EtherCAT Coupler Unit and EtherCAT Slave Terminals Referencing lists of the data that is required to configure systems with NX-series Units. Learning how to use NX Units
Learning how to use CJseries Units with an NJseries CPU Unit.
Creating data transfer protocols for general-purpose devices connected to CJseries Serial Communications Units.

Description The system and configuration of EtherCAT Slave Terminals, which consist of an NX-series EtherCAT Coupler Unit and NX Units, are described along with the hardware, setup, and functions of the EtherCAT Coupler Unit that are required to configure, control, and monitor NX Units through EtherCAT. Lists of the power consumptions, weights, and other NX Unit data that is required to configure systems with NX-series Units are provided.
Describes the hardware, setup methods, and functions of the NX Units. Manuals are available for the following Units. Digital I/O Units, Analog I/O Units, System Units, Position Interface Units, Communications Interface Units, Load Cell Input Units, and IO-Link Master Units.
The methods and precautions for using CJ-series Units with an NJ501 CPU Unit are described, including access methods and programming interfaces. Manuals are available for the following Units. Analog I/O Units, Insulated-type Analog I/O Units, Temperature Control Units, ID Sensor Units, Highspeed Counter Units, Serial Communications Units, DeviceNet Units, EtherNet/IP Units, and CompoNet Master Units.
Describes operating procedures for the CX-Protocol.

30

NJ/NX-series Instructions Reference Manual (W502)

Revision History

Revision History

A manual revision code appears as a suffix to the catalog number on the front and back covers of the manual.

Cat. No. W502-E1-24

Revision code

Revision code 01 02 03 04 05 06 07 08 09 10 11 12 13
14 15 16
17
18 19 20 21

Date

Revised content

July 2011 Original production

September 2011 Corrected mistakes.

March 2012

Made changes accompanying release of unit version 1.01 of the CPU Unit and version 1.02 of the Sysmac Studio.

May 2012

Made changes accompanying release of unit version 1.02 of the CPU Unit and version 1.03 of the Sysmac Studio.

August 2012 Made changes accompanying release of unit version 1.03 of the CPU Unit and version 1.04 of the Sysmac Studio.

February 2013 Made changes accompanying release of unit version 1.04 of the CPU Unit and version 1.05 of the Sysmac Studio.

April 2013

Made changes accompanying release of unit version 1.05 of the CPU Unit and version 1.06 of the Sysmac Studio.

June 2013

Made changes accompanying release of unit version 1.06 of the CPU Unit and version 1.07 of the Sysmac Studio.

September 2013 Made changes accompanying release of unit version 1.07 of the CPU Unit and version 1.08 of the Sysmac Studio.

December 2013 Made changes accompanying release of unit version 1.08 of the CPU Unit and version 1.09 of the Sysmac Studio.

July 2014

Made changes accompanying release of unit version 1.09 of the CPU Unit and version 1.10 of the Sysmac Studio.

January 2015 Made changes accompanying release of unit version 1.10 of the CPU Unit and version 1.12 of the Sysmac Studio.

April 2015

· Made changes accompanying the addition of NX-series NX701- CPU Units and the release of version 1.13 of the Sysmac Studio.

· Added information on the NJ101- NJ-series CPU Units.

· Corrected mistakes.

October 2015 · Made changes accompanying the addition of hardware revision.

· Corrected mistakes.

April 2016

Made changes accompanying release of unit version 1.11 of the CPU Unit and version 1.15 of the Sysmac Studio.

July 2016

· Made changes accompanying release of unit version 1.12 of the CPU Unit and version 1.16 of the Sysmac Studio.

· Corrected mistakes.

October 2016 · Made changes accompanying release of unit version 1.13 of the CPU Unit and version 1.17 of the Sysmac Studio.

· Corrected mistakes.

November 2016 Corrected mistakes.

January 2017 Corrected mistakes.

April 2017 Corrected mistakes.

October 2017 · Made changes accompanying release of unit version 1.16 of the CPU Unit and version 1.20 of the Sysmac Studio.

· Corrected mistakes.

NJ/NX-series Instructions Reference Manual (W502)

31

Revision History

Revision code 22 23
24

Date April 2018 April 2018
July 2018

Revised content · Made changes accompanying release of unit version 1.18 of the CPU
Unit and version 1.22 of the Sysmac Studio. · Corrected mistakes. · Made changes accompanying addition of NX-series NX102 CPU Unit. · Made changes accompanying the transfer of event codes to the NJ/NX-
series Troubleshooting Manual. · Corrected mistakes. · Corrected mistakes.

32

NJ/NX-series Instructions Reference Manual (W502)

1
Instruction Set
This section provides a table of the instructions that you can use with NJ/NX-series Controllers.
Instruction Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2

NJ/NX-series Instructions Reference Manual (W502)

1-1

1 Instruction Set

Instruction Set

Type
Ladder Diagram Instructions

Instruction LD LDN

AND

ANDN

OR

ORN

Out OutNot

ST Statement IF Instructions
CASE
WHILE

REPEAT

EXIT RETURN FOR

Sequence Input Instructions

R_TRIG (Up) F_TRIG (Down)

TestABit

TestABitN

Sequence Out- RS put Instructions

Name Load Load NOT AND AND NOT OR OR NOT
Output Output NOT
If
Case While
Repeat
Break Loop Return Repeat Start
Up Trigger Down Trigger Test A Bit Test A Bit NOT Reset-Priority Keep

Function

Page

Reads the value of a BOOL variable.

2-16

Reads the inverse of the value of a BOOL vari- 2-16 able.

Takes the logical AND of the value of a BOOL 2-18 variable and the input value.

Takes the logical AND of the inverse of the

2-18

value of a BOOL variable and the input value.

Takes the logical OR of the value of a BOOL 2-20 variable and the execution condition.

Takes the logical OR of the inverse of the value 2-20 of a BOOL variable and the execution condition.

Takes the logical result from the previous

2-22

instruction and outputs it to a BOOL variable.

Takes the inverse of the logical result from the 2-22 previous instruction and outputs it to a BOOL variable.

Uses the evaluation result of a specified condi- 2-26 tion expression to select one of two statements to execute.

Selects the statement to execute based on the 2-30 value of a specified integer expression.

Repeatedly executes a statement as long as the evaluation result of a specified condition expression is TRUE.

2-34

Executes a statement once and then executes 2-36 it repeatedly until a specified condition expression is TRUE.

Used to end repeat processing from the lowest 2-38 level FOR, WHILE, or REPEAT instruction.

Ends a function or function block and returns 2-41 processing to the calling instruction.

Marks the starting position for repeat processing of statements between the FOR and END_FOR statements and specifies the repeat condition.

2-42

Outputs TRUE for one task period only when 2-44 the input signal changes to TRUE.

Outputs TRUE for one task period only when 2-44 the input signal changes to FALSE.

Outputs the value of the specified bit in a bit string.

2-47

Outputs the inverse of the value of the speci- 2-47 fied bit in a bit string.

Retains the value of a BOOL variable. It gives 2-50 priority to the Reset input if both the Set input and Reset input are TRUE.

1-2

NJ/NX-series Instructions Reference Manual (W502)

1 Instruction Set

Instruction Set

Type

Instruction

Sequence Out- SR put Instructions

Set Reset SetBits

ResetBits

SetABit

ResetABit

OutABit

Sequence Control Instructions

End RETURN

MC

MCR JMP

FOR

NEXT

BREAK

Comparison Instructions

EQ (=) NE (<>)

LT (<)

LE (<=)

GT (>)

GE (>=)

EQascii

NEascii

LTascii

LEascii

Name

Function

Page

Set-Priority Keep

Retains the value of a BOOL variable. It gives 2-53 priority to the Set input if both the Set input and Reset input are TRUE.

Set

Changes a BOOL variable to TRUE.

2-56

Reset

Changes a BOOL variable to FALSE.

2-56

Set Bits Reset Bits

Changes consecutive bits in bit string data to 2-59

TRUE.

1

Changes consecutive bits in bit string data to 2-59

FALSE.

Set A Bit

Changes the specified bit in bit string data to 2-61 TRUE.

Reset A Bit

Changes the specified bit in bit string data to 2-61 FALSE.

Output A Bit

Changes the specified bit in bit string data to 2-63 TRUE or FALSE.

End

Ends execution of a program in the current

2-66

task period.

Return

Ends a function or function block and returns 2-67 processing to the calling instruction.

Master Control Start

Marks the starting point of a master control region and resets the master control region.

2-68

Master Control End Marks the end point of a master control region. 2-68

Jump

Moves processing to the specified jump desti- 2-80 nation.

Repeat Start

Marks the starting position for repeat process- 2-82 ing and specifies the repeat condition.

Repeat End

Marks the ending position for repeat process- 2-82 ing.

Break Loop

Cancels repeat processing from the lowest

2-89

level FOR instruction to the NEXT instruction.

Equal

Determines if two or more values or text strings 2-92 are all equivalent.

Not Equal

Determines if two values or text strings are not 2-94 equivalent.

Less Than

Performs a less than comparison between val- 2-97 ues.

Less Than Or Equal

Performs a less than or equal comparison between values.

2-97

Greater Than

Performs a greater than comparison between 2-97 values.

Greater Than Or Equal

Performs a greater than or equal comparison 2-97 between values.

Text String

Determines if two or more text strings are all

Comparison Equal equivalent.

2-100

Text String Comparison Not Equal

Determines if two text strings are not equiva- 2-102 lent.

Text String Comparison Less Than

Performs a less than comparison between text 2-104 strings.

Text String Comparison Less Than or Equal

Performs a less than or equal comparison between text strings.

2-104

NJ/NX-series Instructions Reference Manual (W502)

1-3

1 Instruction Set

Type
Comparison Instructions

Instruction GTascii
GEascii

Cmp ZoneCmp TableCmp AryCmpEQ AryCmpNE AryCmpLT AryCmpLE
AryCmpGT AryCmpGE
AryCmpEQV AryCmpNEV
AryCmpLTV
AryCmpLEV
AryCmpGTV
AryCmpGEV

Timer Instructions

TON TOF

TP

AccumulationTimer

Timer

Name

Function

Page

Text String Comparison Greater Than

Performs a greater than comparison between 2-104 text strings.

Text String Comparison Greater Than or Equal

Performs a greater than or equal comparison 2-104 between text strings.

Compare

Compares two values.

2-107

Zone Comparison Determines if the comparison data is within the 2-109 specified maximum and minimum values.

Table Comparison Compares the comparison data with multiple 2-111 defined ranges in a comparison table.

Array Comparison Determines if the corresponding elements of 2-114

Equal

two arrays are equal.

Array Comparison Determines if the corresponding elements of 2-114

Not Equal

two arrays are not equal.

Array Comparison Performs a less than comparison between the 2-116

Less Than

corresponding elements of two arrays.

Array Comparison Less Than Or Equal

Performs a less than or equal comparison between the corresponding elements of two arrays.

2-116

Array Comparison Performs a greater than comparison between 2-116

Greater Than

the corresponding elements of two arrays.

Array Comparison Greater Than Or Equal

Performs a greater than or equal comparison between the corresponding elements of two arrays.

2-116

Array Value

Determines if the elements of an array are

Comparison Equal equal to a value.

2-119

Array Value Comparison Not Equal

Determines if the elements of an array are not 2-119 equal to a value.

Array Value Comparison Less Than

Performs a less than comparison between a value and the elements of an array.

2-121

Array Value Comparison Less Than Or Equal

Performs a less than or equal comparison

2-121

between a value and the elements of an array.

Array Value Comparison Greater Than

Performs a greater than comparison between a 2-121 value and the elements of an array.

Array Value Comparison Greater Than Or Equal

Performs a greater than or equal comparison 2-121 between a value and the elements of an array.

On-Delay Timer

Outputs TRUE when the set time elapses after 2-126 the timer starts.

Off-Delay Timer

Outputs FALSE when the set time elapses after the timer starts.

2-132

Timer Pulse

Outputs TRUE while the set time elapses after 2-135 the timer starts.

Accumulation Timer

Totals the time that the timer input is TRUE. 2-138

Hundred-ms Timer Outputs TRUE when the set time elapses after 2-141 the timer starts. The time is set in increments of 100 ms.

1-4

NJ/NX-series Instructions Reference Manual (W502)

1 Instruction Set

Instruction Set

Type
Counter Instructions

Instruction CTD

CTD_**

CTU CTU_** CTUD CTUD_**

Math Instructions

ADD (+) AddOU (+OU)

SUB (-) SubOU (-OU)

MUL (*) MulOU (*OU)

DIV (/) MOD ABS
RadToDeg
DegToRad
SIN COS TAN ASIN ACOS
ATAN

Name

Function

Page

Down-counter

Decrements the counter value when the counter input signal is received. The preset value and counter value must have an INT data type.

2-146

Down-counter

Decrements the counter value when the

2-148

Group

counter input signal is received. The preset

value and counter value must be one of the fol-

lowing data types: DINT, LINT, UDINT, or ULINT.

1

Up-counter

Increments the counter value when the counter 2-150 input signal is received. The preset value and counter value must have an INT data type.

Up-counter Group

Increments the counter value when the counter input signal is received. The preset value and counter value must be one of the following data types: DINT, LINT, UDINT, or ULINT.

2-152

Up-down Counter

Creates an up-down counter that operates according to an up-counter input and a downcounter input. The preset value and counter value must have an INT data type.

2-155

Up-down Counter Group

Creates an up-down counter that operates according to an up-counter input and a downcounter input. The preset value and counter value must be one of the following data types: DINT, LINT, UDINT, or ULINT.

2-159

Addition

Adds integers and real numbers. Also joins text 2-166 strings.

Addition with Overflow Check

Adds integers and real numbers. Also performs an overflow check for the integer addition result.

2-170

Subtraction

Subtracts integers and real numbers.

2-174

Subtraction with Overflow Check

Subtracts integers or real numbers. Also performs an overflow check for the integer subtraction result.

2-177

Multiplication

Multiplies integers and real numbers.

2-181

Multiplication with Overflow Check

Multiplies integers and real numbers and outputs the result. Also performs an overflow check for the integer multiplication result.

2-185

Division

Divides integers or real numbers.

2-189

Modulo-division Finds the remainder for division of integers. 2-192

Absolute Value

Finds the absolute value of an integer or real 2-194 number.

Radians to Degrees

Converts a real number from radians (rad) to 2-196 degrees (°).

Degrees to Radians

Converts a real number from degrees (°) to radians (rad).

2-196

Sine in Radians Calculates the sine of a real number.

2-198

Cosine in Radians Calculates the cosine of a real number.

2-198

Tangent in Radians Calculates the tangent of a real number.

2-198

Principal Arc Sine Calculates the arcsine of a real number.

2-201

Principal Arc Cosine

Calculates the arccosine of a real number.

2-201

Principal Arc Tangent

Calculates the arctangent of a real number. 2-201

NJ/NX-series Instructions Reference Manual (W502)

1-5

1 Instruction Set

Type
Math Instructions

Instruction SQRT LN LOG EXP

EXPT (**)
Inc Dec Rand AryAdd AryAddV
ArySub
ArySubV
AryMean
ArySD
ModReal
Fraction
CheckReal
BCD Conversion **_BCD_TO_*** Instructions
**_TO_BCD_***

BCD_TO_**

BCDsToBin

BinToBCDs_**

AryToBCD

AryToBin

Data Type Conversion Instructions

**_TO_*** (Integer-toInteger Conversion Group)
**_TO_*** (Integer-toBit String Conversion Group)

Name

Function

Page

Square Root

Finds the square root of a number.

2-204

Natural Logarithm Finds the natural logarithm of a real number. 2-206

Logarithm Base 10 Finds the base-10 logarithm of a real number. 2-206

Natural Exponential Operation

Performs calculations for the natural exponen- 2-209 tial function.

Exponentiation

Raises one real number to the power of another real number.

2-211

Increment

Increments an integer value.

2-217

Decrement

Decrements an integer value.

2-217

Random Number Generates pseudorandom numbers.

2-219

Array Addition

Adds corresponding elements of two arrays. 2-221

Array Value Addition

Adds the same value to specified elements of 2-223 an array.

Array Subtraction Subtracts corresponding elements of two arrays.

2-225

Array Value Subtraction

Subtracts the same value from specified ele- 2-227 ments of an array.

Array Mean

Calculates the average of the elements of an 2-229 array.

Array Element

Calculates standard deviation of the elements 2-231

Standard Deviation of an array.

Real Number Modulo-division

Calculates the remainder of real number divi- 2-233 sion.

Real Number Fraction

Finds the fractional part of a real number.

2-235

Real Number Check

Checks a real number to see if it is infinity or 2-237 nonnumeric data.

BCD-to-Unsigned Converts BCD bit strings into unsigned inteInteger Conversion gers. Group

2-242

Unsigned Integer- Converts unsigned integers to BCD bit strings. 2-245 to-BCD Conversion Group

BCD Data Type-to- Converts BCD bit strings into unsigned inteUnsigned Integer gers. Conversion Group

2-247

Signed BCD-toSigned Integer Conversion

Converts signed BCD bit strings to signed inte- 2-250 gers.

Signed Integer-toBCD Conversion Group

Converts signed integers to signed BCD bit strings.

2-253

Array BCD Conversion

Converts the elements of an unsigned integer 2-256 array to BCD bit strings.

Array Unsigned

Converts the elements of an array of BCD bit 2-258

Integer Conversion strings into unsigned integers.

Integer-to-Integer Converts integers to integers with different Conversion Group data types.

2-262

Integer-to-Bit String Conversion Group

Converts integers to bit strings.

2-265

1-6

NJ/NX-series Instructions Reference Manual (W502)

1 Instruction Set

Instruction Set

Type

Instruction

Name

Function

Page

Data Type Con- **_TO_*** (Integer-to-

version Instruc- Real Number Conver-

tions

sion Group)

Integer-to-Real

Converts integers to real numbers.

Number

Conversion Group

2-268

**_TO_*** (Bit String-to- Bit String-to-

Converts bit strings to integers.

Integer Conversion

Integer Conversion

Group)

Group

2-270

**_TO_*** (Bit String-to- Bit String-to-Bit

Converts bit strings to bit strings with different 2-272

Bit String Conversion String Conversion data types.

1

Group)

Group

**_TO_*** (Bit String-to- Bit String-to-Real Converts bit strings to real numbers.

Real Number Conver- Number

sion Group)

Conversion Group

2-274

**_TO_*** (Real Number-to-Integer Conversion Group)

Real Number-to- Converts real numbers to integers. Integer Conversion Group

2-276

**_TO_*** (Real Number-to-Bit String Conversion Group)

Real Number-to-Bit Converts real numbers to bit strings. String Conversion Group

2-279

**_TO_*** (Real Number-to-Real Number Conversion Group)

Real Number-to- Converts real numbers to real numbers with

Real Number

different data types.

Conversion Group

2-281

**_TO_STRING (Integer-to-Text String Conversion Group)

Integer-to-Text String Conversion Group

Converts integers to text strings.

2-283

**_TO_STRING (Bit String-to-Text String Conversion Group)

Bit String-to-Text String Conversion Group

Converts bit strings to text strings.

2-285

**_TO_STRING (Real Number-to-Text String Conversion Group)

Real Number-to- Converts real numbers to text strings. Text String Conversion Group

2-287

RealToFormatString

REAL-toFormatted Text String

Converts a REAL variable to a text string with 2-289 the specified format.

LrealToFormatString

LREAL-toFormatted Text String

Converts a LREAL variable to a text string with 2-294 the specified format.

STRING_TO_** (Text String-to-Integer Conversion Group)

Text String-to-

Converts text strings to integers.

Integer Conversion

Group

2-299

STRING_TO_** (Text String-to-Bit String Conversion Group)

Text String-to-Bit String Conversion Group

Converts text strings to bit strings.

2-301

STRING_TO_** (Text String-to-Real Number Conversion Group)

Text String-to-Real Converts text strings to real numbers. Number Conversion Group

2-303

TO_** (Integer Conver- Integer Conversion Converts integers, bit strings, real numbers,

sion Group)

Group

and text strings to integers.

2-306

TO_** (Bit String Con- Bit String

Converts integers, bit strings, real numbers,

version Group)

Conversion Group and text strings to bit strings.

2-308

TO_** (Real Number Conversion Group)

Real Number

Converts integers, bit strings, real numbers,

Conversion Group and text strings to real numbers.

2-310

EnumToNum

Enumeration-toInteger

The EnumToNum instruction converts enumer- 2-312 ation data to DINT data.

NumToEnum

Integer-toEnumeration

The NumToEnum instruction converts DINT data to enumeration data.

2-314

NJ/NX-series Instructions Reference Manual (W502)

1-7

1 Instruction Set

Type
Data Type Conversion Instructions

Instruction TRUNC
Round

RoundUp

Bit String Processing Instructions

AND (&) OR

XOR

XORN

NOT AryAnd

AryOr

AryXor

AryXorN

Selection Instructions

SEL MUX LIMIT

Band Zone MAX MIN AryMax

AryMin

ArySearch

Data Movement Instructions

MOVE
MoveBit MoveDigit TransBits MemCopy

Name

Function

Page

Truncate

Truncates a real number at the first decimal digit to make an integer.

2-316

Round Off Real Number

Rounds a real number at the first decimal digit 2-316 to make an integer.

Round Up Real Number

Rounds up a real number at the first decimal 2-316 digit to make an integer.

Logical AND

Performs a logical AND operation on Boolean 2-320 variables or individual bits in bit stings.

Logical OR

Performs a logical OR operation on Boolean variables or individual bits in bit stings.

2-320

Logical Exclusive OR

Performs a logical exclusive OR operation on Boolean variables or individual bits in bit stings.

2-320

Logical Exclusive NOR

Performs a logical exclusive NOR operation on 2-323 Boolean variables or individual bits in bit stings.

Bit Reversal

Reverses the value of a Boolean variable or individual bits in a bit string.

2-325

Array Logical AND Performs a logical AND operation on Boolean 2-327 variables or individual bits in bit stings between arrays.

Array Logical OR

Performs a logical OR operation on Boolean 2-327 variables or individual bits in bit stings between arrays.

Array Logical Exclusive OR

Performs a logical exclusive OR operation on 2-327 Boolean variables or individual bits in bit stings between arrays.

Array Logical Exclusive NOR

Performs a logical exclusive NOR operation on 2-327 Boolean variables or individual bits in bit stings between arrays.

Binary Selection Selects one of two selections.

2-332

Multiplexer

Selects one of two to five selections.

2-334

Limiter

Limits the value of the input variable to the specified minimum and maximum values.

2-337

Deadband Control Performs deadband control.

2-339

Dead Zone Control Adds a bias value to the input value.

2-342

Maximum

Finds the largest of two to five values.

2-345

Minimum

Finds the smallest of two to five values.

2-345

Array Maximum

Finds the elements with the largest value in a 2-347 one-dimensional array.

Array Minimum

Finds the elements with the smallest value in a 2-347 one-dimensional array.

Array Search

Searches for the specified value in a onedimensional array.

2-350

Move

Moves the value of a constant or variable to another variable.

2-354

Move Bit

Moves one bit in a bit string.

2-357

Move Digit

Moves digits (4 bits per digit) in a bit string.

2-359

Move Bits

Moves one or more bits in a bit string.

2-361

Memory Copy

Moves one or more array elements. The move 2-363 source and move destination must have the same data type.

1-8

NJ/NX-series Instructions Reference Manual (W502)

1 Instruction Set

Instruction Set

Type

Instruction

Name

Function

Page

Data Movement SetBlock Instructions

Block Set

Moves the value of a variable or constant to one or more array elements.

2-365

Exchange

Data Exchange

Exchanges the values of two variables.

2-367

AryExchange

Array Data Exchange

Exchanges the elements of two arrays.

2-369

AryMove

Array Move

Moves one or more array elements. The data 2-371

types of the move source and move destination can be different.

1

Clear

Initialize

Initializes a variable.

2-373

Copy**ToNum (Bit String to Signed Integer)

Bit Pattern Copy (Bit String to Signed Integer) Group

Copies the content of a bit string directly to a 2-375 signed integer.

Copy**To*** (Bit String Bit Pattern Copy

to Real Number)

(Bit String to Real

Number) Group

Copies the content of a bit string directly to a real number.

2-377

CopyNumTo** (Signed Integer to Bit String)

Bit Pattern Copy (Signed Integer to Bit String) Group

Copies the content of a signed integer directly 2-379 to a bit string.

CopyNumTo** (Signed Integer to Real Number)

Bit Pattern Copy (Signed Integer to Real Number) Group

Copies the content of a signed integer directly 2-381 to a real number.

Copy**To*** (Real Number to Bit String)

Bit Pattern Copy (Real Number to Bit String) Group

Copies the content of a real number directly to 2-383 a bit string.

Copy**ToNum (Real Number to Signed Integer)

Bit Pattern Copy (Real Number to Signed Integer) Group

Copies the content of a real number directly to 2-385 a signed integer.

Shift Instructions AryShiftReg

Shift Register

Shifts a bit string one bit to the left and inserts 2-388 the input value to the least-significant bit. The bit string consists of array elements.

AryShiftRegLR

Reversible Shift Register

Shifts a bit string one bit to the left or right and inserts the input value to the least-significant or most-significant bit. The bit string consists of array elements.

2-390

ArySHL

Array N-element Left Shift

Shifts array elements by one or more elements 2-393 to the left (toward the higher elements).

ArySHR

Array N-element Right Shift

Shifts array elements by one or more elements 2-393 to the right (toward the lower elements).

SHL

N-bit Left Shift

Shifts a bit string by one or more bits to the left 2-396

(toward the higher bits).

SHR

N-bit Right Shift

Shifts a bit string by one or more bits to the right (toward the lower bits).

2-396

NSHLC

Shift N-bits Left with Carry

Shifts an array of bit strings that includes the 2-398 Carry (CY) Flag by one or more bits to the left (toward the higher elements).

NSHRC

Shift N-bits Right with Carry

Shifts an array of bit strings that includes the 2-398 Carry (CY) Flag by one or more bits to the right (toward the lower elements).

ROL

Rotate N-bits Left Rotates a bit string by one or more bits to the 2-400 left (toward the higher bits).

ROR

Rotate N-bits Right Rotates a bit string by one or more bits to the 2-400 right (toward the lower bits).

NJ/NX-series Instructions Reference Manual (W502)

1-9

1 Instruction Set

Type
Conversion Instructions

Instruction Swap Neg Decoder Encoder BitCnt ColmToLine_** LineToColm Gray UTF8ToSJIS SJISToUTF8 PWLApprox
PWLApproxNoLineChk
PWLLineChk
MovingAverage DispartReal UniteReal NumToDecString NumToHexString HexStringToNum_** FixNumToString

Name Swap Bytes
Reverse Sign Bit Decoder
Bit Encoder
Bit Counter Column to Line Conversion Group
Line to Column Conversion
Gray Code Conversion UTF-8 to SJIS Character Code Conversion SJIS to UTF-8 Character Code Conversion Broken Line Approximation with Broken Line Data Check Broken Line Approximation without Broken Line Data Check Broken Line Data Check
Moving Average Separate Mantissa and Exponent Combine Real Number Mantissa and Exponent Fixed-length Decimal Text String Conversion Fixed-length Hexadecimal Text String Conversion Hexadecimal Text String-to-Number Conversion Group Fixed-decimal Number-to-Text String Conversion

Function

Page

Swaps the upper byte and lower byte of a 16- 2-404 bit value.

Reverses the sign of a number.

2-405

Sets the specified bit to TRUE and the other 2-407 bits to FALSE in array elements that consist of a maximum of 256 bits.

Finds the position of the highest TRUE bit in array elements that consist of a maximum of 256 bits.

2-410

Counts the number of TRUE bits in a bit string. 2-412

Extracts bit values from the specified position of array elements and outputs them as a bit string.

2-413

Takes the bits from a bit string and outputs them to the specified bit position in array elements.

2-415

Converts a gray code into an angle.

2-417

Converts a UTF-8 text string to a SJIS BYTE 2-422 array.

Converts a SJIS BYTE array to a UTF-8 text 2-424 string.

Performs broken line approximations for inte- 2-426 gers or real numbers along with a check of the validity of the broken line data.

Performs broken line approximations for inte- 2-426 gers or real numbers along without a check of the validity of the broken line data.

Checks whether the X coordinates in the broken line data that is used for a Broken Line Approximation without Broken Line Data Check instruction are in ascending order.
Calculates a moving average.
Separates a real number into the signed mantissa and the exponent.
Combines a signed mantissa and exponent to make a real number.

2-432
2-435 2-441 2-444

Converts an integer to a fixed-length decimal 2-446 text string.

Converts an integer to a fixed-length hexadeci- 2-446 mal text string.

Converts a hexadecimal text string to an inte- 2-449 ger.

Converts a signed fixed-decimal number to a 2-451 decimal text string.

1-10

NJ/NX-series Instructions Reference Manual (W502)

Instruction Set

1 Instruction Set

Type
Conversion Instructions

Instruction StringToFixNum
DtToString

DateToString TodToString

GrayToBin_**

BinToGray_**

StringToAry
AryToString
DispartDigit UniteDigit_** Dispart8Bit
Unite8Bit_**
ToAryByte
AryByteTo
SizeOfAry PackWord PackDword LOWER_BOUND
UPPER_BOUND

Name

Function

Page

Text String-toFixed-decimal Conversion

Converts a decimal text string to a signed fixed-decimal number.

2-453

Date and Time-toText String Conversion

Converts a date and time to a text string.

2-456

Date-to-Text String Conversion
Time of Day-toText String Conversion

Converts a date to a text string. Converts a time of day to a text string.

2-458
1
2-459

Gray Code-to-

Converts a gray code to a bit string.

Binary Code

Conversion Group

2-461

Binary Code-toGray Code Conversion

Converts a bit string to a gray code.

2-461

TextString-to-Array Converts a text string to a BYTE array. Conversion

2-463

Array-to-TextString Converts a BYTE array to a text string. Conversion

2-465

Four-bit Separation Separates a bit string into 4-bit units.

2-467

Four-bit Join Group Joins 4-bit units of data into a bit string.

2-469

Byte Data Separation

Separates a bit string into individual bytes.

2-471

Byte Data Join Group

Joins bytes of data into a bit string.

2-473

Conversion to Byte Separates the value of a variable into bytes

Array

and stores them in a BYTE array.

2-475

Conversion from Byte Array

Joins BYTE array elements and stores the result in a variable.

2-480

Get Number of Array Elements
2-byte Join

Gets the number of elements in an array. Joins two 1-byte data into a 2-byte data.

2-485 2-487

4-byte Join

Joins four 1-byte data into a 4-byte data.

2-489

Get First Number Gets the first number of array dimensions. of Array

2-491

Get Last Number Gets the last number of array dimensions. of Array

2-491

NJ/NX-series Instructions Reference Manual (W502)

1-11

1 Instruction Set

Type
Stack and Table Instructions

Instruction StackPush StackFIFO StackLIFO StackIns

StackDel

RecSearch

RecRangeSearch

RecSort RecNum
RecMax

RecMin

FCS Instructions StringSum StringLRC StringCRCCCITT StringCRC16 AryLRC_** AryCRCCCITT AryCRC16

Name

Function

Page

Push onto Stack Stores a value in a stack.

2-498

First In First Out Removes the bottom value from a stack.

2-507

Last In First Out Removes the top value from a stack.

2-507

Insert into Stack

Inserts a value at a specified position in a stack.

2-510

Delete from Stack Deletes a value from a specified position in a 2-512 stack.

Record Search

Searches an array of structures for elements that match the search key with the specified method.

2-514

Range Record Search

Searches an array of structures for elements 2-519 that match the search condition range with the specified method.

Record Sort

Sorts the elements of an array of structures. 2-524

Get Number of Records

Finds the number of records in an array of structures to the end data.

2-530

Maximum Record Search

Searches the specified member in the struc- 2-532 tures of an array of structures for the maximum value.

Minimum Record Search

Searches the specified member in the struc- 2-532 tures of an array of structures for the minimum value.

Checksum Calculation

Calculates the checksum for a text string.

2-538

Calculate Text String LRC

Calculates the LRC value (horizontal parity). 2-540

Calculate Text

Calculates the CRC-CCITT value using the

String CRC-CCITT XMODEM method.

2-542

Calculate Text String CRC-16

Calculates the CRC-16 value using the MOD- 2-544 BUS method.

Calculate Array LRC Group

Calculates the LRC value for an array

2-546

Calculate Array CRC-CCITT

Calculates the CRC-CCITT value using the XMODEM method.

2-548

Calculate Array CRC-16

Calculates the CRC-16 value using the MOD- 2-550 BUS method.

1-12

NJ/NX-series Instructions Reference Manual (W502)

Instruction Set

1 Instruction Set

Type
Text String Instructions

Instruction CONCAT LEFT

RIGHT

MID

FIND
LEN REPLACE
DELETE INSERT GetByteLen ClearString ToUCase
ToLCase
TrimL
TrimR
AddDelimiter
SubDelimiter

Name

Function

Page

Concatenate String Joins two to five text strings.

2-554

Get String Left

Extracts a text string with the specified number 2-556 of characters from the start (left) of a text string.

Get String Right Extracts a text string with the specified number 2-556

of characters from the end (right) of a text

string.

Get String Any

Extracts a text string with the specified number 2-558

1

of characters from the specified character posi-

tion.

Find String

Searches a specified text string for the position 2-560 of a specified text string.

String Length

Finds the number of characters in a text string. 2-562

Replace String

Replaces part of a text string with another text 2-563 string

Delete String

Deletes all or part of a text string.

2-565

Insert String

Inserts a text string into another text string.

2-567

Get Byte Length Counts the number of bytes in a text string. 2-569

Clear String

Clears a text string.

2-571

Convert to Uppercase

Converts all single-byte letters in a text string 2-573 to uppercase.

Convert to Lowercase

Converts all single-byte letters in a text string 2-573 to lowercase.

Trim String Left

Removes blank space from the beginning of a 2-575 text string.

Trim String Right

Removes blank space from the end of a text string.

2-575

Put Text Strings with Delimiters

Converts the values in a structure to text strings and adds delimiters.

2-577

Get Text Strings Minus Delimiters

Reads delimited data from a text string and stores the results as the values of the members of a structure.

2-588

NJ/NX-series Instructions Reference Manual (W502)

1-13

1 Instruction Set

Type
Time and Time of Day Instructions

Instruction ADD_TIME ADD_TOD_TIME ADD_DT_TIME SUB_TIME SUB_TOD_TIME SUB_TOD_TOD SUB_DATE_DATE SUB_DT_DT SUB_DT_TIME MULTIME DIVTIME CONCAT_DATE_TOD DT_TO_TOD
DT_TO_DATE SetTime GetTime DtToSec DateToSec TodToSec SecToDt
SecToDate SecToTod TimeToNanoSec TimeToSec NanoSecToTime
SecToTime ChkLeapYear GetDaysOfMonth

Name

Function

Page

Add Time

Adds two times.

2-600

Add Time to Time Adds a time to a time of day. of Day

2-602

Add Time to Date Adds a time to a date and time. and Time

2-604

Subtract Time

Subtracts one time from another.

2-606

Subtract Time from Subtracts a time from a time of day. Time of Day

2-608

Subtract Time of Day

Subtracts a time of day from another time of day.

2-610

Subtract Date

Subtracts another date from another date.

2-611

Subtract Date and Subtracts another date and time from another 2-612

Time

date and time.

Subtract Time from Subtracts a time from a date and time. Date and Time

2-614

Multiply Time

Multiplies a time by a specified number.

2-616

Divide Time

Divides a time by a specified number.

2-618

Concatenate Date Combines a date and a time of day. and Time of Day

2-620

Extract Time of

Extracts the time of day from a date and time.

Day from Date and

Time

2-622

Extract Date from Extracts the date from a date and time. Date and Time

2-624

Set Time

Sets the system time.

2-626

Get Time of Day Reads the current time.

2-628

Convert Date and Converts a date and time to the number of sec- 2-630 Time to Seconds onds from 00:00:00 on January 1, 1970.

Convert Date to Seconds

Converts a date to the number of seconds from 2-632 00:00:00 on January 1, 1970.

Convert Time of Day to Seconds

Converts a time of day to the number of sec- 2-633 onds from 00:00:00.

Convert Seconds to Date and Time

Converts the number of seconds from 00:00:00 on January 1, 1970 to a date and time.

2-634

Convert Seconds Converts the number of seconds from

to Date

00:00:00 on January 1, 1970 to a date.

2-636

Convert Seconds Converts the number of seconds from

to Time of Day

00:00:00 to a time of day.

2-638

Convert Time to Nanoseconds

Converts a time to nanoseconds.

2-640

Convert Time to Seconds

Converts a time to seconds.

2-641

Convert Nanoseconds to Time

Converts nanoseconds to a time.

2-642

Convert Seconds Converts seconds to a time. to Time

2-643

Check for Leap Year

Checks for a leap year.

2-645

Get Days in Month Gets the number of days in the specified month.

2-646

1-14

NJ/NX-series Instructions Reference Manual (W502)

1 Instruction Set

Instruction Set

Type

Instruction

Name

Function

Page

Time and Time of Day Instructions

DaysToMonth GetDayOfWeek

Convert Days to Month
Get Day of Week

Calculates the month based on the number of days from January 1.
Gets the day of the week for the specified year, month, and day of month.

2-648 2-650

GetWeekOfYear

Get Week Number Gets the week number for the specified year, 2-652 month, and day of month.

DtToDateStruct

Break Down Date Converts a date and time to the year, month, 2-654

and Time

day, hour, minutes, seconds, and nanosec-

1

onds.

DateStructToDt

Join Time

Joins a year, month, day, hour, minutes, sec- 2-656 onds, and nanoseconds into a date and time.

TruncTime

Truncate Time

Truncates a TIME variable below the specified 2-658 time unit.

TruncDt

Truncate Date and Truncates a DT variable below the specified

Time

time unit.

2-662

TruncTod

Truncate Time of Truncates a TOD variable below the specified 2-666

Day

time unit.

Analog Control PIDAT Instructions

PID Control with Autotuning

Performs PID control with autotuning (2-PID control with set point filter).

2-672

PIDAT_HeatCool

Heating/Cooling PID with Autotuning

Performs heating/cooling PID control with

2-697

autotuning (2-PID control with set point filter).

TimeProportionalOut

Time-proportional Converts a manipulated variable to a time-pro- 2-735

Output

portional output.

LimitAlarm_**

Upper/Lower Limit Alarm Group

Outputs an alarm if the input value is below the 2-752 lower limit set value or above the upper limit set value.

LimitAlarmDv_**

Upper/Lower Deviation Alarm Group

Outputs an alarm if the deviation in the input value from the reference value exceeds the lower deviation set value or the upper deviation set value.

2-756

LimitAlarmDvStbySeq_**

Upper/Lower Deviation Alarm with Standby Sequence Group

Outputs upper and lower deviation alarms with 2-761 a standby sequence.

ScaleTrans

Scale Transforma- Converts input values from an input range to 2-776

tion

an output range.

AC_StepProgram

Step Program

Calculates the present set point and the pre- 2-779 dicted set point every task period according to the specified program pattern.

System Control TraceSamp Instructions

Data Trace Sampling

Performs sampling for a data trace.

2-806

TraceTrig

Data Trace Trigger Generates a trigger for data tracing.

2-809

GetTraceStatus

Read Data Trace Reads the execution status of a data trace. Status

2-812

SetAlarm

Create Userdefined Error

Creates a user-defined error.

2-816

ResetAlarm

Reset Userdefined Error

Resets a user-defined error.

2-821

GetAlarm

Get User-defined Error Status

Gets the highest event level (of user-defined 2-823 error levels 1 to 8) and the highest level event code of the current user-defined errors.

ResetPLCError

Reset PLC Controller Error

Resets errors in the PLC Function Module.

2-825

NJ/NX-series Instructions Reference Manual (W502)

1-15

1 Instruction Set

Type System Control Instructions
Program Control Instructions

Instruction GetPLCError
ResetCJBError GetCJBError
GetEIPError
ResetMCError GetMCError
ResetECError GetECError ResetNXBError GetNXBError
GetNXUnitError
SetInfo ResetUnit GetNTPStatus RestartNXUnit NX_ChangeWriteMode NX_SaveParam NX_ReadTotalPowerOnTime PLC_ReadTotalPowerOnTime PrgStart PrgStop PrgStatus

Name

Function

Page

Get PLC Controller Error Status

Gets the highest level status (partial fault or minor fault) and highest level event code of the current Controller errors in the PLC Function Module.

2-828

Reset CJ Bus Controller Error

Resets a Controller Error in the I/O bus.

2-830

Get I/O Bus Error Status

Gets the highest level status and highest level 2-832 event code of the current Controller errors in the I/O bus of the NJ-series CPU Unit.

Get EtherNet/IP Error Status

Gets the highest level status (partial fault or minor fault) and highest level event code of the current Controller errors in the EtherNet/IP Function Module.

2-834

Reset Motion Control Error

Resets a Controller Error in the Motion Control 2-836 Function Module.

Get Motion Control Error Status

Gets the highest level status (partial fault or minor fault) and highest level event code of the current Controller errors in the Motion Control Function Module.

2-841

Reset EtherCAT Error

Resets a Controller Error in the EtherCAT Mas- 2-843 ter Function Module.

Get EtherCAT Error Status

Detects errors in the EtherCAT Master Func- 2-845 tion Module.

Reset NX Bus Error

Resets the current Controller errors in the NX 2-848 Bus Function Module.

Get NX Bus Error Status

Gets the highest level status of all current Con- 2-850 troller errors in the NX Bus Function Module of the NX-series CPU Unit.

Get NX Unit Error Status

Gets the highest level status and highest level event code of the current Controller errors in the NX Bus Function Module of the NX-series CPU Unit or NX Units.

2-852

Create User-

Creates user-defined information.

defined Information

2-860

Restart Unit

Restarts a CPU Bus Unit or Special I/O Unit. 2-862

Read NTP Status Reads the NTP status.

2-866

Restart NX Unit Restarts an EtherCAT Coupler Unit or NX Unit. 2-868

Change to NX Unit Changes an EtherCAT Coupler Unit or NX Unit 2-874

Write Mode

to a mode that allows writing data.

Save NX Unit Parameters

Saves the data that was written to an EtherCAT Coupler Unit or NX Unit.

2-879

Read NX Unit Total Reads the total power ON time from a Commu- 2-885 Power ON Time nications Coupler Unit or NX Unit.

Read PLC Total Power ON Time

Reads the total power ON time from a speci- 2-893 fied CPU Unit.

Enable Program

Enables the execution of the specified program.

2-898

Disable Program Disables execution of the specified program. 2-907

Read Program Sta- Reads the status of the specified program. tus

2-927

1-16

NJ/NX-series Instructions Reference Manual (W502)

Instruction Set

1 Instruction Set

Type

Instruction

Name

Function

Page

EtherCAT Communications Instructions

EC_CoESDOWrite EC_CoESDORead

Write EtherCAT CoE SDO
Read EtherCAT CoE SDO

Writes a value to a CoE object of a specified slave on the EtherCAT network.
Reads a value from a CoE object of a specified slave on the EtherCAT network.

2-934 2-937

EC_StartMon

Start EtherCAT Packet Monitor

Starts packet monitoring for EtherCAT commu- 2-942 nications.

EC_StopMon

Stop EtherCAT Packet Monitor

Stops execution of packet monitoring for Ether- 2-948 CAT communications.

1

EC_SaveMon

Save EtherCAT Packets

Saves EtherCAT communications packet data 2-950 to an internal file in the main memory of the CPU Unit.

EC_CopyMon

Transfer EtherCAT Transfers packet data in an internal file in the 2-952

Packets

main memory of the CPU Unit to a SD Memory

Card.

EC_DisconnectSlave

Disconnect EtherCAT Slave

Disconnects the specified slave from the Eth- 2-954 erCAT network.

EC_ConnectSlave

Connect EtherCAT Connects the specified slave to the EtherCAT 2-961

Slave

network.

EC_ChangeEnableSet- Enable/Disable

ting

EtherCAT Slave

Enables or disables an EtherCAT slave.

2-963

NX_WriteObj

Write NX Unit Object

Writes data to an NX object in an EtherCAT Coupler Unit or NX Unit.

2-980

NX_ReadObj

Read NX Unit Object

Reads data from an NX object in an EtherCAT 2-995 Coupler Unit or NX Unit.

IO-Link Commu- IOL_ReadObj

nications

Instruction

IOL_WriteObj

Read IO-Link Device Object
Write IO-Link Device Object

Reads data from IO-Link device objects. Writes data to IO-Link device objects.

2-1006 2-1015

NJ/NX-series Instructions Reference Manual (W502)

1-17

1 Instruction Set

Type
EtherNet/IP Communications Instructions

Instruction CIPOpen
CIPOpenWithDataSize
CIPRead
CIPWrite
CIPSend CIPClose CIPUCMMRead
CIPUCMMWrite
CIPUCMMSend SktUDPCreate SktUDPRcv SktUDPSend SktTCPAccept SktTCPConnect SktTCPRcv SktTCPSend SktGetTCPStatus SktClose SktClearBuf
SktSetOption ModbusTCPCmd ModbusTCPRead ModbusTCPWrite

Name

Function

Page

Open CIP Class 3 Connection (Large_Forward_O pen)

Opens a CIP class 3 connection (Large_Forward_Open) with the specified remote node. The data length is set to 1,994 bytes.

2-1026

Open CIP Class 3 Connection with Specified Data Size

Opens a CIP class 3 connection with the spec- 2-1035 ified remote node that allows class 3 explicit messages of the specified data length or shorter to be sent and received.

Read Variable Class 3 Explicit

Uses a class 3 explicit message to read the value of a variable in another Controller on a CIP network.

2-1039

Write Variable Class 3 Explicit

Uses a class 3 explicit message to write the value of a variable in another Controller on a CIP network.

2-1045

Send Explicit

Sends a class 3 CIP message to a specified

Message Class 3 device on a CIP network.

2-1051

Close CIP Class 3 Closes the CIP class 3 connection to the spec- 2-1056

Connection

ified handle.

Read Variable UCMM Explicit

Uses a UCMM explicit message to read the 2-1059 value of a variable in another Controller on the specified CIP network.

Write Variable UCMM Explicit

Uses a UCMM explicit message to write the value of a variable in another Controller on a CIP network.

2-1064

Send Explicit Message UCMM

Sends a UCMM CIP message to a specified device on a CIP network.

2-1071

Create UDP Socket

Creates a UDP socket request to open a servo 2-1081 port for the built-in EtherNet/IP.

UDP Socket Receive

Reads the data from the receive buffer for a UDP socket for the built-in EtherNet/IP.

2-1089

UDP Socket Send Sends data from a UDP port for the built-in EtherNet/IP.

2-1092

Accept TCP Socket

Requests accepting a TCP socket for the built- 2-1095 in EtherNet/IP.

Connect TCP Socket

Connects to a remote TCP port from the built- 2-1098 in EtherNet/IP.

TCP Socket Receive

Reads the data from the receive buffer for a TCP socket for the built-in EtherNet/IP.

2-1107

TCP Socket Send Sends data from a TCP port for the built-in Eth- 2-1110 erNet/IP.

Read TCP Socket Reads the status of a TCP socket. Status

2-1113

Close TCP/UDP Socket

Closes the specified TCP or UDP socket for the built-in EtherNet/IP.

2-1116

Clear TCP/UDP Socket Receive Buffer

Clears the receive buffer for the specified TCP 2-1119 or UDP socket for the built-in EtherNet/IP.

Set TCP Socket Option

Sets the option for TCP socket specified for the 2-1122 built-in EtherNet/IP.

Send Modbus TCP Sends general commands using Modbus-TCP 2-1127 General Command protocol.

Send Modbus TCP Reads data that is requested by sending read 2-1135 Read Command commands using Modbus-TCP protocol.

Send Modbus TCP Sends write commands using Modbus-TCP Write Command protocol.

2-1143

1-18

NJ/NX-series Instructions Reference Manual (W502)

1 Instruction Set

Instruction Set

Type

Instruction

Name

Function

Page

EtherNet/IP Communications Instructions

ChangeIPAdr ChangeFTPAccount

Change IP Address
Change FTP Account

Changes the IP address of the built-in Ether- 2-1151 Net/IP port or the IP address of an EtherNet/IP Unit.
Changes the FTP login name and password of 2-1159 the built-in EtherNet/IP port or those of an EtherNet/IP Unit.

ChangeNTPServerAdr Change NTP

Changes the address of the NTP server of the 2-1163

Server Address

built-in EtherNet/IP port or the address of an

1

EtherNet/IP Unit.

FTPGetFileList

Get FTP Server File List

Gets a list of the files in the FTP server.

2-1167

FTPGetFile

Get File from FTP Downloads a file from the FTP server. Server

2-1184

FTPPutFile

Put File onto FTP Uploads a file to the FTP server. Server

2-1193

FTPRemoveFile

Delete FTP Server Deletes a file from the FTP server. File

2-1204

FTPRemoveDir

Delete FTP Server Deletes a directory from the FTP server. Directory

2-1214

Serial Communications Instructions

ExecPMCR

Protocol Macro

Requests execution of a communications

2-1220

sequence (protocol data) registered in a Serial

Communications Unit.

SerialSend

SCU Send Serial Sends data in No-protocol Mode from a serial 2-1233 port on a Serial Communications Unit.

SerialRcv

SCU Receive Serial

Receives data in No-protocol Mode from a serial port on a Serial Communications Unit. It then clears the receive buffer after reading the data.

2-1244

SerialRcvNoClear

SCU Receive Serial without Receive Buffer Clear

Receives data in No-protocol Mode from a serial port on a Serial Communications Unit. It does not clear the receive buffer after reading the data.

2-1244

SendCmd

Send Command

Uses a serial gateway and sends a command to a Serial Communications Unit. Or, sends an explicit command to a DeviceNet Unit or CompoNet Master Unit.

2-1259

NX_SerialSend

Send No-protocol Data

Sends data in No-protocol Mode from a serial port on an NX-series Communications Interface Unit or Option Board.

2-1272

NX_SerialRcv

Receive Noprotocol Data

Reads data in No-protocol Mode from a serial port on an NX-series Communications Interface Unit or Option Board.

2-1285

NX_ModbusRtuCmd

Send Modbus RTU General Command

Sends general commands from a serial port on an NX-series Communications Interface Unit or Option Board to Modbus-RTU slaves using Modbus-RTU protocol.

2-1299

NX_ModbusRtuRead

Send Modbus RTU Read Command

Sends read commands from a serial port on an NX-series Communications Interface Unit or Option Board to Modbus-RTU slaves using Modbus-RTU protocol.

2-1310

NX_ModbusRtuWrite

Send Modbus RTU Write Command

Sends write commands from a serial port on an NX-series Communications Interface Unit or Option Board to Modbus-RTU slaves using Modbus-RTU protocol.

2-1322

NJ/NX-series Instructions Reference Manual (W502)

1-19

1 Instruction Set

Type Serial Communications Instructions
SD Memory Card Instructions
Time Stamp Instructions

Instruction NX_SerialSigCtl
NX_SerialSigRead NX_SerialStatusRead NX_SerialBufClear NX_SerialStartMon NX_SerialStopMon FileWriteVar
FileReadVar
FileOpen FileClose FileSeek FileRead FileWrite FileGets FilePuts FileCopy FileRemove FileRename DirCreate DirRemove BackupToMemoryCard NX_DOutTimeStamp
NX_AryDOutTimeStamp

Name Serial Control Signal ON/OFF Switching Read Serial Control Signal Read Serial Port Status Clear Buffer Start Serial Line Monitoring Stop Serial Line Monitoring Write Variable to File
Read Variable from File
Open File
Close File
Seek File
Read File
Write File
Get Text String
Put Text String
Copy File
Delete File
Change File Name
Create Directory
Delete Directory
SD Memory Card Backup Write Digital Output with Specified Time Stamp Write Digital Output Array with Specified Time Stamp

Function

Page

Turns ON or OFF the ER or RS signal of a serial port on an NX-series Communications Interface Unit or Option Board.

2-1334

Reads the CS or DR signal of a serial port on 2-1343 an Option Board.

Reads the status of a serial port on an Option 2-1348 Board.

Clears the send or receive buffer.

2-1353

Starts serial line monitoring of an NX-series Communications Interface Unit.

2-1363

Stops serial line monitoring of an NX-series Communications Interface Unit.

2-1368

Writes the value of a variable to the specified file in the SD Memory Card. The value is written in binary format.

2-1374

Reads the contents of the specified file on the 2-1379 SD Memory Card as binary data and writes it to a variable.

Opens the specified file in the SD Memory Card.

2-1384

Closes the specified file in the SD Memory Card.

2-1388

Sets a file position indicator in the specified file 2-1391 in the SD Memory Card.

Reads the data from the specified file in the SD 2-1395 Memory Card.

Writes data to the specified file in the SD Mem- 2-1403 ory Card.

Reads a text string of one line from the speci- 2-1411 fied file in the SD Memory Card.

Writes a text string to the specified file in the 2-1419 SD Memory Card.

Copies the specified file in the SD Memory Card.

2-1428

Deletes the specified file from the SD Memory 2-1437 Card.

Changes the name of the specified file or directory in the SD Memory Card.

2-1442

Creates a directory with the specified name in 2-1447 the SD Memory Card.

Deletes the specified directory from the SD Memory Card.

2-1450

Backs up data to an SD Memory Card.

2-1453

Writes a value to the output bit of a Digital Out- 2-1470 put Unit that supports time stamp refreshing.

Outputs pulses from a Digital Output Unit that 2-1476 supports time stamp refreshing.

1-20

NJ/NX-series Instructions Reference Manual (W502)

Instruction Set

1 Instruction Set

Type

Instruction

Name

Function

Page

Other Instructions

ReadNbit_** WriteNbit_**

N-bit Read Group Reads zero or more bits from a bit string. N-bit Write Group Writes zero or more bits to a bit string.

2-1486 2-1488

ChkRange

Check Subrange Variable

Determines if the value of a variable is within 2-1490 the valid range of the range type specification.

GetMyTaskStatus

Read Current Task Reads the status of the current task. Status

2-1492

GetMyTaskInterval

Read Current Task Reads the task period of the current task. Period

2-1495

1

Task_IsActive

Determine Task Status

Determines if the specified task is currently in 2-1498 execution.

Lock

Lock Tasks

Starts an exclusive lock between tasks. Execu- 2-1500 tion of any other task with a lock region with the same lock number is disabled.

Unlock

Unlock Tasks

Stops an exclusive lock between tasks.

2-1500

ActEventTask

Activate Event Task

Activates an event task.

2-1507

Get**Clk

Get Clock Pulse Group

Outputs a clock pulse at the specified cycle.

2-1513

Get**Cnt

Get Incrementing Free-running Counter Group

Gets the values of free-running counters of the 2-1514 specified cycle.

· Refer to the NJ/NX-series Motion Control Instructions Reference Manual (Cat. No. W508) for the specifications of the motion control instructions.
· Refer to the Sysmac Studio Version 1 Operation Manual (Cat. No. W504) for the specifications of the simulation instructions.

NJ/NX-series Instructions Reference Manual (W502)

1-21

1 Instruction Set

1-22

NJ/NX-series Instructions Reference Manual (W502)

2
Instruction Descriptions
This section describes the specifications of the instructions that you can use with NJ/NX-series Controllers.

Using this Section . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3 Ladder Diagram Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-15 ST Statement Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-25 Sequence Input Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-43 Sequence Output Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-49 Sequence Control Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-65 Comparison Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-91 Timer Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-125 Counter Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-145 Math Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-165 BCD Conversion Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-241 Data Type Conversion Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-261 Bit String Processing Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-319 Selection Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-331 Data Movement Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-353 Shift Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-387 Conversion Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-403 Stack and Table Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-497 FCS Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-537 Text String Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-553 Time and Time of Day Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-599 Analog Control Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-671 System Control Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-805 Program Control Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-897 EtherCAT Communications Instructions . . . . . . . . . . . . . . . . . . . . . . . . . 2-933 IO-Link Communications Instruction . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1005

NJ/NX-series Instructions Reference Manual (W502)

2-1

2 Instruction Descriptions
EtherNet/IP Communications Instructions . . . . . . . . . . . . . . . . . . . . . . . 2-1025 Serial Communications Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1219 SD Memory Card Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1373 Time Stamp Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1469 Other Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1485

2-2

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Using this Section

Using this Section

The notation used to describe instructions in this section is explained below.

Items

The following items are provided.

Item

Description

Instruction

The instruction word is given.

2

Example: MoveBit

Name

The name of the instruction is given. Example: Move Bit

Items

FB/FUN

Whether the instruction is a function block (FB) instruction or a function (FUN) instruction is given. You can call FB instructions only from programs and function blocks. You can call FUN instructions from programs, function blocks, and functions.

Graphic expression The figure that represents the instruction in a ladder diagram is given.

Example for a FUN Instruction

Example for a FB Instruction

Instruction option Instruction word

Instance specification

Input variable name (@)MoveBit

Output variable name

Upward differentiation AryShiftReg_instance specification

AryShiftReg

In-out variable name

EN In InPos InOut

ENO

Shift Reset In InOut

ENO

ST expression

InOutPos

Size

The instruction option, upward differentiation specification, and instance specification are described below.
Instruction option: Support for the instruction option is indicated by "(@)" before the FUN instruction. If support for the instruction option is indicated, you can place "@" before the instruction word to specify upward differentiation. An instruction for which upward differentiation is specified is executed when the value of the EN input variable was FALSE in the previous task period and is TRUE in the current task period.
Upward differentiation specification: This is indicated by the arrow pointing into the instruction at the entry point of the input variable. Instructions with this specification operate as upwardly differentiated instructions.
Instance specification: An instance of an instruction is indicated by "XX_instance" above an FB instruction. You must assign an instance name to any instance of an instruction that you specify.
The notation that represents the instruction in ST is given.
There are two ways that you can use to code an instruction in ST. These are described below.
1. Directly Specifying the Correspondence between the Parameters and the Input, Output, and InOut Variables Example: MoveBit(In:=abc, InPos:=def, InOut:=ghi, InOutPos:=jkl);
2. Specifying Only the Parameters and Omitting the Input, Output, and In-Out Variables Example: MoveBit(In, InPos, InOut, InOutPos);
Method 2 is used in this section.
You must assign an instance name to any instruction that is given as "XX_instance(variable_name)."
Example: TON_instance (In, PT, Q, ET);

NJ/NX-series Instructions Reference Manual (W502)

2-3

2 Instruction Descriptions

Item Variables
Function Related Systemdefined Variables Related Semi-userdefined Variables Additional Information Precautions for Correct Use Sample Programming

Description

· Name The input variables, output variables, and in-out variables are given. Example: In1 However, variables that are used by many instructions are not given on the pages that describe individual instructions. The following eight variables are commonly used. The specifications of these variables are given later. (EN, ENO, Execute, Done, Busy, Error, ErrorID, and ErrorIDEx)
· Meaning The name of the variable is given. Example: Up-counter
· I/O Whether the variable is an input variable, output variable, or in-out variable is given.
· Description The meaning of the variable and any restrictions are given.
· Valid range The range that the variable can take is given. "Depends on data type" indicates that the valid range of the variable depends on the data type that you use. The valid ranges of the data types are given later in this section.
· Unit The unit of the value that is specified with the variable is given. "---" indicates that there is no unit. Example: Bytes
· Default The specified default value is automatically used for the variable if you do not assign a parameter to the instruction before it is executed. "---" indicates the following:

Input variables:

The default value of the data type of the input variable is assigned. The default values of the data types are given later in this section. If the input variable is a structure, the default value is given in the specifications of the structure in the description of the function of the instruction.

Output variables: Default values are not set.

In-out variables: Default values are not set.

· Data type The data type of the variable is given. The use of enumerations, arrays, structures, and unions is also given.

The function of the instruction is described. Variable names are given in italic text. Example: In1 Array names are followed by "[]". Example: InOut[]

The system-defined variables that are related to the instruction are given. Refer to the NJ/NXseries CPU Unit Software User's Manual (Cat. No. W501) or NY-series Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for details on system-defined variables.

The semi-user-defined variables and variable names that are related to the instruction are given. Refer to the specified manuals for details on semi-user-defined variables.

Additional information on the function of the instruction is provided. This includes related instructions and helpful information for application of the instruction.

Precautions for application of the instruction are given. The conditions under which errors occur for the instruction are also given here.

Short samples of how to use the instruction in an application program are provided. The ladder diagram and ST for the same process are shown.

Common Variables
The specifications of variables that are used for many instructions (EN, ENO, Execute, Done, Busy, Error, ErrorID, and ErrorIDEx) are described below. These variables are not described in the tables of variables for individual instructions. Check the graphic or ST expression for the instruction to see if an instruction uses these variables.

2-4

NJ/NX-series Instructions Reference Manual (W502)

Using this Section

2 Instruction Descriptions

EN

EN is an input variable that gives the execution condition for a FUN instruction. When you use a FUN instruction in a ladder diagram, connect the execution condition to EN.

Name Meaning

I/O

Description

Data type

Valid range Default

EN Enable (Execu- Input tion Condition)

TRUE: Instruction is executed.*

BOOL

FALSE: Instruction is not executed.

TRUE or FALSE

TRUE

* If upward differentiation (@) is specified as an instruction option, the execution condition is when the value of EN changes

from FALSE to TRUE. If downward differentiation (%) is specified as an instruction option, the execution condition is when

the value of EN changes from TRUE to FALSE.

· FB instructions do not have an EN input variable.

2

· When you call a FUN instruction from structured text, omit the EN input variable. The EN input variable is not required in structured text because the execution condition for the instruction is determined by the operation sequence.

Common Variables

ENO

The ENO output variable passes the execution to the next instruction in a ladder diagram. Normally, when instruction execution is completed, the value of ENO changes to TRUE. Execution of the next instruction is then started.

Name Meaning

I/O

ENO Enable Output Output

Description
TRUE: Normal end.*
FALSE: Error end, execution in progress, or execution condition not met.

Data type BOOL

Valid range
TRUE or FALSE

Default ---

* ENO is TRUE only while the execution condition is met. The value of ENO changes to FALSE when the execution condition is no longer met after a normal end.
· Most FUN instructions and FB instructions have ENO output variables. There are, however, some instructions that do not have an ENO output variable.
· Omit the ENO output variable in structured text. The ENO output variable is not required in structured text because the execution condition for the next instruction is determined by the operation sequence.

Execute, Done, and Busy
Execute is an input variable that gives the execution condition for some FB instructions. Instruction execution starts when Execute changes to TRUE. After Execute changes to TRUE, execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the instruction execution time exceeds the task period.

NJ/NX-series Instructions Reference Manual (W502)

2-5

2 Instruction Descriptions

Done is an output variable that shows the completion of execution for some FB instructions. Busy is an output variable that shows that instruction execution is in progress for some FB instructions.

Name Execute

Meaning Execute

I/O Input

Done

Done

Busy

Busy

Output

Description
TRUE: Instruction is executed.*1 FALSE: Instruction is not executed.*2
TRUE: Normal end.*3*4 FALSE: Error end, execution in
progress, or execution condition not met.
TRUE: Execution processing is in progress.
FALSE: Execution processing is not in progress.

Data type BOOL
BOOL

Valid range TRUE or FALSE
TRUE or FALSE

Initial value FALSE
---

*1 If the value of Execute is already TRUE when Controller operation starts, the instruction is not executed. To execute the instruction in that case, first change the value of Execute to FALSE.
*2 Processing is completed to the end even if Execute changes to FALSE during execution.
*3 The value of Done changes to FALSE when the execution condition is no longer met after a normal end.
*4 If the execution condition is no longer met when a normal end occurs, the value of Done is TRUE for one task period and it then changes to FALSE.

Timing charts are given below for instructions that have EN and ENO variables (i.e., instructions that are completed in one task period) and for instructions that have Execute and Busy variables (i.e., instructions that are processed over more than one task period).

 Instructions Completed in One Task Period

Task period Task period Task period Task period

EN

TRUE

FALSE

Instruction

Instruction

Instruction

Instruction

executed.

executed.

executed.

executed.

ENO

TRUE FALSE

Processing of the instruction is

Processing of the instruction is

started because EN is TRUE.

not started because EN is FALSE.

The execution condition is not ENO changes to TRUE when met, so ENO changes to FALSE. processing of the instruction

is completed normally.

Processing of the instruction is started because EN is TRUE. The execution condition is met, so ENO remains TRUE.

2-6

NJ/NX-series Instructions Reference Manual (W502)

Using this Section

2 Instruction Descriptions

 Instructions Processed over More Than One Task Period

Task Task period period

Task period

Task period

Task Task period period

Task Task period period

Execute TRUE FALSE

Instruction Instruction Instruction Instruction Instruction Instruction Instruction Instruction executed. executed. executed. executed. executed. executed. executed. executed.

Busy

TRUE FALSE

Done

TRUE FALSE

2

Processing of the instruction is started because Execute is TRUE. Busy changes to TRUE and Done changes to FALSE.

Busy changes to FALSE and

Even if Execute changes to

Done changes to TRUE when

FALSE during processing of

processing of the instruction

the instruction, Busy remains

is completed normally.

TRUE until processing of the

Execute is FALSE, so instruction is completed.

Done changes to FALSE.

Execute is FALSE at the end of processing, so Done is TRUE for one task period and then it changes to FALSE.

Common Variables

Error, ErrorID, and ErrorIDEx

Error, ErrorID, and ErrorIDEx are output variables that show that an error occurred in the execution of some FB instructions.

Name

Meaning

I/O

Error

Error

ErrorID

Error code

Output

ErrorIDEx Expansion error code

Description

Data type

TRUE: Error end.*1*2

BOOL

FALSE: Normal end, execution in progress, or execution condition not met.

This is the error ID for an error end. WORD

The value is WORD#16#0 for a normal end.

This is the error ID for an Expan- DWORD sion Unit Hardware Error.

The value is DWORD#16#0 for a normal end.

Valid range

Initial value

TRUE or FALSE

---
Depends on the instruction.

*1 The value of Error changes to FALSE when the execution condition is no longer met after an error end.
*2 If the execution condition is no longer met when an error end occurs, the value of Error is TRUE for one task period and it then changes to FALSE.

Refer to A-1 Error Codes That You Can Check with ErrorID for a list of the error codes that you can check with ErrorID and the NJ/NX-series Troubleshooting Manual (Cat. No. W503) for the meanings of the error codes.

NJ/NX-series Instructions Reference Manual (W502)

2-7

2 Instruction Descriptions

Timing charts are provided below for Execute, Done, Busy, Error, ErrorID, and ErrorIDEx.

 Normal End

Execute Busy Done

TRUE FALSE
TRUE FALSE
TRUE FALSE

One task period

Error

TRUE FALSE

ErrorID

ErrorIDEx

Execution starts when Execute changes to TRUE. Busy changes to TRUE, Done changes to FALSE, and Error changes to FALSE.

Execute is FALSE at the end of execution, so Done is TRUE for one task period and then changes to FALSE.

Instruction processing continues to the end even if Execute changes to FALSE during execution (when Busy is TRUE).

Normal end. Busy changes to FALSE and Done changes to TRUE. Error does not change (remains FALSE).

Execute changed to FALSE, so Done changes to FALSE.

2-8

NJ/NX-series Instructions Reference Manual (W502)

Using this Section

2 Instruction Descriptions

 Error End

Execute Busy Done

TRUE FALSE
TRUE FALSE
TRUE FALSE

Error

TRUE FALSE

ErrorID

ErrorIDEx

One task period
2

Valid Ranges and Default Values of Variables

Execution starts when Execute changes to TRUE. Busy changes to TRUE, Done changes to FALSE, Error changes to FALSE, ErrorID changes to WORD#16#0, and ErrorIDEx changes to DWORD#16#0.

Execute is FALSE at the end of execution, so Error is TRUE for one task period and then changes to FALSE.
Instruction processing continues to the end even if Execute changes to FALSE during execution (when Busy is TRUE).

Execute changed to FALSE, so Error changes to FALSE. ErrorID and ErrorIDEx do not change.
Error end. Busy changes to FALSE and Error changes to TRUE. Done does not change (remains FALSE). ErrorID and ErrorIDEx output error IDs.

Valid Ranges and Default Values of Variables

The valid range of a variable indicates the range of values that variable can take. The default value of a variable indicates the value that is assigned to an input variable when the instruction is executed without a parameter assigned to the input variable. These values are defined for each data type. If specific values are not given for an instruction, then the valid ranges and default values of the data types are applied. These variables are indicated by "depends on data type" in the valid range column and by "---" in the input variable default column. The valid ranges and default values of the data types are given in the following tables.

Classification
Boolean

Data type
BOOL

TRUE or FALSE

Valid range

FALSE

Default

Bit string

BYTE WORD DWORD LWORD

BYTE#16#00 to FF WORD#16#0000 to FFFF DWORD#16#00000000 to FFFFFFFF LWORD#16#0000000000000000 to FFFFFFFFFFFFFFFF

BYTE#16#00 WORD#16#0000 DWORD#16#0000_0000 LWORD#16#0000_0000_0000_0000

NJ/NX-series Instructions Reference Manual (W502)

2-9

2 Instruction Descriptions

Classification
Integers

Data type USINT UINT UDINT ULINT SINT INT DINT LINT

REAL

Real numbers LREAL

TIME

DATE

Times, durations, dates, and text strings

TOD DT

STRING

Valid range

Default

USINT#0 to +255

USINT#0

UINT#0 to +65535

UINT#0

UDINT#0 to +4294967295

UDINT#0

ULINT#0 to +18446744073709551615

ULINT#0

SINT#-128 to +127

SINT#0

INT#-32768 to +32767

INT#0

DINT#-2147483648 to +2147483647

DINT#0

LINT#-9223372036854775808 to +9223372036854775807

LINT#0

REAL#-3.402823e+38 to -1.175495e-38,

REAL#0

0,

+1.175495e-38 to +3.402823e+38, +/-

LREAL#-1.79769313486231e+308 to -2.22507385850721e-308,

LREAL#0

0,
+2.22507385850721e-308 to +1.79769313486231e+308,

+/-

T#-9223372036854.775808ms
(T#-106751d_23h_47m_16s_854.775808ms) to T#9223372036854.775807ms

T#0s

(T#+106751d_23h_47m_16s_854.775807ms)

D#1970-01-01 to D#2106-02-06

D#1970-01-01

(January 1, 1970 to February 6, 2106)

TOD#00:00:00.000000000 to TOD#23:59:59.999999999

TOD#00:00:00.000000000

(0:00 and 0.000000000 to 23:59 and 59.999999999 seconds)

DT#1970-01-01-00:00:00.000000000 to DT#2106-02- DT#1970-01-01-00:00:00.000000000 06-23:59:59.999999999

(0:00 and 0.000000000 on January 1, 1970 to 23:59 and 59.999999999 seconds on February 6, 2106)

Character code: UTF-8

''

0 to 1,986 bytes (1,985 single-byte alphanumeric characters plus the final NULL character)

2-10

NJ/NX-series Instructions Reference Manual (W502)

Using this Section

2 Instruction Descriptions

Derivative Data Types (Enumerations, Structures, and Unions)
Variables that use derivative data types (enumerations, structures, and unions) are specified as such in the tables of variable data types. The notation is described below.

Enumerations

The data type for an enumerated variable is given within the table. The following is an example. Here, the data type of the Out variable is enumerated type _eDAYOFWEEK. The enumerators are described in the description of the function of the instruction.

Bit strings

Integers

2
Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

Derivative Data Types (Enumerations, Structures, and Unions)

In

OK

OK

Out

Refer to Function for the enumerators of the enumerated type _eDAYOFWEEK.

Structures and Unions
The data type for a structure or union variable is given within the table. The following is an example. Here, the data type of the In1 variable is structure _sPORT. Details on the members of a structure or union are given in the description of the function of the instruction.

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In1

Refer to Function for details on the structure _sPORT.

The tables also indicate any variables for which you can specify a structure, a structure member, a union, or a union member as the parameter. In the following example, you can specify a parameter with a basic data type, or you can specify a structure, a structure member, a union, or a union member for the In1 variable. To specify a structure or union, specify only the structure or the union as the parameter. To specify a structure member or a union member, specify the member as the parameter.

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In1

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK

A structure, structure member, union, or union member can also be specified.

NJ/NX-series Instructions Reference Manual (W502)

2-11

2 Instruction Descriptions

Array Specifications
Array variable names are followed by "[]" and "(array)" is specified. For these variables, specify an element of the array (i.e., specify the subscript) as the parameter. An example is shown below. Here, the table shows that In1[] is a BYTE array.

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In1[] (array)

OK

The data type table indicates the arrays for which structures and unions can be used as elements, as shown in the following example. For these variables, specify an element of the array (i.e., specify the subscript) as the parameter.

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In1[] (array)

Arrays of structures or unions can also be specified.

The table indicates any variables for which you can specify either an array or an array element as the parameter. In the following example, you can specify a parameter with a basic data type, or you can specify an array or an array element. To specify an array, specify only the array as the parameter. To specify an array element, specify an element of the array (i.e., specify the subscript) as the parameter.

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In1

An array or array element can also be specified.

2-12

NJ/NX-series Instructions Reference Manual (W502)

Using this Section

2 Instruction Descriptions

Others

Errors Detected for All Instructions

The errors that can occur for an instruction are given in the Precautions for Correct Use section. The following three errors, however, can be detected for any instruction. They are not listed in the Precautions for Correct Use sections.

· Reading or writing elements that exceed the range of an array variable. Example: Setting a[4] for an input variable for the array variable a[0..3].

· Passing parameters that are not variables to instructions for which array variables are defined for

input, output, or in-out variables.

2

· Assigning a text string that is longer than the defined number of bytes to a STRING variable.

· Assigning a text string that does not end in a NULL character to a STRING variable.

· Dividing an integer variable by 0.

Others

Precautions for All Instructions
The amount of processing that is required for some instructions depends on the parameters that you connect. If there is too much processing, the instruction execution time increases and the task period may be exceeded. This will result in a Task Period Exceeded error. Adjust the amount of processing to a suitable amount.

NJ/NX-series Instructions Reference Manual (W502)

2-13

2 Instruction Descriptions

2-14

NJ/NX-series Instructions Reference Manual (W502)

Ladder Diagram Instructions

2
Ladder Diagram Instructions

Instruction LD and LDN AND and ANDN OR and ORN Out and OutNot

Name
Load/ Load NOT
AND/ AND NOT
OR/ OR NOT
Output/ Output NOT

Page 2-16 2-18 2-20 2-22

NJ/NX-series Instructions Reference Manual (W502)

2-15

2 Instruction Descriptions

LD and LDN

LD: Reads the value of a BOOL variable. LDN: Reads the inverse of the value of a BOOL variable.

Instruction LD

Name Load

FB/FUN ---

Graphic expression

Variable Variable

Variable

ST expression None

LDN

Load NOT

---

Upward differentiation
Variable Variable

Downward differentiation
Variable

None

Upward

Downward

differentiation differentiation

Variables
None

Function

 LD
The LD instruction reads the value of the specified BOOL variable and outputs it to the next instruction. If the value of the specified variable is TRUE, then TRUE is output. If the value is FALSE, then FALSE is output. Use the LD instruction for the first NO bit from the bus bar or for the first NO bit of a logic block.

 LDN

The LD instruction reads the inverse of the value of the specified BOOL variable and outputs it to the next instruction. If the value of the specified variable is TRUE, then FALSE is output. If the value is FALSE, then TRUE is output. Use the LDN instruction for the first NC bit from the bus bar or for the first NC bit of a logic block.
The operation is as shown below if you do not specify upward or downward differentiation.

Instruction

Value of variable

Output value

TRUE

TRUE

LD

FALSE

FALSE

TRUE

FALSE

LDN

FALSE

TRUE

2-16

NJ/NX-series Instructions Reference Manual (W502)

Ladder Diagram Instructions

2 Instruction Descriptions

If you specify upward or downward differentiation, the operation depends on the following: the value of the variable the last time the instruction was executed and the current value of the variable. This is shown below.

Instruction

Differentiation specification

Value of variable at last execution and current value of variable

Output value

FALSE at the last execution  Currently TRUE

TRUE

Upward differentiation

Other than the above.

FALSE

LD

Downward differentia- TRUE at the last execution  Currently FALSE

TRUE

tion

Other than the above.

FALSE

FALSE at the last execution  Currently TRUE

FALSE

Upward differentiation

LDN

Downward differentia-

Other than the above. TRUE at the last execution  Currently FALSE

TRUE FALSE

2

tion

Other than the above.

TRUE

LD and LDN

The following figure shows a programming example and timing chart.

A

TRUE FALSE

A

B1

B1

TRUE FALSE

A

B2

B2 TRUE

FALSE

A

B3 TRUE



B3 FALSE

A

B4 TRUE



B4 FALSE

 A

B5 B5 TRUE

FALSE

A

B6

TRUE

B6 FALSE

Instruction execution
Precautions for Correct Use
· An error occurs in the following case and the output value from the last execution is retained. · You specify an array element for the variable value and the element does not exist. Example: A BOOL array a[0..5] is defined, but the instruction is executed using a[10] as the variable.
· Do not use these instructions as the rightmost instruction on a rung. If you do, an error occurs on the Sysmac Studio and you cannot transfer the user program to the Controller.

NJ/NX-series Instructions Reference Manual (W502)

2-17

2 Instruction Descriptions

AND and ANDN

AND: ANDN:

Takes the logical AND of the value of a BOOL variable and the execution condition.
Takes the logical AND of the inverse of the value of a BOOL variable and the execution condition.

Instruction Name

AND

AND

FB/FUN ---

Graphic expression Variable

ST expression
result:=vBool1 AND vBOOL2; result:=vBool1 & vBool2;

ANDN

AND NOT ---

Variable

Variable

Upward

Downward

differentiation differentiation

Variable

result:=vBool1 AND NOT vBool2;

Variable

Variable

Upward

Downward

differentiation differentiation

Variables
None

Function

 AND
The AND instruction takes the logical AND of the value of a specified BOOL variable and the execution condition and outputs it to the next instruction. Use the AND instruction for a NO bit connected in series with the previous instruction.

 ANDN
The ANDN instruction takes the logical AND of the inverse of the value of a specified BOOL variable and the execution condition and outputs it to the next instruction. Use the ANDN instruction for a NC bit connected in series with the previous instruction.
The following figure shows a programming example of the AND instruction. It takes the logical AND of variable A and variable B and outputs it to variable C.

A

B

C

LD

AND

Out

instruction instruction instruction

A B

C

It takes the logical AND of variable A and variable B and outputs the result to variable C.

2-18

NJ/NX-series Instructions Reference Manual (W502)

Ladder Diagram Instructions

2 Instruction Descriptions

The operation is as shown below if you do not specify upward or downward differentiation.

Instruction

Combination of variable value and execution condition

Output value

AND ANDN

Variable value: TRUE Execution condition: TRUE Other than the above. Variable value: FALSE Execution condition: TRUE Other than the above.

TRUE
FALSE TRUE
FALSE

If you specify upward or downward differentiation, the operation depends on the following: the value of
the variable the last time the instruction was executed, the current value of the variable, and the execu- 2
tion condition. This is shown below.

AND and ANDN

Instruction

Differentiation specification

Combination of value of variable at last execution, current value of variable, and execution condition

Output value

Upward differentiation

Variable value: FALSE at the last execution  Currently TRUE
Execution condition: TRUE

TRUE

AND ANDN

Downward differentiation
Upward differentiation
Downward differentiation

Other than the above. Variable value: TRUE at the last execution  Currently FALSE Execution condition: TRUE Other than the above. Variable value: FALSE at the last execution  Currently TRUE Execution condition: TRUE Variable value: Ignored Execution condition: FALSE Other than the above. Variable value: TRUE at the last execution  Currently FALSE Execution condition: TRUE Variable value: Ignored Execution condition: FALSE Other than the above.

FALSE TRUE FALSE FALSE TRUE FALSE TRUE

Precautions for Correct Use
· An error occurs in the following case and the output value from the last execution is retained. · You specify an array element for the variable value and the element does not exist. Example: A BOOL array a[0..5] is defined, but the instruction is executed using a[10] as the variable.
· Do not use these instructions as the rightmost instruction on a rung. If you do, an error occurs on the Sysmac Studio and you cannot transfer the user program to the Controller.
· You cannot connect these instructions directly to the bus bar.

NJ/NX-series Instructions Reference Manual (W502)

2-19

2 Instruction Descriptions

OR and ORN

OR: ORN:

Takes the logical OR of the value of a BOOL variable and the execution condition.
Takes the logical OR of the inverse of the value of a BOOL variable and the execution condition.

Instruction

Name

OR

OR

FB/FUN ---

ORN

OR NOT ---

Graphic expression

Variable

Variable
Upward differentiation

VVaarriiaabbllee
DDoowwnnwwaarrdd ddiiffffeerreennttiiaattiioonn

Variable

Variable
Upward differentiation

Variable
Downward differentiation

ST expression result:=vBool1 OR vBool2;
result:=vBool1 OR NOT vBool2;

Variables
None

Function

 OR
The OR instruction takes the logical OR of the value of a specified BOOL variable and the execution condition and outputs it to the next instruction. Use the OR instruction for a NO bit connected in parallel with the previous instruction. Use the OR instruction to configure a logical OR between an NO bit and one of the following: a LD or LDN instruction connected directly to the bus bar, or the logic block starting with a LD or LDN instruction and ending with the instruction immediately before the OR instruction.

 ORN
The ORN instruction takes the logical OR of the inverse of the value of a specified BOOL variable and the execution condition and outputs it to the next instruction. Use the ORN instruction for a NC bit connected in parallel with the previous instruction. Use the ORN instruction to configure a logical OR between an NC bit and one of the following: a LD or LDN instruction connected directly to the bus bar, or the logic block starting with a LD or LDN instruction and ending with the instruction immediately before the ORN instruction.
The following figure shows a programming example of the OR instruction. It takes the logical OR of variable A and variable B and outputs it to variable C.

LD instruction

A

C

B Out instruction

OR instruction

2-20

NJ/NX-series Instructions Reference Manual (W502)

Ladder Diagram Instructions

2 Instruction Descriptions

A B

C

It takes the logical OR of variable A and variable B and outputs the result to variable C.

The operation is as shown below if you do not specify upward or downward differentiation.

Instruction

Combination of variable value and execution condition

Output value

Variable value: FALSE

FALSE

OR

Execution condition: FALSE

Other than the above.

TRUE

Variable value: TRUE

FALSE

2

ORN

Execution condition: FALSE

Other than the above.

TRUE

OR and ORN

If you specify upward or downward differentiation, the operation depends on the following: the value of the variable the last time the instruction was executed, the current value of the variable, and the execution condition. This is shown below.

Instruction OR

Differentiation specification

Combination of value of variable at last execution, current value of variable, and execution condition

Output value

Variable value: FALSE at the last execution  Currently TRUE

Upward differentiation

Execution condition: Ignored. Variable value: Ignored

TRUE

Execution condition: TRUE

Other than the above.

FALSE

Variable value: TRUE at the last execution  Currently FALSE

Downward differentiation

Execution condition: Ignored. Variable value: Ignored

TRUE

Execution condition: TRUE

ORN

Upward differentiation
Downward differentiation

Other than the above. Variable value: FALSE at the last execution  Currently TRUE Execution condition: FALSE
Other than the above. Variable value: TRUE at the last execution  Currently FALSE Execution condition: FALSE
Other than the above.

FALSE FALSE
TRUE FALSE
TRUE

Precautions for Correct Use
· An error occurs in the following case and the output value from the last execution is retained. · You specify an array element for the variable value and the element does not exist. Example: A BOOL array a[0..5] is defined, but the instruction is executed using a[10] as the variable.
· Do not use these instructions as the rightmost instruction on a rung. If you do, an error occurs on the Sysmac Studio and you cannot transfer the user program to the Controller.

NJ/NX-series Instructions Reference Manual (W502)

2-21

2 Instruction Descriptions

Out and OutNot

Out: OutNot:

Takes the logical result from the previous instruction and outputs it to a BOOL variable.
Takes the inverse of the logical result from the previous instruction and outputs it to a BOOL variable.

Instruction

Name

Out

Output

FB/FUN ---

Graphic expression Variable

ST expression
Variable:=(Logic expression up to previous instruction);

Variable

Variable

OutNot

Output NOT

---

Upward differentiation

Downward differentiation

Variable

Variable:=NOT(Logic expression up to previous instruction);

Variables
None

Function
 Out
The Out instruction takes the logical result from the previous instruction and outputs it to a specified BOOL variable. The operation is as shown below if you do not specify upward or downward differentiation.

Logic processing result from previous instruction
TRUE
FALSE

Output
TRUE FALSE

You can specify upward or downward differentiation for the Out instruction. If upward or downward differentiation is specified, the output value is determined by changes in the result of logic processing from the previous instruction between the last execution of the instruction and the current execution. The operation is according to the current logical result from the previous instruction, as shown in the following table.

Differentiation specification Upward differentiation Downward differentiation

Results of logic processing from the previous execution and current execution
FALSE at the last execution  Currently TRUE Other than the above. TRUE at the last execution  Currently FALSE Other than the above.

Output
TRUE FALSE TRUE FALSE

2-22

NJ/NX-series Instructions Reference Manual (W502)

Ladder Diagram Instructions

2 Instruction Descriptions

 OutNot
The OutNot instruction takes the inverse of the logical result from the previous instruction and outputs it to a specified BOOL variable.

Logic processing result from previous instruction
TRUE FALSE

Output
FALSE TRUE

The following figure shows a programming example and timing chart.

Out and OutNot

A

TRUE FALSE

2

A

B1

B1

TRUE FALSE

B2

B2

TRUE FALSE

B3

B3

TRUE FALSE

B4

B4 TRUE

FALSE

Instruction executed
Additional Information
Differences between the Set and Reset Instructions and the Out and OutNot Instructions
· The Set and Reset instructions operate only when the input value changes to TRUE. They do not operate when the input value is FALSE. When the input value is FALSE, the output does not change.
· The Out and OutNot instructions affect the output whether the logical result of the previous instruction is TRUE or FALSE.

NJ/NX-series Instructions Reference Manual (W502)

2-23

2 Instruction Descriptions

Precautions for Correct Use

· In the following case, an error occurs and nothing is output. · You specify an array element for the variable value and the element does not exist. Example: A BOOL array a[0..5] is defined, but the instruction is executed using a[10] as the variable.
· The following connections are possible. · You can connect another Out instruction after an Out instruction.

A

B

C

· You can connect an LD instruction and Out instruction after an Out instruction.

A

BC

D

· The following connections are not possible. · You cannot connect only an LD instruction after an Out instruction.

A

BC

· Functions and function blocks cannot be connected after an Out instruction.

A

B

MOVE

EN C In

ENO Out D

· Branches and joins cannot be used after Out instructions.

A

B

A

B

C

D

2-24

NJ/NX-series Instructions Reference Manual (W502)

ST Statement Instructions

2
ST Statement Instructions

Instruction IF CASE WHILE REPEAT EXIT RETURN FOR

Name If Case While Repeat Break Loop Return Repeat Start

Page 2-26 2-30 2-34 2-36 2-38 2-41 2-42

NJ/NX-series Instructions Reference Manual (W502)

2-25

2 Instruction Descriptions

IF

The IF construct uses the evaluation result of a specified condition expression to select one of two statements to execute.

Instruction IF

Name If

FB/FUN ---

Graphic expression None

ST expression
IF condition expression THEN
statement; ELSIF condition expression THEN
statement; ELSE
statement; END_IF;

Variables
None

Function

The IF construct uses the evaluation result of a specified condition expression to select one of two statements to execute. Use a condition expression that evaluates to TRUE or FALSE.

Item used for condition expression

Example

Evaluation result

Logic expression
BOOL variable
BOOL constant Function with a BOOL return value

a>3 a=b abc TRUE FUN name

If the value of variable a is greater than 3, the result is TRUE. Otherwise, the result is FALSE.
If the values of variables a and b are equal, the result is TRUE. Otherwise, the result is FALSE.
If the value of variable abc is TRUE, the result is TRUE. If it is FALSE, the result is FALSE.
TRUE
If the function returns TRUE, the result is TRUE. If it returns FALSE, the result is FALSE.

You can use the following operators in the logic expression.

Operator

Meaning

=

Equals

Example a=b

Evaluation result
If the values of variables a and b are equal, the result is TRUE. Otherwise, the result is FALSE.

<>

Not equals

a<>b

If the values of variables a and b are not equal, the result is TRUE. Otherwise, the result is FALSE.

<

a<b

If the value of variable a is less than the value of variable b, the

result is TRUE. Otherwise, the result is FALSE.

<=

a<=b

If the value of variable a is less than or equal to the value of

variable b, the result is TRUE. Otherwise, the result is FALSE.

Comparison

>

a>b

If the value of variable a is greater than the value of variable b,

the result is TRUE. Otherwise, the result is FALSE.

>= AND (&) Logical AND

a>=b
a AND b a & b

If the value of variable a is greater than or equal to the value of variable b, the result is TRUE. Otherwise, the result is FALSE.
The result is the logical AND of BOOL variables a and b.

2-26

NJ/NX-series Instructions Reference Manual (W502)

ST Statement Instructions

2 Instruction Descriptions

Operator OR XOR

Meaning Logical OR Exclusive OR

NOT

NOT

Example a OR b a XOR b
NOT a

Evaluation result The result is the logical OR of BOOL variables a and b. The result is the logical exclusive OR of BOOL variables a and b. The result is the NOT of BOOL variable a.

The flowchart in the following example shows the evaluation results for condition expressions 1 and 2. You can use more than one statement for each of statements 1 to 3.

IF condition expression 1 THEN

statement 1;

ELSIF condition expression 2 THEN

statement 2;

2

ELSE

statement 3;

IF

END_IF;

Condition FALSE expression 1

TRUE Statement 1

Condition FALSE expression 2
TRUE

Statement 2

Statement 3

Additional Information
· You can use the IF construct to build a hierarchy. The following example executes statement 11 if the evaluation results of both condition expression 1 and condition expression 11 are TRUE.
IF condition expression 1 THEN IF condition expression 11 THEN statement 11; ELSIF condition expression 12 THEN statement 12; ELSE statement 13; END_IF;
ELSIF condition expression 2 THEN statement 2;
ELSE statement 3;
END_IF;

NJ/NX-series Instructions Reference Manual (W502)

2-27

2 Instruction Descriptions
You can use ELSIF more than once. The following processing flow is for this example. IF condition expression 1 THEN
statement 1; ELSIF condition expression 2 THEN
statement 2; ELSIF condition expression 3 THEN
statement 3; ELSE
statement 4; END_IF;

Condition FALSE expression 1

TRUE Statement 1

Condition FALSE expression 2

TRUE

Condition expression 3

FALSE

Statement 2

TRUE

Statement 3

Statement 4

· You do not use ELSIF if there is only one condition expression. You do not use ELSE if no processing is performed when none of the condition expressions are TRUE. The following processing flow is for this example.
IF condition expression THEN statement;
END_IF;

Condition expression

FALSE

TRUE

Statement

· There are no restrictions on the statements that you can use. You can use the same types of statements for the statements in the IF construct as you do for the statements outside the IF construct. For example, you can use function block calls and FOR constructs.
Precautions for Correct Use
· You must always use IF and END_IF. They must be paired. · You can use a hierarchy that is 15 levels deep, but count all levels of IF, CASE, FOR, WHILE, and
REPEAT constructs.

2-28

NJ/NX-series Instructions Reference Manual (W502)

ST Statement Instructions

2 Instruction Descriptions

Sample Programming

This example assigns INT#0 to variable def if the value of variable abc is less than INT#0. It assigns INT#1 to variable def and INT#2 to variable ghi if the value of variable abc is INT#0. It assigns INT#3 to variable def if the value of variable abc is none of the above.

Variable Data type Initial value

abc

INT

0

def

INT

0

ghi

INT

0

IF (abc<INT#0) THEN

2

def:=INT#0;

ELSIF (abc=INT#0) THEN

IF

def:=INT#1;

ghi:=INT#2;

ELSE

def:=INT#3;

END_IF;

NJ/NX-series Instructions Reference Manual (W502)

2-29

2 Instruction Descriptions

CASE

You use the CASE construct to select the statement to execute based on the value of a specified integer expression.

Instruction CASE

Name Case

FB/FUN ---

Graphic expression None

ST expression
CASE integer expression OF
value: statement;
value: statement;
· · · ELSE
statement; END_CASE;

Variables
None

Function

You use the CASE construct to select the statement to execute based on the value of a specified integer expression.
You can use any of the following as the integer expression and values.

Integer expression Values

Allowed notation
Integer variable, integer constant, integer expression, or a function that returns an integer return value, enumeration variable, enumeration expression, or enumerator
Integer constants

The flowchart in the following example shows the processing flow for an integer expression. You can use more than one statement for each of the statements.
CASE integer expression OF 1 : statement 1; 2 : statement 2; ... n : statement n; ELSE statement m;
END_CASE;

2-30

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

ST Statement Instructions

Equal to value 1?

TRUE

FALSE

Equal to value 2?

TRUE

FALSE

2

CASE

Equal to value n?

TRUE

FALSE

Statement m

Statement n

Statement 2

Statement 1

Additional Information
· You can use the CASE construct to build a hierarchy. The following example executes statement 12 if the value of integer expression 1 is 1 and the value of integer expression 11 is 2.
CASE integer expression 1 OF 1 : CASE integer expression 1 OF 1 : statement 11; 2 : statement 12; ELSE statement 1m; END_CASE; 2 : statement 2; 3 : statement 3; ELSE statement m;
END_CASE;
· You can use more than one value at the same time. Separate values with commas. The following example executes statement 1 if the value of the integer expression is either 1 or 2.
CASE integer expression 1 OF 1,2 : statement 1; 3 : statement 2; 4 : statement 3; ELSE statement m;
END_CASE;

NJ/NX-series Instructions Reference Manual (W502)

2-31

2 Instruction Descriptions

· You can use a range of consecutive values. Place two periods between the numbers to indicate consecutive values. The following example executes statement 1 if the value of the integer expression is between 10 and 15, inclusive.
CASE integer expression 1 OF 10..15: statement 1; 16: statement 2; 17: statement 3; ELSE statement m;
END_CASE;

· You can omit ELSE. If you do, none of the statements is executed if none of the values is equal to the value of the integer expression.
· There are no restrictions on the statements that you can use. You can use the same types of statements for the statements in the CASE construct as you do for the statements outside the CASE construct. For example, you can use function block calls and FOR constructs.
· The following is different in comparison to a C language switch statement. With a C language switch statement, all statements after a value that equals the integer expression are executed unless a break statement is used. With the CASE statement, only the statements that correspond directly to the value that equals the integer expression are executed. For example, in the following example, statements 1 to 3 are executed for the C language switch statement. Here, only statement 1 is executed for the CASE instruction.

C Language switch Statement
val=1; switch val {
case 1: statement 1;
case 2: statement 2;
case 3: statement 3; }

CASE Instruction
val:=1; CASE val OF
1: statement 1;
2: statement 2;
3: statement 3;
END_CASE;

Precautions for Correct Use
· You must always use CASE and END_CASE. They must be paired. · The data types of the integer expression and values can be different. · Each value can be given only once. · You can use a hierarchy that is 15 levels deep, but count all levels of IF, CASE, FOR, WHILE, and
REPEAT constructs.

2-32

NJ/NX-series Instructions Reference Manual (W502)

ST Statement Instructions

2 Instruction Descriptions

Sample Programming

This example assigns INT#10 to variable def if the value of variable abc is INT#1, INT#20 if the value of variable abc is INT#2, and INT#30 if the value of variable abc is INT#3. Otherwise, it assigns the value of variable ghi to variable def.

Variable Data type Initial value

abc

INT

0

def

INT

0

ghi

INT

0

CASE abc OF

2

INT#1:

def:=INT#10;

CASE

INT#2:

def:=INT#20;

INT#3:

def:=INT#30;

ELSE

def:=ghi;

END_CASE;

This example assigns INT#10 to variable def if the value of variable abc is INT#1, INT#20 if the value of variable abc is INT#2 or INT#5, and INT#30 if the value of variable abc is between INT#6 and INT#10, inclusive. Otherwise, it does nothing.

Variable abc def

Data type INT INT

Initial value 0 0

CASE abc OF INT#1: def:=INT#10; INT#2,INT#5: def:=INT#20; INT#6..INT#10: def:=INT#30;
END_CASE;

NJ/NX-series Instructions Reference Manual (W502)

2-33

2 Instruction Descriptions

WHILE

The WHILE construct repeatedly executes a statement as long as the evaluation result of a specified condition expression is TRUE.

Instruction WHILE

Name While

FB/FUN ---

Graphic expression None

ST expression
WHILE condition expression DO
statement; END_WHILE;

Variables
None

Function

The WHILE construct repeatedly executes a statement as long as the evaluation result of a specified condition expression is TRUE. Use a condition expression that evaluates to TRUE or FALSE.

Item used for condition expression

Example a>3

Logic expression a=b

BOOL variable

abc

Evaluation result
If the value of variable a is greater than 3, the result is TRUE. Otherwise, the result is FALSE. If the values of variables a and b are equal, the result is TRUE. Otherwise, the result is FALSE. If the value of variable abc is TRUE, the result is TRUE. If it is FALSE, the result is FALSE.

BOOL constant
Function with a BOOL return value

TRUE FUN name

TRUE
If the function returns TRUE, the result is TRUE. If it returns FALSE, the result is FALSE.

You can use the following operators in the logic expression.

Operator

Meaning

Example

Evaluation result

=

Equals

a=b

If the values of variables a and b are equal, the result is TRUE.

Otherwise, the result is FALSE.

<>

Not equals

a<>b

If the values of variables a and b are not equal, the result is TRUE. Otherwise, the result is FALSE.

<

a<b

If the value of variable a is less than the value of variable b, the

result is TRUE. Otherwise, the result is FALSE.

<=

a<=b

If the value of variable a is less than or equal to the value of

variable b, the result is TRUE. Otherwise, the result is FALSE.

Comparison

>

a>b

If the value of variable a is greater than the value of variable b,

the result is TRUE. Otherwise, the result is FALSE.

>=

a>=b

If the value of variable a is greater than or equal to the value of

variable b, the result is TRUE. Otherwise, the result is FALSE.

AND (&) Logical AND

a AND b a & b

The result is the logical AND of BOOL variables a and b.

OR

Logical OR

a OR b

The result is the logical OR of BOOL variables a and b.

XOR

Exclusive OR

a XOR b

The result is the logical exclusive OR of BOOL variables a and b.

NOT

NOT

NOT a

The result is the NOT of BOOL variable a.

2-34

NJ/NX-series Instructions Reference Manual (W502)

ST Statement Instructions

2 Instruction Descriptions

The following processing flow is for this example. You can use more than one statement.
WHILE condition expression DO statement;
END_WHILE;

Condition expression

FALSE

TRUE

Statement
2

WHILE

Additional Information
· The statement is not executed even once if the condition expression is FALSE the first time it is evaluated.
· There are no restrictions on the statements that you can use. You can use the same types of statements for the statements in the WHILE construct as you do for the statements outside the WHILE construct. For example, you can use function block calls and FOR constructs.

Precautions for Correct Use
· You must always use WHILE and END_WHILE. They must be paired. · You can use a hierarchy that is 15 levels deep, but count all levels of IF, CASE, FOR, WHILE, and
REPEAT constructs.

Sample Programming

This example adds INT#7 to variable abc as long as the value of variable abc is less than or equal to INT#1000.

Variable Data type Initial value

abc

INT

0

abc:=INT#0; WHILE abc<=INT#1000 DO
abc:=abc+INT#7; END_WHILE;

NJ/NX-series Instructions Reference Manual (W502)

2-35

2 Instruction Descriptions

REPEAT

The REPEAT construct executes a statement once and then executes it repeatedly until a specified condition expression is TRUE.

Instruction REPEAT

Name Repeat

FB/FUN ---

Graphic expression None

ST expression
REPEAT statement;
UNTIL condition expression END_REPEAT;

Variables
None

Function

The REPEAT construct executes a statement once and then executes it repeatedly until a specified condition expression is TRUE. Use a condition expression that evaluates to TRUE or FALSE.

Item used for condition expression

Example a>3

Logic expression a=b

BOOL variable

abc

Evaluation result
If the value of variable a is greater than 3, the result is TRUE. Otherwise, the result is FALSE. If the values of variables a and b are equal, the result is TRUE. Otherwise, the result is FALSE. If the value of variable abc is TRUE, the result is TRUE. If it is FALSE, the result is FALSE.

BOOL constant
Function with a BOOL return value

TRUE FUN name

TRUE
If the function returns TRUE, the result is TRUE. If it returns FALSE, the result is FALSE.

You can use the following operators in the logic expression.

Operator

Meaning

Example

Evaluation result

=

Equals

a=b

If the values of variables a and b are equal, the result is TRUE.

Otherwise, the result is FALSE.

<>

Not equals

a<>b

If the values of variables a and b are not equal, the result is TRUE. Otherwise, the result is FALSE.

<

a<b

If the value of variable a is less than the value of variable b, the

result is TRUE. Otherwise, the result is FALSE.

<= Comparison
>

a<=b a>b

If the value of variable a is less than or equal to the value of variable b, the result is TRUE. Otherwise, the result is FALSE.
If the value of variable a is greater than the value of variable b, the result is TRUE. Otherwise, the result is FALSE.

>=

a>=b

If the value of variable a is greater than or equal to the value of

variable b, the result is TRUE. Otherwise, the result is FALSE.

AND (&) Logical AND

a AND b a & b

The result is the logical AND of BOOL variables a and b.

OR

Logical OR

a OR b

The result is the logical OR of BOOL variables a and b.

XOR

Exclusive OR

a XOR b

The result is the logical exclusive OR of BOOL variables a and b.

NOT

NOT

NOT a

The result is the NOT of BOOL variable a.

2-36

NJ/NX-series Instructions Reference Manual (W502)

ST Statement Instructions

2 Instruction Descriptions

The following processing flow is for this example. You can use more than one statement.
REPEAT statement;
UNTIL condition expression END_REPEAT;

Statement

Condition

TRUE

expression

2

FALSE

REPEAT

Additional Information
· The statement is executed once before the condition expression is evaluated. Therefore, the statement is always executed at least once.
· There are no restrictions on the statements that you can use. You can use the same types of statements for the statements in the REPEAT construct as you do for the statements outside the REPEAT construct. For example, you can use function block calls and FOR constructs.

Precautions for Correct Use
· You must always use REPEAT, UNTIL, and END_REPEAT. They must be used as a set. · You can use a hierarchy that is 15 levels deep, but count all levels of IF, CASE, FOR, WHILE, and
REPEAT constructs.

Sample Programming

This example adds INT#1 to variable abc until the value of variable abc exceeds INT#10.

Variable Data type Initial value

abc

INT

0

abc:=INT#0; REPEAT
abc:=abc+INT#1; UNTIL abc>INT#10 END_REPEAT;

NJ/NX-series Instructions Reference Manual (W502)

2-37

2 Instruction Descriptions

EXIT

The EXIT instruction is used to end repeat processing from the lowest level FOR, WHILE, or REPEAT instruction.

Instruction EXIT

Name Break Loop

FB/FUN ---

Graphic expression None

ST expression
FOR Index:=0 TO 9 BY 1 DO
IF Error[Index] THEN EXIT;
END_IF; END_FOR;

Variables
None

Function
The EXIT instruction is used to end repeat processing from the lowest level FOR, WHILE, or REPEAT instruction. Processing moves to the next instruction after the repeat processing.
In the following programming, the value of variable A is checked every repetition during repeat processing for the FOR instruction. If the value of variable A is TRUE, the EXIT instruction is executed and the repeat processing is ended. If that occurs, C:=B; following END_IF is not executed and the value of variable C is retained.
FOR position:=INT#0 TO INT#10 BY INT#1 DO IF (A=TRUE) THEN EXIT;
END_IF; C:=B; END_FOR;

2-38

NJ/NX-series Instructions Reference Manual (W502)

ST Statement Instructions

2 Instruction Descriptions

The flowchart for this programming is given below.
START position : = INT#0

INT#0  position  INT#10

FALSE

TRUE

A = TRUE

TRUE

If the value of variable A is

2

TRUE, the EXIT instruction is

EXIT

FALSE C : = B

executed and the repeat processing is ended. The value of C at that point is retained.

position : = position + INT#1

END
When the EXIT instruction is executed, only the lowest level of repeat processing is ended. Therefore, in the following programming, when the value of variable B is TRUE, EXIT instruction 2 is executed and the repeat processing for WHILE instruction 2 is ended. As the result, processing moves to x:=x+1;. In this case, repeat processing for WHILE instruction 1 (one level higher) is continued.
If the value of variable A is TRUE, EXIT instruction 1 is executed and the repeat processing for WHILE instruction 1 is ended. As the result, processing moves to C:=D;.

x:=INT#0; y:=INT#0; WHILE x<=INT#10 DO
IF (A=TRUE) THEN EXIT;
END_IF; WHILE y<=INT#20 DO
IF (B=TRUE) THEN EXIT;
END_IF; y := y+1; END_WHILE; x = x+1; END_WHILE C:=D;

// WHILE instruction 1 // EXIT instruction 1 // WHILE instruction 2 // EXIT instruction 2

NJ/NX-series Instructions Reference Manual (W502)

2-39

2 Instruction Descriptions

The flowchart for this programming is given below.
START
x := INT#0 y := INT#0

Repeat processing for WHILE instruction 1
Repeat processing for WHILE instruction 2

x  INT#10

FALSE

TRUE

A = TRUE

TRUE

FALSE

y  INT#20

FALSE

TRUE B = TRUE

TRUE

FALSE y := y+1

If the value of variable A is TRUE, the repeat processing for WHILE instruction 1 is ended.
If the value of variable B is TRUE, the repeat processing for WHILE instruction 2 is ended.

x := x+1
C := D
END
Precautions for Correct Use
· Always place this instruction between the FOR and END_FOR, WHILE and END_WHILE, or REPEAT and END_REPEAT instructions.
· If you nest repeat processing, one EXIT instruction is required for each nesting level to end all of the repeat processing.

2-40

NJ/NX-series Instructions Reference Manual (W502)

ST Statement Instructions

2 Instruction Descriptions
RETURN
Refer to RETURN on page 2-67 in the Sequence Control Instructions for a description of this instruction.
2

RETURN

NJ/NX-series Instructions Reference Manual (W502)

2-41

2 Instruction Descriptions
FOR
Refer to FOR and NEXT on page 2-82 in the Sequence Control Instructions for a description of this instruction.

2-42

NJ/NX-series Instructions Reference Manual (W502)

Sequence Input Instructions

2
Sequence Input Instructions

Instruction R_TRIG (Up) and F_TRIG (Down)
TestABit and TestABitN

Name
Up Trigger/ Down Trigger
Test A Bit/ Test A Bit NOT

Page 2-44 2-47

NJ/NX-series Instructions Reference Manual (W502)

2-43

2 Instruction Descriptions

R_TRIG (Up) and F_TRIG (Down)

R_TRIG (Up): Outputs TRUE for one task period only when the input signal changes to TRUE. F_TRIG (Down): Outputs TRUE for one task period only when the input signal changes to FALSE.

Instruction R_TRIG

Name

Up Trigger Up

F_TRIG Down

Down Trigger

FB/FUN FB
FUN FB
FUN

Graphic expression

R_TRIG_instance

R_TRIG

Clk

Q

Up

In

Out

F_TRIG_instance

F_TRIG

Clk

Q

Down

In

Out

ST expression R_TRIG_instance(Clk, Q);
None F_TRIG_instance(Clk, Q);
None

Variables

Name Clk, In Q, Out

Meaning Input signal Output signal

I/O Input Output

Description Input signal Output signal

Bit strings

Integers

Valid range Depends on data type. Depends on data type.

Unit
-----

Default
-----

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

Clk, In

OK

Q, Out

OK

Function
 R_TRIG
R_TRIG assigns TRUE to output signal Q for one task period only when input signal Clk changes to TRUE. Otherwise, the value of Q is FALSE.
 Up
The functions of the R_TRIG instruction and the Up instruction are the same. The Clk variable of the F_TRIG instruction corresponds to the In variable of the Down instruction. The Q variable corresponds to the Out variable. However, the operation of the Up instruction is different from the operation of the R_TRIG instruction in the first task period in which it is executed. Refer to the Precautions for Correct Use for the operation of the Up instruction in the first task period in which it is executed.

2-44

NJ/NX-series Instructions Reference Manual (W502)

Sequence Input Instructions

2 Instruction Descriptions

The following figure shows a programming example and timing chart.

LD

ST

R_TRIG_instance

A

R_TRIG

abc

Clk

Q

R_TRIG_instance(A, abc);

LD

2

A

Up

abc

In

R_TRIG (Up) and F_TRIG (Down)

TRUE Clk, In FALSE

Q, Out=abc

TRUE FALSE

Task period
 F_TRIG
F_TRIG assigns TRUE to output signal Q for one task period only when input signal Clk changes to FALSE. Otherwise, the value of Q is FALSE.

 Down
The functions of the F_TRIG instruction and the Down instruction are exactly the same. The Clk variable of the F_TRIG instruction corresponds to the In variable of the Down instruction. The Q variable corresponds to the Out variable.
The following figure shows a programming example and timing chart.

LD

ST

F_TRIG_instance

A

F_TRIG

abc

Clk

Q

F_TRIG_instance(A, abc);

LD

A

Down abc

In

Clk, In

TRUE FALSE

Q, Out=abc TRUE FALSE

Task period

NJ/NX-series Instructions Reference Manual (W502)

2-45

2 Instruction Descriptions

Precautions for Correct Use
· Detection of upward or downward differentiation depends on differences between the current value of Clk or In and the value the last time the instruction was executed. Caution is required when using the JMP instruction or other times that the instruction is not executed every task period.
· If power is interrupted, the value of Clk or In is not detected as FALSE. The value of Clk or In is detected as FALSE only if the instruction evaluates the value of Clk or In while Clk or In is FALSE.
· In the first task period in which the Up instruction is executed, the value of Out is FALSE regardless of the value of In.
· If the value of In in the Up instruction is TRUE when the power supply is turned ON, the value of Out remains FALSE until the value of In changes to FALSE and then to TRUE.
· In the first task period in which the F_TRIG instruction is executed, the value of Q is FALSE regardless of the value of Clk.
· If the value of Clk in the F_TRIG instruction is FALSE when the power supply is turned ON, the value of Q remains FALSE until the value of Clk changes to TRUE and then to FALSE.
· In the first task period in which the Down instruction is executed, the value of Out is FALSE regardless of the value of In.
· If the value of In in the Down instruction is FALSE when the power supply is turned ON, the value of Out remains FALSE until the value of In changes to TRUE and then to FALSE.

Version Information
The value of Q when the R_TRIG instruction is executed and the value of Clk is TRUE depends on the unit version of the CPU Unit and the timing of execution of the instruction, as described in the following table.

Timing of execution of R_TRIG when Clk is TRUE
Task period in which R_TRIG is first executed When the power supply is turned ON

Value of Q

CPU Unit with unit version 1.02 CPU Unit with unit version 1.01

or later

or earlier

The value of Q is TRUE.

The value of Q is always FALSE.

The value of Q is TRUE.

The value of Q remains FALSE until the value of Clk changes to FALSE and then to TRUE.

2-46

NJ/NX-series Instructions Reference Manual (W502)

Sequence Input Instructions

2 Instruction Descriptions

TestABit and TestABitN

TestABit: Outputs the value of the specified bit in a bit string. TestABitN: Outputs the inverse of the value of the specified bit in a bit string.

Instruction TestABit

Name Test A Bit

FB/FUN FUN

TestABitN

Test A Bit NOT

FUN

Graphic expression

ST expression

(@)TestABit

Out:=TestABit (In, Pos);

EN

Out

In Pos

2

(@)TestABitN

EN

Out

In

Pos

Out:=TestABitN (In, Pos);

TestABit and TestABitN

Variables

Name In Pos Out

Meaning Bit string Bit position Bit value

I/O Input Output

Description

Valid range

Unit

Bit string Specified bit position

Depends on data type.
---
0 to No. of bits in In - 1

TestABit

Depends on data type. ---

Value of specified bit

TestABitN

Inverse of value of specified bit

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default * 0
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK OK OK OK

Pos

OK

Out

OK

NJ/NX-series Instructions Reference Manual (W502)

2-47

2 Instruction Descriptions

Function

 TestABit
The TestABit instruction assigns the value of the bit at bit position Pos in the bit string In to the bit value Out when EN is TRUE. When EN is FALSE, the value of Out is FALSE.

 TestABitN

The TestABitN instruction assigns the inverse of the value of the bit at bit position Pos in the bit string In to the bit value Out when EN is TRUE. When EN is FALSE, the value of Out is FALSE. The following example shows the TestABit instruction when Pos is USINT#3.

LD

ST

def:=TestABit(abc, USINT#3);

TestABit

def

EN abc In USINT#3 Pos

Pos=USINT#3

Most-significant bit

Bit 0

In=abc 1 0

0 0 1 0 1 1

Out=def TRUE

Precautions for Correct Use
· If this instruction is used in a ladder diagram, the value of Out changes to FALSE if an error occurs in the previous instruction on the rung.
· An error occurs in the following case. Out will be FALSE. · The value of Pos is greater than No. of bits in In - 1.

2-48

NJ/NX-series Instructions Reference Manual (W502)

Sequence Output Instructions

2
Sequence Output Instructions

Instruction RS SR Set and Reset SetBits and ResetBits SetABit and ResetABit OutABit

Name Reset-Priority Keep Set-Priority Keep Set/Reset Set Bits/Reset Bits Set A Bit/Reset A Bit Output A Bit

Page 2-50 2-53 2-56 2-59 2-61 2-63

NJ/NX-series Instructions Reference Manual (W502)

2-49

2 Instruction Descriptions

RS

The RS instruction retains the value of a BOOL variable. It gives priority to the Reset input if both the Set input and Reset input are TRUE.

Instruction RS

Name

FB/FUN

Reset-Priority Keep FB

Graphic expression

RS_instance

RS

Set

Q1

Reset1

ST expression
RS_instance(Set, Reset1, Q1);

Variables

Name Set* Reset1* Q1

Meaning Set Reset Keep

I/O Input Output

Description Set input Reset input Keep output

Valid range

Unit

Depends on data type. ---

Depends on data type. ---

Default 0
---

* On Sysmac Studio version 1.03, you can use "S" instead of "Set" and "R1" instead of "Reset1" to more clearly show the correspondence between the variables and the parameter names in ST expressions. For example, you can use the following notation: RS_instance(S:=A, R1:=B, Q1=>abc);.

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

Set

OK

Reset1

OK

Q1

OK

Function

The RS instruction forms a self-holding output that gives priority to resetting. The following table shows the relationship between the inputs are outputs.

Value of Set TRUE TRUE

Value of Reset1

Value of Q1

TRUE

FALSE

FALSE

TRUE

FALSE FALSE

TRUE FALSE

FALSE Not changed.

2-50

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Sequence Output Instructions

The following figure shows a programming example and timing chart.

LD

ST

RS_instance

A

RS

abc

Set

Q1

B Reset1

RS_instance(A, B, abc);

Set=A

TRUE FALSE

2

TRUE Reset1=B FALSE

RS

Q1=abc

TRUE FALSE

Additional Information

· The RS instruction behaves like the following self-holding rung.

A

B

abc

abc

· However, if the RS instruction is in a master control region and the master control region is reset, the behavior will not be the same as the above self-holding rung.

Instruction/rung

Value of B

Value of abc

RS instruction

TRUE

Not changed.

FALSE

FALSE

Self-holding rung

TRUE

FALSE

FALSE

Precautions for Correct Use
· Never use an NC bit directly from an external device for the Reset1 input. The internal power supply in the Controller will not turn OFF immediately when the AC power is interrupted (even for momentary interruptions), and the input from the Input Unit may change to ON first. This could cause the Reset1 input to change to TRUE.
· If this instruction is used in a ladder diagram, the value of Q1 is retained if an error occurs in the previous instruction on the rung.
· If this instruction is not executed due to the execution of a jump instruction (e.g., the JMP instruction), Q1 retains the value from the last execution.
· If this instruction is in a master control region and the master control region is reset, the operation is as follows: · If the value of Reset1 is TRUE, the value of Q1 is retained. If the value of Reset1 is FALSE, the value of Q1 changes to FALSE. · FALSE is input to the instruction that is connected to Q1 even if the value of Q1 is TRUE.

NJ/NX-series Instructions Reference Manual (W502)

2-51

2 Instruction Descriptions
· Even if you connect a parameter with a Retain attribute to Q1, the value will not be retained when the power is interrupted. After the power supply is restored, the value of Q1 will be FALSE when the operating mode is changed to RUN mode and the instruction is executed. If the self-holding rung given in Additional Information is used, the value is retained even after the power supply is restored.

2-52

NJ/NX-series Instructions Reference Manual (W502)

Sequence Output Instructions

2 Instruction Descriptions

SR

The SR instruction retains the value of a BOOL variable. It gives priority to the Set input if both the Set input and Reset input are TRUE.

Instruction SR

Name Set-Priority Keep

FB/FUN FB

Graphic expression

SR_instance

SR

Set1

Q1

Reset

ST expression SR_instance(Set1, Reset, Q1);
2

Variables

SR

Name Set1* Reset Q1

Meaning Set Reset Keep

I/O Input Output

Description Set input Reset input Keep output

Valid range

Unit

Depends on data type. ---

Depends on data type. ---

Default 0
---

* On Sysmac Studio version 1.03, you can use "S1" instead of "Set1" and "R" instead of "Reset" to more clearly show the correspondence between the variables and the parameter names in ST expressions. For example, you can use the following notation: SR_instance(S1:=A, R:=B, Q1=>abc);.

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

Set1

OK

Reset

OK

Q1

OK

Function

The SR instruction forms a self-holding output that gives priority to setting. The following table shows the relationship between the inputs are outputs.

Value of Set1 TRUE TRUE

Value of Reset TRUE FALSE

Value of Q1 TRUE TRUE

FALSE FALSE

TRUE FALSE

FALSE Not changed.

NJ/NX-series Instructions Reference Manual (W502)

2-53

2 Instruction Descriptions

The following figure shows a programming example and timing chart.

LD

ST

SR_instance

A

SR

abc

Set1

Q1

B Reset

SR_instance(A, B, abc);

Set1=A

TRUE FALSE

TRUE Reset=B FALSE

Q1=abc

TRUE FALSE

Additional Information

· The SR instruction behaves like the following self-holding rung.

A

abc

abc

B

· However, if the SR instruction is in a master control region and the master control region is reset, the behavior will not be the same as the above self-holding rung.

Instruction/rung SR instruction

Value of B TRUE FALSE

Value of abc Not changed. FALSE

Self-holding rung

TRUE FALSE

FALSE

Precautions for Correct Use
· Never use an NC bit directly from an external device for the Reset input. The internal power supply in the Controller will not turn OFF immediately when the AC power is interrupted (even for momentary interruptions), and the input from the Input Unit may change to ON first. This could cause the Reset input to change to TRUE.
· If this instruction is used in a ladder diagram, the value of Q1 is retained if an error occurs in the previous instruction on the rung.
· If this instruction is not executed due to the execution of a jump instruction (e.g., the JMP instruction), Q1 retains the value from the last execution.
· If this instruction is in a master control region and the master control region is reset, the operation is as follows: · If the value of Reset is TRUE, the value of Q1 is retained. If the value of Reset is FALSE, the value of Q1 changes to FALSE. · FALSE is input to the instruction that is connected to Q1 even if the value of Q1 is TRUE.

2-54

NJ/NX-series Instructions Reference Manual (W502)

Sequence Output Instructions

2 Instruction Descriptions
· Even if you connect a parameter with a Retain attribute to Q1, the value will not be retained when the power is interrupted. After the power supply is restored, the value of Q1 will be FALSE when the operating mode is changed to RUN mode and the instruction is executed. If the self-holding rung given in Additional Information is used, the value is retained even after the power supply is restored.
2

SR

NJ/NX-series Instructions Reference Manual (W502)

2-55

2 Instruction Descriptions

Set and Reset

Set: Reset:

Changes a BOOL variable to TRUE. Changes a BOOL variable to FALSE.

Instruction Set

Name Set

FB/FUN ---

Reset

Reset

---

Graphic expression

Out

Out

Out

PS

NS

S

Upward

Downward

differentiation differentiation

Out

Out

Out

PR

NR

R

Upward

Downward

differentiation differentiation

ST expression None
None

Variables

Name Out

Meaning

I/O

Output

Output

Description Output

Valid range

Unit

Depends on data type. ---

Default
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

Out

OK

Function

 Set
The Set instruction changes Out to TRUE if the input is TRUE. If Out is TRUE, the Set instruction will not change it to FALSE even if the input changes to FALSE. Use the Reset instruction to change Out to FALSE.

 Reset

The Reset instruction changes Out to FALSE if the input is TRUE. If Out is FALSE, the Reset instruction will not change it to TRUE even if the input changes to FALSE. Use the Set instruction to change Out to TRUE.

The operation is as shown below if you do not specify upward or downward differentiation.

Instruction

Input

Output value

Set Reset

TRUE FALSE TRUE FALSE

TRUE Not changed. FALSE Not changed.

2-56

NJ/NX-series Instructions Reference Manual (W502)

Sequence Output Instructions

2 Instruction Descriptions

If you specify upward or downward differentiation, the operation depends on the following: the value of the input for the last execution and the current value of the input. This is shown below.

Instruction

Differentiation specification

Value of input at last execution and current value

Output value

FALSE at the last execution  Currently TRUE

TRUE

Upward differentiation

Other than the above.

Not changed.

Set

Downward differentia- TRUE at the last execution  Currently FALSE

TRUE

tion

Other than the above.

Not changed.

Reset

Upward differentiation
Downward differentiation

FALSE at the last execution  Currently TRUE Other than the above. TRUE at the last execution  Currently FALSE Other than the above.

FALSE

Not changed.

FALSE

2

Not changed.

Set and Reset

The following figure shows a programming example and timing chart.
LD

A

abc

S

B

abc

R

A

TRUE FALSE

TRUE B FALSE

abc

TRUE FALSE

LD

A

abc

PS

B

abc

PR

A

TRUE FALSE

TRUE B FALSE

abc

TRUE FALSE

LD

A

abc

NS

B

abc

NR

A

TRUE FALSE

TRUE B FALSE

abc

TRUE FALSE

NJ/NX-series Instructions Reference Manual (W502)

2-57

2 Instruction Descriptions
Additional Information
Differences between the Set and Reset Instructions and the Out Instruction
· The Set and Reset instructions operate only when the input value changes to TRUE. They do not operate when the input value is FALSE. When the input value is FALSE, the output does not change.
· The Out instruction changes the specified variable to TRUE when the result from the previous instruction is TRUE and to FALSE when the result from the previous instruction is FALSE. It operates both when the input is TRUE and when it is FALSE.
Differences between the Set and Reset Instructions and the SR and RS Instructions
· The SR and RS instructions require that the Set input and Reset input are in the same place in the program. You can place the Set and Reset instructions in different places.
Precautions for Correct Use
· If this instruction is in a master control region and the master control region is reset, the value of Out is retained.
· If this instruction is not executed due to the execution of a jump instruction (e.g., the JMP instruction), the value of Out is retained.
· These instructions will not change the value of Out if you specify upward differentiation and the input is TRUE immediately after the power turns ON. The input must first change to FALSE and then to TRUE before the value of Out changes.
· These instructions will change the value of Out if you do not specify upward differentiation and the input is TRUE immediately after the power turns ON. In this case it is not necessary for the input to change to FALSE first.

2-58

NJ/NX-series Instructions Reference Manual (W502)

Sequence Output Instructions

2 Instruction Descriptions

SetBits and ResetBits

SetBits: ResetBits:

Changes consecutive bits in bit string data to TRUE. Changes consecutive bits in bit string data to FALSE.

Instruction SetBits

Name Set Bits

FB/FUN FUN

ResetBits

Reset Bits

FUN

Graphic expression

ST expression

(@)SetBits

EN InOut

ENO

SetBits(InOut, Pos, Size);
2

Pos

Out

Size

(@)ResetBits

EN InOut

ENO

ResetBits(InOut, Pos, Size);

Pos

Out

Size

SetBits and ResetBits

Variables

Name InOut Pos
Size
Out

Meaning Bit string Bit position

I/O In-out

Number of bits
Return value

Input Output

Description Bit string Specified bit position
Number of bits
Always TRUE

Valid range

Unit

Depends on data type. ---

0 to No. of bits in InOut - 1
---
0 to No. of bits in InOut

TRUE only

---

Default
---
0
1
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

InOut Pos Size Out

OK OK OK OK OK OK
OK

Function
 SetBits
The SetBits instruction changes the value of Size bits from the bit position Pos in the bit string InOut to TRUE. The status of the other bits will not change.

NJ/NX-series Instructions Reference Manual (W502)

2-59

2 Instruction Descriptions

 ResetBits

The ResetBits instruction changes the value of Size bits from the bit position Pos in the bit string InOut to FALSE. The status of the other bits will not change.

The following example shows the SetBits instruction when Pos is USINT#3 and Size is USINT#2.

LD

ST

SetBits(abc, USINT#3, USINT#2);

SetBits

EN
InOut abc

ENO abc

USINT#3 Pos USINT#2 Size

Pos=USINT#3

Most-significant bit

Bit 0

InOut=abc 1 1 0 0 0 0 0 1

1 1 0 1 1 0 0 1

Size=USINT#2

Additional Information
Use these instructions to globally set variables with AT specification in memory areas that handle data by word (e.g., the DM Area) to TRUE or FALSE.

Precautions for Correct Use
· If this instruction is in a master control region and the master control region is reset, the value of InOut is retained.
· If this instruction is not executed due to the execution of a jump instruction (e.g., the JMP instruction), the value of InOut is retained.
· The value of InOut does not change if the value of Size is 0. · Return value Out is not used when the instruction is used in ST. · An error occurs in the following cases. ENO will be FALSE, and Out and InOut will not change.
· The value of Pos is greater than No. of bits in InOut - 1. · The value of Size is outside of the valid range. · The value of Pos or Size exceeds the number of bits in InOut.

2-60

NJ/NX-series Instructions Reference Manual (W502)

Sequence Output Instructions

2 Instruction Descriptions

SetABit and ResetABit

SetABit: ResetABit:

Changes the specified bit in bit string data to TRUE. Changes the specified bit in bit string data to FALSE.

Instruction SetABit

Name Set A Bit

FB/FUN FUN

ResetABit

Reset A Bit

FUN

Graphic expression

ST expression

(@)SetABit

EN InOut

ENO

SetABit (InOut, Pos);
2

Pos

Out

(@)ResetABit

EN InOut

ENO

ResetABit (InOut, Pos);

Pos

Out

SetABit and ResetABit

Variables

Name InOut Pos

Meaning Bit string Bit position

I/O In-out Input

Out

Return

Output

value

Description Bit string Specified bit position
Always TRUE

Valid range

Unit

Depends on data type. ---

0 to No. of bits in InOut --- 1

TRUE only

---

Default
---
0
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

InOut Pos Out

OK OK OK OK OK
OK

Function
 SetABit
The SetABit instruction changes the value of the bit at bit position Pos in the bit string InOut to TRUE. The bits that are not specified do not change. Even if EN changes to FALSE after execution, the Pos bit in InOut will not change.

NJ/NX-series Instructions Reference Manual (W502)

2-61

2 Instruction Descriptions

 ResetABit

The ResetABit instruction changes the value of the bit at bit position Pos in the bit string InOut to FALSE.

The bits that are not specified do not change. Even if EN changes to FALSE after execution, the Pos bit in InOut will not change.

The following example shows the SetABit instruction when Pos is USINT#3.

LD

ST

SetABit(abc, USINT#3);

SetABit

EN
InOut abc

ENO abc

USINT#3 Pos

Pos=USINT#3

Most-significant bit

Bit 0

InOut=abc 1 1 0 0 0 0 0 1

1 1 0 0 1 0 0 1

Additional Information

Differences between the SetABit and ResetABit Instructions and the OutABit Instruction
· The SetABit and ResetABit instructions change the value of the specified bit to either TRUE or FALSE.
· With the OutABit instruction, however, you can dynamically change the value to which the specified bit is set.

Precautions for Correct Use
· If this instruction is in a master control region and the master control region is reset, the value of InOut is retained.
· If this instruction is not executed due to the execution of a jump instruction (e.g., the JMP instruction), the value of InOut is retained.
· Return value Out is not used when the instruction is used in ST. · An error occurs in the following case. ENO will be FALSE, and Out and InOut will not change.
· The value of Pos is greater than No. of bits in In - 1.

2-62

NJ/NX-series Instructions Reference Manual (W502)

Sequence Output Instructions

2 Instruction Descriptions

OutABit

The OutABit instruction changes the specified bit in bit string data to TRUE or FALSE.

Instruction OutABit

Name Output A Bit

FB/FUN FUN

Graphic expression

(@)OutABit

EN InOut

ENO

ST expression OutABit (InOut, Pos, BitVal);

Pos

Out

BitVal

2

OutABit

Variables

Name InOut Pos
BitVal Out

Meaning Bit string Bit position
Set value Return value

I/O In-out
Input
Output

Description Bit string Specified bit position
Value to set Always TRUE

Valid range

Unit

Depends on data type. ---

0 to No. of bits in InOut

- 1

---

Depends on data type.

TRUE only

---

Default
---
0
TRUE
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

InOut Pos BitVal Out

OK OK OK OK OK
OK OK

NJ/NX-series Instructions Reference Manual (W502)

2-63

2 Instruction Descriptions

Function

The OutABit instruction stores the value of set value BitVal at bit position Pos in the bit string InOut. Only the bit at Pos changes.
The following example is for when Pos is USINT#2 and BitVal is TRUE.

LD

ST

OutABit(abc, USINT#2, TRUE);

OutABit

EN

ENO

InOut

abc

abc

USINT#2 Pos TRUE BitVal

Pos=USINT#2

Most-significant bit

Bit 0

InOut=abc 1 1 0 0 0 0 0 1

1 1 0 0 0 1 0 1

Additional Information
Differences between the SetABit and ResetABit Instructions and the OutABit Instruction
· The SetABit and ResetABit instructions change the value of the specified bit to either TRUE or FALSE.
· With the OutABit instruction, however, you can dynamically change the value to which the specified bit is set if you change the value of BitVal.
Precautions for Correct Use
· If this instruction is in a master control region and the master control region is reset, the value of InOut is retained.
· If this instruction is not executed due to the execution of a jump instruction (e.g., the JMP instruction), the value of InOut is retained.
· Return value Out is not used when the instruction is used in ST. · An error will occur in the following case. ENO will be FALSE, and Out and InOut will not change.
· The value of Pos is greater than No. of bits in InOut - 1.

2-64

NJ/NX-series Instructions Reference Manual (W502)

Sequence Control Instructions

2
Sequence Control Instructions

Instruction End RETURN MC and MCR
JMP FOR and NEXT
BREAK

Name End Return Master Control Start/ Master Control End Jump Repeat Start/ Repeat End Break Loop

Page 2-66 2-67 2-68 2-80 2-82 2-89

NJ/NX-series Instructions Reference Manual (W502)

2-65

2 Instruction Descriptions

End

The End instruction ends execution of a program in the current task period.

Instruction End

Name End

FB/FUN FUN

Graphic expression
End EN ENO

ST expression None

Variables
None
Function
The End instruction ends execution of a program in the current task period. The following figure shows a programming example. When the End instruction is executed in the example, the SR instruction that follows it is not executed.
LD

Any instructions after this point are not executed.

End EN ENO

SR_instance

A

SR

abc

Set1

Q1

B Reset

Precautions for Correct Use
· This instruction must be used only in a program. · If this instruction is used in a function, function block, or inline ST, a building error will occur. · You must connect this instruction to the left bus bar.

2-66

NJ/NX-series Instructions Reference Manual (W502)

Sequence Control Instructions

2 Instruction Descriptions

RETURN

The RETURN instruction ends a function or function block and returns processing to the calling instruction.

Instruction RETURN

Name Return

FB/FUN FUN

Graphic expression

RETURN

EN

ENO

ST expression RETURN;

2 Variables
None

RETURN

Function

The RETURN instruction ends a function or function block and returns processing to the calling instruction.
The following figure shows a programming example. When the RETURN instruction is executed in the example, the SR instruction that follows it is not executed.

LD

ST

Any instructions after this point are not executed because processing returns to the calling instruction.

RETURN

EN

ENO

SR_instance

A

SR

abc

Set1

Q1

B Reset

RETURN; SR_instance(A, B, abc);

Precautions for Correct Use
· Observe the following precautions if you use this instruction in a ladder diagram. · Use this instruction only in functions and function blocks. If you use it in a program, a building error will occur. · Always connect this instruction directly to the left bus bar.
· Before you execute this instruction set the return values, output variables, and ENO value of the POU.
· If you use this instruction too often, the flow of processing will be difficult to understand. Use it with caution.

NJ/NX-series Instructions Reference Manual (W502)

2-67

2 Instruction Descriptions

MC and MCR

MC: Marks the starting point of a master control region and resets the master control region. MCR: Marks the end point of a master control region.

Instruction MC

Name
Master Control Start

FB/FUN ---

MCR

Master Control End ---

Graphic expression
MC In ENO MCNo
MCR EN ENO MCNo

ST expression None
None

Variables

Name
In (MC instruction only)
MCNo

Meaning
Master control input
Master control number

I/O Input

Description FALSE: Resets the master control region.
Master control number

Valid range

Unit

Depends on data type.

--0 to 14*

* The number is automatically registered by the Sysmac Studio. You do not need to set it.

Default ---
0

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In (MC

OK

instruction

only)

MCNo

OK

Function
Master control is used to stop processing or place in an equivalent status all POUs in a specified region of a program. You can use master control to easily control the execution conditions for a relatively long segment of processing.
The region in the program for which master control is applied is called the master control region. You place the MC instruction at the start of the master control region and the MCR instruction at the end. When the value of the master control input In changes to FALSE, the outputs for all LD instructions that are connected to the left bus bar in the master control region are forced to change to FALSE. This is called a master control reset.
When master control is reset, the POUs that follow the LD instructions, as a rule, operate as if the execution condition is FALSE. There are, however, some POUs that operate differently. This is explained later.

2-68

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Sequence Control Instructions

Master control region

MC In ENO 0 MCNo
A

The value that is output from the LD instruction changes to FALSE regardless of the value of variable A.

MCR

EN ENO

0 MCNo

2

If the value of In is TRUE, then master control is not reset. The POUs in the master control region operate normally.

MC and MCR

POU Operation during a Master Control Reset
The operation of the POUs when master control is reset depends on the POU as described in the following table.

POU Out and OutABit instructions OutNot instruction Set and Reset instructions TON instruction TOF instruction
TP instruction
AccumulationTimer instruction
Timer instructions CTU, CTD, and CTUD instructions JMP instruction

Operation

FALSE is output to the specified variable.

FALSE is output to the specified variable.

The output from before the master control reset is retained.

The instruction operates with a FALSE value for timer input In. That means that the timer is reset. The value of elapsed time ET changes to 0 and the value of timer output Q changes to FALSE.

The instruction operates with a TRUE value for timer input In. That means that the timer is reset. The value of elapsed time ET changes to 0 and the value of timer output Q changes to TRUE. However, if an Out instruction is connected to Q, the execution condition to the Out instruction is FALSE.

The instruction operates with a FALSE value for timer input In. That means that the timer is reset.

Timing active:

The value of elapsed time ET is incremented to the end and then returns to 0. The value of timer output Q is TRUE until the end of timing, and then it changes to FALSE.

Timing not active: The value of ET changes to 0 and the value of Q changes to FALSE.

However, if an Out instruction is connected to Q, the execution condition to the Out instruction is FALSE even while timing is active.

The instruction operates with a FALSE value for timer input In. That means that the timer stops. The values of elapsed time ET and timer output Q are retained. However, if an Out instruction is connected to Q, the execution condition to the Out instruction is FALSE even if the value of Q is TRUE. However, reset Reset is enabled.

The instruction operates with a FALSE value for timer input In. That means that the timer is reset. Remaining time ET is set to the value of set time PT, and the value of timer output Q changes to FALSE.

These instructions are not executed. If the instruction was in operation before the master control reset, the count value from before the reset is held. If an Out instruction is connected to the Counter Completion Flag, Q, the execution condition to the Out instruction is FALSE.

This instruction is not executed.

NJ/NX-series Instructions Reference Manual (W502)

2-69

2 Instruction Descriptions

POU FOR and NEXT instructions BREAK instruction Function blocks that are executed over more than one task period (i.e., instructions with Done, Busy, and Error output variables)
Other functions Other function blocks

Operation
These instructions are not executed.
This instruction is not executed.
The power flow from the left bus bar changes to FALSE. If the instruction was operating before the master control reset, execution of the instruction is continued until processing is completed. Busy, Done, and Error outputs will be made, but FALSE will always be output if the next instruction is an output instruction. If a variable is directly connected to Busy, Done, or Error, the proper value for the instruction specifications will be assigned to that variable. You can also get the value of Busy, Done, or Error in the form instance_name.output_variable.
These are not executed.
The power flow from the left bus bar changes to FALSE.

The operation of some typical instructions is described below.

 Out
FALSE is output while the master control is reset.

MC_ON 0

MC
In ENO MCNo

A

B

MCR
EN ENO 0 MCNo

MC_ON

TRUE FALSE

A

TRUE FALSE

Output from TRUE LD instruction FALSE

B TRUE FALSE

Master control reset

 OutNot

FALSE is output while the master control is reset. Caution is required because this operation of the OutNot instruction is different from when the output of the previous LD instruction is FALSE.

MC_ON

MC

In ENO 0 MCNo

MC_ON

TRUE FALSE

Master control reset

A

B

A

TRUE FALSE

MCR
EN ENO 0 MCNo

Output from TRUE LD instruction FALSE
B TRUE FALSE

2-70

NJ/NX-series Instructions Reference Manual (W502)

Sequence Control Instructions

2 Instruction Descriptions

 Set and Reset

The previous value of the output is retained while the master control is reset.

MC_ON 0

MC
In ENO MCNo

Master control reset

MC_ON

TRUE FALSE

A

B

S

A

TRUE FALSE

Output from TRUE LD instruction FALSE

MCR EN ENO

B TRUE FALSE

2

0 MCNo

Master control reset

MC and MCR

MC_ON 0

MC
In ENO MCNo

A

B

R

MCR
EN ENO 0 MCNo

MC_ON

TRUE FALSE

A

TRUE FALSE

Output from TRUE LD instruction FALSE

B TRUE FALSE

Master control reset

MC_ON

TRUE FALSE

A

TRUE FALSE

Output from TRUE LD instruction FALSE

B TRUE FALSE

Master control reset

MC_ON

TRUE FALSE

A

TRUE FALSE

Output from TRUE LD instruction FALSE

B TRUE FALSE

NJ/NX-series Instructions Reference Manual (W502)

2-71

2 Instruction Descriptions

 CTU, CTD, and CTUD

The previous counter value is retained while the master control is reset. When the master control reset is cleared, counting continues from the counter value that was retained.

MC_ON 0

MC
In ENO MCNo

CTU_instance

A

CTU

CU

Q

Reset CV B

PV

MCR
EN ENO 0 MCNo

MC_ON

TRUE FALSE

A

TRUE FALSE

Output from TRUE LD instruction FALSE

B

Master control reset

Operation of POUs with Input Upward Differentiation or Input Downward Differentiation
The POUs that are given in the following table have upward or downward differentiation specifications.

Differentiation Input upward differentiation
Input downward differentiation

Instructions
· LD, LDN, AND, ANDN, OR, ORN, and OUT with upward differentiation specifications
· R_TRIG (Up) · Functions with an @ input upward differentiation option · Functions blocks (e.g., counter instructions) with input upward differentiation
specifications
· LD, LDN, AND, ANDN, OR, ORN, and OUT with downward differentiation specifications
· F_TRIG (Down)

When the master control is reset or the reset is cleared, the execution conditions for these POUs change. That means that the upward or downward differentiation conditions for these POUs may be met. If the upward or downward differentiation conditions are met, then the instructions are executed accordingly. The operation of some typical instructions is described below.

 R_TRIG (Up)

When the master control is reset, the execution condition changes to FALSE. If the execution condition is TRUE when the master control reset is cleared, the input upward differentiation condition is met and the instruction operates accordingly.

MC_ON 0

MC
In ENO MCNo

R_TRIG_instance

A

R_TRIG

Clk

QB

MCR
EN ENO 0 MCNo

Master control reset

MC_ON

TRUE FALSE

A

TRUE FALSE

Output from TRUE LD instruction FALSE

B TRUE FALSE

Input upward differentiation condition met.

2-72

NJ/NX-series Instructions Reference Manual (W502)

Sequence Control Instructions

2 Instruction Descriptions

 F_TRIG (Down)

When the master control is reset, the execution condition changes to FALSE. If the previous execution condition was TRUE, then the input downward differentiation condition is met. However, the value of the output from the F_TRIG (Down) instruction during the master control reset is forced to change to FALSE, so the output value changes to FALSE.

MC_ON

MC

Master control reset

In ENO 0 MCNo

MC_ON

TRUE FALSE

F_TRIG_instance

A

F_TRIG

A

TRUE FALSE

Clk

QB

MCR

Output from LD instruction

TRUE FALSE

2

EN ENO 0 MCNo

B TRUE FALSE

MC and MCR

The input downward differentiation condition is met, but master control is reset, so the output is FALSE.

 Set and Reset with Input Upward Differentiation Specification

The previous value of the output is retained while the master control is reset. When the master control reset is cleared, the execution condition changes to TRUE and the instruction operates.

MC_ON 0

MC
In ENO MCNo

Master control reset

MC_ON

TRUE FALSE

A

B

S

MCR
EN ENO 0 MCNo

A

TRUE FALSE

Output from TRUE LD instruction FALSE

B TRUE FALSE

Master control reset

MC_ON

TRUE FALSE

A

TRUE FALSE

Output from TRUE LD instruction FALSE

B TRUE FALSE

Here, the input upward differentiation condition is met and the output value changes to TRUE.

NJ/NX-series Instructions Reference Manual (W502)

2-73

2 Instruction Descriptions

MC_ON 0

MC
In ENO MCNo

A

B

PR

MCR
EN ENO 0 MCNo

MC_ON

TRUE FALSE

A

TRUE FALSE

Output from LD instruction

TRUE FALSE

B TRUE FALSE

Master control reset Master control reset

MC_ON

TRUE FALSE

A

TRUE FALSE

Output from LD instruction

TRUE FALSE

B TRUE FALSE

Here, the input upward differentiation condition is met and the output value changes to FALSE.

 Set and Reset with Input Downward Differentiation Specification

When the master control is reset, the execution condition changes to FALSE. If the previous execution condition was TRUE, then the input downward differentiation condition is met. However, during the master control reset, the previous output value is retained, so as a result the value of the output is retained.

MC_ON 0

MC
In ENO MCNo

MC_ON

TRUE FALSE

Master control reset

A

B

NS

MCR
EN ENO 0 MCNo

A

TRUE FALSE

Output from LD instruction

TRUE FALSE

B TRUE FALSE

The input downward differentiation condition is met, but master control is reset, so the output is retained.

MC_ON 0

MC
In ENO MCNo

MC_ON

TRUE FALSE

Master control reset

A

B

NR

MCR
EN ENO 0 MCNo

A

TRUE FALSE

Output from LD instruction

TRUE FALSE

B TRUE FALSE

The input downward differentiation condition is met, but master control is reset, so the output is retained.

2-74

NJ/NX-series Instructions Reference Manual (W502)

Sequence Control Instructions

2 Instruction Descriptions

 CTU, CTD, and CTUD

When the master control is reset, the value of the counter input changes to FALSE. If the value of the counter input is TRUE when the master control reset is cleared, the input upward differentiation condition is met and the instruction counts.

MC_ON

MC

Master control reset

In ENO

0 MCNo CTU_instance

MC_ON

TRUE FALSE

A

CTU

CU

Q

A

TRUE FALSE

Reset CV B

PV MCR

Output from LD instruction

TRUE FALSE

2

EN ENO

B

0 MCNo

Input upward differentiation condition met.

MC and MCR

Always use the MC and MCR instructions as a pair in the same POU. The same value is used for

master control number MCNo for both of the paired MC and MCR instructions. The user does not set the value of MCNo. It is automatically registered by the Sysmac Studio.

The MC and MCR instructions can be nested to up to 15 levels.

MC In ENO 0 MCNo
MC In ENO 1 MCNo
MCR EN ENO 1 MCNo
MCR EN ENO 0 MCNo
The following figure shows a programming example.
If the value of bit A is FALSE, the master control region is reset. While the master control region is in a reset state, the TON and MOVE instructions are not executed. Also the Out instruction and OutNot instruction will output FALSE to bits D and E.

NJ/NX-series Instructions Reference Manual (W502)

2-75

2 Instruction Descriptions

A

MC

In ENO 0 MCNo

B T#10ms

TON_instance

TON

In

Q

PT

ET

abc def

Reset.

UINT#0 UINT#10 UINT#1

FOR

EN

ENO

InitVal Index

EndVal

StepVal

position

These are not executed.

INT#0

MOVE

EN

ENO

In

Out

array[position]

NEXT EN ENO

C

D

E

FALSE is output.

MCR EN ENO 0 MCNo
Precautions for Correct Use
· These instructions must be used in a ladder diagram. They cannot be used in ST. They also cannot be used in inline ST in a ladder diagram.
· Always connect In directly to the left bus bar. You cannot pass a variable or constant to In. · Always use the MC and MCR instructions as a pair in the same POU. · Always place the MCR instruction after the MC instruction. · Do not nest the MC and MCR instructions to more than 15 levels. · If there is inline ST in the master control region, the inline ST is not executed when the master control
region is reset.

2-76

NJ/NX-series Instructions Reference Manual (W502)

Sequence Control Instructions

2 Instruction Descriptions

· If you use the MC and MCR instructions and the JMP instruction together, the operation is as follows:
· The following figure shows an MC-MCR pair inside a JMP-Label pair. Here, the jump is executed regardless of the value of In.

Flow of processing

JMP instruction executed.

Label

MC

In ENO

Not executed due

0 MCNo

to JMP instruction.

MCR

2

EN ENO

0 MCNo

Label

MC and MCR

Instructions after the label are executed.

· The following figure shows a JMP-Label pair inside an MC-MCR pair. Here, operation is as given in the following table.

Value of In TRUE FALSE

Operation Master control region is not reset. The jump is made. Master control region is reset. The jump is not made.

In = TRUE

Flow of processing

MC instruction not executed.
JMP instruction executed.
Not executed due to JMP instruction.

MC In ENO 0 MCNo
Label
Label

In = FALSE

Flow of processing MC instruction executed.
0

MC
In ENO MCNo

JMP instruction not executed.

Label

Master control reset

Label

Instructions after the label are executed.
MCR instruction not executed.

MCR
EN ENO 0 MCNo

MCR instruction executed.

MCR
EN ENO 0 MCNo

NJ/NX-series Instructions Reference Manual (W502)

2-77

2 Instruction Descriptions

· The instructions are in the following order in the following figure: JMP instruction, MC instruction, Label, and MCR instruction. First, the jump is made. As a result, the MC instruction is not executed. Therefore, the instructions after the Label instruction are executed. If the value of In is FALSE, the MCR instruction is executed, but nothing changes.

In = TRUE

In = FALSE

Flow of processing JMP instruction executed.
Label

Flow of processing

JMP instruction executed.

Label

Not executed due to JMP instruction.
MC instruction not executed.

MC In ENO 0 MCNo
Label

Not executed due to JMP instruction.
MC instruction not executed.

MC In ENO 0 MCNo
Label

Instructions after the label are executed.
MCR instruction not executed.

MCR
EN ENO 0 MCNo

Instructions after the label are executed.
MCR instruction executed, but nothing changes.

MCR
EN ENO 0 MCNo

· The instructions are in the following order in the following figure: MC instruction, JMP instruction, MCR instruction, and Label. Here, operation is as given in the following table.

Value of In TRUE FALSE

Operation Master control region is not reset. The jump is made. Master control region is reset. The jump is not made.

In = TRUE Flow of processing

MC instruction not executed.
JMP instruction executed.

MC In ENO 0 MCNo
Label

In = FALSE

Flow of processing

MC instruction executed.
Master control reset

MC In ENO 0 MCNo
Label

Not executed due to JMP instruction.
MCR instruction not executed.

Label

MCR
EN ENO 0 MCNo

JMP instruction not executed.
MCR instruction executed.

Label

MCR
EN ENO 0 MCNo

Instructions after the label are executed.

2-78

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Sequence Control Instructions

· If you use the MC and MCR instructions and the FOR and NEXT instructions together, the operation is as follows:
· The following figure shows an MC-MCR pair inside a FOR-NEXT pair. Here, operation is as given in the following table.

Value of In

Operation

TRUE

Master control region is not reset. The FOR loop is executed.

FALSE

Master control region is reset. The FOR loop is executed, but the instructions between the MC and MCR instructions are not executed.

In = TRUE

In = FALSE

Flow of processing

Flow of processing

2

FOR instruction executed.

FOR

FOR instruction executed.

FOR

MC and MCR

MC instruction not executed.
MCR instruction not executed.

MC In ENO 0 MCNo
MCR EN ENO 0 MCNo
NEXT

MC instruction executed.
Master control reset
MCR instruction executed.

MC In ENO 0 MCNo
MCR EN ENO 0 MCNo
NEXT

· The following figure shows a FOR-NEXT pair inside an MC-MCR pair. Here, operation is as given in the following table.

Value of In

Operation

TRUE

Master control region is not reset. The FOR loop is executed.

FALSE

Master control region is reset. The FOR loop is not executed.

In = TRUE Flow of processing

In = FALSE Flow of processing

MC instruction not executed.
FOR instruction executed.

MC In ENO 0 MCNo
FOR

MC instruction executed.
FOR instruction not executed.

MC In ENO 0 MCNo
FOR

NEXT

Master control reset

NEXT

MCR instruction not executed.

MCR
EN ENO 0 MCNo

MCR instruction executed.

MCR
EN ENO 0 MCNo

· A building error occurs if the FOR, NEXT, MC, and MCR instructions are used in either of the following orders.

FOR, MC, NEXT, MCR, or MC, FOR, MCR, NEXT

NJ/NX-series Instructions Reference Manual (W502)

2-79

2 Instruction Descriptions

JMP

The JMP instruction moves processing to the specified jump destination.

Instruction JMP

Name Jump

FB/FUN FUN

Graphic expression Label

ST expression None

Variables
None
Function
When the execution condition is TRUE, the JMP instruction moves processing to the jump destination specified by a Label in a ladder diagram. The label can be any text string. The following figure shows a programming example. This example uses the text string STEP1 as the label. When the JMP instruction is executed, processing moves to the location marked STEP1. In this example, the Out instruction between the JMP instruction and the Label is not executed, and the value of variable B is retained.
LD

STEP1

Not executed and value of variable B retained.

A

B

STEP1

C

D

Additional Information
· You can also jump to a Label instruction above the JMP instruction in the section. · You can use the same Label instruction as the jump destination for more than one JMP instruction.
Precautions for Correct Use
· You cannot omit labels. If you omit a label, a building error will occur. · Place the JMP and Label instructions in the same POU and in the same section. · Do not set the same Label instruction more than once in the same section. · You cannot jump into a FOR-NEXT loop from outside the loop.

2-80

NJ/NX-series Instructions Reference Manual (W502)

Sequence Control Instructions

2 Instruction Descriptions

· The following restrictions apply to the characters that can be used as labels.

Item

Specification

Maximum number of bytes

127 bytes

127 characters when converted to ACSII

31 characters when converted to Japanese characters (including single-byte kana)

Character code

UTF-8

Applicable characters

Not case sensitive.

English alphanumeric characters and other language characters.

Symbols: _ (underbar) and ~ (tilda)

Prohibited text strings

· Any text string that starts with ASCII characters 0 to 9 (character codes 16#30 to 16#39)

2

· A text string that consists of only a single _ (underbar) ASCII character

JMP

· Any text string that includes two or more consecutive _ (underbar) ASCII characters

· Any text string that starts with an _ (underbar) ASCII character

· Any text string that ends with an _ (underbar) ASCII character · Any text string that starts with `P_'

Prohibited characters

Blank space ! " # $ & ' ( ) * + , - . / : ; < = > ? @ [ ] ^ ` %

· Variable names cannot be used as labels.

NJ/NX-series Instructions Reference Manual (W502)

2-81

2 Instruction Descriptions

FOR and NEXT

FOR: NEXT:

Marks the starting position for repeat processing and specifies the repeat condition. Marks the ending position for repeat processing.

Instruction FOR

Name Repeat Start

FB/FUN FUN

NEXT

Repeat End

FUN

Graphic expression

FOR

EN

ENO

InitVal Index

EndVal

StepVal

NEXT EN ENO

ST expression
FOR Index:=InitVal TO EndVal BY StepVal DO
expression END_FOR*;
* In ST, do not use NEXT to mark the ending position of repeat processing. Use END_FOR instead.

Variables

Name

Meaning

I/O

InitVal

Initial value

EndVal StepVal

End value Increment

Input

Index

Control variable

Output

Description

Valid range

Unit

Value to set the Index to

when repetition is started. Depends on data

Value of Index where repeti- type.*1

tion is stopped

---

Value to add to Index each Depends on the data time processing is repeated type.*3

Loop index

Depends on data type. ---

Default *2 *4
---

*1 When using a ladder diagram, set InitVal so that it is less than EndVal. *2 If you omit an input parameter, the default value is not applied. A building error will occur. *3 When using a ladder diagram, 0 and negative numbers are not included. When using an ST program, 0 is not included. *4 If you omit the input parameter in a ladder diagram, the default value is not applied. A building error will occur. If you omit
the input parameter in ST, a default value of 1 is applied.

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

InitVal EndVal StepVal Index

OK OK OK OK OK OK OK OK An enumeration, array element or structure member can also be specified.*
OK OK OK OK OK OK OK OK An array element or structure member can also be specified.
OK OK OK OK OK OK OK OK An array element or structure member can also be specified.
OK OK OK OK OK OK OK OK An array element or structure member can also be specified.

* You cannot specify enumerations in ladder diagrams.

2-82

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Sequence Control Instructions

Function

The FOR and NEXT instructions repeat the processing that you place between them. (FOR and END_FOR are used in ST.) The processing procedure for a FOR-NEXT loop is as follows:
1 The value of InitVal is set in control variable Index.

2 The values of StepVal, Index, and EndVal are checked to see if the conditions in the following

table are met. If the conditions are met, processing moves to step 3. If the conditions are not

met, repeat processing is not performed, and processing moves to the next process after the

NEXT instruction (or END_FOR in ST).

2

Programming language

Conditions to start repeat processing

Ladder diagram

StepVal  0 and Index  EndVal

ST

StepVal  0 and Index  EndVal

StepVal < 0 and Index  EndVal

FOR and NEXT

3 The values of Index and EndVal are checked to see if the conditions in the following table are
met. If the conditions are met, processing moves to step 4. If the conditions are not met, repeat processing is ended, and processing moves to the next process after the NEXT instruction (or END_FOR in ST).

Programming language Conditions to continue repeat processing

Ladder diagram

Index  EndVal

ST

If StepVal  0, Index must be  EndVal

If StepVal < 0, Index must be  EndVal

4 The processing between the FOR instruction and the NEXT instruction (or the END_FOR
instruction in ST) is executed once.

5 The value of StepVal is added to Index.

6 Processing returns to step 3.

The following example is for when InitVal is INT#0, EndVal is INT#9, and StepVal is INT#1. The MOVE instruction is executed 10 times and INT#0 is assigned to array variables AryOut[0] to AryOut[9].

LD

ST

INT#0 INT#9 INT#1

FOR

EN

ENO

InitVal Index

EndVal

StepVal

position

INT#0

MOVE

EN

ENO

In

Out

AryOut[position]

FOR position:=INT#0 TO INT#9 BY INT#1 DO AryOut[position]:=INT#0;
END_FOR;

NEXT EN ENO

NJ/NX-series Instructions Reference Manual (W502)

2-83

2 Instruction Descriptions

START
INT#0 InitVal INT#9 EndVal INT#1 StepVal
InitVal  Index

StepVal  0 and Index < EndVal*

FALSE

TRUE Index  EndVal

FALSE

TRUE
INT#0AryOut[Index] Index + StepVal  Index

INT#0 is assigned in order to AryOut[0] to AryOut[9].

AryOut[0] AryOut[1] AryOut[2] AryOut[3] AryOut[4] AryOut[5] AryOut[6] AryOut[7] AryOut[8] AryOut[9]

INT#0 INT#0 INT#0 INT#0 INT#0 INT#0 INT#0 INT#0 INT#0 INT#0

END

* For ST: InitVal  EndVal

ST Programming Example That Uses Expressions or Functions for Input Variables.
If you use these instructions in an ST program, you can use the following notation for the InitVal, EndVal, and StepVal input variables. · An expression with an integer result · A function that returns an integer · A function that returns an enumerator
The following example programs a function for EndVal and an expression for StepVal. A := DINT#1; B := DINT#2; C := REAL#9.6; FOR i := 0 TO RoundUp(C) BY A+B DO DINTArray[i] := i; END_FOR;

Version Information Sysmac Studio version 1.08 or higher is required to use expressions for EndVal and StepVal. You can use an expression for InitVal even with Sysmac Studio version 1.07 or lower.

2-84

NJ/NX-series Instructions Reference Manual (W502)

Sequence Control Instructions

2 Instruction Descriptions

Additional Information

· Execute a BREAK instruction (or an EXIT instruction in ST) to cancel repeat processing. The processing between the BREAK instruction and the NEXT instruction will not be executed.

· FOR-NEXT loops (or FOR-END_FOR loops in ST) can be nested. In the following figure, the processes are performed in the following order.

Process A  Process B  Process B  Process C  Process A  Process B  Process B  Process C  Process A  Process B  Process B  Process C

2

FOR

InitVal=INT#0 EndVal=INT#2 StepVal=INT#1

FOR and NEXT

Process A
FOR

InitVal=INT#0 EndVal=INT#1 StepVal=INT#1

Process B

NEXT Process C
NEXT

Precautions for Correct Use

· In a ladder diagram, connect the FOR and NEXT instructions directly to the left bus bar.
· Always use the FOR and NEXT instructions (FOR and END_FOR statements in ST) as a pair. A programming error will occur if there is not the same number of both instructions.
· Program the paired FOR and NEXT instructions in the same section.
· Set the condition to end repetition carefully so that you do not create an infinite loop. If an infinite loop occurs, task execution will time out.
Example: If the values that are given in the following table are used for the input parameters to the variables, the value of Index will never be greater than the value of EndVal because the maximum value of SINT data is 127. Therefore, an infinite loop is created. Do not set the maximum value for the data type in EndVal.

Variable InitVal EndVal StepVal Index

Value of input parameter SINT#0 SINT#127 SINT#1 ---

NJ/NX-series Instructions Reference Manual (W502)

2-85

2 Instruction Descriptions

· The following table describes operation according to the values of StepVal, InitVal, and EndVal.

Programming language
Ladder diagram

Value of StepVal StepVal > 0

StepVal < 0

StepVal = 0

ST

StepVal > 0

StepVal < 0

StepVal = 0

Values of InitVal and EndVal
InitVal  EndVal InitVal > EndVal
InitVal < EndVal
InitVal  EndVal
InitVal < EndVal InitVal  EndVal
InitVal  EndVal InitVal > EndVal
InitVal < EndVal
InitVal  EndVal InitVal  EndVal InitVal > EndVal

Operation
Operation is normal.
The processing between the FOR and NEXT instructions is not executed even once. An error does not occur.
The processing between the FOR and NEXT instructions is executed an indeterminate number of times. Do not use settings like these. An error does not occur.
The processing between the FOR and NEXT instructions is not executed even once. An error does not occur.
An infinite loop occurs and task execution times out.
The processing between the FOR and NEXT instructions is not executed even once. An error does not occur.
Operation is normal.
The processing between the FOR and END_FOR instructions is not executed even once. An error does not occur.
The processing between the FOR and END_FOR instructions is not executed even once. An error does not occur.
Operation is normal.
An infinite loop occurs and task execution times out.
The processing between the FOR and END_FOR instructions is not executed even once. An error does not occur.

· The FOR-NEXT loops can be nested up to 15 levels, but count all nesting levels for the following instructions: IF, CASE, FOR, WHILE, and REPEAT.
· If loops are nested, you will need one BREAK instruction (or one EXIT instruction in ST) for each nesting level to cancel all repeat processing.
· Do not use Jump Instructions (e.g., the JMP instruction) to interrupt repeat processing. Always use a BREAK instruction (or an EXIT instruction in ST) to cancel repeat processing.
· The operation to change the values of InitVal, EndVal, and StepVal during repeat processing is different in a ladder diagram and ST.

Variable InitVal EndVal StepVal

Operation

Ladder diagram

ST

The new value is not applied until repeat pro- The new value is not applied until repeat pro-

cessing is completed.

cessing is completed.

The new value is applied even during repeat processing.

The intended operation may not occur. Do not change the value of this variable during repeat processing.

· In a ladder diagram, use the same data type for InitVal, EndVal, StepVal, and Index. Otherwise, a building error will occur.
· Set the data type of Index to include the valid ranges of InitVal, EndVal, and StepVal. Otherwise, a building error will occur.

2-86

NJ/NX-series Instructions Reference Manual (W502)

Sequence Control Instructions

2 Instruction Descriptions

· The value of Index after repeat processing is different in a ladder diagram and ST. In a ladder diagram, the value of StepVal is not added to Index at the end of repeat processing. In ST, the value of StepVal is added to Index at the end of repeat processing. Processing is repeated the same number of times.

The following example is for when InitVal is 1, EndVal is 100 and StepVal is 1. Ladder diagram: The value of Index will be 100 after 100 repetitions. ST: The value of Index will be 101 after 100 repetitions.
· Caution is required when you specify upward or downward differentiation for a LD, AND, or OR instruction in a FOR loop in a ladder diagram and an array is used for the LD, AND, or OR instruction.

For upward or downward differentiation, the value of the specified variable at the previous execution

is compared with the value of the specified variable at the current execution to determine upward or

downward differentiation. Normally, the value of the specified variable does not change every time the instruction is executed. However, if an array is specified in a FOR loop, the array element

2

changes each time the instruction is executed. Therefore, upward or downward differentiation is

determined by comparing different array elements.

The following table shows the relationship between the values of x[i-1] and x[i], and the increment

processing for Count1[i].

FOR and NEXT

Value of x[i-1] TRUE TRUE FALSE FALSE

Value of x[i] TRUE FALSE TRUE FALSE

Increment processing for Count1[i] Not executed. Not executed. Executed. Not executed.

FOR

EN

ENO

DINT#0 InitVal Index i

DINT#10 EndVal

DINT#1 StepVal

x[i]

Inc

Count1[i]

EN ENO InOut

Upward differentiation is detected by comparing x[i] to x[i-1].

NEXT EN ENO

· In the following programming, upward differentiation of x[i] is detected by the R_TRIG instruction. An instance of the R_TRIG instruction is provided for each element of x[i], so it is possible to detect the elements of x[i] for which there was upward differentiation. The following table shows the relationship between the value of x[i] for the previous execution of R_TRIG_instance[i], the value of x[i] for the current execution of R_TRIG_instance[i], and the increment processing of Count2[i].

Value of x[i] for previous execution of R_TRIG_in-
stance[i] TRUE TRUE FALSE FALSE

Value of x[i] for current execution of R_TRIG_in-
stance[i] TRUE FALSE TRUE FALSE

Increment processing for Count2[i]
Not executed. Not executed. Executed. Not executed.

NJ/NX-series Instructions Reference Manual (W502)

2-87

2 Instruction Descriptions

DINT#0 DINT#10 DINT#1

FOR

EN

ENO

InitVal Index i

EndVal

StepVal

The values of x[i] at the previous execution and the current execution of R_TRIG_instance[i] are compared to determine upward differentiation.

R_TRIG_instance[i]

x[i]

R_TRIG

Clk

Q

R_TRIG_instance[i].Q Count2[i]

Inc
EN ENO InOut

NEXT EN ENO

2-88

NJ/NX-series Instructions Reference Manual (W502)

Sequence Control Instructions

2 Instruction Descriptions

BREAK

The BREAK instruction is used to cancel repeat processing from the lowest level FOR instruction to the NEXT instruction.

Instruction BREAK

Name Break Loop

FB/FUN FUN

Graphic expression
BREAK EN ENO

ST expression None

2 Variables
None

BREAK

Function
The BREAK instruction cancels the repeat processing from the lowest level FOR instruction to the NEXT instruction. It moves processing to the next instruction after the NEXT instruction. The processing between the BREAK instruction and the NEXT instruction is not executed. The following figure shows a programming example. When the FOR loop is executed, the value of variable A is checked each time. If the value of variable A is TRUE, the repeat processing is ended immediately. In this example, the Out instruction after the BREAK instruction is not executed, and the value of variable C is retained.
LD

INT#0 INT#10 INT#1
A

FOR

EN

ENO

InitVal Index

EndVal

StepVal

BREAK EN ENO

position

B

C

NEXT EN ENO

NJ/NX-series Instructions Reference Manual (W502)

2-89

2 Instruction Descriptions

START
INT#0 InitVal INT#10 EndVal INT#1 StepVal

StepVal > 0 and InitVal < EndVal

FALSE

TRUE InitVal  Index

Index  EndVal

FALSE

TRUE
A FALSE

TRUE

B  C

If the value of A is TRUE, the repeat processing is ended immediately. The value of C is retained.

END
Precautions for Correct Use
· Always place this instruction between the FOR and NEXT instructions. · If you nest FOR and NEXT instructions, one BREAK instruction is required for each nesting level to
end all of the repeat processing. · Do not use Jump Instructions (e.g., the JMP instruction) to interrupt repeat processing. Always use a
BREAK instruction to cancel repeat processing.

2-90

NJ/NX-series Instructions Reference Manual (W502)

Comparison Instructions

2
Comparison Instructions

Instruction EQ (=) NE (<>) LT (<), LE (<=), GT (>), and GE (>=)
EQascii NEascii LTascii, LEascii, GTascii, and GEascii
Cmp ZoneCmp TableCmp AryCmpEQ and AryCmpNE
AryCmpLT, AryCmpLE, AryCmpGT, and AryCmpGE
AryCmpEQV and AryCmpNEV
AryCmpLTV, AryCmpLEV, AryCmpGTV, and AryCmpGEV

Name
Equal
Not Equal
Less Than/Less Than Or Equal/ Greater Than/Greater Than Or Equal
Text String Comparison Equal
Text String Comparison Not Equal
Text String Comparison Less Than/Text String Comparison Less Than or Equal Text String Comparison Greater Than/Text String Comparison Greater Than or Equal
Compare
Zone Comparison
Table Comparison
Array Comparison Equal/ Array Comparison Not Equal
Array Comparison Less Than/Array Comparison Less Than Or Equal Array Comparison Greater Than/Array Comparison Greater Than Or Equal
Array Value Comparison Equal/Array Value Comparison Not Equal
Array Value Comparison Less Than/Array Value Comparison Less Than Or Equal Array Value Comparison Greater Than/Array Value Comparison Greater Than Or Equal

Page 2-92 2-94 2-97 2-100 2-102
2-104
2-107 2-109 2-111 2-114
2-116
2-119
2-121

NJ/NX-series Instructions Reference Manual (W502)

2-91

2 Instruction Descriptions

EQ (=)

The EQ (=) instruction determines if the contents of two or more variables are all equivalent.

Instruction

Name

EQ (=)

Equal

FB/FUN FUN

Graphic expression

(@)EQ

EN

Out

In1

::

InN

ST expression
Out:=(In1=In2) & (In2=In3) & ··· & (InN-1=InN);

(@)=

EN

Out

In1

::

InN

Variables

Name In1 to InN
Out

Meaning
Comparison data
Comparison result

I/O Input
Output

Description
Values to compare, N = 2 to 5
Comparison result

Valid range Depends on data type.
Depends on data type.

Unit
---
---

Default 0*
---

* If you omit the input parameter that connects to InN, the default value is not applied, and a building error will occur. For example, if N is 3 and the input parameters that connect to In1 and In2 are omitted, the default values are applied, but if the input parameter that connects to In3 is omitted, a building error will occur.

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In1 to InN Out

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK *
Enumerations can also be specified. OK

* You can specify TIME, DATE, TOD, DT and STRING data with Sysmac Studio version 1.02 or higher. If you open a project that was created with Sysmac Studio version 1.01 or lower on Sysmac Studio version 1.02 or higher and then use any of these data types, refresh the display. To refresh the display, right-click the instruction in the Edit Pane and select Update. If you do not refresh the display, a building error will occur.

Function
The EQ (=) instruction determines if the contents of from two to five variables In1 to InN are all equivalent. The comparison result Out is TRUE only when all values are equivalent. Otherwise, the value of Out is FALSE. When comparing STRING data, "equivalent" means that both the lengths and contents of the text strings are the same.

2-92

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Comparison Instructions

The following example is for when In1 is INT#3, In2 is INT#5 and In3 is INT#10. The value of variable abc will be FALSE.

LD

ST

abc:=(INT#3=INT#5)&(INT#5=INT#10);

EQ

abc

EN INT#3 In1 INT#5 In2 INT#10 In3

The EQ instruction determines if In1 to In3 are all equivalent.

2

If they are different, the value of abc will be FALSE.

EQ (=)

Compared to see if they are equivalent. Different.

In1 INT#3

In2 INT#5

In3 INT#10

Out=abc FALSE

Additional Information
· The functions of the EQ instruction and the = instruction are exactly the same. Use the form that is easier to use.
· When you compare TIME, DT, or TOD data, adjust the data so that the precision of the values is the same. Use the following instructions to adjust the precision of the values: TruncTime (page 2-658), TruncDt (page 2-662), and TruncTod (page 2-666).

Precautions for Correct Use
· If the data types of In1 to InN are different, they will be expanded to a data type that includes the ranges of all of the data types.
· You cannot compare bit string data (BYTE, WORD, DWORD, or LWORD) with integers. You cannot compare bit string data to real number data (SINT, INT, DINT, LINT, USINT, UDINT, ULINT, REAL, and LREAL).
· Signed integers (SINT, INT, DINT, and LINT) cannot be compared to unsigned integers (USINT, UINT, UDINT, and ULINT).
· Always compare data with the same data type for TIME, DATE, TOD, DT, and STRING data. If variables with different data types are specified, a building error will occur.
· You can compare enumerations only to other enumerations. The data types must also be the same to compare enumerations.
· Two values that are positive infinity or two values that are negative infinity are equivalent.
· If any of the values of In1 to InN is nonnumeric data, the value of Out is FALSE. · If this instruction is used in a ladder diagram, the value of Out changes to FALSE if an error occurs in
the previous instruction on the rung.
· If In1 to InN are real numbers, the desired results may not be achieved due to rounding error. Do not use this instruction to check if two values are equal when one or more of them is a real number. Use a value comparison instruction and check to see if the difference in the absolute values is within the allowable range. For example, the following programming can be used to check to see if the sum of REAL variables real_a and real_b is equal to 0.1. If the value of BOOL variable boolv is TRUE, the two values are considered to be equal.
boolv := (ABS((real_a + real_b) - 0.1) < threshold);
threshold: Value for allowable range

NJ/NX-series Instructions Reference Manual (W502)

2-93

2 Instruction Descriptions

NE (<>)

The NE (<>) instruction determines if the contents of two variables are not equivalent.

Instruction NE (<>)

Name Not Equal

FB/FUN FUN

Graphic expression

(@)NE

EN

Out

In1

In2

ST expression Out:=(In1<>In2);

(@)<>

EN

Out

In1

In2

Variables

Name

Meaning

In1 and In2 Comparison data

Out

Comparison

result

I/O Input
Output

Description Values to compare
Comparison result

Valid range

Unit

Depends on data type. ---

Depends on data type. ---

* If you omit an input parameter, the default value is not applied. A building error will occur.

Default *
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In1 and In2 OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK

*

Enumerations can also be specified.

Out

OK

* You can specify TIME, DATE, TOD, DT, and STRING data with Sysmac Studio version 1.02 or higher. If you open a project that was created with Sysmac Studio version 1.01 or lower on Sysmac Studio version 1.02 or higher and then use any of these data types, refresh the display. To refresh the display, right-click the instruction in the Edit Pane and select Update. If you do not refresh the display, a building error will occur.

2-94

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Comparison Instructions

Function

The NE (<>) instruction determines if the contents of two variables In1 and In2 are not equivalent. If they are not equivalent, the comparison result Out is TRUE. If they are equivalent, Out is FALSE. When comparing STRING data, "equivalent" means that both the lengths and contents of the text strings are the same.
The following example is for when In1 equals In2 (both have a value of INT#5). The value of variable abc will be FALSE.

abc:=(INT#5<>INT#5);

NE

abc

2

EN

INT#5 In1

INT#5 In2

NE (<>)

The NE instruction determines if In1 and In2 are different. If they are the same, the value of abc will be FALSE.

Compared to see if they are different. Equivalent

Out=abc FALSE

In1 INT#5

In2 INT#5

Additional Information
· The functions of the NE instruction and the <> instruction are exactly the same. Use the form that is easier to use.
· When you compare TIME, DT, or TOD data, adjust the data so that the precision of the values is the same. Use the following instructions to adjust the precision of the values: TruncTime (page 2-658), TruncDt (page 2-662), and TruncTod (page 2-666).

Precautions for Correct Use
· If the data types of In1 and In2 are different, the smaller one is expanded to a data type that includes the ranges of both of the data types.
· You cannot compare bit string data (BYTE, WORD, DWORD, or LWORD) with integers (SINT, INT, DINT, LINT, USINT, UDINT, ULINT). You cannot compare bit string data with real number data (REAL and LREAL).
· Signed integers (SINT, INT, DINT, and LINT) cannot be compared to unsigned integers (USINT, UINT, UDINT, and ULINT).
· Always compare data with the same data type for TIME, DATE, TOD, DT, and STRING data. If variables with different data types are specified, a building error will occur.
· You can compare enumerations only to other enumerations. The data types must also be the same to compare enumerations.
· Two values that are positive infinity or two values that are negative infinity are equivalent. · If the value of either In1 or In2 is nonnumeric data, the value of Out is TRUE. · If this instruction is used in a ladder diagram, the value of Out changes to FALSE if an error occurs in
the previous instruction on the rung.

NJ/NX-series Instructions Reference Manual (W502)

2-95

2 Instruction Descriptions
· If In1 and In2 are real numbers, the desired results may not be achieved due to rounding error. Do not use this instruction to check if two values are different when one or both of them is a real number. Use a value comparison instruction and check to see if the difference in the absolute values is greater than the allowable range. For example, the following programming can be used to check to see if the sum of REAL variables real_a and real_b is not equal to 0.1. If the value of BOOL variable boolv is TRUE, the two values are considered to be not equal. boolv := (ABS((real_a + real_b) - 0.1) > threshold); threshold: Value for allowable range

2-96

NJ/NX-series Instructions Reference Manual (W502)

Comparison Instructions

2 Instruction Descriptions

LT (<), LE (<=), GT (>), and GE (>=)

These instructions compare the sizes of two or more values.

LT (<):

Performs a less than comparison.

LE (<=): Performs a less than or equal comparison.

GT (>):

Performs a greater than comparison.

GE (>=): Performs a greater than or equal comparison.

Instruction LT (<)

Name Less Than

FB/FUN FUN

LE (<=)

Less Than Or Equal

FUN

GT (>)

Greater Than

FUN

GE (>=)

Greater Than Or FUN Equal

Graphic expression

(@)LT

EN

Out

In1

::

InN

(@)<

EN

Out

In1

::

InN

(@)LE

EN

Out

In1

::

InN

(@)<=

EN

Out

In1

::

InN

(@)GT

EN

Out

In1

::

InN

(@)>

EN

Out

In1

::

InN

(@)GE

EN

Out

In1

::

InN

(@)>=

EN

Out

In1

::

InN

ST expression

2

Out:=(In1<In2) & (In2<In3)

& ··· &

(InN-1<InN);

LT (<), LE (<=), GT (>), and GE (>=)

Out:=(In1<=In2) & (In2<=In3) & ··· & (InN-1<=InN);

Out:=(In1>In2) & (In2>In3) & ··· & (InN-1>InN);

Out:=(In1>=In2) & (In2>=In3) & ··· & (InN-1>=InN);

NJ/NX-series Instructions Reference Manual (W502)

2-97

2 Instruction Descriptions

Variables

Name In1 to InN
Out

Meaning
Comparison data
Comparison result

I/O Input
Output

Description
Values to compare, N = 2 to 5
Comparison result

Valid range Depends on data type.
Depends on data type.

Unit
---
---

Default 0*
---

* If you omit the input parameter that connects to InN, the default value is not applied, and a building error will occur. For example, if N is 3 and the input parameters that connect to In1 and In2 are omitted, the default values are applied, but if the input parameter that connects to In3 is omitted, a building error will occur.

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In1 to InN Out

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK

*

*

OK

* You can specify BYTE, WORD, DWORD, LWORD, TIME, DATE, TOD, DT, and STRING data with Sysmac Studio version 1.02 or higher. If you open a project that was created with Sysmac Studio version 1.01 or lower on Sysmac Studio version 1.02 or higher and then use any of these data types, refresh the display. To refresh the display, right-click the instruction in the Edit Pane and select Update. If you do not refresh the display, a building error will occur.

Function

These instructions compare the data in In1 to InN (N = 2 to 5). The output value Out is shown below for each instruction.

Instruction

Value of Out

LT (<)

If In1 < In2 < ... < InN, Out is TRUE. Otherwise, it is FALSE.

LE (<=)

If In1 <= In2 <= ... <= InN, Out is TRUE. Otherwise, it is FALSE.

GT (>)

If In1 > In2 > ... > InN, Out is TRUE. Otherwise, it is FALSE.

GE (>=)

If In1 >= In2 >= ... >= InN, Out is TRUE. Otherwise, it is FALSE.

The relationship between values with data types that are not integers or real numbers are determined as given in the following table.

Data type

Relationship

BYTE, WORD, DWORD, or LWORD The data is compared as unsigned integers.

TIME

The numerically larger value is considered to be larger.

DATE, TOD, or DT

Later dates or times of day are considered to be larger.

STRING

The specifications are the same as for the LTascii, LEascii, GTascii, and GEascii instructions (page 2-104). Refer to the specified page for details.

2-98

NJ/NX-series Instructions Reference Manual (W502)

Comparison Instructions

2 Instruction Descriptions

The following example shows the LE instruction when In1 is INT#3, In2 is INT#5 and In3 is INT#10. The value of variable abc will be TRUE.

LD

ST

abc:=(INT#3<= INT#5)&(INT#5<=INT#10);

LE

abc

EN

INT#3 In1 INT#5 In2 INT#10 In3

The LE instruction determines if In1  In2  In3.

2

If the comparison conditions are met, the value of abc will be TRUE.

LT (<), LE (<=), GT (>), and GE (>=)

Values are compared to see if In1  In2  In3.
Comparison conditions met. Out=abc

TRUE

In1 INT#3

In2 INT#5

In3 INT#10

Additional Information
· The functions of the LT and < instructions, the LE and <= instructions, the GT and > instructions, and the GE and >= instructions are exactly the same. Use the form that is easier to use.
· When you compare TIME, DT, or TOD data, adjust the data so that the precision of the values is the same. Use the following instructions to adjust the precision of the values: TruncTime (page 2-658), TruncDt (page 2-662), and TruncTod (page 2-666).

Precautions for Correct Use
· If the data types of In1 to InN are different, they will be expanded to a data type that includes the ranges of all of the data types.
· Signed integers (SINT, INT, DINT, and LINT) cannot be compared to unsigned integers (USINT, UINT, UDINT, and ULINT).
· You cannot compare bit string data (BYTE, WORD, DWORD, or LWORD) with integers (SINT, INT, DINT, LINT, USINT, UINT, UDINT, or ULINT). You cannot compare bit string data with real number data (REAL or LREAL).
· Always compare data with the same data type for TIME, DATE, TOD, DT, and STRING data. If variables with different data types are specified, a building error will occur.
· If In1 to InN2 are real numbers, error may cause unexpected processing results. This can occur, for example, when they contain non-terminating decimal numbers.
· Two values that are positive infinity or two values that are negative infinity are equivalent. · If any of the values of In1 to InN is nonnumeric data, the value of Out is FALSE. · If this instruction is used in a ladder diagram, the value of Out changes to FALSE if an error occurs in
the previous instruction on the rung.

NJ/NX-series Instructions Reference Manual (W502)

2-99

2 Instruction Descriptions

EQascii

The EQascii instruction determines if two or more text strings are all equivalent.

Instruction EQascii

Name

FB/FUN

Text String Com- FUN parison Equal

Graphic expression

(@)EQascii

EN

Out

In1

::

InN

ST expression
Out:=EQascii(In1, ··, InN);

Variables

Name In1 to InN
Out

Meaning
Comparison text strings
Comparison result

I/O Input
Output

Description
Text strings to compare, N = 2 to 5
Comparison result

Valid range Depends on data type.
Depends on data type.

Unit
---
---

Default '' *
---

* If you omit the input parameter that connects to InN, the default value is not applied, and a building error will occur. For example, if N is 3 and the input parameters that connect to In1 and In2 are omitted, the default values are applied, but if the input parameter that connects to In3 is omitted, a building error will occur.

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In1 to InN

OK

Out

OK

Function

The EQascii instruction determines if from two to five text strings In1 to InN are all equivalent. If the are all equivalent, comparison result Out changes to TRUE. Otherwise, the value of Out is FALSE. "Equivalent" means that both the lengths and contents of the text strings are the same.
The following example is for when In1 is "A", In2 is "AB", and In3 is "ABC". The value of variable abc will be FALSE.

LD

ST

abc:=EQascii('A', `AB', `ABC');

EQascii

abc

EN

`A' In1 `AB' In2 `ABC' In3

2-100

NJ/NX-series Instructions Reference Manual (W502)

Comparison Instructions

2 Instruction Descriptions

The EQascii instruction determines if In1 to In3 are all equivalent. If they are different, the value of abc will be FALSE.

Compared to see if they are equivalent. Different.

Out=abc FALSE

In1 'A'

In2 'AB'

In3 'ABC'

Additional Information

The text string comparison instructions are convenient when you want to reorder text strings according to the character codes. For example, the character codes for alphabet characters are in the same order

2

as the alphabet characters. This allows you to alphabetize.

EQascii

Version Information
With Sysmac Studio version 1.02 or higher, the EQ (=) instruction (page 2-92) can also be used to compare text strings. The specifications of the EQ (=) instruction for comparing text strings are the same as for the EQascii instruction.

Precautions for Correct Use
· Do not use this instruction as the rightmost instruction on a rung. If you do, an error occurs on the Sysmac Studio and you cannot transfer the user program to the Controller.
· If this instruction is used in a ladder diagram, the value of Out changes to FALSE if an error occurs in the previous instruction on the rung.
· Specify text strings that contain only ASCII characters for In1 to InN.

NJ/NX-series Instructions Reference Manual (W502)

2-101

2 Instruction Descriptions

NEascii

The NEascii instruction determines if two text strings are not equivalent.

Instruction NEascii

Name

FB/FUN

Text String Com- FUN parison Not Equal

Graphic expression

(@)NEascii

EN

Out

In1

In2

ST expression Out:=NEascii(In1, In2);

Variables

Name

Meaning

In1 and In2 Comparison text strings

Out

Comparison

result

I/O Input
Output

Description Text strings to compare
Comparison result

Valid range

Unit

Depends on data type. ---

Depends on data type. ---

* If you omit an input parameter, the default value is not applied. A building error will occur.

Default *
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In1 and In2

OK

Out

OK

Function

The NEascii instruction determines if two text strings In1 and In2 are not equivalent. If they are different, comparison result Out will be TRUE. If they are the same, comparison result Out will be FALSE. "Equivalent" means that both the lengths and contents of the text strings are the same.
The following example is for when In1 is "A" and In2 is "AB". The value of variable abc will be TRUE.

LD

ST

abc:=NEascii('A', `AB');

NEascii

abc

EN `A' In1 `AB' In2

2-102

NJ/NX-series Instructions Reference Manual (W502)

Comparison Instructions

2 Instruction Descriptions

The NEascii instruction determines if In1 and In2 are different. If they are different, the value of abc will be TRUE.

Compared to see if they are different. Different

Out=abc TRUE

In1 'A'

In2 'AB'

Additional Information

The text string comparison instructions are convenient when you want to reorder text strings according to the character codes. For example, the character codes for alphabet characters are in the same order

2

as the alphabet characters. This allows you to alphabetize.

NEascii

Version Information
With Sysmac Studio version 1.02 or higher, the NE (<>) instruction (page 2-94) can also be used to compare text strings. The specifications of the NE (<>) instruction for comparing text strings are the same as for the NEascii instruction.

Precautions for Correct Use
· Do not use this instruction as the rightmost instruction on a rung. If you do, an error occurs on the Sysmac Studio and you cannot transfer the user program to the Controller.
· If this instruction is used in a ladder diagram, the value of Out changes to FALSE if an error occurs in the previous instruction on the rung.
· Specify text strings that contain only ASCII characters for In1 and In2.

NJ/NX-series Instructions Reference Manual (W502)

2-103

2 Instruction Descriptions

LTascii, LEascii, GTascii, and GEascii

These instructions compare the sizes of two or more text strings. LTascii: Performs a less than comparison. LEascii: Performs a less than or equal comparison. GTascii: Performs a greater than comparison. GEascii: Performs a greater than or equal comparison.

Instruction LTascii

Name
Text String Comparison Less Than

FB/FUN FUN

LEascii GTascii

Text String Comparison Less Than or Equal

FUN

Text String Comparison Greater Than

FUN

GEascii

Text String Comparison Greater Than or Equal

FUN

Graphic expression

(@)LTascii

EN

Out

In1

::

InN

(@)LEascii

EN

Out

In1

::

InN

(@)GTascii

EN

Out

In1

::

InN

(@)GEascii

EN

Out

In1

::

InN

ST expression Out:=LTascii(In1, ···, InN);
Out:=LEascii(In1, ···, InN);
Out:=GTascii(In1, ···, InN);
Out:=GEascii(In1, ···, InN);

Variables

Name In1 to InN
Out

Meaning
Comparison text strings
Comparison result

I/O Input
Output

Description
Text strings to compare, N = 2 to 5
Comparison result

Valid range Depends on data type.
Depends on data type.

Unit
---
---

Default ''*
---

* If you omit the input parameter that connects to InN, the default value is not applied, and a building error will occur. For example, if N is 3 and the input parameters that connect to In1 and In2 are omitted, the default values are applied, but if the input parameter that connects to In3 is omitted, a building error will occur.

2-104

NJ/NX-series Instructions Reference Manual (W502)

Comparison Instructions
STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

2 Instruction Descriptions

Bit strings

Integers

Times, durations, dates, and text strings

In1 to InN

OK

Out

OK

Function

2

LTascii, LEascii, GTascii, and GEascii

These instructions compare the sizes of from two to five text strings in In1 to InN (N = 2 to 5). The output value Out is shown below for each instruction.

Instruction

Value of Out

LTascii LEascii

If In1 < In2 <...< InN, Out is TRUE. Otherwise, it is FALSE. If In1  In2 ... InN, Out is TRUE. Otherwise, it is FALSE.

GTascii GEascii

If In1 > In2 >...> InN, Out is TRUE. Otherwise, it is FALSE. If In1  In2 ... InN, Out is TRUE. Otherwise, it is FALSE.

The sizes of the character codes are compared. The comparison procedure is as follows:
First, the first character codes in all of the text strings are compared. If the character codes are different, the result of the size comparison for the text strings is determined by the size relationship between those character codes. If the character codes are the same, comparison continues in order to the other characters until a different character code is found. If the lengths of the text strings are different, NULL characters (16#00) are added to the shorter text string to complete the comparison.
The relationships between various text strings are as follows:

'AD'(16#414400) < 'BC'(16#424400)

'ADC' (16#41444300)< 'B'(16#42000000)

'ABC' (16#41424300)< 'ABD'(16#41424400)

'ABC' (16#41424300)> 'AB'(16#41420000)

'AB' (16#414200)= 'AB'(16#414200)
If the text string contains multi-byte characters, the characters are separated into individual bytes before comparison. For example, the two-byte character 16#C281 is handled as 16#C2 and 16#81.
The following example for the LEascii instruction is for when In1 is "AB", In2 is "AC", and In3 is "AC". The value of variable abc will be TRUE.

LD

ST

abc:=LEascii('AB', `AC', `AC');

LEascii

abc

EN `AB' In1 `AC' In2 `AC' In3

NJ/NX-series Instructions Reference Manual (W502)

2-105

2 Instruction Descriptions

The LEascii instruction determines if In1  In2  In3. If the comparison conditions are met, the value of abc will be TRUE.

Values are compared to see if In1  In2  In3.
Comparison conditions met. Out=abc

TRUE

In1 'AB'

In2 'AC'

In3 'AC'

Additional Information
The text string comparison instructions are convenient when you want to reorder text strings according to the character codes. For example, the character codes for alphabet characters are in the same order as the alphabet characters. This allows you to alphabetize.
Version Information
With Sysmac Studio version 1.02 or higher, the LT (<), LE (<=), GT (>), and GE (>=) instructions (page 2-97) can also be used to compare text strings. The specifications of the LT (<), LE (<=), GT (>), and GE (>=) instructions for comparing text strings are the same as for the LTascii, LEascii, GTascii, and GEascii instructions.

Precautions for Correct Use
· Do not use this instruction as the rightmost instruction on a rung. If you do, an error occurs on the Sysmac Studio and you cannot transfer the user program to the Controller.
· If this instruction is used in a ladder diagram, the value of Out changes to FALSE if an error occurs in the previous instruction on the rung.
· Specify text strings that contain only ASCII characters for In1 to InN.

2-106

NJ/NX-series Instructions Reference Manual (W502)

Comparison Instructions

2 Instruction Descriptions

Cmp

The Cmp instruction compares two values.

Instruction

Name

FB/FUN

Cmp

Compare

FUN

Graphic expression

(@)Cmp

EN ENO

In1

Out

In2 OutEQ

OutGT

OutGE

OutNE

OutLT

OutLE

ST expression Out:=Cmp(In1, In2, OutEQ, OutGT, OutGE, OutNE, OutLT, OutLE);
You can omit Out.
2

Cmp

Variables

Name In1 and In2
Out OutEQ OutGT
OutGE
OutNE OutLT OutLE

Meaning
Comparison data Return value Equal flag
Greater than flag Greater than or equal flag
Not equal flag
Less than flag
Less than or equal flag

I/O Input
Output

Description Values to compare

Valid range

Unit

Depends on data type. ---

Always TRUE Equal flag Greater than flag

TRUE only

Greater than or equal flag
Not equal flag Less than flag Less than or equal flag

---
Depends on data type.

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default *
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In1 and In2

Out

OK

OutEQ

OK

OutGT

OK

OutGE

OK

OutNE

OK

OutLT

OK

OutLE

OK

OK OK OK OK OK OK OK OK OK OK

NJ/NX-series Instructions Reference Manual (W502)

2-107

2 Instruction Descriptions

Function

The Cmp instruction compares two values (In1 and In2) and outputs flag values. The values of the flags are as follows:

Flag

Value

OutEQ

If In1 equals In2, the flag shows TRUE. Otherwise the flag shows FALSE.

OutGT

If In1 is greater than In2, the flag shows TRUE. Otherwise the flag shows FALSE.

OutGE

If In1 is greater than or equal to In2, the flag shows TRUE. Otherwise the flag shows FALSE.

OutNE

If In1 is not equal to In2, the flag shows TRUE. Otherwise the flag shows FALSE.

OutLT

If In1 is less than In2, the flag shows TRUE. Otherwise the flag shows FALSE.

OutLE

If In1 is less than or equal to In2, the flag shows TRUE. Otherwise the flag shows FALSE.

The following example is for when In1 is INT#10 and In2 is INT#20. The values of variables def, ghi, and jkl will be FALSE, and the values of abc, mno, pqr, and stu will be TRUE.

LD

ST

abc:=Cmp(INT#10, INT#20, def, ghi, jkl, mno, pqr, stu);

Cmp

EN ENO

INT#10 In1

abc

INT#20 In2 OutEQ def

OutGT ghi

OutGE jkl

OutNE mno

OutLT

pqr

OutLE stu

The Cmp instruction compares In1 and In2. The results are given below for the various criteria.

In1 and In2 are compared. In1 INT#10 In2 INT#20

Out OutEQ OutGT OutGE OutNE OutLT OutLE

Always TRUE FALSE because In1 does not equal In2. FALSE because In1 is not greater than In2. FALSE because In1 is not greater than or equal to In2. TRUE because In1 does not equal In2. TRUE because In1 is less than In2. TRUE because In1 is less than or equal to In2.

Out=abc OutEQ=def OutGT=ghi OutGE=jkl OutNE=mno OutLT=pqr OutLE=stu

TRUE FALSE FALSE FALSE TRUE TRUE TRUE

Precautions for Correct Use
· If the data types of In1 and In2 are different, the smaller one is expanded to a data type that includes the ranges of both of the data types.
· If In1 and In2 are real numbers, error may cause unexpected processing results. This can occur, for example, when they contain non-terminating decimal numbers.
· Signed integers (SINT, INT, DINT, and LINT) cannot be compared to unsigned integers (USINT, UINT, UDINT, and ULINT).
· Two values that are positive infinity or two values that are negative infinity are equivalent. · If the value of either In1 or In2 is nonnumeric data, the values of OutEQ, OutGT, OutGE, OutNE,
OutLT, and OutLE are FALSE.

2-108

NJ/NX-series Instructions Reference Manual (W502)

Comparison Instructions

2 Instruction Descriptions

ZoneCmp

The ZoneCmp instruction determines if the comparison data is within the specified maximum and minimum values.

Instruction

Name

FB/FUN

Graphic expression

ST expression

ZoneCmp

Zone Comparison FUN

(@)ZoneCmp

Out:=ZoneCmp(MN, In,

EN

Out

MX);

MN

In

MX

2

ZoneCmp

Variables

Name MN In
MX Out

Meaning

I/O

Minimum value

Comparison data

Input

Maximum value

Comparison result

Output

Description Minimum value Value to compare
Maximum value Comparison result

Valid range

Unit

Depends on data type. ---

Depends on data type. ---

* If you omit an input parameter, the default value is not applied. A building error will occur.

Default 0 *
0
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

MN

In

MX

Out

OK

OK OK OK OK OK OK OK OK OK OK OK OK OK OK *
OK OK OK OK OK OK OK OK OK OK OK OK OK OK *
OK OK OK OK OK OK OK OK OK OK OK OK OK OK *

* You can specify TIME, DATE, TOD, and DT data with CPU Units with unit version 1.01 or later and Sysmac Studio version 1.02 or higher.

NJ/NX-series Instructions Reference Manual (W502)

2-109

2 Instruction Descriptions

Function

The ZoneCmp instruction determines if comparison data In is between maximum value MX and minimum value MN. If MX  In  MN, Out will be TRUE. Otherwise, Out will be FALSE.
The relationship between values with data types that are not integers or real numbers are determined as given in the following table.

Data type TIME DATE, TOD, or DT

Relationship The numerically larger value is considered to be larger. Later dates or times of day are considered to be larger.

The following example is for when MN is INT#10, In is INT#20 and MX is INT#30. The value of variable abc will be TRUE.

LD

ST

ZoneCmp

abc

EN INT#10 MN INT#20 In INT#30 MX

abc:=ZoneCmp(INT#10, INT#20, INT#30);

The ZoneCmp instruction determines if MX  In  MN. If the comparison conditions are met, the value of abc will be TRUE.

The instruction determines if In is between MX and MN.

MX INT#30

Comparison conditions met.

In INT#20

Out=abc TRUE

MN INT#10

Additional Information
When you compare TIME, DT, or TOD data, adjust the data so that the precision of the values is the same. Use the following instructions to adjust the precision of the values: TruncTime (page 2-658), TruncDt (page 2-662), and TruncTod (page 2-666).

Precautions for Correct Use
· If the data types of In, MX, and MN are different, they will be expanded to a data type that includes the ranges of all of the data types.
· If In, MX, and MN are real numbers, error may cause unexpected processing results. This can occur, for example, when they contain non-terminating decimal numbers.
· Signed integers (SINT, INT, DINT, and LINT) cannot be compared to unsigned integers (USINT, UINT, UDINT, and ULINT).
· Always compare data with the same data type for TIME, DATE, TOD, and DT data. If variables with different data types are specified, a building error will occur.
· Two values that are positive infinity or two values that are negative infinity are equivalent. · If the value of In is nonnumeric data, the value of Out is FALSE. · If this instruction is used in a ladder diagram, the value of Out changes to FALSE if an error occurs in
the previous instruction on the rung. · An error occurs in the following cases. Out will be FALSE.
· The value of MN is greater than the value of MX. · Either MX or MN contains nonnumeric data.

2-110

NJ/NX-series Instructions Reference Manual (W502)

Comparison Instructions

2 Instruction Descriptions

TableCmp

The TableCmp instruction compares the comparison data with multiple defined ranges in a comparison table.

Instruction TableCmp

Name

FB/FUN

Table Comparison FUN

Graphic expression

ST expression

(@)TableCmp

EN

Out

Out:=TableCmp(In, Table, Size, AryOut);

In

Table

Size

2

AryOut

TableCmp

Variables

Name In
Table[] (twodimensional array) Size
AryOut[] (array)

Meaning Comparison data Comparison table
Comparison size
Individual comparison results array

I/O Input In-out

Out

Comparison Output

result

Description Value to compare

Valid range

Unit

Two-dimensional array that

contains the elements for

the defined ranges

Depends on data type. ---

Number of elements in Table[] to which to compare In

Comparison results for Table[] elements

Depends on data type. ---

TRUE: Condition met.

FALSE: Condition not met.

TRUE: In meets all compari- Depends on data type. --son conditions for elements of Table[].

FALSE: The comparison condition is not met for one or more sets of elements.

* If you omit an input parameter, the default value is not applied. A building error will occur.

Default * 1
-----

NJ/NX-series Instructions Reference Manual (W502)

2-111

2 Instruction Descriptions

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

Bit strings

Integers

Times, durations, dates, and text strings

In

Table[] (twodimensional array)

Size

AryOut[] OK (array)

Out

OK

OK OK OK OK OK OK OK OK OK OK Must be a two-dimensional array with elements that have the same data type as In.
OK

Function

The TableCmp instruction compares comparison data In with the number of defined ranges specified by the value of Size in comparison table Table[].
Table[] is a two-dimensional array. The first dimension contains the numbers of the defined ranges. In the second dimension, element 0 is set value A of the defined range and element 1 is set value B of the defined range.

Set value A

Set value B

Range 0

Table[0,0]

Table[0,1]

Range 1

Table[1,0]

Table[1,1]

Range Size - 1 Table[Size-1,0]

Table[Size-1,1]

Set value A and set value B define range as shown below. Set value A and set value B are always included in the range.

Set value A  Set value B

Set value A  Set value B

Defined range

Defined range

Defined range

Set value A

Set value B

Set value B

Set value A

The results of comparing In and Table[] are stored in individual comparison results array AryOut[]. If In

is within the defined range for element i, AryOut[i] will be TRUE. If it is not within the range, AryOut[i] will

be FALSE. If all Size elements of AryOut[] are TRUE, comparison result Out will be TRUE. Otherwise, it

will be FALSE.

2-112

NJ/NX-series Instructions Reference Manual (W502)

Comparison Instructions

2 Instruction Descriptions

The following example is for when In is INT#120 and Size is UINT#3.

LD

ST

ghi:=TableCmp(INT#120, abc[1,2], UINT#3, def[3]);

INT#120 abc[1,2] UINT#3
def[3]

TableCmp
EN In Table Size AryOut

ghi def[3]

In=INT#120

2

TableCmp

Table[0,0]=abc[1,2]

0 Table[0,1]=abc[1,3]

99

Size=UINT#3 Table[1,0]=abc[2,2]

100 Table[1,1]=abc[2,3]

199

Table[2,0]=abc[3,2]

200 Table[2,1]=abc[3,3]

299

AryOut[0]=def[3] AryOut[1]=def[4] AryOut[2]=def[5]

FALSE TRUE FALSE

Out=ghi FALSE

Precautions for Correct Use
· Use the same data type for In and Table[]. Otherwise, a building error will occur. · Use a two-dimensional array for Table[]. · If an array with more than two dimensions is used for Table[], the elements in the third and higher
dimensions are ignored. · If the AryOut[] array is larger than the value of Size, the comparison results will be stored in AryOut[0]
to AryOut[Size-1]. Other elements of the array will not change. · Signed integers (SINT, INT, DINT, and LINT) cannot be compared to unsigned integers (USINT, UINT,
UDINT, and ULINT). · If real numbers are compared, error may cause unexpected processing results. This can occur, for
example, when they contain non-terminating decimal numbers. · If the value of Size is 0, the value of Out will be FALSE and AryOut[] will not change. · If this instruction is used in a ladder diagram, the value of Out changes to FALSE if an error occurs in
the previous instruction on the rung. · An error occurs in the following cases. Out will be FALSE.
· If the value of Size exceeds the size of the AryOut[] array. · If the value of Size exceeds the size of the first dimension of the Table[] array. · The size of the second dimension of Table [] is 1.

NJ/NX-series Instructions Reference Manual (W502)

2-113

2 Instruction Descriptions

AryCmpEQ and AryCmpNE

These instructions compare the values of the elements of two arrays.

AryCmpEQ:

Determines if the elements are equal.

AryCmpNE:

Determines if the elements are not equal.

Instruction AryCmpEQ

Name
Array Comparison Equal

FB/FUN FUN

Graphic expression

(@)AryCmpEQ

EN In1 In2 Size AryOut

ENO Out

ST expression
AryCmpEQ(In1, In2, Size, AryOut);

AryCmpNE

Array Comparison FUN Not Equal

(@)AryCmpNE

EN

ENO

AryCmpNE(In1, In2, Size, AryOut);

In1

Out

In2

Size

AryOut

Variables

Name In1[] and In2[] (arrays) Size
AryOut[] (array) Out

Meaning Comparison arrays
Number of comparison elements Comparison results array Return value

I/O Input In-out Output

Description

Valid range

Unit

Arrays containing the elements to compare

Depends on data type.

---
Number of elements to com- Depends on data type. pare

Comparison results array Depends on data type. ---

Always TRUE

TRUE only

---

* If you omit an input parameter, the default value is not applied. A building error will occur.

Default *
1
-----

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In1[] (array) OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK

In2[] (array)

Must be an array with the same data type as In1[].

Size

OK

AryOut[] OK (array)

Out

OK

2-114

NJ/NX-series Instructions Reference Manual (W502)

Comparison Instructions

2 Instruction Descriptions

Function

These instructions compare the values of the elements with the same element numbers in two arrays (In1[0] to In1[Size-1] and In2[0] and In2[Size-1]). The comparison results are stored in comparison results array AryOut[] in the elements with the corresponding element numbers (AryOut[0] to AryOut[Size -1]).
The value of AryOut[i] is as follows for each instruction:

Instruction

Value of AryOut[i]

AryCmpEQ

If In1[i] = In2[i], the result is TRUE. Otherwise, it is FALSE.

AryCmpNE

If In1[i]  In2[i], the result is TRUE. Otherwise, it is FALSE.

The following example shows the AryCmpEQ instruction when Size is UINT#3.

2

LD

ST

AryCmpEQ and AryCmpNE

AryCmpEQ(abc[1], def[2], UINT#3, ghi[3]);

abc[1] def[2] UINT#3
ghi[3]

AryCmpEQ

EN

ENO

In1

In2

Size

AryOut

ghi[3]

In1[0]=abc[1] 100 In2[0]=def[2] 100 Size=UINT#3 In1[1]=abc[2] 120 In2[1]=def[3] 130
In1[2]=abc[3] 140 In2[2]=def[4] 160

AryOut[0]=ghi[3] AryOut[1]=ghi[4] AryOut[2]=ghi[5]

TRUE FALSE FALSE

Precautions for Correct Use
· Use the same data type for In1[] and In2[]. If they are different, a building error will occur. · Use an AryOut[] array that is at least as large as the value of Size. · If In1[] and In2[] contain real numbers, error may cause unexpected processing results. This can
occur, for example, when they contain non-terminating decimal numbers. · If the value of Size is 0, the value of Out will be TRUE and AryOut[] will not change. · Return value Out is not used when the instruction is used in ST. · An error occurs in the following cases. ENO will be FALSE, and AryOut[] will not change.
· If the In1[], In2[], or AryOut[] array is smaller than the value of Size.

NJ/NX-series Instructions Reference Manual (W502)

2-115

2 Instruction Descriptions

AryCmpLT, AryCmpLE, AryCmpGT, and AryCmpGE

These instructions compare the values of the elements of two arrays.

AryCmpLT:

Performs a less than comparison.

AryCmpLE:

Performs a less than or equal comparison.

AryCmpGT:

Performs a greater than comparison.

AryCmpGE:

Performs a greater than or equal comparison.

Instruction AryCmpLT

Name
Array Comparison Less Than

FB/FUN FUN

Graphic expression

(@)AryCmpLT

EN In1 In2 Size AryOut

ENO Out

ST expression
AryCmpLT(In1, In2, Size, AryOut);

AryCmpLE

Array Comparison FUN Less Than Or Equal

(@)AryCmpLE

EN

ENO

AryCmpLE(In1, In2, Size, AryOut);

In1

Out

In2

Size

AryOut

AryCmpGT

Array Comparison FUN Greater Than

(@)AryCmpGT

EN

ENO

AryCmpGT(In1, In2, Size, AryOut);

In1

Out

In2

Size

AryOut

AryCmpGE

Array Comparison Greater Than Or Equal

FUN

(@)AryCmpGE

EN

ENO

AryCmpGE(In1, In2, Size, AryOut);

In1

Out

In2

Size

AryOut

2-116

NJ/NX-series Instructions Reference Manual (W502)

Comparison Instructions

2 Instruction Descriptions

Variables

Name

Meaning

I/O

Description

Valid range

Unit Default

In1[] and Comparison

Arrays containing the ele- Depends on data type.

*

In2[]

arrays

ments to compare

(arrays)

Input

---

Size

Number of

Number of elements to com- Depends on data type.

1

comparison

pare

elements

AryOut[] Comparison In-out

Comparison results array Depends on data type. ---

---

(array)

results array

2

Out

Return value Output

Always TRUE

TRUE only

---

---

* If you omit an input parameter, the default value is not applied. A building error will occur.

Bit strings

Integers

Times, durations, dates, and text strings

AryCmpLT, AryCmpLE, AryCmpGT, and AryCmpGE
STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In1[] (array)

In2[] (array)

Size

AryOut[] OK (array)

Out

OK

OK OK OK OK OK OK OK OK OK Must be an array with the same data type as In1[]. OK

NJ/NX-series Instructions Reference Manual (W502)

2-117

2 Instruction Descriptions

Function

These instructions compare the values of the elements with the same element numbers in two arrays (In1[0] to In1[Size -1] and In2[0] and In2[Size -1]). The comparison results are stored in comparison results array AryOut[] in the elements with the corresponding element numbers (AryOut[0] to AryOut[Size -1]).
The value of AryOut[i] is as follows for each instruction:

Instruction

Value of AryOut[i]

AryCmpLT

If In1[i] < In2[i], the result is TRUE. Otherwise, it is FALSE.

AryCmpLE

If In1[i] <= In2[i], the result is TRUE. Otherwise, it is FALSE.

AryCmpGT

If In1[i] > In2[i], the result is TRUE. Otherwise, it is FALSE.

AryCmpGE

If In1[i] >= In2[i], the result is TRUE. Otherwise, it is FALSE.

The following example shows the AryCmpLT instruction when Size is UINT#3.

LD

ST

AryCmpLT(abc[1], def[2], UINT#3, ghi[3]);

abc[1] def[2] UINT#3
ghi[3]

AryCmpLT

EN

ENO

In1

In2

Size

AryOut

ghi[3]

In1[0]=abc[1] 110 In2[0]=def[2] 100

Size=UINT#3 In1[1]=abc[2]

120 In2[1]=def[3]

130

In1[2]=abc[3] 140 In2[2]=def[4] 160

AryOut[0]=ghi[3] AryOut[1]=ghi[4] AryOut[2]=ghi[5]

FALSE TRUE TRUE

Precautions for Correct Use
· Use the same data type for In1[] and In2[]. If they are different, a building error will occur. · Use an AryOut[] array that is at least as large as the value of Size. · If In1[] and In2[] contain real numbers, error may cause unexpected processing results. This can
occur, for example, when they contain non-terminating decimal numbers. · If the value of Size is 0, the value of Out will be TRUE and AryOut[] will not change. · Return value Out is not used when the instruction is used in ST. · An error occurs in the following cases. ENO will be FALSE, and AryOut[] will not change.
· If the In1[], In2[], or AryOut[] array is smaller than the value of Size.

2-118

NJ/NX-series Instructions Reference Manual (W502)

Comparison Instructions

2 Instruction Descriptions

AryCmpEQV and AryCmpNEV

These instructions compare a value to the values of the elements of an array. AryCmpEQV: Determines if the elements are equal. AryCmpNEV: Determines if the elements are not equal.

Instruction AryCmpEQV

Name
Array Value Comparison Equal

FB/FUN FUN

Graphic expression

ST expression

(@)AryCmpEQV

AryCmpEQV(In1, In2, Size,

EN

ENO

AryOut);

2

In1

Out

In2

Size

AryOut

AryCmpNEV

Array Value Comparison Not Equal

FUN

(@)AryCmpNEV

EN In1 In2 Size AryOut

ENO Out

AryCmpNEV(In1, In2, Size, AryOut);

AryCmpEQV and AryCmpNEV

Variables

Name

Meaning

In1[] (array) Comparison array

In2

Comparison

value

Size

Number of

comparison

elements

AryOut[] (array)

Comparison results array

Out

Return value

I/O Input In-out Output

Description Array containing the elements to compare Value to compare

Valid range Depends on data type.

Number of elements to com- Depends on data type. pare

Unit
---

Comparison results array Depends on data type. ---

Always TRUE

TRUE only

---

* If you omit an input parameter, the default value is not applied. A building error will occur.

Default *
1
-----

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In1[] (array) OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK

In2

Must be same data type as the elements of In1[].

Size

OK

AryOut[] OK (array)

Out

OK

NJ/NX-series Instructions Reference Manual (W502)

2-119

2 Instruction Descriptions

Function

These instructions compare comparison value In2 with the specified elements in an array (In1[0] to In1[Size -1]). The comparison results are stored in comparison results array AryOut[] in the elements with the corresponding element numbers (AryOut[0] to AryOut[Size -1]).

The value of AryOut[i] is as follows for each instruction:

Instruction AryCmpEQV AryCmpNEV

Value of AryOut[i] If In1[i] = In2, the result is TRUE. Otherwise, it is FALSE. If In1[i]  In2, the result is TRUE. Otherwise, it is FALSE.

The following example shows the AryCmpEQV instruction when In2 is INT#10 and Size is UINT#3.

LD

ST

AryCmpEQV(abc[1], INT#10, UINT#3, def[2]);

abc[1] INT#10 UINT#3
def[2]

AryCmpEQV

EN In1 In2 Size AryOut

ENO

def[2]

Size=UINT#3

In1[0]=abc[1] In1[1]=abc[2] In1[2]=abc[3]

10 In2=INT#10 20 In2=INT#10 30 In2=INT#10

AryOut[0]=def[2] AryOut[1]=def[3] AryOut[2]=def[4]

TRUE FALSE FALSE

Precautions for Correct Use
· Use the same data type for In1[] and In2. If they are different, a building error will occur. · Use an AryOut[] array that is at least as large as the value of Size. · If In1[] contains real numbers and In2 is a real number, error may cause unexpected processing
results. This can occur, for example, when they contain non-terminating decimal numbers. · If the value of Size is 0, the value of Out will be TRUE and AryOut[] will not change. · Return value Out is not used when the instruction is used in ST. · An error occurs in the following case. ENO will be FALSE, and AryOut[] will not change.
· If the In1[] or AryOut[] array is smaller than the value of Size.

2-120

NJ/NX-series Instructions Reference Manual (W502)

Comparison Instructions

2 Instruction Descriptions

AryCmpLTV, AryCmpLEV, AryCmpGTV, and AryCmpGEV

These instructions compare a value to the values of the elements of an array.

AryCmpLTV: Performs a less than comparison.

AryCmpLEV: Performs a less than or equal comparison.

AryCmpGTV: Performs a greater than comparison.

AryCmpGEV: Performs a greater than or equal comparison.

2

AryCmpLTV, AryCmpLEV, AryCmpGTV, and AryCmpGEV

Instruction AryCmpLTV

Name
Array Value Comparison Less Than

FB/FUN FUN

Graphic expression

(@)AryCmpLTV

EN In1 In2 Size AryOut

ENO Out

ST expression
AryCmpLTV(In1, In2, Size, AryOut);

AryCmpLEV

Array Value Comparison Less Than Or Equal

FUN

(@)AryCmpLEV

EN In1 In2 Size AryOut

ENO Out

AryCmpLEV(In1, In2, Size, AryOut);

AryCmpGTV

Array Value Comparison Greater Than

FUN

(@)AryCmpGTV

EN In1 In2 Size AryOut

ENO Out

AryCmpGTV(In1, In2, Size, AryOut);

AryCmpGEV

Array Value Comparison Greater Than Or Equal

FUN

(@)AryCmpGEV

EN In1 In2 Size AryOut

ENO Out

AryCmpGEV(In1, In2, Size, AryOut);

NJ/NX-series Instructions Reference Manual (W502)

2-121

2 Instruction Descriptions

Variables

Name

Meaning

In1[] (array) Comparison array

In2

Comparison

value

Size

Number of

comparison

elements

AryOut[] (array)

Comparison results array

Out

Return value

I/O Input In-out Output

Description
Array containing the elements to compare
Value to compare

Valid range Depends on data type.

Number of elements to com- Depends on data type. pare

Unit
---

Comparison results array Depends on data type. ---

Always TRUE

TRUE only

---

* If you omit an input parameter, the default value is not applied. A building error will occur.

Default *
1
-----

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In1[] (array)

In2

Size

AryOut[] OK (array)

Out

OK

OK OK OK OK OK OK OK OK OK Must be same data type as the elements of In1[]. OK

2-122

NJ/NX-series Instructions Reference Manual (W502)

Comparison Instructions

2 Instruction Descriptions

AryCmpLTV, AryCmpLEV, AryCmpGTV, and AryCmpGEV

Function

These instructions compare comparison value In2 with the specified elements in an array (In1[0] to In1[Size - 1]). The comparison results are stored in comparison results array AryOut[] in the elements with the corresponding element numbers (AryOut[0] to AryOut[Size -1]).

The value of AryOut[i] is as follows for each instruction:

Instruction

Value of AryOut[i]

AryCmpLTV

If In1[i] < In2, the result is TRUE. Otherwise, it is FALSE.

AryCmpLEV

If In1[i] <= In2, the result is TRUE. Otherwise, it is FALSE.

AryCmpGTV

If In1[i] > In2, the result is TRUE. Otherwise, it is FALSE.

AryCmpGEV

If In1[i] >= In2, the result is TRUE. Otherwise, it is FALSE.

2

The following example shows the AryCmpLEV instruction when In2 is INT#20 and Size is UINT#3.

LD

ST

AryCmpLEV(abc[1], INT#20, UINT#3, def[2]);

abc[1] INT#20 UINT#3
def[2]

AryCmpLEV

EN In1 In2 Size AryOut

ENO

def[2]

Size=UINT#3

In1[0]=abc[1] In1[1]=abc[2] In1[2]=abc[3]

10

In2=INT#20

20

In2=INT#20

30

In2=INT#20

AryOut[0]=def[2] AryOut[1]=def[3] AryOut[2]=def[4]

TRUE TRUE FALSE

Precautions for Correct Use
· Use the same data type for In1[] and In2. If they are different, a building error will occur. · Use an AryOut[] array that is at least as large as the value of Size. · If In1[] contains real numbers and In2 is a real number, error may cause unexpected processing
results. This can occur, for example, when they contain non-terminating decimal numbers. · If the value of Size is 0, the value of Out will be TRUE and AryOut[] will not change. · Return value Out is not used when the instruction is used in ST. · An error occurs in the following case. ENO will be FALSE, and AryOut[] will not change.
· If the In1[] or AryOut[] array is smaller than the value of Size.

NJ/NX-series Instructions Reference Manual (W502)

2-123

2 Instruction Descriptions

2-124

NJ/NX-series Instructions Reference Manual (W502)

Timer Instructions

2
Timer Instructions

Instruction TON TOF TP AccumulationTimer Timer

Name On-Delay Timer Off-Delay Timer Timer Pulse Accumulation Timer Hundred-ms Timer

Page 2-126 2-132 2-135 2-138 2-141

NJ/NX-series Instructions Reference Manual (W502)

2-125

2 Instruction Descriptions

TON

The TON instruction outputs TRUE when the set time elapses after the timer starts.

Instruction TON

Name On-Delay Timer

FB/FUN FB

Graphic expression

TON_instance

TON

In

Q

PT

ET

ST expression
TON_instance (In, PT, Q, ET);

Variables

Name In
PT

Meaning

I/O

Timer input

Set time

Input

Q

Timer

output

Output

ET

Elapsed

time

Description TRUE: Timer start signal FALSE: Timer reset signal Time from when timer starts until Q changes to TRUE TRUE: Timer output ON FALSE: Timer output OFF Elapsed time since timer started

Valid range Depends on data type.
* Depends on data type.
*

Unit
---
ms
---
ms

* T#0ms to T#106751d_23h_47m_16s_854.775807ms

Default FALSE 0
---

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

Bit strings

Integers

Times, durations, dates, and text strings

In

OK

PT

OK

Q

OK

ET

OK

Function
The TON instruction outputs TRUE when the set time elapses after the timer starts. The time is set in nanoseconds. The timer starts when timer input In changes to TRUE. Elapsed time ET is incremented as time elapses. When ET reaches set time PT, timer output Q changes to TRUE. ET is not incremented after that. The timer is reset when In changes to FALSE. ET changes to 0 and Q changes to FALSE. If the timer is started and then In changes to FALSE before ET reaches PT, the timer is reset.

2-126

NJ/NX-series Instructions Reference Manual (W502)

Timer Instructions

2 Instruction Descriptions

The following figure shows a programming example and timing chart when PT is T#10ms. Variable abc will change to TRUE 10 ms after variable A changes to TRUE.

LD

ST

A T#10ms

TON_instance

TON

In

Q

PT

ET

TON_instance(A, T#10ms, abc, def); abc def

PT=T#10ms

In=A

TRUE FALSE

2

TRUE Q=abc FALSE

TON

ET=def

Additional Information

· Use the TP instruction (page 2-135) for a timer that changes the timer output to TRUE when timing starts and then changes the timer output to FALSE when the set time is reached.
· Use the TOF instruction (page 2-132) for a timer that starts when In changes to FALSE and then changes the timer output to FALSE when the elapsed time reaches the set time.
· To reduce timer execution time, use the Timer instruction (page 2-141), which times in increments of 100 ms.
· If you are connected to an HMI that does not support TIME data, you must convert the set time from integer data to TIME data before you input it to this instruction. Use the NanoSecToTime instruction (page 2-642) to convert integer data to TIME data. Use the TimeToNanoSec instruction (page 2-640) to convert TIME data to integer data. Both instructions express the time in nanoseconds. The user programming for when the INT variable msIntVar is the set time in milliseconds is given below.

LD

Setparameter
msIntVar LINT#1000000

MUL
EN ENO In1 In2

tmpLintVar

NanoSecToTime

EN tmpLintVar In

ENO

Trigger

TON_instance TON

In

Q

msTimeVar PT

ET

TON_instance.Q

Tout

msTimeVar

ST
tmpLintVar:=msIntVar*LINT#1000000; msTimeVar:=NanoSecToTime(tmpLintVar); TON_instance(In:=Trigger, PT:=msTimeVar, Q=>Tout);

NJ/NX-series Instructions Reference Manual (W502)

2-127

2 Instruction Descriptions

Precautions for Correct Use

· The timing error for which Q is TRUE for PT is -100 ns to (100 ns + 1 task period). The above range includes the following: · The ±100 ns is the timing error of ET.
· Time ET is judged to see if it has reached PT every task period. If time ET reaches PT immediately after the judgement is completed, there is a delay of one task period.
· The time is displayed in increments of 0.001 ms on the Sysmac Studio, but the timing accuracy is 1 ns.
· The timer starts as soon as operation starts if In is already TRUE.
· If T#0ms or a negative number is set for PT, Q will change to TRUE as soon as the value of In changes to TRUE.
· You can change the value of PT while the value of In is TRUE. Operation is as follows:

Timer status
After completion of timing

Value of Q TRUE

Value of PT after it is changed
---

Timing in progress

FALSE

PT  ET

PT < ET

Operation
The value of Q remains TRUE. The value of ET also does not change. (It remains at the value of PT before it was changed.)
Timing is continued. When the value of ET reaches the value of PT, the value of Q changes to TRUE and ET is no longer incremented.
The value of Q changes to TRUE immediately. Incrementing ET stops immediately.

· If this instruction is in a master control region and the master control region is reset, the timer is reset. The value of ET changes to 0 and the value of Q changes to FALSE.
· If this instruction is not executed due to the execution of a jump instruction (e.g., the JMP instruction), the value of ET is not updated. However, timing still continues. Therefore, ET is updated to the correct value the next time the instruction is executed.
· If this instruction is used in a ladder diagram, the value of Q changes to FALSE if an error occurs in the previous instruction on the rung.

2-128

NJ/NX-series Instructions Reference Manual (W502)

Timer Instructions

2 Instruction Descriptions

Sample Programming

 Measuring Time with One On-Delay Timer
The value of TimeUp will change to TRUE 1 second after the value of Trigger changes to TRUE.

LD

Variable Trigger TimeUp

Data type BOOL BOOL

Initial value

Comment

FALSE

Execution condition

FALSE

Timer output

TON_instance TON
2

TON

Trigger T#1s

TON_instance

TON

In

Q

PT

ET

TimeUp

ST

Variable Trigger TimeUp

Data type BOOL BOOL

Initial value

Comment

FALSE

Execution condition

FALSE

Timer output

TON_instance TON

IF (Trigger=TRUE) THEN TON_instance(In:=TRUE, PT:=T#1s, Q=>TimeUp);
ELSE TON_instance(In:=FALSE, Q=>TimeUp);
END_IF;

The following ST programming performs the same operation.

ST

Variable Trigger TimeUp

Data type BOOL BOOL

Initial value

Comment

FALSE

Execution condition

FALSE

Timer output

TON_instance TON

TON_instance(In:=Trigger, PT:=T#1s, Q=>TimeUp);

NJ/NX-series Instructions Reference Manual (W502)

2-129

2 Instruction Descriptions

 Measuring Time with Multiple On-Delay Timers

In this example, a total of 100 instances of the On-Delay Timer instruction, TON_instance[0] to TON_instance[99], are programmed. Each timer starts when the value of the corresponding timer input Input[0] to Input[99] changes to TRUE. The timers for the first 10 instances, TON_instance[0] to TON_instance[9], change the corresponding values in TimeUp[i] to TRUE i+1 seconds (i = 0 to 9) after execution is started. The timers for the remaining 90 instances, TON_instance[10] to TON_instance[99], change the corresponding values in TimeUp[i] (i = 10 to 99) to TRUE as soon as execution is started.

TON_instance[0] 1s

TimeUp[0] TRUE

TON_instance[1] 2s

TimeUp[1] TRUE

:

:

TON_instance[9] 10s

: TimeUp[9] TRUE

TON_instance[10] 0s

:

:

TON_instance[99] 0s

TimeUp[10] TRUE :
TimeUp[99] TRUE

LD

Variable Input

Data type

Initial value

ARRAY[0..99] OF BOOL [100(FALSE)]

Comment Timer input

TimeUp TimePT TON_instance i

ARRAY[0..99] OF BOOL ARRAY[0..99] OF TIME ARRAY[0..99] OF TON UINT

[100(FALSE)] [T#1s, T#2s, T#3s, T#4s, T#5s, T#6s, T#7s, T#8s, T#9s, T#10s, 90(T#0s)]

Timer output Set time

0

Index

FOR

EN

ENO

UINT#0 InitVal Index i

UINT#99 EndVal

UINT#1 StepVal

Input[i] TimePT[i]

TON_instance[i]

TON

In

Q

PT

ET

NEXT EN ENO

TimeUp[i]

2-130

NJ/NX-series Instructions Reference Manual (W502)

Timer Instructions

2 Instruction Descriptions

ST

Variable

Data type

Initial value

Comment

Input

ARRAY[0..99] OF BOOL [100(FALSE)]

Timer input

TimeUp

ARRAY[0..99] OF BOOL [100(FALSE)]

Timer output

TimePT

[T#1s, T#2s, T#3s, T#4s, T#5s, T#6s,

ARRAY[0..99] OF TIME

Set time

T#7s, T#8s, T#9s, T#10s, 90(T#0s)]

TON_instance ARRAY[0..99] OF TON

i

UINT

0

Index

FOR i :=UINT#0 TO UINT#99 DO

TON_instance[i]( In := Input[i],

2

PT := TimePT[i],

Q =>TimeUp[i]);

END_FOR;

TON

NJ/NX-series Instructions Reference Manual (W502)

2-131

2 Instruction Descriptions

TOF

The TOF instruction outputs FALSE when the set time elapses after the timer starts.

Instruction TOF

Name Off-Delay Timer

FB/FUN FB

Graphic expression

TOF_instance

TOF

In

Q

PT

ET

ST expression
TOF_instance (In, PT, Q, ET);

Variables

Name In
PT

Meaning

I/O

Timer input

Set time

Input

Q

Timer

output

Output

ET

Elapsed

time

Description TRUE: Timer reset signal FALSE: Timer start signal Time from when timer starts until Q changes to FALSE TRUE: Timer output ON FALSE: Timer output OFF Elapsed time since timer started

Valid range Depends on data type.
* Depends on data type.
*

Unit ---
ms ---
ms

* T#0ms to T#106751d_23h_47m_16s_854.775807ms

Default FALSE 0
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

PT

OK

Q

OK

ET

OK

Function
The TOF instruction outputs FALSE when the set time elapses after the timer starts. The time is set in nanoseconds. The timer starts when timer input In changes to FALSE. Elapsed time ET is incremented as time elapses. When ET reaches set time PT, timer output Q changes to FALSE. ET is not incremented after that. The timer is reset when In changes to TRUE. ET changes to 0 and Q changes to TRUE. If the timer is started and then In changes to FALSE before ET reaches PT, the timer is reset.

2-132

NJ/NX-series Instructions Reference Manual (W502)

Timer Instructions

2 Instruction Descriptions

The following figure shows a programming example and timing chart for a PT of T#10ms. Variable abc will change to FALSE 10 ms after variable A changes to FALSE.

LD

ST

A T#10ms

TOF_instance

TOF

In

Q

PT

ET

TOF_instance(A, T#10ms, abc, def); abc def

PT=T#10ms

In=A

TRUE FALSE

2

TRUE Q=abc
FALSE

TOF

ET=def

Additional Information

· Use the TP instruction (page 2-135) for a timer that changes the timer output to TRUE when timing starts and then changes the timer output to FALSE when the set time is reached.
· Use the TON instruction (page 2-126) for a timer that starts when In changes to TRUE and then changes the timer output to TRUE when the elapsed time reaches the set time.
· If you are connected to an HMI that does not support TIME data, you must convert the set time from integer data to TIME data before you input it to this instruction. Use the NanoSecToTime instruction (page 2-642) to convert integer data to TIME data. Use the TimeToNanoSec instruction (page 2-640) to convert TIME data to integer data. Both instructions express the time in nanoseconds. The user programming for when the INT variable msIntVar is the set time in milliseconds is given below.

LD

Setparameter
msIntVar LINT#1000000

MUL
EN ENO In1 In2

tmpLintVar

NanoSecToTime

EN tmpLintVar In

ENO

Trigger

TOF_instance TOF

In

Q

msTimeVar PT

ET

TOF_instance.Q

Tout

msTimeVar

ST
tmpLintVar:=msIntVar*LINT#1000000; msTimeVar:=NanoSecToTime(tmpLintVar); TOF_instance(In:=Trigger, PT:=msTimeVar, Q=>Tout);

NJ/NX-series Instructions Reference Manual (W502)

2-133

2 Instruction Descriptions

Precautions for Correct Use

· The timing error for which Q is TRUE for PT is -100 ns to (100 ns + 1 task period). The above range includes the following:
· The ±100 ns is the timing error of ET.
· Time ET is judged to see if it has reached PT every task period. If time ET reaches PT immediately after the judgement is completed, there is a delay of one task period.
· The time is displayed in increments of 0.001 ms on the Sysmac Studio, but the timing accuracy is 1 ns.
· If T#0ms or a negative number is set for PT, Q will change to FALSE as soon as the value of In changes to FALSE.
· The value of Q changes to TRUE immediately after execution of this instruction regardless of the value of In. Q is FALSE from only when the timer is started until the time that is set with PT elapses.

· You can change the value of PT while the value of In is FALSE. Operation is as follows:

Timer status Value of Q

Value of PT after it is changed

Operation

After comple- FALSE tion of timing

Timing in progress

TRUE

--PT  ET PT < ET

The value of Q remains FALSE. The value of ET also does not change. (It remains at the value of PT before it was changed.)
Timing is continued. When the value of ET reaches the value of PT, the value of Q changes to FALSE and ET is no longer incremented.
The value of Q changes to FALSE immediately. Incrementing ET stops immediately.

· If this instruction is in a master control region and the master control region is reset, the operation is as follows:
· The value of ET changes to 0 and the value of Q changes to TRUE.
· If an Out instruction is connected to Q, the execution condition to the Out instruction is FALSE.
· Timing starts as soon as the reset is released.
· If this instruction is not executed due to the execution of a jump instruction (e.g., the JMP instruction), the value of ET is not updated. However, timing still continues. Therefore, ET is updated to the correct value the next time the instruction is executed.
· If this instruction is used in a ladder diagram, the value of Q changes to FALSE if an error occurs in the previous instruction on the rung.

2-134

NJ/NX-series Instructions Reference Manual (W502)

Timer Instructions

2 Instruction Descriptions

TP

The TP instruction outputs TRUE while the set time elapses after the timer starts.

Instruction TP

Name Timer Pulse

FB/FUN FB

Graphic expression

TP_instance

TP

In

Q

PT

ET

ST expression
TP_instance (In, PT, Q, ET);

2 Variables

TP

Name In
PT

Meaning

I/O

Timer input

Set time

Input

Q

Timer

output

Output

ET

Elapsed

time

Description TRUE: Timer start signal FALSE: Timer reset signal Time that Q remains at TRUE TRUE: Timer output ON FALSE: Timer output OFF Elapsed time since timer started

* T#0ms to T#106751d_23h_47m_16s_854.775807ms

Valid range

Unit

Depends on data type. ---

*

ms

Depends on data type. ---

*

ms

Default FALSE 0
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

PT

OK

Q

OK

ET

OK

Function
The TP instruction outputs TRUE while the set time elapses after the timer starts. The time is set in nanoseconds. The timer starts when timer input In changes to TRUE and timer output Q changes to TRUE. Elapsed time ET is incremented as time elapses. When ET reaches set time PT, timer output Q changes to FALSE. ET is not incremented after that. The timer is reset when In changes to FALSE. ET changes to 0. The timer is not reset even if In changes to FALSE after the timer starts but before ET reaches PT.

NJ/NX-series Instructions Reference Manual (W502)

2-135

2 Instruction Descriptions

The following figure shows a programming example and timing chart for a PT of T#10ms. Variable abc changes to TRUE as soon as variable A changes to TRUE. Variable abc changes to FALSE 10 ms later.

LD

ST

A T#10ms

TP_instance

TP

In

Q

PT

ET

TP_instance(A, T#10ms, abc, def); abc def

In=A

TRUE FALSE

TRUE Q=abc
FALSE

ET=def

PT=T#10ms

Additional Information

· Use the TON instruction (page 2-126) for a timer that starts when In changes to TRUE and then changes the timer output to TRUE when the elapsed time reaches the set time.
· Use the TOF instruction (page 2-132) for a timer that starts when In changes to FALSE and then changes the timer output to FALSE when the elapsed time reaches the set time.
· If you are connected to an HMI that does not support TIME data, you must convert the set time from integer data to TIME data before you input it to this instruction. Use the NanoSecToTime instruction (page 2-642) to convert integer data to TIME data. Use the TimeToNanoSec instruction (page 2-640) to convert TIME data to integer data. Both instructions express the time in nanoseconds. The user programming for when the INT variable msIntVar is the set time in milliseconds is given below.

LD

Setparameter
msIntVar LINT#1000000

MUL
EN ENO In1 In2

tmpLintVar

NanoSecToTime

EN tmpLintVar In

ENO

Trigger

TP_instance TP

In

Q

msTimeVar PT

ET

TP_instance.Q

Tout

msTimeVar

ST
tmpLintVar:=msIntVar*LINT#1000000; msTimeVar:=NanoSecToTime(tmpLintVar); TP_instance(In:=Trigger, PT:=msTimeVar, Q=>Tout);

2-136

NJ/NX-series Instructions Reference Manual (W502)

Timer Instructions

2 Instruction Descriptions

Precautions for Correct Use

· The timing error for which Q is TRUE for PT is -100 ns to (100 ns + 1 task period). The above range includes the following: · The ±100 ns is the timing error of ET. · Time ET is judged to see if it has reached PT every task period. If time ET reaches PT immediately after the judgement is completed, there is a delay of one task period.
· The time is displayed in increments of 0.001 ms on the Sysmac Studio, but the timing accuracy is 1 ns.
· The timer starts as soon as operation starts if In is already TRUE.
· If T#0ms or a negative number is set for PT, Q will not change to TRUE even if the value of In 2
changes to TRUE.

· You can change the value of PT while the value of In is TRUE. Operation is as follows:

TP

Timer status
After completion of timing

Value of Q FALSE

Value of PT after it is changed
---

Timing in progress

TRUE

PT  ET PT < ET

Operation
The value of Q remains FALSE. The value of ET also does not change. (It remains at the value of PT before it was changed.)
Timing is continued. When the value of ET reaches the value of PT, the value of Q changes to FALSE and ET is no longer incremented.
The value of Q changes to FALSE immediately. Incrementing ET stops immediately.

· If this instruction is in a master control region and the master control region is reset, timing is continued to the end if the timer is operating. Then, the value of ET changes to 0 and the value of Q changes to FALSE. However, if an Out instruction is connected to Q, the execution condition to the Out instruction is FALSE even if the value of Q is TRUE.
· If this instruction is not executed due to the execution of a jump instruction (e.g., the JMP instruction), the value of ET is not updated and timing is not performed. Timing restarts when the instruction is executed again.
· If this instruction is used in a ladder diagram, the value of Q changes to FALSE if an error occurs in the previous instruction on the rung.

NJ/NX-series Instructions Reference Manual (W502)

2-137

2 Instruction Descriptions

AccumulationTimer

The AccumulationTimer instruction totals the time that the timer input is TRUE.

Instruction

Name

FB/FUN

AccumulationTimer Accumulation Timer FB

Graphic expression

AccumulationTimer_instance

AccumulationTimer

In

Q

PT

ET

Reset

ST expression
AccumulationTimer_instance(In, PT, Reset, Q, ET);

Variables

Name

Meaning

I/O

In

Timer input

PT Reset

Set time Reset

Input

Q

Timer

output

Output

ET

Total time

Description TRUE: Timer operates FALSE: Timer stops Maximum time TRUE: Timer reset FALSE: Timer not reset TRUE: ET reached PT. FALSE: ET has not reached PT. Total time

Valid range Depends on data type. * Depends on data type. Depends on data type.
*

Unit --ms -----
ms

* T#0ms to T#106751d_23h47m_16s_854.775807ms

Default FALSE 0 FALSE
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

PT

OK

Reset

OK

Q

OK

ET

OK

Function
The AccumulationTimer instruction totals the time that the timer input is TRUE. The time is set in nanoseconds. If reset Reset is FALSE, the timer starts when In changes to TRUE. Total time ET is incremented as time elapses. The timer stops when In changes to FALSE. ET is held. When In changes to TRUE again, the timer starts again. ET is incremented from the value that was previously held. When ET reaches set time PT, timer output Q changes to TRUE. ET is not incremented after that. The timer is reset when Reset changes to TRUE. ET changes to 0 and Q changes to FALSE.

2-138

NJ/NX-series Instructions Reference Manual (W502)

Timer Instructions

2 Instruction Descriptions

The following figure shows a programming example and timing chart for a PT of T#10ms. Variable abc changes to TRUE when variable A is TRUE for a total of 10 ms (i.e., the total time).

LD

ST

A
T#10ms abc

AccumulationTimer_instance

AccumulationTimer

In

Q

PT

ET

Reset

AccumulationTimer_instance(A, T#10ms, abc, def, ghi); def ghi

TRUE

In=A

FALSE

2

TRUE Reset=abc FALSE

PT=T#10ms ET=ghi

AccumulationTimer

Q=def

TRUE FALSE

Additional Information

· Use the TON instruction (page 2-126) for a timer that resets the timer output and elapsed time when In changes to FALSE.
· If you are connected to an HMI that does not support TIME data, you must convert the set time from integer data to TIME data before you input it to this instruction. Use the NanoSecToTime instruction (page 2-642) to convert integer data to TIME data. Use the TimeToNanoSec instruction (page 2-640) to convert TIME data to integer data. Both instructions express the time in nanoseconds. The user programming for when the INT variable msIntVar is the set time in milliseconds is given below.

LD

Setparameter
msIntVar LINT#1000000

MUL
EN ENO In1 In2

tmpLintVar

NanoSecToTime

EN tmpLintVar In

ENO

msTimeVar

Trigger

msTimeVar

AccumulationTimer_instance

AccumulationTimer

In

Q

PT

ET

Reset

AccumulationTimer_instance.Q

Tout

ST
tmpLintVar:=msIntVar*LINT#1000000; msTimeVar:=NanoSecToTime(tmpLintVar); AccumulationTimer_instance(In:=Trigger, PT:=msTimeVar, Q=>Tout);

NJ/NX-series Instructions Reference Manual (W502)

2-139

2 Instruction Descriptions

Precautions for Correct Use

· The timing error for which Q is TRUE for PT is -100 ns to (100 ns + 1 task period). The above range includes the following:
· The ±100 ns is the timing error of ET. · Time ET is judged to see if it has reached PT every task period. If time ET reaches PT immedi-
ately after the judgement is completed, there is a delay of one task period.
· The time is displayed in increments of 0.001 ms on the Sysmac Studio, but the timing accuracy is 1 ns.
· If In and Reset are both TRUE, Reset has priority. That is, ET changes to 0 and Q changes to FALSE.
· The timer starts as soon as operation starts if In is already TRUE.
· If T#0ms or a negative number is set for PT, Q will change to TRUE as soon as the value of In changes to TRUE.
· You can change the value of PT before the value of ET reaches the value of PT. Operation is as follows:

Timer status
After completion of timing

Value of Q TRUE

Value of PT after it is changed
---

PT  ET

Timing in progress

FALSE

PT < ET

Operation
The value of Q remains TRUE. The value of ET also does not change. (It remains at the value of PT before it was changed.)
When the value of In changes to TRUE, timing is continued. When the value of ET reaches the value of PT, the value of Q changes to TRUE and ET is no longer incremented.
When the value of In changes to TRUE, the value of Q changes to TRUE immediately. Incrementing ET stops immediately.

· If this instruction is in a master control region and the master control region is reset, the operation is as follows:
· The timer stops. The values of ET and Q at that time are retained.
· When the master control reset is cleared, ET is incremented again from the value that was retained.
· If an Out instruction is connected to Q, the execution condition to the Out instruction is FALSE even if the value of Q is TRUE.
· Reset is enabled.
· If this instruction is not executed due to the execution of a jump instruction (e.g., the JMP instruction), the value of ET is not updated. However, timing still continues. Therefore, ET is updated to the correct value the next time the instruction is executed.
· If this instruction is used in a ladder diagram, the value of Q changes to FALSE if an error occurs in the previous instruction on the rung.

2-140

NJ/NX-series Instructions Reference Manual (W502)

Timer Instructions

2 Instruction Descriptions

Timer

The Timer instruction outputs TRUE when the set time elapses after the timer starts. The time is set in increments of 100 ms.

Instruction Timer

Name

FB/FUN

Hundred-ms Timer FUN

Graphic expression

ST expression

Timer In

Out:=Timer (In, PT, Tim-

Out

erDat, Q, ET);

PT

Q

TimerDat
2

ET

Timer

Variables

Name In
PT TimerDat Out
Q ET

Meaning

I/O

Timer input

Set time

Input

Timer status In-out Return value

Timer output
Remaining time

Output

Description

Valid range

TRUE: Timer start specification

FALSE: Timer reset specification

Depends on data type.

Time from when timer starts until Q changes to TRUE

Current status of timer

---

TRUE: Make timer output TRUE

FALSE: Make timer output FALSE
Same meaning as Out.

Depends on data type.

Remaining time

Unit
---
ms ---
---
ms

* If you omit an input parameter, the default value is not applied. A building error will occur.

Default FALSE
* ---
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

PT

TimerDat

Out

OK

Q

OK

ET

OK Structure _sTimer
OK

NJ/NX-series Instructions Reference Manual (W502)

2-141

2 Instruction Descriptions

Function

The Timer instruction outputs TRUE when the set time elapses after the timer starts. The time is set in increments of 100 ms.
The timer is reset when timer input In changes to FALSE. Remaining time ET is set to set time PT, and timer output Q changes to FALSE.
The timer starts when In changes to TRUE. The value of ET is timed down. When the value of ET reaches 0, timer output Q changes to TRUE. ET is not timed down after that.
The timer is reset if In changes to FALSE after the timer starts but before ET reaches 0.
The data type of timer status TimerDat is structure _sTimer.
The following figure shows a programming example and timing chart when PT is UINT#10. Variable ghi will change to TRUE 1,000 ms (1 s) after variable A changes to TRUE.

LD

ST

def:=Timer(A, UINT#10, abc, ghi, jkl);

A
UINT#10 abc

Timer

In

PT

Q

TimerDat

ET

def
ghi abc jkl

PT=UINT#10

TRUE In=A FALSE
TRUE Q=ghi FALSE

ET=jkl

Additional Information
For more precise timing, use the TON instruction (page 2-126), which is set in nanoseconds. The TON instruction times in nanoseconds when the instruction is executed, so it is more precise than the Timer instruction. However, the execution time of the Timer instruction is shorter.

Precautions for Correct Use
· Timing is performed at the beginning of the POU that contains this instruction. Therefore, the value of ET will be the same regardless of where the instruction is executed in the POU.
· The timing error for which Q is TRUE for PT is + 1 task period. The above range includes the following: · Time ET is judged to see if it has reached PT every task period. If time ET reaches PT immediately after the judgement is completed, there is a delay of one task period.
· Although TimerDat is an in-out variable, it is not necessary to pass any values. Create a memory area for the size of the _sTimer structure and pass it to the instruction.
· Do not change the contents of TimerDat. · The timer starts as soon as operation starts if In is already TRUE. · If the value of PT changes, the new value is used from the next time that the timer is reset. The value
is not updated while timing is in progress. · If this instruction is in a master control region and the master control region is reset, the timer is reset.
ET is set to the value of PT and the value of Q changes to FALSE.

2-142

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions
· If this instruction is not executed due to the execution of a jump instruction (e.g., the JMP instruction), the value of ET is not updated. However, timing still continues. Therefore, ET is updated to the correct value the next time the instruction is executed.
· If this instruction is used in a ladder diagram, the values of Q and Out change to FALSE if an error occurs in the previous instruction on the rung.
2

Timer Instructions

Timer

NJ/NX-series Instructions Reference Manual (W502)

2-143

2 Instruction Descriptions

2-144

NJ/NX-series Instructions Reference Manual (W502)

Counter Instructions

2
Counter Instructions

Instruction CTD CTD_** CTU CTU_** CTUD CTUD_**

Name Down-counter Down-counter Group Up-counter Up-counter Group Up-down Counter Up-down Counter Group

Page 2-146 2-148 2-150 2-152 2-155 2-159

NJ/NX-series Instructions Reference Manual (W502)

2-145

2 Instruction Descriptions

CTD

The CTD instruction decrements the counter value when the counter input signal is received. The preset value and counter value must have an INT data type.

Instruction CTD

Name Down-counter

FB/FUN FB

Graphic expression

CTD_instance

CTD

CD

Q

Load CV

PV

ST expression
CTD_instance (CD, Load, PV, Q, CV);

Variables

Name CD
Load* PV
Q
CV

Meaning
Counter input
Load signal
Preset value
Counter output
Counter value

I/O Input Output

Description Counter input
TRUE: Set CV to PV. Counter preset value

Valid range

Unit

Depends on data type.
---
0 to 32767

TRUE: Counter output ON Depends on data type.

FALSE: Counter output OFF
---

Counter present value

0 to 32767

Default FALSE 0
---

* On Sysmac Studio version 1.03, you can use "LD" instead of "Load" to more clearly show the correspondence between the variables and the parameter names in ST expressions. For example, you can use the following notation: CTD_instance (CD:=A, LD:=abc, PV:=INT#5, Q=>def, CV=>ghi);.

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

CD

OK

Load

OK

PV

OK

Q

OK

CV

OK

Function
The CTD instruction creates a down counter. The preset value and counter value must have an INT data type. When load signal Load changes to TRUE, counter value CV is set to the value of preset value PV and counter output Q changes to FALSE. When counter input signal CD changes to TRUE, CV is decremented. When the value of CV reaches 0 or less, the value of Q changes to TRUE. After the value of CV reaches 0 or less, CV does not change even if CD changes to TRUE.

2-146

NJ/NX-series Instructions Reference Manual (W502)

Counter Instructions

2 Instruction Descriptions

CD is ignored while Load is TRUE. CV is not decremented. The following figure shows a programming example and timing chart for a PV of INT#5.

LD

ST

A
abc INT#5

CTD_instance

CTD

CD

Q

Load

CV

PV

def ghi

CTD_instance(A, abc, INT#5, def, ghi);

CD=A

TRUE FALSE

2

Load=abc

TRUE FALSE

CTD

PV=INT#5

CV=ghi

Q=def

0 TRUE FALSE

When Load changes to TRUE, CV

When CV reaches 0, Q

is set to the value of PV and Q

changes to TRUE.

changes to FALSE.

CV is decremented as soon as

Load changes to FALSE.

Additional Information
· Use the CTU instruction (page 2-150) to create a counter that increments the counter value each time the counter input signal is received.
· Use the CTUD instruction (page 2-155) to create a counter that is both incremented and decremented.

Precautions for Correct Use
· Change Load to TRUE and then back to FALSE to restart a counter that has completed counting down.
· Even when PV is set to a negative value, CV is set to the value of PV when the value of Load changes to TRUE. The value of CV will be 0 or less, so the value of Q changes to TRUE immediately. After that, the value of CV is not decremented even if the value of CD changes.
· If the value of CD is FALSE and the power supply is interrupted or the operating mode is changed to PROGRAM mode, the value of CV is decremented once if the value of CD is TRUE when instruction execution is restarted.
· If this instruction is used in a ladder diagram, the value of Q changes to FALSE if an error occurs in the previous instruction on the rung.

NJ/NX-series Instructions Reference Manual (W502)

2-147

2 Instruction Descriptions

CTD_**

The CTD_** instruction decrements the counter value when the counter input signal is received. The preset value and counter value must be one of the following data types: DINT, LINT, UDINT, or ULINT.

Instruction CTD_**

Name
Down-counter Group

FB/FUN FB

Graphic expression

CTD_**_instance

CTD_**

CD

Q

Load

CV

PV

ST expression
CTD_**_instance (CD, Load, PV, Q, CV); "**" must be DINT, LINT, UDINT, or ULINT.

"**" must be DINT, LINT, UDINT, or ULINT.

Variables

Name CD Load*1 PV
Q
CV

Meaning

I/O

Counter input
Load signal

Input

Preset value

Counter output
Counter value

Output

Description

Valid range

Unit

Counter input

TRUE: Set CV to PV.

Depends on data type.
---

Counter preset value

Depends on data type.*2

TRUE: Counter output ON Depends on data type.

FALSE: Counter output OFF

---

Counter present value

Depends on data

type.*2

Default FALSE 0
---

*1 On Sysmac Studio version 1.03, you can use "LD" instead of "Load" to more clearly show the correspondence between the variables and the parameter names in ST expressions. For example, you can use the following notation:CTD_LINT_instance(CD:=A, LD:=abc, PV:=LINT#5, Q=>def, CV=>ghi);.
*2 Negative numbers are excluded.

Bit string

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

CD

OK

Load

OK

PV

Q

OK

CV

OK OK

OK OK

Must be the same data type as PV

Function
A CTD_** instruction creates a down counter. The preset value and counter value must be one of the following data types: DINT, LINT, UDINT, or ULINT. The name of the instruction is determined by the data type of PV and CV. For example, if they are the CV data type, the instruction is CTD_LINT.

2-148

NJ/NX-series Instructions Reference Manual (W502)

Counter Instructions

2 Instruction Descriptions

When load signal Load changes to TRUE, counter value CV is set to the value of preset value PV and counter output Q changes to FALSE. When counter input signal CD changes to TRUE, CV is decremented. When the value of CV reaches 0 or less, the value of Q changes to TRUE.
After the value of CV reaches 0 or less, CV does not change even if CD changes to TRUE.
CD is ignored while Load is TRUE. CV is not decremented.
The following figure shows a CTD_LINT programming example and timing chart for a PV of LINT#5.

LD

ST

CTD_LINT_instance(A, abc, LINT#5, def, ghi);

CTD_LINT_instance

A

CTD_LINT

def

CD abc Load

Q CV ghi

2

LINT#5 PV

CTD_**

CD=A

TRUE FALSE

Load=abc

TRUE FALSE

PV=LINT#5

CV=ghi

Q=def

0 TRUE FALSE

When Load changes to TRUE,

When CV reaches 0, Q

CV is set to the value of PV and

changes to TRUE.

Q changes to TRUE.

CV is decremented as soon as

Load changes to FALSE.

Additional Information
· Use the CTU instruction (page 2-150) to create a counter that increments the counter value each time the counter input signal is received.
· Use the CTUD instruction (page 2-155) to create a counter that is both incremented and decremented.

Precautions for Correct Use
· Change Load to TRUE and then back to FALSE to restart a counter that has completed counting down.
· Use the same data type for PV and CV. · Even when PV is set to a negative value, CV is set to the value of PV when the value of Load
changes to TRUE. The value of CV will be 0 or less, so the value of Q changes to TRUE immediately. After that, the value of CV is not decremented even if the value of CD changes. · If the value of CD is FALSE and the power supply is interrupted or the operating mode is changed to PROGRAM mode, the value of CV is decremented once if the value of CD is TRUE when instruction execution is restarted. · If this instruction is used in a ladder diagram, the value of Q changes to FALSE if an error occurs in the previous instruction on the rung.

NJ/NX-series Instructions Reference Manual (W502)

2-149

2 Instruction Descriptions

CTU

The CTU instruction increments the counter value when the counter input signal is received. The preset value and counter value must have an INT data type.

Instruction CTU

Name Up-counter

FB/FUN FB

Graphic expression

CTU_instance

CTU

CU

Q

Reset CV

PV

ST expression
CTU_instance (CU, Reset, PV, Q, CV);

Variables

Name CU Reset* PV Q
CV

Meaning
Counter input
Reset signal
Preset value
Counter output
Counter value

I/O Input Output

Description Counter input
TRUE: Reset CV to 0.
Counter preset value

Valid range

Unit

Depends on data type.
---
0 to 32767

TRUE: Counter output ON Depends on data type.

FALSE: Counter output OFF
---

Counter present value

0 to 32767

Default FALSE 0
---

* On Sysmac Studio version 1.03, you can use "R" instead of "Reset" to more clearly show the correspondence between the variables and the parameter names in ST expressions. For example, you can use the following notation: CTU_instance (CU:=A, R:=abc, PV:=INT#5, Q=>def, CV=>ghi);.

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

CU

OK

Reset

OK

PV

OK

Q

OK

CV

OK

Function
The CTU instruction creates an up counter. The preset value and counter value must have an INT data type. When reset signal Reset changes to TRUE, counter value CV changes to 0 and counter output Q changes to FALSE. When counter input signal CU changes to TRUE, CV is incremented. When the value of CV reaches the value of PV or higher, the value of Q changes to TRUE.

2-150

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Counter Instructions

After the value of CV reaches the value of PV or higher, the value of CV does not change even if the value of CU changes to TRUE. CU is ignored while Reset is TRUE. CV is not incremented. The following figure shows a programming example and timing chart for a PV of INT#5.

LD

ST

CTU_instance(A, abc, INT#5, def, ghi);

CTU_instance

A

CTU

def

CU

Q

abc Reset CV ghi

INT#5 PV
2

CU=A

TRUE FALSE

CTU

TRUE Reset=abc FALSE

PV=INT#5

CV=ghi

Q=def

0 TRUE FALSE

When Reset changes to TRUE,

When CV reaches PV , Q

CV is reset to 0 and Q changes to

changes to TRUE.

FALSE.

CV is incremented as soon as Reset

changes to FALSE.

Additional Information
· Use the CTD instruction (page 2-146) to create a counter that decrements the counter value each time the counter input signal is received.
· Use the CTUD instruction (page 2-155) to create a counter that is both incremented and decremented.

Precautions for Correct Use

· Change Reset to TRUE and then back to FALSE to restart a counter that has completed counting up.
· Even when PV is set to a negative value, CV is set to 0 when the value of Reset changes to TRUE. The value of CV will be higher than the value of PV, so the value of Q changes to TRUE immediately. After that, the value of CV is not incremented even if the value of CU changes.
· The following operation is performed if the value of PV changes while the value of Reset is FALSE.

Value of PV Larger than the current value of CV

Meaning The count operation is continued.

Equal to or smaller than the current value of CV

The count operation is ended. The value of Q changes to TRUE. The current value of CV is retained. It does not change.

· If the value of CU is FALSE and the power supply is interrupted or the operating mode is changed to PROGRAM mode, the value of CV is incremented once if the value of CU is TRUE when instruction execution is restarted.
· If this instruction is used in a ladder diagram, the value of Q changes to FALSE if an error occurs in the previous instruction on the rung.

NJ/NX-series Instructions Reference Manual (W502)

2-151

2 Instruction Descriptions

CTU_**

The CTU_** instruction increments the counter value when the counter input signal is received. The preset value and counter value must be one of the following data types: DINT, LINT, UDINT, or ULINT.

Instruction CTU_**

Name

FB/FUN

Up-counter Group FB

Graphic expression

CTU_**_instance

CTU_**

CU

Q

Reset CV

PV

"**" must be DINT, LINT, UDINT, or ULINT.

ST expression
CTU_**_instance (CU, Reset, PV, Q, CV); "**" must be DINT, LINT, UDINT, or ULINT.

Variables

Name CU Reset*1 PV Q
CV

Meaning
Counter input
Reset signal
Preset value
Counter output
Counter value

I/O Input Output

Description Counter input

Valid range

Unit

TRUE: Reset CV to 0.

Depends on data type.
---

Counter preset value

Depends on data type.*2

TRUE: Counter output ON Depends on data type.

FALSE: Counter output OFF

---

Counter present value

Depends on data

type.*2

Default FALSE 0
---

*1 On Sysmac Studio version 1.03, you can use "R" instead of "Reset" to more clearly show the correspondence between the variables and the parameter names in ST expressions. For example, you can use the following notation: CTU_LINT_instance(CU:=A, R:=abc, PV:=LINT#5, Q=>def, CV=>ghi);.
*2 Negative numbers are excluded.

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

CU

OK

Reset

OK

PV

Q

OK

CV

OK OK

OK OK

Must be the same data type as PV

Function
A CTU_** instruction creates an up counter. The preset value and counter value must be one of the following data types: DINT, LINT, UDINT, or ULINT. The name of the instruction is determined by the data type of PV and CV. For example, if they are the LINT data type, the instruction is CTU_LINT.

2-152

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Counter Instructions

When reset signal Reset changes to TRUE, counter value CV changes to 0 and counter output Q changes to FALSE. When counter input signal CU changes to TRUE, CV is incremented. When the value of CV reaches the value of PV or higher, the value of Q changes to TRUE.
After the value of CV reaches the value of PV or higher, the value of CV does not change even if the value of CU changes to TRUE.
CU is ignored while Reset is TRUE. CV is not incremented.
The following figure shows a CTU_LINT programming example and timing chart for a PV of LINT#5.

LD

ST

CTU_LINT_instance(A, abc, LINT#5, def, ghi);

CTU_LINT_instance

A

CTU_LINT

def

2

CU

Q

abc Reset CV ghi

LINT#5 PV

CTU_**

CU=A

TRUE FALSE

TRUE Reset=abc
FALSE

PV=LINT#5

CV=ghi

Q=def

0 TRUE FALSE

When Reset changes to TRUE,

When CV reaches PV, Q

CV is reset to 0 and Q changes to

changes to TRUE.

FALSE.

CV is incremented as soon as Reset

changes to FALSE.

Additional Information
· Use the CTD instruction (page 2-146) to create a counter that decrements the counter value each time the counter input signal is received.
· Use the CTUD instruction (page 2-155) to create a counter that is both incremented and decremented.

Precautions for Correct Use

· Change Reset to TRUE and then back to FALSE to restart a counter that has completed counting up.
· Even when PV is set to a negative value, CV is set to 0 when the value of Reset changes to TRUE. The value of CV will be higher than the value of PV, so the value of Q changes to TRUE immediately. After that, the value of CV is not incremented even if the value of CU changes.
· Use the same data type for PV and CV.
· The following operation is performed if the value of PV changes while the value of Reset is FALSE.

Value of PV

Meaning

Larger than the current value of CV The count operation is continued.

Equal to or smaller than the current value of CV

The count operation is ended. The value of Q changes to TRUE. The current value of CV is retained. It does not change.

· If the value of CU is FALSE and the power supply is interrupted or the operating mode is changed to PROGRAM mode, the value of CV is incremented once if the value of CU is TRUE when instruction execution is restarted.

NJ/NX-series Instructions Reference Manual (W502)

2-153

2 Instruction Descriptions
· If this instruction is used in a ladder diagram, the value of Q changes to FALSE if an error occurs in the previous instruction on the rung.

2-154

NJ/NX-series Instructions Reference Manual (W502)

Counter Instructions

2 Instruction Descriptions

CTUD

The CTUD instruction creates an up-down counter that operates according to an up-counter input and a down-counter input. The preset value and counter value must have an INT data type.

Instruction CTUD

Name Up-down Counter

FB/FUN FB

Graphic expression

ST expression

CTUD_instance

CTUD

CU

QU

CD

QD

Reset CV

Load

PV

CTUD_instance (CU, CD, Reset, Load, PV, QU, QD, CV);
2

CTUD

Variables

Name CU CD
Reset* Load* PV

Meaning
Up-counter input
Downcounter input
Reset signal
Load signal
Preset value

I/O Input

QU

Up-counter

output

QD

Downcounter

Output

output

CV

Counter

value

Description Up counter input

Valid range

Unit

Down counter input

Depends on data type.

TRUE: Reset CV to 0.

---
TRUE: CV set to PV.

The final counter value when operating as an up counter

0 to 32767

The initial counter value when operating as a down counter

TRUE: up-counter output ON

FALSE: up-counter output

OFF

Depends on data type.

TRUE: down-counter output

ON

---

FALSE: down-counter output OFF

Counter present value

0 to 32767

Default FALSE 0
---

* On Sysmac Studio version 1.03, you can use "R" instead of "Reset" and "LD" instead of "Load" to more clearly show the correspondence between the variables and the parameter names in ST expressions. For example, you can use the following notation: CTUD_instance(CU:=A, CD:=B, R:=abc, LD:=def, PV:=INT#3, QU=>ghi, QD=>jkl, CV=>mno);.

NJ/NX-series Instructions Reference Manual (W502)

2-155

2 Instruction Descriptions

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

Bit string

Integers

Times, durations, dates, and text strings

CU

OK

CD

OK

Reset

OK

Load

OK

PV

OK

QU

OK

QD

OK

CV

OK

Function
The CTUD instruction creates an up-down counter that operates according to an up-counter input signal and a down-counter input signal. It has the functions of both an up counter and a down counter. The preset value and counter value must have an INT data type.
Operation as an Up Counter
When reset signal Reset changes to TRUE, counter value CV changes to 0 and up-counter output QU changes to FALSE. When up-counter input signal CU changes to TRUE, CV is incremented. When the value of CV reaches the value of PV or higher, the value of QU changes to TRUE. After the value of CV reaches the value of PV or higher, the value of CV does not change even if the value of CU changes to TRUE.
Operation as a Down Counter
When load signal Load changes to TRUE, counter value CV changes to the value of preset value PV and down-counter output QD changes to FALSE. When down-counter input signal CD changes to TRUE, CV is decremented. When the value of CV reaches 0 or less, the value of QD changes to TRUE. After the value of CV reaches 0 or less, CV does not change even if CD changes to TRUE.
Common Operation for Up and Down Counters
CU and CD are ignored while Load and Reset are TRUE. CV is not incremented or decremented. If both CU and CD change to TRUE at the same time, CV will not change. If Reset and Load are both TRUE, Reset has priority and the value of CV changes to 0. If Reset changes to TRUE, CV changes to 0, and so QD changes to TRUE. If Load changes to TRUE, the value of CV changes to PV, and so QU changes to TRUE.

2-156

NJ/NX-series Instructions Reference Manual (W502)

Counter Instructions

2 Instruction Descriptions

The following table shows the relationship between Reset, Load, CV, QU, and QD. This assumes that the value of PV is larger than 0.

Reset Load

CV

QU

QD

Operation

0 or lower

FALSE TRUE

Only up counter operation is performed.
· CV is incremented when CU changes to TRUE. It is not decremented when CD changes to TRUE.

FALSE

FALSE

Between FALSE 0 and PV

FALSE

Both up and down counter operation is performed.
· CV is incremented when CU changes to TRUE and decremented when CD changes to TRUE.

PV or TRUE FALSE Only down counter operation is performed.

higher

· CV is decremented when CD changes to TRUE. It is

not incremented when CU changes to TRUE.

2

TRUE FALSE 0

FALSE TRUE The up counter is reset.

· The value of CV is set to 0.

CTUD

FALSE TRUE PV

TRUE

FALSE

The down counter is reset. · The value of CV is set to PV.

TRUE TRUE 0

FALSE TRUE

The up counter is reset. Reset take priority over Load. · The value of CV is set to 0.

The following figure shows a programming example and timing chart for a PV of INT#3.

LD

ST

A
B abc def INT#3

CTUD_instance

CTUD

CU

QU

CD

QD

Reset

CV

Load

PV

CTUD_instance(A, B, abc, def, INT#3, ghi, jkl, mno);
ghi
jkl mno

NJ/NX-series Instructions Reference Manual (W502)

2-157

2 Instruction Descriptions

CU=A CD=B

TRUE FALSE
TRUE FALSE

TRUE Reset=abc FALSE
TRUE Load=def FALSE

CV=mno

PV=INT#3 0

QU=ghi QD=jkl

TRUE FALSE
TRUE FALSE

When CV reaches PV, QU changes to TRUE.
When Reset changes to TRUE, CV changes to 0, QU changes to FALSE, and QD changes to TRUE.
When Reset changes to FALSE, the counter inputs are enabled. When CU changes to TRUE, CV is incremented. This causes QD to change to FALSE.
When CD changes to TRUE, CV is decremented.
When CV reaches 0, QD changes to TRUE. When Load changes to TRUE, CV changes to PV . This causes QU to change to TRUE and QD to change to FALSE.
Additional Information
Use the CTD instruction (page 2-146) or CTU instruction (page 2-150) to create a counter that only decrements or only increments.

Precautions for Correct Use
· If you change Reset to TRUE to reset the up-counter operation, QU will change to FALSE and QD will change to TRUE.
· If you change Load to TRUE to reset the down-counter operation, QD will change to FALSE and QU will change to TRUE.
· Even when PV is set to a negative value, CV is set to the value of PV when the value of Load changes to TRUE. The value of CV will be 0 or less, so the value of QD changes to TRUE immediately. After that, the value of CV is not decremented even if the value of CD changes. When the value of Reset changes to TRUE, the value of CV changes to 0. The value of CV will be the value of PV or higher, so the value of QU changes to TRUE immediately. After that, the value of CV is not incremented even if the value of CU changes.
· You can change the value of PV during execution of the instruction. If the new value of PV is less than the current value of CV, the value of QU changes to TRUE immediately.
· If the value of CU or CD is FALSE and the power supply is interrupted or the operating mode is changed to PROGRAM mode, the value of CV is incremented or decremented once if the value of CU or CD is TRUE when instruction execution is restarted.

2-158

NJ/NX-series Instructions Reference Manual (W502)

Counter Instructions

2 Instruction Descriptions

CTUD_**

The CTUD_** instruction creates an up-down counter that operates according to an up-counter input and a down-counter input. The preset value and counter value must be one of the following data types: DINT, LINT, UDINT, or ULINT.

Instruction

Name

FB/FUN

Graphic expression

ST expression

CTUD_**

Up-down Counter FB Group

CTUD_**_instance

CTUD_**

CU

QU

CD

QD

Reset

CV

CTUD_**_instance (CU,

CD, Reset, Load, PV, QU,

QD, CV);

"**" must be DINT, LINT,

2

UDINT, or ULINT.

Load

PV

"**" must be DINT, LINT, UDINT,

or ULINT.

CTUD_**

Variables

Name CU CD
Reset*1 Load*1 PV

Meaning
Up-counter input
Downcounter input
Reset signal
Load signal

I/O Input

Preset value

QU

Up-counter

output

QD

Down-

counter

Output

output

CV

Counter

value

Description Up counter input

Valid range

Unit

Down counter input

Depends on data type.

TRUE: Reset CV to 0.

---
TRUE: CV set to PV.

The final counter value when operating as an up counter
The initial counter value when operating as a down counter

Depends on data type.*2

TRUE: up-counter output ON

FALSE: up-counter output

OFF

Depends on data type.

TRUE: down-counter output

ON

---

FALSE: down-counter output OFF

Counter present value

Depends on data type.*2

Default FALSE 0
---

*1 On Sysmac Studio version 1.03, you can use "R" instead of "Reset" and "LD" instead of "Load" to more clearly show the correspondence between the variables and the parameter names in ST expressions. For example, you can use the following notation: CTUD_LINT_instance(CU:=A, CD:=B, R:=abc, LD:=def, PV:=LINT#3, QU=>ghi, QD=>jkl, CV=>mno);.
*2 Negative numbers are excluded.

NJ/NX-series Instructions Reference Manual (W502)

2-159

2 Instruction Descriptions

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

Bit string

Integers

Times, durations, dates, and text strings

CU

OK

CD

OK

Reset

OK

Load

OK

PV

QU

OK

QD

OK

CV

OK OK

OK OK

Must be the same data type as PV

Function
A CTUD_** instruction creates an up-down counter that operates according to an up-counter input signal and a down-counter input signal. The counter has the functions of both an up counter and a down counter. The preset value and counter value must be one of the following data types: DINT, LINT, UDINT, or ULINT. The name of the instruction is determined by the data type of PV and CV. For example, if they are the LINT data type, the instruction is CTUD_LINT.
Operation as an Up Counter
When reset signal Reset changes to TRUE, counter value CV changes to 0 and up-counter output QU changes to FALSE. When up-counter input signal CU changes to TRUE, CV is incremented. When the value of CV reaches the value of PV or higher, the value of QU changes to TRUE. After the value of CV reaches the value of PV or higher, the value of CV does not change even if the value of CU changes to TRUE.
Operation as a Down Counter
When load signal Load changes to TRUE, counter value CV changes to the value of preset value PV and down-counter output QD changes to FALSE. When down-counter input signal CD changes to TRUE, CV is decremented. When the value of CV reaches 0 or less, the value of QD changes to TRUE. After the value of CV reaches 0 or less, CV does not change even if CD changes to TRUE.
Common Operation for Up and Down Counters
CU and CD are ignored while Load or Reset is TRUE. CV is not incremented or decremented. If both CU and CD change to TRUE at the same time, CV will not change. If Reset and Load are both TRUE, Reset has priority and the value of CV changes to 0. If Reset changes to TRUE, CV changes to 0, and so QD changes to TRUE. If Load changes to TRUE, the value of CV changes to PV, and so QU changes to TRUE.

2-160

NJ/NX-series Instructions Reference Manual (W502)

Counter Instructions

2 Instruction Descriptions

The following table shows the relationship between Reset, Load, CV, QU, and QD. This assumes that the value of PV is larger than 0.

Reset Load

CV

QU

QD

Operation

0 or lower

FALSE TRUE

Only up counter operation is performed.
· CV is incremented when CU changes to TRUE. It is not decremented when CD changes to TRUE.

FALSE

FALSE

Between FALSE 0 and PV

FALSE

Both up and down counter operation is performed.
· CV is incremented when CU changes to TRUE and decremented when CD changes to TRUE.

PV or TRUE FALSE Only down counter operation is performed.

higher

· CV is decremented when CD changes to TRUE. It is

not incremented when CU changes to TRUE.

2

TRUE FALSE 0

FALSE TRUE The up counter is reset.

· The value of CV is set to 0.

CTUD_**

FALSE TRUE PV

TRUE

FALSE

The down counter is reset. · The value of CV is set to PV.

TRUE TRUE 0

FALSE TRUE

The up counter is reset. Reset take priority over Load. · The value of CV is set to 0.

The following figure shows a CTUD_LINT programming example and timing chart for a PV of LINT#3.

LD

ST

A
B abc def LINT#3

CTUD_LINT_instance

CTUD_LINT

CU

QU

CD

QD

Reset

CV

Load

PV

ghi
jkl mno

CTUD_LINT_instance(A, B, abc, def, LINT#3, ghi, jkl, mno);

NJ/NX-series Instructions Reference Manual (W502)

2-161

2 Instruction Descriptions

CU=A CD=B

TRUE FALSE
TRUE FALSE

Reset=abc Load=def

TRUE FALSE
TRUE FALSE

CV=mno

PV=LINT#3 0

QU=ghi QD=jkl

TRUE FALSE
TRUE FALSE

When CV reaches PV, QU changes to TRUE.
When Reset changes to TRUE, CV changes to 0, QU changes to FALSE, and QD changes to TRUE.
When Reset changes to FALSE, the counter inputs are enabled. When CU changes to TRUE, CV is incremented. This causes QD to change to FALSE.
When CD changes to TRUE, CV is decremented.
When CV reaches 0, QD changes to TRUE.
When Load changes to TRUE, CV changes to PV. This causes QU to change to TRUE and QD to change to FALSE.
Additional Information
Use the CTD instruction (page 2-146) or CTU instruction (page 2-150) to create a counter that only decrements or only increments.

Precautions for Correct Use
· If you change Reset to TRUE to reset the up-counter operation, QU will change to FALSE and QD will change to TRUE.
· If you change Load to TRUE to reset the down-counter operation, QD will change to FALSE and QU will change to TRUE.
· Even when PV is set to a negative value, CV is set to the value of PV when the value of Load changes to TRUE. The value of CV will be 0 or less, so the value of QD changes to TRUE immediately. After that, the value of CV is not decremented even if the value of CD changes. When the value of Reset changes to TRUE, the value of CV changes to 0. The value of CV will be the value of PV or higher, so the value of QU changes to TRUE immediately. After that, the value of CV is not incremented even if the value of CU changes.
· You can change the value of PV during execution of the instruction. If the new value of PV is less than the current value of CV, the value of QU changes to TRUE immediately.
· Use the same data type for PV and CV.

2-162

NJ/NX-series Instructions Reference Manual (W502)

Counter Instructions

2 Instruction Descriptions
· If the value of CU or CD is FALSE and the power supply is interrupted or the operating mode is changed to PROGRAM mode, the value of CV is incremented or decremented once if the value of CU or CD is TRUE when instruction execution is restarted.
2

CTUD_**

NJ/NX-series Instructions Reference Manual (W502)

2-163

2 Instruction Descriptions

2-164

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

2
Math Instructions

Instruction ADD (+)

Name Addition

Page

Instruction

2-166 EXP

AddOU (+OU) SUB (-) SubOU (-OU)
MUL (*) MulOU (*OU)
DIV (/) MOD ABS RadToDeg and DegToRad
SIN, COS, and TAN
ASIN, ACOS, and ATAN
SQRT LN and LOG

Addition with Overflow Check
Subtraction
Subtraction with Overflow Check
Multiplication
Multiplication with Overflow Check
Division
Modulo-division
Absolute Value
Radians to Degrees/ Degrees to Radians
Sine in Radians/ Cosine in Radians/ Tangent in Radians
Principal Arc Sine/ Principal Arc Cosine/ Principal Arc Tangent
Square Root
Natural Logarithm/ Logarithm Base 10

2-170 2-174 2-177
2-181 2-185
2-189 2-192 2-194 2-196
2-198
2-201
2-204 2-206

EXPT (**) Inc and Dec Rand
AryAdd AryAddV
ArySub ArySubV AryMean ArySD
ModReal
Fraction
CheckReal

Name Natural Exponential Operation Exponentiation Increment/Decrement Random Number

Page 2-209
2-211 2-217 2-219

Array Addition Array Value Addition

2-221 2-223

Array Subtraction Array Value Subtraction Array Mean Array Element Standard Deviation Real Number Modulo-division

2-225 2-227 2-229 2-231
2-233

Real Number Fraction

2-235

Real Number Check

2-237

NJ/NX-series Instructions Reference Manual (W502)

2-165

2 Instruction Descriptions

ADD (+)

The ADD (+) instruction adds integers or real numbers. It also joins text strings.

Instruction ADD (+)

Name Addition

FB/FUN FUN

Graphic expression

(@)ADD

EN ENO

In1

Out

::

InN

ST expression Out:=In1 + In2;

(@)+

EN ENO

In1

Out

::

InN

Variables

Name

Meaning

I/O

Description

Valid range

Unit

Default

In1 to InN Add values Input

Numbers to add

Depends on data type. ---

0*2

Ladder diagram: N = 2 to 5

ST: N = 2*1

Out

Output

Output

Output value

value

Depends on data type. ---

---

*1 However, you can use more instructions if you use them as operators in an expression, such as result:= val1 + val2 +

val3;. You can use up to 64 instructions in one expression.

*2 If you omit the input parameter that connects to InN, the default value is not applied, and a building error will occur. For example, if N is 3 and the input parameters that connect to In1 and In2 are omitted, the default values are applied, but if the input parameter that connects to In3 is omitted, a building error will occur.

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In1 to InN Out

OK OK OK OK OK OK OK OK OK OK

OK

OK OK OK OK OK OK OK OK OK OK

OK

Function
In a ladder diagram, the Add (+) instruction adds between two and five integers or real numbers and outputs the result to output value Out. In ST, the Add instruction adds two integers or real numbers and outputs the result to output value Out.
Add values In1 to InN can have different data types. However, use the combination that data types to include are existed. If they are different, calculations are performed with the data type that includes the range of all of the data types. For example, if In1 is INT data and In2 is DINT data, calculations are performed with DINT data. Here, the addition result is DINT data.

2-166

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

ADD (+)

2 Instruction Descriptions

Refer to Data Type Ranking Table and Casting Rules in the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) or NY-series Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for the including relationship on data types.

Data type that includes In1 to InN Examples: If INT data are added, then INT data is used. If INT and DINT data are added, then DINT data is used.

In1

Addition

In2

:

:

Addition result Assignment Out

InN

2

Processing for Overflows

An overflow occurs if the sum of In1 to InN exceeds the valid range of the data type of the addition result. If an overflow occurs, the data types of In1 to InN, the data type of the addition result, and the value of the addition result will be as shown in the following table.

Data types of In1 to InN All integer data
At least one real number

Data type of addition result
Integer data
Real number data

Value of addition result
Of the sum of In1 to InN, the addition result will be the value that can be expressed by the number of bits in the data type of the addition result.*1 ±*2

*1 For example, if the value of In1 is INT#32767 and the value of In2 is INT#3, the addition result will be INT data. The value of the addition result will be the lower 16 bits of the sum (32,770), i.e., INT#-32766.
*2 If the sum of In1 to InN is positive, the addition result will be positive infinity. If the sum is negative, the addition result will be negative infinity.

Notation Examples

The following example is for when In1 is INT#10, In2 is INT#20 and In3 is INT#30. The value of INT variable abc will be INT#60.

LD

ST

abc:=INT#10+INT#20+INT#30;

ADD

EN INT#10 In1 INT#20 In2 INT#30 In3

ENO abc

The ADD instruction adds In1 through InN. The calculation is 10 + 20 + 30 = 60, so the value of abc will be INT#60.

In1 INT#10 + In2 INT#20 + In3 INT#30

Added.

Out=abc INT#60

NJ/NX-series Instructions Reference Manual (W502)

2-167

2 Instruction Descriptions

Joining Text Strings
If In1 to InN are STRING data, the text strings are joined. However, if In1 to InN are STRING data, you must use the instruction in a ladder diagram. The following example is for when In1 is UV, In2 is WX and In3 is YZ. The value of STRING variable abc will be `UVWXYZ'.
LD

ADD

EN `UV' In1 `WX' In2 `YZ' In3

ENO abc

In1 `UV'

Text strings joined.

In2 `WX'

Out=abc `UVWXYZ'

In3 `YZ'

Differences in Specifications between Ladder Diagrams and ST

Specifications of this instruction depend on whether it is used in a ladder diagram or ST. The following table gives the differences in specifications. In ladder diagrams, the specifications of the ADD instruction and the + instruction are exactly the same.

Item

Ladder diagram

ST

Maximum number of values to 5

2*1

add

Omitting input parameters for values to add

You can omit everything except for the input parameters connected to InN.

You cannot omit any input parameters.

Existence of EN and ENO vari- Present ables

None

Number of data processing bits if the values to add are all integer data

8, 16, 32, or 64*2

32 or 64*3

Joining of text strings

Possible.

Not possible.

Errors

An error occurs if the size that results None from joining text strings exceeds 1,986 bytes.

*1 However, you can use more instructions if you use them as operators in an expression, such as result := val1 + val2 + val3;. You can use up to 64 instructions in one expression.

*2 The number of processing bits is aligned with the largest data type of all the values to add. For example, if you add SINT, INT, and DINT data, the data processing bits will be aligned to the size of DINT data, i.e., 32-bit processing is performed.

*3 If there is no LINT or ULINT data in the values to add, 32-bit processing is used. For example, if two SINT values are added, 32-bit processing is used. If there is LINT or ULINT data in the values to add, 64-bit processing is used.

2-168

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

ADD (+)

2 Instruction Descriptions

Additional Information
· When you calculate real numbers, use the CheckReal instruction (page 2-237) to see if Out is positive infinity, negative infinity, or nonnumeric data.
· Use the CONCAT instruction (page 2-554) to join text strings in structured text.

Precautions for Correct Use

· Out can have a different data type than the addition result. However, the data type of Out must include the valid range of the data type of the addition result. Otherwise, a building error will occur.
Refer to Data Type Ranking Table and Casting Rules in the NJ/NX-series CPU Unit Software User's 2
Manual (Cat. No. W501) or NY-series Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for the including relationship on data types.
· When you join text strings, use STRING data for In1 to InN and Out.
· An error will not occur even if an underflow or overflow occurs in the addition.
· If an underflow or overflow occurs in addition, the calculation result may not be as expected. Allow sufficient leeway in the sizes of the data types for input and output parameters so that overflows and underflows do not occur.
· Addition results of positive or negative infinity are handled as follows for real number values.

Addition + plus number

Addition result +

- plus number

-

+ plus +

+

- plus - + plus -

-
Nonnumeric data

· If any of the values of In1 to InN is nonnumeric data, the value of the addition result is nonnumeric data.
· An error will occur in the following cases. ENO will be FALSE, and Out will not change.
· The size of the joined text string exceeds 1,986 bytes when joining strings.

NJ/NX-series Instructions Reference Manual (W502)

2-169

2 Instruction Descriptions

AddOU (+OU)

The AddOU (+OU) instruction adds integers and real numbers. It also performs an overflow check for integer addition result.

Instruction AddOU (+OU)

Name
Addition with Overflow Check

FB/FUN FUN

Graphic expression

(@)AddOU

EN In1 :: InN

ENO Out

ST expression Out:=AddOU(In1, ···, InN);

(@)+OU

EN ENO

In1

Out

::

InN

Variables

Name In1 to InN Out

Meaning
Add values
Output value

I/O Input Output

Description Numbers to add, N = 2 to 5 Output value

Valid range Depends on data type. Depends on data type.

Unit
-----

Default
0* ---

* If you omit the input parameter that connects to InN, the default value is not applied, and a building error will occur. For example, if N is 3 and the input parameters that connect to In1 and In2 are omitted, the default values are applied, but if the input parameter that connects to In3 is omitted, a building error will occur.

Bit strings

Integers

Times, durations, dates, and text strings

Real numbers

LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

STRING DT TOD
DATE TIME

LREAL REAL

In1 to InN Out

OK OK OK OK OK OK OK OK OK * OK * OK OK OK OK OK OK OK OK OK OK

* If any of In1 to InN is REAL data, an overflow check is not performed.

Function
The AddOU (+OU) instruction adds between two and five integers or real numbers and outputs the result to output value Out.
Add values In1 to InN can have different data types. However, use the combination that data types to include are existed. If they are different, calculations are performed with the data type that includes the range of all of the data types. For example, if In1 is INT data and In2 is DINT data, calculations are performed with DINT data. Here, the addition result is DINT data. Refer to Data Type Ranking Table and Casting Rules in the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) or NY-series Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for the including relationship on data types.

2-170

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

AddOU (+OU)

2 Instruction Descriptions

Processing for Overflows

An overflow occurs if the sum of In1 to InN exceeds the valid range of the data type of the addition result. If all of In1 to InN are integer data and an overflow occurs, the value of the P_CY system-defined variable (Carry Flag) changes to TRUE.
If any of In1 to InN is REAL data, an overflow check is not performed. Therefore the value of P_CY will not change.

Data type that includes In1 to InN

Examples:

If INT data are added, then INT data is used.

If INT and DINT data are added, then DINT data is used.

2

In1

Addition

In2

:

:

Addition result Assignment Out

InN P_CY

Changes to TRUE if In1 to InN are all integer data and the value of the addition result exceeds the valid range of the data type of the addition result. The data type of Out is not relevant.

If an overflow occurs, the data types of In1 to InN, the data type of the addition result, the value of the addition result, and the value of P_CY will be as shown in the following table.

Data types of In1 to InN All integer data
At least one real number

Data type of addition result
Integer data
Real number data

Value of addition result
Of the sum of In1 to InN, the addition result will be the value that can be expressed by the number of bits in the data type of the addition result.*1 ±*2

Value of P_CY TRUE
Does not change.

*1 For example, if the value of In1 is INT#32767 and the value of In2 is INT#3, the addition result will be INT data. The value of the addition result will be the lower 16 bits of the sum (32,770), i.e., INT#-32766.
*2 If the sum of In1 to InN is positive, the addition result will be positive infinity. If the sum is negative, the addition result will be negative infinity.

NJ/NX-series Instructions Reference Manual (W502)

2-171

2 Instruction Descriptions

Notation Examples

The following example is for when In1 is INT#32767, In2 is INT#1 and variable abc has an INT data type. In1 to InN are all INT data, so the addition result is INT data. The sum of the two numbers (32,768) exceeds the valid range of INT data, so the value of P_CY changes to TRUE. The value of INT variable abc will be INT#-32768 (the lower 16 bits of 32,768).

LD

ST

abc:=AddOU(INT#32767, INT#1);

AddOU

EN INT#32767 In1
INT#1 In2

ENO abc

The AddOU instruction adds In1 to InN. The sum of the two numbers (32,768) exceeds the valid range of INT data, so the value of P_CY changes to TRUE.

In1 INT#32767 + In2 INT#1

Added.

32,767+1 = the value of the lower 16 bits of 32,768 (INT data size = 16 bits)
Out=abc INT#-32768

P_CY TRUE

The sum of the two numbers exceeds the valid range of INT data, so the value of P_CY changes to TRUE.

Differences in Specifications between Ladder Diagrams and ST
There are no differences in the specifications of this instruction regardless of whether it is used in a ladder diagram or ST. In ladder diagrams, there are no differences in the specifications of the AddOU instruction and the +OU instruction.

Related System-defined Variables

Name P_CY

Meaning Carry (CY) Flag

Data type BOOL

Description
TRUE: Overflow occurred for integer calculations.
FALSE: Overflow did not occur for integer calculations.

Additional Information
· If Out is REAL data, use the CheckReal instruction (page 2-237) to see if Out is positive infinity, negative infinity, or nonnumeric data.
· Use the ADD (+) instruction (page 2-166) if there is no need for an overflow check. It will reduce processing time.

2-172

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

2 Instruction Descriptions

Precautions for Correct Use

· Out can have a different data type than the addition result. However, the data type of Out must include the valid range of the data type of the addition result. Otherwise, a building error will occur. Refer to Data Type Ranking Table and Casting Rules in the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) or NY-series Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for the including relationship on data types.

· If an underflow or overflow occurs in addition, the calculation result may not be as expected. Allow sufficient leeway in the sizes of the data types for input and output parameters so that overflows and underflows do not occur.

· Addition results of positive or negative infinity are handled as follows for real number values.

Addition

Addition result

2

+ plus number

+

- plus number

-

+ plus +

+

- plus -

-

+ plus -

Nonnumeric data

· If any of the values of In1 to InN is nonnumeric data, the value of the addition result is nonnumeric data.

AddOU (+OU)

NJ/NX-series Instructions Reference Manual (W502)

2-173

2 Instruction Descriptions

SUB (-)

The SUB (-) instruction subtracts integers and real numbers.

Instruction SUB (-)

Name Subtraction

FB/FUN FUN

Graphic expression

(@)SUB

EN ENO

In1

Out

In2

(@)-

EN ENO

In1

Out

In2

ST expression Out:=In1 - In2;

Variables

Name

Meaning

I/O

Description

Valid range

Unit

In1

Minuend

Minuend

Input

In2

Subtrahend

Subtrahend

Depends on data type. ---

Out

Output

Output

Output value

value

Depends on data type. ---

* If you omit an input parameter, the default value is not applied. A building error will occur.

Default 0*
---

Bit string

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In1

OK OK OK OK OK OK OK OK OK OK

In2

OK OK OK OK OK OK OK OK OK OK

Out

OK OK OK OK OK OK OK OK OK OK

Function
The SUB (-) instruction subtracts subtrahend In2 from minuend In1 and outputs the result to output value Out.

In1 and In2 can have different data types. However, use the combination that data types to include are existed. If they are different, calculations are performed with the data type that includes the range of all of the data types. For example, if In1 is INT data and In2 is DINT data, calculations are performed with DINT data. Here, the subtraction result is DINT data.
Data type that includes In1 and In2 Examples: If subtraction is performed for INT data, then INT data is used. If subtraction is performed for INT and DINT data, then DINT data is used.

Subtraction result

Assignment

In1

- In2

=

Out

2-174

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Math Instructions

SUB (-)

Refer to Data Type Ranking Table and Casting Rules in the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) or NY-series Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for the including relationship on data types.

Processing for Overflows

An overflow occurs if the difference between In1 and In2 exceeds the valid range of the data type of the subtraction result. If an overflow occurs, the data types of In1 and In2, the data type of the subtraction result, and the value of the subtraction result will be as shown in the following table.

Data types of In1 and In2

Data type of subtraction result

Value of subtraction result

All integer data

Integer data

Of the difference between In1 to InN, the subtraction

2

result will be the value that can be expressed by the num-

ber of bits in the data type of the subtraction result.*1

At least one real number

Real number data

±*2

*1 For example, if the value of In1 is INT#32767 and the value of In2 is INT#3, the subtraction result will be INT data. The value of the subtraction result will be the lower 16 bits of the difference (32,770), i.e., INT#-32766.
*2 If the difference between In1 and InN is positive, the subtraction result will be positive infinity. If the difference is negative, the subtraction result will be negative infinity.

Notation Examples

The following example is for when In1 is INT#50 and In2 is INT#10. The value of INT variable abc will be INT#40.

LD

ST

abc:=INT#50-INT#10;

SUB

EN INT#50 In1 INT#10 In2

ENO abc

The SUB instruction subtracts In2 from In1. The calculation is 50 - 10 = 40, so the value of abc will be INT#40.

In1 INT#50 - In2 INT#10

Subtracted.

Out=abc INT#40

Differences in Specifications between Ladder Diagrams and ST

Specifications of this instruction depend on whether it is used in a ladder diagram or ST. The following table gives the differences in specifications. In ladder diagrams, the specifications of the SUB instruction and the - instruction are exactly the same.

Item

Ladder diagram

ST

Existence of EN and ENO variables

Present

None

Number of data processing bits if the minuend and subtrahend are inte- 8, 16, 32, or 64*1 ger data

32 or 64*2

*1 The number of processing bits is aligned with the larger data type of the minuend and subtrahend. For example, if you perform subtraction for SINT and DINT data, the data processing bits will be aligned to the size of DINT data, i.e., 32-bit processing is performed.

*2 If there is no LINT or ULINT data in the minuend and subtrahend, 32-bit processing is used. For example, if you perform subtraction for two SINT values, 32-bit processing is used. If there is LINT or ULINT data in the minuend and subtrahend, 64-bit processing is used.

NJ/NX-series Instructions Reference Manual (W502)

2-175

2 Instruction Descriptions

Additional Information
When you calculate real numbers, use the CheckReal instruction (page 2-237) to see if Out is positive infinity, negative infinity, or nonnumeric data.

Precautions for Correct Use

· Out can have a different data type than the subtraction result. However, the data type of Out must include the valid range of the data type of the subtraction result. Otherwise, a building error will occur. Refer to Data Type Ranking Table and Casting Rules in the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) or NY-series Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for the including relationship on data types.
· An error will not occur even if an underflow or overflow occurs in the subtraction.
· If an underflow or overflow occurs in subtraction, the calculation result may not be as expected. Allow sufficient leeway in the sizes of the data types for input and output parameters so that overflows and underflows do not occur.
· Subtraction results of positive or negative infinity are handled as follows for real number values.

Subtraction + minus number Number minus + - minus number Number minus - + minus + + minus - - minus + - minus -

Subtraction result + - - + Nonnumeric data + - Nonnumeric data

· If the value of In1 or In2 is nonnumeric data, the value of the subtraction result is nonnumeric data.

2-176

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

2 Instruction Descriptions

SubOU (-OU)

The SubOU (-OU) instruction subtracts integers or real numbers. It also performs an overflow check for integer subtraction result.

Instruction

Name

FB/FUN

Graphic expression

ST expression

SubOU (-OU)

Subtraction with Overflow Check

FUN

(@)SubOU

Out:=SubOU(In1, In2);

EN

ENO

In1

Out

In2

2

(@)-OU

EN ENO

In1

Out

In2

Variables

Name In1 In2 Out

Meaning

I/O

Minuend Input
Subtrahend

Output value

Output

Description Minuend Subtrahend Output value

Valid range

Unit

Depends on data type. ---

Depends on data type. ---

* If you omit an input parameter, the default value is not applied. A building error will occur.

Default
0* ---

Bit strings

Integers

Times, durations, dates, and text strings

SubOU (-OU)

Real numbers

LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

STRING DT TOD
DATE TIME

LREAL REAL

In1

OK OK OK OK OK OK OK OK OK * OK *

In2

OK OK OK OK OK OK OK OK OK * OK *

Out

OK OK OK OK OK OK OK OK OK OK

* If In1 or In2 is REAL data, an overflow check is not performed.

Function
The SubOU (-OU) instruction subtracts subtrahend In2 from minuend In1 and outputs the result to output value Out.
In1 and In2 can have different data types. However, use the combination that data types to include are existed. If they are different, calculations are performed with the data type that includes the range of all of the data types. For example, if In1 is INT data and In2 is DINT data, calculations are performed with DINT data. Here, the subtraction result is DINT data. Refer to Data Type Ranking Table and Casting Rules in the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) or NY-series Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for the including relationship on data types.

NJ/NX-series Instructions Reference Manual (W502)

2-177

2 Instruction Descriptions

Processing for Overflows
An overflow occurs if the difference between In1 and In2 exceeds the valid range of the data type of the subtraction result. If In1 and In2 are both integer data and an overflow occurs, the value of the P_CY system-defined variable (Carry Flag) changes to TRUE. If either In1 or In2 is REAL data, an overflow check is not performed. Therefore the value of P_CY will not change.
Data type that includes In1 and In2 Examples: If subtraction is performed for INT data, then INT data is used. If subtraction is performed for INT and DINT data, then DINT data is used.

In1

- In2

Subtraction result Assignment

=

Out

P_CY

Changes to TRUE if In1 and In2 are both integer data and the value of the subtraction result exceeds the valid range of the data type of the subtraction result. The data type of Out is not relevant.

If an overflow occurs, the data types of In1 and In2, the data type of the subtraction result, the value of the subtraction result, and the value of P_CY will be as shown in the following table.

Data types of In1 and In2 All integer data
At least one real number

Data type of subtraction result
Integer data
Real number data

Value of subtraction result

Value of P_CY

Of the difference between In1 to InN, the subtraction result will be the value that can be expressed by the number of bits in the data type of the subtraction result.*1
±*2

TRUE
Does not change.

*1 For example, if the value of In1 is INT#32767 and the value of In2 is INT#-3, the subtraction result will be INT data. The value of the subtraction result will be the lower 16 bits of the difference (32,770), i.e., INT#-32766.
*2 If the difference between In1 and InN is positive, the subtraction result will be positive infinity. If the difference is negative, the subtraction result will be negative infinity.

Notation Examples

The following example is for when In1 is SINT#-128, In2 is SINT#1, and variable abc is SINT data. In1 and In2 are both SINT data, so the subtraction result is SINT data. The difference between the two values (-129) exceeds the valid range of SINT data, so the value of P_CY changes to TRUE. The value of SINT variable abc will be SINT#127 (the value of the lower eight bits of -129).

LD

ST

abc:=SubOU(SINT#-128, SINT#1);

SubOU

EN SINT#-128 In1
SINT#1 In2

ENO abc

2-178

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

2 Instruction Descriptions

The SubOU instruction subtracts In2 from In1. The difference between the two values (-129) exceeds the valid range of SINT data, so the value of P_CY changes to TRUE.
-128 - 1 = the value of the lower 8 bits of -129 (SINT data size = 8 bits)

In1 SINT#-128 - In2 SINT#1

Subtracted.

Out=abc SINT#127

P_CY TRUE

The difference of the two numbers exceeds the valid range of SINT data, so the value of P_CY changes to TRUE.

Differences in Specifications between Ladder Diagrams and ST

2

There are no differences in the specifications of this instruction regardless of whether it is used in a ladder diagram or ST. In ladder diagrams, there are no differences in the specifications of the SubOU instruction and the - OU instruction.

Related System-defined Variables

Name P_CY

Meaning Carry (CY) Flag

Data type BOOL

Description
TRUE: Overflow occurred for integer calculations. FALSE: Overflow did not occur for integer calculations.

Additional Information
· When you calculate real numbers, use the CheckReal instruction (page 2-237) to see if Out is positive infinity, negative infinity, or nonnumeric data.
· Use the SUB (-) instruction (page 2-174) if there is no need for an overflow check. It will reduce processing time.

SubOU (-OU)

NJ/NX-series Instructions Reference Manual (W502)

2-179

2 Instruction Descriptions

Precautions for Correct Use

· Out can have a different data type than the subtraction result. However, the data type of Out must include the valid range of the data type of the subtraction result. Otherwise, a building error will occur. Refer to Data Type Ranking Table and Casting Rules in the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) or NY-series Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for the including relationship on data types.
· If an underflow or overflow occurs in subtraction, the calculation result may not be as expected. Allow sufficient leeway in the sizes of the data types for input and output parameters so that overflows and underflows do not occur.
· Subtraction results of positive or negative infinity are handled as follows for real number values.

Subtraction

Subtraction result

+ minus number

+

Number minus +

-

- minus number Number minus - + minus + + minus - - minus + - minus -

- + Nonnumeric data + - Nonnumeric data

· If the value of In1 or In2 is nonnumeric data, the value of the subtraction result is nonnumeric data.

2-180

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

MUL (*)

2 Instruction Descriptions

MUL (*)

The MUL (*) instruction multiplies integers and real numbers.

Instruction

Name

FB/FUN

Graphic expression

ST expression

MUL (*)

Multiplication

FUN

(@)MUL

Out:=In1 * In2;

EN ENO

In1

Out

::

InN

(@)*

2

EN ENO

In1

Out

::

InN

Variables

Name

Meaning

I/O

Description

Valid range

Unit

Default

In1 to InN Values to Input

Numbers to multiply

Depends on data type. ---

1*2

multiply

Ladder diagram: N = 2 to 5

ST: N = 2*1

Out

Output

Output

Output value

value

Depends on data type. ---

---

*1 However, you can use more instructions if you use them as operators in an expression, such as result:= val1 * val2 *

val3;. You can use up to 64 instructions in one expression.

*2 If you omit the input parameter that connects to InN, the default value is not applied, and a building error will occur. For example, if N is 3 and the input parameters that connect to In1 and In2 are omitted, the default values are applied, but if the input parameter that connects to In3 is omitted, a building error will occur.

Bit string

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In1 to InN Out

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK

Function
In a ladder diagram, the MUL (*) instruction multiplies between two and five integers or real numbers and outputs the result to output value Out. In ST, the MUL instruction multiplies two integers or real numbers and outputs the result to output value Out.
Values to multiply In1 to InN can have different data types. However, use the combination that data types to include are existed. If they are different, calculations are performed with the data type that includes the range of all of the data types. For example, if In1 is INT data and In2 is DINT data, calculations are performed with DINT data. Here, the multiplication result is DINT data.

NJ/NX-series Instructions Reference Manual (W502)

2-181

2 Instruction Descriptions

Refer to Data Type Ranking Table and Casting Rules in the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) or NY-series Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for the including relationship on data types.

Data type that includes In1 to InN Examples: If INT data are multiplied, then INT data is used. If INT and DINT data are multiplied, then DINT data is used.

In1

In2

:

:

Multiplication
Multiplication result Assignment Out

InN

Processing for Overflows

An overflow occurs if the product of In1 to InN exceeds the valid range of the data type of the multiplication result. If an overflow occurs, the data types of In1 to InN, the data type of the multiplication result, and the value of the multiplication result will be as shown in the following table.

Data types of In1 to InN All integer data
At least one real number

Data type of multiplication result
Integer data
Real number data

Value of multiplication result
Of the product of In1 to InN, the multiplication result will be the value that can be expressed by the number of bits in the data type of the multiplication result.*1 ±*2

*1 For example, if the value of In1 is INT#16384 and the value of In2 is INT#2, the multiplication result will be INT data. The value of the multiplication result will be the lower 16 bits of the product (32,768), i.e., INT#-32768.

*2 If the product of In1 to InN is positive, the multiplication result will be positive infinity. If the product is negative, the multiplication result will be negative infinity.

Notation Examples

The following example is for when In1 is INT#10, In2 is INT#20 and In3 is INT#30. The value of INT variable abc will be INT#6000.

LD

ST

abc:=INT#10*INT#20*INT#30;

MUL

EN INT#10 In1 INT#20 In2 INT#30 In3

ENO abc

The MUL instruction multiplies In1 to InN. The calculation is 10 × 20 × 30 = 6,000, so the value of abc will be INT#6000.

In1 INT#10

Multiplied. × In2 INT#20 × In3 INT#30

Out=abc INT#6000

2-182

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Math Instructions

MUL (*)

Differences in Specifications between Ladder Diagrams and ST
Specifications of this instruction depend on whether it is used in a ladder diagram or ST. The following table gives the differences in specifications. In ladder diagrams, the specifications of the MUL instruction and the * instruction are exactly the same.

Item

Ladder diagram

ST

Maximum number of values to multiply 5

2*1

Omitting input parameters for values to multiply

You can omit everything except for the input parameters connected to InN.

You cannot omit any input parameters.

Existence of EN and ENO variables Number of data processing bits if the

Present 8, 16, 32, or 64*2

None 32 or 64*3

2

values to multiple are all integer data

*1 However, you can use more instructions if you use them as operators in an expression, such as result:= val1 * val2 * val3;. You can use up to 64 instructions in one expression.

*2 The number of processing bits is aligned with the largest data type of all the values to multiply. For example, if you multiply SINT, INT, and DINT data, the data processing bits will be aligned to the size of DINT data, i.e., 32bit processing is performed.

*3 If there is no LINT or ULINT data in the values to multiply, 32-bit processing is used. For example, if two SINT values are multiplied, 32-bit processing is used. If there is LINT or ULINT data in the values to multiply, 64-bit processing is used.

Additional Information
When you calculate real numbers, use the CheckReal instruction (page 2-237) to see if Out is positive infinity, negative infinity, or nonnumeric data.

Precautions for Correct Use

· Out can have a different data type than the multiplication result. However, the data type of Out must include the valid range of the data type of the multiplication result. Otherwise, a building error will occur. Refer to Data Type Ranking Table and Casting Rules in the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) or NY-series Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for the including relationship on data types.
· An error will not occur even if an underflow or overflow occurs in the multiplication.
· If an underflow or overflow occurs in multiplication, the calculation result may not be as expected. Allow sufficient leeway in the sizes of the data types for input and output parameters so that overflows and underflows do not occur.
· Multiplication results of positive or negative infinity are handled as follows for real number values.

Multiplication + times positive number + times negative number

Multiplication result + -

- times positive number - times negative number + times + - times - + times - + times 0 - times 0

- + + + - Nonnumeric data Nonnumeric data

NJ/NX-series Instructions Reference Manual (W502)

2-183

2 Instruction Descriptions
· If any of the values of In1 to InN is nonnumeric data, the value of the multiplication result is nonnumeric data.

2-184

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

2 Instruction Descriptions

MulOU (*OU)

The MulOU (*OU) instruction multiplies integers and real numbers and outputs the result. It also performs an overflow check for integer multiplication result.

Instruction

Name

FB/FUN

Graphic expression

ST expression

MulOU (*OU)

Multiplication with Overflow Check

FUN

(@)MulOU

Out:=MulOU(In1, ···, InN);

EN

ENO

In1

Out

:: InN

2

(@)*OU

EN ENO

In1

Out

::

InN

Variables

Name In1 to InN
Out

Meaning
Values to multiply
Output value

I/O Input
Output

Description
Numbers to multiply, N = 2 to 5
Output value

Valid range

Unit

Depends on data type. ---

Depends on data type. ---

Default 1*
---

* If you omit the input parameter that connects to InN, the default value is not applied, and a building error will occur. For example, if N is 3 and the input parameters that connect to In1 and In2 are omitted, the default values are applied, but if the input parameter that connects to In3 is omitted, a building error will occur.

Bit string

Integers

Times, durations, dates, and text strings

MulOU (*OU)

Real numbers

LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

STRING DT TOD
DATE TIME

LREAL REAL

In1 to InN Out

OK OK OK OK OK OK OK OK OK * OK * OK OK OK OK OK OK OK OK OK OK

* If any of In1 to InN is REAL data, an overflow check is not performed.

Function
The MUL (*) instruction multiplies between two and five integers or real numbers and outputs the result to output value Out.
Values to multiply In1 to InN can have different data types. However, use the combination that data types to include are existed. If they are different, calculations are performed with the data type that includes the range of all of the data types. For example, if In1 is INT data and In2 is DINT data, calculations are performed with DINT data. Here, the multiplication result is DINT data. Refer to Data Type Ranking Table and Casting Rules in the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) or NY-series Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for the including relationship on data types.

NJ/NX-series Instructions Reference Manual (W502)

2-185

2 Instruction Descriptions

Processing for Overflows

An overflow occurs if the product of In1 to InN exceeds the valid range of the data type of the multiplication result. If all of In1 to InN are integer data and an overflow occurs, the value of the P_CY systemdefined variable (Carry Flag) changes to TRUE.
If any of In1 to InN is REAL data, an overflow check is not performed. Therefore the value of P_CY will not change.
Data type that includes In1 to InN Examples: If INT data are multiplied, then INT data is used. If INT and DINT data are multiplied, then DINT data is used.

In1

In2

:

:

Multiplication
Multiplication result Assignment Out

InN P_CY

Changes to TRUE if In1 to InN are all integer data and the value of the multiplication result exceeds the valid range of the data type of the multiplication result. The data type of Out is not relevant.

If an overflow occurs, the data types of In1 to InN, the data type of the multiplication result, the value of the multiplication result, and the value of P_CY will be as shown in the following table.

Data types of In1 to InN All integer data
At least one real number

Data type of multiplication result
Integer data
Real number data

Value of multiplication result

Value of P_CY

Of the product of In1 to InN, the multiplication result will be the value that can be expressed by the number of bits in the data type of the multiplication result.*1
±*2

TRUE
Does not change.

*1 For example, if the value of In1 is INT#16384 and the value of In2 is INT#2, the multiplication result will be INT data. The value of the multiplication result will be the lower 16 bits of the product (32,768), i.e., INT#-32768.
*2 If the product of In1 to InN is positive, the multiplication result will be positive infinity. If the product is negative, the multiplication result will be negative infinity.

Notation Examples

The following example is for when In1 is INT#20000, In2 is INT#2 and variable abc has an INT data type. In1 to InN are all INT data, so the addition result is INT data. The product of the two values (40,000) exceeds the valid range of INT data, so the value of P_CY changes to TRUE. The value of INT variable abc will be INT#-25536 (the lower 16 bits of 40,000).

LD

ST

abc:=MulOU(INT#20000, INT#2);

MulOU

EN INT#20000 In1
INT#2 In2

ENO abc

2-186

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

MulOU (*OU)

2 Instruction Descriptions

The MulOU instruction multiplies In1 to InN. The product of the two values (40,000) exceeds the valid range of INT data, so the value of P_CY changes to TRUE.

In1 INT#20000 × In2 INT#2

Multiplied.

20000 × 2 = the value of the lower 16 bits of 40,000 (INT data size = 16 bits)
Out=abc INT#-25536

P_CY TRUE

The product of the two numbers exceeds the valid range of INT data, so the value of P_CY changes to TRUE.

Differences in Specifications between Ladder Diagrams and ST

2

There are no differences in the specifications of this instruction regardless of whether it is used in a ladder diagram or ST. In ladder diagrams, there are no differences in the specifications of the MulOU instruction and the *OU instruction.

Related System-defined Variables

Name P_CY

Meaning Carry (CY) Flag

Data type BOOL

Description
TRUE: Overflow occurred for integer calculations. FALSE: Overflow did not occur for integer calculations.

Additional Information
· When you calculate real numbers, use the CheckReal instruction (page 2-237) to see if Out is positive infinity, negative infinity, or nonnumeric data.
· Use the MUL (*) instruction (page 2-181) if there is no need for an overflow check. It will reduce processing time.

NJ/NX-series Instructions Reference Manual (W502)

2-187

2 Instruction Descriptions

Precautions for Correct Use

· Out can have a different data type than the multiplication result. However, the data type of Out must include the valid range of the data type of the multiplication result. Otherwise, a building error will occur. Refer to Data Type Ranking Table and Casting Rules in the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) or NY-series Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for the including relationship on data types.
· If an underflow or overflow occurs in multiplication, the calculation result may not be as expected. Allow sufficient leeway in the sizes of the data types for input and output parameters so that overflows and underflows do not occur.

· Multiplication results of positive or negative infinity are handled as follows for real number values.

Multiplication + times positive number + times negative number - times positive number - times negative number + times + - times - + times - + times 0 - times 0

Multiplication result + - - + + + - Nonnumeric data Nonnumeric data

· If any of the values of In1 to InN is nonnumeric data, the value of the multiplication result is nonnumeric data.

2-188

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

DIV (/)

2 Instruction Descriptions

DIV (/)

The DIV (/) instruction divides integers or real numbers.

Instruction DIV (/)

Name Division

FB/FUN FUN

Graphic expression

(@)DIV

EN ENO

In1

Out

In2

ST expression Out:=In1/ In2;

(@)/

2

EN ENO

In1

Out

In2

Variables

Name

Meaning

I/O

Description

Valid range

Unit

In1

Dividend

Dividend

Input

In2

Divisor

Divisor

Depends on data type. ---

Out

Output

Output

Output value

value

Depends on data type. ---

* If you omit an input parameter, the default value is not applied. A building error will occur.

Default *
---

Bit string

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In1

OK OK OK OK OK OK OK OK OK OK

In2

OK OK OK OK OK OK OK OK OK OK

Out

OK OK OK OK OK OK OK OK OK OK

Function
The DIV (/) instruction divides dividend In1 by divisor In2 and outputs the result to output value Out.
In1 and In2 can have different data types. However, use the combination that data types to include are existed. If they are different, calculations are performed with the data type that includes the range of all of the data types. For example, if In1 is INT data and In2 is DINT data, calculations are performed with DINT data. Here, the division result is DINT data. If In1 and In2 are integers and there is a remainder, the remainder is truncated. Refer to Data Type Ranking Table and Casting Rules in the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) or NY-series Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for the including relationship on data types.

NJ/NX-series Instructions Reference Manual (W502)

2-189

2 Instruction Descriptions

Data type that includes In1 and In2 Examples: If division is performed for INT data, then INT data is used. If division is performed for INT and DINT data, then DINT data is used.
If In1 and In2 are integers and there is a remainder, the remainder is truncated.

Division result

Assignment

In1

/ In2

=

Out

Processing for Overflows

An overflow occurs if the quotient of In1 and In2 exceeds the valid range of the data type of the division result. If an overflow occurs, the data types of In1 and In2, the data type of the division result, and the value of the division result will be as shown in the following table.

Data types of In1 and In2 At least one real number

Data type of division result
Real number data

Value of division result
±*

* If the quotient of In1 and In2 is positive, the division result will be positive infinity. If the quotient is negative, the division result will be negative infinity.

Notation Examples

The following example is for when In1 is INT#100 and In2 is INT#5. The value of INT variable abc will be INT#20.

LD

ST

abc:=INT#100/INT#5;

DIV

EN INT#100 In1
INT#5 In2

ENO abc

The DIV instruction divides In1 by InN. The calculation is 100/5 = 20, so the value of abc will be INT#20.

In1 INT#100 / In2 INT#5

Divided.

Out=abc INT#20

2-190

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Math Instructions

DIV (/)

Differences in Specifications between Ladder Diagrams and ST
Specifications of this instruction depend on whether it is used in a ladder diagram or ST. The following table gives the differences in specifications. In ladder diagrams, the specifications of the DIV instruction and the / instruction are exactly the same.

Item

Ladder diagram

ST

Existence of EN and ENO variables

Present

None

Number of data processing bits if the dividend and divisor are integer data 8, 16, 32, or 64*1 32 or 64*2

*1 The number of processing bits is aligned with the larger data type of the dividend and divisor. For example, if

you perform division for SINT and DINT data, the data processing bits will be aligned to the size of DINT data,

i.e., 32-bit processing is performed. *2 If there is no LINT or ULINT data in the dividend and divisor, 32-bit processing is used. For example, if you per-

2

form division for two SINT values, 32-bit processing is used. If there is LINT or ULINT data in the dividend and

divisor, 64-bit processing is used.

Additional Information
When you calculate real numbers, use the CheckReal instruction (page 2-237) to see if Out is positive infinity, negative infinity, or nonnumeric data.

Precautions for Correct Use

· Out can have a different data type than the division result. However, the data type of Out must include the valid range of the data type of the division result. Otherwise, a building error will occur. Refer to Data Type Ranking Table and Casting Rules in the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) or NY-series Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for the including relationship on data types.
· An error will not occur even if an underflow or overflow occurs in the division.
· If an underflow or overflow occurs in division, the calculation result may not be as expected. Allow sufficient leeway in the sizes of the data types for input and output parameters so that overflows and underflows do not occur.
· Division results of positive infinity, negative infinity, or 0 are handled as follows for real number values.

In1

+

Positive number

0

Negative number

-

+

Nonnu- 0 meric data

0

0

Nonnumeric data

Positive + number

Positive 0 number

Negative - number

In2

0

+

+

Nonnu- - meric data

-

Negative - number

Negative 0 number

Positive + number

-

Nonnu- 0 meric data

0

0

Nonnumeric data

· If the value of In1 or In2 is nonnumeric data, the value of the division result is nonnumeric data. · An error occurs in the following case. ENO will be FALSE, and Out will not change.
· In1 and In2 are integers and the value of In2 is 0.

NJ/NX-series Instructions Reference Manual (W502)

2-191

2 Instruction Descriptions

MOD

The MOD instruction finds the remainder for division of integers.

Instruction MOD

Name Modulo-division

FB/FUN FUN

Graphic expression

(@)MOD

EN ENO

In1

Out

In2

ST expression Out:=In1 MOD In2;

Variables

Name

Meaning

I/O

Description

Valid range

Unit

In1

Dividend

Dividend

Input

In2

Divisor

Divisor

Depends on data type. ---

Out

Remainder Output

Remainder

Depends on data type. ---

* If you omit an input parameter, the default value is not applied. A building error will occur.

Default *
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In1

OK OK OK OK OK OK OK OK

In2

OK OK OK OK OK OK OK OK

Out

OK OK OK OK OK OK OK OK

Function
The MOD instruction divides dividend In1 by divisor In2 to find the remainder.

The data types of In1, In2, and remainder Out can have different data types. However, use the combination that data types to include are existed.
Refer to Data Type Ranking Table and Casting Rules in the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) or NY-series Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for the including relationship on data types.

This instruction performs the calculation with the following formula.
Out = In1 - (In1/In2)* In2 (The decimal point is truncated in the division operation.) Examples of the values of In1, In2, and Out are given in the following table.

Value of In1

Value of In2

Value of Out

5

3

2

5

-3

2

-5

3

-2

-5

-3

-2

2-192

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

2 Instruction Descriptions

The following example is for when In1 is INT#18 and In2 is INT#5. The value of variable abc will be INT#3.

LD

ST

abc:=INT#18 MOD INT#5;

MOD

EN INT#18 In1
INT#5 In2

ENO abc

The MOD instruction divides In1 by In2 to find the remainder.

The remainder of 18/5 is 3, so the value of abc will be INT#3.

2

In1 INT#18

Remainder calculated.

/ In2 INT#5

Out=abc INT#3

Precautions for Correct Use
· Set the data type of Out to include the valid ranges of In1 and In2. Refer to Data Type Ranking Table and Casting Rules in the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) or NYseries Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for the including relationship on data types.

MOD

NJ/NX-series Instructions Reference Manual (W502)

2-193

2 Instruction Descriptions

ABS

The ABS instruction finds the absolute value of an integer or real number.

Instruction ABS

Name Absolute Value

FB/FUN FUN

Graphic expression

(@)ABS

EN ENO

In

Out

ST expression Out:=ABS(In);

Variables

Name

Meaning

I/O

Description

Valid range

Unit

In

Number to Input

Number to process

Depends on data type. ---

process

Out

Absolute Output

Absolute value

value

Depends on data type. --*2

*1 If you omit an input parameter, the default value is not applied. A building error will occur.

*2 Negative numbers are excluded.

Default *1
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In

OK OK OK OK OK OK OK OK OK OK

Out

OK OK OK OK OK OK OK OK OK OK

Function

The ABS instruction outputs the absolute value of the number to process In. The data types of In and absolute value Out can have different data types.
The following example is for when In is REAL#-10.3. The value of variable abc will be REAL#10.3.

LD

ST

abc:=ABS(REAL#-10.3);

ABS

EN ENO

REAL#-10.3 In

abc

The ABS instruction outputs the absolute value of In. The absolute value of REAL#-10.3 is found, so the value of abc will be REAL#10.3.

|-10.3| is taken.

In REAL#-10.3

Out=abc REAL#10.3

2-194

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

2 Instruction Descriptions

Additional Information
When you calculate real numbers, use the CheckReal instruction (page 2-237) to see if Out is positive infinity, negative infinity, or nonnumeric data.

Precautions for Correct Use

· Set the data type of Out to include the absolute value of In.

· If the value of In is positive infinity, negative infinity, or nonnumeric data, the value of Out is as shown

below. Value of In

Value of Out

2

+

+

-

+

Nonnumeric data Nonnumeric data

ABS

NJ/NX-series Instructions Reference Manual (W502)

2-195

2 Instruction Descriptions

RadToDeg and DegToRad

RadToDeg: DegToRad:

Converts a real number from radians (rad) to degrees (°). Converts a real number from degrees (°) to radians (rad).

Instruction RadToDeg

Name

FB/FUN

Radians to Degrees FUN

DegToRad

Degrees to Radians FUN

Graphic expression

(@)RadToDeg

EN

ENO

In

Out

(@)DegToRad

EN

ENO

In

Out

ST expression Out:=RadToDeg(In);
Out:=DegToRad(In);

Variables

Name

Meaning

I/O

Description

Valid range

Unit

In

Data to

Input

Data to convert

Depends on data type. · RadToDeg: Radians

convert

· DegToRad: Degrees

Out

Conversion Output Conversion result Depends on data type. · RadToDeg: Degrees

result

· DegToRad: Radians

* If you omit an input parameter, the default value is not applied. A building error will occur.

Default *
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In

OK OK

Out

OK OK

Function
 RadToDeg
The RadToDeg instruction converts the data to convert In from radians (rad) to degrees (°). The following conversion is used.
Out=In*180/
 DegToRad
The DegToRad instruction converts the data to convert In from degrees (°) to radians (rad). The following conversion is used.
Out=In*/180

2-196

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

RadToDeg and DegToRad

2 Instruction Descriptions

The following example for the DegToRad instruction is for when In is REAL#45. The value of the REAL variable abc will be REAL#0.785398.

LD

ST

abc:=DegToRad(REAL#45);

DegToRad

EN REAL#45 In

ENO abc

The DegToRad instruction converts the value of In from degrees (°) to radians (rad).

An angle of 45° is 0.785398 rad, so the value of abc will be REAL#0.785398.

2

Converted to radians.

In REAL#45

Out=abc REAL#0.785398

Additional Information
Use the CheckReal instruction (page 2-237) to see if Out is positive infinity, negative infinity, or nonnumeric data.

Precautions for Correct Use

· If the absolute value of the conversion result exceeds the maximum value of the data type of Out, the value of Out will be positive or negative infinity.
· If the absolute value of the conversion result is lower than the minimum value of the data type of Out, the value of Out will be 0.
· Make sure that the data type of Out is equal to or larger than the data type of In.
· If the value of In is positive infinity, negative infinity, or nonnumeric data, the value of Out is as shown below.

Value of In +

Value of Out +

-

-

Nonnumeric data Nonnumeric data

· If you pass an integer parameter to In, the data type is converted as follows:

Data type of parameter that is passed to In

Data type of In

USINT, UINT, SINT, or INT UDINT or DINT

REAL LREAL

ULINT or LINT

A building error will occur.

NJ/NX-series Instructions Reference Manual (W502)

2-197

2 Instruction Descriptions

SIN, COS, and TAN

These instructions perform trigonometric calculations on real numbers. SIN: Finds the sine of a number. COS: Finds the cosine of a number. TAN: Finds the tangent of a number.

Instruction SIN

Name Sine in Radians

FB/FUN FUN

COS

Cosine in Radians FUN

TAN

Tangent in Radians FUN

Graphic expression

(@)SIN

EN ENO

In

Out

(@)COS

EN ENO

In

Out

(@)TAN

EN ENO

In

Out

ST expression Out:=SIN(In);
Out:=COS(In);
Out:=TAN(In);

Variables

Name

Meaning

I/O

Description

Valid range

In

Number to Input

Number to process

Depends on data type.

process

Out

Calculation Output

Calculation result

result

· SIN*2
· COS*2
· TAN Depends on data type.

*1 If you omit an input parameter, the default value is not applied. A building error will occur.

*2 The valid range is -1.000000e+0 to 1.000000e+0 for REAL data. The valid range is -1.00000000000000e+0 to 1.00000000000000e+0 for LREAL data.

Unit Radians
---

Default *1
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In

OK OK

Out

OK OK

STRING

2-198

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

SIN, COS, and TAN

2 Instruction Descriptions
Function
These instructions perform trigonometric calculations on real numbers. Number to process In is an angle in radians (rad).
 SIN
The SIN instruction finds the sine of In.
Out 1
2
In
-1
 COS
The COS instruction finds the cosine of In.
Out 1
In
-1
 TAN
The TAN instruction finds the tangent of In.
Out

1

0

In

-1

NJ/NX-series Instructions Reference Manual (W502)

2-199

2 Instruction Descriptions

The following example for the COS instruction is for when In is REAL#3.141592. The value of variable abc will be REAL#-1.0.

LD

ST

abc:=COS(REAL#3.141592);

COS

EN ENO

REAL#3.141592 In

abc

The COS instruction finds the cosine of In. The cosine of 3.141592 is -1.0, so the value of abc will be REAL#-1.0.

In REAL#3.141592

Cosine found.

Out=abc REAL#-1.0

Additional Information
· Use the RadToDeg and DegToRad instructions (page 2-196) to convert between degrees and radians.
· If In for the TAN instruction is n/2, when n is an integer, then the value of Out will be positive or negative infinity. Use the CheckReal instruction (page 2-237) to see if the value of Out is positive infinity or negative infinity.

Precautions for Correct Use

· If the value of In is positive infinity, negative infinity, or nonnumeric data, the value of Out is nonnumeric data.
· If you pass an integer parameter to In, the data type is converted as follows:

Data type of parameter that is passed to In

Data type of In

USINT, UINT, SINT, or INT

REAL

UDINT or DINT

LREAL

ULINT or LINT

A building error will occur.

2-200

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

ASIN, ACOS, and ATAN

2 Instruction Descriptions

ASIN, ACOS, and ATAN

These instructions perform inverse trigonometric calculations on real numbers. ASIN: Finds the arc sine of a number. ACOS: Finds the arc cosine of a number. ATAN: Finds the arc tangent of a number.

Instruction

Name

FB/FUN

Graphic expression

ST expression

ASIN

Principal Arc Sine FUN

(@)ASIN

Out:=ASIN(In);

2

EN ENO

In

Out

ACOS

Principal Arc Cosine

FUN

(@)ACOS

EN ENO

In

Out

Out:=ACOS(In);

ATAN

Principal Arc Tangent

FUN

(@)ATAN

EN ENO

In

Out

Out:=ATAN(In);

Variables

Name In
Out

Meaning
Number to process
Calculation result

I/O Input
Output

Description Number to process
Calculation result

Valid range

Unit

Depends on data type. ---

· ASIN

rad

-/2 to /2

· ACOS

0 to 

· ATAN

-/2 to /2

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default *
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In

OK OK

Out

OK OK

Function
These instructions perform inverse trigonometric calculations on real numbers. The calculation result Out is an angle in radians (rad).
 ASIN
The ASIN instruction finds the arc sine of In. Out is between -/2 and /2.

NJ/NX-series Instructions Reference Manual (W502)

2-201

2 Instruction Descriptions

Out 2

-1.0

0

In 1.0

-2
 ACOS
The ACOS instruction finds the arc cosine of In. Out is between 0 and .
Out

2

In

-1.0

0

1.0

 ATAN
The ATAN instruction finds the arc tangent of In. Out is between -/2 and /2. If the value of In is positive infinity, the value of Out is /2. If the value of In is negative infinity, the value of Out is -/2.
Out

2

In 0

-2

2-202

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

2 Instruction Descriptions

The following example for the ACOS instruction is for when In is REAL#-1.0. The value of variable abc will be REAL#3.141592.

LD

ST

abc:=ACOS(REAL#-1.0);

ACOS

EN ENO

REAL#-1.0 In

abc

The ACOS instruction finds the arccosine of In.

The arccosine of -1.0 is 3.141592, so the value of abc will be REAL#3.141592.

2

Arccosine found.

In REAL#-1.0

Out=abc REAL#3.141592

Additional Information
Use the RadToDeg and DegToRad instructions (page 2-196) to convert between degrees and radians.

Precautions for Correct Use

· If In is not between -1.0 and 1.0 for the ASIN or ACOS instruction, the value of Out is nonnumeric data. That also applies when the value of In is negative infinity, positive infinity, or nonnumeric data.
· If the value of In is nonnumeric data for the ATAN instruction, the value of Out is nonnumeric data.
· If you pass an integer parameter to In, the data type is converted as follows:

Data type of parameter that is passed to In

Data type of In

USINT, UINT, SINT, or INT

REAL

UDINT or DINT

LREAL

ULINT or LINT

A building error will occur.

ASIN, ACOS, and ATAN

NJ/NX-series Instructions Reference Manual (W502)

2-203

2 Instruction Descriptions

SQRT

The SQRT instruction finds the square root of a number.

Instruction

Name

FB/FUN

Graphic expression

SQRT

Square Root

FUN

(@)SQRT

EN ENO

In

Out

ST expression Out:=SQRT(In);

Variables

Name

Meaning

I/O

Description

Valid range

Unit

In

Number to Input

Number to process

Depends on data type. ---

process

*1

Out

Square root Output

Square root

*3

---

*1 Negative numbers are excluded.

*2 If you omit an input parameter, the default value is not applied. A building error will occur.

*3 The valid range is 0.000000e+00 to 1.844674e+19 or positive infinity for REAL data. The valid range is 0.00000000000000e+000 to 1.34078079299425e+154 or positive infinity for LREAL data.

Default *2
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In

OK OK

Out

OK OK

Function
The SQRT instruction finds the square root of number to process In. The data types of In and square root Out can have different data types.
Out

2

1

01

4

In

2-204

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

SQRT

2 Instruction Descriptions

The following example is for when In is REAL#16.0. The value of variable abc will be REAL#4.0.

LD

ST

abc:=SQRT(REAL#16.0);

SQRT

EN ENO

REAL#16.0 In

abc

The SQRT instruction finds the square root of In. The square root of 16.0 is 4.0, so the value of abc will be REAL#4.0.

Square root is found.

2

In REAL#16.0

Out=abc REAL#4.0

Additional Information
Use the CheckReal instruction (page 2-237) to see if the value of Out is positive infinity.

Precautions for Correct Use

· If the value of In is not a positive number, the value of Out is as shown below.

Value of In

Value of Out

Negative number

Nonnumeric data

0 + - Nonnumeric data

0 + Nonnumeric data Nonnumeric data

· If you pass an integer parameter to In, the data type is converted as follows:

Data type of parameter that is passed to In
USINT, UINT, SINT, or INT
UDINT or DINT
ULINT or LINT

Data type of In
REAL LREAL A building error will occur.

NJ/NX-series Instructions Reference Manual (W502)

2-205

2 Instruction Descriptions

LN and LOG

These instructions find the logarithm of a real number.

LN:

Finds the natural logarithm of a number.

LOG: Finds the base-10 logarithm of a number.

Instruction LN

Name Natural Logarithm

FB/FUN FUN

LOG

Logarithm Base 10 FUN

Graphic expression

(@)LN

EN ENO

In

Out

(@)LOG

EN ENO

In

Out

ST expression Out:=LN(In);
Out:=LOG(In);

Variables

Name In
Out

Meaning
Number to process
Logarithm

I/O Input
Output

Description Number to process
Logarithm

Valid range

Unit

Depends on data type. --*1

*3

---

*1 Negative numbers are excluded.
*2 If you omit an input parameter, the default value is not applied. A building error will occur.
*3 LN: If In and Out are REAL data: -8.73365448e+1 to 8.87228390e+1, or -/+ If In is REAL and Out is LREAL data: -8.7336544750000000e+1 to 8.8722839050000000e+1 or -/+ If In is LREAL and Out is REAL data: -7.08384950e+2 to 7.09782712e+2 or -/+ If In and Out are LREAL data: -7.0838495021978327e+1 to 7.0978271289338399e+2 or -/+
LOG: If In and Out are REAL data: -3.79297795e+1 to 3.85318394e+1 or -/+ If In is REAL and Out is LREAL data: -3.7929779453965430e+1 to 3.8531839419564961e+1 or -/+ If In is LREAL and Out is REAL data: -3.07652656e+2 to 3.08254716e+2 or -/+ If In and Out are LREAL data: -3.0765265556858878e+2 to 3.0825471555991674e+2 or -/+

Default *2
---

Bit string

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In

OK OK

Out

OK OK

STRING

2-206

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

2 Instruction Descriptions
Function
These instructions find the logarithm of a real number.
 LN
The LN instruction finds the natural logarithm (logarithm to base e, where e = 2.718282).
Out
2
1 In
0 1 2.718282

LN and LOG

 LOG
The LOG instruction finds the base-10 logarithm.
Out

1

In

01

10

The following example for the LOG instruction is for when In is REAL#1000.0. The value of variable abc will be REAL#3.0.

LD

ST

abc:=LOG(REAL#1000.0);

LOG

EN ENO

REAL#1000.0 In

abc

NJ/NX-series Instructions Reference Manual (W502)

2-207

2 Instruction Descriptions

The LOG instruction finds the base-10 logarithm of a real number. The base-10 logarithm of 1,000.0 is 3.0 so the value of abc will be REAL#3.0.

Common logarithm is taken.

In REAL#1000.0

Out=abc REAL#3.0

Additional Information
Use the CheckReal instruction (page 2-237) to see if Out is positive infinity, negative infinity, or nonnumeric data.

Precautions for Correct Use

· If the value of In is not a positive number, the value of Out is as shown below.

Value of In Negative number

Value of Out Nonnumeric data

0 + - Nonnumeric data

- + Nonnumeric data Nonnumeric data

· If you pass an integer parameter to In, the data type is converted as follows:

Data type of parameter that is passed to In
USINT, UINT, SINT, or INT UDINT or DINT ULINT or LINT

Data type of In
REAL LREAL A building error will occur.

2-208

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

EXP

2 Instruction Descriptions

EXP

The EXP instruction performs calculations for the natural exponential function.

Instruction EXP

Name
Natural Exponential Operation

FB/FUN FUN

Graphic expression

(@)EXP

EN ENO

In

Out

ST expression Out:=EXP(In);

Variables

2

Name In Out

Meaning
Exponent
Calculation result

I/O Input Output

Description Exponent Calculation result

Valid range
Depends on data type.
Depends on data type. *2

*1 If you omit an input parameter, the default value is not applied. A building error will occur. *2 Negative numbers are excluded.

Unit -----

Default *1 ---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In

OK OK

Out

OK OK

Function
The EXP instruction returns the value of eIn, where e is Euler's constant and In is an input variable.
Out

2.718282

1

01

In

NJ/NX-series Instructions Reference Manual (W502)

2-209

2 Instruction Descriptions

The following example is for when In is REAL#1.0. The value of variable abc will be REAL#2.718282.

LD

ST

abc:=EXP(REAL#1.0);

EXP

EN ENO

REAL#1.0 In

abc

The EXP instruction returns the natural logarithm of In to the base e. The value of e1 is 2.718282, so the value of abc will be REAL#2.718282.

e is taken to the Inth power

In REAL#1

Out=abc REAL#2.718282

Additional Information
· Use the EXPT (**) instruction (page 2-211) to find the powers of numbers with bases other than e. · Use the CheckReal instruction (page 2-237) to see if Out is positive infinity, negative infinity, or non-
numeric data.

Precautions for Correct Use

· If the value of In is 0.0, positive infinity, negative infinity, or nonnumeric data, the value of Out is as shown below.

Value of In
0 + - Nonnumeric data

Value of Out

Other than the right

NX1P2

1.0

1.0

Nonnumeric data

+

Nonnumeric data

0.0

Nonnumeric data

Nonnumeric data

· If you pass an integer parameter to In, the data type is converted as follows:

Data type of parameter that is passed to In

Data type of In

USINT, UINT, SINT, or INT UDINT or DINT

REAL LREAL

ULINT or LINT

A building error will occur.

2-210

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

EXPT (**)

2 Instruction Descriptions

EXPT (**)

The EXPT (**) instruction raises one real number to the power of another real number.

Instruction EXPT (**)

Name Exponentiation

FB/FUN FUN

Graphic expression

(@)EXPT

EN ENO

In

Out

Pwr

ST expression
Out:=EXPT(In, Pwr); Out:=In ** Pwr;

(@)**

2

EN ENO

In

Out

Pwr

Variables

Name

Meaning

I/O

Description

Valid range

Unit

In

Base

Base number

number

(e.g., 5 for 52)

Input

Pwr

Exponent

Exponent

(e.g., 2 for 52)

Depends on data type. ---

Out

Calculation Output

Calculation result

result

Depends on data type. ---

* If you omit an input parameter, the default value is not applied. A building error will occur.

The Instruction of LD and the EXPT Instruction in ST

Default *
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In

OK OK

Pwr

OK OK

Out

OK OK

NJ/NX-series Instructions Reference Manual (W502)

2-211

2 Instruction Descriptions

The ** Operator in ST
Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In

OK OK OK OK OK OK OK OK OK OK

Pwr

OK OK OK OK OK OK OK OK OK OK

Out

OK OK OK OK OK OK OK OK OK OK

Function

The EXPT (**) instruction raises base number In to exponent Pwr to find InPwr.
The following example is for when In is REAL#10.0 and Pwr is REAL#3.0. The value of variable abc will be REAL#1000.0.

LD

ST

EXPT

EN ENO

REAL#10.0 In

abc

REAL#3.0 Pwr

abc:=EXPT(REAL#10.0, REAL#3.0);

The ACOS instruction finds In to the power of Pwr. 10.03.0 is 1,000.0, so the value of abc will be REAL#1000.0.

In REAL#10.0 In to the power of Pwr (10.03.0) is found. Out=abc REAL#1000.0
Pwr REAL#3.0

Difference in Specifications between Ladder Diagrams and ST
Specifications of this instruction depend on whether it is used in a ladder diagram or the ** operator is used in ST. The following table gives the differences in specifications. The specifications of the EXPT instruction and the ** instruction of ladder diagrams and the EXPT function of ST are exactly the same.

Item
Existence of the EN and EN0 variables Number of data processing bits if In and Pwr are integer data

EXPT functions in ladder diagrams and ST
Present 32 or 64 *1

** operator in ST
None 64*2

*1. Operation is performed with the smaller real number included, from either REAL or LREAL data. For example, if you operate SINT and DINT data, the data processing bits will be aligned to the size of LREAL data, i.e., 64bit processing is performed.
*2. 64-bit processing is performed. For example, if two SINT values are exponentiated, 64-bit processing is performed.

2-212

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

EXPT (**)

2 Instruction Descriptions

Additional Information
· Use the EXP instruction (page 2-209) to find powers of base e. · Use the CheckReal instruction (page 2-237) to see if Out is positive infinity, negative infinity, or non-
numeric data.

Precautions for Correct Use

· If the absolute value of the calculation result is lower than the minimum value for a real number, the

value of Out will be 0.

Example: (1.175494e-38)2  0

2

· An error will not occur even if an underflow or overflow occurs in the calculation when the ** operator

is used.

· If an underflow or overflow occurs in the calculation when the ** operator is used, the calculation

result may not be as expected. Allow sufficient leeway in the sizes of the data types for input and

output parameters so that overflows and underflows do not occur.

· For the EXPT instruction and ** instruction of ladder diagrams and the EXPT function of ST, if you

pass an integer parameter to In, the data type is converted as follows:

Data type of parameter that is passed to In

Data type of In

USINT, UINT, SINT, or INT

REAL

UDINT or DINT ULINT or LINT

LREAL A building error will occur.

· When the ** operator is used, if you select the version 1.15 or earlier in the Select Device Area of the Project Properties Dialog Box on the Sysmac Studio for an NX701 CPU Unit, NJ-series CPU Unit and NY-series Controller, integer variables are calculated as real number variables even if they set as operands. If a rounding error is included in the result of calculations, the result may not be an intended value because all values after the decimal point are truncated. Use the EXPT and TO_** (Integer Conversion Group) instructions together to round values after the decimal point. Example) TO_INT (EXPT(X,Y))

NJ/NX-series Instructions Reference Manual (W502)

2-213

2 Instruction Descriptions

Combination of In and Pwr values
The following table shows the values of Out for different combinations of In and Pwr values.
 The EXPT Function for a Device Other Than the NX1P2 CPU Unit

In

+

1 to +

Non-

1

0 to 1

0 -1 to 0 -1

-1 to -

-

nume ric

data

+

+

Positive even number

Positive odd number

+

Positive decimal number

+

1

Numb er*1*2

1

0

1

Numb er*1*2

0

0

1

+

1

Numb er*1*2

1

Numb er*2*3

-1

Numb er*1*2

Numb er*2*3

+

Nonnumeric data

Nonnu meric data
Nonnu meric data

0

1

1

1

1

1

1

Negative even

Pwr

number

Negative odd number

0

Negative decimal number

Numb er*1*2

1

Numb er*1*2

+

Numb er*1*2

1

Numb er*2*3

-1

Numb er*1*2

Numb er*2*3

0

Nonnumeric data

Nonnu meric data

Nonnu

-

0

0

1

+

+

+

1

0

0

meric

data

Nonnumeric data

1

Nonnu meric 1 data

Nonnu meric 1 data

Nonnumeric data

Nonnu

1

meric data

1

*1. If the calculation result exceeds the valid range of the data type of Out, the value of Out will be positive infinity. *2. If the calculation result is too close to 0 to express with the data type of Out or if it is an unnormalized number,
the value of Out will be 0. *3. If the calculation result exceeds the valid range of the data type of Out, the value of Out will be negative infinity.

2-214

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

EXPT (**)

2 Instruction Descriptions

 The EXPT Function for the NX1P2 CPU Unit

In

+

1 to +

Non-

1

0 to 1

0 -1 to 0 -1

-1 to -

-

nume ric

data

+

+

Positive even number

Positive odd number

+

Positive decimal number

+

1

Numb er*1*2

1

0

1

Numb er*1*2

0

0

1

Numb er*1*2

1

Numb er*2*3

-1

+

1

Nonnu meric data

Numb er*1*2

+

Numb er*2*3

-

Nonnu meric data

2

Nonnumeric data

+

0

1

1

1

1

1

1

Negative even

Pwr

number

Negative odd number

0

Negative decimal number

Numb er*1*2

1

Numb er*1*2

+

Numb er*1*2

1

Numb er*2*3

-1

Numb er*1*2

0

Numb er*2*3

-0

Nonnumeric data

0

Nonnu meric data

Nonnu

-

0

0

1

+

+

+

1

0

0

meric

data

Nonnumeric data

1

Nonnu meric 1 data

Nonnu meric 1 data

Nonnumeric data

Nonnu

1

meric data

1

*1. If the calculation result exceeds the valid range of the data type of Out, the value of Out will be positive infinity. *2. If the calculation result is too close to 0 to express with the data type of Out or if it is an unnormalized number,
the value of Out will be 0. *3. If the calculation result exceeds the valid range of the data type of Out, the value of Out will be negative infinity.

NJ/NX-series Instructions Reference Manual (W502)

2-215

2 Instruction Descriptions

 The ** Operator

+

1 to +

1

+

+

Positive even number

Positive odd number

+

+

1

Numbe r*1*2*3

1

In 0 to 1 0 -1 to 0 -1

0

1

Numb er*1*2

0

0

1

Numb er*1*2

1

Numb er*2*4

-1

-1 to -

-

+

1

Numbe r*1*2*3

+

Numb er*2*3 - *4

Nonnume
ric data Nonnu meric data
Nonnu meric data

Positive decimal number

0

1

Pwr Negative even number

Negative odd number

0

Negative decimal number

-

0

Nonnumeric data

1

1

Numb er*1*2

1

0

1

1

Numb er*1*2

+*5

Nonnumeric data

+

1

Numb er*1*2

1

Numb er*2*4

-1

1

Numb er*1*2

0

Numb er*2*4

-0

Nonnumeric data

0

+

+

+

1

0

0

Nonnumeric data

1

Nonnumeric data

1

1
Nonnu meric data
Nonnu meric data Nonnu meric data 1

*1. If the calculation result exceeds the valid range of the data type of Out, the value of Out will be positive infinity. *2. If the calculation result is too close to 0 to express with the data type of Out or if it is an unnormalized number,
the value of Out will be 0. *3. When both In and Pwr are integer data, if the calculation result exceeds the valid range of the data type of Out,
Out will contain an undefined value. *4. If the calculation result exceeds the valid range of the data type of Out, the value of Out will be negative infinity. *5. When both In and Pwr are integer data, Out will contain an undefined value.

2-216

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

Inc and Dec

2 Instruction Descriptions

Inc and Dec

Inc: Dec:
Instruction Inc

Increments an integer value. Decrements an integer value.

Name Increment

FB/FUN FUN

Dec

Decrement

FUN

Graphic expression

ST expression

(@)Inc

Inc(InOut);

EN ENO

InOut

2

Out

(@)Dec
EN ENO InOut

Dec(InOut);

Out

Variables

Name InOut Out

Meaning
Target data
Return value

I/O In-out Output

Description Target data Always TRUE

Valid range

Unit

Depends on data type. ---

TRUE only

---

Default
-----

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

InOut

Out

OK

OK OK OK OK OK OK OK OK

Function
 Inc
The Inc instruction increments target data InOut. If the result exceeds the maximum value of InOut, InOut returns to the minimum value.
 Dec
The Dec instruction decrements target data InOut. If the result exceeds the minimum value of InOut, InOut returns to the maximum value.

NJ/NX-series Instructions Reference Manual (W502)

2-217

2 Instruction Descriptions

The following example for the Inc instruction is for when variable abc is passed to InOut. If the value of abc is INT#4, the value of abc after the instruction is executed will be INT#5.

LD

ST

Inc(abc);

Inc

EN ENO

InOut

abc

abc

The Inc instruction increments InOut. If the value of abc is INT#4, the value of abc after the instruction is executed will be INT#5.

InOut=abc INT#4

Incremented.

InOut=abc INT#5

Precautions for Correct Use
Return value Out is not used when the instruction is used in ST.

2-218

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

2 Instruction Descriptions

Rand

The Rand instruction generates pseudorandom numbers.

Instruction Rand

Name Random Number

FB/FUN FB

Graphic expression
Rand_instance
Rand Execute ENO Seed Rnd

ST expression
Rand_instance(Execute, Seed, Rnd);

2

Variables

Name

Meaning

I/O

Description

Valid range

Unit

Default

Seed

Random

Input

Random number pattern

Depends on data type. ---

*1

number pattern

0: Not specified

Rnd

Random

Output Random number

*2

number

---

---

*1 If you omit the input parameter, the value will be 0. It will not be the value that is specified for the Initial Value attribute.

*2 0.00000000000000e+0 to 1.00000000000000e+0

Bit strings

Integers

Real

Times, durations, dates, and text strings

Rand

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

Seed Rnd

OK OK

Function

The Rand instruction specifies random number Rnd. The value of Rnd is different each time the instruction is executed: Random number pattern Seed specifies the random number system. If the value of Seed is the same, the same random number series is generated each time the power supply is turned ON. This allows you to generate a repeatable series of random numbers.
If the value of Seed is 0, random numbers that cannot be repeated are generated. If you do not want to generate the same series of random numbers each time the power supply is turned ON, set the value of Seed to 0.
The following programming example is for when Seed is UINT#1. The value of Seed is not 0, so random numbers that can be repeated are generated.

LD

ST

Rand_instance

A

Rand

Execute ENO UINT#1 Seed Rnd abc

Rand_instance(A, UINT#1, abc);

NJ/NX-series Instructions Reference Manual (W502)

2-219

2 Instruction Descriptions

The Rand instruction generates a repeatable series of random numbers. Power ON

1st execution: Rnd = abc LREAL#0.12 2nd execution: Rnd = abc LREAL#0.34 3rd execution: Rnd = abc LREAL#0.56

Power supply turned OFF and ON again.

The same random numbers are generated each time the power supply is turned ON.

1st execution: Rnd = abc LREAL#0.12 2nd execution: Rnd = abc LREAL#0.34 3rd execution: Rnd = abc LREAL#0.56
* The values of the random numbers that are given above are examples. The actual values will be different.
Additional Information
The value of Rnd is a real number between 0 and 1. Use the following processing to generate random numbers within a specific range.
Example: The following formula generates random numbers between 100 and 200. Rand_instance(A, UINT#1, abc); Random number:=LREAL_TO_INT((200.0-100.0)*abc)+100;

2-220

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

AryAdd

2 Instruction Descriptions

AryAdd

The AryAdd instruction adds corresponding elements of two arrays.

Instruction AryAdd

Name Array Addition

FB/FUN FUN

Graphic expression

ST expression

(@)AryAdd

EN

ENO

AryAdd(In1, In2, Size, AryOut);

In1

Out

In2

Size

AryOut

2

Variables

Name

Meaning

I/O

Description

Valid range

Unit

In1[] (array) and In2[] (array)
Size

Array to process
Number of elements to process

Input

Array to process
Depends on data type. --Number of elements to process

AryOut[] (array)

Calculation In-out results array

Calculation results array

Depends on data type. ---

Out

Return

Output

Always TRUE

value

TRUE only

---

* If you omit an input parameter, the default value is not applied. A building error will occur.

Default *
1
---
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In1[] (array)

In2[] (array)

Size

AryOut[] (array)

Out

OK

OK OK OK OK OK OK OK OK OK OK Must be an array with the same data type as In1[]. OK Must be an array with the same data type as In1[].

Function
The AryAdd instruction adds Size elements of arrays to process In1[] and In2[] starting from In1[0] and In2[0]. The results are assigned to corresponding elements of calculation results array AryOut[].

NJ/NX-series Instructions Reference Manual (W502)

2-221

2 Instruction Descriptions

The following example is for when Size is UINT#3.

LD

ST

AryAdd(abc[1], def[2], UINT#3, ghi[3]);

abc[1] def[2] UINT#3
ghi[3]

AryAdd

EN

ENO

In1

In2

Size

AryOut

ghi[3]

Size=UINT#3

In1[0]=abc[1] In1[1]=abc[2] In1[2]=abc[3]

1234 + In2[0]=def[2] 2345 + In2[1]=def[3] 3456 + In2[2]=def[4]

2345 3456 4567

AryOut[0]=ghi[3] AryOut[1]=ghi[4] AryOut[2]=ghi[5]

3579 5801 8023

Precautions for Correct Use
· Use the same data type for In1[], In2[], and AryOut[]. If they are different, a building error will occur. · If the calculation results exceed the valid range of AryOut[], the results will be illegal values. An error
will not occur. Corruption will not occur in the data in the memory area adjacent to those elements. · The values in AryOut[] do not change if the value of Size is 0. · Return value Out is not used when the instruction is used in ST. · An error occurs in the following cases. ENO will be FALSE, and AryOut[] will not change.
· The value of Size exceeds the array range of In1[], In2p[], or AryOut[].

2-222

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

AryAddV

2 Instruction Descriptions

AryAddV

The AryAddV instruction adds the same value to specified elements of an array.

Instruction AryAddV

Name
Array Value Addition

FB/FUN FUN

Graphic expression

ST expression

(@)AryAddV

EN

ENO

AryAddV(In1, In2, Size, AryOut);

In1

Out

In2

Size

AryOut

2

Variables

Name

Meaning

I/O

Description

Valid range

Unit

In1[] (array) Addition array

Addition array

In2

Value to add

Input

Value to add

Depends on data type. ---

Size

Number of

elements

Number of elements of In1[] for addition

AryOut[] (array)

Addition results array

In-out

Addition results array

Depends on data type. ---

Out

Return

Output

Always TRUE

value

TRUE only

---

* If you omit an input parameter, the default value is not applied. A building error will occur.

Default * 1
-----

Bit string

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In1[] (array)

In2

Size

AryOut[] (array)

Out

OK

OK OK OK OK OK OK OK OK OK OK Must be same data type as In1[].
OK Must be same data type as In1[].

Function
The AryAddV instruction adds value to add In2 to Size elements of addition array In1[] starting from In1[0]. It outputs the results to addition results array AryOut[].

NJ/NX-series Instructions Reference Manual (W502)

2-223

2 Instruction Descriptions

The following example is for when In2 is INT#11 and Size is UINT#3.

LD

ST

AryAddV(abc[1], INT#11, UINT#3, def[2]);

abc[1] INT#11 UINT#3
def[2]

AryAddV

EN

ENO

In1

In2

Size

AryOut

def[2]

In1[0]=abc[1] Size=UINT#3 In1[1]=abc[2]
In1[2]=abc[3]

12 + 23 + 34 +

In2=INT#11 In2=INT#11 In2=INT#11

AryOut[0]=def[2]

23

AryOut[1]=def[3]

34

AryOut[2]=def[4]

45

Precautions for Correct Use
· Use the same data type for In1[], In2, and AryOut[]. If they are different, a building error will occur. · If the addition results exceed the valid range of AryOut[], the elements of AryOut[] will contain illegal
values. An error will not occur. Corruption will not occur in the data in the memory area adjacent to those elements. · The values in AryOut[] do not change if the value of Size is 0. · Return value Out is not used when the instruction is used in ST. · An error occurs in the following cases. ENO will be FALSE, and AryOut[] will not change. · If the value of Size exceeds the array area of In1[] or AryOut[].

2-224

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

ArySub

2 Instruction Descriptions

ArySub

The ArySub instruction subtracts corresponding elements of two arrays.

Instruction ArySub

Name Array Subtraction

FB/FUN FUN

Graphic expression

ST expression

(@)ArySub

EN

ENO

ArySub(In1, In2, Size, AryOut);

In1

Out

In2

Size

AryOut

2

Variables

Name

Meaning

I/O

Description

Valid range

Unit

In1[] (array) Minuend array

Minuend array

In2[] (array)

Subtrahend array

Input

Subtrahend array

Depends on data type. ---

Size

Number of

elements

Number of elements for subtraction

AryOut[] (array)

Subtraction In-out results array

Subtraction results array

Depends on data type. ---

Out

Return

Output

Always TRUE

value

TRUE only

---

* If you omit an input parameter, the default value is not applied. A building error will occur.

Default * 1
-----

Bit string

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In1[] (array)

In2[] (array)

Size

AryOut[] (array)

Out

OK

OK OK OK OK OK OK OK OK OK OK Must be same data type as In1[].
OK Must be same data type as In1[].

Function
The ArySub instruction subtracts Size elements of subtrahend array In2[] from corresponding elements of minuend array In1[] starting with In1[0] and In2[0]. It outputs the subtraction results to subtraction results array AryOut[].

NJ/NX-series Instructions Reference Manual (W502)

2-225

2 Instruction Descriptions

The following example is for when Size is UINT#3.

LD

ST

ArySub(abc[1], def[2], UINT#3, ghi[3]);

abc[1] def[2] UINT#3
ghi[3]

ArySub

EN In1 In2 Size AryOut

ENO

ghi[3]

In1[0]=abc[1] 12 - In2[0]=def[2]

1

Size=UINT#3 In1[1]=abc[2] 23 - In2[1]=def[3]

2

In1[2]=abc[3] 34 - In2[2]=def[4]

3

AryOut[0]=ghi[3] 11 AryOut[1]=ghi[4] 21 AryOut[2]=ghi[5] 31

Precautions for Correct Use
· Use the same data type for In1[], In2[], and AryOut[]. If they are different, a building error will occur. · If the subtraction results exceed the valid range of AryOut[], the elements of AryOut[] will contain ille-
gal values. An error will not occur. Corruption will not occur in the data in the memory area adjacent to those elements. · The values in AryOut[] do not change if the value of Size is 0. · Return value Out is not used when the instruction is used in ST. · An error occurs in the following cases. ENO will be FALSE, and AryOut[] will not change. · The value of Size exceeds the array range of In1[], In2[], or AryOut[].

2-226

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

ArySubV

2 Instruction Descriptions

ArySubV

The ArySubV instruction subtracts the same value from specified elements of an array.

Instruction ArySubV

Name
Array Value Subtraction

FB/FUN FUN

Graphic expression

ST expression

(@)ArySubV

EN

ENO

ArySubV(In1, In2, Size, AryOut);

In1

Out

In2

Size

AryOut

2

Variables

Name

Meaning

I/O

Description

Valid range

Unit

In1[] (array) Minuend array

Minuend array

In2

Subtrahend Input

Subtrahend

Depends on data type. ---

Size

Number of

elements

Number of elements of In1[] for subtraction

AryOut[] (array)

Subtraction In-out results array

Subtraction results array

Depends on data type. ---

Out

Return

Output

Always TRUE

value

TRUE only

---

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default * 1
---
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In1[] (array)

In2

Size

AryOut[] (array)

Out

OK

OK OK OK OK OK OK OK OK OK OK Must be same data type as the elements of In1[]. OK Must be same data type as In1[].

Function
The ArySubV instruction subtracts subtrahend In2 from Size elements of minuend array In1[] starting from In1[0]. It outputs the results to subtraction results array AryOut[].

NJ/NX-series Instructions Reference Manual (W502)

2-227

2 Instruction Descriptions

The following example is for when In2 is INT#11 and Size is UINT#3.

LD

ST

ArySubV(abc[1], INT#11, UINT#3, def[2]);

abc[1] INT#11 UINT#3
def[2]

ArySubV

EN

ENO

In1

In2

Size

AryOut

def[2]

Size=UINT#3

In1[0]=abc[1] In1[1]=abc[2] In1[2]=abc[3]

22 33 44 -

In2=INT#11 In2=INT#11 In2=INT#11

AryOut[0]=def[2] 11 AryOut[1]=def[3] 22 AryOut[2]=def[4] 33

Precautions for Correct Use
· Use the same data type for In1[], In2, and AryOut[]. If they are different, a building error will occur. · If the subtraction results exceed the valid range of AryOut[], the elements of AryOut[] will contain ille-
gal values. An error will not occur. Corruption will not occur in the data in the memory area adjacent to those elements. · The values in AryOut[] do not change if the value of Size is 0. · Return value Out is not used when the instruction is used in ST. · An error occurs in the following cases. ENO will be FALSE, and AryOut[] will not change. · The value of Size exceeds the array area of In1[] or AryOut[].

2-228

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

2 Instruction Descriptions

AryMean

The AryMean instruction calculates the average of the elements of an array.

Instruction AryMean

Name Array Mean

FB/FUN FUN

Graphic expression

(@)AryMean

EN

ENO

In

Out

Size

ST expression Out := AryMean(In, Size);

2 Variables

Name

Meaning

I/O

Description

Valid range

Unit

In[] (array) Size

Array to process
Number of elements to process

Input

Array to process Number of In[] elements

Depends on data type. ---

Out

Calculation Output

Calculation result

result

Depends on data type. ---

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default * 1
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

AryMean

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In[] (array) Size Out

OK OK OK OK OK OK OK OK OK OK OK OK
OK OK OK OK OK OK OK OK OK OK OK

Function

The AryMean instruction calculates the average of Size elements of array to process In[] starting from In[0].
The following example is for when Size is UINT#5.

LD

ST

def:=AryMean(abc[1], UINT#5);

AryMean

EN abc[1] In

ENO def

UINT#5 Size

Size=UINT#5

In[0]=abc[1] In[1]=abc[2] In[2]=abc[3] In[3]=abc[4] In[4]=abc[5]

1234 2345 3456 4567 5678

Average calculated. Out=def 3456

NJ/NX-series Instructions Reference Manual (W502)

2-229

2 Instruction Descriptions
Precautions for Correct Use
· Refer to the descriptions of the functions of the ADD (+) instruction (page 2-166), SUB (-) instruction (page 2-174), MUL (*) instruction (page 2-181), and DIV (/) instruction (page 2-189) for the calculation results when the value of In[] is positive infinity, negative infinity, or nonnumeric data.
· If In[] or Out is an integer, the decimal portion of the average is truncated. · If you use a different data type for In[] and Out, make sure the valid range of Out includes the valid
range of In[]. · If the calculation result exceeds the valid range of Out, Out will contain an illegal value. An error will
not occur. · If an intermediate value in the calculation process exceeds the valid range of IN[], Out will contain an
illegal value. An error will not occur. · If the value of Size is 0, the value of Out is 0. · An error occurs in the following case. ENO will be FALSE, and Out will not change.
· The value of Size exceeds the array area of In[].

2-230

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

ArySD

2 Instruction Descriptions

ArySD

The ArySD instruction calculates standard deviation of the elements of an array.

Instruction ArySD

Name
Array Element Standard Deviation

FB/FUN FUN

Graphic expression

(@)ArySD

EN ENO

In

Out

Size

ST expression Out:=ArySD(In, Size);

2

Variables

Name

Meaning

I/O

Description

Valid range

Unit

In[] (array) Size

Array to process
Number of elements

Input

Array to process
Number of elements of In[] for conversion

Depends on data type. ---

Out

Standard Output

Standard deviation

deviation

Depends on data type. ---

* If you omit an input parameter, the default value is not applied. A building error will occur.

Default *
2
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In[] (array) Size Out

OK OK OK
OK OK

Function

The ArySD instruction calculates the standard deviation of Size elements of array to process In[] starting from In[0].

Standard deviation =

(In[i]-InM) 2
i
Size-1

i: Subscript of In[], 0 to Size - 1 InM: Average value of In[0] to In[Size - 1]

NJ/NX-series Instructions Reference Manual (W502)

2-231

2 Instruction Descriptions

The following example is for when Size is UINT#5.

LD

ST

def:=ArySD(abc[1], UINT#5);

ArySD

EN abc[1] In

ENO def

UINT#5 Size

Size=UINT#5

In[0]=abc[1] In[1]=abc[2] In[2]=abc[3] In[3]=abc[4] In[4]=abc[5]

123.4

234.5 345.6

Standard

deviation

calculated.

Out=def

175.6645

456.7

567.8

Precautions for Correct Use
· If the value of Size is 0 or 1, the value of Out is 0. · If an intermediate value in the calculation process exceeds the valid range of IN[], Out will contain an
illegal value. An error will not occur. · An error occurs in the following case. ENO will be FALSE, and Out will not change.
· The value of Size exceeds the array area of In[].

2-232

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

2 Instruction Descriptions

ModReal

The ModReal instruction calculates the remainder of real number division.

Instruction ModReal

Name
Real Number Modulo-division

FB/FUN FUN

Graphic expression

(@)ModReal

EN

ENO

In1

Out

In2

ST expression Out:=ModReal(In1, In2);

2

Variables

Name In1 In2 Out

Meaning Dividend Divisor Remainder

I/O Input Output

Description Dividend Divisor Remainder

Valid range

Unit

Depends on data type. ---

Depends on data type. ---

* If you omit an input parameter, the default value is not applied. A building error will occur.

Default *
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

ModReal

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In1

OK OK

In2

OK OK

Out

OK OK

Function

The ModReal instruction divides dividend In1 by divisor In2 to find the remainder.
The following example is for when In1 is REAL#-9.9 and In2 is REAL#-3.14. The value of variable abc will be REAL#-0.48.

LD

ST

abc:=ModReal(REAL#-9.9, REAL#-3.14);

ModReal

EN ENO

REAL#-9.9 In1

abc

REAL#-3.14 In2

The ModReal instruction divides In1 by In2 to find the remainder. The remainder of -9.9/(-3.14) is -0.48, so the value of abc will be REAL#-0.48.

Remainder calculated.

In1 REAL#-9.9 / In2 REAL#-3.14

Out=abc REAL#-0.48

NJ/NX-series Instructions Reference Manual (W502)

2-233

2 Instruction Descriptions

Additional Information
Use the CheckReal instruction (page 2-237) to see if the value of Out is positive infinity, negative infinity, or nonnumeric data.

Precautions for Correct Use

· The following table shows the values of Out for different combinations of In1 and In2 values.

In1

0

Number

+

-

Nonnumeric data

0

Nonnumeric data

Nonnumeric data

Nonnumeric data

Nonnumeric data

Nonnumeric data

Number

0

Remainder of Nonnumeric

In1/In2

data

Nonnumeric data

Nonnumeric data

In2

+

0

Value of In1

Nonnumeric data

Nonnumeric data

Nonnumeric data

-

0

Value of In1

Nonnumeric data

Nonnumeric data

Nonnumeric data

Nonnumeric Nonnumeric

data

data

Nonnumeric data

Nonnumeric data

Nonnumeric data

Nonnumeric data

· If you pass an integer parameter to In1 or In2, the data type is converted as follows:

Data type of parameter that is passed to In1 or In2

Data type of In1 or In2

USINT, UINT, SINT, or INT

REAL

UDINT or DINT ULINT or LINT

LREAL A building error will occur.

2-234

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

Fraction

2 Instruction Descriptions

Fraction

The Fraction instruction finds the fractional part of a real number.

Instruction Fraction

Name
Real Number Fraction

FB/FUN FUN

Graphic expression

(@)Fraction

EN ENO

In

Out

ST expression Out:=Fraction(In);

Variables

2

Name

Meaning

I/O

Description

Valid range

Unit

In

Real

Input

Real number

number

Depends on data type. ---

Out

Fractional Output

Fractional part

part

Depends on data type. ---

* If you omit an input parameter, the default value is not applied. A building error will occur.

Default *
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In

OK OK

Out

OK OK

Function

The Fraction instruction finds the fractional part of real number In.
The following example is for when In is REAL#-123.456. The value of variable abc will be REAL#-0.456.

LD

ST

abc:=Fraction(REAL#-123.456);

Fraction

EN ENO

REAL#-123.456 In

abc

The Fraction instruction finds the fractional part of In. The fractional part of -123.456 is -0.456, so the value of abc will be REAL#0.456.

Fractional part extracted.

In REAL#-123.456

Out=abc REAL#-0.456

NJ/NX-series Instructions Reference Manual (W502)

2-235

2 Instruction Descriptions

Additional Information

· Use the CheckReal instruction (page 2-237) to see if the value of Out is positive infinity, negative infinity, or nonnumeric data.

· If you pass an integer parameter to In, the data type is converted as follows:

Data type of parameter that is passed to In
USINT, UINT, SINT, or INT UDINT or DINT ULINT or LINT

Data type of In
REAL LREAL A building error will occur.

2-236

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

CheckReal

2 Instruction Descriptions

CheckReal

The CheckReal instruction checks a real number to see if it is infinity or nonnumeric data.

Instruction CheckReal

Name
Real Number Check

FB/FUN FUN

Graphic expression

ST expression

(@)CheckReal

EN

ENO

CheckReal(In, Nan, PosInfinite, NegInfinite);

In

Out

Nan

PosInfinite

NegInfinite

2

Variables

Name In Out Nan
PosInfinite
NegInfinite

Meaning
Real number
Return value
Nonnumeri c data check result
Positive infinity check result
Negative infinity check result

I/O Input
Output

Description Real number

Valid range

Unit

Depends on data type. ---

Always TRUE

TRUE only

TRUE: Nonnumeric data
FALSE: Not nonnumeric data

TRUE: Positive infinity

---

FALSE: Not positive infinity Depends on data type.

TRUE: Negative infinity FALSE: Not negative infinity

* If you omit an input parameter, the default value is not applied. A building error will occur.

Default *
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In

Out

OK

Nan

OK

PosInfinite OK

NegInfinite OK

OK OK

NJ/NX-series Instructions Reference Manual (W502)

2-237

2 Instruction Descriptions

Function

The CheckReal instruction checks a real number In to see if it is nonnumeric data, positive infinity, or negative infinity. It outputs the results to Nan, PosInfinite, and NegInfinite.
The following figure shows a programming example. The values of REAL variables a and b are multiplied and the result is tested to see if it is a real number. If the multiplication result is a real number, it is assigned to variable d.

LD

ST

MUL

EN ENO

a In1

c

b In2

CheckReal

EN

ENO

c In

Nan abc

PosInfinite def NegInfinite ghi

abc def ghi

MOVE

EN c In

ENO Out d

c:=a*b; CheckReal(c, abc, def, ghi); IF ( (abc=FALSE) AND (def=FALSE) AND (ghi=FALSE) ) THEN
d:=c; END_IF;

If the product c of a and b is not nonnumeric data, positive infinity, or negative infinity, then the value of c is assigned to d.

START

a× b  c
c is nonnumeric data. TRUE FALSE
Nan = abc  FALSE

CheckReal Nan = abc  TRUE

c is positive infinity. TRUE

FALSE

PosInfinite = def  FALSE

PosInfinite = def  TRUE

TRUE c is negative infinity.

FALSE

NegInfinite = ghi  FALSE

NegInfinite = ghi  TRUE

c  d END

2-238

NJ/NX-series Instructions Reference Manual (W502)

Math Instructions

2 Instruction Descriptions

Additional Information
Use this instruction on the result of a math instruction that handles real numbers to see if the result is nonnumeric data, positive infinity, or negative infinity.

Precautions for Correct Use

· Return value Out is not used when the instruction is used in ST.

· If you pass an integer parameter to In, the data type is converted as follows:

Data type of parameter that is passed to In

Data type of In

2

USINT, UINT, SINT, or INT

REAL

UDINT or DINT

LREAL

ULINT or LINT

A building error will occur.

CheckReal

NJ/NX-series Instructions Reference Manual (W502)

2-239

2 Instruction Descriptions

2-240

NJ/NX-series Instructions Reference Manual (W502)

BCD Conversion Instructions

2
BCD Conversion Instructions

Instruction **_BCD_TO_*** **_TO_BCD_*** BCD_TO_** BCDsToBin BinToBCDs_** AryToBCD AryToBin

Name
BCD-to-Unsigned Integer Conversion Group Unsigned Integer-to-BCD Conversion Group
BCD Data Type-to-Unsigned Integer Conversion Group Signed BCD-to-Signed Integer Conversion Signed Integer-to-BCD Conversion Group Array BCD Conversion
Array Unsigned Integer Conversion

Page 2-242 2-245 2-247 2-250 2-253 2-256 2-258

NJ/NX-series Instructions Reference Manual (W502)

2-241

2 Instruction Descriptions

**_BCD_TO_***

These instructions convert BCD bit strings into unsigned integers.

Instruction **_BCD_TO_***

Name
BCD-to-Unsigned Integer Conversion Group

FB/FUN FUN

Graphic expression

(@)**_BCD_TO_***

EN

ENO

In

Out

"**" must be a bit string data type. "***" must be an integer data type.

ST expression Out:=**_BCD_TO_*** (In);
"**" must be a bit string data type. "***" must be an integer data type.

Variables

Name

Meaning

I/O

Description

Valid range

Unit

In

Data to

Input

Data to convert

*

---

convert

Out

Conversion Output

Conversion result

*

---

result

* The valid ranges depend on the data types of In and Out. Refer to Function, below, for details.

Default 0
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK OK OK OK

Out

OK OK OK OK OK OK OK OK

Function

These instructions convert data to convert In (which must be a BCD bit string) into an unsigned integer. The name of the instruction is determined by the data types of In and conversion result Out. For example, if In is WORD data and Out is UINT data, the name of the instruction is WORD_BCD_TO_UINT. The following example for the WORD_BCD_TO_UINT instruction is for when In is WORD16#3452.

LD

ST

abc:=WORD_BCD_TO_UINT(WORD#16#3452);

WORD_BCD_TO_UINT

EN WORD#16#3452 In

ENO abc

WORD BCD data In WORD#16#3452
2-242

UNIT data Out=abc 3452
NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

BCD Conversion Instructions

The following table shows the valid ranges for In and Out according to their data types.

Data type Data type

of In

of Out

Valid range for In

Valid range for Out

USINT

UINT

UDINT

BYTE

ULINT SINT

16#00 to 16#99 (BCD)

0 to 99

INT

DINT

LINT

USINT

16#0000 to 16#0255 (BCD)

0 to 255

2

UINT

UDINT

16#0000 to 16#9999 (BCD)

0 to 9999

**_BCD_TO_***

WORD

ULINT SINT

16#0000 to 16#0127 (BCD)

0 to 127

INT

DINT

16#0000 to 16#9999 (BCD)

0 to 9999

LINT

USINT

16#0000_0000 to 16#0000_0255 (BCD)

0 to 255

UINT

16#0000_0000 to 16#0006_5535 (BCD)

0 to 65535

DWORD

UDINT ULINT SINT

16#0000_0000 to 16#9999_9999 (BCD) 16#0000_0000 to 16#0000_0127 (BCD)

0 to 99999999 0 to 127

INT

16#0000_0000 to 16#0003_2767 (BCD)

0 to 32767

DINT LINT

16#0000_0000 to 16#9999_9999 (BCD)

0 to 99999999

USINT

16#0000_0000_0000_0000 to 16#0000_0000_0000_0255 (BCD)

0 to 255

UINT

16#0000_0000_0000_0000 to 16#0000_0000_0006_5535 (BCD)

0 to 65535

UDINT

16#0000_0000_0000_0000 to 16#0000_0042_9496_7295 (BCD)

0 to 4294967295

LWORD

ULINT SINT

16#0000_0000_0000_0000 to 16#9999_9999_9999_9999 (BCD)
16#0000_0000_0000_0000 to 16#0000_0000_0000_0127 (BCD)

0 to 9999999999999999 0 to 127

INT

16#0000_0000_0000_0000 to

16#0000_0000_0003_2767 (BCD)

0 to 32767

DINT

16#0000_0000_0000_0000 to 16#0000_0021_4748_3647 (BCD)

0 to 2147483647

LINT

16#0000_0000_0000_0000 to 16#9999_9999_9999_9999 (BCD)

0 to 9999999999999999

Additional Information
· To convert a BCD bit string to an integer, use a BCD_TO_** instruction (page 2-247). · To convert an integer to a BCD bit string, use a **_TO_BCD_*** instruction (page 2-245).

Precautions for Correct Use
· Always use the correct instruction name for the data types of In and Out. · If the data size of Out is larger than the data size of In, the upper digits of Out will contain 0. · An error occurs in the following cases. ENO will be FALSE, and Out will not change.

NJ/NX-series Instructions Reference Manual (W502)

2-243

2 Instruction Descriptions
· The value of In is outside of the valid range. · The value in In is not BCD bit string data (i.e., contains A, B, C, D, E, or F hexadecimal).

2-244

NJ/NX-series Instructions Reference Manual (W502)

BCD Conversion Instructions

2 Instruction Descriptions

**_TO_BCD_***

These instructions convert unsigned integers to BCD bit strings.

Instruction

Name

FB/FUN

Graphic expression

ST expression

**_TO_BCD_***

Unsigned Integer- FUN to-BCD Conversion Group

(@)**_TO_BCD_***

Out:=**_TO_BCD_*** (In);

EN In

ENO Out "**" must be an integer data

type.

"**" must be an integer data type.

"***" must be a bit string

"***" must be a bit string data type. data type.

2

**_TO_BCD_***

Variables

Name

Meaning

I/O

Description

Valid range

Unit

In

Data to

Input

Data to convert

*

---

convert

Out

Conversion Output

Conversion result

*

---

result

* The valid ranges depend on the data types of In and Out. Refer to Function, below, for details.

Default 0
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK OK OK OK OK OK OK OK

Out

OK OK OK OK

Function

These instructions convert data to convert In (which must be an unsigned integer) to a BCD bit string. The name of the instruction is determined by the data types of In and conversion result Out. For example, if In is UINT data and Out is WORD data, the name of the instruction is UINT_TO_BCD_WORD. The following example for the UINT_TO_BCD_WORD instruction is for when In is UNIT#3452.

LD

ST

abc:=UINT_TO_BCD_WORD(UINT#3452);

UINT_TO_BCD_WORD

EN UINT#3452 In

ENO abc

UNIT data In UINT#3452

WORD BCD data Out=abc 16#3452

NJ/NX-series Instructions Reference Manual (W502)

2-245

2 Instruction Descriptions

The following table shows the valid ranges for In and Out according to their data types.

Data type of In
USINT

Data type of Out
BYTE WORD DWORD LWORD

Valid range for In 0 to 99
0 to 255

UINT

BYTE WORD DWORD LWORD

0 to 99 0 to 9999
0 to 65535

UDINT ULINT SINT

BYTE WORD DWORD LWORD
BYTE WORD DWORD LWORD
BYTE WORD DWORD LWORD

0 to 99 0 to 9999 0 to 99999999 0 to 4294967295 0 to 99 0 to 9999 0 to 99999999 0 to 9999999999999999 0 to 99
0 to 127

BYTE

0 to 99

WORD 0 to 9999

INT

DWORD

LWORD 0 to 32767

DINT LINT

BYTE WORD DWORD LWORD
BYTE WORD DWORD LWORD

0 to 99 0 to 9999 0 to 99999999
0 to 2147483647
0 to 99 0 to 9999 0 to 99999999
0 to 9999999999999999

Valid range for Out
16#00 to 16#99 (BCD) 16#0000 to 16#0255 (BCD) 16#0000_0000 to 16#000_0255 (BCD) 16#0000_0000_0000_0000 to 16#0000_0000_0000_0255 (BCD) 16#00 to 16#99 (BCD) 16#0000 to 16#9999 (BCD) 16#0000_0000 to 16#0006_5535 (BCD) 16#0000_0000_0000_0000 to 16#0000_0000_0006_5535 (BCD) 16#00 to 16#99 (BCD) 16#0000 to 16#9999 (BCD) 16#0000_0000 to 16#9999_9999 (BCD) 16#0000_0000_0000_0000 to 16#0000_0042_9496_7295 (BCD) 16#00 to 16#99 (BCD) 16#0000 to 16#9999 (BCD) 16#0000_0000 to 16#9999_9999 (BCD) 16#0000_0000_0000_0000 to 16#9999_9999_9999_9999 (BCD) 16#00 to 16#99 (BCD) 16#0000 to 16#0127 (BCD) 16#0000_0000 to 16#0000_0127 (BCD) 16#0000_0000_0000_0000 to 16#0000_0000_0000_0127 (BCD) 16#00 to 16#99 (BCD) 16#0000 to 16#9999 (BCD) 16#0000_0000 to 16#0003_2767 (BCD) 16#0000_0000_0000_0000 to 16#0000_0000_0003_2767 (BCD) 16#00 to 16#99 (BCD) 16#0000 to 16#9999 (BCD) 16#0000_0000 to 16#9999_9999 (BCD) 16#0000_0000_0000_0000 to 16#0000_0021_4748_3647 (BCD) 16#00 to 16#99 (BCD) 16#0000 to 16#9999 (BCD) 16#0000_0000 to 16#9999_9999 (BCD) 16#0000_0000_0000_0000 to 16#9999_9999_9999_9999 (BCD)

Additional Information
· To convert a specific BCD bit string to an integer, use a **_BCD_TO_*** instruction (page 2-242). · To convert a BCD bit string to an integer, use a BCD_TO_** instruction (page 2-247).

Precautions for Correct Use
· Always use the correct instruction name for the data types of In and Out. · If the data size of Out is larger than the data size of In, the upper digits of Out will contain 0. · An error occurs in the following case. ENO will be FALSE, and Out will not change.
· The value of In is outside of the valid range.

2-246

NJ/NX-series Instructions Reference Manual (W502)

BCD Conversion Instructions

2 Instruction Descriptions

BCD_TO_**

The BCD_TO_** instruction converts BCD bit strings into unsigned integers.

Instruction

Name

FB/FUN

Graphic expression

ST expression

BCD_TO_**

BCD Data Type-to- FUN Unsigned Integer Conversion Group

(@)BCD_TO_**

EN

ENO

In

Out

Out:=BCD_TO_** (In);
"**" must be an integer data type.

"**" must be an integer data type.
2

Variables

BCD_TO_**

Name

Meaning

I/O

Description

Valid range

Unit

In

Data to

Input

Data to convert

*1

---

convert

Out

Conversion Output

Conversion result

*1

---

result

*1 The valid ranges depend on the data types of In and Out. Refer to Function, below, for details.

*2 If you omit the input parameter, the default value is not applied. A building error will occur.

Default *2
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK OK OK OK

Out

OK OK OK OK OK OK OK OK

Function

These instructions convert data to convert In (which must be a BCD bit string) into an unsigned integer. The name of the instruction is determined by the data type of conversion result Out. For example, if Out is the UINT data type, the instruction is BCD_TO_UINT. The following example for the BCD_TO_UINT instruction is for when In is WORD#16#3452.

LD

ST

abc:=BCD_TO_UINT(WORD#16#3452);

BCD_TO_UINT

EN WORD#16#3452 In

ENO abc

WORD BCD data In WORD#16#3452

UNIT data Out=abc 3452

NJ/NX-series Instructions Reference Manual (W502)

2-247

2 Instruction Descriptions

The following table shows the valid ranges for In and Out according to their data types.

Data type of In
BYTE WORD DWORD
LWORD

Data type of Out
USINT UINT UDINT ULINT SINT INT DINT LINT USINT UINT UDINT ULINT SINT INT DINT LINT USINT UINT UDINT ULINT SINT INT DINT LINT USINT
UINT
UDINT
ULINT
SINT
INT
DINT
LINT

Valid range for In
16#00 to 16#99 (BCD)
16#0000 to 16#0255 (BCD)
16#0000 to 16#9999 (BCD)
16#0000 to 16#0127 (BCD)
16#0000 to 16#9999 (BCD)
16#0000_0000 to 16#0000_0255 (BCD) 16#0000_0000 to 16#0006_5535 (BCD) 16#0000_0000 to 16#9999_9999 (BCD) 16#0000_0000 to 16#0000_0127 (BCD) 16#0000_0000 to 16#0003_2767 (BCD) 16#0000_0000 to 16#9999_9999 (BCD) 16#0000_0000_0000_0000 to 16#0000_0000_0000_0255 (BCD) 16#0000_0000_0000_0000 to 16#0000_0000_0006_5535 (BCD) 16#0000_0000_0000_0000 to 16#0000_0042_9496_7295 (BCD) 16#0000_0000_0000_0000 to 16#9999_9999_9999_9999 (BCD) 16#0000_0000_0000_0000 to 16#0000_0000_0000_0127 (BCD) 16#0000_0000_0000_0000 to 16#0000_0000_0003_2767 (BCD) 16#0000_0000_0000_0000 to 16#0000_0021_4748_3647 (BCD) 16#0000_0000_0000_0000 to 16#9999_9999_9999_9999 (BCD)

Valid range for Out
0 to 99
0 to 255 0 to 9999 0 to 127 0 to 9999 0 to 255 0 to 65535 0 to 99999999 0 to 127 0 to 32767 0 to 99999999 0 to 255 0 to 65535 0 to 4294967295 0 to 9999999999999999 0 to 127 0 to 32767 0 to 2147483647 0 to 9999999999999999

Additional Information
· To convert a specific BCD bit string to an integer, use a **_BCD_TO_*** instruction (page 2-242). · To convert an integer to a BCD bit string, use a **_TO_BCD_*** instruction (page 2-245).

2-248

NJ/NX-series Instructions Reference Manual (W502)

BCD Conversion Instructions

2 Instruction Descriptions
Precautions for Correct Use
· Always use the correct instruction name for the data type of Out. · If the data size of Out is larger than the data size of In, the upper digits of Out will contain 0. · An error occurs in the following cases. ENO will be FALSE, and Out will not change.
· The value of In is outside of the valid range. · The value in In is not BCD bit string data (i.e., contains A, B, C, D, E, or F hexadecimal).
2

BCD_TO_**

NJ/NX-series Instructions Reference Manual (W502)

2-249

2 Instruction Descriptions

BCDsToBin

The BCDsToBin instruction converts signed BCD bit strings to signed integers.

Instruction BCDsToBin

Name
Signed BCD-toSigned Integer Conversion

FB/FUN FUN

Graphic expression

(@)BCDsToBin

EN In Format

ENO Out

ST expression Out:=BCDsToBin(In, Format);

Variables

Name

Meaning

I/O

Description

Valid range

In Format

Data to convert
Data format number

Input

Data to convert Format of BCD bit string

*1 _BCD0 to _BCD3

Out

Conversion Output

Conversion result

*1

result

*1 The valid range depends on the value of Format. Refer to Function, below, for details.

*2 If you omit the input parameter, the default value is not applied. A building error will occur.

Unit ---
---

Default *2
_BCD0
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In Format Out

OK OK OK OK Refer to Function for the enumerators of the enumerated type _eBCD_FORMAT. Must be a signed integer data type that is the same size as In.

Function
The BCDsToBin instruction converts signed BCD bit string In to a signed integer.

2-250

NJ/NX-series Instructions Reference Manual (W502)

BCD Conversion Instructions

2 Instruction Descriptions

The data type of data format number Format is enumerated type _eBCD_FORMAT. Select one of the following: _BCD0, _BCD1, _BCD2, or _BCD3. The sign specification in the upper four bits of In depends on the BCD format number. The data format examples shown below use WORD data for In.

Format = _BCD0 Valid range of In: -999 to 999 (BCD) 15 1211 8 7 4 3 0
In

Format = _BCD1 Valid range of In: -7999 to 7999 (BCD) 15 1211 8 7 4 3 0
In

3 BCD digits (12 bits)

3 BCD digits (12 bits)

Sign bit

BCD digit 4 (three bits: 12 to 14)

0: Positive 1: Negative

Sign bit 0: Positive

1: Negative

2

BCDsToBin

Format = _BCD2 Valid range of In: -999 to 9999 (BCD)
15 1211 8 7 4 3 0 In

Format = _BCD3 Valid range of In: -1999 to 9999 (BCD)
15 1211 8 7 4 3 0
In

3 BCD digits (12 bits)
#0 to #9: BCD digit 4 (positive) #F: Negative (#A to #E: error)

3 BCD digits (12 bits)
#0 to #9: BCD digit 4 (positive) #A: Negative, BCD digit 4 is 1 #F: Negative, BCD digit 4 is 0 (#B to #E: error)

The same sizes of data types are used for In and Out. The valid ranges depend on the value of Format, as shown below.

Data type of
In  Data type of Out

BYTE 
SINT
WORD  INT
DWORD 
DINT
LWORD 
LINT

_BCD0 -9 to 9
-999 to 999
-9999999 to 9999999
-999999999999999 to 999999999999999

Value of Format

_BCD1

_BCD2

-79 to 79

-9 to 99

_BCD3 -19 to 99

-7999 to 7999

-999 to 9999

-1999 to 9999

-79999999 to 79999999

-9999999 to 99999999 -19999999 to 99999999

-7999999999999999 to -999999999999999 to -1999999999999999 to 7999999999999999 9999999999999999 9999999999999999

The following example is for when In is WORD#2#1011_0100_0101_0010 and Format is _BCD1.

LD

ST

WORD#2#1011_0100_0101_0010 _BCD1

BCDsToBin

EN In Format

ENO

abc:=BCDsToBin(WORD#2#1011_0100_0101_0010, _BCD1);
abc

WORD BCD data In WORD#2#1011_0100_0101_0010

Out=abc

INT data -3452

NJ/NX-series Instructions Reference Manual (W502)

2-251

2 Instruction Descriptions
Precautions for Correct Use
· Use the same sizes of data types for In and Out. · An error occurs in the following cases. ENO will be FALSE, and Out will not change.
· The value of Format is _BCD0 and the upper digit of In is 2 to F. · The value of Format is _BCD2 and the upper digit of In is A to E. · The value of Format is _BCD3 and the upper digit of In is B to E. · Except for the above conditions, any digit in In is A to F. · The value of Format is outside of the valid range.

2-252

NJ/NX-series Instructions Reference Manual (W502)

BCD Conversion Instructions

2 Instruction Descriptions

BinToBCDs_**

These instructions convert signed integers to signed BCD bit strings.

Instruction

Name

FB/FUN

Graphic expression

ST expression

BinToBCDs_**

Signed Integer-toBCD Conversion Group

FUN

(@)BinToBCDs_**

EN

ENO

Out:=BinToBCDs(In, Format);

In Format

Out "**" must be a bit string data

"**" must be a bit string data type.

type.

2

BinToBCDs_**

Variables

Name In
Format
Out

Meaning

I/O

Data to convert
Data format number

Input

Conversion Output result

Description Data to convert
Format of BCD bit string
Conversion result

Valid range *
_BCD0 to _BCD3 *

* The valid range depends on the value of Format. Refer to Function, below, for details.

Unit ---
---

Default 0
_BCD0
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In Format Out

OK OK OK OK Refer to Function for the enumerators of the enumerated type _eBCD_FORMAT.
Must be same size of data type as In

Function
These instructions convert signed integer In to a signed BCD bit string. The name of the instruction is determined by the data type of Out. For example, if Out is the WORD data type, the instruction is BinToBCDs_WORD.

NJ/NX-series Instructions Reference Manual (W502)

2-253

2 Instruction Descriptions

The data type of data format number Format is enumerated type _eBCD_FORMAT. Select one of the following: _BCD0, _BCD1, _BCD2, or _BCD3. The sign specification in the upper four bits of Out depends on the BCD format number. The data format examples shown below use WORD data for Out.

Format = _BCD0 Valid range of Out: -999 to 999 (BCD) 15 1211 8 7 4 3 0
Out

Format = _BCD1 Valid range of Out: -7999 to 7999 (BCD) 15 1211 8 7 4 3 0
Out

3 BCD digits (12 bits)
Sign bit 0: Positive 1: Negative

3 BCD digits (12 bits)
BCD digit 4 (three bits: 12 to 14)
Sign bit 0: Positive 1: Negative

Format = _BCD2 Valid range of Out: -999 to 9999 (BCD)
15 1211 8 7 4 3 0 Out

Format = _BCD3 Valid range of Out: -1999 to 9999 (BCD) 15 1211 8 7 4 3 0
Out

3 BCD digits (12 bits)
#0 to #9: BCD digit 4 (positive) #F: Negative (#A to #E: error)

3 BCD digits (12 bits)
#0 to #9: BCD digit 4 (positive) #A: Negative, BCD digit 4 is 1 #F: Negative, BCD digit 4 is 0 (#B to #E: error)

The same sizes of data types are used for In and Out. The valid ranges depend on the value of Format, as shown below.

Data type of
In  Data type of Out

SINT 
BYTE
INT 
WORD
DINT 
DWORD
LINT 
LWORD

_BCD0 -9 to 9
-999 to 999
-9999999 to 9999999 -999999999999999 to 999999999999999

Value of Format

_BCD1

_BCD2

-79 to 79

-9 to 99

_BCD3 -19 to 99

-7999 to 7999

-999 to 9999

-1999 to 9999

-79999999 to 79999999

-9999999 to 99999999

-19999999 to 99999999

-7999999999999999 to -999999999999999 to -1999999999999999 to 7999999999999999 9999999999999999 9999999999999999

The following example shows the BinToBCDs_WORD instruction when In is INT#-3452 and Format is _BCD1.

LD

ST

abc:=BinToBCDs_WORD(INT#-3452,_BCD1);

BinToBCDs_WORD

INT#-3452 _BCD1

EN In Format

ENO abc

INT data In INT#-3452

Out=abc

WORD BCD data 2#1011_0100_0101_0010

2-254

NJ/NX-series Instructions Reference Manual (W502)

BCD Conversion Instructions

2 Instruction Descriptions
Precautions for Correct Use
· Always use the correct instruction name for the data type of Out. · An error occurs in the following cases. ENO will be FALSE, and Out will not change.
· The value of In is outside of the valid range. · The value of Format is outside of the valid range.
2

BinToBCDs_**

NJ/NX-series Instructions Reference Manual (W502)

2-255

2 Instruction Descriptions

AryToBCD

The AryToBCD instruction converts the elements of an unsigned integer array to BCD bit strings.

Instruction AryToBCD

Name
Array BCD Conversion

FB/FUN FUN

Graphic expression

(@)AryToBCD

EN

ENO

In

Out

Size

AryOut

ST expression
AryToBCD(In, Size, AryOut);

Variables

Name

Meaning

I/O

Description

Valid range

Unit

Default

In[] (array)

Unsigned integer array

Input

Unsigned integer array

*1

*2 ---

Size

Number of

Number of elements of In[] Depends on data type.

1

elements

for conversion

AryOut[] BCD array In-out

BCD array

*1

(array)

---

---

Out

Return

Output

Always TRUE

value

TRUE only

---

---

*1 The valid ranges depend on the data types of the elements of In[] and AryOut[]. Refer to Function for details.

*2 If you omit an input parameter, the default value is not applied. A building error will occur.

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In[] (array)

Size

AryOut[] (array)

Out

OK

OK OK OK OK OK
Must be a bit string array. The data type must be the same size as the elements of In[].

2-256

NJ/NX-series Instructions Reference Manual (W502)

BCD Conversion Instructions

2 Instruction Descriptions

Function

The AryToBCD instruction converts Size elements of unsigned integer array In[] starting from In[0] to a BCD bit string. It outputs the BCD bit string to BCD array AryOut[].

The following example is for when Size is UINT#3.

LD

ST

AryToBCD(abc[1], UINT#3, def[2]);

AryToBCD

EN abc[1] In

ENO

2

UINT#3 Size

AryOut def[2]

def[2]

AryToBCD

Size=UINT#3

In[0]=abc[1] In[1]=abc[2] In[2]=abc[3]

16#10EC 16#0013 16#123B

AryOut[0]=def[2] AryOut[1]=def[3] AryOut[2]=def[4]

4332 0019 4667

The following table shows the valid ranges for In[] and AryOut[] according to the data types of their elements.

Data type of the ele- Data type of the ele-

ments of In[]

ments of AryOut[]

Valid range of In[]

USINT

BYTE

0 to 99

UINT

WORD

0 to 9999

UDINT

DWORD

0 to 99999999

ULINT

LWORD

0 to 9999999999999999

Valid range of AryOut[]
16#00 to 16#99 (BCD) 16#0000 to 16#9999 (BCD) 16#0000_0000 to 16#9999_9999 (BCD) 16#0000_0000_0000_0000 to 16#9999_9999_9999_9999 (BCD)

Precautions for Correct Use
· Use the same data type and size for In[] and AryOut[]. For example, if the elements of In[] are UINT data, use WORD as the data type of the elements of AryOut[]. Otherwise, a building error will occur.
· This instruction does not convert signed binary to signed BCD. Use an unsigned integer (USINT, UINT, UDINT, or ULINT) as the data type of In[].
· The values in AryOut[] do not change if the value of Size is 0. · Return value Out is not used when the instruction is used in ST. · An error occurs in the following cases. ENO will be FALSE, and AryOut[] will not change.
· The value of In[] is outside of the valid range. · The value of Size exceeds the array area of In[] or AryOut[].

NJ/NX-series Instructions Reference Manual (W502)

2-257

2 Instruction Descriptions

AryToBin

The AryToBin instruction converts the elements of an array of BCD bit strings into unsigned integers.

Instruction AryToBin

Name
Array Unsigned Integer Conversion

FB/FUN FUN

Graphic expression

(@)AryToBin

EN

ENO

In

Out

Size

AryOut

ST expression
AryToBin(In, Size, AryOut);

Variables

Name

Meaning

I/O

Description

Valid range

Unit

Default

In[] (array)

Array of BCD bit strings

Input

Array of BCD bit strings

*1

*2 ---

Size

Number of

Number of elements of In[] Depends on data type.

1

elements

for conversion

AryOut[] Unsigned In-out

Unsigned integer array

*1

(array)

integer

array

---

---

Out

Return

Output

Always TRUE

value

TRUE only

---

---

*1 The valid ranges depend on the data types of the elements of In[] and AryOut[]. Refer to Function for details.

*2 If you omit an input parameter, the default value is not applied. A building error will occur.

Bit string

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In[] (array) Size AryOut[] (array) Out

OK OK OK OK OK
Must be an unsigned integer array. The data type must be the same size as the elements of In[].
OK

2-258

NJ/NX-series Instructions Reference Manual (W502)

BCD Conversion Instructions

2 Instruction Descriptions

Function

The AryToBin instruction converts Size elements of array of BCD bit strings In[] starting from In[0] to unsigned integers. It outputs the unsigned integers to unsigned integer array AryOut[].

The following example is for when Size is UINT#3.

LD

ST

AryToBin(abc[1], UINT#3, def[2]);

AryToBin

EN abc[1] In

ENO

2

UINT#3 Size

AryOut def[2]

def[2]

AryToBin

In[0]=abc[1]
Size=UINT#3 In[1]=abc[2] In[2]=abc[3]

4332 0019 4667

AryOut[0]=def[2] AryOut[1]=def[3] AryOut[2]=def[4]

16#10EC 16#0013 16#123B

The following table shows the valid ranges for In[] and AryOut[] according to the data types of their elements.

Data type of the ele- Data type of the ele-

ments of In[]

ments of AryOut[]

Valid range of In[]

Valid range of AryOut[]

BYTE

USINT

16#00 to 16#99 (BCD)

0 to 99

WORD

UINT

16#0000 to 16#9999 (BCD)

0 to 9999

DWORD

UDINT

16#0000_0000 to 16#9999_9999 (BCD)

0 to 99999999

LWORD

ULINT

16#0000_0000_0000_0000 to

0 to 9999999999999999

16#9999_9999_9999_9999 (BCD)

Precautions for Correct Use
· Use the same data type and size for In[] and AryOut[]. For example, if the elements of In[] are WORD data, use USINT as the data type of the elements of AryOut[]. Otherwise, a building error will occur.
· This instruction does not convert signed BCD to signed binary. Use an unsigned integer (USINT, UINT, UDINT, or ULINT) as the data type of AryOut [].
· The values in AryOut[] do not change if the value of Size is 0. · Return value Out is not used when the instruction is used in ST. · An error occurs in the following cases. ENO will be FALSE, and AryOut[] will not change.
· The value of Size exceeds the array area of In[] or AryOut[]. · A value in In[] is not a BCD bit string (i.e., contains A, B, C, D, E, or F hexadecimal).

NJ/NX-series Instructions Reference Manual (W502)

2-259

2 Instruction Descriptions

2-260

NJ/NX-series Instructions Reference Manual (W502)

Data Type Conversion Instructions

2
Data Type Conversion Instructions

Instruction
**_TO_*** (Integer-to-Integer Conversion Group)
**_TO_*** (Integer-to-Bit String Conversion Group)
**_TO_*** (Integer-to-Real Number Conversion Group)
**_TO_*** (Bit String-toInteger Conversion Group)

Name
Integer-to-Integer Conversion Group
Integer-to-Bit String Conversion Group
Integer-to-Real Number Conversion Group
Bit String-to-Integer Conversion Group

**_TO_*** (Bit String-to-Bit String Conversion Group)

Bit String-to-Bit String Conversion Group

**_TO_*** (Bit String-to-Real Number Conversion Group)
**_TO_*** (Real Number-toInteger Conversion Group)
**_TO_*** (Real Number-toBit String Conversion Group)
**_TO_*** (Real Number-toReal Number Conversion Group)
**_TO_STRING (Integer-toText String Conversion Group)
**_TO_STRING (Bit String-toText String Conversion Group)

Bit String-to-Real Number Conversion Group
Real Number-to-Integer Conversion Group
Real Number-to-Bit String Conversion Group
Real Number-to-Real Number Conversion Group
Integer-to-Text String Conversion Group
Bit String-to-Text String Conversion Group

**_TO_STRING (Real Number-to-Text String Conversion Group)

Real Number-to-Text String Conversion Group

Page

Instruction

2-262 RealToFormatString

2-265 LrealToFormatString

2-268 2-270
2-272
2-274 2-276 2-279 2-281

STRING_TO_** (Text Stringto-Integer Conversion Group)
STRING_TO_** (Text Stringto-Bit String Conversion Group)
STRING_TO_** (Text Stringto-Real Number Conversion Group)
TO_** (Integer Conversion Group)
TO_** (Bit String Conversion Group)
TO_** (Real Number Conversion Group)
EnumToNum

2-283 NumToEnum
2-285 TRUNC, Round, and RoundUp
2-287

Name REAL-to-Formatted Text String LREAL-to-Formatted Text String Text String-to-Integer Conversion Group Text String-to-Bit String Conversion Group
Text String-to-Real Number Conversion Group Integer Conversion Group
Bit String Conversion Group Real Number Conversion Group Enumeration-to-Integer
Integer-to-Enumeration
Truncate/Round Off Real Number/Round Up Real Number

Page 2-289 2-294 2-299 2-301
2-303
2-306 2-308 2-310 2-312
2-314 2-316

NJ/NX-series Instructions Reference Manual (W502)

2-261

2 Instruction Descriptions

**_TO_*** (Integer-to-Integer Conversion Group)

These instructions convert integers to integers with different data types.

Instruction **_TO_***

Name
Integer-to-Integer Conversion Group

FB/FUN FUN

Graphic expression

(@)**_TO_***

EN

ENO

In

Out

"**" and "***" must be different integer data types.

ST expression Out:=**_TO_*** (In);
"**" and "***" must be different integer data types.

Variables

Name

Meaning

I/O

Description

Valid range

Unit

In

Data to

Input

Data to convert

*

---

convert

Out

Conversion Output

Conversion result

*

---

result

* The valid ranges depend on the data types of In and Out. Refer to Function, below, for details.

Default 0
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In

OK OK OK OK OK OK OK OK

Out

OK OK OK OK OK OK OK OK

Function

These instructions convert an integer, In, to an integer with a different data type.
The name of the instruction is determined by the data types of In and conversion result Out. For example, if In is INT data and Out is DINT data, the name of the instruction is INT_TO_DINT.
The following example for the INT_TO_DINT instruction is for when In is INT#1234.

LD

ST

abc:=INT_TO_DINT(INT#1234);

INT_TO_DINT

EN INT#1234 In

ENO abc

INT data In INT#1234

DINT data Out=abc 1234

2-262

NJ/NX-series Instructions Reference Manual (W502)

Data Type Conversion Instructions

**_TO_*** (Integer-to-Integer Conversion Group)

2 Instruction Descriptions

The following table shows the valid ranges for In and Out according to their data types.

Data type Data type

of In

of Out

Valid range for In and Out

UINT

UDINT

0 to 255

ULINT

USINT

SINT

0 to 127

INT

DINT

0 to 255

LINT

USINT

0 to 255

UDINT ULINT

0 to 65535

2

UINT

SINT

0 to 127

INT

0 to 32767

DINT LINT

0 to 65535

USINT

0 to 255

UINT

0 to 65535

ULINT

0 to 4294967295

UDINT

SINT

0 to 127

INT

0 to 32767

DINT

0 to 2147483647

LINT

0 to 4294967295

USINT

0 to 255

UINT

0 to 65535

UDINT

0 to 4294967295

ULINT

SINT

0 to 127

INT

0 to 32767

DINT

0 to 2147483647

LINT

0 to 9223372036854775807

USINT

UINT UDINT

0 to 127

SINT

ULINT

INT

DINT

-128 to 127

LINT

USINT

0 to 255

UINT

UDINT

0 to 32767

INT

ULINT

SINT

-128 to 127

DINT LINT

-32768 to 32767

USINT

0 to 255

UINT

0 to 65535

DINT

UDINT ULINT

0 to 2147483647

SINT

-128 to 127

INT

-32768 to 32767

LINT

-2147483648 to 2147483647

NJ/NX-series Instructions Reference Manual (W502)

2-263

2 Instruction Descriptions

Data type of In
LINT

Data type of Out
USINT UINT UDINT ULINT SINT INT DINT

Valid range for In and Out
0 to 255 0 to 65535 0 to 4294967295 0 to 9223372036854775807 -128 to 127 -32768 to 32767 -2147483648 to 2147483647

Additional Information
To convert data with any data type to integer data, use a TO_** (Integer Conversion Group) instruction (page 2-306).

Precautions for Correct Use
· Always use the correct instruction name for the data types of In and Out. · If In is a signed integer and the data size of Out is larger than the data size of In, sign extension is
performed. · If In is an unsigned integer and the data size of Out is larger than the data size of In, the upper digits
of Out will contain 0. · If the data size of Out is smaller than the data size of In, the upper digits are truncated in Out.

2-264

NJ/NX-series Instructions Reference Manual (W502)

Data Type Conversion Instructions

2 Instruction Descriptions

**_TO_*** (Integer-to-Bit String Conversion Group)

These instructions convert integers to bit strings.

Instruction

Name

FB/FUN

Graphic expression

ST expression

**_TO_***

Integer-to-Bit String FUN Conversion Group

(@)**_TO_***

Out:=**_TO_*** (In);

EN In

ENO Out

"**" must be an integer data

2

type.

"**" must be an integer data type. "***" must be a bit string "***" must be a bit string data type. data type.

Variables

Name In
Out

Meaning
Data to convert
Conversion result

I/O Input
Output

Description Data to convert
Conversion result

Valid range *
*

Unit
---
---

* The valid ranges depend on the data types of In and Out. Refer to Function, below, for details.

Default 0
---

Bit strings

Integers

Times, durations, dates, and text strings

**_TO_*** (Integer-to-Bit String Conversion Group)
STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT
DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD
BYTE Boolean BOOL

In

OK OK OK OK OK OK OK OK*1

Out

OK OK*1 OK OK

*1 For an NX1P2 CPU Unit, a CPU Unit with unit version 1.14 or later and Sysmac Studio version 1.18 or higher are required to use the LINT_TO_WORD instruction.

Function

These instructions convert an integer, In, to a bit string.
The name of the instruction is determined by the data types of In and conversion result Out. For example, if In is INT data and Out is WORD data, the name of the instruction is INT_TO_WORD.
The following example for the INT_TO_WORD instruction is for when In is INT#-1234.

LD

ST

abc:=INT_TO_WORD(INT#-1234);

INT_TO_WORD

EN INT#-1234 In

ENO abc

NJ/NX-series Instructions Reference Manual (W502)

2-265

2 Instruction Descriptions

INT data In INT#-1234

WORD data Out=abc 16#FB2E

The following table shows the valid ranges for In and Out according to their data types.

Data type of In
USINT
UINT
UDINT
ULINT

Data type of Out
BYTE WORD DWORD LWORD BYTE WORD DWORD LWORD BYTE WORD DWORD LWORD BYTE WORD DWORD

Valid range for In
0 to 255
0 to 255
0 to 65535
0 to 255 0 to 65535 0 to 4294967295 0 to 255 0 to 65535 0 to 4294967295

LWORD 0 to 18446744073709551645

SINT INT DINT LINT

BYTE WORD DWORD LWORD BYTE WORD DWORD LWORD BYTE WORD DWORD LWORD BYTE WORD DWORD
LWORD

-128 to 127
-128 to 127
-32768 to 32767
-128 to 127 -32768 to 32767 -2147483648 to 2147483647 -128 to 127 -32768 to 32767 -2147483648 to 2147483647 -9223372036854775808 to 9223372036854775807

Valid range for Out
16#00 to 16#FF
16#00 to 16#FF
16#0000 to 16#FFFF
16#00 to 16#FF 16#0000 to 16#FFFF 16#0000_0000 to 16#FFFF_FFFF 16#00 to 16#FF 16#0000 to 16#FFFF 16#0000_0000 to 16#FFFF_FFFF 16#0000_0000_0000_0000 to 16#FFFF_FFFF_FFFF_FFFF
16#00 to 16#FF
16#00 to 16#FF
16#0000 to 16#FFFF
16#00 to 16#FF 16#0000 to 16#FFFF 16#0000_0000 to 16#FFFF_FFFF 16#00 to 16#FF 16#0000 to 16#FFFF 16#0000_0000 to 16#FFFF_FFFF 16#0000_0000_0000_0000 to 16#FFFF_FFFF_FFFF_FFFF

Additional Information
· To convert a bit string to an integer, use a **_TO_*** (Bit String-to-Integer Conversion Group) instruction (page 2-270).
· To convert data with any data type to a bit string, use a TO_** (Bit String Conversion Group) instruction (page 2-308).

Precautions for Correct Use
· Always use the correct instruction name for the data types of In and Out. · If In is a signed integer and the data size of Out is larger than the data size of In, sign extension is
performed.

2-266

NJ/NX-series Instructions Reference Manual (W502)

Data Type Conversion Instructions

2 Instruction Descriptions
· If In is an unsigned integer and the data size of Out is larger than the data size of In, the upper digits of Out will contain 0.
· If the data size of Out is smaller than the data size of In, the upper digits are truncated in Out.
2

**_TO_*** (Integer-to-Bit String Conversion Group)

NJ/NX-series Instructions Reference Manual (W502)

2-267

2 Instruction Descriptions

**_TO_*** (Integer-to-Real Number Conversion Group)

These instructions convert integers to real numbers.

Instruction **_TO_***

Name
Integer-to-Real Number Conversion Group

FB/FUN FUN

Graphic expression

(@)**_TO_***

EN

ENO

In

Out

"**" must be an integer data type. "***" must be a real number data type.

ST expression
Out:=**_TO_*** (In);
"**" must be an integer data type. "***" must be a real number data type.

Variables

Name

Meaning

I/O

Description

Valid range

Unit

In

Data to

Input

Data to convert

*

---

convert

Out

Conversion Output

Conversion result

*

---

result

* The valid ranges depend on the data types of In and Out. Refer to Function, below, for details.

Default 0
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In

OK OK OK OK OK OK OK OK

Out

OK OK

Function

These instructions convert an integer, In, to a real number.
The name of the instruction is determined by the data types of In and conversion result Out. For example, if In is INT data and Out is REAL data, the name of the instruction is INT_TO_REAL.
The following example for the INT_TO_REAL instruction is for when In is INT#1234.

LD

ST

abc:=INT_TO_REAL(INT#1234);

INT_TO_REAL

EN INT#1234 In

ENO abc

2-268

NJ/NX-series Instructions Reference Manual (W502)

Data Type Conversion Instructions

**_TO_*** (Integer-to-Real Number Conversion Group)

2 Instruction Descriptions

INT data In INT#1234

REAL data Out=abc 1.234e+3

The following table shows the valid ranges for In and Out according to their data types.

Data type of In
USINT UINT UDINT ULINT SINT INT DINT
LINT

Data type of Out
REAL LREAL REAL LREAL REAL LREAL REAL LREAL REAL LREAL REAL LREAL REAL LREAL REAL
LREAL

Valid range for In 0 to 255 0 to 65535 0 to 4294967295 0 to 18446744073709551615 -128 to 127 -32768 to 32767 -2147483648 to 2147483647 -9223372036854775808 to 9223372036854775807

Valid range for Out

0 to 2.55e+2

0 to 6.5535e+4

0 to 4.294967e+9 0 to 4.294967295e+9

2

0 to 1.844674e+19

0 to 1.84467440737095e+19

-1.28e+2 to 1.27e+2

-3.2768e+4 to 3.2767e+4
-2.147483e+9 to 2.147483e+9 -2.147483648e+9 to 2.147483647e+9 -9.223372e+18 to 9.223372e+18 -9.22337203685477e+18 to 9.22337203685477e+18

Additional Information
· To convert a real number to an integer, use a **_TO_*** (Real Number-to-Integer Conversion Group) instruction (page 2-276).
· To convert data with any data type to a real number, use a TO_** (Real Number Conversion Group) instruction (page 2-310).

Precautions for Correct Use

· Always use the correct instruction name for the data types of In and Out.

· Depending on the data types of In and Out, rounding will be performed for the effective digits of the real number. This will cause error between the values before and after conversion. The following

table lists the data types that result in error.

Data type of In
DINT LINT UDINT ULINT
LINT
ULINT

Data type of Out
REAL
REAL
LREAL LREAL

Values for which error occurs
-16777216 or lower, or 16777216 or higher
16777216 or higher -9007199254740992 or lower, or 9007199254740992 or higher 9007199254740992 or higher

NJ/NX-series Instructions Reference Manual (W502)

2-269

2 Instruction Descriptions

**_TO_*** (Bit String-to-Integer Conversion Group)

These instructions convert bit strings to integers.

Instruction **_TO_***

Name
Bit String-to-Integer Conversion Group

FB/FUN FUN

Graphic expression

(@)**_TO_***

EN

ENO

In

Out

"**" must be a bit string data type. "***" must be an integer data type.

ST expression
Out:=**_TO_*** (In);
"**" must be a bit string data type. "***" must be an integer data type.

Variables

Name

Meaning

I/O

Description

Valid range

Unit

In

Data to

Input

Data to convert

*

---

convert

Out

Conversion Output

Conversion result

*

---

result

* The valid ranges depend on the data types of In and Out. Refer to Function, below, for details.

Default 0
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In

OK OK OK OK

Out

OK OK OK OK OK OK OK OK

Function

These instructions convert a bit string, In, to an integer.
The name of the instruction is determined by the data types of In and conversion result Out. For example, if In is WORD data and Out is INT data, the name of the instruction is WORD_TO_INT.
The following example for the WORD_TO_INT instruction is for when In is WORD #16#1234.

LD

ST

abc:=WORD_TO_INT(WORD#16#1234);

WORD_TO_INT

EN WORD#16#1234 In

ENO abc

2-270

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Data Type Conversion Instructions

**_TO_*** (Bit String-to-Integer Conversion Group)

WORD data In WORD#16#1234

Out=abc

INT data 4660

The following table shows the valid ranges for In and Out according to their data types.

Data type Data type

of In

of Out

Valid range for In

Valid range for Out

USINT

UINT UDINT

0 to 255

BYTE

ULINT SINT INT DINT

16#00 to 16#FF

-128 to 127

2

LINT

USINT

16#00 to 16#FF

0 to 255

UINT

UDINT

16#0000 to 16#FFFF

0 to 65535

WORD

ULINT SINT

16#00 to 16#FF

-128 to 127

INT

DINT

16#0000 to 16#FFFF

-32768 to 32767

LINT

USINT

16#00 to 16#FF

0 to 255

UINT

16#0000 to 16#FFFF

0 to 65535

DWORD

UDINT ULINT SINT

16#0000_0000 to 16#FFFF_FFFF 16#00 to 16#FF

0 to 4294967295 -128 to 127

INT

16#0000 to 16#FFFF

-32768 to 32767

DINT LINT

16#0000_0000 to 16#FFFF_FFFF

-2147483648 to 2147483647

USINT

16#00 to 16#FF

0 to 255

UINT

16#0000 to 16#FFFF

0 to 65535

UDINT

16#0000_0000 to 16#FFFF_FFFF

0 to 4294967295

LWORD

ULINT SINT

16#0000_0000_0000_0000 to 16#FFFF_FFFF_FFFF_FFFF
16#00 to 16#FF

0 to 18446744073709551645 -128 to 127

INT

16#0000 to 16#FFFF

-32768 to 32767

DINT

16#0000_0000 to 16#FFFF_FFFF

-2147483648 to 2147483647

LINT

16#0000_0000_0000_0000 to 16#FFFF_FFFF_FFFF_FFFF

-9223372036854775808 to 9223372036854775807

Additional Information
· To convert an integer to a bit string, use a **_TO_*** (Integer-to-Bit String Conversion Group) instruction (page 2-265).
· To convert data with any data type to a bit string, use a TO_** (Bit String Conversion Group) instruction (page 2-308).
Precautions for Correct Use
· Always use the correct instruction name for the data types of In and Out. · If the data size of Out is larger than the data size of In, the upper digits of Out will contain 0. · If the data size of Out is smaller than the data size of In, the upper digits are truncated in Out.

NJ/NX-series Instructions Reference Manual (W502)

2-271

2 Instruction Descriptions

**_TO_*** (Bit String-to-Bit String Conversion Group)

These instructions convert bit strings to bit strings with different data types.

Instruction **_TO_***

Name
Bit String-to-Bit String Conversion Group

FB/FUN FUN

Graphic expression

(@)**_TO_***

EN

ENO

In

Out

ST expression Out:=**_TO_*** (In);
"**" and "***" must be different bit string data types.

"**" and "***" must be different bit string data types.

Variables

Name In

Meaning
Data to convert

I/O Input

Description Data to convert

Valid range *

Unit
---

Out

Conversion Output

Conversion result

*

---

result

* The valid ranges depend on the data types of In and Out. Refer to Function, below, for details.

Default 0
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In

OK OK OK OK

Out

OK OK OK OK

Function

These instructions convert a bit string, In, to a bit string with a different data type.
The name of the instruction is determined by the data types of In and conversion result Out. For example, if In is WORD data and Out is DWORD data, the name of the instruction is WORD_TO_DWORD.
The following example for the WORD_TO_DWORD instruction is for when In is WORD#16#F123.

LD

ST

abc:=WORD_TO_DWORD(WORD#16#F123);

WORD_TO_DWORD

EN WORD#16#F123 In

ENO abc

2-272

NJ/NX-series Instructions Reference Manual (W502)

Data Type Conversion Instructions

2 Instruction Descriptions

WORD data In WORD#16#F123

DWORD data Out=abc 16#0000F123

The following table shows the valid ranges for In and Out according to their data types.

Data type Data type

of In

of Out

Valid range for In and Out

WORD

BYTE

DWORD 16#00 to 16#FF

LWORD

BYTE

16#00 to 16#FF

WORD

DWORD LWORD

16#0000 to 16#FFFF

2

BYTE

16#00 to 16#FF

DWORD WORD

16#0000 to 16#FFFF

LWORD 16#0000_0000 to 16#FFFF_FFFF

BYTE

16#00 to 16#FF

LWORD WORD

16#0000 to 16#FFFF

DWORD 16#0000_0000 to 16#FFFF_FFFF

Additional Information
To convert data with any data type to a bit string, use a TO_** (Bit String Conversion Group) instruction (page 2-308).

Precautions for Correct Use
· Always use the correct instruction name for the data types of In and Out. · If the data size of Out is larger than the data size of In, the upper digits of Out will contain 0. · If the data size of Out is smaller than the data size of In, the upper digits are truncated when the data
is output to Out.

**_TO_*** (Bit String-to-Bit String Conversion Group)

NJ/NX-series Instructions Reference Manual (W502)

2-273

2 Instruction Descriptions

**_TO_*** (Bit String-to-Real Number Conversion Group)

These instructions convert bit strings to real numbers.

Instruction **_TO_***

Name
Bit String-to-Real Number Conversion Group

FB/FUN FUN

Graphic expression

(@)**_TO_***

EN

ENO

In

Out

"**" must be a bit string data type. "***" must be a real number data type.

ST expression
Out:=**_TO_*** (In);
"**" must be a bit string data type. "***" must be a real number data type.

Variables

Name

Meaning

I/O

Description

Valid range

Unit

In

Data to

Input

Data to convert

*

---

convert

Out

Conversion Output

Conversion result

*

---

result

* The valid ranges depend on the data types of In and Out. Refer to Function, below, for details.

Default 0
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In

OK OK OK OK

Out

OK OK

Function

These instructions take a bit string, In, as an unsigned integer of the same size and convert it to a real number.
The name of the instruction is determined by the data types of In and conversion result Out. For example, if In is WORD data and Out is REAL data, the name of the instruction is WORD_TO_REAL.
The following example for the WORD_TO_REAL instruction is for when In is WORD#16#8000.

LD

ST

abc:=WORD_TO_REAL(WORD#16#8000);

WORD_TO_REAL

EN WORD#16#8000 In

ENO abc

2-274

NJ/NX-series Instructions Reference Manual (W502)

Data Type Conversion Instructions

**_TO_*** (Bit String-to-Real Number Conversion Group)

2 Instruction Descriptions

WORD data In WORD#16#8000

REAL data Out=abc 3.2768e+4

The following table shows the valid ranges for In and Out according to their data types.

Data type of
In

Data type of Out

Valid range for In

Valid range for Out

BYTE

REAL LREAL

16#00 to 16#FF

0 to 2.55e+2

WORD

REAL LREAL

16#0000 to 16#FFFF

0 to 6.5535e+4

DWORD

REAL LREAL

16#0000_0000 to 16#FFFF_FFFF

0 to 4.294967e+9 0 to 4.294967295e+9

2

LWORD

REAL LREAL

16#0000_0000_0000_0000 to 16#FFFF_FFFF_FFFF_FFFF

0 to 1.844674e+19 0 to 1.84467440737095e+19

Additional Information
· To convert a real number to a bit string, use a **_TO_*** (Real Number-to-Bit String Conversion Group) instruction (page 2-279).
· To convert data with any data type to a real number, use a TO_** (Real Number Conversion Group) instruction (page 2-310).

Precautions for Correct Use

· Always use the correct instruction name for the data types of In and Out.

· Depending on the data types of In and Out, rounding will be performed for the effective digits of the real number. This will cause error between the values before and after conversion. The following table lists the data types that result in error.

Data type of In
DWORD
LWORD

Data type of Out
REAL
LREAL

Values for which error occurs
16#0100_0000 or higher 16#0002_0000_0000_0000 or higher

NJ/NX-series Instructions Reference Manual (W502)

2-275

2 Instruction Descriptions

**_TO_*** (Real Number-to-Integer Conversion Group)

These instructions convert real numbers to integers.

Instruction **_TO_***

Name
Real Number-toInteger Conversion Group

FB/FUN FUN

Graphic expression

(@)**_TO_***

EN

ENO

In

Out

"**" must be a real number data type. "***" must be an integer data type.

ST expression
Out:=**_TO_*** (In);
"**" must be a real number data type. "***" must be an integer data type.

Variables

Name In

Meaning
Data to convert

I/O Input

Description Data to convert

Valid range *

Unit
---

Out

Conversion Output

Conversion result

*

---

result

* The valid ranges depend on the data types of In and Out. Refer to Function, below, for details.

Default 0
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In

OK OK

Out

OK OK OK OK OK OK OK OK

Function

These instructions convert a real number, In, to an integer.
The name of the instruction is determined by the data types of In and conversion result Out. For example, if In is LREAL data and Out is LINT data, the name of the instruction is LREAL_TO_LINT.
The following example for the LREAL_TO_LINT instruction is for when In is LREAL#1.0e+10.

LD

ST

abc:=LREAL_TO_LINT(LREAL#1.0e+10);

LREAL_TO_LINT

EN LREAL#1.0e+10 In

ENO abc

2-276

NJ/NX-series Instructions Reference Manual (W502)

Data Type Conversion Instructions

**_TO_*** (Real Number-to-Integer Conversion Group)

2 Instruction Descriptions

LREAL data In LREAL#1.0e+10

LINT data Out=abc 10000000000

The fractional part of the value of In is rounded off to the closest integer. The following table shows how values are rounded.

Value of fractional
part

Treatment

Examples

Less than The fractional part is truncated. 0.5

1.49  1 -1.49  -1

0.5

If the ones digit is an even number, the fractional part 1.50  2

is truncated. If it is an odd number, the value is

2.50  2

2

rounded up.

-1.50  -2

-2.50  -2

Greater than 0.5

The fractional part is rounded up.

1.51  2 -1.51  -2

The following table shows the valid ranges for In and Out according to their data types.

Data type of In
REAL

Data type of Out
USINT UINT UDINT ULINT SINT INT DINT LINT

Valid range for In
0 to 2.55e+2 0 to 6.5535e+4 0 to 4.294967e+9 0 to 1.844674e+19 -1.28e+2 to 1.27e+2 -3.2768e+4 to 3.2767e+4 -2.147483e+9 to 2.147483e+9 -9.223372e+18 to 9.223372e+18

LREAL

USINT UINT UDINT ULINT SINT INT DINT LINT

0 to 0.255e+3 0 to 6.5535e+4 0 to 4.294967295e+9 0 to 1.84467440737095e+19 -1.28e+2 to 1.27e+2 -3.2768e+4 to 3.2767e+4 -2.147483648e+9 to 2.147483647e+9 -9.22337203685477e+18 to 9.22337203685477e+18

Valid range for Out
0 to 255 0 to 65535 0 to 4294967295 0 to 18446744073709551615 -128 to 127 -32768 to 32767 -2147483648 to 2147483647 -9223372036854775808 to 9223372036854775807 0 to 255 0 to 65535 0 to 4294967295 0 to 18446744073709551615 -128 to 127 -32768 to 32767 -2147483648 to 2147483647 -9223372036854775808 to 9223372036854775807

NJ/NX-series Instructions Reference Manual (W502)

2-277

2 Instruction Descriptions

Additional Information

· To convert an integer to a real number, use an Integer-to-Real Number Conversion Group Instruction.
· To convert data with any data type to an integer, use an Integer Conversion Group Instruction.
· You can use the following instructions to convert a real number to an integer: TRUNC (Truncate), Round (Round Off Real Number), and RoundUp (Round Up Real Number). All of these instructions have a REAL input and DINT output, or a LREAL input and LINT output. The differences between these instructions are shown in the following table.

Input value REAL_TO_INT
REAL#1.6 INT#2

Output value

TRUNC

Round

DINT#1

DINT#2

RoundUp DINT#2

REAL#1.5 INT#2

DINT#1

DINT#2

DINT#2

REAL#1.5 REAL#2.5

INT#1 INT#2

DINT#1 DINT#2

DINT#1 DINT#2

DINT#2 DINT#3

REAL#-1.6 INT#-2

DINT#-1

DINT#-2

DINT#-2

REAL#-1.5 INT#-2

DINT#-1

DINT#-2

DINT#-2

REAL#-1.4 INT#-1

DINT#-1

DINT#-1

DINT#-2

REAL#-2.5 INT#-2

DINT#-2

DINT#-2

DINT#-3

Precautions for Correct Use
· Always use the correct instruction name for the data types of In and Out. · If the conversion result exceeds the valid range of Out, Out will contain an undefined value. Always
make sure that the value of In is within the valid range so that the conversion result will not exceed the valid range of Out.

2-278

NJ/NX-series Instructions Reference Manual (W502)

Data Type Conversion Instructions

**_TO_*** (Real Number-to-Bit String Conversion Group)

2 Instruction Descriptions

**_TO_*** (Real Number-to-Bit String Conversion Group)

These instructions convert real numbers to bit strings.

Instruction

Name

FB/FUN

Graphic expression

ST expression

**_TO_***

Real Number-to- FUN Bit String Conversion Group

(@)**_TO_***

Out:=**_TO_*** (In);

EN

ENO

In

Out

"**" must be a real number

2

data type.

"**" must be a real number data type. "***" must be a bit string data type.

"***" must be a bit string data type.

Variables

Name In
Out

Meaning
Data to convert
Conversion result

I/O Input
Output

Description Data to convert
Conversion result

Valid range

Unit

Depends on data type. ---

Depends on data type. ---

Default 0
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In

Out

OK OK OK OK

OK OK

Function

These instructions convert a real number, In, to a bit string.
The name of the instruction is determined by the data types of In and conversion output Out. For example, if In is LREAL data and Out is DWORD data, the name of the instruction is LREAL_TO_DWORD.
The following example for the LREAL_TO_DWORD instruction is for when In is LREAL#6.5536e+4.

LD

ST

abc:=LREAL_TO_DWORD(LREAL#6.5536e+4);

LREAL_TO_DWORD

EN LREAL#6.5536e+4 In

ENO abc

NJ/NX-series Instructions Reference Manual (W502)

2-279

2 Instruction Descriptions

LREAL data In LREAL#6.5536e+4

DWORD data Out=abc 16#0001_0000

Conversion is performed using the following procedure.
1 The fractional part of the value of In is rounded off to the closest integer as described below.
2 The resulting integer is taken as an unsigned integer and output as a bit string.

The following table shows how values are rounded.

Value of fractional part Less than 0.5 0.5
Greater than 0.5

Treatment
The fractional part is truncated. If the ones digit is an even number, the fractional part is truncated. If it is an odd number, the value is rounded up. The fractional part is rounded up.

Examples
1.49  1 1.50  2 2.50  2
1.51  2

The following table gives some conversion examples.

Value of In
1.6 3.5

Integer
2 4

Value of Out
16#0002
16#0004

Additional Information
To convert a bit string to a real number, use a **_TO_*** (Bit String-to-Real Number Conversion Group) instruction (page 2-274).

Precautions for Correct Use
· Always use the correct instruction name for the data types of In and Out. · If the conversion result exceeds the valid range of Out, Out will contain an undefined value. Always
make sure that the value of In is within the valid range so that the conversion result will not exceed the valid range of Out. · When you input a negative value, the conversion result depends on the CPU Unit model. If you input a negative value, sufficiently debug before use.

2-280

NJ/NX-series Instructions Reference Manual (W502)

Data Type Conversion Instructions

**_TO_*** (Real Number-to-Real Number Conversion Group)

2 Instruction Descriptions

**_TO_*** (Real Number-to-Real Number Conversion Group)

These instructions convert real numbers to real numbers with different data types.

Instruction

Name

FB/FUN

Graphic expression

ST expression

**_TO_***

Real Number-toReal Number Conversion Group

FUN

(@)**_TO_***

Out:=**_TO_*** (In);

EN

ENO

In

Out

"**" and "***" must be dif-

2

ferent real number data

"**" and "***" must be different real

types.

number data types.

Variables

Name In

Meaning
Data to convert

I/O Input

Description Data to convert

Valid range *

Unit
---

Out

Conversion Output

Conversion result

*

---

result

* The valid ranges depend on the data types of In and Out. Refer to Function, below, for details.

Default 0
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In

OK OK

Out

OK OK

Function

These instructions convert a real number, In, to a real number with a different data type.
The name of the instruction is determined by the data types of In and conversion result Out. For example, if In is REAL data and Out is LREAL data, the name of the instruction is REAL_TO_LREAL.
The following example for the REAL_TO_LREAL instruction is for when In is REAL#3.141592e+0.

LD

ST

abc:=REAL_TO_LREAL(REAL#3.141592e+0);

REAL_TO_LREAL

EN REAL#3.141592e+0 In

ENO abc

NJ/NX-series Instructions Reference Manual (W502)

2-281

2 Instruction Descriptions

REAL data In REAL#3.141592e+0

LREAL data Out=abc 3.141592e+0

The following table shows the valid ranges for In and Out according to their data types.

Data type of In REAL LREAL

Data type of Out LREAL REAL

Valid range for In and Out
-3.402823e+38 to 3.402823e+38 or +/-

Additional Information
To convert data with any data type to a real number, use a TO_** (Real Number Conversion Group) instruction (page 2-310).

Precautions for Correct Use
· Always use the correct instruction name for the data types of In and Out. · If the value of In is positive or negative infinity, the value of Out is positive or negative infinity. · If the value of In is nonnumeric data, the value of Out is nonnumeric data. · If the conversion result exceeds the valid range of Out, the value of Out will be infinity with the same
sign as the value of In. · For the LREAL_TO_REAL instruction, if the value of In is closer to 0 than ±1.175494e-38, the value
of Out will be 0.

2-282

NJ/NX-series Instructions Reference Manual (W502)

Data Type Conversion Instructions

**_TO_STRING (Integer-to-Text String Conversion Group)

2 Instruction Descriptions

**_TO_STRING (Integer-to-Text String Conversion Group)

These instructions convert integers to text strings.

Instruction **_TO_STRING

Name
Integer-to-Text String Conversion Group

FB/FUN FUN

Graphic expression

ST expression

(@)**_TO_STRING

Out:=**_TO_STRING(In);

EN In

ENO

Out

"**" must be an integer data type.

2

"**" must be an integer data type.

Variables

Name

Meaning

I/O

Description

Valid range

Unit

In

Data to

Input

Data to convert

convert

Out

Conversion Output

Conversion result

result

Depends on data type. ---

*

---

* The valid range depends on the data type of In. Refer to Function for details.

Default 0
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In

OK OK OK OK OK OK OK OK

Out

OK

Function
These instructions convert an integer, In, to a text string. The number given in In is output to conversion result Out as a text string. A NULL character (16#00) is placed at the end of Out. The text in Out is left-aligned. If the value in In requires fewer digits than provided by the data type of In, zeros will not be output to the upper digits of Out. In other words, leading zeros are suppressed. If In contains a negative value, a minus sign (-) is added to the front of the text string. The name of the instruction is determined by the data type of In. For example, if In is the INT data type, the instruction is INT_TO_STRING.

NJ/NX-series Instructions Reference Manual (W502)

2-283

2 Instruction Descriptions

The following example for the INT_TO_STRING instruction is for when In is INT#1234.

LD

ST

abc:=INT_TO_STRING(INT#1234);

INT_TO_STRING

EN INT#1234 In

ENO abc

INT data In INT#1234

STRING data Out=abc `1234'

The valid range of Out depends on the data type of In as shown below:

Data type of In

Valid range of Out (maximum number of bytes)

USINT

4 bytes (three single-byte alphanumeric characters plus the final NULL character)

UINT

6 bytes (five single-byte alphanumeric characters plus the final NULL character)

UDINT

11 bytes (10 single-byte alphanumeric characters plus the final NULL character)

ULINT

21 bytes (20 single-byte alphanumeric characters plus the final NULL character)

SINT

5 bytes (four single-byte alphanumeric characters plus the final NULL character)

INT

7 bytes (six single-byte alphanumeric characters plus the final

NULL character)

DINT

12 bytes (11 single-byte alphanumeric characters plus the final NULL character)

LINT

21 bytes (20 single-byte alphanumeric characters plus the final NULL character)

Additional Information
To convert a text string number to an integer, use a STRING_TO_** (Text String-to-Integer Conversion Group) instruction (page 2-299).

Precautions for Correct Use
· Always use the correct instruction name for the data type of In.

2-284

NJ/NX-series Instructions Reference Manual (W502)

Data Type Conversion Instructions

**_TO_STRING (Bit String-to-Text String Conversion Group)

2 Instruction Descriptions

**_TO_STRING (Bit String-to-Text String Conversion Group)

These instructions convert bit strings to text strings.

Instruction **_TO_STRING

Name
Bit String-to-Text String Conversion Group

FB/FUN FUN

Graphic expression

ST expression

(@)**_TO_STRING

Out:=**_TO_STRING(In);

EN In

ENO Out

"**" must be a bit string data type.

2

"**" must be a bit string data type.

Variables

Name

Meaning

I/O

Description

Valid range

Unit

In

Data to

Input

Data to convert

convert

Out

Conversion Output

Conversion result

result

Depends on data type. ---

*

---

* The valid range depends on the data type of In. Refer to Function for details.

Default 0
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In

OK OK OK OK

Out

OK

Function
These instructions convert a bit string, In, to a text string. The hexadecimal number given in In is output to conversion result Out as a text string. The #16 prefix of the hexadecimal number is not output to Out. A NULL character (16#00) is placed at the end of Out.
The text in Out is left-aligned. If the value in In requires fewer digits than provided by the data type of In, the upper digits of Out will contain 0. In other words, the unused digits are padded with zeros. The number of bytes in Out (including the NULL character) will always be one greater than twice the number of bytes in In.
The name of the instruction is determined by the data type of In. For example, if In is the WORD data type, the instruction is WORD_TO_STRING.

NJ/NX-series Instructions Reference Manual (W502)

2-285

2 Instruction Descriptions

The following example for the WORD_TO_STRING instruction is for when In is WORD#16#1F.

LD

ST

abc:=WORD_TO_STRING(WORD#16#1F);

WORD_TO_STRING

EN WORD#16#1F In

ENO abc

WORD data In WORD#16#1F

STRING data Out=abc `001F'

The valid range of Out depends on the data type of In as shown below:

Data type of In BYTE

Valid range of Out (maximum number of bytes)
3 bytes (two single-byte alphanumeric characters plus the final NULL character)

WORD

5 bytes (four single-byte alphanumeric characters plus the final NULL character)

DWORD

9 bytes (eight single-byte alphanumeric characters plus the final NULL character)

LWORD

17 bytes (16 single-byte alphanumeric characters plus the final NULL character)

Additional Information
To convert In to a signed text string, first convert it to a signed integer using a **_TO_*** (Bit String-toInteger Conversion Group) instruction (page 2-270) and then use a **_TO_STRING (Integer-to-Text String Conversion Group) instruction (page 2-283).

Precautions for Correct Use
· Always use the correct instruction name for the data type of In.

2-286

NJ/NX-series Instructions Reference Manual (W502)

Data Type Conversion Instructions

**_TO_STRING (Real Number-to-Text String Conversion Group)

2 Instruction Descriptions

**_TO_STRING (Real Number-toText String Conversion Group)

These instructions convert real numbers to text strings.

Instruction **_TO_STRING

Name
Real Number-toText String

FB/FUN FUN

Graphic expression (@)**_TO_STRING

ST expression Out:=**_TO_STRING(In);

2

Conversion Group

EN In

ENO Out

"**" must be a real number data type.

"**" must be a real number data type.

Variables

Name In
Out

Meaning
Data to convert
Conversion result

I/O Input
Output

Description Data to convert
Conversion result

Valid range

Unit

Depends on

---

data type.

*

---

* The valid range depends on the data type of In. Refer to Function for details.

Default 0.0
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In

OK OK

Out

OK

Function

These instructions convert a real number, In, to a text string. In is expressed as an alphanumeric text string and output to conversion result Out.
The format of Out is as follows:

- i . ffffff e+nn Fractional part Exponent

Sign column

Decimal point

Integer part

NJ/NX-series Instructions Reference Manual (W502)

2-287

2 Instruction Descriptions

Item Sign column
Integer part Decimal point Fractional part Exponent

Description
If In contains a negative value, a minus sign (-) is added. If In contains a positive value, a plus sign (+) is not added.
The integer part is always only one digit.
The decimal point is always given even if In is not a decimal number.
If In is REAL data, 6 digits are given. If In is LREAL data, 14 digits are given.
The exponent is always given. "nn" is 2 or 3 digits. The sign of "nn" is positive (+) if the absolute value of In is 1.0 or higher and negative (-) if it is less than 1.0.

A NULL character (16#00) is placed at the end of Out.
The name of the instruction is determined by the data type of In. For example, if In is the REAL data type, the instruction is REAL_TO_STRING.
The following example shows the REAL_TO_STRING instruction when In is REAL#-1234.567.

LD

ST

abc:=REAL_TO_STRING(REAL#-1234.567);

REAL_TO_STRING

EN REAL#-1234.567 In

ENO abc

REAL Data

STRING Data

In REAL#-1234.567

Out=abc `-1.234567e+03'

If the value of In is 0, infinity, or nonnumeric data, the value of Out is as shown below.

Value of In

Value of Out

0

0

+

inf

-

-inf

Nonnumeric data `nan' or `-nan'

Additional Information
· To convert a text string to a real number, use a STRING_TO_** (Text String-to-Real Number Conversion Group) instruction (page 2-303).
· To specify the format when you convert a real number to a text string, use the RealToFormatString instruction (page 2-289) or the LrealToFormatString instruction (page 2-294).

Precautions for Correct Use
· Always use the correct instruction name for the data type of In.

2-288

NJ/NX-series Instructions Reference Manual (W502)

Data Type Conversion Instructions

RealToFormatString

2 Instruction Descriptions

RealToFormatString

The RealToFormatString instruction converts a REAL variable to a text string with the specified format.

Instruction RealToFormatString

Name
REAL-to-Formatted Text String

FB/FUN FUN

Graphic expression

ST expression

(@)RealToFormatString

EN

ENO

In

Out:=RealToFormatString(In, Exponent, Sign, Out MinLen, DecPlace);

Exponent

Sign

MinLen

2

DecPlace

Variables

Name

Meaning

I/O

Description

Valid range

Unit

In

Data to

convert

Data to convert

Exponent Exponent

TRUE: Exponent

Sign

Sign column Input

FALSE: No exponent TRUE: Sign column FALSE: No sign column

Depends on

data type.

---

MinLen

Minimum number of digits

Minimum number of digits in Out

DecPlace Precision

Number of decimal digits in Out 0 to 15

Out

Conversion Output Conversion result

result

327 bytes max. --(326 single-byte alphanumeric characters plus the final NULL character)

Default 0.0
FALSE
6
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In

Exponent OK

Sign

OK

MinLen

OK

DecPlace

OK

Out

OK OK

Function
The RealToFormatString instruction converts REAL variable In to a text string. In is expressed as an alphanumeric text string and output to conversion result Out. A NULL character (16#00) is placed at the end of Out.

NJ/NX-series Instructions Reference Manual (W502)

2-289

2 Instruction Descriptions

If In contains a negative value, a minus sign (-) is added to the front of the text string. If In contains a positive value, a plus sign (+) is not added to the front of the text string. The format of Out is determined by exponent Exponent, sign column Sign, minimum number of digits MinLen, and precision DecPlace.
Minimum number of digits

- iiii . ffffffff e+nn

Integer part Fractional part Exponent

Sign column

Decimal point

Input variable Exponent Sign
MinLen
DecPlace

Description
Exp specifies whether an exponent is given.
TRUE: Exponent
FALSE: No exponent
Sign specifies whether there is a sign column.
TRUE: Sign column
FALSE: No sign column
The sign column is used only for a minus sign (-). If the number is positive when the sign column is specified, the sign column will contain a blank character. If the number is negative when no sign column is specified, a minus sign (-) will be added to the front of the integer part.
However, if the number of digits in the conversion result exceeds the value of MinLen and the conversion result is positive, the highest digit is placed in the sign column.
MinLen is the minimum number of total digits for the sign column, integer part, decimal point, fractional part, and exponent.
If the conversion result has fewer digits than the value of MinLen, the text string will be right-aligned (except for the sign column) and remaining digits will contain blank characters. If the number of digits in the conversion result exceeds the value of MinLen, the text string is left-aligned and the text string for the digits that exceed the value of MinLen is assigned to Out.
DecPlace is the number of digits in the fractional part.
If the number of digits exceeds the value of DecPlace, the extra digits in the fractional portion are rounded off as described below. If the value of DecPlace is 0, the fractional part and decimal point are not given.

The following examples show the relationships between the values of the input variables and the value of Out when In is REAL#-1234.567.

Example 1: Exponent: FALSE Sign: FALSE MinLen: USINT#16 DecPlace: USINT#10

2-290

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Data Type Conversion Instructions

RealToFormatString

Here, no sign column is specified for a negative number, so a minus sign (-) is added to the front of the integer part.

LD

ST

RealToFormatString

REAL#-1234.567
FALSE FALSE USINT#16 USINT#10

EN In Exponent Sign MinLen DecPlace

ENO abc

16

abc:=RealToFormatString(REAL#-1234.567, FALSE, FALSE, USINT#16, USINT#10);
2

-1234 . 5670000000 10

Example 2: Exponent: TRUE Sign: FALSE MinLen: USINT#21 DecPlace: USINT#10
Here, the value of MinLen exceeds the number of digits in the text string, so the text string is rightaligned and blank characters are added before it.
21
-1 . 2345670000 e+03
10

Example 3: Exponent: TRUE Sign: TRUE MinLen: USINT#22 DecPlace: USINT#10
The sign column is always on the left. Blank characters are added to the front of the integer part.
22

-

1 . 2345670000 e+03

10

Example 4: Exponent: TRUE Sign: TRUE MinLen: USINT#12 DecPlace: USINT#3
The fourth decimal place is rounded off because DecPlace is USINT#3.
12
- 1 . 235 e+03
3

NJ/NX-series Instructions Reference Manual (W502)

2-291

2 Instruction Descriptions

Example 5: Exponent: TRUE Sign: TRUE MinLen: USINT#12 DecPlace: USINT#0
The first decimal place is rounded off because DecPlace is USINT#0. The decimal point is also not given.
12

-

1 e+03

Example 6: Exponent: FALSE Sign: TRUE MinLen: USINT#8 DecPlace: USINT#0
Here, no exponent is given and the integer part is only four digits. The first decimal place is rounded off.
8

-

1 2 3 5

Example 7: Exponent: FALSE Sign: TRUE MinLen: USINT#2 DecPlace: USINT#0
Here, the number of digits in the integer part of In (four digits) is larger than the value of MinLen (USINT#2). The four digits of the integer part are given.
5
- 1235

The following examples show the relationships between the values of the input variables and the value of Out when In is REAL#123456.7.
Example 8: Exponent: FALSE Sign: TRUE MinLen: USINT#4 DecPlace: USINT#0
Here, the number of digits in the integer part of In (six digits) is larger than the value of MinLen (USINT#4). The six digits of the integer part are given. The value of In is positive, so the highest digit is placed in the sign column.
6

1 23457

If the value of In is infinity, or nonnumeric data, the value of Out is as shown below.

Value of In + - Nonnumeric data

Value of Out `inf' `-inf' `nan' or `-nan'

2-292

NJ/NX-series Instructions Reference Manual (W502)

Data Type Conversion Instructions

2 Instruction Descriptions

The following table shows how values are rounded.

Value of fractional
part Less than 0.5 0.5
Greater than 0.5

Treatment
The fractional part is truncated.
If the ones digit is an even number, the fractional part is truncated. If it is an odd number, the value is rounded up. The fractional part is rounded up.

Examples
1.49  1
1.50  2 2.50  2 1.51  2

2 Additional Information

· Exponent, Sign, MinLen, and DecPlace can be omitted. The defaults are applied for any omitted input variables.
· To convert a LREAL variable to a text string, use the LrealToFormatString instruction (page 2-294).
· To convert a text string to a real number, use a STRING_TO_** (Text String-to-Real Number Conversion Group) instruction (page 2-303).

Precautions for Correct Use
An error occurs in the following cases. ENO will be FALSE, and Out will not change. · The value of DecPlace is outside of the valid range. · The value of DecPlace is greater than the value of MinLen.

RealToFormatString

NJ/NX-series Instructions Reference Manual (W502)

2-293

2 Instruction Descriptions

LrealToFormatString

The LrealToFormatString instruction converts a LREAL variable to a text string with the specified format.

Instruction
LrealToFormatStrin g

Name
LREAL-toFormatted Text String

FB/FUN FUN

Graphic expression

(@)LrealToFormatString

EN In Exponent Sign MinLen DecPlace

ENO

ST expression
Out:=LrealToFormatString (In, Exponent, Sign, Out MinLen, DecPlace);

Variables

Name

Meaning

I/O

Description

Valid range

Unit

In

Data to

convert

Data to convert

Exponent Exponent

TRUE: Exponent

Sign

Sign column Input

FALSE: No exponent TRUE: Sign column FALSE: No sign column

Depends on

data type.

---

MinLen

Minimum number of digits

Minimum number of digits in Out

DecPlace Precision

Number of decimal digits in Out 0 to 15

Out

Conversion Output Conversion result

result

327 bytes max. --(326 single-byte alphanumeric characters plus the final NULL character)

Default 0.0
FALSE
6
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In

Exponent OK

Sign

OK

MinLen

OK

DecPlace

OK

Out

OK OK

2-294

NJ/NX-series Instructions Reference Manual (W502)

Data Type Conversion Instructions

LrealToFormatString

2 Instruction Descriptions

Function
The LrealToFormatString instruction converts LREAL variable In to a text string. In is expressed as an alphanumeric text string and output to conversion result Out. A NULL character (16#00) is placed at the end of Out. If In contains a negative value, a minus sign (-) is added to the front of the text string. If In contains a positive value, a plus sign (+) is not added to the front of the text string. The format of Out is determined by exponent Exponent, sign column Sign, minimum number of digits MinLen, and precision DecPlace.
Minimum number of digits
2
- iiii . ffffffff e+nn
Integer part Fractional part Exponent Sign column Decimal point

Input variable Exponent Sign
MinLen
DecPlace

Description
Exp specifies whether an exponent is given.
TRUE: Exponent
FALSE: No exponent
Sign specifies whether there is a sign column.
TRUE: Sign column
FALSE: No sign column
The sign column is used only for a minus sign (-). If the number is positive when the sign column is specified, the sign column will contain a blank character. If the number is negative when no sign column is specified, a minus sign (-) will be added to the front of the integer part.
However, if the number of digits in the conversion result exceeds the value of MinLen and the conversion result is positive, the highest digit is placed in the sign column.
MinLen is the minimum number of total digits for the sign column, integer part, decimal point, fractional part, and exponent.
If the conversion result has fewer digits than the value of MinLen, the text string will be right-aligned (except for the sign column) and remaining digits will contain blank characters. If the number of digits in the conversion result exceeds the value of MinLen, the text string is left-aligned and the text string for the digits that exceed the value of MinLen is assigned to Out.
DecPlace is the number of digits in the fractional part.
If the number of digits exceeds the value of DecPlace, the extra digits in the fractional portion are rounded off as described below. If the value of DecPlace is 0, the fractional part and decimal point are not given.

The following examples show the relationships between the values of the input variables and the value of Out when In is LREAL#-1234.56789.

Example 1: Exponent: FALSE Sign: FALSE MinLen: USINT#16 DecPlace: USINT#10

NJ/NX-series Instructions Reference Manual (W502)

2-295

2 Instruction Descriptions

Here, no sign column is specified for a negative number, so a minus sign (-) is added to the front of the integer part.

LD

ST

LrealToFormatString

LREAL#-1234.56789
FALSE FALSE USINT#16 USINT#10

EN In Exponent Sign MinLen DecPlace

ENO abc

abc:=LrealToFormatString(LREAL#-1234.56789, FALSE, FALSE, USINT#16, USINT#10);

16 -1234 . 5678900000
10

Example 2: Exponent: TRUE Sign: FALSE MinLen: USINT#21 DecPlace: USINT#10
Here, the value of MinLen exceeds the number of digits in the text string, so the text string is rightaligned and blank characters are added before it.
21
-1 . 2345678900 e+03
10

Example 3: Exponent: TRUE Sign: TRUE MinLen: USINT#22 DecPlace: USINT#10
The sign column is always on the left. Blank characters are added to the front of the integer part.
22

-

1 . 2345678900 e+03

10

Example 4: Exponent: TRUE Sign: TRUE MinLen: USINT#12 DecPlace: USINT#3
The fourth decimal place is rounded off because DecPlace is USINT#3.
12
- 1 . 235 e+03
3

2-296

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Data Type Conversion Instructions

LrealToFormatString

Example 5: Exponent: TRUE Sign: TRUE MinLen: USINT#12 DecPlace: USINT#0
The first decimal place is rounded off because DecPlace is USINT#0. The decimal point is also not given.
12

-

1 e+03

2
Example 6: Exponent: FALSE Sign: TRUE MinLen: USINT#8 DecPlace: USINT#0
Here, no exponent is given and the integer part is only four digits. The first decimal place is rounded off.
8

-

1 2 3 5

Example 7: Exponent: FALSE Sign: TRUE MinLen: USINT#2 DecPlace: USINT#0
Here, the number of digits in the integer part of In (four digits) is larger than the value of MinLen (USINT#2). The four digits of the integer part are given.
5
- 1235

The following examples show the relationships between the values of the input variables and the value of Out when In is LREAL#123456.789.
Example 8: Exponent: FALSE Sign: TRUE MinLen: USINT#4 DecPlace: USINT#0
Here, the number of digits in the integer part of In (six digits) is larger than the value of MinLen (USINT#4). The six digits of the integer part are given. The value of In is positive, so the highest digit is placed in the sign column.
6

1 23457

If the value of In is infinity, or nonnumeric data, the value of Out is as shown below.

Value of In + - Nonnumeric data

Value of Out `inf' `-inf' `nan' or `-nan'

NJ/NX-series Instructions Reference Manual (W502)

2-297

2 Instruction Descriptions

The following table shows how values are rounded.

Value of fractional
part Less than 0.5 0.5
Greater than 0.5

Treatment
The fractional part is truncated.
If the ones digit is an even number, the fractional part is truncated. If it is an odd number, the value is rounded up. The fractional part is rounded up.

Examples
1.49  1
1.50  2 2.50  2 1.51  2

Additional Information
· Exponent, Sign, MinLen, and DecPlace can be omitted. The defaults are applied for any omitted input variables.
· To convert a REAL variable to a text string, use the RealToFormatString instruction (page 2-289). · To convert a text string to a real number, use a STRING_TO_** (Text String-to-Real Number Conver-
sion Group) instruction (page 2-303).

Precautions for Correct Use
An error occurs in the following cases. ENO will be FALSE, and Out will not change. · The value of DecPlace is outside of the valid range. · The value of DecPlace is greater than the value of MinLen.

2-298

NJ/NX-series Instructions Reference Manual (W502)

Data Type Conversion Instructions

2 Instruction Descriptions

STRING_TO_** (Text String-toInteger Conversion Group)

These instructions convert text strings to integers.

Instruction STRING_TO_**

Name
Text String-toInteger Conversion Group

FB/FUN FUN

Graphic expression

ST expression

(@)STRING_TO_**

Out:=STRING_TO_** (In);

EN In

ENO

Out

"**" must be an integer data type.

2

"**" must be an integer data type.

Variables

Name

Meaning

I/O

Description

Valid range

Unit

In

Data to

Input

Data to convert

convert

Out

Conversion Output

Conversion result

result

*

---

Depends on data type. ---

* The valid range depends on the data type of Out. Refer to Function for details.

Default ''
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

STRING_TO_** (Text String-to-Integer Conversion Group)

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In

OK

Out

OK OK OK OK OK OK OK OK

Function
These instructions convert a text string, In, to an integer. Basically, the text string in In must consist only of numbers 0 to 9. The following exceptions are possible. · If the first character in In is a single minus sign (-) or a single plus sign (+), it is processed as the sign. · Any blank characters at the beginning of In are ignored. · Any blank characters between an initial minus sign (-) or plus sign (+) and a number are ignored. · Any single underbars (`_') at any location are ignored. · An error occurs if there are two or more consecutive underbars (`_') at any location. · An error occurs if there are any underbars (`_') at the beginning or end. · An error occurs if there are any underbars (`_') between the minus signs (`-') or plus sign (`+') and the
number at the beginning. The name of the instruction is determined by the data type of conversion result Out. For example, if Out is the DINT data type, the instruction is STRING_TO_DINT.

NJ/NX-series Instructions Reference Manual (W502)

2-299

2 Instruction Descriptions

The following example for the STRING_TO_DINT instruction is for when In is `123456789'.

LD

ST

abc:=STRING_TO_DINT(`123456789');

STRING_TO_DINT

EN `123456789' In

ENO abc

STRING data In `123456789'

DINT data Out=abc 123456789

The valid range of In depends on the data type of Out as shown below:

Data type of Out

Valid range of In (maximum number of bytes)*

USINT

4 bytes (three single-byte alphanumeric characters plus the final NULL character)

UINT

6 bytes (five single-byte alphanumeric characters plus the final NULL character)

UDINT

11 bytes (10 single-byte alphanumeric characters plus the final NULL character)

ULINT

21 bytes (20 single-byte alphanumeric characters plus the final NULL character)

SINT INT

5 bytes (four single-byte alphanumeric characters plus the final NULL character)
7 bytes (six single-byte alphanumeric characters plus the final NULL character)

DINT

12 bytes (11 single-byte alphanumeric characters plus the final NULL character)

LINT

21 bytes (20 single-byte alphanumeric characters plus the final NULL character)

* Any blank characters (` ') at the beginning of the text string, any zeros at the beginning of the text string, and any underbars (`_') in the text string are not included in the number of bytes.

Additional Information
· To convert a text string to a hexadecimal number, use a STRING_TO_** (Text String-to-Bit String Conversion Group) instruction (page 2-301).
· To convert an integer to a text string, use a **_TO_STRING (Integer-to-Text String Conversion Group) instruction (page 2-283).
Precautions for Correct Use
· Always use the correct instruction name for the data type of Out. · If the value of In is `-0', the value of Out is 0. · An error occurs in the following cases. ENO will be FALSE, and Out will not change.
· The text string in In does not express a number. · The conversion result exceeds the valid range of the data type of Out.

2-300

NJ/NX-series Instructions Reference Manual (W502)

Data Type Conversion Instructions

STRING_TO_** (Text String-to-Bit String Conversion Group)

2 Instruction Descriptions

STRING_TO_** (Text String-to-Bit String Conversion Group)

These instructions convert text strings to bit strings.

Instruction STRING_TO_**

Name
Text String-to-Bit String Conversion Group

FB/FUN FUN

Graphic expression

ST expression

(@)STRING_TO_**

Out:=STRING_TO_** (In);

EN In

ENO

Out

"**" must be a bit string data type.

2

"**" must be a bit string data type.

Variables

Name

Meaning

I/O

Description

Valid range

Unit

In

Data to

Input

Data to convert

convert

Out

Conversion Output

Conversion result

result

*

---

Depends on data type. ---

* The valid range depends on the data type of Out. Refer to Function for details.

Default ''
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In

OK

Out

OK OK OK OK

Function
These instructions interpret the content of a text string, In, as a hexadecimal number and convert it to a bit string. Basically, the text string in In must consist only of `0' to `9', `a' to `f', and `A' to `F'. The following exception is possible. · Any continuous blank characters or zeros at the beginning of In are ignored. · Any single underbars (`_') at any location are ignored. · An error occurs if there are two or more consecutive underbars (`_') at any location. · An error occurs if there are any underbars (`_') at the beginning or end. · An error occurs if there are any underbars (`_') between the minus signs (`-') or plus sign (`+') and the
number at the beginning. The name of the instruction is determined by the data type of conversion result Out. For example, if Out is the BYTE data type, the instruction is STRING_TO_BYTE.

NJ/NX-series Instructions Reference Manual (W502)

2-301

2 Instruction Descriptions

The following example for the STRING_TO_BYTE instruction is for when In is ` AB'. Any blank characters at the beginning are ignored.

LD

ST

abc:=STRING_TO_BYTE(' AB');

STRING_TO_BYTE

EN ` AB' In

ENO abc

STRING data In ` AB'

BYTE data Out=abc 16#AB

The valid range of In depends on the data type of Out as shown below:

Data type of Out

Valid range of In (maximum number of bytes)*

BYTE

3 bytes (two single-byte alphanumeric characters plus the final NULL character)

WORD DWORD

5 bytes (four single-byte alphanumeric characters plus the final NULL character)
9 bytes (eight single-byte alphanumeric characters plus the final NULL character)

LWORD

17 bytes (16 single-byte alphanumeric characters plus the final NULL character)

* Any blank characters (` ') at the beginning of the text string, any zeros at the beginning of the text string, and any underbars (`_') in the text string are not included in the number of bytes.

Additional Information
· To treat a signed number as a text string, use a STRING_TO_** (Text String-to-Integer Conversion Group) instruction (page 2-299).
· To convert a bit string to a text string, use a **_TO_STRING (Bit String-to-Text String Conversion Group) instruction (page 2-285).
Precautions for Correct Use
· Always use the correct instruction name for the data type of Out. · An error occurs in the following cases. ENO will be FALSE, and Out will not change.
· The text string in In does not express a number. · The conversion result exceeds the valid range of the data type of Out.

2-302

NJ/NX-series Instructions Reference Manual (W502)

Data Type Conversion Instructions

STRING_TO_** (Text String-to-Real Number Conversion Group)

2 Instruction Descriptions

STRING_TO_** (Text String-toReal Number Conversion Group)

These instructions convert text strings to real numbers.

Instruction STRING_TO_**

Name

FB/FUN

Text String-to-Real FUN

Graphic expression

ST expression Out:=STRING_TO_** (In);

2

Number Conver-

(@)STRING_TO_**

sion Group

EN In

ENO

Out

"**" must be a real number data type.

"**" must be a real number data type.

Variables

Name In

Meaning
Data to convert

I/O Input

Description Data to convert

Out

Conversion Output

Conversion result

result

Valid range

Unit

311 bytes max. (310

---

single-byte alphanu-

meric characters plus

the final NULL charac-

ter)

Depends on data type. ---

Default ''
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In

OK

Out

OK OK

Function

These instructions convert a text string, In, to a real number.
The name of the instruction is determined by the data type of conversion result Out. For example, if Out is the LREAL data type, the instruction is STRING_TO_LREAL.
The format of the text sting in In is given below.

`

'

- iiii . ffffffff e+nn

Sign

Integer part

Fractional part Exponent

(blank) (blank) Decimal point

NJ/NX-series Instructions Reference Manual (W502)

2-303

2 Instruction Descriptions

2-304

Name Sign Integer part
Decimal point Fractional part
Exponent

Format
· Any consecutive blank characters at the beginning of the text string are ignored. Any following single plus or minus sign is treated as the sign.
· The plus sign can be omitted.
· Any consecutive blank characters after the sign are ignored.
· The characters after the sign and up to the decimal point are taken as the integer part. Any consecutive blank characters after the sign are not included in the integer part. The sign may sometimes be omitted.
· If the decimal point and fractional part are omitted, the characters up to the exponent are taken as the integer part.
· If the decimal point, fractional part, and exponent are omitted, the characters up to the end of the text string are taken as the integer part.
· The integer part consists of `0' to `9'.
· The integer part cannot be omitted.
· The maximum number of digits in the integer part is the maximum text string length of 1985 minus the total number of bytes in the following: the sign, decimal point, fractional part, exponent, and blank characters before and after the sign.
· A single period (`.') following the integer part is taken as the decimal point.
· Omit the decimal point if there is no fractional part.
· The characters after the decimal point and up to the exponent are taken as the fractional part.
· If the exponent is omitted, the characters up to the end of the text string are taken as the fractional part.
· The fractional part consists of `0' to `9'.
· The fractional part can be omitted.
· The fractional part can consist of a maximum of 15 digits.
· If there is no decimal point, then there is no fractional part.
· The exponent consists of a single `e' or `E' after the fractional part, a following single plus or minus sign, and the remaining characters to the end of the text string.
· If there is no fractional part, then the above text string after the decimal point is taken as the exponent.
· If there is no decimal point or fractional part, then the above text string after the integer part is taken as the exponent.
· The numeric part of the exponent consists of `0' to `9'.
· The exponent can be omitted.
· The numeric part of the exponent can consist of a maximum of three digits.

Example 1: The following example uses the sign, decimal point, and fractional part, but does not use an exponent.

LD

ST

abc:=STRING_TO_LREAL(`-123.4567');

STRING_TO_LREAL

EN `-123.4567' In

ENO abc

STRING data

In`

' - 123 . 4567

LREAL data Out=abc -1.234567e+2

Example 2: The following example uses the sign, decimal point, fractional part, and exponent.

STRING data In` + 1 2 3 . 4 5 6 7 e + 0 2 '

LREAL data Out=abc 1.234567e+4

NJ/NX-series Instructions Reference Manual (W502)

Data Type Conversion Instructions

STRING_TO_** (Text String-to-Real Number Conversion Group)

2 Instruction Descriptions

Example 3: The following example does not use the sign, but uses the decimal point, fractional part, and exponent.

STRING data

In`

' 123 . 4567 e-02

LREAL data Out=abc 1.234567

Example 4: The following example does not use the sign, fractional part, decimal point, and exponent.

STRING data

LREAL data

In`

' 1

Out=abc

1.0

2

If the value of In is `+inf', the value of Out is positive infinity. If the value of In is `-inf', the value of Out is negative infinity. In either case, characters are not case sensitive.
Additional Information
To convert a real number to a text string, use a **_TO_STRING (Real Number-to-Text String Conversion Group) instruction (page 2-287).
Precautions for Correct Use
· Always use the correct instruction name for the data type of Out. · Any single underbars (`_') at any location in In are ignored. · An error occurs if there are any underbars (`_') at the beginning or end of In. · An error occurs if there are two or more consecutive underbars (`_') at any location in In. · An error occurs if there are any underbars (`_') between the minus signs (`-') or plus sign (`+') and the
number at the beginning of In. · If the content of In exceeds the precision of the data type of Out, the value is rounded. · If the content of In is closer to 0 than the minimum value of the data type of Out, the value of Out will
be 0. · If the content of In exceeds the valid range of Out, Out will be positive infinity for a positive number or
negative infinity for a negative number. · An error occurs in the following cases. ENO will be FALSE, and Out will not change.
· The text string in In does not express a number. · The text string in In has a decimal point but not a fractional part.

NJ/NX-series Instructions Reference Manual (W502)

2-305

2 Instruction Descriptions

TO_** (Integer Conversion Group)

These instructions convert integers, bit strings, real numbers, and text strings to integers.

Instruction TO_**

Name
Integer Conversion Group

FB/FUN FUN

Graphic expression

(@)TO_**

EN ENO

In

Out

ST expression Out:=TO_** (In);
"**" must be an integer data type.

"**" must be an integer data type.

Variables

Name

Meaning

I/O

Description

Valid range

In

Data to

Input

Data to convert

*1

convert

Out

Conversion Output

Conversion result

*1

result

*1 The valid ranges depend on the data types of In and Out.

*2 If you omit the input parameter, the default value is not applied. A building error will occur.

Unit
---
---

Default *2
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In

OK OK OK OK OK OK OK OK OK OK OK OK OK OK

OK

Out

OK OK OK OK OK OK OK OK

Function

These instructions convert the integer, bit string, real number, or text string in In to an integer.
The name of the instruction is determined by the data type of conversion result Out. For example, if Out is the LINT data type, the instruction is TO_LINT.
The following example for the TO_LINT instruction is for when In is LREAL#1.0e+10.

LD

ST

abc:=TO_LINT(LREAL#1.0e+10);

TO_LINT

EN ENO

LREAL#1.0e+10 In

abc

LREAL data In LREAL#1.0e+10

LINT data Out=abc 10000000000

2-306

NJ/NX-series Instructions Reference Manual (W502)

Data Type Conversion Instructions

TO_** (Integer Conversion Group)

2 Instruction Descriptions

· Conversion is performed to within the effective digits of the data type of In. If In is a real number, the fractional part is rounded off to the closest integer. The following table shows how values are rounded.

Value of

fractional

Treatment

Examples

part

Less than The fractional part is truncated. 0.5

1.49  1

0.5

If the ones digit is an even number, the fractional part 1.50  2

is truncated. If it is an odd number, the value is rounded up.

2.50  2

Greater

The fractional part is rounded up.

1.51  2

than 0.5

2

The valid ranges for In and Out depend on their data types. Refer to the descriptions of the functions of the following instructions for the valid ranges: **_TO_*** (Integer-to-Integer Conversion Group) (page 2262), **_TO_*** (Bit String-to-Integer Conversion Group) (page 2-270), and **_TO_*** (Real Numberto-Integer Conversion Group) (page 2-276).
For detailed specifications when In is STRING data, refer to Function for the STRING_TO_** (Text String-to-Integer Conversion Group) instructions (page 2-299).

Precautions for Correct Use
· Always use the correct instruction name for the data type of Out. · If the data type of In is for a bit string and the sizes of the data types of In and Out are different, the
following processing is performed. · If the data size of Out is larger than the data size of In, the upper digits of Out will contain 0. · If the data size of Out is smaller than the data size of In, the upper digits are truncated in Out. · Observe the following precautions if In is STRING data. · If the first character in In is a minus sign (-) or a plus sign (+), it is processed as the sign. · Except for a minus sign (-) or a plus sign (+) at the beginning, In must consist of consecutive `0' to
`9' characters. Underbars (`_') and blank characters before or after the `-' or `+' are allowed in the text string. · If the conversion result exceeds the valid range of Out, Out will contain an undefined value. Always make sure that the value of In is within the valid range so that the conversion result will not exceed the valid range of Out. · An error occurs in the following cases. ENO will be FALSE, and Out will not change. · In is STRING data, but the text sting in In does not express a number.

NJ/NX-series Instructions Reference Manual (W502)

2-307

2 Instruction Descriptions

TO_** (Bit String Conversion Group)

These instructions convert integers, bit strings, real numbers, and text strings to bit strings.

Instruction TO_**

Name
Bit String Conversion Group

FB/FUN FUN

Graphic expression

(@)TO_**

EN ENO

In

Out

ST expression Out:=TO_**(In);
"**" must be a bit string data type.

"**" must be a bit string data type.

Variables

Name

Meaning

I/O

Description

Valid range

In

Data to

Input

Data to convert

*1

convert

Out

Conversion Output

Conversion result

*1

result

*1 The valid ranges depend on the data types of In and Out.

*2 If you omit the input parameter, the default value is not applied. A building error will occur.

Unit
---
---

Default *2
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In

OK OK OK OK OK OK OK OK OK OK OK OK OK OK

OK

Out

OK OK OK OK

Function

These instructions convert the integer, bit string, real number, or text string in In to a bit string.
The name of the instruction is determined by the data type of conversion result Out. For example, if Out is the WORD data type, the instruction is TO_WORD.
The following example for the TO_WORD instruction is for when In is INT#-1234.

LD

ST

abc:=TO_WORD(INT#-1234);

TO_WORD

EN ENO

INT#-1234 In

abc

INT data In INT#-1234

WORD data Out=abc 16#FB2E

2-308

NJ/NX-series Instructions Reference Manual (W502)

Data Type Conversion Instructions

2 Instruction Descriptions

The valid ranges for In and Out depend on their data types. Refer to the descriptions of the functions of the following instructions for the valid ranges: **_TO_*** (Integer-to-Bit String Conversion Group) (page 2-265), **_TO_*** (Bit String-to-Bit String Conversion Group) (page 2-272), and **_TO_*** (Real Number-to-Bit String Conversion Group) (page 2-279).
For detailed specifications when In is STRING data, refer to Function for the STRING_TO_** (Text String-to-Bit String Conversion Group) instructions (page 2-301).

Precautions for Correct Use

· Always use the correct instruction name for the data type of Out. · If the conversion result exceeds the valid range of Out, Out will contain an undefined value. Always

2

make sure that the value of In is within the valid range so that the conversion result will not exceed

the valid range of Out.

· An error occurs in the following cases. ENO will be FALSE, and Out will not change.

· In is STRING data, but the text sting in In does not express a number.

TO_** (Bit String Conversion Group)

NJ/NX-series Instructions Reference Manual (W502)

2-309

2 Instruction Descriptions

TO_** (Real Number Conversion Group)

These instructions convert integers, bit strings, real numbers, and text strings to real numbers.

Instruction TO_**

Name
Real Number Conversion Group

FB/FUN FUN

Graphic expression

(@)TO_**

EN ENO

In

Out

ST expression Out:=TO_**(In);
"**" must be a real number data type.

"**" must be a real number data type.

Variables

Name

Meaning

I/O

Description

Valid range

Unit

Default

In

Data to

Input

Data to convert

convert

*1, *2

---

*3

Out

Conver-

Output

Conversion result

*1

sion result

---

---

*1 The valid ranges depend on the data types of In and Out.

*2 For STRING data, the valid range is 311 bytes max. (310 single-byte alphanumeric characters plus the final NULL character).

*3 If you omit the input parameter, the default value is not applied. A building error will occur.

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In

OK OK OK OK OK OK OK OK OK OK OK OK OK OK

OK

Out

OK OK

Function

These instructions convert the integer, bit string, real number, or text string in In to a real number.
The name of the instruction is determined by the data type of conversion result Out. For example, if Out is the REAL data type, the instruction is TO_REAL. If the value of In is positive or negative infinity, the value of Out is positive or negative infinity.
The following example for the TO_REAL instruction is for when In is INT#1234.

LD

ST

abc:=TO_REAL(INT#1234);

TO_REAL

EN ENO

INT#1234 In

abc

2-310

NJ/NX-series Instructions Reference Manual (W502)

Data Type Conversion Instructions

2 Instruction Descriptions

INT data In INT#1234

REAL data Out=abc 1.234e+3

The valid ranges for In and Out depend on their data types. Refer to the descriptions of the functions of the following instructions for the valid ranges: **_TO_*** (Integer-to-Real Number Conversion Group) (page 2-268), **_TO_*** (Bit String-to-Real Number Conversion Group) (page 2-274), and **_TO_*** (Real Number-to-Real Number Conversion Group) (page 2-281).
For detailed specifications when In is STRING data, refer to Function for the STRING_TO_** (Text String-to-Real Number Conversion Group) instructions (page 2-303).

Precautions for Correct Use

2

· Always use the correct instruction name for the data type of Out. · An error occurs in the following cases. ENO will be FALSE, and Out will not change.
· In is STRING data, but the text sting in In does not express a number.

TO_** (Real Number Conversion Group)

NJ/NX-series Instructions Reference Manual (W502)

2-311

2 Instruction Descriptions

EnumToNum

The EnumToNum instruction converts enumeration data to DINT data.

Instruction EnumToNum

Name
Enumeration-toInteger

FB/FUN FUN

Graphic expression

(@)EnumToNum

EN

ENO

In

Out

ST expression Out:=EnumToNum(In);

Variables

Name In
Out

Meaning
Data to convert
Conversion result

I/O Input
Output

Description Data to convert
Conversion result

Valid range ---

Unit ---

Depends on data type. ---

Default 0
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In

Enumeration

Out

OK

Function

The EnumToNum instruction converts the value of data to convert In, which is an enumeration, to a DINT value and outputs the value to conversion result Out.
Use this instruction, for example, to monitor the value of an enumerated variable on an HMI or other display device that does not handle enumerated variables.
The following example shows how to convert enumerator red of the enumeration Color to a value and output that value to DINT variable Output. If the value of enumerator red is 0, Output will be DINT#0.

LD

ST

Color#red

EnumToNum

EN

ENO

In

Output

Output:=EnumToNum(Color#red);

2-312

NJ/NX-series Instructions Reference Manual (W502)

Data Type Conversion Instructions

EnumToNum

2 Instruction Descriptions

Precautions for Correct Use
Version Information A CPU Unit with unit version 1.02 or later and Sysmac Studio version 1.03 or higher are required to use this instruction.

Sample Programming
In this sample, the operating mode of the user program is defined with enumerated data type Enum- 2
Mode. To monitor the operating mode on the HMI, the value of variable myEnumMode (an enumeration with a data type of EnumMode) is converted and the converted value is output to DINT variable Monitor_myMode. For example, if the value of myEnumMode is mode2, the value of Monitor_myMode will be 2.
 Data Type Definition

Name EnumMode mode0 mode1 mode2

Enumeration value --0 1 2

Comment Enumerated data type Member Member Member

LD Name
myEnumMode
Monitor_myMode

Data type EnumMode
DINT

Default mode0
0

Comment
Value of mode in enumerated data type
Monitored mode value

P_On myEnumMode

EnumToNum

EN

ENO

In

Monitor_myMode

ST Name
myEnumMode

Data type EnumMode

Default mode0

Monitor_myMode

DINT

0

Monitor_myMode:=EnumToNum(myEnumMode);

Comment
Value of mode in enumerated data type
Monitored mode value

NJ/NX-series Instructions Reference Manual (W502)

2-313

2 Instruction Descriptions

NumToEnum

The NumToEnum instruction converts DINT data to enumeration data.

Instruction NumToEnum

Name
Integer-toEnumeration

FB/FUN FUN

Graphic expression

(@)NumToEnum

EN

Out

In

InOut

ST expression NumToEnum(In,InOut);

Variables

Name In
InOut
Out

Meaning
Data to convert
Conversion result
Return value

I/O Input
In-out
Output

Description Data to convert
Conversion result

Valid range
Depends on data type.
---

Unit ---
---

TRUE: Instruction was executed normally.
FALSE: Instruction was not executed or an error occurred.

Depends on data --type.

Default 0
---
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In

InOut

Out

OK

OK Enumeration

Function

The NumToEnum instruction converts the value of data to convert In, which is DINT data, to an enumeration value and outputs that value to conversion result InOut.
Use this instruction, for example, to change the value of an enumerated variable from an HMI or other display device that does not handle enumerated variables.
The following example shows how to convert the value of DINT variable In1 and output the results to variable ColorA, which has an enumerated data type of Color. If green is the enumerator that corresponds to an enumeration value of 1 for Color and the value of In1 is 1, the value of ColorA will be green.

LD

ST

In1 ColorA

NumToEnum
EN In InOut

NumToEnum(In1,ColorA);

2-314

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Data Type Conversion Instructions

NumToEnum

Additional Information
If you use this instruction in a ladder diagram, you can use Out to see if the value of In is within the range of values for InOut.

Precautions for Correct Use

An error occurs if the value of In is not within the range of values for InOut. Out will be FALSE, and the value of InOut will not change.

Version Information

2

A CPU Unit with unit version 1.02 or later and Sysmac Studio version 1.03 or higher are required to use this instruction.

Sample Programming
In this sample, the operating mode of the user program is defined with enumerated data type EnumMode. To change the operating mode from an HMI, the value of Input_myMode, which is a DINT variable, is written. In the user program, the value of Input_myMode is converted and the converted value is output to variable myEnumMode (an enumeration with a data type of EnumMode). For example, if the value of Input_myMode is 1, the value of myEnumMode will be mode1.
 Data Type Definition

Name EnumMode mode0 mode1 mode2

Enumeration value --0 1 2

Comment Enumerated data type Member Member Member

LD Name
myEnumMode
Input_myMode

Data type EnumMode
DINT

Default mode0
0

Comment
Value of mode in enumerated data type
Value of mode to which to change

P_On
Input_myMode myEnumMode

NumToEnum
EN In InOut

ST Name
myEnumMode

Data type EnumMode

Default mode0

Input_myMode

DINT

0

NumToEnum(Input_myMode, myEnumMode);

NJ/NX-series Instructions Reference Manual (W502)

Comment Value of mode in enumerated data type Value of mode to which to change
2-315

2 Instruction Descriptions

TRUNC, Round, and RoundUp

These instructions change real numbers to integers.

TRUNC:

Truncates the number at the first decimal digit.

Round:

Rounds the number at the first decimal digit.

RoundUp: Rounds up the number at the first decimal digit.

Instruction TRUNC

Name Truncate

FB/FUN FUN

Round RoundUp

Round Off Real Number
Round Up Real Number

FUN FUN

Graphic expression

(@)TRUNC

EN

ENO

In

Out

(@)Round

EN

ENO

In

Out

(@)RoundUp

EN

ENO

In

Out

ST expression Out:=TRUNC(In);
Out:=Round(In);
Out:=RoundUp(In);

Variables

Name

Meaning

I/O

Description

Valid range

Unit

In

Data to

Input

Data to convert

convert

Depends on data type. ---

Out

Conversion Output

Conversion result

result

Depends on data type. ---

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default *
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

In

OK OK

Out

OK OK

Function
These instructions change the real number in In to an integer by eliminating the fractional part.
 TRUNC
The TRUNC instruction truncates the number at the first decimal digit.

STRING

2-316

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Data Type Conversion Instructions

TRUNC, Round, and RoundUp

 Round

The Round instruction rounds the number at the first decimal digit. The following table shows how values are rounded.

Value of fractional part

Treatment

Examples

Less than 0.5

The fractional part is truncated.

1.49  1

-1.49  -1

0.5

If the ones digit is an even number, the fractional part 1.50  2

is truncated. If it is an odd number, the value is rounded up.

2.50  2 -1.50  -2

-2.50  -2

Greater than 0.5

The fractional part is rounded up.

1.51  2 -1.51  -2

2

 RoundUp
The RoundUp instruction rounds up the number at the first decimal digit.

The differences in these three instructions are shown by the following examples.

Input value

TRUNC

Output value Round

RoundUp

REAL#1.6 DINT#1

DINT#2

DINT#2

REAL#1.5 DINT#1

DINT#2

DINT#2

REAL#1.5 DINT#1

DINT#1

DINT#2

REAL#2.5 DINT#2

DINT#2

DINT#3

REAL#-1.6 DINT#-1

DINT#-2

DINT#-2

REAL#-1.5 DINT#-1

DINT#-2

DINT#-2

REAL#-1.4 DINT#-1

DINT#-1

DINT#-2

REAL#-2.5 DINT#-2

DINT#-2

DINT#-3

The following example for the TRUNC instruction is for when In is REAL#-3.55. The value of variable abc will be DINT#-3.

LD

ST

REAL#-3.55

TRUNC

EN

ENO

In

abc:=TRUNC(REAL#-3.55); abc

The TRUNC instruction truncates the number at the first decimal digit. The value of In is REAL#-3.55, so the value of abc will be DINT#-3.

Truncated at decimal point.

In REAL#-3.55

Out=abc DINT#-3

Additional Information

If the data type of In is REAL, the data type of Out is DINT. If the data type of In is LREAL, the data type of Out is LINT.

Precautions for Correct Use
If the conversion result exceeds the valid range of Out, Out will contain an undefined value. Always make sure that the value of In is within the valid range so that the conversion result will not exceed the valid range of Out.

NJ/NX-series Instructions Reference Manual (W502)

2-317

2 Instruction Descriptions

2-318

NJ/NX-series Instructions Reference Manual (W502)

Bit String Processing Instructions

2
Bit String Processing Instructions

Instruction AND (&), OR, and XOR
XORN NOT AryAnd, AryOr, AryXor, and AryXorN

Name
Logical AND/Logical OR/ Logical Exclusive OR
Logical Exclusive NOR
Bit Reversal
Array Logical AND/ Array Logical OR/ Array Logical Exclusive OR/ Array Logical Exclusive NOR

Page 2-320
2-323 2-325 2-327

NJ/NX-series Instructions Reference Manual (W502)

2-319

2 Instruction Descriptions

AND (&), OR, and XOR

These instructions perform processing on Boolean variables or individual bits in bit stings.

AND (&): Logical AND

OR:

Logical OR

XOR:

Logical Exclusive OR

Instruction AND (&)

Name Logical AND

FB/FUN FUN

OR XOR

Logical OR

FUN

Logical Exclusive OR

FUN

Graphic expression

(@)AND

EN In1 :: InN

ENO

(@)&
EN ENO In1 :: InN

Out Out

(@)OR

EN ENO

In1

Out

::

InN

(@)XOR

EN ENO

In1

Out

::

InN

ST expression Out:=In1 AND ··AND InN; Out:=In1 & ··& InN;
Out:=In1 OR ··OR InN;
Out:=In1 XOR ··XOR InN;

Variables

Name In1 to InN
Out

Meaning
Data to process
Processing result

I/O Input
Output

Description

Valid range

Unit

Data to process, where N is Depends on data type. --2 to 5

Processing result

Depends on data type. ---

Default 0*
---

* If you omit the input parameter that connects to InN, the default value is not applied, and a building error will occur. For example, if N is 3 and the input parameters that connect to In1 and In2 are omitted, the default values are applied, but if the input parameter that connects to In3 is omitted, a building error will occur.

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In1 to InN Out

OK OK OK OK OK

Must be same data type as In1 to InN

2-320

NJ/NX-series Instructions Reference Manual (W502)

Bit String Processing Instructions

2 Instruction Descriptions

Function

These instructions perform processing on Boolean variables or corresponding bits in bit strings. The data to process is in In1 to InN. In1 to InN and Out must be the same data types.
If there are more than two data to process, processing is performed with the following procedure.

1 Processing is performed for In1 and In2.

2 Processing is performed for the results of step 1 and In3.

3 Processing is performed for the results of step 2 and In4.

2

··· ···

AND (&), OR, and XOR

The relationships between input and output variables are given in the following tables.

 AND (&)

If both bits are TRUE, then the processing result is TRUE. Otherwise, the processing result is FALSE.

In1 bit FALSE FALSE TRUE TRUE

In2 bit FALSE TRUE FALSE TRUE

Out bit FALSE FALSE FALSE TRUE

 OR

If both bits are FALSE, then the processing result is FALSE. Otherwise, the processing result is TRUE.

In1 bit

In2 bit

Out bit

FALSE

FALSE

FALSE

FALSE

TRUE

TRUE

TRUE

FALSE

TRUE

TRUE

TRUE

TRUE

 XOR

If both bits are the same, then the processing result is FALSE. If one bit is TRUE and the other is FALSE, then the processing result is TRUE.

In1 bit FALSE

In2 bit FALSE

Out bit FALSE

FALSE TRUE TRUE

TRUE FALSE TRUE

TRUE TRUE FALSE

NJ/NX-series Instructions Reference Manual (W502)

2-321

2 Instruction Descriptions

The following example shows the AND instruction when In1 is BYTE#16#3A, In2 is BYTE#16#28 and In3 is BYTE#16#73.

LD

ST

abc:=BYTE#16#3A AND BYTE#16#28 AND BYTE#16#73;

AND

EN BYTE#16#3A In1 BYTE#16#28 In2 BYTE#16#73 In3

ENO abc

In1=BYTE#16#3A 0 0 1 1 1 0 1 0 In2=BYTE#16#28 0 0 1 0 1 0 0 0 In3=BYTE#16#73 0 1 1 1 0 0 1 1

Out=abc

Logical ANDs between bits 0 0 1 0 0 0 0 0

The functions of the AND instruction and the & instruction are exactly the same. Use the form that is easier to use.

Additional Information
In ST, there is no limit to the number of input variables if you use the following notation. Out:=In1 AND In2 AND In3 AND In4 AND In5 AND In6 ··· Out:=In1 & In2 & In3 & In4 & In5 & In6 ··· Out:=In1 OR In2 OR In3 OR In4 OR In5 OR In6 ··· Out:=In1 XOR In2 XOR In3 XOR In4 XOR In5 XOR In6 ···

Precautions for Correct Use
The data types of In1 to InN and Out must all be the same. Otherwise, a building error will occur.

2-322

NJ/NX-series Instructions Reference Manual (W502)

Bit String Processing Instructions

2 Instruction Descriptions

XORN

The XORN instruction performs a logical exclusive NOR operation on Boolean variables or individual bits in bit stings.

Instruction XORN

Name
Logical Exclusive NOR

FB/FUN FUN

Graphic expression

ST expression

(@)XORN EN ENO

Out:=In1 XOR NOT ·· XOR NOT InN;

In1

Out

::

InN

2

XORN

Variables

Name In1 to InN
Out

Meaning
Data to process
Processing result

I/O Input
Output

Description

Valid range

Unit

Data to process, where N is Depends on data type. --2 to 5

Processing result

Depends on data type. ---

Default 0*
---

* If you omit the input parameter that connects to InN, the default value is not applied, and a building error will occur. For example, if N is 3 and the input parameters that connect to In1 and In2 are omitted, the default values are applied, but if the input parameter that connects to In3 is omitted, a building error will occur.

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In1 to InN Out

OK OK OK OK OK

Must be same data type as In1 to InN

Function
The XORN instruction performs processing on Boolean variables or corresponding bits in bit strings. The data to process is in In1 to InN. In1 to InN and Out must be the same data types.
If there are more than two data to process, processing is performed with the following procedure.
1 Processing is performed for In1 and In2. 2 Processing is performed for the results of step 1 and In3. 3 Processing is performed for the results of step 2 and In4.

··· ···

NJ/NX-series Instructions Reference Manual (W502)

2-323

2 Instruction Descriptions

The relationships between input and output variables are given in the following table. If both values are the same, then the processing result is TRUE. Otherwise, the processing result is FALSE.

In1 bit

In2 bit

Out bit

FALSE

FALSE

TRUE

FALSE

TRUE

FALSE

TRUE

FALSE

FALSE

TRUE

TRUE

TRUE

The following example is for when In1 is BYTE#16#3A, In2 is BYTE#16#28, and In3 is BYTE#16#73.

LD

ST

XORN

EN ENO

BYTE#16#3A In1

abc

BYTE#16#28 In2

BYTE#16#73 InN

abc:=BYTE#16#3A XOR NOT BYTE#16#28 XOR NOT BYTE#16#73;

In1=BYTE#16#3A 0 0 1 1 1 0 1 0 In2=BYTE#16#28 0 0 1 0 1 0 0 0 In3=BYTE#16#73 0 1 1 1 0 0 1 1

Out=abc

Logical exclusive NORs between bits 0 1 1 0 0 0 0 1

Precautions for Correct Use
The data types of In1 to InN and Out must all be the same. Otherwise, a building error will occur.

2-324

NJ/NX-series Instructions Reference Manual (W502)

Bit String Processing Instructions

2 Instruction Descriptions

NOT

The NOT instruction reverses the value of a Boolean variable or the individual bits in a bit string.

Instruction NOT

Name Bit Reversal

FB/FUN FUN

Graphic expression

(@)NOT

EN ENO

In

Out

ST expression Out:=NOT In;

2 Variables

NOT

Name

Meaning

I/O

Description

Valid range

Unit

In

Data to

Input

Data to process

process

Depends on data type. ---

Out

Processing Output

Processing result

result

Depends on data type. ---

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default *
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK OK OK OK OK

Out

Must be same data type as In

Function

The NOT instruction reverses the value of a Boolean variable or the values of individual bits in a bit string. The data to process is in In. In and processing result Out must have the same number of bits, i.e., they must be the same data type.
The following example is for when In is BYTE#16#73.

LD

ST

abc:=NOT(BYTE#16#73);

NOT

EN BYTE#16#73 In

ENO abc

In=BYTE#16#73 0 1 1 1 0 0 1 1

Out=abc

Individual bits reversed. 1 0 0 0 1 1 0 0

NJ/NX-series Instructions Reference Manual (W502)

2-325

2 Instruction Descriptions
Precautions for Correct Use
The data types of In and Out must be the same. Otherwise, a building error will occur.

2-326

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Bit String Processing Instructions

AryAnd, AryOr, AryXor, and AryXorN

These instructions process Boolean variables or individual bits in bit stings between arrays.

AryAnd: Logical AND

AryOr:

Logical OR

AryXor:

Logical Exclusive OR

AryXorN: Logical Exclusive NOR

2

AryAnd, AryOr, AryXor, and AryXorN

Instruction AryAnd

Name

FB/FUN

Array Logical AND FUN

Graphic expression

(@)AryAnd

EN

ENO

In1

Out

In2

Size

AryOut

ST expression
AryAnd(In1, In2, Size, AryOut);

AryOr

Array Logical OR FUN

(@)AryOr

EN

ENO

In1

Out

In2

Size

AryOut

AryOr(In1, In2, Size, AryOut);

AryXor

Array Logical Exclusive OR

FUN

(@)AryXor

EN

ENO

In1

Out

In2

Size

AryOut

AryXor(In1, In2, Size, AryOut);

AryXorN

Array Logical Exclusive NOR

FUN

(@)AryXorN

EN

ENO

In1

Out

In2

Size

AryOut

AryXorN(In1, In2, Size, AryOut);

Variables

Name

Meaning

I/O

Description

Valid range

In1[] and In2[] (arrays)
Size

Array to process
Number of elements

Input

Array to process

Number of elements to process

Depends on data type.

AryOut[] (array)

Processing results array

In-out

Processing results array

Depends on data type.

Out

Return value Output

Always TRUE

TRUE only

* If you omit an input parameter, the default value is not applied. A building error will occur.

Unit ---
-----

Default *
1
-----

NJ/NX-series Instructions Reference Manual (W502)

2-327

2 Instruction Descriptions

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

Bit strings

Integers

Times, durations, dates, and text strings

In1[] (array) OK OK OK OK OK

In2[] (array)

Size

AryOut[] (array)

Out

OK

Must be same data type as In1[] OK
Must be same data type as In1[]

Function

These instructions process Size elements from the beginning of arrays to process In1[] and In2[]. Processing is performed for corresponding bits of corresponding elements. The processing results are stored in corresponding elements of AryOut[]. In1[] to In2[] and AryOut[] must be the same data types.
The relationships between input and output variables are given in the following tables.

 AryAnd

If both bits are TRUE, then the processing result is TRUE. Otherwise, the processing result is FALSE.

Bit of ele- Bit of ele- Bit of Ary-

ment in In1[] ment in In2[]

Out[]

FALSE

FALSE

FALSE

FALSE

TRUE

FALSE

TRUE

FALSE

FALSE

TRUE

TRUE

TRUE

 AryOr

If both bits are FALSE, then the processing result is FALSE. Otherwise, the processing result is TRUE.

Bit of ele- Bit of ele- Bit of Ary-

ment in In1[] ment in In2[]

Out[]

FALSE FALSE TRUE

FALSE TRUE FALSE

FALSE TRUE TRUE

TRUE

TRUE

TRUE

2-328

NJ/NX-series Instructions Reference Manual (W502)

Bit String Processing Instructions

2 Instruction Descriptions

 AryXor

If both bits are the same, then the processing result is FALSE. If one bit is TRUE and the other is FALSE, then the processing result is TRUE.

Bit of ele- Bit of ele- Bit of Ary-

ment in In1[] ment in In2[]

Out[]

FALSE

FALSE

FALSE

FALSE

TRUE

TRUE

TRUE

FALSE

TRUE

TRUE

TRUE

FALSE

 AryXorN
If both bits are the same, then the processing result is TRUE. If one bit is TRUE and the other is FALSE, 2
then the processing result is FALSE.

Bit of ele- Bit of ele- Bit of Ary-

ment in In1[] ment in In2[]

Out[]

FALSE

FALSE

TRUE

FALSE

TRUE

FALSE

TRUE

FALSE

FALSE

TRUE

TRUE

TRUE

AryAnd, AryOr, AryXor, and AryXorN

The following example shows the AryAnd instruction when Size is UINT#3.

LD

ST

AryAnd(abc[1], def[2], UINT#3, ghi[3]);

abc[1] def[2] UINT#3
ghi[3]

AryAnd

EN

ENO

In1

In2

Size

AryOut

ghi[3]

Size=UINT#3

In1[0]=abc[1] In1[1]=abc[2] In1[2]=abc[3]

TRUE FALSE FALSE

AND In2[0]=def[2] AND In2[1]=def[3] AND In2[2]=def[4]

TRUE TRUE FALSE

AryOut[0]=ghi[3] AryOut[1]=ghi[4] AryOut[2]=ghi[5]

TRUE FALSE FALSE

Precautions for Correct Use
· The data types of In1[], In2[], and AryOut[] must be the same. If they are different, a building error will occur.
· Use an AryOut[] array that has at least as many elements as the value of Size. · The values in AryOut[] do not change if the value of Size is 0. · Return value Out is not used when the instruction is used in ST. · An error occurs in the following cases. ENO will be FALSE, and AryOut[] will not change.
· The value of Size exceeds the number of elements in In1[], In2[], or AryOut[].

NJ/NX-series Instructions Reference Manual (W502)

2-329

2 Instruction Descriptions

2-330

NJ/NX-series Instructions Reference Manual (W502)

Selection Instructions

2
Selection Instructions

Instruction SEL MUX LIMIT Band Zone MAX and MIN AryMax and AryMin ArySearch

Name Binary Selection Multiplexer Limiter Deadband Control Dead Zone Control Maximum/Minimum Array Maximum/Array Minimum Array Search

Page 2-332 2-334 2-337 2-339 2-342 2-345 2-347 2-350

NJ/NX-series Instructions Reference Manual (W502)

2-331

2 Instruction Descriptions

SEL

The SEL instruction selects one of two selections.

Instruction SEL

Name Binary Selection

FB/FUN FUN

Graphic expression

(@)SEL

EN ENO

G

Out

In0

In1

ST expression Out:=SEL(G, In0, In1);

Variables

Name G

Meaning Gate

In0 and In1 Selections

Out

Selection

result

I/O Input Output

Description FALSE: Selects In0. TRUE: Selects In1. Selections Selection result

Valid range

Unit

Depends on data type. ---

Depends on data type. ---

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default FALSE
*
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

G

OK

In0 and In1 OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK

Enumerations can also be specified.*

Out

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK

Enumerations can also be specified.*

* A CPU Unit with unit version 1.02 or later and Sysmac Studio version 1.03 or higher are required to specify enumerations.

2-332

NJ/NX-series Instructions Reference Manual (W502)

Selection Instructions

2 Instruction Descriptions

Function
The SEL instruction selects one of two selections, In0 and In1. Gate G specifies which of In0 and In1 to select. If G is FALSE, In0 is assigned to Out. If G is TRUE, In1 is assigned to Out.

FALSE G
TRUE

Out: = In1

Out: = In0

2

SEL

The following example is for when In0 is INT#10, In1 is INT#20, and G is TRUE. The value of variable abc will be INT#20.

LD

ST

abc:=SEL(TRUE, INT#10, INT#20);

SEL

EN ENO

TRUE G

abc

INT#10 In0

INT#20 In1

The SEL instruction selects In0 or In1. G is TRUE, so In1 (INT#20) is selected and assigned to abc.
In0 INT#10
Out=abc INT#20 In1 INT#20
G is TRUE, so In1 is assigned to Out.

Additional Information

Version Information
With a CPU Unit with unit version 1.02 or later and Sysmac Studio version 1.03 or higher, the MUX instruction (page 2-334) can also be used.

Precautions for Correct Use
· In0, In1, and Out may be different data types, but observe the following precautions. · Set the valid range of Out to include the valid ranges of In0 and In1. · In0, In1, and Out cannot be different varieties of data types (such as a bit string and an integer, or an integer and a text string).

NJ/NX-series Instructions Reference Manual (W502)

2-333

2 Instruction Descriptions

MUX

The MUX instruction selects one of two to five selections.

Instruction MUX

Name Multiplexer

FB/FUN FUN

Graphic expression

(@)MUX

EN ENO

K

Out

In0

In1

 

InN

ST expression
Out:=MUX(K, In0, In1, ···, InN);

Variables

Name

Meaning

I/O

K

Selector

Input In0 to InN Selections

Out

Selection Output

result

Description 0: Selects In0. 1: Selects In1. 2: Selects In2. 3: Selects In3. 4: Selects In4. Selections N is 1 to 4.*2 Selection result

Valid range 0 to N

Unit

Default

*1

---

Depends on data type.

0*3

Depends on data type. ---

---

*1 If you omit an input parameter, the default value is not applied. A building error will occur.
*2 With a CPU Unit with unit version 1.01 or earlier and Sysmac Studio version 1.02 or lower, N is 2 to 4.
*3 If you omit the input parameter that connects to InN, the default value is not applied, and a building error will occur. For example, if N is 2 and the input parameters that connect to In0 and In1 are omitted, the default values are applied, but if the input parameter that connects to In2 is omitted, a building error will occur.

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT
ULINT
UDINT UINT
USINT LWORD DWORD WORD
BYTE Boolean BOOL

K

OK*1

OK*1

In0 to InN OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK

Enumerations can also be specified.*2

Out

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK

Enumerations can also be specified.*2

*1 With a CPU Unit with unit version 1.02 or later and Sysmac Studio version 1.03 or higher, use a ULINT variable. With a CPU Unit with unit version 1.01 or earlier and Sysmac Studio version 1.02 or lower, use a USINT variable.
*2 A CPU Unit with unit version 1.02 or later and Sysmac Studio version 1.03 or higher are required to specify enumerations.

2-334

NJ/NX-series Instructions Reference Manual (W502)

Selection Instructions

2 Instruction Descriptions

Function
The MUX instruction selects one of two to five selections, In0 to InN. Selector K specifies which of In0 to InN to select. The value of one of the input variables is assigned to Out according to the value of K. In0 is assigned if K is 0, In1 is assigned if K is 1, etc.

K = 0

TRUE

FALSE

2

MUX

K = 1

TRUE

FALSE

K = N

TRUE

Out: = InN

Out: = In1

Out: = In0

The following example is for when In0 is INT#10, In1 is INT#20, In2 is INT#30, and K is ULINT#2. The value of variable abc will be INT#30.

LD

ST

MUX

EN ENO

ULINT#2 K

abc

INT#10 In0

INT#20 In1

INT#30 In2

abc:=MUX(ULINT#2, INT#10, INT#20, INT#30);

The MUX instruction selects from among In0 to InN. K is ULINT#2, so In2 (INT#30) is selected and assigned to abc.
In0 INT#10

In1 INT#20

Out=abc INT#30

In2 INT#30

K is ULINT#2, so In2 is assigned to Out.

NJ/NX-series Instructions Reference Manual (W502)

2-335

2 Instruction Descriptions
Precautions for Correct Use
· In0 to InN and Out may be different data types, but observe the following precautions. · Set the valid range of Out to include the valid ranges of In0 to InN. · In0 to InN and Out cannot be different varieties of data types (such as a bit string and an integer, or an integer and a text string).
· An error occurs in the following cases. ENO will be FALSE, and Out will not change. · The value of K is outside the valid range (i.e., less than 0 or greater than N).

2-336

NJ/NX-series Instructions Reference Manual (W502)

Selection Instructions

2 Instruction Descriptions

LIMIT

The LIMIT instruction limits the value of the input variable to the specified minimum and maximum values.

Instruction

Name

FB/FUN

Graphic expression

ST expression

LIMIT

Limiter

FUN

(@)LIMIT

Out:=LIMIT(MN, In, MX);

EN ENO

MN

Out

In

MX

2

LIMIT

Variables

Name

Meaning

I/O

Description

Valid range

Unit

MN

Minimum

value

Minimum value of limiter

In

Data to limit

Input

Data to limit

Depends on data type. ---

MX

Maximum

value

Maximum value of limiter

Out

Processing Output

Processing result

result

Depends on data type. ---

* If you omit an input parameter, the default value is not applied. A building error will occur.

Default *
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

MN

OK OK OK OK OK OK OK OK OK OK

In

OK OK OK OK OK OK OK OK OK OK

MX

OK OK OK OK OK OK OK OK OK OK

Out

OK OK OK OK OK OK OK OK OK OK

NJ/NX-series Instructions Reference Manual (W502)

2-337

2 Instruction Descriptions

Function
The LIMIT instruction limits the value of data to limit In according to the maximum value, MX, and the minimum value, MN. The value of processing result Out is as shown below.

Value of In In < MN MN  In  MX MX < In

Value of Out MN In MX

The following example is for when MN is INT#-10 and MX is INT#20.

LD

ST

def:=LIMIT(INT#-10, abc, INT#20);

LIMIT

EN ENO

INT#-10 MN

def

abc In

INT#20 MX

Out=def

MX=INT#20

MN=INT#-10

In=abc

Precautions for Correct Use
· In, MN, MX, and Out may be different data types, but observe the following precautions. · Set the valid range of Out to include the valid ranges of In, MN, and MX. · Do not combine signed integers (SINT, INT, DINT, and LINT) together with unsigned integers (USINT, UINT, UDINT, and ULINT) for In, MN, and MX.
· An error occurs in the following case. ENO will be FALSE, and Out will not change. · The value of MX is smaller than the value of MN.

2-338

NJ/NX-series Instructions Reference Manual (W502)

Selection Instructions

2 Instruction Descriptions

Band

The Band instruction performs deadband control.

Instruction

Name

FB/FUN

Graphic expression

ST expression

Band

Deadband Control FUN

(@)Band

Out:=Band(MN, In, MX);

EN ENO

MN

Out

In

MX
2

Band

Variables

Name

Meaning

I/O

Description

Valid range

Unit

MN

Minimum

value

Minimum value of deadband

In

Data to control

Input

Data to control

Depends on data type. ---

MX

Maximum

value

Maximum value of deadband

Out

Processing Output

Processing result

result

Depends on data type. ---

* If you omit an input parameter, the default value is not applied. A building error will occur.

Default *
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

MN

OK OK OK OK OK OK

In

OK OK OK OK OK OK

MX

OK OK OK OK OK OK

Out

OK OK OK OK OK OK

NJ/NX-series Instructions Reference Manual (W502)

2-339

2 Instruction Descriptions

Function
The Band instruction controls the value of data to control In according to the maximum value, MX, and the minimum value, MN. The value of processing result Out is as shown below.

Value of In In < MN MN  In  MX MX < In

Value of Out In - MN 0 In - MX

The following example is for when MN is INT#-10 and MX is INT#20.

LD

ST

def:=Band(INT#-10, abc, INT#20);

Band

EN ENO

INT#-10 MN

def

abc In

INT#20 MX

Out=def

MN=INT#-10

MX=INT#20

In=abc

Precautions for Correct Use

· In, MN, MX, and Out may be different data types, but observe the following precaution. · Set the valid range of Out to include the valid ranges of In, MN, and MX.
· If the value of In is nonnumeric data, the value of Out is nonnumeric data. · If the value of In, MN, or MX is positive infinity or negative infinity, the value of Out is as shown below.

Value of In +

Value of MN + -

Value of MX + - + -

Value of Out 0 Error 0 +

2-340

NJ/NX-series Instructions Reference Manual (W502)

Selection Instructions

2 Instruction Descriptions

Value of In -

Value of MN + -

Value of MX + - + -

Value of Out - Error 0 0

· An error occurs in the following cases. ENO will be FALSE, and Out will not change. · The value of MX is smaller than the value of MN. · Either MX or MN contains nonnumeric data. · The processing result exceeds the valid range of Out.
2

Band

NJ/NX-series Instructions Reference Manual (W502)

2-341

2 Instruction Descriptions

Zone

The Zone instruction adds a bias value to the input value.

Instruction Zone

Name

FB/FUN

Dead Zone Control FUN

Graphic expression

(@)Zone

EN ENO

BiasN

Out

In

BiasP

ST expression
Out:=Zone(BiasN, In, BiasP);

Variables

Name

Meaning

I/O

Description

Valid range

Unit

BiasN

Negative bias

Negative bias

In

Data to control

Input

Data to control

Depends on data type. ---

BiasP

Positive bias

Positive bias

Out

Processing Output

Processing result

result

Depends on data type. ---

* If you omit an input parameter, the default value is not applied. A building error will occur.

Default *
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

BiasN In BiasP Out

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK

2-342

NJ/NX-series Instructions Reference Manual (W502)

Selection Instructions

2 Instruction Descriptions

Function
The Zone instruction controls the value of data to control In according to the positive bias, BiasP, and the negative bias, BiasN. The value of processing result Out is as shown below.

Value of In

Value of Out

In < 0

In + BiasN

In = 0

0

0 < In

In + BiasP

2

Zone

The following example is for when BiasP is INT#20 and BiasN is INT#-20.

LD

ST

def:=Zone(INT#-20, abc, INT#20);

Zone

EN ENO

INT#-20 BiasN

def

abc In

INT#20 BiasP

Out=def

BiasP=INT#20

BiasN=INT#-20

In=abc

Precautions for Correct Use

· In, BiasP, BiasN, and Out may be different data types, but observe the following precaution. · Set the valid range of Out to include the valid ranges of In, BiasP, and BiasN.
· If the value of In is nonnumeric data, the value of Out is nonnumeric data. · If the value of In, BiasP, or BiasN is positive infinity or negative infinity, the value of Out is as shown
below.

Value of In

Value of BiasP Value of BiasN Value of Out

+

+

+

-

+

+

+

Error

-

-

0

NJ/NX-series Instructions Reference Manual (W502)

2-343

2 Instruction Descriptions

Value of In -

Value of BiasP + -

Value of BiasN + - + -

Value of Out 0 - Error -

· An error occurs in the following cases. ENO will be FALSE, and Out will not change. · BiasP is less than BiasN. · Either BiasP or BiasN contains nonnumeric data. · The processing result exceeds the valid range of Out.

2-344

NJ/NX-series Instructions Reference Manual (W502)

Selection Instructions

2 Instruction Descriptions

MAX and MIN

MAX: Finds the largest of two to five values. MIN: Finds the smallest of two to five values.

Instruction MAX

Name Maximum

FB/FUN FUN

MIN

Minimum

FUN





Graphic expression

(@)MAX

EN ENO

In1

Out



InN

(@)MIN

EN ENO

In1

Out

InN



ST expression Out:=MAX(In1, In2, ···, InN);
2
Out:=MIN(In1, In2, ···, InN);

MAX and MIN

Variables

Name

Meaning

I/O

Description

Valid range

Unit

Default

In1 to InN Data to

Input

Data to process, where N is Depends on data type. ---

0*

process

2 to 5

Out

Search

Output

Search result

result

Depends on data type. ---

---

* If you omit the input parameter that connects to InN, the default value is not applied, and a building error will occur. For example, if N is 3 and the input parameters that connect to In1 and In2 are omitted, the default values are applied, but if the input parameter that connects to In3 is omitted, a building error will occur.

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In1 to InN Out

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK

NJ/NX-series Instructions Reference Manual (W502)

2-345

2 Instruction Descriptions

Function

 MAX
The MAX instruction finds the largest value of two to five data to process, In1 to InN.

 MIN
The MIN instruction finds the smallest value of two to five data to process, In1 to InN. The following example is for the MAX instruction when In1 is INT#10, In2 is INT#5, In3 is INT#23, In4 is INT#14, and In5 is INT#-5.

LD

ST

abc:=MAX(INT#10, INT#5, INT#23, INT#14, INT#-5);

MAX

EN ENO

INT#10 In1

abc

INT#5

In2

INT#23 In3

INT#14 In4

INT# -5 In5

In1 INT#10 In2 INT#5 In3 INT#23 In4 INT#14 In5 INT#-5

Out=abc

INT#23

Additional Information
To find the largest or smallest of six or more values, use the AryMax or AryMin instruction (page 2-347).
Precautions for Correct Use
· In1 to InN and Out may be different data types, but observe the following precaution. · Set the valid range of Out to include the valid ranges of In1 to InN. · Do not combine signed integers (SINT, INT, DINT, and LINT) together with unsigned integers (USINT, UINT, UDINT, and ULINT) for In1 to InN.
· If In1 to InN are real numbers, the desired results may not be achieved due to error.

2-346

NJ/NX-series Instructions Reference Manual (W502)

Selection Instructions

2 Instruction Descriptions

AryMax and AryMin

AryMax: AryMin:

Finds the elements with the largest value in a one-dimensional array. Finds the elements with the smallest value in a one-dimensional array.

Instruction

Name

FB/FUN

Graphic expression

ST expression

AryMax

Array Maximum

FUN

(@)AryMax

EN

ENO

Out:=AryMax(In, Size, InOutPos, Num);

In

Out

Size

Num

2

InOutPos

AryMin

Array Minimum

FUN

(@)AryMin

EN

ENO

Out:=AryMin(In, Size, InOutPos, Num);

In

Out

Size

Num

InOutPos

AryMax and AryMin

Variables

Name

Meaning

I/O

Description

Valid range

In[] (array) Array to search

Array to search

Size

Number of

Input

Number of elements in Depends on data type.

elements to

In[] to search

search

InOutPos Found element number

In-out

Array element number Depends on data type. where value was found

Out Num

Search result Number found

Output

Search result Number found

Depends on data type.

* If you omit the input parameter, the default value is not applied. A building error will occur.

Unit
---
---
---

Default * 1
---
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In[] (array)
Size InOutPos Out
Num

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK *
OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK
* OK

* You can specify TIME, DATE, TOD, DT, and STRING data with CPU Units with unit version 1.01 or later and Sysmac Studio version 1.02 or higher.

NJ/NX-series Instructions Reference Manual (W502)

2-347

2 Instruction Descriptions

Function

These instructions search Size elements in array to search In[] starting from In[0]. The value that is found is assigned to Out, the element number where it was found is assigned to InOutPos, and the number of times the value was found is assigned to Num. If Num is greater than 1, the value in InOutPos is the number of the lowest element that contains the value that was found.
The relationship between values with data types that are not integers or real numbers are determined as given in the following table.

TIME

Data type

Relationship The numerically larger value is considered to be larger.

DATE, TOD, or DT STRING

Later dates or times of day are considered to be larger.
The specifications are the same as for the LTascii, LEascii, GTascii, and GEascii instructions (page 2-104). Refer to the specified page for details.

 AryMax
The AryMax instruction finds the largest value.

 AryMin
The AryMin instruction finds the smallest value.

The following example shows the AryMax instruction when Size is UINT#6. The input parameter that is passed to In[] is abc[2], so the search starts from abc[2].

LD

ST

ghi:=AryMax(abc[2], UINT#6, def, jkl);

AryMax

abc[2] UINT#6

EN In Size InOutPos

ENO
ghi Num jkl

def

def

The lowest element number that contains the largest value is 3. Not searched.

Size=UINT#6

In[0]=abc[2] In[1]=abc[3] In[2]=abc[4] In[3]=abc[5] In[4]=abc[6] In[5]=abc[7]

9999 2345 9999 4321 4567 1234 9999 9999

Largest value = 9999
Out=ghi InOutPos=def
Num=jkl

INT#9999 UINT#3 UINT#2

Not searched.

Additional Information
When you compare TIME, DT, or TOD data, adjust the data so that the precision of the values is the same. Use the following instructions to adjust the precision of the values: TruncTime (page 2-658), TruncDt (page 2-662), and TruncTod (page 2-666).

Precautions for Correct Use
· If you use a different data type for In[] and Out, make sure the valid range of Out includes the valid range of In[].

2-348

NJ/NX-series Instructions Reference Manual (W502)

Selection Instructions

2 Instruction Descriptions
· If In[] contains real numbers, the desired results may not be achieved due to error. · Always used a one-dimensional array for In[]. · If the value of Size is 0, the values of Out and Num are 0. The value of InOutPos does not change. · If In[] contains STRING data and the value of Size is 0, Out is a text string containing only the NULL
character. · An error occurs in the following cases. ENO will be FALSE, and Out will not change.
· The value of Size is outside of the valid range. · Size exceeds the array area of In[]. · In[] is not a one-dimensional array. · In[] is STRING data and it does not end in a NULL character.
2

AryMax and AryMin

NJ/NX-series Instructions Reference Manual (W502)

2-349

2 Instruction Descriptions

ArySearch

The ArySearch instruction searches for the specified value in a one-dimensional array.

Instruction ArySearch

Name Array Search

FB/FUN FUN

Graphic expression

(@)ArySearch

EN In Size Key InOutPos

ENO Out
Num

ST expression
Out:=ArySearch(In, Size, Key, InOutPos, Num);

Variables

Name In[] (array) Size
Key InOutPos
Out Num

Meaning

I/O

Array to search

Number of elements to

Input

search

Search key

Found element number

In-out

Search result
Number found

Output

Description Array to search

Valid range

Unit

Depends on data type.

Number of elements in In[] 1 to 65535

to search

---

Value to search for
Array element number where value was found

Depends on data type. Depends on data type. ---

Search result Number found

Depends on data type. ---

* If you omit an input parameter, the default value is not applied. A building error will occur.

Default * 1
-----
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In[] (array)
Size Key InOutPos Out Num

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK *
Arrays of enumerations can also be specified. OK
Must be same data type as the elements of In[]. OK
OK OK

* You can specify TIME, DATE, TOD, and DT data with CPU Units with unit version 1.01 or later and Sysmac Studio version 1.02 or higher.

2-350

NJ/NX-series Instructions Reference Manual (W502)

Selection Instructions

2 Instruction Descriptions

Function

The ArySearch instruction searches Size elements of one-dimensional array to search In[] for elements with the same value as search key Key. The search starts from In[0].
The values of search result Out, found element number InOutPos, and number found Num are as follows:

Element with same value as Out
Key

InOutPos

Num

Exists.

TRUE Lowest element number that con- Number of elements with

tains the same value as Key

same value as Key

2

Does not exist. FALSE Does not change.

0

ArySearch

The relationship between values with data types that are not integers or real numbers are determined as given in the following table.

Data type

Relationship

TIME

The numerically larger value is considered to be larger.

DATE, TOD, or DT

Later dates or times of day are considered to be larger.

The following example is for when Size is UINT#6 and Key is INT#5555. The input parameter that is passed to In[] is abc[2], so the search starts from abc[2].

LD

ST

ghi:=ArySearch(abc[2], UINT#6, INT#5555, def, jkl);

ArySearch

abc[2] UINT#6 INT#5555
def

EN In Size Key InOutPos

ENO ghi
Num jkl
def

The lowest element number that contains same value as Key is 3.

Not searched.

Size=UINT#6

In[0]=abc[2] In[1]=abc[3] In[2]=abc[4] In[3]=abc[5] In[4]=abc[6] In[5]=abc[7]

5555 2345 5555 5555 4567 1234 9876 5555

Key=INT#5555 Out=ghi TRUE
InOutPos=def UINT#3 Num=jkl UINT#2
Not searched.

Additional Information
When you compare TIME, DT, or TOD data, adjust the data so that the precision of the values is the same. Use the following instructions to adjust the precision of the values: TruncTime (page 2-658), TruncDt (page 2-662), and TruncTod (page 2-666).

NJ/NX-series Instructions Reference Manual (W502)

2-351

2 Instruction Descriptions
Precautions for Correct Use
· Always use a one-dimensional array for In[]. · Make sure that Key has the same data type as the elements of In[]. · If the value of Size is 0, the values of Out and Num are 0. The value of InOutPos does not change. · Always use a variable for the input parameter to pass to Key. A building error will occur if a constant is
passed. · If Key is an enumeration, you cannot directly pass an enumerator to it. A building error will occur if an
enumerator is passed to it directly. · An error occurs in the following cases. ENO will be FALSE, and Out, Num, and InOutPos will not
change. · Size exceeds the array area of In[]. · In[] is STRING data and it does not end in a NULL character. · In[] is not a one-dimensional array.

2-352

NJ/NX-series Instructions Reference Manual (W502)

Data Movement Instructions

2
Data Movement Instructions

Instruction MOVE MoveBit MoveDigit TransBits MemCopy SetBlock Exchange AryExchange AryMove Clear Copy**ToNum (Bit String to Signed Integer) Copy**To*** (Bit String to Real Number) CopyNumTo** (Signed Integer to Bit String) CopyNumTo** (Signed Integer to Real Number) Copy**To*** (Real Number to Bit String) Copy**ToNum (Real Number to Signed Integer)

Name Move Move Bit Move Digit Move Bits Memory Copy Block Set Data Exchange Array Data Exchange Array Move Initialize Bit Pattern Copy (Bit String to Signed Integer) Group Bit Pattern Copy (Bit String to Real Number) Group Bit Pattern Copy (Signed Integer to Bit String) Group Bit Pattern Copy (Signed Integer to Real Number) Group Bit Pattern Copy (Real Number to Bit String) Group Bit Pattern Copy (Real Number to Signed Integer) Group

Page 2-354 2-357 2-359 2-361 2-363 2-365 2-367 2-369 2-371 2-373 2-375
2-377
2-379
2-381
2-383
2-385

NJ/NX-series Instructions Reference Manual (W502)

2-353

2 Instruction Descriptions

MOVE

The MOVE instruction moves the value of a constant or variable to another variable.

Instruction MOVE

Name Move

FB/FUN FUN

Graphic expression

(@)MOVE

EN

ENO

In

Out

ST expression Out:=In;

Variables

Name

Meaning

I/O

Description

Valid range

In

Move

Input

Move source

source

Out

Move

Output

Move destination

destination

Depends on data type. Depends on data type.

* If you omit the input parameter, the default value is not applied. A building error will occur.

Unit
---
---

Default *
*

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK In
An enumeration, array, array element, structure, or structure member can also be specified.

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK

Out

Must be the same data type as In if In is an enumeration, array element, structure, or structure member.

Must be an array with the same data type, size, and subscripts if In is an array.

Function

The MOVE instruction moves the value in move source In to move destination Out. The input parameter that is passed to In can be a variable or constant. You can specify an enumeration, array, array element, structure, or structure member for In.
The following figure shows a programming example. The content of variable abc is moved to variable def.

LD

ST

def:=abc;

MOVE

EN abc In

ENO Out def

The MOVE instruction moves the value of In to Out.

In=abc

Moved.

Out=def

2-354

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Data Movement Instructions

Additional Information

· When moving an array, you can move either one element or all of the elements in the array. To move only one element, add the subscript to the array variable name. To move the entire array, do not add the subscript to the array variable name.
Moving One Array Element

LD

ST

def[5]:=abc[3];

MOVE

2

EN

ENO

abc[3] In

Out def[5]

MOVE

Moving All Array Elements

LD

ST

def:=abc;

MOVE

EN abc In

ENO Out def

· When moving a structure, you can move either one member or all of the members in the structure. To move only one member, specify the member. To move the entire structure, give only the structure name.
Moving One Member of a Structure

LD

ST

def.n:=abc.m;

abc.m

MOVE

EN

ENO

In

Out

def.n

Moving the Entire Structure

LD

ST

def:=abc;

MOVE

EN abc In

ENO Out def

· You can use the MemCopy instruction to move an entire array faster than with the MOVE instruction.

Precautions for Correct Use
· The data types of In and Out can be different as long as they are both in one of the following groups. The valid range of Out must include the valid range of In.

NJ/NX-series Instructions Reference Manual (W502)

2-355

2 Instruction Descriptions
· BYTE, WORD, DWORD, and LWORD · USINT, UINT, UDINT, ULINT, SINT, INT, DINT, LINT, REAL, and LREAL · If In is an enumeration, array element, structure, or structure member, then Out must have the same data type as In. · If In is an array, an array of the same data type, size, and subscripts must be used for Out.

2-356

NJ/NX-series Instructions Reference Manual (W502)

Data Movement Instructions

2 Instruction Descriptions

MoveBit

The MoveBit instruction moves one bit in a bit string.

Instruction MoveBit

Name Move Bit

FB/FUN FUN

Graphic expression

ST expression

(@)MoveBit

EN

ENO

MoveBit(In, InPos, InOut, InOutPos);

In

Out

InPos

InOut

2
InOutPos

MoveBit

Variables

Name

Meaning

I/O

Description

Valid range

Unit

In

Move

source

Move source

Depends on data type.

InPos

Move source bit Input

Position of bit in In to move 0 to No. of bits in In - 1
---

InOutPos

Move destination bit

Position of bit in Out to receive the bit

0 to No. of bits in InOut - 1

InOut

Move

In-out

destination

Move destination

Depends on data type. ---

Out

Return

Output

Always TRUE

value

TRUE only

---

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default *
0
-----

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In InPos InOutPos InOut Out

OK OK OK OK OK OK
OK OK OK OK OK

NJ/NX-series Instructions Reference Manual (W502)

2-357

2 Instruction Descriptions

Function

The MoveBit instruction moves one bit from the bit position InPos in move source In to the bit position InOutPos in move destination InOut.
The following example is for when InPos is USINT#3 and InOutPos is USINT#5.

LD

ST

MoveBit(abc, USINT#3, def, USINT#5);

MoveBit

EN

ENO

abc In

USINT#3 InPos

InOut

def

def

USINT#5 InOutPos

Most-significant bit In=abc 0 0

InPos=USINT#3 Bit 0
0 0 1 0 0 0

InOut=def 0 0

1 0 0 0 0 0

InOutPos=USINT#5

Precautions for Correct Use
· Return value Out is not used when the instruction is used in ST. · An error occurs in the following cases. ENO will be FALSE, and InOut will not change.
· The value of InPos is outside of the valid range. · The value of InOutPos is outside of the valid range.

2-358

NJ/NX-series Instructions Reference Manual (W502)

Data Movement Instructions

2 Instruction Descriptions

MoveDigit

The MoveDigit instruction moves digits (4 bits per digit) in a bit string.

Instruction MoveDigit

Name Move Digit

FB/FUN FUN

Graphic expression

ST expression

(@)MoveDigit

EN

ENO

MoveDigit(In, InPos, InOut, InOutPos, Size);

In

Out

InPos

InOut

2
InOutPos

Size

MoveDigit

Variables

Name

Meaning

I/O

Description

Valid range

Unit

In

Move

source

Move source

Depends on data type.

InPos

Move source digit

Position of digit in In to move *2

InOutPos Move

Input

Position of digit in Out to

*3

---

destination

receive the digit

digit

Size

Number of

digits

Number of digits to move *4

InOut

Move

In-out

destination

Move destination

Depends on data type. ---

Out

Return

Output

Always TRUE

value

TRUE only

---

*1 If you omit the input parameter, the default value is not applied. A building error will occur.

*2 0 to No. of bits in In/4 - 1

*3 0 to No. of bits in InOut/4 - 1

*4 0 to No. of bits in In/4

Default *1
0
1
-----

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In InPos InOutPos Size InOut Out

OK OK OK OK OK OK OK
OK OK OK OK OK

NJ/NX-series Instructions Reference Manual (W502)

2-359

2 Instruction Descriptions

Function

The MoveDigit instruction moves Size digits from the InPos digit in move source In to the InOutPos digit in move destination InOut. One digit is four bits.
The following example is for when InPos is USINT#1, InOutPos is USINT#2, and Size is USINT#2.

LD

ST

MoveDigit(abc, USINT#1, def, USINT#2, USINT#2);

MoveDigit

abc USINT#1
def

EN In InPos InOut

ENO def

USINT#2 InOutPos USINT#2 Size

1 digit = 4 bits In=abc

Size=USINT#2

InPos=USINT#1

Digit 3 Digit 2 Digit 1 Digit 0

InOut=def

Digit 3 Digit 2 Digit 1 Digit 0

InOutPos=USINT#2
Precautions for Correct Use
· If the position of the digit at the destination exceeds the most-significant digit of InOut, the remaining digits are stored the least-significant digits of InOut.
· If the position of the digit at the source exceeds the most-significant digit of In, the remaining digits are moved to the least-significant digits of In.
· If the value of Size is 0, the value of Out will be TRUE and InOut will not change. · Return value Out is not used when the instruction is used in ST. · An error occurs in the following cases. ENO will be FALSE, and InOut will not change.
· The value of InPos is outside of the valid range. · The value of InOutPos is outside of the valid range. · The value of Size is outside of the valid range.

2-360

NJ/NX-series Instructions Reference Manual (W502)

Data Movement Instructions

2 Instruction Descriptions

TransBits

The TransBits instruction moves one or more bits in a bit string.

Instruction TransBits

Name Move Bits

FB/FUN FUN

Graphic expression

ST expression

(@)TransBits

EN

ENO

TransBits(In, InPos, InOut, InOutPos, Size);

In

Out

InPos

InOut

2
InOutPos

Size

TransBits

Variables

Name

Meaning

I/O

Description

Valid range

Unit

In

Move

source

Move source

Depends on data type.

InPos

Move source bit

Position of bit in In to move *2

InOutPos Move

Input

Position of bit in Out to

*3

---

destination

receive the bit

bit

Size

Number of

bits

Number of bits to move

*4

InOut

Move

In-out

destination

Move destination

Depends on data type. ---

Out

Return

Output

Always TRUE

value

TRUE only

---

*1 If you omit an input parameter, the default value is not applied. A building error will occur.

*2 0 to No. of bits in In - 1

*3 0 to No. of bits in InOut - 1

*4 0 to No. of bits in In

Default *1
0
1
-----

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In InPos InOutPos Size InOut Out

OK OK OK OK OK OK OK
OK OK OK OK OK

NJ/NX-series Instructions Reference Manual (W502)

2-361

2 Instruction Descriptions

Function

The TransBis instruction moves Size bits from the InPos bit in move source In to the InOutPos bit in move destination InOut.
The following example is for when InPos is USINT#3, InOutPos is USINT#4, and Size is USINT#2.

LD

ST

TransBits(abc, USINT#3, def, USINT#4, USINT#2);

TransBits

abc USINT#3
def

EN In InPos InOut

ENO def

USINT#4 InOutPos USINT#2 Size

Most-significant bit

In=abc

0 0

InPos=USINT#3 Bit 0
0 0 0 0 0 0

Size=USINT#2

InOut=def 1 1 0 0 1 1 1 1 InOutPos=USINT#4

Additional Information
The bits in the move source and move destination can overlap.
Precautions for Correct Use
· Set the instruction so that the positions of the bits at the source and destination do not exceed the most-significant bit in In or InOut. An error will occur and the instruction will not operate.
· Nothing is moved if the value of Size is 0. · The bits in InOut that are not involved in the move operation do not change. · Return value Out is not used when the instruction is used in ST. · An error occurs in the following cases. ENO will be FALSE, and InOut will not change.
· The value of InPos is outside of the valid range. · The value of InOutPos is outside of the valid range. · The value of Size is outside of the valid range. · The value of InPos or Size exceeds the number of bits in In. · The value of InOutPos or Size exceeds the number of bits in InOut.

2-362

NJ/NX-series Instructions Reference Manual (W502)

Data Movement Instructions

2 Instruction Descriptions

MemCopy

The MemCopy instruction moves one or more array elements. The move source and move destination must have the same data type.

Instruction MemCopy

Name Memory Copy

FB/FUN FUN

Graphic expression

ST expression

(@)MemCopy

MemCopy(In, AryOut, Size);

EN

ENO

In

Out

AryOut
2

Size

MemCopy

Variables

Name In[] (array)
Size AryOut[] (array) Out

Meaning
Move source array
Number of elements
Move destination array
Return value

I/O Input In-out Output

Description Move source array

Valid range

Unit

Depends on data type. ---
Number of array elements to move

Move destination array

Depends on data type. ---

Always TRUE

TRUE only

---

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default *
1
---
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In[] (array)
Size AryOut[] (array) Out

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK Arrays of enumerations or structures can also be specified. OK Must be an array with the same data type as In[].
OK

NJ/NX-series Instructions Reference Manual (W502)

2-363

2 Instruction Descriptions

Function

The MemCopy instruction moves Size elements of move source array In[] starting from In[0] to move destination array AryOut[] starting from AryOut[0].
The following example is for when Size is UINT#3.

LD

ST

MemCopy(abc[1], def[2], UINT#3);

abc[1]
def[2] UINT#3

MemCopy

EN In AryOut

ENO

Size

def[2]

In[0]=abc[1] Size=UINT#3 In[1]=abc[2]
In[2]=abc[3]

1234 2345 3456

AryOut[0]=def[2] AryOut[1]=def[3] AryOut[2]=def[4]

1234 2345 3456

Additional Information

· You can specify different positions in the same array for In[] and AryOut[]. The source and destination data can overlap.
The following example is for when In is A[2], AryOut is A[4], and Size is UINT#3.

Size=UINT#3

A[1] In=A[2]
A[3] AryOut=A[4]
A[5] A[6]

1234 2345 3456 4567 5678 6789

A[1] In=A[2]
A[3] AryOut=A[4]
A[5] A[6]

1234 2345 3456 2345 3456 4567

· Use the AryMove instruction (page 2-371) if the source and destination have different data types. · If the data types of In[] and AryOut[] are the same, this instruction is faster than the AryMove instruc-
tion. · Use the MOVE instruction (page 2-354) to move variables that are not arrays.

Precautions for Correct Use
· Use the same data type for In[] and AryOut[]. If they are different, a building error will occur. · If In[] and AryOut[] are STRING arrays, their sizes must be the same. · If the value of Size is 0, the value of Out will be TRUE and AryOut[] will not change. · Return value Out is not used when the instruction is used in ST. · An error occurs in the following cases. ENO will be FALSE, and AryOut[] will not change.
· Size exceeds the array area of In[]. · Size exceeds the array area of AryOut[].

2-364

NJ/NX-series Instructions Reference Manual (W502)

Data Movement Instructions

2 Instruction Descriptions

SetBlock

The SetBlock instruction moves the value of a variable or constant to one or more array elements.

Instruction SetBlock

Name Block Set

FB/FUN FUN

Graphic expression

(@)SetBlock

EN

ENO

In

Out

AryOut

ST expression SetBlock(In, AryOut, Size);

Size

2

SetBlock

Variables

Name

Meaning

I/O

Description

Valid range

Unit

In

Move

Move source

source

Input

Depends on data type. ---

Size

Number of

Number of array elements to

elements

move

AryOut[] (array)

Move

In-out

destination

array

Move destination array

Depends on data type. ---

Out

Return

Output

Always TRUE

value

TRUE only

---

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default * 1
---
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In
Size AryOut[] (array) Out

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK An enumeration, structure, or structure member can also be specified. OK Must be an array with elements that have the same data type as In.
OK

Function
The SetBlock instruction moves the value of move source In to Size locations in move destination array AryOut[] starting from AryOut[0].

NJ/NX-series Instructions Reference Manual (W502)

2-365

2 Instruction Descriptions

The following example is for when Size is UINT#3.

LD

ST

SetBlock(abc, def[1], UINT#3);

abc
def[1] UINT#3

SetBlock

EN In AryOut

ENO

Size

def[1]

In=abc 1234

AryOut[0]=def[1] AryOut[1]=def[2] AryOut[2]=def[3]

1234 1234 1234

Size=UINT#3

Precautions for Correct Use
· Use the same data type for In and AryOut[]. If they are different, a building error will occur. · If In and AryOut[] are STRING data, their sizes must be the same. · If the value of Size is 0, the value of Out will be TRUE and AryOut[] will not change. · Return value Out is not used when the instruction is used in ST. · An error occurs in the following case. ENO will be FALSE, and AryOut[] will not change.
· The value of Size exceeds the array area of AryOut[].

2-366

NJ/NX-series Instructions Reference Manual (W502)

Data Movement Instructions

2 Instruction Descriptions

Exchange

The Exchange instruction exchanges the values of two variables.

Instruction Exchange

Name Data Exchange

FB/FUN FUN

Graphic expression

(@)Exchange

EN InOut1

ENO

ST expression Exchange(InOut1, InOut2);

InOut2
2
Out

Exchange

Variables

Name
InOut1 and InOut2
Out

Meaning
Data to exchange
Return value

I/O In-out
Output

Description Data to exchange
Always TRUE

Valid range

Unit

Depends on data type. ---

TRUE only

---

Default
---
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

InOut1
InOut2 Out

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK An enumeration, structure, or structure member can also be specified. Must be same data type as InOut1.
OK

Function

The Exchange instruction exchanges the values of data to exchange InOut1 and InOut2. You can specify enumerations, structures, or structure members for InOut1 and InOut2.
The following figure shows a programming example. The values in variables abc and def are exchanged.

LD

ST

Exchange(abc, def);

Exchange

EN

ENO

InOut1

abc

abc

InOut2

def

def

Out

NJ/NX-series Instructions Reference Manual (W502)

2-367

2 Instruction Descriptions

The Exchange instruction exchanges the values of InOut1 and InOut2.

InOut1=abc

Exchanged.

InOut1=abc

InOut2=def

InOut2=def

Precautions for Correct Use

· The data types of InOut1 and InOut2 must be the same. If they are different, a building error will occur.
· Return value Out is not used when the instruction is used in ST.
· An error occurs in the following cases. ENO will be FALSE, and InOut1 and InOut2 will not change.
· Both InOut1 and InOut2 are STRING data and the length of the text string in one of them does not fit into the other.

2-368

NJ/NX-series Instructions Reference Manual (W502)

Data Movement Instructions

2 Instruction Descriptions

AryExchange

The AryExchange instruction exchanges the elements of two arrays.

Instruction AryExchange

Name
Array Data Exchange

FB/FUN FUN

Graphic expression

(@)AryExchange

EN

ENO

InOut1

ST expression
AryExchange(InOut1, InOut2, Size);

InOut2

2

Size

Out

AryExchange

Variables

Name Size
InOut1[] and InOut2[] (arrays) Out

Meaning
Number of elements
Arrays to exchange

I/O Input
In-out

Return value

Output

Description Number of elements to exchange Arrays to exchange
Always TRUE

Valid range

Unit

Depends on data type. ---

Depends on data type. ---

Default 1
---

TRUE only

---

---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

Size
InOut1[] (array)
InOut2[] (array) Out

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK
Arrays of enumerations or structures can also be specified. Must be an array with the same data type as InOut1[].
OK

Function
The AryExchange instruction exchanges Size elements from InOut1[0] of array to exchange InOut1[] with Size elements from InOut2[0] of array to exchange InOut2[].

NJ/NX-series Instructions Reference Manual (W502)

2-369

2 Instruction Descriptions

The following example is for when Size is UINT#2.

LD

ST

AryExchange(abc[1], def[2], UINT#2);

abc[1]
def[2] UINT#2

AryExchange

EN InOut1

ENO

InOut2

Size

abc[1] def[2]

Size=UINT#2

InOut1[0]=abc[1] InOut1[1]=abc[2]

Exchanged InOut2[0]=def[2] InOut2[1]=def[3]

Additional Information
· Use the MOVE instruction (page 2-354) to assign constants to variables. · Use the MemCopy instruction (page 2-363) to copy the values of variables to other variables.
Precautions for Correct Use
· Use the same data type for the elements of InOut1[] and InOut2[]. If they are different, a building error will occur.
· If the value of Size is 0, the value of Out will be TRUE and InOut1[] and InOut2[] will not change. · Return value Out is not used when the instruction is used in ST. · An error occurs in the following cases. ENO will be FALSE, and InOut1[] and InOut2[] will not change.
· The value of Size exceeds the array range of InOut1[] or InOut2[]. · InOut1[] and InOut2[] are STRING arrays and there is an element with a text string that exceeds
the size of the element in the other array. · InOut1[] and InOut2[] are STRING arrays and there is an element that does not end in a NULL
character.

2-370

NJ/NX-series Instructions Reference Manual (W502)

Data Movement Instructions

2 Instruction Descriptions

AryMove

The AryMove instruction moves one or more array elements. The data types of the move source and move destination can be different.

Instruction AryMove

Name Array Move

FB/FUN FUN

Graphic expression

ST expression

(@)AryMove

AryMove(In, AryOut, Size);

EN

ENO

In

Out

AryOut
2

Size

AryMove

Variables

Name

Meaning

I/O

Description

Valid range

Unit

In[] (array) Size

Move source array
Number of elements

Input

Array to move
Number of elements to move

Depends on data type. ---

AryOut[] (array)

Move result In-out array

Move result array

Depends on data type. ---

Out

Return

Output

Always TRUE

value

TRUE only

---

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default *
1
-----

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In[] (array)
Size AryOut[] (array) Out

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK Arrays of enumerations or structures can also be specified. OK
OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK Arrays of enumerations or structures can also be specified.
OK

Function
The AryMove instruction moves Size elements of move source array In[] starting from In[0] to move result array AryOut[] starting from AryOut[0]. The data types of In[] and AryOut[] can be different.

NJ/NX-series Instructions Reference Manual (W502)

2-371

2 Instruction Descriptions

The following example is for when Size is UINT#2.

LD

ST

AryMove(abc[1], def[2], UINT#2);

abc[1]
def[2] UINT#2

AryMove

EN In AryOut

ENO

Size

def[2]

In[0]=abc[1] Size=UINT#2 In[1]=abc[2]

Moved

AryOut[0]=def[2] AryOut[1]=def[3]

Additional Information

· If the data types of In[] and AryOut[] are the same, the MemCopy instruction is faster.
· You can specify the same array for In[] and AryOut[]. Also, the move source and destination data can overlap. The following example is for when In[0] is A[2], AryOut[0] is A[4], and Size is UINT#3.

Size=UINT#3

A[0] A[1] In=A[2] A[3] AryOut=A[4] A[5] A[6]

1234 2345 3456 4567 5678 6789 7890

A[0] A[1] In=A[2] A[3] AryOut=A[4] A[5] A[6]

1234 2345 3456 4567 3456 4567 5678

Precautions for Correct Use
· The data types of In[] and AryOut[] can be different as long as they are both in one of the following groups. The valid range of AryOut[] must include the valid range of In[]. · BYTE, WORD, DWORD, and LWORD · USINT, UINT, UDINT, ULINT, SINT, INT, DINT, LINT, REAL, and LREAL
· If In[] is an array of structures, use the same data types for In[] and AryOut[]. · If the value of Size is 0, the value of Out will be TRUE and AryOut[] will not change. · Return value Out is not used when the instruction is used in ST. · An error occurs in the following case. ENO will be FALSE, and AryOut[] will not change.
· The value of Size exceeds the size of In[] or AryOut[]. · In[] or AryOut[] is a STRING array and the length of a text string in an element to move exceeds
the size of the element in AryOut[].

2-372

NJ/NX-series Instructions Reference Manual (W502)

Data Movement Instructions

2 Instruction Descriptions

Clear

The Clear instruction initializes a variable.

Instruction

Name

FB/FUN

Clear

Initialize

FUN

Graphic expression
(@)Clear EN ENO InOut

ST expression Clear(InOut);

Out
2

Variables

Clear

Name InOut
Out

Meaning
Data to initialize
Return value

I/O In-out
Output

Description Data to initialize
Always TRUE

Valid range

Unit

Depends on data type. ---

TRUE only

---

Default
---
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

InOut Out

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK An enumeration, array, array element, structure, or structure member can also be specified.
OK

Function

The Clear instruction initializes the value of data to initialize InOut. If an initial value attribute is set for a variable, the specified initial value is used. If an initial value attribute is not set, the default initial value for the data type of InOut is used. If InOut is an external variable, the default initial value of the data type of InOut is used regardless of the initial value attribute of the global variable for the external variable.
The default values for the data types are given below.

BOOL

Data type

FALSE

Default initial value

BYTE, WORD, DWORD, or LWORD USINT, UINT, UDINT, ULINT, SINT, INT, DINT, LINT, REAL, or LREAL TIME DATE

16#0 0
T#0ms D#1970-1-1

TOD DT STRING

TOD#0:0:0 DT#1970-1-1-0:0:0 ''

NJ/NX-series Instructions Reference Manual (W502)

2-373

2 Instruction Descriptions

If InOut is an array, array element, structure, or structure member, the following processing is performed.

InOut

Processing

Array

All elements in the array are initialized.

Array element

Only the specified element is initialized.

Structure

All members in the structure are initialized.

Structure member

Only the specified member is initialized.

The following figure shows a programming example. The value of variable abc is initialized.

LD

ST

Clear(abc);

Clear

EN ENO

InOut

abc

abc

The Clear instruction initializes the value of InOut. The data type of abc is INT, so the value of abc will be INT#0.

Initialized. InOut=abc INT#100

InOut=abc INT#0

Additional Information
· If InOut is an array that is used as a stack, execute this instruction and also set the variable that manages the number of items stored in the stack to 0.
· If you initialize a cam data variable with this instruction, it will not contain the data that was saved with the MC_SaveCamTable instruction. It will contain all zeros.

Precautions for Correct Use
· Return value Out is not used when the instruction is used in ST. · To initialize an enumerated variable, use the Initial Value attribute. If the Initial Value attribute is not
set, the value of the enumerated variable will be 0. · Do not perform processing that meets all of the following conditions. The operation is not reliable.
· Pass one element of a BOOL array as an in-out variable to a function or function block. · Execute the Clear instruction in the function or function block. · Use the in-out variable that received the element of the above BOOL array as the parameter to
pass to the Clear instruction.

2-374

NJ/NX-series Instructions Reference Manual (W502)

Data Movement Instructions

2 Instruction Descriptions

Copy**ToNum (Bit String to Signed Integer)

The Copy**ToNum instruction copies the content of a bit string directly to a signed integer.

Instruction

Name

FB/FUN

Graphic expression

ST expression

Copy**ToNum

Bit Pattern Copy FUN (Bit String to Signed Integer) Group

(@)Copy**ToNum

Out:=Copy**ToNum(In);

EN In

ENO Out

"**" must be a bit string data

2

"**" must be a bit string data type. type.

Variables

Name In
Out

Meaning
Copy source
Copy destination

I/O Input
Output

Description Copy source
Copy destination

Valid range

Unit

Depends on data type. ---

Depends on data type. ---

Default 0
---

Bit strings

Integers

Times, durations, dates, and text strings

Copy**ToNum (Bit String to Signed Integer)
STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK OK OK OK

Out

Must be a signed integer data type that is the same size as the data type of In.

Function

The Copy**ToNum instruction copies the content of copy source In directly to copy destination Out. There are four instructions depending on the data types of In and Out.

In

Out

Instruction

BYTE

SINT

CopyByteToNum

WORD

INT

CopyWordToNum

DWORD

DINT

CopyDwordToNum

LWORD

LINT

CopyLwordToNum

NJ/NX-series Instructions Reference Manual (W502)

2-375

2 Instruction Descriptions

The following example for the CopyWordToNum instruction is for when In is WORD#16#4D2.

LD

ST

abc:=CopyWordToNum(WORD#16#4D2);

CopyWordToNum

EN WORD#16#4D2 In

ENO abc

In

WORD#16#4D2 (WORD#2#00000100_11010010)

INT#1234 Out = abc (2#00000100_11010010)

2-376

NJ/NX-series Instructions Reference Manual (W502)

Data Movement Instructions

2 Instruction Descriptions

Copy**To*** (Bit String to Real Number)

The Copy**To*** instruction copies the content of a bit string directly to a real number.

Instruction Copy**To***

Name
Bit Pattern Copy (Bit String to Real Number) Group

FB/FUN FUN

Graphic expression

ST expression

(@)CopyDwordToReal

Out:=CopyDwordToReal(In);

EN In

ENO

or Out Out:=CopyLwordToLreal(In);

2

(@)CopyLwordToLreal

EN

ENO

In

Out

Variables

Name In
Out

Meaning
Copy source
Copy destination

I/O Input
Output

Description Copy source
Copy destination

Valid range

Unit

Depends on data type. ---

Depends on data type. ---

Default 0
---

Bit strings

Integers

Times, durations, dates, and text strings

Copy**To*** (Bit String to Real Number)
STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK OK

Out

Must be REAL if the data type of In is DWORD and LREAL if the data type of In is LWORD.

NJ/NX-series Instructions Reference Manual (W502)

2-377

2 Instruction Descriptions

Function

The Copy**To*** instruction copies the content of copy source In directly to copy destination Out. There are two instructions depending on the data types of In and Out.

In

Out

Instruction

DWORD

REAL

CopyDwordToReal

LWORD

LREAL

CopyLwordToLreal

The following example for the CopyDwordToReal instruction is for when In is DWORD#16#40200000.

LD

ST

abc:=CopyDwordToReal(DWORD#16#40200000);

CopyDwordToReal

EN DWORD#16#40200000 In

ENO abc

DWORD#16#40200000 In (DWORD#2#01000000_00100000_00000000_00000000)

Out = abc

REAL#2.5 (2#01000000_00100000_00000000_00000000)

2-378

NJ/NX-series Instructions Reference Manual (W502)

Data Movement Instructions

2 Instruction Descriptions

CopyNumTo** (Signed Integer to Bit String)

The CopyNumTo** instruction copies the content of a signed integer directly to a bit string.

Instruction

Name

FB/FUN

Graphic expression

ST expression

CopyNumTo**

Bit Pattern Copy (Signed Integer to Bit String) Group

FUN

(@)CopyNumTo**

Out:=CopyNumTo**(In);

EN In

ENO Out

"**" must be a bit string data

2

"**" must be a bit string data type.

type.

Variables

Name In
Out

Meaning
Copy source
Copy destination

I/O Input
Output

Description Copy source
Copy destination

Valid range

Unit

Depends on data type. ---

Depends on data type. ---

Default 0
---

Bit strings

Integers

Times, durations, dates, and text strings

CopyNumTo** (Signed Integer to Bit String)
STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK OK OK OK

Out

Must be a bit string data type that is the same size as the data type of In.

Function

The CopyNumTo** instruction copies the content of copy source In directly to copy destination Out. There are four instructions depending on the data types of In and Out.

In SINT INT

Out BYTE WORD

Instruction CopyNumToByte CopyNumToWord

DINT LINT

DWORD LWORD

CopyNumToDword CopyNumToLword

NJ/NX-series Instructions Reference Manual (W502)

2-379

2 Instruction Descriptions

The following example for the CopyNumToWord instruction is for when In is INT#1234.

LD

ST

abc:=CopyNumToWord(INT#1234);

CopyNumToWord

EN INT#1234 In

ENO abc

In

INT#1234 (2#00000100_11010010)

Out = abc

WORD#16#4D2 (2#00000100_11010010)

2-380

NJ/NX-series Instructions Reference Manual (W502)

Data Movement Instructions

2 Instruction Descriptions

CopyNumTo** (Signed Integer to Real Number)

The CopyNumTo** instruction copies the content of a signed integer directly to a real number.

Instruction CopyNumTo**

Name
Bit Pattern Copy (Signed Integer to Real Number) Group

FB/FUN FUN

Graphic expression

ST expression

(@)CopyNumToReal

Out:=CopyNumToReal(In);

EN In

ENO

or Out Out:=CopyNumToLreal(In);

2

(@)CopyNumToLreal

EN

ENO

In

Out

Variables

Name In
Out

Meaning
Copy source
Copy destination

I/O Input
Output

Description Copy source
Copy destination

Valid range

Unit

Depends on data type. ---

Depends on data type. ---

Default 0
---

Bit strings

Integers

Times, durations, dates, and text strings

CopyNumTo** (Signed Integer to Real Number)
STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK OK

Out

Must be REAL if the data type of In is DINT and LREAL if the data type of In is LINT.

Function

The CopyNumTo** instruction copies the content of copy source In directly to copy destination Out. There are two instructions depending on the data types of In and Out.

In DINT LINT

Out REAL LREAL

Instruction CopyNumToReal CopyNumToLreal

NJ/NX-series Instructions Reference Manual (W502)

2-381

2 Instruction Descriptions

The following example for the CopyNumToReal instruction is for when In is DINT#1075838976.

LD

ST

abc:=CopyNumToReal(DINT#1075838976);

CopyNumToReal

EN DINT#1075838976 In

ENO abc

DINT#1075838976 In (2#01000000_00100000_00000000_00000000)

Out = abc

REAL#2.5 (2#01000000_00100000_00000000_00000000)

2-382

NJ/NX-series Instructions Reference Manual (W502)

Data Movement Instructions

2 Instruction Descriptions

Copy**To*** (Real Number to Bit String)

The Copy**To*** instruction copies the content of a real number directly to a bit string.

Instruction Copy**To***

Name
Bit Pattern Copy (Real Number to Bit String) Group

FB/FUN FUN

Graphic expression

ST expression

(@)CopyRealToDword

Out:=CopyRealToDword(In);

EN In

ENO

or Out Out:=CopyLrealToLword(In);

2

(@)CopyLrealToLword

EN

ENO

In

Out

Variables

Name In
Out

Meaning
Copy source
Copy destination

I/O Input
Output

Description Copy source
Copy destination

Valid range

Unit

Depends on data type. ---

Depends on data type. ---

Default 0.0
---

Bit strings

Integers

Times, durations, dates, and text strings

Copy**To*** (Real Number to Bit String)
STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK OK

Out

Must be DWORD if the data type of In is REAL and LWORD if the data type of In is LREAL.

NJ/NX-series Instructions Reference Manual (W502)

2-383

2 Instruction Descriptions

Function

The Copy**To*** instruction copies the content of copy source In directly to copy destination Out. There are two instructions depending on the data types of In and Out.

In

Out

Instruction

REAL

DWORD

CopyRealToDword

LREAL

LWORD

CopyLrealToLword

The following example for the CopyRealToDword instruction is for when In is REAL#2.5.

LD

ST

abc:=CopyRealToDword(REAL#2.5);

CopyRealToDword

EN REAL#2.5 In

ENO abc

REAL#2.5 In (2#01000000_00100000_00000000_00000000)

Out = abc DWORD#16#40200000 (2#01000000_00100000_00000000_00000000)

2-384

NJ/NX-series Instructions Reference Manual (W502)

Data Movement Instructions

2 Instruction Descriptions

Copy**ToNum (Real Number to Signed Integer)

The Copy**ToNum instruction copies the content of a real number directly to a signed integer.

Instruction Copy**ToNum

Name
Bit Pattern Copy (Real Number to Signed Integer) Group

FB/FUN FUN

Graphic expression

ST expression

(@)CopyRealToNum

Out:=CopyRealToNum(In);

EN In

ENO

or Out Out:=CopyLrealToNum(In);

2

(@)CopyLrealToNum

EN

ENO

In

Out

Variables

Name In
Out

Meaning
Copy source
Copy destination

I/O Input
Output

Description Copy source
Copy destination

Valid range

Unit

Depends on data type. ---

Depends on data type. ---

Default 0.0
---

Bit strings

Integers

Times, durations, dates, and text strings

Copy**ToNum (Real Number to Signed Integer)
STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK OK

Out

Must be DINT if the data type of In is REAL and LINT if the data type of In is LREAL.

Function

The Copy**ToNum instruction copies the content of copy source In directly to copy destination Out. There are two instructions depending on the data types of In and Out.

In REAL LREAL

Out DINT LINT

Instruction CopyRealToNum CopyLrealToNum

NJ/NX-series Instructions Reference Manual (W502)

2-385

2 Instruction Descriptions

The following example for the CopyRealToNum instruction is for when In is REAL#2.5.

LD

ST

abc:=CopyRealToNum(REAL#2.5);

CopyRealToNum

EN REAL#2.5 In

ENO abc

In

REAL#2.5 (2#01000000_00100000_00000000_00000000)

Out = abc

DINT#1075838976 (2#01000000_00100000_00000000_00000000)

2-386

NJ/NX-series Instructions Reference Manual (W502)

Shift Instructions

2
Shift Instructions

Instruction AryShiftReg AryShiftRegLR ArySHL and ArySHR
SHL and SHR
NSHLC and NSHRC
ROL and ROR

Name Shift Register Reversible Shift Register Array N-element Left Shift/ Array N-element Right Shift N-bit Left Shift/ N-bit Right Shift Shift N-bits Left with Carry/ Shift N-bits Right with Carry Rotate N-bits Left/ Rotate N-bits Right

Page 2-388 2-390 2-393
2-396
2-398
2-400

NJ/NX-series Instructions Reference Manual (W502)

2-387

2 Instruction Descriptions

AryShiftReg

The AryShiftReg instruction shifts a shift register one bit to the left and inserts the input value to the least-significant bit. The shift register consists of array elements.

Instruction AryShiftReg

Name Shift Register

FB/FUN FB

Graphic expression

AryShiftReg_instance

AryShiftReg

Shift Reset In InOut

ENO

ST expression
AryShiftReg_instance(Shift, Reset, In, InOut, Size);

Size

Variables

Name

Meaning

I/O

Shift

Shift

Reset In Size
InOut[] (array)

Reset Input value
Number of elements in array of bit strings Array of bit strings

Input In-out

Description
Shifted when signal changes to TRUE.
TRUE: Register is reset.
Value to insert to least-significant bit of InOut[].
Number of elements to use as a shift register in InOut[].

Valid range Depends on data type.

Unit
---

Default FALSE 1

Array of bit strings

Depends on data type. ---

---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

Shift

OK

Reset

OK

In

OK

Size

OK

InOut[] (array)

OK OK OK OK OK

2-388

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Shift Instructions

Function

The AryShiftReg instruction shifts Size array elements in the array of bit strings InOut[] to the left (i.e., toward most-significant bit) when Shift changes to TRUE. The shift operation starts from InOut[0]. Input value In is inserted to the least-significant bit. The most-significant bit of the array of bit strings is output to the Carry (CY) Flag (P_CY).

P_CY

Size elements In

2

InOut[1]

InOut[0]

When Reset is TRUE, CY and all of bits in Size elements starting from InOut[0] are set to FALSE.

AryShiftReg

The following example is for when InOut[] is a BYTE array and Size is UINT#2.

LD

ST

A
abc def
ghi[1] UINT#2

AryShiftReg_instance

AryShiftReg

Shift Reset In InOut

ENO

Size

ghi[1]

AryShiftReg_instance(A, abc, def, ghi[1], UINT#2);

Size=UINT#2

InOut[1]=ghi[2] 1 0 1 0 1 0 0 0

InOut[0]=ghi[1] 1 1 0 1 0 0 1 1

In=def 1

P_CY InOut[1]=ghi[2]

1

0 1 0 1 0 0 0 1

InOut[0]=ghi[1] 1 0 1 0 0 1 1 1

Related System-defined Variables

P_CY

Name

Meaning Carry (CY) Flag

Data type BOOL

Description Value stored in Carry Flag

Precautions for Correct Use
· While Reset is TRUE, the register is not shifted even if Shift changes to TRUE. · ENO will change to TRUE when Shift changes to TRUE and the shift operation is performed normally,
or when Reset is TRUE and the reset operation is performed normally. · The InOut[] does not change if the value of Size is 0. · An error occurs in the following case. ENO will be FALSE, and InOut[] will not change.
· The value of Size exceeds the array area of InOut[].

NJ/NX-series Instructions Reference Manual (W502)

2-389

2 Instruction Descriptions

AryShiftRegLR

The AryShiftRegLR instruction shifts a bit string one bit to the left or right and inserts the input value to the least-significant or most-significant bit. The bit string consists of array elements.

Instruction AryShiftRegLR

Name
Reversible Shift Register

FB/FUN FB

Graphic expression

AryShiftRegLR_instance

AryShiftRegLR

ShiftL ShiftR Reset In InOut

ENO

ST expression
AryShiftRegLR_instance (ShiftL, ShiftR,Reset, In, InOut, Size);

Size

Variables

Name

Meaning

I/O

ShiftL

Left shift

ShiftR

Right shift

Reset In

Reset Input value

Input

Size
InOut[] (array)

Number of elements in array of bit strings
Array of bit strings

In-out

Description
Shifted left when signal changes to TRUE.
Shifted right when signal changes to TRUE.
TRUE: Register is reset.
Value to insert to least-significant or most-significant bit of InOut[]
Number of elements to use as a shift register in InOut[].

Valid range Depends on data type.

Unit
---

Default FALSE 1

Array of bit strings

Depends on data type. ---

---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

ShiftL

OK

ShiftR

OK

Reset

OK

In

OK

Size

OK

InOut[] (array)

OK OK OK OK OK

2-390

NJ/NX-series Instructions Reference Manual (W502)

Shift Instructions

2 Instruction Descriptions

Function

The AryShiftRegLR instruction shifts Size array elements of array of bit strings InOut[] to the left when ShiftL changes to TRUE. The shift operation starts from InOut[0]. Input value In is inserted to the leastsignificant bit. The most-significant bit of the array of bit strings is output to the Carry (CY) Flag (P_CY).

P_CY

Size elements In

2

InOut[1]

InOut[0]

AryShiftRegLR

When ShiftR changes to TRUE, the bits are shifted one bit to the right and In is inserted to the most-significant bit. The least-significant bit of the array of bit strings is output to the Carry (CY) Flag (P_CY).

Size elements

In

P_CY

InOut[1]

InOut[0]

When Reset is TRUE, P_CY and all of the bits in Size elements starting from InOut[0] are set to FALSE.

The following example is for when InOut is BYTE data, Size is UINT#2 and ShiftL changes to TRUE.

LD

ST

A
B abc def
ghi[1] UINT#2

AryShiftRegLR_instance

AryShiftRegLR

ShiftL ShiftR Reset In InOut

ENO

Size

AryShiftRegLR_instance(A, B, abc, def, ghi[1], UINT#2); ghi[1]

Size=UINT#2

InOut[1]=ghi[2] 1 0 1 0 1 0 0 0

InOut[0]=ghi[1] 1 1 0 1 0 0 1 1

In=def 1

P_CY InOut[1]=ghi[2]

1

0 1 0 1 0 0 0 1

InOut[0]=ghi[1] 1 0 1 0 0 1 1 1

NJ/NX-series Instructions Reference Manual (W502)

2-391

2 Instruction Descriptions

Related System-defined Variables

P_CY

Name

Meaning Carry (CY) Flag

Data type BOOL

Description Value stored in Carry Flag

Precautions for Correct Use
· While Reset is TRUE, the register is not shifted even if ShiftL or ShiftR changes to TRUE. · The register is not shifted if both ShiftL and ShiftR change to TRUE at the same time. · ENO will change to TRUE when ShiftL or ShiftR changes to TRUE and the shift operation is per-
formed normally, or when Reset is TRUE and the reset operation is performed normally. · The InOut[] does not change if the value of Size is 0. · An error occurs in the following case. ENO will be FALSE, and InOut[] will not change.
· The value of Size exceeds the array area of InOut[].

2-392

NJ/NX-series Instructions Reference Manual (W502)

Shift Instructions

2 Instruction Descriptions

ArySHL and ArySHR

These instructions shift array elements by one or more elements. ArySHL: Shifts the array to the left (toward the higher elements). ArySHR: Shifts the array to the right (toward the lower elements).

Instruction ArySHL

Name
Array N-element Left Shift

FB/FUN FUN

ArySHR

Array N-element Right Shift

FUN

Graphic expression

ST expression

(@)ArySHL

EN InOut

ENO

ArySHL(InOut, Size, Num);
2

ArySHL and ArySHR

Size

Out

Num

(@)ArySHR

EN InOut

ENO

ArySHR(InOut, Size, Num);

Size

Out

Num

Variables

Name Size
Num
InOut[] (array) Out

Meaning

I/O

Number of elements in shift register
Number of elements to shift

Input

Shift register array

In-out

Return value

Output

Description

Valid range

Unit

Number of elements in shift register

Depends on data type. --Number of elements to shift

Shift register array

Depends on data type. ---

Always TRUE

TRUE only

---

Default 1
-----

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

Size Num
InOut[] (array)
Out

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK Arrays of structures can also be specified. OK

NJ/NX-series Instructions Reference Manual (W502)

2-393

2 Instruction Descriptions

Function

These instructions shift the upper Size elements in shift register array InOut[] by Num elements. The values that are shifted out of the array are discarded. The default initial value for the data type of InOut[] is stored in the empty elements. If InOut[] is an array of structures, the members of the structures in all elements are initialized. The default values for the data types are given below.

Data type of InOut

Default

BOOL

FALSE

BYTE, WORD, DWORD, or LWORD

16#0

USINT, UINT, UDINT, ULINT, SINT, INT, DINT, LINT, 0 REAL, or LREAL

TIME

T#0ms

DATE

D#1970-1-1

TOD

TOD#0:0:0

DT

DT#1970-1-1-0:0:0

STRING

''

 ArySHL
The ArySHL instruction shifts the array to the left (toward the higher elements of the array).

 ArySHR
The ArySHR instruction shifts the array to the right (toward the lower elements of the array). The following example shows the ArySHL instruction when Size is UINT#6 and Num is UINT#2.

LD

ST

ArySHL(abc[1], UINT#6, UINT#2);

abc[1] UINT#6 UINT#2

ArySHL

EN InOut

ENO

Size Num

abc[1]

Size=UINT#6

InOut[5] =abc[6]
9

InOut[4] =abc[5]
8

InOut[3] =abc[4]
7

InOut[2] =abc[3]
3

InOut[1] =abc[2]
2

InOut[0] =abc[1]
1

Discarded.

InOut[5] =abc[6]
7

InOut[4] =abc[5]
3

InOut[3] =abc[4]
2

InOut[2] =abc[3]
1

InOut[1] =abc[2]
0

InOut[0] =abc[1]
0

2-394

Zeros inserted. NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Additional Information
If InOut[] is BOOL data, the results will be the same as shifting a bit string of Size bits by Num bits.

Precautions for Correct Use

· The shift operation is not performed if the value of Num is 0.

· If the value of Num is larger than Size, all values from InOut[0] to InOut[Size-1] are initialized.

· Return value Out is not used when the instruction is used in ST.

· An error occurs in the following case. ENO will be FALSE, and InOut[] will not change.

2

· The value of Size exceeds the array area of InOut[].

Shift Instructions

ArySHL and ArySHR

NJ/NX-series Instructions Reference Manual (W502)

2-395

2 Instruction Descriptions

SHL and SHR

These instructions shift a bit string by one or more bits. SHL: Shifts the bit string to the left (toward the higher bits). SHR: Shifts the bit string to the right (toward the lower bits).

Instruction SHL

Name N-bit Left Shift

FB/FUN FUN

SHR

N-bit Right Shift

FUN

Graphic expression

(@)SHL

EN

ENO

In

Out

Num

(@)SHR

EN

ENO

In

Out

Num

ST expression Out:=SHL(In, Num);
Out:=SHR(In, Num);

Variables

Name In
Num*2 Out

Meaning
Data to shift
Number to shift
Processing result

I/O Input Output

Description Data to shift
Number of bits to shift
Processing result

Valid range

Unit

Depends on data type. ---

0 to No. of bits in In

Bits

Depends on data type. ---

Default
*1
1 ---

*1 If you omit the input parameter, the default value is not applied. A building error will occur.
*2 On Sysmac Studio version 1.03, you can use "N" instead of "Num" to more clearly show the correspondence between the variables and the parameter names in ST expressions. For example, you can use the following notation: Out:=SHL(In:=BYTE#16#89, N:=ULINT#2);.

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In Num
Out

OK OK OK OK
OK
*

OK
*
Must be same data type as In

* With a CPU Unit with unit version 1.02 or later and Sysmac Studio version 1.03 or higher, use a ULINT variable. With a CPU Unit with unit version 1.01 or earlier and Sysmac Studio version 1.02 or lower, use a USINT variable.

Function
These instructions shift data to shift In (bit string data) by the number of bits specified in number to shift Num. The bits that are shifted out of the register are discarded and zeros are inserted into the other end of the register.

2-396

NJ/NX-series Instructions Reference Manual (W502)

Shift Instructions

2 Instruction Descriptions

 SHL
The SHL instruction shifts bits from right to left (from least-significant to most-significant bits). The following example is for when In is BYTE#16#89 and Num is ULINT#2.

LD

ST

abc:=SHL(BYTE#16#89, ULINT#2);

SHL

BYTE#16#89 ULINT#2

EN In Num

ENO abc

Bit 7

Bit 0

2

In 1 0 0 0 1 0 0 1

Out=abc 0 0 1 0 0 1 0 0

SHL and SHR

Shifted 2 bits left.

Zeros inserted to lower 2 bits.

 SHR
The SHR instruction shifts bits from left to right (from most-significant to least-significant bits). The following example is for when In is BYTE#16#89 and Num is ULINT#2.

LD

ST

abc:=SHR(BYTE#16#89, ULINT#2);

SHR

BYTE#16#89 ULINT#2

EN In Num

ENO abc

Bit 7

Bit 0

In 1 0 0 0 1 0 0 1

Out=abc 0 0 1 0 0 0 1 0

Shifted 2 bits right.

Zeros inserted to upper 2 bits.

Additional Information

The ROL and ROR instructions insert the bits that are shifted out of the register into the other end of the register.

Precautions for Correct Use
· The data types of In and Out must be the same. · If Num is 0, an error will not occur and the value of In will be assigned directly to Out. · If the value of Num exceeds the number of bits specified in In, an error will not occur and the value of
Out will be 16#0.

NJ/NX-series Instructions Reference Manual (W502)

2-397

2 Instruction Descriptions

NSHLC and NSHRC

These instructions shift an array of bit strings by one or more bits. The Carry (CY) Flag is included. NSHLC: Shifts the array to the left (toward the higher elements). NSHRC: Shifts the array to the right (toward the lower elements).

Instruction NSHLC

Name

FB/FUN

Shift N-bits Left with FUN Carry

NSHRC

Shift N-bits Right with Carry

FUN

Graphic expression

(@)NSHLC

EN InOut

ENO

Size

Out

Num

(@)NSHRC

EN InOut

ENO

Size

Out

Num

ST expression NSHLC(InOut, Size, Num);
NSHRC(InOut, Size, Num);

Variables

Name Size
Num InOut[] (array) Out

Meaning
Number of bits in shift register
Number of bits to shift
Shift register array
Return value

I/O Input In-out Output

Description Number of bits in shift register Number of bits to shift Bit string array to shift
Always TRUE

Valid range

Unit

Default

Depends on data type. Bits

1

Depends on data type. ---

---

TRUE only

---

---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

Size Num InOut[] (array) Out

OK OK OK OK OK OK OK
OK

2-398

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Shift Instructions

Function

These instructions shift Size array elements in shift register array InOut[] by the number of bits specified in Num. The shift register starts at InOut[0]. The last bit that is shifted out of the register is output to the Carry (CY) Flag. Zeros are inserted for the bits at the other end.

 NSHLC
The NSHLC instruction shifts bits from the lower elements in the array to the higher elements and from the least-significant bits to the most-significant bits.

 NSHRC
The NSHRC instruction shifts bits from the higher elements in the array to the lower elements and from 2
the most-significant bits to the least-significant bits.
The following example shows the NSHLC instruction when InOut[] is a BYTE array, Size is USINT#80 and Num is USINT#3.

LD

ST

NSHLC and NSHRC

NSHLC(abc[1], USINT#80, USINT#3);

abc[1] USINT#80
USINT#3

NSHLC

EN InOut

ENO

Size Num

abc[1]

InOut[9] =abc[10]
0 1 1

Size = USINT#80 bits

InOut[8] =abc[9]
1 0 1

InOut[1] =abc[2]

Discarded. CY

InOut[9] =abc[10]

InOut[8] =abc[9]

1

1 0 1

Last bit shifted out of register is stored in CY Flag.

InOut[1] =abc[2]

0 0 1

Bit 7

Bit 0

InOut[0] =abc[1] 0 0 1
Num = USINT#3 (Shift 3 bits.)
InOut[0] =abc[1]
0 0 0
FALSE inserted for Num = USINT#3 (3 bits).

Related System-defined Variables

P_CY

Name

Meaning Carry (CY) Flag

Data type BOOL

Description Value stored in Carry Flag

Precautions for Correct Use
· The shift operation is not performed if the value of Num is 0. · If the value of Num is larger than Size, Size bits from bit 0 of InOut[0] are changed to FALSE. The
value of the Carry Flag (CY) changes to FALSE. · Return value Out is not used when the instruction is used in ST. · An error occurs in the following case. ENO will be FALSE, and InOut[] will not change.
· The value of Size exceeds the array area of InOut[].

NJ/NX-series Instructions Reference Manual (W502)

2-399

2 Instruction Descriptions

ROL and ROR

These instructions rotate a bit string by one or more bits. ROL: Rotates the bit string to the left (toward the higher bits). ROR: Rotates the bit string to the right (toward the lower bits).

Instruction ROL

Name Rotate N-bits Left

FB/FUN FUN

ROR

Rotate N-bits Right FUN

Graphic expression

(@)ROL

EN

ENO

In

Out

Num

(@)ROR

EN

ENO

In

Out

Num

ST expression Out:=ROL(In, Num);
Out:=ROR(In, Num);

Variables

Name In
Num*2 Out

Meaning
Data to rotate
Number of bits
Processing result

I/O Input Output

Description Data to rotate
Number of bits to rotate
Processing result

Valid range

Unit

Depends on data type. ---

0 to No. of bits in In

Bits

Depends on data type. ---

Default *1
1
---

*1 If you omit the input parameter, the default value is not applied. A building error will occur.
*2 On Sysmac Studio version 1.03, you can use "N" instead of "Num" to more clearly show the correspondence between the variables and the parameter names in ST expressions. For example, you can use the following notation: Out:=ROL(In:=BYTE#16#89, N:=ULINT#2);.

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In Num
Out

OK OK OK OK
OK *

OK *
Must be same data type as In

* With a CPU Unit with unit version 1.02 or later and Sysmac Studio version 1.03 or higher, use a ULINT variable. With a CPU Unit with unit version 1.01 or earlier and Sysmac Studio version 1.02 or lower, use a USINT variable.

Function
These instructions rotate data to rotate In (bit string data) by the number of bits specified in number of bits Num. Bits that are shifted out of the register are inserted into the other end of the register.

2-400

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Shift Instructions

 ROL
The ROL instruction rotates bits from right to left (from least-significant to most-significant bits). The following example is for when In is BYTE#16#89 and Num is ULINT#2.

LD

ST

abc:=ROL(BYTE#16#89, ULINT#2);

ROL

BYTE#16#89 ULINT#2

EN In Num

ENO abc

2

Bit 7

Bit 0

In 1 0 0 0 1 0 0 1

Out=abc 0 0 1 0 0 1 1 0

Shifted 2 bits left.

ROL and ROR

Most-significant 2 bits of In are inserted into least-significant 2 bits.

 ROR

The ROR instruction rotates bits from left to right (from most-significant to least-significant bits). The following example is for when In is BYTE#16#89 and Num is ULINT#2.

LD

ST

abc:=ROR(BYTE#16#89, ULINT#2);

ROR

BYTE#16#89 ULINT#2

EN In Num

ENO abc

Bit 7

Bit 0

In 1 0 0 0 1 0 0 1

Out=abc 0 1 1 0 0 0 1 0

Shifted 2 bits right.

Least-significant 2 bits of In are inserted into most-significant 2 bits.

Additional Information
The SHL and SHR instructions discard the bits that are shifted out of the register and insert zeros into the other end of the register.

Precautions for Correct Use
· The data types of In and Out must be the same. · If Num is 0, an error will not occur and the value of In will be assigned directly to Out. · If the value of Num exceeds the number of bits specified in In, an error will not occur and the bits will
be rotated by the number of bits specified in Num. For example, if In is WORD data, the value of Out will be the same regardless of whether the value of Num is USINT#1 or USINT#17.

NJ/NX-series Instructions Reference Manual (W502)

2-401

2 Instruction Descriptions

2-402

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2
Conversion Instructions

Instruction Swap Neg Decoder Encoder BitCnt

Name Swap Bytes Reverse Sign Bit Decoder Bit Encoder Bit Counter

ColmToLine_** LineToColm Gray UTF8ToSJIS
SJISToUTF8
PWLApprox and PWLApproxNoLineChk
PWLLineChk MovingAverage DispartReal UniteReal
NumToDecString and NumToHexString
HexStringToNum_**

Column to Line Conversion Group Line to Column Conversion Gray Code Conversion UTF-8 to SJIS Character Code Conversion SJIS to UTF-8 Character Code Conversion Broken Line Approximation with Broken Line Data Check and Broken Line Approximation without Broken Line Data Check Broken Line Data Check Moving Average Separate Mantissa and Exponent Combine Real Number Mantissa and Exponent Fixed-length Decimal Text String Conversion/ Fixed-length Hexadecimal Text String Conversion Hexadecimal Text String-toNumber Conversion Group

FixNumToString

Fixed-decimal Number-to-Text String Conversion

Page 2-404 2-405 2-407 2-410 2-412
2-413 2-415 2-417 2-422

Instruction StringToFixNum DtToString DateToString TodToString GrayToBin_** and BinToGray_** StringToAry AryToString DispartDigit UniteDigit_**

2-424 Dispart8Bit

2-426 Unite8Bit_**

2-432 2-435 2-441 2-444

ToAryByte AryByteTo SizeOfAry PackWord

2-446 PackDword

2-449 2-451

LOWER_BOUND / UPPER_BOUND

Name Text String-to-Fixed-decimal Conversion Date and Time-to-Text String Conversion Date-to-Text String Conversion Time of Day-to-Text String Conversion Gray Code-to-Binary Code Conversion Group/ Binary Code-to-Gray Code Conversion Text String-to-Array Conversion Array-to-Text String Conversion Four-bit Separation Four-bit Join Group

Page 2-453 2-456 2-458 2-459 2-461
2-463 2-465 2-467 2-469

Byte Data Separation

2-471

Byte Data Join Group

2-473

Conversion to Byte Array Conversion from Byte Array Get Number of Array Elements 2-byte Join
4-byte Join

2-475 2-480 2-485 2-487
2-489

Get First Number of Array/ Get Last Number of Array

2-491

NJ/NX-series Instructions Reference Manual (W502)

2-403

2 Instruction Descriptions

Swap

The Swap instruction swaps the upper byte and lower byte of a 16-bit value.

Instruction Swap

Name Swap Bytes

FB/FUN FUN

Graphic expression

(@)Swap

EN ENO

In

Out

ST expression Out:=Swap(In);

Variables

Name In
Out

Meaning

I/O

Data to convert

Input

Conversion Output result

Description Data to convert
Conversion result

Valid range

Unit

Depends on data type. ---

Depends on data type. ---

Default 0
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

Out

OK

Function

The Swap instruction swaps the upper byte and lower byte of data to convert In and assigns the result to conversion result Out.
The following example is for when In is WORD#16#1234.

LD

ST

abc:=Swap(WORD#16#1234);

Swap

EN ENO

WORD#16#1234 In

abc

Upper byte Lower byte (bits 8 to 15) (bits 0 to 7)

Bit

Bit

15

0

In 0 0 0 1 0 0 1 0 0 0 1 1 0 1 0 0

Bit

Bit

15

0

Out = abc 0 0 1 1 0 1 0 0 0 0 0 1 0 0 1 0

2-404

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

Neg

The Neg instruction reverses the sign of a number.

Instruction Neg

Name Reverse Sign

FB/FUN FUN

Graphic expression

(@)Neg

EN ENO

In

Out

ST expression Out:=Neg(In);

2 Variables

Neg

Name In
Out

Meaning

I/O

Data to convert

Input

Conversion Output result

Description Data to convert
Conversion result

Valid range

Unit

Depends on data type. ---

Depends on data type. ---

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default *
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK OK OK OK OK OK OK OK OK OK

Out

OK OK OK OK OK OK OK OK OK OK

Function
The Neg instruction reverses the sign of data to convert In. The value of Out depends on the data type of In.

Data type of In Signed integer: SINT, INT, DINT, or LINT
Unsigned integers: USINT, UNIT, UDINT, or ULINT Real numbers: REAL or LREAL

Value of Out
All bits in In are reversed and then 1 is added. (This is the same as multiplying In by -1.)
All bits in In are reversed and then 1 is added.
In × (-1)

NJ/NX-series Instructions Reference Manual (W502)

2-405

2 Instruction Descriptions

The following example is for when In is INT#123.

LD

ST

abc:=Neg(INT#123);

Neg

EN ENO

INT#123 In

abc

Bits reversed and 1 added.

In 123(2#0000_0000_0111_1011)

Out = abc -123(2#1111_1111_1000_0101)

The following example is for when In is UINT#123.

Bits reversed and 1 added.

In 123(2#0000_0000_0111_1011)

Out = abc 65413(2#1111_1111_1000_0101)

Precautions for Correct Use
If you use a different data type for In and Out, make sure the valid range of Out includes the valid range of In. Otherwise, an error will not occur and the value of Out will be an illegal value. For example, if the value of In is SINT#-128 and the data type of Out is INT, the value of Out will be INT#-128 instead of INT#128.
In=SINT#-128 2#1000_0000
Expanded to INT data.
2#0000_0000_1000_0000
Bits reversed and 1 added.
Out=INT#-128 2#1111_1111_1000_0000

2-406

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

Decoder

The Decoder instruction sets the specified bit to TRUE and the other bits to FALSE in array elements that consist of a maximum of 256 bits.

Instruction Decoder

Name Bit Decoder

FB/FUN FUN

Graphic expression

ST expression

(@)Decoder

Decoder(In, Size, InOut);

EN

ENO

In

Out

Size

InOut

2

Decoder

OLL
Variables

Name In
Size
InOut[] (array) Out

Meaning

I/O

Conversion bit position
Bits to convert

Input

Array to convert

In-out

Return value

Output

Description Bit position to convert

Valid range

Unit

Depends on data type. ---

Number of bits to convert 0 to 8

Bits

Array to convert

Depends on data type. ---

Always TRUE

TRUE only

---

Default 0 1
-----

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In Size InOut[] (array) Out

OK OK
OK OK OK OK OK
OK

Function
The Decoder instruction converts array elements with 2Size bits that start from InOut[0] in array to convert InOut[]. It sets the specified bit to TRUE. It sets the other bits to FALSE. The bit to make TRUE is specified by the Size bits in the lower byte of conversion bit position In. Always attach the element number to the in-out parameter that is passed to InOut[], e.g., array[3]. Consider an example where In is BYTE#16#09, Size is USINT#4, and InOut[] is a BYTE array. The value of the Size bits in the lower bits of In is 16#9, which is 9 decimal. Therefore, the ninth bit from the least-significant bit of InOut[] is made TRUE and the other bits are made FALSE.

NJ/NX-series Instructions Reference Manual (W502)

2-407

2 Instruction Descriptions

InOut[] is a BYTE array, so the ninth bit from the least-significant bit is bit 1 in InOut[1]. Therefore, bit 1 in InOut[1] is made TRUE, all other bits in InOut[1] are made FALSE, and all bits in InOut[0] are made FALSE.

LD

ST

Decoder(BYTE#16#09, USINT#4, abc[3]);

BYTE#16#09 USINT#4
abc[3]

Decoder

EN In Size InOut

ENO

abc[3]

Bit

Bit

7

0

In 0 0 0 0 1 0 0 1

Size=USINT#4

InOut[0]=abc[3] 2Size = 16 bits
InOut[1]=abc[4]

Bit

Bit

7

0

0 0 0 0 0 0 0 0

Bit

Bit

7

0

0 0 0 0 0 0 1 0

The corresponding bit is made TRUE. (2#1001 = Bit 9) Other bits are made FALSE.

If the number of bits in the elements of InOut[] is larger than the number of bits specified by Size, the values of the remaining bits are retained. Consider an example where In is BYTE#16#02, Size is USINT#2, and InOut[] is a WORD array. Size is USINT#2, so the value is set in the lower 4 bits of InOut[0]. The values of the remaining bits in InOut[0] (bits 4 to 15) are retained.

Bit

Bit

7

0

In 0 0 0 0 0 0 1 0

Size=USINT#2

Bit

Bit Bit

15

4

0

InOut[0] 0 1 0 1 1 0 0 1 0 0 1 0 0 1 0 0

2Size = 4 bits Bits 4 to 15: Retained.

Bit 2: Changed to TRUE. Bits 0, 1, and 3: Changed to FALSE.

Additional Information
Use the Encoder instruction (page 2-410) to find the position of the highest TRUE bit in array elements that consist of a maximum of 256 bits.

2-408

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions
Precautions for Correct Use
· If the value of Size is 0, all bits in InOut[] change to FALSE. · Return value Out is not used when the instruction is used in ST. · An error occurs in the following cases. ENO will be FALSE, and InOut[] will not change.
· The value of Size is outside of the valid range. · The value of 2Size exceeds the number of bits in the array elements of InOut[].
2

Decoder

NJ/NX-series Instructions Reference Manual (W502)

2-409

2 Instruction Descriptions

Encoder

The Encoder instruction finds the position of the highest TRUE bit in array elements that consist of a maximum of 256 bits.

Instruction Encoder

Name Bit Encoder

FB/FUN FUN

Graphic expression

(@)Encoder

EN

ENO

In

Out

Size

ST expression Out:=Encoder(In, Size);

Variables

Name In[] (array)
Size

Meaning
Array to convert
Bits to convert

I/O Input

Description Array to convert

Valid range Depends on data type.

Number of bits to convert 0 to 8

Out

Conver- Output

Conversion result

sion result

Depends on data type.

* If you omit the input parameter, the default value is not applied. A building error will occur.

Unit ---
Bits
---

Default *
1
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In[] (array) Size Out

OK OK OK OK OK OK
OK

Function
The Encoder instruction finds the position of a TRUE bit in a specified range of bits in array to convert In[]. The instruction looks for a TRUE bit in 2Size bits from In[0]. The position of the TRUE bit in this range is expressed in binary and stored in the Size bits in the lower bits of conversion result Out. FALSE is stored in the remaining bits of Out. If there is more than one TRUE bit in the specified range, the position of the highest bit that is TRUE is found. Always attach the element number to input parameter that is passed to In[], e.g., array[3]. Consider an example for when Size is USINT#4 and In[] is a BYTE array. Size is USINT#4, so the range in which to find a TRUE bit is 24, or 16 bits, from In[0]. In the following diagram, the ninth bit in the range is TRUE.

2-410

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

Size is USINT#4, so 2#1001 (i.e., 9) is stored in the lower 4 bits of Out. FALSE is stored in the upper four bits of Out.

LD

ST

def:=Encoder(abc[3], USINT#4);

Encoder

EN abc[3] In USINT#4 Size

ENO def

Bit

Bit

7

0

In[0]=abc[3] 0 0 0 0 0 0 0 0

2

Encoder

2Size = 16 bits

In[1]=abc[4]

Bit

Bit

7

0

0 0 0 0 0 0 1 0

The position of the TRUE bit is output. Bit 9 is indicated by 2#1001.

Out=def 0 0 0 0 1 0 0 1
FALSE is set. Size=USINT#4
Additional Information
Use the Decoder instruction (page 2-407) to make one bit TRUE and the other bits FALSE in array elements that consist of a maximum of 256 bits.

Precautions for Correct Use
· If the value of Size is 0, all bits in Out change to FALSE. · An error occurs in the following cases. ENO will be FALSE, and Out will not change.
· The value of Size is outside of the valid range. · The value of 2Size exceeds the number of bits in the array elements of In[]. · The value of all bits in In[] that are specified by Size change to FALSE.

NJ/NX-series Instructions Reference Manual (W502)

2-411

2 Instruction Descriptions

BitCnt

The BitCnt instruction counts the number of TRUE bits in a bit string.

Instruction BitCnt

Name Bit Counter

FB/FUN FUN

Graphic expression

(@)BitCnt

EN ENO

In

Out

ST expression Out:=BitCnt(In);

Variables

Name In
Out

Meaning
Count string
Count result

I/O Input
Output

Description
String in which to count TRUE bits
Number of TRUE bits

Valid range

Unit

Depends on data type. ---

0 to No. of bits in In

---

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default *
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK OK OK OK

Out

OK

Function
The BitCnt instruction counts the number of TRUE bits in count string In. The following example is for when In is BYTE data with a value of BYTE#16#85.

LD

BitCnt

EN BYTE#16#85 In

ENO abc

ST abc:=BitCnt(BYTE#16#85);

In 1 0 0 0 1 0 0 1 The number of TRUE (1) bits is counted.

Out = abc

3

2-412

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

ColmToLine_**

The ColmToLine_** instruction extracts bit values from the specified position of array elements and outputs them as a bit string.

Instruction

Name

FB/FUN

Graphic expression

ST expression

ColmToLine_**

Column to Line

FUN

Conversion Group

(@)ColmToLine_**

EN

ENO

Out:=ColmToLine_**(In, Size, Pos);

In Size Pos

Out "**" must be a bit string data

type.

2

"**" must be a bit string data type.

ColmToLine_**

Variables

Name In[] (array) Size
Pos Out

Meaning

I/O

Array to convert

Number of elements to Input convert

Bit position to convert

Conversion Output result

Description Array to convert

Valid range

Unit

Depends on data type.

Number of elements in In[] 0 to No. of bits in Out

to convert

---

Bit position to convert Conversion result

0 to No. of bits in In[] - 1
Depends on data type. ---

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default * 1
0
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In[] (array) Size Pos Out

OK OK OK OK OK OK
OK OK OK OK

Function
The ColmToLine_** instruction extracts bit values from the specified position of array elements and outputs them in order as a bit string. First, Size elements are extracted from array to convert In[] starting from In[0]. Then, only the values of bits in Pos are extracted. These are placed in order in a bit string of Size bits and stored in conversion result Out from the least-significant bit. FALSE is stored in the remaining bits of Out. The name of the instruction is determined by the data type of Out. For example, if Out is the BYTE data type, the instruction is ColmToLine_BYTE. Always attach the element number to input parameter that is passed to In[], e.g., array[3].

NJ/NX-series Instructions Reference Manual (W502)

2-413

2 Instruction Descriptions

The following example shows the ColmToLine_BYTE instruction when Pos is USINT#3 and Size is USINT#4.

LD

ST

def:=ColmToLine_BYTE(abc[3], USINT#4, USINT#3);

ColmToLine_BYTE

EN abc[3] In USINT#4 Size USINT#3 Pos

ENO def

Pos= Most-significant bit USINT#3 Bit 0

Size=USINT#4

In[0]=abc[3] In[1]=abc[4] In[2]=abc[5] In[3]=abc[6]

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0

Out=def 0 0 0 0 1 0 1 0 FALSE is set. Size=USINT#4
Additional Information
Use the LineToColm instruction (page 2-415) to output a bit string to the specified bit position in array elements.
Precautions for Correct Use
· If the value of Size is 0, all bits in Out change to FALSE. · An error occurs in the following cases. ENO will be FALSE, and Out will not change.
· The value of Size is outside of the valid range. · The value of Pos is outside of the valid range. · The value of Size exceeds the array area of In[].

2-414

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

LineToColm

The LineToColm instruction takes the bits from a bit string and outputs them to the specified bit position in array elements.

Instruction LineToColm

Name
Line to Column Conversion

FB/FUN FUN

Graphic expression

ST expression

(@)LineToColm

EN

ENO

LineToColm(In, InOut, Size, Pos);

In

Out

InOut
2

Size

Pos

LineToColm

Variables

Name In Size
Pos InOut[] (array)

Meaning

I/O

Data to convert

Number of elements in Input result

Conversion bit position

Conversion In-out result array

Description Data to convert
Number of elements in result
Bit position to receive the conversion Conversion result

Valid range

Unit

Depends on data type.

0 to No. of bits in In
---

0 to No. of bits in InOut[] - 1
Depends on data type. ---

Out

Return

Output

Always TRUE

value

TRUE only

---

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default * 1
0
-----

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In Size Pos InOut[] (array) Out

OK OK OK OK OK OK
OK OK OK OK
OK

Function
The LineToColm instruction takes the bits from a bit string and outputs them to the specified bit position in array elements.

NJ/NX-series Instructions Reference Manual (W502)

2-415

2 Instruction Descriptions

First, Size bits are extracted from the least-significant bit of data to convert In. These bits are treated individually. Then, the bits are stored in conversion result array InOut[] in the Pos bit of the elements starting from InOut[0]. Size specifies the number of array elements to receive bits. The values of all bits for which values are not stored are retained.
The following example is for when Pos is USINT#3 and Size is USINT#4.

LD

ST

LineToColm(abc, def[1], USINT#4, USINT#3);

abc
def[1] USINT#4 USINT#3

LineToColm

EN In InOut

ENO

Size Pos

def[1]

Size=USINT#4

Most-significant bit In = abc 0 0 0 0 0 0

Bit 0
0 0 1 0 1 0

Pos= Most-significant bit USINT#3

Bit 0

Size=USINT#4

InOut[0]=def[1] InOut[1]=def[2] InOut[2]=def[3] InOut[3]=def[4]

0 0 1 0 0 0 0 1 0 1 0 0 0 0 0 1 1 0 1 1 0 1 0 1

1 0 0 0 0 1 0 0 1 0 1 0 1 0 0 0 0 0 0 0 1 0 0 0

Retained

Additional Information
Use the ColmToLine_** instruction (page 2-413) to extract bit values from the specified position of array elements and output them as a bit string.

Precautions for Correct Use
· If the value of Size is 0, the values in InOut[] do not change. · Return value Out is not used when the instruction is used in ST. · An error occurs in the following cases. ENO will be FALSE, and InOut[] will not change.
· The value of Size is outside of the valid range. · The value of Pos is outside of the valid range. · The value of Size exceeds the array area of InOut[].

2-416

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

Gray

The Gray instruction converts a gray code into an angle.

Instruction

Name

FB/FUN

Graphic expression

ST expression

Gray

Gray Code Conver- FUN sion

(@)Gray

EN

ENO

Out:=Gray(In, Resolution, ERC, ZPC);

In

Out

Resolution

ERC

ZPC

2

Gray

Variables

Name

Meaning

I/O

In

Data to

convert

Resolution Resolution

ERC

Encoder remainder correction

Input

ZPC

Zero point correction

Out

Conversion Output

result

* 0 to 3.59999999999999e+2

Description Gray code to convert Resolution
Encoder remainder correction Zero point correction Conversion result

Valid range

Unit

Depends on data type.

_R256, _R1B to _R15B, _R360, _R720, or _R1024
---
0 to Resolution

Default 0 _R256
0

*

°

---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In Resolution ERC ZPC Out

OK Refer to Function for the enumerators of the enumerated type _eGRY_RESOLUTION.
OK OK
OK

Function
The Gray instruction converts the gray code in In (the output value from a rotary encoder) to an angle. The conversion result Out is in degrees.

NJ/NX-series Instructions Reference Manual (W502)

2-417

2 Instruction Descriptions

The data type of Resolution is enumerated type _eGRY_RESOLUTION. The meaning of the enumerators are as follows:

Enumerator

Meaning

_R256

256

_R1B

1-bit (2)

_R2B

2-bit (4)

_R3B

3-bit (8)

_R4B

4-bit (16)

_R5B

5-bit (32)

_R6B

6-bit (64)

_R7B

7-bit (128)

_R8B

8-bit (256)

_R9B

9-bit (512)

_R10B

10-bit (1024)

_R11B

11-bit (2048)

_R12B

12-bit (4096)

_R13B

13-bit (8192)

_R14B

14-bit (16384)

_R15B

15-bit (32768)

_R360

360

_R720

720

_R1024

1024

Gray Code

The Gray code is a reflected binary code. Two successive values, such as 0 and 1 and 1 and 2, differ in only one bit. Gray codes are used for the output from absolute encoders.

The following tables shows the 4-bit Binary code and Gray code.

Decimal number
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Binary code

Gray code

23 22 21 20 d c b a

00000000

00010001

00100011

00110010

01000110

01010111

01100101

01110100

10001100

10011101

10101111

10111110

11001010

11011011

11101001

11111000

2-418

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

Using the Gray code enables prevention of instantaneously incorrect output values because only one bit in the Gray code will change when the output value of the encoder is incremented or decremented by 1. The following figure shows the difference in the output value from an encoder for the Gray code and Binary code.
Difference When Output Value Changes from 1 to 2

Binary code

Gray code

24

TRUE FALSE

e

TRUE FALSE

23 TRUE FALSE

d TRUE FALSE

22 TRUE

c TRUE

2

FALSE

FALSE

21 TRUE FALSE

b TRUE FALSE

Gray

20 TRUE FALSE

a

TRUE FALSE

The value of two bits change. This means that an incorrect value may be output instantaneously until the values of all bits are set.

The value of only one bit changes, so an incorrect value is not output.

ERC: Encoder Remainder Correction
The ERC variable is used to specify the Gray code range when the encoder resolution is not a power of 2. The range is specified so that there is only one bit difference between the maximum and minimum encoder output values. For example, consider the use of an absolute encoder with a resolution of 360. Nine bits are used for the Gray code. The range that can be expressed with nine bits is 0 to 511. In this case, a range of 180 from the center of 0 to 511 is used for the Gray code, i.e., 76 to 435. Therefore, a Gray code of 001101010 (76 decimal) is output for an output value of 0, and a Gray code of 101101010 (435 decimal) is output for an output value of 359. There is a difference in only one bit between these values. In this case, the value of encoder remainder correction ERC is 76.

Gray code Decimal
i hg f edcb a
0 00 00 0 0 0 0 0

ERC (encoder remainder correction)
76

For an output value of 0

76 0 0 1 1 0 1 0 1 0 180

There is a difference in only one bit.

255 0 1 0 0 0 0 0 0 0 256 1 1 0 0 0 0 0 0 0

Resolution: 360

180

For an output value of 359 435 1 0 1 1 0 1 0 1 0

76 511 1 0 0 0 0 0 0 0 0

NJ/NX-series Instructions Reference Manual (W502)

2-419

2 Instruction Descriptions

ZPC: Zero Point Correction
The ZPC variable is set to offset the zero position of the rotary encoder. For example, to offset the zero position for a rotary encoder with a resolution of 256, the value of ZPC would be 256 × (90/360), or 64.

Notation Example
The following example is for when In is WORD#16#1A9, Resolution is _R10B, ERC is UINT#0, and ZPC is UINT#337.
First, the resolution is 10 bits, so one increment in the Gray code is 360°/1,024, or 0.35°. A decimal value of 305 corresponds to a Gray code of 16#01A9. Therefore, the angle before compensation is 0.35° × 305, or 106.75°. The value of ERC is 0 and the value of ZPC is 377. Therefore, the angle after compensation is 106.75° - (0 + 337) × 0.35°, or -11.20°. The range of the values of Out is 0 or greater, so the value is -11.20° + 360°, or 348.80°. The value of Out will be LREAL#348.8.

LD

ST

abc:=Gray(WORD#16#1A9, _R10B, UINT#0, UINT#337);

Gray

EN

ENO

WORD#16#1A9 In

abc

_R10B Resolution

UINT# 0 ERC

UINT#337 ZPC

Gray code: 16#01A9=305 305

Angle before compensation: 0.35°×305=106.75°

Angle after compensation: 106.75°-(0+337)×0.35°+360° =348.80°

0 -32

One increment in Gray code =360°/1024 =0.35°

Additional Information
Refer to the user documentation for your rotary encoder for the values to specify for Resolution and ERC.

2-420

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

Converting from Gray Code to Binary Code

The following processing can be used to convert from Gray code to Binary code. The logic symbols in the figure represent logical exclusive ORs.

Conversion Circuit for Five Bits

e d Gray code c b a

24

23

22 Binary code

21

20

2

Gray

Precautions for Correct Use
An error occurs in the following cases. ENO will be FALSE, and Out will not change. · The value of Resolution is outside of the valid range. · The value of ERC exceeds the resolution that is specified in Resolution. · The value of ZPC exceeds the resolution that is specified in Resolution. · In, when converted to a bit string, is smaller than the value of ERC. · The value of the bit string after correction for ERC exceeds the resolution that is specified in Resolu-
tion.

NJ/NX-series Instructions Reference Manual (W502)

2-421

2 Instruction Descriptions

UTF8ToSJIS

The UTF8ToSJIS instruction converts a UTF-8 text string to a SJIS BYTE array.

Instruction UTF8ToSJIS

Name
UTF-8 to SJIS Character Code Conversion

FB/FUN FUN

Graphic expression

(@)UTF8ToSJIS

EN

ENO

In

Out

SJISCode

ST expression
Out:=UTF8ToSJIS(In, SJISCode);

Variables

Name In
SJISCode[] (array) Out

Meaning Text string to convert SJIS array

I/O Input
In-out

Number of converted elements

Output

Description Text string to convert

Valid range

Unit

Depends on data type. ---

Array of SJIS character codes

Depends on data type. ---

Number of elements stored 0 to 1985

---

in SJISCode[]

Default '' ---
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

SJIS-

OK

Code[]

(array)

Out

OK

Function
The UTF8ToSJIS instruction converts the text string to convert in In (a UTF-8 text string) to a SJIS array in SJISCode[] (a BYTE array of SJIS character codes). Each byte of the converted data is stored in order starting from SJISCode[0]. The number of elements of converted data that was stored in SJISCode[] is stored as the number of converted elements in Out.

2-422

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

The following example is for when In is .

LD

ST

def:=UTF8ToSJIS( , abc[0]);

abc[0]

UTF8ToSJIS

EN In SJISCode

ENO

def abc[0]

SJISCode[0]=abc[0] BYTE#16#82

In

SJISCode[1]=abc[1] BYTE#16#A0

2

Out=def UINT#2

UTF8ToSJIS

Precautions for Correct Use
· NULL characters at the end of In are not converted. They are also not counted for the number of converted elements.
· If the In text string contains only the NULL character, the value of Out will be 0 and SJISCode[] will not change.
· The elements of SJISCode[] past the number of elements specified in Out do not change. For example, if the number of converted elements is 5, SJISCode[5] and later elements do not change.
· An error occurs in the following cases. ENO will be FALSE, and Out and SJISCode[] will not change. · The number of elements in the conversion result exceeds the size of the output parameter that is connected to SJISCode[]. · The contents of In includes characters that cannot be converted.
Version Information
A CPU Unit with unit version 1.01 or later and Sysmac Studio version 1.02 or higher are required to use this instruction.

NJ/NX-series Instructions Reference Manual (W502)

2-423

2 Instruction Descriptions

SJISToUTF8

The SJISToUTF8 instruction converts a SJIS BYTE array to a UTF-8 text string.

Instruction SJISToUTF8

Name
SJIS to UTF-8 Character Code Conversion

FB/FUN FUN

Graphic expression

(@)SJISToUTF8

EN

ENO

In

Out

Size

ST expression Out:=SJISToUTF8(In, Size);

Variables

Name In[] (array) Size
Out

Meaning
SJIS array to convert
Number of SJIS array elements
Resulting text string

I/O Input Output

Description
Array of SJIS character codes to convert*1
Number of elements of In[] to convert

Valid range

Unit

Depends on data type. ---

UTF-8 text string after con- Depends on data type. --version

Default *2 ---
---

*1 The maximum number of elements is 1,986, including the NULL character (BYTE#16#00). The maximum number of elements is 1,985 without the NULL character.
*2 If you omit the input parameter, the default value is not applied. A building error will occur.

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In[] (array)

OK

Size

OK

Out

OK

Function
The SJISToUTF8 instruction converts the elements in a SJIS array to convert in In[] (a BYTE array) to a UTF-8 text string. Size number of elements are converted starting with In[0]. However, if there is a NULL character (BYTE#16#00) before Size elements are converted, conversion is canceled at that point. The resulting text string after conversion is stored as resulting text string in Out. A NULL character is placed at the end of Out.

2-424

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

The following example is for when In[0] is BYTE#16#82, In[1] is BYTE#16#A0, and Size is UINT#2.

LD

ST

def:=SJISToUTF8(abc[0], UINT#2);

SJISToUTF8

EN abc[0] In
UINT#2 Size

ENO def

In[0]=abc[0] BYTE#16#82 In[1]=abc[1] BYTE#16#A0

Out=def

2

Size UINT#2

SJISToUTF8

Precautions for Correct Use
· If the value of Size is 0, Out is a text string containing only the NULL character. · An error occurs in the following cases. ENO will be FALSE, and Out will not change.
· The value of Size exceeds the number of elements in In[]. · The contents of In[] includes characters that cannot be converted.
Version Information A CPU Unit with unit version 1.01 or later and Sysmac Studio version 1.02 or higher are required to use this instruction.

NJ/NX-series Instructions Reference Manual (W502)

2-425

2 Instruction Descriptions

PWLApprox and PWLApproxNoLineChk

The PWLApprox and PWLApproxNoLineChk instructions perform broken line approximations for inte-

ger or real number data.

PWLApprox:

Checks to see if the broken line data is valid.

PWLApproxNoLineChk: Does not check to see if the broken line data is valid.

Instruction PWLApprox

Name
Broken Line Approximation with Broken Line Data Check

FB/FUN FUN

PWL Approx NoLineChk

Broken Line Approximation without Broken Line Data Check

FUN

Graphic expression

(@)PWLApprox

EN

ENO

In

Out

Line

Num

ST expression Out:=PWLApprox(In, Line, Num);

(@)PWLApproxNoLineChk

Out:=PWLApproxNoLineChk(

EN In Line Num

ENO Out

In, Line, Num);

Variables

Name In
Line[] (array) Num
Out

Meaning

I/O

Data to convert

Broken line data array Input

Number of broken line data

Conversion Output result

Description Data to convert

Valid range

Unit

Broken line data array

Depends on data type. ---

Number of broken line data

Conversion result

Depends on data type. ---

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default * 1
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In Line[] (array) Num Out

OK OK OK OK OK OK OK OK OK OK Must be an array with elements that have the same data type as In.
OK OK OK OK OK OK OK OK OK OK OK

2-426

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

Function

The PWLApprox and PWLApproxNoLineChk instructions perform approximation for data to convert In. The approximation is based on broken line data that consists of Num times 2 elements that start with Line[0,0] in broken line data array Line[].
As shown below, the Y coordinate that corresponds to the X coordinate In of the broken line data is assigned to conversion result Out.

Y

The instruction will find the value of Out that corresponds to the value (X0,Y0)

2

of In on the broken line graph. Out

(X2,Y2)

(X Num-2,Y Num-2)

(X1,Y1)

(X Num-1,Y Num-1)

PWLApprox and PWLApproxNoLineChk

X In
Elements of Broken Line Data Array Line[] and Number of Broken Line Data Num
Line[] must be a two-dimensional or three-dimensional array. Set the number of elements for the first dimension to 2. Then use the coordinate values (X0,Y0), (X1,Y1), etc., of the points in the broken line data as the elements of Line[] as shown in the following figure. The number of broken line data Num is one half of the number of elements of Line[], which is used in the broken line approximation calculations.

NJ/NX-series Instructions Reference Manual (W502)

2-427

2 Instruction Descriptions

Y (X0,Y0)

(X2,Y2)

(X1,Y1)

(X Num-2,Y Num-2) (X Num-1,Y Num-1)

X

Using a Two-dimensional Array for Line[]

Line[0,0] Line[0,1] Line[1,0] Line[1,1] Line[2,0] Line[2,1]
: Line[Num-1,0] Line[Num-1,1]

X0 Y0 X1 Y1 X2 Y2
:
X Num-1 Y Num-1

Using a Three-dimensional Array for Line[]

Line[0,0,0] Line[0,0,1] Line[0,1,0] Line[0,1,1] Line[0,2,0] Line[0,2,1]
: Line[0, Num-1,0] Line[0, Num-1,1]

X0 Y0 X1 Y1 X2 Y2
:
X Num-1 Y Num-1

Notation Example
An example of approximation when the value of In is LREAL#3.0 for broken line data array abc[] with four elements is given below. The values of the elements of abc[] are given below for when Num is UINT#4. abc[0.0] = X0 = LREAL#1.0, abc[0,1] =Y0 = LREAL#5.0, abc[1.0] = X1 = LREAL#2.0, abc[1,1] =Y1 = LREAL#6.0, abc[2.0] = X2 = LREAL#4.0, abc[2,1] =Y2 = LREAL#2.0, abc[3.0] = X3 = LREAL#5.0, abc[3,1] =Y3 = LREAL#3.0 The value of conversion result Out will be LREAL#4.0.

LD

ST

def:=PWLApprox(LREAL#3.0, abc[0,0], UINT#4);

PWLApprox

EN

ENO

LREAL#3.0 In

def

abc[0,0] Line

UINT#4 Num

2-428

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Conversion Instructions

Y

(abc[0,0],abc[0,1])=(1.0,5.0)

(abc[1,0],abc[1,1])=(2.0,6.0)

Out=def=LREAL#4.0

(abc[3,0],abc[3,1])=(5.0,3.0)

2
(abc[2,0],abc[2,1])=(4.0,2.0)
X In=LREAL#3.0

PWLApprox and PWLApproxNoLineChk

Difference between the PWLApprox and PWLApproxNoLineChk Instructions
The PWLApprox and PWLApproxNoLineChk instructions are different in whether the validity of In and Line[] are checked. This also makes the processing times different. The specifications of both instructions are given in the following table.

Instruction
PWLApprox
PWLApprox NoLineChk

Checks
· The contents of Line[] are checked to make sure the elements are in ascending order of the X coordinates.
· If In and Line[] are integers, In and the elements of Line[] are checked to make sure they are not nonnumeric data, positive infinity, or negative infinity.
No checks are performed.

Processing when the data is not valid
· An error occurs. · The value of ENO will be
FALSE. · The value of Out will not
change.
· An error will not occur. · The value of ENO will be
TRUE. · A valid value may not be out-
put to Out.

Processing time Long
Short

PWLApproxNoLineChk and PWLLineChk Instructions
Although the PWLApproxNoLineChk instruction does not check the validity of In and Line[], the processing time is short. Therefore, if you can be sure that the input variables are valid, it is better to use the PWLApproxNoLineChk instruction rather than the PWLApprox instruction. The PWLLineChk instruction (page 2-432) checks the contents of Line[] to see if the X coordinates are in ascending order. Therefore, you can shorten the processing time if you normally use the PWLApproxNoLineChk instruction and combine the PWLLineChk instruction with it only when you cannot ensure that the X coordinates in Line[] are in ascending order.
Additional Information
You can also shorten the processing time by restricting the range of elements in the broken line data array that is used for approximation conversion.

NJ/NX-series Instructions Reference Manual (W502)

2-429

2 Instruction Descriptions

In the previous example, the processing time will be shorter for the value of In (LREAL#3.0) if the values of the X coordinates in the elements of the broken line data array consist of only the four elements that are close to 3.0 (abc[1,0],abc[1,1])=(2.0,6.0) and (abc[2,0],abc[2,1])=(4.0,2.0).
In this case, Num is UINT#2 and the element of abc[] that is passed to Line[] is abc[1,0].
The conversion result Out is still LREAL#4.0.

LD

ST

def:=PWLApprox(LREAL#3.0, abc[1,0], UINT#2);

PWLApprox

EN

ENO

LREAL#3.0 In

def

abc[1,0] Line

UINT#2 Num

Y

(abc[1,0],abc[1,1])=(2.0,6.0)

Out=def=LREAL#4.0

Use only the values of the X coordinates in the elements of the broken line data array that are close to the value of In.

(abc[2,0],abc[2,1])=(4.0,2.0)
X In=LREAL#3.0

2-430

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

Precautions for Correct Use

· If the value of In is smaller than the value of Line[0,0] (i.e., the value of X1), then the value of Out will be the value of Line[0,1] (i.e., the value of Y1).

· If the value of In is larger than the value of Line[Num-1,0] (i.e., the value of XNum), then the value of Out will be the value of Line[Num-1,1] (i.e., the value of YNum).

· Line[] must be a two-dimensional or three-dimensional array. Set the number of elements for the first dimension to 2.

· If the value of Num is 0, the value of Out is 0.

· An error will occur for the PWLApprox instruction in the following cases. ENO will be FALSE, and Out

will not change. An error will not occur in these cases for the PWLApproxNoLineChk instruction.

2

· The X coordinates of the broken line data are not in ascending order, the condition X1 < X2 < ... < XNum is not met.

· In and Line[] are REAL data and their values are nonnumeric data, positive infinity, or negative infinity.

· An error will occur for the PWLApprox instruction and the PWLApproxNoLineChk instruction in the following cases. ENO will be FALSE, and Out will not change.

· The value of Num exceeds the array area of Line[].

· The value of In exceeds the X coordinates in the broken line data that is specified for Line[].

PWLApprox and PWLApproxNoLineChk

Version Information
A CPU Unit with unit version 1.03 or later and Sysmac Studio version 1.04 or higher are required to use the PWLApproxNoLineChk instruction.

NJ/NX-series Instructions Reference Manual (W502)

2-431

2 Instruction Descriptions

PWLLineChk

The PWLLineChk instruction is used to check whether the X coordinates in the broken line data that is used for a Broken Line Approximation without Broken Line Data Check instruction are in ascending order.

Instruction PWLLineChk

Name
Broken Line Data Check

FB/ FUN
FUN

Graphic expression

(@)PWLLineChk

EN

Out

Line

Num

ST expression Out:=PWLLineChk(Line, Num);

Variables

Name Line[] (array)
Num
Out

Meaning Broken line data array Number of broken line data
Result

I/O Input Output

Description Broken line data array Number of broken line data Result

Valid range

Unit

Depends on data type.

---

Depends on data type.

---

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default (*) 1 ---

Bit strings

Integers

Times, durations, dates, and text strings

Real numbers

Boolean BOOL

STRING DT TOD
DATE TIME

LREAL REAL

LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE

Line[] (array)

Num

Out

OK

OK OK OK OK OK OK OK OK OK OK OK

Function
The PWLLineChk instruction is used to check whether the X coordinates in the broken line data array Line[] that is used for a Broken Line Approximation without Broken Line Data Check (PWLApproxNoLineChk) instruction are in ascending order. If the X coordinates are in ascending order, result Out will be TRUE. If they are not, result Out will be FALSE.

Elements of Broken Line Data Array Line[] and Number of Broken Line Data Num
Line[] must be a two-dimensional or three-dimensional array. Set the number of elements for the first dimension to 2. Then use the coordinate values (X0,Y0), (X1,Y1), etc., of the points in the broken line data as the elements of Line[] as shown in the following figure. The number of broken line data Num is one half of the number of elements of Line[], which is used in the broken line approximation calculations.

2-432

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

Y

(X0,Y0)

(X2,Y2)

(X Num-2,Y Num-2)

(X1,Y1)
(X Num-1,Y Num-1)
2

PWLLineChk

X

Using a Two-dimensional Array for Line[]

Line[0,0] Line[0,1] Line[1,0] Line[1,1] Line[2,0] Line[2,1]
: Line[Num-1,0] Line[Num-1,1]

X0 Y0 X1 Y1 X2 Y2
:
X Num-1 Y Num-1

Using a Three-dimensional Array for Line[]

Line[0,0,0] Line[0,0,1] Line[0,1,0] Line[0,1,1] Line[0,2,0] Line[0,2,1]
: Line[0, Num-1,0] Line[0, Num-1,1]

X0 Y0 X1 Y1 X2 Y2
:
X Num-1 Y Num-1

Notation Example
An example of determining whether the X coordinates are in ascending order in the broken line data array abc[] with four elements is given below. The values of the elements of abc[] are given below for when Num is UINT#4. abc[0.0] = X0 = LREAL#1.0, abc[0,1] = Y0 = LREAL#5.0, abc[1.0] = X1 = LREAL#6.0, abc[1,1] = Y1 = LREAL#6.0, abc[2.0] = X2 = LREAL#4.0, abc[2,1] = Y2 = LREAL#2.0, abc[3.0] = X3 = LREAL#5.0, abc[3,1] = Y3 = LREAL#3.0 The X coordinates are not in ascending order, so the value of Out is FALSE.

LD

abc[0,0] UINT#4

PWLLineChk
EN Line Num

ST def:=PWLLineChk(abc[0,0], UINT#4); def

NJ/NX-series Instructions Reference Manual (W502)

2-433

2 Instruction Descriptions
Y (abc[0,0],abc[0,1])=(1.0,5.0) (abc[1,0],abc[1,1])=(6.0,6.0)
The X coordinates are not in ascending order.
(abc[3,0],abc[3,1])=(5.0,3.0)
(abc[2,0],abc[2,1])=(4.0,2.0) X
Additional Information
· Use the PWLLineChk in combination with the PWLApproxNoLineChk instruction. Refer to PWLApprox and PWLApproxNoLineChk Instructions (page 2-426) for details on the PWLApproxNoLineChk instruction.
· Use the PWLApprox instruction to check the broken line data every time you perform broken line approximation. Refer to PWLApprox and PWLApproxNoLineChk Instructions (page 2-426) for details on the PWLApprox instruction. The processing time of the PWLApproxNoLineChk instruction is shorter than the processing time of the PWLApprox instruction.
Precautions for Correct Use
· Line[] must be a two-dimensional or three-dimensional array. Set the number of elements for the first dimension to 2.
· An error will occur in the following cases. Out will be FALSE. · The value of Num exceeds the array area of Line[]. · Line[] is REAL data and an element is nonnumeric data, positive infinity, or negative infinity.
Version Information A CPU Unit with unit version 1.03 or later and Sysmac Studio version 1.04 or higher are required to use this instruction.

2-434

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

MovingAverage

The MovingAverage instruction calculates a moving average.

Instruction MovingAverage

Name Moving Average

FB/FUN FUN

Graphic expression

(@)MovingAverage

EN In CurIndex

ENO Out

ST expression
Out:=MovingAverage(In, CurIndex, Buf, BufSize, Q);

Buf

2

BufSize Q

MovingAverage

Variables

Name

Meaning

I/O

Description

Valid range

In

Input value

BufSize
CurIndex
Buf[] (array) Q

Maximum number stored
Input value storage position
Input value storage array
Calculation completed flag

Input In-out

Out

Calculation Output

result

Number to include in average
Maximum number of elements to include in average

Depends on data type.

Position in Buf[] in which to store In

Array to store In values

TRUE: BufSize elements or more have been stored in Buf[]
FALSE: BufSize elements are not yet stored in Buf[]
Calculation result

Depends on data type. Depends on data type.

* If you omit the input parameter, the default value is not applied.A building error will occur.

Unit
---
---
---

Default * 1
---
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

BufSize

CurIndex

Buf[] (array)

Q

OK

Out

OK OK OK OK OK OK OK OK OK OK OK OK
Must be an array with elements that have the same data type as In.
OK OK OK OK OK OK OK OK OK OK

NJ/NX-series Instructions Reference Manual (W502)

2-435

2 Instruction Descriptions

Function

The MovingAverage instruction stores the value of input value In in input value storage array Buf[] each time it is executed. It stores the average of the stored values in calculation result Out. Specify the maximum number of elements to include in the average with BufSize.
The processing procedure when BufSize is UINT#3 is described below as an example. The instruction and statement are written as follows:

LD

ST

jkl:=MovingAverage(abc, def, ghi[1], UINT#3, mno);

abc
def
ghi[1] UINT#3
mno

MovingAverage

EN

ENO

In

CurIndex

Buf

BufSize Q

jkl def ghi[1]
mno

First Time a Number Is Input

The input value storage position CurIndex is set to 0 and the instruction is executed. Buf[0] to Buf[BufSize-1] of input value storage array Buf[] are cleared to zeros and the first input value In is stored in Buf[0]. The value of calculation completed flag Q changes to FALSE. This indicates that the number of values that are stored in Buf[] has not reached BufSize yet. While the value of Q is FALSE, the average value is calculated for the CurIndex + 1 numbers that start from Buf[0]. The calculation result is stored in Out. Finally, the value of CurIndex is incremented.

First Execution of Instruction
CurIndex=def 0 In=abc 1234

Buf[0]=ghi[1] Buf[1]=ghi[2] Buf[2]=ghi[3]

1234 The value of In is stored in Buf[0].

0 0

Cleared to zeros.

Out=jkl

1234

Average of Buf[0] to Buf[0] (i.e., the value of Buf[0])

CurIndex=def 1 Incremented

Q=mno FALSE

FALSE because the number of numbers stored has not reached BufSize.

2-436

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

Inputting Numbers Up to BufSize

Each time the instruction is executed, the value of In is stored in Buf[CurIndex]. The average of CurIndex + 1 numbers that start from Buf[0] is calculated and stored in Out.
When the number of instruction executions reaches BufSize, the value of Q changes to TRUE.

Second Execution of Instruction

Buf[0]=ghi[1] Buf[1]=ghi[2] Buf[2]=ghi[3]

1234 2345 The value of In is stored in Buf[1].
0

CurIndex=def 1

Out=jkl 1789 Average of Buf[0] and Buf[1]

In=abc 2345

CurIndex=def 2 Incremented

2

Q=mno FALSE

FALSE because the number of numbers stored has not reached BufSize.

MovingAverage

Third Execution of Instruction
CurIndex=def 2 In=abc 3456

Buf[0]=ghi[1] Buf[1]=ghi[2] Buf[2]=ghi[3]

1234 2345 3456 The value of In is stored in Buf[2].

Out=jkl 2345 Average of Buf[0] to Buf[2]

CurIndex=def Q=mno

3 Incremented
TRUE TRUE because the number of numbers stored has reached BufSize.

Inputting Numbers after Reaching BufSize

Each time the instruction is executed, Buf[0] to Buf[BufSize-1] are overwritten with the value of In in cyclic fashion. The average of Buf[0] to Buf[BufSize-1] is calculated and stored in Out. The value of CurIndex returns to 1 after it reaches BufSize and it is then incremented again. The value of Q remains TRUE.
Fourth Execution of Instruction

CurIndex=def 3 In=abc 4567

Buf[0]=ghi[1] Buf[1]=ghi[2] Buf[2]=ghi[3]

4567 2345 3456

Buf[0] is overwritten with the value of In.

Out=jkl 3456 CurIndex=def 1
Q=mno TRUE

Average of Buf[0] to Buf[2]
Returns to 1. TRUE because the number of numbers stored has reached BufSize.

Fifth Execution of Instruction

CurIndex=def 1 In=abc 5678

Buf[0]=ghi[1] Buf[1]=ghi[2] Buf[2]=ghi[3]

4567 5678 3456

Buf[1] is overwritten with the value of In.

Out=jkl 4567 Average of Buf[0] to Buf[2]

CurIndex=def 2 Q=mno TRUE

Incremented
TRUE because the number of numbers stored has reached BufSize.

NJ/NX-series Instructions Reference Manual (W502)

2-437

2 Instruction Descriptions

Initializing the Stored Values
If the value of CurIndex is set to 0 before the instruction is executed, the values in Buf[0] to Buf[BufSize- 1] are set to 0 and the current value of In is stored again in Buf[0]. The value of CurIndex changes to 1 and the value of Q changes to FALSE.

Changing the Value of BufSize

If you change the value of BufSize and execute the instruction, operation is performed with the new value of BufSize and the current value of CurIndex.
Status before Instruction Execution BufSize=3

Buf[0]=ghi[1] Buf[1]=ghi[2] Buf[2]=ghi[3]

4567 2345 3456

Out=jkl 3456 CurIndex=def 2
Q=mno TRUE

Instruction Execution after Setting BufSize to 2

CurIndex=def 2 In=abc 5678

Buf[0]=ghi[1] Buf[1]=ghi[2] Buf[2]=ghi[3]

5678 2345 3456

Out=jkl 4011 CurIndex=def 1

CurIndex is equal to or higher than BufSize, so the value of In is stored in Buf[1].
Not included in the average.
Average of Buf[0] and Buf[1] CurIndex is equal to or higher than BufSize, so the value of CurIndex returns to 1.

Q=mno TRUE TRUE because the number of numbers stored has reached BufSize.

Precautions for Correct Use
· Use the same data type for In and the elements of Buf[]. If they are different, a building error will occur.
· Use a Buf[] array that is at least as large as the value of BufSize. · Even if the calculation result exceeds the valid range of Out, an error will not occur. The value of Out
will be an illegal value. · If the value of BufSize is 0, the values of Out and CurIndex change to 0. The value of Q changes to
TRUE. · If you change the value of BufSize, always set the value of CurIndex to 0 and initialize the stored val-
ues. · An error occurs in the following cases. ENO will be FALSE, and Out will not change.
· The value of BufSize exceeds the size of the Buf[] array.

2-438

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Conversion Instructions

Sample Programming

This sample shows how to eliminate the effect of noise and other disturbances in analog input data, e.g., from a sensor. It assigns the average (DataAve) of the last 25 values of the input data (InputData) to the input data (InputDataForOperating) for the next process. InputData is input every task period as long as the value of the execution condition (Trigger) is TRUE. Until 25 values of InputData are input, there is not enough data to calculate the average, so the most recent value of InputData is assigned to InputDataForOperating.
When the value of Trigger changes to TRUE, the average is cleared and input of InputData is started again from the beginning.

InputData: Measured value for the current task period

Measured value

Task period

2

MovingAverage

Time Average of last 25 values is assigned to InputDataForOperating.
LD

Variable Trigger InputData Buffer DataAve OneRound IndexNo InputDataForOperating

Data type BOOL INT ARRAY[0..24] OF INT INT BOOL UINT INT

Initial value FALSE 10 [25(0)] 0 FALSE 0 0

Comment Execution condition Input value Input value storage array Average value Flag that indicates 25 inputs Input value storage position Input to next operation

When Trigger changes to TRUE, 0 is assigned to IndexNo. While Trigger is TRUE, the value of InputData is input every task period and the average is calculated.

Trigger

@MOVE

EN UINT#0 In

ENO Out IndexNo

InputData IndexNo
Buffer[0] UINT#25 OneRound

MovingAverage

EN In CurIndex

ENO

Buf

BufSize Q

DataAve

When there are 25 or more input values for InputData , DataAve is assigned to InputDataForOperating.

OneRound

MOVE

EN DataAve In

ENO Out InputDataForOperating

Until there are 25 or more input values for InputData , InputData is assigned to InputDataForOperating.

OneRound

MOVE

EN InputData In

ENO Out InputDataForOperating

NJ/NX-series Instructions Reference Manual (W502)

2-439

2 Instruction Descriptions

ST

Variable

Data type

Trigger

BOOL

LastTrigger

BOOL

Operating

BOOL

OperatingStart BOOL

Buffer

ARRAY[0..24] OF INT

InputData

INT

DataAve

INT

OneRound

BOOL

IndexNo

UINT

InputDataFor Operating

INT

Initial value FALSE FALSE FALSE FALSE [25(0)] 10 0 FALSE 0

Comment Execution condition Value of Trigger from previous task period Processing Processing started Input value storage array Input value Average value Flag that indicates 25 inputs Input value storage position

0

Input to next operation

// Detect when Trigger changes to TRUE. IF ( (Trigger=TRUE) AND (LastTrigger=FALSE) ) THEN
OperatingStart:=TRUE; Operating:=TRUE; END_IF; LastTrigger:=Trigger;

// Clear the average. IF (OperatingStart=TRUE) THEN
IndexNo:=UINT#0; OperatingStart:=FALSE; END_IF;

// Calculate the moving average.

IF (Operating=TRUE) THEN

DataAve:=MovingAverage(

In

:=InputData,

CurIndex:=IndexNo,

Buf

:=Buffer[0],

BufSize :=UINT#25,

Q

:=OneRound);

IF (OneRound=TRUE) THEN // Assign the average of last 25 values to InputDataForOperating. InputDataForOperating:=DataAve;
ELSE // Assign the most recent value to InputDataForOperating. InputDataForOperating:=InputData;
END_IF; END_IF;

// End average processing. IF (Trigger=FALSE) THEN
Operating:=FALSE; END_IF;

2-440

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

DispartReal

The DispartReal instruction separates a real number into the signed mantissa and the exponent.

Instruction

Name

FB/FUN

Graphic expression

ST expression

DispartReal

Separate Mantissa FUN and Exponent

(@)DispartReal

EN

ENO

Out:=DispartReal(In, Fraction, Exponent);

In

Out

Fraction

Exponent

2

DispartReal

Variables

Name In Out Fraction Exponent

Meaning
Real number
Return value
Signed mantissa
Exponent

I/O Input
Output

Description Real number to separate Always TRUE Signed mantissa Exponent

Valid range

Unit

Depends on data type. ---

TRUE only

*2

---

*3

*1 If you omit the input parameter, the default value is not applied. A building error will occur. *2 The valid ranges depend on the data types of In and Fraction. Refer to Function for details. *3 If In is REAL data, -44 to 32. If In is LREAL data, -322 to 294

Default *1
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

Out

OK

Fraction

Exponent

OK OK
Must be DINT if the data type of In is REAL and LINT if the data type of In is LREAL. OK

Function
The DispartReal instruction separates real number In into signed mantissa Fraction and exponent Exponent. If In is REAL data, Fraction is a 7-digit integer. If In is LREAL data, Fraction is a 15-digit integer.

NJ/NX-series Instructions Reference Manual (W502)

2-441

2 Instruction Descriptions

The following example is for when In is REAL data with a value of REAL#-123.456.

LD

ST

DispartReal(REAL#-123.456, abc, def);

DispartReal

EN

ENO

REAL#-123.456 In

Fraction abc

Exponent def

In REAL#-123.456

Signed mantissa Fraction = abc -1234560

Exponent

Exponent = def

-4

The following example is for when In is LREAL data with a value of LREAL#-123.456789.

LD

ST

DispartReal(LREAL#-123.456789, abc, def);

DispartReal

EN

ENO

LREAL#-123.456789 In

Fraction abc

Exponent def

In LREAL#-123.456789

Signed mantissa Fraction = abc

-123456789000000

Exponent

Exponent = def

-12

The following table shows the valid ranges for Fraction according to the data types In and Fraction.

Data type of In REAL LREAL

Data type of Fraction DINT LINT

Valid range of Fraction -9999999 to 9999999 -999999999999999 to 999999999999999

Additional Information
Use the UniteReal instruction (page 2-444) to combine a signed mantissa and exponent to form a real number.

Precautions for Correct Use
· Depending on the value of In, error may occur in the conversion to an integer.

2-442

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

· If the number of valid digits in In exceeds the number of valid digits of Fraction, the value is rounded to fit in the valid range of Fraction. The following table shows how values are rounded.

Value of fractional part

Treatment

Examples

Less than 0.5

The fractional part is truncated.

1.49  1 -1.49  -1

0.5

If the ones digit is an even number, the value is trun- 1.50  2

cated. If it is an odd number, the value is rounded up. 2.50  2

-1.50  -2

-2.50  -2

Greater than 0.5

The fractional part is rounded up.

1.51  2

-1.51  -2

2

· An error occurs in the following case. ENO will be FALSE, and Fraction and Exponent will not change.
· The value of In is nonnumeric or infinity.

DispartReal

NJ/NX-series Instructions Reference Manual (W502)

2-443

2 Instruction Descriptions

UniteReal

The UniteReal instruction combines a signed mantissa and exponent to make a real number.

Instruction UniteReal

Name
Combine Real Number Mantissa and Exponent

FB/FUN FUN

Graphic expression

(@)UniteReal

EN

ENO

Fraction

Out

Exponent

ST expression
Out:=UniteReal(Fraction, Exponent);

Variables

Name

Meaning

I/O

Description

Valid range

Fraction
Exponent Out

Signed mantissa Exponent Real number

Input Output

Signed mantissa
Exponent Real number

Depends on data type. Depends on data type.

* If you omit the input parameter, the default value is not applied. A building error will occur.

Unit
-----

Default *
0
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

Fraction Exponent Out

OK OK OK Must be REAL if the data type of Fraction is DINT and LREAL if the data type of Fraction is LINT.

Function

The UniteReal instruction combines signed mantissa Fraction and exponent Exponent to make real number Out.
The following example is for when Fraction is DINT#-15 and Exponent is INT#-1.

LD

ST

abc:=UniteReal(DINT#15, INT#-1);

DINT#-15 INT# -1

UniteReal

EN

ENO

Fraction

abc

Exponent

Signed mantissa Fraction DINT#-15
Exponent Exponent INT#-1

Out=abc REAL#-1.5

2-444

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

Additional Information
Use the DispartReal instruction (page 2-441) to separate a real number into the signed mantissa and exponent.

Precautions for Correct Use

· Depending on the values of Fraction and Exponent, error may occur in the conversion from an integer to a real number.

· If the combined result exceeds the valid range of Out and Exponent is positive, the value of Out will

be infinity with the same sign as Fraction. If Exponent is negative, the value of Out will be 0.

2

UniteReal

NJ/NX-series Instructions Reference Manual (W502)

2-445

2 Instruction Descriptions

NumToDecString and NumToHexString

NumToDecString: Converts an integer to a fixed-length decimal text string. NumToHexString: Converts an integer to a fixed-length hexadecimal text string.

Instruction NumToDecString

Name
Fixed-length Decimal Text String Conversion

FB/FUN FUN

NumToHexString

Fixed-length Hexadecimal Text String Conversion

FUN

Graphic expression

ST expression

(@)NumToDecString

EN

ENO

In

L

Fill

Out:=NumToDecString(In, L, Fill);
Out

(@)NumToHexString

EN

ENO

In

L

Fill

Out:=NumToHexString(In, L, Fill);
Out

Variables

Name In L
Fill
Out

Meaning Integer Number of characters Fill character Text string

I/O Input Output

Description

Valid range

Unit

Integer

Depends on data type.

Number of characters in Out 0 to 1985
---

Fill character

_BLANK or _ZERO

Text string

Depends on data type. ---

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default * 1
_BLANK
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK OK OK OK OK OK OK OK

L

OK

Fill

Refer to Function for the enumerators for the enumerated type _eFILL_CHR.

Out

OK

Function
 NumToDecString
The NumToDecString instruction converts integer In to a decimal text string of UTF-8 alphanumeric characters. If In contains a negative value, a minus sign (-) is added to the front of the text string.

2-446

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

 NumToHexString

The NumToHexString instruction converts integer In to a hexadecimal text string of UTF-8 alphanumeric characters. If In is negative, it is expressed in its two's complement (bits inverted and then 1 added).
For either instruction, the number of characters in text string Out is adjusted to number of characters L. If there are not enough characters, the upper digits are filled with fill character Fill. If the number of characters in the conversion result exceeds L, L characters from the lower digits of the conversion result are assigned to Out. The NULL character is not included in the number of characters.
The data type of Fill is enumerated type _eFILL_CHR. The meaning of the enumerators are as follows:

Enumerator

Meaning

_BLANK

'' (blank character)

_ZERO

`0'

2

The following examples are for the NumToDecString instruction.

LD

ST

jkl:=NumToDecString(abc, def, ghi);

NumToDecString and NumToHexString

NumToDecString

EN abc In def L ghi Fill

ENO jkl

In = abc = INT#128, L = def = UINT#8, Fill = ghi = _BLANK

Out = jkl

1 2 8

In = abc = INT#-128, L = def = UINT#8, Fill = ghi = _BLANK

Out = jkl

- 1 2 8

In = abc = INT#-128, L = def = UINT#8, Fill = ghi = _ZERO Out = jkl - 0 0 0 0 1 2 8

The following examples are for the NumToHexString instruction.

LD

ST

jkl:=NumToHexString(abc, def, ghi);

NumToHexString

EN abc In def L ghi Fill

ENO jkl

In = abc = INT#128, L = def = UINT#8, Fill = ghi = _BLANK

Out = jkl

8 0

In = abc = INT#128, L = def = UINT#8, Fill = ghi = _ZERO Out = jkl 0 0 0 0 0 0 8 0

In = abc = INT#-128, L = def = UINT#8, Fill = ghi = _BLANK Out = jkl F F F F F F 8 0

NJ/NX-series Instructions Reference Manual (W502)

2-447

2 Instruction Descriptions

Precautions for Correct Use

· If the value of L is 0, Out is a text string containing only the NULL character.
· If the number of characters in the conversion result exceeds the value of L, L characters from the lower characters of the conversion result are stored in Out. The following is an example.

Instruction

Value of In Value of L Value of Out

NumToDecString

28

128

2

NumToHexString

80

· An error occurs in the following cases. ENO will be FALSE, and Out will not change. · The value of L is outside of the valid range. · The value of Fill is outside of the valid range.

2-448

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

HexStringToNum_**

The HexStringToNum_** instruction converts a hexadecimal text string to an integer.

Instruction
HexStringToNu m_**

Name

FB/FUN

Hexadecimal Text FUN String-to-Number Conversion Group

Graphic expression

ST expression

(@)HexStringToNum_**

Out:=HexStringToNum_**(In);

EN In

ENO

Out

"**" must be an integer data type.

"**" must be an integer data type.
2

Variables

Name In
Out

Meaning
Hexadecimal text string
Integer

I/O Input
Output

Description Hexadecimal text string

Valid range

Unit

Depends on data type. ---

Integer

Depends on data type. ---

Default ''
---

Bit strings

Integers

Times, durations, dates, and text strings

HexStringToNum_**
STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

Out

OK OK OK OK OK OK OK OK

Function

The HexStringToNum_** instruction converts hexadecimal text string In to an integer. Any spaces (16#20) or `0' (16#30) in the upper digits are ignored. Underbars (16#5F) in the text string are ignored.
The name of the instruction is determined by the data type of Out. For example, if Out is the INT data type, the instruction is HexStringToNum_INT.
A few examples are given below.

LD

ST

def:=HexStringToNum_INT(abc);

HexStringToNum_INT

EN abc In

ENO def

In = abc

8 0

Out = def = 128

In = abc

- 8 0

Out = def = -128

In = abc - 0 0 0 0 0 0 F

Out = def = -15

NJ/NX-series Instructions Reference Manual (W502)

2-449

2 Instruction Descriptions
Precautions for Correct Use
· Even if the conversion result exceeds the valid range of Out, an error will not occur. The value of Out will be an illegal value.
· An error occurs in the following cases. ENO will be FALSE, and Out will not change. · The content of In includes characters that cannot be converted to numbers.

2-450

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

FixNumToString

The FixNumToString instruction converts a signed fixed-decimal number to a decimal text string.

Instruction FixNumToString

Name
Fixed-decimal Number-to-Text String Conversion

FB/FUN FUN

Graphic expression

(@)FixNumToString

EN

ENO

In

Out

Zero

ST expression
Out:=FixNumToString(In, Zero);

2 Variables

FixNumToString

Name In
Zero

Meaning
Fixeddecimal number
Zero augmentation

I/O Input

Out

Decimal Output

text string

Description Signed fixed-decimal number
Augmentation of zeros if there are less than 3 decimal digits TRUE: Add `0' FALSE: Do not add `0' Decimal text string

Valid range

Unit

Depends on data type. ---

Depends on data type. ---

Default 0 TRUE
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

Zero

OK

Out

OK

Function
The FixNumToString instruction converts signed fixed-decimal number In to a decimal text string. The following conversion is used.
1 The hexadecimal number In is converted to a decimal number.
2 The result is divided by 1,000.
Zero augmentation Zero specifies whether to add `0' to the third decimal place of Out when there are less than three decimal digits in In. If the value of Zero is TRUE, `0' is added. A NULL character is placed at the end of Out.

NJ/NX-series Instructions Reference Manual (W502)

2-451

2 Instruction Descriptions

A few examples are given below.
LD

FixNumToString

EN
abc In def Zero

ENO ghi

ST ghi:=FixNumToString(abc, def);

In = abc
16#0001462C (10#83500) 16#00051AA4 (10#334500) 16#0003BEFC (10#245500)

Out = ghi

Zero = def = TRUE Zero = def = FALSE

`83.500'

`83.5'

`334.500'

`334.5'

`245.500'

`245.5'

Additional Information
The format for fixed-point decimal numbers is the same as the fixed-decimal output format of the OMRON FZ-series Vision Sensors.

2-452

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

StringToFixNum

The StringToFixNum instruction converts a decimal text string to a signed fixed-decimal number.

Instruction StringToFixNum

Name
Text String-toFixed-decimal Conversion

FB/FUN FUN

Graphic expression

(@)StringToFixNum

EN

ENO

In

Out

ST expression Out:=StringToFixNum(In);

Variables

2

Name In
Out

Meaning
Decimal text string
Fixed-decimal number

I/O Input
Output

Description Decimal text string
Fixed-decimal number

Valid range

Unit

Depends on data type. ---

Depends on data type. ---

Default ''
---

Bit strings

Integers

Times, durations, dates, and text strings

StringToFixNum
STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

Out

OK

Function

The StringToFixNum instruction converts decimal text string In to a fixed-decimal number. The following conversion is used.
1 The number in In is multiplied by 1,000.
2 The fractional part is truncated.

3 The result is given as a 32-bit hexadecimal number (DWORD).

A few examples are given below.

LD

ST

def:=StringToFixNum(abc);

StringToFixNum

EN abc In

ENO def

NJ/NX-series Instructions Reference Manual (W502)

2-453

2 Instruction Descriptions

In = abc `83.5'
`334.5'
`245.5'

Out = def
16#0001462C (10#83500)
16#00051AA4 (10#334500)
16#0003BEFC (10#245500)

The format of the text sting in In is given below.

- iiii . ffffffff e+nn
Sign Integer Fractional part Exponent part
(Blank) (Blank) Decimal point

Name Sign
Integer part
Decimal point Fractional part
Exponent

Format
· Any consecutive blank characters (16#20) at the beginning of the text string are ignored. Any single plus or minus sign that follows is treated as the sign.
· The sign can be omitted. · Any consecutive blank characters after the sign are ignored.
· Consecutive numbers (`0' to `9') after the sign and up to the decimal point are taken as the integer part. The sign may sometimes be omitted. There may be blank characters between the sign and the integer part.
· If the decimal point and fractional part are omitted, the characters up to the exponent are taken as the integer part.
· If the decimal point, fractional part, and exponent are omitted, the characters up to the end of the text string are taken as the integer part.
· The integer part cannot be omitted. · The maximum number of digits in the integer part is the maximum text string length of 1986
minus the total number of bytes in the following: the sign, decimal point, fractional part, exponent, and blank characters before and after the sign.
· A single dot (`.') following the integer part is taken as the decimal point. · Omit the decimal point if there is no fractional part.
· Consecutive numbers (`0' to `9') after the decimal point and up to the exponent are taken as the fractional part.
· If the exponent is omitted, the characters up to the end of the text string are taken as the fractional part.
· The fractional part can be omitted. If there is no decimal point, then there is no fractional part. · The fractional part can consist of a maximum of 15 digits.
· The exponent consists of a single `e' or `E' after the fractional part, a following single plus or minus sign, and the remaining continuous numbers (`0' to `9') to the end of the text string.
· If there is no fractional part, then the above text string after the decimal point is taken as the exponent.
· If there is no decimal point or fractional part, then the above text string after the integer part is taken as the exponent.
· The exponent can be omitted. · The numeric part of the exponent can consist of a maximum of three digits.

Example 1: The following example uses the sign, decimal point, and fractional part, but does not use an exponent.

In`

' + 123 . 4567

Out 0001E240

2-454

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

Example 2: The following example uses the sign, decimal point, fractional part, and exponent.

`

'

In + 1 . 2 3 4 5 6 7 e + 0 2

Out 0001E240

Example 3: The following example does not use the sign, but uses the decimal point, fractional part, and exponent.

`

'

In 1 2 3 4 5 . 6 7 e - 0 2

Out 0001E240

Example 4: The following example does not use the sign, fractional part, decimal point, and exponent.

In` 1 '

Out 00003E8

2

Additional Information
The format for fixed-point decimal numbers is the same as the fixed-decimal output format of the OMRON FZ-series Vision Sensors.

StringToFixNum

Precautions for Correct Use
· The digits after the third decimal digit are truncated in In. · Underbars (16#5F) in the text string in In are ignored. · An error occurs in the following cases. ENO will be FALSE, and Out will not change.
· The content of In includes characters that cannot be converted to numbers. · The content of In has a decimal point but not a fractional part.

NJ/NX-series Instructions Reference Manual (W502)

2-455

2 Instruction Descriptions

DtToString

The DtToString instruction converts a date and time to a text string.

Instruction DtToString

Name
Date and Time-to-Text String Conversion

FB/FUN FUN

Graphic expression

(@)DtToString

EN

ENO

In

Out

ST expression Out:=DtToString(In);

Variables

Name In

Meaning
Date and time

I/O Input

Description Date and time

Out

Text string Output

Text string

Valid range

Unit

Depends on data type.

Year, month, day, hour, minutes, seconds

30 bytes (29 single-byte --alphanumeric characters plus the final NULL character)

Default DT#197 0-1-10:0:0
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

Out

OK

Function

The DtToString instruction converts date and time In to a text string. A NULL character is placed at the end of text string Out.
An example when In is 2010-5-23-07:00:15.873232345 (7:00 am and 15.873232345 seconds on May 23, 2010) is given below. The value of variable abc will be `2010-05-23-07:00:15.873232345'.

LD

ST

abc:=DtToString(DT#2010-05-23-07:00:15.873232345);

DtToString

EN DT#2010-05-23-07:00:15.873232345 In

ENO abc

The DtToString instruction converts date and time In to a text string. The value of In is 7:00 am and 15.873232345 seconds on May 23, 2010, so the value of abc will be `2010-05-23-07:00:15.873232345'.

Converted to text string.

In DT#2010-05-23-07:00:15.873232345

Out=abc '2010-05-23-07:00:15.873232345'

2-456

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

Additional Information
Out is in nanoseconds. To get a text string in seconds or milliseconds, combine this instruction with the LEFT or RIGHT instruction (page 2-556). An example to get a text string in seconds is given below.
LD

P_On

DtToString

EN DT#2000-01-23-01:23:45.678 In

ENO abc

2

LEFT

EN abc In UINT#19 L

ENO def

DtToString

ST def:=LEFT(DtToString(DT#2000-01-23-01:23:45.678), UINT#19);

NJ/NX-series Instructions Reference Manual (W502)

2-457

2 Instruction Descriptions

DateToString

The DateToString instruction converts a date to a text string.

Instruction DateToString

Name
Date-to-Text String Conversion

FB/FUN FUN

Graphic expression

(@)DateToString

EN

ENO

In

Out

ST expression Out:=DateToString(In);

Variables

Name In

Meaning

I/O

Date

Input

Out

Text string Output

Description Date
Text string

Valid range Depends on data type.
11 bytes (10 single-byte alphanumeric characters plus the final NULL character)

Unit Year, month, day
---

Default D#1970-1-1
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

Out

OK

Function

The DateToString instruction converts date In to a text string. A NULL character is placed at the end of Out.
An example when In is 2010-5-23 (May 23, 2010) is given below. The value of variable abc will be `2010-05-23'.

LD

ST

abc:=DateToString(D#2010-05-23);

DateToString

EN D#2010-05-23 In

ENO abc

The DateToString instruction converts date In to a text string. The value of In is May 23, 2010, so the value of abc will be `2010-05-23'.

Converted to text string.

In D#2010-05-23

Out=abc '2010-05-23'

2-458

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

TodToString

The TodToString instruction converts a time of day to a text string.

Instruction TodToString

Name

FB/FUN

Time of Day-to-Text FUN String Conversion

Graphic expression

(@)TodToString

EN

ENO

In

Out

ST expression Out:=TodToString(In);

Variables

2

TodToString

Name In

Meaning

I/O

Time of day Input

Out

Text string Output

Description Time of day
Text string

Valid range Depends on data type.
19 bytes (18 single-byte alphanumeric characters plus the final NULL character)

Unit
Hour, minutes, seconds
---

Default TOD#0:0:0
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

Out

OK

Function

The TodToString instruction converts time of day In to a text string. A NULL character is placed at the end of Out. An example when In is 07:00:15.873232345 (7:00 am and 15.873232345 seconds) is given below. The value of variable abc will be `07:00:15.873232345'.

LD

ST

abc:=TodToString(TOD#07:00:15.873232345);

TodToString

EN TOD#07:00:15.873232345 In

ENO abc

The TodToString instruction converts time of day In to a text string. The value of In is 7:00 am and 15.873232345 seconds, so the value of abc will be `07:00:15.873232345'.

Converted to text string.

In TOD#07:00:15.873232345

Out=abc '07:00:15.873232345'

NJ/NX-series Instructions Reference Manual (W502)

2-459

2 Instruction Descriptions

Additional Information
Out is in nanoseconds. To get a text string in seconds or milliseconds, combine this instruction with the LEFT or RIGHT instruction (page 2-556). An example to get a text string in seconds is given below.
LD

TodToString

EN TOD#01:23:45.678 In

ENO abc

LEFT

EN abc In
UINT#8 L

ENO def

ST def:=LEFT(TodToString(TOD#01:23:45.678), UINT#8);

2-460

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

GrayToBin_** and BinToGray_**

GrayToBin_**: Converts a gray code to a bit string. BinToGray_**: Converts a bit string to a gray code.

Instruction

Name

FB/FUN

Graphic expression

ST expression

GrayToBin_**

Gray Code-toBinary Code Conversion Group

FUN

(@)GrayToBin_**

Out:=GrayToBin_**(In);

EN In

ENO Out "**" must be a bit string data type.

2

"**" must be a bit string data type.

BinToGray_**

Binary Code-toGray Code Conversion

FUN

(@)BinToGray_**

EN

ENO

In

Out

"**" must be a bit string data type.

Out:=BinToGray_**(In);
"**" must be a bit string data type.

GrayToBin_** and BinToGray_**

Variables

Name In
Out

Meaning

I/O

Data to convert

Input

Conversion Output result

Description Data to convert
Conversion result

Valid range

Unit

Depends on data type. ---

Depends on data type. ---

Default 0
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK OK OK OK

Out

Must be same data type as In

Function
 GrayToBin_**
The GrayToBin_** instructions convert the gray code in date to convert In to a bit string. The conversion procedure is as follows for when In and Out are BYTE data.
1 The most-significant bit (bit 7) of In is used as is as the most-significant bit (bit 7) of Out.
2 An exclusive logical OR is taken of the value of bit 6 in In and the value of bit 7 in Out. The result
is used as bit 6 of Out.
3 This process is repeated through the least-significant bit (bit 0) of Out.

NJ/NX-series Instructions Reference Manual (W502)

2-461

2 Instruction Descriptions

The following example for the GrayToBin_BYTE instruction is for when In is BYTE#16#A5.

LD

ST

abc:=GrayToBin_BYTE(BYTE#16#A5);

GrayToBin_BYTE

EN BYTE#16#A5 In

ENO abc

Most-significant bit

Bit 0

In 1 0 1 0 0 1 0 1

XOR XOR XOR XOR XOR XOR XOR

Out = abc 1 1 0 0 0 1 1 0
 BinToGray_**
The BinToGray_** instructions convert the bit string in data to convert In to a gray code. The conversion procedure is as follows for when In and Out are BYTE data.
1 The most-significant bit (bit 7) of In is used as is as the most-significant bit (bit 7) of Out.
2 An exclusive logical OR is taken of the value of bit 7 in In and the value of bit 6 in In. The result
is used as bit 6 of Out.
3 This process is repeated through the least-significant bit (bit 0) of Out.

The following example for the BinToGray_BYTE instruction is for when In is BYTE#16#C6.

LD

ST

abc:=BinToGray_BYTE(BYTE#16#C6);

BinToGray_BYTE

EN BYTE#16#C6 In

ENO abc

Most-significant bit

Bit 0

In 1 1 0 0 0 1 1 0

XOR XOR XOR XOR XOR XOR XOR

Out = abc 1 0 1 0 0 1 0 1
The name of the instruction is determined by the data types of In and Out. For example, if In and Out are the WORD data type, the instruction is GrayToBin_WORD or BinToGray_WORD.

Precautions for Correct Use
The data types of In and Out must be the same. 2-462

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

StringToAry

The StringToAry instruction converts a text string to a BYTE array.

Instruction StringToAry

Name

FB/FUN

Text String-to-Array FUN Conversion

Graphic expression

(@)StringToAry

EN In AryOut

ENO Out

ST expression
Out:=StringToAry(In, AryOut);

2

Variables

StringToAry

Name In AryOut[] (array) Out

Meaning

I/O

Text string Input

BYTE array In-out

Number of bytes to convert

Output

Description Text string BYTE array

Valid range

Unit

Depends on data type. ---

Depends on data type. ---

Number of bytes to convert 0 to 1985

Bytes

Default ''
---
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

AryOut[]

OK

(array)

Out

OK

Function
The StringToAry instruction takes the character codes in text string In as numbers and stores them individually in a BYTE array, AryOut[]. The number of bytes that was converted is stored in Out.

NJ/NX-series Instructions Reference Manual (W502)

2-463

2 Instruction Descriptions

The following example is for when In is `XYZ'.

LD

ST

def:=StringToAry('XYZ', abc[1]);

`XYZ' abc[1]

StringToAry

EN In AryOut

ENO

def abc[1]

In `XYZ'

AryOut[0]=abc[1] AryOut[1]=abc[2] AryOut[2]=abc[3]

16#58 16#59 16#5A

Character code for `X' Character code for `Y' Character code for `Z'

Out=def UINT#3

Precautions for Correct Use
· The NULL character at the end of In is not stored in AryOut[]. · If the In text string contains only the NULL character, the value of Out will be 0 and AryOut[] will not
change. · An error occurs in the following cases. ENO will be FALSE, and Out and AryOut[] will not change.
· The number of bytes in In is larger than the number of elements in AryOut[].

2-464

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

AryToString

The AryToString instruction converts a BYTE array to a text string.

Instruction AryToString

Name

FB/FUN

Array-to-Text String FUN Conversion

Graphic expression

(@)AryToString

EN

ENO

In

Out

Size

ST expression Out:=AryToString(In, Size);

2 Variables

AryToString

Name

Meaning

I/O

In[] (array) BYTE array

Input

Size

Number of

elements to

convert

Out

Text string Output

Description
BYTE array Maximum number of elements: 1985
Number of elements of In[] for conversion

Valid range

Unit

Depends on data type.

---
0 to 1985

Text string

Depends on data type. ---

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default
*
1
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In[] (array)

OK

Size

OK

Out

OK

Function
The AryToString instruction takes the elements of a BYTE array, In[], from In[0] as character codes and stores them in text string Out. A NULL character is placed at the end of Out. Size specifies the number of elements of In[] to convert. If there is a NULL character between In[0] and In[Size-1], no character codes past it are stored in Out.

NJ/NX-series Instructions Reference Manual (W502)

2-465

2 Instruction Descriptions

The following example is for when Size is UINT#3.

LD

ST

def:=AryToString(abc[1], UINT#3);

AryToString

EN abc[1] In
UINT#3 Size

ENO def

Size = UINT#3

In[0]=abc[1] In[1]=abc[2] In[2]=abc[3] In[3]=abc[4] In[4]=abc[5]

16#56 16#57 16#58 16#59 16#5A

Character code for `V' Character code for `W' Character code for `X' Character code for `Y' Character code for `Z'

Out = def `VWX'

Precautions for Correct Use
· If the value of Size is 0, Out is a text string containing only the NULL character. · An error occurs in the following cases. ENO will be FALSE, and Out will not change.
· The value of Size exceeds the array area of In[].

2-466

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

DispartDigit

The DispartDigit instruction separates a bit string into 4-bit units.

Instruction

Name

FB/FUN

Graphic expression

ST expression

DispartDigit

Four-bit Separation FUN

(@)DispartDigit

EN

ENO

DispartDigit(In, Num, AryOut);

In

Out

Num

AryOut

2

DispartDigit

Variables

Name

Meaning

I/O

Description

Valid range

In Num

Data to separate
Number of digits to separate

Input

Bit string to separate

Depends on data type.

Number of digits to separate 0 to No. of bits in In

AryOut[] (array)

Separation results array

In-out Separation results array

16#00 to 16#0F

Out

Return value

Output Always TRUE

TRUE only

* If you omit the input parameter, the default value is not applied. A building error will occur.

Unit
-------

Default * 1
---
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In Num AryOut[] (array) Out

OK OK OK OK OK
OK
OK

Function
The DispartDigit instruction separates data to separate In into 4-bit units (digits) and stores them in separation results array AryOut[]. First, In is separated into 4-bit units. Then, the lowest 4 bits are stored in AryOut[0]. AryOut[0] is BYTE data, so 16#0 is stored in bits 4 to 7. This process is repeated for the number of digits that is specified in number of digits to separate Num.

NJ/NX-series Instructions Reference Manual (W502)

2-467

2 Instruction Descriptions

The following example is for when Num is USINT#3.

LD

ST

DispartDigit(abc, USINT#3, def[1]);

abc USINT#3
def[1]

DispartDigit

EN In Num AryOut

ENO

def[1]

Highest digit

In=abc C

7

Num=USINT#3

Digit 2 Digit 1 Digit 0

5

2

A

6

AryOut[0]=def[1] AryOut[1]=def[2] AryOut[2]=def[3]

Bits 4 to 7
0 0
0

Bits 0 to 3
6 A 2

Num=USINT#3

16#0
Additional Information
Use the UniteDigit_** instruction (page 2-469) to join 4-bit units from array elements.
Precautions for Correct Use
· The values in AryOut[] do not change if the value of Num is 0. · Return value Out is not used when the instruction is used in ST. · An error occurs in the following cases. ENO will be FALSE, and AryOut[] will not change.
· The value of Num is outside of the valid range. · The value of Num exceeds the array area of AryOut[].

2-468

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

UniteDigit_**

The UniteDigit_** instructions join 4-bit units of data into a bit string.

Instruction

Name

FB/FUN

Graphic expression

ST expression

UniteDigit_**

Four-bit Join Group FUN

(@)UniteDigit_**

EN

ENO

Out:=UniteDigit_**(In, Num);

In

Out

Num

"**" must be a bit string data

"**" must be a bit string data type. type.

2

UniteDigit_**

Variables

Name

Meaning

I/O

Description

Valid range

In[] (array) Num

Array to join
Number of digits to join

Input

Array to join Number of digits to join

Depends on data type. 0 to No. of bits in Out

Out

Joined result

Output

Bit string with joined result Depends on data type.

* If you omit the input parameter, the default value is not applied. A building error will occur.

Unit
-----

Default * 1
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In[] (array) Num Out

OK OK
OK OK OK OK

Function
The UniteDigit_** instructions join 4-bit units from the elements of array to join In[]. It creates a bit string in joined result Out. (Four bits is one digit.) Number of digits to join Num specifies the number of array elements to join. First, the lower four bits from each element from In[0] to In[Num-1] are joined to create a bit string with Num digits. To this, 16#0 is added to the upper digits for the number of digits of Out minus the value of Num. The result is stored in Out. The name of the instruction is determined by the data type of Out. For example, if Out is the WORD data type, the instruction is UniteDigit_WORD.

NJ/NX-series Instructions Reference Manual (W502)

2-469

2 Instruction Descriptions

The following example shows the UniteDigit_WORD instruction when Num is USINT#3.

LD

ST

def:=UniteDigit_WORD(abc[1], USINT#3);

UniteDigit_WORD

abc[1] USINT#3

EN In Num

ENO def

Num=USINT#3

In[0]=abc[1] In[1]=abc[2] In[2]=abc[3] In[3]=abc[4]

Bits Bits 4 to 7 0 to 3

1

6

0

A

4

2

5

B

Highest digit Digit 2 Digit 1 Digit 0

Out=def 0

2

A

6

16#0

Num=USINT#3

Additional Information
Use the DispartDigit instruction (page 2-467) to separate a bit string into 4-bit units.

Precautions for Correct Use
· If the value of Num is 0, the value of Out is 0. · An error occurs in the following cases. ENO will be FALSE, and Out will not change.
· The value of Num is outside of the valid range. · The value of Num exceeds the array area of In[].

2-470

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

Dispart8Bit

The Dispart8Bit instruction separates a bit string into individual bytes.

Instruction

Name

FB/FUN

Graphic expression

ST expression

Dispart8Bit

Byte Data Separation

FUN

(@)Dispart8Bit

EN

ENO

Dispart8Bit(In, Num, AryOut);

In

Out

Num

AryOut

2

Dispart8Bit

Variables

Name In Num
AryOut[] (array) Out

Meaning Data to separate Number of bytes to separate Separation results array Return value

I/O Input In-out Output

Description

Valid range

Bit string to separate

Depends on data type.

Number of bytes to separate 0 to No. of bytes in In

Separation results array

Depends on data type.

Always TRUE

TRUE only

* If you omit the input parameter, the default value is not applied. A building error will occur.

Unit
-------

Default * 1
---
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In Num AryOut[] (array) Out

OK OK OK OK OK
OK
OK

Function
The Dispart8Bit instruction separates data to separate In into individual bytes and stores them in separation results array AryOut[]. First, In is separated into bytes. Then, the lowest byte is stored in AryOut[0]. Then, the next byte is stored in AryOut[1]. This process is repeated for the number of bytes that is specified in number of bytes to separate Num.

NJ/NX-series Instructions Reference Manual (W502)

2-471

2 Instruction Descriptions

The following example is for when Num is USINT#3.

LD

ST

Dispart8Bit(abc, USINT#3, def[1]);

abc USINT#3
def[1]

Dispart8Bit

EN

ENO

In

Num

AryOut

def[1]

Highest byte
In=abc A0 23

Num=USINT#3
Byte 2 Byte 1 Byte 0 06 21 AA 36

AryOut[0]=def[1] AryOut[1]=def[2] AryOut[2]=def[3]

36 AA Num=USINT#3 21

Additional Information
Use the Unite8Bit_** instruction (page 2-473) to join 1-byte units from array elements.
Precautions for Correct Use
· Return value Out is not used when the instruction is used in ST. · An error occurs in the following cases. ENO will be FALSE, and AryOut[] will not change.
· The value of Num is outside of the valid range. · The value of Num exceeds the number of bytes in In.

2-472

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

Unite8Bit_**

The Unite8Bit_** instructions join bytes of data into a bit string.

Instruction

Name

FB/FUN

Graphic expression

ST expression

Unite8Bit_**

Byte Data Join Group

FUN

(@)Unite8Bit_**

EN

ENO

In

Num

Out:=Unite8Bit_**(In, Num); Out "**" must be a bit string data
type.

"**" must be a bit string data type.

2

Unite8Bit_**

Variables

Name In[] (array) Num
Out

Meaning Array to join Number of bytes to join Joined result

I/O Input Output

Description Array to join Number of bytes to join

Valid range Depends on data type. 0 to No. of bytes in Out

Unit
---

Bit string with joined result Depends on data type. ---

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default * 1
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In[] (array) Num Out

OK OK
OK OK OK OK

Function
The Unite8Bit_** instructions join elements of array to join In[] to create a bit string in joined result Out. Number of bytes to join Num specifies the number of array elements to join. First, In[0] to In[Num-1] are joined to create a bit string with Num bytes. To this, 16#00 is added to the upper bytes for the number of bytes of Out minus the value of Num. The result is stored in Out. The name of the instruction is determined by the data type of Out. For example, if Out is the DWORD data type, the instruction is Unite8Bit_DWORD.

NJ/NX-series Instructions Reference Manual (W502)

2-473

2 Instruction Descriptions

The following example shows the Unite8Bit_DWORD instruction when Num is USINT#3.

LD

ST

def:=Unite8Bit_DWORD(abc[1], USINT#3);

Unite8Bit_DWORD

abc[1] USINT#3

EN In Num

ENO def

In[0]=abc[1]

36

Num=USINT#3 In[1]=abc[2]

AA

In[2]=abc[3]

21

In[3]=abc[4]

A0

Highest Byte 2 Byte 1 Byte 0 byte Out=def 00 21 AA 36

16#00

Num=USINT#3

Additional Information
Use the Dispart8Bit instruction (page 2-471) to separate a bit string into 1-byte units.

Precautions for Correct Use
· If the value of Num is 0, the value of Out is 0. · An error occurs in the following cases. ENO will be FALSE, and Out will not change.
· The value of Num is outside of the valid range. · The value of Num exceeds the array area of In[].

2-474

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

ToAryByte

The ToAryByte instruction separates a variable into bytes and stores the bytes in a BYTE array.

Instruction ToAryByte

Name
Conversion to Byte Array

FB/FUN FUN

Graphic expression

ST expression

(@)ToAryByte

EN

ENO

Out:=ToAryByte(In, Order, AryOut);

In

Out

Order

AryOut

2

ToAryByte

Variables

Name In Order
AryOut[] (array) Out

Meaning
Data to convert
Conversion order
Conversion results array
Number of elements in result

I/O Input In-out Output

Description Data to convert Conversion order
Conversion results array
Number of elements in result

Valid range Depends on data type. _LOW_HIGH or _HIGH_LOW Depends on data type.
Depends on data type.

* If you omit the input parameter, the default value is not applied. A building error will occur.

Unit
-------

Default * _LOW _HIGH
---
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In
Order AryOut[] (array) Out

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK An enumeration, array, array element, structure, or structure member can also be specified. Refer to Function for the enumerators for the enumerated type _eBYTE_ORDER.
OK
OK

Function

The ToAryByte instruction separates the value of data to convert In into individual bytes and stores them in order in conversion results array AryOut[] starting from AryOut[0]. Number of elements in result Out contains the number of elements stored in AryOut[].
Conversion order Order specifies the order in which to convert the value of In to bytes. The data type of Order is enumerated type _eBYTE_ORDER. The meaning of the enumerators are as follows:

Enumerator _LOW_HIGH _HIGH_LOW

Meaning Lower byte first, higher byte last Higher byte first, lower byte last

NJ/NX-series Instructions Reference Manual (W502)

2-475

2 Instruction Descriptions

When the Data Type of In Is Two Bytes or Larger

If the data type of In is two bytes or larger, In is separated into bytes and stored in AryOut[]. The following data types have two bytes or more.

Classification Bit strings Integers Real numbers Times, durations, dates, and text strings Others

Data type WORD, DWORD, and LWORD UINT, UDINT, ULINT, INT, DINT, and LINT REAL and LREAL TIME, DATE, TOD, DT, and STRING types of two bytes or more
An enumeration, an array for which the total for all elements is 2 bytes or more, an array element that is 2 bytes or more, a structure for which the total for all members is 2 bytes or more, or a structure member that is 2 bytes or more

The processing procedure is as follows:
1 First, the value in In is separated into words (two bytes). 2 The lowest word is separated into bytes.

3 If Order is _LOW_HIGH, the lower byte is stored in AryOut[0] and the higher byte is stored in
AryOut[1]. If Order is _HIGH_LOW, the higher byte is stored in AryOut[0] and the lower byte is stored in AryOut[1].
4 The next word is separated into bytes and stored in AryOut[2] and AryOut[3] in the same way.

5 This process is repeated to the end of the value of In. If In is an array, the same process is
repeated to the last element in In. The following example is for when In is a DWORD array with three elements and Order is _LOW_HIGH.

LD

ST

ghi:=ToAryByte(abc, _LOW_HIGH, def[1]);

abc _LOW_HIGH
def[1]

ToAryByte

EN In Order AryOut

ENO

ghi def[1]

In[0]=abc[0] In[1]=abc[1] In[2]=abc[2]

DWORD#16#01234567 DWORD#16#89ABCDEF DWORD#16#CCDDEEFF

2-476

AryOut[0]=def[1] AryOut[1]=def[2] AryOut[2]=def[3] AryOut[3]=def[4] AryOut[4]=def[5] AryOut[5]=def[6] AryOut[6]=def[7] AryOut[7]=def[8] AryOut[8]=def[9] AryOut[9]=def[10] AryOut[10]=def[11] AryOut[11]=def[12]

16#67 16#45 16#23 16#01 16#EF 16#CD 16#AB 16#: 89 16#FF 16#EE 16#DD 16#CC

Out = ghi = UINT#12

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Conversion Instructions

The following example is for when In is the same as above and Order is _HIGH_LOW.

In[0] DWORD#16#01234567 In[1] DWORD#16#89ABCDEF In[2] DWORD#16#CCDDEEFF

AryOut[0] AryOut[1] AryOut[2]

16#45 16#67 16#01

AryOut[3] 16#23

AryOut[4] 16#CD

AryOut[5] AryOut[6]

16#EF 16#89

Out = UINT#12

AryOut[7] 16#: AB

AryOut[8] 16#EE

AryOut[9] 16#FF

2

AryOut[10] 16#CC

AryOut[11] 16#DD

ToAryByte

When the Data Type of In Is One Byte

If the data type of In is one byte, In is stored in AryOut[] as one byte. The following data types have one byte.

Classification

Data type

Bit strings

BYTE

Integers

USINT and SINT

Real numbers

None

Times, durations, dates, STRING types with one byte and text strings

Others

An array for which the total for all elements is 1 byte, an array element that is 1 byte, a structure for which the total for all members is 1 byte, or a structure member that is 1 byte.

The following storage method is used.

Value of Order

In (array or not)

Storage method in AryOut[]

_LOW_HIGH

Not an array Array Not an array

_HIGH_LOW Array

Value of In is stored in AryOut[0].
Value of In[i] is stored in AryOut[i].
Value of In is stored in AryOut[1]. 16#00 is stored in AryOut[0].
In[i] (where i is even) is stored in AryOut[i+1]. In[i] (where i is odd) is stored in AryOut[i-1]. If the number of elements in In[] is odd, 16#00 is stored last in AryOut[n-1].

The following example is for when In is a SINT array with three elements and Order is _LOW_HIGH.

In[0] SINT#1 In[1] SINT#2 In[2] SINT#3

AryOut[0] AryOut[1] AryOut[2]

16#01 16#02 16#03

Out = UINT#3

The following example is for when In is the same as above and Order is _HIGH_LOW.

In[0] SINT#1 In[1] SINT#2 In[2] SINT#3

AryOut[0] AryOut[1] AryOut[2] AryOut[3]

16#02 16#01 16#00 16#03

Out = UINT#4

NJ/NX-series Instructions Reference Manual (W502)

2-477

2 Instruction Descriptions

When In Is BOOL Data

If the data type of In is BOOL (one bit), data is stored in AryOut[] as described below.

Value of Order

In (array or not)

Storage method in AryOut[]

Not an array

The logical OR of the value of In and 16#00 is stored in AryOut[0].

Array _LOW_HIGH

Values of In[0] to In[7] are joined and stored in AryOut[0]. Values of In[8] to In[15] are joined and stored in AryOut[1]. The same process is repeated to store the rest of the data. If there is not sufficient data in In[] for 8 values, FALSE is added to the most-significant bit. The value of Out is always even. If there are not sufficient bit values, the remaining values will all be FALSE.

Not an array

The logical OR of the value of In and 16#00 is stored in AryOut[1]. 16#00 is stored in AryOut[0]

Array _HIGH_LOW

Values of In[0] to In[7] are joined and stored in AryOut[1]. Values of In[8] to In[15] are joined and stored in AryOut[0]. The same process is repeated to store the rest of the data. The value of Out is always even. If there are not sufficient bit values, the remaining values will all be FALSE.

The following example is for when In is a BOOL array with 21 elements and Order is _LOW_HIGH.

In[0] TRUE In[1] FALSE In[2] FALSE In[3] TRUE In[4] FALSE In[5] FALSE In[6] FALSE In[7] TRUE In[8] TRUE In[9] FALSE In[10] TRUE In[11] FALSE In[12] FALSE In[13] FALSE In[14] TRUE In[15] FALSE In[16] FALSE In[17] FALSE In[18] TRUE In[19] FALSE In[20] FALSE

AryOut[0] AryOut[1] AryOut[2] AryOut[3]

16#89 16#45 16#04 16#00

Out = UINT#4

2-478

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

The following example is for when In is the same as above and Order is _HIGH_LOW.

In[0] TRUE

AryOut[0] 16#45

In[1] FALSE In[2] FALSE

AryOut[1] AryOut[2]

16#89 16#00

Out = UINT#4

In[3] TRUE

AryOut[3] 16#04

In[4] FALSE

In[5] FALSE

In[6] FALSE

In[7] TRUE

In[8] TRUE

In[9] FALSE

2

In[10] TRUE

ToAryByte

In[11] FALSE

In[12] FALSE

In[13] FALSE

In[14] TRUE

In[15] FALSE

In[16] FALSE

In[17] FALSE

In[18] TRUE

In[19] FALSE

In[20] FALSE

Precautions for Correct Use
· Always use a variable for the input parameter to pass to In. A building error will occur if a constant is passed.
· If In is an enumeration, you cannot directly pass an enumerator to it. A building error will occur if an enumerator is passed to it directly.
· If In is STRING data, the text string is not converted to numbers. The contents of the variable is taken as a bit string and converted to a byte array.
· If In is a structure, adjustment areas between members may be inserted into AryOut[]. · If the value of Order is _HIGH_LOW and the total number of bytes in In is an odd number, 16#00 is
added to the end of In to make an even number of bytes before the conversion is started. · An error occurs in the following cases. ENO will be FALSE, and Out and AryOut[] will not change.
· The value of Order is outside of the valid range. · The conversion result exceeds the array area of AryOut[].

NJ/NX-series Instructions Reference Manual (W502)

2-479

2 Instruction Descriptions

AryByteTo

The AryByteTo instruction joins BYTE array elements and stores the result in a variable.

Instruction AryByteTo

Name
Conversion from Byte Array

FB/FUN FUN

Graphic expression

(@)AryByteTo

EN In Size Order OutVal

ENO Out

ST expression
AryByteTo(In, Size, Order, OutVal);

Variables

Name In[] (array) Size
Order OutVal Out

Meaning

I/O

Array to convert

Number of elements to Input convert

Conversion order

Conver- In-out sion result

Return value

Output

Description Array to convert

Valid range

Unit

Number of elements in In[] Depends on data type.

to convert

---

Conversion order Conversion result

_LOW_HIGH or _HIGH_LOW
Depends on data type. ---

Always TRUE

TRUE only

---

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default *
1
_LOW _HIGH
---
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In[] (array) Size Order
OutVal
Out

OK OK
Refer to Function for the enumerators for the enumerated type _eBYTE_ORDER. OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK
An enumeration, array, array element, structure, or structure member can also be specified. OK

Function
The AryByteTo instruction takes the first Size elements in array to convert In[] and joins them to match the size of the data type of conversion result OutVal. It then stores the result in OutVal.

2-480

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Conversion Instructions

Order specifies the order to join the elements of In[]. The data type of Order is enumerated type _eBYTE_ORDER. The meaning of the enumerators are as follows:

Enumerators

Meaning

_LOW_HIGH Lower byte first, higher byte last

_HIGH_LOW Higher byte first, lower byte last

When the Data Type of OutVal Is Two Bytes or Larger

If the data type of OutVal is two bytes or larger, elements from In[] are joined so that the result is just

large enough for the size of the data type of OutVal. The result is stored in OutVal. The following data

types have two bytes or more.

Classification

Data type

2

Bit strings

WORD, DWORD, and LWORD

AryByteTo

Integers

UINT, UDINT, ULINT, INT, DINT, and LINT

Real numbers

REAL and LREAL

Times, durations, dates, and text strings

TIME, DATE, TOD, DT, and STRING types of two bytes or more

Others

An enumeration, an array for which the total for all elements is 2 bytes or more, an array element that is 2 bytes or more, a structure for which the total for all members is 2 bytes or more, or a structure member that is 2 bytes or more

The processing procedure is as follows:
1 In[0] and In[1] are joined according to the value of Order to create one word (two bytes) of data.
If Order is _LOW_HIGH, the higher byte is stored in In[1] and the lower byte is stored in In[0]. If Order is _HIGH_LOW, the higher byte is stored in In[0] and the lower byte is stored in In[1].
2 In the same way elements that start from In[2] and In[3] are joined to make more words of data.

3 The words of data are joined to match the size of the data type of OutVal. For example, if OutVal
is DWORD data, four individual words of data are joined.
4 The resulting data is stored in OutVal.

The following example is for when OutVal is DWORD data, Size is UINT#4, and Order is _LOW_HIGH.

LD

ST

AryByteTo(abc[1], UINT#4, _LOW_HIGH, def);

AryByteTo

abc[1] UINT#4 _LOW_HIGH
def

EN In Size Order OutVal

ENO def

Size = UINT#4

In[0]=abc[1] In[1]=abc[2] In[2]=abc[3] In[3]=abc[4]

BYTE#16#67 BYTE#16#45 BYTE#16#23 BYTE#16#01

OutVal=def DWORD#16#01234567

NJ/NX-series Instructions Reference Manual (W502)

2-481

2 Instruction Descriptions

The following example is for when OutVal is the same as above, Size is UINT#4, and Order is _HIGH_LOW.

Size = UINT#4

In[0] BYTE#16#67 In[1] BYTE#16#45 In[2] BYTE#16#23 In[3] BYTE#16#01

OutVal DWORD#16#23016745

When the Data Type of OutVal Is One Byte

If the data type of OutVal is one byte, one byte of In[] is stored directly in OutVal. The following data types have one byte.

Classification Bit strings Integers Real numbers Times, durations, dates, and text strings Others

BYTE USINT and SINT None STRING types with one byte

Data type

An array for which the total for all elements is 1 byte, an array element that is 1 byte, a structure for which the total for all members is 1 byte, or a structure member that is 1 byte.

The following storage method is used.

Value of Order
_LOW_HIGH
_HIGH_LOW

OutVal (array or not) Not an array Array Not an array Array

Storage method in OutVal
Value of In[0] is stored in OutVal Value of In[i] is stored in OutVal[i] Value of In[1] is stored in OutVal In[i] (where i is even) is stored in OutVal[i+1]. In[i] (where i is odd) is stored in OutVal[i-1]. If the value of Size is odd, data is stored up to OutVal[Size] and 16#00 is stored in OutVal[Size-1].

The following example is for when OutVal is a SINT array with three elements, Size is UINT#3, and Order is _LOW_HIGH.

Size = UINT#3

In[0] BYTE#16#01 In[1] BYTE#16#02 In[2] BYTE#16#03

OutVal[0] OutVal[1] OutVal[2]

SINT#1 SINT#2 SINT#3

The following example is for when OutVal and Size are the same as above and Order is _HIGH_LOW.

Size = UINT#3

In[0] BYTE#16#01 In[1] BYTE#16#02 In[2] BYTE#16#03

OutVal[0] OutVal[1] OutVal[2] OutVal[3]

SINT#2 SINT#1 SINT#0 SINT#3

2-482

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

When OutVal Is BOOL Data

If the data type of OutVal is BOOL (one bit), data is stored in OutVal as described below.

Value of Order

OutVal (array or not)

Storage method in OutVal

Not an array

Value of bit 0 of In[0] is stored in OutVal.

Array _LOW_HIGH

Value of In[0] is separated and stored in OutVal[0] to OutVal[7]. Value of In[1] is separated and stored in OutVal[8] to OutVal[15]. The same process is repeated to store the rest of the data. Remaining bits are discarded.

_HIGH_LOW

Not an array Array

Value of bit 0 of In[1] is stored in OutVal.

Value of In[0] is separated and stored in OutVal[8] to OutVal[15]. Value

2

of In[1] is separated and stored in OutVal[0] to OutVal[7]. The same

process is repeated to store the rest of the data.

Remaining bits are discarded.

AryByteTo

The following example is for when OutVal is a BOOL array with 21 elements, Size is UINT#3, and Order is _LOW_HIGH.

In[0] Size = UINT#3 In[1]
In[2]

BYTE#16#89 BYTE#16#45 BYTE#16#04

OutVal[0] OutVal[1] OutVal[2] OutVal[3] OutVal[4] OutVal[5] OutVal[6] OutVal[7] OutVal[8] OutVal[9] OutVal[10] OutVal[11] OutVal[12] OutVal[13] OutVal[14] OutVal[15] OutVal[16] OutVal[17] OutVal[18] OutVal[19] OutVal[20]

TRUE FALSE FALSE TRUE FALSE FALSE FALSE TRUE TRUE FALSE TRUE FALSE FALSE FALSE TRUE FALSE FALSE FALSE TRUE FALSE FALSE

NJ/NX-series Instructions Reference Manual (W502)

2-483

2 Instruction Descriptions

The following example is for when OutVal and Size are the same as above and Order is _HIGH_LOW.

Size = UINT#3

In[0] In[1] In[2]

BYTE#16#89 BYTE#16#45 BYTE#16#04

OutVal[0] OutVal[1] OutVal[2] OutVal[3] OutVal[4] OutVal[5] OutVal[6] OutVal[7] OutVal[8] OutVal[9] OutVal[10] OutVal[11] OutVal[12] OutVal[13] OutVal[14] OutVal[15] OutVal[16] OutVal[17] OutVal[18] OutVal[19] OutVal[20]

TRUE
FALSE
TRUE
FALSE
FALSE
FALSE
TRUE
FALSE
TRUE
FALSE
FALSE
TRUE
FALSE
FALSE
FALSE
TRUE
Not changed. Not changed. Not changed. Not changed. Not changed.

Precautions for Correct Use
· If OutVal is a structure, some of the values of In[] may be inserted in adjustment areas between members depending on the composition.
· If the value of Size is 0, the value of Out will be TRUE and OutVal will not change. · Return value Out is not used when the instruction is used in ST. · An error occurs in the following cases. ENO will be FALSE, and OutVal will not change.
· The value of Order is outside of the valid range. · The value of Size exceeds the number of elements in In[].

2-484

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

SizeOfAry

The SizeOfAry instruction gets the number of elements in an array.

Instruction SizeOfAry

Name
Get Number of Array Elements

FB/FUN FUN

Graphic expression

(@)SizeOfAry

EN

ENO

In

Out

ST expression Out:=SizeOfAry(In);

Variables

2

SizeOfAry

Name In[] (array) Out

Meaning
Array
Number of elements

I/O Input Output

Description Array Number of elements

Valid range

Unit

Depends on data type. ---

Depends on data type. ---

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default *
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In[] (array) Out

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK Arrays of enumerations or structures can also be specified. OK

Function

The SizeOfAry instruction gets the number of elements in array In[]. For the input parameter, use an array name, such as array, and not an array element name, such as array[0].
The following figure shows a programming example.

Variable

Data type

abc

ARRAY[0..3] OF INT

LD

ST

def:=SizeOfAry(abc);

SizeOfAry

EN abc In

ENO def

In[0]=abc[0] In[1]=abc[1] In[2]=abc[2] In[3]=abc[3]

Number of array elements Out=def UINT#4

NJ/NX-series Instructions Reference Manual (W502)

2-485

2 Instruction Descriptions

Additional Information

In[] can be an array with two or more dimensions. Out will contain the total number of elements for all dimensions of In[]. For example, if the input parameter that is passed to In[] is ARRAY[0..1,0..2], the
value of Out will be UINT#6.

Variable

Data type

abc

ARRAY[0..1,0..2] OF BOOL

LD

ST

def:=SizeOfAry(abc);

SizeOfAry

EN abc In

ENO def

In[0,0]=abc[0,0] In[0,1]=abc[0,1] In[0,2]=abc[0,2] In[1,0]=abc[1,0] In[1,1]=abc[1,1] In[1,2]=abc[1,2]

Number of array elements Out=def UINT#6

2-486

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

PackWord

The PackWord instruction joins two 1-byte data into a 2-byte data.

Instruction

Name

FB/ FUN

Graphic expression

ST expression

PackWord

2-byte Join

FUN

(@)PackWord

EN

ENO

Out:=PackWord(High,Low);

High

Out

Low

2

PackWord

Version Information
A CPU Unit with unit version 1.12 or later and Sysmac Studio version 1.16 or higher are required to use this instruction.

Variables

Name High Low Out

Meaning Byte data H Byte data L Joined data

I/O Input Output

Description Data in bytes stored in bit 15-8 Data in bytes stored in bit 7-0 2-byte data

Valid range
Depends on data type.
Depends on data type.
Depends on data type.

Unit -------

Default 0 0 ---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

High Low Out

OK OK
OK

NJ/NX-series Instructions Reference Manual (W502)

2-487

2 Instruction Descriptions

Function
The PackWord instruction joins two 1-byte data into a 2-byte data. The data specified in High is stored in bit 15-8, and the data specified in Low is stored in bit 7-0.

The following example shows the instruction when High is 16#12 and Low is 16#34. The value of variable abc will be 16#1234.

 LD

High 16#12 Low 16#34

15

87

0

Out=abc 16#12 34

P_On

PackWord

16#12 16#34

EN High Low

ENO abc

 ST
abc:=PackWord(16#12,16#34);

2-488

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

PackDword

The PackDword instruction joins four 1-byte data into a 4-byte data.

Instruction

Name

FB/ FUN

Graphic expression

ST expression

PackDword

4-byte Join

FUN

(@)PackDword

Out:=PackDword(

EN

ENO

HighHigh,

HighHigh

Out

HighLow

LowHigh

LowLow

HighLow,

LowHigh,

2

LowLow);

PackDword

Version Information
A CPU Unit with unit version 1.12 or later and Sysmac Studio version 1.16 or higher are required to use this instruction.

Variables

Name HighHigh HighLow LowHigh LowLow Out

Meaning

I/O

Byte data HH

Byte data HL Byte data LH

Input

Byte data LL

Joined data Output

Description Data in bytes stored in bit 31-24 Data in bytes stored in bit 23-16 Data in bytes stored in bit 15-8 Data in bytes stored in bit 7-0 4-byte data

Valid range
Depends on data type.
Depends on data type.
Depends on data type.
Depends on data type.
Depends on data type.

Unit -----------

Default 0 0 0 0 ---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

HighHigh HighLow LowHigh LowLow Out

OK OK OK OK
OK

NJ/NX-series Instructions Reference Manual (W502)

2-489

2 Instruction Descriptions

Function
The PackDword instruction joins four 1-byte data into a 4-byte data. The data specified in HighHigh is stored in bit 31-24, the data specified in HighLow in bit 23-16, the data specified in LowHigh in bit 15-8, and the data specified in LowLow in bit 7-0.

The following example shows the instruction when HighHigh is 16#12, HighLow is 16#34, LowHigh is 16#56, and LowLow is 16#78.
The value of variable abc will be 16#12345678.

HighHigh 16#12

HighLow 16#34

31 24 23 16 15 8 7

0

Out=abc 16#12 34 56 78

LowHigh 16#56

 LD

LowLow 16#78

P_On

PackDword

16#12
16#34 16#56 16#78

EN HighHigh HighLow LowHigh LowLow

ENO abc

 ST
abc:=PackDword(16#12,16#34,16#56,16#78);

2-490

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

LOWER_BOUND / UPPER_BOUND

The LOWER_BOUND instruction gets the first number of array dimensions. The UPPER_BOUND instruction gets the last number of array dimensions.

Instruction

Name

FB/ FUN

Graphic expression

ST expression
2

LOWER_BOU ND

Get First Number of Array

FUN

(@)LOWER_BOUND

EN ARR DIM

ENO Out

Out:=LOWER_BOUND(ARR, DIM);

UPPER_BOUN D

Get Last Number of Array

FUN

(@)UPPER_BOUND

EN ARR DIM

ENO Out

Out:=UPPER_BOUND(ARR, DIM);

LOWER_BOUND / UPPER_BOUND

Version Information
A CPU Unit with unit version 1.18 or later and Sysmac Studio version 1.22 or higher are required to use this instruction.

Variables

Name

Meaning

I/O

Description

Valid range

Unit

ARR

Array to process

Input

Specify the array from which to

get the first number or last

---

number of array. *1

---

DIM

Dimension

Specify the dimension. *2

---

---

Out

Return value Output

LOWER_BOUND: First number Depends on UPPER_BOUND: Last number data type.

---

*1. Use an array name, such as array, and not an array element name, such as array[0].

*2. For one-dimensional array, specify 1.

Default --1 ---

NJ/NX-series Instructions Reference Manual (W502)

2-491

2 Instruction Descriptions

STRING DT TOD
DATE TIME LREAL Real numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE

Boolean

Bit strings

Integers

Times, durations, dates, and text strings

BOOL

ARR
DIM Out

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK Arrays of enumerations or structures can also be specified. OK OK

Function
The LOWER_BOUND instruction gets the first number of the dimension specified in DIM of the array variable specified in ARR. Similarly, the UPPER_BOUND instruction gets the last number of the dimension specified in DIM of the array variable specified in ARR.

Related System-defined Variables

Name P_PRGER

Meaning Instruction Error Flag

Data type
BOOL

Description
TRUE: Error occurred. It remains TRUE until changed to FALSE. FALSE: Set to FALSE by the user program.

Precautions for Correct Use
An error will occur in the following cases. ENO will change to FALSE, and Out will not change. · ARR is not an array. · The value specified in DIM is 0 or less, or exceeds the range of the dimension of ARR.

2-492

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

Sample Programming

Calculating the Sum of an Array
This sample programming shows how to define a one-dimensional variable-length array variable and how to get the first number and last number of the dimension in the variable-length array variable.
 User-defined Function Program (Sum)

Internal Variables
i

Variable

Data type DINT

Initial value

Comment
2

LOWER_BOUND / UPPER_BOUND

Input/output vari-
ables

Variable
EN ENO a

I/O
Input Output In-out

Data type
BOOL BOOL ARRAY[*] OF INT

Comment

Return value

Variable Sum

Data type INT

Initial value

Comment

Sum := 0; FOR i := LOWER_BOUND(a,1) TO UPPER_BOUND(a,1) DO
Sum := Sum + a[i]; END_FOR;

NJ/NX-series Instructions Reference Manual (W502)

2-493

2 Instruction Descriptions

 Calling Program

Internal Variables

Variable
v1 v2 sum1 sum2

Data type
ARRAY[0..4] OF INT ARRAY[0..9] OF INT INT INT

Initial value
[1,2,3,4,5] [1,2,3,4,5,6,7,8,9,10]

Sum1 = 1+2+3+4+5 =15

P_On

Sum

EN

ENO

v1 a

a

v1 sum1

Sum2 = 1+2+3+4+5+6+7+8+9+10 =55

P_On

Sum

EN

ENO

v2 a

a v2 sum2

Comment

Adding 2×2 Matrices
This sample programming shows how to define a multi-dimensional variable-length array variable and how to use the LOWER_BOUND and UPPER_BOUND instructions for the multi-dimensional variablelength array variable.
 User-defined Function Program (Matrix_Add)

Internal Variables
i j m1 m2 n1 n2

Variable

Data type
DINT DINT DINT DINT DINT DINT

Initial value

Comment

Input/output vari-
ables

Variable
EN ENO A B C

I/O
Input Output In-out In-out In-out

Data type
BOOL BOOL ARRAY[*,*] OF DINT ARRAY[*,*] OF DINT ARRAY[*,*] OF DINT

Comment

2-494

NJ/NX-series Instructions Reference Manual (W502)

Conversion Instructions

2 Instruction Descriptions

Return value

Variable Matrix_Add

Data type BOOL

Initial value

m1 := LOWER_BOUND(C,1); m2 := UPPER_BOUND(C,1); n1 := LOWER_BOUND(C,2); n2 := UPPER_BOUND(C,2);
FOR i := m1 TO m2 DO FOR j := n1 TO n2 DO C[i,j] := A[i,j] + B[i,j]; END_FOR;
END_FOR;
 Calling Program

Internal Variables
X Y Z

Variable

Data type
ARRAY[0..1,0..1] OF DINT ARRAY[0..1,0..1] OF DINT ARRAY[0..1,0..1] OF DINT

Initial value
[0, 1, 2, 3] [1, 2, 3, 4]

// Z = X + Y = |0 1| + |1 2| = |1 3|

//

|2 3| |3 4| |5 7|

Matrix_Add(X, Y, Z);

Comment
2
Comment

LOWER_BOUND / UPPER_BOUND

NJ/NX-series Instructions Reference Manual (W502)

2-495

2 Instruction Descriptions

2-496

NJ/NX-series Instructions Reference Manual (W502)

Stack and Table Instructions

2
Stack and Table Instructions

Instruction StackPush StackFIFO and StackLIFO StackIns StackDel RecSearch RecRangeSearch RecSort RecNum RecMax and RecMin

Name Push onto Stack First In First Out/Last In First Out Insert into Stack Delete from Stack Record Search Range Record Search Record Sort Get Number of Records Maximum Record Search/ Minimum Record Search

Page 2-498 2-507 2-510 2-512 2-514 2-519 2-524 2-530 2-532

NJ/NX-series Instructions Reference Manual (W502)

2-497

2 Instruction Descriptions

StackPush

The StackPush instruction stores a value at the top of a stack.

Instruction StackPush

Name Push onto Stack

FB/FUN FUN

Graphic expression

(@)StackPush

EN In InOut

ENO Out

Size Num

ST expression
StackPush(In, InOut, Size, Num);

Variables

Name

Meaning

I/O

In

Input value

Size
InOut[] (array) Num
Out

Number of stack elements

Input

Stack array

Number of stored elements
Return value

In-out Output

Description

Valid range

Unit

Value, structure, or structure

member to place in the

stack Number of stack array

Depends on data type. ---

elements

Array that functions as stack
Number of elements stored Depends on data type. --in stack

Always TRUE

TRUE only
---

Default
---
1
-----

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In
Size InOut[] (array) Num Out

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK An enumeration, structure, or structure member can also be specified. OK Must be an array with elements that have the same data type as In.
OK OK

2-498

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Stack and Table Instructions

Function

The instruction assumes that there are number of stored elements Num elements stored in stack array InOut[]. Input value In is written to the next element, InOut[Num]. Then, Num is incremented. For number of stack elements Size, specify the number of elements in InOut[] to use as a stack.
The following example is for when Size is UINT#5 and Num is UINT#2.

LD

ST

StackPush(INT#3456, abc[1], UINT#5, def);

StackPush

2

EN

ENO

INT#3456 In

StackPush

abc[1]

InOut

abc[1]

UINT#5 Size

Num

def

def

Num=def UINT#2

Incremented Num=def UINT#3

Size=UINT#5

InOut[0]=abc[1] InOut[1]=abc[2] InOut[2]=abc[3] InOut[3]=abc[4] InOut[4]=abc[5]

1234 2345
0 : 0 0

Stored

InOut[0]=abc[1] InOut[1]=abc[2] InOut[2]=abc[3] InOut[3]=abc[4] InOut[4]=abc[5]

1234 2345 3456
0 0

In INT#3456

Additional Information
Use the StackFIFO or StackLIFO instruction (page 2-507) to remove the bottom or top value that was stored in the stack.

Precautions for Correct Use
· Use the same data type for In and the elements of InOut[]. If they are different, a building error will occur.
· When an element in the array is passed to InOut[], all elements below the passed element are processed.
· The value of InOut[] or Num does not change if the value of Size is 0. · Always use a variable for the input parameter to pass to In. A building error will occur if a constant is
passed. · If In is an enumeration, you cannot directly pass an enumerator to it. A building error will occur if an
enumerator is passed to it directly. · Return value Out is not used when the instruction is used in ST. · An error occurs in the following cases. ENO will be FALSE, and InOut[] will not change.
· The value of Size is not 0 and Num is greater than or equal to Size. · The value of Size exceeds the array area of InOut[]. · In and InOut[] are STRING data and the number of bytes in In exceeds the size of InOut[].

NJ/NX-series Instructions Reference Manual (W502)

2-499

2 Instruction Descriptions

Sample Programming

The array variable StcA[0..9] is used as a stack. As preparations, three values (UINT#1111, UINT#2222, and UINT#3333) are stored in the stack.

StcA[0] StcA[1] StcA[2] StcA[3] StcA[4] StcA[5] StcA[6] StcA[7] StcA[8] StcA[9]

1111 2222 3333
0 0 0 0 0 0 0

The StackPush instruction is used to store a new value (UINT#4444) at the top of the stack StcA[3]. That means there will be four values in the stack.

StcANum UINT#3

StackPush instruction executed. StcANum UINT#4

StcA[0] StcA[1] StcA[2] StcA[3] StcA[4] StcA[5] StcA[6] StcA[7] StcA[8] StcA[9]

1111 2222 3333
0 0 0 0 0 0 0

Stored. StcAInVal UINT#4444

StcA[0] StcA[1] StcA[2] StcA[3] StcA[4] StcA[5] StcA[6] StcA[7] StcA[8] StcA[9]

1111 2222 3333 4444
0 0 0 0 0 0

Then, the StackLIFO instruction is used to remove one value at the top of the stack StcA[3]. That means there will be three values in the stack.

StackLIFO instruction executed.

StcANum UINT#4

StcANum UINT#3

StcA[0] StcA[1] StcA[2] StcA[3] StcA[4] StcA[5] StcA[6] StcA[7] StcA[8] StcA[9]

1111 2222 3333 4444
0 0 0 0 0 0

Removed. UINT#4444

StcA[0] StcA[1] StcA[2] StcA[3] StcA[4] StcA[5] StcA[6] StcA[7] StcA[8] StcA[9]

1111 2222 3333 4444
0 0 0 0 0 0

2-500

NJ/NX-series Instructions Reference Manual (W502)

Stack and Table Instructions

2 Instruction Descriptions

Finally, the StackIns instruction is used to insert a value (UINT#5555) between StcA[1] and StcA[2]. That means there will be four values in the stack.

StackIns instruction executed.

StcANum UINT#3

StcANum UINT#4

StcA[0] 1111

StcA[0] 1111

StcA[1] 2222

StcA[1] 2222

StcA[2] 3333

StcA[2] 5555

StcA[3] 4444

StcA[3] 3333

StcA[4]

0

StcA[4]

0

StcA[5]

0

StcA[5]

0

StcA[6]

0

Inserted.

StcA[6]

0

StcA[7]

0

StcA[8]

0

In UINT#5555

StcA[7]

0

StcA[8]

0

2

StcA[9]

0

StcA[9]

0

StackPush

LD Variable
InitStc StcANum StcA StcASize SetParaPush StcAInVal StcAPushStat StackPush_err StcALIFOStat StcAOutVal StackLIFO_err
SetParaIns
StcAInsVal StcAOffset StcAInsStat StackIns_err

Data type BOOL UINT ARRAY[0..9] OF UINT UINT BOOL UINT BOOL BOOL BOOL UINT BOOL
BOOL
UINT UINT BOOL BOOL

Initial value FALSE 0 [10(0)] 0 FALSE 0 FALSE FALSE FALSE 0 FALSE
FALSE
0 0 FALSE FALSE

Comment Stack initialization condition Number of stored elements Stack array Number of stack elements Execution condition to set StcAInVal. Value added by StackPush StackPush execution condition StackPush error flag StackLIFO execution condition Value removed by StackLIFO StackLIFO error flag Execution condition to set StcAInsVal and StcAOffset Value inserted by StackIns Offset for StackIns StackIns execution condition StackIns error flag

NJ/NX-series Instructions Reference Manual (W502)

2-501

2 Instruction Descriptions

Initialize stack. InitStc

Inline ST Note: The contents of the inline ST are given below.

Store three values in stack.

InitStc

StackPush

UINT#1111
StcA[0] StcASize
StcANum

EN In InOut
Size Num

ENO

UINT#2222
StcA[0] StcASize
StcANum

StackPush

EN In InOut

ENO

Size Num

UINT#3333
StcA[0] StcASize
StcANum

StackPush

EN In InOut

ENO

Size Num

Set the value to add with StackPush.

SetParaPush UINT#4444

MOVE

EN

ENO

In

Out

StcAInVal

2-502

NJ/NX-series Instructions Reference Manual (W502)

Stack and Table Instructions

2 Instruction Descriptions

Add data with StackPush instruction.

StcAPushStat
StcAinVal StcA[0]
StcASize StcANum

StackPush

EN In InOut

ENO

Size Num

StackPush_err

Processing after normal end of StackPush

StcAPushStat StackPush_err

Inline ST

1 // Processing after normal end of StackPush 2 ;

2

StackPush

Processing after error end of StackPush StcAPushStat StackPush_err

Inline ST
1 // Processing after error end of StackPush 2 ;

Remove data with StackLIFO instruction.

StcALIFOStat

StackLIFO

EN

ENO

StcA[0]
StcAOutVal StcASize
StcANum

InOut
OutVal
Size Num

StackLIFO_err

Processing after normal end of StackLIFO StcALIFOStat StackLIFO_err

Inline ST
1 // Processing after normal end of StackLIFO 2 ;

Processing after error end of StackLIFO StcALIFOStat StackLIFO_err

Inline ST
1 // Processing after error end of StackLIFO 2 ;

Set the insert value and offset with StackInsh.

SetParaIns UINT#5555

MOVE

EN

ENO

In

Out

StcAInsVal

UINT#2

MOVE

EN

ENO

In

Out

StcAOffset

NJ/NX-series Instructions Reference Manual (W502)

2-503

2 Instruction Descriptions

Insert data with StackIns instruction.

StcAInsStat
StcAInsVal
StcA[0] StcASize
StcANum StcAOffset

StackIns

EN In InOut

ENO

Size Num

Offset

StackIns_err

Processing after normal end of StackIns

StcAInsStat

StackIns_err

Inline ST
1 // Processing after normal end of StackIns 2 ;

Processing after error end of StackIns

StcAInsStat

StackIns_err

Inline ST
1 // Processing after error end of StackIns 2 ;

Contents of Inline ST
StcANUM:=0; Clear(StcA); StcASize:=SizeOfAry(StcA);

2-504

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Stack and Table Instructions

ST

Variable InitStc preInitStc StcANum StcA

Data type BOOL BOOL UINT ARRAY[0..9] OF UINT

Initial value FALSE FALSE 0 [10(0)]

Comment Stack initialization condition Value of InitStc from previous task period Number of stored elements Stack array

StcASize StcAPushStat
preStcAPushStat
StcAInVal StcAPush_OK

UINT BOOL
BOOL
UINT BOOL

0 FALSE
FALSE
0 FALSE

Number of stack elements

StackPush execution condition

Value of StcAPushStat from previous task period

Value added by StackPush

2

StackPush normal end flag

StackPush

StcAPushNormalEnd BOOL

StcAPushErrorEnd BOOL

StcALIFOStat

BOOL

FALSE FALSE FALSE

Processing after normal end of StackPush Processing after error end of StackPush StackLIFO execution condition

preStcALIFOStat

BOOL

StcAOutVal

UINT

StcALIFO_OK

BOOL

StcALIFONormalEnd BOOL

FALSE
0 FALSE FALSE

Value of StcALIFOStat from previous task period Value removed by StackLIFO StackLIFO normal end flag Processing after normal end of StackLIFO

StcALIFOErrorEnd StcAInsStat
preStcAInsStat
StcAInsVal StcAOffset

BOOL BOOL
BOOL
UINT UINT

FALSE FALSE
FALSE
0 0

Processing after error end of StackLIFO StackIns execution condition Value of StcAInsStat from previous task period Value inserted by StackIns Offset for StackIns

StcAIns_OK StcAInsNormalEnd StcAInsErrorEnd

BOOL BOOL BOOL

FALSE FALSE FALSE

StackIns normal end flag Processing after normal end of StackIns Processing after error end of StackIns

// Initialize stack. IF ( (InitStc=TRUE) AND (preInitStc=FALSE) ) THEN
StcANum:=0; Clear(StcA); StcASize:=SizeOfAry(StcA); END_IF;

// Store three values in stack. IF ( (InitStc=TRUE) AND (preInitStc=FALSE) ) THEN
StackPush(In:=UINT#1111, InOut:=StcA[0], Size:=StcASize, Num:=StcANum); StackPush(In:=UINT#2222, InOut:=StcA[0], Size:=StcASize, Num:=StcANum); StackPush(In:=UINT#3333, InOut:=StcA[0], Size:=StcASize, Num:=StcANum); END_IF;

preInitStc:=InitStc;

// Add data with StackPush instruction.

IF ( (StcAPushStat=TRUE) AND (preStcAPushStat=FALSE) ) THEN

StcAInVal:=UINT#4444;

StackPush(

In :=StcAInVal, // Value to add

InOut :=StcA[0],

// First element in stack array

Size :=StcASize,

// Number of stack elements

Num :=StcANum,

// Number of stored elements

ENO =>StcAPush_OK); // Normal end flag

NJ/NX-series Instructions Reference Manual (W502)

2-505

2 Instruction Descriptions

IF (StcAPush_OK=TRUE) THEN StcAPushNormalEnd:=TRUE;
ELSE StcAPushErrorEnd :=TRUE;
END_IF; END_IF; preStcAPushStat:=StcAPushStat;

// Processing after normal end // Processing after error end

// Remove data with StackLIFO instruction.

IF ( (StcALIFOStat=TRUE) AND (preStcALIFOStat=FALSE) ) THEN

StackLIFO(

InOut :=StcA[0],

// First element in stack array

OutVal :=StcAOutVal, // Value removed from stack

Size :=StcASize,

// Number of stack elements

Num :=StcANum,

// Number of stored elements

ENO =>StcALIFO_OK); // Normal end flag

IF (StcALIFO_OK=TRUE) THEN

StcALIFONormalEnd:=TRUE; // Processing after normal end

ELSE

StcALIFOErrorEnd:=TRUE; // Processing after error end

END_IF;

END_IF;

preStcALIFOStat:=StcALIFOStat;

// Insert data with StackIns instruction.

IF ( (StcAInsStat=TRUE) AND (preStcAInsStat=FALSE) ) THEN

StcAInsVal:=UINT#5555;

StcAOffset:=UINT#2;

StackIns(

In :=StcAInsVal, // Value to insert into stack

InOut :=StcA[0],

// First element in stack array

Size :=StcASize,

// Number of stack elements

Num :=StcANum,

// Number of stored elements

Offset:=StcAOffset, // Offset at which to insert value

ENO =>StcAIns_OK); // Normal end flag

IF (StcAIns_OK=TRUE) THEN

StcAInsNormalEnd:=TRUE;// Processing after normal end

ELSE

StcAInsErrorEnd:=TRUE; // Processing after error end

END_IF;

END_IF;

preStcAInsStat:=StcAInsStat;

2-506

NJ/NX-series Instructions Reference Manual (W502)

Stack and Table Instructions

2 Instruction Descriptions

StackFIFO and StackLIFO

StackFIFO: Removes the bottom value from a stack. StackLIFO: Removes the top value from a stack.

Instruction StackFIFO

Name First In First Out

FB/FUN FUN

Graphic expression

ST expression

(@)StackFIFO

EN

ENO

StackFIFO(InOut, OutVal, Size, Num);

Out InOut

2

OutVal

Size Num

StackFIFO and StackLIFO

StackLIFO

Last In First Out

FUN

(@)StackLIFO

EN InOut

ENO Out

OutVal

Size Num

StackLIFO(InOut, OutVal, Size, Num);

Variables

Name Size
InOut[] (array) OutVal Num
Out

Meaning

I/O

Number of stack elements

Input

Stack array

Output value
Number of stored elements
Return value

In-out Output

Description
Number of stack array elements

Valid range

Unit

Depends on data type. ---

Array that functions as stack

Value or structure output from stack

Depends on data type. ---

Number of elements stored in stack

Always TRUE

TRUE only

---

Default 1
-----

NJ/NX-series Instructions Reference Manual (W502)

2-507

2 Instruction Descriptions

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

Bit strings

Integers

Times, durations, dates, and text strings

Size
InOut[] (array)
OutVal Num Out

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK
Arrays of enumerations or structures can also be specified. Must be the same data type as the elements of InOut[]. OK
OK

Function

The instruction assumes that there are number of stored elements Num elements stored in stack array InOut[]. The instruction removes a value from the stack and assigns it to output value OutVal. For number of stack elements Size, specify the number of elements in InOut[] to use as a stack.

 StackFIFO
The StackFIFO removes the bottom value from a stack. Value of InOut[0] is assigned to OutVal. Then, all Num - 1 elements from InOut[1] are shifted to the next lower element in the stack array. Then 0 is stored in InOut[Num-1]. Finally, Num is decremented.
The following example is for when Size is UINT#5 and Num is UINT#3.

LD

ST

StackFIFO(abc[1], def, UINT#5, ghi);

abc[1]
def UINT#5
ghi

StackFIFO

EN

ENO

InOut

OutVal

Size Num

abc[1] def ghi

Num = ghi UINT#3

Size=UINT#5

InOut[0]=abc[1] InOut[1]=abc[2] InOut[2]=abc[3] InOut[3]=abc[4] InOut[4]=abc[5]

1234 2345 3456
0 0

Removed.

OutVal = def

Decremented. Num = ghi UINT#2

InOut[0]=abc[1] InOut[1]=abc[2] InOut[2]=abc[3] InOut[3]=abc[4] InOut[4]=abc[5]

2345 3456 3456
0 0

OutVal = def INT#1234

2-508

NJ/NX-series Instructions Reference Manual (W502)

Stack and Table Instructions

2 Instruction Descriptions

 StackLIFO
The StackLIFO instruction removes the top value from a stack. Value of InOut[Num-1] is assigned to OutVal. Then, Num is decremented. The following example is for when Size is UINT#5 and Num is UINT#2.

LD

ST

StackLIFO(abc[1], def, UINT#5, ghi);

abc[1]
def UINT#5
ghi

StackLIFO

EN

ENO

InOut

OutVal

Size Num

abc[1] def ghi

Num = ghi UINT#3

2
Decremented. Num = ghi UINT#2

StackFIFO and StackLIFO

Size=UINT#5

InOut[0]=abc[1] InOut[1]=abc[2] InOut[2]=abc[3] InOut[3]=abc[4] InOut[4]=abc[5]

1234 2345 3456
0 0

Removed.

InOut[0]=abc[1] InOut[1]=abc[2] InOut[2]=abc[3] InOut[3]=abc[4] InOut[4]=abc[5]

1234 2345 3456
0 0

OutVal = def

OutVal = def INT#3456

Precautions for Correct Use
· Use the same data type for InOut[] and OutVal. If they are different, a building error will occur. · When an element in the array is passed to InOut[], all elements below the passed element are pro-
cessed. · The values in InOut[], Num, and OutVal do not change if the value of Size or Num is 0. · Return value Out is not used when the instruction is used in ST. · An error occurs in the following cases. ENO will be FALSE, and OutVal will not change.
· The values of Num and Size are not 0 and Num is greater than Size. · The value of Size exceeds the array area of InOut[]. · InOut[] is a STRING array and any of the elements does not end in a NULL character. · InOut[] is a STRING array and the number of bytes in the elements exceeds the size of OutVal.
Sample Programming
Refer to the sample programming that is provided for the StackPush instruction (page 2-498).

NJ/NX-series Instructions Reference Manual (W502)

2-509

2 Instruction Descriptions

StackIns

The StackIns instruction inserts a value at a specified position in a stack.

Instruction StackIns

Name Insert into Stack

FB/FUN FUN

Graphic expression

(@)StackIns

EN ENO

In

Out

InOut

Size Num

Offset

ST expression
StackIns(In, InOut, Size, Num, Offset);

Variables

Name

Meaning

I/O

In

Insert value

Size
Offset InOut[] (array) Num
Out

Number of stack elements
Offset

Input

Stack array

Number of stored elements
Return value

In-out Output

Description

Valid range

Unit

Value, structure, or structure member to insert into the stack

Number of stack array elements

Depends on data type. ---

Position in stack at which to insert In
Array that functions as stack

Number of elements stored Depends on data type. --in stack

Always TRUE

TRUE only
---

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default * 1 0
---
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In
Size Offset InOut[] (array) Num Out

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK An enumeration, structure, or structure member can also be specified. OK OK Must be an array with elements that have the same data type as In.
OK OK

2-510

NJ/NX-series Instructions Reference Manual (W502)

Stack and Table Instructions

2 Instruction Descriptions

Function

The instruction assumes that there are number of stored elements Num elements stored in stack array InOut[]. Insert value In is inserted at the position specified by the offset Offset (InOut[Offset]). All higher elements, i.e., InOut[Offset] to InOut[Num-1], are moved to the next higher element in the stack array. Then, Num is incremented. For number of stack elements Size, specify the number of elements in InOut[] to use as a stack.
The following example is for when Size is UINT#6, Num is UINT#3 and Offset is UINT#1.

LD

ST

StackIns

StackIns(INT#2345, abc[1], UINT#6, def, UINT#1);

2

EN ENO

INT#2345 In

InOut

StackIns

abc[1] UINT#6 Size

abc[1]

Num

def

def

UINT#1 Offset

Num=def UINT#3

Incremented. Num=def UINT#4

Size=UINT#6

InOut[0]=abc[1] InOut[1]=abc[2] InOut[2]=abc[3] InOut[3]=abc[4] InOut[4]=abc[5] InOut[5]=abc[6]

1234 3456 4567
0 0 0

Offset=UINT#1 Inserted. In INT#2345

InOut[0]=abc[1] InOut[1]=abc[2] InOut[2]=abc[3] InOut[3]=abc[4] InOut[4]=abc[5] InOut[5]=abc[6]

1234 2345 3456 4567
0 0

Precautions for Correct Use
· Use the same data type for In and InOut[]. If they are different, a building error will occur. · When an element in the array is passed to InOut[], all elements below the passed element are pro-
cessed. · The values in InOut[] and Num do not change if the value of Size is 0. · Always use a variable for the input parameter to pass to In. A building error will occur if a constant is
passed. · If In is an enumeration, you cannot directly pass an enumerator to it. A building error will occur if an
enumerator is passed to it directly. · Return value Out is not used when the instruction is used in ST. · An error occurs in the following cases. ENO will be FALSE, and InOut[] will not change.
· The value of Size is not 0 and Size is not greater than Num and Num is not greater than or equal to Offset.
· The value of Size exceeds the array area of InOut[]. · In and InOut[] are STRING data and the number of bytes in In exceeds the size of InOut[].

Sample Programming
Refer to the sample programming that is provided for the StackPush instruction (page 2-498).

NJ/NX-series Instructions Reference Manual (W502)

2-511

2 Instruction Descriptions

StackDel

The StackDel instruction deletes a value from a specified position in a stack.

Instruction StackDel

Name Delete from Stack

FB/FUN FUN

Graphic expression
(@)StackDel EN ENO
Out InOut

ST expression
StackDel(InOut, Size, Num, Offset);

Size Num

Offset

Variables

Name Size
Offset

Meaning
Number of stack elements
Offset

I/O Input

InOut[] (array) Num
Out

Stack array

Number of stored elements
Return value

In-out Output

Description

Valid range

Unit

Number of stack array elements
Offset of value to delete from stack

Depends on data type. ---

Array that functions as stack

Number of elements stored Depends on data type. --in stack

Always TRUE

TRUE only

---

Default 1 0
-----

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

Size Offset
InOut[] (array)
Num Out

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK Arrays of enumerations or structures can also be specified. OK OK

Function
The instruction assumes that there are number of stored elements Num elements stored in stack array InOut[]. The value is deleted from the position specified by the offset Offset (InOut[Offset]). All higher elements, i.e., InOut[Offset+1] to InOut[Num-1], are moved to the next lower element in the stack array. Then, Num is decremented. For number of stack elements Size, specify the number of elements in InOut[] to use as a stack.

2-512

NJ/NX-series Instructions Reference Manual (W502)

Stack and Table Instructions

2 Instruction Descriptions

The following example is for when Size is UINT#6, Num is UINT#3 and Offset is UINT#1.

LD

ST

StackDel(abc[1], UINT#6, def, UINT#1);

StackDel EN ENO

InOut

abc[1] UINT#6
def

Size Num

abc[1] def

UINT#1 Offset

2

Num = def UINT#3

Decremented. Num=def UINT#2

StackDel

Size=UINT#6

InOut[0]=abc[1] InOut[1]=abc[2] InOut[2]=abc[3] InOut[3]=abc[4] InOut[4]=abc[5] InOut[5]=abc[6]

1234 2345 3456
0 0 0

Offset=UINT#1 Deleted.

InOut[0]=abc[1] InOut[1]=abc[2] InOut[2]=abc[3] InOut[3]=abc[4] InOut[4]=abc[5] InOut[5]=abc[6]

1234 3456 3456
0 0 0

Precautions for Correct Use
· When an element in the array is passed to InOut[], all elements below the passed element are processed.
· The values in InOut[] and Num do not change if the value of Size or Num is 0. · Return value Out is not used when the instruction is used in ST. · An error occurs in the following cases. ENO will be FALSE, and InOut[] will not change.
· The values of Num and Size are not 0 and Size is not greater than or equal to Num and Num is not greater than Offset.
· The value of Size exceeds the array area of InOut[].

NJ/NX-series Instructions Reference Manual (W502)

2-513

2 Instruction Descriptions

RecSearch

The RecSearch instruction searches an array of structures for elements that match the search key with the specified method.

Instruction RecSearch

Name Record Search

FB/FUN FUN

Graphic expression

(@)RecSearch

EN In Size Member Key Mode InOutPos

ENO Out
Num

ST expression
Out:=RecSearch(In, Size, Member, Key, Mode, InOutPos, Num);

Variables

Name In[] (array) Size
Member Key Mode

Meaning

I/O

Array to search

Number of elements to search

Member to Input search

Search key

Search method

InOutPos[] (array)
Out

Element numbers of matching elements
Search result

In-out

Output

Num

Number of matches

Description

Valid range

Unit

Array of structures to search ---

Number of array elements to search

Member of In[] structure to search Search value Search method
Element numbers of matching elements

Depends on data type. ---
_LINEAR, _BIN_ASC, _BIN_DESC Depends on data type. ---

TRUE: There are elements that match conditions
FALSE: There are no elements that match conditions
Number of matches

Depends on data type. ---

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default * 1
* _LINEAR
---
---

2-514

NJ/NX-series Instructions Reference Manual (W502)

Stack and Table Instructions
STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

2 Instruction Descriptions

Bit strings

Integers

Times, durations, dates, and text strings

In[] (array) Size Member

Key

Mode

InOutPos[] (array)

Out

OK

Num

Specify an array of structures.

OK

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK

*

2

Specify the same data type as the search member of In[]

Must be the same data type as Member.

Refer to Function for the enumerators of the enumerated type _eSEARCH_MODE.

OK

RecSearch

OK

* You can specify TIME, DATE, TOD, DT, and STRING data with CPU Units with unit version 1.01 or later and Sysmac Studio version 1.02 or higher.

Function

The RecSearch instruction searches Size elements in the array of structures In[]. The search range is therefore from In[0] to In[Size-1]. The instruction searches member to search Member in the structures for members that match the search key Key. One of the members to search in the elements of In[] is passed as an argument to Member. If any matching elements are found, the value of search result Out changes to TRUE. The element number of the matching element is assigned to InOutPos[0] and the number of matching elements is assigned to Num. If there is more than one matching element, the element number of the lowest matching element in In[] is assigned to InOutPos[0]. If there are no matching elements, the value of Out will be FALSE and InOutPos[0] and Num will be 0.
Always attach the element number to input parameter that is passed to In[], e.g., array[3].
The data type of search method Mode is enumerated type _eSEARCH_MODE. The meanings of the enumerators are as follows:

Enumerator

Meaning

_LINEAR

Linear search

_BIN_ASC

Ascending binary search

_BIN_DESC

Descending binary search

For a linear search, the search is performed in order from the first element of In[].

NJ/NX-series Instructions Reference Manual (W502)

2-515

2 Instruction Descriptions

The following example is for when Size is UINT#5, Key is INT#1234 and Mode is _LINEAR.

LD

ST

abc[0] UINT#5 abc[0].m INT#1234 _LINEAR
def[0]

RecSearch

EN In Size Member Key Mode InOutPos

ENO Num

ghi jkl
def[0]

ghi:=RecSearch(abc[0], UINT#5, abc[0].m, INT#1234, _LINEAR, def[0], jkl);

Mode=_LINEAR

Key INT#1234

Member=abc[0].m

In[0]=abc[0] In[1]=abc[1] Size=UINT#5 In[2]=abc[2] In[3]=abc[3] In[4]=abc[4]

0000 3456 0000
0000 2345 0000
0000 1234 0000
0000 3456 0000
0000 1234 0000

Member m Out = ghi Num = jkl

TRUE Matches UINT# 2

InOutPos[0] = def[0] UINT#2
For an ascending binary search, the array elements in the input parameter that is passed to In[] must be in ascending order before this instruction is executed. Then a binary search is performed by executing this instruction.

2-516

NJ/NX-series Instructions Reference Manual (W502)

Stack and Table Instructions

2 Instruction Descriptions

Using the same example as before, the order of the array elements and the processing results will be as shown below for an ascending binary search.

Mode=_BIN_ASC

Key INT#1234

In[0]=abc[0] In[1]=abc[1]

0000 1234 0000
0000 1234 0000

Out = ghi

TRUE Matches

InOutPos[0] = def[0] UINT#0

Num = jkl

UINT#2

0000

Size=UINT#5 In[2]=abc[2]

2345

Member = abc[0].m

2

0000

RecSearch

In[3]=abc[3]

0000 3456 0000

Member m

In[4]=abc[4]

0000 3456 0000

For a descending binary search, the array elements in the input parameter that is passed to In[] must be in descending order before this instruction is executed. Then a binary search is performed by executing this instruction.
Using the same example as before, the order of the array elements and the processing results will be as shown below for a descending binary search.

Mode=_BIN_DESC

Key INT#1234

Member=abc[0].m

In[0]=abc[0] In[1]=abc[1] Size=UINT#5 In[2]=abc[2] In[3]=abc[3] In[4]=abc[4]

0000 3456 0000
0000 3456 0000
0000 2345 0000
0000 1234 0000
0000 1234 0000

Member m

Out = ghi

TRUE Matches

InOutPos[0] = def[0] UINT#3

Num = jkl

UINT#2

Additional Information
· In[] can be a member of a higher-level structure. Example: In[0]=str0.str1[0]
· In[] can be an array with two or more dimensions. If In[] is a two-dimensional array, the element number in the first dimension of the element that matches the search conditions is assigned to InOutPos[0] and the element number in the second dimension is assigned to InOutPos[1].

NJ/NX-series Instructions Reference Manual (W502)

2-517

2 Instruction Descriptions
· If In[] is a three-dimensional array, the element number in the first dimension of the element that matches the search conditions is assigned to InOutPos[0], the element number in the second dimension is assigned to InOutPos[1], and the element number in the third dimension is assigned to InOutPos[2].
· When you search TIME, DT, or TOD data, adjust the data so that the precision of Member and Key is the same. Use the following instructions to adjust the precision of the values: TruncTime (page 2658), TruncDt (page 2-662), and TruncTod (page 2-666).
Precautions for Correct Use
· Use an array that is the element of a structure for In[]. Otherwise, a building error will occur. · The data types of Key and Member must be the same. If they are different, a building error will occur. · When an element in the array is passed to In[], all elements below the passed element are pro-
cessed. · If Member is a real number, depending on the value of Member, the desired results may not be
achieved due to error. · If Key is a real number, do not specify nonnumeric data for Key. · If the value of Size is 0, the value of Out is FALSE and the value of Num is 0. InOutPos[] does not
change. · The correct result is not obtained if the value of Mode is _BIN_ASC or _BIN_DESC and the elements
of In[] are not in ascending or descending order. Place the elements in ascending or descending order before executing this instruction. · An error occurs in the following cases. ENO will be FALSE, and Out, InOutPos[], and Num will not change. · The value of Mode is outside of the valid range. · The value of Size exceeds the array area of In[]. · Member is not a member of In[]. · The array size of InOutPos[] is smaller than the number of dimensions of In[]. · Member is STRING data and it does not end in a NULL character.

2-518

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Stack and Table Instructions

RecRangeSearch

The RecRangeSearch instruction searches an array of structures for elements that match the search condition range with the specified method.

Instruction RecRangeSearch

Name
Range Record Search

FB/FUN FUN

Graphic expression

ST expression

(@)RecRangeSearch

Out:=RecRangeSearch(In,

EN In

ENO

Size, Member, MN, MX, Out Condition, Mode, InOutPos,

Size

Num

Num);

Member

2

MN

MX

Condition

Mode

InOutPos

RecRangeSearch

Variables

Name

Meaning

I/O

Description

Valid range

In[] (array) Size Member MN MX Condition

Array to search

Number of elements to search

Member to search

Search condition lower limit
Search condition upper limit

Input

Search condition

Mode

Search method

InOutPos[] (array)
Out

Element numbers of matching elements
Search result

In-out

Output

Num

Number of matches

Array of structures to search ---

Number of array elements to search

Member of In[] structure to search
Search condition lower limit

Depends on data type.

Search condition upper limit

Search condition
Search method Element numbers of matching elements

_EQ_BOTH, _EQ_MIN, _EQ_MAX, _NE_BOTH
_LINEAR, _BIN_ASC, _BIN_DESC
Depends on data type.

TRUE: There are elements that match conditions
FALSE: There are no elements that match conditions
Number of matches

Depends on data type.

* If you omit the input parameter, the default value is not applied. A building error will occur.

Unit
---
---
---

Default * 1
*
_EQ_ BOTH _LINEAR ---
---

NJ/NX-series Instructions Reference Manual (W502)

2-519

2 Instruction Descriptions

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

Bit strings

Integers

Times, durations, dates, and text strings

In[] (array) Size Member

MN

MX

Condition

Mode

InOutPos[] (array)

Out

OK

Num

Specify an array of structures. OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK
* Specify the same data type as the search member of In[].
Must be the same data type as Member. Must be the same data type as Member. Refer to Function for the enumerators for the enumerated type _eSEARCH_CONDITION. Refer to Function for the enumerators for the enumerated type _eSEARCH_MODE. OK
OK

* You can specify TIME, DATE, TOD, DT, and STRING data with CPU Units with unit version 1.01 or later and Sysmac Studio version 1.02 or higher.

Function

The RecRangeSearch instruction searches Size elements in the array of structures In[]. The search range is therefore from In[0] to In[Size-1]. The instruction searches member to search Member in the structures for members that match the search condition.
Condition specifies the search condition. Mode specifies the search method. Details are provided below. One of the members to search in the elements of In[] is passed as an argument to Member.
If any elements that match the search condition are found, the value of search result Out changes to TRUE. The element number of the matching element is assigned to InOutPos[0] and the number of matching elements is assigned to Num. If there is more than one matching element, the element number of the lowest matching element in In[] is assigned to InOutPos[0]. If there are no matching elements, the value of Out will be FALSE and InOutPos[0] and Num will be 0.
Always attach the element number to input parameter that is passed to In[], e.g., array[3].
The data type of search condition Condition is enumerated type _eSEARCH_CONDITION. The meanings of the enumerators are as follows:

Enumerator _EQ_BOTH _EQ_MIN _EQ_MAX _NE_BOTH

Meaning MN  Member  MX MN  Member < MX MN < Member  MX MN < Member < MX

2-520

NJ/NX-series Instructions Reference Manual (W502)

Stack and Table Instructions

2 Instruction Descriptions

The data type of search method Mode is enumerated type _eSEARCH_MODE. The meaning of the enumerators are as follows:

Enumerator

Meaning

_LINEAR

Linear search

_BIN_ASC

Ascending binary search

_BIN_DESC Descending binary search

For a linear search, the search is performed in order from the first element of In[].
The following example is for when Size is UINT#5, MN is INT#1000, MX is INT#2000, Condition is _EQ_BOTH and Mode is _LINEAR.

LD

ST

2

ghi:=RecRangeSearch(abc[0], UINT#5, abc[0].m, INT#1000, INT#2000, _EQ_BOTH, _LINEAR, def[0], jkl);

RecRangeSearch

abc[0] UINT#5 abc[0].m INT#1000 INT#2000 _EQ_BOTH _LINEAR
def[0]

RecRangeSearch

EN In Size Member MN MX Condition Mode InOutPos

ENO Num

ghi jkl
def[0]

Condition=_EQ_BOTH Mode=_LINEAR

MN INT#1000 MX INT#2000

Member = abc[0].m

In[0]=abc[0]

In[1]=abc[1]

Size=UINT#5

In[2]=abc[2]

In[3]=abc[3]

In[4]=abc[4]

0000 3456 0000
0000 2345 0000
0000 1234 0000
0000 3456 0000
0000 1234 0000

Member m

Out = ghi Num = jkl

TRUE Matches UINT#2

InOutPos[0] = def[0] UINT#2
For an ascending binary search, the array elements in the input parameter that is passed to In[] must be in ascending order before this instruction is executed. Then a binary search is performed by executing this instruction.

NJ/NX-series Instructions Reference Manual (W502)

2-521

2 Instruction Descriptions

Using the same example as before, the order of the array elements and the processing results will be as shown below for an ascending binary search.

Condition=_EQ_BOTH MN INT#1000

Mode=_BIN_ASC

MX INT#2000

In[0]=abc[0] In[1]=abc[1] In[2]=abc[2] Size=UINT#5 In[3]=abc[3] In[4]=abc[4]

0000 1234 0000
0000 1234 0000

Out = ghi

TRUE Matches

InOutPos[0] = def[0] UINT#0

Num = jkl

UINT#2

0000 2345 0000

Member = abc[0].m

0000
3456 Member m 0000

0000 3456 0000

For a descending binary search, the array elements in the input parameter that is passed to In[] must be in descending order before this instruction is executed. Then a binary search is performed by executing this instruction.
Using the same example as before, the order of the array elements and the processing results will be as shown below for a descending binary search.

Condition=_EQ_BOTH

MN INT#11000000

Mode=_LINEAR

MX INT#22000000

Member = abc[0].m

In[0]=abc[0] In[1]=abc[1] Size=UINT#5 In[2]=abc[2] In[3]=abc[3] In[4]=abc[4]

0000 3456 0000

Member m

0000 3456 0000

0000 2345 0000

0000 1234 0000

0000 1234 0000

Out = ghi

TRUE Matches

InOutPos[0] = def[0] UINT#3

Num = jkl

UINT#2

2-522

NJ/NX-series Instructions Reference Manual (W502)

Stack and Table Instructions

RecRangeSearch

2 Instruction Descriptions
Additional Information
· In[] can be a member of a higher-level structure. Example: In[0]=str0.str1[0]
· In[] can be an array with two or more dimensions. If In[] is a two-dimensional array, the element number in the first dimension of the element that matches the search conditions is assigned to InOutPos[0] and the element number in the second dimension is assigned to InOutPos[1].
· If In[] is a three-dimensional array, the element number in the first dimension of the element that matches the search conditions is assigned to InOutPos[0], the element number in the second dimension is assigned to InOutPos[1], and the element number in the third dimension is assigned to InOutPos[2].
· When you search TIME, DT, or TOD data, adjust the data so that the precision of Member, MN, and 2
MX is the same. Use the following instructions to adjust the precision of the values: TruncTime (page 2-658), TruncDt (page 2-662), and TruncTod (page 2-666).
Precautions for Correct Use
· Make the data types of Member, MN, and MX the same as the data type of the members that are searched in In[]. Otherwise, a building error will occur.
· Use an array that is the element of a structure for In[]. Otherwise, a building error will occur. · When an element in the array is passed to In[], all elements below the passed element are pro-
cessed. · If Member is a real number, depending on the value of Member, the desired results may not be
achieved due to error. · If MN or MX is a real number, do not specify nonnumeric data for MN or MX. · If the value of Size is 0, the value of Out is FALSE and the value of Num is 0. InOutPos[] does not
change. · The correct result is not obtained if the value of Mode is _BIN_ASC or _BIN_DESC and the elements
of In[] are not in ascending or descending order. Place the elements in ascending or descending order before executing this instruction. · An error occurs in the following cases. ENO will be FALSE, and Out, InOutPos[], and Num will not change. · MN is greater than MX. · The value of Condition is outside of the valid range. · The value of Mode is outside of the valid range. · The value of Size exceeds the array area of In[]. · Member is not a member of In[]. · The array size of InOutPos[] is smaller than the number of dimensions of In[].

NJ/NX-series Instructions Reference Manual (W502)

2-523

2 Instruction Descriptions

RecSort

The RecSort instruction sorts the elements of an array of structures.

Instruction RecSort

Name Record Sort

FB/FUN FB

Graphic expression
RecSort_instance RecSort
Execute Done InOut

Size Busy Member Error Order

ST expression
RecSort_instance(Execute, InOut, Size, Member, Order, Done, Busy, Error);

Variables

Name Size
Member Order

Meaning

I/O

Number of elements to sort

Member to Input sort

Sort order

InOut[] (array)

Sort array In-out

Description

Valid range

Unit

Number of array elements to sort
Depends on data type. ---
Member of In[] structure to sort

Sort order

_ASC, _DESC

Array of structures to sort ---

---

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default 1 * _ASC
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

Size
Member
Order InOut[] (array)

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK
* Specify the same data type as the sort member of InOut[] Refer to Function for the enumerators of the enumerated type _eSORT_ORDER.
Specify an array of structures.

* You can specify TIME, DATE, TOD, DT, and STRING data with CPU Units with unit version 1.01 or later and Sysmac Studio version 1.02 or higher.

2-524

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Stack and Table Instructions

Function

When the value of Execute is TRUE, Size elements of InOut[] (a structure array) is sorted. Specifically, the elements from InOut[0] to InOut[Size-1] are sorted. Specifically, the elements from InOut[0] to InOut[Size-1] are sorted. Order specifies the sort order. Details are provided below. One of the members to sort in the elements of In[] is passed as an argument to Member.
Always attach the element number to the in-out parameter that is passed to InOut[], e.g., array[3].
The data type of sort order Order is enumerated type _eSORT_ORDER. The meaning of the enumerators are as follows:

Enumerator Meaning

_ASC

Ascending

2

_DESC

Descending

RecSort

The relationship between values with data types that are not integers or real numbers are determined as given in the following table.

Data type

Relationship

TIME

The numerically larger value is considered to be larger.

DATE, TOD, or DT

Later dates or times of day are considered to be larger.

STRING

The specifications are the same as for the LTascii, LEascii, GTascii, and GEascii instructions (page 2-104). Refer to the specified page for details.

The following example is for when Size is UINT#5, Member is 3456 and Order is _Asc.

LD

ST

A
abc[0] UINT#5 abc[0].m
_ASC

RecSort_instance RecSort
Execute Done InOut
Size Busy Member Error Order

def
abc[0] ghi jkl

RecSort_instance(A, abc[0], UINT#5, abc[0].m, _ASC, def, ghi, jkl);

Order=_ASC

Member = abc[0].m

InOut[0]=abc[0] InOut[1]=abc[1] InOut[2]=abc[2] Size=UINT#5 InOut[3]=abc[3] InOut[4]=abc[4]

0000 3456 0000

Member m

0000 2345 0000

0000 1234 0000

Sorted.

0000 3456 0000

0000 1234 0000

InOut[0]=abc[0] InOut[1]=abc[1] InOut[2]=abc[2] InOut[3]=abc[3] InOut[4]=abc[4]

0000 1234 0000
0000 1234 0000
0000 2345 0000
0000 3456 0000
0000 3456 0000

NJ/NX-series Instructions Reference Manual (W502)

2-525

2 Instruction Descriptions

Additional Information
· If the power supply is interrupted during execution of this instruction, the contents of InOut may be corrupted. If you back up the contents of InOut[] each time the instruction is completed normally, you can restore the data if it is corrupted. Refer to Sample Programming.
· When you sort TIME, DT, or TOD data, adjust the data so that the precision of Member is the same. Use the following instructions to adjust the precision of the values: TruncTime (page 2-658), TruncDt (page 2-662), and TruncTod (page 2-666).

Precautions for Correct Use
· Use an array that is the element of a structure for InOut[]. Otherwise, a building error will occur. · Execution of this instruction is continued until processing is completed even if the value of Execute
changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing. · Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error. · If Member is a real number, depending on the value of Member, the desired results may not be achieved due to error. · When an element in the array is passed to InOut[], all elements below the passed element are processed. · If the value of Size is 0, the value of Done will be TRUE and InOut[] will not change. · An error occurs in the following cases. Done and Busy will be FALSE and Error will be TRUE. · The value of Order is outside of the valid range. · The value of Size exceeds the array area of InOut[]. · Member is not a member of InOut[]. · Member is STRING data and it does not end in a NULL character.

Sample Programming

In this sample, the RecSort instruction is used to sort an array Abc[] of MyStr structures in ascending order. The member to sort is Abc[].m. To prevent loosing data even if power is interrupted during processing, Abc[] is backed up in a variable named Abc_backup[] before sorting. If a power interruption occurs, the contents of Abc_backup[] is restored to Abc[] and the sort operation is redone.
Definitions of Global Variables

Data Types

Variable Data type Comment

MyStr

STRUCT Structure

I

BOOL

Member

m

INT

Member

n

REAL

Member

Global Variables

Variable

Data type

Initial value

Abc

ARRAY[0..4] OF MyStr

[5((l:=FALSE, m:=0, n:=0.0))]

Abc_backup

ARRAY[0..4] OF MyStr

[5((l:=FALSE, m:=0, n:=0.0))]

Retain

Comment

Sort array

Backup of Abc[]

2-526

NJ/NX-series Instructions Reference Manual (W502)

Stack and Table Instructions

2 Instruction Descriptions

LD

Internal Variables

Variable

Data type Initial value

Sorting

BOOL

FALSE

OperatingEnd Trigger Operating RS_instance RecSort_instance

BOOL BOOL BOOL RS RecSort

FALSE FALSE FALSE

Retain

Comment
Processing (retained) Processing completed Execution condition Processing

External Variables

Variable

Data type

Comment

2

Abc

ARRAY[0..4] OF MyStr Sort array

Abc_backup

ARRAY[0..4] OF MyStr Backup of Abc[]

RecSort

NJ/NX-series Instructions Reference Manual (W502)

2-527

2 Instruction Descriptions

Restore Abc_backup[] to Abc[] after power interruption.

P_First_RunMode

Sorting

MOVE

EN Abc_backup In

ENO Out Abc

Determine if execution of the RecSort instruction is completed.

RecSort_instance.Done

OperatingEnd

RecSort_instance.Error

Accept trigger. Trigger
OperatingEnd

RS_instance

RS

Set

Q1

Reset1

Operating

Make backup and execute RecSort instruction.

Operating

@MOVE

EN Abc In

ENO Out

Abc_backup

Abc[0] UINT#5 Abc[0].m
_ASC

RecSort_instance RecSort
Execute Done InOut

Size Member Order

Busy Error

Sorting

Processing after normal end. Operating RecSort_instance.Done

Inline ST
1 // Processing after normal end. 2 ;

Processing after error end Operating RecSort_instance.Error

Inline ST
1 // Processing after error end 2 ;

2-528

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Stack and Table Instructions

ST

Internal Variables

Variable

Data type Initial value Retain

Comment

Sorting

BOOL

FALSE

Processing (retained)

Trigger

BOOL

LastTrigger

BOOL

OperatingStart Operating RS_instance RecSort_instance

BOOL BOOL RS RecSort

FALSE FALSE FALSE FALSE

Execution condition Value of Trigger from previous task period Processing started Processing
2

RecSort

External Variables

Variable
Abc Abc_backup

Data type
ARRAY[0..4] OF MyStr ARRAY[0..4] OF MyStr

Comment
Sort array Backup of Abc[]

// Restore Abc_backup[] to Abc[] after power interruption. IF ( (P_First_RunMode = TRUE) AND (Sorting = TRUE) ) THEN
Abc:=Abc_backup; END_IF;

// Detect when Trigger changes to TRUE.

IF ( (Trigger=TRUE) AND (LastTrigger=FALSE) ) THEN

OperatingStart :=TRUE;

Operating

:=TRUE;

END_IF;

LastTrigger:=Trigger;

// Initialize RecSort instruction.

IF (OperatingStart=TRUE) THEN

Abc_backup:=Abc;

RecSort_instance(

Execute :=FALSE,

// Start condition

InOut :=Abc[0], // Sort array

Member :=Abc[0].m); // Member to sort

OperatingStart:=FALSE;

END_IF;

// Execute RecSort instruction. IF (Operating=TRUE) THEN
RecSort_instance( Execute:=TRUE, InOut :=Abc[0], Size :=UINT#5, Member :=Abc[0].m, Order :=_ASC, Busy =>Sorting);

IF (RecSort_instance.Done=TRUE) THEN // Processing after normal end. Operating:=FALSE;
END_IF;

IF (RecSort_instance.Error=TRUE) THEN // Processing after error end. Operating:=FALSE;
END_IF; END_IF;

NJ/NX-series Instructions Reference Manual (W502)

2-529

2 Instruction Descriptions

RecNum

The RecNum instruction finds the number of records in an array of structures to the end data.

Instruction RecNum

Name
Get Number of Records

FB/FUN FUN

Graphic expression

(@)RecNum

EN

ENO

In

Out

Member

EndDat

ST expression
Out:=RecNum(In, Member, EndDat);

Variables

Name In[] (array)
Member
EndDat

Meaning
Array to process
Member to process
End data

I/O Input

Description
Array of structures to process
Member of In[] structure to process
End data

Valid range
---

Unit

---
Depends on data type.

Out

Number of Output

Number of records

records

Depends on data type. ---

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default *
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In[] (array) Member
EndDat Out

Specify an array of structures. OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK
*1 Enumerations can also be specified.*2 Must be the same data type as the members to process in In[]. Must be the same data type as Member. OK

*1 You can specify TIME, DATE, TOD, and DT data with CPU Units with unit version 1.01 or later and Sysmac Studio version 1.02 or higher.
*2 A CPU Unit with unit version 1.02 or later and Sysmac Studio version 1.03 or higher are required to specify enumerations.

Function
The RecNum instruction searches from the start of an array In[] (whose elements are structures). The instruction searches for elements for which the value of member to process Member matches end data EndDat. As the result, it assigns the number of elements (records) up to the element just before the element with an EndDat match to Out. One of the members to process in the elements of In[] is passed as an argument to Member. Always attach the element number to input parameter that is passed to In[], e.g., array[3].

2-530

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Stack and Table Instructions

The following example is for when EndDat is INT#9999.

LD

ST

def:=RecNum(abc[0], abc[0].m, INT#9999);

RecNum

EN

ENO

abc[0] In

def

abc[0].m Member

INT#9999 EndDat

EndDat INT#9999

Member = abc[0].m

2

RecNum

In[0]=abc[0] In[1]=abc[1] In[2]=abc[2] In[3]=abc[3] In[4]=abc[4]

0000 3456 0000
0000 2345 0000
0000 1234 0000
0000 9999 0000
0000 1234 0000

Member m Num = def UINT#3
Matches EndDat.

Additional Information
· In[] can be a member of a higher-level structure. Example: In[0]=str0.str1[0]
· When you search TIME, DT, or TOD data, adjust the data so that the precision of Member and EndDat is the same. Use the following instructions to adjust the precision of the values: TruncTime (page 2-658), TruncDt (page 2-662), and TruncTod (page 2-666).

Precautions for Correct Use
· Use an array that is the element of a structure for In[]. Otherwise, a building error will occur. · The data types of Member and EndDat must be the same. If they are different, a building error will
occur. · If there are no members in In[] that match EndDat, the total number of elements in In[] is assigned to
Out. · If Member is a real number, depending on the value of Member, the desired results may not be
achieved due to error. · If EndDat is a real number, do not specify nonnumeric data for it. · When an element in the array is passed to In[], all elements below the passed element are pro-
cessed. · An error occurs in the following cases. ENO will be FALSE, and Out will not change.
· Member is not a member of In[]. · Member is STRING data and it does not end in a NULL character.

NJ/NX-series Instructions Reference Manual (W502)

2-531

2 Instruction Descriptions

RecMax and RecMin

RecMax: RecMin:

Searches the specified member in the structures of an array of structures for the maximum value.
Searches the specified member in the structures of an array of structures for the minimum value.

Instruction RecMax

Name
Maximum Record Search

FB/FUN FUN

Graphic expression

(@)RecMax

EN In Size Member InOutPos

ENO Out
Num

ST expression
Out:=RecMax(In, Size, Member, InOutPos, Num);

RecMin

Minimum Record Search

FUN

(@)RecMin

EN

ENO

Out:=RecMin(In, Size, Member, InOutPos, Num);

In

Out

Size

Num

Member

InOutPos

Variables

Name In[] (array) Size
Member InOutPos[] (array) Out Num

Meaning

I/O

Array to search

Number of elements to Input search

Member to search

Found element number

In-out

Search result
Number found

Output

Description

Valid range

Unit

Array of structures to search ---

Number of array elements to

search

---

Depends on data type.

Member of In[] structure to search

Found element number

Depends on data type. ---

Search result Number found

Depends on data type. ---

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default * 1 *
---
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In[] (array) Size
2-532

Specify an array of structures. OK
NJ/NX-series Instructions Reference Manual (W502)

Stack and Table Instructions
STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

2 Instruction Descriptions

Bit strings

Integers

Times, durations, dates, and text strings

Member
InOutPos[] (array) Out
Num

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK *
Specify the same data type as the search member of In[]. OK
2
OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK *
OK

* You can specify TIME, DATE, TOD, DT, and STRING data with CPU Units with unit version 1.01 or later and Sysmac Studio version 1.02 or higher.

RecMax and RecMin

Function

These instructions search Size elements in an array of structures In[]. The search range is therefore from In[0] to In[Size-1]. The instruction searches member to search Member in the structures.
One of the members to search in the elements of In[] is passed as an argument to Member. The element number of the element with the maximum or minimum value is assigned to InOutPos[0] and the number of elements that were found is assigned to Num. If more than one element was found, the element number of the lowest element with the maximum or minimum value in In[] is assigned to InOutPos[0].
Always attach the element number to input parameter that is passed to In[], e.g., array[3].
The relationship between values with data types that are not integers or real numbers are determined
as given in the following table.

Data type TIME DATE, TOD, or DT

Relationship The numerically larger value is considered to be larger. Later dates or times of day are considered to be larger.

STRING

The specifications are the same as for the LTascii, LEascii, GTascii, and GEascii instructions (page 2-104). Refer to the specified page for details.

 RecMax
The RecMax instruction searches for the maximum value. The maximum value of the member to search is assigned to search result Out.

 RecMin
The RecMin instruction searches for the minimum value. The minimum value of the member to search is assigned to search result Out. The following example shows the RecMax instruction when Size is UINT#5.

NJ/NX-series Instructions Reference Manual (W502)

2-533

2 Instruction Descriptions

LD

ST

ghi:=RecMax(abc[0], UINT#5, abc[0].m, def[0], jkl);

abc[0] UINT#5 abc[0].m
def[0]

RecMax

EN In Size Member InOutPos

ENO Num

ghi jkl
def[0]

Member=abc[0].m

In[0]=abc[0] In[1]=abc[1] Size=UINT#5 In[2]=abc[2] In[3]=abc[3] In[4]=abc[4]

0000 1234 0000
0000 2345 0000
0000 3456 0000
0000 1234 0000
0000 3456 0000

Member m

Out = ghi Num = jkl

INT#3456 UINT#2

InOutPos[0] = def[0] UINT#2

Additional Information
· In[] can be a member of a higher-level structure. Example: In[0]=str0.str1[0]
· In[] can be an array with two or more dimensions. If In[] is a two-dimensional array, the element number in the first dimension of the element that matches the search conditions is assigned to InOutPos[0] and the element number in the second dimension is assigned to InOutPos[1].
· If In[] is a three-dimensional array, the element number in the first dimension of the element that matches the search conditions is assigned to InOutPos[0], the element number in the second dimension is assigned to InOutPos[1], and the element number in the third dimension is assigned to InOutPos[2].
· When you search TIME, DT, or TOD data, adjust the data so that the precision of Member is the same. Use the following instructions to adjust the precision of the values: TruncTime (page 2-658), TruncDt (page 2-662), and TruncTod (page 2-666).

Precautions for Correct Use
· If you use a different data type for Member and Out, use only the following data types and make sure the valid range of Out includes the valid range of Member. · USINT, UINT, UDINT, ULINT, SINT, INT, DINT, LINT, REAL, and LREAL
· If Member is a real number, depending on the value of Member, the desired results may not be achieved due to error.

2-534

NJ/NX-series Instructions Reference Manual (W502)

Stack and Table Instructions

2 Instruction Descriptions
· When In is an enumeration, always use a variable for the input parameter to pass to In. A building error will occur if a constant is passed.
· If the value of Size is 0, the values of Out and Num are 0. If Member is STRING data and the value of Size is 0, Out is a text string containing only the NULL character. The values in InOutPos[] do not change.
· An error occurs in the following cases. ENO will be FALSE, and Out, InOutPos[], and Num will not change. · The value of Size exceeds the array area of In[]. · Member is not a member of In[]. · The array size of InOutPos[] is smaller than the number of dimensions of In[]. · Member is STRING data and it does not end in a NULL character.
2

RecMax and RecMin

NJ/NX-series Instructions Reference Manual (W502)

2-535

2 Instruction Descriptions

2-536

NJ/NX-series Instructions Reference Manual (W502)

FCS Instructions

2
FCS Instructions

Instruction StringSum StringLRC StringCRCCCITT StringCRC16 AryLRC_** AryCRCCCITT AryCRC16

Name Checksum Calculation Calculate Text String LRC Calculate Text String CRC-CCITT Calculate Text String CRC-16 Calculate Array LRC Group Calculate Array CRC-CCITT Calculate Array CRC-16

Page 2-538 2-540 2-542 2-544 2-546 2-548 2-550

NJ/NX-series Instructions Reference Manual (W502)

2-537

2 Instruction Descriptions

StringSum

The StringSum instruction calculates the checksum for a text string.

Instruction StringSum

Name
Checksum Calculation

FB/FUN FUN

Graphic expression

(@)StringSum

EN

ENO

In

Out

Size

ST expression Out:=StringSum(In, Size);

Variables

Name In
Size Out

Meaning Text string to process Byte size Checksum

I/O Input Output

Description Text string to process
Byte size of checksum Checksum

Valid range

Unit

Depends on data type. ---

1 or 2

Bytes

Number of bytes speci- Bytes fied by Size

Default ''
1
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

Size

OK

Out

OK

Function

The StringSum instruction calculates the checksum of text string to process In. Checksum Out will be the number of bytes specified with byte size Size. Out is given as a hexadecimal text string with a NULL character stored at the end.
The following example is for when In is `1234' and Size is USINT#2.

LD

ST

abc:=StringSum('1234', USINT#2);

StringSum

EN
`1234' In USINT#2 Size

ENO abc

In `1234'

Character codes 31 32 33 34

Total calculated.

Byte size Size = USINT#2 Out = abc `CA'

If Size was USINT#1 in the above example, Out would be `A'.

2-538

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions
Precautions for Correct Use
· If the sum of the character codes in In exceeds the number of digits of Size, the upper digits are discarded.
· An error occurs in the following cases. ENO will be FALSE, and Out will not change. · The value of Size is outside of the valid range. · The number of bytes in In is 0 (i.e., the NULL character only).
2

FCS Instructions

StringSum

NJ/NX-series Instructions Reference Manual (W502)

2-539

2 Instruction Descriptions

StringLRC

The StringLRC instruction calculates the LRC value (horizontal parity).

Instruction StringLRC

Name
Calculate Text String LRC

FB/FUN FUN

Graphic expression

(@)StringLRC

EN

ENO

In

Out

ST expression Out:=StringLRC(In);

Variables

Name In
Out

Meaning Text string to process LRC value

I/O Input
Output

Description Text string to process
LRC value

Valid range

Unit

Depends on data type. ---

3 bytes max. (two sin- --gle-byte alphanumeric characters plus the final NULL character)

Default ''
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

Out

OK

Function

The StringLRC instruction calculates the LRC value (horizontal parity) of text string to process In. The LRC value is the exclusive logical OR of the character codes for the text string in In. The LRC value (Out) is given as a hexadecimal text string with a NULL character stored at the end.
The following example is for when In is `1234'.

LD

ST

abc:=StringLRC(`1234');

StringLRC

EN `1234' In

ENO abc

In `1234'

Character codes

Exclusive logical OR

31 32 33 34

Out = abc `04'

2-540

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions
Precautions for Correct Use
An error occurs in the following cases. ENO will be FALSE, and Out will not change. · The number of bytes in In is 0 (i.e., the NULL character only).
2

FCS Instructions

StringLRC

NJ/NX-series Instructions Reference Manual (W502)

2-541

2 Instruction Descriptions

StringCRCCCITT

The StringCRCCCITT instruction calculates the CRC-CCITT value using the XMODEM method.

Instruction StringCRCCCITT

Name
Calculate Text String CRC-CCITT

FB/FUN FUN

Graphic expression

(@)StringCRCCCITT

EN In Initial OutOrder

ENO Out

ST expression
Out:=StringCRCCCITT(In, Initial, OutOrder);

Variables

Name In
Initial
OutOrder

Meaning

I/O

Text string to process

Initial value Input

Byte order

Out

CRC-

Output

CCITT

value

Description Text string to process

Valid range

Unit

Initial value of CRC-CCITT value

Depends on data type. ---

Order to process bytes in In _LOW_HIGH, _HIGH_LOW

CRC-CCITT value

5 bytes (four single-

---

byte alphanumeric

characters plus the final

NULL character)

Default ''
0
_HIGH _LOW
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In Initial OutOrder Out

OK OK
Refer to Function for the enumerators of the enumerated type _eBYTE_ORDER. OK

Function

The StringCRCCCITT instruction calculates the CRC-CCITT value of text string to process In using the XMODEM method. CRC-CCITT value Out is given as a hexadecimal text string with a NULL character stored at the end.
Set Initial to the initial value for CRC-CCITT value calculation. OutOrder specifies the byte order. The data type of OutOrder is enumerated type _eBYTE_ORDER. The meanings of the enumerators are as follows:

Enumerators _LOW_HIGH

Meaning Lower byte first, upper byte last

_HIGH_LOW

Upper byte first, lower byte last

2-542

NJ/NX-series Instructions Reference Manual (W502)

FCS Instructions

2 Instruction Descriptions

The following example is for when In is `RD', Initial is WORD#16#0000, and OutOrder is _HIGH_LOW.

LD

ST

abc:=StringCRCCCITT('RD', WORD#16#0000, _HIGH_LOW);

StringCRCCCITT

`RD' WORD#16#0000
_HIGH_LOW

EN In Initial OutOrder

ENO abc

In `RD'

2

Character codes

CRC-CCITT value

52 44

Out = abc `609D'

StringCRCCCITT

Precautions for Correct Use
An error occurs in the following cases. ENO will be FALSE, and Out will not change. · The value of OutOrder is outside of the valid range. · The number of bytes in In is 0 (i.e., the NULL character only).

NJ/NX-series Instructions Reference Manual (W502)

2-543

2 Instruction Descriptions

StringCRC16

The StringCRC16 instruction calculates the CRC-16 value using the MODBUS method.

Instruction StringCRC16

Name
Calculate Text String CRC-16

FB/FUN FUN

Graphic expression

(@)StringCRC16

EN

ENO

In

Out

Initial

OutOrder

ST expression
Out:=StringCRC16(In, Initial, OutOrder);

Variables

Name In
Initial
OutOrder

Meaning

I/O

Text string to process

Initial value Input

Byte order

Out

CRC-16 Output

value

Description Text string to process

Valid range

Unit

Depends on data type.

Initial value of CRC-16 value

---

Order to process bytes in In _LOW_HIGH, _HIGH_LOW

CRC-16 value

5 bytes (four single-

---

byte alphanumeric

characters plus the final

NULL character)

Default ''
16#FFF F _LOW _HIGH
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In Initial OutOrder Out

OK OK
Refer to Function for the enumerators of the enumerated type _eBYTE_ORDER. OK

Function

The StringCRC16 instruction calculates the CRC-16 value of text string to process In using the MODBUS method. CRC-16 value Out is given as a hexadecimal text string with a NULL character stored at the end.
Set Initial to the initial value for CRC-16 value calculation. OutOrder specifies the byte order. The data type of OutOrder is enumerated type _eBYTE_ORDER. The meanings of the enumerators are as follows:

Enumerators _LOW_HIGH

Meaning Lower byte first, upper byte last

_HIGH_LOW

Upper byte first, lower byte last

2-544

NJ/NX-series Instructions Reference Manual (W502)

FCS Instructions

2 Instruction Descriptions

The following example is for when In is `01', Initial is WORD#16#FFFF and OutOrder is _LOW_HIGH.

LD

ST

StringCRC16

EN

ENO

`01' In

abc

WORD#16#FFFF Initial

_LOW_HIGH OutOrder

abc:=StringCRC16('01', WORD#16#FFF _LOW_HIGH);

In `01'

2

Character codes 30 31

CRC-16 value

Out = abc `D464'

StringCRC16

Precautions for Correct Use
An error occurs in the following cases. ENO will be FALSE, and Out will not change. · The value of OutOrder is outside of the valid range. · The number of bytes in In is 0 (i.e., the NULL character only).

NJ/NX-series Instructions Reference Manual (W502)

2-545

2 Instruction Descriptions

AryLRC_**

The AryLRC_** instructions calculate the LRC value for an array.

Instruction AryLRC_**

Name
Calculate Array LRC Group

FB/FUN FUN

Graphic expression

(@)AryLRC_**

EN

ENO

In

Out

Size

"**" must be a bit string data type.

ST expression Out:=AryLRC_**(In, Size);
"**" must be a bit string data type.

Variables

Name

Meaning

I/O

Description

Valid range

Unit

In[] (array) Size

Array to process
Number of elements to process

Input

Array to process Number of In[] elements

Depends on data type. ---

Out

LRC value Output

LRC value

Depends on data type. ---

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default * 1
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In[] (array) Size Out

OK OK OK OK

OK Must be same data type as In[]

Function
The AryLRC_** instructions calculate the LRC value (exclusive logical OR) of Size array elements of array to process In[] starting from In[0]. The name of the instruction is determined by the data type of In[]. For example, if In[] is the WORD data type, the instruction is AryLRC_WORD. Always attach the element number to in-out parameter that is passed to In[], e.g., array[3].

2-546

NJ/NX-series Instructions Reference Manual (W502)

FCS Instructions

2 Instruction Descriptions

The following example shows the AryLRC_WORD instruction when Size is UINT#5.

LD

ST

def:=AryLRC_WORD(abc[4], UINT#5);

AryLRC_WORD

EN abc[4] In UINT#5 Size

ENO def

In[0]=abc[4] 16#1234

In[1]=abc[5] 16#2345 Exclusive logical OR

Size = UINT#5 In[2]=abc[6] 16#3456 In[3]=abc[7] 16#4567

Out = def 16#1638

2

In[4]=abc[8] 16#5678

AryLRC_**

Precautions for Correct Use
· Use the same data type for In[] and Out. · If the value of Size is 0, the value of Out is 16#00. · An error occurs in the following case. ENO will be FALSE, and Out will not change.
· The value of Size exceeds the array area of In[].

NJ/NX-series Instructions Reference Manual (W502)

2-547

2 Instruction Descriptions

AryCRCCCITT

The AryCRCCCITT instruction calculates the CRC-CCITT value using the XMODEM method.

Instruction AryCRCCCITT

Name
Calculate Array CRC-CCITT

FB/FUN FUN

Graphic expression

(@)AryCRCCCITT

EN In Size Initial OutOrder

ENO Out

ST expression
Out:=AryCRCCCITT(In, Size, Initial, OutOrder);

Variables

Name

Meaning

I/O

Description

Valid range

Unit

In[] (array) Array to process

Array to process

Size Initial

Number of elements to process
Initial value

Input

Number of In[] elements
Initial value of CRC-CCITT value

Depends on data type.
---

OutOrder Byte order

Order to process bytes in In _LOW_HIGH, _HIGH_LOW

Out

CRC-

Output

CRC-CCITT value

CCITT

value

Depends on data type. ---

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default *
1
0
_HIGH _LOW
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In[] (array) Size Initial OutOrder Out

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK
OK Refer to Function for the enumerators for the enumerated type _eBYTE_ORDER.
OK

Function
The AryCRCCCITT instruction calculates the CRC-CCITT value of Size elements of array to process In[] starting from In[0]. The XMODEM method is used. Set Initial to the initial value for CRC-CCITT value calculation. OutOrder specifies the byte order.

2-548

NJ/NX-series Instructions Reference Manual (W502)

FCS Instructions

2 Instruction Descriptions

The data type of OutOrder is enumerated type _eBYTE_ORDER. The meaning of the enumerators are as follows:

Enumerators

Meaning

_LOW_HIGH Lower byte first, upper byte last

_HIGH_LOW Upper byte first, lower byte last

Always attach the element number to in-out parameter that is passed to In[], e.g., array[3].
The following example is for when Size is UINT#2, Initial is WORD#16#0000, and OutOrder is _LOW_HIGH.

LD

ST

AryCRCCCITT

abc[4]
UINT#2 WORD#16#0000
_LOW_HIGH

EN In Size Initial OutOrder

ENO def

def:=AryCRCCCITT(abc[4], UINT#2,

2

WORD#16#0000,

_LOW_HIGH);

AryCRCCCITT

In[0]=abc[4] 16#52 Size = UINT#2 In[1]=abc[5] 16#44

CRC-CCITT value

16#5244

Out = def 16#9D60

Precautions for Correct Use
· If the value of Size is 0, the value of Out is WORD#16#00. · An error occurs in the following cases. ENO will be FALSE, and Out will not change.
· The value of OutOrder is outside of the valid range. · The value of Size exceeds the array area of In[].

NJ/NX-series Instructions Reference Manual (W502)

2-549

2 Instruction Descriptions

AryCRC16

The AryCRC16 instruction calculates the CRC-16 value using the MODBUS method.

Instruction AryCRC16

Name
Calculate Array CRC-16

FB/FUN FUN

Graphic expression

(@)AryCRC16

EN

ENO

In

Out

Size

Initial

OutOrder

ST expression
Out:=AryCRC16(In, Size, Initial, OutOrder);

Variables

Name In[] (array) Size
Initial

Meaning

I/O

Array to process

Number of elements to process
Initial value

Input

Description Array to process

Valid range

Unit

Number of In[] elements

Depends on data type.

---

Initial value of CRC-16 value

OutOrder Byte order

Order to process bytes in In _LOW_HIGH, _HIGH_LOW

Out

CRC-16 Output

CRC-16 value

value

Depends on data type. ---

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default *
1
16#FFF F _LOW _HIGH
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In[] (array) Size Initial OutOrder Out

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK
OK Refer to Function for the enumerators for the enumerated type _eBYTE_ORDER.
OK

Function
The AryCRC16 instruction calculates the CRC-16 value of Size array elements of array to process In[] starting from In[0]. The MODBUS method is used. Set Initial to the initial value for CRC-16 value calculation. OutOrder specifies the byte order.

2-550

NJ/NX-series Instructions Reference Manual (W502)

FCS Instructions

2 Instruction Descriptions

The data type of OutOrder is enumerated type _eBYTE_ORDER. The meaning of the enumerators are as follows:

Enumerator

Meaning

_LOW_HIGH Lower byte first, upper byte last

_HIGH_LOW Upper byte first, lower byte last

Always attach the element numbers to the input parameter that is passed to In[], e.g., array[3].
The following example is for when Size is UINT#2, Initial is WORD#16#FFFF and OutOrder is _LOW_HIGH.

LD

ST

AryCRC16

EN

ENO

abc[4] In

def

UINT#2 Size

WORD#16#FFFF Initial

_LOW_HIGH OutOrder

def:=AryCRC16(abc[4], UINT#2,

2

WORD#16#FFFF,

_LOW_HIGH);

AryCRC16

In[0]=abc[4] Size = UINT#2 In[1]=abc[5]

16#30 16#31

CRC-16 value

Out = def 16#D464

Precautions for Correct Use
· If the value of Size is 0, the value of Out is WORD#16#0. · An error occurs in the following cases. ENO will be FALSE, and Out will not change.
· The value of OutOrder is outside of the valid range. · The value of Size exceeds the array area of In[].

NJ/NX-series Instructions Reference Manual (W502)

2-551

2 Instruction Descriptions

2-552

NJ/NX-series Instructions Reference Manual (W502)

Text String Instructions

2
Text String Instructions

Instruction CONCAT LEFT and RIGHT MID FIND LEN REPLACE DELETE INSERT GetByteLen ClearString ToUCase and ToLCase
TrimL and TrimR AddDelimiter SubDelimiter

Name Concatenate String Get String Left/Get String Right Get String Any Find String String Length Replace String Delete String Insert String Get Byte Length Clear String Convert to Uppercase/ Convert to Lowercase Trim String Left/Trim String Right Put Text Strings with Delimiters Get Text Strings Minus Delimiters

Page 2-554 2-556 2-558 2-560 2-562 2-563 2-565 2-567 2-569 2-571 2-573
2-575 2-577 2-588

NJ/NX-series Instructions Reference Manual (W502)

2-553

2 Instruction Descriptions

CONCAT

The CONCAT instruction joins two to five text strings.

Instruction CONCAT

Name

FB/FUN

Concatenate String FUN

Graphic expression

(@)CONCAT

EN

ENO

In1

Out

:

InN

ST expression Out:=CONCAT(In1,···, InN);

Variables

Name In1 to InN

Meaning
Strings to join

I/O Input

Description

Valid range

Unit

Text strings to join, where N Depends on data type. --is 2 to 5

Default ''*

Out

Result of Output

Text string that resulted from Depends on data type. ---

---

joining

joining

* If you omit the input parameter that connects to InN, the default value is not applied, and a building error will occur. For example, if N is 3 and the input parameters that connect to In1 and In2 are omitted, the default values are applied, but if the input parameter that connects to In3 is omitted, a building error will occur.

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In1 to InN

OK

Out

OK

Function

The CONCAT instruction joins 2 to 5 text strings in strings to join In1 to InN in that order. It adds a NULL character to the end.
The following example is for when In1 is `AB', In2 is `C' and In3 is `DEF'. The value of variable abc will be `ABCDEF'.

LD

ST

CONCAT

EN `AB' In1
`C' In2 `DEF' In3

ENO abc

abc:=CONCAT('AB', `C', `DEF');

2-554

NJ/NX-series Instructions Reference Manual (W502)

Text String Instructions

2 Instruction Descriptions

In1 `AB' In2 `C' In3 `DEF'

Joined.

Out=abc `ABCDEF'

Precautions for Correct Use

An error occurs in the following cases. ENO will be FALSE, and Out will not change.

· The length of the joined character strings exceeds 1,986 bytes.

2

CONCAT

NJ/NX-series Instructions Reference Manual (W502)

2-555

2 Instruction Descriptions

LEFT and RIGHT

These instructions extract a text string with the specified number of characters. LEFT: Extracts characters from the left (beginning) of the text string. RIGHT: Extracts characters from the right (end) of the text string.

Instruction LEFT

Name Get String Left

FB/FUN FUN

RIGHT

Get String Right

FUN

Graphic expression

(@)LEFT

EN

ENO

In

Out

L

(@)RIGHT

EN

ENO

In

Out

L

ST expression Out:=LEFT(In, L);
Out:=RIGHT(In, L);

Variables

Name In
L
Out

Meaning
Source string
Number of characters
Extraction result

I/O Input Output

Description
Text string from which to extract characters
Number of characters to extract
Extracted text string

Valid range

Unit

Depends on data type.

--0 to 1985

Depends on data type. ---

Default ''
1
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

L

OK

Out

OK

Function
These instructions extract a text string with the number of characters specified by number of characters L from the source string In. A NULL character is placed at the end of extraction result Out.
 LEFT
Extracts characters from the left (beginning) of In.

2-556

NJ/NX-series Instructions Reference Manual (W502)

Text String Instructions

2 Instruction Descriptions

The following example is for when In is `ABCDEF' and L is UINT#3. The value of variable abc will be `ABC'.

LD

ST

abc:=LEFT(`ABCDEF', UINT#3);

LEFT

EN `ABCDEF' In

ENO abc

UINT#3 L

In `ABCDEF'

2

LEFT and RIGHT

Three characters extracted from the left.

Out=abc `ABC'

 RIGHT
Extracts characters from the right (end) of In. The following example is for when In is `ABCDEF' and L is UINT#3. The value of variable abc will be `DEF'.

LD

ST

abc:=RIGHT(`ABCDEF', UINT#3);

RIGHT

EN `ABCDEF' In
UINT#3 L

ENO abc

In `ABCDEF'

Three characters extracted from the right. Out=abc `DEF'

Precautions for Correct Use
· If the value of L is larger than the number of characters in In or it is within the valid range, an error does not occur and all of the characters in In are copied to Out.
· If the value of L is 0, an error does not occur and only the NULL character is assigned to Out. · Multi-byte characters are counted as one character each. · An error occurs in the following cases. ENO will be FALSE, and Out will not change.
· In results in a character code error.

NJ/NX-series Instructions Reference Manual (W502)

2-557

2 Instruction Descriptions

MID

The MID instruction extracts a text string with the specified number of characters from the specified character position.

Instruction MID

Name Get String Any

FB/FUN FUN

Graphic expression

(@)MID

EN ENO

In

Out

L

P

ST expression Out:=MID(In, L, P);

Variables

Name In L P Out

Meaning
Source string
Number of characters
First character
Extraction result

I/O Input Output

Description Text string from which to extract characters Number of characters to extract First character to extract
Extracted text string

Valid range

Unit

Depends on data type.

0 to 1985
---
1 to 1985

Depends on data type. ---

Default ''
1
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

L

OK

P

OK

Out

OK

Function
The MID instruction extracts a text string with the number of characters specified by number of characters L from the source string In. The first character to extract is specified by first character P. A NULL character is placed at the end of extraction result Out.

2-558

NJ/NX-series Instructions Reference Manual (W502)

Text String Instructions

2 Instruction Descriptions

The following example is for when In is `ABCDEF', L is UINT#3, and P is UINT#2. The value of variable abc will be `BCD'.

LD

ST

abc:=MID(`ABCDEF', UINT#3, UINT#2);

MID

EN ENO

`ABCDEF' In

abc

UINT#3 L

UINT#2 P

2
In `ABCDEF'

MID

Three characters are extracted starting from second character. Out=abc `BCD'

Precautions for Correct Use
· If the value of L is 0, an error does not occur and only the NULL character is assigned to Out. · Multi-byte characters are counted as one character each. · An error occurs in the following cases. ENO will be FALSE, and Out will not change.
· In results in a character code error. · In does not have enough characters for the number of characters specified by L from the position
specified by P. · The value of P is 0.

NJ/NX-series Instructions Reference Manual (W502)

2-559

2 Instruction Descriptions

FIND

The FIND instruction searches a specified text string for the position of a specified text string.

Instruction FIND

Name Find String

FB/FUN FUN

Graphic expression

(@)FIND

EN ENO

In1

Ou

In2

ST expression Out:=FIND(In1, In2);

Variables

Name In1
In2 Out

Meaning

I/O

String to search

Input

Search key

Search result

Output

Description Text string to search
Text string to search for Search result

Valid range

Unit

Depends on data type. ---

0 to 1985

---

Default '' ---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In1

OK

In2

OK

Out

OK

Function

The FIND instruction searches for search key In2 in string to search In1. The position of In2 from the start of In1 is assigned to search result Out. If In2 is not found in In1, Out is 0.
The following example is for when In1 is `ABCDEF' and In2 is `CD'. The value of variable abc will be UINT#3.

LD

ST

FIND

EN ENO

`ABCDEF' In1

abc

`CD' In2

abc:=FIND(`ABCDEF', `CD');

In1 `ABCDEF' Searches for position of In2 in In1. Out=abc

In2

`CD'

UINT#3

2-560

NJ/NX-series Instructions Reference Manual (W502)

Text String Instructions

2 Instruction Descriptions
Precautions for Correct Use
· Make sure the number of characters in In2 is less than the number of characters in In1. Otherwise, the value of Out will be 0.
· If In2 exists more than once in In1, the position of the first In2 from the beginning of In1 is assigned to Out.
· If the value of In1 and In2 is only the NULL character, the value of Out is 1. · Multi-byte characters are counted as one character each. · An error occurs in the following cases. ENO will be FALSE, and Out will not change.
· In1 or In2 results in a character code error.
2

FIND

NJ/NX-series Instructions Reference Manual (W502)

2-561

2 Instruction Descriptions

LEN

The LEN instruction finds the number of characters in a text string.

Instruction LEN

Name String Length

FB/FUN FUN

Graphic expression

(@)LEN

EN ENO

In

Out

ST expression Out:=LEN(In);

Variables

Name In
Out

Meaning Length string Find result

I/O Input
Output

Description Text string to find length
Length detection result

Valid range

Unit

Depends on data type. ---

0 to 1985

---

Default ''
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

Out

OK

Function

The LEN instruction finds the number of characters in length string In. A NULL character at the end of In is not counted.
The following example is for when In is `ABCDEF'. The value of variable abc will be UINT#6.

LD

ST

LEN

EN ENO

`ABCDEF' In

abc

abc:=LEN(`ABCDEF');

Number of characters

In `ABCDEF'

Out=abc UINT#6

Precautions for Correct Use
· Multi-byte characters are counted as one character each. · An error occurs in the following cases. ENO will be FALSE, and Out will not change.
· In results in a character code error.

2-562

NJ/NX-series Instructions Reference Manual (W502)

Text String Instructions

2 Instruction Descriptions

REPLACE

The REPLACE instruction replaces part of a text string with another text string.

Instruction REPLACE

Name Replace String

FB/FUN FUN

Graphic expression

ST expression

(@)REPLACE

EN

ENO

Out:=REPLACE(In1, In2, L, P);

In1

Ou

In2

L

P

2

REPLACE

Variables

Name In1
In2 L P
Out

Meaning

I/O

String for replaceme nt

Insert string
Number of characters

Input

Replaceme nt start position

Replaceme Output nt result

Description

Valid range

Unit

Text string for replacement

Text string to insert
Number of characters to delete Replacement start position

Depends on data type.
---
0 to 1985 1 to 1985

Text string after replacement Depends on data type. ---

Default ''
1
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In1

OK

In2

OK

L

OK

P

OK

Out

OK

Function
The REPLACE instruction replaces part of string for replacement In1 with string to insert In2. First the number of characters specified by L from the position specified by P are deleted from In1. In2 is then inserted for the deleted characters. A NULL character is placed at the end of replacement result Out.

NJ/NX-series Instructions Reference Manual (W502)

2-563

2 Instruction Descriptions

The following example is for when In1 is `ABCDEF', In2 is `GHI', P is UINT#2, and L is UINT#4. The value of variable abc will be `AGHIF'.

LD

ST

abc:=REPLACE(`ABCDEF', `GHI', UINT#4, UINT#2);

REPLACE

EN `ABCDEF' In1

ENO abc

`GHI' In2

UINT#4 L

UINT#2 P

Deleted
In `ABCDEF' Insert
Repl `GHI'

Out=abc `AGHIF'

Precautions for Correct Use
· If L is 0, an error will not occur and all of the characters in In1 are inserted to Out. · If the value of In2 is 0, L characters are deleted from P in In1. · Multi-byte characters are counted as one character each. · An error occurs in the following cases. ENO will be FALSE, and Out will not change.
· In1 results in a character code error. · In1 does not have enough characters for the number of characters specified by L from the position
specified by P. · The value of P is 0. · The length of the character string after the replacement exceeds 1,986 bytes.

2-564

NJ/NX-series Instructions Reference Manual (W502)

Text String Instructions

2 Instruction Descriptions

DELETE

The DELETE instruction deletes all or part of a text string.

Instruction DELETE

Name Delete String

FB/FUN FUN

Graphic expression

ST expression

(@)DELETE

Out:=DELETE(In, L, P);

EN

ENO

In

Out

L

P

2

Variables

DELETE

Name In L P Out

Meaning
String for deletion
Number of characters
Deletion start position
Deletion result

I/O Input Output

Description

Valid range

Unit

Text string for deletion Depends on data type.

Number of characters to 0 to 1985

delete

---

Deletion start position

1 to 1985

Text string after deletion Depends on data type. ---

Default ''
1
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

L

OK

P

OK

Out

OK

Function
The DELETE string deletes the number of characters specified by L from the position specified by P from In. A NULL character is placed at the end of deletion result Out.

NJ/NX-series Instructions Reference Manual (W502)

2-565

2 Instruction Descriptions

The following example is for when In is 'ABCDEF', L is UINT#4, and P is UINT#2. The value of variable abc will be 'AF'.

LD

ST

abc:=DELETE(`ABCDEF', UINT#4, UINT#2);

DELETE

EN `ABCDEF' In

ENO abc

UINT#4 L

UINT#2 P

Deleted In `ABCDEF'

Out=abc `AF'

Precautions for Correct Use
· If L is 0, an error will not occur and all of the characters in In are inserted to Out. · Multi-byte characters are counted as one character each. · An error occurs in the following cases. ENO will be FALSE, and Out will not change.
· In results in a character code error. · In does not have enough characters for the number of characters specified by L from the position
specified by P. · The value of P is 0.

2-566

NJ/NX-series Instructions Reference Manual (W502)

Text String Instructions

2 Instruction Descriptions

INSERT

The INSERT instruction inserts a text string into another text string.

Instruction INSERT

Name Insert String

FB/FUN FUN

Graphic expression

ST expression

(@)INSERT

Out:=INSERT(In1, In2, P);

EN

ENO

In1

Ou

In2

P

2

Variables

INSERT

Name In1 In2 P
Out

Meaning
Original string
Insert string
Insertion start position
Insertion result

I/O Input Output

Description Text string into which to insert string Text string to insert
Insertion start position

Valid range

Unit

Depends on data type.
---
0 to 1985

Text string after insertion Depends on data type. ---

Default ''
0
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In1

OK

In2

OK

P

OK

Out

OK

Function
The INSERT instruction inserts insertion string In2 into original string In1 at insertion start position P. A NULL character is placed at the end of insertion result Out.

NJ/NX-series Instructions Reference Manual (W502)

2-567

2 Instruction Descriptions

The following example is for when In1 is 'ABCD', In2 is 'GHI', and P is UINT#2. The value of variable abc will be 'ABGHICD'.

LD

ST

abc:=INSERT(`ABCD', `GHI', UINT#2);

INSERT

EN `ABCD' In1

ENO abc

`GHI' In2

UINT#2 P

In1 `ABCD' Insert
In2 `GHI'

Out=abc `ABGHICD'

Additional Information
If P is 0, In1 is inserted at the end of In2.
Precautions for Correct Use
· Multi-byte characters are counted as one character each. · An error occurs in the following cases. ENO will be FALSE, and Out will not change.
· In1 results in a character code error. · The value of P is greater than the number of characters in In1. · The length of the character string after the insertion exceeds 1,986 bytes.

2-568

NJ/NX-series Instructions Reference Manual (W502)

Text String Instructions

2 Instruction Descriptions

GetByteLen

The GetByteLen instruction counts the number of bytes in a text string.

Instruction GetByteLen

Name Get Byte Length

FB/FUN FUN

Graphic expression

(@)GetByteLen

EN

ENO

In

Out

ST expression Out:=GetByteLen(In);

2 Variables

GetByteLen

Name In
Out

Meaning
Count string
Number of bytes

I/O Input
Output

Description Text string to count number of bytes Number of bytes

Valid range Depends on data type.
0 to 1985

Unit
---
Bytes

Default ''
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

Out

OK

Function

The GetByteLen instruction counts the number of bytes in count string In. A NULL character at the end of the text string is not counted.
The following example is for when In is `ABCDEF'. The value of variable abc will be 6.

LD

ST

abc:=GetByteLen(`ABCDEF');

GetByteLen

EN `ABCDEF' In

ENO abc

Number of bytes

In `ABCDEF'

Out=abc

6

NJ/NX-series Instructions Reference Manual (W502)

2-569

2 Instruction Descriptions
Additional Information
If In contains only ASCII characters, the result will be the same as the result of the LEN instruction.

2-570

NJ/NX-series Instructions Reference Manual (W502)

Text String Instructions

2 Instruction Descriptions

ClearString

The ClearString instruction clears a text string.

Instruction

Name

FB/FUN

ClearString

Clear String

FUN

Graphic expression

(@)ClearString

EN InOut

ENO

ST expression ClearString(InOut);

Out
2

Variables

ClearString

Name InOut Out

Meaning

I/O

Clear string In-out

Return value

Output

Description Text string to clear Always TRUE

Valid range

Unit

Depends on data type. ---

TRUE only

---

Default
-----

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

InOut

OK

Out

OK

Function

The ClearString instruction clears clear string InOut. NULL characters are stored in the entire range of InOut.
The following figure shows a programming example. The content of STRING variable will be all NULL characters.

LD

ST

ClearString(abc);

ClearString

EN

ENO

InOut

abc

abc

The ClearString instruction stores NULL characters in the entire range of InOut.
The following example is for when abc is a 5-character STRING variable. InOut=abc NULL NULL NULL NULL NULL

NJ/NX-series Instructions Reference Manual (W502)

2-571

2 Instruction Descriptions
Precautions for Correct Use
Return value Out is not used when the instruction is used in ST.

2-572

NJ/NX-series Instructions Reference Manual (W502)

Text String Instructions

2 Instruction Descriptions

ToUCase and ToLCase

ToUCase: Converts all single-byte letters in a text string to uppercase. ToLCase: Converts all single-byte letters in a text string to lowercase.

Instruction

Name

FB/FUN

Graphic expression

ST expression

ToUCase ToLCase

Convert to Uppercase
Convert to Lowercase

FUN FUN

(@)ToUCase

Out:=ToUCase(In);

EN

ENO

In

Out

2

(@)ToLCase

Out:=ToLCase(In);

EN

ENO

In

Out

ToUCase and ToLCase

Variables

Name In
Out

Meaning

I/O

Data to convert

Input

Conversion Output result

Description Text string to convert
Converted text string

Valid range

Unit

Depends on data type. ---

Depends on data type. ---

Default ''
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

Out

OK

Function

 ToUCase
The ToUCase instruction converts all single-byte letters in data to convert In to uppercase.
 ToLCase
The ToLCase instruction converts all single-byte letters in data to convert In to lowercase. Both instructions output a NULL character at the end of the text string. Only single-byte characters are changed.

NJ/NX-series Instructions Reference Manual (W502)

2-573

2 Instruction Descriptions

The following example for the ToUCase instruction is for when In is `xyz'. The value of variable abc will be `XYZ'.

LD

ST

abc:=ToUCase(`xyz');

ToUCase

EN `xyz' In

ENO abc

The ToUCase instruction converts all single-byte letters in In to uppercase.

Converted to uppercase. In 'xyz'

Out=abc 'XYZ'

Precautions for Correct Use
· Two-byte letters are not converted. · An error occurs in the following cases. ENO will be FALSE, and Out will not change.
· In results in a character code error.

2-574

NJ/NX-series Instructions Reference Manual (W502)

Text String Instructions

2 Instruction Descriptions

TrimL and TrimR

TrimL: Removes blank space from the beginning of a text string. TrimR: Removes blank space from the end of a text string.

Instruction

Name

FB/FUN

Graphic expression

ST expression

TrimL TrimR

Trim String Left

FUN

Trim String Right FUN

(@)TrimL

Out:=TrimL(In);

EN ENO

In

Out

2

(@)TrimR

Out:=TrimR(In);

EN ENO

In

Out

TrimL and TrimR

Variables

Name In
Out

Meaning
String to trim
Trimming result

I/O Input
Output

Description Text string to trim
Text string after trimming

Valid range

Unit

Depends on data type. ---

Depends on data type. ---

Default ''
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

Out

OK

Function

 TrimL
The TrimL instruction deletes blank characters from the beginning of string to trim In. If there are no blank characters at the beginning of the text string, nothing is done.
 TrimR
The TrimR instruction deletes blank characters from the end of string to trim In. If there are no blank characters at the end of the text string, nothing is done. Both instructions output a NULL character at the end of the text string. Both ASCII spaces (16#20) and two-byte Japanese spaces (16#E38080) are treated as blank characters.

NJ/NX-series Instructions Reference Manual (W502)

2-575

2 Instruction Descriptions

The following example for the TrimL instruction is for when In is ` be ` AB C'.

LD

ST

AB C'. The value of variable abc will

abc:=TrimL(` AB C');

TrimL

EN ` AB C' In

ENO abc

The TrimL instruction deletes blank characters from the beginning of In.

The blank characters from

the beginning of In are deleted.

In ' AB C'

Out=abc 'AB C'

Precautions for Correct Use
An error occurs in the following cases. ENO will be FALSE, and Out will not change. · In results in a character code error.

2-576

NJ/NX-series Instructions Reference Manual (W502)

Text String Instructions

2 Instruction Descriptions

AddDelimiter

The AddDelimiter instruction converts the values in a structure to text strings and adds delimiters.

Instruction AddDelimiter

Name
Put Text Strings with Delimiters

FB/FUN FUN

Graphic expression

AddDelimiter

EN

ENO

In

Out

Delimiter

ST expression
Out:=AddDelimiter(In,Delimiter);

2

Variables

AddDelimiter

Name

Meaning

I/O

Description

Valid range

Unit

In Delimiter
Out

Input structure Delimiter
Return value

Input Output

Structure to convert to text Depends on data type of mem- ---

strings

bers.

Delimiter

_COMMA

---

_TAB

_SEMICOLON

_SPACE

Text strings with delimiters 1,986 bytes max. (1,985 single- --byte alphanumeric characters plus the final NULL character)

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default * _COMMA
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In Delimiter Out

Structure Refer to Function for the enumerators for the enumerated data type _eDELIMITER.
OK

Function

The AddDelimiter instruction starts from the beginning of input structure In and converts the values of the members to text strings, which it separates with delimiter Delimiter and then concatenates. The concatenated text string is output to return value Out. A NULL character is placed at the end of Out.
The data type of Delimiter is enumerated type _eDELIMITER. The meanings of the enumerators are as follows:

Enumerator _COMMA _TAB _SEMICOLON _SPACE

Meaning `,' (comma) `$T' (tab) `;'(semicolon) ` ` (blank character)

The values of the members of In are converted according to their data type, as described next.

NJ/NX-series Instructions Reference Manual (W502)

2-577

2 Instruction Descriptions

 Boolean Data
FALSE is converted to `0' and TRUE is converted to `1'.

 Bit String Data
Bits strings are treated as hexadecimal numbers and converted to text strings that express them as alphanumeric characters. The 16# prefix of the hexadecimal number is not output to the text string.
If the value of the member requires fewer digits than are provided by the data type of the member, the upper digits will contain `0'. In other words, the unused digits are padded with zeros.
The number of characters in the text string depends on the data type as shown in the following table.

Data type of member BYTE WORD DWORD LWORD

Number of characters 2 single-byte alphanumeric characters 4 single-byte alphanumeric characters 8 single-byte alphanumeric characters 16 single-byte alphanumeric characters

Examples are given below.

Value of member BYTE#16#AB LWORD#16#0123

Converted text string 'AB' '0000000000000123'

 Integer Data
The value of the integer is converted to a text string. Upper digits that are 0 are not output to the text string. If the value of the member is negative, a minus sign (-) is added to the front of the text string. Examples are given below.

Value of member UINT#0012 LINT#-12

Converted text string '12' '-12'

 Real Number Data
The structure of the text string to which the value of the member is converted is shown below.

- i . f f f f f f e+n n

Sign column

Fractional Exponent part Decimal point

Integer part

Item Sign column
Integer part Decimal point Fractional part
Exponent

Description If the value of the member is negative, a minus sign (-) is added. If the value of the member is positive, a plus sign (+) is not added. The integer part is always only one digit. The decimal point is always given even if the value of the member is not a decimal number. If the member is REAL data, 6 digits are given. If the member is LREAL data, 14 digits are given. The exponent is always given. `e' indicates the exponent e.
"nn" is 2 or 3 digits.
The sign of "nn" is positive (+) if the absolute value of the member is 1.0 or higher and negative (-) if it is less than 1.0. If the value of the member is 0, this portion is `+'(positive).

2-578

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Text String Instructions

If the value of the member is infinity, or nonnumeric data, the text string will be as shown below.

Value of member + - Nonnumeric data

Text string 'inf' '-inf' `nan' or `-nan'

Examples are given below.

Value of member

Converted text string

REAL#3.14e1

'3.140000e+01'

REAL#-123.4567

'-1.234567e+02'

REAL#0

'0.000000e+00'

2

LREAL#0.00123456789

'1.23456789000000e-03'

LREAL#1.0e308

'1.00000000000000e+308'

AddDelimiter

 Duration Data
The structure of the text string to which the value of the member is converted is shown below.

- A A d B B h C C m DD . EE s

Sign column Days 'd' Hours 'h' Minutes'm' Seconds Decimal 's' point

Item Sign column
Days
Hours Minutes Seconds
`d', `h', `m', `s', and the decimal point

Description If the value of the member is negative, a minus sign (-) is added.
If the value of the member is positive, a plus sign (+) is not added. The number of days is always given. The range of the value is 0 to 106751. Upper digits are not padded with 0. The number of hours is always given in two digits. The range of the value is 00 to 23. The number of minutes is always given in two digits. The range of the value is 00 to 59. The number of seconds is always given. The value of DD is always given in two digits between 00 and 59. The value of EE is always given in two digits between 000000000 and 999999999 These are always given.

Examples are given below.
Value of member T#-180122000ms T#100d2h3m5.678s T#2h3m5.678s

Converted text string '-2d02h02m02.000000000s' '100d02h03m05.678000000s' '0d02h03m05.678000000s'

 Date Data
The structure of the text string to which the value of the member is converted is shown below.

YYYY - MM - DD

Year Hyphen Month Hyphen Day
The month and day are converted to two digits each and output to the text string.

An example is shown below.

Value of member D#2010-1-2

Converted text string '2010-01-02'

NJ/NX-series Instructions Reference Manual (W502)

2-579

2 Instruction Descriptions

 Date and Time Data
The structure of the text string to which the value of the member is converted is shown below.

YYYY - MM - DD - hh : mm : ss . SS

Year

Hyphen Month

Colon Hyphen Day Hyphen Hour Colon Minutes

Decimal point

Decimal part of seconds

Integer part of seconds

The month (MM), day (DD), hour (hh), minutes (mm), and integer part of the seconds (ss) are

converted to two digits each and output to the text string. The fractional part of the seconds (ss) is

converted to nine digits and output to the text string.

An example is shown below.

Value of member DT#2004-09-23-12:16:8.12

Converted text string '2004-09-23-12:16:08.120000000'

 Time of Day Data
The structure of the text string to which the value of the member is converted is shown below.

hh : mm : ss . SS

Colon Colon Hour Minutes

Decimal point

Integer part

of seconds

Decimal part of seconds

The hour (hh), minutes (mm), and integer part of the seconds (ss) are converted to two digits each

and output to the text string. The fractional part of the seconds (ss) is converted to nine digits and

output to the text string.

An example is shown below.

Value of member TOD#2:16:28.12

Converted text string '02:16:28.120000000'

 Text String Data
The text string is output without any changes. The NULL character at the end of the text string is not included. For example, if the value of the member is `ABC' and includes a NULL character at the end, `ABC' without the NULL character is output to the text string.

 Structure Data
The values of the members are converted in order from the start of the structure down to the nesting levels that are not structures. The values of the members are converted to text strings according to the rules for their data types. For example, if a member of structure A has a data type of Structure_B, the conversion works as shown below. Commas are used as delimiters in this example.

Structure A

Member memberA memberB memberC

Data type STRING Structure_B STRING

Value 'ABC'
---
'XYZ'

Structure B

Member Data type Value member1 INT INT#12 member2 INT INT#34 member3 INT INT#56

Structure A is converted to a text string. 'ABC,12,34,56,XYZ'

 Enumeration Data
The value of the enumeration is treated as DINT data and converted accordingly.
For example, assume that an enumeration Color has three enumerators: red, yellow, and green. The numbers associated with these enumerators are as follows: red = 1, yellow = 2, green = 3. If the value of a member of enumeration Color is yellow, the text string will be `2'.

2-580

NJ/NX-series Instructions Reference Manual (W502)

Text String Instructions

2 Instruction Descriptions

 Array Data
The text strings for the elements of the array are separated with the delimiter. The value of each element is converted according to the conversion rules for the data type of the array. Only one-dimensional arrays are converted.
For example, take the INT array myArray[0..2]. If the value of myArray[0] is INT#225, the value of myArray[1] is INT#-128, the value of myArray[2] is INT#0, and the delimiter is a comma, the text string would be as follows: `225,-128,0'.

Notation Example

The following notation is used to convert the myStruct structure to the myString text string. The `,' (comma) is the delimiter.

2

LD

ST

AddDelimiter

myStruct _COMMA

AddDelimiter

EN In Delimiter

ENO

myString:=AddDelimiter(myStruct,_COMMA); myString

Structure myStruct

Member member1 member2 member3 member4

Data type STRING INT WORD REAL

Value 'XYZ' INT#12 WORD#16#00AB REAL#3.14e0

Converted to a text string. Out = myString 'XYZ,12,00AB,3.140000e+00'

Additional Information
· You can combine this instruction with the FilePuts instruction (page 2-1419) to easily write values to specified CSV files in an SD Memory Card. Refer to Sample Programming for an application example.
· You can use the SubDelimiter instruction (page 2-588) to read text strings that were converted with the AddDelimiter instruction and output them as the values of the members of a structure.

Precautions for Correct Use
· Do not use the delimiter in the values of the members of In. If the delimiter is used in the values of the members of In, the SubDelimiter instruction will not correctly convert the text strings to the values of the members of a structure.
· An error occurs in the following cases. ENO will be FALSE, and Out will not change. · The text string that resulted from conversion exceeds 1,986 bytes, including the final NULL character. · A member of In is an array with more than one dimension. · A member of In is a union.
Version Information
A CPU Unit with unit version 1.02 or later and Sysmac Studio version 1.03 or higher are required to use this instruction.

NJ/NX-series Instructions Reference Manual (W502)

2-581

2 Instruction Descriptions

Sample Programming
The myStruct structure has ten members that are SINT variables. Here, the contents of myArray[0..99], which is an array of structure type myStruct, are stored in 100 lines of a file named `ABC.csv' in CSV file format in the SD Memory Card. Each line contains the values of the members of an array element converted to 10 text strings. Commas are inserted between them. A CR+LF code is added to the end of each line. The processing procedure is as follows:
1 The FileOpen instruction is used to open the file `ABC.csv.'
2 The AddDelimiter instruction is used to convert an element of myArray[] for one line and output
the results to the Temp STRING variable.
3 The CONCAT instruction is used to concatenate Temp and CR+LF and then store the results in
the StrDat STRING variable.
4 StrDat is written to the file.

5 Steps 2 to 4 are repeated for 100 lines.

6 The FileClose instruction is used to close the file.

Structure myStruct

Member member0 member1

Data type SINT SINT

    

member9

SINT

Array myArray[0..99] of structure type myStruct

myArray[0]
myArray[1] . . .

member0 member1

member9

SINT#1234 SINT#5678      SINT#9012

SINT#8487 SINT#9256      SINT#1211

.

.

.

myArray[99] SINT#0596 SINT#6511      SINT#2212

STRING variable Temp 1234,5678,

Converted to STRING data one line at a time.
     ,9012

STRING variable StrDat 1234,5678,

CR+LF added to the end.
     ,9012 CR+LF

Results written to the file.

100 lines

`ABC.csv' file

1234,5678,. . . . . 9012

. . . . . . . . . .

.

. . . . . . . . . .

.

. . . . . . . . . .

.

. . . . . . . . . .

.

2-582

NJ/NX-series Instructions Reference Manual (W502)

Text String Instructions

2 Instruction Descriptions

 Data Type Definition

Name

Data type

Comment

myStruct

STRUCT

Structure

member0

SINT

Member

member1

SINT

Member

member2

SINT

Member

member3

SINT

Member

member4

SINT

Member

member5

SINT

Member

member6

SINT

Member

member7

SINT

Member

member8

SINT

Member

2

member9

SINT

Member

AddDelimiter

LD
Internal Variables

Variable

OperatingEnd

Trigger
Operating Index Fid
StrDat

myArray

Temp
RS_instance FileOpen_instance FilePuts_instance FileClose_instance

Data type
BOOL
BOOL BOOL INT DWORD STRING[256]
ARRAY[0..99] OF myStruct
STRING[256] RS FileOpen FilePuts FileClose

Initial value

Comment

False
False
False 0 16#0
''
[100((member0:=0,member1:=0,member2:=0,member3:=0,member4:=0,member5:=0,member6:=0,me mber7:=0,member8:=0,member9:=0))]
''

Processing completed Execution condition Processing Index File ID Text string data
Numeric data
Temporary data

External Variables

Variable _Card1Ready

BOOL

Data type

Comment SD Memory Card Ready Flag

NJ/NX-series Instructions Reference Manual (W502)

2-583

2 Instruction Descriptions

Determine if SD Memory Card instruction execution is completed.

FileClose_instance.Done

OperatingEnd

FileOpen_instance.Error

FilePuts_instance.Error

FileClose_instance.Error

Accept trigger. Trigger _Card1Ready
OperatingEnd

RS_instance

RS

Set

Q1

Reset1

Operating

Initialize row index.

Operating

Inline ST 1 Index:=INT#0;

Execute FileOpen instruction. Operating

FileOpen_instance FileOpen

Execute Done

`ABC.csv' FileName Busy

_RDWR_CREATE Mode

Error

ErrorID FileID Fid

FileOpen_instance.Error

Inline ST
1 // Processing after error end 2 ;

2-584

NJ/NX-series Instructions Reference Manual (W502)

Text String Instructions

2 Instruction Descriptions

Create a text string for one line. Operating FileOpen_instance.Done FilePuts_instance.Busy FileClose_instance.Busy
myArray[Index] _COMMA

AddDelimiter

EN In Delimiter

ENO

Temp

Temp '$r$l'

CONCAT

EN

ENO

In1

In2

StrDat

AddDelimiter

Write a text string for one line to the file.

2
FilePuts_instance

Operating FileOpen_instance.Done FilePuts_instance.Busy FileClose_instance.Busy

FilePuts

Fid StrDat

Execute FileID In

Done Busy Error ErrorID

Increment the line index. Operating FilePuts_instance.Done
Index

Inc
EN ENO InOut

FilePuts_instance.Error Inline ST 1 // Processing after error end 2 ;

Execute the FileClose instruction after 100 lines are written.

Operating

>

EN

Index In1

Fid

INT#99 In2

FileClose_instance

FileClose

Execute FileID

Done Busy Error ErrorID

FileClose_instance.Error

Inline ST
1 // Processing after error end 2 ;

Operating FileClose_instance.Done

Inline ST
1 // Processing after normal end 2 ;

NJ/NX-series Instructions Reference Manual (W502)

2-585

2 Instruction Descriptions

ST
Internal Variables

Variable

Trigger

LastTrigger

OperatingStart
Operating Stage Index Fid StrDat

myArray

Temp FileOpen_instance FilePuts_instance FileClose_instance

Data type
BOOL
BOOL
BOOL BOOL INT INT DWORD STRING[256]
ARRAY[0..99] OF myStruct
STRING[256] FileOpen FilePuts FileClose

False

Initial value

False

False
False 0 0 16#0 '' [100((member0:=0,member1:=0,member2:=0,member3:=0,member4:=0,member5:=0, member6:=0,member7:=0,member8:=0,member9:=0))] ''

Comment
Execution condition Value of Trigger from previous task period Processing started Processing Stage change Index File ID Text string data
Numeric data
Temporary data

External Variables

Variable _Card1Ready

BOOL

Data type

Comment SD Memory Card Ready Flag

// Start sequence when Trigger changes to TRUE.

IF ( (Trigger=TRUE) AND (LastTrigger=FALSE) AND (_Card1Ready=TRUE) ) THEN

OperatingStart:=TRUE;

Operating

:=TRUE;

END_IF;

LastTrigger:=Trigger;

// Initialize instance.

IF (OperatingStart=TRUE) THEN

FileOpen_instance(Execute:=FALSE);

FilePuts_instance(Execute:=FALSE);

FileClose_instance(Execute:=FALSE);

Stage

:=INT#1;

Index

:=INT#0;

// Initialize row index.

OperatingStart:=FALSE;

END_IF;

// Execute instruction.

IF (Operating=TRUE) THEN

CASE Stage OF

1 :

// Open file.

FileOpen_instance(

Execute :=TRUE,

FileName:='ABC.csv',

// File name

Mode :=_RDWR_CREATE, // Read file

FileID =>Fid);

// File ID

IF (FileOpen_instance.Done=TRUE) THEN

2-586

NJ/NX-series Instructions Reference Manual (W502)

Text String Instructions

2 Instruction Descriptions

Stage:=INT#2; END_IF;

// Normal end

IF (FileOpen_instance.Error=TRUE) THEN

Stage:=INT#99;

// Error end

END_IF;

2 : StrDat:='';

// Create a text string for one line.

Temp :=AddDelimiter(myArray[Index],_COMMA); StrDat:=CONCAT(In1:=Temp, In2:='$r$l');

Stage:=INT#3;

2

AddDelimiter

3 :

// Write text string.

FilePuts_instance(

Execute:=TRUE,

FileID :=Fid,

In

:=StrDat);

IF (FilePuts_instance.Done=TRUE) THEN Index:=Index+INT#1;

IF (Index>INT#99) THEN // If 100 lines were written... Stage:=INT#4;
ELSE FilePuts_instance(Execute:=FALSE); Stage:=INT#2;
END_IF; END_IF;

IF (FilePuts_instance.Error=TRUE) THEN

Stage:=INT#99;

// Error end

END_IF;

4 :

// Close file.

FileClose_instance(

Execute:=TRUE,

FileID :=Fid);

// File ID

IF (FileClose_instance.Done=TRUE) THEN Operating:=FALSE; // Normal end
END_IF;

IF (FileClose_instance.Error=TRUE) THEN

Stage:=INT#99;

// Error end

END_IF;

99 :

// Processing after error end

Operating:=FALSE;

END_CASE;

END_IF;

NJ/NX-series Instructions Reference Manual (W502)

2-587

2 Instruction Descriptions

SubDelimiter

The SubDelimiter instruction reads delimited data from a text string and stores the results as the values of the members of a structure.

Instruction SubDelimiter

Name
Get Text Strings Minus Delimiters

FB/FUN FUN

Graphic expression

SubDelimiter

EN

ENO

In

Out

OutStruct

ST expression Out:=SubDelimiter(In, OutStruct, Delimiter);

Delimiter

Variables

Name In
Delimiter OutStruct Out

Meaning
Input text string

I/O Input

Delimiter

Storage structure
Return value

In-out Output

Description Delimited text string to convert to the values of the members of a structure Delimiter
Structure to store results of data conversion Always TRUE

Valid range 1,986 bytes max. (1,985 single-byte alphanumeric characters plus the final NULL character) _COMMA, _TAB, _SEMICOLON, _SPACE 8,192 bytes max.
TRUE only

Unit ---
-------

Default ''
_COMMA -----

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

Delimiter

Refer to Function for the enumerators for the enumerated data type _eDELIMITER.

OutStruct

Structure

Out

OK

Function

The SubDelimiter instruction converts the delimited text string data from input text string In and stores the results as the values of the members of storage structure OutStruct. The text strings are delimited with delimiter Delimiter. The results are stored as the values of the members in order from the start of the structure.

The data type of Delimiter is enumerated type _eDELIMITER. The meanings of the enumerators are as follows:

Enumerator _COMMA _TAB _SEMICOLON _SPACE

Meaning `,' (comma) `$T' (tab) `;'(semicolon) ` `(blank character)

2-588

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Text String Instructions

If the number of text strings that are delimited in In exceeds the number of members of OutStruct, the remaining data is ignored.
If the number of text strings that are delimited in In is less than the number of members of OutStruct, the values of the remaining members are not changed.
If a member of OutStruct is a structure and there is not sufficient data in In for all of the members of that structure, the data is still stored as far as possible.
If a member of OutStruct is an array and there is not sufficient data in In for all of the elements of that array, the data is still stored as far as possible.

SubDelimiter

The delimited data in In consists of STRING data. The STRING data is converted according to data types of the members of OutStruct, as described next.
2
 Boolean Data
If the STRING data is `FALSE' or `0', it is converted to FALSE. If the STRING data is `TRUE' or `1', it is converted to TRUE.
The following are exceptions. · Any continuous `0' characters before `0' or `1' are ignored. · `FALSE' and `TRUE' are not case sensitive.
Conversion is not possible if the STRING data is not `FALSE', `TRUE', `0', or `1'.

 Bit String Data
The conversion rules are the same as for the STRING_TO_** (Text String-to-Bit String Conversion Group) instruction (page 2-301). Conversion is not possible if the data does not express a hexadecimal number.

 Integer Data
The conversion rules are the same as for the STRING_TO_** (Text String-to-Integer Conversion Group) instruction (page 2-299). Conversion is not possible if the data does not express an integer number.

 Real Number Data
The conversion rules are the same as for the STRING_TO_** (Text String-to-Real Number Conversion Group) instruction (page 2-303). Conversion is not possible if the data does not express a real number.

 Duration Data
Data with the following structure is converted to a duration.

- A A d B B h C C m DD s EE ms

Sign column Days 'd'

Hours Minutes

'h'

'm'

's' Seconds

'ms' Milliseconds

Item Sign column
Days Hours Minutes Seconds Milliseconds

Description If there is a `+' (positive) or if there is no sign column, the value of the member will be positive. If there is a `-' (negative), the value of the member will be negative. The value of AA is truncated after the 11th digit below the decimal point. The value of BB is truncated after the 11th digit below the decimal point. The value of CC is truncated after the 10th digit below the decimal point. The value of DD is truncated after the 9th digit below the decimal point. The value of EE is truncated after the 6th digit below the decimal point.

NJ/NX-series Instructions Reference Manual (W502)

2-589

2 Instruction Descriptions

Note 1 Any ` ` (blank characters) before the sign column, days, hours, minutes, seconds, or milliseconds are ignored.
2 If any characters in the values of AA, BB, CC, DD, or EE are separated with a single `_' (underbar), the underbar is ignored.
3 Even if the value of the days, hours, minutes, seconds, or milliseconds is a real number with a `.' (period), the data can still be converted.
4 If the days, hours, minutes, seconds, or milliseconds is included in the data, conversion is possible even if the other items are omitted.
5 Even if there is a `0' before the value of the days, hours, minutes, seconds, or milliseconds, the data can still be converted.
Conversion is not possible in the following cases. · The data is not in the above structure. · There is an `_' (underbar) between the sign column and the days. · `.' (periods) or `_' (underbars) appear consecutively. For example, if the STRING data is `-0.5d48h0.123456789ms', the value of the member will be T#- 2d12h0m0s0.123456ms(T#-216000000.123456ms).
 Date Data
Data with the following structure is converted to a date.
YYYY - MM - DD

Year Hyphen Month Hyphen Days
The following are exceptions. · Any ` ` (blank characters) before the year, month, or day are ignored. · If any characters in the values of the year, month, or day are separated with a single `_' (under-
bar), the underbar is ignored. · Even if there is a `0' before the value of the year, month, or day, the data can still be converted.

Conversion is not possible in the following cases. · The data is not in the above structure. · The date does not exist. For example, if the STRING data is `2000-1-01', the value of the member will be D#2000-01-01.

 Date and Time Data
Data with the following structure is converted to a duration.

YYYY - MM - DD - hh : mm : ss . sssssssss

Decimal point

Year Hyphen Month Hyphen Day Hyphen Hour Colon Minutes Colon

Seconds

Item Year, month, and day Hour Minutes Seconds
Hyphens and colons

Description This is the year, month, and day that express the date.
The range of the value is 0 to 23. The range of the value is 0 to 59. The range of the value is 0 to 59.999999999. If the value is an integer, a decimal point is not required. These are always required.

Note 1 Any ` ` (blank characters) before the year, month, day, hour, minutes, or seconds are ignored.

2-590

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Text String Instructions

2 If any characters in the values of the year, month, day, hour, minutes, or seconds are separated with a single `_' (underbar), the underbar is ignored.
3 Even if there is a `0' before the value of the year, month, day, hour, minutes, or seconds, the data can still be converted.

Conversion is not possible in the following cases. · The data is not in the above structure. · The date does not exist.
For example, if the STRING data is `2000-01-23-4:56:07.89', the value of the member will be DT#2000-01-23-04:56:07.89.

 Time of Day Data

2

Data with the following structure is converted to a time of day.

SubDelimiter

hh : mm : ss . sssssssss

Minutes

Seconds

Hour Colon Colon Decimal point

Item Hour Minutes Seconds
Colons

Description The range of the value is 0 to 23. The range of the value is 0 to 59. The range of the value is 0 to 59.999999999. If the value is an integer, a decimal point (`.' (period)) is not required. These are always required.

Note 1 Any ` `(blank characters) before the hour, minutes, or seconds are ignored. 2 If any characters in the values of hour, minutes, or seconds are separated with a single `_' (underbar), the underbar is ignored. 3 Even if there is a `0' before the value of the hour, minutes, or seconds, the data can still be converted.

Conversion is not possible in the following cases. · The data is not in the above structure. · `.' (periods) or `_' (underbars) appear consecutively.
For example, if the STRING data is `12:23:34.567', the value of the member will be TOD#12:23:34.567.

 Text String Data
The value of the member will be the data with a NULL character added to the end. However, conversion is not possible if the text string exceeds the size of the member.
For example, if the STRING data is `ABC' without a NULL character at the end, the value of the member will be `ABC' with a NULL character at the end.

 Structure Data
The STRING data is converted according to the conversion rules for the data types of the members. The data is converted in order from the start and stored as the values of the members of the structure down to the nesting levels that are not structures. For example, if a member of structure A is Structure_B, the conversion works as shown below.
Stored as members of structure A.

'ABC,12,34,56,XYZ'

Structure A

Member memberA memberB memberC

Data type Value STRING 'ABC'
Structure_B --STRING 'XYZ'

Structure B

Member Data type Value member1 INT INT#12 member2 INT INT#34 member3 INT INT#56

NJ/NX-series Instructions Reference Manual (W502)

2-591

2 Instruction Descriptions

 Enumeration Data
STRING data that expresses a DINT variable is converted to an enumerator of the enumeration. The same rules as for integers are used to convert to DINT data, the value of the DINT data is taken as the value of the enumeration, and that value is converted to the corresponding enumerator. However, conversion is not possible if the STRING data does not express a DINT value. For example, assume that an enumeration Color has three enumerators: red, yellow, and green. The numbers associated with these enumerators are as follows: red = 1, yellow = 2, green = 3. If the data is `3', the value of the member will be green.
 Array Data
Each delimited data is converted to the value of an element. The conversion rules for the data type of the array are used. Conversion is possible only if the members are one-dimensional arrays. For example, assume that a member is the myString[0..3] BYTE array. If the comma-delimited text string `AA,BB,CC,DD' is converted to the elements of the array, myString[0] will be BYTE#16#AA, myString[1] will be BYTE#16#BB, myString[2] will be BYTE#16#CC, and myString[3] will be BYTE#16#DD.

Notation Example

The following notation reads comma-delimited data from the myString text string and stores the text strings as the values of the members of the myStruct structure.

LD

ST

myString
myStruct _COMMA

SubDelimiter

EN

ENO

In

OutStruct

Delimiter

SubDelimiter(myString,myStruct,_COMMA);

myString 'XYZ,1234,aB,3.14'

Structure myStruct

Member member1 member2 member3 member4

Data type

Value

STRING

' '

INT

INT#0

WORD WORD#16#0000

REAL

REAL#0

Data from myString is stored as the values of the members of myStruct.

Structure myStruct

Member member1 member2 member3 member4

Data type

Value

STRING

'XYZ'

INT

INT#1234

WORD WORD#16#00AB

REAL REAL#3.14e+0

Additional Information
· You can combine this instruction with the FileGets instruction (page 2-1411) to easily read values from specified CSV files in an SD Memory Card. Refer to Sample Programming for an application example.
· Use this instruction to return a text string that was converted with the AddDelimiter instruction (page 2-577) to structure data.
Precautions for Correct Use
· If there is more than one consecutive delimiter in In, the delimited data will not exist. If the delimited data does not exist, the value of the member of OutStruct will be undefined.
· Do not use the delimiter in In for anything other than the delimiter. If you use the delimiter for any other purpose, the instruction will still treat it as a delimiter.

2-592

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Text String Instructions

· If there is a STRING member in OutStruct, do not attach a final NULL character to the corresponding data in In. If you use a NULL character anywhere except at the end of In, only the text string through the first NULL character will be converted.

· If there is an enumeration in OutStruct, make sure that the corresponding data in In is a value that is defined as an enumerator. An error will not occur even if the value of the enumerated variable is not a value that is defined as an enumerator.

· An error occurs in the following cases. ENO changes to FALSE and the values in OutStruct will be undefined.

· Conversion to a value with the data type of the member of OutStruct is not possible.

· The conversion result exceeds the valid range of the value of the data type of the member of OutStruct.

· A member of OutStruct is an array with more than one dimension.

2

· A member of OutStruct is a union.

· The size of OutStruct exceeds 8,192 bytes.

SubDelimiter

Version Information
A CPU Unit with unit version 1.02 or later and Sysmac Studio version 1.03 or higher are required to use this instruction.

Sample Programming

Here, multiple lines of text strings that are separated by carriage returns (i.e., CR codes) are stored in a file named `ABC.csv.' The text string on each line is delimited by commas. Text strings are read from this file one line at a time, and the comma-delimited data is stored as the values of the members of the myArray[] array variables in the myStruct structure from the start of the structure. The myStruct structure has five members that are STRING variables. Processing ends when the data is read to the end of the file (i.e., when it is read to the EOF code).
`ABC.csv' file
OK CR A,B,C CR ABC,DEF CR

EOF

Lines are read one at a time and stored in myArray[] members.

myArray[0].member0 'OK' myArray[1].member0 'A' myArray[0].member0 Undefined myArray[1].member1 'B' myArray[0].member0 Undefined myArray[1].member2 'C' myArray[0].member0 Undefined myArray[1].member3 Undefined myArray[0].member0 Undefined myArray[1].member4 Undefined

myArray[2].member0 'ABC'
myArray[2].member1 'DEF' myArray[2].member2 Undefined myArray[2].member3 Undefined myArray[2].member4 Undefined

The processing procedure is as follows:
1 The FileOpen instruction is used to open the file `ABC.csv.' 2 The FileGets instruction is used to read one line from the file.
3 The SubDelimiter is used to store comma-delimited text strings as the values of the myArray[]
members.
4 Steps 2 and 3 are repeated until the EOF (end of file).
5 The FileClose instruction is used to close the file.

NJ/NX-series Instructions Reference Manual (W502)

2-593

2 Instruction Descriptions

 Data Type Definition

Name myStruct member0 member1 member2 member3 member4

Data type STRUCT STRING STRING STRING STRING STRING

Comment Structure Member Member Member Member Member

LD
Internal Variables

Variable

OperatingEnd

Trigger Operating Index Fid

myArray

RS_instance FileOpen_instance FileGets_instance FileClose_instance

Data type

Initial value

BOOL

False

BOOL

False

BOOL

False

INT

0

DWORD
ARRAY[0..999] OF myStruct
RS FileOpen FileGets FileClose

16#0
[1000((member0:='',member1:='',member2:='',member3:='',member4:=''))]

Comment
Processing completed Execution condition Processing myArray[] element index File ID
Integer data

External Variables

Variable _Card1Ready

BOOL

Data type

Comment SD Memory Card Ready Flag

2-594

NJ/NX-series Instructions Reference Manual (W502)

Text String Instructions

2 Instruction Descriptions

Determine if instruction execution is completed.

FileClose_instance.Done

OperatingEnd

FileOpen_instance.Error

FileGets_instance.Error

FileClose_instance.Error

2

SubDelimiter

Accept trigger. Trigger _Card1Ready
OperatingEnd

RS_instance

RS

Set

Q1

Reset1

Operating

Initialize InDat[] element index.

Operating

Inline ST

1 Index:=INT#0;

Execute FileOpen instruction. Operating

FileOpen_instance FileOpen

Execute Done

`ABC.csv' FileName Busy

_READ_EXIST Mode

Error

ErrorID FileID Fid

FileOpen_instance.Error

Inline ST
1 // Processing after error end 2 ;

NJ/NX-series Instructions Reference Manual (W502)

2-595

2 Instruction Descriptions

Execute FileGets instruction. Operating FileOpen_instance.Done FileGets_instance.Busy FileClose_instance.Busy

FileGets_instance FileGets

Fid TRUE

Execute FileID TrimLF

Done Busy Error ErrorID Out EOF

FileGets_instance.Error Inline ST

Execute SubDelimiter instruction.

1 // Processing after error end 2 ;

Operating FileGets_instance.Done

SubDelimiter

EN

ENO

FileGets_instance.Out In

Out

myArray[Index]

OutStruct

_COMMA Delimiter

Index

Inc
EN ENO InOut

Execute FileClose instruction when EOF is detected. Operating FileGets_instance.EOF
Fid

FileClose_instance

FileClose

Execute FileID

Done Busy Error ErrorID

FileClose_instance.Error

Inline ST
1 // Processing after error end 2 ;

Processing after normal end Operating FileClose_instance.Done

Inline ST
1 // Processing after normal end 2 ;

2-596

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Text String Instructions

ST

Internal Variables

Variable

Data type

Initial value

Comment

Trigger

BOOL

False

Execution condition

Value of Trigger

LastTrigger

BOOL

False

from previous task period

OperatingStart

BOOL

False

Processing started

Operating

BOOL

False

Processing

myArray Stage

ARRAY[0..999] OF myStruct

[1000((member0:='',member1:='',member2:='',member3:='',member4:=''))]

Integer data

2

INT

0

Stage change

SubDelimiter

Index

INT

0

myArray[] element index

Fid

DWORD

16#0

File ID

FileOpen_instance

FileOpen

FileGets_instance

FileGets

FileClose_instance

FileClose

External Variables

Variable _Card1Ready

Data type BOOL

Comment SD Memory Card Ready Flag

// Start sequence when Trigger changes to TRUE.

IF ( (Trigger=TRUE) AND (LastTrigger=FALSE) AND (_Card1Ready=TRUE) ) THEN

OperatingStart:=TRUE;

Operating

:=TRUE;

END_IF;

LastTrigger:=Trigger;

// Initialize instance.

IF (OperatingStart=TRUE) THEN

FileOpen_instance(Execute:=FALSE);

FileGets_instance(Execute:=FALSE);

FileClose_instance(Execute:=FALSE);

Stage

:=INT#1;

Index

:=INT#0;

OperatingStart:=FALSE;

END_IF;

// Execute instruction.

IF (Operating=TRUE) THEN

CASE Stage OF

1 :

// Open file.

FileOpen_instance(

Execute :=TRUE,

FileName:='ABC.csv',

// File name

Mode :=_READ_EXIST, // Read file

FileID =>Fid);

// File ID

IF (FileOpen_instance.Done=TRUE) THEN

Stage:=INT#2;

// Normal end

END_IF;

IF (FileOpen_instance.Error=TRUE) THEN

NJ/NX-series Instructions Reference Manual (W502)

2-597

2 Instruction Descriptions

Stage:=INT#99; END_IF;

// Error end

2 :

// Read text string.

FileGets_instance(

Execute:=TRUE,

FileID :=Fid,

TrimLF :=TRUE);

IF (FileGets_instance.Done=TRUE) THEN // Store the text strings that were read as the values of the
myArray[] member. SubDelimiter(FileGets_instance.Out,myArray[Index],_COMMA); Index:=Index+INT#1;

// Reached end of file. IF (FileGets_instance.EOF=TRUE) THEN
Stage:=INT#3; // Normal end ELSE
FileGets_instance(Execute:=FALSE); END_IF; END_IF;

IF (FileGets_instance.Error=TRUE) THEN

Stage:=INT#99;

// Error end

END_IF;

3 :

// Close file.

FileClose_instance(

Execute:=TRUE,

FileID :=Fid);

// File ID

IF (FileClose_instance.Done=TRUE) THEN Operating:=FALSE; // Normal end
END_IF;

IF (FileClose_instance.Error=TRUE) THEN

Stage:=INT#99;

// Error end

END_IF;

99 :

// Processing after error end

Operating:=FALSE;

END_CASE;

END_IF;

2-598

NJ/NX-series Instructions Reference Manual (W502)

Time and Time of Day Instructions

2
Time and Time of Day Instructions

Instruction ADD_TIME
ADD_TOD_TIME
ADD_DT_TIME SUB_TIME
SUB_TOD_TIME
SUB_TOD_TOD SUB_DATE_DATE
SUB_DT_DT SUB_DT_TIME
MULTIME DIVTIME CONCAT_DATE_TOD
DT_TO_TOD
DT_TO_DATE
SetTime GetTime DtToSec
DateToSec

Name Add Time

Page

Instruction

2-600 TodToSec

Add Time to Time of Day

2-602 SecToDt

Add Time to Date and Time Subtract Time

2-604 SecToDate 2-606 SecToTod

Subtract Time from Time of Day Subtract Time of Day Subtract Date

2-608 TimeToNanoSec
2-610 TimeToSec 2-611 NanoSecToTime

Subtract Date and Time Subtract Time from Date and Time Multiply Time Divide Time Concatenate Date and Time of Day Extract Time of Day from Date and Time Extract Date from Date and Time Set Time Get Time of Day Convert Date and Time to Seconds Convert Date to Seconds

2-612 SecToTime 2-614 ChkLeapYear

2-616 2-618 2-620

GetDaysOfMonth DaysToMonth GetDayOfWeek

2-622 GetWeekOfYear

2-624 DtToDateStruct

2-626 2-628 2-630

DateStructToDt TruncTime TruncDt

2-632 TruncTod

NJ/NX-series Instructions Reference Manual (W502)

Name Convert Time of Day to Seconds Convert Seconds to Date and Time Convert Seconds to Date Convert Seconds to Time of Day Convert Time to Nanoseconds Convert Time to Seconds Convert Nanoseconds to Time Convert Seconds to Time Check for Leap Year

Page 2-633
2-634
2-636 2-638
2-640
2-641 2-642
2-643 2-645

Get Days in Month Convert Days to Month Get Day of Week

2-646 2-648 2-650

Get Week Number

2-652

Break Down Date and Time 2-654

Join Time Truncate Time Truncate Date and Time

2-656 2-658 2-662

Truncate Time of Day

2-666

2-599

2 Instruction Descriptions

ADD_TIME

The ADD_TIME instruction adds two times.

Instruction

Name

FB/FUN

ADD_TIME

Add Time

FUN

Graphic expression

(@)ADD_TIME

EN

ENO

In1

Out

In2

ST expression Out:=ADD_TIME(In1, In2);

Variables

Name In1 In2 Out

Meaning Add time 1 Add time 2 Total time

I/O Input Output

Description Add time 1 Add time 2 Total time

Valid range

Unit

Depends on data type. ns

Depends on data type. ns

Default T#0s
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In1

OK

In2

OK

Out

OK

Function

The ADD_TIME instruction adds two times, In1 and In2. The result of addition in Out is also a time. The following example is for when In1 is T#1d2h3m4s and In2 is T#5d6h7m8s.

LD

ST

abc:=ADD_TIME(T#1d2h3m4s, T#5d6h7m8s);

ADD_TIME

EN T#1d2h3m4s In1 T#5d6h7m8s In2

ENO abc

In1

T#1d2h3m4s

+

In2

T#5d6h7m8s

Out=abc T#6d8h10m12s

2-600

NJ/NX-series Instructions Reference Manual (W502)

Time and Time of Day Instructions

2 Instruction Descriptions
Precautions for Correct Use
An error will not occur even if the addition result exceeds the valid range of Out. · T#106751d_23h_47m_16s_854.775807ms + T#0.000001ms
 T#-106751d_23h_47m_16s_854.775808ms · T#-106751d_23h_47m_16s_854.775808ms + T#-0.000001ms
 T#106751d_23h_47m_16s_854.775807ms
2

ADD_TIME

NJ/NX-series Instructions Reference Manual (W502)

2-601

2 Instruction Descriptions

ADD_TOD_TIME

The ADD_TOD_TIME instruction adds a time to a time of day.

Instruction ADD_TOD_TIME

Name
Add Time to Time of Day

FB/FUN FUN

Graphic expression

ST expression

(@)ADD_TOD_TIME

EN

ENO

In1

In2

Out:=ADD_TOD_TIME(In1, In2);
Out

Variables

Name In1
In2 Out

Meaning
Add time of day
Add time
Resulting time of day

I/O Input Output

Description Add time of day
Add time Resulting time of day

Valid range Depends on data type. Depends on data type.

Unit

Default

Hour, min- TOD#0:0 utes, seconds :0

ns

T#0s

Hour, min- --utes, seconds

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In1

OK

In2

OK

Out

OK

Function

The ADD_TOD_TIME instruction adds a time, In2, to a time of day In1. The result of addition in Out is also a time of day.

The following example is for when In1 is TOD#23:59:59.999999999 and In2 is T#1d0h0m0.000000001s.

LD

ST

ADD_TOD_TIME

EN TOD#23:59:59.999999999 In1
T#1d0h0m0.000000001s In2

ENO abc

abc:=ADD_TOD_TIME(TOD#23:59:59.999999999, T#1d0h0m0.000000001s);

In1

TOD#23:59:59.999999999

+

In2

T#1d0h0m0.000000001s

Out=abc TOD#0:0:0.000000000

2-602

NJ/NX-series Instructions Reference Manual (W502)

Time and Time of Day Instructions

2 Instruction Descriptions
Precautions for Correct Use
An error will not occur even if the addition result exceeds the valid range of Out. · TOD#23:59:59.999999999 + T#0.000001ms  TOD#0:0:0.000000000 · TOD#0:0:0.000000000 + T#-0.000001ms  TOD#23:59:59.999999999
2

ADD_TOD_TIME

NJ/NX-series Instructions Reference Manual (W502)

2-603

2 Instruction Descriptions

ADD_DT_TIME

The ADD_DT_TIME instruction adds a time to a date and time.

Instruction ADD_DT_TIME

Name
Add Time to Date and Time

FB/FUN FUN

Graphic expression

ST expression

(@)ADD_DT_TIME

EN

ENO

In1

In2

Out:=ADD_DT_TIME(In1, In2);
Out

Variables

Name In1
In2 Out

Meaning
Add date and time

I/O Input

Add time
Addition result date and time

Output

Description Add date and time

Valid range

Depends on data type.

Add time Addition result date and time Depends on data type.

Unit
Year, month, day, hour, minutes, seconds
ns
Year, month, day, hour, minutes, seconds

Default DT#197 0-1-10:0:0
T#0s
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In1

OK

In2

OK

Out

OK

2-604

NJ/NX-series Instructions Reference Manual (W502)

Time and Time of Day Instructions

2 Instruction Descriptions

Function

The ADD_DT_TIME instruction adds a time, In2, to a date and time In1. The result of addition in Out is also a date and time. Leap years are also accounted for. The following example is for when In1 is DT#1970-1-1-0:0:0 and In2 is T#1d.

LD

ST

abc:=ADD_DT_TIME(DT#1970-1-1-0:0:0, T#1d);

ADD_DT_TIME

EN DT#1970-1-1-0:0:0 In1

ENO abc

2

T#1d In2

In1 + In2
Out=abc

DT#1970-1-1-0:0:0 T#1d DT#1970-1-2-0:0:0

ADD_DT_TIME

Related System-defined Variables

Name _CurrentTime

Meaning

Data type

System Time of Day DT

Description
The time of day from the system clock. The number of seconds from 00:00:00 on January 1,1970.

Precautions for Correct Use
An error will not occur even if the addition result exceeds the valid range of Out. · DT#2554-7-21-23:34:33.709551615 + T#0.000001ms  DT#1970-1-1-0:0:0 · DT#1970-1-1-0:0:0 + T#-0.000001ms  DT#2554-7-21-23:34:33.709551615

NJ/NX-series Instructions Reference Manual (W502)

2-605

2 Instruction Descriptions

SUB_TIME

The SUB_TIME instruction subtracts one time from another.

Instruction SUB_TIME

Name Subtract Time

FB/FUN FUN

Graphic expression

(@)SUB_TIME

EN

ENO

In1

Out

In2

ST expression Out:=SUB_TIME(In1, In2);

Variables

Name In1
In2
Out

Meaning
Original time
Time to subtract
Resulting time

I/O Input Output

Description Original time
Time to subtract
Resulting time

Valid range

Unit

Default

Depends on data type. ns

T#0s

Depends on data type. ns

---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In1

OK

In2

OK

Out

OK

Function

The SUB_TIME instruction subtracts a time In2 from another time In1. The result of subtraction in Out is also a time.
The following example is for when In1 and In2 are T#1d.

LD

ST

abc:=SUB_TIME(T#1d, T#1d);

SUB_TIME

EN T#1d In1 T#1d In2

ENO abc

In1

T#1d

-

In2

T#1d

Out=abc T#0s

2-606

NJ/NX-series Instructions Reference Manual (W502)

Time and Time of Day Instructions

2 Instruction Descriptions
Precautions for Correct Use
An error will not occur even if the subtraction result exceeds the valid range of Out. · T#106751d_23h_47m_16s_854.775807ms - T#-0.000001ms
 T#-106751d_23h_47m_16s_854.775808ms · T#-106751d_23h_47m_16s_854.775808ms - T#0.000001ms
 T#106751d_23h_47m_16s_854.775807ms
2

SUB_TIME

NJ/NX-series Instructions Reference Manual (W502)

2-607

2 Instruction Descriptions

SUB_TOD_TIME

The SUB_TOD_TIME instruction subtracts a time from a time of day.

Instruction SUB_TOD_TIME

Name
Subtract Time from Time of Day

FB/FUN FUN

Graphic expression

(@)SUB_TOD_TIME

EN

ENO

In1

Out

In2

ST expression
Out:=SUB_TOD_TIME(In1, In2);

Variables

Name In1
In2
Out

Meaning

I/O

Time of day

Time to subtract
Resulting time of day

Input Output

Description Time of day
Time to subtract
Resulting time of day

Valid range Depends on data type.

Unit

Default

Hour, min- TOD#0:0 utes, seconds :0

ns

T#0s

Depends on data type. Hour, min- --utes, seconds

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In1

OK

In2

OK

Out

OK

Function

The SUB_TOD_TIME instruction subtracts a time In2 from a time of day In1. The result of subtraction in Out is also a time of day.
The following example is for when In1 is TOD#23:59:59 and In2 is T#1s.

LD

ST

abc:=SUB_TOD_TIME(TOD#23:59:59, T#1s);

SUB_TOD_TIME

EN TOD#23:59:59 In1
T#1s In2

ENO abc

In1

TOD#23:59:59

-

In2

T#1s

Out=abc TOD#23:59:58

2-608

NJ/NX-series Instructions Reference Manual (W502)

Time and Time of Day Instructions

2 Instruction Descriptions
Precautions for Correct Use
An error will not occur even if the subtraction result exceeds the valid range of Out. · TOD#23:59:59.999999999 - T#-0.000001ms  TOD#0:0:0 · TOD#0:0:0 - T#0.000001ms  TOD#23:59:59.999999999
2

SUB_TOD_TIME

NJ/NX-series Instructions Reference Manual (W502)

2-609

2 Instruction Descriptions

SUB_TOD_TOD

The SUB_TOD_TOD instruction subtracts a time of day from another time of day.

Instruction SUB_TOD_TOD

Name
Subtract Time of Day

FB/FUN FUN

Graphic expression

(@)SUB_TOD_TOD

EN

ENO

In1

Out

In2

ST expression
Out:=SUB_TOD_TOD(In1, In2);

Variables

Name In1
In2
Out

Meaning

I/O

Time of day 1
Time of day 2

Input

Resulting Output time

Description Time of day 1
Time of day 2
Resulting time

Valid range

Unit

Default

Depends on data type.

Hour, min- TOD#0:0 utes, seconds :0

Depends on data type. ns

---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In1

OK

In2

OK

Out

OK

Function

The SUB_TOD_TOD instruction subtracts time of day In2 from time of day In1. The result of subtraction in Out is a time.
The following example is for when In1 is TOD#23:59:59.999999999 and In2 is TOD#23:59:50.000000000.

LD

ST

SUB_TOD_TOD

EN TOD#23:59:59.999999999 In1 TOD#23:59:50.000000000 In2

ENO abc

abc:=SUB_TOD_TOD(TOD#23:59:59.999999999, TOD#23:59:50.000000000);

In1

TOD#23:59:59.999999999

-

In2

TOD#23:59:50.000000000

Out=abc T#0d0h0m9.999999999s

2-610

NJ/NX-series Instructions Reference Manual (W502)

Time and Time of Day Instructions

2 Instruction Descriptions

SUB_DATE_DATE

The SUB_DATE_DATE instruction subtracts another date from another date.

Instruction

Name

SUB_DATE_DATE Subtract Date

FB/FUN FUN

Graphic expression

ST expression

(@)SUB_DATE_DATE

EN

ENO

In1

In2

Out:=SUB_DATE_DATE(In1, In2);
Out

2

Variables

SUB_DATE_DATE

Name In1 In2 Out

Meaning Date 1 Date 2 Resulting time

I/O Input Output

Description Date 1 Date 2 Resulting time

Valid range Depends on data type. Depends on data type.

Unit
Year, month, day
ns

Default
D#19701-1
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In1

OK

In2

OK

Out

OK

Function

The SUB_DATE_DATE instruction subtracts date In2 from date In1. The result of subtraction in Out is a time.
The following example is for when In1 is D#1970-1-7 and In2 is D#1970-1-2.

LD

ST

abc:=SUB_DATE_DATE(D#1970-1-7, D#1970-1-2);

D#1970-1-7 D#1970-1-2

SUB_DATE_DATE

EN

ENO

In1

abc

In2

In1

D#1970-1-7

-

In2

D#1970-1-2

Out=abc T#5d0h0m0.000000000s

NJ/NX-series Instructions Reference Manual (W502)

2-611

2 Instruction Descriptions

SUB_DT_DT

The SUB_DT_DT instruction subtracts another date and time from another date and time.

Instruction SUB_DT_DT

Name
Subtract Date and Time

FB/FUN FUN

Graphic expression

(@)SUB_DT_DT

EN

ENO

In1

Out

In2

ST expression
Out:=SUB_DT_DT(In1, In2);

Variables

Name In1
In2
Out

Meaning
Date and time 1
Date and time 2
Resulting time

I/O Input Output

Description Date and time 1
Date and time 2
Resulting time

Valid range Depends on data type. Depends on data type.

Unit
Year, month, day, hour, minutes, seconds
ns

Default
DT#197 0-1-10:0:0
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In1

OK

In2

OK

Out

OK

Function

The SUB_DT_DT instruction subtracts date and time In2 from date and time In1. The result of subtraction in Out is a time.
The following example is for when In1 is DT#1970-1-7-0:0:0 and In2 is DT#1970-1-2-0:0:0.

LD

ST

SUB_DT_DT

EN DT#1970-1-7-0:0:0 In1 DT#1970-1-2-0:0:0 In2

ENO abc

abc:=SUB_DT_DT(DT#1970-1-7-0:0:0, DT#1970-1-2-0:0:0);

In1

DT#1970-1-7-0:0:0

-

In2

DT#1970-1-2-0:0:0

Out=abc T#5d

2-612

NJ/NX-series Instructions Reference Manual (W502)

Time and Time of Day Instructions

2 Instruction Descriptions

Related System-defined Variables

Name _CurrentTime

Meaning

Data type

System Time of Day DT

Description
The time of day from the system clock. The number of seconds from 00:00:00 on January 1,1970.

Precautions for Correct Use
If the processing result exceeds the valid range of Out, Out will contain an illegal value.
2

SUB_DT_DT

NJ/NX-series Instructions Reference Manual (W502)

2-613

2 Instruction Descriptions

SUB_DT_TIME

The SUB_DT_TIME instruction subtracts a time from a date and time.

Instruction SUB_DT_TIME

Name
Subtract Time from Date and Time

FB/FUN FUN

Graphic expression

(@)SUB_DT_TIME

EN

ENO

In1

Out

In2

ST expression
Out:=SUB_DT_TIME(In1, In2);

Variables

Name In1
In2 Out

Meaning

I/O

Date and time

Input

Time to subtract
Resulting date and time

Output

Description Date and time
Time to subtract Resulting date and time

Valid range Depends on data type.

Unit
Year, month, day, hour, minutes, seconds
ns

Default DT#197 0-1-10:0:0
T#0s

Depends on data type. Year, month, --day, hour, minutes, seconds

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In1

OK

In2

OK

Out

OK

2-614

NJ/NX-series Instructions Reference Manual (W502)

Time and Time of Day Instructions

2 Instruction Descriptions

Function

The SUB_DT_TIME instruction subtracts a time In2 from a date and time In1. The result of subtraction in Out is a date and time. Leap years are also accounted for.
The following example is for when In1 is DT#1970-1-1-0:0:0 and In2 is T#1d.

LD

ST

abc:=SUB_DT_TIME(DT#1970-1-7-0:0:0, T#1d);

SUB_DT_TIME

EN DT#1970-1-7-0:0:0 In1

ENO abc

2

T#1d In2

SUB_DT_TIME

In1

DT#1970-1-7-0:0:0

-

In2

T#1d

Out=abc DT#1970-1-6-0:0:0

Related System-defined Variables

Name _CurrentTime

Meaning

Data type

System Time of Day DT

Description
The time of day from the system clock. The number of seconds from 00:00:00 on January 1,1970.

Precautions for Correct Use
An error will not occur even if the subtraction result exceeds the valid range of Out. · DT#2554-7-21-23:34:33.709551615 - T#-0.000001ms  DT#1970-1-1-0:0:0 · DT#1970-1-1-0:0:0 - T#0.000001ms  DT#2554-7-21-23:34:33.709551615

NJ/NX-series Instructions Reference Manual (W502)

2-615

2 Instruction Descriptions

MULTIME

The MULTIME instruction multiplies a time by a specified number.

Instruction MULTIME

Name Multiply Time

FB/FUN FUN

Graphic expression

(@)MULTIME

EN

ENO

In1

Out

In2

ST expression Out:=MULTIME(In1, In2);

Variables

Name In1
In2 Out

Meaning
Original time
Multiplier
Resulting time

I/O Input Output

Description Original time
Multiplier Resulting time

Valid range Depends on data type. Depends on data type.

* If you omit the input parameter, the default value is not applied. A building error will occur.

Unit ns
---
ns

Default T#0s
*
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In1

OK

In2

OK OK OK OK OK OK OK OK OK OK

Out

OK

Function

The MULTIME instruction multiplies a time In1 by multiplier In2. The result of multiplication in Out is also a time.
The following example is for when In1 is T#1d2h3m30s and In2 is INT#2.

LD

ST

abc:=MULTIME(T#1d2h3m30s, INT#2);

MULTIME

EN T#1d2h3m30s In1
INT#2 In2

ENO abc

In1

T#1d2h3m30s

× In2

INT#2

Out=abc T#2d4h7m

2-616

NJ/NX-series Instructions Reference Manual (W502)

Time and Time of Day Instructions

2 Instruction Descriptions

Precautions for Correct Use

· If In2 is a real number, the multiplication result is rounded to the nearest nanosecond. The following table shows how values are rounded.

Value below nanoseconds

Treatment

Examples

Less than 0.5 The value is truncated.

1.49  1

0.5

If the ones digit is an even number, the value is trun- 1.50  2

cated. If it is an odd number, the value is rounded up. 2.50  2

Greater than The value is rounded up. 0.5

1.51  2

2

MULTIME

· If the value of In2 is 0, positive infinity, negative infinity, or nonnumeric data, the value of Out is as shown below.

Value of In2
0 + -

Value of Out

Other than the right

NX1P2

T#0s

T#0s

T#-106751d23h47m16.854775808s

T#-0d0h0m0s1e-6ms

T#-106751d23h47m16.854775808s

T#-0d0h0m0s1e-6ms

Nonnumeric data

T#-106751d23h47m16.854775808s

T#0s

· An error will not occur even if the multiplication result exceeds the valid range of Out.
· T#53375d_23h_53m_38s_427.387904ms * USINT#2  T#-106751d_23h_47m_16s_854.775808ms
· T#-53375d_23h_53m_38s_427.387905ms * USINT#2  T#106751d_23h_47m_16s_854.775806ms

NJ/NX-series Instructions Reference Manual (W502)

2-617

2 Instruction Descriptions

DIVTIME

The DIVTIME instruction divides a time by a specified number.

Instruction DIVTIME

Name Divide Time

FB/FUN FUN

Graphic expression

(@)DIVTIME

EN

ENO

In1

Out

In2

ST expression Out:=DIVTIME(In1, In2);

Variables

Name In1
In2

Meaning
Original time
Number to divide by

I/O Input

Description Original time
Number to divide by

Valid range Depends on data type.

Out

Resulting Output

Resulting time

time

Depends on data type.

* If you omit the input parameter, the default value is not applied. A building error will occur.

Unit ns
---
ns

Default T#0s
*
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In1

OK

In2

OK OK OK OK OK OK OK OK OK OK

Out

OK

Function

The DIVTIME instruction divides a time In1 by a number In2. The result of division in Out is also a time. The following example is for when In1 is T#1d and In2 is INT#2.

LD

ST

abc:=DIVTIME(T#1d, INT#2);

T#1d INT#2

DIVTIME

EN

ENO

In1

abc

In2

In1

T#1d

/

In2

INT#2

Out=abc T#12h

2-618

NJ/NX-series Instructions Reference Manual (W502)

Time and Time of Day Instructions

2 Instruction Descriptions

Precautions for Correct Use

· If the value of In2 is 0, positive infinity, negative infinity, or nonnumeric data, the value of Out is as shown below.

Value of In2

Other than the right

Value of Out

NX1P2

0

T#-106751d23h47m16.854775808s

T#0d_0h_0m_0s_1e-006

+

T#0s

T#0s

-

T#0s

T#0s

Nonnumeric data T#-106751d23h47m16.854775808s

T#0s

2

· If In2 is a real number, there may be error of up to several nanoseconds.

· If In2 is a real number, the division result is rounded to the nearest nanosecond. The following table shows how values are rounded.

DIVTIME

Value below nanoseconds Less than 0.5 0.5
Greater than 0.5

Description

Example

The fractional part is truncated.
If the ones digit is an even number, the value is truncated. If it is an odd number, the value is rounded up.
The fractional part is rounded up.

1.49  1
1.50  2 2.50  2
1.51  2

· An error occurs in the following case. ENO will be FALSE, and Out will not change. · In2 is an integer with a value of 0.

NJ/NX-series Instructions Reference Manual (W502)

2-619

2 Instruction Descriptions

CONCAT_DATE_TOD

The CONCAT_DATE_TOD instruction combines a date and a time of day.

Instruction
CONCAT_DATE _TOD

Name
Concatenate Date and Time of Day

FB/FUN FUN

Graphic expression

(@)CONCAT_DATE_TOD

EN

ENO

In1

In2

ST expression Out:=CONCAT_DATE_TOD(In1, In2);
Out

Variables

Name In1
In2

Meaning

I/O

Date

Input Time of day

Out

Combined Output

date and

time

Description Date
Time of day
Combined date and time

Valid range Depends on data type. Depends on data type.

Unit

Default

Year, month, D#1970-

day

1-1

Hour, min- TOD#0:0 utes, seconds :0

Year, month, --day, hour, minutes, seconds

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In1

OK

In2

OK

Out

OK

2-620

NJ/NX-series Instructions Reference Manual (W502)

Time and Time of Day Instructions

2 Instruction Descriptions

Function

The CONCAT_DATE_TOD instruction combines a date In1 and a time of day In2. The result of combining in Out is also a date and time.
The following example is for when In1 is D#1970-1-7 and In2 is TOD#23:59:59.999999999.

LD

ST

abc:=CONCAT_DATE_TOD(D#1970-1-7, TOD#23:59:59.999999999);

CONCAT_DATE_TOD

EN D#1970-1-7 In1

ENO abc

2

TOD#23:59:59.999999999 In2

In1

D#1970-1-7

+ In2

TOD#23:59:59.999999999

Out=abc DT#1970-1-7-23:59:59.999999999

CONCAT_DATE_TOD

Related System-defined Variables

Name _CurrentTime

Meaning

Data type

System Time of Day DT

Description
The time of day from the system clock. The number of seconds from 00:00:00 on January 1,1970.

Precautions for Correct Use
An error occurs in the following case. ENO will be FALSE, and Out will not change. · The results of combining exceeds the valid range of Out (e.g., the value of In1 is D#2554-7-21 and
the value of In2 is larger than TOD#23:34:33.709551615).

NJ/NX-series Instructions Reference Manual (W502)

2-621

2 Instruction Descriptions

DT_TO_TOD

The DT_TO_TOD instruction extracts the time of day from a date and time.

Instruction DT_TO_TOD

Name
Extract Time of Day from Date and Time

FB/FUN FUN

Graphic expression

(@)DT_TO_TOD

EN

ENO

In

Out

ST expression Out:=DT_TO_TOD(In);

Variables

Name In

Meaning
Date and time

I/O Input

Description Date and time

Out

Time of day Output

Time of day

Valid range Depends on data type.
Depends on data type.

Unit

Default

Year, month, day, hour, minutes, seconds

DT#19701-1-0:0:0

Hour, min- --utes, seconds

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

Out

OK

Function

The DT_TO_TOD instruction extracts the time of day from date and time In. The following example is for when In is DT#1970-1-7-23:59:59.999999999.

LD

ST

abc:=DT_TO_TOD(DT#1970-1-7-23:59:59.999999999);

DT_TO_TOD

EN DT#1970-1-7-23:59:59.999999999 In

ENO abc

In

DT#1970-1-7-23:59:59.999999999

Out=abc TOD#23:59:59.999999999

2-622

NJ/NX-series Instructions Reference Manual (W502)

Time and Time of Day Instructions

2 Instruction Descriptions

Related System-defined Variables

Name _CurrentTime

Meaning

Data type

System Time of Day DT

Description
The time of day from the system clock. The number of seconds from 00:00:00 on January 1,1970.

2

DT_TO_TOD

NJ/NX-series Instructions Reference Manual (W502)

2-623

2 Instruction Descriptions

DT_TO_DATE

The DT_TO_DATE instruction extracts the date from a date and time.

Instruction DT_TO_DATE

Name
Extract Date from Date and Time

FB/FUN FUN

Graphic expression

(@)DT_TO_DATE

EN

ENO

In

Out

ST expression Out:=DT_TO_DATE(In);

Variables

Name In

Meaning
Date and time

I/O Input

Description Date and time

Out

Date

Output

Date

Valid range Depends on data type.
Depends on data type.

Unit
Year, month, day, hour, minutes, seconds
Year, month, day

Default DT#197 0-1-10:0:0
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

Out

OK

Function

The DT_TO_DATE instruction extracts the date from date and time In. The following example is for when In is DT#1970-1-7-23:59:59.999999999.

LD

ST

abc:=DT_TO_DATE(DT#1970-1-7-23:59:59.999999999);

DT_TO_DATE

EN DT#1970-1-7-23:59:59.999999999 In

ENO abc

In

DT#1970-1-7-23:59:59.999999999

Out=abc D#1970-1-7

2-624

NJ/NX-series Instructions Reference Manual (W502)

Time and Time of Day Instructions

2 Instruction Descriptions

Related System-defined Variables

Name _CurrentTime

Meaning

Data type

System Time of Day DT

Description
The time of day from the system clock. The number of seconds from 00:00:00 on January 1,1970.

2

DT_TO_DATE

NJ/NX-series Instructions Reference Manual (W502)

2-625

2 Instruction Descriptions

SetTime

The SetTime instruction sets the system time.

Instruction

Name

FB/FUN

SetTime

Set Time

FUN

Graphic expression

(@)SetTime

EN

ENO

In

Out

ST expression SetTime(In);

Variables

Name

Meaning

I/O

Description

Valid range

Unit

Default

In

Time data Input

Current time to set system *1

time

Year, month, day, hour, minutes, seconds

DT#197 0-1-10:0:0

Out

Return

Output

Always TRUE

value

TRUE only

---

---

*1 The valid range is for any of the following GMTs (Greenwich Mean Times). The valid range for an NX-series CPU Unit is DT#1970-01-01-00:00:00.000000000 to DT#2069-12-3123:59:59.999999999 (0:00:000000000 on January 1, 1970 to 23:59:59.999999999 on December 31, 2069). The valid range for an NJ-series CPU Unit is DT#1970-01-01-00:00:00.000000000 to DT#2106-02-0623:59:59.999999999 (0:00:000000000 on January 1, 1970 to 23:59:59.999999999 on February 6, 2106).

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

Out

OK

2-626

NJ/NX-series Instructions Reference Manual (W502)

Time and Time of Day Instructions

2 Instruction Descriptions

Function

The SetTime instruction sets the system time to date and time In. The following programming example is for when In is DT#1970-1-7:23:59:59.999999999.

LD

ST

SetTime(DT#1970-1-7-23:59:59.999999999);

SetTime

EN

ENO

DT#1970-1-7-23:59:59.999999999 In

2

SetTime

The SetTime instruction sets the value of In to the system time of day.

Set to the system time of day.

System Time of Day

In DT#1970-1-7-23:59:59.999999999

23:59 and 59.999999999 seconds on January 7, 1970

Related System-defined Variables

Name _CurrentTime

Meaning

Data type

System Time of Day DT

Description
The time of day from the system clock. The number of seconds from 00:00:00 on January 1,1970.

Additional Information
The following methods can also be used to set the system time. · Sysmac Studio · NTP function

Precautions for Correct Use
· For In, specify the time for the set time zone (do not specify Greenwich mean time (GMT)). · You cannot set a time in In that is lower than 1970-1-1-0:0:0.000000000 GMT. · A time lag will occur when updating the internal time. If the time is read immediately after executing
this instruction, the old time may be read. · Return value Out is not used when the instruction is used in ST. · An error occurs in the following cases. ENO will be FALSE, and Out will not change.
· The value of In is outside of the valid range. · The value of In is below 1970-1-1-0:0:0.000000000 GMT.

NJ/NX-series Instructions Reference Manual (W502)

2-627

2 Instruction Descriptions

GetTime

The GetTime instruction reads the current time.

Instruction

Name

FB/FUN

GetTime

Get Time of Day FUN

Graphic expression

(@)GetTime

EN

ENO

Out

ST expression Out:=GetTime();

Variables

Name

Meaning

I/O

Description

Valid range

Unit

Default

Out

Current

Output

Current time

*

time

Year, month, --day, hour, minutes, seconds

* The valid range is for any of the following GMTs (Greenwich Mean Times). The valid range for an NX-series CPU Unit is DT#1970-01-01-00:00:00.000000000 to DT#2069-12-31-23:59:59.999999999 (0:00:000000000 on January 1, 1970 to 23:59:59.999999999 on December 31, 2069). The valid range for an NJ-series CPU Unit is DT#1970-01-01-00:00:00.000000000 to DT#2106-02-06-23:59:59.999999999 (0:00:000000000 on January 1, 1970 to 23:59:59.999999999 on February 6, 2106). The valid range for an NY-series Controller is DT#2000-01-01-00:00:00.000000000 to DT#2099-12-3123:59:59.999999999 (00:00:00.000000000 on January 1, 2000 to 23:59:59.999999999 on December 31, 2099).

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

Out

OK

2-628

NJ/NX-series Instructions Reference Manual (W502)

Time and Time of Day Instructions

2 Instruction Descriptions

Function

The GetTime instruction reads the current time. The current time of day is the time for the set time zone (not Greenwich mean time (GMT)).
The following figure shows a programming example. The current time is assigned to variable abc.

LD

ST

abc:=GetTime();

GetTime

EN

ENO

abc

2

GetTime

The GetTime instruction assigns the current time to abc.

For 23:59 and 59.999999999 seconds on January 7, 1970

System Time of Day

System time of day

is assigned.

23:59 and 59.999999999 seconds on January 7, 1970

Out=abc DT#1970-1-7-23:59:59.999999999

Related System-defined Variables

Name _CurrentTime

Meaning

Data type

System Time of Day DT

Description
The time of day from the system clock. The number of seconds from 00:00:00 on January 1,1970.

Additional Information
· Use the DtToSec instruction (page 2-630) to convert the current time of day to the system time of day (number of seconds from 00:00:00 on January 1,1970).
· Use the DtToDateStruct instruction (page 2-654) to convert the current time of day to a date (year, month, day, minutes, and seconds).
· Use the GetDayOfWeek instruction (page 2-650) to read the day of the week.

NJ/NX-series Instructions Reference Manual (W502)

2-629

2 Instruction Descriptions

DtToSec

The DtToSec instruction converts a date and time to the number of seconds from 00:00:00 on January 1, 1970.

Instruction DtToSec

Name
Convert Date and Time to Seconds

FB/FUN FUN

Graphic expression

(@)DtToSec

EN

ENO

In

Out

ST expression Out:=DtToSec(In);

Variables

Name In
Out

Meaning
Date and time

I/O Input

Seconds Output

Description Date and time
Number of seconds from 00:00:00 on January 1, 1970

Valid range Depends on data type.
0 to 18446744073

Unit
Year, month, day, hour, minutes, seconds
Seconds

Default DT#197 0-1-10:0:0
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

Out

OK

Function

The DtToSec instruction converts the date and time in In to the number of seconds from 00:00:00 on January 1, 1970. The converted value is in seconds. The value is truncated below the seconds.
The following example is for when In is DT#1970-1-2-0:0:0.999999999.

LD

ST

abc:=DtToSec(DT#1970-1-2-0:0:0.999999999);

DtToSec

EN DT#1970-1-2-0:0:0.999999999 In

ENO abc

In

DT#1970-1-2-0:0:0.999999999

-

DT#1970-1-1-0:0:0.000000000

Out=abc

LINT#86400

s

[

2-630

NJ/NX-series Instructions Reference Manual (W502)

Time and Time of Day Instructions

2 Instruction Descriptions

Related System-defined Variables

Name _CurrentTime

Meaning

Data type

System Time of Day DT

Description
The time of day from the system clock. The number of seconds from 00:00:00 on January 1,1970.

Additional Information

Use the SecToDt instruction (page 2-634) to convert the number of seconds from 00:00:00 on January

1,1970 to a date and time.

2

DtToSec

NJ/NX-series Instructions Reference Manual (W502)

2-631

2 Instruction Descriptions

DateToSec

The DateToSec instruction converts a date to the number of seconds from 00:00:00 on January 1, 1970.

Instruction DateToSec

Name
Convert Date to Seconds

FB/FUN FUN

Graphic expression

(@)DateToSec

EN

ENO

In

Out

ST expression Out:=DateToSec(In);

Variables

Name In
Out

Meaning

I/O

Date

Input

Seconds Output

Date

Description

Number of seconds from 00:00:00 on January 1, 1970

Valid range Depends on data type.
0 to 18446659200

Unit Year, month, day Seconds

Default DT#197 0-1-1
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

Out

OK

Function

The DateToSec instruction converts 00:00:00 on date In to the number of seconds from 00:00:00 on January 1, 1970. The converted value is in seconds.
The following example is for when In is D#1970-1-2.

LD

ST

D#1970-1-2

DateToSec

EN

ENO

In

abc

abc:=DateToSec(D#1970-1-2);

In

D#1970-1-2

-

DT#1970-1-1-0:0:0.000000000

Out=abc

LINT#86400

s

[

Additional Information
Use the SecToDate instruction (page 2-636) to convert the number of seconds from 00:00:00 on January 1,1970 to a date.

2-632

NJ/NX-series Instructions Reference Manual (W502)

Time and Time of Day Instructions

2 Instruction Descriptions

TodToSec

The TodToSec instruction converts a time of day to the number of seconds from 00:00:00.

Instruction TodToSec

Name
Convert Time of Day to Seconds

FB/FUN FUN

Graphic expression

(@)TodToSec

EN

ENO

In

Out

ST expression Out:=TodToSec(In);

2 Variables

TodToSec

Name In

Meaning

I/O

Time of day Input

Out

Seconds Output

Description Time of day
Number of seconds from 00:00:00

Valid range Depends on data type.
0 to 86399

Unit

Default

Hour, min- TOD#0:0 utes, seconds :0

Seconds

---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

Out

OK

Function

The TodToSec instruction converts the time of day in In to the number of seconds from 00:00:00. The converted value is in seconds. The value is truncated below the seconds.
The following example is for when In is TOD#12:0:0.999999999.

LD

ST

abc:=TodToSec(TOD#12:0:0.999999999);

TOD#12:0:0.999999999

TodToSec

EN

ENO

In

abc

In

TOD#12:0.0.999999999

-

TOD#0:0:0.000000000

Out=abc

LINT#43200

s

[

Additional Information
Use the SecToTod instruction (page 2-638) to convert the number of seconds from 00:00:00 on January 1,1970 to a time of day.

NJ/NX-series Instructions Reference Manual (W502)

2-633

2 Instruction Descriptions

SecToDt

The SecToDt instruction converts the number of seconds from 00:00:00 on January 1, 1970 to a date and time.

Instruction SecToDt

Name

FB/FUN

Convert Seconds to FUN Date and Time

Graphic expression

(@)SecToDt

EN

ENO

In

Out

ST expression Out:=SecToDt(In);

Variables

Name In
Out

Meaning

I/O

Seconds Input

Date and time

Output

Description Number of seconds from 00:00:00 on January 1, 1970 Date and time

Valid range 0 to 18446744073

Unit Seconds

Default 0

Depends on data type.

Year, month, --day, hour, minutes, seconds

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

Out

OK

Function

The SecToDt instruction converts the number of seconds from 00:00:00 on January 1, 1970 in In to a date and time.
The following example is for when In is LINT#86400.

LD

ST

abc:=SecToDt(LINT#86400);

SecToDt

EN LINT#86400 In

ENO abc

DT#1970-1-1-0:0:0.000000000

+ In

LINT#86400

s

Out=abc DT#1970-1-2-0:0:0.000000000
[

2-634

NJ/NX-series Instructions Reference Manual (W502)

Time and Time of Day Instructions

2 Instruction Descriptions

Related System-defined Variables

Name _CurrentTime

Meaning

Data type

System Time of Day DT

Description
The time of day from the system clock. The number of seconds from 00:00:00 on January 1,1970.

Additional Information

Use the DtToSec instruction (page 2-630) to convert the current time of day to the number of seconds

from 00:00:00 on January 1,1970.

2

SecToDt

Precautions for Correct Use
An error occurs in the following case. ENO will be FALSE, and Out will not change. · The value of In is outside of the valid range.

NJ/NX-series Instructions Reference Manual (W502)

2-635

2 Instruction Descriptions

SecToDate

The SecToDate instruction converts the number of seconds from 00:00:00 to a date.

Instruction SecToDate

Name

FB/FUN

Convert Seconds to FUN Date

Graphic expression

(@)SecToDate

EN

ENO

In

Out

ST expression Out:=SecToDate(In);

Variables

Name In

Meaning

I/O

Seconds Input

Out

Date

Output

Description Number of seconds from 00:00:00 Date

Valid range 0 to 18446744073

Unit Seconds

Default 0

Depends on data type. Year, month, --day

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

Out

OK

Function

The SecToDate instruction converts the number of seconds from 00:00:00 in In to a date. The value is truncated below date.
The following example is for when In is LINT#86400.

LD

ST

abc:=SecToDate(LINT#86400);

LINT#86400

SecToDate

EN

ENO

In

abc

D#1970-1-1

+ In

LINT#86400 s

Out=abc D#1970-1-2
[

Additional Information
Use the DateToSec instruction (page 2-632) to convert a date to the number of seconds from 00:00:00 on January 1,1970.

2-636

NJ/NX-series Instructions Reference Manual (W502)

Time and Time of Day Instructions

2 Instruction Descriptions
Precautions for Correct Use
An error occurs in the following case. ENO will be FALSE, and Out will not change. · The value of In is outside of the valid range.
2

SecToDate

NJ/NX-series Instructions Reference Manual (W502)

2-637

2 Instruction Descriptions

SecToTod

The SecToTod instruction converts the number of seconds from 00:00:00 to a time of day.

Instruction SecToTod

Name
Convert Seconds to Time of Day

FB/FUN FUN

Graphic expression

(@)SecToTod

EN

ENO

In

Out

ST expression Out:=SecToTod(In);

Variables

Name In
Out

Meaning

I/O

Seconds Input

Time of day Output

Description Number of seconds from 00:00:00 Time of day

* Negative numbers are excluded.

Valid range

Unit

Depends on data type.* Seconds

Default 0

Depends on data type. Hour, min- --utes, seconds

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

Out

OK

Function

The SecToTod instruction converts the number of seconds from 00:00:00 in In to a time of day. If the value of In is 24 hours or longer, In is divided by 24 and the remainder is converted to the time of day.
The following example is for when In is LINT#86410.

LD

ST

abc:=SecToTod(LINT#86410);

SecToTod

EN LINT#86410 In

ENO abc

TOD#00:00:00 Remainder of division by 24 In LINT#86410 s

Out=abc

TOD#0:0:10.000000000
[

Additional Information
Use the TodToSec instruction (page 2-633) to convert a time of day to the number of seconds from 00:00:00 on January 1,1970.

2-638

NJ/NX-series Instructions Reference Manual (W502)

Time and Time of Day Instructions

2 Instruction Descriptions
Precautions for Correct Use
An error occurs in the following case. ENO will be FALSE, and Out will not change. · The value of In is outside of the valid range.
2

SecToTod

NJ/NX-series Instructions Reference Manual (W502)

2-639

2 Instruction Descriptions

TimeToNanoSec

The TimeToNanoSec instruction converts a time to nanoseconds.

Instruction TimeToNanoSec

Name
Convert Time to Nanoseconds

FB/FUN FUN

Graphic expression

(@)TimeToNanoSec

EN

ENO

In

Out

ST expression Out:=TimeToNanoSec(In);

Variables

Name

Meaning

I/O

Description

In

Time

Input

Time

Out

Nanosecon Output Nanoseconds

ds

* -9223372036854775808 to 9223372036854775807

Valid range Depends on data type. *

Unit ns ns

Default T#0s
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

Out

OK

Function

The TimeToNanoSec instruction converts the time in In to nanoseconds. The following example is for when In is T#1d1h1m1.999999999s.

LD

ST

abc:=TimeToNanoSec(T#1d1h1m1.999999999s);

TimeToNanoSec

EN T#1d1h1m1.999999999s In

ENO abc

Nanoseconds

In T#1d1h1m1.999999999s

Out=abc

LINT#90061000000000 ns
[

Additional Information
Use the NanoSecToTime instruction (page 2-642) to convert nanoseconds to a time.

2-640

NJ/NX-series Instructions Reference Manual (W502)

Time and Time of Day Instructions

2 Instruction Descriptions

TimeToSec

The TimeToSec instruction converts a time to seconds.

Instruction TimeToSec

Name
Convert Time to Seconds

FB/FUN FUN

Graphic expression

(@)TimeToSec

EN

ENO

In

Out

ST expression Out:=TimeToSec(In);

Variables

2

Name In Out

Meaning Time Seconds

I/O Input Output

Description Time Seconds

Valid range
Depends on data type. -9223372036 to 9223372036

Unit ns Seconds

Default T#0s
---

Bit strings

Integers

Times, durations, dates, and text strings

TimeToSec
STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

Out

OK

Function

The TimeToSec instruction converts the time in In to seconds. The value is truncated below the seconds.
The following example is for when In is T#1d1h1m1.999999999s.

LD

ST

TimeToSec

EN T#1d1h1m1.999999999s In

ENO abc

abc:=TimeToSec(T#1d1h1m1.999999999s);

Seconds

In T#1d1h1m1.999999999s

Out=abc LINT#90061 s

[

Additional Information
Use the SecToTime instruction (page 2-643) to convert seconds to a time.

Precautions for Correct Use
In is in nanoseconds. Out is in seconds.

NJ/NX-series Instructions Reference Manual (W502)

2-641

2 Instruction Descriptions

NanoSecToTime

The NanoSecToTime instruction converts nanoseconds to a time.

Instruction NanoSecToTime

Name
Convert Nanoseconds to Time

FB/FUN FUN

Graphic expression

ST expression

(@)NanoSecToTime

EN

ENO

In

Out:=NanoSecToTime(In); Out

Variables

Name

Meaning

I/O

Description

In

Nanosecon Input

Nanoseconds

ds

Out

Time

Output Time

* -9223372036854775808 to 9223372036854775807

Valid range *

Unit ns

Depends on data type. ns

Default 0
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

Out

OK

Function

The NanoSecToTime instruction converts the number of nanoseconds in In to a time. The following example is for when In is LINT#90061000000000.

LD

ST

abc:=NanoSecToTime(LINT#90061000000000);

NanoSecToTime

EN LINT#90061000000000 In

ENO abc

Time

In LINT#90061000000000 ns

Out=abc

T#1d1h1m1s
[

Additional Information
Use the TimeToNanoSec instruction (page 2-640) to convert a time to nanoseconds.

2-642

NJ/NX-series Instructions Reference Manual (W502)

Time and Time of Day Instructions

2 Instruction Descriptions

SecToTime

The SecToTime instruction converts seconds to a time.

Instruction SecToTime

Name
Convert Seconds to Time

FB/FUN FUN

Graphic expression

(@)SecToTime

EN

ENO

In

Out

ST expression Out:=SecToTime(In);

2 Variables

SecToTime

Name In

Meaning

I/O

Seconds Input

Out

Time

Output

Description Seconds
Time

Valid range -9223372036 to 9223372036
Depends on data type.

Unit Seconds
ns

Default 0
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

Out

OK

Function

The SecToTime instruction converts the number of seconds in In to a time. The following example is for when In is LINT#90061.

LD

ST

abc:=SecToTime(LINT#90061);

SecToTime

EN LINT#90061 In

ENO abc

Time In LINT#90061 s

Out=abc T#1d1h1m1s
[

Additional Information
Use the TimeToSec instruction (page 2-641) to convert a time to seconds.

NJ/NX-series Instructions Reference Manual (W502)

2-643

2 Instruction Descriptions
Precautions for Correct Use
· In is in seconds. Out is in nanoseconds. · An error occurs in the following case. ENO will be FALSE, and Out will not change.
· The value of In is outside of the valid range.

2-644

NJ/NX-series Instructions Reference Manual (W502)

Time and Time of Day Instructions

2 Instruction Descriptions

ChkLeapYear

The ChkLeapYear instruction is used to check for a leap year.

Instruction ChkLeapYear

Name
Check for Leap Year

FB/FUN FUN

Graphic expression

ST expression

(@)ChkLeapYear

EN

ENO

In

Out:=ChkLeapYear(In); Out

2 Variables

Name In Out

Meaning Year Result

I/O Input Output

Description Year TRUE: Leap year FALSE: Not leap year

Valid range 1970 to 2554 Depends on data type.

Unit Year
---

Default 1970
---

Bit strings

Integers

Times, durations, dates, and text strings

ChkLeapYear
STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

Out

OK

Function

The ChkLeapYear instruction is used to check to see if year In is a leap year. If it is a leap year, the value of result Out is TRUE. If it is not a leap year, Out is FALSE.
The following example is for when In is UINT#2012.

LD

ST

abc:=ChkLeapYear(UINT#2012);

ChkLeapYear

EN UINT#2012 In

ENO Out abc

Check for Leap Year

In UINT#2012 Year

Out=abc TRUE

[

Precautions for Correct Use
If the value of In exceeds the valid range, an error will not occur and the value of Out will be an illegal value.

NJ/NX-series Instructions Reference Manual (W502)

2-645

2 Instruction Descriptions

GetDaysOfMonth

The GetDaysOfMonth instruction gets the number of days in the specified month.

Instruction GetDaysOfMonth

Name

FB/FUN

Get Days in Month FUN

Graphic expression

(@)GetDaysOfMonth

EN Year Month

ENO Out

ST expression
Out:=GetDaysOfMonth(Year, Month);

Variables

Name Year Month Out

Meaning Year Month Days

I/O Input Output

Description Year Month Days

Valid range 1970 to 2554 1 to 12 28 to 31

Bit strings

Integers

Unit Year Month Days

Default 1970 1
---

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

Year Month Out

OK OK OK

Function

The GetDaysOfMonth instruction gets the number of days in month Month of year Year. The following example is for when Year is UINT#2012 and Month is USINT#2.

LD

ST

UINT#2012 USINT#2

GetDaysOfMonth

EN Year Month

ENO

abc:=GetDaysOfMonth(UINT#2012, USINT#2); abc

Year UINT#2012 Year

Days

Month USINT#2 Month

Out=abc USINT#29 Days
[

Precautions for Correct Use
· If the value of Year exceeds the valid range, an error will not occur and the value of Out will be an illegal value.
· An error occurs in the following case. ENO will be FALSE, and Out will not change. · The value of Month is outside of the valid range.

2-646

NJ/NX-series Instructions Reference Manual (W502)

Time and Time of Day Instructions

2 Instruction Descriptions

Sample Programming

This sample gets the number of days in the current month.

LD
Internal Variables

Variable Data type

Initial value

Comment

abc

_sDT

(Year:=0, Month:=0, Day:=0, Hour:=0, Min:=0, Sec:=0, NSec:=0)

Date and time

def

USINT

0

Days in current month

External Variables

Variable

Data type

Constant

Comment

2

_CurrentTime

DATE_AND_TIME

System Time of Day

GetDaysOfMonth

Always TRUE Flag

P_On

DtToDateStruct

EN _CurrentTime In

ENO DateStruct abc

GetDaysOfMonth

abc.Year abc.Month

EN Year Month

ENO def

ST
Internal Variables

Variable Data type

Initial value

Comment

abc

_sDT

(Year:=0, Month:=0, Day:=0, Hour:=0, Min:=0, Sec:=0, NSec:=0)

Date and time

def

USINT

0

Days in current month

External Variables

Variable

_CurrentTime

Data type DATE_AND_TIME

Constant

Comment

System Time of Day

DtToDateStruct(_CurrentTime, abc); def:=GetDaysOfMonth(abc.Year, abc.Month);

NJ/NX-series Instructions Reference Manual (W502)

2-647

2 Instruction Descriptions

DaysToMonth

The DaysToMonth instruction calculates the month based on the number of days from January 1.

Instruction DaysToMonth

Name
Convert Days to Month

FB/FUN FUN

Graphic expression

ST expression

(@)DaysToMonth

EN Year Days

ENO

Out:=DaysToMonth(Year, Days);
Out

Variables

Name Year Days

Meaning Year Days

I/O Input

Out

Month

Output

Description Year Number of days from January 1 Month

Valid range 1970 to 2554 1 to 365 1 to 366 for a leap year 1 to 12

Unit Year Days
Month

Default 1970 1
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

Year Days Out

OK OK OK

Function

The DaysToMonth instruction calculates the month based on the number of days in Days from January 1 in year Year.
The following example is for when Year is UINT#2012 and Days is UINT#32.

LD

ST

abc:=DaysToMonth(UINT#2012, UINT#32);

DaysToMonth

UINT#2012 UINT#32

EN Year Days

ENO abc

Year UINT#2012 Year Month Days UINT#32 Days

Out=abc USINT#2 Month
[

2-648

NJ/NX-series Instructions Reference Manual (W502)

Time and Time of Day Instructions

2 Instruction Descriptions
Precautions for Correct Use
· If the value of Year exceeds the valid range, an error will not occur and the value of Out will be an illegal value.
· An error occurs in the following case. ENO will be FALSE, and Out will not change. · The value of Days is outside of the valid range.
2

DaysToMonth

NJ/NX-series Instructions Reference Manual (W502)

2-649

2 Instruction Descriptions

GetDayOfWeek

The GetDayOfWeek instruction gets the day of the week for the specified year, month, and day of month.

Instruction GetDayOfWeek

Name Get Day of Week

FB/FUN FUN

Graphic expression

ST expression

(@)GetDayOfWeek

EN

ENO

In

Out:=GetDayOfWeek(In); Out

Variables

Name In
Out

Meaning
Year, month, day
Day of the week

I/O Input
Output

Description Year, month, day
Day of the week

Valid range Depends on data type.
_MON, _TUE, _WED, _THU, _FRI, _SAT, _SUN

* If you omit the input parameter, the default value is not applied. A building error will occur.

Unit
Year, month, day
Day of the week

Default *
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK

OK

Out

Refer to Function for the enumerators for the enumerated type _eDAYOFWEEK.

Function

The GetDayOfWeek instruction gets the day of the week for the year, month, and day of month specified in In. The data type of Out is enumerated type _eDAYOFWEEK. The meanings of the enumerators are as follows:

Enumerator

Meaning

_MON

Monday

_TUE

Tuesday

_WED

Wednesday

_THU

Thursday

_FRI

Friday

_SAT

Saturday

_SUN

Sunday

2-650

NJ/NX-series Instructions Reference Manual (W502)

Time and Time of Day Instructions

2 Instruction Descriptions

The following example is for when In is D#2011-1-1.
LD

GetDayOfWeek

EN D#2011-1-1 In

ENO abc

ST abc:=GetDayOfWeek(D#2011-1-1);

Day of the week

In D#2011-1-1

Out=abc _SAT Day of the week

2

Related System-defined Variables

GetDayOfWeek

Name _CurrentTime

Meaning

Data type

System Time of Day DT

Description
The time of day from the system clock. The number of seconds from 00:00:00 on January 1,1970.

NJ/NX-series Instructions Reference Manual (W502)

2-651

2 Instruction Descriptions

GetWeekOfYear

The GetWeekOfYear instruction gets the week number for the specified year, month, and day of month.

Instruction GetWeekOfYear

Name

FB/FUN

Get Week Number FUN

Graphic expression

(@)GetWeekOfYear

EN

ENO

In

Out

ST expression Out:=GetWeekOfYear(In);

Variables

Name

Meaning

I/O

Description

Valid range

In

Year,

Input

Year, month, day

month, day

Out

Week

Output

Week number

Depends on data type. 1 to 54

* If you omit the input parameter, the default value is not applied. A building error will occur.

Unit
Year, month, day
Week

Default *
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

Out

OK

OK

OK

Function

The GetWeekOfYear instruction gets the week number for the year, month, and day of month specified in In. Weeks are counted from Monday to Sunday. The count is incremented when changing from Sunday to Monday.
January 1 is always in week 1. For example, if January 1 is a Thursday, January 1 to January 4 (Sunday) is week 1 and January 5 (Monday) to January 11 (Sunday) is week 2.
The following example is for when In is D#2011-2-1.

LD

ST

abc:=GetWeekOfYear(D#2011-2-1);

GetWeekOfYear

EN D#2011-2-1 In

ENO abc

Week number

In D#2011-2-1

Out=abc Week USINT#6

2-652

NJ/NX-series Instructions Reference Manual (W502)

Time and Time of Day Instructions

2 Instruction Descriptions

Related System-defined Variables

Name _CurrentTime

Meaning

Data type

System Time of Day DT

Description
The time of day from the system clock. The number of seconds from 00:00:00 on January 1,1970.

2

GetWeekOfYear

NJ/NX-series Instructions Reference Manual (W502)

2-653

2 Instruction Descriptions

DtToDateStruct

The DtToDateStruct instruction converts a date and time to the year, month, day, hour, minutes, seconds, and nanoseconds.

Instruction DtToDateStruct

Name
Break Down Date and Time

FB/FUN FUN

Graphic expression

(@)DtToDateStruct

EN

ENO

In

Out

DateStruct

ST expression
Out:=DtToDateStruct(In, DateStruct);

Variables

Name In

Meaning
Date and time

I/O Input

Out DateStruct

Return value
Date and time

Output

Description Date and time
Always TRUE

Valid range Depends on data type.
TRUE only

Unit
Year, month, day, hour, minutes, seconds

Default
DT#197 0-1-10:0:0

Date and time as a year,

---

month, day, hour, minutes,

seconds, and nanoseconds

---

---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

Out

OK

DateStruct

OK Refer to Function for details on the structure _sDT.

Function

The DtToDateStruct instruction converts the date and time in In to the year, month, day, hour, minutes, seconds, and nanoseconds. The data in the broken down date and time in Out is the structure _sDT. The meanings of the members are as follows:

Name Out

Meaning Date and time

Year Month Day Hour Min Sec Nsec

Year Month Day Hour Minutes Seconds Nanoseconds

Content

Data type

Date and time as a year, _sDT month, day, hour, minutes, seconds, and nanoseconds

Year

UINT

Month

USINT

Day

USINT

Hour

USINT

Minutes

USINT

Seconds

USINT

Nanoseconds

ULINT

Valid range ---
1970 to 2554 1 to 12 1 to 31 0 to 23 0 to 59 0 to 59 0 to 999999999

Unit ---
Year Month Day Hour Minutes Seconds Nanoseconds

Default ---
---

2-654

NJ/NX-series Instructions Reference Manual (W502)

Time and Time of Day Instructions

2 Instruction Descriptions

The following example is for when In is DT#1970-1-2-12:34:56.999999999.

LD

ST

DtToDateStruct(DT#1970-1-2-12:34:56.999999999, abc);

DtToDateStruct

EN DT#1970-1-2-12:34:56.999999999 In

ENO DateStruct abc

Broken down

In DT#1970-1-2-12:34:56.999999999

Out=abc .Year UINT#1970 Year

.Month USINT#1 Month

.Day USINT#2 Day

2

.Hour USINT#12 Hour

.Min USINT#34 Minutes

.Sec USINT#56 Seconds

.Nsec ULINT#999999999 Nanoseconds

DtToDateStruct

Related System-defined Variables

Name _CurrentTime

Meaning

Data type

System Time of Day DT

Description
The time of day from the system clock. The number of seconds from 00:00:00 on January 1,1970.

Additional Information

· Use the DateStructToDt instruction (page 2-656) to join a year, month, day, hour, minutes, seconds, and nanoseconds into a date and time.
· The following example shows how to find the current time of day.

LD

ST

DtToDateStruct(_CurrentTime, abc);

DtToDateStruct

EN _CurrentTime In

ENO DateStruct abc

Precautions for Correct Use
Return value Out is not used when the instruction is used in ST.

NJ/NX-series Instructions Reference Manual (W502)

2-655

2 Instruction Descriptions

DateStructToDt

The DateStructToDt instruction joins a year, month, day, hour, minutes, seconds, and nanoseconds into a date and time.

Instruction DateStructToDt

Name Join Time

FB/FUN FUN

Graphic expression

ST expression

(@)DateStructToDt

EN

ENO

In

Out:=DateStructToDt(In); Out

Variables

Name In

Meaning
Date and time

I/O Input

Out

Date and Output

time

Description
Date and time as a year, month, day, hour, minutes, seconds, and nanoseconds
Date and time

Valid range
---
Depends on data type.

Unit
---
Year, month, day, hour, minutes, seconds

Default
---
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

Refer to Function for details on the structure _sDT.

Out

OK

Function

The DateStructToDt instruction joins the year, month, day, hour, minutes, seconds, and nanoseconds in In into a date and time. The data type of In is structure _sDT. The meanings of the members are as follows:

Name In

Meaning Date and time

Year Month Day Hour Min Sec Nsec

Year Month Day Hour Minutes Seconds Nanoseconds

Content

Data type

Date and time as a year, _sDT month, day, hour, minutes, seconds, and nanoseconds

Year

UINT

Month

USINT

Day

USINT

Hour

USINT

Minutes

USINT

Seconds

USINT

Nanoseconds

ULINT

Valid range ---
1970 to 2554 1 to 12 1 to 31 0 to 23 0 to 59 0 to 59 0 to 999999999

Unit ---
Year Month Day Hour Minutes Seconds Nanoseconds

Default ---
1970 1
0

2-656

NJ/NX-series Instructions Reference Manual (W502)

Time and Time of Day Instructions

2 Instruction Descriptions

The following example is for the following values for the members of In: Year is UINT#1970, Month is USINT#1, Day is USINT#2, Hour is USINT#12, Min is USINT#34, Sec is USINT#56, and Nsec is ULINT#999999999.

LD

ST

def:=DateStructToDt(abc);

DateStructToDt

EN abc In

ENO def

DateStructToDt

In=abc .Year UINT#1970 Year

.Month USINT#1 Month

2

.Day USINT#2 .Hour USINT#12

Day Hour

Joined

Out=def DT#1970-1-2-12:34:56.999999999

.Min USINT#34 Minutes

.Sec USINT#56 Seconds

.Nsec ULINT#999999999 Nanoseconds

Related System-defined Variables

Name _CurrentTime

Meaning

Data type

System Time of Day DT

Description
The time of day from the system clock. The number of seconds from 00:00:00 on January 1,1970.

Additional Information
Use the DtToDateStruct instruction (page 2-654) to break down a date and time into a year, month, day, hour, minutes, seconds, and nanoseconds.

Precautions for Correct Use
An error occurs in the following cases. ENO will be FALSE, and Out will not change. · The value of a member of In is outside of the valid range. · The processing result exceeds the valid range of Out.

NJ/NX-series Instructions Reference Manual (W502)

2-657

2 Instruction Descriptions

TruncTime

The TruncTime instruction truncates a TIME variable below the specified time unit.

Instruction TruncTime

Name Truncate Time

FB/FUN FUN

Graphic expression

(@)TruncTime

EN

ENO

In

Out

Accuracy

ST expression
Out:=TruncTime(In, Accuracy);

Variables

Name In
Accuracy

Meaning
Time to truncate
Smallest unit after truncation

I/O Input

Out

Time after Output

truncation

Description Time to truncate The smallest time unit to leave after truncation
Time after truncation

Valid range

Unit

Depends on data type. ns

_NANOSEC,

---

_MICROSEC,

_MILLISEC,

_SEC

Depends on data type. ns

Default T#0s _NANOSEC
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In Accuracy Out

OK Refer to Function for the enumerators of enumeration type _eSUBSEC.
OK

Function

The TruncTime instruction truncates all digits below the smallest unit after truncation that is specified in Accuracy from the time to truncate in In. The resulting time after truncation is stored in time after truncation Out.
The data type of Accuracy is enumerated type _eSUBSEC. The meanings of the enumerators are as follows:

Enumerator _NANOSEC _MICROSEC _MILLISEC _SEC

Meaning Nanoseconds Microseconds Milliseconds Seconds

2-658

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Time and Time of Day Instructions

The following example is for when In is TIME#123.456789012s and Accuracy is _MICROSEC.

LD

ST

abc:=TruncTime(T#123.456789012s, _MICROSEC);

TruncTime

EN

ENO

T#123.456789012s In

abc

_MICROSEC Accuracy

In T#123.456789012s

All digits below the microseconds are truncated.

Accuracy _MICROSEC

Out=abc T#123.456789s

2

TruncTime

Additional Information
Before you compare two TIME variables with the EQ (=) instruction (page 2-92) or other instructions, use the TruncTime instruction to convert the two variables to the same accuracy.

Precautions for Correct Use

Version Information
A CPU Unit with unit version 1.01 or later and Sysmac Studio version 1.02 or higher are required to use this instruction.

Sample Programming

The following programming example determines if the ON time of the sensor output is equal to or greater than the threshold value. The operation mode can be either the threshold setting mode or the execution mode. The operations of these modes are described in the following table.

Operation mode Threshold setting mode
Execution mode

Operation
The ON time of the sensor output is measured and the resulting value is set as the threshold.
The ON time of the sensor output is measured and compared with the threshold. If the ON time is equal to or greater than the threshold, the operation is considered normal.

The time is compared in milliseconds. The TruncTime instruction is used to truncate the digits in the measured time below milliseconds. The current operation mode is stored in the RecentMode variable. The result is stored in the Result variable. The value of Result is TRUE if operation is normal and FALSE if there is an error.

Definitions of Global Variables

Data type: Enumeration

Variable

Mode

SET

0

EXEC

1

Enumerator

Comment Operation mode Threshold setting Execution

NJ/NX-series Instructions Reference Manual (W502)

2-659

2 Instruction Descriptions

Global Variables

Variable

Data type

RecentMode Mode

Initial value SET

Comment The current operation mode

LD
Internal Variables

Variable
SensorOut ElapsedTime SensorTime

LongTime

ThresholdTime Result TON_instance

Data type Initial value

BOOL TIME TIME

FALSE T#0s T#0s

TIME

T#1h

TIME BOOL TON

T#0s FALSE

Comment
Sensor output Elapsed time Sensor ON time A time that is sufficiently longer than the sensor ON time Threshold Result, TRUE: Normal, FALSE: Error

External Variables

Variable RecentMode

Mode

Data type

Comment The current operation mode

Measure the sensor output ON time.

TON_instance

SensorOut

TON

In

Q

LongTime PT

ET

ElapsedTime

ElapsedTime

MOVE

EN

ENO

In

Out

SensorTime

Set the threshold.

SensorOut
RecentMode SET

EQ
EN In1 In2

SensorTime _MILLISEC

TruncTime

EN In Accuracy

ENO

ThresholdTime

Determine if result is normal or error.

RecentMode EXEC

EQ
EN In1 In2

SensorTime ThresholdTime

GE
EN In1 In2

Result

2-660

NJ/NX-series Instructions Reference Manual (W502)

Time and Time of Day Instructions

2 Instruction Descriptions

ST

Internal Variables

Variable

Data type Initial value

Comment

SensorOut

BOOL

FALSE

Sensor output

ElapsedTime

TIME

T#0s

Elapsed time

SensorTime

TIME

T#0s

Sensor ON time

LongTime

TIME

T#1h

A time that is sufficiently longer than the sensor ON time

SensorDone

BOOL

FALSE

Sensor output OFF flag

ThresholdTime

TIME

T#0s

Threshold

Result TON_instance

BOOL TON

FALSE

Result, TRUE: Normal, FALSE: Error

2

F_TRIG_instance F_TRIG

TruncTime

External Variables

Variable RecentMode

Mode

Data type

Comment The current operation mode

// Execute TON instruction.

TON_instance(

In:=SensorOut, // Timer input

PT:=LongTime,

// Set time

ET=>ElapsedTime); // Elapsed time

// Set sensor ON time to the elapsed time of TON. IF (SensorOut=TRUE) THEN
SensorTime:=ElapsedTime; END_IF;

// Detect when sensor output turns OFF. F_TRIG_instance(Clk:=SensorOut, Q=>SensorDone); Result:=FALSE;

// Set the threshold.

IF (SensorDone=TRUE AND RecentMode=SET) THEN

ThresholdTime:=TruncTime(

In

:=SensorTime,

Accuracy:=_MILLISEC); // Accuracy is milliseconds.

// Determine if result is normal or error.

ELSIF (SensorDone=TRUE AND RecentMode=EXEC) THEN

IF (SensorTime >= ThresholdTime) THEN

Result:=TRUE;

END_IF;

END_IF;

NJ/NX-series Instructions Reference Manual (W502)

2-661

2 Instruction Descriptions

TruncDt

The TruncDt instruction truncates a DT variable below the specified time unit.

Instruction TruncDt

Name
Truncate Date and Time

FB/FUN FUN

Graphic expression

(@)TruncDt

EN

ENO

In

Out

Accuracy

ST expression Out:=TruncDt(In, Accuracy);

Variables

Name In
Accuracy

Meaning

I/O

Date and time to truncate

Smallest unit after truncation

Input

Out

Date and Output

time after

truncation

Description Date and time to truncate
The smallest time unit to leave after truncation
Date and time after truncation

Valid range Depends on data type.
_NANOSEC, _MICROSEC, _MILLISEC, _SEC Depends on data type.

Unit Year, month, day, hour, minutes, seconds ---
Year, month, day, hour, minutes, seconds

Default DT#197 0-1-10:0:0
_NANOSEC
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In Accuracy Out

OK Refer to Function for the enumerators of enumeration type _eSUBSEC.
OK

Function

The TruncDt instruction truncates all digits below the smallest unit after truncation that is specified in Accuracy from the date and time to truncate in In. The resulting date and time after truncation is stored in date and time after truncation Out.

The data type of Accuracy is enumerated type _eSUBSEC. The meanings of the enumerators are as follows:

Enumerator _NANOSEC _MICROSEC _MILLISEC _SEC

Meaning Nanoseconds Microseconds Milliseconds Seconds

2-662

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Time and Time of Day Instructions

The following example is for when In is DT#1970-1-1-12:34:56.789012345 and Accuracy is _SEC.

LD

ST

TruncDt

EN

ENO

DT#1970-1-1-12:34:56.789012345 In

abc

_SEC Accuracy

abc:=TruncDt(DT#1970-1-1-12:34:56.789012345, _SEC);

All digits below the In DT#1970-1-1-12:34:56.789012345 seconds are truncated.

Accuracy _SEC

Out=abc DT#1970-01-01-12:34:56.000000000
2

TruncDt

Additional Information
Before you compare two DT variables with the EQ (=) instruction (page 2-92) or other instructions, use the TruncDt instruction to convert the two variables to the same accuracy.

Precautions for Correct Use

Version Information
A CPU Unit with unit version 1.01 or later and Sysmac Studio version 1.02 or higher are required to use this instruction.

Sample Programming
The following programming example records the date and time and the current voltage when a sensor output turns ON. The date and time is recorded in milliseconds. The sensor output is stored in SensorOut and the voltage is stored in Voltage. The current date and time is obtained with the GetTime instruction. The date and times and the voltages are stored in order in a Stack variable as Recent structures whose members are the date and time and corresponding voltage.

Definitions of Global Variables

Data Types
Variable Record DandT Voltage

Data type STRUCT DT REAL

Comment Structure Date and time Voltage

Global Variables

Variable Recent Stack

Data type Record ARRAY[0..99] OF Record

Initial value (DandT:=DT#1970-1-1-0:0:0,Voltage:=0.0) [100((DandT:=DT#1970-1-1-0:0:0,Voltage:=0.0))]

Comment Present value Stack

NJ/NX-series Instructions Reference Manual (W502)

2-663

2 Instruction Descriptions

LD
Internal Variables

Variable
SensorOut Voltage NumDat

Data type
BOOL REAL UINT

Initial value
FALSE 0.0 UINT#0

Comment
Sensor output Voltage Current number of stored data

External Variables

Variable
Recent Stack

Data type
Record ARRAY[0..99] OF Record

Comment
Present value Stack

Record date and time and voltage

SensorOut

GetTime

EN

ENO

_MILLISEC

TruncDt

EN

ENO

In

Accuracy

Recent.DandT

Voltage

MOVE

EN

ENO

In

Out

Recent.Voltage

Recent
Stack[0] UINT#100
NumDat

StackPush

EN In InOut

ENO

Size Num

ST
Internal Variables

Variable
Trigger SensorOut Voltage NumDat

R_TRIG_instance

Data type

Initial value

BOOL BOOL REAL UINT

FALSE FALSE 0.0 UINT#0

R_TRIG

Comment
Trigger Sensor output Voltage Current number of stored data

External Variables

Variable
Recent Stack

Data type
Record ARRAY[0..99] OF Record

Comment
Present value Stack

2-664

NJ/NX-series Instructions Reference Manual (W502)

Time and Time of Day Instructions

2 Instruction Descriptions

// Activate trigger when sensor output turns ON. R_TRIG_instance(SensorOut, Trigger);

IF (Trigger=TRUE) THEN

// Store the current date and time down to the milliseconds.

Recent.DandT:=TruncDt(

In

:=GetTime(), // Get the date and time.

Accuracy:=_MILLISEC); // Accuracy is milliseconds.

// Get current voltage. Recent.Voltage:=Voltage;

// Record date and time and voltage in stack. StackPush(

2

In :=Recent, // Date and time, and voltage

InOut:=Stack[0], // Stack array

TruncDt

Size :=UINT#100, // Number of stack array elements: 100

Num :=NumDat); // Number of data currently stored

END_IF;

NJ/NX-series Instructions Reference Manual (W502)

2-665

2 Instruction Descriptions

TruncTod

The TruncTod instruction truncates a TOD variable below the specified time unit.

Instruction TruncTod

Name
Truncate Time of Day

FB/FUN FUN

Graphic expression

(@)TruncTod

EN

ENO

In

Out

Accuracy

ST expression
Out:=TruncTod(In, Accuracy);

Variables

Name In
Accuracy

Meaning

I/O

Time of day to truncate

Smallest unit after truncation

Input

Out

Time of day Output

after

truncation

Description Time of day to truncate The smallest time unit to leave after truncation
Time of day after truncation

Valid range Depends on data type.
_NANOSEC, _MICROSEC, _MILLISEC, _SEC Depends on data type.

Unit

Default

Hour, min- TOD#0:0 utes, seconds :0

---

_NANO-

SEC

Hour, min- --utes, seconds

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In Accuracy Out

OK Refer to Function for the enumerators of enumeration type _eSUBSEC.
OK

Function

The TruncTod instruction truncates all digits below the smallest unit after truncation that is specified in Accuracy from the time of day to truncate in In. The resulting time of day after truncation is stored in time of day after truncation Out.

The data type of Accuracy is enumerated type _eSUBSEC. The meanings of the enumerators are as follows:

Enumerator _NANOSEC _MICROSEC _MILLISEC _SEC

Meaning Nanoseconds Microseconds Milliseconds Seconds

2-666

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Time and Time of Day Instructions

The following example is for when In is TOD#12:34:56.789012345 and Accuracy is _MILLISEC.

LD

ST

TruncTod

EN

ENO

TOD#12:34:56.789012345 In

abc

_MILLISEC Accuracy

abc:=TruncTod(TOD#12:34:56.789012345, _MILLISEC);

All digits below the In TOD#12:34:56.789012345 milliseconds are truncated.

Accuracy _MILLISEC

Out=abc TOD#12:34:56.789

2

TruncTod

Additional Information
Before you compare two TOD variables with the EQ (=) instruction (page 2-92) or other instructions, use the TruncTod instruction to convert the two variables to the same accuracy.

Precautions for Correct Use

Version Information
A CPU Unit with unit version 1.01 or later and Sysmac Studio version 1.02 or higher are required to use this instruction.

Sample Programming
The following programming example records the time of day and the current voltage when a sensor output turns ON. The time of day is recorded in seconds. The sensor output is stored in SensorOut and the voltage is stored in Voltage. The current time of day is obtained with the GetTime and DT_TO_TOD instructions. The times of day and the voltages are stored in order in a Stack variable as Recent structures whose members are the time of day and corresponding voltage.

Definitions of Global Variables

Data Types
Variable Record TofD Voltage

Data type STRUCT TOD REAL

Comment Structure Time of day Voltage

Global Variables

Variable Recent Stack

Data type Record ARRAY[0..99] OF Record

Initial value (TofD:=TOD#0:0:0,Voltage:=0.0) [100((TofD:=TOD#0:0:0,Voltage:=0.0))]

NJ/NX-series Instructions Reference Manual (W502)

Comment Present value Stack
2-667

2 Instruction Descriptions

LD
Internal Variables

Variable
SensorOut Voltage NumDat

Data type
BOOL REAL UINT

Initial value
FALSE 0.0 UINT#0

Comment
Sensor output Voltage Current number of stored data

External Variables

Variable
Recent Stack

Data type
Record ARRAY[0..99] OF Record

Comment
Present value Stack

Record time of day and voltage

SensorOut

GetTime

EN

ENO

DT_TO_TOD

EN

ENO

In

_SEC

TruncTod

EN

ENO

In

Accuracy

Recent.TofD

Voltage

MOVE

EN

ENO

In

Out

Recent.Voltage

Recent
Stack[0] UINT#100
NumDat

StackPush

EN In InOut

ENO

Size Num

ST
Internal Variables

Variable
Trigger SensorOut TmpTod Voltage NumDat

R_TRIG_instance

Data type
BOOL BOOL TOD REAL UINT

Initial value
FALSE FALSE TOD#0:0:0 0.0 UINT#0

R_TRIG

Comment
Trigger Sensor output Temporary variable Voltage Current number of stored data

External Variables

Variable
Recent Stack

Data type
Record ARRAY[0..99] OF Record

Comment
Present value Stack

2-668

NJ/NX-series Instructions Reference Manual (W502)

Time and Time of Day Instructions

2 Instruction Descriptions

// Activate trigger when sensor output turns ON. R_TRIG_instance(SensorOut, Trigger);

IF (Trigger=TRUE) THEN

// Store the current time of day down to the seconds.

TmpTod

:=DT_TO_TOD(GetTime()); // Get time of day.

Recent.TofD:=TruncTod(

In

:=TmpTod,

Accuracy:=_SEC); // Accuracy is seconds.

// Get current voltage. Recent.Voltage:=Voltage;

// Record time of day and voltage in stack.

2

StackPush(

In :=Recent, // Time of day and voltage

TruncTod

InOut:=Stack[0], // Stack array

Size :=UINT#100, // Number of stack array elements: 100

Num :=NumDat); // Number of data currently stored

END_IF;

NJ/NX-series Instructions Reference Manual (W502)

2-669

2 Instruction Descriptions

2-670

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

2
Analog Control Instructions

Instruction PIDAT PIDAT_HeatCool TimeProportionalOut LimitAlarm_** LimitAlarmDv_** LimitAlarmDvStbySeq_**
ScaleTrans AC_StepProgram

Name PID Control with Autotuning Heating/Cooling PID with Autotuning Time-proportional Output Upper/Lower Limit Alarm Group Upper/Lower Deviation Alarm Group Upper/Lower Deviation Alarm with Standby Sequence Group Scale Transformation Step Program

Page 2-672 2-697 2-735 2-752 2-756 2-761
2-776 2-779

NJ/NX-series Instructions Reference Manual (W502)

2-671

2 Instruction Descriptions

PIDAT

The PIDAT instruction performs PID control with autotuning (2-PID control with set point filter).

Instruction

Name

FB/FUN

Graphic expression

ST expression

PIDAT

PID Control with

FB

Autotuning

PIDAT_instance

PIDAT

Run

ATDone

ManCtl

ATBusy

StartAT

Error

PV

ErrorID

SP

MV

OprSetParams

InitSetParams

ProportionalBand

IntegrationTime

DerivativeTime

ManMV

PIDAT_instance( Run, ManCtl, StartAT, PV, SP, OprSetParams, InitSetParams, ProportionalBand, IntegrationTime, DerivativeTime, ManMV, ATDone, ATBusy, Error, ErrorID, MV);

Variables

Name

Meaning

I/O

Run

Execution

condition

ManCtl

Manual/auto control

StartAT
PV SP OprSet Params
InitSet Params Proportiona l Band IntegrationTime

Autotuning execution condition
Process value
Set point
Operation setting parameters
Initial setting parameters
Proportional band
Integration time

Input

In-out DerivativeT Derivative time ime

ManMV

Manual manipulated variable

Description TRUE: Execute FALSE: Stop TRUE: Manual operation FALSE: Automatic operation TRUE: Execute FALSE: Cancel
Process value Set point Parameters set during operation
Initial setting parameters

Valid range

Unit

Depends on data type.
--*1
---

Default FALSE 0 ---

Proportional band

0.01 to 1000.00

% FS

Integration time

T#0.0000s to

The higher the value is, the

T#10000.0000s*2

weaker the integral action is.

No integral action is performed

for 0. Derivative time

T#0.0000s to

s

---

The higher the value is, the

T#10000.0000s*2

stronger the derivative action is.

No derivative action is per-

formed for 0.

Manual manipulated variable -320 to 320

%

2-672

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

PIDAT

2 Instruction Descriptions

Name

Meaning

I/O

Description

Valid range

Unit Default

ATDone

Autotuning

TRUE: Normal completion

normal completion

FALSE: *3

Depends on data type. ---

ATBusy

Autotuning

Output TRUE: Autotuning

---

busy

FALSE: Not autotuning

MV

Manipulated

variable

Manipulated variable

-320 to 320

%

*1 Value of input range lower limit InitSetParams.RngLowLmt to Value of input range upper limit InitSetParams.RngUpLmt

*2 Digits below 0.0001 s are truncated.

*3 FALSE indicates an error end, that PID control is in progress without autotuning, or that PID control is not in progress.
2

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

Run

OK

ManCtl

OK

StartAT

OK

PV

SP

OprSet Params

InitSet Params

Proportiona l Band

Integration Time

DerivativeT ime

ManMV

ATDone

OK

ATBusy

OK

MV

OK OK Refer to Function for details on the structure _sOPR_SET_PARAMS. Refer to Function for details on the structure _sINIT_SET_PARAMS. OK
OK OK OK
OK

Function
The PIDAT instruction performs PID control of a manipulated variable for a temperature controller or other device. PID control is started when the value of execution condition Run changes to TRUE. While the value of Run is TRUE, the following process is repeated periodically: process value PV is read, PID processing is performed, and manipulated variable MV is output. PID control is stopped when the value of Run changes to FALSE.
Autotuning is supported to automatically find the optimum PID constants. When the value of the autotuning execution condition StartAT changes to TRUE, the PID constants are autotuned.

NJ/NX-series Instructions Reference Manual (W502)

2-673

2 Instruction Descriptions

Structure Specifications

The data type of operation setting parameter OprSetParams is structure _sOPR_SET_PARAMS. The specifications are as follows:

Name

Meaning

Description

Data type Valid range Unit Default

OprSetParams

Operation Setting Parameters

MVLowLmt MV Lower Limit

MVUpLmt

MV Upper Limit

ManResetVal Manual Reset Value

MVTrackSw MVTrackVal StopMV

MV Tracking Switch
MV Tracking Value
Stop MV

ErrorMV

Error MV

Alpha

2-PID Parameter 

ATCalcGain

Autotuning Calculation Gain

ATHystrs

Autotuning Hysteresis

Parameters that are set during operation.
The lower limit of the MV.
The upper limit of the MV.
The value of MV when the deviation is 0 for the proportional action.
TRUE: ON
FALSE: OFF
The value that is set in MV during MV tracking.
The value that is set in MV when instruction execution is stopped.
The value that is set in MV when an error occurs.
The set point filter is disabled if the set point filter coefficient  is 0.
Adjustment coefficient from autotuning results. Stability is given higher priority with higher values. The speed of response is given higher priority with lower values.
The hysteresis of the limit cycle.

_sO-

---

PR_SET_PAR

AMS

REAL

REAL

-320 to 320*

REAL

-320 to 320

BOOL REAL REAL
REAL

Depends on data type.
-320 to 320

REAL

0.00 to 1.00

REAL

REAL

0.1 to 10.0

---

---

0
100 %
0

---

FALSE

0

%

0.65
1.0 ---

% FS 0.2

* MVLowLmt must be less than MVUpLmt.
The data type of initial setting parameter InitSetParams is structure _sINIT_SET_PARAMS. The specifications are as follows:

Name InitSetParams
SampTime RngLowLmt RngUpLmt

Meaning Initial Setting Parameters
Sampling Period Lower Limit of Input Range Upper Limit of Input Range

Description

Data type

Initial setting parameters. _sINIT_SET_PAR AMS

The period for PID pro- TIME cessing.

The lower limit of PV and REAL SP.

The upper limit of PV and REAL SP.

Valid range
---
T#0.0001s to #100.0000s
-32000 to 32000*

Unit Default

---

---

s

T#0.1s

0

---

100

DirOpr

Action Direction

TRUE: Forward action BOOL FALSE: Reverse action

Depends on data type.

FALSE

* RngLowLmt must be less than RngUpLmt.

2-674

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

PIDAT

2 Instruction Descriptions

Meanings of Variables
The meanings of the variables that are used in this command are described below.

 Run (Execution Condition)
This is the execution condition for the instruction. PID control is performed while the value is TRUE. PID control is stopped when the value changes to FALSE.

 ManCtl (Manual/Auto Control)

This instruction can be executed in one of two modes: Manual operation or automatic operation. The

value of ManCtl determines which mode is used.

2

Value of ManCtl

Operation mode

Value of MV

TRUE

Manual

Value of ManMV (PID control is not performed.)

FALSE

Automatic

Value that is calculated for PID control

 StartAT (Autotuning Execution Condition)
This is the execution condition for autotuning the PID constants. If the value of StartAT is TRUE when the value of Run changes to TRUE, autotuning is performed when PID control is started. If the value of StartAT changes to TRUE during PID control (i.e., when the value of Run is TRUE), autotuning is performed during PID control. In either case, autotuning is canceled if the value of StartAT changes to FALSE during autotuning. Autotuning is described in more detail later.

 PV (Process Value)
This is the process value of the controlled system.

 SP (Set Point)
This is the set point for the controlled system.

 MVLowLmt (MV Lower Limit) and MVUpLmt (MV Upper Limit)

You can limit the value of MV. MVLowLmt and MVUpLmt are the lower and upper limits to MV. MVLowLmt must always be less than MVUpLmt.

MV from PID processing Less than MVLowLmt Between MVLowLmt and MVUpLmt, inclusive Greater than MVUpLmt

Value of MV MVLowLmt MV from PID processing MVUpLmt

If stop MV StopMV, error MV ErrorMV, or manual MV ManMV is set in manipulated variable MV, limit control is not applied.
You can change MVLowLmt or MVUpLmt even if the control status of this instruction is not autotuning during automatic operation.
However, if you change MVLowLmt or MVUpLmt to an expansion direction during operation, the value of MV which is the same as one in the last sampling period is output and changed smoothly at this time (bumpless).
Repeated changing of MVLowLmt or MVUpLmt will effect the control performance so that sufficient control performance may not obtain.
Confirm the effects on the control performance before you repeatedly change MVLowLmt or MVUpLmt during operation.

NJ/NX-series Instructions Reference Manual (W502)

2-675

2 Instruction Descriptions
 ManResetVal (Manual Reset Value)
This is the value of MV when the deviation (i.e., the difference between PV and SP) is 0 for the proportional action. The value of ManResetVal determines the location of the proportional action band. When integral operation is performed, the manual reset value is ignored. Therefore, the setting of ManResetVal is enabled when the value of IntegrationTime is 0.
 MVTrackSw (MV Tracking Switch)
MV tracking is a function that sets the MV to an external input value (called the MV tracking value) during automatic operation. MV tracking is performed while the value of MVTrackSw is TRUE. When the value of MVTrackSw changes to FALSE, the value of MV returns to the result of PID processing. The value of MV is changed smoothly at this time (bumpless).
MV
MVTrackVal
Time
MVTrackSw = TRUE MVTrackSw = FALSE
 MVTrackVal (MV Tracking Value)
This is the value to which MV is set during MV tracking. The value of MVTrackVal is limited by the values of MVLowLmt and MVUpLmt.
 StopMV (Stop MV)
This is the value to which MV is set when the value of Run is FALSE (i.e., when execution of this instruction is stopped).
 ErrorMV (Error MV)
This is the value to which MV is set when an error occurs (i.e., when the value of Error is TRUE). If the value of ErrorMV is not within the valid range (-320 to 320), the value of MV will be 0 when an error occurs.
 Alpha (2-PID Parameter )
This parameter determines the coefficient of the set point filter. Refer to the description in 2-PID Control with Set Point Filter on page 2-682 for details. Normally set the value of Alpha to 0.65.
 ATCalcGain (Autotuning Calculation Gain)
This variable gives the coefficient of the PID constants that were calculated by autotuning when they are applied to the actual PID constants. If a value of 1.00 is specified, the results of autotuning are used directly. Increase the value of ATCalcGain to give priority to stability and decrease it to give priority to response.
 ATHystrs (Autotuning Hysteresis)
This is the hysteresis that is used in the limit cycle for autotuning. More accurate tuning is achieved if the value of ATHystrs is small. However, if the process value is not stable and proper autotuning is difficult, increase the value. Refer to the description of autotuning for details.

2-676

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Analog Control Instructions

PIDAT

 SampTime (Sampling Period)
This is the minimum value of the period for PID processing. Refer to the description of the execution timing of PID processing for details. PID processing is not performed again until the time specified for SampTime has elapsed since the last time PID processing was performed.

 RngLowLmt (Lower Limit of Input Range) and RngUpLmt (Upper Limit of Input Range)
These are the lower limit and upper limit of PV and SP. An error will occur if the value of the parameter connected to PV or SP exceeds either of these limits. RngLowLmt must always be less than RngUpLmt.

 DirOpr (Action Direction)

2

This variable specifies if MV is increased or decreased for changes in the value of PV. These are called a forward action and a reverse action.

Value of DirOpr TRUE FALSE

Meaning Forward action Reverse action

Value of MV Increases with the value of PV. Decreases with the value of PV.

The difference between a forward action and reverse action are described here for temperature control. A forward action is used to control the MV for a cooling device. That is, the higher the process temperature, the larger the MV of the cooling device must be. On the other hand, a reverse action is used to control the MV for a heating device. That is, the lower the process temperature, the larger the MV of the heating device must be.
Forward Action (DirOpr = TRUE) MV
MVUpLmt

MVLowLmt

Cooling device The MV increases as the proc
PV

MV MVUpLmt

Reverse Action (DirOpr = FALSE)
Heating device The MV increases as the proc

MVLowLmt
PV
 ProportionalBand (Proportional Band)
This is one of the three PID constants. Refer to the description of the proportional action for details. The larger the ProportionalBand is, the greater the offset is. Hunting occurs if the ProportionalBand is too small.
 IntegrationTime (Integration Time)
This is one of the three PID constants. Refer to the description of the integral action for details. The larger the value of IntegrationTime is, the weaker the integral action is.

NJ/NX-series Instructions Reference Manual (W502)

2-677

2 Instruction Descriptions

 DerivativeTime (Derivative Time)
This is one of the three PID constants. Refer to the description of the derivative action for details. The larger the value of DerivativeTime is, the stronger the derivative action is.
 ManMV (Manual Manipulated Variable)
MV is set to this value during manual operation (while ManCtl is TRUE). However, immediately after changing from automatic to manual operation, the value of MV from automatic operation is used. MV is set to the value of ManMV only when it changes after operation switches to manual operation. When operation changes from manual to automatic operation, the value of MV from manual operation is used. The value of ManMV does not have to be between MVLowLmt and MVUpLmt.
Value of MV from automatic operation used.
MV

Value of MV from manual operation used.

ManCtl changed to TRUE.

Time ManCtl changed to FALSE.

Value of ManMV changed.
 ATDone (Autotuning Normal Completion)
This flag indicates when autotuning was completed normally. It changes to TRUE when autotuning is completed normally and remains TRUE as long as the value of StartAT is TRUE. It is FALSE in the following cases. · An autotuning error end occurred. · Autotuning is in progress (i.e., while the value of ATBusy is TRUE). · PID control is in progress without autotuning. · PID control is not in progress (i.e., the value of Run is FALSE). · The value of StartAT is FALSE.

 ATBusy (Autotuning Busy)
This flag indicates when autotuning is in progress. It is TRUE while autotuning is in progress. Otherwise it is FALSE.

 MV (Manipulated Variable)
This is the manipulated variable that is applied to the controlled system.

Introduction to PID Control
PID control is a feedback control method that repeatedly measures the process value of the controlled system and calculates a manipulated variable so that the process value approaches a set point. This instruction therefore outputs a manipulated variable for the following inputs: process value, set point, and calculation parameters. PID control periodically measures the process value, calculates the manipulated variable, and outputs the manipulated variable so that the process value approaches the set point.

2-678

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

PIDAT

2 Instruction Descriptions

Set point Parameters

Process value

Repeatedly executed.

PID processing

Manipulated variable

Controlled system

Proportional (P), Integral (I), and Derivative (D) Actions

PID control is performed by combining the proportional action, integral action, and derivative action.

These actions are described next.

2

 Proportional Action (P)

The proportional action increases the absolute value of the manipulated variable in proportion to the deviation between the process value and the set point. The process value of the controlled system changes as shown below.

Process value A small deviation produces a small MV, which produces a small change in the process value.

Set point

Time
A large deviation produces a large MV, which produces a large change in the process value.

The proportional band is one of the settings that are used for the proportional action. The proportional band is the range of the process value to which the proportional action is applied. If the process value is not in the proportional band, the manipulated variable is set to 100% or 0%. The proportional band is expressed as the percentage of the input range in which to perform the proportional action (% FS). The following diagram shows the proportional band set to 10% FS.

Manipulated variable

100% FS input range
Proportional band at 10% FS

100%

0%

Lower limit of input range

Process value Upper limit of input range

Another parameter for the proportional action is the manual reset value. The manual reset value is the manipulated variable that is used when the deviation is 0. The manual reset value determines the position of the proportional action range in the process value-manipulated variable graph. The relationship between the manual reset value and the proportional action region is shown below.
The position of the proportional action range is determined so that the manipulated variable when the process value and the set point are the same equals the manual reset value.

NJ/NX-series Instructions Reference Manual (W502)

2-679

2 Instruction Descriptions

Manipulated variable
100% a b
0%

Proportional action region when the manual reset value is a.
The position of the proportional action range is determined so that the manipulated variable when the process value and the set point are the same equals the manual reset value.

Process value Set point
Proportional action region when the manual reset value is b.

If the manual reset value is not suitable, the deviation will never reach 0. The remaining deviation is called the offset or the residual deviation. You can make the proportional band narrower to reduce the offset. If the proportional band is too narrow, the process value will not stop at the set point. This is called overshooting. If the process value does not stabilize and oscillates around the set point, it is called hunting.

Process value

Proportional band is too narrow (hunting occurs).

Set point

Offset

The proportional band is suitable.

Proportional band is too wide Time (there is a large offset).

 Integral Action (I)

Very accurate adjustment of the proportional band and manual reset value is required to bring the offset to 0 with only the proportional action. Also, the size of the offset varies with the disturbance, so it is necessary to repeat the adjustment frequently. To simplify the operation, an integral action is used in combination with the proportional action. The integral action integrates the deviation on the time axis and then increases the absolute value of the manipulated variable in proportion to the result. When normal distribution operation is performed, the manual reset value is ignored. The following graph on the left shows changes in the manipulated variable for the integral action when a deviation occurs in stepwise fashion. The following graph on the right shows changes in the manipulated variable when the integral and proportional actions are combined.

Manipulated Variable for Integral Action

Manipulated Variable for Integral and Proportional Actions Together

Stepwise response Deviation 0

Stepwise response Deviation 0

Manipulated variable Manipulated variable

Time

Time

Proportional and integral actions

Integral action only

Proportional action only

0

0

Time

Time

2-680

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Analog Control Instructions

PIDAT

One of the parameters for the integral action is the integration time. This is the time for the manipulated variable from the integral action to equal the manipulated variable from the proportional action when a stepwise deviation occurs. The shorter the integration time is, the stronger the integral action is. A short integration time reduces the time for the offset to reach 0, but it can also cause hunting.
Stepwise response Deviation 0

Time

Manipulated

Proportional and integral actions

variable

Integral action only

Proportional action only

2

0 Integration time

Time

 Derivative Action (D)
If the proportional and integral actions are used together, the offset will reach 0 and the process value will reach the set point. However, if disturbance causes the process value to change quickly, time is required to restore the original state. The derivative action functions to quickly return the process value to the set point when there is a disturbance. The derivative action differentiates the deviation on the time axis and then increases the absolute value of the manipulated variable in proportion to the result. In other words, the larger the change in the process value is, the larger the absolute value of the manipulated variable for the derivative action is. The changes in the manipulated variable for the derivative action when a deviation occurs in stepwise fashion are shown below. The changes in the manipulated variable when the derivative and proportional actions are combined are also shown.

Manipulated Variable for Derivative Action

Manipulated Variable for Derivative and Proportional Actions Together

Deviation Stepwise response 0

Deviation Stepwise response 0

Manipulated variable
0

Time

Time

Manipulated

variable

Proportional and derivative actions

Time

0 Proportional action only Time
Derivative action only

One of the parameters for the derivative action is the derivative time. This is the time for the manipulated variable from the derivative action to equal the manipulated variable from the proportional action when a ramp deviation occurs. The longer the derivative time is, the stronger the derivative action is. A long derivative time provides a rapid response to disturbances, but it can also cause hunting.
Deviation Ramp response 0

Manipulated variable
0

Derivative time

Time Proportional and derivative actions Proportional action Derivative action
Time

NJ/NX-series Instructions Reference Manual (W502)

2-681

2 Instruction Descriptions

The total of the manipulated variables for the proportional, integral, and derivative actions is the manipulated variable for PID control. The changes in the manipulated variable for PID control for a stepwise and ramp deviations are shown below.

Deviation Stepwise response
0

Deviation Ramp response
0

Manipulated variable
0 Derivative action only

Time
Manipulated PID control variable Integral action only Proportional action only
0 Time

Time PID control Integral action only Derivative action only
Time Proportional action only

2-PID Control with Set Point Filter

There are three main parameters that you must adjust to perform PID control: the proportional band, integration time, and derivative time. These are called the PID constants. The values of the PID constants affect the following two performances of PID control.
· Set point response: The ability to follow changes in the set point.
· Disturbance response: The ability of correcting the process value for large changes that are caused by disturbances
A block diagram for basic PID control is shown below. The set point and disturbance enter the block diagram at different positions. Therefore, finding the optimum PID constants for both set point response performance and disturbance response performance is difficult. In other words, if the PID constants are set for set point response, response to disturbances is slow. If the PID constants are set for disturbance response, overshooting occurs.

Set point

+ Deviation -

P+I

Disturbance

Manipulated

+ variable

+

-

+

Controlled Process value system

D

To enable both set point response and disturbance response, 2-PID control is used. The 2 in "2-PID" indicates that there are separate parameters to adjust the set point response and the disturbance response. A block diagram for this is shown below. A set point filter that includes an adjustment parameter is added. The PID constants are adjusted to maximize disturbance response. A set point filter adjusts the set point to optimize the set value response for those values. You can adjust the values of the PID constants and the set value of the set point filter independently to increase both the set point response and the disturbance response.

Adjustment for set point response

Adjustment for disturbance response

Disturbance

Set point

Manipulated

Set point filter

+ Deviation -

P+I

+ variable

+

-

+

Controlled system

Process value

D

2-682

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

2 Instruction Descriptions

The formulas of the blocks of this instruction are shown below. The set point filter value (i.e., a coeffi-
cient for the set point) is adjusted by using the integration time and the 2-PID parameter . The optimum value of  is 0.65. It normally does not need to be changed. The lower the value of  is, the smaller the influence of the set point filter is.

Set point

Set point filter
1 + (1-)Ti  s 1 + Ti  s

Proportional +

Disturbance

integral components

Manipulated

+ Deviation Kp + Kp

+ variable

+

-

Ti  s -

+

Controlled system

Process value Kp: Proportional constant

Advanced derivative

Ti: Integration time

component

Td: Derivative time

Kp  Td  s

s: Laplace operator

1 +   Td  s

: 2-PID parameter : Incomplete derivative coefficient
2

Starting PID Control
You must use suitable PID constants to execute this instruction. There are the following two ways to achieve this.
 When Suitable PID Constants Are Not Known
Perform autotuning at the start of operation to find suitable PID constants. Change the value of Run to TRUE while the value of StartAT is TRUE. First, autotuning is executed, and then PID control is started with the PID constants that are found.
 When Suitable PID Constants Are Known
Set suitable PID constants in ProportionalBand, IntegrationTime, and DerivativeTime, and then change Run to TRUE. ProportionalBand, IntegrationTime, and DerivativeTime are in-out variables. You cannot set constants for the input parameters. Always define suitable variables, and then assign the values to input parameters.
You can change the PID constants during operation. You can also perform autotuning during operation. To start autotuning during operation, change the value of StartAT to TRUE.

PIDAT

NJ/NX-series Instructions Reference Manual (W502)

2-683

2 Instruction Descriptions

Control Status and Manipulated Variable

Manipulated variable MV is determined according to the control status as shown in the following table.

Control status
Error end MV tracking during automatic operation Autotuning during automatic operation

ManCtl (manual/auto control)
FALSE

Not autotuning during automatic operation
Instruction execution stopped
Manual operation

TRUE

Value of variable

Run (execution con-
dition)

Error (error end)

MVTrackSw (MV tracking
switch)

ATBusy (autotuning busy)

TRUE

---
TRUE

FALSE

TRUE

FALSE

FALSE

TRUE

FALSE

FALSE

---

---

---

Manipulated variable MV
ErrorMV (error MV) MVTrackVal (MV tracking value)
Value repeatedly changes between upper limit of MV and lower limit of MV. Value calculated with current PID constants. StopMV (Stop MV)
ManMV (manual manipulated variable)

Autotuning
The 2-PID parameter  is not adjusted very often, so the main parameters that are adjusted for this instruction are the PID constants. The PIDAT instruction supports autotuning of the PID constants. The limit cycle method is used for autotuning. With the limit cycle method, the manipulated variable is temporarily changed to the upper and lower limits of the manipulated variable to find the optimum PID constants based on the resulting changes in the process value. If autotuning is executed when the set point is greater than the process value, the manipulated variable is first set to the upper limit. When the deviation reaches 0, the manipulated variable is set to the lower limit. When the deviation becomes greater than the autotuning hysteresis, the manipulated variable is set to the upper limit again. This process is repeated twice to calculate the optimum PID constants.
If autotuning is executed when the set point is less than the process value, the manipulated variable is first set to the lower limit. Then, the optimum values for the PID constants are calculated with the procedure that is given above.

2-684

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

PIDAT

2 Instruction Descriptions

Set point

Autotuning executed. Process value

Autotuning hysteresis

Manipulated variable

Time

MV upper limit

2

MV lower limit
Time
The manipulated variable is set to the MV upper limit.
When the deviation reaches 0, the manipulated variable is set to the MV lower limit.
When the deviation becomes greater than the autotuning hysteresis, the manipulated variable is set to the MV upper limit again.
Autotuning is executed during PID control (i.e., when the value of Run is TRUE) if the value of StartAT changes to TRUE. If StartAT is TRUE when Run changes to TRUE, autotuning is executed at the start of PID control. When autotuning is completed normally, the calculated PID constants are used immediately. Autotuning is canceled if the value of StartAT changes to FALSE during autotuning (i.e., when ATBusy is TRUE). If autotuning is canceled, PID control is started again with the previous PID constants.

Execution Timing of PID Control
PID control is repeated periodically. PID processing is performed when the PIDAT instruction is executed in the user program. However, if sampling period SampTime has not elapsed since the last time PID processing was performed, PID processing is nor performed. If the elapsed time since the last time PID processing was executed exceeds SampTime, the excess time (elapsed time - SampTime) is carried forward to the next period. This is shown in the following diagram.
Task period = 60 ms and SampTime < 60 ms
The task period is greater than or equal to SampTime, so PID processing is executed once every task period.

Task period

Task period

Task period

Task period

Task period

PIDAT

PIDAT

PIDAT

PIDAT

AutoPID

60 ms

60 ms

60 ms

60 ms

PID processing executed.

PID processing executed.

PID processing executed.

PID processing executed.

PID processing executed.

Time

NJ/NX-series Instructions Reference Manual (W502)

2-685

2 Instruction Descriptions

Task period = 60 ms and SampTime = 100 ms The task period is less than SampTime, so DIP processing is not executed every period.

Task period

Task period

Task period

Task period

Task period

PIDAT

PIDAT

PIDAT

PIDAT

PIDAT

60 ms

60 ms

60 ms

60 ms

PID processing
executed. Time

PID processing not executed.

PID processing executed.

PID processing not executed.

PID processing executed.

Not executed because elapsed time (60 ms) < 100 ms.
Executed because elapsed time (60 + 60 ms = 120 ms) > 100 ms. The remaining 20 ms is carried over.

Executed because elapsed time (80 + 60 ms = 140 ms) > 100 ms. The remaining 40 ms is carried over.

Not executed because elapsed time (20 + 60 ms = 80 ms) < 100 ms.

Timing Charts
Timing charts for the instruction variables are provided below for different situations.

 Autotuning Executed during Automatic Operation
Run TRUE FALSE

StartAT ATBusy

TRUE FALSE
TRUE FALSE

ATDone

TRUE FALSE

PV

SP

Time MV

StopMV

PID processing

PID processing

Time

Autotuning
PID constants updated for results of autotuning.

MV set to StopMV.

2-686

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

2 Instruction Descriptions

 Autotuning Executed at the Start of PIDAT Execution
Run TRUE FALSE

StartAT ATBusy

TRUE FALSE
TRUE FALSE

ATDone TRUE FALSE

PV

SP

2

MV StopMV

Time

Autotuning

PID processing

Time

PID constants updated for MV set to StopMV. results of autotuning.

PIDAT

NJ/NX-series Instructions Reference Manual (W502)

2-687

2 Instruction Descriptions

 Autotuning Canceled
Run TRUE FALSE

StartAT TRUE FALSE
ATBusy TRUE FALSE

ATDone

TRUE FALSE

PV SP

ATBusy also changes to FALSE when autotuning is canceled.
ATDone remains FALSE.

Time MV

StopMV

PID processing

PID processing

Time

Autotuning
Autotuning canceled. MV set to StopMV. The PID constants from before autotuning was started are set.

2-688

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

PIDAT

2 Instruction Descriptions

 An Autotuning Error Occurs during Autotuning
An autotuning error occurs and autotuning is stopped in the following cases. · If the MV equals the MV upper limit and the time for the deviation to reach 0 exceeds 19,999 s. · If the MV equals the MV lower limit and the time for the deviation to reach ATHystrs or higher
exceeds 19,999 s.
If autotuning is canceled, PID control is started again with the previous PID constants.

Run

TRUE FALSE

StartAT ATBusy ATDone

TRUE FALSE
TRUE FALSE
TRUE FALSE

PV

SP

2
ATBusy changes to FALSE as soon as an error occurs. ATDone remains FALSE.

Time MV

StopMV

PID processing

PID processing

Time

Autotuning

Error occurs.

MV is set to StopMV.

The PID constants from before

autotuning was started are set.

Additional Information

Adjusting PID Constants
· If you need to eliminate hunting even if it takes time to stabilize the control system, increase the value of ProportionalBand. If a certain amount of hunting is not a problem, but it is necessary for the controlled system to stabilize quickly, decrease the value of ProportionalBand.
PV Small ProportionalBand.
SP
Large ProportionalBand.
Time

NJ/NX-series Instructions Reference Manual (W502)

2-689

2 Instruction Descriptions

· If hunting continues too long, increase ProportionalBand or increase IntegrationTime.
PV

SP Increase ProportionalBand or increase IntegrationTime.
Time
· If rapid hunting occurs, decrease DerivativeTime.
PV

SP Decrease DerivativeTime.

Time

Initial PID Constants for Temperature Control

If you use the PIDAT instruction for temperature control, use the following initial values of the PID constants as reference. Use the default values for the other variables.

Variables

Initial values (reference values)*

ProportionalBand

10%FS

IntegrationTime

233 s

DerivativeTime

40 s

* If you perform autotuning, use the results from autotuning.

Precautions for Correct Use

· The values of PV and SP must be between the values of RngLowLmt and RngUpLmt, inclusive. Align the units of these variables as shown below.

Unit

Values of PV and SP

Values of RngLowLmt and RngUpLmt

% FS
Physical unit

PV = (Process value in physical units - MIN)/(MAX - MIN) × 100 SP = (Set point in physical units - MIN)/(MAX - MIN) × 100* PV = Process value in physical units SV = Set point in physical units

RngLowLmt = 0 RngUpLmt = 100 RngLowLmt = MIN RngUpLmt = MAX*

* MAX: Upper limit of input range in physical units, MIN: Lower limit of input range in physical units,

· The following table shows which variables can be changed depending on the operating status.

Variables
Run ManCtl StartAT PV SP MVLowLmt

Instruction execution stopped*1
Possible Possible Possible Possible Possible Possible

Control status Automatic operation when autotuning is not
being executed*2 Possible Possible Possible Possible Possible Possible

Automatic operation when autotuning is being
executed*3 Possible Possible Possible Possible Not possible Not possible

2-690

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

PIDAT

2 Instruction Descriptions

Control status

Variables

Instruction execution stopped*1

Automatic operation when autotuning is not
being executed*2

Automatic operation when autotuning is being
executed*3

MVUpLmt

Possible

Possible

Not possible

ManResetVal

Possible

Possible

Not possible

MVTrackSw

Possible

Possible

Not possible

MVTrackVal

Possible

Possible

Not possible

StopMV

Possible

Possible

Possible

ErrorMV

Possible

Possible

Possible

Alpha

Possible

Possible

Not possible

2

ATCalcGain

Possible

Possible

Not possible

ATHystrs

Possible

Possible

Not possible

SampTime

Possible

Not possible

Not possible

RngLowLmt

Possible

Not possible

Not possible

RngUpLmt

Possible

Not possible

Not possible

DirOpr

Possible

Not possible

Not possible

ProportionalBand

Possible

Possible

Not possible

IntegrationTime

Possible

Possible

Not possible

DerivativeTime

Possible

Possible

Not possible

ManMV

Possible

Possible

Possible

*1 ManCtl is TRUE, Run is FALSE, Error is TRUE, or MVTrackSw is TRUE.
*2 ManCtl is FALSE, Run is TRUE, Error is FALSE, MVTrackSw is FALSE, and ATBusy is FALSE.
*3 ManCtl is FALSE, Run is TRUE, Error is FALSE, MVTrackSw is FALSE, and ATBusy is TRUE.
· SampTime is truncated below 100 nanoseconds.
· If the value of StartAT changes to TRUE while the value of ManCtl is TRUE, autotuning starts the next time the value of ManCtl changes to FALSE.
· If the value of ErrorMV is not within the valid range (-320 to 320), the value of MV will be 0 when an error occurs.
· Autotuning is canceled if the value of ManCtl changes to TRUE during autotuning.
· The value of Error does not change to TRUE even if an error occurs during autotuning.
· An error occurs in the following case. Error will change to TRUE, and an error code is assigned to ErrorID. ATDone and ATBusy change to FALSE. MV is set to the value of ErrorMV if the values of ManCtl and Run are FALSE. If the value of ErrorMV is outside of the valid range, the value of MV is 0.

Error The value of an input variable is outside of the valid range. RngLowLmt is greater than or equal to RngUpLmt. MVLowLmt is greater than or equal to MVUpLmt.

Value of ErrorID 16#0400 16#0401

· If an error stop is required for conditions other than the above, program the system so that the value of Run changes to FALSE when the error occurs.
· If an error occurs because the value of PV or SP exceeds the valid range, the error status is maintained for five seconds even if the value returns to within the valid range sooner. That is, the value of Error will remain FALSE for five seconds.
· PID control is restarted automatically if the value of Run is TRUE after the error is reset. Autotuning is restarted automatically if the values of Run and StartAT are TRUE.
· A check is made for errors each sampling period.

NJ/NX-series Instructions Reference Manual (W502)

2-691

2 Instruction Descriptions

Sample Programming
In this sample, the PIDAT instruction is used to perform temperature control. The manipulated variable of the PIDAT instruction is converted to a time-proportional value and output to a heating device. This sample uses a timer instruction to convert to a time-proportional value. To use the TimeProportionalOut instruction to convert to a time-proportional value, refer to the sample programming that is provided for the TimeProportionalOut instruction (page 2-735).

Specifications

Temperature control is performed according to the following specifications.

Item

Specification

Input type Input Unit

K thermocouple CJ1W-PH41U Isolated-type Universal Input Unit

Output Unit

CJ1W-OD212 Transistor Output Unit

Set point Sampling period for PID control

90°C 100 ms

Output control period

1 s

Configuration and Settings

The following setting is used for the CJ1W-PH41U Input Unit.

Setting Input1:Input signal type

Set value K(1)

The following I/O map settings are used.

Unit CJ1W-PH41U

I/O port Ch1_AIInPV

CJ1W-OD212

Ch1_Out00

Description Process value for input 1 (INT data) Bit 00 of output word 1

Variable AI1 DO1

Processing
· The manipulation value MV of the PIDAT instruction is obtained to control the output to the temperature controller. The output to the temperature controller is turned ON and OFF.
· The sampling period (InitSetParams.SampTime) of the PIDAT instruction is set to 100 ms. The task period must be sufficiently shorter than 100 ms. Therefore, the value of MV is refreshed every 100 ms.
· The output control period is 1 s. During that period, the ON time and OFF time of the output control value are controlled with a time-proportional output. For example, if the obtained value of MV is 20%, the output to the temperature control is ON for 200 ms and OFF for 800 ms. This is repeated at a 1-s period.
1-s period

Output control value

ON OFF

PID processing

200 ms

MV at this point: 20%

800 ms

300 ms

100-ms period MV at this point: 30%

700 ms Time

2-692

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Analog Control Instructions

PIDAT

· If the most recent value of MV is smaller than the value of MV when the output control values were determined, the output control values do not change. If the most recent value of MV is larger than the value of MV when the output control values were determined, the most recent value is immediately reflected in the output control values. For example, assume that the output control values were determined when the value of MV was 20% (ON 200 ms, OFF 800 ms). If after 100 ms, the new value of MV is 30%, the output control values are immediately changed to turn the output ON for 300 ms and OFF for 700 ms.
1-s period

200 ms

800 ms

Output control value

ON OFF

PID processing

2

MV at this point: 20%

100-ms period Time

MV at this point: 30% The output control values are immediately changed to turn the output ON for 300 ms and OFF for 700 ms.
· If autotuning is performed and the value of MV is 100%, the output is immediately turned ON regardless of the control period.

Application Programming

LD Variable
Run1 ManCtl1

Data type BOOL BOOL

FALSE FALSE

Initial value

StartAT1

BOOL

FALSE

PV1

REAL

0.0

SP1

REAL

90

OprSetParams1

_sOPR_SET_PARAMS

(MVLowLmt:=0.0, MVUpLmt:=100.0, ManResetVal:=0.0, MVTrackSw:=FALSE, MVTrackVal:=0.0, StopMV:=0.0, ErrorMV:=0.0, Alpha:=0.65, ATCalcGain:=1.0, ATHystrs:=0.2)

InitSetParams1

_sINIT_SET_PARAMS

(SampTime:=T#100ms, RngLowLmt:=0.0, RngUpLmt:=1000.0, DirOpr:=FALSE)

PB1

REAL

10

Retain

Comment

Execution condition

Manual/auto control

Autotuning execution condition

Process value

Set point

Operation setting parameters

Initial setting parameters Proportional band

TI1

TIME

T#0S

Integration time

TD1 ManMV1 ATDone1 ATBusy1 Error1

TIME REAL BOOL BOOL BOOL

T#0S 0.0 FALSE FALSE FALSE

Derivative time
Manual manipulated variable Autotuning normal completion Executing autotuning Error

NJ/NX-series Instructions Reference Manual (W502)

2-693

2 Instruction Descriptions

Variable ErrorID1 MV1 PulseOnTime PulseCycTime ResetPulse PIDAT_instance TOF_instance TON_instance

Data type WORD REAL TIME TIME BOOL PIDAT TOF TON

16#0 0.0 T#0s T#1s FALSE

Initial value

Retain

Comment

Error ID

Manipulated variable

Control output ON time

Control period

Timer reset

Obtain the process value. Inline ST
Note: The contents of the inline ST are given below at Contents of Inline ST1.

Execute PIDAT instruction. Run1

PIDAT_instance PIDAT

ManCtl1 StartAT1
PV1 SP1 OprSetParams1 InitSetParams1
PB1
TI1
TD1
ManMV1

Run

ATDone

ManCtl

ATBusy

StartAT

Error

PV

ErrorID

SP

MV

OprSetParams

InitSetParams

ProportionalBand

IntegrationTime

DerivativeTime

ManMV

ATBusy1 Error1 ErrorID1 MV1
PB1 TI1 TD1 ManMV1

ATDone1

Time-proportional output Inline ST
Note: The contents of the inline ST are given below at Contents of Inline ST2.

2-694

Contents of Inline ST1
PV1:=INT_TO_REAL(AI1)/REAL#10.0;

// Convert PV AI1 to real number. // CJ1W-PH41U output is ten times the process value, so divide by 10.0.

Contents of Inline ST2

PulseOnTime:=MULTIME(PulseCycTime, MV1/REAL#100.0);

// Calculate ON time output control value.

TOF_instance(In:=BOOL#FALSE, PT:=PulseOnTime, Q=>DO1);

// Switch between ON and OFF with TOF instruction.

TON_instance(In:=BOOL#TRUE, PT:=PulseCycTime, Q=>ResetPulse); // Measure timer reset time with TON instruction.

IF (ResetPulse=BOOL#TRUE) THEN

// Reset timer.

TOF_instance(In:=BOOL#TRUE);

TON_instance(In:=BOOL#FALSE);

END_IF;

IF ( (ATBusy1=BOOL#TRUE) & (MV1=REAL#100.0) ) THEN

// If MV1 = 100% for autotuning...

DO1:=BOOL#TRUE;

// Turn ON the output immediately.

END_IF;

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Analog Control Instructions

PIDAT

ST

Variable

Data type

Initial value

Retain

Comment

Run1

BOOL

FALSE

Execution condition

ManCtl1

BOOL

FALSE

Manual/auto control

StartAT1

BOOL

FALSE

Autotuning execution condition

PV1

REAL

0.0

Process value

SP1

REAL

90

Set point

OprSetParams1 _sOPR_SET_PARAMS

(MVLowLmt:=0.0, MVUpLmt:=100.0, ManResetVal:=0.0, MVTrackSw:=FALSE, MVTrackVal:=0.0, StopMV:=0.0, ErrorMV:=0.0, Alpha:=0.65, ATCalcGain:=1.0, ATHystrs:=0.2)

Operation setting parameters

2

InitSetParams1 _sINIT_SET_PARAMS

(SampTime:=T#100ms, RngLowLmt:=0.0, RngUpLmt:=1000.0, DirOpr:=FALSE)

Initial setting parameters

PB1

REAL

10

Proportional band

TI1

TIME

T#0S

Integration time

TD1 ManMV1

TIME REAL

ATDone1

BOOL

ATBusy1 Error1 ErrorID1 MV1 PulseOnTime PulseCycTime ResetPulse PIDAT_instance TOF_instance TON_instance

BOOL BOOL WORD REAL TIME TIME BOOL PIDAT TOF TON

T#0S 0.0
FALSE
FALSE FALSE 16#0 0.0 T#0s T#1s FALSE

Derivative time
Manual manipulated variable Autotuning normal completion Executing autotuning Error Error ID Manipulated variable Control output ON time Control period Timer reset

// Convert PV AI1 to real number. PV1:=INT_TO_REAL(AI1)/REAL#10.0; // CJ1W-PH41U output is ten times the process value, so divide by 10.0.

// Execute PIDAT instruction.

PIDAT_instance(

Run

:=Run1,

ManCtl

:=ManCtl1,

StartAT

:=StartAT1,

PV

:=PV1,

SP

:=SP1,

OprSetParams

:=OprSetParams1,

InitSetParams :=InitSetParams1,

ProportionalBand :=PB1,

IntegrationTime :=TI1,

DerivativeTime :=TD1,

ManMV

:=ManMV1,

ATDone

=>ATDone1,

ATBusy

=>ATBusy1,

NJ/NX-series Instructions Reference Manual (W502)

2-695

2 Instruction Descriptions

Error ErrorID MV

=>Error1, =>ErrorID1, =>MV1);

// Time-proportional output

PulseOnTime:=MULTIME(PulseCycTime, MV1/REAL#100.0);

// Calculate ON time output control value.

TOF_instance(In:=BOOL#FALSE, PT:=PulseOnTime, Q=>DO1);

// Switch between ON and OFF with TOF instruction.

TON_instance(In:=BOOL#TRUE, PT:=PulseCycTime, Q=>ResetPulse);

// Measure timer reset time with TON instruction.

IF (ResetPulse=BOOL#TRUE) THEN

// Reset timer.

TOF_instance(In:=BOOL#TRUE);

TON_instance(In:=BOOL#FALSE);

END_IF;

IF ( (ATBusy1=BOOL#TRUE) & (MV1=REAL#100.0) ) THEN // If MV1 = 100% for autotuning...

DO1:=BOOL#TRUE;

// Turn ON the output immediately.

END_IF;

2-696

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

2 Instruction Descriptions

PIDAT_HeatCool

The PIDAT_HeatCool instruction performs heating/cooling PID control with autotuning (2-PID control with set point filter).

Instruction

Name

FB/ FUN

Graphic expression

ST expression

PIDAT_HeatCool_instance(

PIDAT_HeatCool_instance PIDAT_HeatCool

Run, ManCtl,

2

Run

ATDone

StartAT,

ManCtl

ATBusy

PV,

StartAT

Error

SP,

PV

ErrorID

DeadBand,

SP

MV

OprSetParams,

PIDAT _HeatCool

Heating/Cool-

ing PID with

FB

Autotuning

DeadBand

MV_Heat

OprSetParams

MV_Cool

InitSetParams

ProportionalBand_Heat

IntegrationTime_Heat

InitSetParams, ProportionalBand_Heat, IntegrationTime_Heat, DerivativeTime_Heat, ProportionalBand_Cool, IntegrationTime_Cool,

DerivativeTime_Heat

DerivativeTime_Cool,

ProportionalBand_Cool

ManMV, CtlPrd_Cool,

IntegrationTime_Cool

ATDone, ATBusy,

DerivativeTime_Cool

Error,

ErrorID,

ManMV

MV,

CtlPrd_Cool

MV_Heat, MV_Cool);

PIDAT_HeatCool

NJ/NX-series Instructions Reference Manual (W502)

2-697

2 Instruction Descriptions

Variables

Name Run
ManCtl
StartAT
PV SP DeadBand OprSet Params InitSet Params

Meaning

I/O

Execution condition

Manual/auto control

Autotuning execution condition

Process value

Set point Deadband

Input

Operation setting parameters

Initial setting parameters

CtlPrd _Cool

Cooling control period

Proportional Band_Heat

Proportional band for heating control

IntegrationTime_Heat

Integration time for heating control

Derivative Time_Heat

Derivative time for heating control

Proportional Band_Cool

Proportional band for cooling control

In-out

IntegrationTime_Cool

Integration time for cooling control

Derivative Time_Cool

Derivative time for cooling control

ManMV

Manual manipulated variable

Description TRUE: Execute FALSE: Stop TRUE: Manual operation FALSE: Automatic operation TRUE: Execute FALSE: Cancel

Valid range

Unit

Depends on data type.
---

Process value *1
Set point Deadband/overlap band setting -320.0 to 320.0 % Parameters set during operation

---

Initial setting parameters

---

Control period when time-proportional output is used for MV_Cool

T#0.1s to T#100s

Proportional band for heating control

0.01 to 1000.00 %FS

Integration time for heating con-

trol The higher the value is, the weaker the integral action is. No integral action is performed

T#0.0000s to T#10000.0000s *2

for 0. s
Derivative time for heating con-

trol The higher the value is, the stronger the derivative action is. No derivative action is per-

T#0.0000s to T#10000.0000s *2

formed for 0.

Proportional band for cooling control

0.01 to 1000.00 %FS

Integration time for cooling con-

trol The higher the value is, the weaker the integral action is. No integral action is performed

T#0.0000s to T#10000.0000s *2

for 0. s
Derivative time for cooling con-

trol The higher the value is, the stronger the derivative action is. No derivative action is per-

T#0.0000s to T#10000.0000s *2

formed for 0.

Manual manipulated variable

-320 to 320

%

Default FALSE 0 --T#20s
---

2-698

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

2 Instruction Descriptions

Name ATDone ATBusy MV MV_Heat
MV_Cool

Meaning

I/O

Description

Valid range

Unit

Autotuning normal completion
Autotuning busy

TRUE: Normal completion FALSE: *3
TRUE: Autotuning FALSE: Not autotuning

--Depends on data type.

Manipulated

Manipulated variable

variable

Output

Manipulated

variable for heating con-

Manipulated variable for heating control

0 to 320

%

trol

Manipulated variable for cooling control

Manipulated variable for cooling control

0 to 320

Default
---
2

*1 Value of input range lower limit InitSetParams.RngLowLmt to Value of input range upper limit InitSetParams.RngUpLmt *2 Digits below 0.0001 s are truncated. *3 FALSE indicates an error end, that PID control is in progress without autotuning, or that PID control is not in progress.

Bit strings

Integers

Times, durations, dates, and text strings

PIDAT_HeatCool

Real numbers

Boolean BOOL

STRING DT TOD
DATE TIME

LREAL REAL

LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE

Run

OK

ManCtl

OK

StartAT

OK

PV

SP

DeadBand

OprSet Params

InitSet Params

CtlPrd _Cool

Proportional Band_Heat

IntegrationTime_Heat

Derivative Time_Heat

Proportional Band_Cool

IntegrationTime_Cool

Derivative Time_Cool

ManMV

ATDone

OK

OK OK OK Refer to Function for details on the structure _sOPR_SET_PARAMS. Refer to Function for details on the structure _sINIT_SET_PARAMS.
OK OK
OK OK OK OK OK OK

NJ/NX-series Instructions Reference Manual (W502)

2-699

2 Instruction Descriptions

Real numbers

Boolean BOOL

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE

TIME

LREAL REAL

LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE

ATBusy

OK

MV

OK

MV_Heat

OK

MV_Cool

OK

Function
The PIDAT_HeatCool instruction performs heating/cooling PID control of a manipulated variable for a temperature controller or other device. Heating/cooling PID control is started when the value of execution condition Run changes to TRUE. While the value of Run is TRUE, the following process is repeated periodically: process value PV is read, heating/cooling PID processing is performed, and manipulated variable for heating MV_Heat and manipulated variable for cooling MV_Cool are output. Heating/cooling PID control is stopped when the value of Run changes to FALSE.
Autotuning is supported to automatically find the optimum PID constants for heating control and for cooling control. When the value of the autotuning execution condition StartAT changes to TRUE, the PID constants for heating control and cooling control are autotuned.

2-700

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

PIDAT_HeatCool

2 Instruction Descriptions

Difference between the PIDAT_HeatCool and PIDAT Instructions

 PIDAT_HeatCool Instruction
The PIDAT_HeatCool instruction uses both a heating device and a cooling device to control the temperature. Therefore, manipulated variables are output for two different control operations: the manipulated variable for heating control, MV_Heat, and the manipulated variable for cooling control, MV_Cool. Autotuning finds the optimum PID constants for heating control and the optimum PID constants for cooling control.

MV_Heat MV_Cool

The manipulated variable for heating control MV_Heat increases as the value of PV decreases.

2

The manipulated variable for cooling control MV_Cool increases as the value of PV increases.

SP

PV

 PIDAT Instruction
The PIDAT instruction uses either a heating device or a cooling device to control the temperature. Therefore, only one manipulated variable (MV) is output. Also, there is a parameter, action direction DirOpr, that determines whether the manipulated variable is output to a heating device or to a cooling device. The PIDAT_HeatCool instruction does not use DirOpr.

When a heating device is used,

MV

action direction DirOpr = FALSE

When a cooling device is used,

MV

action direction DirOpr = TRUE

SP

PV

SP

PV

NJ/NX-series Instructions Reference Manual (W502)

2-701

2 Instruction Descriptions

Manipulated Variable MV Compared with Manipulated Variable for Heating Control MV_Heat and Manipulated Variable for Cooling Control MV_Cool
MV is the manipulated variable for an instruction like the PIDAT instruction that uses either a heating device or a cooling device to control the temperature. The PIDAT_HeatCool instruction also calculates MV in the same way as the PIDAT instruction. MV is then distributed to the manipulated variable for heating and the manipulated variable for cooling. The following figure shows conceptually how the value of MV is distributed to MV_Heat and MV_Cool. The value of MV_Cool is the absolute value of MV when MV is negative.

MV MV
0 SP

MV_Heat MV_Cool

MV_Heat MV_Cool

The value of MV

is distributed to

MV_Heat and

MV_Cool.

0

PV

SP

PV

The above figure is conceptual. The actual values of MV_Heat and MV_Cool are not exactly the negative and positive values of MV. The values of MV_Heat and MV_Cool are calculated from special formulas based on the value of MV.

2-702

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

PIDAT_HeatCool

2 Instruction Descriptions

Structure Specifications
The data type of operation setting parameter OprSetParams is structure _sOPR_SET_PARAMS. The specifications are as follows:

Name

Meaning

Description

Data type Valid range Unit Default

OprSetParams

Operation Setting Parameters

Parameters that are set during operation.

_sO-

---

PR_SET_PAR

AMS

---

---

MVLowLmt MVUpLmt

MV Lower Limit
MV Upper Limit

Lower limit of MV_Heat and MV_Cool
Upper limit of MV_Heat and MV_Cool

REAL REAL

-320 to 320*1

-100
2

%

100

ManReset Val

Manual Reset Not used. Value

REAL

-320 to 320

0

MVTrackSw

MV Tracking MV Tracking Switch

Switch

TRUE: ON

BOOL

Depends on

data type.

---

FALSE

FALSE: OFF

MVTrackVal

MV Tracking Value

The value that is set in MV during MV tracking.

REAL

StopMV

Stop MV

The value that is set in MV when instruction execution is stopped.

REAL

-320 to 320 %

0

ErrorMV

Error MV

The value that is set in MV when an error occurs.

REAL

2-PID Param- The set point filter is dis-

0.00 to 1.00

Alpha

eter 

abled if the set point fil- REAL

0.65

ter coefficient  is 0.

ATCalcGain

Autotuning Calculation Gain

Adjustment coefficient from autotuning results. Stability is given higher priority with higher values. The speed of response is given higher priority with lower values.

REAL

---

0.1 to 10.0

0.8

ATHystrs

Autotuning Hysteresis

The hysteresis of the limit cycle.

REAL

0.01 to 10.0 %FS 0.05

*1 MVLowLmt must be less than MVUpLmt.

NJ/NX-series Instructions Reference Manual (W502)

2-703

2 Instruction Descriptions

The data type of initial setting parameter InitSetParams is structure _sINIT_SET_PARAMS. The specifications are as follows:

Name InitSetParams
SampTime RngLowLmt RngUpLmt DirOpr

Meaning
Initial Setting Parameters

Description
Initial setting parameters.

Sampling Period
Lower Limit of Input Range
Upper Limit of Input Range
Action Direction

The period for PID processing.
The lower limit of PV and SP.
The upper limit of PV and SP.
Not used.

Data type _sINIT_SET_PAR AMS TIME
REAL
REAL
BOOL

Valid range
---
T#0.0001s to #100.0000s
-32000 to 32000*1
Depends on data type.

*1 RngLowLmt must be less than RngUpLmt.

Unit Default
--- ---
s T#0.05s 0
--- 100 FALSE

Meanings of Variables
The meanings of the variables that are used in this command are described below.

 Run (Execution Condition)
This is the execution condition for the instruction.
Heating/cooling PID control is performed while the value is TRUE. Heating/cooling PID control is stopped when the value changes to FALSE.

 ManCtl (Manual/Auto Control)
This instruction can be executed in one of two modes: Manual operation or automatic operation. The value of ManCtl determines which mode is used.

Value of ManCtl TRUE FALSE

Operation mode Manual
Automatic

Value of MV
Value of ManMV (Heating/cooling PID control is not performed.)
Value that is calculated for heating/cooling PID control

 StartAT (Autotuning Execution Condition)
This is the execution condition for autotuning the PID constants. If the value of StartAT is TRUE when the value of Run changes to TRUE, autotuning is performed when PID control is started. If the value of StartAT changes to TRUE during heating/cooling PID control (i.e., when the value of Run is TRUE), autotuning is performed during heating/cooling PID control. In either case, autotuning is canceled if the value of StartAT changes to FALSE during autotuning. Autotuning is described in more detail later.

 PV (Process Value)
This is the process value of the controlled system.

 SP (Set Point)
This is the set point for the controlled system.

2-704

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

2 Instruction Descriptions

 DeadBand (Deadband)
DeadBand determines how the value of MV is distributed to MV_Heat and MV_Cool. DeadBand gives the range of the value of MV centered on an MV value of 0 within which both heating and cooling control operations are not performed.
The following table and figure show the relationship between the value of MV and the values of MV_Heat and MV_Cool.

Value of MV

Value of MV_Heat

Value of MV_Cool

Larger than the deadband (Area A)

Positive. Increases as the value of MV increases.

0

Within the deadband (Area B) 0

Smaller than the deadband (Area C)

0

0

Positive. Increases as the value of

2

MV decreases.

MV_Cool

MV_Heat MV_Cool

MV_Heat

PIDAT_HeatCool

MV = Negative

MV = Positive value

value

0%

C

B

A

DeadBand
If the value of MV is within this range, the values of MV_Heat and MV_Cool are 0%.
You can also set a negative value for DeadBand. If the value of DeadBand is negative while the value of MV is within the deadband, both heating and cooling control are performed. The following table and figure show the relationship between the value of MV and the values of MV_Heat and MV_Cool when the value of DeadBand is negative.

Value of MV Larger than the deadband (Area A)
Within the deadband (Area B)
Smaller than the deadband (Area C)

Value of MV_Heat Positive. Increases as the value of MV increases. Positive. Increases as the value of MV increases.
0

Value of MV_Cool
0
Positive. Increases as the value of MV decreases. Positive. Increases as the value of MV decreases.

MV_Cool

MV_Heat MV_Cool

MV_Heat

MV = Negative

MV = Positive value

value

0%

C

B

A

DeadBand If the value of MV is within this range, the values of MV_Heat and MV_Cool are both positive.

NJ/NX-series Instructions Reference Manual (W502)

2-705

2 Instruction Descriptions

 MVLowLmt (MV Lower Limit) and MVUpLmt (MV Upper Limit)
You can limit the values of MV_Heat and MV_Cool. The upper and lower limits of MV_Heat and MV_Cool are determined by MVLowLmt and MVUpLmt. The following procedure is used to find the values of MV_Heat and MV_Cool.
1 The heating/cooling PID processing is performed to find MV. The upper and lower limits of MV are calculated from special formulas based on MVLowLmt and MVUpLmt.
2 MV_Heat and MV_Cool are found by distributing MV.

The following figure shows the relationship between MV, MV_Heat, and MV_Cool when MVLowLmt is -100 and MVUpLmt is 200. The calculated upper limit of MV_Heat is 200 and the calculated lower limit is 0. The calculated upper limit of MV_Cool is 100 and the calculated lower limit is 0. In other words, the upper limit of MV_Heat is the same as the value of MVUpLmt, but the upper limit of MV_Cool is the absolute value of MVLowLmt.

MV

Value calculated from MVUpLmt

MV

Upper limit of MV is approx. 200.

Value calculated from MVLowLmt

0

SP

PV

Lower limit of MV is approx. -100.

The value of MV is distributed to MV_Heat and MV_Cool.

MV_Heat MV_Cool
MVUpLmt=200
MVLowLmt=100

Upper limit of MV_Heat is 200. Upper limit of MV_Cool is 100.

SP

PV

2-706

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

2 Instruction Descriptions

The following figure shows the relationship between MV, MV_Heat, and MV_Cool when MVLowLmt is 100 and MVUpLmt is 200. The calculated upper limit of MV_Heat is 200 and the calculated lower limit is 100. The value of MV_Cool is always 0. In other words, the upper and lower limits of MV_Heat are the same as MVUpLmt and MVLowLmt.

MV

Value calculated from MVUpLmt

MV

Upper limit of MV is approx. 200.

Lower limit of MV is approx. 100.

2

Value calculated from MVLowLmt

SP

PV

PIDAT_HeatCool

The value of MV is distributed to MV_Heat and MV_Cool.

MV_Heat MV_Cool
MVUpLmt=200

The upper limit of MV_Heat is 200 and the lower limit is 100.

MVLowLmt=100

MV_Cool is always 0.

SP

PV

As shown above, the upper and lower limits of MV_Heat and MV_Cool change as shown in the following table depending on whether MVLowLmt and MVUpLmt are positive values or negative values.

Value of MVLowLmt
Positive Negative

Value of MVUpLmt
Positive Positive

Negative

Negative

MV_Heat

Lower limit Upper limit

MVLowLmt

MVUpLmt

0

MVUpLmt

0

0

MV_Cool

Lower limit Upper limit

0

0

0

Absolute value

of MVLowLmt

Absolute value Absolute value of MVUpLmt of MVLowLmt

Always set MVLowLmt and MVUpLmt so that MVLowLmt is less than MVUpLmt. Also, if MV is set to StopMV, ErrorMV, or ManMV, limit control is not applied.

You can change MVLowLmt and MVUpLmt even if the control status of this instruction is not autotuning during automatic operation.

However, if you change MVLowLmt or MVUpLmt to an expansion direction during operation, the value of MV_Heat or MV_Cool which is the same as one in the last sampling period is output and changed smoothly at this time (bumpless).

Repeated changing of MVLowLmt or MVUpLmt will affect the control performance so that sufficient control performance may not obtain.

Confirm the effects on the control performance before you repeatedly change MVLowLmt or MVUpLmt during operation.

NJ/NX-series Instructions Reference Manual (W502)

2-707

2 Instruction Descriptions

 ManResetVal (Manual Reset Value)
This instruction does not use this variable. Any value that is set is ignored.
 MVTrackSw (MV Tracking Switch)
MV tracking is a function that sets the MV to an external input value (called the MV tracking value) during automatic operation. MV tracking is performed while the value of MVTrackSw is TRUE. When the value of MVTrackSw changes to FALSE, the value of MV returns to the result of heating/cooling PID processing. At this time, the value of MV takes on the value of MVTrackVal. This prevents the values of MV_Heat and MV_Cool from changing abruptly.
MV_Heat

MV_Heat distributed from MVTrackVal

The value of MV takes on the value of MVTrackVal. MV_Heat and MV_Cool do not change abruptly.

Time
MVTrackSw = TRUE
MVTrackSw = FALSE
 MVTrackVal (MV Tracking Value)
This is the value to which MV is set during MV tracking. The value of MVTrackVal is limited by the values of MVLowLmt and MVUpLmt.
 StopMV (Stop MV)
This is the value to which MV is set when the value of Run is FALSE (i.e., when execution of this instruction is stopped).
 ErrorMV (Error MV)
This is the value to which MV is set when an error occurs (i.e., when the value of Error is TRUE). If the value of ErrorMV is not within the valid range (-320 to 320), the value of MV will be 0 when an error occurs.
 Alpha (2-PID Parameter )
This parameter determines the coefficient of the set point filter. Refer to the description in 2-PID Control with Set Point Filter in the section on the PIDAT instruction (page 2-672) for details. Normally set the value of Alpha to 0.65.
 ATCalcGain (Autotuning Calculation Gain)
This variable gives the coefficient of the PID constants that were calculated by autotuning when they are applied to the actual PID constants. If a value of 1.00 is specified, the results of autotuning are used directly. Increase the value of ATCalcGain to give priority to stability and decrease it to give priority to response.
 ATHystrs (Autotuning Hysteresis)
This is the hysteresis that is used in the limit cycle for autotuning. More accurate tuning is achieved if the value of ATHystrs is small. However, if the process value is not stable and proper autotuning is difficult, increase the value.

2-708

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Analog Control Instructions

PIDAT_HeatCool

Refer to the description of autotuning in the section on the PIDAT instruction (page 2-672) for details.
 SampTime (Sampling Period)
This is the minimum value of the period for heating/cooling PID processing. Refer to the description of the execution timing of heating/cooling PID processing for details. Heating/cooling PID processing is not performed again until the time specified for SampTime has elapsed since the last time heating/cooling PID processing was performed.
 RngLowLmt (Lower Limit of Input Range) and RngUpLmt (Upper Limit of Input Range)
These are the lower limit and upper limit of PV and SP. An error will occur if the value of the param- 2
eter connected to PV or SP exceeds either of these limits. RngLowLmt must always be less than RngUpLmt.
 DirOpr (Action Direction)
This instruction does not use this variable. Any value that is set is ignored.
 CtlPrd_Cool (Control Period)
This variable sets the control period for time-proportional output of MV_Cool when you use this instruction together with the TimeProportionalOut instruction (page 2-735). Set the same value here and for control period CtlPrd of the TimeProportionalOut instruction. If you do not use time-proportional output for MV_Cool, set the default value, T#20s.
 ProportionalBand_Heat and ProportionalBand_Cool (Proportional Bands)
This is one of the three PID constants. Refer to the description of the proportional action in the section on the PIDAT instruction (page 2-672) for details. If the values of ProportionalBand_Heat and ProportionalBand_Cool are large, the offset will be large. Hunting occurs if a proportional band is too small.
 IntegrationTime_Heat and IntegrationTime_Cool (Integration Times)
This is one of the three PID constants. Refer to the description of the integral action in the section on the PIDAT instruction (page 2-672) for details. The larger the value of IntegrationTime_Heat or IntegrationTime_Cool is, the weaker the integral action is.
 DerivativeTime_Heat and DerivativeTime_Cool (Derivative Times)
This is one of the three PID constants. Refer to the description of the derivative action in the section on the PIDAT instruction (page 2-672) for details. The larger the value of DerivativeTime_Heat or DerivativeTime_Cool is, the stronger the derivative action is.
 ManMV (Manual Manipulated Variable)
MV is set to this value during manual operation (while ManCtl is TRUE). However, MV is set to the value of ManMV only when it changes after operation switches to manual operation. The value of MV immediately after changing from automatic to manual operation will be the value of MV_Heat if that value is positive and the value of MV_Cool otherwise. Also, the value of MV immediately after changing from manual to automatic operation will be the value of MV_Heat if that value is positive and the value of MV_Cool otherwise.

NJ/NX-series Instructions Reference Manual (W502)

2-709

2 Instruction Descriptions

The value of ManMV does not have to be between MVLowLmt and MVUpLmt.

MV_Heat

Value of MV_Heat from automatic operation is used.

Value of MV_Heat from manual operation is used.

ManCtl changed to TRUE.

Time ManCtl changed to FALSE.

Value of ManMV changed.
 ATDone (Autotuning Normal Completion)
This flag indicates when autotuning was completed normally. It changes to TRUE when autotuning is completed normally and remains TRUE as long as the value of StartAT is TRUE. It is FALSE in the following cases. · An autotuning error end occurred. · Autotuning is in progress (i.e., while the value of ATBusy is TRUE). · Heating/cooling PID control is in progress without autotuning. · Heating/cooling PID control is not in progress (i.e., the value of Run is FALSE). · The value of StartAT is FALSE.

 ATBusy (Autotuning Busy)
This flag indicates when autotuning is in progress. It is TRUE while autotuning is in progress. Otherwise it is FALSE.

 MV (Manipulated Variable)
This is the manipulated variable found by the heating/cooling PID processing. MV_Heat and MV_Cool are found by distributing MV.

 MV_Heat (Manipulated Variable for Heating Control)
This is the manipulated variable that is applied to the heating device.

 MV_Cool (Manipulated Variable for Cooling Control)
This is the manipulated variable that is applied to the cooling device.

2-710

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

PIDAT_HeatCool

2 Instruction Descriptions
Heating/Cooling PID Processing
Refer to the section on the PIDAT instruction (page 2-672) for details on PID processing. Heating/cooling PID processing is used to find the manipulated variables using the PID constants for heating control and the PID constants for cooling control. If MV is less than or equal to 0 in the previous processing results, the PID constants for heating control are used. If the previous MV is greater than 0, the PID constants for cooling control are used.
Proportional (P), Integral (I), and Derivative (D) Actions Refer to the section on the PIDAT instruction (page 2-672) for details on the proportional action (P), 2
integral action (I), and derivative action (D).
2-PID Control with Set Point Filter
Refer to the description in 2-PID Control with Set Point Filter in the section on the PIDAT instruction (page 2-672) for details.
Heating/Cooling PID with Autotuning
You must use the optimum PID constants to execute this instruction. There are the following two ways to achieve this.
 When Optimum PID Constants Are Not Known
If you do not know the optimum PID constants, perform autotuning at the start of operation to find them. Change the value of Run to TRUE while the value of StartAT is TRUE. First, autotuning is executed, and then heating/cooling PID control is started with the PID constants that are found.
 When Optimum PID Constants Are Known
Set ProportionalBand_Heat, IntegrationTime_Heat, DerivativeTime_Heat, ProportionalBand_Cool, IntegrationTime_Cool, and DerivativeTime_Cool to the optimum PID constants and then change the value of Run to TRUE. ProportionalBand_Heat, IntegrationTime_Heat, DerivativeTime_Heat, ProportionalBand_Cool, IntegrationTime_Cool, and DerivativeTime_Cool are in-out variables. You cannot set constants for the input parameters. Always define suitable variables, and then assign the values to input parameters. You can change the PID constants during operation. You can also perform autotuning during operation. To start autotuning during operation, change the value of StartAT to TRUE.

NJ/NX-series Instructions Reference Manual (W502)

2-711

2 Instruction Descriptions

Control Status and Manipulated Variable

Manipulated variable MV is determined according to the control status as shown in the following table.

Value of variable

Control status Error end

ManCtl (manual/auto control)

Run (execution con-
dition)

Error (error end)

TRUE

MVTrackSw (MV tracking
switch)
---

ATBusy (autotuning busy)

Manipulated variable MV

ErrorMV (error MV)

MV tracking during automatic operation
Autotuning during automatic operation

FALSE

Not autotuning during automatic operation
Instruction execution stopped
Manual operation

TRUE

TRUE
FALSE ---

TRUE

FALSE

FALSE

---

---

FALSE TRUE
FALSE

MVTrackVal (MV tracking value)
Value repeatedly changes between upper limit of MV and lower limit of MV.
Value calculated with current PID constants.
StopMV (Stop MV)*1
ManMV (manual manipulated variable)*2

*1 If the value of StopMV is outside of the valid range, the value of MV is 0. *2 If the value of ManMV is outside of the valid range, the value of MV is 0.

2-712

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

PIDAT_HeatCool

2 Instruction Descriptions

Autotuning

The 2-PID parameter  is not adjusted very often, so the main parameters that are adjusted for this instruction are the PID constants.

The PIDAT instruction supports autotuning of the PID constants. The limit cycle method is used for autotuning. With the limit cycle method, the manipulated variable is temporarily changed to the upper and lower limits of the limit cycle manipulated variable to find the optimum PID constants based on the resulting changes in the process value.

When you start execution of autotuning, the manipulated variable is first set to the upper limit of the limit

cycle manipulated variable. When the deviation reaches 0 or lower, the manipulated variable is set to

the lower limit of the limit cycle manipulated variable. When the deviation becomes greater than the autotuning hysteresis, the manipulated variable is set to the upper limit of the limit cycle manipulated

2

variable again. This process is repeated two and a half times to calculate the optimum PID constants.

The upper and lower limits of the limit cycle manipulated variable are calculated from the values of the

parameters.

Autotuning executed.

Set point Process value

Autotuning hysteresis
Manipulated variable Upper limit of limit cycle MV

Time

Lower limit of limit cycle MV

Time

The manipulated variable is set to upper limit of the limit cycle manipulated variable.

When autotuning is completed, heating/cooling PID processing is

When the deviation reaches 0 or lower, the manipulated variable is set to the lower limit of the

performed based on the PID constants that were found.

limit cycle manipulated variable.

When the deviation becomes greater than the

autotuning hysteresis, the manipulated variable is set

to the upper limit of the limit cycle manipulated

variable again.

Autotuning is executed during heating/cooling PID control (i.e., when the value of Run is TRUE) if the

value of StartAT changes to TRUE. If StartAT is TRUE when Run changes to TRUE, autotuning is exe-

cuted at the start of PID control. When autotuning is completed normally, the calculated PID constants

are used immediately. Autotuning is canceled if the value of StartAT changes to FALSE during autotun-

ing (i.e., when ATBusy is TRUE). If autotuning is canceled, heating/cooling PID control is started again

with the previous PID constants.

NJ/NX-series Instructions Reference Manual (W502)

2-713

2 Instruction Descriptions

Execution Timing of Heating/Cooling PID Control
Heating/cooling PID control is repeated periodically. Heating/cooling PID processing is performed when the PIDAT instruction is executed in the user program. However, if sampling period SampTime has not elapsed since the last time heating/cooling PID processing was performed, heating/cooling PID processing is not performed. If the elapsed time since the last time heating/cooling PID processing was executed exceeds SampTime, the excess time (elapsed time - SampTime) is carried forward to the next period. Even if this instruction is not executed as a result of the PrgStop or MC instruction, the elapsed time from the last execution of heating/cooling PID processing is set to 0 at the timing shown by "PID processing executed" in the following figures.
Task period = 60 ms and SampTime < 60 ms
The task period is greater than or equal to SampTime, so PID processing is executed once every task period.

Task period

Task period

Task period

Task period

Task period

PIDAT

PIDAT

PIDAT

PIDAT

AutoPID

60 ms

60 ms

60 ms

60 ms

PID processing executed.

PID processing executed.

PID processing executed.

PID processing executed.

PID processing executed.

Time

Task period = 60 ms and SampTime = 100 ms The task period is less than SampTime, so DIP processing is not executed every period.

Task period

Task period

Task period

Task period

Task period

Task period

PIDAT

PIDAT

PIDAT

PIDAT

PIDAT

PIDAT

60 ms

60 ms

60 ms

60 ms

60 ms

PID processing executed. PID processing PID processing executed. PID processing PID processing executed. PID processing executed.

Time

not executed.

not executed. Executed because elapsed time

Not executed because

(80 + 60 ms = 140 ms)  100 ms.

elapsed time (60 ms) < 100 ms.

The remaining 40 ms is carried over.

Executed because elapsed time (60 + 60 ms = 120 ms)  100 ms. The remaining 20 ms is carried over.

Not executed because elapsed time (20 + 60 ms = 80 ms) < 100 ms.

Executed because elapsed time (40 + 60 ms = 100 ms)  100 ms. A time of 0 ms is carried over.

2-714

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

PIDAT_HeatCool

2 Instruction Descriptions

Timing Charts
Timing charts for the instruction variables are provided below for different situations.

 Autotuning Executed during Automatic Operation

· In the following figure, the value of ManCtl is FALSE, so the value of MV will be StopMV as long as the value of Run is FALSE.

· When the value of Run changes to TRUE, MV is output based on the PID constants.

· Autotuning is executed when the value of StartAT changes to TRUE. The value of ATBusy

changes to TRUE. · When autotuning is completed, the value of ATBusy changes to FALSE and the value of ATDone

2

changes to TRUE.

· After autotuning is completed, MV is output based on the PID constants that were found with autotuning.

· When the value of Run changes to FALSE, the value of MV changes to StopMV. Also, the value of ATDone changes to FALSE.

Run ManCtl StartAT ATBusy ATDone
Error

TRUE FALSE
TRUE FALSE
TRUE FALSE TRUE FALSE
TRUE FALSE TRUE FALSE
PV SP

ATHystrs

MV Upper limit of limit cycle MV

Time

StopMV Lower limit of limit cycle MV

Time

Heating/cooling PID processing
Autotuning
PID constants updated for results of autotuning.

MV set to StopMV.

NJ/NX-series Instructions Reference Manual (W502)

2-715

2 Instruction Descriptions

 Autotuning Executed at the Start of PIDAT Execution
· In the following figure, the value of ManCtl is FALSE, so the value of MV will be StopMV as long as the value of Run is FALSE.
· While the value of Run is TRUE, autotuning is not executed even if the value of StartAT changes to TRUE.
· Autotuning is executed when the values of both StartAT and Run change to TRUE. The value of ATBusy changes to TRUE.
· When autotuning is completed, the value of ATBusy changes to FALSE and the value of ATDone changes to TRUE.
· After autotuning is completed, MV is output based on the PID constants that were found with autotuning.

Run ManCtl

TRUE FALSE
TRUE FALSE

StartAT ATBusy

TRUE FALSE
TRUE FALSE

ATDone Error

TRUE FALSE
TRUE FALSE

PV SP

ATHystrs

MV Upper limit of limit cycle MV
StopMV Lower limit of limit cycle MV

Time

Autotuning

Time Heating/cooling PID processing

PID constants updated MV set to StopMV. for results of autotuning.

2-716

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

PIDAT_HeatCool

2 Instruction Descriptions

 Autotuning Canceled

· In the following figure, the value of ManCtl is FALSE, so the value of MV will be StopMV as long as the value of Run is FALSE.

· When the value of Run changes to TRUE, MV is output based on the PID constants.

· Autotuning is executed when the value of StartAT changes to TRUE. The value of ATBusy changes to TRUE.

· Autotuning is canceled if the value of StartAT changes to FALSE during autotuning. The value of ATBusy changes to FALSE.

· After autotuning is completed, MV is output based on the PID constants from just before autotuning was started.

· When the value of Run changes to FALSE, the value of MV changes to StopMV. · The value of ATDone does not change to TRUE because autotuning was aborted.

2

Run ManCtl

TRUE FALSE
TRUE FALSE

StartAT ATBusy ATDone
Error

TRUE FALSE
TRUE FALSE
TRUE FALSE TRUE FALSE
PV

SP

MV Upper limit of limit cycle MV

Time

StopMV Lower limit of limit cycle MV

Time

Heating/cooling PID processing

Autotuning

Autotuning canceled.

MV set to StopMV.

The PID constants from before

autotuning was started are set.

NJ/NX-series Instructions Reference Manual (W502)

2-717

2 Instruction Descriptions

 An Autotuning Error Occurs during Autotuning

An autotuning error occurs and autotuning is stopped in the following cases.
· If the manipulated variable equals the upper limit of the limit cycle manipulated variable and the time for the deviation to reach 0 exceeds 19,999 s.
· If the manipulated variable equals the lower limit of the limit cycle manipulated variable and the time for the deviation to reach ATHystrs or higher exceeds 19,999 s.
The value of Error does not change to TRUE even if an error occurs during autotuning. Autotuning is also not recorded in the event log.
If autotuning is canceled, heating/cooling PID control is started again with the previous PID constants.
· In the following figure, the value of ManCtl is FALSE, so the value of MV will be StopMV as long as the value of Run is FALSE.
· When the value of Run changes to TRUE, MV is output based on the PID constants.
· Autotuning is executed when the value of StartAT changes to TRUE. The value of ATBusy changes to TRUE.
· Autotuning is canceled immediately if an autotuning error occurs during execution of autotuning. The value of ATBusy changes to FALSE.
· The value of Error does not change to TRUE even if an error occurs during autotuning.
· After autotuning is canceled, MV is output based on the PID constants from just before autotuning was started.
· When the value of Run changes to FALSE, the value of MV changes to StopMV.
· The value of ATDone does not change to TRUE because autotuning was aborted.

Run ManCtl

TRUE FALSE
TRUE FALSE

StartAT ATBusy

TRUE FALSE
TRUE FALSE

ATDone Error

TRUE FALSE
TRUE FALSE

PV

SP

2-718

MV Upper limit of limit cycle MV

Time

StopMV Lower limit of limit cycle MV

Time

Heating/cooling PID processing

Autotuning
MV set to StopMV. Error occurs. The PID constants from before autotuning was started are set.

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

PIDAT_HeatCool

2 Instruction Descriptions

Additional Information
Adjusting PID Constants
Refer to the section on the PIDAT instruction (page 2-672) for the adjustment methods for PID constants.

Initial PID Constants for Temperature Control

If you use the PIDAT instruction for temperature control, use the following initial values of the PID constants as reference. Use the default values for the other variables.

2

Variables ProportionalBand_Heat and ProportionalBand_Cool IntegrationTime_Heat and IntegrationTime_Cool DerivativeTime_Heat and DerivativeTime_Cool

Initial values (reference values)*1 10%FS 233 s 40 s

*1 If you perform autotuning, use the results from autotuning.

Precautions for Correct Use

· The values of PV and SP must be between the values of RngLowLmt and RngUpLmt, inclusive. Align the units of these variables as shown below.

Unit % FS
Physical unit

Values of PV and SP
PV = (Process value in physical units - MIN)/(MAX - MIN) × 100 SP = (Set point in physical units - MIN)/(MAX - MIN) × 100*1 PV = Process value in physical units SV = Set point in physical units

Values of RngLowLmt and RngUpLmt
RngLowLmt = 0 RngUpLmt = 100
RngLowLmt = MIN RngUpLmt = MAX*1

*1 MAX: Upper limit of input range in physical units, MIN: Lower limit of input range in physical units,

NJ/NX-series Instructions Reference Manual (W502)

2-719

2 Instruction Descriptions

· The following table shows which variables can be changed depending on the operating status.

Variables
Run ManCtl StartAT DeadBand PV SP MVLowLmt MVUpLmt ManResetVal*5 MVTrackSw MVTrackVal StopMV ErrorMV Alpha ATCalcGain ATHystrs CtlPrdCool SampTime RngLowLmt RngUpLmt DirOpr*5 ProportionalBand_Heat IntegrationTime_Heat DerivativeTime_Heat ProportionalBand_Cool IntegrationTime_Cool DerivativeTime_Cool ManMV

Instruction execution
stopped*1 Possible Possible Possible Possible Possible Possible Possible Possible
--Possible Possible Possible Possible Possible Possible Possible Possible Possible Possible Possible
--Possible Possible Possible Possible Possible Possible Possible

Control status Automatic operation when autotuning is not being exe-
cuted*2 Possible Possible Possible Possible Possible Possible Possible Possible
--Possible Possible Possible Possible Possible Possible Possible Possible Not possible*6 Not possible*6 Not possible*6
--Possible Possible Possible Possible Possible Possible Possible

Automatic operation when autotuning is being executed*3 Possible Possible Possible Possible Possible Not possible*4 Not possible*4 Not possible*4 ---
Not possible*4 Not possible*4
Possible Possible Not possible*4 Not possible*4 Not possible*4 Not possible*4 Not possible*4 Not possible*4 Not possible*4
---
Not possible*7 Not possible*7 Not possible*7 Not possible*7 Not possible*7 Not possible*7
Possible

*1 ManCtl is TRUE, Run is FALSE, Error is TRUE, or MVTrackSw is TRUE. *2 ManCtl is FALSE, Run is TRUE, Error is FALSE, MVTrackSw is FALSE, and ATBusy is FALSE. *3 ManCtl is FALSE, Run is TRUE, Error is FALSE, MVTrackSw is FALSE, and ATBusy is TRUE. *4 Autotuning is executed with the value from just before execution of autotuning. *5 This instruction does not use this variable. You can change the value, but it is ignored. *6 Operation is performed with the value from just before the execution of the operation. *7 You can change the value, but it is ignored. When autotuning is completed, the values are overwritten with
the values calculated with autotuning.

2-720

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

PIDAT_HeatCool

2 Instruction Descriptions

· SampTime is truncated below 100 nanoseconds.

· If the value of StartAT changes to TRUE while the value of ManCtl is TRUE, autotuning starts the next time the value of ManCtl changes to FALSE.

· If the value of ErrorMV is not within the valid range (-320 to 320), the value of MV will be 0 when an error occurs.

· Autotuning is canceled if the value of ManCtl changes to TRUE during autotuning.

· The value of Error does not change to TRUE even if an error occurs during autotuning. Autotuning is also not recorded in the event log.

· An error occurs in the following case. Error will change to TRUE, and an error code is assigned to

ErrorID. ATDone and ATBusy change to FALSE. MV is set to the value of ErrorMV if the values of

ManCtl and Run are FALSE. If the value of ErrorMV is outside of the valid range, the value of MV is 0.

Error

Value of ErrorID

2

The value of an input variable is outside of the valid range. 16#0400

RngLowLmt is greater than or equal to RngUpLmt.

16#0401

MVLowLmt is greater than or equal to MVUpLmt.

· If an error stop is required for conditions other than the above, program the system so that the value of Run changes to FALSE when the error occurs.
· If an error occurs because the value of PV or SP exceeds the valid range, the error status is maintained for five seconds even if the value returns to within the valid range sooner. That is, the value of Error will remain FALSE for five seconds.
· Heating/cooling PID control is restarted automatically if the value of Run is TRUE after the error is reset. Autotuning is restarted automatically if the values of Run and StartAT are TRUE.
· A check is made for errors each sampling period.
· If backup and restore operations are performed under the following conditions, the PID constants that were found with autotuning will revert to the values from before the backup operation. Use it with caution.
· A Retain attribute is specified for the in-out parameters.
· The operations are performed in the following order: backup, autotuning, and then restore.
· When you change from automatic operation to manual operation, the value of MV_Heat or MV_Cool, whichever is positive, is taken on to achieve bumpless operation (i.e., to prevent abrupt changes). Therefore, the value of the other variable may change abruptly.

Version Information
A CPU Unit with unit version 1.08 or later and Sysmac Studio version 1.09 or higher are required to use this instruction.

NJ/NX-series Instructions Reference Manual (W502)

2-721

2 Instruction Descriptions

Sample Programming

In this sample, the PIDAT_HeatCool instruction is used to perform temperature control. There is one analog thermocouple input from the controlled system. There are two outputs to the controlled system, a heating digital output and a cooling digital output. The heating digital output turns the heating device ON and OFF. The cooling digital output opens and closes the solenoid valve for the cooling water.

Controller

Thermocouple analog input
Output to turn heating device ON and OFF Output to open and close solenoid cooling water valve

Controlled system

Unit Configuration
The following Units are connected. · CJ1W-AD04U Isolated-type Universal Input Unit · CJ1W-OC201 Relay Contact Output Unit

I/O Map
The I/O maps for the Units are set as shown in the following tables.
 C1JW-AD04U

Port

Description

Ch1_AIInPV

Process value for input 1

Read/ write

Data type

R

INT

Variable J01_Ch1_AIInPV

Variable comment
Thermocouple input

Variable type
Global variable

 CJ1W-OC201

Port Ch1_Out00 Ch1_Out04

Description
Bit 00 of output word 1 Bit 04 of output word 1

Read/ write

Data type

RW BOOL

RW BOOL

Variable J02_Ch1_Out00 J02_Ch1_Out04

Variable comment

Variable type

Output to heat- Global vari-

ing device

able

Output to cool- Global vari-

ing device

able

2-722

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

PIDAT_HeatCool

2 Instruction Descriptions

Touch Panel Specifications
This sample assumes that a touch panel is connected to the Controller. The following I/O information is handled through the touch panel.

I/O

Information

Sample programming execution flag

Manual/auto control flag

Set point

Inputs

Autotuning execution flag

Deadband

Initial setting parameters

2

Operation setting parameters

Proportional band, integration time, and

derivative time for heating control

I/O

Proportional band, integration time, and

derivative time for cooling control

Manual manipulated variable

Outputs

Process value Autotuning normal completion flag Autotuning executing flag Error flag Manipulated variable Manipulated variable for heating control Manipulated variable for cooling control

Converting the Manipulated Variables to Time-proportional Outputs
In this sample, a digital ON/OFF output is used for both the heating device and the cooling device. Therefore, it is necessary to convert the manipulated variables for the heating and cooling devices to time-proportional outputs. The TimeProportionalOut instruction (page 2-735) converts a manipulated variable to a time-proportional output.
However, during autotuning, the outputs to the heating and cooling devices must be changed immediately after the MV_Heat and MV_Cool outputs from the PIDAT_HeatCool instruction change. Therefore, the TimeProportionalOut instruction cannot be used. If the TimeProportionalOut instruction was used, the outputs to the heating and cooling devices would change only at the control period that was set by the user. In this sample, timer instructions are used to convert the manipulated variables to timeproportional outputs during autotuning.

NJ/NX-series Instructions Reference Manual (W502)

2-723

2 Instruction Descriptions

Application Programming
Definitions of Global Variables

Global Variables

Variable

Data type

J01_Ch1_AIInPV

INT

J02_Ch1_Ou t00

BOOL

J02_Ch1_Ou t04

BOOL

PTIn_Run

BOOL

PTIn_ManCtl BOOL

PTIn_SP

REAL

PTIn_StartAT BOOL

PTIn_DeadBand

REAL

PTIn_InitParam

_sINIT_SET_PA RAMS

PTIn_InitSetOpr_SampTime

LINT

PTIn_OprParam

_sOPR_SET_P ARAMS

PTOut_PV REAL PT_PB_Heat REAL

Initial value 0 FALSE FALSE FALSE

AT
IOBus://rack# 0/slot#0/Ch1 _AIInPV
IOBus://rack# 0/slot#1/Ch1 _Out/Ch1_O ut00
IOBus://rack# 0/slot#1/Ch1 _Out/Ch1_O ut04

FALSE

FALSE
0
(SampTime := T#100ms, RngLowLmt := 0.0, RngUpLmt := 100.0, DirOpr := False)
100
(MVLowLmt := -100, MVUpLmt := 100, ManResetVal := 0.0, MVTrackSw := False, MVTrackVal := 0.0, StopMV := 0.0, ErrorMV := 0.0, Alpha := 0.65, ATCalcGain := 1.0, ATHystrs := 0.2)
0
1

Retain

Network Publish Not published. Not published. Not published.
Input
Input Input Input Input
Input
Input
Input
Output Input

Comment
Thermocouple input from CJ1W-AD04U
Heating output to CJ1W-OC201
Cooling output to CJ1W-OC201
Sample programming execution flag input from touch panel Manual/auto control flag input from touch panel Set point input from touch panel Autotuning execution flag input from touch panel Deadband input from touch panel
Initial setting parameter input from touch panel
Sampling period input from touch panel (unit: ms)
Operation setting parameter input from touch panel
Process value output to touch panel Proportional band for heating control I/O from touch panel

2-724

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

PIDAT_HeatCool

2 Instruction Descriptions

Variable

Data type

Initial value

PT_TI_Heat LINT

1000

PT_TD_Heat LINT

1000

PT_PB_Cool REAL

1

PT_TI_Cool LINT

1000

PT_TD_Cool LINT

1000

PT_ManMV REAL

PTOut_ATDone

BOOL

PTOut_ATBusy

BOOL

PTOut_Error BOOL

PTOut_MV REAL

PTOut_MVHeat

REAL

PTOut_MVCool

REAL

0 FALSE FALSE FALSE 0 0
0

Net-

AT

Retain work

Comment

Publish

Input

Integration time for heating control I/O from touch panel (unit: ms)

Input

Derivative time for heating control I/O from touch panel (unit: ms)

Proportional band for

Input

cooling control I/O

2

from touch panel

Input

Integration time for cooling control I/O from touch panel (unit: ms)

Input

Derivative time for cooling control I/O from touch panel (unit: ms)

Input

Manual manipulated variable I/O from touch panel

Output

Autotuning normal completion flag output to touch panel

Output

Autotuning executing flag output to touch panel

Output

Error flag output to touch panel

Output

Manipulated variable output to touch panel

Output

Manipulated variable for heating control output to touch panel

Output

Manipulated variable for cooling control output to touch panel

NJ/NX-series Instructions Reference Manual (W502)

2-725

2 Instruction Descriptions

LD
Internal Variables

Variable

PB_Heat

PB_Cool MV MV_Heat

MV_Cool

PIDAT_HeatCool_inst
TI_Heat TI_Cool TD_Heat TD_Cool ManMV CtlPrd_Cool CtlPrd_Heat
TPOHeat_inst

TPOCool_inst
ATHeatPhase ATCoolPhase MVHeatTime MVCoolTime

AT_Heat_inst

AT_Cool_inst

EachCtlPrd_ATHeat_inst

EachCtlPrd_ATCool_inst PV

Data type
REAL
REAL REAL REAL
REAL
PIDAT_HeatCool TIME TIME TIME TIME REAL TIME TIME TimeProportionalOut TimeProportionalOut BOOL BOOL TIME TIME
TP
TP
TON
TON
REAL

Initial value 0 0 0 0 0
T#0s T#0s T#0s T#0s 0 T#20s T#2s
FALSE FALSE T#0s T#0s
0

Comment
Proportional band for heating control
Proportional band for cooling control
Manipulated variable
Manipulated variable for heating control
Manipulated variable for cooling control
Instance of PIDAT_HeatCool instruction
Integration time for heating control
Integration time for cooling control
Derivative time for heating control
Derivative time for cooling control
Manual manipulated variable
Cooling control period
Heating control period
Instance of TimeProportionalOut instruction for heating control
Instance of TimeProportionalOut instruction for cooling control
Autotuning heating control flag
Autotuning cooling control flag
Autotuning heating control time
Autotuning cooling control time
Instance of TP instruction for heating control manipulated variable output during autotuning
Instance of TP instruction for cooling control manipulated variable output during autotuning
Instance of TON instruction for heating control manipulated variable output during autotuning
Instance of TON instruction for cooling control manipulated variable output during autotuning
Process value

2-726

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

PIDAT_HeatCool

2 Instruction Descriptions

External Variables

Variable

Data type

Comment

J01_Ch1_AIInPV

INT

Thermocouple input from CJ1W-AD04U

J02_Ch1_Out00

BOOL

Heating output to CJ1W-OC201

J02_Ch1_Out04

BOOL

Cooling output to CJ1W-OC201

PTIn_Run

BOOL

Sample programming execution flag input from touch panel

PTIn_ManCtl PTIn_SP

BOOL REAL

Manual/auto control flag input from

touch panel

Set point input from touch panel

2

PTIn_StartAT

BOOL

Autotuning execution flag input from touch panel

PTIn_DeadBand

REAL

Deadband input from touch panel

PTIn_InitParam

_sINIT_SET_PARAMS

Initial setting parameter input from touch panel

PTIn_InitSetOpr_SampTime LINT

Sampling period input from touch panel (unit: ms)

PTIn_OprParam

_sOPR_SET_PARAMS

Operation setting parameter input from touch panel

PTOut_PV

REAL

Process value output to touch panel

PT_PB_Heat

REAL

Proportional band for heating control I/O from touch panel

PT_TI_Heat

LINT

Integration time for heating control I/O from touch panel (unit: ms)

PT_TD_Heat

LINT

Derivative time for heating control I/O from touch panel (unit: ms)

PT_PB_Cool

REAL

Proportional band for cooling control I/O from touch panel

PT_TI_Cool

LINT

Integration time for cooling control I/O from touch panel (unit: ms)

PT_TD_Cool

LINT

Derivative time for cooling control I/O from touch panel (unit: ms)

PT_ManMV

REAL

Manual manipulated variable I/O from touch panel

PTOut_ATDone

BOOL

Autotuning normal completion flag output to touch panel

PTOut_ATBusy

BOOL

Autotuning executing flag output to touch panel

PTOut_Error

BOOL

Error flag output to touch panel

PTOut_MV

REAL

Manipulated variable output to touch panel

PTOut_MVHeat

REAL

Manipulated variable for heating control output to touch panel

PTOut_MVCool

REAL

Manipulated variable for cooling control output to touch panel

NJ/NX-series Instructions Reference Manual (W502)

2-727

2 Instruction Descriptions

Convert unit of input values from CJ1W-AD04U and touch panel. Inline ST Note: The contents of the inline ST are given below at Contents of Inline ST1.

Execute PIDAT_HeatCool instruction.

PIDAT_HeatCool_inst

PTIn_Run

PIDAT_HeatCool

PTIn_ManCtl PTIn_StartAT
PV PTIn_SP PTIn_DeadBand PTIn_OprParam PTIn_InitParam
PB_Heat

Run

ATDone

ManCtl

ATBusy

StartAT

Error

PV

ErrorID

SP

MV

DeadBand

MV_Heat

OprSetParams

MV_Cool

InitSetParams

ProportionalBand_Heat

IntegrationTime_Heat TI_Heat

DerivativeTime_Heat TD_Heat

ProportionalBand_Cool PB_Cool

IntegrationTime_Cool TI_Cool

DerivativeTime_Cool TD_Cool

ManMV ManMV

CtlPrd_Cool CtlPrd_Cool

MV MV_Heat MV_Cool
PB_Heat TI_Heat TD_Heat PB_Cool TI_Cool TD_Cool ManMV

Prepare to convert to time-proportional outputs during execution of autotuning. PIDAT_HeatCool_inst.ATBusy Inline ST Note: The contents of the inline ST are given below at Contents of Inline ST2.

MVHeatTime T#0s

>
EN In1 In2

ATHeatPhase

EachCtlPrd_ATHeat_inst.Q

EachCtlPrd_ATHeat_inst TON

In

Q

CtlPrd_Heat PT

ET

MVCoolTime T#0s

>
EN In1 In2

ATCoolPhase

EachCtlPrd_ATCool_inst.Q

EachCtlPrd_ATCool_inst TON

In

Q

CtlPrd_Cool PT

ET

2-728

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

PIDAT_HeatCool

2 Instruction Descriptions

Heating output to CJ1W-OC201 PIDAT_HeatCool_inst.ATBusy

ATHeatPhase
MVHeatTime CtlPrd_Heat

=
EN In1 In2

MVHeatTime CtlPrd_Heat

<>
EN In1 In2

MVHeat CtlPrd_Heat

TPOHeat_Inst

TimeProportionalOut

Enable AIn CtlPrd MinPlsWidth Delay

DOut Error

J02_Ch1_Out00

AT_Heat

2

EachCtlPrd_ATHeat_inst.Q

TP

ATHeatPhase

In

Q

MVHeatTime PT

ET

Cooling output to CJ1W-OC201 PIDAT_HeatCool_inst.ATBusy

MVCool CtlPrd_Cool

TPOCool_Inst

TimeProportionalOut

Enable AIn CtlPrd MinPlsWidth Delay

DOut Error

ATCoolPhase
MVCoolTime CtlPrd_Cool

=
EN In1 In2

MVCoolTime CtlPrd_Cool

<>
EN In1 In2

EachCtlPrd_ATCool_inst.Q MVCoolTime

AT_Cool

TP

In

Q

PT

ET

Create output values to touch panel. Inline ST Note: The contents of the inline ST are given below at Contents of Inline ST3.

J02_Ch1_Out04 ATCoolPhase

 Contents of Inline ST1
// Convert unit of input values from CJ1W-AD04U and touch panel. PV := INT_TO_REAL(J01_Ch1_AIInPV)/REAL#10.0;
PTIn_InitParam.SampTime := NanoSecToTime(PTIn_InitSetOpr_SampTime*1000000);
PB_Heat := PT_PB_Heat; TI_Heat := NanoSecToTime(PT_TI_Heat*1000000); TD_Heat := NanoSecToTime(PT_TD_Heat*1000000); PB_Cool := PT_PB_Cool; TI_Cool := NanoSecToTime(PT_TI_Cool*1000000); TD_Cool := NanoSecToTime(PT_TD_Cool*1000000);
ManMV := PT_ManMV;

NJ/NX-series Instructions Reference Manual (W502)

2-729

2 Instruction Descriptions

 Contents of Inline ST2
MVHeatTime := MULTIME(CtlPrd_Heat,(MV_Heat/100)); MVCoolTime := MULTIME(CtlPrd_Cool,(MV_Cool/100));

 Contents of Inline ST3
// Create output values to touch panel. PTOut_PV := PV;

PTOut_ATDone := PIDAT_HeatCool_inst.ATDone; PTOut_ATBusy := PIDAT_HeatCool_inst.ATBusy; PTOut_Error := PIDAT_HeatCool_inst.Error;

PTOut_MV

:= PIDAT_HeatCool_inst.MV;

PTOut_MVHeat := PIDAT_HeatCool_inst.MV_Heat;

PTOut_MVCool := PIDAT_HeatCool_inst.MV_Cool;

PT_PB_Heat := PB_Heat; PT_TI_Heat := TimeToNanoSec( TI_Heat )/1000000; PT_TD_Heat := TimeToNanoSec( TD_Heat )/1000000; PT_PB_Cool := PB_Cool; PT_TI_Cool := TimeToNanoSec( TI_Cool )/1000000; PT_TD_Cool := TimeToNanoSec( TD_Cool )/1000000;

PT_ManMV := ManMV;

2-730

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

PIDAT_HeatCool

2 Instruction Descriptions

ST

Internal Variables

Variable

Data type

Initial value

Comment

PB_Heat

REAL

0

Proportional band for heating control

PB_Cool

REAL

0

Proportional band for cooling control

MV

REAL

0

Manipulated variable

MV_Heat MV_Cool

REAL REAL

0

Manipulated variable for heating control

0

Manipulated variable for cooling

2

control

PIDAT_HeatCool_inst

PIDAT_HeatCool

Instance of PIDAT_HeatCool instruction

TI_Heat

TIME

T#0s

Integration time for heating control

TI_Cool

TIME

T#0s

Integration time for cooling control

TD_Heat

TIME

T#0s

Derivative time for heating control

TD_Cool

TIME

T#0s

Derivative time for cooling control

ManMV

REAL

0

Manual manipulated variable

CtlPrd_Cool

TIME

T#20s

Cooling control period

CtlPrd_Heat

TIME

T#2s

Heating control period

TPOHeat_inst

TimeProportionalOut

Instance of TimeProportionalOut instruction for heating control

TPOCool_inst

TimeProportionalOut

Instance of TimeProportionalOut instruction for cooling control

ATHeatPhase

BOOL

FALSE Autotuning heating control flag

ATCoolPhase

BOOL

FALSE Autotuning cooling control flag

MVHeatTime

TIME

T#0s

Autotuning heating control time

MVCoolTime

TIME

T#0s

Autotuning cooling control time

AT_Heat_inst

TP

Instance of TP instruction for heating control manipulated variable output during autotuning

AT_Cool_inst

TP

Instance of TP instruction for cooling control manipulated variable output during autotuning

EachCtlPrd_ATHeat_inst

TON

Instance of TON instruction for heating control manipulated variable output during autotuning

EachCtlPrd_ATCool_inst

TON

Instance of TON instruction for cooling control manipulated variable output during autotuning

PV

REAL

0

Process value

NJ/NX-series Instructions Reference Manual (W502)

2-731

2 Instruction Descriptions

External Variables

Variable
J01_Ch1_AIInPV J02_Ch1_Out00 J02_Ch1_Out04

PTIn_Run

PTIn_ManCtl PTIn_SP PTIn_StartAT PTIn_DeadBand PTIn_InitParam

PTIn_InitSetOpr_SampTime

PTIn_OprParam PTOut_PV PT_PB_Heat

PT_TI_Heat

PT_TD_Heat

PT_PB_Cool

PT_TI_Cool

PT_TD_Cool

PT_ManMV

PTOut_ATDone

PTOut_ATBusy PTOut_Error PTOut_MV

PTOut_MVHeat

PTOut_MVCool

Data type INT BOOL BOOL BOOL BOOL REAL BOOL REAL _sINIT_SET_PARAMS LINT _sOPR_SET_PARAMS REAL REAL LINT LINT REAL LINT LINT REAL BOOL BOOL BOOL REAL REAL REAL

Comment
Thermocouple input from CJ1W-AD04U
Heating output to CJ1W-OC201
Cooling output to CJ1W-OC201
Sample programming execution flag input from touch panel
Manual/auto control flag input from touch panel
Set point input from touch panel
Autotuning execution flag input from touch panel
Deadband input from touch panel
Initial setting parameter input from touch panel
Sampling period input from touch panel (unit: ms)
Operation setting parameter input from touch panel
Process value output to touch panel
Proportional band for heating control I/O from touch panel
Integration time for heating control I/O from touch panel (unit: ms)
Derivative time for heating control I/O from touch panel (unit: ms)
Proportional band for cooling control I/O from touch panel
Integration time for cooling control I/O from touch panel (unit: ms)
Derivative time for cooling control I/O from touch panel (unit: ms)
Manual manipulated variable I/O from touch panel
Autotuning normal completion flag output to touch panel
Autotuning executing flag output to touch panel
Error flag output to touch panel
Manipulated variable output to touch panel
Manipulated variable for heating control output to touch panel
Manipulated variable for cooling control output to touch panel

// Convert unit of input values from CJ1W-AD04U and touch panel. PV := INT_TO_REAL(J01_Ch1_AIInPV)/REAL#10.0;
PTIn_InitParam.SampTime := NanoSecToTime(PTIn_InitSetOpr_SampTime*1000000);

2-732

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Analog Control Instructions

PIDAT_HeatCool

PB_Heat := PT_PB_Heat; TI_Heat := NanoSecToTime(PT_TI_Heat*1000000); TD_Heat := NanoSecToTime(PT_TD_Heat*1000000); PB_Cool := PT_PB_Cool; TI_Cool := NanoSecToTime(PT_TI_Cool*1000000); TD_Cool := NanoSecToTime(PT_TD_Cool*1000000);

ManMV := PT_ManMV;

// Execute PIDAT_HeatCool instruction.

PIDAT_HeatCool_inst(Run

:=PTIn_Run,

ManCtl

:=PTIn_ManCtl,

StartAT

:=PTIn_StartAT,

PV

:=PV,

SP

:=PTIn_SP,

DeadBand

:=PTIn_DeadBand,

OprSetParams

:=PTIn_OprParam,

InitSetParams

:=PTIn_InitParam,

ProportionalBand_Heat :=PB_Heat,

IntegrationTime_Heat :=TI_Heat,

DerivativeTime_Heat :=TD_Heat,

ProportionalBand_Cool :=PB_Cool,

IntegrationTime_Cool :=TI_Cool,

DerivativeTime_Cool :=TD_Cool,

ManMV

:=ManMV,

CtlPrd_Cool

:=CtlPrd_Cool,

MV

=>MV,

MV_Heat

=>MV_Heat,

MV_Cool

=>MV_Cool);

// Prepare to convert to time-proportional outputs during execution // of autotuning. IF PIDAT_HeatCool_inst.ATBusy THEN
MVHeatTime := MULTIME(CtlPrd_Heat, (MV_Heat/100) ); MVCoolTime := MULTIME(CtlPrd_Cool, (MV_Cool/100) ); END_IF;

ATHeatPhase := PIDAT_HeatCool_inst.ATBusy & (MVHeatTime>T#0s); EachCtlPrd_ATHeat_inst(In:= ATHeatPhase & NOT(EachCtlPrd_ATHeat_inst.Q),
PT:= CtlPrd_Heat);

ATCoolPhase := PIDAT_HeatCool_inst.ATBusy & (MVCoolTime>T#0s); EachCtlPrd_ATCool_inst(In:= ATCoolPhase & NOT(EachCtlPrd_ATCool_inst.Q),
PT:= CtlPrd_Cool);

// Heating output to CJ1W-OC201 TPOHeat_inst(Enable :=NOT(PIDAT_HeatCool_inst.ATBusy),
AIn :=MV_Heat, CtlPrd :=CtlPrd_Heat ); AT_Heat_inst(In:= ATHeatPhase & (MVHeatTime<>CtlPrd_Heat) & NOT(EachCtlPrd_ATHeat_inst.Q) , PT:= MVHeatTime); J02_Ch1_Out00 :=( TPOHeat_inst.DOut ) OR
( ATHeatPhase & (MVHeatTime=CtlPrd_Heat)) OR ( AT_Heat_inst.Q & ATHeatPhase );

// Cooling output to CJ1W-OC201 TPOCool_inst(Enable :=NOT(PIDAT_HeatCool_inst.ATBusy),
AIn :=MV_Cool, CtlPrd :=CtlPrd_Cool ); AT_Cool_inst(In:= ATCoolPhase & (MVCoolTime<>CtlPrd_Cool) & NOT(EachCtlPrd_ATCool_inst.Q) , PT:= MVCoolTime); J02_Ch1_Out04 :=( TPOCool_inst.DOut ) OR
( ATCoolPhase & (MVCoolTime=CtlPrd_Cool)) OR

NJ/NX-series Instructions Reference Manual (W502)

2
2-733

2 Instruction Descriptions

( AT_Cool_inst.Q & ATCoolPhase );

// Create output values to touch panel. PTOut_PV := PV;

PTOut_ATDone := PIDAT_HeatCool_inst.ATDone; PTOut_ATBusy := PIDAT_HeatCool_inst.ATBusy; PTOut_Error := PIDAT_HeatCool_inst.Error;

PTOut_MV

:= PIDAT_HeatCool_inst.MV;

PTOut_MVHeat := PIDAT_HeatCool_inst.MV_Heat;

PTOut_MVCool := PIDAT_HeatCool_inst.MV_Cool;

PT_PB_Heat := PB_Heat; PT_TI_Heat := TimeToNanoSec(TI_Heat)/1000000; PT_TD_Heat := TimeToNanoSec(TD_Heat)/1000000; PT_PB_Cool := PB_Cool; PT_TI_Cool := TimeToNanoSec(TI_Cool)/1000000; PT_TD_Cool := TimeToNanoSec(TD_Cool)/1000000;

PT_ManMV := ManMV;

2-734

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

TimeProportionalOut

2 Instruction Descriptions

TimeProportionalOut

The TimeProportionalOut instruction converts a manipulated variable to a time-proportional output.

Instruction

Name

FB/ FUN

Graphic expression

ST expression

TimeProportion alOut

Timeproportional Output

FB

TimeProportionalOut_instance(

TimeProportionalOut_Instance

Enable, AIn,

TimeProportionalOut

CtlPrd,

Enable AIn

DOut Error

MinPlsWidth, Delay,

2

CtlPrd MinPlsWidth Delay

DOut, Error);

Variables

Name

Meaning

I/O

Description

Valid range

Unit

Enable

Enable

TRUE: Execute
FALSE: Reset time-proportional output

Depends on data type.

---

AIn CtlPrd

Manipulated variable
Control period

Input

Manipulated variable
Control period of timeproportional output

0 to 100

%

T#0.1s to T#100s

s

MinPlsWidth

Minimum pulse width

Minimum pulse width

0 to 50

%

Delay

Delay

ON-delay time

0 to 100

%

DOut

Timeproportional output

Output

TRUE: Time-proportional output is ON.
FALSE: Time-proportional output is OFF.

Depends on data type.

---

Default FALSE
0 T#2s 1 0
---

Bit strings

Integers

Times, durations, dates, and text strings

Real numbers

Boolean BOOL

STRING DT TOD
DATE TIME

LREAL REAL

LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE

Enable

OK

AIn

CtlPrd

MinPls Width

Delay

DOut

OK

OK OK
OK OK

NJ/NX-series Instructions Reference Manual (W502)

2-735

2 Instruction Descriptions

Function
The TimeProportionalOut instruction converts a manipulated variable, such as the one for PID control, to a time-proportional output. A time-proportional output converts a manipulated variable to a time ratio between ON and OFF. While Enable is TRUE, the value of manipulated variable AIn is converted to time-proportional output DOut for control period CtlPrd. If Enable changes to FALSE, the time-proportional output is reset. DOut and Error change to FALSE. The values of CtlPrd, MinPlsWidth, and Delay are updated when Enable changes from FALSE to TRUE. The following example is for when the value of CtlPrd is 10 s and the value of AIn is 20%. While Enable is TRUE, DOut is TRUE for two seconds and then FALSE for eight seconds. This is repeated at a 10second period.
LD

TimeProportionalOut_Instance

A

TimeProportionalOut

B

PV T#10s REAL#0 REAL#0

Enable AIn CtlPrd MinPlsWidth Delay

DOut Error Error0

ST TimeProportionalOut_instance(A,PV,T#10s,REAL#0,REAL#0,B,Error0);

TRUE Enable = A FALSE

AIn = PV = 20% TRUE
DOut = B FALSE

CtlPrd = T#10s

2 s

8 s

CtlPrd = T#10s

2 s

8 s

CtlPrd = T#10s 2 s

When Enable changes to TRUE, When Enable changes to FALSE,

DOut starts operation.

DOut changes to FALSE.

Time

Resolution of Time-proportional Output DOut
The minimum unit for the conversion of the value of AIn to DOut is the resolution of DOut. If the resolution of the value of AIn is higher than the resolution of DOut, AIn is rounded to the resolution of DOut when it is converted to DOut. The resolution of DOut is given by the following formula.
Resolution of DOut (%) = Task period ÷ CtlPrd × 100 For example, if the task period is 1 ms and the value of CtlPrd is 1 s, the resolution of DOut is 0.1%. In this case, the digits after the first decimal digit of the value of AIn are truncated.

2-736

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

TimeProportionalOut

2 Instruction Descriptions

Update Timing of the Value of Manipulated Variable AIn
When value of AIn is updated depends on whether DOut is FALSE or TRUE.

 DOut = FALSE

While DOut is FALSE, any change in the value of AIn is applied in the next control period.

CtlPrd = 1 s

CtlPrd = 1 s

700 ms

900 ms

TRUE DOut FALSE

2

AIn

(%)

90

Value updated.

Value updated. 70

If DOut is FALSE when AIn changes, the change is applied in the next control period.

Time

 DOut = TRUE
While DOut is TRUE, any change in the value of AIn is applied immediately.
For example, the following figure shows the operation when the value of control period CtlPrd is 1 s. · If the value of AIn is 60% at the start of the control period and it changes to 50% while DOut is
TRUE, DOut is TRUE for only 500 ms. · Assume that the value of AIn was 90% at the start of the control period, that DOut changes to
TRUE, and that 300 ms later AIn changes to 10%. In this case, 100 ms, which is 10%, has already elapsed, so DOut changes to FALSE immediately.

AIn changes to 50%,

When AIn changes to 10%, over 100 ms has already

so DOut is TRUE for only 500 ms. elapsed since DOut changed to TRUE. Therefore,

DOut changes to FALSE as soon as AIn changes.

DOut

TRUE FALSE

CtlPrd = 1 s 600 ms 500 ms

CtlPrd = 1 s 900 ms
300 ms

AIn

(%)

90

Value

updated. Value

60

updated.

50

Value updated.

Value updated. 10

If DOut is TRUE when AIn changes, the change is applied immediately.

Time

NJ/NX-series Instructions Reference Manual (W502)

2-737

2 Instruction Descriptions

Operation of Time-proportional Output DOut for Minimum Pulse Width MinPlsWidth
The minimum pulse width is the minimum time that DOut will retain a value of TRUE or FALSE. You can set minimum pulse width MinPlsWidth to reduce chattering in DOut. For example, if the number of times a fan is turned ON and OFF is reduced in cooling control, power consumption is reduced.

The following table shows the operation of DOut for the relationship between the values of MinPlsWidth and AIn.

Relationship between the values of MinPlsWidth and AIn AIn < MinPlsWidth

Operation of DOut Always FALSE

MinPlsWidth  AIn  100 - MinPlsWidth AIn > 100 - MinPlsWidth

Time-proportional output Always TRUE

For example, the following figure shows the operation of DOut when MinPlsWidth is 30%. If the value of AIn is greater than 70%, DOut is always TRUE. When AIn decreases to 70% or lower, DOut operates for the time-proportional output.

CtlPrd = 1 s

CtlPrd = 1 s

DOut

TRUE FALSE
AIn (%) 100
70

700 ms

If the value of AIn exceeds If the value of AIn is 70% or lower, DOut 70%, DOut is always TRUE. operates for the time-proportional output.

Value updated.

Value updated.

Time

If the value of AIn is less than 30%, DOut is always FALSE. When AIn increases to 30% or higher, DOut operates for the time-proportional output.

CtlPrd = 1 s

CtlPrd = 1 s

300 ms

DOut

TRUE FALSE

AIn (%)

If the value of AIn is less than 30%, DOut is always FALSE.

If the value of AIn is 30% or higher, DOut operates for the time-proportional output.

Value updated. 30

Value updated.

0 Time

2-738

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Analog Control Instructions

TimeProportionalOut

Operation of Time-proportional Output DOut for Delay

The delay prevents DOut from changing to TRUE until the set time has elapsed from the start of the control period. If more than one of this instruction is used, you can offset the timing of when DOut changes to TRUE by setting Delay. This reduces the chance that DOut will turn ON simultaneously for more than one instruction. For example, if you operate more than one heating device, you can use Delay to offset when the output to each heating device turns ON to reduce the power that is used at any one time.

DOut changes to TRUE after the percentage of time specified with Delay elapses from the start of the control period.

For example, you could set the following values for devices A and B, which have the same control period.

2

Device Device A

Value of Delay 0%

Value of AIn Value of CtlPrd

20%

10 s

Device B

30%

DOut for device A changes to TRUE at the start of the control period. DOut for device B changes to TRUE three seconds after the start of the control period.

TRUE DOut for device A FALSE
TRUE DOut for device B FALSE

CtlPrd = 10 s 2 s
3s 2s

CtlPrd = 10 s 2 s

3s 2s

Time

Precautions for Correct Use

· Set the value of control period CtlPrd to a multiple of the task period of the task to which the program is assigned. If the task period is not set to a multiple of CtlPrd, the actual control period will be from when control period CtlPrd ends until the next time the task is executed. For example, if the task period is set to 3 ms and the value of CtlPrd is 1 s, the actual control period will be 1,002 ms (from when CtlPrd ends until the next time the task is executed).

TRUE DOut FALSE

Actual control period = 1,002 ms CtlPrd = 1 s

Time

Task period = 3 ms

2 ms

· Set the task period and control period CtlPrd so that the resolution of DOut is 0.1% or less. If the resolution of DOut exceeds 0.1%, the error between the ratio when DOut is TRUE and the value of AIn will be excessive and control performance will decrease. For example, if CtlPrd is 10 s, set the task period to 10 ms or lower.
· If you use more than one of this instruction and need to synchronize the control periods, use the instructions in the same program. If you use them in different programs, the control periods will depend on the timing of the execution of the programs, and they will not be synchronized.
· The time from when the value of Enable changes to TRUE and operation starts for DOut is not constant.

NJ/NX-series Instructions Reference Manual (W502)

2-739

2 Instruction Descriptions

· An error occurs if the value of AIn, CtlPrd, MinPlsWidth, or Delay is outside of the valid range. Error changes to TRUE and DOut changes to FALSE. If the value of AIn exceeds the valid range, the operation of DOut will be as shown below depending on when the error is reset.
· If the error is reset after the point where DOut changes to TRUE, the time-proportional output for DOut is restarted from the next control period.

DOut

TRUE FALSE

Error

TRUE FALSE

AIn (%)
101

CtlPrd = 1 s 600 ms

CtlPrd = 1 s

CtlPrd = 1 s 600 ms

The value of AIn is

The value of AIn is inside of

outside of the valid range, the valid range, so Error is

so Error is TRUE.

FALSE.

Value updated.

Value updated.

Time-proportional output is restarted from the next control period after the error is reset.

60 Value updated.

Time

· If the error is reset before the point where DOut changes to TRUE, the time-proportional output for DOut is restarted in the control period in which the error was reset.

Delay = 20%

CtlPrd = 1 s

200 ms 600 ms

CtlPrd = 1 s 200 ms 600 ms

DOut

TRUE FALSE

Error

AIn (%)
101

Time-proportional output is restarted in the control period in which the error was reset. The value of AIn is outside of the The value of AIn is inside of the valid range, so Error is TRUE. valid range, so Error is FALSE.

Value updated.

Value updated.

60 Value updated.

Time

Version Information
A CPU Unit with unit version 1.02 or later and Sysmac Studio version 1.03 or higher are required to use this instruction.

Sample Programming

This sample performs temperature control for four points with upper/lower limit alarms and upper/lower deviation alarms. PID control is performed. The manipulated variables of PID control are converted to
time-proportional output values that are output to heating devices.

Process temperature Set point

PID control

Conversion to time-proportional output

Heating device

2-740

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Analog Control Instructions

TimeProportionalOut

Specifications

Temperature control is performed according to the following specifications.

Item

Specification

Input Unit

CJ1W-PH41U Isolated-type Universal Input Unit

Input types

K thermocouples

Output Unit

CJ1W-OD212 Transistor Output Unit

Set point

100°C

Upper limit of temperature

200°C

Lower limit of temperature

0°C

2

Hysteresis of upper/lower limit alarm

5°C

Upper deviation temperature

50°C

Lower deviation temperature

50°C

Hysteresis of upper/lower deviation alarm 3°C

Sampling period for PID control

100 ms

Output control period

1 s

Configuration and Settings

The following settings are used for the CJ1W-PH41U Input Unit.

Item Input1:Input signal type Input2:Input signal type Input3:Input signal type Input4:Input signal type

Set value K(1) K(1) K(1) K(1)

The following I/O map settings are used.

Unit

I/O port

Description

Ch1_AIInPV

Process value for input 1 (INT data)

CJ1W-PH41U

Ch2_AIInPV Ch3_AIInPV

Process value for input 2 (INT data) Process value for input 3 (INT data)

Ch4_AIInPV

Process value for input 4 (INT data)

Ch1_Out00

Bit 00 of output word 1

CJ1W-OD212

Ch1_Out01 Ch1_Out02

Bit 01 of output word 1 Bit 02 of output word 1

Ch1_Out03

Bit 03 of output word 1

Variable AI1 AI2 AI3 AI4 DO1 DO2 DO3 DO4

The inputs and outputs for the temperature control for the four points correspond as shown below.

Input

Output

AI1

DO1

AI2

DO2

AI3

DO3

AI4

DO4

The task period of the task to which the program is assigned is 1 ms.

NJ/NX-series Instructions Reference Manual (W502)

2-741

2 Instruction Descriptions

 Configuration Diagram
CJ1W-PH41U CJ1W-OD212

Bit 00 of output word 1
Bit 01 of output word 1
Bit 02 of output word 1
Bit 03 of output word 1

Heating device Control target
Sensor with K thermocouple

Input 1

Heating device Control target
Sensor with K thermocouple

Input 2

Heating device Control target
Sensor with K thermocouple

Input 3

Heating device Control target
Sensor with K thermocouple

Input 4

Processing
Perform the following procedure for all four points.
1 Get the process temperature. 2 Use the LimitAlarm_REAL instruction to output upper/lower limit alarms for the process tem-
perature.
3 Perform an output as a safety measure if an error occurs in the LimitAlarm_REAL instruction or
if an upper/lower limit alarm occurs.
4 Use the LimitAlarmDv_REAL instruction to output upper/lower deviation alarms for the deviation
between the set point and the process temperature.
5 Perform an output as a safety measure if an error occurs in the LimitAlarmDv_REAL instruction
or if an upper/lower deviation alarm occurs.
6 Perform temperature control with the PIDAT instruction.
7 Use the TimeProportionalOut instruction to output the manipulated variable as a time-propor-
tional value to the heating device.

2-742

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Analog Control Instructions

TimeProportionalOut

 Operation of Upper/Lower Limit Alarms and Upper/Lower Deviation Alarms

Process temperature (°C)
Upper limit of temperature 200 195
150 Upper deviation temperature = 50°C 147
Set point 100
Lower deviation temperature = 50°C 53 50
5 Lower limit of temperature 0

Hysteresis of upper/ lower limit alarm = 5°C

Hysteresis of upper/ lower deviation alarm = 3°C

2
Time

Upper limit alarm TRUE FALSE
Lower limit alarm TRUE FALSE

Upper deviation alarm

TRUE FALSE

Lower deviation alarm

TRUE FALSE

Error in LimitAlarm_REAL instruction Yes No
Error in LimitAlarmDv_REAL instruction Yes No

Output for safety measure

TRUE

for LimitAlarm_REAL instruction FALSE

Output for safety measure

TRUE

for LimitAlarmDv_REAL instruction FALSE

Application Programming
Definitions of Global Variables

Global Variables

Name AI1

Data type
INT

AT*1 IOBus://rack#0/slot#0/Ch1_AIInPV

AI2

INT

IOBus://rack#0/slot#0/Ch2_AIInPV

AI3

INT

IOBus://rack#0/slot#0/Ch3_AIInPV

AI4
DO1 DO2 DO3 DO4

INT
BOOL BOOL BOOL BOOL

IOBus://rack#0/slot#0/Ch4_AIInPV
IOBus://rack#0/slot#1/Ch1_Out/Ch1_Out00 IOBus://rack#0/slot#1/Ch1_Out/Ch1_Out01 IOBus://rack#0/slot#1/Ch1_Out/Ch1_Out02 IOBus://rack#0/slot#1/Ch1_Out/Ch1_Out03

NJ/NX-series Instructions Reference Manual (W502)

Comment
Process value for input 1 (INT data) Process value for input 2 (INT data) Process value for input 3 (INT data) Process value for input 4 (INT data) Bit 00 of output word 1 Bit 01 of output word 1 Bit 02 of output word 1 Bit 03 of output word 1
2-743

2 Instruction Descriptions

*1 AT when the CJ1W-PH41U Unit is mounted to slot number 0 in rack number 0 and the CJ1W-OD212 Unit is mounted to slot number 1 in rack number 0.

Note The global variables that are assigned to an I/O port of a Unit are automatically created according to the I/O map settings.
LD

Internal Variables

Name

index

LimitAlarm_ON

Data type UINT BOOL

0 True

Default

LimitAlarmDv_ON BOOL

True

TimeProportion alOut_ON

BOOL

AI

INT

PV

ARRAY[0..3] OF REAL

SP

ARRAY[0..3] OF REAL

DOut_TPO

BOOL

True
0 [4(0.0)] [4(100)] False

HighVal

ARRAY[0..3] OF REAL [4(200)]

LowVal

ARRAY[0..3] OF REAL [4(0.0)]

Hystrs_LimitAlarm ARRAY[0..3] OF REAL [4(5)]

Q_LimitAlarm

ARRAY[0..3] OF BOOL

HighAlm LowAlm

ARRAY[0..3] OF BOOL ARRAY[0..3] OF BOOL

Error_LimitAlarm ARRAY[0..3] OF BOOL

[4(False)]
[4(False)] [4(False)]
[4(False)]

Alm_LimitAlarm ARRAY[0..3] OF BOOL [4(False)]

DvHighVal

ARRAY[0..3] OF REAL [4(50)]

DvLowVal

ARRAY[0..3] OF REAL [4(50)]

Q_LimitAlarmDv
HighAlmDv LowAlmDv Error_LimitAlarmDv
Hystrs_LimitAlarmDv

ARRAY[0..3] OF BOOL ARRAY[0..3] OF BOOL ARRAY[0..3] OF BOOL ARRAY[0..3] OF BOOL
ARRAY[0..3] OF REAL

[4(False)] [4(False)] [4(False)] [4(False)]
[4(3)]

Alm_LimitAlarmDv
Run

ARRAY[0..3] OF BOOL [4(False)] ARRAY[0..3] OF BOOL [4(False)]

Retain

Comment

Loop index
Execution of Upper/Lower Limit Alarm instruction
Execution of Upper/Lower Deviation Alarm instruction
Execution of Timeproportional Output instruction
Present value
Process value
Set point
Time-proportional output
Upper limit set value of upper/lower limit alarm
Lower limit set value of upper/lower limit alarm
Hysteresis of upper/lower limit alarm
Upper/lower limit alarm output
Upper limit alarm
Lower limit alarm
Error in LimitAlarm_REAL instruction
Output for safety measure for Upper/Lower Limit Alarm instruction
Upper deviation set value of upper/lower deviation alarm
Lower deviation set value of upper/lower deviation alarm
Upper/lower deviation alarm output
Upper deviation alarm
Lower deviation alarm
Error in LimitAlarmDv_REAL instruction
Hysteresis of upper/lower deviation alarm
Output for safety measure for Upper/Lower Deviation Alarm instruction
Execution condition

2-744

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Analog Control Instructions

TimeProportionalOut

Internal Variables

Name

Data type

Default

Retain

Comment

ManCtl

ARRAY[0..3] OF BOOL [4(False)]

Manual/auto control

StartAT

ARRAY[0..3] OF BOOL [4(False)]

Autotuning execution condition

OprSetParams InitSetParams

_sOPR_SET_PARAMS _sINIT_SET_PARAMS

(MVLowLmt:=0.0, MVUpLmt:=100.0, ManResetVal:=0.0, MVTrackSw:=False, MVTrackVal:=0.0, StopMV:=0.0, ErrorMV:=0.0, Alpha:=0.65, ATCalcGain:=1.0, ATHystrs:=0.2)
(SampTime:=T#100ms, RngLowLmt:=-10.0,
RngUpLmt:=1000.0, DirOpr:=False)

Operation setting parameters
2
Initial setting parameters

PB

ARRAY[0..3] OF REAL [4(10)]

Proportional band

TI

ARRAY[0..3] OF TIME [4(T#0S)]

Integration time

TD ManMV

ARRAY[0..3] OF TIME ARRAY[0..3] OF REAL

[4(T#0S)] [4(0.0)]

ATDone ATBusy Error_PIDAT

ARRAY[0..3] OF BOOL ARRAY[0..3] OF BOOL ARRAY[0..3] OF BOOL

[4(False)] [4(False)] [4(False)]

ErrorID

ARRAY[0..3] OF WORD

MV CtlPrd MinPlsWidth Delay

ARRAY[0..3] OF REAL ARRAY[0..3] OF TIME ARRAY[0..3] OF REAL ARRAY[0..3] OF REAL

Error_TimeProp ortionalOut

ARRAY[0..3] OF BOOL

LimitAlarm_REAL_instance
LimitAlarmDv_REAL_instance
PIDAT_instance
TimeProportion alOut_instance

ARRAY[0..3] OF LimitAlarm_REAL
ARRAY[0..3] OF LimitAlarmDv_REAL
ARRAY[0..3] OF PIDAT
ARRAY[0..3] OF TimeProportionalOut

[4(16#0)]
[4(0.0)] [4(T#1s)] [4(0.0)] [4(0.0)]
[4(False)]

Derivative time
Manual manipulated variable
Autotuning normal completion
Autotuning busy
Error in PIDAT instruction
Error ID for PIDAT instruction
Manipulated variable
Control period
Minimum pulse width
ON-delay time
Error in TimeProportionalOut instruction

External Variables
AI1 AI2 AI3 AI4 DO1 DO2 DO3 DO4

Name

INT INT INT INT BOOL BOOL BOOL BOOL

NJ/NX-series Instructions Reference Manual (W502)

Data type

Comment
Process value for input 1 Process value for input 2 Process value for input 3 Process value for input 4 Bit 00 of output word 1 Bit 01 of output word 1 Bit 02 of output word 1 Bit 03 of output word 1
2-745

2 Instruction Descriptions

Control temperature for four points.

UINT#0 UINT#3 UINT#1

FOR EN InitVal EndVal StepVal

ENO Index

index

Obtain the process value. Inline ST
Note: Refer to Contents of Inline ST 1 for the contents of the inline ST.

Upper/lower limit alarm
LimitAlarm_ON
HighVal[index] PV[index]
LowVal[index] Hystrs_LimitAlarm[index]

LimitAlarm_REAL_Instance[index] LimitAlarm_REAL

Q_LimitAlarm[index]

Enable H X L EPS

Q QH QL Error

HighAlm[index] LowAlm[index] Error_LimitAlarm[index]

Perform an output as a safety measure if an error occurs in the LimitAlarm_REAL instruction or if an upper/lower limit alarm occurs.

Q_LimitAlarm[index] Error_LimitAlarm[index]

OR

EN

ENO

In1

In2

Alm_LimitAlarm[index]

Upper/lower deviation alarm
LimitAlarmDv_ON
PV[index] DvHighVal[index]
SP[index] DvLowVal[index] Hystrs_LimitAlarmDv[index]

LimitAlarmDv_REAL_Instance[index] LimitAlarmDv_REAL

Q_LimitAlarmDv[index]

Enable

Q

X

QH HighAlmDv[index]

H

QL LowAlmDv[index]

Y

Error Error_LimitAlarmDv[index]

L

EPS

Perform an output as a safety measure if an error occurs in the LimitAlarmDv_REAL instruction or if an upper/lower limit alarm occurs.

Q_LimitAlarmDv[index] Error_LimitAlarmDv[index]

OR

EN

ENO

In1

In2

Alm_LimitAlarmDv[index]

2-746

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Analog Control Instructions

TimeProportionalOut

Execute PIDAT instruction. PIDAT_instance[index]

Run[index]

PIDAT

ManCtl[index] StartAT[index]
PV[index] SP[index] OprSetParams InitSetParams
PB[index]
TI[index]
TD[index]
ManMV[index]

Run

ATDone

ManCtl

ATBusy

StartAT

Error

PV

ErrorID

SP

MV

OprSetParams

InitSetParams

ProportionalBand

IntegrationTime

DerivativeTime

ManMV

ATDone[index]
ATBusy[index] Error_PIDAT[index] ErrorID[index] MV[index]
PB[index] TI[index] TD[index] ManMV[index]

Time-proportional output TimeProportionalOut_ON

TimeProportionalOut_Instance[index] TimeProportionalOut

DOut_TPO

MV[index] CtlPrd[index] MinPlsWidth[index] Delay[index]

Enable AIn CtlPrd MinPlsWidth Delay

DOut Error

Error_TimeProportionalOut[index]

Perform outputs for bits 00 to 03 of output word 1. Inline ST
Note: Refer to Contents of Inline ST 2 for the contents of the inline ST.

NEXT

EN

ENO

 Contents of Inline ST 1
// Get values of inputs 1 to 4. CASE index OF
INT#0: AI:=AI1;
INT#1: AI:=AI2;
INT#2: AI:=AI3;
ELSE AI:=AI4;
END_CASE;
// Convert PV AI to real number. PV[index]:=INT_TO_REAL(AI)/REAL#10.0; // CJ1W-PH41U output is ten times the process value, so divide by 10.0.

 Contents of Inline ST 2
// Perform outputs for bits 00 to 03 of output word 1. CASE index OF
INT#0: DO1:=DOut_TPO;
INT#1: DO2:=DOut_TPO;
INT#2: DO3:=DOut_TPO;
ELSE DO4:=DOut_TPO;
END_CASE;

NJ/NX-series Instructions Reference Manual (W502)

2
2-747

2 Instruction Descriptions

ST

Internal Variables

Name

index

LimitAlarm_ON

Data type UINT BOOL

0 True

Default

LimitAlarmDv_ON BOOL

True

TimeProportionalO ut_ON

BOOL

AI

INT

PV

ARRAY[0..3] OF REAL

SP

ARRAY[0..3] OF REAL

DOut_TPO

BOOL

True
0 [4(0.0)] [4(100)] False

HighVal

ARRAY[0..3] OF REAL [4(200)]

LowVal

ARRAY[0..3] OF REAL [4(0.0)]

Hystrs_LimitAlarm ARRAY[0..3] OF REAL [4(5)]

Q_LimitAlarm
HighAlm LowAlm
Error_LimitAlarm

ARRAY[0..3] OF BOOL
ARRAY[0..3] OF BOOL ARRAY[0..3] OF BOOL
ARRAY[0..3] OF BOOL

[4(False)]
[4(False)] [4(False)]
[4(False)]

Alm_LimitAlarm

ARRAY[0..3] OF BOOL [4(False)]

DvHighVal

ARRAY[0..3] OF REAL [4(50)]

DvLowVal

ARRAY[0..3] OF REAL [4(50)]

Q_LimitAlarmDv

ARRAY[0..3] OF BOOL

HighAlmDv LowAlmDv

ARRAY[0..3] OF BOOL ARRAY[0..3] OF BOOL

Error_LimitAlarmDv ARRAY[0..3] OF BOOL

[4(False)]
[4(False)] [4(False)]
[4(False)]

Hystrs_LimitAlarmDv ARRAY[0..3] OF REAL [4(3)]

Alm_LimitAlarmDv ARRAY[0..3] OF BOOL [4(False)]

Run ManCtl
StartAT

ARRAY[0..3] OF BOOL ARRAY[0..3] OF BOOL
ARRAY[0..3] OF BOOL

[4(False)] [4(False)]
[4(False)]

Retain

Comment

Loop index
Execution of Upper/Lower Limit Alarm instruction
Execution of Upper/Lower Deviation Alarm instruction
Execution of Timeproportional Output instruction
Present value
Process value
Set point
Time-proportional output
Upper limit set value of upper/lower limit alarm
Lower limit set value of upper/lower limit alarm
Hysteresis of upper/lower limit alarm
Upper/lower limit alarm output
Upper limit alarm
Lower limit alarm
Error in LimitAlarm_REAL instruction
Output for safety measure for Upper/Lower Limit Alarm instruction
Upper deviation set value of upper/lower deviation alarm
Lower deviation set value of upper/lower deviation alarm
Upper/lower deviation alarm output
Upper deviation alarm
Lower deviation alarm
Error in LimitAlarmDv_REAL instruction
Hysteresis of upper/lower deviation alarm
Output for safety measure for Upper/Lower Deviation Alarm instruction
Execution condition
Manual/auto control
Autotuning execution condition

2-748

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Analog Control Instructions

TimeProportionalOut

Internal Variables

Name

Data type

Default

Retain

Comment

OprSetParams

_sOPR_SET_PARAMS

(MVLowLmt:=0.0, MVUpLmt:=100.0, ManResetVal:=0.0, MVTrackSw:=False, MVTrackVal:=0.0, StopMV:=0.0, ErrorMV:=0.0, Alpha:=0.65, ATCalcGain:=1.0, ATHystrs:=0.2)

Operation setting parameters

InitSetParams

_sINIT_SET_PARAMS

(SampTime:=T#100ms, RngLowLmt:=-10.0, RngUpLmt:=1000.0, DirOpr:=False)

Initial setting parame-

ters

2

PB

ARRAY[0..3] OF REAL [4(10)]

Proportional band

TI

ARRAY[0..3] OF TIME [4(T#0S)]

Integration time

TD ManMV

ARRAY[0..3] OF TIME ARRAY[0..3] OF REAL

[4(T#0S)] [4(0.0)]

ATDone ATBusy Error_PIDAT

ARRAY[0..3] OF BOOL ARRAY[0..3] OF BOOL ARRAY[0..3] OF BOOL

[4(False)] [4(False)] [4(False)]

ErrorID

ARRAY[0..3] OF WORD

MV CtlPrd MinPlsWidth Delay

ARRAY[0..3] OF REAL ARRAY[0..3] OF TIME ARRAY[0..3] OF REAL ARRAY[0..3] OF REAL

Error_TimeProporti onalOut

ARRAY[0..3] OF BOOL

LimitAlarm_REAL_instance

ARRAY[0..3] OF LimitAlarm_REAL

LimitAlarmDv_RE- ARRAY[0..3] OF

AL_instance

LimitAlarmDv_REAL

PIDAT_instance

ARRAY[0..3] OF PIDAT

TimeProportionalO ARRAY[0..3] OF

ut_instance

TimeProportionalOut

[4(16#0)]
[4(0.0)] [4(T#1s)] [4(0.0)] [4(0.0)]
[4(False)]

Derivative time
Manual manipulated variable
Autotuning normal completion
Autotuning busy
Error in PIDAT instruction
Error ID for PIDAT instruction
Manipulated variable
Control period
Minimum pulse width
ON-delay time
Error in TimeProportionalOut instruction

External Variables
AI1 AI2 AI3 AI4 DO1 DO2 DO3 DO4

Name

INT INT INT INT BOOL BOOL BOOL BOOL

Data type

Comment
Process value for input 1 Process value for input 2 Process value for input 3 Process value for input 4 Bit 00 of output word 1 Bit 01 of output word 1 Bit 02 of output word 1 Bit 03 of output word 1

NJ/NX-series Instructions Reference Manual (W502)

2-749

2 Instruction Descriptions

2-750

// Control temperature for four points. FOR index:=UINT#0 TO UINT#3 BY UINT#1 DO

// Get values of inputs 1 to 4. CASE index OF INT#0: AI:=AI1; INT#1: AI:=AI2; INT#2: AI:=AI3; ELSE AI:=AI4;
END_CASE;

// Convert PV AI to real number. PV[index]:=INT_TO_REAL(AI)/REAL#10.0; // CJ1W-PH41U output is ten times // the process value, so divide by 10.0.

// Upper/lower limit alarm

LimitAlarm_REAL_instance[index](

Enable :=LimitAlarm_ON,

H

:=HighVal[index],

X

:=PV[index],

L

:=LowVal[index],

EPS :=Hystrs_LimitAlarm[index],

Q

=>Q_LimitAlarm[index],

QH

=>HighAlm[index],

QL

=>LowAlm[index],

Error =>Error_LimitAlarm[index]);

// Perform an output as a safety measure if an error occurs in the // LimitAlarmDv_REAL instruction or if an upper/lower limit alarm occurs.
Alm_LimitAlarm[index]:=Q_LimitAlarm[index] OR Error_LimitAlarm[index];

// Upper/lower deviation alarm

LimitAlarmDv_REAL_instance[index](

Enable :=LimitAlarmDv_ON,

X

:=PV[index],

H

:=DvHighVal[index],

Y

:=SP[index],

L

:=DvLowVal[index],

EPS :=Hystrs_LimitAlarmDv[index],

Q

=>Q_LimitAlarmDv[index],

QH

=>HighAlmDv[index],

QL

=>LowAlmDv[index],

Error =>Error_LimitAlarmDv[index]);

// Perform an output as a safety measure if an error occurs in the // LimitAlarmDv_REAL instruction or if an upper/lower limit alarm occurs. Alm_LimitAlarmDv[index]:=Q_LimitAlarmDv[index] OR Error_LimitAlarmDv[index];

// Execute PIDAT instruction.

PIDAT_instance[index](

Run

:=Run[index],

ManCtl

:=ManCtl[index],

StartAT

:=StartAT[index],

PV

:=PV[index],

SP

:=SP[index],

OprSetParams :=OprSetParams,

InitSetParams :=InitSetParams,

ProportionalBand:=PB[index],

IntegrationTime :=TI[index],

DerivativeTime :=TD[index],

ManMV

:=ManMV[index],

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

2 Instruction Descriptions

ATDone ATBusy Error ErrorID MV

=>ATDone[index], =>ATBusy[index], =>Error_PIDAT[index], =>ErrorID[index], =>MV[index]);

// Time-proportional output

TimeProportionalOut_instance[index](

Enable

:=TimeProportionalOut_ON,

AIn

:=MV[index],

CtlPrd

:=CtlPrd[index],

MinPlsWidth :=MinPlsWidth[index],

Delay

:=Delay[index],

DOut Error

=>DOut_TPO, =>Error_TimeProportionalOut[index]);

2

// Perform outputs for bits 00 to 03 of output word 1. CASE index OF
INT#0: DO1:=DOut_TPO;
INT#1: DO2:=DOut_TPO;
INT#2: DO3:=DOut_TPO;
ELSE DO4:=DOut_TPO;
END_CASE;

END_FOR;

TimeProportionalOut

NJ/NX-series Instructions Reference Manual (W502)

2-751

2 Instruction Descriptions

LimitAlarm_**

The LimitAlarm_** instruction outputs an alarm if the input value is below the lower limit set value or above the upper limit set value.

Instruction

Name

FB/ FUN

Upper/Lower

LimitAlarm_** Limit Alarm

FB

Group

Graphic expression

LimitAlarm_**_Instance

LimitAlarm_**

Enable H X L EPS

Q QH QL Error

ST expression
LimitAlarm_**_instance( Enable, H, X, L, EPS, Q, QH, QL, Error);

"**" must be REAL or LREAL.

"**" must be REAL or LREAL.

Variables

Name Enable H X L EPS
Q
QH
QL

Meaning

I/O

Description

Valid range

Unit

Enable

TRUE: Execute FALSE: Reset alarm

Upper limit set value
Input value

Input

Upper limit set value for the input value
Value to monitor

Depends on data type.
---

Lower limit set value

Lower limit set value for the input value

Hysteresis

Hysteresis of the alarm

Depends on data type.*

Alarm output

TRUE: There is either an upper limit alarm or a lower limit alarm.
FALSE: There is neither an upper limit alarm nor a lower limit alarm.

Upper limit alarm

Output

TRUE: There is an upper limit alarm.
FALSE: There is no upper limit

Depends on data type.

---

alarm.

Lower limit alarm

TRUE: There is a lower limit alarm.
FALSE: There is no lower limit alarm.

* Negative numbers are excluded.

Default FALSE 0
---

2-752

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Analog Control Instructions

Real numbers

Boolean BOOL

LimitAlarm_**

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME

LREAL REAL

LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE

Enable

OK

H

X

L

EPS

Q

OK

QH

OK

QL

OK

OK OK

Must be same data type as H.

Must be same data type as H.

2

Must be same data type as H.

Function
The LimitAlarm_** instruction monitors the input value to see if it is between the lower limit set value and the upper limit set value. The LimitAlarm_** instruction outputs an alarm if the input value is below the lower limit set value or above the upper limit set value. Use this instruction in temperature control, e.g., to monitor the process temperature.
Input value X is monitored while Enable is TRUE. If the value of X exceeds the value of upper limit set value H, upper limit alarm QH changes to TRUE. If the value of X goes below the value of lower limit set value L, lower limit alarm QL changes to TRUE. If the value of either QH or QL is TRUE, the value of alarm output Q is TRUE. The values of X, H, L, and hysteresis EPS are continuously updated while Enable is TRUE.
If Enable changes to FALSE, the alarm is reset. When the alarm is reset, Q, QH, and QL change to FALSE.
The data types of H, X, L, and EPS must be either REAL or LREAL. The name of the instruction is determined by the data types of H, X, L, and EPS. If the name of the instruction is LimitAlarm_LREAL, the data types of H, X, L, and EPS are all LREAL.

Operation of Upper Limit Alarm QH

The value of upper limit alarm QH changes as shown below. You can set the hysteresis to prevent hunting in the limit alarm.
· If Input value X > Upper limit set value H, then QH is TRUE.
· If Input value X < Upper limit set value H - Hysteresis EPS, then QH is FALSE.

Input value X Upper limit set value H

Hysteresis EPS

TRUE Upper limit alarm QH FALSE

Time

NJ/NX-series Instructions Reference Manual (W502)

2-753

2 Instruction Descriptions

Operation of Lower Limit Alarm QL
The value of lower limit alarm QL changes as shown below. You can set the hysteresis to prevent hunting in the limit alarm. · If Input value X < Lower limit set value L, then QL is TRUE. · If Input value X > Lower limit set value L + Hysteresis EPS, then QL is FALSE.
Input value X
Hysteresis EPS
Lower limit set value L

Lower

limit

alarm

QL

TRUE FALSE

Time

Notation Example

The following notation example sets upper limit set value H to 100°C, lower limit set value L to 50°C, and hysteresis EPS to 10°C.

LD

A
LREAL#100 PV
LREAL#50 LREAL#10

LimitAlarm_LREAL_Instance

LimitAlarm_LREAL

Enable H X L EPS

Q QH QL Error

Alarm
H_Alarm L_Alarm Error0

ST LimitAlarm_LREAL_instance(A,LREAL#100,PV,LREAL#50,LREAL#10,Alarm,H_Alarm,L_Alarm,Error0);

X = PV (°C)
H = LREAL#100

L = LREAL#50

Enable = A QH = H_Alarm QL = L_Alarm
Q = Alarm

TRUE FALSE
TRUE FALSE
TRUE FALSE
TRUE FALSE

EPS = LREAL#10 Time

2-754

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

LimitAlarm_**

2 Instruction Descriptions

Additional Information

· Use the LimitAlarm_REAL instruction to reduce the instruction execution time. · You can set EPS to less than H - L. If you do so, both QH and QL can be TRUE at the same time.

Input value X

Hysteresis EPS for the lower limit alarm

Upper limit set value H Lower limit set value L

Hysteresis EPS for the upper limit alarm
2

Upper limit alarm QH TRUE FALSE
Lower limit alarm QL TRUE FALSE

Time

· You can set H and L so that H < L. If you do so, either QH or QL will always be TRUE.

Input value X Lower limit set value L

Hysteresis EPS for the lower limit alarm

Upper limit set value H
Upper limit alarm QH TRUE FALSE
Lower limit alarm QL TRUE FALSE

Hysteresis EPS for the upper limit alarm
Time

Precautions for Correct Use
· An error occurs if the value of EPS is outside of the valid range. Error changes to TRUE, and Q, QH, and QL change to FALSE.
· You can use this instruction for safety measures, for example, to turn OFF a temperature control output when an alarm is output. If you do so, design the safety measures so that safety is maintained even when an error causes Q, QH, and HL to change to FALSE. For an application example, refer to the sample programming that is provided for the TimeProportionalOut instruction (page 2-735).
Version Information
A CPU Unit with unit version 1.02 or later and Sysmac Studio version 1.03 or higher are required to use this instruction.

Sample Programming
Refer to the sample programming that is provided for the TimeProportionalOut instruction (page 2-735).

NJ/NX-series Instructions Reference Manual (W502)

2-755

2 Instruction Descriptions

LimitAlarmDv_**

The LimitAlarmDv_** instruction outputs an alarm if the deviation in the input value from the reference value exceeds the lower deviation set value or the upper deviation set value.

Instruction

Name

FB/ FUN

Upper/Lower

LimitAlarmDv_** Deviation

FB

Alarm Group

Graphic expression

LimitAlarmDv_**_Instance

LimitAlarmDv_**

Enable X H Y L EPS

Q QH QL Error

ST expression
LimitAlarmDv_**instance( Enable, X, H, Y, L, EPS, Q, QH, QL, Error);

"**" must be REAL or LREAL.

"**" must be REAL or LREAL.

Variables

Name Enable X H Y L EPS
Q
QH
QL

Meaning

I/O

Description

Valid range

Unit

Enable

TRUE: Execute FALSE: Reset alarm

Input value

Value to monitor

Upper

Set value for an alarm for an

deviation set

upward deviation in respect to Depends on

value

the reference value

data type.

Reference value

Input

Reference value for deviation

---

Lower deviation set value

Set value for an alarm for a downward deviation in respect to the reference value

Hysteresis

Hysteresis of the alarm

Depends on data type.*

Deviation alarm output

TRUE: There is either an upper deviation alarm or a lower deviation alarm.
FALSE: There is neither an upper deviation alarm nor a lower deviation alarm.

Upper deviation alarm

Output

TRUE: There is an upper deviation alarm.
FALSE: There is no upper deviation alarm.

Depends on data type.

---

Lower deviation alarm

TRUE: There is a lower deviation alarm.
FALSE: There is no lower deviation alarm.

* Negative numbers are excluded.

Default FALSE 0
---

2-756

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

LimitAlarmDv_**

2 Instruction Descriptions

Real numbers

Boolean BOOL

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME

LREAL REAL

LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE

Enable

OK

X

H

Y

L

EPS

Q

OK

QH

OK

QL

OK

OK OK

Must be same data type as X.

Must be same data type as X.

2

Must be same data type as X.

Must be same data type as X.

Function
The LimitAlarmDv_** instruction monitors the deviation in the input value from the reference value to see if it exceeds the lower deviation set value or the upper deviation set value. If the deviation exceeds the lower deviation set value or the upper deviation set value, the instruction outputs an alarm. Use this instruction in temperature control, e.g., to monitor the deviation in the process temperature from the set point.
The deviation in input value X from the reference value Y is monitored while Enable is TRUE. If the upward deviation in X from Y exceeds the value of upper deviation set value H, upper deviation alarm QH changes to TRUE. If the downward deviation in X from Y exceeds the value of lower deviation set value L, lower deviation alarm QL changes to TRUE. If the value of either QH or QL is TRUE, the value of alarm output Q is TRUE. The values of X, H, Y, L, and hysteresis EPS are continuously updated while Enable is TRUE.
If Enable changes to FALSE, the alarm is reset. When the alarm is reset, Q, QH, and QL change to FALSE.
The data types of X, H, Y, L, and EPS must be either REAL or LREAL. The name of the instruction is determined by the data types of X, H, Y, L, and EPS. If the name of the instruction is LimitAlarmDv_LREAL, the data types of X, H, Y, L, and EPS are all LREAL.

NJ/NX-series Instructions Reference Manual (W502)

2-757

2 Instruction Descriptions

Operation of Upper Deviation Alarm QH

Upper deviation alarm QH is the alarm for an upward deviation in respect to reference value Y. The value of QH changes as shown below. You can set the hysteresis to prevent hunting in the deviation alarm.
· If Input value X - Reference value Y > Upper deviation set value H, then QH is TRUE.
· If Input value X - Reference value Y < Upper deviation set value H - Hysteresis EPS, then QH is FALSE.

Input value X

Upper deviation set value H

Hysteresis EPS

Reference value X

Upper deviation alarm QH

TRUE FALSE

Time

Operation of Lower Deviation Alarm QL

Lower deviation alarm QL is the alarm for a downward deviation in respect to reference value Y. The value of QL changes as shown below. You can set the hysteresis to prevent hunting in the deviation alarm.
· If -(Input value X - Reference value Y) > Lower deviation set value L, then QL is TRUE.
· If -(Input value X - Reference value Y) < Lower deviation set value L - Hysteresis EPS, then QL is FALSE.

Input value X

Lower deviation set value L

Reference value X

Lower deviation alarm QL TRUE FALSE

Hysteresis EPS Time

2-758

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

LimitAlarmDv_**

2 Instruction Descriptions

Notation Example

The following notation example sets upper deviation set value H to 50°C, lower deviation set value L to 40°C, and hysteresis EPS to 10°C.

LD

LimitAlarmDv_LREAL_Instance

A

LimitAlarmDv_LREAL

Alarm

Enable

Q

PV X

QH

H_Alarm

LREAL#50 H

QL

L_Alarm

SP Y

Error

Error0

2

LREAL#40 L

LREAL#10 EPS

ST LimitAlarmDv_LREAL_instance(A,PV,LREAL#50,SP,LREAL#40,LREAL#10,Alarm,H_Alarm,L_Alarm,Error0);

X = PV (°C)
H = LREAL#50
Y = SP L = LREAL#40

TRUE Enable = A FALSE

QH = H_Alarm QL = L_Alarm

TRUE FALSE
TRUE FALSE

Q = Alarm

TRUE FALSE

EPS = LREAL#10 Time

Additional Information

· Use the LimitAlarmDv_REAL instruction to reduce the instruction execution time. · You can set EPS to less than H + L. If you do so, both QH and QL can be TRUE at the same time.

Input value X Upper deviation set value H

Hysteresis EPS

Lower deviation set value L for the lower deviation alarm

Reference value X

Hysteresis EPS for the upper deviation alarm

Upper deviation alarm QH Lower deviation alarm QL

TRUE FALSE
TRUE FALSE

Time

NJ/NX-series Instructions Reference Manual (W502)

2-759

2 Instruction Descriptions

· You can set H and L so that H + L = 0. If you do so, either QH or QL will always be TRUE. For example, the following figure shows the operation when the value of L is -60 and the value of H is 30.

Input value X

Lower deviation set value L = -60 Upper deviation set value H = 30

Hysteresis EPS for the lower deviation alarm = 10

Reference value X
Upper deviation alarm QH TRUE FALSE
Lower deviation alarm QL TRUE FALSE

Hysteresis EPS for the upper deviation alarm = 10
Time

Precautions for Correct Use
· An error occurs if the value of EPS is outside of the valid range. Error changes to TRUE, and Q, QH, and QL change to FALSE.
· You can use this instruction for safety measures, for example, to turn OFF a temperature control output when a deviation alarm is output. If you do so, design the safety measures so that safety is maintained even when an error causes Q, QH, and HL to change to FALSE. For an application example, refer to the sample programming that is provided for the TimeProportionalOut instruction (page 2735).
Version Information
A CPU Unit with unit version 1.02 or later and Sysmac Studio version 1.03 or higher are required to use this instruction.

Sample Programming
Refer to the sample programming that is provided for the TimeProportionalOut instruction (page 2-735).

2-760

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

LimitAlarmDvStbySeq_**

2 Instruction Descriptions

LimitAlarmDvStbySeq_**

The LimitAlarmDvStbySeq_** instruction outputs upper and lower deviation alarms with a standby sequence.

Instruction

Name

FB/ FUN

Upper/Lower

Deviation

LimitAlarmDvStbySeq_**

Alarm with Standby

FB

Sequence

Group

Graphic expression

ST expression

LimitAlarmDvStbySeq_**_instance(

Enable,

X,

H,

2

LimitAlarmDvStbySeq_**_Instance

Y,

LimitAlarmDvStbySeq_**

L,

Enable X

Q

EPS,

QH

Q,

H

QL

QH,

Y

StbySeqFlag

QL,

L

Error

StbySeqFlag,

EPS

Error);

"**" must be REAL or LREAL.

"**" must be REAL or LREAL.

Variables

Name Enable X H Y L EPS
Q
QH
QL StbySeq Flag

Meaning
Enable
Input value Upper deviation set value Reference value Lower deviation set value
Hysteresis
Deviation alarm output
Upper deviation alarm
Lower deviation alarm Standby Sequence Enabled Flag

I/O Input
Output

Description

Valid range

TRUE: Execute

FALSE: Reset alarm

Value for deviation alarm

Set value for an alarm for an upward devi- Depends on

ation in respect to the reference value

data type.

Reference value for deviation

Set value for an alarm for a downward deviation in respect to the reference value

Hysteresis of the alarm

Depends on data type.*

TRUE: There is either an upper deviation alarm or a lower deviation alarm.

FALSE: There is neither an upper deviation alarm nor a lower deviation alarm.

TRUE: There is an upper deviation alarm.

FALSE: There is no upper deviation alarm.

Depends on data type.

TRUE: There is a lower deviation alarm.

FALSE: There is no lower deviation alarm.

Unit ---
---

TRUE: Enabled FALSE: Disabled

* Negative numbers are excluded.

Default FALSE 0
---

NJ/NX-series Instructions Reference Manual (W502)

2-761

2 Instruction Descriptions

Real numbers

Boolean BOOL

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME

LREAL REAL

LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE

Enable

OK

X

H

Y

L

EPS

Q

OK

QH

OK

QL

OK

StbySeq Flag

OK

OK OK Must be same data type as X. Must be same data type as X. Must be same data type as X. Must be same data type as X.

Function
The LimitAlarmDvStbySeq_** instruction monitors the deviation in the input value from the reference value to see if it exceeds the lower deviation set value or the upper deviation set value. If the deviation exceeds the lower deviation set value or the upper deviation set value, the instruction outputs an alarm. However, the instruction will not output an alarm until the reference value first goes to between the lower and upper deviation set values. Use this instruction in temperature control, e.g., to not output a deviation alarm until the process temperature is stable.
The deviation in input value X from the reference value Y is monitored while Enable is TRUE. However, the deviation is not monitored while Standby Sequence Enabled Flag StbySeqFlag is TRUE. If the upper deviation in X from Y exceeds the value of upper deviation set value H, upper deviation alarm QH changes to TRUE. If the lower deviation in X from Y exceeds the value of lower deviation set value L, lower deviation alarm QL changes to TRUE. If the value of either QH or QL is TRUE, the value of alarm output Q is TRUE. The values of X, H, Y, L, and EPS are continuously updated while Enable is TRUE.
If Enable changes to FALSE, the alarm is reset. When the alarm is reset, Q, QH, QL, and StbySeqFlag change to FALSE.

2-762

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Analog Control Instructions

LimitAlarmDvStbySeq_**

StbySeqFlag changes to FALSE when all of the following conditions are met after Enable changes to TRUE. After StbySeqFlag changes to FALSE, it will not change to TRUE until Enable changes from FALSE to TRUE.
· Input value X - Reference value Y < Upper deviation set value H - Hysteresis EPS
· -(Input value X - Reference value Y) < Lower deviation set value L - Hysteresis EPS

X (°C)

StbySeqFlag changes to FALSE when the value of X enters this range after Enable changes to TRUE.

Upper deviation set value H Y
Lower deviation set value L

Hysteresis
2

Enable TRUE FALSE
Standby Sequence Enabled TRUE Flag StbySeqFlag FALSE

Even when the deviation of X from Y exceeds L, StbySeqFlag remains FALSE.
Time

The data types of X, H, Y, L, and EPS must be either REAL or LREAL. The name of the instruction is determined by the data types of X, H, Y, L, and EPS. If the name of the instruction is LimitAlarmDvStbySeq_LREAL, the data types of X, H, Y, L, and EPS are all LREAL.

Operation of Upper Deviation Alarm QH

Upper deviation alarm QH is the alarm for an upward deviation in respect to reference value Y. The value of QH changes as shown below while StbySeqFlag is FALSE. You can set the hysteresis to prevent hunting in the deviation alarm.
· If Input value X - Reference value Y > Upper deviation set value H, then QH is TRUE.
· If Input value X - Reference value Y < Upper deviation set value H - Hysteresis EPS, then QH is FALSE.

Input value X

Upper deviation set value H

Hysteresis EPS

Reference value X

Upper

deviation

alarm

QH

TRUE FALSE

Standby Sequence Enabled Flag StbySeqFlag

TRUE FALSE

Time StbySeqFlag is TRUE, so QH does not change to TRUE.

Operation of Lower Deviation Alarm QL
Lower deviation alarm QL is the alarm for a downward deviation in respect to reference value Y. The value of QL changes as shown below while StbySeqFlag is FALSE. You can set the hysteresis to prevent hunting in the deviation alarm. · If -(Input value X - Reference value Y) > Lower deviation set value L, then QL is TRUE.

NJ/NX-series Instructions Reference Manual (W502)

2-763

2 Instruction Descriptions

· If -(Input value X - Reference value Y) < Lower deviation set value L - Hysteresis EPS, then QL is FALSE.

Input value X Reference value X

Lower deviation set value H

Hysteresis EPS

Lower

deviation

alarm

QL

TRUE FALSE

Standby Sequence TRUE Enabled Flag StbySeqFlag FALSE

Time StbySeqFlag is TRUE, so QL does not change to TRUE.

Notation Example

The following notation example sets upper deviation set value H to 50°C, lower deviation set value L to 40°C, and hysteresis EPS to 10°C.

LD

LimitAlarmDvStbySeq_LREAL_Instance

A

LimitAlarmDvStbySeq_LREAL

Alarm

PV LREAL#50
SP LREAL#40 LREAL#10

Enable X H Y L EPS

Q QH QL StbySeqFlag Error

H_Alarm L_Alarm Stby Error0

ST

LimitAlarmDvStbySeq_LREAL_Instance(A,PV,LREAL#50,SP,LREAL#40,LREAL#10,Alarm,H_Alarm,L_Alarm,Stby,Error0);

X = PV (°C)
H = LREAL#50
Y = SP L = LREAL#40

EPS = LREAL#10

Enable = A

TRUE FALSE

StbySeqFlag = Stby TRUE FALSE

QH = H_Alarm QL = L_Alarm

TRUE FALSE
TRUE FALSE

Q = Alarm

TRUE FALSE

Time

2-764

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Analog Control Instructions

LimitAlarmDvStbySeq_**

Additional Information
· Use the LimitAlarmDvStbySeq_REAL instruction to reduce the instruction execution time. · You can set EPS to less than H + L. If you do so, both QH and QL can be TRUE at the same time.
Refer to the LimitAlarmDv_** instruction (page 2-756). · You can set H and L so that H + L < 0. If you do so, either QH or QL will always be TRUE while
StbySeqFlag is FALSE. Refer to the LimitAlarmDv_** instruction (page 2-756).
Precautions for Correct Use · An error occurs if the value of EPS is outside of the valid range. Error changes to TRUE, and Q, QH, 2
and QL change to FALSE. · You can use this instruction for safety measures, for example, to turn OFF a temperature control out-
put when a deviation alarm is output. If you do so, design the safety measures so that safety is maintained even when an error causes Q, QH, and QL to change to FALSE. Refer to Sample Programming for an application example.
Version Information
A CPU Unit with unit version 1.02 or later and Sysmac Studio version 1.03 or higher are required to use this instruction.

Sample Programming

This sample performs temperature control for four points with upper/lower limit alarms and upper/lower deviation alarms with standby sequences. PID control is performed. The manipulated variables of PID
control are converted to time-proportional output values that are output to heating devices.

Process temperature Set point

PID control

Conversion to time-proportional output

Heating device

Specifications

Temperature control is performed according to the following specifications.

Item

Specification

Input Unit

CJ1W-PH41U Isolated-type Universal Input Unit

Input types Output Unit

K thermocouples CJ1W-OD212 Transistor Output Unit

Set point Upper limit of temperature Lower limit of temperature Hysteresis of upper/lower limit alarm Upper deviation temperature Lower deviation temperature Hysteresis of upper/lower deviation alarm Sampling period for PID control

100°C 200°C 0°C 5°C 50°C 50°C 3°C 100 ms

Output control period

1 s

NJ/NX-series Instructions Reference Manual (W502)

2-765

2 Instruction Descriptions

Configuration and Settings

The following settings are used for the CJ1W-PH41U Input Unit.

Item Input1:Input signal type Input2:Input signal type Input3:Input signal type Input4:Input signal type

Set value K(1) K(1) K(1) K(1)

The following I/O map settings are used.

Unit

I/O port

Description

Ch1_AIInPV

Process value for input 1 (INT data)

CJ1W-PH41U

Ch2_AIInPV Ch3_AIInPV

Process value for input 2 (INT data)
Process value for input 3 (INT data)

Ch4_AIInPV Ch1_Out00

Process value for input 4 (INT data)
Bit 00 of output word 1

CJ1W-OD212

Ch1_Out01 Ch1_Out02 Ch1_Out03

Bit 01 of output word 1 Bit 02 of output word 1 Bit 03 of output word 1

Variable AI1
AI2
AI3
AI4 DO1 DO2 DO3 DO4

The inputs and outputs for the temperature control for the four points correspond as shown below.

Input AI1 AI2 AI3 AI4

Output DO1 DO2 DO3 DO4

The task period of the task to which the program is assigned is 1 ms.

 Configuration Diagram
Refer to the sample programming that is provided for the TimeProportionalOut instruction (page 2735).

Processing
Perform the following procedure for all four points.
1 Get the process temperature.
2 Use the LimitAlarm_REAL instruction to output upper/lower limit alarms for the process tem-
perature.
3 Perform an output as a safety measure if an error occurs in the LimitAlarm_REAL instruction or
if an upper/lower limit alarm occurs.

2-766

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

LimitAlarmDvStbySeq_**

2 Instruction Descriptions

4 Use the LimitAlarmDvStbySeq_REAL instruction to output upper/lower deviation alarms with a
standby sequence for the deviation between the set point and the process temperature.
5 Perform an output as a safety measure if an error occurs in the LimitAlarmDvStbySeq_REAL
instruction or if an upper/lower deviation alarm occurs.
6 Perform temperature control with the PIDAT instruction.

7 Use the TimeProportionalOut instruction to output the manipulated variable as a time-propor-

tional value to the heating device.

 Operation of Upper/Lower Limit Alarms and Upper/Lower Deviation Alarms

2

with Standby Sequence

Process temperature (°C)
Upper limit of temperature 200 195
150 Upper deviation temperature = 50°C 147
Set point 100

Hysteresis of upper/

Hysteresis of upper/

lower deviation alarm = 3°C lower limit alarm = 5°C

Lower deviation temperature = 50°C 53 50
5 Lower limit of temperature 0

Upper limit alarm

TRUE FALSE

Lower limit alarm

TRUE FALSE

Time

TRUE Upper deviation alarm FALSE

Lower deviation alarm TRUE FALSE

Standby sequence Enabled Disabled

Error in LimitAlarm_REAL instruction Yes No
Error in LimitAlarmDv_REAL instruction Yes No

Output for safety measure for LimitAlarm_REAL instruction

TRUE FALSE

Output for safety measure for

TRUE

LimitAlarmDvStbySeq_REAL instruction FALSE

NJ/NX-series Instructions Reference Manual (W502)

2-767

2 Instruction Descriptions

Application Programming

LD

Name

Data type

index

UINT

0

LimitAlarm_ON

BOOL

True

Default

LimitAlarmDvStbySeq_ON

BOOL

True

TimeProportionalO ut_ON

BOOL

AI

INT

PV

ARRAY[0..3] OF REAL

SP

ARRAY[0..3] OF REAL

DOut_TPO

BOOL

True
0 [4(0.0)] [4(100)] False

HighVal

ARRAY[0..3] OF REAL [4(200)]

LowVal

ARRAY[0..3] OF REAL [4(0.0)]

Hystrs_LimitAlarm ARRAY[0..3] OF REAL [4(5)]

Q_LimitAlarm
HighAlm LowAlm
Error_LimitAlarm

ARRAY[0..3] OF BOOL
ARRAY[0..3] OF BOOL ARRAY[0..3] OF BOOL
ARRAY[0..3] OF BOOL

[4(False)]
[4(False)] [4(False)]
[4(False)]

Alm_LimitAlarm

ARRAY[0..3] OF BOOL [4(False)]

DvHighVal

ARRAY[0..3] OF REAL [4(50)]

DvLowVal

ARRAY[0..3] OF REAL [4(50)]

Q_LimitAlarmDv
HighAlmDv LowAlmDv
StbySeqFlag

ARRAY[0..3] OF BOOL
ARRAY[0..3] OF BOOL ARRAY[0..3] OF BOOL
ARRAY[0..3] OF BOOL

[4(False)]
[4(False)] [4(False)]
[4(False)]

Error_LimitAlarmDvStbySeq

ARRAY[0..3] OF BOOL

[4(False)]

Hystrs_LimitAlarmDv ARRAY[0..3] OF REAL [4(3)]

Retain

Comment

Loop index

Execution of Upper/Lower Limit Alarm instruction

Execution of Upper/Lower Deviation Alarm with Standby Sequence instruction

Execution of TimeProportionalOut instruction

Present value

Process value

Set point

Time-proportional output

Upper limit set value of upper/lower limit alarm

Lower limit set value of upper/lower limit alarm

Hysteresis of upper/lower limit alarm

Upper/lower limit alarm output

Upper limit alarm

Lower limit alarm

Error in LimitAlarm_REAL instruction

Output for safety measure for Upper/Lower Limit Alarm instruction

Upper deviation set value of upper/lower deviation alarm

Lower deviation set value of upper/lower deviation alarm

Upper/lower deviation alarm output

Upper deviation alarm

Lower deviation alarm

Standby Sequence Enabled Flag

Error in LimitAlarmDvStbySeq_REAL instruction

Hysteresis of upper/lower deviation alarm

2-768

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

LimitAlarmDvStbySeq_**

2 Instruction Descriptions

Name

Data type

Default

Retain

Comment

Alm_LimitAlarmDv ARRAY[0..3] OF BOOL [4(False)]

Output for safety measure for Upper/Lower Deviation Alarm instruction

Run

ARRAY[0..3] OF BOOL [4(False)]

Execution condition

ManCtl

ARRAY[0..3] OF BOOL [4(False)]

Manual/auto control

StartAT

ARRAY[0..3] OF BOOL [4(False)]

Autotuning execution condition

(MVLowLmt:=0.0, MVUpLmt:=100.0,

OprSetParams

_sOPR_SET_PARAMS

ManResetVal:=0.0, MVTrackSw:=False, MVTrackVal:=0.0, StopMV:=0.0, ErrorMV:=0.0, Alpha:=0.65, ATCalcGain:=1.0, ATHystrs:=0.2)

Operation setting parameters

2

InitSetParams

_sINIT_SET_PARAMS

(SampTime:=T#100ms, RngLow-Lmt:=-10.0, RngUpLmt:=1000.0, DirOpr:=False)

Initial setting parameters

PB

ARRAY[0..3] OF REAL [4(10)]

Proportional band

TI

ARRAY[0..3] OF TIME [4(T#0S)]

Integration time

TD ManMV

ARRAY[0..3] OF TIME ARRAY[0..3] OF REAL

[4(T#0S)] [4(0.0)]

ATDone ATBusy Error_PIDAT

ARRAY[0..3] OF BOOL ARRAY[0..3] OF BOOL ARRAY[0..3] OF BOOL

[4(False)] [4(False)] [4(False)]

ErrorID

ARRAY[0..3] OF WORD

MV CtlPrd MinPlsWidth Delay

ARRAY[0..3] OF REAL ARRAY[0..3] OF TIME ARRAY[0..3] OF REAL ARRAY[0..3] OF REAL

Error_TimeProportio nalOut

ARRAY[0..3] OF BOOL

LimitAlarm_REAL_instance
LimitAlarmDvStbySeq_REAL_instance
PIDAT_instance
TimeProportionalO ut_instance

LimitAlarm_REAL
LimitAlarmDvStbySeq_REAL PIDAT
TimeProportionalOut

[4(16#0)]
[4(0.0)] [4(T#1s)] [4(0.0)] [4(0.0)]
[4(False)]

Derivative time
Manual manipulated variable
Autotuning normal completion
Autotuning busy
Error in PIDAT instruction
Error ID for PIDAT instruction
Manipulated variable
Control period
Minimum pulse width
ON-delay time
Error in TimeProportionalOut instruction

NJ/NX-series Instructions Reference Manual (W502)

2-769

2 Instruction Descriptions

Control temperature for four points.

UINT#0 UINT#3 UINT#1

FOR EN InitVal EndVal StepVal

ENO Index

index

Obtain the process value. Inline ST
Note: Refer to Contents of Inline ST 1 for the contents of the inline ST.

Upper/lower limit alarm
LimitAlarm_ON
HighVal[index] PV[index]
LowVal[index] Hystrs_LimitAlarm[index]

LimitAlarm_REAL_Instance

LimitAlarm_REAL

Enable H X L EPS

Q QH QL Error

Q_LimitAlarm[index]
HighAlm[index] LowAlm[index] Error_LimitAlarm[index]

Perform an output as a safety measure if an error occurs in the LimitAlarm_REAL instruction or if an upper/lower limit alarm occurs.

Q_LimitAlarm[index] Error_LimitAlarm[index]

OR

EN

ENO

In1

In2

Alm_LimitAlarm[index]

Upper/lower deviation alarm with standby sequence

LimitAlarmStbySeqDv_ON

LimitAlarmDvStbySeq_REAL_Instance LimitAlarmDvStbySeq_REAL

PV[index] DvHighVal[index]
SP[index] DvLowVal[index] Hystrs_LimitAlarmDv[index]

Enable X H Y L EPS

Q QH QL StbySeqFlag Error

Q_LimitAlarmDv[index]
HighAlmDv[index] LowAlmDv[index] StbySeqFlag[index] Error_LimitAlarmDvStbySeqFlag[index]

Perform an output as a safety measure if an error occurs in the LimitAlarmDvStbySeq_REAL instruction or if an upper/lower limit alarm occurs.

Q_LimitAlarmDv[index] Error_LimitAlarmDvStbySeq[index]

OR

EN

ENO

In1

In2

Alm_LimitAlarmDv[index]

2-770

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Analog Control Instructions

LimitAlarmDvStbySeq_**

Execute PIDAT instruction. Run[index]

PIDAT_instance PIDAT

ManCtl[index] StartAT[index]
PV[index] SP[index] OprSetParams InitSetParams
PB[index]
TI[index]
TD[index]
ManMV[index]

Run

ATDone

ManCtl

ATBusy

StartAT

Error

PV

ErrorID

SP

MV

OprSetParams

InitSetParams

ProportionalBand

IntegrationTime

DerivativeTime

ManMV

ATDone[index]
ATBusy[index] Error_PIDAT[index] ErrorID[index] MV[index]
PB[index] TI[index] TD[index] ManMV[index]

Time-proportional output TimeProportionalOut_ON
MV[index] CtlPrd[index] MinPlsWidth[index] Delay[index]

TimeProportionalOut_Instance

TimeProportionalOut

Enable AIn CtlPrd MinPlsWidth Delay

DOut Error

DOut_TPO Error_TimeProportionalOut[index]

Perform outputs for bits 00 to 03 of output word 1. Inline ST
Note: Refer to Contents of Inline ST 2 for the contents of the inline ST.

NEXT

EN

ENO

 Contents of Inline ST 1
// Get values of inputs 1 to 4. CASE index OF
INT#0: AI:=AI1;
INT#1: AI:=AI2;
INT#2: AI:=AI3;
ELSE AI:=AI4;
END_CASE;
// Convert PV AI to real number. PV[index]:=INT_TO_REAL(AI)/REAL#10.0; // CJ1W-PH41U output is ten times the process value, so divide by 10.0.
 Contents of Inline ST 2
// Perform outputs for bits 00 to 03 of output word 1. CASE index OF
INT#0: DO1:=DOut_TPO;
INT#1: DO2:=DOut_TPO;
INT#2: DO3:=DOut_TPO;
ELSE DO4:=DOut_TPO;
END_CASE;

NJ/NX-series Instructions Reference Manual (W502)

2
2-771

2 Instruction Descriptions

ST Name
index
LimitAlarm_ON

Data type UINT
BOOL

0 True

Default

LimitAlarmDvStbySeq_ON

BOOL

True

TimeProportionalO ut_ON

BOOL

AI

INT

PV

ARRAY[0..3] OF REAL

SP

ARRAY[0..3] OF REAL

DOut_TPO

BOOL

True
0 0.0 [4(100)] False

HighVal

ARRAY[0..3] OF REAL [4(200)]

LowVal

ARRAY[0..3] OF REAL [4(0.0)]

Hystrs_LimitAlarm ARRAY[0..3] OF REAL [4(5)]

Q_LimitAlarm
HighAlm LowAlm
Error_LimitAlarm

ARRAY[0..3] OF BOOL
ARRAY[0..3] OF BOOL ARRAY[0..3] OF BOOL
ARRAY[0..3] OF BOOL

[4(False)]
[4(False)] [4(False)]
[4(False)]

Alm_LimitAlarm

ARRAY[0..3] OF BOOL [4(False)]

DvHighVal

ARRAY[0..3] OF REAL [4(50)]

DvLowVal

ARRAY[0..3] OF REAL [4(50)]

Q_LimitAlarmDv
HighAlmDv LowAlmDv
StbySeqFlag

ARRAY[0..3] OF BOOL
ARRAY[0..3] OF BOOL ARRAY[0..3] OF BOOL
ARRAY[0..3] OF BOOL

[4(False)]
[4(False)] [4(False)]
[4(False)]

Error_LimitAlarmDvStbySeq

ARRAY[0..3] OF BOOL

[4(False)]

Hystrs_LimitAlarmDv ARRAY[0..3] OF REAL [4(3)]

Alm_LimitAlarmDv ARRAY[0..3] OF BOOL [4(False)]

Run ManCtl

ARRAY[0..3] OF BOOL ARRAY[0..3] OF BOOL

[4(False)] [4(False)]

Retain

Comment

Loop index

Execution of Upper/Lower Limit Alarm instruction

Execution of Upper/Lower Deviation Alarm with Standby Sequence instruction

Execution of Timeproportional Output instruction

Present value

Process value

Set point

Time-proportional output

Upper limit set value of upper/lower limit alarm

Lower limit set value of upper/lower limit alarm

Hysteresis of upper/lower limit alarm

Upper/lower limit alarm output

Upper limit alarm

Lower limit alarm

Error in LimitAlarm_REAL instruction

Output for safety measure for Upper/Lower Limit Alarm instruction

Upper deviation set value of upper/lower deviation alarm

Lower deviation set value of upper/lower deviation alarm

Upper/lower deviation alarm output

Upper deviation alarm

Lower deviation alarm

Standby Sequence Enabled Flag

Error in LimitAlarmDvStbySeq_REAL instruction

Hysteresis of upper/lower deviation alarm

Output for safety measure for Upper/Lower Deviation Alarm instruction

Execution condition

Manual/auto control

2-772

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Analog Control Instructions

LimitAlarmDvStbySeq_**

Name StartAT OprSetParams
InitSetParams

Data type ARRAY[0..3] OF BOOL _sOPR_SET_PARAMS
_sINIT_SET_PARAMS

Default
[4(False)]
(MVLowLmt:=0.0, MVUpLmt:=100.0, ManResetVal:=0.0, MVTrackSw:=False, MVTrackVal:=0.0, StopMV:=0.0, ErrorMV:=0.0, Alpha:=0.65, ATCalcGain:=1.0, ATHystrs:=0.2) (SampTime:=T#100ms, RngLowmt:=-10.0, RngUpLmt:=1000.0, DirOpr:=False)

Retain

Comment

Autotuning execution condition

Operation setting parameters

Initial setting parameters

PB

ARRAY[0..3] OF REAL [4(10)]

TI

ARRAY[0..3] OF TIME [4(T#0S)]

Proportional band

Integration time

2

TD ManMV

ARRAY[0..3] OF TIME ARRAY[0..3] OF REAL

[4(T#0S)] [4(0.0)]

ATDone ATBusy Error_PIDAT

ARRAY[0..3] OF BOOL ARRAY[0..3] OF BOOL ARRAY[0..3] OF BOOL

[4(False)] [4(False)] [4(False)]

ErrorID

ARRAY[0..3] OF WORD

MV CtlPrd MinPlsWidth Delay

ARRAY[0..3] OF REAL ARRAY[0..3] OF TIME ARRAY[0..3] OF REAL ARRAY[0..3] OF REAL

Error_TimeProporti onalOut

ARRAY[0..3] OF BOOL

LimitAlarm_REAL_instance

LimitAlarm_REAL

LimitAlarmDvStby- LimitAlarmDvStbySeq_Seq_REAL_instance REAL

PIDAT_instance

PIDAT

TimeProportionalO ut_instance

TimeProportionalOut

[4(16#0)]
[4(0.0)] [4(T#1s)] [4(0.0)] [4(0.0)]
[4(False)]

Derivative time
Manual manipulated variable
Autotuning normal completion
Autotuning busy
Error in PIDAT instruction
Error ID for PIDAT instruction
Manipulated variable
Control period
Minimum pulse width
ON-delay time
Error in TimeProportionalOut instruction

// Control temperature for four points. FOR index:=UINT#0 TO UINT#3 BY UINT#1 DO
// Get values of inputs 1 to 4. CASE index OF
INT#0: AI:=AI1;
INT#1: AI:=AI2;
INT#2: AI:=AI3;
ELSE AI:=AI4;
END_CASE;
// Convert PV AI to real number. PV[index]:=INT_TO_REAL(AI)/REAL#10.0; // CJ1W-PH41U output is ten times the // process value, so divide by 10.0.
// Upper/lower limit alarm

NJ/NX-series Instructions Reference Manual (W502)

2-773

2 Instruction Descriptions

2-774

LimitAlarm_REAL_instance(

Enable :=LimitAlarm_ON,

H

:=HighVal[index],

X

:=PV[index],

L

:=LowVal[index],

EPS :=Hystrs_LimitAlarm[index],

Q

=>Q_LimitAlarm[index],

QH

=>HighAlm[index],

QL

=>LowAlm[index],

Error =>Error_LimitAlarm[index]);

// Perform an output as a safety measure if an error occurs in the // LimitAlarm_REAL instruction or if an upper/lower limit alarm occurs.
Alm_LimitAlarm[index]:=Q_LimitAlarm[index] OR Error_LimitAlarm[index];

// Upper/lower deviation alarm with standby sequence

LimitAlarmDvStbySeq_REAL_instance(

Enable

:=LimitAlarmDvStbySeq_ON,

X

:=PV[index],

H

:=DvHighVal[index],

Y

:=SP[index],

L

:=DvLowVal[index],

EPS

:=Hystrs_LimitAlarmDv[index],

Q

=>Q_LimitAlarmDv[index],

QH

=>HighAlmDv[index],

QL

=>LowAlmDv[index],

StbySeqFlag =>StbySeqFlag[index],

Error

=>Error_LimitAlarmDvStbySeq[index]);

// Perform an output as a safety measure if an error occurs in the // LimitAlarmDvStbySeq_REAL instruction // or if an upper/lower limit alarm occurs. Alm_LimitAlarmDv[index]:=Q_LimitAlarmDv[index] OR Error_LimitAlarmDvStbySeq[index];

// Execute PIDAT instruction.

PIDAT_instance(

Run

:=Run[index],

ManCtl

:=ManCtl[index],

StartAT

:=StartAT[index],

PV

:=PV[index],

SP

:=SP[index],

OprSetParams :=OprSetParams,

InitSetParams :=InitSetParams,

ProportionalBand:=PB[index],

IntegrationTime :=TI[index],

DerivativeTime :=TD[index],

ManMV

:=ManMV[index],

ATDone

=>ATDone[index],

ATBusy

=>ATBusy[index],

Error

=>Error_PIDAT[index],

ErrorID

=>ErrorID[index],

MV

=>MV[index]);

// Time-proportional output

TimeProportionalOut_instance(

Enable

:=TimeProportionalOut_ON,

AIn

:=MV[index],

CtlPrd

:=CtlPrd[index],

MinPlsWidth :=MinPlsWidth[index],

Delay

:=Delay[index],

DOut

=>DOut_TPO,

Error

=>Error_TimeProportionalOut[index]);

// Perform outputs for bits 00 to 03 of output word 1.

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

CASE index OF INT#0: DO1:=DOut_TPO; INT#1: DO2:=DOut_TPO; INT#2: DO3:=DOut_TPO; ELSE DO4:=DOut_TPO;
END_CASE;
END_FOR;

2 Instruction Descriptions
2

LimitAlarmDvStbySeq_**

NJ/NX-series Instructions Reference Manual (W502)

2-775

2 Instruction Descriptions

ScaleTrans

The ScaleTrans instruction converts input values from an input range to an output range.

Instruction ScaleTrans

Name

FB/FUN

Scale Transfor- FUN mation

Graphic expression

(@)ScaleTrans

EN SclIn X0 Y0 X1 Y1 SclOfs

ENO Out

ST expression
Out :=ScaleTrans(SclIn,X0,Y0,X1,Y1, SclOfs);

Variables

Name SclIn X0
Y0
X1
Y1 SclOfs Out

Meaning
Input value
Input range lower limit
Output range lower limit
Input range upper limit
Output range upper limit
Offset
Output Value

I/O Input Output

Description Value to scale
Lower limit of input range

Valid range

Lower limit of output range Upper limit of input range

Depends on data type.

Upper limit of output range
Offset for output value Value after scale transformation

Unit -----

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default *
0
---

Bit strings

Integers

Times, durations, dates, and text strings

Real numbers

Boolean BOOL

STRING DT TOD
DATE TIME

LREAL REAL

LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE

SclIn X0 X1 Y0 Y1 SclOfs Out

OK OK OK OK OK OK OK OK OK OK OK OK OK OK

Function
The Scale Trans instruction scales the value of input value SclIn from an input range to an output range. The input range is specified with input range lower limit X0 and input range upper limit X1. The output range is specified with output range lower limit Y0 and output range upper limit Y1. The value of offset SclOfs is added to the value that was scaled to the output range and the result is output as output value Out. SclOfs is used, for example, to correct for error in temperature control.

2-776

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

ScaleTrans

2 Instruction Descriptions

The following conversion is used.

Y1-Y0

Out =

(Sclln - X0) + Y0 + SclOfs

X1-X0

Output
Y1 Out

SclOfs

Y0

0

X0 SclIn

X1

Input

2

Notation Example
The following notation example scales an input value of 2,500 from an input range of 0 to 4,000 to an output range of 0% to 100%. An offset of 5% is added to the output value. The following values are used: SclIn = REAL#2500, X0 = REAL#0, X1 = REAL#4000, Y0 = REAL#0, Y1 = REAL#100, and SclOfs = REAL#5. The value of Out will be REAL#67.5.

LD

ST

AIn0 REAL#0 REAL#0 REAL#4000 REAL#100 REAL#5

ScaleTrans

EN SclIn X0 Y0 X1 Y1 SclOfs

ENO Out

Out :=ScaleTrans(AIn0,REAL#0,REAL#0,REAL#4000, REAL#100,REAL#5);

Output

Y1 REAL#100
Out REAL#67.5 62.5

ScOfs REAL#5

Y0 REAL#0 X0 REAL#0

X1 REAL#4000

Input

SclIn REAL#2500

An input value of 2,500 is scaled to 62.5 for an input range of 0 to 4,000 and an output range of 0 to 100. When an offset of 5 is added, Out becomes REAL#67.5.

NJ/NX-series Instructions Reference Manual (W502)

2-777

2 Instruction Descriptions

Additional Information

· When scaling SclIn to the ranges of the values of PV and SP of the PIDAT instruction, pass the following parameters to Y0 and Y1.

Variable Y0 Y1

Parameter InitSetParams.RngLowLmt (input range lower limit of the PIDAT instruction) InitSetParams.RngUpLmt (input range upper limit of the PIDAT instruction)

· Settings are also possible with X1 < X0 and Y1 < Y0.

Precautions for Correct Use

Version Information
A CPU Unit with unit version 1.05 or later and Sysmac Studio version 1.06 or higher are required to use this instruction.

2-778

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Analog Control Instructions

AC_StepProgram

AC_StepProgram

The AC_StepProgram instruction calculates the present set point and the predicted set point every task period according to the specified program pattern.

Instruction
AC_Step Program

Name Step Program

FB/ FUN
FB

Graphic expression

AC_StepProgram_instance

AC_StepProgram

Enable

Done

Hold

Busy

Advance

Error

PV

ErrorID

IntegrationTime

Wait

Alpha

StepNo

Option

PresentSP

ProgramPattern

ST expression

AC_StepProgram_instance(

Enable, Hold, Advance, PV,

IntegrationTime, Alpha, Option,

ProgramPattern, Done, Busy, Error, ErrorID, Wait, StepNo,

2

PresentSP, PredictSP, TimeInfo);

PredictSP TimeInfo

Variables

Name

Meaning

I/O

Enable

Enable

Hold

Hold

Advance

Advance

PV

Process value

Input

IntegrationTime

Integration time

Alpha
Option
ProgramPattern[] array

2-PID parameter  Option
Program pattern

In-out

Wait

Waiting

StepNo PresentSP PredictSP

Present step number Present set point Predicted set point

Output

TimeInfo

Clock information

Description TRUE: Execute FALSE: Stop TRUE: Hold FALSE: Do not hold The number of the step that is executed is incremented each time this variable changes to TRUE. Measured value (process value)*1
Integration time*2
2-PID parameter *4 Option*5

Valid range

Unit

Depends on data type.

---

T#0.0000s to T#10000.0000s s
*3

0.00 to 1.00

---

---

Program pattern

---

---

TRUE: Waiting FALSE: Not waiting

Depends on data type.

The number of the current step 0 to 99

The calculated present set point Depends on

---

The calculated predicted set point data type.

Clock information to monitor the progress of the instruction

---

Default
FALSE
0 T#0s 0 -----
---

*1 It is the same as PV in the PIDAT instruction. Refer to PV (Process Value) on page 2-783 for details.

*2 It is the same as IntegrationTime in the PIDAT instruction. Refer to IntegrationTime (Integration Time) on page 2-783 for details.

*3 Digits below 0.0001 s are truncated.

*4 It is the same as OprSetParams.Alpha in the PIDAT instruction. Refer to Alpha (2-PID Parameter ) on page 2-784 for details.

*5 Refer to Structure Specifications on page 2-782 for details.

NJ/NX-series Instructions Reference Manual (W502)

2-779

2 Instruction Descriptions

Real numbers

Boolean BOOL

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME

LREAL REAL

LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE

Enable

OK

Hold

OK

Advance

OK

PV

IntegrationTime

Alpha

Option

ProgramPattern[] array*1*2*3

Wait

OK

StepNo

PresentSP

PredictSP

TimeInfo

OK OK
OK Refer to Function for details on the structure _sAC_STEP_OPTION.
Refer to Function for details on the structure _sAC_STEP_DATA. Specify an array.
OK OK OK
Refer to Function for details on the structure _sAC_STEP_TIME.

*1 The array can have a maximum of 100 elements.

*2 This is a one-dimensional array. If an array with more than one dimension is specified, a building error will occur.

*3 The first array element number is 0. If a number other than 0 is specified for the first array element, a building error will occur.

Function
You use the AC_StepProgram instruction together with the PIDAT instruction to calculate present set point PresentSP and predicted set point PredictSP every task period when you perform manipulated variable control for a temperature controller or other controller.
The present set point is the set point in the present task period. The predicted set point is arrived at by applying delay compensation for 2-PID control to the present set point. By passing predicted set point PredictSP to set point SP of the PIDAT instruction, you can improve the tracking characteristic of programmed control with the PIDAT instruction.

2-780

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

2 Instruction Descriptions

PresentSP (Present Set Point)
Present set point PresentSP is the set point in the present task period. For example, assume that the user sets the set points for 0, 10, 40, and 60 minutes after the start of control as shown below. Also assume that the current time is 30 minutes after the start of control. The AC_StepProgram instruction performs linear interpolation of the set points for 10 minutes and 40 minutes after the start of control and calculates PresentSP.
PresentSP

Set point

User-specified set points for 0, 10, 40, and 60 minutes

2

0

10

30 40

60 Time [min]

(Current time)

PredictSP (Predicted Set Point)

Predicted set point PredictSP is arrived at by applying delay compensation for 2-PID control to present set point PresentSP. If PresentSP is passed to SP in the PIDAT instruction without compensation, PV in the PIDAT instruction will not match the set point. This is illustrated in the following figure.

PresentSP Control value

Set point Process value

AC_StepProgram

0 10

30 40

60 Time [min]

The set point that can been compensated for delay is given by PredictSP. The AC_StepProgram

instruction calculates PredictSP based on integration time IntegrationTime and 2-PID parameter 

Alpha. By passing PredictSP to SP of the PIDAT instruction, the tracking characteristic of programmed

control with the PIDAT instruction is improved.

PredictSP Control value PresentSP

Set point Process value

0 10

30 40

60 Time [min]

NJ/NX-series Instructions Reference Manual (W502)

2-781

2 Instruction Descriptions

Structure Specifications

The data type of Option is structure _sAC_STEP_OPTION. The specifications are as follows:

Name Option
StartAtPV StartStepNo EndStepNo
Reserved

Meaning Option
Start at PV
Start step number End step number
Reserved.

Description
Option
TRUE: Enable starting at PV FALSE: Disable starting at PV The step number from which to start processing The step number from which to end processing*1

Data type _sAC_STEP _OPTION
BOOL
USINT
USINT

Valid range --Depends on data type.
0 to 99

Reserved.

ARRAY[0..31] Depends on

OF BYTE

data type.

Unit Default ---
FALSE
--- 0
All 32 elements contain 0.

*1 A setting of 0 treats the highest element number in ProgramPattern[] as the end step number.

The data type of the elements of program pattern ProgramPattern[] is structure _sAC_STEP_DATA. The specifications are as follows:

Name Program Pattern
ReachSP
TimeWidth
WaitWidth
WaitTime Limit

Meaning Program pattern Target set point
Time width
Wait width
Wait time upper limit

Description
Program pattern
The target step point for the step The time width of the step*1 The wait width of the step*2 The upper limit of the wait width of the step*1*3

Data type _sAC_STEP _DATA REAL
TIME
REAL
TIME

Valid range ---
Depends on data type.

Unit Default ---
--0
s T#0s
--- 0
s T#0s

*1 The resolution is one task period. *2 A setting of 0 or less is treated as 0. *3 A setting of 0 or less is treated as T#0s.

2-782

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Analog Control Instructions

AC_StepProgram

The data type of clock information TimeInfo is structure _sAC_STEP_TIME. The specifications are as follows:

Name

Meaning

Description

Data type

Valid range Unit Default

TimeInfo

Clock information

Clock information

_sAC_STEP _TIME

---

--- ---

ProgramTime

The total of TimeWidth Program time from step 0 to End-
StepNo.

TIME

The elapsed time from

ElapseTime

Elapsed time when instruction execu- TIME tion started*1

Progress Time
LeftTime

Progress time
Remaining time

The elapsed time from when instruction execution started*2
The time from the present until all processing is completed*2

TIME TIME

2

Non-negative value

s

T#0s

StepProgress- Step prog-

Time

ress time

The elapsed time from the start of the current step*2

TIME

StepLeftTime

Step remaining time

The time from the present until all processing is completed for the current step*2

TIME

*1 Includes the wait time. Does not include the hold time. *2 This value does not include the wait time and hold time.

Meanings of Variables
The meanings of the variables that are used in this instruction are described below.
 Enable (Enable)
This is the execution condition for the instruction. Instruction execution starts when Enable changes to TRUE. Instruction execution stops when Enable changes to FALSE.
 Hold (Hold)
This is the execution flag for holding. Holding is performed when Hold changes to TRUE. Details on holding are provided later.
 Advance (Advance)
If the value changes to TRUE during instruction execution, processing moves to the next step. Details on advancing are provided later.
 PV (Process Value)
This variable gives the process value of the controlled system. It is the same as PV in the PIDAT instruction.
 IntegrationTime (Integration Time)
This variable is the same as IntegrationTime in the PIDAT instruction.

NJ/NX-series Instructions Reference Manual (W502)

2-783

2 Instruction Descriptions

Input the value of IntegrationTime or the IntegrationTime variable in the PIDAT instruction or PIDAT_HeatCool instruction.
 Alpha (2-PID Parameter )
This variable is the same as OprSetParams.Alpha in the PIDAT instruction. Input the value of OprSetParams.Alpha or the OprSetParams.Alpha variable in the PIDAT instruction or PIDAT_HeatCool instruction.
 StartAtPV (Start at PV)
This variable is the execution flag for starting at the process value. Starting at the process value is performed when StartAtPV is TRUE. Details on starting at the process value are provided later.
 StartStepNo (Start Step Number) and EndStepNo (End Step Number)
These variables give the number for the step from which to start processing and the number of the step to end processing of the steps in the program pattern. A setting of 0 for EndStepNo treats the highest element number in ProgramPattern[] as the end step number. Details on program patterns and steps are provided later.
 ReachSP (Target Set Point)
This variable gives the set point that should be reached at the end of the step in the program pattern. Details on program patterns and steps are provided later.
 TimeWidth (Time Width)
This variable gives the time width for the step in the program pattern. Details on program patterns and steps are provided later.
 WaitWidth (Wait Width)
This variable gives the threshold for performing waiting in the step in the program pattern. Details on waiting are provided later.
 WaitTimeLimit (Wait Time Limit)
This variable gives the upper limit of the wait time for waiting in the step in the program pattern. If the value of WaitTimeLimit is T#0, the upper limit of the wait time is infinity. Details on waiting are provided later.
 Wait (Waiting)
This variable is a flag that indicates if waiting is in progress. If Wait is TRUE, waiting is in progress. Details on waiting are provided later.
 StepNo (Present Step Number)
This variable gives the number of the current step. Details on program patterns and steps are provided later.

2-784

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

AC_StepProgram

2 Instruction Descriptions

 PresentSP (Present Set Point)
This variable gives the calculated present set point.

 PredictSP (Predicted Set Point)
This variable gives the calculated predicted set point.

 ProgramTime (Program Time)
This variable gives the total of TimeWidth from step 0 to EndStepNo in the program pattern. Details on program patterns and steps are provided later.

 ElapseTime (Elapsed Time)

2

This variable gives the elapsed time from when instruction execution started. This value includes the wait time but not the hold time.

Details on waiting and holding are provided later.

 ProgressTime (Progress Time)
This variable gives the elapsed time from when instruction execution started. This value does not include the wait time and hold time.
Details on waiting and holding are provided later.

 LeftTime (Remaining Time)
This variable gives the time from the present until all processing is completed. This value does not include the wait time and hold time.
Details on waiting and holding are provided later.

 StepProgressTime (Step Progress Time)
This variable gives the elapsed time from the start of the current step in the program pattern. This value does not include the wait time and hold time.
Details on program patterns, steps, waiting, and holding are provided later.

 StepLeftTime (Step Remaining Time)
This variable gives the time from the present until all processing is completed for the current step in the program pattern. This value does not include the wait time and hold time.
Details on program patterns, steps, waiting, and holding are provided later.

NJ/NX-series Instructions Reference Manual (W502)

2-785

2 Instruction Descriptions

Program Pattern

The program pattern divides the processing from the start to end of execution of the instruction into steps and chronologically gives the target set point and time width for each step. The program pattern is expressed in the ProgramPattern[] array, which has elements with a data type of _sAC_STEP_DATA. Each element of ProgramPattern[] corresponds to one step.
An example of a program pattern is provided below. If the values of the ReachSP and TimeWidth elements of ProgramPattern[] are as given in the following table, the relation between time and the set points after instruction execution is started is shown in the following figure.

Step number Value of ReachSP Value of TimeWidth
Set point 200

0 0
30 T#0s

1 1
100 T#10m

ProgramPattern[] element number

2

3

4

5

2

3

4

5

120

200

200

80

T#15m T#0s T#15m T#4m

6 6
80 T#5m

7 7 0
T#0s

PresentSP

120
100 80

30

0 10 m 15 m

15 m 4 m 5 m

Time [min]

Linear interpolation is perform for the set points for the steps and the value of PresentSP is calculated for each point. The solid line in the figure represents PresentSP. For each task period, the value of PresentSP at that point is output.

 Relation between the Value of TimeWidth and the Time Width of the Step

The following table shows the relation between the value of TimeWidth and the time width of the step.

Value of TimeWidth T#0s
Positive Negative

Step number 0 Not 0 -----

Time width of the step Treated as T#0s. Treated as one task period. The value of TimeWidth is the time width of the step. Treated as one task period.

 Operation for Step Time Width That Is Less Than One Task Period

The resolution of the step time width is one task period. The following table describes the operation for a step time width that is less than one task period.

Step number 0
Not 0

Time width of the step T#0s
Not T#0s ---

Operation
The value of ReachSP for step 0 is the initial value for PresentSP. Actual processing starts from step 1.
Processing for the current step is executed for only one task period and then processing moves to the next step.

2-786

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

AC_StepProgram

2 Instruction Descriptions

Start Step Number StartStepNo and End Step Number EndStepNo
You can set any steps in the program pattern as the start step and the end step for processing. Set the number of the start step in StartStepNo and the number of the end step in EndStepNo. For example, if you set StartStepNo to 3 and EndStepNo to 6 when you execute the instruction, processing is performed from step 3 through step 6.

 Changing the Value of StartStepNo or EndStepNo during Instruction Execution

You can change the values of StartStepNo and EndStepNo during execution of the instruction. The operation that occurs if you change these values is described in the following table.

2

Variable StartStepNo
EndStepNo

New step number ---
Changing to a step number that is equal to or higher than the current step number Changing to a step number that is lower than the current step number

Operation
Processing will start from the beginning of the step specified by the new StartStepNo.
Progressing will end when the step specified by the new EndStepNo is completed.
Processing ends as soon as the end step number is changed. The value of Done changes to TRUE.

Waiting
Due to delays in the controlled system, the value of PV may not reach the value of ReachSP with TimeWidth for the current step. Waiting can be applied to continue processing the current step even if the time width specified in TimeWidth is exceeded. The following variables in ProgramPattern[] are related to waiting: wait width WaitWidth, wait time upper limit WaitTimeLimit, and waiting Wait.
 Condition for Waiting
Waiting occurs if the difference between ReachSP and PV exceeds WaitWidth after the end time for the current step.
 End of Waiting
If the difference between ReachSP and PV becomes equal to or less than WaitWidth before WaitTimeLimit is reached after the start of waiting, waiting ends at that time and processing moves to the next step.
If the difference between ReachSP and PV does not become equal to or less than WaitWidth before WaitTimeLimit is reached after the start of waiting, waiting ends when the time set for WaitTimeLimit expires and processing moves to the next step. However, if the value of WaitTimeLimit is T#0, the upper limit of the wait time is infinity. Therefore, waiting occurs without a time limit until the difference between ReachSP and PV becomes less than or equal to WaitWidth.
 Monitoring Waiting
You can monitor waiting with the value of Wait. If processing is currently waiting, the value of Wait is TRUE. If processing is not currently waiting, the value of Wait is FALSE.

NJ/NX-series Instructions Reference Manual (W502)

2-787

2 Instruction Descriptions

 Timing during Waiting
The operations of the time-related variables during waiting are described in the following table.

Name ElapseTime ProgressTime LeftTime StepProgressTime StepLeftTime

Operation Continues timing. Stops timing and retains the value from when waiting started. Starts timing again from the retained value when waiting ends.
Goes to the value of TimeWidth for the current step and then retains that value. Goes to 0 and then retains that value.

 PresentSP and PredictSP during Waiting
During waiting, both PresentSP and PredictSP retain the value of ReachSP.

The following figure provides a graph of PV when the difference between ReachSP and PV becomes equal to or less than WaitWidth within the time set for WaitTimeLimit. The difference between ReachSP and PV still exceeds WaitWidth after the end time for the current step, so waiting occurs. When the difference between ReachSP and PV becomes less than or equal to WaitWidth, processing moves to the next step.

WaitWidth for the current step

Set point

ReachSP for the current step

PV Wait time

End time for the current step

Time Start of next step

WaitTimeLimit for the current step
The following figure provides a graph of PV when the difference between ReachSP and PV does not become equal to or less than WaitWidth within the time set for WaitTimeLimit. Processing moves to the next step after the time that is set for WaitTimeLimt expires.

WaitWidth for the current step

Set point

ReachSP for the current step

PV Wait time

End time for the current step

Time Start of next step

WaitTimeLimit for the current step

2-788

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

AC_StepProgram

2 Instruction Descriptions

Holding
Processing for the current step is held unconditionally whenever the value Hold is TRUE. While processing is held, timing is stopped for all time-related variables. Timing is started again for these time-related variables when the value of Hold changes to FALSE.

 Timing while Holding
The operations of the time-related variables while processing is held are described in the following table.

Name

Operation

2

ElapseTime

Stops timing and retains the value from when holding started. Starts timing again

ProgressTime

from the retained value when holding ends.

LeftTime

StepProgressTime

StepLeftTime

 PresentSP and PredictSP while Holding
While processing is held, PresentSP retains the value from when holding started. While processing is held, PredictSP has the same value as PresentSP.

 Holding during Waiting
If you hold processing during waiting, waiting is ended. Therefore, the value of Wait changes to FALSE. When holding is ended, the conditions for waiting are judged again.

Start at PV
You can start processing when the value of PV and the value of PresentSP are equal. If the value of StartAtPV is TRUE when Enable changes to TRUE, the start at PV operation is used. Processing is performed as follows for the start at PV operation.
1 The value of PV is obtained.
2 A search is made from step 0 to the last step for the time when the value of PV first equals the
value of PresentSP.
If the value of PresentSP increases from the start of step 0, the search is made only until just before the value of PresentSP starts to decrease. In the same way, if the value of PresentSP decreases from the start of step 0, the search is made only until just before the value of PresentSP starts to increase.
3 Processing is started from the point that was found in the above search.

If there is no time in the search range where PV an PresentSP have the same value, processing is started from step 0.

NJ/NX-series Instructions Reference Manual (W502)

2-789

2 Instruction Descriptions

An example of the start at PV operation is provided below. The following table gives the contents of ProgramPattern[].

Step number Value of ReachSP Value of TimeWidth

0 0
30 T#0s

1 1
100 T#10m

ProgramPattern[] element number

2

3

4

5

2

3

4

5

120

200

200

80

T#15m T#0s T#15m T#4m

6 6
80 T#5m

7 7 0
T#0s

In this example, the value of PresentSP increases from the value for step 0. Therefore, a search is made only for 40 minutes after the start of processing, i.e., the point where the value of PresentSP starts to decrease.
Assume that the value of PV at the start of instruction execution is 110. In this case, processing starts as shown in the following figure where PresentSP equals 110.

Set point 200

Processing is started from this point.
A search is made only to this point, i.e., to where the value of PresentSP starts to decrease.

120 110
100 80

30 0 10 m

15 m

15 m 4 m 5 m

Time [min]

Search range
 Timing for Start at PV Operation
The operations of the time-related variables for the start at PV operation are described in the following table.

Name ElapseTime ProgressTime LeftTime StepProgressTime
StepLeftTime

Operation Contains 0. Gives the time from step 0 to the point that was found in the search. Gives the time from the present to the end of EndStepNo. Gives the time from the beginning of the current step to the point that was found in the search. Gives the time from the present until all processing is completed for the current step.

 Changing the Value of StartAtPV during Instruction Execution
Any changes to the value of StartAtPV during execution of the instruction are ignored.

2-790

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

2 Instruction Descriptions

Advancing
If the value of Advance changes to TRUE during instruction execution, processing moves to the beginning of the next step.

 Timing for Advancing
The operations of the time-related variables when processing is advanced to the next step are described in the following table.

Name

Operation

ElapseTime

Continues timing.

2

ProgressTime

Gives the total of TimeWidth from step 0 until the current step.

LeftTime

Gives the time from the next step to the end of EndStepNo.

StepProgressTime

Contains 0 because processing moves to the start of the next step.

StepLeftTime

Gives the value of TimeWidth for the next step.

 Changing the Value of StartStepNo and Advancing Processing at the Same Time
If you change the values of StartStepNo and Advance to TRUE at the same time, changing the value of StartStepNo is given priority. Therefore, processing moves to the start of StartStepNo.

AC_StepProgram

NJ/NX-series Instructions Reference Manual (W502)

2-791

2 Instruction Descriptions

Changing the Program Pattern during Instruction Execution

You can change the contents of ProgramPattern[] during execution of the instruction. If you change the contents of ProgramPattern[], the PresentSP is calculated again. Processing is started again from the time in StepProgressTime at the step that was in execution before the program pattern was changed. You can also change the contents of previous steps.
For example, assume that the contents of ProgramPattern[] are changed during execution of step 4. Also assume that the previous value of StepProgressTime was T#5m. After you change the program pattern, processing will start again at a value of T#5m for StepProgressTime in step 4.

Set point

StepProgressTime = T#5m during execution of step 4

Set point

Time [min] Contents of ProgramPattern[] changed.
Processing is started again at StepProgressTime = T#5m in step 4.

Time [min]
If the value of TimeWidth for the step is smaller than the value of StepProgressTime, processing is started again from the start of the next step.

 Timing for Changes in the Program Pattern during Instruction Execution
The operations of the time-related variables when the program pattern is changed during instruction execution are described in the following table.

Name ProgramTime ElapseTime ProgressTime
LeftTime StepProgressTime StepLeftTime

Operation Gives the total of TimeWidth from step 0 to EndStepNo after the change. Continues timing. Gives the total of StepProgressTime and the total of TimeWidth from step 0 to one step before the current step after the change. Gives the time from the present to the end of EndStepNo after the change. Timing continues from the value before the change. Gives the time from the present in the current step until all processing is completed for the current step after the change.

2-792

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

AC_StepProgram

2 Instruction Descriptions

 Changing the Program Pattern during Waiting
If you change the program pattern during waiting, waiting judgement is performed again for the recalculated PresentSP. However, if the value of StepProgressTime is larger than the value of WaitTimeLimit after the change, waiting is ended immediately and processing moves to the next step.
 Changing the Program Pattern during Holding
If you change the program pattern during holding, holding continues for the recalculated PresentSP.

Timing Charts

2

The following figure shows a timing chart for normal operation.

Enable Hold

TRUE FALSE
TRUE FALSE

Done Busy Error

TRUE FALSE
TRUE FALSE
TRUE FALSE

ErrorID Wait
PresentSP PredictSP

TRUE FALSE

16#0000

Execution starts when Enable changes

to TRUE.

Busy changes to TRUE, Done changes

to FALSE, and Error changes to FALSE.

The values of PresentSP and PredictSP

are updated.

Waiting is started.

Holding starts.

Wait changes to TRUE.

Hold changes to TRUE and Wait changes to FALSE.

Execution ends when Enable changes to FALSE. Done changes to FALSE.
Processing ends when execution of all steps through EndStepNo is completed. Busy changes to FALSE and Done changes to TRUE. The values of PresentSP and PredictSP are retained.

Holding ends. Hold changes to FALSE.

NJ/NX-series Instructions Reference Manual (W502)

2-793

2 Instruction Descriptions

The following figure shows a timing chart for when an error occurs.

Enable Done Busy Error

TRUE FALSE
TRUE FALSE
TRUE FALSE
TRUE FALSE

ErrorID
Wait PresentSP PredictSP

TRUE FALSE

16#0000 16#****

Execution starts when Enable changes to TRUE. Busy changes to TRUE, Done changes

Execution ends when Enable changes to FALSE. Error changes to FALSE.

to FALSE, and Error changes to FALSE.

The values of PresentSP and PredictSP

are updated.

Error occurs.

Waiting is started.

Busy changes to FALSE, Error changes to TRUE, and Wait

Wait changes to TRUE. changes to FALSE.

ErrorID is updated.

The values of PresentSP and PredictSP are retained.

Precautions for Correct Use

· An error occurs in the following cases. Error will change to TRUE, and an error code is assigned to ErrorID.

Error
The value of IntegrationTime, Alpha, StartStepNo, or EndStepNo is outside of the valid range.
The final element number in the ProgramPattern[] array exceeded 99.

Value of ErrorID 16#0400
16#0416

Version Information
A CPU Unit with unit version 1.06 or later and Sysmac Studio version 1.07 or higher are required to use this instruction.

2-794

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Analog Control Instructions

AC_StepProgram

Sample Programming
This sample performs temperature control with the optimum PID parameters for each step in the AC_StepProgram instruction.

Processing

This sample performs the following two processes.

· It calculates the optimum PID parameters for each step.

· It controls temperature according to the program pattern.

2

Both of these processes are described below.
 Calculating Optimum PID Parameters for Each Step
Before temperature is controlled according to the program pattern, the optimum PID parameters for each step must be calculated. Autotuning with the PIDAT instruction is used to calculate the PID parameters.
The calculated PID parameters are stored in the PIDbank[] array of structures with the step numbers used as the array subscripts. The members of the elements of PIDbank[] give the proportional bands, integration times, and derivative times.

The processing procedure is as follows:
1 The user changes the value of ACSP_Enable to the AC_StepProgram instruction to TRUE.
The AC_StepProgram instruction is executed and the value of present step number StepNo changes to 0.
2 The user changes the value of execution condition Run to the PIDAT instruction to TRUE.
The PIDAT instruction is executed.
3 The user changes the value of autotuning execution condition StartAT to TRUE.
The value of Hold to the AC_StepProgram instruction changes to TRUE and holding is performed. Autotuning for the PIDAT instruction is executed and the optimum PID parameters are calculated for step 0.
4 Autotuning is completed.
The value of autotuning normal completion ATDone from the PIDAT instruction changes to TRUE. The calculated PID parameters are stored in PIDbank[0].
5 The user changes the value of Hold to the AC_StepProgram instruction to FALSE.
Holding for the AC_StepProgram instruction is canceled. After a while, processing moves to the next step and the value of StepNo changes to 1.
6 The user repeats steps 3 to 5 for each step number.
The optimum PID parameters for all steps are stored in PIDbank[].

NJ/NX-series Instructions Reference Manual (W502)

2-795

2 Instruction Descriptions

 Controlling Temperature According to the Program Pattern
The optimum PID parameters for each step are used to control temperature according to the program pattern. The processing procedure is as follows:
1 The user changes the value of ACSP_Enable to the AC_StepProgram instruction to TRUE.
The AC_StepProgram instruction is executed and the value of step number StepNo changes to 0.
2 The user changes the value of execution condition Run to the PIDAT instruction to TRUE.
The PIDAT instruction is executed.
3 For each task period, manipulated value MV from the PIDAT instruction is output.
4 The TimeProportionalOut instruction performs time-proportional output according to the value of
MV.
5 After a while, processing moves to the next step.
6 Steps 3 to 5 are repeated through the end step.

Setup with the Sysmac Studio

To use the sample programming, you must use the Sysmac Studio to set the network configuration, I/O map, and data type definitions.

 Network Settings
The configuration of the network is given in the following table. A Slave Terminal with the following configuration is connected at EtherCAT node address 1. The device names that are given in the following table are used.

Unit number 0 1 2

Model number NX-ECC201 NX-TS2101 NX-OD3121

Unit EtherCAT Coupler Unit Temperature Input Unit Digital Output Unit

Device name E001 N1 N2

2-796

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

2 Instruction Descriptions

 I/O Map
The following I/O map settings are used.

Position

Port

Description

R/W

Data type

Variable

Variable type

Unit1

Ch1 Measured Channel measured R REAL N1_Ch1_Mea-

Global

Value REAL*1 value (REAL)

sured_Value_REAL variable

Unit1

Ch2 Measured Channel measured R REAL N1_Ch2_Mea-

Global

Value REAL *2 value (REAL)

sured_Value_REAL variable

Unit2

Output Bit 00 Output bit 00

W BOOL N2_Output_Bit_00 Global variable

Unit2

Output Bit 01 Output bit 01

W BOOL N2_Output_Bit_01 Global variable

2

Unit2

Output Bit 02 Output bit 02

W BOOL N2_Output_Bit_02 Global variable

Unit2

Output Bit 03 Output bit 03

W BOOL N2_Output_Bit_03 Global variable

*1 You must add 0x6003:01 (Ch1 Measured Value REAL) to the I/O entries for the NX-TS2101 Temperature Input Unit.

*2 You must add 0x6003:02 (Ch2 Measured Value REAL) to the I/O entries for the NX-TS2101 Temperature Input Unit.

 Data Type Definitions
The structure sPID_BANK is defined as shown in the following table.

Structure

Name sPID_BANK
PB TI TD

Data type STRUCT
REAL TIME TIME

Comment PID parameter structure
Proportional band Integration time Derivative time

AC_StepProgram

NJ/NX-series Instructions Reference Manual (W502)

2-797

2 Instruction Descriptions

LD
Internal Variables

Variable

ACSP_Enable

Hold Advance

Option

ProgramPattern
ACSP_Busy ACSP_Error ACSP_ErrorID Wait StepNo PresentSP PredictSP

Data type BOOL BOOL BOOL _sAC_STEP _OPTION
ARRAY[0..7] OF _sAC_STEP_DATA
BOOL BOOL WORD BOOL USINT REAL REAL

Initial value
FALSE
FALSE FALSE (StartAtPV:=FALSE, StartStepNo:=0, EndStepNo:=7, Reserved:=[32(16#0)]) [(ReachSP:=30.0, TimeWidth:=T#0s, WaitWidth:=3.0, WaitTimeLimit:=T#1m),
(ReachSP:=100.0, TimeWidth:=T#10m, WaitWidth:=3.0, WaitTimeLimit:=T#1m),
(ReachSP:=120.0, TimeWidth:=T#15m, WaitWidth:=3.0, WaitTimeLimit:=T#1m),
(ReachSP:=150.0, TimeWidth:=T#0s, WaitWidth:=3.0, WaitTimeLimit:=T#1m),
(ReachSP:=150.0, TimeWidth:=T#15m, WaitWidth:=3.0, WaitTimeLimit:=T#1m),
(ReachSP:=80.0, TimeWidth:=T#4m, WaitWidth:=3.0, WaitTimeLimit:=T#1m),
(ReachSP:=80.0, TimeWidth:=T#5m, WaitWidth:=3.0, WaitTimeLimit:=T#1m),
(ReachSP:=10.0, TimeWidth:=T#0s, WaitWidth:=3.0, WaitTimeLimit:=T#1m)]
FALSE
FALSE
WORD#16#0
FALSE 0 0.0 0.0

Comment Enable for AC_StepProgram Hold Advance Option
Program pattern
Execution of AC_StepProgram in progress AC_StepProgram error AC_StepProgram error code Waiting Present step number Present set point Predicted set point

2-798

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

AC_StepProgram

2 Instruction Descriptions

Internal Variables

Variable

TimeInfo

ACSP_Done
Run ManCtl StartAT

OprSetParams

InitSetParams
ManMV ATBusy PID_ErrorID PID_Error MV ATDone
TPO_Error
PIDbank ACSP PID TPO

Data type

Initial value

Comment

_sAC_STEP_TIME

(ProgramTime:=T#0s, ElapseTime:=T#0s, ProgressTime:=T#0s, LeftTime:=T#0s, StepProgressTime:=T#0s, StepLeftTime:=T#0s)

Clock information

BOOL

FALSE

AC_StepProgram completion

BOOL

FALSE

PIDAT instruction execution condition

BOOL BOOL

FALSE FALSE

Manual/auto control Autotuning execution

2

condition

_sOPR_SET _PARAMS

(MVLowLmt:=0.0, MVUpLmt:=100.0, ManResetVal:=0.0, MVTrackSw:=FALSE, MVTrackVal:=0.0, StopMV:=0.0, ErrorMV:=0.0, Alpha:=0.65, ATCalcGain:=1.0, ATHystrs:=0.2)

Operation setting parameters

_sINIT_SET _PARAMS

(SampTime:=T#250ms, RngLowLmt:=-200.0, RngUpLmt:=1300.0, DirOpr:=FALSE)

Initial setting parameters

REAL

0.0

Manual manipulated variable

BOOL

FALSE

Autotuning busy

WORD

WORD#16#0

PIDAT error code

BOOL

FALSE

PIDAT error

REAL

0.0

Manipulated variable

BOOL

FALSE

Autotuning normal completion

BOOL

FALSE

TimeProportionalOut error

ARRAY[0..7] OF sPID_BANK

[8((PB:=10, TI:=T#233s, TD:=T#60s))]

Storage array for optimum PID parameters

AC_StepProgram

PIDAT

TimeProportionalOut

External Variables

Variable
N1_Ch1_Measured_Value_REAL N2_Output_Bit_00

Data type
REAL
BOOL

Constant
-----

Comment
Channel measured value (REAL) Output bit

NJ/NX-series Instructions Reference Manual (W502)

2-799

2 Instruction Descriptions

Perform holding for AC_StepProgram instruction during autotuning.

StartAT

Hold

S

Execute AC_StepProgram instruction. ACSP_Enable
Hold Advance N1_Ch1_Measured_Value_REAL PIDbank[StepNo].TI OprSetParams.Alpha
Option
ProgramPattern
Execute PIDAT instruction. Run
ManCtl StartAT N1_Ch1_Measured_Value_REAL PredictSP OprSetParams InitSetParams
PIDbank[StepNo].PB
PIDbank[StepNo].TI
PIDbank[StepNo].TD
ManMV

ACSP

AC_StepProgram

Enable

Done

Hold

Busy

Advance

Error

PV

ErrorID

IntegrationTime

Wait

Alpha

StepNo

Option

PresentSP

ProgramPattern

PredictSP TimeInfo

PID

PIDAT

Run

ATDone

ManCtl

ATBusy

StartAT

Error

PV

ErrorID

SP

MV

OprSetParams

InitSetParams

ProportionalBand

IntegrationTime

DerivativeTime

ManMV

ACSP_Done
ACSP_Busy ACSP_Error ACSP_ErrorID Wait StepNo PresentSP
ProgramPattern PredictSP TimeInfo
ATDone
ATBusy PID_Error PID_ErrorID MV
PIDbank[StepNo].PB
PIDbank[StepNo].TI
PIDbank[StepNo].TD
ManMV

Execute TimeProportionalOut instruction. TPO

TimeProportionalOut

MV T#2s

Enable AIn CtlPrd MinPlsWidth Delay

DOut Error

N2_Output_Bit_00 TPO_Error

2-800

NJ/NX-series Instructions Reference Manual (W502)

Analog Control Instructions

AC_StepProgram

2 Instruction Descriptions

ST
Internal Variables

Variable
ACSP_Enable Hold Advance

Option

ProgramPattern
ACSP_Busy ACSP_Error ACSP_ErrorID Wait StepNo PresentSP PredictSP

Data type
BOOL BOOL BOOL
_sAC_STEP _OPTION

Initial value

Comment

FALSE

Enable for AC_StepProgram

FALSE

Hold

FALSE

Advance

(StartAtPV:=FALSE, StartStepNo:=0, EndStepNo:=7, Reserved:=[32(16#0)])

Option

[(ReachSP:=30.0, TimeW-

idth:=T#0s,

2

WaitWidth:=3.0,

WaitTimeLimit:=T#1m),

(ReachSP:=100.0, TimeWidth:=T#10m, WaitWidth:=3.0, WaitTimeLimit:=T#1m),

(ReachSP:=120.0, TimeWidth:=T#15m, WaitWidth:=3.0, WaitTimeLimit:=T#1m),

ARRAY[0..7] OF _sAC_STEP_DATA

(ReachSP:=150.0, TimeWidth:=T#0s, WaitWidth:=3.0, WaitTimeLimit:=T#1m),
(ReachSP:=150.0, TimeWidth:=T#15m, WaitWidth:=3.0, WaitTimeLimit:=T#1m),

Program pattern

(ReachSP:=80.0, TimeWidth:=T#4m, WaitWidth:=3.0, WaitTimeLimit:=T#1m),

(ReachSP:=80.0, TimeWidth:=T#5m, WaitWidth:=3.0, WaitTimeLimit:=T#1m),

BOOL
BOOL
WORD
BOOL USINT REAL REAL

(ReachSP:=10.0, TimeWidth:=T#0s, WaitWidth:=3.0, WaitTimeLimit:=T#1m)]
FALSE
FALSE
WORD#16#0
FALSE 0 0.0 0.0

Execution of AC_StepProgram in progress AC_StepProgram error AC_StepProgram error code Waiting Present step number Present set point Predicted set point

NJ/NX-series Instructions Reference Manual (W502)

2-801

2 Instruction Descriptions

Internal Variables

Variable

TimeInfo

Data type _sAC_STEP_TIME

ACSP_Done Run ManCtl StartAT
PreStartAT

BOOL BOOL BOOL BOOL
BOOL

OprSetParams

_sOPR_SET _PARAMS

InitSetParams

_sINIT_SET _PARAMS

ManMV
ATBusy PID_ErrorID PID_Error MV
ATDone

REAL
BOOL WORD BOOL REAL
BOOL

TPO_Error
PIDbank
TPO_Enable MinPlsWidth Delay ACSP PID TPO

BOOL
ARRAY[0..7] OF sPID_BANK
BOOL
REAL REAL AC_StepProgram PIDAT TimeProportionalOut

External Variables

Variable
N1_Ch1_Measured_Value_REAL N2_Output_Bit_00

Data type
REAL
BOOL

Initial value
(ProgramTime:=T#0s, ElapseTime:=T#0s, ProgressTime:=T#0s, LeftTime:=T#0s, StepProgressTime:=T#0s, StepLeftTime:=T#0s)
FALSE
FALSE
FALSE
FALSE
TRUE
(MVLowLmt:=0.0, MVUpLmt:=100.0, ManResetVal:=0.0, MVTrackSw:=FALSE, MVTrackVal:=0.0, StopMV:=0.0, ErrorMV:=0.0, Alpha:=0.65, ATCalcGain:=1.0, ATHystrs:=0.2) (SampTime:=T#250ms, RngLowLmt:=-200.0, RngUpLmt:=1300.0, DirOpr:=FALSE)
0.0
FALSE WORD#16#0 FALSE 0.0
FALSE
FALSE
[8((PB:=10, TI:=T#233s, TD:=T#60s))]
FALSE
0.0 0.0

Comment
Clock information
AC_StepProgram completion PIDAT instruction execution condition Manual/auto control Autotuning execution condition Autotuning execution condition for previous task period
Operation setting parameters
Initial setting parameters
Manual manipulated variable Autotuning busy PIDAT error code PIDAT error Manipulated variable Autotuning normal completion TimeProportionalOut error Storage array for optimum PID parameters Enable for TimeProportionalOut Minimum pulse width Delay

Constant
-----

Comment
Channel measured value (REAL) Output bit

2-802

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Analog Control Instructions

AC_StepProgram

TPO_Enable := TRUE;

// Perform holding for AC_StepProgram instruction during autotuning. IF StartAT AND PreStartAT=FALSE THEN
Hold := TRUE; END_IF; PreStartAT := StartAT;

// Execute AC_StepProgram instruction.

IF ACSP_Enable THEN

ACSP(Enable Hold

:=ACSP_Enable, :=Hold,

2

Advance

:=Advance,

PV

:=N1_Ch1_Measured_Value_REAL,

IntegrationTime:=PIDbank[StepNo].TI,

Alpha

:=OprSetParams.Alpha,

Option

:=Option,

ProgramPattern :=ProgramPattern,

Done

=>ACSP_Done,

Busy

=>ACSP_Busy,

Error

=>ACSP_Error,

ErrorID

=>ACSP_ErrorID,

Wait

=>Wait,

StepNo

=>StepNo,

PresentSP

=>PresentSP,

PredictSP

=>PredictSP,

TimeInfo

=>TimeInfo);

END_IF;

// Execute PIDAT instruction.

IF Run THEN

PID(Run

:=Run,

ManCtl

:=ManCtl,

StartAT

:=StartAT,

PV

:=N1_Ch1_Measured_Value_REAL,

SP

:=PredictSP,

OprSetParams :=OprSetParams,

InitSetParams :=InitSetParams,

ProportionalBand:=PIDbank[StepNo].PB,

IntegrationTime :=PIDbank[StepNo].TI,

DerivativeTime :=PIDbank[StepNo].TD,

ManMV

:=ManMV,

ATDone

=>ATDone,

ATBusy

=>ATBusy,

Error

=>PID_Error,

ErrorID

=>PID_ErrorID,

MV=>MV);

END_IF;

// Execute TimeProportionalOut instruction.

TPO(Enable

:=TPO_Enable,

AIn

:=MV,

CtlPrd

:=T#2s,

MinPlsWidth:=MinPlsWidth,

Delay

:=Delay,

DOut

=>N2_Output_Bit_00,

Error

=>TPO_Error);

NJ/NX-series Instructions Reference Manual (W502)

2-803

2 Instruction Descriptions

2-804

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

2
System Control Instructions

Instruction TraceSamp TraceTrig GetTraceStatus SetAlarm ResetAlarm GetAlarm ResetPLCError GetPLCError ResetCJBError GetCJBError GetEIPError ResetMCError GetMCError ResetECError GetECError ResetNXBError GetNXBError GetNXUnitError SetInfo ResetUnit GetNTPStatus RestartNXUnit NX_ChangeWriteMode NX_SaveParam NX_ReadTotalPowerOnTime PLC_ReadTotalPowerOnTime

Name Data Trace Sampling Data Trace Trigger Read Data Trace Status Create User-defined Error Reset User-defined Error Get User-defined Error Status Reset PLC Controller Error Get PLC Controller Error Status Reset CJ Bus Controller Error Get I/O Bus Error Status Get EtherNet/IP Error Status Reset Motion Control Error Get Motion Control Error Status Reset EtherCAT Error Get EtherCAT Error Status Reset NX Bus Error Get NX Bus Error Status Get NX Unit Error Status Create User-defined Information Restart Unit Read NTP Status Restart NX Unit Change to NX Unit Write Mode Save NX Unit Parameters Read NX Unit Total Power ON Time Read PLC Total Power ON Time

Page 2-806 2-809 2-812 2-816 2-821 2-823 2-825 2-828 2-830 2-832 2-834 2-836 2-841 2-843 2-845 2-848 2-850 2-852 2-860 2-862 2-866 2-868 2-874 2-879 2-885 2-893

NJ/NX-series Instructions Reference Manual (W502)

2-805

2 Instruction Descriptions

TraceSamp

The TraceSamp instruction performs sampling for a data trace.

Instruction TraceSamp

Name
Data Trace Sampling

FB/FUN FUN

Graphic expression

(@)TraceSamp

EN TraceNo Point

ENO Out

ST expression
TraceSamp(TraceNo, Point);

Variables

Name TraceNo Point
Out

Meaning
Trace number
Sampling point number
Return value

I/O Input Output

Description Trace number Sampling point number
Always TRUE

Valid range

Unit

*1

Depends on data type. ---

TRUE only

---

*1 The range is 0 to 3 for an NX701 or NJ501 CPU Unit, and for an NY-series Controller. The range is 0 to 1 for an NX1P2, NJ301 or NJ101 CPU Unit.

Default 0
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

TraceNo

OK

Point

OK

Out

OK

Function
The TraceSamp instruction performs sampling for a data trace. The sampling settings are specified from the Sysmac Studio. The present values for all variables that are set to be sampled are read and stored with trace number TraceNo and sampling point number Point in trace memory. This instruction is executed only during execution of data tracing and only when the sampling timing is set to sampling instructions from the Sysmac Studio. The following figure shows a programming example. Trace number 1 and sampling point number 2 are attached, and the present values of all variables to be sampled are stored in trace memory.

2-806

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

System Control Instructions

TraceSamp

LD

ST

TraceSamp(USINT#1, USINT#2);

USINT#1 USINT#2

TraceSamp

EN TraceNo Point

ENO

The present values for all variables that are set to be sampled are read and stored with trace number TraceNo and sampling point number Point in trace memory.

TraceNo USINT#1

2

Point USINT#2

-------------- --------------------------- --------------

Present values of all variables that are set to be sampled

Stored.

Trace memory

Related System-defined Variables

Name *1

Meaning Trace Information

Data type *2

Trace information*3

Description

*1 NX701 or NJ501 CPU Unit, and NY-series Controller: The variable name is _PLC_TraceSta[0..3]. NX1P2, NJ301 or NJ101 CPU Unit: The variable name is _PLC_TraceSta[0..1].
*2 _sTRACE_STA[]
*3 Refer to the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) or NY-series Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for details.

Additional Information
· Refer to the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) or NY-series Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for details on data tracing.
· Tracing is used to sample the values of specified variables under specified conditions. The conditions are specified from the Sysmac Studio.
· This instruction can be located in more than one place in the user program. Programming can be written to sample according to specific conditions.
· Point can be suitably set so that you can see which sampled values on the Data Trace Window in the Sysmac Studio were returned by which TraceSamp instruction. Point will default to 0 if it is omitted.

Precautions for Correct Use
· Return value Out is not used when the instruction is used in ST. · In the following cases, nothing is done and the instruction ends normally.
· Data tracing is stopped. · The sampling timing is not set to sampling instructions in the trace settings. · The value of TraceNo is not the trace number set from the Sysmac Studio. · An error occurs in the following case. ENO will be FALSE. · The value of TraceNo is outside of the valid range.

NJ/NX-series Instructions Reference Manual (W502)

2-807

2 Instruction Descriptions

Sample Programming
Here, sampling is performed at the end of each process A to D. The values of the variables are stored at each point.
LD

Process A

USINT#0 USINT#11

TraceSamp

EN TraceNo Point

ENO

Process B

USINT#1 USINT#12

TraceSamp

EN TraceNo Point

ENO

Process C

USINT#2 USINT#13

TraceSamp

EN TraceNo Point

ENO

Process D

USINT#3 USINT#14

TraceSamp

EN TraceNo Point

ENO

ST
Process A TraceSamp(USINT#0, USINT#11); Process B TraceSamp(USINT#1, USINT#12); Process C TraceSamp(USINT#2, USINT#13); Process D TraceSamp(USINT#3, USINT#14);

2-808

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

2 Instruction Descriptions

TraceTrig

The TraceTrig instruction generates a trigger for data tracing.

Instruction TraceTrig

Name

FB/FUN

Data Trace Trigger FUN

Graphic expression

(@)TraceTrig

EN

ENO

TraceNo

Out

ST expression TraceTrig(TraceNo);

Variables

2

Name TraceNo
Out

Meaning
Trace number
Return value

I/O Input
Output

Description Trace number
Always TRUE

Valid range *1
TRUE only

*1 The range is 0 to 3 for an NX701 or NJ501 CPU Unit, and for an NY-series Controller. The range is 0 to 1 for an NX1P2, NJ301 or NJ101 CPU Unit.

Unit
---
---

Default 0
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

TraceTrig

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

TraceNo

OK

Out

OK

Function

The TraceTrig instruction generates a trigger for data tracing. It does not matter whether the trigger conditions that were set from the Sysmac Studio have been met. Sampling starts if data tracing is in progress for trace number TraceNo when the instruction is executed.
The following figure shows a programming example. Here, a data trace trigger is generated for trace number 1.

LD

ST

TraceTrig(USINT#1);

USINT#1

TraceTrig

EN

ENO

TraceNo

Here, a data trace trigger is generated for trace number TraceNo.

Trace number TraceNo USINT#1

Trigger generated for data trace. Sampling is started.

NJ/NX-series Instructions Reference Manual (W502)

2-809

2 Instruction Descriptions

Related System-defined Variables

Name *1

Meaning Trace Information

Data type *2

Description Trace information*3

*1 NX701 or NJ501 CPU Unit, and NY-series Controller: The variable name is _PLC_TraceSta[0..3]. NX1P2, NJ301 or NJ101 CPU Unit: The variable name is _PLC_TraceSta[0..1].
*2 _sTRACE_STA[]
*3 Refer to the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) or NY-series Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for details.

Additional Information
· Refer to the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) or NY-series Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for details on data tracing.
· This instruction can be located in more than one place in the user program. Programming can be written to generate a trigger according to specific conditions.
· Programming can be written to generate triggers in ways that are not possible for normal trigger conditions settings, such as programming to generate a trigger based on a comparison of two variables.

Precautions for Correct Use
· Return value Out is not used when the instruction is used in ST. · In the following cases, nothing is done and the instruction ends normally.
· Data tracing is stopped. · The trigger condition has already been met. · The value of TraceNo is not the trace number set from the Sysmac Studio. · A continuous trace is specified as the trace type for the trace number that is specified with Tra-
ceNo. · An error occurs in the following case. ENO will be FALSE.
· The value of TraceNo is outside of the valid range.

Sample Programming

Here, a data trace trigger is generated to store the values of variables when the current speed exceeds the maximum speed. The TraceTrig instruction is executed when the value of Current_speed exceeds the value of Max_speed.

LD

Variable Current_speed Max_speed

Data type INT INT

Initial value 0 20

Comment Current speed Maximum speed

Current_speed Max_speed

GT
EN In1 In2

USINT#1

TraceTrig

EN

ENO

TraceNo

2-810

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

2 Instruction Descriptions

ST Variable
Current_speed Max_speed

Data type INT INT

IF (Current_speed > Max_speed) THEN TraceTrig(USINT#1);
END_IF;

Initial value 0 20

Comment Current speed Maximum speed

2

TraceTrig

NJ/NX-series Instructions Reference Manual (W502)

2-811

2 Instruction Descriptions

GetTraceStatus

The GetTraceStatus instruction reads the execution status of a data trace.

Instruction GetTraceStatus

Name
Read Data Trace Status

FB/FUN FUN

Graphic expression

(@)GetTraceStatus

EN

ENO

TraceNo

Out

IsStart

IsComplete

ParamErr

IsTrigger

ST expression
GetTraceStatus(TraceNo, IsStart, IsComplete, ParamErr, IsTrigger);

Variables

Name TraceNo
Out
IsStart

Meaning
Trace number
Return value
Executing flag

I/O Input

IsComplete Completed flag
Output
ParamErr Parameter error flag

IsTrigger Trigger flag

Description Trace number

Valid range *1

Always TRUE

TRUE only

TRUE: Data trace in progress.
FALSE: Data trace not in progress.
TRUE: Data trace was completed.
FALSE: Data trace in progress or not executed.
TRUE: Data trace setting error.
FALSE: No data trace setting error.
TRUE: Data trace trigger condition met.
FALSE: Data trace trigger condition not met.

Depends on data type.

*1 The range is 0 to 3 for an NX701 or NJ501 CPU Unit, and for an NY-series Controller. The range is 0 to 1 for an NX1P2, NJ301 or NJ101 CPU Unit.

Unit
---
---

Default 0
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

TraceNo

OK

Out

OK

IsStart

OK

2-812

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

System Control Instructions

numbers REAL

Boolean BOOL

GetTraceStatus

Bit strings

Integers

Real

Times, durations, dates, and text strings

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

IsComplete OK ParamErr OK IsTrigger OK

Function

2

The GetTraceStatus instruction reads the execution status of the data trace that is specified with trace number TraceNo. The status that is read is output to execution flag IsStart, completed flag IsComplete, parameter error flag ParamErr, and trigger flag IsTrigger.
The value of ParamErr changes to TRUE when one of the following errors is found in the trace settings.
· A variable that is specified in the trigger or sampling settings does not exist.
· Sampling is set to be performed on a specified task period, but the specified task does not exist.
The following figure shows a programming example. The GetTraceStatus instruction reads the execution status of the data trace with trace number 1.

LD

ST

USINT#1

GetTraceStatus

EN TraceNo

ENO
IsStart IsComplete
ParamErr IsTrigger

GetTraceStatus(USINT#1, abc, def, ghi, jkl);
abc def ghi jkl

The GetTraceStatus instruction reads the execution status of the data trace that is specified with trace number TraceNo. TraceNo USINT#1

-------------- --------------------------- --------------
Data trace

Read.

IsStart IsComplete ParamErr IsTrigger

Related System-defined Variables

Name *1

Meaning Trace Information

Data type *2

Description Trace information*3

*1 NX701 or NJ501 CPU Unit, and NY-series Controller: The variable name is _PLC_TraceSta[0..3]. NX1P2, NJ301 or NJ101 CPU Unit: The variable name is _PLC_TraceSta[0..1].
*2 _sTRACE_STA[]
*3 Refer to the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) or NY-series Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for details.

NJ/NX-series Instructions Reference Manual (W502)

2-813

2 Instruction Descriptions
Additional Information
Refer to the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) or NY-series Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for details on data tracing.
Precautions for Correct Use
· Return value Out is not used when the instruction is used in ST. · This instruction reads the contents of the _PLC_TraceSta[] system-defined variable. You cannot
access this variable directly. Always use this instruction to read the contents of the variable. · An error occurs in the following case. ENO will be FALSE.
· The value of TraceNo is outside of the valid range.

2-814

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

GetTraceStatus

2 Instruction Descriptions

Sample Programming

In this sample, the GetTraceStatus instruction reads the execution status of the data trace with trace number 3. If the data trace is in progress, the TraceTrig instruction is executed to trigger data tracing.

LD

Variable StaFlag A B

Data type BOOL BOOL BOOL

Initial value FALSE FALSE FALSE

Comment Trace execution status

2

P_On USINT#3

GetTraceStatus

EN TraceNo

ENO
IsStart IsComplete
ParamErr IsTrigger

StaFlag

StaFlag A

B USINT#3

TraceTrig

EN

ENO

TraceNo

ST Variable
StaFlag A B

Data type BOOL BOOL BOOL

Initial value FALSE FALSE FALSE

Comment Trace execution status

GetTraceStatus(TraceNo:=USINT#3, IsStart=>StaFlag);

IF ( (StaFlag=TRUE) AND (A=TRUE) AND (B=TRUE) ) THEN TraceTrig(TraceNo:=USINT#3);
END_IF;

NJ/NX-series Instructions Reference Manual (W502)

2-815

2 Instruction Descriptions

SetAlarm

The SetAlarm instruction creates a user-defined error.

Instruction SetAlarm

Name
Create Userdefined Error

FB/FUN FUN

Graphic expression

(@)SetAlarm

EN Code Info1 Info2

ENO Out

ST expression
SetAlarm(Code, Info1, Info2);

Variables

Name

Meaning

I/O

Description

Valid range

Unit

Code

Event code

Event code of user-defined 1 to 40000 error to generate

Info1 Info2 Out

Attached information 1
Attached information 2
Return value

Input Output

Values recorded in event log

---

when the user-defined error Depends on data type.

is generated

Always TRUE

TRUE only

---

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default 1
*
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

Code Info1 Info2 Out

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK

Function
The SetAlarm instruction generates the user-defined error that corresponds to event code Code. Event codes are defined in the event setting table on the Sysmac Studio. The time of occurrence, event name, event group, event code Code, event level, additional information Info1, additional information Info2, and detailed information are stored in the user event log area that corresponds to the level of the event code. The value for the time of occurrence is automatically obtained. The event name, event group, and detailed information that are set from the Sysmac Studio are recorded. The event level that corresponds to the event code is recorded. The event levels are given below. The smaller the event code is, the higher the event level is.

2-816

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

SetAlarm

2 Instruction Descriptions

Event code 1 to 5000 5001 to 10000 10001 to 15000 15001 to 20000 20001 to 25000 25001 to 30000 30001 to 35000 35001 to 40000

Classification: User fault level 1 2 3 4 5 6 7 8

The following figure shows a programming example. A user-defined error with event code 101 is gener- 2
ated. The values of variables abc and def are stored as attached information.

LD

ST

SetAlarm(UINT#101, abc, def);

UINT#101 abc def

SetAlarm

EN Code Info1 Info2

ENO

A user-defined error with event code Code is generated. Also, the time of occurrence, event name, event group, event code Code, event level, additional information Info1, additional information Info2, and detailed information are stored in the user event log area.

Event code Code UINT#101

User-defined error generated.

Time of occurrence

Event name

Event group

Event code Code

UINT#101

Event level

Attached information: Info1 = abc

Attached information: Info2 = def

Detailed information

User-defined Event Log Area Written.

Related System-defined Variables

Name _AlarmFlag

Meaning
Error Status of Userdefined Errors

Data type WORD

Description
These flags indicate when user-defined errors are detected. Bit 0 to bit 7 indicate the status of user-defined error levels 1 to 8.*1

*1 Refer to the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) or NY-series Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for details.

NJ/NX-series Instructions Reference Manual (W502)

2-817

2 Instruction Descriptions

Additional Information
You can specify either global variables or local variables for Info1 and Info2.

Precautions for Correct Use
· Up to 32 user-defined errors can be generated in each of the eight event levels (for up to 256 userdefined errors total).
· If a user-defined error for the same event code already exists, the new error is not recorded in the event log.
· Always use variables for the input parameters that pass Info1 and Info2. If you use a constant, a building error will occur.
· An error does not occur even if the value of Code is not set as a event code on the Sysmac Studio. If the event code is not registered, the event group and detailed information are not recorded in the user-defined event log. The value of Code is recorded for the event name.
· Return value Out is not used when the instruction is used in ST. · An error occurs in the following cases. ENO will be FALSE.
· The value of Code is outside of the valid range. · An attempt was made to generate more than the maximum number of user-defined errors.

Sample Programming

In this sample, the value of variable A changes between TRUE and FALSE every five seconds. The value of A is monitored. If it does not change for more than five seconds, a user-defined error with event code 102 is generated. UINT#123 and UINT#456 are given as the attached information.
When variable F changes to TRUE, the user-defined error is cleared.

LD
Internal Variables

Variable
A B C F Abc Def TON_instance0 TON_instance1

Data type Initial value

BOOL BOOL BOOL BOOL UINT UINT TON TON

FALSE FALSE FALSE FALSE 123 456

External Variables

Variable _AlarmFlag

Data type WORD

Constant

Comment

Error Status of User-defined Errors

2-818

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

2 Instruction Descriptions

Check the value of variable A.

TON_instance0

A

TON

B

In

Q

T#5s PT

ET

TON_instance1

A

TON

C

In

Q

T#5s PT

ET

2
Create user-defined error.

B

@SetAlarm

EN

ENO

UINT#102 Code

C

Abc Info1

Def Info2

Reset user-defined error.

F

B

C

WORD#16#0000 _AlarmFlag

NE
EN In1 In2

UINT#102

@ResetAlarm

EN Code

ENO

SetAlarm

NJ/NX-series Instructions Reference Manual (W502)

2-819

2 Instruction Descriptions

ST
Internal Variables

Variable
A B C F Abc Def TON_instance0 TON_instance1

Data type
BOOL BOOL BOOL BOOL UINT UINT TON TON

Initial value FALSE FALSE FALSE FALSE 123 456

External Variables

Variable _AlarmFlag

Data type WORD

Constant

Comment

Error Status of User-defined Errors

// Check the value of variable A. IF (A=TRUE) THEN
TON_instance0(In:=TRUE, PT:=T#5s, Q=>B); ELSE
TON_instance0(In:=FALSE, Q=>B); END_IF;
IF (A=FALSE) THEN TON_instance1(In:=TRUE, PT:=T#5s, Q=>C);
ELSE TON_instance1(In:=FALSE, Q=>C);
END_IF;
// Create user-defined error. IF (B=TRUE) OR (C=TRUE) THEN
SetAlarm( Code :=UINT#102 Info1 :=Abc, info2 :=Def);
END_IF;
// Reset user-defined error. IF (F=TRUE) & (B=FALSE) & (C=FALSE) & (_AlarmFlag<>WORD#16#0000) THEN
ResetAlarm(Code:=UINT#102); END_IF;

2-820

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

ResetAlarm

2 Instruction Descriptions

ResetAlarm

The ResetAlarm instruction resets a user-defined error.

Instruction ResetAlarm

Name
Reset User-defined Error

FB/FUN FUN

Graphic expression

(@)ResetAlarm

EN

ENO

Code

Out

ST expression ResetAlarm(Code);

Variables

2

Name Code

Meaning

I/O

Event code Input

Out

Return

Output

value

Description
Event code of user-defined error to reset 16#0:Reset all application
errors.
Always TRUE

Valid range Depends on data type.
TRUE only

Unit
---
---

Default 0
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

Code

OK

Out

OK

Function

The ResetAlarm instruction resets the user-defined error specified by event code Code. An event is then recorded in the user-defined event log area to show that a specific user-defined error was reset. The event code for this event is 65533 and the level is user information.
If the value of Code is 0, all current user-defined errors are reset. An event is then recorded in the userdefined event log area to show that all user-defined errors were reset. The event code for this event is 65534 and the level is user information.
The following figure shows a programming example. A user-defined error for event code 101 is reset.

LD

ST

ResetAlarm(UINT#101);

UINT#101

ResetAlarm

EN Code

ENO

NJ/NX-series Instructions Reference Manual (W502)

2-821

2 Instruction Descriptions

The ResetAlarm instruction resets the user-defined error specified by event code Code. Also an event is recorded in the user-defined event log area to show that a specific user-defined error was reset.

Event code Code UINT#101

User-defined error is reset.

Event code: 65533 Event level: User information

Written.

User-defined Event Log Area

Related System-defined Variables

Name _AlarmFlag

Meaning
Error Status of Userdefined Errors

Data type WORD

Description
These flags indicate when user-defined errors are detected.
Bit 0 to bit 7 indicate the status of user-defined error levels 1 to 8.*1

*1 Refer to the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) or NY-series Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for details.

Precautions for Correct Use
· An error does not occur if the user-defined error specified by Code has not occurred. · Return value Out is not used when the instruction is used in ST. · An error occurs in the following case. ENO will be FALSE.
· The value of Code is outside of the valid range.

Sample Programming
Refer to the sample programming that is provided for the SetAlarm instruction (page 2-816).

2-822

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

GetAlarm

2 Instruction Descriptions

GetAlarm

The GetAlarm instruction gets the highest event level (of user-defined error levels 1 to 8) and the highest level event code of the current user-defined errors.

Instruction

Name

FB/FUN

Graphic expression

ST expression

GetAlarm

Get User-defined Error Status

FUN

(@)GetAlarm EN

Out:=GetAlarm(Level, Code); Out

Level

Code

2

Variables

Name

Meaning

I/O

Out

Error flag

Level Code

Highest event level

Output

Highest level event code

Description
TRUE: User-defined error exists.
FALSE:No user-defined error
Highest event level of all current user-defined errors
0: No user-defined error 1 to 8: Event level
Highest level event code of all current user-defined errors
0: No user-defined error 1 to 40000: Event level

Valid range Depends on data type.
0 to 8
0 to 40000

Unit ---

Default ---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

Out

OK

Level

OK

Code

OK

Function
The GetAlarm instruction gets the highest event level and the highest level event code of the current user-defined errors and outputs them to Level and Code. If there are currently no user-defined errors, the value of error flag Out is FALSE. If there is more than one use-defined error at the highest event level, the value of Code is the event code for the user-defined error that occurred first.

NJ/NX-series Instructions Reference Manual (W502)

2-823

2 Instruction Descriptions

The following figure shows a programming example.

LD

ST

abc:=GetAlarm(def, ghi);

GetAlarm
EN Level Code

abc
def ghi

The GetAlarm instruction gets the highest event level and the highest level event code of the current user-defined error and outputs them to Level and Code.
Current user-defined error exists. Out=abc TRUE

Current user-defined error

Acquired.

Level=def

Code =ghi

Related System-defined Variables

Name _AlarmFlag

Meaning
Error Status of Userdefined Errors

Data type WORD

Description
These flags indicate when user-defined errors are detected.
Bit 0 to bit 7 indicate the status of user-defined error levels 1 to 8.*1

*1 Refer to the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) or NY-series Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for details.

Precautions for Correct Use
If this instruction is used in a ladder diagram, the value of Out changes to FALSE if an error occurs in the previous instruction on the rung.

2-824

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

ResetPLCError

2 Instruction Descriptions

ResetPLCError

The ResetPLCError instruction resets errors in the PLC Function Module.

Instruction ResetPLCError

Name
Reset PLC Controller Error

FB/FUN FB

Graphic expression

ST expression

ResetPLCError_instance ResetPLCError

ResetPLCError(Execute, Done, Busy, Error, ErrorID);

Execute

Done

Busy

Error ErrorID

2

Variables
Only common variables are used.

Function

The ResetPLCError instruction resets errors in the PLC Function Module. The following figure shows a programming example.

LD

ST

ResetPLCError_instance

A

ResetPLCError

abc

Execute

Done Busy def Error ghi ErrorID jkl

ResetPLCError_instance(A, abc, def, ghi, jkl);

The ResetPLCError instruction resets errors in the PLC Function Module.

Controller error in the PLC Function Module.

Error is reset.

Related System-defined Variables

Name _PLC_ErrSta

Meaning
Error Status of PLC Function Module

Data type WORD

Description
Contains the error status of the PLC Function Module.*1

*1 Refer to the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) or NY-series Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for details.

Precautions for Correct Use
The error may not be reset immediately after you execute this instruction. Use the GetPLCError instruction to confirm that the errors were reset.

NJ/NX-series Instructions Reference Manual (W502)

2-825

2 Instruction Descriptions

Sample Programming

The ResetPLCError instruction is executed when the value of Trigger changes to TRUE. Normal end processing is performed if execution of the ResetPLCError instruction ends normally (i.e., if the value of Done is TRUE). Error end processing is performed if execution ends in an error (i.e., if the value of Error is TRUE).

LD

Variable OperatingEnd Trigger Operating RS_instance ResetPLCError_instance

Data type BOOL BOOL BOOL RS ResetPLCError

Initial value FALSE FALSE FALSE

Comment Processing completed Execution condition Processing

Determine if execution of the ResetPLCError has ended.

ResetPLCError_instance.Done

OperatingEnd

ResetPLCError_instance.Error

Accept trigger. Trigger
OperatingEnd

RS_instance

RS

Set

Q1

Reset1

Operating

Execute ResetPLCError instruction. Operating

Operating

ResetPLCError_instance

ResetPLCError

Execute

Done Busy Error ErrorID

Processing after normal end
Operating ResetPLCError_instance.Done Inline ST 1 // Processing after normal end 2 ;

Processing after error end Operating ResetPLCError_instance.Error

Inline ST
1 // Processing after error end 2 ;

2-826

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

2 Instruction Descriptions

ST Variable
Trigger

Data type BOOL

LastTrigger

BOOL

OperatingStart Operating ResetPLCError_instance

BOOL BOOL ResetPLCError

Initial value FALSE
FALSE
FALSE FALSE

Comment Execution condition Value of Trigger from previous task period Processing started Processing

// Detect when Trigger changes to TRUE.

IF ( (Trigger=TRUE) AND (LastTrigger=FALSE) ) THEN

OperatingStart:=TRUE;

2

Operating

:=TRUE;

END_IF;

LastTrigger:=Trigger;

// Initialize ResetPLCError_instance. IF (OperatingStart=TRUE) THEN
ResetPLCError_instance(Execute:=FALSE); OperatingStart:=FALSE; END_IF;

// Execute ResetPLCError instruction. IF (Operating=TRUE) THEN
ResetPLCError_instance(Execute:=TRUE);

IF (ResetPLCError_instance.Done=TRUE) THEN // Processing after normal end Operating:=FALSE;
END_IF;

IF (ResetPLCError_instance.Error=TRUE) THEN // Processing after error end Operating:=FALSE;
END_IF; END_IF;

ResetPLCError

NJ/NX-series Instructions Reference Manual (W502)

2-827

2 Instruction Descriptions

GetPLCError

The GetPLCError instruction gets the highest level status (partial fault or minor fault) and highest level event code of the current Controller errors in the PLC Function Module.

Instruction GetPLCError

Name
Get PLC Controller Error Status

FB/FUN FUN

Graphic expression

(@)GetPLCError

EN

Out

Level

Code

ST expression
Out:=GetPLCError(Level, Code);

Variables

Name

Meaning

I/O

Description

Valid range

Unit

Default

Out

Error flag

TRUE: Controller error exists.

Depends on data type.

FALSE:No Controller error

Level

Highest level status

Highest level status of all current Controller errors in the PLC Function Module

0, 2, or 3

Output

0: No Controller error 2: Partial fault level 3: Minor fault level

Code

Highest level event code

Highest level event code of all current Controller errors in the PLC Function Module
16#0000_0000: No Controller error 16#0007_0000 to 16#FFFF_FFFF: Event code

16#00000000
16#00070000 to 16#FFFFFFFF

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

Out

OK

Level

OK

Code

OK

Function
The GetPLCError instruction gets the highest level status and the highest level event code of the current Controller errors in the PLC Function Module and outputs them to Level and Code. If there are currently no Controller errors, the value of error flag Out is FALSE. If there is more than one Controller error at the highest event level, the value of Code is the event code for the Controller error that occurred first.

2-828

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

2 Instruction Descriptions

The following figure shows a programming example.

LD

ST

abc:=GetPLCError(def, ghi);

GetPLCError
EN Level Code

abc
def ghi

The GetPLCError instruction gets the highest level status and the highest level event code of the

current Controller errors in the PLC Function Module and outputs them to Level and Code.

Out=abc TRUE

Current Controller error exists.

2

Controller error in the PLC Function Module.

Acquired.

Level =def

Code =ghi

Related System-defined Variables

Name _PLC_ErrSta

Meaning
Error Status of PLC Function Module

Data type WORD

Description
Contains the error status of the PLC Function Module.*1

*1 Refer to the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) or NY-series Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for details.

GetPLCError

NJ/NX-series Instructions Reference Manual (W502)

2-829

2 Instruction Descriptions

ResetCJBError

The ResetCJBError instruction resets a Controller error in the I/O bus.

Instruction ResetCJBError

Name
Reset CJ Bus Controller Error

FB/FUN FB

Graphic expression

ResetCJBError_instance

ResetCJBError

Execute UnitNo

Done Busy Error ErrorID

ST expression
ResetCJBError_instance( Execute, UnitNo, Done, Busy, Error, ErrorID);

Precautions for Correct Use You cannot use this instruction in an NX-series CPU Unit.

Variables

Name UnitNo

Meaning
Unit number

I/O Input

Description
Unit number for which to reset errors

Valid range

Unit

_CBU_No00 to _CBU_- --No15, _SIO_No00 to _SIO_No95

_UNIT_ALL

Default
_UNIT _ALL

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

UnitNo

Refer to Function for the enumerators of the enumerated type _eUnitNo.

Function

The ResetCJBError instruction resets a Controller error in the I/O bus. If the Unit specified by unit number UnitNo is a CJ-series Special Unit, the Unit is restarted.
The data type of UnitNo is enumerated type _eUnitNo. The meanings of the enumerators are as follows:

Enumerators

Meaning

_CBU_No00 to _CBU_No15 _SIO_No00 to _SIO_No95

Unit number of CPU Bus Unit, 00 to 15 Unit number of Special I/O Unit, 00 to 95

_UNIT_ALL

All Units

2-830

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

ResetCJBError

2 Instruction Descriptions

The following example is for when UnitNo is _CBU_No00. The Controller error on the I/O bus is reset and the CPU Bus Unit with unit number 0 is restarted.

LD

ST

A _CBU_No00

ResetCJBError_instance

ResetCJBError

Execute UnitNo

Done Busy Error ErrorID

abc
def ghi jkl

ResetCJBError_instance(A, _CBU_No00, abc, def, ghi, jkl);

The ResetCJBError instruction resets a Controller error in the I/O bus.

2

Also, the CPU Bus Unit with unit number UnitNo is restarted.

There is a current Controller error in the I/O bus.

Error is reset.

UnitNo = _CBU_No00: CPU Bus Unit with unit number 0 is restarted.

Related System-defined Variables

Name _CJB_ErrSta

Meaning I/O Bus Error Status

Data type WORD

Description Contains the error status of the I/O bus.*1

*1 Refer to the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) for details.

Precautions for Correct Use
· The error may not be reset immediately after you execute this instruction. Use the GetCJBError instruction to confirm that the errors were reset.
· An error occurs in the following cases. Error will be FALSE. · The value of UnitNo is outside of the valid range. · The Unit specified by UnitNo does not exist.

NJ/NX-series Instructions Reference Manual (W502)

2-831

2 Instruction Descriptions

GetCJBError

The GetCJBError instruction gets the highest level status and highest level event code of the current Controller errors in the I/O bus of the NJ-series CPU Unit.

Instruction GetCJBError

Name
Get I/O Bus Error Status

FB/FUN FUN

Graphic expression

(@)GetCJBError

EN

Out

Level

Code

ST expression
Out:=GetCJBError(Level, Code);

Precautions for Correct Use You cannot use this instruction in an NX-series CPU Unit.

Variables

Name

Meaning

I/O

Out

Error flag

Level

Highest level status

Code

Highest level event code

Output

Description

Valid range

TRUE: Controller error exists.

Depends on data type.

FALSE:No Controller error

Highest level status of all current 0, 2, or 3 Controller errors in the I/O bus

0: No Controller error 2: Partial fault level 3: Minor fault level

Highest level event code of all current Controller errors in the I/O bus
16#0000_0000: No Controller error 16#0007_0000 to 16#FFFF_FFFF: Event code

16#00000000
16#00070000 to 16#FFFFFFFF

Unit ---

Default ---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

Out

OK

Level

OK

Code

OK

2-832

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

2 Instruction Descriptions

Function

The GetCJBError instruction gets the highest level status and the highest level event code of the current Controller errors in the I/O bus and outputs them to Level and Code. If there are currently no Controller errors, the value of error flag Out is FALSE. If there is more than one Controller error at the highest event level, the value of Code is the event code for the Controller error that occurred first.
The following figure shows a programming example.

LD

ST

abc:=GetCJBError(def, ghi);

2

GetCJBError

abc

EN Level def Code ghi

The GetCJBError instruction gets the highest level status and the highest level event code of the current Controller errors in the I/O bus and outputs them to Level and Code.

There is a current Controller error in the I/O bus.

Acquired.

Out=abc TRUE Level =def Code =ghi

Current Controller error exists.

Related System-defined Variables

Name _CJB_ErrSta

Meaning I/O Bus Error Status

Data type WORD

Description Contains the error status of the I/O bus.*1

*1 Refer to the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) for details.

GetCJBError

NJ/NX-series Instructions Reference Manual (W502)

2-833

2 Instruction Descriptions

GetEIPError

The GetEIPError instruction gets the highest level status (partial fault or minor fault) and highest level event code of the current Controller errors in the EtherNet/IP Function Module.

Instruction GetEIPError

Name
Get EtherNet/IP Error Status

FB/FUN FUN

Graphic expression

(@)GetEIPError

EN

Out

Level

Code

ST expression
Out:=GetEIPError(Level, Code);

Variables

Name

Meaning

I/O

Out

Error flag

Level

Highest event level

Code

Highest level event code

Output

Description
TRUE: Controller error exists.
FALSE:No Controller error
Highest level status of all current Controller errors in the EtherNet/IP Function Module
0: No Controller error 2: Partial fault level 3: Minor fault level
Highest level event code of all current Controller errors in the EtherNet/IP Function Module
16#0000_0000: No Controller error 16#0007_0000 to 16#FFFF_FFFF: Event code

Valid range Depends on data type.
0, 2, or 3
16#00000000 16#00070000 to 16#FFFFFFFF

Unit ---

Default ---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

Out

OK

Level

OK

Code

OK

Function
The GetEIPError instruction gets the highest level status and the highest level event code of the current Controller errors in the EtherNet/IP Function Module and outputs them to Level and Code. If there are currently no Controller errors, the value of error flag Out is FALSE. If there is more than one Controller error at the highest event level, the value of Code is the event code for the Controller error that occurred first.

2-834

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

2 Instruction Descriptions

The following figure shows a programming example.

LD

ST

abc:=GetEIPError(def, ghi);

GetEIPError
EN Level Code

abc
def ghi

The GetEIPError instruction gets the highest level status and the highest level event code of the

current Controller errors in the EtherNet/IP Function Module and outputs them to Level and

Code.

Out=abc

TRUE

Current Controller error exists.

2

Controller error in the EtherNet/IP Function Module.

Acquired.

Level =def

Code =ghi

Related System-defined Variables

Name _EIP_ErrSta

Meaning
Error Status of EtherNet/IP Function Module

Data type WORD

Description
Contains the error status of the EtherNet/IP Function Module.*1

*1 Refer to the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) or NY-series Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for details.

GetEIPError

NJ/NX-series Instructions Reference Manual (W502)

2-835

2 Instruction Descriptions

ResetMCError

The ResetMCError instruction resets Controller errors in the Motion Control Function Module.

Instruction ResetMCError

Name
Reset Motion Control Error

FB/FUN FB

Graphic expression

ResetMCError_instance

ResetMCError

Execute

Done Busy Failure Error ErrorID

ST expression
ResetMCError_instance( Execute, Done, Busy, Failure Error, ErrorID);

Variables

Name Failure

Meaning

I/O

Failure end Output

Description
TRUE: The errors were not reset.
FALSE:The errors were reset normally.

Valid range Depends on data type.

Unit ---

Default ---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

Failure

OK

Function

The ResetMCError instruction resets a Controller error in the Motion Control Function Module. If the errors are not reset, the value of Failure changes to TRUE.
No matter what task the program that executes the ResetMCError is placed in, this instruction resets errors for all axes and all axes groups.
The following figure shows a programming example.

LD

ST

ResetMCError_instance(A, abc, def,

ResetMCError_instance

ghi, jkl, mno);

A

ResetMCError

abc

Execute

Done Busy def Failure ghi Error jkl ErrorID mno

2-836

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

ResetMCError

2 Instruction Descriptions

The ResetMCError instruction resets Controller errors in the Motion Control Function Module. If the errors are not reset, the value of Failure changes to TRUE.

Controller error in the Motion Control Function Module.

Error is reset. Failure =ghi

TRUE if the error could not be reset and FALSE if the error was reset.

Related System-defined Variables

Name _MC_ErrSta

Meaning

Data type

Description

2

Motion Control Error Status

WORD

Contains the error status of the Motion Control Function Module.*1

*1 Refer to the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) or NY-series Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for details.

Precautions for Correct Use
· The error may not be reset immediately after you execute this instruction. Use the GetMCError instruction to confirm that the errors were reset.
· If you attempt to execute this instruction during an MC Test Run, the value of Busy remains TRUE and the instruction is not executed.
· If you execute this instruction for an OMRON G5-series Servo Drive, perform exclusive control of the instructions so that the ResetECError instruction is not executed at the same time. If the ResetMCError and ResetECError instructions are executed at the same time, the G5-series Servo Drive will no longer accept SDO communications.

Version Information

· With a CPU Unit with unit version 1.02 to 1.09, you can create only 100 instances of this instruction.

· If you transfer a user program that has more than 100 instances of this instruction to a Controller with a CPU Unit with unit version 1.02 to 1.09, a Controller error will occur. The Controller error depends on the transfer method that is used for the user program as given below.

User program transfer method
Project transferred with synchronization function
User program transferred with online editing

Event code for Controller error
10250000 hex 571D0000 hex 571D0000 hex

Level of Controller error
Major fault level Observation Observation

· If you transfer a user program that has more than 100 instances of this instruction to a Controller with a CPU Unit with unit version 1.01 or earlier, the above Controller error will not occur. However, if you create too many instances of this instruction, the user program will become too large and a major fault level Controller error will occur.

NJ/NX-series Instructions Reference Manual (W502)

2-837

2 Instruction Descriptions
Sample Programming
This sample detects Controller errors in the EtherCAT Master Function Module and Motion Control Function Module. If errors are detected, they are reset. The processing procedure is as follows:
1 The GetECError instruction is executed to detect any Controller errors in the EtherCAT Master Function Module.
2 If errors are detected, they are reset with the ResetECError instruction. 3 The GetMCError instruction is executed to detect any Controller errors in the Motion Control
Function Module.
4 If errors are detected, they are reset with the ResetMCError instruction.

2-838

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

System Control Instructions

ResetMCError

LD

Variable

Data type

Initial value

Comment

Request

BOOL

FALSE

Error detection reset request

EC_Err_Level

UINT

0

Highest event level in EtherCAT Master Function Module

EC_Err_Code

DWORD

DWORD#16#0

Highest level event code in EtherCAT Master Function Module

EC_Operating

BOOL

FALSE

Resetting error in EtherCAT Master Function Module

MC_Err_Level

UINT

0

Highest event level in Motion Control Function Module

MC_Err_Code

DWORD

DWORD#16#0

Highest level event code in Motion Control Function Module

MC_Operating

BOOL

FALSE

Resetting error in Motion Control Function Module

2

Normal_End

BOOL

FALSE

Normal end

ResetECError_instance ResetECError

ResetMCError_instance ResetMCError

Execute GetECError instruction.

Request

GetECError
EN Level Code

EC_Operating
EC_Err_Level EC_Err_Code

Execute ResetECError instruction if error occurs in EtherCAT Master Function Module.

ResetECError_instance

EC_Operating

ResetECError

Execute

Done Busy Error ErrorID

Execute GetMCError instruction after resetting error in EtherCAT Master Function Module or if there is no error.

ResetECError_instance.Done

Request

EC_Operating

GetMCError
EN Level Code

MC_Operating
MC_Err_Level MC_Err_Code

Execute ResetMCError instruction if error occurs in Motion Control Function Module.

MC_Operating

ResetMCError_instance ResetMCError

Execute

Done Busy Failure Error ErrorID

Processing after normal end ResetMCError_instance.Done

Normal_End

Request

EC_Operating

MC_Operating

ResetECError_instance.Done MC_Operating

NJ/NX-series Instructions Reference Manual (W502)

2-839

2 Instruction Descriptions

ST

Variable Request EC_Error EC_Err_Level EC_Err_Code EC_Stage MC_Error MC_Err_Level MC_Err_Code MC_Stage ResetECError_instance ResetMCError_instance

Data type BOOL BOOL UINT DWORD INT BOOL UINT DWORD INT ResetECError ResetMCError

Initial value

Comment

FALSE

Error detection reset request

FALSE

Error in EtherCAT Master Function Module

0

Highest event level in EtherCAT Master Function Module

DWORD#16#0 Highest level event code in EtherCAT Master Function Module

0

Error reset in EtherCAT Master Function Module

FALSE

Error in Motion Control Function Module

0

Highest event level in Motion Control Function Module

DWORD#16#0 Highest level event code in Motion Control Function Module

0

Error reset in Motion Control Function Module

IF (Request=TRUE) THEN EC_Error:=GetECError(EC_Err_Level, EC_Err_Code);
MC_Error:=GetMCError(MC_Err_Level, MC_Err_Code);

// Determine error resetting requests. // Detect Controller errors in EtherCAT Master Function // Module. // Detect Controller errors in Motion Control Function // Module.

IF (EC_Error=TRUE) THEN // Controller error in EtherCAT Master Function Module.

CASE EC_Stage OF

0 :

// Initialize

ResetECError_instance(Execute:=FALSE);

EC_Stage:=INT#1;

1 :

// Resetting Controller error in EtherCAT Master Function Module.

ResetECError_instance(Execute:=TRUE);

IF (ResetECError_instance.Done=TRUE) THEN

EC_Stage:=INT#99; // Normal end

END_IF;

IF (ResetECError_instance.Error=TRUE) THEN

EC_Stage:=INT#98; // Error end

END_IF;

99 :

// Processing after normal end

EC_Stage:=INT#0;

98 :

// Processing after error end.

EC_Stage:=INT#0;

END_CASE;

END_IF;

IF (MC_Error=TRUE) THEN // Controller error in Motion Control Function Module.

CASE MC_Stage OF

0 :

// Initialize

ResetMCError_instance(Execute:=FALSE);

MC_Stage:=INT#1;

1 :

// Resetting Controller error in Motion Control Function Module.

IF (EC_Error=FALSE) THEN // Recover operation for all slaves.

ResetMCError_instance(Execute:=TRUE);

IF (ResetMCError_instance.Done=TRUE) THEN

MC_Stage:=INT#99; // Normal end

END_IF;

IF ( (ResetMCError_instance.Error=TRUE) OR (ResetMCError_instance.Failure=TRUE) ) THEN

MC_Stage:=INT#98; // Error end

END_IF;

END_IF;

99 :

// Processing after normal end

MC_Stage:=INT#0;

98 :

// Processing after error end.

MC_Stage:=INT#0;

END_CASE;

END_IF;

END_IF;

2-840

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

GetMCError

2 Instruction Descriptions

GetMCError

The GetMCError instruction gets the highest level status (partial fault or minor fault) and highest level event code of the current Controller errors in the Motion Control Function Module.

Instruction

Name

FB/FUN

Graphic expression

ST expression

GetMCError

Get Motion Control FUN Error Status

(@)GetMCError EN

Out:=GetMCError(Level, Code); Out

Level

Code

2

Variables

Name

Meaning

I/O

Out

Error flag

Level

Highest level status

Code

Highest level event code

Output

Description
TRUE: Controller error exists.
FALSE:No Controller error
Highest level status of all current Controller errors in the Motion Control Function Module
0: No Controller error 2: Partial fault level 3: Minor fault level
Highest level event code of all current Controller errors in the Motion Control Function Module
16#0000_0000: No Controller error 16#0007_0000 to 16#FFFF_FFFF: Event code

Valid range Depends on data type.
0, 2, or 3
16#00000000 16#00070000 to 16#FFFFFFFF

Unit ---

Default ---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

Out

OK

Level

OK

Code

OK

NJ/NX-series Instructions Reference Manual (W502)

2-841

2 Instruction Descriptions

Function

The GetMCError instruction gets the highest level status and the highest level event code of the current Controller errors in the Motion Control Function Module and outputs them to Level and Code. If there are currently no Controller errors, the value of error flag Out is FALSE. If there is more than one Controller error at the highest event level, the value of Code is the event code for the Controller error that occurred first.
The following figure shows a programming example.

LD

ST

abc:=GetMCError(def, ghi);

GetMCError
EN Level Code

abc
def ghi

The GetMCError instruction gets the highest level status and the highest level event code of the

current Controller errors in the Motion Control Function Module and outputs them to Level and

Code.

Current Controller error exists.

Out=abc TRUE

Controller error in the Motion Control Function Module.

Acquired.

Level =def

Code =ghi

Related System-defined Variables

Name _MC_ErrSta

Meaning
Error Status of Motion Control Function Module

Data type WORD

Description
Contains the error status of the Motion Control Function Module.*1

*1 Refer to the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) or NY-series Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for details.

Sample Programming
Refer to the sample programming that is provided for the ResetMCError instruction (page 2-836).

2-842

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

ResetECError

2 Instruction Descriptions

ResetECError

The ResetECError instruction resets a Controller error in the EtherCAT Master Function Module.

Instruction ResetECError

Name
Reset EtherCAT Error

FB/FUN FB

Graphic expression

ResetECError_instance

ResetECError

Execute

Done Busy Error ErrorID

ST expression ResetECError_instance( Execute, Done, Busy, Error, ErrorID);
2

Variables
Only common variables are used.

Function

The ResetECError instruction resets Controller errors in the EtherCAT Master Function Module. The following figure shows a programming example.

LD

ST

ResetECError_instance(A, abc, def, ghi, jkl);

ResetECError_instance

A

ResetECError

abc

Execute

Done Busy def Error ghi ErrorID jkl

The ResetECError instruction resets a Controller error in the EtherCAT Master Function Module.

Controller error in the EtherCAT Master Function Module.

Error is reset.

Related System-defined Variables

Name _EC_ErrSta

Meaning

Data type

Built-in EtherCAT Error WORD

Description
Contains a summary of the errors in the EtherCAT Master Function Module.*1

*1 Refer to the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) or NY-series Industrial Panel PC / Industrial Box PC Built-in EtherCAT Port User's Manual (Cat. No. W562) for details.

NJ/NX-series Instructions Reference Manual (W502)

2-843

2 Instruction Descriptions
Precautions for Correct Use
· The error may not be reset immediately after you execute this instruction. Use the GetECError instruction to confirm that the errors were reset.
· If you execute this instruction for an OMRON G5-series Servo Drive, perform exclusive control of the instructions so that the ResetMCError, MC_Reset, or MC_GroupReset instruction is not executed at the same time. If any of these three instructions and the ResetECError instruction are executed at the same time, the G5-series Servo Drive will no longer accept SDO communications.
· You cannot execute this instruction during execution of the following instructions: EC_DisconnectSlave, EC_ConnectSlave, EC_ChangeEnableSetting, ResetECError, RestartNXUnit, and NX_ChangeWriteMode.
· An error occurs in the following case. Error will change to TRUE. · This instruction is executed again while processing to clear a Controller error from the EtherCAT Master Function Module is in progress. · The EC_DisconnectSlave, EC_ConnectSlave, EC_ChangeEnableSetting, ResetECError, RestartNXUnit, or NX_ChangeWriteMode instruction is already in execution.
Sample Programming
Refer to the sample programming that is provided for the ResetMCError instruction (page 2-836).

2-844

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

GetECError

2 Instruction Descriptions

GetECError

The GetECError instruction detects errors in the EtherCAT Master Function Module.

Instruction GetECError

Name
Get EtherCAT Error Status

FB/FUN FUN

Graphic expression

(@)GetECError

EN

Out

Level

Code

ST expression
Out:=GetECError(Level, Code);

2

Variables

Name

Meaning

I/O

Out

Error flag

Level

Highest level status
Output

Code

Highest level event code

Description
TRUE: Error exists.*1
FALSE: No error
Status of the current error with the highest level*1
0: No error 2: Partial fault level 3: Minor fault level
Event code of the current error with the highest level*1

Valid range Depends on data type. 0, 2, or 3
16#00000000 16#00070000 to 16#FFFFFFFF

Unit ---

Default ---

*1 The errors that are detected depend on the unit version of the CPU Unit and the version of the Sysmac Studio. Refer to Function for details.

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

Out

OK

Level

OK

Code

OK

NJ/NX-series Instructions Reference Manual (W502)

2-845

2 Instruction Descriptions

Function
The GetECError instruction detects errors in the EtherCAT Master Function Module. The value of Out is TRUE if there is an error and FALSE if there is no error. Level gives the status of the current error with the highest level. Code gives the event code of the current error with the highest level.

Detected Errors and Output Variable Values
The errors that are detected by this instruction depend on the unit version of the CPU Unit. The following table lists the errors that are detected for each unit version.

Unit version of CPU Unit 1.02 or later
1.01 or earlier

Detected errors
Communications port errors, master errors, and slave errors
Communications port errors and master errors

The following table shows the relationship between the unit version of the CPU Unit, the status of the EtherCAT Master Function Module, and the values of the output variables.

Unit version of CPU Unit 1.04 or later
1.02 or 1.03
1.00 or 1.01

Status of EtherCAT Master Func-
tion Module

Value of Out

No error

FALSE

Communications TRUE port error or master error

Slave error
No error
Communications port error or master error

FALSE TRUE

Slave error
No error
Communications port error or master error

FALSE FALSE TRUE

Slave error

FALSE

Value of Level
0 Status of the current error with the highest level 2: Partial fault level 3: Minor fault level
0 Status of the current error with the highest level 2: Partial fault level 3: Minor fault level
0 Status of the current error with the highest level 2: Partial fault level 3: Minor fault level 0

Value of Code
16#0000_0000 Event code of the current error with the highest level.*1 16#0007_0000 to 16#FFFF_FFFF 16#0000_0000 16#0000_0000 Event code of the current error with the highest level.*1 16#0007_0000 to 16#FFFF_FFFF 16#0000_0000 16#0000_0000 Event code of the current error with the highest level.*1 16#0007_0000 to 16#FFFF_FFFF
16#0000_0000

*1 If there is more than one error at the highest event level, the value of Code is the event code for the error that occurred first.

2-846

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

GetECError

2 Instruction Descriptions

Notation Example

The following figure shows a programming example.

LD

ST

abc:=GetECError(def, ghi);

GetECError
EN Level Code

abc
def ghi

The GetECError instruction detects current communications port errors, master errors, and slave

2

errors in the EtherCAT Master Function Module.

Current errors in the EtherCAT Master Function Module

Acquired.

Out = abc Level = def Code =ghi

TRUE

There is a current error.
Highest level of all current errors Highest level event code of all current errors

Related System-defined Variables

Name

Meaning

Data type

Description

_EC_ErrSta

Built-in EtherCAT Error WORD

Contains a summary of the errors in the EtherCAT Master Function Module.*2

_EC_PortErr*1

Communications Port WORD Error

Contains a summary of the EtherCAT master communications port errors.*2

_EC_MstrErr*1

Master Error

WORD

Contains a summary of the EtherCAT master errors and the slave errors detected by the EtherCAT master.*2

_EC_SlavErr

Slave Error

WORD

Contains a summary of the overall EtherCAT slave error status.*2

*1 The GetECError instruction gets the errors that are shown by _EC_PortErr (Communications Port Error) and _EC_MstrErr (Master Error).

*2 Refer to the NJ/NX-series CPU Unit Built-in EtherCAT Port User's Manual (Cat. No. W505) or NY-series Industrial Panel PC / Industrial Box PC Built-in EtherCAT Port User's Manual (Cat. No. W562) for details.

Precautions for Correct Use

Version Information A CPU Unit with unit version 1.02 or later is required to detect slave errors with this instruction.

Sample Programming
Refer to the sample programming that is provided for the ResetMCError instruction (page 2-836).

NJ/NX-series Instructions Reference Manual (W502)

2-847

2 Instruction Descriptions

ResetNXBError

The ResetNXBError instruction resets the current Controller errors in the NX Bus Function Module.

Instruction

Name

FB/ FUN

Graphic expression

ST expression

ResetNXBError

Reset NX Bus Error

FB

ResetNXBError_instance

ResetNXBError

Execute

Done

Busy

Error

ErrorID

ResetNXBError_instance( Execute, Done, Busy, Error, ErrorID);

Precautions for Correct Use You can use this instruction for the NX102 CPU Unit and NX1P2 CPU Unit.

Variables
Only common variables are used.

Function
The ResetNXBError instruction resets the current Controller errors in the NX Bus Function Module.
After an error is reset, the Busy output variable changes to FALSE and the Done output variable changes to TRUE. For Safety Control Units, however, errors are not reset. If this instruction is executed again in a different instance from the instance for which error reset processing is in progress, the latter instruction will result in an error. The Error output variable of the latter command changes to TRUE and the error code (Multi-execution of Instructions: 041A) is output to the ErrorID output variable.

Related System-defined Variables

Name _NXB_ErrSta

Meaning NX Bus Function Module Error Status

Additional Information
· If you execute this instruction in the Simulator, when Execute changes from FALSE to TRUE, Done changes to TRUE, Busy changes to FALSE, Error changes to FALSE, and ErrorID changes to 0. And, errors will not be cleared.
· If the cause of the error is not solved and the error status remains after resetting an error, the error reset may appear to be impossible.

2-848

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

2 Instruction Descriptions
· The event log is not cleared.
Precautions for Correct Use
You cannot use this instruction in an event task. A compiling error will occur.
2

ResetNXBError

NJ/NX-series Instructions Reference Manual (W502)

2-849

2 Instruction Descriptions

GetNXBError

The GetNXBError instruction gets the highest level status of all current Controller errors in the NX Bus Function Module of the NX-series CPU Unit.

Instruction

Name

FB/ FUN

Graphic expression

ST expression

GetNXBError

Get NX Bus Error Status

FUN

GetNXBError

EN

Out

UnitProxy Level

Out:=GetNXBError( UnitProxy, Level);

Precautions for Correct Use You can use this instruction for the NX102 CPU Unit and NX1P2 CPU Unit.

Variables

Name

Meaning

I/O

Description

Valid range

Unit

Out

Error flag

TRUE: Error exists. FALSE: No error

Depends on data type.

UnitProxy

Lower level NX Unit

NX Unit where the status of the current error is Level

---

Output Status of the current error with

---

Level

Highest level status

the highest level 0: No error 2: Partial fault level

0, 2, or 3

3: Minor fault level

Default ---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

Out UnitProxy Level

OK Refer to Function for details on the structure _sNXUNIT_ID.
OK

2-850

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

GetNXBError

2 Instruction Descriptions

Function
The GetNXBError instruction gets the highest level status (partial fault or minor fault) of the current Controller errors in the NX Bus Function Module. This instruction applies to the NX102 CPU Unit, NX1P2 CPU Unit and NX Unit connected to the NX bus on the CPU Unit.

The value of Out is TRUE if there is an error and FALSE if there is no error.
Level gives the status of the current error with the highest level.
UnitProxy returns the UnitProxy of the NX Unit where the status of the current error is Level.
If errors of the same level occur in more than one Unit, it returns UnitProxy of the NX Unit that is closest 2
to the master and has the lowest unit number.

The data type of UnitProxy is structure _sNXUNIT_ID. The specifications are as follows:

Name

Meaning

Description

Data type

UnitProxy

Lower level NX Unit

NX Unit where the status of the current error is Level

_sNXUNIT_ID

NodeAdr

Node address

Node address of the Communications Coupler Unit

UINT

IPAdr

IP address

IP address of the Communications Coupler Unit

BYTE[5]

UnitNo

Unit number

Unit number of the NX Unit

UDINT

Path

Path

Path information to the NX Unit

BYTE[64]

PathLength

Valid path length

Valid path length

USINT

Pass a _sNXUNIT_ID structure variable that is created in the variable table to UnitProxy.

Related System-defined Variables

Name _NXB_ErrSta _NXB_MstrErrSta _NXB_UnitErrSta[1] to [63]

Meaning NX Bus Function Module Error Status NX Bus Function Module Master Error Status NX Bus Function Module Unit Error Status

Additional Information
· If you execute this instruction in the Simulator, this instruction always returns No error, and Out changes to FALSE, Level changes to 0, and the value of UnitProxy is undefined.

NJ/NX-series Instructions Reference Manual (W502)

2-851

2 Instruction Descriptions

GetNXUnitError

The GetNXUnitError instruction gets the highest level status and highest level event code of the current Controller errors in the NX Bus Function Module of the NX-series CPU Unit or NX Units.

Instruction

Name

FB/ FUN

GetNXUnitErro Get NX Unit

r

Error Status

FB

Graphic expression

GetNXUnitError_instance

GetNXUnitError

Execute UnitProxy Timeout

Done Busy Error ErrorID ErrorIDEx Level Code

ST expression
GetNXUnitError_instance( Execute, UnitProxy, TimeOut, Done, Busy, Error, ErrorID, ErrorIDEx, Level, Code);

Precautions for Correct Use You can use this instruction for the NX102 CPU Unit and NX1P2 CPU Unit.

Variables

Name UnitProxy

Meaning Specified Unit

I/O

Description

Specifies the target NX Unit.

Valid range

Unit

---

---

TimeOut

Input Timeout time

2.0 s when the timeout time is set to 0

0 to 60000

ms

Level Code

Highest level status
Output
Highest level event code

Status of the current error with the highest level 0: No error 2: Partial fault level 3: Minor fault level
Highest level event code of all the current errors

0, 2, or 3
--16#00000000
16#00070000 to 16#FFFFFFFF

*1 If you omit an input parameter, the default value is not applied. A building error will occur.

Default *1 2000 (2.0 s)
---

2-852

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

GetNXUnitError

2 Instruction Descriptions

numbers REAL

Boolean BOOL

Bit strings

Integers

Real

Times, durations, dates, and text strings

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

UnitProxy

Refer to Function for details on the structure _sNXUNIT_ID.

TimeOut

OK

Level

OK

Code

OK

2

Function
The GetNXUnitError instruction outputs the highest level status (partial fault or minor fault) and highest level event code of the current Controller errors in the NX Bus Function Module and NX Units, as well as the lower level NX Units from which to get the data. This instruction applies to the NX102 CPU Unit, NX1P2 CPU Unit and NX Unit connected to the NX bus on the CPU Unit.

The Unit from which to get data is specified with UnitProxy. The instruction finishes getting data when the value of Done changes to TRUE.

The data type of UnitProxy is structure _sNXUNIT_ID. The specifications are as follows:

Name UnitProxy
NodeAdr
IPAdr UnitNo Path PathLength

Meaning Specified Unit Node address
IP address Unit number Path Valid path length

Description Specified Unit Node address of the Communications Coupler Unit IP address of the Communications Coupler Unit Unit number of the specified Unit Path information to the specified Unit Valid path length

Data type _sNXUNIT_ID UINT
BYTE[5] UDINT BYTE[64] USINT

Pass a device variable that is assigned to the specified Unit to UnitProxy.

TimeOut specifies the timeout time. If a response does not return within the timeout time, it judges that communications failed.

Level gives the status of the current error with the highest level.
Code gives the event code of the current error with the highest level. If errors of the same level occur in more than one Unit, it gives the oldest event code. If there is no error, it gives 16#00000000.

NJ/NX-series Instructions Reference Manual (W502)

2-853

2 Instruction Descriptions

Specified NX Unit and Variable Values
The values output to in-out and output variables vary depending on the specified NX Unit. The relationship between the specified NX Unit and the value of each variable is shown in the following table.

Specified Unit Value of Level Value of Code

NX102 CPU Unit NX1P2 CPU Unit

NX Unit on CPU Unit

Highest level status of CPU Unit

Highest level status of NX Unit

If there are more than one error: Highest level event code If there are more than one error in the same level: Oldest event code If there is no error: 16#0000_0000

Combined Use with the GetNXBError Instruction
In the user program, normally use the GetNXBError (Get NX Bus Error Status) instruction to monitor if there are errors on the NX bus.
When the Level output variable of the GetNXBError instruction is other than 0, the value that indicates the NX Unit with the highest event level is stored in UnitProxy of the instruction.
To get Level and Code of the NX Unit where the error occurred, execute the GetNXUnitError ininstruction.

Related System-defined Variables

Name _NXB_UnitErrFlagTbl

Meaning NX Unit Error Status

2-854

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

System Control Instructions

GetNXUnitError

Additional Information

Parameters That You Need Pass to UnitProxy

The following describes the parameters that you need to pass to the UnitProxy input variable.

 Using Only the User Program to Pass Parameters to UnitProxy

Pass ErrorUnit which is the value of UnitProxy that you get from the GetNXBError instruction sent to the NX Bus Function Module.

condition1

GetNXBError

2

EN

UnitProxy Level

ErrorUnit

condition2 ErrorUnit

instance

GetNXUnitError

Execute UnitProxy Timeout

Done Busy Error ErrorID ErrorIDEx Level Code

 Using the Device Variable to Pass Parameters to UnitProxy
Create a device variable that specifies the Unit on the NX bus and pass it to UnitProxy of this instruction.

External variables

Variable N1_Node_location_information

Data type _sNXUNIT_ID

Constant

Comment

condition1

N1_Node_location_information

instance

GetNXUnitError

Execute UnitProxy Timeout

Done Busy Error ErrorID ErrorIDEx Level Code

Run in the Simulator

If you run this instruction in the Simulator, the result when Execute changes from FALSE to TRUE is as shown in the table below.

Output variable Done Busy Error ErrorID

Meaning TRUE FALSE FALSE 0

NJ/NX-series Instructions Reference Manual (W502)

2-855

2 Instruction Descriptions

Output variable

Meaning

ErrorIDEx

0

Level

0

Code

0

Precautions for Correct Use

· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is normally completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error.
· A compiling error will occur if you use this instruction in an event task. Do not use this instruction in event tasks.
· You cannot execute this instruction more than once at the same time. Only one instance can be executed at a time.
· Error is TRUE if an error occurred. The meanings of the values of ErrorID and ErrorIDEx are given in the following table.

Value of ErrorID 16#0400 16#041A
16#2C00

Value of ErrorIDEx
16#00000000
16#00000000 16#0000 0401 16#0000 1001 16#0000 1002 16#0017 0000 16#0020 0000 16#0021 0000
16#0000 1010
16#0000 1101
16#0000 110B
16#0000 1110 16#0000 1111 16#0000 2101
16#0000 2110
16#0000 2210
16#0000 2213

16#0000 2230

Description
· The value of UnitProxy is outside of the valid range. · The value of TimeOut is outside of the valid range. While this instruction was being executed, it was executed again. The specified Unit does not support the instruction. An input parameter, output parameter, or in-out parameter is incorrect. Confirm that the intended parameter is used for the input parameter, output parameter, or in-out parameter.
The data size of the specified NX object does not agree with the data size specified in WriteDat. The Unit is not correct. Check the Unit. The size of the read data is too large. Make sure that the read data specification is correct. There is no object that corresponds to the value of Obj.Index. There is no object that corresponds to the value of Obj.Subindex. The specified NX object cannot be written. The value of WriteDat exceeds the range of the values of the NX object to write. The specified Unit is not in a mode that allows writing data. Instruction execution was not possible because the specified Unit was performing an I/O check. Execute the instruction after the I/O check is completed. The status of the specified Unit does not agree with the value of the read source or write destination NX object. Take the following actions if the value of Obj.Index is between 0x6000 and 0x6FFF or between 0x7000 and 0x7FFF. · Delete the read source or write designation NX object from the I/O allo-
cation settings. · Reset the error for the specified Unit. · Place the specified Unit in a mode that does not allow writing data.

2-856

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

GetNXUnitError

2 Instruction Descriptions

Value of ErrorID

Value of ErrorIDEx

Description

16#0000 2231

Instruction execution was not possible because the specified Unit was performing initialization. Wait for the Unit to start normal operation and then execute the instruction.

16#0000 250F

Hardware access failed. Execute the instruction again.

16#0000 2601 16#0000 2602 16#0010 0000

The specified Unit does not support this instruction. Check the version of the Unit.

16#0000 2603

Execution of the instruction failed. Execute the instruction again. Make sure that at least one channel is enabled in the selections of the

2

channels to use.

16#0000 2621

The NX Unit is not in a status in which it can acknowledge the instruction. Wait for a while and then execute the instruction again.

16#0001 0000

The specified Unit does not exist. Make sure that the Unit configuration is correct.

16#0011 0000

The specified port number does not exist. Make sure that the Unit configuration is correct.

16#0012 0000 16#0013 0000 16#0015 0000 16#0016 0000

The value of UnitProxy is not correct. Set the variable that indicates the specified EtherCAT Coupler Unit again.

16#2C00

16#0014 0000
16#0030 0000 16#8001 0000

The specified node address is not correct. Make sure that the Unit configuration is correct.
The specified Unit is busy. Execute the instruction again.

16#0031 0000

The specified Unit is not supported for connection. Check the version of the Unit.

16#80000000 16#80050000 16#81010000 16#81020000 16#82020000 16#82030000 16#82060000 to 16#8FFF0000 16#90010000 to 16#FFFE0000

An error occurred in the communications network. Execute the instruction again.

16#8002 0000 16#8003 0000 16#8103 0000 16#8200 0000

An error occurred in the communications network. Reduce the amount of communications traffic.

16#8004 0000 16#8100 0000 16#8201 0000 16#8204 0000 16#8205 0000 16#9000 0000

An error occurred in the communications network. Check the Unit and cable connections. Make sure that the power supply to the Unit is ON.

16#2C02

16#00000000

A timeout occurred during communications.

NJ/NX-series Instructions Reference Manual (W502)

2-857

2 Instruction Descriptions

Sample Programming
This sample passes the Unit, level, and code values to variables for display on a touch panel if an error occurs on the NX bus.

The system configuration is as shown below. Assume that three NX Units are connected to an NX1P2 CPU Unit.

Device Variables
NX Units 1st NX Unit 2nd NX Unit 3rd NX Unit

Device variable N1_Node_location_information N2_Node_location_information N3_Node_location_information

Definitions of Global Variables

Global Variables

Variable N1_Node_location_information N2_Node_location_information N3_Node_location_information HMI_Level*1 HMI_Code*1 HMI_Unit*1

Data type _sNXUNIT_ID _sNXUNIT_ID _sNXUNIT_ID UINT DWORD UDINT

Constant

*1 The variables that begin with HMI are variables for display on a touch panel .

Internal variables

Variable
instance ErrorOccurred ErrorUnit DummyLowerUnit

Data type
GetNXUnitError BOOL _sNXUNIT_ID _sNXUNIT_ID

Constant

Comment Comment

2-858

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

2 Instruction Descriptions

P_On

GetNXBError EN
UnitProxy Level

ErrorOccurred ErrorUnit

ErrorOccurred

instance GetNXUnitError

ErrorUnit

Execute UnitProxy

Done Busy

Timeout

Error

ErrorID

ErrorIDEx

Level

Code

2

instance.Done

instance.Level

MOVE

EN

ENO

In

Out

HMI_Level

instance.Code

MOVE

EN

ENO

In

Out

HMI_Code

ErrorUnit.UnitNo

MOVE

EN

ENO

In

Out

HMI_Unit

GetNXUnitError

NJ/NX-series Instructions Reference Manual (W502)

2-859

2 Instruction Descriptions

SetInfo

The SetInfo instruction creates user-defined information.

Instruction SetInfo

Name
Create Userdefined Information

FB/FUN FUN

Graphic expression

(@)SetInfo

EN

ENO

Code

Out

Info1

Info2

ST expression SetInfo(Code, Info1, Info2);

Variables

Name

Meaning

I/O

Description

Valid range

Unit

Code

Event code

Event code of user-defined 40001 to 60000 information to generate

Info1 Info2 Out

Attached information 1
Attached information 2
Return value

Input Output

Values recorded in event log

---

when the user-defined infor- Depends on data type.

mation is generated

Always TRUE

TRUE only

---

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default 40001
*
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

Code Info1 Info2 Out

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK

STRING

2-860

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

SetInfo

2 Instruction Descriptions

Function

The SetInfo instruction generates the user-defined information specified by event code Code. The time of occurrence, event code Code, event level, attached information Info1, and attached information Info2 are stored in the user event log area that corresponds to the level of the event code.
The following figure shows a programming example. User-defined information for event code 40001 is generated. The values of variables abc and def are stored as attached information.

LD

ST

SetInfo(UINT#40001, abc, def);

2
SetInfo

EN

ENO

UINT#40001 Code

abc Info1

def Info2

The SetInfo instruction generates the user-defined information specified by event code Code. Also, the time of occurrence, event code Code, event level, attached information Info1, and attached information Info2 are stored in the user event log area that corresponds to the level of the event code.

Event code Code UINT#40001

User-defined information generated.

Time of occurrence

Event code Code

UINT#40001

Event level

Attached information: Info1 = abc

Attached information: Info2 = def

Written.

User-defined Event Log Area

Precautions for Correct Use
· Always use variables for the input parameters that are passed to Info1 and Info2. If the attached information is not used, specify a dummy variable. A building error will occur if a constant is specified.
· Return value Out is not used when the instruction is used in ST. · An error occurs in the following case. ENO will be FALSE.
· The value of Code is outside of the valid range.

NJ/NX-series Instructions Reference Manual (W502)

2-861

2 Instruction Descriptions

ResetUnit

The ResetUnit instruction restarts a CPU Bus Unit or Special I/O Unit.

Instruction ResetUnit

Name Restart Unit

FB/FUN FB

Graphic expression

ResetUnit_instance

ResetUnit

Execute UnitNo

Done Busy Error ErrorID

ST expression
ResetUnit_instance(Execute, UnitNo, Done, Busy, Error, ErrorID);

Precautions for Correct Use You cannot use this instruction in an NX-series CPU Unit.

Variables

Name UnitNo

Meaning
Unit number

I/O Input

Description
Unit number of Unit to restart

Valid range

Unit

_CBU_No00 to _CBU_- --No15, _SIO_No00 to _SIO_No95

Default
_CBU _No00

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

UnitNo

Refer to Function for the enumerators of enumeration type _eUnitNo.

Function

The ResetUnit instruction restarts a CPU Bus Unit or Special I/O Unit. The Unit to restart is specified by UnitNo.
The data type of UnitNo is enumerated type _eUnitNo. The meanings of the enumerators are as follows:

Enumerators

Meaning

_CBU_No00 to _CBU_No15

Unit number of CPU Bus Unit, 00 to 15

_SIO_No00 to _SIO_No95

Unit number of Special I/O Unit, 00 to 95

2-862

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

ResetUnit

2 Instruction Descriptions

The following example is for when UnitNo is _CBU_No00. CPU Bus Unit with unit number 0 is restarted.

LD

ST

A _CBU_No00

ResetUnit_instance

ResetUnit

Execute UnitNo

Done Busy Error ErrorID

ResetUnit_instance(A, _CBU_No00, abc, def, ghi, jkl);
abc
def ghi jkl

The ResetUnit instruction restarts the CPU Bus Unit or Special I/O Unit with UnitNo.

2

UnitNo = _CBU_No00: CPU Bus Unit with unit number 0 is restarted.

Precautions for Correct Use
· This instruction will not end in an error even if restart processing is in progress for the Unit specified by UnitNo. The value of Busy remains at TRUE and the value of Done changes to TRUE when restart processing is finished. Restart requests are not queued.
· The Unit is restarted if the value of Execute is TRUE when operation starts. · An error occurs in the following cases. Error will change to TRUE.
· The value of UnitNo is outside of the valid range. · The Unit specified with UnitNo does not exist. · Restart processing failed.

Sample Programming

When the value of Trigger changes to TRUE, the baud rate of serial port 1 on the Serial Communications Unit with a unit number of 0 is set to 38,400 bps and the Unit is restarted.
Definitions of Global Variables

Global Variables

Name

Data type

Initial value

AT

Retain

Comment

SCU_P1_BaudrateCfg

USINT

0

IOBus://rack#0/slot#0 /P1_BaudrateCfg

Baud rate

NJ/NX-series Instructions Reference Manual (W502)

2-863

2 Instruction Descriptions

LD
Internal Variables

Variable
OperatingEnd Trigger Operating RS_instance ResetUnit_instance

Data type
BOOL BOOL BOOL RS ResetUnit

Initial value
FALSE
FALSE
FALSE

External Variables

Variable SCU_P1_BaudrateCfg

Data type USINT

Comment Processing completed Execution condition Processing
Comment Baud rate

Determine if execution of the ResetUnit has ended.

ResetUnit_instance.Done

OperatingEnd

ResetUnit_instance.Error

Accept trigger.

Trigger

ResetUnit_instance.Busy

OperatingEnd

RS_instance

RS

Set

Q1

Reset1

Operating

Set baud rate in device variable.

Operating

MOVE

EN USINT#8 In

ENO Out

SCU_P1_BaudrateCfg

Execute ResetUnit instruction. ResetUnit_instance

Operating

ResetUnit

_CBU_No00

Execute UnitNo

Done Busy Error ErrorID

Processing after normal end Operating ResetUnit_instance.Done

Inline ST
1 // Processing after normal end 2 ;

Processing after error end Operating ResetUnit_instance.Error

Inline ST
1 // Processing after error end 2 ;

2-864

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

ResetUnit

2 Instruction Descriptions

ST
Internal Variables

Variable Trigger

LastTrigger

OperatingStart Operating ResetUnit_instance

Data type BOOL

Initial value
FALSE

BOOL

FALSE

BOOL BOOL ResetUnit

FALSE FALSE

Comment
Execution condition Value of Trigger from previous task period Processing started Processing

External Variables

Variable

Data type

Comment

2

SCU_P1_BaudrateCfg USINT

Baud rate

// Detect when Trigger changes to TRUE.

IF ( (Trigger=TRUE) AND (LastTrigger=FALSE) AND (ResetUnit_instance.Busy=FALSE) ) THEN

OperatingStart:=TRUE;

Operating

:=TRUE;

END_IF;

LastTrigger:=Trigger;

// Initialize ResetUnit_instance and set baud rate in device variable. IF (OperatingStart=TRUE) THEN
ResetUnit_instance(Execute:=FALSE); SCU_P1_BaudrateCfg:=USINT#8; OperatingStart :=FALSE; END_IF;

// Execute ResetUnit instruction.

IF (Operating=TRUE) THEN

ResetUnit_instance(

Execute :=TRUE,

// Execution condition

UnitNo :=_CBU_No00); // Unit number

IF (ResetUnit_instance.Done=TRUE) THEN // Processing after normal end Operating:=FALSE;
END_IF;

IF (ResetUnit_instance.Error=TRUE) THEN // Processing after error end Operating:=FALSE;
END_IF; END_IF;

NJ/NX-series Instructions Reference Manual (W502)

2-865

2 Instruction Descriptions

GetNTPStatus

The GetNTPStatus instruction reads the NTP status.

Instruction GetNTPStatus

Name Read NTP Status

FB/FUN FUN

Graphic expression

(@)GetNTPStatus

EN

ENO

Out

ExecTime

ExecNormal

ST expression
GetNTPStatus(ExecTime, ExecNormal);

Variables

Name Out ExecTime
Exec Normal

Meaning
Return value
NTP last normal operation time

I/O Output

NTP normal end flag

Description Always TRUE NTP last normal operation time
TRUE: Normal end FALSE: Error end

Valid range TRUE only
Depends on data type.

Unit
---
Year, month, day, hour, minutes, seconds
---

Default ---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

Out

OK

ExecTime

OK

Exec

OK

Normal

Function

The GetNTPStatus instruction reads the NTP status. The following information is read: ExecTime (NTP last normal operation time) and ExecNormal (NTP normal end flag).
The following figure shows a programming example.

LD

ST

GetNTPStatus(abc, def);

GetNTPStatus

EN

ENO

ExecTime abc ExecNormal def

2-866

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

2 Instruction Descriptions

The GetNTPStatus instruction reads the NTP status. The values of ExecTime and ExecNormal will be as follows when the last normal NTP operation was at 00:00.00 on July 7, 2011.

NTP server

Read.

ExecTime ExecNormal

DT#2011-07-07-00:00:00.000000000 TRUE

Related System-defined Variables

Name

2

Meaning

Data type

Description

_EIP_NTPResult

NTP Status

*1

Contains the NTP status.*2

*1 _sNTP_RESULT *2 Refer to the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) for details.

Precautions for Correct Use
· Out (Return value) is not used when the instruction is used in ST. · This instruction reads the contents of the _EIP_NTPResult system-defined variable. You cannot
access this variable directly. Always use this instruction to read the contents of the variable.

GetNTPStatus

NJ/NX-series Instructions Reference Manual (W502)

2-867

2 Instruction Descriptions

RestartNXUnit

The RestartNXUnit instruction restarts an EtherCAT Coupler Unit or NX Unit.

Instruction RestartNXUnit

Name
Restart NX Units

FB/FUN FB

Graphic expression

RestartNXUnit_instance

RestartNXUnit

Execute UnitProxy

Done Busy Error ErrorID ErrorIDEx

ST expression
RestartNXUnit_instance(Execute, UnitProxy, Done, Busy, Error, ErrorID, ErrorIDEx);

Variables

Name

Meaning

I/O

Description

Valid range

UnitProxy Specified Unit Input

A Unit to restart: EtherCAT Cou- ---

---

pler Unit, NX Bus Function Mod-

ule or NX Unit

* If you omit the input parameter, the default value is not applied. A building error will occur.

Bit strings

Integers

Unit

Default

*

Times, durations, dates, and text strings

Real numbers

Boolean BOOL

STRING DT TOD
DATE TIME

LREAL REAL

LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE

UnitProxy

Refer to Function for details on the structure _sNXUNIT_ID.

Function
The RestartNXUnit instruction restarts an EtherCAT Coupler Unit or an NX Unit on the EtherCAT Coupler Unit, and an NX Unit connected to the NX bus on the NX Bus Function Module or on the CPU Unit. You can use it to restart a specified Unit independently. However, you cannot restart an EtherCAT Coupler Unit or NX Bus Function Module independently. If you specify an EtherCAT Coupler Unit or NX Bus Function Module, all of the NX Units that are connected to it are also restarted.
The Unit to restart is specified with UnitProxy.

2-868

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

RestartNXUnit

2 Instruction Descriptions

The data type of UnitProxy is structure _sNXUNIT_ID. The meanings of the members are as follows:

Name UnitProxy
NodeAdr
IPAdr UnitNo Path PathLength

Meaning Specified Unit
Node address
IP address
Unit number Path Valid path length

Content Specified Unit Node address of the Communications Coupler Unit IP address of the Communications Coupler Unit Unit number of specified Unit Path information to the specified Unit
Valid path length

Data type _sNXUNIT_ID UINT
BYTE[5] UDINT BYTE[64] USINT

Pass a device variable that is assigned to the specified EtherCAT Coupler Unit or an NX Unit on the 2
EtherCAT Coupler Unit, and an NX Unit connected to the NX bus on the NX Bus Function Module or on the CPU Unit to UnitProxy.

Notation Example

The following example shows a case of restarting all EtherCAT Slave Terminals. A variable that is named `ECAT1' with a data type of _sNXUNIT_ID is assigned to the EtherCAT Coupler Unit.

LD

ST

A ECAT1

RestartNXUnit_instance

RestartNXUnit

Execute UnitProxy

Done Busy Error ErrorID ErrorIDEx

abc
def ghi jkl mno

RestartNXUnit_instance(A, ECAT1, abc, def, ghi, jkl, mno);

Built-in EtherCAT port ECAT1

EtherCAT

NX Units

Coupler Unit

The `ECAT1' EtherCAT Coupler Unit and all of the NX Units that are connected to it are restarted.

NJ/NX-series Instructions Reference Manual (W502)

2-869

2 Instruction Descriptions

Related System-defined Variables

Name _EC_MBXSlavTbl[i] "i" is the node address.

Meaning
Message Communications Enabled Slave Table

Data type BOOL

NX Unit Message Enabled BOOL _NXB_UnitMsgActiveTbl Status
[i]

Description
This variable indicates whether communications are possible for each slave.
TRUE: Communications are possible.
FALSE: Communications are not possible.
This table indicates the slaves that can perform message communications. Use this variable to confirm that communications with the relevant slave are possible.

Additional Information
You can use the following procedure to write data with the following attributes to an EtherCAT Coupler Unit, an NX Unit on the EtherCAT Coupler Unit, or an NX Unit connected to the NX bus of the CPU Unit. · Power OFF Retain attribute · The values are updated when the Unit is restarted.
1 Use the NX_ChangeWriteMode instruction (page 2-874) to change the Unit to a mode that allows writing data.
2 Use the NX_WriteObj instruction (page 2-980) to write data to the Unit.
3 Use the NX_SaveParam instruction (page 2-879) to save the data that you wrote.
4 Use the RestartNXUnit instruction to restart the Unit.
Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section (page 2-3) for a timing chart for Execute, Done, Busy, and Error. · If you specify a Unit that is assigned to a motion control axis (data type _sAXIS_REF) for UnitProxy,
a Controller error will occur in the Motion Control Function Module. Use the ResetMCError instruction (page 2-836) to reset the Controller error. · For UnitProxy, specify the device variable that is assigned to an EtherCAT Coupler Unit or an NX Unit on the EtherCAT Coupler Unit, and an NX Unit connected to the NX bus of the NX Bus Function Module or the CPU Unit in the I/O Map of the Sysmac Studio. Refer to the Sysmac Studio Version 1 Operation Manual (Cat. No. W504-E1-07 or later) for details on assigning device variables. · If the RestartNXUnit instruction is executed during execution of another RestartNXUnit instruction or execution of the NX_ChangeWriteMode instruction (page 2-874), the RestartNXUnit instruction that is executed later will be queued. Up to 192 instructions can be queued. A building error will occur if an attempt is made to queue more than 192 instructions. The time that an instruction is queued is not included in the timeout time. · The value of Busy is TRUE while the instruction is queued. · This instruction is related to NX Message Communications Errors. If too many instructions that are related to NX Message Communications Errors are executed at the same time, an NX Message Communications Error will occur. Refer to A-4 Instructions Related to NX Message Communications Errors for a list of the instructions that are related to NX Message Communications Errors.

2-870

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

RestartNXUnit

2 Instruction Descriptions

· You cannot execute this instruction during execution of the following instructions: EC_DisconnectSlave, EC_ConnectSlave, EC_ChangeEnableSetting, ResetECError, RestartNXUnit, and NX_ChangeWriteMode. An error will occur if you attempt to execute it.
· Error is TRUE if an error occurred. The meanings of the values of ErrorID and ErrorIDEx are given in the following table.

Value of ErrorID Value of ErrorIDEx

Meaning

16#0419

16#0000 0000

The data type of UnitProxy is not correct.

16#2C00

16#0000 0401

The specified Unit does not support the instruction.

16#0000 1001 16#0000 1002 16#0017 0000 16#0020 0000 16#0021 0000

An input parameter, output parameter, or in-out parameter is incor-

rect.

Confirm that the intended parameter is used for the input parameter,

output parameter, or in-out parameter.

2

16#0000 1010

The data size of the specified NX object does not agree with the data size specified in WriteDat.

16#0000 1101

The Unit is not correct. Check the Unit.

16#0000 110B

The size of the read data is too large. Make sure that the read data specification is correct.

16#0000 1110

There is no object that corresponds to the value of Obj.Index.

16#0000 1111

There is no object that corresponds to the value of Obj.Subindex.

16#0000 2101

The specified NX object cannot be written.

16#0000 2110

The value of WriteDat exceeds the range of the values of the NX object to write.

16#0000 2210

The specified Unit is not in a mode that allows writing data.

16#0000 2213

Instruction execution was not possible because the specified Unit was performing an I/O check. Execute the instruction after the I/O check is completed.

16#0000 2230

The status of the specified Unit does not agree with the value of the read source or write destination NX object. Take the following actions if the value of Obj.Index is between 0x6000 and 0x6FFF or between 0x7000 and 0x7FFF.
· Delete the read source or write designation NX object from the I/O allocation settings.

· Reset the error for the specified Unit.

· Place the specified Unit in a mode that does not allow writing data.

16#0000 2231

Instruction execution was not possible because the specified Unit was performing initialization. Wait for the Unit to start normal operation and then execute the instruction.

16#0000 250F

Hardware access failed. Execute the instruction again.

16#0000 2601 16#0000 2602 16#0010 0000

The specified Unit does not support this instruction. Check the version of the Unit.

16#0000 2603

Execution of the instruction failed. Execute the instruction again. Make sure that at least one channel is enabled in the selections of the channels to use.

16#0000 2621

The NX Unit is not in a status in which it can acknowledge the instruction. Wait for a while and then execute the instruction again.

16#0001 0000

The specified Unit does not exist. Make sure that the Unit configuration is correct.

NJ/NX-series Instructions Reference Manual (W502)

2-871

2 Instruction Descriptions

Value of ErrorID
16#2C00
16#2C01 16#2C02 16#2C05 16#2C06 16#2C07

Value of ErrorIDEx
16#0011 0000
16#0012 0000 16#0013 0000 16#0015 0000 16#0016 0000
16#0014 0000
16#0030 0000 16#8001 0000
16#0031 0000
16#80000000 16#80050000 16#81010000 16#81020000 16#82020000 16#82030000 16#82060000 to 16#8FFF0000 16#90010000 to 16#FFFE0000 16#8002 0000 16#8003 0000 16#8103 0000 16#8200 0000 16#8004 0000 16#8100 0000 16#8201 0000 16#8204 0000 16#8205 0000 16#9000 0000
16#0000 0000
16#0000 0000
---
16#00000000
16#0000 0000

Meaning The specified port number does not exist. Make sure that the Unit configuration is correct. The value of UnitProxy is not correct. Set the variable that indicates the specified EtherCAT Coupler Unit again.
The specified node address is not correct. Make sure that the Unit configuration is correct. The specified Unit is busy. Execute the instruction again. The specified Unit is not supported for connection. Check the version of the Unit. An error occurred in the communications network. Execute the instruction again.
An error occurred in the communications network. Reduce the amount of communications traffic.
An error occurred in the communications network. Check the Unit and cable connections. Make sure that the power supply to the Unit is ON.
An attempt was made to queue more than 192 RestartNXUnit and NX_ChangeWriteMode instructions. A timeout occurred during communications. An error occurred in the EtherCAT network. Check the value of UnitProxy and the EtherCAT network configuration. The specified Unit is already being restarted from the Sysmac Studio. Therefore, this instruction does not need to be executed. A slave that cannot be specified for the instruction was connected at the slave node address of the specified Unit. Check the value of UnitProxy and the EtherCAT network configuration.

2-872

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

2 Instruction Descriptions

Version Information

A CPU Unit with unit version 1.05 or later and Sysmac Studio version 1.06 or higher are required to use this instruction. However, some versions/unit versions of the following products do not support restarting specified NX Units independently.
· CPU Units
· Sysmac Studio
· EtherCAT Coupler Units
· NX Units

If the unit version of a product does not support restarting specified NX Units independently, you

can specify only the EtherCAT Coupler Unit as the Unit to restart.

2

Refer to the NX-series EtherCAT Coupler Unit User's Manual (Cat. No. W519-E1-03 or later) for

the unit versions of products that support restarting specified NX Units independently.

Sample Programming
Refer to the sample programming for the NX_WriteObj instruction (page 2-980).

RestartNXUnit

NJ/NX-series Instructions Reference Manual (W502)

2-873

2 Instruction Descriptions

NX_ChangeWriteMode

The NX_ChangeWriteMode instruction changes an EtherCAT Coupler Unit or NX Unit to a mode that allows writing data.

Instruction NX_Change WriteMode

Name
Change to NX Unit Write Mode

FB/FUN FB

Graphic expression

NX_ChangeWriteMode_instance

NX_ChangeWriteMode

Execute UnitProxy

Done Busy Error ErrorID ErrorIDEx

ST expression
NX_ChangeWriteMode_instance (Execute, UnitProxy, Done, Busy, Error, ErrorID, ErrorIDEx);

Variables

Name UnitProxy

Meaning

I/O

Specified Unit Input

Description

Valid range

Unit for which to change the mode ---

Unit ---

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default *

Bit strings

Integers

Times, durations, dates, and text strings

Real numbers

Boolean BOOL

STRING DT TOD
DATE TIME

LREAL REAL

LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE

UnitProxy

Refer to Function for details on the structure _sNXUNIT_ID.

Function
The NX_ChangeWriteMode instruction changes the mode for an EtherCAT Coupler Unit, an NX Unit on the EtherCAT Coupler Unit, or an NX Unit connected to the NX bus of the CPU Unit to a mode that allows writing data. The Unit for which to change the mode is specified with UnitProxy. Data can be written when the value of Done changes to TRUE.

The data type of UnitProxy is structure _sNXUNIT_ID. The meanings of the members are as follows:

Name UnitProxy
NodeAdr
IPAdr UnitNo Path PathLength

Meaning Specified Unit
Node address
IP address
Unit number Path Valid path length

Content
Unit for which to change the write mode
Node address of the Communications Coupler Unit
IP address of the Communications Coupler Unit
Unit number of specified Unit
Path information to the specified Unit
Valid path length

Data type _sNXUNIT_ID UINT
BYTE[5] UDINT BYTE[64] USINT

Pass the device variable that is assigned to the specified Unit to UnitProxy.

2-874

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

NX_ChangeWriteMode

2 Instruction Descriptions

Related Instructions and Execution Procedure

You can use this instruction to write data with the following attributes to an EtherCAT Coupler Unit, an NX Unit on the EtherCAT Coupler Unit, or an NX Unit connected to the NX bus of the CPU Unit.

· Power OFF Retain attribute

· The values are updated when the Unit is restarted.

Use the following procedure to execute the related instructions.

1 Use the NX_ChangeWriteMode instruction to change the Units to a mode that allows writing

data.

2 Use the NX_WriteObj instruction (page 2-980) to write data to the Unit.

2

3 Use the NX_SaveParam instruction (page 2-879) to save the data that you wrote.

4 Use the RestartNXUnit instruction (page 2-868) to restart the Unit.

Notation Example

The following notation example changes the `NX1' NX Unit to a mode that allows writing data. A variable that is named `NX1' with a data type of _sNXUNIT_ID is assigned to the NX Unit to change.

LD

ST

NX_ChangeWriteMode_instance

A

NX_ChangeWriteMode

abc

Execute NX1 UnitProxy

Done Busy def Error ghi ErrorID jkl ErrorIDEx mno

NX_ChangeWriteMode_instance(A, NX1, abc, def, ghi, jkl, mno);

Built-in EtherCAT port

NX1
The `NX1' NX Unit is changed to a mode that allows writing data.

EtherCAT

NX Units

Coupler Unit

NJ/NX-series Instructions Reference Manual (W502)

2-875

2 Instruction Descriptions

Related System-defined Variables

Name _EC_MBXSlavTbl[i] "i" is the node address.

Meaning
Message Communications Enabled Slave Table

Data type BOOL

NX Unit Message Enabled BOOL _NXB_UnitMsgActiveTbl Status
[i]

Description
This variable indicates whether communications are possible for each slave.
TRUE: Communications are possible.
FALSE: Communications are not possible.
This table indicates the slaves that can perform message communications. Use this variable to confirm that communications with the relevant slave are possible.

Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section (page 2-3) for a timing chart for Execute, Done, Busy, and Error.
· If you specify a Unit that is assigned to a motion control axis (data type _sAXIS_REF) for UnitProxy, a Controller error will occur in the Motion Control Function Module. If that occurs, use the ResetMCError instruction (page 2-836) to reset the Controller error.
· For UnitProxy, specify the device variable that is assigned to an EtherCAT Coupler Unit, an NX Unit on the EtherCAT Coupler Unit, or an NX Unit connected to the NX bus of the CPU Unit in the I/O Map of the Sysmac Studio. Refer to the Sysmac Studio Version 1 Operation Manual (Cat. No. W504-E107 or later) for details on assigning device variables.
· If the NX_ChangeWriteMode instruction is executed during execution of another NX_ChangeWriteMode instruction or execution of the RestartNXUnit instruction (page 2-868), the RestartNXUnit instruction that is executed later will be queued. Up to 192 instructions can be queued. A building error will occur if an attempt is made to queue more than 192 instructions. The time that an instruction is queued is not included in the timeout time.
· The value of Busy is TRUE while the instruction is queued.
· This instruction is related to NX Message Communications Errors. If too many instructions that are related to NX Message Communications Errors are executed at the same time, an NX Message Communications Error will occur. Refer to A-4 Instructions Related to NX Message Communications Errors) for a list of the instructions that are related to NX Message Communications Errors.
· You cannot execute this instruction during execution of the following instructions: EC_DisconnectSlave, EC_ConnectSlave, EC_ChangeEnableSetting, ResetECError, RestartNXUnit, and NX_ChangeWriteMode. An error will occur if you attempt to execute it.

2-876

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

System Control Instructions

NX_ChangeWriteMode

· Error is TRUE if an error occurred. The meanings of the values of ErrorID and ErrorIDEx are given in the following table.

Value of ErrorID Value of ErrorIDEx

Meaning

16#0419

16#0000 0000

The data type of UnitProxy is not correct.

16#0000 0401

The specified Unit does not support the instruction.

16#0000 1001 16#0000 1002 16#0017 0000 16#0020 0000 16#0021 0000

An input parameter, output parameter, or in-out parameter is incorrect. Confirm that the intended parameter is used for the input parameter, output parameter, or in-out parameter.

16#0000 1010

The data size of the specified NX object does not agree with the data size specified in WriteDat.

16#0000 1101

The correct Unit was not specified. Check the Unit.

2

16#0000 110B

The size of the read data is too large. Make sure that the read data specification is correct.

16#0000 1110

There is no object that corresponds to the value of Obj.Index.

16#0000 1111

There is no object that corresponds to the value of Obj.Subindex.

16#0000 2101

The specified NX object cannot be written.

16#0000 2110

The value of WriteDat exceeds the range of the values of the NX object to write.

16#0000 2210

The specified Unit is not in a mode that allows writing data.

16#0000 2213

Instruction execution was not possible because the specified Unit was performing an I/O check. Execute the instruction after the I/O check is completed.

The status of the specified Unit does not agree with the value of the read source or write destination NX object. Take the following actions if the value of Obj.Index is between 0x6000 and 0x6FFF or between 0x7000 and 0x7FFF.

16#2C00

16#0000 2230

· Delete the read source or write designation NX object from the I/O allocation settings.
· Reset the error for the specified Unit.

· Place the specified Unit in a mode that does not allow writing data.

16#0000 2231

Instruction execution was not possible because the specified Unit was performing initialization. Wait for the Unit to start normal operation and then execute the instruction.

16#0000 250F

Hardware access failed. Execute the instruction again.

16#0000 2601 16#0000 2602 16#0010 0000

The specified Unit does not support this instruction. Check the version of the Unit.

16#0000 2603

Execution of the instruction failed. Execute the instruction again. Make sure that at least one channel is enabled in the selections of the channels to use.

16#0000 2621

The NX Unit is not in a status in which it can acknowledge the instruction. Wait for a while and then execute the instruction again.

16#0001 0000

The specified Unit does not exist. Make sure that the Unit configuration is correct.

16#0011 0000

The specified port number does not exist. Make sure that the Unit configuration is correct.

16#0012 0000 16#0013 0000 16#0015 0000 16#0016 0000

The value of UnitProxy is not correct. Set the variable that indicates the specified EtherCAT Coupler Unit again.

NJ/NX-series Instructions Reference Manual (W502)

2-877

2 Instruction Descriptions

Value of ErrorID Value of ErrorIDEx

16#0014 0000

16#0030 0000 16#8001 0000

16#0031 0000

16#2C00

16#80000000 16#80050000 16#81010000 16#81020000 16#82020000 16#82030000 16#82060000 to 16#8FFF0000 16#90010000 to 16#FFFE0000
16#8002 0000 16#8003 0000 16#8103 0000 16#8200 0000
16#8004 0000 16#8100 0000 16#8201 0000 16#8204 0000 16#8205 0000 16#9000 0000

16#2C01

16#0000 0000

16#2C02

16#0000 0000

16#2C05

---

16#2C07

16#0000 0000

Meaning The specified node address is not correct. Make sure that the Unit configuration is correct. The specified Unit is busy. Execute the instruction again. The specified Unit is not supported for connection. Check the version of the Unit. An error occurred in the communications network. Execute the instruction again.
An error occurred in the communications network. Reduce the amount of communications traffic.
An error occurred in the communications network. Check the Unit and cable connections. Make sure that the power supply to the Unit is ON.
An attempt was made to queue more than 192 NX_ChangeWriteMode and RestartNXUnit instructions. A timeout occurred during communications. An error occurred in the EtherCAT network. Check the value of UnitProxy and the EtherCAT network configuration. A slave that cannot be specified for the instruction was connected at the slave node address of the specified Unit. Check the value of UnitProxy and the EtherCAT network configuration.

Version Information
A CPU Unit with unit version 1.05 or later and Sysmac Studio version 1.06 or higher are required to use this instruction.

Sample Programming
Refer to the sample programming for the NX_WriteObj instruction (page 2-980).

2-878

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

NX_SaveParam

2 Instruction Descriptions

NX_SaveParam

The NX_SaveParam instruction saves the data that was written to the specified EtherCAT Coupler Unit or NX Unit.

Instruction NX_Save Param

Name
Save NX Unit Parameters

FB/FUN FB

Graphic expression

NX_SaveParam_instance

NX_SaveParam

Execute UnitProxy TimeOut

Done Busy Error ErrorID ErrorIDEx

ST expression NX_SaveParam_instance(Execute, UnitProxy, TimeOut, Done, Busy, Error, ErrorID, ErrorIDEx);
2

Variables

Name UnitProxy TimeOut

Meaning Specified Unit Timeout time

I/O Input

Description Unit for which to save data Timeout time

Valid range --0 to 60,000

Unit --ms

If 0 is set, the timeout time is 2.0 s.

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default
*
2000 (2.0s)

Bit strings

Integers

Times, durations, dates, and text strings

Real numbers

Boolean BOOL

STRING DT TOD
DATE TIME

LREAL REAL

LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE

UnitProxy TimeOut

Refer to Function for details on the structure _sNXUNIT_ID. OK

Function
The NX_SaveParam instruction saves the data that was written to an EtherCAT Coupler Unit, an NX Unit on the EtherCAT Coupler Unit, or an NX Unit connected to the NX bus of the CPU Unit. The Unit for which to save the data is specified with UnitProxy. After the completion of saving the data, the value of Done changes to TRUE. Use the NX_WriteObj instruction (page 2-980) to write the data. Even if power is interrupted after this instruction is executed, the values of the data with a power OFF retain attribute are retained.
TimeOut specifies the timeout time. If a response does not return within the timeout time, it is assumed that communications failed. In that case, the Unit data is not saved.

NJ/NX-series Instructions Reference Manual (W502)

2-879

2 Instruction Descriptions

The data type of UnitProxy is structure _sNXUNIT_ID. The meanings of the members are as follows:

Name UnitProxy
NodeAdr
IPAdr
UnitNo Path PathLength

Meaning Specified Unit Node address
IP address
Unit number Path Valid path length

Description
Unit for which to save data
Node address of the Communications Coupler Unit
IP address of the Communications Coupler Unit
Unit number of specified Unit
Path information to the specified Unit
Valid path length

Data type _sNXUNIT_ID UINT
BYTE[5]
UDINT BYTE[64] USINT

Pass the device variable that is assigned to the specified Unit to UnitProxy.

Related Instructions and Execution Procedure
Depending on the attributes of the data that you write to an EtherCAT Coupler Unit, an NX Unit on the EtherCAT Coupler Unit, or an NX Unit connected to the NX bus of the CPU Unit, you must execute this instruction along with other instructions. The procedures for each case are given below.
 Execution Procedure 1
Use the following procedure to write data with the following attributes. · Power OFF Retain attribute · The values are updated when the Unit is restarted.
1 Use the NX_ChangeWriteMode instruction (page 2-874) to change the Unit to a mode that allows writing data.
2 Use the NX_WriteObj instruction (page 2-980) to write data to the Unit. 3 Use the NX_SaveParam instruction to save the data that you wrote. 4 Use the RestartNXUnit instruction (page 2-868) to restart the Unit.
 Execution Procedure 2
Use the following procedure to write data with the following attributes. · Power OFF Retain attribute · The values are updated as soon as they are written.
1 Use the NX_WriteObj instruction (page 2-980) to write data to the Unit. 2 Use the NX_SaveParam instruction to save the data that you wrote.

2-880

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

NX_SaveParam

2 Instruction Descriptions

Notation Example
The following notation example saves the data that was written to the `NX1' NX Unit. A variable that is named `NX1' with a data type of _sNXUNIT_ID is assigned to the NX Unit.

LD

NX_SaveParam_instance

A

NX_SaveParam

abc

NX1 UINT#0

Execute UnitProxy TimeOut

Done Busy def Error ghi ErrorID jkl ErrorIDEx mno

ST
NX_SaveParam_instance(A, NX1, UINT#0, abc, def, ghi, jkl, mno);
2

Built-in EtherCAT port NX1

EtherCAT Coupler Unit

NX Units

The data that was written to the `NX1' NX Unit is saved.
Use the NX_WriteObj instruction to write the data.

Related System-defined Variables

Name _EC_MBXSlavTbl[i] "i" is the node address.

Meaning
Message Communications Enabled Slave Table

Data type BOOL

Description
This variable indicates whether communications are possible for each slave. TRUE: Communications are possible. FALSE: Communications are not possible.

NJ/NX-series Instructions Reference Manual (W502)

2-881

2 Instruction Descriptions
Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section (page 2-3) for a timing chart for Execute, Done, Busy, and Error. · This instruction will not end in an error even if the Unit specified by UnitProxy is already saving data.
The value of Busy remains at TRUE and the value of Done changes to TRUE when saving the data is completed. Requests to save data are not queued. · An error will not occur even if this instruction is executed without writing data to the Unit. · Some of the Units have restrictions in the number of times that you can write data. Refer to the manuals for the specific Units for details. · For UnitProxy, specify the device variable that is assigned to an EtherCAT Coupler Unit, an NX Unit on the EtherCAT Coupler Unit, or an NX Unit connected to the NX bus of the CPU Unit in the I/O Map of the Sysmac Studio. Refer to the Sysmac Studio Version 1 Operation Manual (Cat. No. W504-E107 or later) for details on assigning device variables. · To write and save data with a Power OFF Retain attribute, execute the NX_SaveParam instruction after you execute the NX_WriteObj instruction (page 2-970). If you restart the Unit before you execute the NX_SaveParam instruction, the previous NX object data is restored. · This instruction is related to NX Message Communications Errors. If too many instructions that are related to NX Message Communications Errors are executed at the same time, an NX Message Communications Error will occur. Refer to A-4 Instructions Related to NX Message Communications Errors for a list of the instructions that are related to NX Message Communications Errors.

2-882

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

System Control Instructions

NX_SaveParam

· Error is TRUE if an error occurred. The meanings of the values of ErrorID and ErrorIDEx are given in the following table.

Value of ErrorID

Value of ErrorIDEx

Meaning

16#0400

16#0000 0000

· The value of UnitProxy is outside of the valid range. · The value of TimeOut is outside of the valid range.

16#0419

16#0000 0000

The data type of UnitProxy is not correct.

16#0000 0401

The specified Unit does not support the instruction.

16#0000 1001 16#0000 1002 16#0017 0000 16#0020 0000 16#0021 0000
16#0000 1010

An input parameter, output parameter, or in-out parameter is incorrect. Confirm that the intended parameter is used for the input parameter, output parameter, or in-out parameter.

The data size of the specified NX object does not agree with

2

the data size specified in WriteDat.

16#0000 1101

The correct Unit was not specified. Check the Unit.

16#0000 110B

The size of the read data is too large. Make sure that the read data specification is correct.

16#0000 1110

There is no object that corresponds to the value of Obj.Index.

16#0000 1111

There is no object that corresponds to the value of Obj.Subindex.

16#0000 2101

The specified NX object cannot be written.

16#0000 2110

The value of WriteDat exceeds the range of the values of the NX object to write.

16#0000 2210

The specified Unit is not in a mode that allows writing data.

16#0000 2213

Instruction execution was not possible because the specified Unit was performing an I/O check. Execute the instruction after the I/O check is completed.

16#2C00

The status of the specified Unit does not agree with the value of the read source or write destination NX object. Take the following actions if the value of Obj.Index is between 0x6000 and 0x6FFF or between 0x7000 and 0x7FFF.

16#0000 2230

· Delete the read source or write designation NX object from the I/O allocation settings.

· Reset the error for the specified Unit.

· Place the specified Unit in a mode that does not allow writing data.

16#0000 2231

Instruction execution was not possible because the specified Unit was performing initialization. Wait for the Unit to start normal operation and then execute the instruction.

16#0000 250F

Hardware access failed. Execute the instruction again.

16#0000 2601 16#0000 2602 16#0010 0000

The specified Unit does not support this instruction. Check the version of the Unit.

16#0000 2603

Execution of the instruction failed. Execute the instruction again. Make sure that at least one channel is enabled in the selections of the channels to use.

16#0000 2621

The NX Unit is not in a status in which it can acknowledge the instruction. Wait for a while and then execute the instruction again.

16#0001 0000

The specified Unit does not exist. Make sure that the Unit configuration is correct.

16#0011 0000

The specified port number does not exist. Make sure that the Unit configuration is correct.

NJ/NX-series Instructions Reference Manual (W502)

2-883

2 Instruction Descriptions

Value of ErrorID
16#2C00
16#2C01 16#2C02

Value of ErrorIDEx 16#0012 0000 16#0013 0000 16#0015 0000 16#0016 0000
16#0014 0000
16#0030 0000 16#8001 0000
16#0031 0000
16#80000000 16#80050000 16#81010000 16#81020000 16#82020000 16#82030000 16#82060000 to 16#8FFF0000 16#90010000 to 16#FFFE0000 16#8002 0000 16#8003 0000 16#8103 0000 16#8200 0000 16#8004 0000 16#8100 0000 16#8201 0000 16#8204 0000 16#8205 0000 16#9000 0000
16#0000 0000
16#0000 0000

Meaning The value of UnitProxy is not correct. Set the variable that indicates the specified EtherCAT Coupler Unit again. The specified node address is not correct. Make sure that the Unit configuration is correct. The specified Unit is busy. Execute the instruction again. The specified Unit is not supported for connection. Check the version of the Unit. An error occurred in the communications network. Execute the instruction again.
An error occurred in the communications network. Reduce the amount of communications traffic.
An error occurred in the communications network. Check the Unit and cable connections. Make sure that the power supply to the Unit is ON.
The number of instructions that can be simultaneously executed was exceeded. A timeout occurred during communications.

Version Information
A CPU Unit with unit version 1.05 or later and Sysmac Studio version 1.06 or higher are required to use this instruction.

Sample Programming
Refer to the sample programming for the NX_WriteObj instruction (page 2-980).

2-884

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

NX_ReadTotalPowerOnTime

2 Instruction Descriptions

NX_ReadTotalPowerOnTime

The NX_ReadTotalPowerOnTime instruction reads the total power ON time from a Communications Coupler Unit or NX Unit.

Instruction

Name

FB/FUN

Graphic expression

ST expression

NX_ReadTotalPowerONTime_instance(

Execute,

NX_ReadTotalPowerOnTime_instance UnitProxy,

NX_Read Read NX Unit

NX_ReadTotalPowerOnTime

Execute

Done

Done,

2

TotalPower Total Power ON FB

UnitProxy

Busy

Busy,

OnTime

Time

Error ErrorID ErrorIDEx

Error, ErrorID,

TotalPowerOnTime

ErrorIDEx,

TotalPowerOnTime);

Variables

Name
UnitProxy
TotalPowerOnTime

Meaning
Specified Unit
Total power ON time

I/O Input
Output

Description
Specifies the target NX Unit.
Stores the total power ON time that was read.

Valid range
---
Depends on data type.

Unit ---

* If you omit an input parameter, the default value is not applied. A building error will occur.

Default *
0

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE
Boolean BOOL

UnitProxy
TotalPowerOnTime

Refer to Function for details on the structure _sNXUNIT_ID. OK

Function
The NX_ReadTotalPowerOnTime instruction reads the approximate total power ON time from a Communications Coupler Unit, an NX Unit on the Communications Coupler Unit, or an NX Unit connected to the NX bus of the CPU Unit. The accuracy is 1 hour per month.
The Unit from which the total power ON time is read is specified with UnitProxy. When the value of Done changes to TRUE, the total power ON time has been read.

NJ/NX-series Instructions Reference Manual (W502)

2-885

2 Instruction Descriptions

The data type of UnitProxy is structure _sNXUNIT_ID. The meanings of the members are as follows:

Name UnitProxy

Meaning Specified Unit

Description Specified Unit

Data type _sNXUNIT_ID

NodeAdr IPAdr UnitNo

Node address IP address Unit number

Node address of the Communications Coupler Unit
IP address of the Communications Coupler Unit
Unit number of specified NX Unit

UINT BYTE[5] UDINT

Path

Path

Path information to the specified Unit BYTE[64]

PathLength Valid path length

Valid path length

USINT

Pass a device variable that is assigned to the specified Communications Coupler Unit, an NX Unit on the Communications Coupler Unit, or an NX Unit connected to the NX bus of the CPU Unit to UnitProxy.

Version Combinations
There are combinations in which you can read the total power ON time depending on the version of the Communications Coupler Unit connected to the CPU Unit, NX Unit on the Communications Coupler Unit, or NX Unit connected to the NX bus of the CPU Unit.
 EtherCAT Slave Terminal

Unit Digital I/O Unit Analog I/O Unit System Unit Position Interface Unit Temperature Input Unit

Version of NX Unit Version 1.0 or later

Version of EtherCAT Coupler Unit Version 1.2 or later

Version 1.1 or later

 NX Unit on NX102 CPU Unit and NX1P2 CPU Unit

Unit Digital I/O Unit Analog I/O Unit System Unit Position Interface Unit Temperature Input Unit

Version of NX Unit Version 1.0 or later
Version 1.1 or later

2-886

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

NX_ReadTotalPowerOnTime

2 Instruction Descriptions

Related System-defined Variables

Name

Meaning

Data type

Description

_EC_MBXSlavTbl[i] "i" is the node address.

Message Communications Enabled Slave BOOL Table

This variable indicates when communications are possible for each slave. TRUE: Communications are possible. FALSE: Communications are not possible.

This table indicates the slaves that can perform

_NXB_UnitMsgActiveTbl[i]

NX Unit Message Enabled Status

BOOL

message communications. Use this variable to confirm that communications with the relevant slave are possible.

2

Additional Information
If this instruction is executed by the Simulator, Busy changes to TRUE for only one task period after Execute changes from FALSE to TRUE. Busy changes to FALSE and Done changes to TRUE the next task period. The value that is read in TotalPowerOnTime will be 0.

Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal end of processing.
· Refer to Using this Section (page 2-3) for a timing chart for Execute, Done, Busy, and Error.
· For UnitProxy, specify the device variable that is assigned to an EtherCAT Coupler Unit, an NX Unit on the EtherCAT Coupler Unit, or an NX Unit connected to the NX bus of the CPU Unit in the I/O Map of the Sysmac Studio. Refer to the Sysmac Studio Version 1 Operation Manual (Cat. No. W504-E107 or later) for details on assigning device variables. An error will occur if you specify an NX-series CPU Unit for UnitProxy.
· There are restrictions in the number of Units that depend on the Communications Coupler Unit. Refer to the manual for your Communications Coupler Unit for details.
· Error is TRUE if an error occurred. The meanings of the values of ErrorID and ErrorIDEx are given in the following table.

NJ/NX-series Instructions Reference Manual (W502)

2-887

2 Instruction Descriptions

Value of ErrorID 16#0400 16#0419
16#2C00

Value of ErrorIDEx 16#0000 0000 16#0000 0000 16#0000 0401 16#0000 1001 16#0000 1002 16#0017 0000 16#0020 0000 16#0021 0000
16#0000 1010
16#0000 1101
16#0000 110B
16#0000 1110 16#0000 1111 16#0000 2101
16#0000 2110
16#0000 2210
16#0000 2213

Meaning
The value of UnitProxy is outside of the valid range. The data type of UnitProxy is not correct. The specified Unit does not support the instruction.
An input parameter, output parameter, or in-out parameter is incorrect. Confirm that the intended parameter is used for the input parameter, output parameter, or in-out parameter.
The data size of the specified NX object does not agree with the data size specified in WriteDat. The Unit is not correct. Check the Unit. The size of the read data is too large. Make sure that the read data specification is correct. There is no object that corresponds to the value of Obj.Index. There is no object that corresponds to the value of Obj.Subindex. The specified NX object cannot be written. The value of WriteDat exceeds the range of the values of the NX object to write. The specified Unit is not in a mode that allows writing data. Instruction execution was not possible because the specified Unit was performing an I/O check. Execute the instruction after the I/O check is completed.

2-888

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

NX_ReadTotalPowerOnTime

2 Instruction Descriptions

Value of ErrorID

Value of ErrorIDEx

Meaning

16#0000 2230

The status of the specified Unit does not agree with the value of the read source or write destination NX object. Take the following actions if the value of Obj.Index is between 0x6000 and 0x6FFF or between 0x7000 and 0x7FFF.
· Delete the read source or write destination NX object from the I/O allocation settings.

· Reset the error for the specified Unit. · Place the specified Unit in a mode that does not allow writing data.

Instruction execution was not possible because the specified Unit was

16#0000 2231

performing initialization. Wait for the Unit to start normal operation and then execute the instruc-

2

tion.

16#0000 250F

Hardware access failed. Execute the instruction again.

16#0000 2601 16#0000 2602 16#0010 0000

The specified Unit does not support this instruction. Check the version of the Unit.

16#0000 2603

Execution of the instruction failed. Execute the instruction again. Make sure that at least one channel is enabled in the selections of the channels to use.

16#0000 2621

The NX Unit is not in a status in which it can acknowledge the instruction. Wait for a while and then execute the instruction again.

16#0001 0000

The specified Unit does not exist. Make sure that the Unit configuration is correct.

16#2C00

16#0011 0000

The specified port number does not exist. Make sure that the Unit configuration is correct.

16#0012 0000 16#0013 0000 16#0015 0000 16#0016 0000

The value of UnitProxy is not correct. Set the variable that indicates the specified EtherCAT Coupler Unit again.

16#0014 0000

The specified node address is not correct. Make sure that the Unit configuration is correct.

16#0030 0000 16#8001 0000

The specified Unit is busy. Execute the instruction again.

16#0031 0000

The specified Unit is not supported for connection. Check the version of the Unit.

16#8000 0000 16#8005 0000 16#8101 0000 16#8102 0000 16#8202 0000 16#8203 0000 16#8206 0000
to 16#8FFF 0000 16#9001 0000
to 16#FFFE 0000

An error occurred in the communications network. Execute the instruction again.

16#8002 0000 16#8003 0000 16#8103 0000 16#8200 0000

An error occurred in the communications network. Reduce the amount of communications traffic.

NJ/NX-series Instructions Reference Manual (W502)

2-889

2 Instruction Descriptions

Value of ErrorID
16#2C00
16#2C01 16#2C02 16#2C05

Value of ErrorIDEx 16#8004 0000 16#8100 0000 16#8201 0000 16#8204 0000 16#8205 0000 16#9000 0000
16#0000 0000
16#0000 0000
---

16#2C07 16#2C08

16#0000 0000 16#00000000

Meaning
An error occurred in the communications network. Check the Unit and cable connections. Make sure that the power supply to the Unit is ON.
The number of instructions that can be simultaneously executed was exceeded. A timeout occurred during communications. An error occurred in the EtherCAT network. Check the value of UnitProxy and the EtherCAT network configuration. A slave that cannot be specified for the instruction was connected at the slave node address of the specified Unit. Check the value of UnitProxy and the EtherCAT network configuration. The total power ON time could not be read.

Sample Programming
Two modes are created in a program: maintenance mode and run mode. With this sample, if the button to read the total power ON time is pressed while in maintenance mode, the total power ON time of Unit 3 (set in advance) is read. If the total power ON time exceeds 5 years, a lamp is lit to indicate that the Unit replacement is necessary. If the button for completion of Unit replacement is pressed after replacing the Unit, the Unit replacement warning lamp turns OFF.

The following system configuration is used.

Unit Unit 1 Unit 2 Unit 3

Description NX Unit (ID) NX Unit (OD) NX Unit (Unit from which to read the total power ON time)

Definitions of Variables

LD
Internal Variables

Variable
Maintenance_Mode Run_Mode PushButton_Read PushButton_Changed Lamp_Warning_UnitLifeTime Read

instance

Data type
BOOL BOOL BOOL BOOL BOOL BOOL NX_ReadTotalPowerOnTime

Initial value FALSE FALSE FALSE FALSE FALSE FALSE

Comment
Maintenance mode Run mode Reading the total power ON time Completion of Unit replacement Unit replacement warning

2-890

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

NX_ReadTotalPowerOnTime

2 Instruction Descriptions

External Variables

Variable
NX_Unit J01_Ch1_In00

J01_Ch1_In01

J01_Ch1_In02 J02_Ch1_Out00

Data type _sNXUNIT_ID BOOL BOOL
BOOL BOOL

Get button status. J01_Ch1_In00
Maintenance mode button J01_Ch1_In00
Maintenance mode button J01_Ch1_In01
Button to read total power ON time J01_Ch1_In02
Button for completion of Unit replacement Read total power ON time. Maintenance_Mode PushButton_Read instance.Done instance.Error

Read

Comment
Maintenance mode button Button to read total power ON time Button for completion of Unit replacement Unit replacement warning lamp
2
Maintenance_Mode
Run_Mode
PushButton_Read
PushButton_Changed
Read

Read

NX_Unit

instance

NX_ReadTotalPowerOnTime

Execute

Done

UnitProxy

Busy

Error

ErrorID

ErrorIDEx

TotalPowerOnTime

instance.Done
instance.TotalPowerOnTime T#1825d

> EN In1 In2

Maintenance_Mode PushButton_Changed

Output warning to lamp. Lamp_Warning_UnitLifeTime

Lamp_Warning_UnitLifeTime S
Lamp_Warning_UnitLifeTime R
J02_Ch1_Out00 Unit replacement warning lamp

NJ/NX-series Instructions Reference Manual (W502)

2-891

2 Instruction Descriptions

ST

Internal Variables

Variable
Maintenance_Mode Run_Mode
PushButton_Read

PushButton_Changed

Lamp_Warning_UnitLifeTime
Read
instance
RS_instance RS_instance2 R_TRIG_instance1 R_TRIG_instance2 R_TRIG_instance3 PushButton_Read_R_TRIG instance_Done_R_TRIG PushButton_Change_R_TRIG

Data type
BOOL BOOL
BOOL
BOOL
BOOL
BOOL NX_ReadTotalPowerOnTime RS RS R_TRIG R_TRIG R_TRIG BOOL BOOL BOOL

Initial value FALSE FALSE FALSE
FALSE
FALSE FALSE

Comment
Maintenance mode Run mode Reading the total power ON time Completion of Unit replacement Unit replacement warning

External Variables

Variable
NX_Unit J01_Ch1_In00
J01_Ch1_In01

J01_Ch1_In02 J02_Ch1_Out00

Data type _sNXUNIT_ID BOOL BOOL
BOOL BOOL

Comment
Maintenance mode button Button to read total power ON time Button for completion of Unit replacement Unit replacement warning lamp

// Get button status.

Maintenance_Mode := J01_Ch1_In00;

Run_Mode

:= NOT(J01_Ch1_In00);

PushButton_Read := J01_Ch1_In01;

PushButton_Changed := J01_Ch1_In02;

R_TRIG_instance1(Clk:= PushButton_Read, Q=>PushButton_Read_R_TRIG);

// Read total power ON time. Rs_instance( Set:= (Maintenance_Mode & PushButton_Read_R_TRIG),
Reset1:=((instance.Done) OR (instance.Error)), Q1=>Read); instance(Execute:=Read, UnitProxy:=NX_Unit);

R_TRIG_instance2(Clk:= instance.Done, Q=>instance_Done_R_TRIG); R_TRIG_instance3(Clk:= PushButton_Changed, Q=>PushButton_Changed_R_TRIG);

RS_instance2(Set:=(instance_Done_R_TRIG & (instance.TotalPowerOnTime>T#1825d)), Reset1:=(Maintenance_Mode & PushButton_Changed_R_TRIG), Q1=>Lamp_Warning_UnitLifeTime);
// Output warning to lamp. J02_Ch1_Out00 := Lamp_Warning_UnitLifeTime;

2-892

NJ/NX-series Instructions Reference Manual (W502)

System Control Instructions

PLC_ReadTotalPowerOnTime

2 Instruction Descriptions

PLC_ReadTotalPowerOnTime

The PLC_ReadTotalPowerOnTime instruction reads the total power ON time from a specified CPU Unit.

Instruction

Name

FB/ FUN

Graphic expression

ST expression

PLC_ReadT otalPowerO nTime

Read PLC Total Power

FUN

PLC_ReadTotalPowerOnTime

EN UnitType

ENO

Out:=PLC_ReadTotalPowerOnTime(

Out

UnitType);

2

ON Time

Precautions for Correct Use You can use this instruction for the NX102 CPU Unit and NX1P2 CPU Unit.

Variables

Name UnitType Out

Meaning

I/O

Unit type

Input

Total Power ON Time

Output

Description

Valid range

Specifies the target Unit.

_CPU_UNIT

Outputs the total power ON time Depends on

that was read.

data type.

Unit ---

Default _CPU_ UNIT
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

UnitType Out

Refer to Function for the enumerators of the enumerated type _ePLC_UNIT_TYPE. OK

Function
The PLC_ReadTotalPowerOnTime instruction reads the approximate total power ON time from a specified CPU Unit. The accuracy is 1 hour per month.
Specify the Unit from which the data is read to UnitType.

NJ/NX-series Instructions Reference Manual (W502)

2-893

2 Instruction Descriptions

The data type of UnitType is enumerated type _ePLC_UNIT_TYPE. The meaning of the enumerator is as follows:

Enumerator _CPU_UNIT

Meaning CPU Unit is specified.

Target Unit
 When Using the NX1P2 CPU Unit
NX-series I/O Units connected to the NX bus of the CPU Unit
NX1P2 CPU Unit

Not the target Unit

Target Unit
The target Unit for reading is the NX1P2 CPU Unit only. In UnitType, set the _CPU_UNIT enumerator of the enumerated type _ePLC_UNIT_TYPE to specify a target Unit. NX-series I/O Units connected to the NX bus of the CPU Unit are not the target Unit for reading.

Additional Information
To read the total power ON time for an NX-series I/O Unit, use NX_ReadTotalPowerOnTime on page 2-885.

Additional Information
If you execute this instruction in the Simulator, the value of Out is always T#0s.
Precautions for Correct Use
If the specified Unit is not the target for reading, an error will occur. ENO will be FALSE, and the value of Out will not change.

2-894

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

System Control Instructions

PLC_ReadTotalPowerOnTime

Sample Programming
This sample creates the two variables Maintenance_Mode and Run_Mode in the program. In the two, the instruction reads the total power ON time of the NX1P2 CPU Unit when the button to read the total power ON time is pressed in Maintenance_Mode. If the total power ON time exceeds 5 years, the Unit replacement warning lamp lights. Once the Unit is replaced and the button for completion of Unit replacement is pressed, the Unit replacement warning lamp turns off.

The system configuration is as shown below.

Unit

Description

2

Unit 1

Unit 1, which is connected to the NX bus of the NX-series CPU Unit NX-series I/O Unit (ID)

Unit 2

Unit 2, which is connected to the NX bus of the NX-series CPU Unit NX-series I/O Unit (IO)

Unit 3

NX1P2 CPU Unit (Target for reading the total power ON time)

Definitions of Variables

ST

External Variables

Variable J01_Ch1_In00

J01_Ch1_In01

J02_Ch1_Out00 Maintenance_Mode Run_Mode PushButton_Read Lamp_Warning_UnitLifeTime PowerOnTime R_TRIG_instance1 PushButton_Read_R_TRIG RS_instance

Data type
BOOL
BOOL
BOOL BOOL BOOL BOOL BOOL TIME R_TRIG BOOL RS

Comment
Maintenance mode button Button to read total power ON time Unit replacement warning lamp

// Get button status.

Maintenance_Mode := J01_Ch1_In00;

Run_Mode

:= NOT(J01_Ch1_In00);

PushButton_Read := J01_Ch1_In01;

R_TRIG_instance1(clk:=PushButton_Read, Q=>PushButton_Read_R_TRIG);

// Read total operating time. PowerOnTime := PLC_ReadTotalPowerOnTime(EN:=(Maintenance_Mode &
PushButton_Read_R_TRIG), UnitType:=_CPU_UNIT);

RS_instance( Set:=(PowerOnTime > T#1825d), Reset1:=Maintenance_Mode, Q1=>Lamp_Warning_UnitLifeTime);

NJ/NX-series Instructions Reference Manual (W502)

2-895

2 Instruction Descriptions
// Output warning to lamp. J02_Ch1_Out00 := Lamp_Warning_UnitLifeTime;

2-896

NJ/NX-series Instructions Reference Manual (W502)

Program Control Instructions

2
Program Control Instructions

Instruction PrgStart PrgStop PrgStatus

Name Enable Program Disable Program Read Program Status

Page 2-898 2-907 2-927

NJ/NX-series Instructions Reference Manual (W502)

2-897

2 Instruction Descriptions

PrgStart

The PrgStart instruction enables the execution of the specified program.

Instruction

Name

FB/FUN

Graphic expression

ST expression

PrgStart

Enable Program

FUN

(@)PrgStart

EN

Out

PrgName

isFirstRun

Out:=PrgStart(PrgName, isFirstRun);

Variables

Name PrgName
isFirstRun Out

Meaning

I/O

Program name
Input
First Program Period Flag enable

Normal end flag

Output

Description
Name of specified program
Operation of the P_First_Run system-defined variable in the first task period when the program is executed TRUE: Change to TRUE. FALSE: Change to FALSE. Normal end flag TRUE: Normal end FALSE: Error end

Valid range

Unit

128 bytes max. (127 single-byte alphanumeric characters plus the final NULL character)
---

Depends on data type.

Depends on data type.

---

*1 If you omit an input parameter, the default value is not applied. A building error will occur.

Default *1
TRUE ---

Bit strings

Integers

Times, durations, dates, and text strings

Real numbers

Boolean BOOL

STRING

DT TOD DATE TIME

LREAL REAL

LINT DINT INT SINT ULINT UDINT UINT USINT LWORD

DWORD WORD BYTE

PrgName

OK

isFirstRun

OK

Out

OK

Function
The PrgStart instruction enables the execution of the program specified with PrgName. The specified program is executed the next time the timing for executing the program occurs. An error does not occur even if the specified program is already enabled. The specified program can be in the same task as this instruction, or it can be in a different task. The value of Out is TRUE if the instruction ends normally and FALSE if the instruction ends in an error.

2-898

NJ/NX-series Instructions Reference Manual (W502)

Program Control Instructions

2 Instruction Descriptions

Operation Example When a Program in the Current Task Is Specified

An operation example is provided below for when a program is specified that is in the same task as the task that executes the instruction.

 Enabling a Program Executed After the PrgStart Instruction

· In this example, there are three programs, P1, P2, and P3, in the same task.

· P3 is disabled from task period 1.

· The PrgStart instruction with P3 specified is executed in P2 of task period 2.

· P3 is executed after P2, so P3 is executed in task period 2.

2

· Thereafter, P3 remains enabled even if you do not execute the PrgStart instruction with P3 speci-

fied.

PrgStart

Task period 1

P1 P2

P3

Task period 2

P1 P2

P3

PrgStart('P3')

Task period 3

P1 P2

P3

Programs

P3 is executed after P2, so P3 is executed in the same task period as the one in which the PrgStart instruction is executed.

Time

 Enabling a Program Executed Before the PrgStart Instruction
· In this example, there are three programs, P1, P2, and P3, in the same task. · P1 is disabled from task period 1. · The PrgStart instruction with P1 specified is executed in P2 of task period 1. · P1 is executed before P2, so P1 is executed in task period 2. · Thereafter, P1 remains enabled even if you do not execute the PrgStart instruction with P1 speci-
fied.

Task period 1

P2

P3

PrgStart('P1')

Task period 2

P1 P2

P3

Task period 3

P1 P2

P3

P1 is executed before P2, so P1 is executed in the next task period after the one in which the PrgStart instruction is executed.

Time

NJ/NX-series Instructions Reference Manual (W502)

2-899

2 Instruction Descriptions

Operation Example When a Program in a Different Task Is Specified
An operation example is provided below for when a program is specified that is in a different task from the task that executes the instruction.
 Enabling a Program in a Task with a Lower Execution Priority Than the Current Task
· There are three programs in this example. P1 is in the primary periodic task, and P2 and P3 are in a periodic task.
· P3 is disabled from task period A of the periodic task. · The PrgStart instruction with P3 specified is executed in P1 of task period 2 of the primary peri-
odic task. · P3 is executed in task period B of the periodic task, which is executed after the PrgStart instruc-
tion is executed. · Thereafter, P3 remains enabled even if you do not execute the PrgStart instruction with P3 speci-
fied.

Primary periodic task
Periodic task (execution priority: 16)

Task period 1 Task period 2

P1

P1

PrgStart('P3')

Task period A P2P3

Task period 3 P1

Task period 4 P1

Task period 5 P1

Task period 6 P1

Task period B P2P3
P3 is executed in the task period that comes after execution of the PrgStart instruction.

Task period C P2P3

Time Time

 Enabling a Program in a Task with a Higher Execution Priority Than the Current Task

· There are three programs in this example. P1 and P2 are in the primary periodic task, and P3 is in a periodic task.
· P2 is disabled from task period 1 of the primary periodic task.
· The PrgStart instruction with P2 specified is executed in P3 of task period A of the periodic task.
· P2 is executed in task period 2 of the primary periodic task, which is executed after the PrgStart instruction is executed.
· Thereafter, P2 remains enabled even if you do not execute the PrgStart instruction with P2 specified.
· The primary periodic task has a higher execution priority than a periodic task, so P3 in task period B and later is executed after processing of P2 is completed.

Primary periodic task

Task period 1 Task period 2 Task period 3 Task period 4 Task period 5 Task period 6

P1P2

P1P2

P1P2

P1P2

P1P2

P1P2

Periodic task (execution priority: 16)

Task period A
P3 PrgStart('P2')
P2 is executed in the task period that comes after execution of the PrgStart instruction.

Task period B P3
P3 in task period B and later is executed after processing of P2 is completed.

Task period C P3

Time Time

2-900

NJ/NX-series Instructions Reference Manual (W502)

Program Control Instructions

2 Instruction Descriptions

 Enabling a Program in a Task with a Lower Execution Priority from an Event Task

· There are three programs in this example. P1 is in an event task (execution priority: 8), and P2 and P3 are in a periodic task (execution priority: 16).

· P3 is disabled from task period 1 of the periodic task.

· The PrgStart instruction with P3 specified is executed in the event task.

· When the event task is executed, P2 and P3 in task period 2 of the periodic task are executed after processing of the event task is completed.

· As a result, P3 in task period 2 of the periodic task is executed because it comes after execution of the PrgStart instruction.

· Thereafter, P3 remains enabled even if you do not execute the PrgStart instruction with P3 specified.

2

PrgStart

Event task (execution priority: 8)

P1 PrgStart('P3')
Event occurs.

Time

Periodic task (execution priority: 16)

Task period 1 P2P3

Task period 2 Task period 3 Task period 4 Task period 5 Task period 6

P2P3 P2P3

P2P3

P2P3

P2P3

P2 is executed in task period 2 after processing of the event task is completed.
P3 is executed in the task period that comes after execution of the PrgStart instruction.

Time

 Enabling a Program in a Task with a Higher Execution Priority from an Event Task
· There are three programs in this example. P1 and P2 are in the primary periodic task, and P3 is in an event task.
· P2 is disabled from task period 1 of the primary periodic task. · The PrgStart instruction with P2 specified is executed in the event task. · P2 is executed in task period 2 of the primary periodic task, which is executed after the PrgStart
instruction is executed. · Thereafter, P2 remains enabled even if you do not execute the PrgStart instruction with P2 speci-
fied.

Primary periodic task

Task period 1 Task period 2 Task period 3 Task period 4 Task period 5 Task period 6

P1P2

P1P2

P1P2

P1P2

P1P2

P1P2

Event task (execution priority: 8)

P3 PrgStart('P2')
Event occurs. P2 is executed in the task period that comes after execution of the PrgStart instruction.

Time Time

NJ/NX-series Instructions Reference Manual (W502)

2-901

2 Instruction Descriptions

 Enabling a Program in an Event Task with a Lower Execution Priority from a Periodic Task
· There are three programs in this example. P1 is in a periodic task (execution priority: 16), and P2 and P3 are in an event task (execution priority: 48).
· P3 in the event task is disabled. · The PrgStart instruction with P3 specified is executed in the periodic task. · P3 is executed in the event task that is executed after the PrgStart instruction is executed. · Thereafter, P3 remains enabled even if you do not execute the PrgStart instruction with P3 speci-
fied.

Periodic task (execution priority: 16)

Task period 1 P1

Task period 2
P1 PrgStart('P3')

Task period 3 P1

Time

Event task (execution priority: 48)

P2P3

P2P3

P2P3

Event occurs.

Event occurs.

Event occurs.

P2P3 Event occurs.

Time

P3 is executed in the event task that comes after execution of the PrgStart instruction.

 Enabling a Program in an Event Task with a Higher Execution Priority from a Periodic Task

· There are three programs in this example. P1 and P2 are in an event task (execution priority: 8), and P2 is in a periodic task (execution priority: 16).
· P2 in the event task is disabled. · The PrgStart instruction with P2 specified is executed in the periodic task. · P2 is executed in the event task that is executed after the PrgStart instruction is executed. · Thereafter, P2 remains enabled even if you do not execute the PrgStart instruction with P2 speci-
fied.

Event task (execution priority: 8)

P1P2

P1P2

Event occurs.

Event occurs.

P1P2

P1P2

Event occurs.

Event occurs.

Time

Periodic task (execution priority: 16)

Task period 1 P3

Task period 2

Task period 3

P3

P3

P3

PrgStart('P2')

P2 is executed in the event task that comes after execution of the PrgStart instruction.

Time

2-902

NJ/NX-series Instructions Reference Manual (W502)

Program Control Instructions

2 Instruction Descriptions

 Enabling a Program in an Event Task with a Lower Execution Priority from an Event Task
· There are three programs in this example. P1 is in an event task (execution priority: 8), and P2 and P3 are in an event task (execution priority: 48).
· P3 in the event task (execution priority: 48) is disabled. · The PrgStart instruction with P3 specified is executed in the event task (execution priority: 8). · P3 is executed in the event task (execution priority: 48) that is executed after the PrgStart instruc-
tion is executed. · Thereafter, P3 remains enabled even if you do not execute the PrgStart instruction with P3 speci-
fied.

Event task (execution priority: 8)

P1 Event occurs.

P1 PrgStart('P3')
Event occurs.

2
Time

PrgStart

Event task (execution priority: 48)

P2P3 Event occurs.

P2P3

P2P3

Event occurs.

Event occurs.

P3 is executed in the event task that comes after execution of the PrgStart instruction.

Time

 Enabling a Program in an Event Task with a Higher Execution Priority from an Event Task

· There are three programs in this example. P1 and P2 are in an event task (execution priority: 8), and P3 is in an event task (execution priority: 48).
· P2 in the event task (execution priority: 8) is disabled.
· The PrgStart instruction with P2 specified is executed in the event task (execution priority: 48).
· P2 is executed in the event task (execution priority: 8) that is executed after the PrgStart instruction is executed.
· Thereafter, P2 remains enabled even if you do not execute the PrgStart instruction with P2 specified.

Event task (execution priority: 8)
Event task (execution priority: 48)

P1P2 Event occurs.
P3 Event occurs.

P1P2

P1P2

P1P2

Event occurs.

Event occurs.

Event occurs.

P3

P3

PrgStart('P2')

Event occurs. P2 is executed in the event task that comes after execution of the PrgStart instruction.

Time Time

First Program Period Flag Enable (isFirstRun)
isFirstRun determines whether the P_First_Run system-defined variable is enabled as shown in the following table. If the value of isFirstRun is TRUE when the instruction is executed, the value of P_First_Run is TRUE for one task period when program execution starts. If the value of isFirstRun is FALSE when the instruction is executed, the value of P_First_Run remains FALSE even when program execution starts.
Use isFirstRun to perform specific processing only if specific conditions are met when program execution starts. When the specific conditions are met, change the value of isFirstRun to TRUE before you execute the instruction. With this program, an algorithm is used to perform specific processing when the value of P_First_Run is TRUE.

NJ/NX-series Instructions Reference Manual (W502)

2-903

2 Instruction Descriptions

The relation between isFirstRun and P_First_Run is shown in the following table. The behavior of P_First_Run depends on whether the specified program is disabled or already enabled.

Value of isFirstRun Status of the program

Value of P_First_Run

TRUE

Disabled.

Changes to TRUE for one task period when the program is executed. Changes to FALSE in the following task period.

Already enabled.

Remains FALSE.

FALSE

---

Remains FALSE.

The following figures show examples of the relation between isFirstRun and P_First_Run.

 When the Value of isFirstRun Is TRUE and the Program Is Disabled
The value of P_First_Run changes to TRUE for one task period when execution of the program starts. Then, the value of P_First_Run changes to FALSE.

P2.P_First_Run TRUE FALSE

Task period 1 P1 P2

Task period 2
P1 P2 PrgStart('P2')

Task period 3 P1 P2

Time

Changes to TRUE for the task period in which P2 execution starts.
 When the Value of isFirstRun Is TRUE and the Program Is Already Enabled
The value of P_First_Run remains FALSE even if the PrgStart instruction is executed.

P2 is already enabled before execution of the PrgStart instruction.

P2.P_First_Run

TRUE FALSE

Task period 1 P1 P2

Task period 2
P1 P2 PrgStart('P2')

Task period 3 P1 P2

Time

Remains FALSE.

 When the Value of isFirstRun Is FALSE

The value of P_First_Run remains FALSE even when execution of the program starts.

P2.P_First_Run

TRUE FALSE

Task period 1 P1 P2

Task period 2
P1 P2 PrgStart('P2')

Task period 3 P1 P2

Remains FALSE even if P2 execution starts.

Time

Notation Example

The following example shows the notation for specifying enabling program P1.

LD

ST

abc:=PrgStart('P1', TRUE);

PrgStart

abc

'P1' TRUE

EN PrgName isFirstRun

2-904

NJ/NX-series Instructions Reference Manual (W502)

Program Control Instructions

2 Instruction Descriptions

Related System-defined Variables

Name P_First_Run P_First_RunMode

Meaning

Data type

Description

This flag is TRUE for one task period after execution

of the program starts. Otherwise it is FALSE.

However, if the value of isFirstRun is changed to

First Program Period Flag

BOOL

FALSE and the PrgStart instruction is executed, P_First_Run remains FALSE even through execu-

tion of the program starts.

Use this flag to perform specific processing when

execution of a program starts.

2

PrgStart

First RUN Period Flag BOOL

This flag is TRUE for only one task period after the operating mode of the CPU Unit is changed from PROGRAM mode to RUN mode if execution of the program is in progress. This flag remains FALSE if execution of the program is not in progress. Use this flag to perform initialization when the CPU Unit begins operation.

Additional Information
· Use the PrgStop instruction (page 2-907) to disable a specified program from the user program. · Use the PrgStatus instruction (page 2-927) to read the status of a specified program from the user
program.

NJ/NX-series Instructions Reference Manual (W502)

2-905

2 Instruction Descriptions
Precautions for Correct Use
· An error will not occur even if you specify a program that is already in an enabled state and execute this instruction.
· If you execute this instruction more than once for the same program, the isFirstRun specification in the instruction instance that was executed first is used.
· If the PrgStop instruction is executed after executing the PrgStart instruction for the same program and it is executed before the program is actually executed, the program is not executed.
· If the PrgStart instruction is executed after executing the PrgStop instruction for the same program and it is executed before the execution timing for the program, the program is not disabled.
· The operation of the programs immediately after the operating mode of the CPU Unit changes to RUN mode is controlled by the setting of the Initial Status for each program on the Sysmac Studio. In other words, the results of executing the PrgStart or PrgStop instruction before changing to RUN mode are not valid.
· If this instruction is executed for a program in a different task, the execution timing of the specified program will depend on the task execution priority of both tasks. In some cases, the Controller may perform unexpected operation. You can execute this instruction in the first program in the task to which the specified program is assigned to make sure that the specified program is executed in the same task period as the instruction.
· The values of the internal variables, input variables, output variables, and in-out variables from the previous time that the specified program was executed are retained. To initialize these variables before you execute the program, change the value of isFirstRun to TRUE before you execute the instruction and then perform initialization processing in the specified program when the value of P_First_Run is TRUE.
· An error will occur in the following case. Out will be FALSE. · The program specified by PrgName does not exist.
Version Information A CPU Unit with unit version 1.08 or later and Sysmac Studio version 1.09 or higher are required to use this instruction.
Sample Programming
Refer to the sample programming for the PrgStop instruction (page 2-907).

2-906

NJ/NX-series Instructions Reference Manual (W502)

Program Control Instructions

2 Instruction Descriptions

PrgStop

The PrgStop instruction disables execution of the specified program.

Instruction

Name

FB/FUN

Graphic expression

ST expression

PrgStop

Disable Program

FUN

(@)PrgStop

EN

Out

PrgName

Out:=PrgStop(PrgName);

2

PrgStop

Variables

Name

Meaning

I/O

Description

PrgName

Program name

Input

Name of specified program

Out

Normal end flag

Output

Normal end flag TRUE: Normal end FALSE: Error end

Valid range

Unit

128 bytes max.

(127 single-byte

alphanumeric characters plus

---

the final NULL

character)

Depends on data type.

---

*1 If you omit an input parameter, the default value is not applied. A building error will occur.

Default *1 ---

Bit strings

Integers

Times, durations, dates, and text strings

Real numbers

Boolean BOOL

STRING

DT TOD DATE TIME

LREAL REAL

LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE

PrgName

OK

Out

OK

Function
The PrgStop instruction disables execution of the program specified with PrgName. The specified program is disabled from the next time the timing for executing the program occurs. An error does not occur even if the specified program is already disabled. The specified program can be in the same task as this instruction, or it can be in a different task. You can specify the program that contains this instruction. If you specify the program that contains the instruction, the program is executed to the end in the task period in which the instruction is executed and then the program is disabled from the next task period. The value of Out is TRUE if the instruction ends normally and FALSE if the instruction ends in an error.

NJ/NX-series Instructions Reference Manual (W502)

2-907

2 Instruction Descriptions

Operation Example When a Program in the Current Task Is Specified
An operation example is provided below for when a program is specified that is in the same task as the task that executes the instruction.

 Disabling a Program Executed After the PrgStop Instruction
· In this example, there are three programs, P1, P2, and P3, in the same task. · P3 is executed in task period 1. · The PrgStop instruction with P3 specified is executed in P2 of task period 2. · P3 is executed after P2, so P3 is disabled from task period 2. · Thereafter, P3 remains disabled even if you do not execute the PrgStop instruction with P3 speci-
fied.

Task period 1

P1 P2

P3

Task period 2

P1 P2

P3

PrgStop('P3')

Task period 3

P1 P2

P3

Programs

P3 is executed after P2, so P3 is disabled from the same task period as the one in which the PrgStop instruction is executed.

Time

 Disabling a Program Executed Before the PrgStop Instruction
· In this example, there are three programs, P1, P2, and P3, in the same task. · P1 is executed in task period 1. · The PrgStop instruction with P2 specified is executed in P2 of task period 1. · P1 is executed before P2, so P1 is disabled from task period 2. · Thereafter, P1 remains disabled even if you do not execute the PrgStop instruction with P1 speci-
fied.

Task period 1

P1 P2

P3

PrgStop('P1')

Task period 2

P2

P3

Task period 3

P2

P3

P1 is executed before P2, so P1 is disabled from the next task period after the one in which the PrgStop instruction is executed.

Time

 Disabling the Program That Includes the PrgStop Instruction
· In this example, there are two programs, P1 and P2, in the same task. · P2 is executed in task period 1. · The PrgStop instruction with P2 specified is executed in P2 of task period 1. · P2 is executed to the end of the program in task period 1. · P2 is disabled from task period 2. · Thereafter, P2 remains disabled even if you do not execute the PrgStop instruction with P2 speci-
fied.

Task period 1
P1 P2 PrgStop('P2')

Task period 2 P1 P2

Task period 3 P1 P2

The program is executed to the end in the task period in which the PrgStop instruction is executed.

The program is disabled from the next task period after the one in which the PrgStop instruction is executed.

Time

2-908

NJ/NX-series Instructions Reference Manual (W502)

Program Control Instructions

2 Instruction Descriptions

Operation Example When a Program in a Different Task Is Specified

An operation example is provided below for when a program is specified that is in a different task from the task that executes the instruction.

 Disabling a Program in a Task with a Lower Execution Priority Than the Current Task
· There are three programs in this example. P1 is in the primary periodic task, and P2 and P3 are in a periodic task.
· P3 is executed in task period A of the periodic task.
· The PrgStop instruction with P3 specified is executed in P1 of task period 2 of the primary periodic 2
task.
· P3 is disabled from task period B of the periodic task, which is executed after the PrgStop instruction is executed.
· Thereafter, P3 remains disabled even if you do not execute the PrgStop instruction with P3 specified.

PrgStop

Primary periodic task
Periodic task (execution priority: 16)

Task period 1 Task period 2

P1

P1

PrgStop('P3')

Task period A P2P3

Task period 3 P1

Task period 4 P1

Task period 5 P1

Task period 6 P1

Task period B P2P3

Task period C P2P3

P3 is disabled from the task period that comes after execution of the PrgStop instruction.

Time Time

 Disabling a Program in a Task with a Higher Execution Priority Than the Current Task

· There are three programs in this example. P1 and P2 are in the primary periodic task, and P3 is in a periodic task.
· P2 is executed in task period 1 of the primary periodic task.
· The PrgStop instruction with P2 specified is executed in P3 of task period A of the periodic task.
· P2 is disabled from task period 2 of the primary periodic task, which is executed after the PrgStop instruction is executed.
· Thereafter, P2 remains disabled even if you do not execute the PrgStop instruction with P2 specified.

Primary periodic task

Task period 1 Task period 2 Task period 3 Task period 4 Task period 5 Task period 6

P1P2

P1P2

P1P2

P1P2

P1P2

P1P2

Periodic task (execution priority: 16)

Task period A
P3 PrgStop('P2')

Task period B P3

P2 is disabled from the task period that comes after execution of the PrgStop instruction.

Task period C P3

Time Time

NJ/NX-series Instructions Reference Manual (W502)

2-909

2 Instruction Descriptions

 Disabling a Program in a Task with a Lower Execution Priority from an Event Task

· There are three programs in this example. P1 is in an event task (execution priority: 8), and P2 and P3 are in a periodic task (execution priority: 16).
· P3 is executed in task period 1 of the periodic task.
· The PrgStop instruction with P3 specified is executed in the event task.
· When the event task is executed, P2 and P3 in task period 2 of the periodic task are executed after processing of the event task is completed.
· As a result, P3 in task period 2 of the periodic task is disabled because it comes after execution of the PrgStop instruction.
· Thereafter, P3 remains disabled even if you do not execute the PrgStop instruction with P3 specified.

Event task (execution priority: 8)

P1 PrgStop('P3')
Event occurs.

Time

Periodic task (execution priority: 16)

Task period 1 P2P3

Task period 2 Task period 3 Task period 4 Task period 5 Task period 6

P2P3 P2P3

P2P3

P2P3

P2P3

P2 is executed in task period 2 after processing of the event task is completed.

Time

P3 is disabled from the task period that comes after execution of the PrgStop instruction.

 Disabling a Program in a Task with a Higher Execution Priority from an Event Task

· There are three programs in this example. P1 and P2 are in the primary periodic task, and P3 is in an event task.
· P2 is executed in task period 1 of the primary periodic task.
· The PrgStop instruction with P2 specified is executed in the event task.
· P2 is disabled from task period 2 of the primary periodic task, which is executed after the PrgStop instruction is executed.
· Thereafter, P2 remains disabled even if you do not execute the PrgStop instruction with P2 specified.

Primary periodic task

Task period 1 Task period 2 Task period 3 Task period 4 Task period 5 Task period 6

P1P2

P1P2

P1P2

P1P2

P1P2

P1P2

Event task (execution priority: 8)

P3 PrgStop('P2')

Event occurs.

P2 is disabled from the task period that comes after

execution of the PrgStop

instruction.

P3 Event occurs.

Time Time

2-910

NJ/NX-series Instructions Reference Manual (W502)

Program Control Instructions

2 Instruction Descriptions

 Disabling a Program in an Event Task with a Lower Execution Priority from a Periodic Task

· There are three programs in this example. P1 is in a periodic task (execution priority: 16), and P2 and P3 are in an event task (execution priority: 48).
· P3 is executed in the event task.
· The PrgStop instruction with P3 specified is executed in the periodic task.
· P3 in the event task is disabled from the event task that is executed after the PrgStop instruction is executed.
· Thereafter, P3 remains disabled even if you do not execute the PrgStop instruction with P3 specified.

Periodic task (execution priority: 16)

Task period 1 P1

Task period 2
P1 PrgStop('P3')

Task period 3 P1

2
Time

PrgStop

Event task (execution priority: 48)

P2P3

P2P3

P2P3

P2P3

Event occurs.

Event occurs.

Event occurs.Event occurs.

Time

P3 is disabled from the event task that comes after execution of the PrgStop instruction.

 Disabling a Program in an Event Task with a Higher Execution Priority from a Periodic Task

· There are three programs in this example. P1 and P2 are in an event task (execution priority: 8), and P2 is in a periodic task (execution priority: 16).
· P2 is executed in the event task.
· The PrgStop instruction with P2 specified is executed in the periodic task.
· P2 in the event task is disabled from the event task that is executed after the PrgStop instruction is executed.
· Thereafter, P2 remains disabled even if you do not execute the PrgStop instruction with P2 specified.

Event task (execution priority: 8)

P1P2

P1P2

Event occurs. Event occurs.

P1P2 Event occurs.

P1P2 Event occurs.

Time

Periodic task (execution priority: 16)

Task period 1 P3

Task period 2

Task period 3

P3

P3

P3

PrgStop('P2')

P2 is disabled from the event task that comes after execution of the PrgStop instruction.

Time

NJ/NX-series Instructions Reference Manual (W502)

2-911

2 Instruction Descriptions

 Disabling a Program in an Event Task with a Lower Execution Priority from an Event Task
· There are three programs in this example. P1 is in an event task (execution priority: 8), and P2 and P3 are in an event task (execution priority: 48).
· P3 in the event task (execution priority: 48) is executed. · The PrgStop instruction with P3 specified is executed in the event task (execution priority: 8). · P3 in the event task (execution priority: 48) is disabled from the event task (execution priority: 48)
that is executed after the PrgStop instruction is executed. · Thereafter, P3 remains disabled even if you do not execute the PrgStop instruction with P3 speci-
fied.

Event task (execution priority: 8)

P1 Event occurs.

P1 PrgStop('P3')
Event occurs.

Time

Event task (execution priority: 48)

P2 Event occurs.

P3

P2P3

P2P3

Event occurs.

Event occurs.

P3 is disabled from the event task that comes after execution of the PrgStop instruction.

Time

 Disabling a Program in an Event Task with a Higher Execution Priority from an Event Task

· There are three programs in this example. P1 and P2 are in an event task (execution priority: 8), and P3 is in an event task (execution priority: 48).
· P2 in the event task (execution priority: 8) is executed.
· The PrgStop instruction with P2 specified is executed in the event task (execution priority: 48).
· P2 in the event task (execution priority: 8) is disabled from the event task (execution priority: 8) that is executed after the PrgStop instruction is executed.
· Thereafter, P2 remains disabled even if you do not execute the PrgStop instruction with P2 specified.

Event task (execution priority: 8)
Event task (execution priority: 48)

P1P2 Event occurs.
P3 Event occurs.

P1P2

P1P2

P1P2

Event occurs.

Event occurs.

Event occurs.

P3 Event occurs.

P3 PrgStop('P2')
P2 is disabled from the event task that comes after execution of the PrgStop instruction.

Time Time

Notation Example

The following example shows the notation for specifying disabling program P1.

LD

ST

abc:=PrgStop('P1');

PrgStop

abc

EN 'P1' PrgName

2-912

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Program Control Instructions

Additional Information
· Use the PrgStart instruction (page 2-898) to enable a specified program from the user program. · Use the PrgStatus instruction (page 2-927) to read the status of a specified program from the user
program.

Precautions for Correct Use

· An error will not occur even if you specify a program that is already in a disabled state and execute

this instruction.

2

· If the PrgStop instruction is executed after executing the PrgStart instruction for the same program

and it is executed before the program is actually executed, the program is not executed.

PrgStop

· If the PrgStart instruction is executed after executing the PrgStop instruction for the same program and it is executed before the execution timing for the program, the program is not disabled.

· Processing for instructions that have an Execute input variable is continued until it is completed even if the execution time exceeds the task period. Before you disable programs that have such instructions, check the values of the Busy output variables from the instructions first to make sure that they are FALSE (i.e., to make sure that instruction execution is not in progress).

· The execution of the NX_DOutTimeStamp or NX_AryDOutTimeStamp instruction sometimes requires more than one task. Before you disable programs that have these instructions, check the values of the Enable input variables to the instructions first to make sure that they are FALSE.

· The operation of the programs immediately after the operating mode of the CPU Unit changes to RUN mode is controlled by the setting of the Initial Status for each program on the Sysmac Studio. In other words, the results of executing the PrgStart or PrgStop instruction before changing to RUN mode are not valid.

· If this instruction is executed for a program in a different task, the timing of disabling the specified program will depend on the task execution priority of both tasks. In some cases, the Controller may perform unexpected operation. You can execute this instruction in the first program in the task to which the specified program is assigned to make sure that the specified program is disabled in the same task period as the instruction.

· Confirm the following for the specified program before you execute this instruction.

· The execution of a motion control instruction is not still in progress.

· Processing for instructions that have an Execute input variable, i.e., instructions for which execution is continued until processing is completed even if the execution time exceeds the task period, is not still in progress.

· There are no time stamp instructions that are still waiting for the specified time.

· Program outputs are not reset when the specified program is disabled. The values from before the execution is disabled are retained. If you need to reset the outputs when the program is disabled, use master control within the specified program to reset them in advance.

· Even if you disable a program with this instruction, processing for any function block instruction with an Execute input variable in the program is continued to the end.

· Even if you disable a program with this instruction, processing for any motion control instructions in the program is continued to the end.

· An error will occur in the following case. Out will be FALSE.

· The program specified by PrgName does not exist.

Version Information
A CPU Unit with unit version 1.08 or later and Sysmac Studio version 1.09 or higher are required to use this instruction.

NJ/NX-series Instructions Reference Manual (W502)

2-913

2 Instruction Descriptions

Sample Programming

 Example in Which One of Three Programs Is Executed in Each Consecutive Task Period
In this example, there are three programs, P1, P2, and P3. One of each of these programs is executed in each consecutive task period and then they are repeated. Instructions are executed in the P_Main program to enable and disable these three programs.

Task period 1 Task period 2 Task period 3 Task period 4

P_Main P1

P_Main P2

P_Main P3

P_Main P1

Time

2-914

NJ/NX-series Instructions Reference Manual (W502)

Program Control Instructions

2 Instruction Descriptions

LD Variable
iStep

Data type

DINT

0

Default

Comment Number of program to execute

Set iStep variable to 0 at start of operation.

P_First_RunMode

MOVE

EN 0 In

ENO Out iStep

Increment iStep variable.

Inc

EN ENO

2

InOut

iStep

iStep

PrgStop

Execute PrgStop and PrgStart instructions.

iStep 1

=
EN In1 In2

@PrgStop
EN 'P3' PrgName

'P1' TRUE

@PrgStart
EN PrgName isFirstRun

iStep 2

=
EN In1 In2

@PrgStop
EN 'P1' PrgName

'P2' TRUE

@PrgStart
EN PrgName isFirstRun

iStep 3

=
EN In1 In2

@PrgStop
EN 'P2' PrgName

'P3' TRUE

@PrgStart
EN PrgName isFirstRun

@MOVE

EN 0 In

ENO Out iStep

NJ/NX-series Instructions Reference Manual (W502)

2-915

2 Instruction Descriptions

ST Variable
iStep

Data type

DINT

0

Default

Comment Number of program to execute

// Set iStep variable to 0 at start of operation. IF P_First_RunMode THEN
iStep:=0; END_IF;
// Increment iStep variable. iStep:=iStep+1;
// Execute PrgStop and PrgStart instructions. IF iStep = 1 THEN
PrgStop('P3'); PrgStart('P1',TRUE); ELSIF iStep = 2 THEN PrgStop('P1'); PrgStart('P2',FALSE); ELSIF iStep = 3 THEN PrgStop('P2'); PrgStart('P3',TRUE); iStep:=0; END_IF;

2-916

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Program Control Instructions

 Example of Executing Only the Specified Program or Programs the Next Time Operation Starts
In this example, the program or programs to execute the next time operation starts are specified before the power supply to the Controller is turned OFF. When the power supply is next turned ON, only the specified program or programs are executed.

Programs, Modules, and Module Configuration

There are eight programs from Program 1 to Program 8. Each program belongs to one of five modules from Module A to Module E.

Module

Programs in module

2

Module A Program 1

PrgStop

Module B Program 2

Module C Program 3 and Program 4

Module D Program 5, Program 6, and Program 7

Module E Program 8

The programs to execute are specified by specifying a module. A combination of modules to execute is called a module configuration.
For example, if a module configuration to execute Module A and Module C was specified, Program 1, Program 3, and Program 4 would be executed.

Specifying Module Configurations to Execute
The module configurations are given with text data in a configuration file. The file name of the configuration file is Config.txt, and it is stored in the root directory of an SD Memory Card. The configuration file can contain more than one module configuration. Before the power supply is turned OFF, a touch panel is used to specify the module configuration to execute next from the contents of the configuration file.

Format of Configuration File
The format of the configuration file is given in the following table.

Row Row 1
Row 2 and higher

Contents Number of module configurations
Module configuration number, Module A execution flag,*1 Module B execution flag, Module C execution flag, Module D execution flag, Module E execution flag

*1 The module is executed if the flag is TRUE and not executed if the flag is FALSE.

An example of the contents of a configuration file is given below.
3 Config1, TRUE, TRUE, TRUE, FALSE, FALSE Config2, TRUE, TRUE, FALSE, TRUE, FALSE Config3, TRUE, TRUE, TRUE, FALSE, TRUE
This configuration file contains three configurations, Config1, Config2, and Config3. Of these, the Config1 module configuration says to execute Module A, Module B, and Module C and to not execute Module D and Module E.

NJ/NX-series Instructions Reference Manual (W502)

2-917

2 Instruction Descriptions

Data Type Definitions
A structure called myConfig is defined as shown in the following table.

Structure

Variable
 myConfig configName moduleA moduleB moduleC moduleD moduleE

Data type
STRUCT STRING[32] BOOL BOOL BOOL BOOL BOOL

Offset type NJ

Comment
Module configuration Module configuration name Module A execution flag Module B execution flag Module C execution flag Module D execution flag Module E execution flag

2-918

NJ/NX-series Instructions Reference Manual (W502)

Program Control Instructions

2 Instruction Descriptions

LD

Variable Open TopLineGetter LineGetter Close

Data type FileOpen FileGets FileGets FileClose

Default

Retain ---------

Comment Instance of FileOpen instruction Instance of FileGets instruction Instance of FileGets instruction Instance of FileClose instruction

PTInput_TargetConfigNum_Retain

USINT

0

CurrentLineNum

USINT

1

Number of the module configuration to execute next time operation starts
--- Current configuration file row

TargetLineNum ConfigNum LineMax isOverLine Busy

USINT

0

USINT

1

USINT

3

BOOL BOOL

FALSE FALSE

---

Row for CurrentConfig in configuration file

2

---

Number given in row 1 of configuration file

PrgStop

---

Number of rows in configuration file obtained from ConfigNum

Error flag when value of PTInput_Tar--- getConfigNum_Retain is larger than
value of LineMax

--- Processing flag

SubDeliNG Error opening

BOOL BOOL BOOL

FALSE FALSE FALSE

--- Read error end flag for CurrentConfig --- Error flag --- Configuration file open execution flag

myFileID TopLineGetting GetConfigNumDone

DWORD BOOL BOOL

0 FALSE FALSE

--- File ID of configuration file --- ConfigNum read execution flag --- ConfigNum read done flag

SelectDone reading

BOOL BOOL

FALSE FALSE

--- CurrentConfig read done flag

---

Configuration file row 2 or higher read execution flag

CurrentConfig Error_exceptOpen

myConfig

(configName:='', moduleA:=FALSE, moduleB:=FALSE, moduleC:=FALSE, moduleD:=FALSE)

BOOL

FALSE

---

Module configuration to execute next time operation starts

---

Configuration file close execution flag when error occurs

NJ/NX-series Instructions Reference Manual (W502)

2-919

2 Instruction Descriptions

Get number of the module configuration to execute next time operation starts.

P_First_RunMode

ADD

EN PTInput_TargetConfigNum_Retain In1
USINT#1 In2

ENO

TargetLineNum

Calculate number of rows from contents of row 1 of configuration file.

GetConfigNumDone

ConfigNum USINT#1

ADD
EN ENO In1 In2

LineMax

Detect error when number of rows in configuration file does not match number of the module configuration to execute next time operation starts.

CurrentLineNum LineMax

>
EN In1 In2

isOverLine

2-920

NJ/NX-series Instructions Reference Manual (W502)

Program Control Instructions

2 Instruction Descriptions

Manage processing flag and error flags. Open.Busy
TopLineGetter.Busy

Busy

LineGetter.Busy

Close.Busy

2

Open.Error

Error

PrgStop

TopLineGetter.Error

LineGetter.Error

isOverLine SubDeliNG TopLineGetter.Error LineGetter.Error

Close.Done

Error_exceptOpen

isOverLine SubDeliNG Error_exceptOpen

NJ/NX-series Instructions Reference Manual (W502)

2-921

2 Instruction Descriptions

Open configuration file.

P_First_RunMode

Open.Done

Open.Error

opening

opening

opening

Busy

Open FileOpen

TopLineGetter.Done

Execute Done

1

'Config.txt' FileName Busy

_RDWR_CREATE Mode

Error

ErrorID

FileID myFileID

TopLineGetting

TopLineGetter.Error 1

TopLineGetting

Read row 1 of configuration file. TopLineGetting Busy

TopLineGetter FileGets

STRING_TO_USINT

myFileID TRUE

Execute FileID TrimLF

Done Busy Error ErrorID Out EOF

EN TopLineGetter.Out In

ENO

2

GetConfigNumDone

LineGetter.Done LineGetter.Error 2

GetConfigNumDone LineGetter.Done SelectDone

Error

LineGetter.Done reading

Read row 2 or higher of configuration file. LineGetter

reading

Busy

FileGets

myFileID TRUE

Execute FileID TrimLF

Done Busy Error ErrorID Out EOF

GetConfigNumDone reading

2-922

NJ/NX-series Instructions Reference Manual (W502)

Program Control Instructions

2 Instruction Descriptions

LineGetter.Done
CurrentLineNum TargetLineNum

=
EN In1 In2

LineGetter.Out CurrentConfig
_COMMA

SubDelimiter

EN

ENO

In

OutStruct

Delimiter

SelectDone

CurrentConfig

SelectDone S
SubDeliNG

SelectDone

Inc

EN ENO

InOut

CurrentLineNum

CurrentLineNum

2

PrgStop

Close configuration file. SelectDone
Error_exceptOpen

Busy myFileID

Close

FileClose

Execute FileID

Done Busy Error ErrorID

Execute PrgStart instruction. SelectDone CurrentConfig.moduleA
'Program1' TRUE
CurrentConfig.moduleB
'Program2' TRUE
CurrentConfig.moduleC
'Program3' TRUE
'Program4' TRUE
CurrentConfig.moduleD
'Program5' TRUE
'Program6' TRUE
'Program7' TRUE
CurrentConfig.moduleE
'Program8' TRUE

PrgStart EN PrgName isFirstRun
PrgStart EN PrgName isFirstRun
PrgStart EN PrgName isFirstRun
PrgStart EN PrgName isFirstRun
PrgStart EN PrgName isFirstRun
PrgStart EN PrgName isFirstRun
PrgStart EN PrgName isFirstRun
PrgStart EN PrgName isFirstRun

NJ/NX-series Instructions Reference Manual (W502)

2-923

2 Instruction Descriptions

ST
Variable Open TopLineGetter LineGetter Close PTInput_TargetConfigNum_Retain CurrentLineNum

Data type FileOpen FileGets FileGets FileClose

USINT

0

USINT

1

TargetLineNum

USINT

0

ConfigNum

USINT

1

LineMax

USINT

3

Default

isOverLine

BOOL

FALSE

Busy SubDeliNG Error opening myFileID TopLineGetting GetConfigNumDone SelectDone

BOOL BOOL BOOL BOOL DWORD BOOL BOOL BOOL

FALSE FALSE FALSE FALSE 0 FALSE FALSE FALSE

reading

BOOL

FALSE

CurrentConfig

myConfig

(configName:='', moduleA:=FALSE, moduleB:=FALSE, moduleC:=FALSE, moduleD:=FALSE)

Error_exceptOpen

BOOL

FALSE

R_GetConfigNumDone RS_1 RS_2 SecondCycle RS_3

R_TRIG RS RS F_TRIG RS

ConvertDone

BOOL

FALSE

RS_4 F_LineGetterDone R_LineGetterDone

RS F_TRIG R_TRIG

isTargetLine

BOOL

FALSE

SubDeliCondition

BOOL

FALSE

Retain ---------
-----
---
---
---
-------------------

Comment Instance of FileOpen instruction Instance of FileGets instruction Instance of FileGets instruction Instance of FileClose instruction Number of the module configuration to execute next time operation starts Current configuration file row Row for CurrentConfig in configuration file Number given in row 1 of configuration file Number of rows in configuration file obtained from ConfigNum Error flag when value of PTInput_TargetConfigNum_Retain is larger than value of LineMax Processing flag Read error end flag for CurrentConfig Error flag Configuration file open execution flag File ID of configuration file ConfigNum read execution flag ConfigNum read done flag CurrentConfig read done flag Configuration file row 2 or higher read execution flag

---

Module configuration to execute next time operation starts

---

Configuration file close execution flag when error occurs

--- Instance of R_TRIG instruction

--- Instance of RS instruction

--- Instance of RS instruction

--- Instance of F_TRIG instruction

--- Instance of RS instruction

Conversion done flag for converting --- character in row 1 of configuration file
to a number.

--- Instance of RS instruction

--- Instance of F_TRIG instruction

--- Instance of R_TRIG instruction

Flag to indicate that current row is the --- row of the module configuration to
execute next time operation starts

---

Expansion execution flag from module configuration to CurrentConfig.

2-924

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Program Control Instructions

Variable RS_5 SubDeliDone R_SelectDone

Data type RS

Default

BOOL

FALSE

R_TRIG

Retain -------

Comment Instance of RS instruction Expansion done flag from module configuration to CurrentConfig. Instance of R_TRIG instruction

// Get number of the module configuration to execute next time operation starts. IF P_First_RunMode THEN
TargetLineNum := PTInput_TargetConfigNum_Retain + USINT#1; END_IF;

// Calculate number of rows from contents of row 1 of configuration file. R_GetConfigNumDone(Clk:=GetConfigNumDone);

2

IF R_GetConfigNumDone.Q THEN

LineMax := ConfigNum + USINT#1;

END_IF;

PrgStop

// Detect error when number of rows in configuration file does not match number // of the module configuration to execute next time operation starts. isOverLine := (CurrentLineNum > LineMax);

// Manage processing flag and error flags. Busy := Open.Busy OR TopLineGetter.Busy OR LineGetter.Busy OR Close.Busy;

Error := Open.Error OR TopLineGetter.Error OR LineGetter.Error OR isOverLine OR SubDeliNG;

RS_1(Set:= (TopLineGetter.Error OR LineGetter.Error OR isOverLine OR SubDeliNG), reset1 := Close.Done, Q1 => Error_exceptOpen);

// Open configuration file. SecondCycle(Clk:=P_First_RunMode); RS_2(Set := SecondCycle.Q, reset1:=(Open.Done OR Open.Error), Q1 => opening); Open(Execute:=(opening & NOT(Busy)), FileName :='Config.txt', FileID => myFileID); RS_3(Set := Open.Done, Reset1:=(TopLineGetter.Done OR TopLineGetter.Error), Q1=>TopLineGetting);

// Read row 1 of configuration file. TopLineGetter(Execute :=(TopLineGetting & NOT(Busy)), FileID := myFileID, TrimLF := TRUE); ConfigNum := STRING_TO_USINT(EN:= TopLineGetter.Done, IN:=TopLineGetter.Out, ENO=>ConvertDone); RS_4(Set := ConvertDone, Reset1:=(LineGetter.Done OR LineGetter.Error), Q1=>GetConfigNumDone); F_LineGetterDone(Clk:=LineGetter.Done); RS_5(Set := (GetConfigNumDone OR F_LineGetterDone.Q), Reset1:=(LineGetter.Done OR SelectDone OR Error), Q1=>reading);

// Read row 2 or higher of configuration file. LineGetter(Execute:=(reading & NOT(Busy)), FileID:=myFileID, TrimLF := TRUE); R_LineGetterDone(Clk:=LineGetter.Done); isTargetLine := (CurrentLineNum = TargetLineNum); SubDeliCondition := (R_LineGetterDone.Q & isTargetLine); SubDelimiter(EN := SubDeliCondition, In := LineGetter.Out, OutStruct := CurrentConfig, Delimiter := _COMMA, ENO => SubDeliDone); IF SubDeliDone THEN
SelectDone := TRUE; END_IF; SubDeliNG := (SubDeliCondition & NOT(SubDeliDone)); Inc(EN := (R_LineGetterDone.Q & NOT(SelectDone)), InOut:= CurrentLineNum);

NJ/NX-series Instructions Reference Manual (W502)

2-925

2 Instruction Descriptions

// Close configuration file. Close(Execute := ((SelectDone OR Error_exceptOpen) & NOT(Busy)), FileID := myFileID);

// Execute PrgStart instruction. R_SelectDone(Clk:=SelectDone); //moduleA PrgStart(EN := (R_SelectDone.Q & isFirstRun:=TRUE); //moduleB PrgStart(EN := (R_SelectDone.Q & isFirstRun:=TRUE); //moduleC PrgStart(EN := (R_SelectDone.Q & isFirstRun:=TRUE); PrgStart(EN := (R_SelectDone.Q & isFirstRun:=TRUE); //moduleD PrgStart(EN := (R_SelectDone.Q & isFirstRun:=TRUE); PrgStart(EN := (R_SelectDone.Q & isFirstRun:=TRUE); PrgStart(EN := (R_SelectDone.Q & isFirstRun:=TRUE); //moduleE PrgStart(EN := (R_SelectDone.Q & isFirstRun:=TRUE);

CurrentConfig.moduleA),
CurrentConfig.moduleB),
CurrentConfig.moduleC), CurrentConfig.moduleC),
CurrentConfig.moduleD), CurrentConfig.moduleD), CurrentConfig.moduleD),
CurrentConfig.moduleE),

PrgName
PrgName
PrgName PrgName
PrgName PrgName PrgName
PrgName

:='Program1',
:='Program2',
:='Program3', :='Program4',
:='Program5', :='Program6', :='Program7',
:='Program8',

2-926

NJ/NX-series Instructions Reference Manual (W502)

Program Control Instructions

2 Instruction Descriptions

PrgStatus

The PrgStatus instruction reads the status of the specified program.

Instruction

Name

FB/FUN

Graphic expression

ST expression

PrgStatus

Read Program Status

FUN

(@)PrgStatus

EN

ENO

PrgName

Out

Out:=PrgStatus(PrgName);

2

PrgStatus

Variables

Name

Meaning

I/O

Description

Valid range

Unit

PrgName Out

Program name

Input

Program status

Output

Name of specified program
Status of program the next time the timing for execution occurs TRUE: Enabled. FALSE: Disabled.

128 bytes max.

(127 single-byte

alphanumeric characters plus

---

the final NULL

character)

Depends on data type.

---

*1 If you omit an input parameter, the default value is not applied. A building error will occur.

Defaul t
*1
---

Bit strings

Integers

Times, durations, dates, and text strings

Real numbers

Boolean BOOL

STRING

DT TOD DATE TIME

LREAL REAL

LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE

PrgName

OK

Out

OK

Function
The PrgStatus instruction reads the status of the program specified with PrgName for the next time the timing for executing the program occurs. The value of Out is TRUE if the specified program will be enabled the next time the timing for executing it occurs. The value of Out is FALSE if the specified program will be disabled the next time the timing for executing it occurs. The following table shows the meaning of "enabled" and "disabled" for the next time the timing for executing a program occurs.

NJ/NX-series Instructions Reference Manual (W502)

2-927

2 Instruction Descriptions

Program status

Description

· The Initial Status for the relevant program is set to Run on the Enabled the next time the timing for execu- Sysmac Studio. tion occurs
· The PrgStart instruction was executed for the program.

· The Initial Status for the relevant program is set to Stop on the Disabled the next time the timing for execu- Sysmac Studio. tion occurs
· The PrgStop instruction was executed for the program.

The specified program can be in the same task as this instruction, or it can be in a different task.

Operation Example
This section provides some examples of the operation of this instruction.
 Reading the Status of a Program After the PrgStatus Instruction in the Current Task
· In this example, there are two programs, P1 and P2, in the same task. · The PrgStop instruction with P2 specified is executed in P1 of task period 1. · The PrgStatus instruction with P2 specified is then executed in P1 of task period 1. · P2 was disabled for task period 1, so the value of Out from the PrgStatus instruction is FALSE.

Task period 1

P1

P2

PrgStop('P2'); PrgStatus('P2');

Task period 2

P1

P2

Programs

P2 was already disabled for task period 1 when the PrgStatus instruction was executed, so the value of Out from the PrgStatus instruction is FALSE.

Time

 Reading the Status of a Program Before the PrgStatus Instruction in the Current Task

· In this example, there are two programs, P1 and P2, in the same task. · The PrgStart instruction with P1 specified is executed in P2 of task period 1. · The PrgStatus instruction with P1 specified is then executed in P2 of task period 1. · P1 was enabled for task period 2, so the value of Out from the PrgStatus instruction is TRUE.

Task period 1

P2

P1

PrgStart('P1'); PrgStatus('P1');

Task period 2 P2

P1 was already enabled for task period 2 when the PrgStatus instruction was executed, so the value of Out from the PrgStatus instruction is TRUE.

Time

2-928

NJ/NX-series Instructions Reference Manual (W502)

Program Control Instructions

2 Instruction Descriptions

 Reading the Status of the Program That Includes the PrgStatus Instruction
· The PrgStop instruction with P1 specified is executed in P1 of task period 1. · The PrgStatus instruction with P1 specified is then executed in P1 of task period 1. · P1 was disabled for task period 2, so the value of Out from the PrgStatus instruction is FALSE.

Task period 1

Task period 2

P1

P2 P2

PrgStop('P1'); PrgStatus('P1');

Time
P1 was already disabled for task period 2 when the PrgStatus instruction was executed, so the value of Out from the PrgStatus instruction is FALSE.
2

Notation Example

PrgStatus

The following example shows the notation for reading the status of the P1 program.

LD

ST

abc:=PrgStatus('P1');

PrgStatus

EN

ENO

'P1' PrgName

abc

Additional Information
· Use the PrgStart instruction (page 2-898) to enable a specified program from the user program. · Use the PrgStop instruction (page 2-907) to disable a specified program from the user program.
Precautions for Correct Use
· An error will occur in the following case. Out will be FALSE. · The program specified by PrgName does not exist.
Version Information A CPU Unit with unit version 1.08 or later and Sysmac Studio version 1.09 or higher are required to use this instruction.

NJ/NX-series Instructions Reference Manual (W502)

2-929

2 Instruction Descriptions

Sample Programming
In this example, there are three programs, P1, P2, and P3. Operations on a touch panel are used to change the program to execute.

Touch Panel Specifications
This example assumes that a touch panel is connected to the Controller. The touch panel has the following lamps.

Lamp name P1 executing lamp P2 executing lamp P3 executing lamp

Description Lit when P1 execution is in progress. Lit when P2 execution is in progress. Lit when P3 execution is in progress.

The touch panel also has the following buttons.

Button name
Execution program change button

Operation when button is pressed
Each time this button is pressed, the program to execute changes in order from P1 to P2 to P3, and then returns to P1.

2-930

NJ/NX-series Instructions Reference Manual (W502)

Program Control Instructions

2 Instruction Descriptions

Global Variables Variable
PTIn_Type PTOut_P1Status PTOut_P2Status PTOut_P3Status

Data type Initial value

INT

0

BOOL

FALSE

BOOL

FALSE

BOOL

FALSE

Comment Execution program change button input P1 executing lamp output P2 executing lamp output P3 executing lamp output

LD

External Variables

Variable

Data type

Comment

2

PTIn_Type

INT

Execution program change button input

PTOut_P1Status

BOOL

P1 executing lamp output

PTOut_P2Status

BOOL

P2 executing lamp output

PTOut_P3Status

BOOL

P3 executing lamp output

PrgStatus

Change program to execute.

=

EN

PTIn_Type In1

'P3'

1 In2

'P1' TRUE

@PrgStop EN PrgName
@PrgStart EN PrgName isFirstRun

PTIn_Type 2

=
EN In1 In2

@PrgStop
EN 'P1' PrgName

'P2' FALSE

@PrgStart
EN PrgName isFirstRun

PTIn_Type 3

=
EN In1 In2

@PrgStop
EN 'P2' PrgName

'P3' FALSE

@PrgStart
EN PrgName isFirstRun

Execute PrgStatus instruction.

P_On

PrgStatus

EN

ENO

'P1' PrgName

PTOut_P1Status

PrgStatus

EN 'P2' PrgName

ENO

PTOut_P2Status

PrgStatus

EN

ENO

'P3' PrgName

PTOut_P3Status

NJ/NX-series Instructions Reference Manual (W502)

2-931

2 Instruction Descriptions

ST
External Variables

Variable

PTIn_Type

PTOut_P1Status PTOut_P2Status PTOut_P3Status

Data type
INT BOOL BOOL BOOL

Comment
Execution program change button input P1 executing lamp output P2 executing lamp output P3 executing lamp output

// Change program to execute. IF PTIn_Type = 1 THEN
PrgStop('P3'); PrgStart('P1',TRUE); ELSIF PTIn_Type = 2 THEN PrgStop('P1'); PrgStart('P2',FALSE); ELSIF PTIn_Type = 3 THEN PrgStop('P2'); PrgStart('P3',FALSE); END_IF;
// Execute PrgStatus instruction. IF P_On THEN
PTOut_P1Status:=PrgStatus('P1'); PTOut_P2Status:=PrgStatus('P2'); PTOut_P3Status:=PrgStatus('P3'); END_IF;

2-932

NJ/NX-series Instructions Reference Manual (W502)

EtherCAT Communications Instructions

2
EtherCAT Communications Instructions

Instruction EC_CoESDOWrite EC_CoESDORead EC_StartMon EC_StopMon EC_SaveMon EC_CopyMon EC_DisconnectSlave EC_ConnectSlave EC_ChangeEnableSetting NX_WriteObj NX_ReadObj

Name Write EtherCAT CoE SDO Read EtherCAT CoE SDO Start EtherCAT Packet Monitor Stop EtherCAT Packet Monitor Save EtherCAT Packets Transfer EtherCAT Packets Disconnect EtherCAT Slave Connect EtherCAT Slave Enable/Disable EtherCAT Slave Write NX Unit Object Read NX Unit Object

Page 2-934 2-937 2-942 2-948 2-950 2-952 2-954 2-961 2-963 2-980 2-995

NJ/NX-series Instructions Reference Manual (W502)

2-933

2 Instruction Descriptions

EC_CoESDOWrite

The EC_CoESDOWrite instruction writes a value to a CoE* object of a specified slave on an EtherCAT network.

Instruction
EC_CoESDOWrite

Name
Write EtherCAT CoE SDO

FB/ FUN
FB

Graphic expression

EC_CoESDOWrite_instance

EC_CoESDOWrite

Execute NodeAdr SdoObj TimeOut WriteDat WriteSize

Done Busy Error ErrorID AbortCode

ST expression
EC_CoESDOWrite_instance(Execute, NodeAdr, SdoObj, TimeOut, WriteDat, WriteSize, Done, Busy, Error, ErrorID, AbortCode);

* CoE stands for CAN Application Protocol over EtherCAT.

Variables

Name

Meaning

I/O

Description

Valid range

Unit

Default

NodeAdr Slave node

Node address of the slave to 1 to 512*1

SdoObj

address SDO

access

SDO parameter

---

---

---

parameter

TimeOut WriteDat

Timeout time Input Write data

0: 2.0s 1 to 65535: 0.1 to 6553.5 s
Write data

Depends on data 0.1 s type.
---

20 (2.0 s)

WriteSize

Write data size

Write data size*2

1 to 2048

Bytes

---

AbortCode Abort code Output Response code for SDO

Depends on data ---

---

access specified by CoE

type.

0: Normal end

*1 The range is 1 to 192 for the NX102 CPU Unit, NX1P2 CPU Unit, and NJ-series CPU Unit.

*2 The write data size may be less than 1 byte, e.g., if the write data is BOOL or a BOOL array. If it is less than 1 byte, set the value of WriteSize to 1.

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

NodeAdr SdoObj TimeOut
WriteDat
WriteSize AbortCode

OK Refer to Function for details on the structure _sSDO_ACCESS.
OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK
An enumeration, array, array element, structure member, or union member can also be specified. OK
OK

2-934

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

EtherCAT Communications Instructions

Function

The EC_CoESDOWrite instruction writes data to the CoE object of the node specified with slave node address NodeAdr. The content of WriteDat is written to the object. The number of bytes of data to write is specified with WriteSize. The SDO parameter is specified with SdoObj.

The data type of SdoObj is structure _sSDO_ACCESS. The specifications are as follows:

Name

Meaning

Description

Data type Valid range Unit Default

SdoObj

SDO

SDO parameter

parameter

_sSDO_ --ACCESS

---

---

Index

Index

Index number in the

UINT

object dictionary defined

1 to 65535

2

in CoE

EC_CoESDOWrite

Subindex

Subindex

IsCompleteAccess Complete access

Subindex number in the object dictionary defined in CoE
Specification of complete access of SDO
TRUE: Access data for all subindexes

USINT BOOL

---

---

Depends on

data type.

FALSE: Access data for the specified subindex

After the write is completed, the instruction waits for the response for the time specified with timeout time TimeOut. The response is stored in AbortCode. AbortCode is 0 for a normal response. A value is stored in AbortCode only when the value of ErrorID is 16#1804 (SDO abort response). The meaning and values of AbortCode depend on the slave. Refer to the manual for the slave.

The following figure shows a timing chart. A value is stored in AbortCode when Busy changes to FALSE after the completion of instruction processing.

Execute Busy

TRUE FALSE
TRUE FALSE

Task period

Done

TRUE FALSE

AbortCode

Cleared to 0.

Updated to result.

Related System-defined Variables

Name _EC_MBXSlavTbl[i] "i" is the node address.

Meaning
Message Communications Enabled Slave Table

Data type BOOL

Description This variable indicates whether communications are possible for each slave. TRUE: Communications are possible. FALSE: Communications are not possible.

Additional Information
· Refer to the NJ/NX-series CPU Unit Built-in EtherCAT Port User's Manual (Cat. No. W505) or NYseries Industrial Panel PC / Industrial Box PC Built-in EtherCAT Port User's Manual (Cat. No. W562) for details on EtherCAT communications.
· Refer to A-5 SDO Abort Codes on page A-26 for the SDO abort codes.

NJ/NX-series Instructions Reference Manual (W502)

2-935

2 Instruction Descriptions
Precautions for Correct Use
· Always use a variable for the input parameter to pass to WriteDat. A building error will occur if a constant is passed.
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error. · This instruction can be used only for the NJ/NX-series and NY-series Controller EtherCAT ports. · You can execute a maximum of 32 of the following instructions at the same time:
EC_CoESDOWrite, EC_CoESDORead, EC_StartMon, EC_StopMon, EC_SaveMon, EC_CopyMon, EC_DisconnectSlave, EC_ConnectSlave, EC_ChangeEnableSetting, IOL_ReadObj, and IOL_WriteObj. · An error occurs in the following cases. Error will change to TRUE, and an error code is assigned to ErrorID. · The EtherCAT master is not in a state that allows message communications. · The slave specified with NodeAdr does not exist. · The slave specified with NodeAdr is not in a state that allows communications. · The slave returns an error response. · More than 32 of the following instructions were executed at the same time:
EC_CoESDOWrite, EC_CoESDORead, EC_StartMon, EC_StopMon, EC_SaveMon, EC_CopyMon, EC_DisconnectSlave, EC_ConnectSlave, EC_ChangeEnableSetting, IOL_ReadObj, and IOL_WriteObj.

2-936

NJ/NX-series Instructions Reference Manual (W502)

EtherCAT Communications Instructions

2 Instruction Descriptions

EC_CoESDORead

The EC_CoESDORead instruction reads a value from a CoE* object of a specified slave on an EtherCAT network.

Instruction
EC_CoESDORead

Name
Read EtherCAT CoE SDO

FB/ FUN
FB

Graphic expression

EC_CoESDORead_instance

EC_CoESDORead

Execute NodeAdr SdoObj TimeOut ReadDat

Done Busy Error ErrorID

ST expression

EC_CoESDORead_instance(Execute,

NodeAdr, SdoObj, TimeOut, ReadDat,

Done, Busy, Error, ErrorID, AbortCode,

ReadSize);

2

AbortCode ReadSize

* CoE stands for CAN Application Protocol over EtherCAT.

EC_CoESDORead

Variables

Name

Meaning

I/O

Description

Valid range

Unit

Default

NodeAdr Slave node

Node address of the slave to 1 to 512*1

address

access

SdoObj

SDO parameter

Input

SDO parameter

---

---

---

TimeOut

Timeout time

0: 2.0s 1 to 65535: 0.1 to 6553.5 s

Depends on data 0.1 s type.

0 (2.0 s)

AbortCode Abort code

Response code for SDO

---

access specified by CoE

ReadSize Read data

Output

0: Normal end

Depends on data

Size of data stored in ReadDat type.

Bytes

---

size

after the data is read*2

ReadDat Read data

In-out Read data buffer

Depends on data ---

---

type.

*1 The range is 1 to 192 for the NX102 CPU Unit, NX1P2 CPU Unit, and NJ-series CPU Unit.

*2 The read data size may be less than 1 byte, e.g., if the read data is BOOL or a BOOL array. If it is less than 1 byte, set the value of ReadSize to 1.

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

NodeAdr SdoObj TimeOut AbortCode ReadSize
ReadDat

OK Refer to Function for details on the structure _sSDO_ACCESS.
OK OK
OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK
An enumeration, array, array element, structure member, or union member can also be specified.

NJ/NX-series Instructions Reference Manual (W502)

2-937

2 Instruction Descriptions

Function

The EC_CoESDORead instruction reads data from the CoE object of the node specified with slave node address NodeAdr. The read data is stored in ReadDat. Then size of data that was stored is stored in ReadSize. The value of ReadSize is valid only when the data was stored successfully. The SDO parameter is specified with SdoObj.

The data type of SdoObj is structure _sSDO_ACCESS. The specifications are as follows:

Name SdoObj
Index

Meaning SDO parameter Index

Subindex

Subindex

IsCompleteAc Complete

cess

access

Description SDO parameter
Index number in the object dictionary defined in CoE Subindex number in the object dictionary defined in CoE Specification of complete access of SDO TRUE:Access data for
all subindexes

Data type _sSDO_ ACCESS UINT
USINT
BOOL

Valid range Unit Default

---

--- ---

1 to 65535

Depends on data type.

--- ---

FALSE:Access data for the specified subindex

After the read is completed, the instruction waits for the response for the time specified with timeout time TimeOut. The response is stored in AbortCode. AbortCode is 0 for a normal response. A value is stored in AbortCode only when the value of ErrorID is 16#1804 (SDO abort response). The meaning and values of AbortCode depend on the slave. Refer to the manual for the slave.

The following figure shows a timing chart. A value is stored in AbortCode when Busy changes to FALSE after the completion of instruction processing.

Execute Busy

TRUE FALSE
TRUE FALSE

Task period

Done

TRUE FALSE

AbortCode

Cleared to 0.

Updated to result.

Related System-defined Variables

Name _EC_MBXSlaveTbl[i] "i" is the node address.

Meaning
Message Communications Enabled Slave Table

Data type BOOL

Description This variable indicates whether communications are possible for each slave. TRUE: Communications are possible. FALSE: Communications are not possible.

Additional Information
· Refer to the NJ/NX-series CPU Unit Built-in EtherCAT Port User's Manual (Cat. No. W505) or NYseries Industrial Panel PC / Industrial Box PC Built-in EtherCAT Port User's Manual (Cat. No. W562) for details on EtherCAT communications.
· Refer to A-5 SDO Abort Codes on page A-26 for the SDO abort codes.

2-938

NJ/NX-series Instructions Reference Manual (W502)

EtherCAT Communications Instructions

2 Instruction Descriptions

Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error. · This instruction can be used only for the NJ/NX-series and NY-series Controller EtherCAT ports. · You can execute a maximum of 32 of the following instructions at the same time:
EC_CoESDOWrite, EC_CoESDORead, EC_StartMon, EC_StopMon, EC_SaveMon, EC_CopyMon, EC_DisconnectSlave, EC_ConnectSlave, EC_ChangeEnableSetting, IOL_ReadObj, and IOL_WriteObj.
· An error occurs in the following cases. Error will change to TRUE, and an error code is assigned to 2
ErrorID. · The EtherCAT master is not in a state that allows message communications. · The slave specified with NodeAdr does not exist. · The slave specified with NodeAdr is not in a state that allows communications. · The slave returns an error response. · The read data size is larger than the size of ReadDat. · More than 32 of the following instructions were executed at the same time:
EC_CoESDOWrite, EC_CoESDORead, EC_StartMon, EC_StopMon, EC_SaveMon, EC_CopyMon, EC_DisconnectSlave, EC_ConnectSlave, EC_ChangeEnableSetting, IOL_ReadObj, and IOL_WriteObj.

EC_CoESDORead

Sample Programming

This sample uses an EtherCAT SDO message to read the software version of an OMRON 1S-series Servo Drive. The node address of the slave is 1. The object index for the software version is 16#100A. The subindex is 0. The read value is stored in STRING variable VersionInfo.
Remote slave node address 1

SDO read

Object Dictionary Settings Index: 16#100A Subindex 0

Built-in EtherCAT port

NJ/NX-series Instructions Reference Manual (W502)

2-939

2 Instruction Descriptions

LD
Internal Variables

Variable Trigger

SdoObject

VersionInfo
EC_CoESDORead_instance

Data type BOOL _sSDO_ACCESS STRING[256] EC_CoESDORead

Initial value
FALSE (Index:=0, Subindex:=0, IsCompleteAccess:=FALSE) ''

Comment Execution condition SDO parameter Read data

External Variables

Variable

_EC_MBXSlavTbl

Data type
ARRAY[1..512] OF BOOL*1

Constant

Comment

Message Communications Enabled Slave Table

*1 For the NX102 CPU Units, NX1P2 CPU Units, and NJ-series CPU Units, the data type is ARRAY [1..192] OF BOOL.

Accept trigger.

Trigger _EC_MBXSlavTbl[1] UINT#16#100A

@MOVE

EN

ENO

In

Out

SdoObject.Index

USINT#0

@MOVE

EN

ENO

In

Out

SdoObject.Subindex

FALSE

@MOVE

EN

ENO

In

Out

SdoObject.IsComleteAccess

UINT#1 SdoObject
UINT#20
VersionInfo

EC_CoESDORead_instance

EC_CoESDORead

Execute NodeAdr SdoObj TimeOut ReadDat

Done Busy Error ErrorID

AbortCode ReadSize

Processing after normal end Trigger EC_CoESDORead_instance.Done

Inline ST
1 // Processing after normal end 2 ;

Processing after error end Trigger EC_CoESDORead_instance.Error

Inline ST
1 // Processing after error end 2 ;

2-940

NJ/NX-series Instructions Reference Manual (W502)

EtherCAT Communications Instructions

2 Instruction Descriptions

ST
Internal Variables

Variable Trigger

SdoObject

DoSdoRead VersionInfo NormalEnd ErrorEnd EC_CoESDORead_instance

Data type BOOL
_sSDO_ACCESS
BOOL STRING[256] UINT UINT EC_CoESDORead

Initial value
FALSE (Index:=0, Subindex:=0, IsCompleteAccess:=FALSE) FALSE '' 0 0

Comment
Execution condition
SDO parameter
Processing Read data Normal end Error end
2

EC_CoESDORead

External Variables

Variable

_EC_MBXSlavTbl

Data type
ARRAY[1..512] OF BOOL *1

Constant

Comment

Message Communications Enabled Slave Table

*1 For the NX102 CPU Units, NX1P2 CPU Units, and NJ-series CPU Units, the data type is ARRAY [1..192] OF BOOL.

// Detect when Trigger changes to TRUE.

IF ( (Trigger=TRUE) AND (DoSdoRead=FALSE) AND (_EC_MBXSlavTbl[1]=TRUE) ) THEN

DoSdoRead

:=TRUE;

SdoObject.Index

:=UINT#16#100A;

SdoObject.Subindex

:=USINT#0;

SdoObject.IsCompleteAccess:=FALSE;

EC_CoESDORead_instance(

Execute:=FALSE,

// Initialize instance.

ReadDat:=VersionInfo); // Dummy

END_IF;

// Execute EC_CoESDORead instruction.

IF (DoSdoRead=TRUE) THEN

EC_CoESDORead_instance(

Execute :=TRUE,

NodeAdr :=UINT#1,

// Node address 1

SdoObj :=SdoObject,

// SDO parameter

TimeOut :=UINT#20,

// Timeout time: 2.0 s

ReadDat :=VersionInfo); // Read data

IF (EC_CoESDORead_instance.Done=TRUE) THEN // Processing after normal end NormalEnd:=NormalEnd+UINT#1;
ELSIF (EC_CoESDORead_instance.Error=TRUE) THEN // Processing after error end ErrorEnd :=ErrorEnd+UINT#1;
END_IF;

END_IF;

NJ/NX-series Instructions Reference Manual (W502)

2-941

2 Instruction Descriptions

EC_StartMon

The EC_StartMon instruction starts execution of packet monitoring for EtherCAT communications.

Instruction EC_StartMon

Name
Start EtherCAT Packet Monitor

FB/ FUN
FB

Graphic expression

EC_StartMon_instance

EC_StartMon

Execute

Done Busy Error ErrorID

ST expression
EC_SatrtMon_instance(Execute, Done, Busy, Error, ErrorID);

Variables
Only common variables are used.

Function
The EC_StartMon instruction starts execution of packet monitoring for EtherCAT communications. The packet monitor function collects a specified number of the most recent EtherCAT communications packets. When the specified number of packets is exceeded, old packets are discarded in order. After the EC_StartMon instruction is executed, packet monitoring continues until the EC_StopMon instruction is executed.

Related System-defined Variables

Name _EC_PktMonStop

Meaning
Packet Monitoring Stopped

Data type BOOL

_EC_PktSaving

Saving Packet Data File

BOOL

Description This variable shows if packet monitoring is stopped. TRUE: Stopped. FALSE: Not stopped. This variable shows if the instruction is saving packet data in an internal file in the main memory of the CPU Unit. TRUE: Saving. FALSE: Not saving.

Additional Information
· You cannot save collected packet data in an internal file of the main memory of the CPU Unit during ECATStartMonitor execution.
· Do the following to save packet data in an internal file in the main memory of the CPU Unit: First, execute the EC_StopMon instruction to stop packet monitoring. Then execute the EC_SaveMon instruction to save the packets.
· Refer to the NJ/NX-series CPU Unit Built-in EtherCAT Port User's Manual (Cat. No. W505) or NYseries Industrial Panel PC / Industrial Box PC Built-in EtherCAT Port User's Manual (Cat. No. W562) for details on EtherCAT communications.

2-942

NJ/NX-series Instructions Reference Manual (W502)

EtherCAT Communications Instructions

EC_StartMon

2 Instruction Descriptions
Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error. · This instruction can be used only for the NJ/NX-series and NY-series Controller EtherCAT ports. · You can execute a maximum of 32 of the following instructions at the same time:
EC_CoESDOWrite, EC_CoESDORead, EC_StartMon, EC_StopMon, EC_SaveMon, EC_CopyMon, EC_DisconnectSlave, EC_ConnectSlave, EC_ChangeEnableSetting, IOL_ReadObj, and IOL_WriteObj.
· An error occurs in the following cases. Error will change to TRUE, and an error code is assigned to 2
ErrorID. · A packet data save operation to an internal file in the main memory of the CPU Unit is in progress. · More than 32 of the following instructions were executed at the same time:
EC_CoESDOWrite, EC_CoESDORead, EC_StartMon, EC_StopMon, EC_SaveMon, EC_CopyMon, EC_DisconnectSlave, EC_ConnectSlave, EC_ChangeEnableSetting, IOL_ReadObj, and IOL_WriteObj.
Version Information
Depending on the unit version of the CPU Unit and the Sysmac Studio version, the following restrictions apply: · For NX701 and NJ101 CPU Units, the instruction can be used with Sysmac Studio version
1.13 or higher. · For an NX1P2 CPU Unit, the instruction can be used with Sysmac Studio version 1.17 or
higher. · For an NJ301 CPU Unit, the instruction can be used with the unit version 1.10 or later and
Sysmac Studio version 1.12 or higher. · For an NY-series Controller, the instruction can be used with Sysmac Studio version 1.17 or
higher.
Sample Programming
This sample transfers EtherCAT communications packets to an SD Memory Card when an EtherCAT slave error occurs. The file name is `PacketFile.' The processing procedure is as follows:
1 The system-defined variable _EC_ErrSta (EtherCAT Error) is monitored and processing is
started if an error occurs.
2 The EC_StopMon instruction is used to stop execution of packet monitoring for EtherCAT com-
munications.
3 The EC_SaveMon instruction is used to save EtherCAT communications packet data to an inter-
nal file in the main memory of the CPU Unit.
4 The EC_CopyMon instruction is used to copy that file to the SD Memory Card. 5 The EC_StartMon instruction is used to restart execution of packet monitoring for EtherCAT
communications.

NJ/NX-series Instructions Reference Manual (W502)

2-943

2 Instruction Descriptions

LD
Internal Variables

Variable
OperatingEnd Operating RS_instance EC_StopMon_instance EC_SaveMon_instance EC_CopyMon_instance EC_StartMon_instance

Data type
BOOL BOOL RS EC_StopMon EC_SaveMon EC_CopyMon EC_StartMon

External Variables

Variable

_EC_ErrSta

Data type WORD

_EC_PktMonStop BOOL

_EC_PktSaving

BOOL

_Card1Ready

BOOL

Initial value

Comment

FALSE FALSE

Processing completed Execution condition

Constant

Comment

Built-in EtherCAT Error Packet Monitoring Stopped Saving Packet Data File SD Memory Card Ready Flag

Determine if instruction execution is completed.

EC_StartMon_instance.Done

OperatingEnd

EC_StopMon_instance.Error

EC_SaveMon_instance.Error

EC_CopyMon_instance.Error

EC_StartMon_instance.Error

Monitor for EtherCAT errors.

_EC_ErrSta WORD#16#00

<>
EN In1 In2

Up

_EC_PktMonStop EC_StopMon_instance.Busy

In

1

EC_SaveMon_instance.Busy EC_CopyMon_instance.Busy EC_StartMon_instance.Busy

1

2

_EC_PktSaving

RS_instance RS

Operating

2

Set

Q1

OperatingEnd Reset1

2-944

NJ/NX-series Instructions Reference Manual (W502)

EtherCAT Communications Instructions

2 Instruction Descriptions

Instruction execution

Operating

_Card1Ready

EC_StopMon_instance EC_StopMon

EC_SaveMon_instance EC_SaveMon

Execute

Done

Execute

Done

3

Busy

Busy

Error

Error

ErrorID

ErrorID

EC_CopyMon_instance

EC_StartMon_instance

EC_CopyMon

EC_StartMon

3

Execute

Done

Execute

Done

`PacketFile' FileName

Busy Error

Busy Error

2

ErrorID

ErrorID

Processing after normal end Operating

Inline ST
1 // Processing after normal end 2 ;

EC_StartMon

NJ/NX-series Instructions Reference Manual (W502)

2-945

2 Instruction Descriptions

ST
Internal Variables

Variable

Data type

EC_Err

BOOL

EC_Err_Trigger DoEC_PktSave Stage R_TRIG_instance EC_StopMon_instance EC_SaveMon_instance EC_CopyMon_instance EC_StartMon_instance

BOOL BOOL INT R_TRIG EC_StopMon EC_SaveMon EC_CopyMon EC_StartMon

Initial value

Comment

FALSE
FALSE FALSE 0

Controller error in the EtherCAT Master Function Module. Detect when EC_Err changes to TRUE. Processing Stage change

External Variables

Variable

_EC_ErrSta

Data type WORD

_EC_PktMonStop BOOL

_EC_PktSaving

BOOL

_Card1Ready

BOOL

Constant

Comment

Built-in EtherCAT Error Packet Monitoring Stopped Saving Packet Data File SD Memory Card Ready Flag

// Start sequence when _EC_ErrSta changes to TRUE. EC_Err:=(_EC_ErrSta <> WORD#16#00); R_TRIG_instance(Clk:=EC_Err, Q=>EC_Err_Trigger);

IF ( (EC_Err_Trigger=TRUE) AND (DoEC_PktSave=FALSE) AND (_EC_PktMonStop=FALSE)

AND (_EC_PktSaving=FALSE) AND (_Card1Ready=TRUE) ) THEN

DoEC_PktSave:=TRUE;

Stage

:=INT#1;

EC_StopMon_instance(Execute:=FALSE); // Initialize instance.

EC_SaveMon_instance(Execute:=FALSE);

EC_CopyMon_instance(Execute:=FALSE);

EC_StartMon_instance(Execute:=FALSE);

END_IF;

// Instruction execution

IF (DoEC_PktSave=TRUE) THEN

CASE Stage OF

1 : // Stop EtherCAT packet monitor.

EC_StopMon_instance(

Execute

:=TRUE);

IF (EC_StopMon_instance.Done=TRUE) THEN Stage:=INT#2; // Normal end
ELSIF (EC_StopMon_instance.Error=TRUE) THEN Stage:=INT#10; // Error end
END_IF;

2 : // Save EtherCAT packet data in an internal file. EC_SaveMon_instance( Execute :=TRUE);

IF (EC_SaveMon_instance.Done=TRUE) THEN Stage:=INT#3; // Normal end
ELSIF (EC_SaveMon_instance.Error=TRUE) THEN Stage:=INT#20; // Error end
END_IF;

2-946

NJ/NX-series Instructions Reference Manual (W502)

EtherCAT Communications Instructions

2 Instruction Descriptions

3 : // Copy EtherCAT packet data file to the SD Memory Card. EC_CopyMon_instance( Execute :=TRUE, FileName :='PacketFile');

IF (EC_CopyMon_instance.Done=TRUE) THEN Stage:=INT#4; // Normal end
ELSIF (EC_CopyMon_instance.Error=TRUE) THEN Stage:=INT#30; // Error end
END_IF;

4 : // Restart EtherCAT packet monitor.

EC_StartMon_instance( Execute :=TRUE);

2

EC_StartMon

IF (EC_StartMon_instance.Done=TRUE) THEN Stage:=INT#0; // Normal end
ELSIF (EC_StartMon_instance.Error=TRUE) THEN Stage:=INT#40; // Error end
END_IF;

0 : // Processing after normal end DoEC_PktSave:=FALSE;

ELSE // Processing after error end DoEC_PktSave:=FALSE;
END_CASE; END_IF;

NJ/NX-series Instructions Reference Manual (W502)

2-947

2 Instruction Descriptions

EC_StopMon

The EC_StopMon instruction stops execution of packet monitoring for EtherCAT communications.

Instruction EC_StopMon

Name
Stop EtherCAT Packet Monitor

FB/ FUN
FB

Graphic expression

EC_StopMon_instance

EC_StopMon

Execute

Done Busy Error ErrorID

ST expression
EC_StopMon_instance(Execute, Done, Busy, Error, ErrorID);

Variables
Only common variables are used.

Function
The EC_StopMon instruction stops execution of packet monitoring for EtherCAT communications. The packet monitor function collects a specified number of the most recent EtherCAT communications packets.

Related System-defined Variables

Name _EC_PktMonStop
_EC_PktSaving

Meaning Packet Monitoring Stopped
Saving Packet Data File

Data type BOOL
BOOL

Description This variable shows if packet monitoring is stopped. TRUE: Stopped. FALSE: Not stopped. This variable shows if the instruction is saving packet data in an internal file in the main memory of the CPU Unit. TRUE: Saving. FALSE: Not saving.

Additional Information
· Do the following to save collected packet data in an internal file in the main memory of the CPU Unit: First, stop packet monitoring. Then execute the EC_SaveMon instruction to save the packets.
· Refer to the NJ/NX-series CPU Unit Built-in EtherCAT Port User's Manual (Cat. No. W505) or NYseries Industrial Panel PC / Industrial Box PC Built-in EtherCAT Port User's Manual (Cat. No. W562) for details on EtherCAT communications.

Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error.

2-948

NJ/NX-series Instructions Reference Manual (W502)

EtherCAT Communications Instructions

2 Instruction Descriptions

· This instruction can be used only for the NJ/NX-series and NY-series Controller EtherCAT ports.

· You can execute a maximum of 32 of the following instructions at the same time: EC_CoESDOWrite, EC_CoESDORead, EC_StartMon, EC_StopMon, EC_SaveMon, EC_CopyMon, EC_DisconnectSlave, EC_ConnectSlave, EC_ChangeEnableSetting, IOL_ReadObj, and IOL_WriteObj.

· An error occurs in the following cases. Error will change to TRUE, and an error code is assigned to ErrorID.

· Packet monitoring is already stopped.

· More than 32 of the following instructions were executed at the same time:

EC_CoESDOWrite, EC_CoESDORead, EC_StartMon, EC_StopMon, EC_SaveMon, EC_Copy-

Mon, EC_DisconnectSlave, EC_ConnectSlave, EC_ChangeEnableSetting, IOL_ReadObj, and

IOL_WriteObj.

2

EC_StopMon

Version Information
Depending on the unit version of the CPU Unit and the Sysmac Studio version, the following restrictions apply: · For NX701 and NJ101 CPU Units, the instruction can be used with Sysmac Studio version
1.13 or higher. · For an NX1P2 CPU Unit, the instruction can be used with Sysmac Studio version 1.17 or
higher. · For an NJ301 CPU Unit, the instruction can be used with the unit version 1.10 or later and
Sysmac Studio version 1.12 or higher. · For an NY-series Controller, the instruction can be used with Sysmac Studio version 1.17 or
higher.

Sample Programming
Refer to the sample programming that is provided for the EC_StartMon instruction (page 2-942).

NJ/NX-series Instructions Reference Manual (W502)

2-949

2 Instruction Descriptions

EC_SaveMon

The EC_SaveMon instruction saves EtherCAT communications packet data to an internal file in the main memory of the CPU Unit.

Instruction EC_SaveMon

Name
Save EtherCAT Packets

FB/ FUN
FB

Graphic expression

EC_SaveMon_instance

EC_SaveMon

Execute

Done Busy Error ErrorID

ST expression
EC_SaveMon_instance(Execute, Done, Busy, Error, ErrorID);

Variables
Only common variables are used.

Function
The EC_SaveMon instruction saves EtherCAT communications packet data that was collected by the packet monitoring function to an internal file in the main memory of the CPU Unit. The packet monitor function collects a specified number of the most recent EtherCAT communications packets.

Related System-defined Variables

Name _EC_PktMonStop

Meaning
Packet Monitoring Stopped

Data type BOOL

_EC_PktSaving

Saving Packet Data File

BOOL

Description This variable shows if packet monitoring is stopped. TRUE: Stopped. FALSE: Not stopped. This variable shows if the instruction is saving packet data in an internal file in the main memory of the CPU Unit. TRUE: Saving. FALSE: Not saving.

Additional Information
· You cannot execute packet monitoring while this instruction is in execution. · Refer to the NJ/NX-series CPU Unit Built-in EtherCAT Port User's Manual (Cat. No. W505) or NY-
series Industrial Panel PC / Industrial Box PC Built-in EtherCAT Port User's Manual (Cat. No. W562) for details on EtherCAT communications.

Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error.

2-950

NJ/NX-series Instructions Reference Manual (W502)

EtherCAT Communications Instructions

2 Instruction Descriptions

· This instruction can be used only for the NJ/NX-series and NY-series Controller EtherCAT ports.

· You cannot execute this instruction while packet monitoring is in progress. Execute the EC_StopMon instruction in advance to stop packet monitoring.

· You can execute a maximum of 32 of the following instructions at the same time: EC_CoESDOWrite, EC_CoESDORead, EC_StartMon, EC_StopMon, EC_SaveMon, EC_CopyMon, EC_DisconnectSlave, EC_ConnectSlave, EC_ChangeEnableSetting, IOL_ReadObj, and IOL_WriteObj.

· An error occurs in the following cases. Error will change to TRUE, and an error code is assigned to ErrorID.

· Packet monitoring is in progress.

· More than 32 of the following instructions were executed at the same time:

EC_CoESDOWrite, EC_CoESDORead, EC_StartMon, EC_StopMon, EC_SaveMon, EC_Copy-

2

Mon, EC_DisconnectSlave, EC_ConnectSlave, EC_ChangeEnableSetting, IOL_ReadObj, and

IOL_WriteObj.

EC_SaveMon

Version Information
Depending on the unit version of the CPU Unit and the Sysmac Studio version, the following restrictions apply: · For NX701 and NJ101 CPU Units, the instruction can be used with Sysmac Studio version
1.13 or higher. · For an NX1P2 CPU Unit, the instruction can be used with Sysmac Studio version 1.17 or
higher. · For an NJ301 CPU Unit, the instruction can be used with the unit version 1.10 or later and
Sysmac Studio version 1.12 or higher. · For an NY-series Controller, the instruction can be used with Sysmac Studio version 1.17 or
higher.

Sample Programming
Refer to the sample programming that is provided for the EC_StartMon instruction (page 2-942).

NJ/NX-series Instructions Reference Manual (W502)

2-951

2 Instruction Descriptions

EC_CopyMon

The EC_CopyMon instruction transfers packet data in an internal file in the main memory of the CPU Unit to a SD Memory Card.

Instruction EC_CopyMon

Name
Transfer EtherCAT Packets

FB/ FUN
FB

Graphic expression

EC_CopyMon_instance

EC_CopyMon

Execute FileName

Done Busy Error ErrorID

ST expression
EC_CopyMon_instance(Execute, FileName, Done, Busy, Error, ErrorID);

Variables

Name FileName

Meaning File name

I/O Input

Description

Valid range

Unit

File name on the SD Memory Depends on data ---

Card

type.

Default
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

FileName

OK

Function
The EC_CopyMon instruction transfers packet data in an internal file in the main memory of the CPU Unit to a SD Memory Card. FileName specifies the file name on the SD Memory Card.

Related System-defined Variables

Name _EC_PktSaving

Meaning
Saving Packet Data File

Data type BOOL

Description This variable shows if the instruction is saving packet data in an internal file in the main memory of the CPU Unit.
TRUE: Saving.
FALSE: Not saving.

Additional Information
Refer to the NJ/NX-series CPU Unit Built-in EtherCAT Port User's Manual (Cat. No. W505) or NY-series Industrial Panel PC / Industrial Box PC Built-in EtherCAT Port User's Manual (Cat. No. W562) for details on EtherCAT communications.

2-952

NJ/NX-series Instructions Reference Manual (W502)

EtherCAT Communications Instructions

2 Instruction Descriptions

Precautions for Correct Use

· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.

· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error.

· This instruction can be used only for the NJ/NX-series and NY-series Controller EtherCAT ports.

· You cannot execute this instruction while a packet save operation is in progress.

· To use this instruction, execute the EC_SaveMon instruction in advance to save the packet data in an internal file in the main memory of the CPU Unit.

· You can execute a maximum of 32 of the following instructions at the same time:

2

EC_CoESDOWrite, EC_CoESDORead, EC_StartMon, EC_StopMon, EC_SaveMon, EC_CopyMon,

EC_DisconnectSlave, EC_ConnectSlave, EC_ChangeEnableSetting, IOL_ReadObj, and IOL_Write-

Obj.

EC_CopyMon

· An error occurs in the following cases. Error will change to TRUE, and an error code is assigned to ErrorID.

· A packet data file save operation is in progress.

· More than 32 of the following instructions were executed at the same time: EC_CoESDOWrite, EC_CoESDORead, EC_StartMon, EC_StopMon, EC_SaveMon, EC_CopyMon, EC_DisconnectSlave, EC_ConnectSlave, EC_ChangeEnableSetting, IOL_ReadObj, and IOL_WriteObj.

Version Information
Depending on the unit version of the CPU Unit and the Sysmac Studio version, the following restrictions apply: · For NX701 and NJ101 CPU Units, the instruction can be used with Sysmac Studio version
1.13 or higher. · For an NX1P2 CPU Unit, the instruction can be used with Sysmac Studio version 1.17 or
higher. · For an NJ301 CPU Unit, the instruction can be used with the unit version 1.10 or later and
Sysmac Studio version 1.12 or higher. · For an NY-series Controller, the instruction can be used with Sysmac Studio version 1.17 or
higher.

Sample Programming
Refer to the sample programming that is provided for the EC_StartMon instruction (page 2-942).

NJ/NX-series Instructions Reference Manual (W502)

2-953

2 Instruction Descriptions

EC_DisconnectSlave

The EC_DisconnectSlave instruction disconnects the specified slave from the network.

Instruction
EC_DisconnectSlave

Name
Disconnect EtherCAT Slave

FB/ FUN
FB

Graphic expression

EC_DisconnectSlave_instance

EC_DisconnectSlave

Execute NodeAdr

Done Busy Error ErrorID

ST expression
EC_DisconnectSlave_instance(Execute, NodeAdr, Done, Busy, Error, ErrorID);

Variables

Name

Meaning

I/O

Description

Valid range

Unit

NodeAdr

Slave node Input

Node address of the slave to 1 to 512*

---

address

disconnect

* The range is 1 to 192 for the NX102 CPU Unit, NX1P2 CPU Unit, and NJ-series CPU Unit.

Default ---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

NodeAdr

OK

Function
The EC_DisconnectSlave instruction disconnects the slave specified with slave node address NodeAdr from the EtherCAT network. Here, disconnection from the network means that the slave is placed in a state in which it does not operate even though it still exists on the network.

Related System-defined Variables

Name _EC_EntrySlavTbl[i] "i" is the node address.

Meaning
Network Connected Slave Table

Data type BOOL[]

_EC_DisconnSlavTbl[i] "i" is the node address.

Disconnected Slave Table

BOOL[]

_EC_DisableSlavTbl[i] "i" is the node address.

Disabled Slave Table BOOL[]

Description This variable shows if slaves are part of (i.e., exist on) the network. TRUE: Part of the network. FALSE: Not part of the network. This variable shows the slaves for which there are currently disconnect commands in effect. TRUE: Disconnect command is in effect. FALSE: Disconnect command is not in effect. This variable shows if slaves are disabled on the network. TRUE: Disabled. FALSE: Not disabled.

2-954

NJ/NX-series Instructions Reference Manual (W502)

EtherCAT Communications Instructions

2 Instruction Descriptions

Additional Information
Refer to the NJ/NX-series CPU Unit Built-in EtherCAT Port User's Manual (Cat. No. W505) or NY-series Industrial Panel PC / Industrial Box PC Built-in EtherCAT Port User's Manual (Cat. No. W562) for details on EtherCAT communications.

Precautions for Correct Use

· Execution of this instruction is continued until processing is completed even if the value of Execute

changes to FALSE or the execution time exceeds the task period. The value of Done changes to

TRUE when processing is completed. Use this to confirm normal completion of processing.

2

· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error.

· This instruction can be used only for the NJ/NX-series and NY-series Controller EtherCAT ports.

EC_DisconnectSlave

· If there are slaves with daisy-chain connections (i.e., connected to the output port) after the disconnected slave, they are disconnected from the EtherCAT network also.

· You cannot execute this instruction during execution of the following instructions: EC_DisconnectSlave, EC_ConnectSlave, EC_ChangeEnableSetting, ResetECError, RestartNXUnit, and NX_ChangeWriteMode.

· You can execute a maximum of 32 of the following instructions at the same time: EC_CoESDOWrite, EC_CoESDORead, EC_StartMon, EC_StopMon, EC_SaveMon, EC_CopyMon, EC_DisconnectSlave, EC_ConnectSlave, EC_ChangeEnableSetting, IOL_ReadObj, and IOL_WriteObj.

· An error occurs in the following case. Error will change to TRUE, and an error code is assigned to ErrorID.

· The slave specified with NodeAdr is not part of the EtherCAT network. That is, the value of _EC_EntrySlavTbl[i] (Network Connected Slave Table) is FALSE.

· The slave specified with NodeAdr is disabled.

· The EC_DisconnectSlave, EC_ConnectSlave, EC_ChangeEnableSetting, ResetECError, RestartNXUnit, or NX_ChangeWriteMode instruction is already in execution.

· More than 32 of the following instructions were executed at the same time: EC_CoESDOWrite, EC_CoESDORead, EC_StartMon, EC_StopMon, EC_SaveMon, EC_CopyMon, EC_DisconnectSlave, EC_ConnectSlave, EC_ChangeEnableSetting, IOL_ReadObj, and IOL_WriteObj.

Sample Programming
This sample disconnects slave 1 from the EtherCAT network and then connects it again. When Trigger1 changes to TRUE, the EC_DisconnectSlave instruction is executed to disconnect slave 1. When Trigger2 changes to TRUE, the EC_ConnectSlave instruction is executed to connect slave 1 again.

Exclusive Control of Instructions
You cannot execute the EC_DisconnectSlave and EC_ConnectSlave instructions at the same time. Both of these instructions are executed over more than one task. Confirm the completion of the instruction that was executed first before you execute the other instruction. The ExclusiveFlg variable (Instruction Exclusive Flag) is used for this purpose. If the value of ExclusiveFlg is TRUE, then one of the instructions is in execution. Do not execute the next instruction while the value of ExclusiveFlg is TRUE.

NJ/NX-series Instructions Reference Manual (W502)

2-955

2 Instruction Descriptions

You cannot execute the EC_DisconnectSlave and EC_ConnectSlave instructions at the same time even in separate tasks. Therefore, ExclusiveFlg is defined as a global variable in this sample programming. That allows this sample programming to perform exclusive control with instructions in other tasks. The same global variable, ExclusiveFlg, must also be used in the other tasks to perform exclusive control of the instructions.
Also, you cannot execute the EC_DisconnectSlave and EC_ConnectSlave instructions at the same time as the EC_ChangeEnableSetting instruction. The sample programming that is provided for the EC_ChangeEnableSetting instruction on page 2-963 uses the same ExclusiveFlg global variable as in this sample programming as an example of exclusive control of instructions.

Definitions of Global Variables

Global Variables

Variable

Data type

ExclusiveFlg BOOL

Initial value FALSE

Comment
Instruction Exclusive Flag

LD
Internal Variables

Variable
Operating1End Trigger1 Operating1 RS_instance1 EC_DisconnectSlave_instance Operating2End Trigger2 Operating2 RS_instance2 EC_ConnectSlave_instance

Data type
BOOL BOOL BOOL RS EC_DisconnectSlave BOOL BOOL BOOL RS EC_ConnectSlave

Initial value

Comment

FALSE FALSE FALSE

Processing 1 completed. Execution condition 1 Processing 1

FALSE FALSE FALSE

Processing 2 completed. Execution condition 2 Processing 2

External Variables

Variable _EC_EntrySlavTbl _EC_DisconnSlavTbl ExclusiveFlg

Data type
ARRAY[1..512] OF BOOL *1 ARRAY[1..512] OF BOOL *1 BOOL

Constant

Comment

Network Connected Slave Table

Disconnected Slave Table

---

Instruction Exclusive Flag

*1 For the NX102 CPU Units, NX1P2 CPU Units, and NJ-series CPU Units, the data type is ARRAY [1..192] OF BOOL.

2-956

NJ/NX-series Instructions Reference Manual (W502)

EtherCAT Communications Instructions

2 Instruction Descriptions

Determine if execution of the EC_DisconnectSlave instruction is completed.

EC_DisconnectSlave_instance.Done

Operating1End

EC_DisconnectSlave_instance.Error

Accept trigger 1. Trigger1 _EC_EntrySlavTbl[1]

RS_instance1 RS

Operating1

Set

Q1

Operating1End Reset1
2

EC_DisconnectSlave

Execute EC_DisconnectSlave instruction. EC_DisconnectSlave_instance

Operating1 ExclusiveFlg

EC_DisconnectSlave

Execute UINT#1 NodeAdr

Done Busy Error ErrorID

Exclusive control of instructions

EC_DisconnectSlave_instance.Busy ExclusiveFlg

S

EC_DisconnectSlave_instance.Busy ExclusiveFlg R
Processing after normal end Operating1 EC_DisconnectSlave_instance.Done

Inline ST
1 // Processing after normal end 2 ;

Processing after error end Operating1 EC_DisconnectSlave_instance.Error

Inline ST
1 // Processing after error end 2 ;

Determine if execution of the EC_ConnectSlave instruction is completed.

EC_ConnectSlave_instance.Done

Operating2End

EC_ConnectSlave_instance.Error

NJ/NX-series Instructions Reference Manual (W502)

2-957

2 Instruction Descriptions

Accept trigger 2. Trigger2 _EC_DisconnSlavTbl[1]
Operating2End

RS_instance2

RS

Set

Q1

Reset1

Operating2

Execute EC_ConnectSlave instruction. Operating2 ExclusiveFlg

EC_ConnectSlave_instance EC_ConnectSlave

Execute UINT#1 NodeAdr
Exclusive control of instructions

Done Busy Error ErrorID

EC_ConnectSlave_instance.Busy ExclusiveFlg

S

EC_ConnectSlave_instance.Busy

ExclusiveFlg R

Processing after normal end Operating2 EC_ConnectSlave_instance.Done

Inline ST
1 // Processing after normal end 2 ;

Processing after error end Operating2 EC_ConnectSlave_instance.Error

Inline ST
1 // Processing after error end 2 ;

2-958

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

EtherCAT Communications Instructions

ST

Internal Variables

Variable

Data type

Initial value

Comment

Trigger1

BOOL

FALSE Execution condition 1

LastTrigger1

BOOL

FALSE

Value of Trigger1 from previous task period

Operating1Start

BOOL

FALSE Processing 1 started.

Operating1

BOOL

FALSE Processing 1

DisconnectSet

BOOL

FALSE

EC_DisconnectSlave instruction execution is in progress.

DisconnectReset

BOOL

FALSE

EC_DisconnectSlave instruction execution is not in progress.

2

EC_DisconnectSlave_instance EC_DisconnectSlave

EC_DisconnectSlave

Trigger2

BOOL

FALSE Execution condition 2

LastTrigger2

BOOL

FALSE

Value of Trigger2 from previous task period

Operating2Start

BOOL

FALSE Processing 2 started.

Operating2

BOOL

FALSE Processing 2

ConnectSet

BOOL

FALSE

EC_ConnectSlave instruction execution is in progress.

ConnectReset

BOOL

FALSE

EC_ConnectSlave instruction execution is not in progress.

EC_ConnectSlave_instance EC_ConnectSlave

R_TRIG_instance1

R_TRIG

F_TRIG_instance1

F_TRIG

RS_instance1

RS

R_TRIG_instance2

R_TRIG

F_TRIG_instance2

F_TRIG

RS_instance2

RS

External Variables

Variable _EC_EntrySlavTbl _EC_DisconnSlavTbl ExclusiveFlg

Data type
ARRAY[1..512] OF BOOL *1 ARRAY[1..512] OF BOOL *1 BOOL

Constant

Comment

Network Connected Slave Table

Disconnected Slave Table

---

Instruction Exclusive Flag

*1 The data type is ARRAY [1..192] OF BOOL for an NJ-series CPU Unit.

// Detect when Trigger1 changes to TRUE.

IF ( (Trigger1=TRUE) AND (LastTrigger1=FALSE) AND (_EC_EntrySlavTbl[1]=TRUE) ) THEN

Operating1Start:=TRUE;

Operating1

:=TRUE;

END_IF;

LastTrigger1:=Trigger1;

// Initialize EC_DisconnectSlave instruction. IF (Operating1Start=TRUE) THEN
EC_DisconnectSlave_instance(Execute:=FALSE); Operating1Start:=FALSE; END_IF;

// Execute EC_DisconnectSlave instruction. IF (Operating1=TRUE) THEN

NJ/NX-series Instructions Reference Manual (W502)

2-959

2 Instruction Descriptions

EC_DisconnectSlave_instance( Execute:=NOT(ExclusiveFlg), NodeAdr:=UINT#1);

// Exclusive control of instructions R_TRIG_instance1(EC_DisconnectSlave_instance.Busy, DisconnectSet); F_TRIG_instance1(EC_DisconnectSlave_instance.Busy, DisconnectReset); RS_instance1(DisconnectSet, DisconnectReset, ExclusiveFlg);

IF (EC_DisconnectSlave_instance.Done=TRUE) THEN // Processing after normal end Operating1:=FALSE;
END_IF;

IF (EC_DisconnectSlave_instance.Error=TRUE) THEN // Processing after error end Operating1:=FALSE;
END_IF; END_IF;

// Detect when Trigger2 changes to TRUE.

IF ( (Trigger2=TRUE) AND (LastTrigger2=FALSE) AND (_EC_DisconnSlavTbl[1]=TRUE) ) THEN

Operating2Start:=TRUE;

Operating2

:=TRUE;

END_IF;

LastTrigger2:=Trigger2;

// Initialize EC_ConnectSlave instruction. IF (Operating2Start=TRUE) THEN
EC_ConnectSlave_instance(Execute:=FALSE); Operating2Start:=FALSE; END_IF;

// Execute EC_ConnectSlave instruction. IF (Operating2=TRUE) THEN
EC_ConnectSlave_instance( Execute:=NOT(ExclusiveFlg), NodeAdr:=UINT#1);

// Exclusive control of instructions R_TRIG_instance2(EC_ConnectSlave_instance.Busy, ConnectSet); F_TRIG_instance2(EC_ConnectSlave_instance.Busy, ConnectReset); RS_instance2(ConnectSet, ConnectReset, ExclusiveFlg);

IF (EC_ConnectSlave_instance.Done=TRUE) THEN // Processing after normal end Operating2:=FALSE;
END_IF;

IF (EC_ConnectSlave_instance.Error=TRUE) THEN // Processing after error end Operating2:=FALSE;
END_IF; END_IF;

2-960

NJ/NX-series Instructions Reference Manual (W502)

EtherCAT Communications Instructions

2 Instruction Descriptions

EC_ConnectSlave

The EC_ConnectSlave instruction connects the specified slave to the EtherCAT network.

Instruction

Name

FB/ FUN

Graphic expression

ST expression

EC_Connect- Connect Ether- FB

Slave

CAT Slave

EC_ConnectSlave_instance EC_ConnectSlave

EC_ConnectSlave_instance(Execute, NodeAdr, Done, Busy, Error, ErrorID);

Execute

Done

NodeAdr

Busy

Error

2

ErrorID

EC_ConnectSlave

Variables

Name

Meaning

I/O

Description

Valid range

Unit

NodeAdr

Slave node Input

Node address of the slave to 0*1 to 512*2

---

address

connect

*1 Here, 0 means all of the slaves that are registered in the network settings.

*2 The range is 0 to 192 for the NX102 CPU Unit, NX1P2 CPU Unit, and NJ-series CPU Unit.

Default ---

Version Information
For an NJ-series CPU Unit, the valid range of slave node addresses depends on the version as follows: · Version 1.10 or later: 0 to 192 · Version 1.09 or earlier: 1 to 192

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

NodeAdr

OK

Function
The EC_ConnectSlave instruction connects the slave specified with slave node address NodeAdr to the EtherCAT network. Here, connection to the network means that the slave exists on the network and it is placed in a state in which it operates.

NJ/NX-series Instructions Reference Manual (W502)

2-961

2 Instruction Descriptions

Related System-defined Variables

Name _EC_EntrySlavTbl[i] "i" is the node address.
_EC_DisconnSlavTbl[i] "i" is the node address.

Meaning Network Connected Slave Table
Disconnected Slave Table

Data type BOOL[]
BOOL[]

Description This variable shows if slaves are part of (i.e., exist on) the network. TRUE: Part of the network. FALSE: Not part of the network. This variable shows the slaves for which there are currently disconnect commands in effect. TRUE: Disconnect command is in effect. FALSE: Disconnect command is not in effect.

Additional Information
Refer to the NJ/NX-series CPU Unit Built-in EtherCAT Port User's Manual (Cat. No. W505) or NY-series Industrial Panel PC / Industrial Box PC Built-in EtherCAT Port User's Manual (Cat. No. W562) for details on EtherCAT communications.

Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error.
· This instruction can be used only for the NJ/NX-series and NY-series Controller EtherCAT ports.
· You cannot execute this instruction during execution of the following instructions: EC_DisconnectSlave, EC_ConnectSlave, EC_ChangeEnableSetting, ResetECError, RestartNXUnit, and NX_ChangeWriteMode.
· You can execute a maximum of 32 of the following instructions at the same time: EC_CoESDOWrite, EC_CoESDORead, EC_StartMon, EC_StopMon, EC_SaveMon, EC_CopyMon, EC_DisconnectSlave, EC_ConnectSlave, EC_ChangeEnableSetting, IOL_ReadObj, and IOL_WriteObj.
· An error occurs in the following cases. Error will change to TRUE, and an error code is assigned to ErrorID.
· The slave specified with NodeAdr is not part of the EtherCAT network. That is, the value of _EC_EntrySlavTbl[i] (Network Connected Slave Table) is FALSE.
· The EC_DisconnectSlave, EC_ConnectSlave, EC_ChangeEnableSetting, ResetECError, RestartNXUnit, or NX_ChangeWriteMode instruction is already in execution.
· More than 32 of the following instructions were executed at the same time: EC_CoESDOWrite, EC_CoESDORead, EC_StartMon, EC_StopMon, EC_SaveMon, EC_CopyMon, EC_DisconnectSlave, EC_ConnectSlave, EC_ChangeEnableSetting, IOL_ReadObj, and IOL_WriteObj.

Sample Programming
Refer to the sample programming that is provided for the EC_DisconnectSlave instruction (page 2-954).

2-962

NJ/NX-series Instructions Reference Manual (W502)

EtherCAT Communications Instructions

2 Instruction Descriptions

EC_ChangeEnableSetting

The EC_ChangeEnableSetting instruction enables or disables an EtherCAT slave.

Instruction

Name

FB/ FUN

Graphic expression

ST expression

EC_Chan- Enable/Dis- FB

EC_ChangeEnableSetting_instance

EC_ChangeEnableSetting_in-

geEnableSet- able Ether-

EC_ChangeEnableSetting

stance(Execute, NodeAdr, IsEnable,

ting

CAT Slave

Execute

Done

Done, Busy, Error, ErrorID);

NodeAdr

Busy

IsEnable

Error ErrorID

2

EC_ChangeEnableSetting

Variables

Name NodeAdr
IsEnable

Meaning

I/O

Slave node address

Enable/disable designation

Input

Description

Valid range

Unit

Node address of the EtherCAT 1 to 512* slave to enable or disable

Designation of whether to

enable or disable the specified

---

EtherCAT slave

Depends on

TRUE: Enable

data type.

FALSE: Disable

* The range is 1 to 192 for the NX102 CPU Unit, NX1P2 CPU Unit, and NJ-series CPU Unit.

Default 1
TRUE

Bit strings

Integers

Times, durations, dates, and text strings

Real numbers

Boolean BOOL

STRING DT TOD
DATE TIME

LREAL REAL

LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE

NodeAdr

OK

IsEnable OK

Function
The EC_ChangeEnableSetting instruction enables or disables the EtherCAT slave that is specified with slave node address NodeAdr. The slave is enabled if enable/disable designation IsEnable is TRUE and disabled if it is FALSE. Enabling or disabling the slave is completed when the instruction is completed normally (i.e., when the value of Done changes to TRUE).

NJ/NX-series Instructions Reference Manual (W502)

2-963

2 Instruction Descriptions

Whether the instruction is completed normally depends on the status of the specified EtherCAT slave, i.e., whether it is enabled or disabled, whether it is participating or not participating, and whether it exists in the EtherCAT network. The status after execution of the instruction is given in the following table according to the status of the EtherCAT slave before execution of the instruction.

Status before instruction execution

Status after instruction execution

Enabled/dis abled

Participating/not partici-
pating

Exists Value of IsEnable *1

Normal/error end

Enabled/disabled

Participating

Yes

Normal end

Enabled

Enabled

Yes Not participating
No

TRUE (Enabled)

Error end *2

Enabled

Yes

Disabled

--- *3

No

Normal end Error end *4

Enabled Disabled *4

Participating

Yes

Normal end

Disabled

Enabled

Yes Not participating
No

Error end *2 FALSE (Disabled)

Enabled

Yes

Disabled

--- *3

No

Normal end Error end *4

Disabled Disabled *4

*1 This indicates whether the specified EtherCAT slave is physically connected to the EtherCAT network.

Yes: Physically connected. No: Not physically connected.

*2 Error code 1800 is returned.

*3 There is no participating/not participating distinction for EtherCAT slaves that are disabled.

*4 The normal/error end status is error end, the enabled/disabled status before the instruction execution is

retained, and Error code 1801 is returned.

 Application Example

The following example shows how to enable the EtherCAT slave at node address 1. UINT#1 is specified for NodeAdr and TRUE is specified for IsEnable.

LD

ST

A
UINT#1 TRUE

EC_ChangeEnableSetting_instance

EC_ChangeEnableSetting

Execute NodeAdr IsEnable

Done Busy Error ErrorID

abc
def ghi jkl

EC_ChangeEnableSetting_instance(A, UINT#1, TRUE, abc, def, ghi, jkl);

2-964

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

EtherCAT Communications Instructions

Related System-defined Variables

Name
_EC_EntrySlavTbl [i] "i" is the node address.
_EC_DisconnSlavTbl[i] "i" is the node address.
_EC_DisableSlavTbl[i] "i" is the node address.

Meaning

Data type

Description

Network Connected Slave Table

BOOL[]

This variable shows if slaves are part of (i.e., exist on) the network.
TRUE: Part of the network.

FALSE: Not part of the network.

This variable shows the slaves for which there are

Disconnected Slave Table

currently disconnect commands in effect. BOOL[] TRUE: Disconnect command is in effect.

FALSE: Disconnect command is not in effect.

2

This variable shows if slaves are disabled.

Disabled Slave Table BOOL[] TRUE: Disabled.

FALSE: Not disabled or not part of the network.

EC_ChangeEnableSetting

Additional Information
· Refer to the NJ/NX-series CPU Unit Built-in EtherCAT Port User's Manual (Cat. No. W505) or NYseries Industrial Panel PC / Industrial Box PC Built-in EtherCAT Port User's Manual (Cat. No. W562) for details on EtherCAT communications.
· Use the EC_ConnectSlave instruction on page 2-961 to connect an EtherCAT slave to the EtherCAT network.

Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error.
· This instruction can be used only for the NJ/NX-series and NY-series Controller EtherCAT ports.
· You cannot execute this instruction during execution of the following instructions: EC_DisconnectSlave, EC_ConnectSlave, EC_ChangeEnableSetting, ResetECError, RestartNXUnit, and NX_ChangeWriteMode.
· The execution results of this instruction are not saved in non-volatile memory in the CPU Unit. Therefore, if the power supply to the Controller is cycled after execution of this instruction or if the user program is downloaded, the enable/disable setting of the EtherCAT slave will return to the value that was set from the Sysmac Studio.
· You can execute a maximum of 32 of the following instructions at the same time: EC_CoESDOWrite, EC_CoESDORead, EC_StartMon, EC_StopMon, EC_SaveMon, EC_CopyMon, EC_DisconnectSlave, EC_ConnectSlave, EC_ChangeEnableSetting, IOL_ReadObj, and IOL_WriteObj.
· An error occurs in the following cases. Error will change to TRUE, and an error code is assigned to ErrorID.
· The slave specified with NodeAdr is not part of the EtherCAT network. That is, the value of _EC_EntrySlavTbl[i] (Network Connected Slave Table) is FALSE.
· The value of NodeAdr is outside of the valid range.
· The EC_DisconnectSlave, EC_ConnectSlave, EC_ChangeEnableSetting, ResetECError, RestartNXUnit, or NX_ChangeWriteMode instruction is already in execution.
· More than 32 of the following instructions were executed at the same time: EC_CoESDOWrite, EC_CoESDORead, EC_StartMon, EC_StopMon, EC_SaveMon, EC_CopyMon, EC_DisconnectSlave, EC_ConnectSlave, EC_ChangeEnableSetting, IOL_ReadObj, and IOL_WriteObj.

NJ/NX-series Instructions Reference Manual (W502)

2-965

2 Instruction Descriptions
Version Information A CPU Unit with unit version 1.04 or later and Sysmac Studio version 1.05 or higher are required to use this instruction.
Sample Programming
 Example of Disconnecting EtherCAT Slaves from the EtherCAT Network
Production line 1 in the following system is left running while EtherCAT slaves C, D, and E on production line 2 are removed. Motion control axes are already set for EtherCAT slaves C, D, and E. Therefore, the EtherCAT slaves are disabled and the axes are changed to unused axes.

EtherCAT

A

B

EtherCAT slaves, axes

Production line 1

C

D

E

Production line 2

EtherCAT slaves, axes

Production line 1 is left running while EtherCAT slaves C, D, and E on production line 2 are removed.
Procedure
The operating procedure for the sample programming is as follows:
1 The operator presses a button on an HMI to turn ON the execution condition. 2 The Controller disables EtherCAT slaves C, D, and E. Also, the axes for those slaves are
changed to unused axes.
3 When disabling and changing the axes to unused axes is completed for all three slaves, the
Controller lights a removal OK lamp.
4 After the operator confirms that the removal OK lamp is lit, the operator removes the three Eth-
erCAT slaves.
Instruction to Change Axes to Unused Axes
The MC_ChangeAxisUse instruction is used to change the axes to unused axes. Refer to the NJ/NXseries Motion Control Instructions Reference Manual (Cat. No. W508) or NY-series Motion Control Instructions Reference Manual (Cat. No. W561) for the detailed specifications of the MC_ChangeAxisUse instruction.

2-966

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

EtherCAT Communications Instructions

Exclusive Control of Instructions
You can execute only one EC_ChangeEnableSetting instruction at the same time. Also, the EC_ChangeEnableSetting instruction is executed over more than one task. Confirm the completion of the EC_ChangeEnableSetting instruction before you execute the next EC_ChangeEnableSetting instruction. The ExclusiveFlg variable (Instruction Exclusive Flag) is used for this purpose. If the value of ExclusiveFlg is TRUE, then an EC_ChangeEnableSetting instruction is in execution. Do not execute the next EC_ChangeEnableSetting instruction while the value of ExclusiveFlg is TRUE.
You cannot execute the EC_ChangeEnableSetting instruction at the same time as another EC_ChangeEnableSetting instruction that is in execution in another task. Therefore, ExclusiveFlg is defined as a
global variable in this sample programming. That allows this sample programming to perform exclusive 2
control with EC_ChangeEnableSetting instructions in the other tasks. The same global variable, ExclusiveFlg, must also be used in the other tasks to perform exclusive control of the instructions. Also, you cannot execute the EC_ChangeEnableSetting instruction at the same time as the EC_DisconnectSlave and EC_ConnectSlave instructions. The sample programming that is provided for the EC_DisconnectSlave instruction on page 2-954 uses the same ExclusiveFlg global variable as in this sample programming as an example of exclusive control of instructions.

EC_ChangeEnableSetting

Axis Variables and Node Addresses for the EtherCAT Slaves
The axis variables that are assigned to the axes for EtherCAT slaves C, D, and E and the node addresses of the slaves are given in the following table.

EtherCAT slaves C D E

Axis variable MC_Axis000 MC_Axis001 MC_Axis002

Node address 1 2 3

Definitions of Global Variables

Global Variables

Variable MC_Axis000 MC_Axis001 MC_Axis002 ExclusiveFlg

Data type _sAXIS_REF

Initial value

AT specification MC://_MC_AX[0]

_sAXIS_REF

MC://_MC_AX[1]

_sAXIS_REF

MC://_MC_AX[2]

BOOL

FALSE

Constant

Comment

Axis variable for EtherCAT slave C

Axis variable for EtherCAT slave D

Axis variable for EtherCAT slave E

---

Instruction Exclusive Flag

LD
Internal Variables

Variable
Operating1End Trigger1 Operating1

AxisUnuseDone_DevC

Data type
BOOL BOOL BOOL BOOL

Initial value

Comment

FALSE FALSE FALSE
FALSE

Processing completed Execution condition Processing Changing axis to unused axis completed for EtherCAT slave C

NJ/NX-series Instructions Reference Manual (W502)

2-967

2 Instruction Descriptions

Internal Variables

Variable

SlaveDisableDone_DevC

DoneHold_DevC

AxisUnuseDone_DevD

SlaveDisableDone_DevD

DoneHold_DevD

AxisUnuseDone_DevE

SlaveDisableDone_DevE

DoneHold_DevE
Light1On MC_ChangeAxisUse_DevC EC_ChangeEnableSetting_DevC MC_ChangeAxisUse_DevD EC_ChangeEnableSetting_DevD MC_ChangeAxisUse_DevE EC_ChangeEnableSetting_DevE

Data type
BOOL
BOOL
BOOL
BOOL
BOOL
BOOL
BOOL
BOOL BOOL MC_ChangeAxisUse EC_ChangeEnableSetting MC_ChangeAxisUse EC_ChangeEnableSetting MC_ChangeAxisUse EC_ChangeEnableSetting

Initial value

Comment

FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE

Disabling EtherCAT slave C completed
Holding completion of processing for EtherCAT slave C
Changing axis to unused axis completed for EtherCAT slave D
Disabling EtherCAT slave D completed
Holding completion of processing for EtherCAT slave D
Changing axis to unused axis completed for EtherCAT slave E
Disabling EtherCAT slave E completed
Holding completion of processing for EtherCAT slave E
Lighting removal OK lamp

External Variables

Variable MC_Axis000

MC_Axis001

MC_Axis002 ExclusiveFlg

Data type _sAXIS_REF _sAXIS_REF _sAXIS_REF BOOL

Constant ---

Comment Axis variable for EtherCAT slave C Axis variable for EtherCAT slave D Axis variable for EtherCAT slave E Instruction Exclusive Flag

2-968

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

EtherCAT Communications Instructions

Accept execution condition trigger. Trigger1 Operating1End

Operating1

Operating1

Change axis to unused axis and disable EtherCAT slave C.

MC_ChangeAxisUse_DevC MC_ChangeAxisUse

Operating1 DoneHold_DevC

Axis MC_Axis000

Axis

AxisUnuseDone_DevC

Execute

Done

2

_mcUnusedAxis AxisUse

Busy

CommandAborted

Error

ErrorID

EC_ChangeEnableSetting

1

AxisUnuseDone_DevC ExclusiveFlg
1 UINT#1 FALSE

Exclusive control of instructions EC_ChangeEnableSetting_DevC.Busy

ExclusiveFlg S

EC_ChangeEnableSetting_DevC EC_ChangeEnableSetting SlaveDisableDone_DevC

Execute NodeAdr IsEnable

Done Busy Error ErrorID

EC_ChangeEnableSetting_DevC.Busy

ExclusiveFlg R

SlaveDisableDone_DevC Operating1End DoneHold_DevC

DoneHold_DevC

Change axis to unused axis and disable EtherCAT slave D.
Operating1 DoneHold_DevC DoneHold_DevD MC_Axis001
_mcUnusedAxis

MC_ChangeAxisUse_DevD

MC_ChangeAxisUse

Axis

Axis

Execute AxisUse

Done Busy CommandAborted Error ErrorID

AxisUnuseDone_DevD

2

AxisUnuseDone_DevD ExclusiveFlg

EC_ChangeEnableSetting_DevD

EC_ChangeEnableSetting

SlaveDisableDone_DevD

2

Execute

Done

UINT#2 NodeAdr

Busy

FALSE IsEnable

Error

ErrorID

NJ/NX-series Instructions Reference Manual (W502)

2-969

2 Instruction Descriptions

Exclusive control of instructions EC_ChangeEnableSetting_DevD.Busy
EC_ChangeEnableSetting_DevD.Busy

ExclusiveFlg S
ExclusiveFlg R

SlaveDisableDone_DevD Operating1End DoneHold_DevD

DoneHold_DevD

Change axis to unused axis and disable EtherCAT slave E.
Operating1 DoneHold_DevD DoneHold_DevE MC_Axis002
_mcUnusedAxis

MC_ChangeAxisUse_DevE

MC_ChangeAxisUse

Axis

Axis

Execute AxisUse

Done Busy CommandAborted Error ErrorID

AxisUnuseDone_DevE

3

AxisUnuseDone_DevE ExclusiveFlg
3 UINT#3 FALSE

Exclusive control of instructions EC_ChangeEnableSetting_DevE.Busy

ExclusiveFlg

EC_ChangeEnableSetting_DevE

EC_ChangeEnableSetting

SlaveDisableDone_DevE

Execute NodeAdr IsEnable

Done Busy Error ErrorID

S

EC_ChangeEnableSetting_DevE.Busy

ExclusiveFlg R

SlaveDisableDone_DevE Operating1End DoneHold_DevE

DoneHold_DevE

Confirm changing axis to unused axis and disabling EtherCAT slave E.

Operating1

DoneHold_DevE

Lighting removal OK lamp

Operating1End

Light1On

S

Operating1End

2-970

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

EtherCAT Communications Instructions

ST

Internal Variables

Variable

Data type

Initial value

Comment

Operating1End

BOOL

FALSE Processing completed

Trigger1

BOOL

FALSE Execution condition

Operating1

BOOL

FALSE Processing

Operating1Set

BOOL

FALSE Processing started

Light1On

BOOL

FALSE Lighting removal OK lamp

DoneHold_DevC

BOOL

Holding completion of proFALSE cessing for EtherCAT

DoneHold_DevD

BOOL

slave C

Holding completion of pro-

2

FALSE cessing for EtherCAT

slave D

EC_ChangeEnableSetting

Holding completion of pro-

DoneHold_DevE

BOOL

FALSE cessing for EtherCAT slave E

ExclusiveFlgSet

BOOL

FALSE

Instruction Exclusive Flag ON

ExclusiveFlgReset

BOOL

FALSE

Instruction Exclusive Flag OFF

R_TRIG_instance1

R_TRIG

RS_instance1

RS

SR_instance1

SR

MC_ChangeAxisUse_DevC MC_ChangeAxisUse

EC_ChangeEnableSetting_DevC

EC_ChangeEnableSetting

R_TRIG_DevC

R_TRIG

F_TRIG_DevC

F_TRIG

RS_ExFlg_DevC

RS

RS_DevC

RS

MC_ChangeAxisUse_DevD MC_ChangeAxisUse

EC_ChangeEnableSetting_DevD

EC_ChangeEnableSetting

R_TRIG_DevD

R_TRIG

F_TRIG_DevD

F_TRIG

RS_ExFlg_DevD

RS

RS_DevD

RS

MC_ChangeAxisUse_DevE MC_ChangeAxisUse

EC_ChangeEnableSetting_DevE

EC_ChangeEnableSetting

R_TRIG_DevE

R_TRIG

F_TRIG_DevE

F_TRIG

RS_ExFlg_DevE

RS

RS_DevE

RS

External Variables

Variable

MC_Axis000

MC_Axis001

MC_Axis002 ExclusiveFlg

Data type _sAXIS_REF _sAXIS_REF _sAXIS_REF BOOL

Constant ---

Comment
Axis variable for EtherCAT slave C Axis variable for EtherCAT slave D Axis variable for EtherCAT slave E Instruction Exclusive Flag

NJ/NX-series Instructions Reference Manual (W502)

2-971

2 Instruction Descriptions

// Accept execution condition trigger. R_TRIG_instance1(Trigger1, Operating1Set); RS_instance1(
Set :=Operating1Set, Reset1:=Operating1End, Q1 =>Operating1);
// Change axis to unused axis for EtherCAT slave C. MC_ChangeAxisUse_DevC(
Axis :=MC_Axis000, Execute:=(Operating1 & NOT(DoneHold_DevC)), AxisUse:=_mcUnusedAxis);
// Disable EtherCAT slave C. EC_ChangeEnableSetting_DevC(
Execute :=(Operating1 & MC_ChangeAxisUse_DevC.Done & NOT(ExclusiveFlg)), NodeAdr :=UINT#1, IsEnable:=FALSE);
// Exclusive control of instructions R_TRIG_DevC(EC_ChangeEnableSetting_DevC.Busy, ExclusiveFlgSet); F_TRIG_DevC(EC_ChangeEnableSetting_DevC.Busy, ExclusiveFlgReset); RS_ExFlg_DevC(
Set :=ExclusiveFlgSet, Reset1:=ExclusiveFlgReset, Q1 =>ExclusiveFlg); RS_DevC( Set :=EC_ChangeEnableSetting_DevC.Done, Reset1:=Operating1End, Q1 =>DoneHold_DevC);
// Change axis to unused axis for EtherCAT slave D. MC_ChangeAxisUse_DevD(
Axis :=MC_Axis001, Execute:=(Operating1 & DoneHold_DevC & NOT(DoneHold_DevD)), AxisUse:=_mcUnusedAxis);
// Disable EtherCAT slave D. EC_ChangeEnableSetting_DevD(
Execute :=(Operating1 & DoneHold_DevC & MC_ChangeAxisUse_DevD.Done & NOT(ExclusiveFlg)),
NodeAdr :=UINT#2, IsEnable:=FALSE);
// Exclusive control of instructions R_TRIG_DevD(EC_ChangeEnableSetting_DevD.Busy, ExclusiveFlgSet); F_TRIG_DevD(EC_ChangeEnableSetting_DevD.Busy, ExclusiveFlgReset); RS_ExFlg_DevD(
Set :=ExclusiveFlgSet, Reset1:=ExclusiveFlgReset, Q1 =>ExclusiveFlg); RS_DevD( Set :=EC_ChangeEnableSetting_DevD.Done, Reset1:=Operating1End, Q1 =>DoneHold_DevD);
// Change axis to unused axis for EtherCAT slave E. MC_ChangeAxisUse_DevE(
Axis :=MC_Axis002, Execute:=(Operating1 & DoneHold_DevD & NOT(DoneHold_DevE)), AxisUse:=_mcUnusedAxis);
// Disable EtherCAT slave E. EC_ChangeEnableSetting_DevE(

2-972

NJ/NX-series Instructions Reference Manual (W502)

EtherCAT Communications Instructions

2 Instruction Descriptions

Execute :=(Operating1 & DoneHold_DevD & MC_ChangeAxisUse_DevE.Done & NOT(ExclusiveFlg)),
NodeAdr :=UINT#3, IsEnable:=FALSE);

// Exclusive control of instructions

R_TRIG_DevE(EC_ChangeEnableSetting_DevE.Busy, ExclusiveFlgSet);

F_TRIG_DevE(EC_ChangeEnableSetting_DevE.Busy, ExclusiveFlgReset);

RS_ExFlg_DevE(

Set :=ExclusiveFlgSet,

Reset1:=ExclusiveFlgReset,

Q1 =>ExclusiveFlg);

RS_DevE(

Set :=EC_ChangeEnableSetting_DevE.Done, Reset1:=Operating1End,

2

Q1 =>DoneHold_DevE);

// Confirm changing axis to unused axis and disabling EtherCAT slave E. Operating1End:=(Operating1 & DoneHold_DevE);

// Lighting removal OK lamp SR_instance1(
Set1:=Operating1End, Q1 =>Light1On);

EC_ChangeEnableSetting

 Example of Connecting EtherCAT Slaves to an EtherCAT Network
Production line 1 from the previous example is left running while EtherCAT slaves F and G are installed on production line 2. Motion control axes are set for EtherCAT slaves F and G. Therefore, the EtherCAT slaves are enabled and the axes are changed to used axes.

EtherCAT

A

B

EtherCAT slaves, axes

Production line 1

F

G

EtherCAT slaves, axes

Production line 2

Production line 1 is left running while EtherCAT slaves F and G are installed on production line 2.
Procedure
The operating procedure for the sample programming is as follows:
1 The operator uses the following procedure to install EtherCAT slaves F and G. 2 The operator presses a button on an HMI to turn ON the execution condition.

NJ/NX-series Instructions Reference Manual (W502)

2-973

2 Instruction Descriptions

3 The Controller enables EtherCAT slaves F and G. Also, the axes for those slaves are changed to
used axes.
4 When enabling and changing the axes to used axes is completed for the two EtherCAT slaves,
the Controller lights an installation completed lamp.
Instruction to Change Axes to Used Axes
The MC_ChangeAxisUse instruction is used to change axes to used axes. Refer to the NJ/NX-series Motion Control Instructions Reference Manual (Cat. No. W508) or NY-series Motion Control Instructions Reference Manual (Cat. No. W561) for the detailed specifications of the MC_ChangeAxisUse instruction.

Exclusive Control of Instructions
You can execute only one EC_ChangeEnableSetting instruction at the same time. Also, the EC_ChangeEnableSetting instruction is executed over more than one task. Confirm the completion of the EC_ChangeEnableSetting instruction before you execute the next EC_ChangeEnableSetting instruction. The ExclusiveFlg variable (Instruction Exclusive Flag) is used for this purpose. If the value of ExclusiveFlg is TRUE, then an EC_ChangeEnableSetting instruction is in execution. Do not execute the next EC_ChangeEnableSetting instruction while the value of ExclusiveFlg is TRUE.
You cannot execute the EC_ChangeEnableSetting instruction at the same time as another EC_ChangeEnableSetting instruction that is in execution in another task. Therefore, ExclusiveFlg is defined as a global variable in this sample programming. That allows this sample programming to perform exclusive control with EC_ChangeEnableSetting instructions in the other tasks. The same global variable, ExclusiveFlg, must also be used in the other tasks to perform exclusive control of the instructions.
Also, you cannot execute the EC_ChangeEnableSetting instruction at the same time as the EC_DisconnectSlave and EC_ConnectSlave instructions. The sample programming that is provided for the EC_DisconnectSlave instruction on page 2-954 uses the same ExclusiveFlg global variable as in this sample programming as an example of exclusive control of instructions.

Axis Variables and Node Addresses for the EtherCAT Slaves
The axis variables that are assigned to the axes for EtherCAT slaves F and G and the node addresses of the slaves are given in the following table.

EtherCAT slaves F G

Axis variable Node address MC_Axis003 4 MC_Axis004 5

Definitions of Global Variables

Global Variables

Variable

Data type

MC_Axis003 _sAXIS_REF

Initial value

AT specification

MC://_MC_AX[3]

MC_Axis004 _sAXIS_REF

MC://_MC_AX[4]

ExclusiveFlg BOOL

FALSE

Constant ---

Comment
Axis variable for EtherCAT slave F Axis variable for EtherCAT slave G Instruction Exclusive Flag

2-974

NJ/NX-series Instructions Reference Manual (W502)

EtherCAT Communications Instructions

2 Instruction Descriptions

LD

Internal Variables

Variable

Data type

Initial value

Comment

Operating2End

BOOL

FALSE

Processing completed

Trigger2

BOOL

FALSE Execution condition

Operating2

BOOL

FALSE Processing

Changing axis to

AxisUseDone_DevF

BOOL

FALSE

used axis completed for EtherCAT

slave F

SlaveEnableDone_DevF

BOOL

FALSE

Enabling EtherCAT slave F completed

2

DoneHold_DevF

BOOL

Holding completion FALSE of processing for

EC_ChangeEnableSetting

EtherCAT slave F

AxisUseDone_DevG

BOOL

FALSE

Changing axis to used axis completed for EtherCAT slave G

SlaveEnableDone_DevG

BOOL

FALSE

Enabling EtherCAT slave G completed

Holding completion

DoneHold_DevG

BOOL

FALSE of processing for EtherCAT slave G

Light2On

BOOL

FALSE

Lighting installation completed lamp

MC_ChangeAxisUse_DevF

MC_ChangeAxisUse

EC_ChangeEnableSetting_DevF EC_ChangeEnableSetting

MC_ChangeAxisUse_DevG

MC_ChangeAxisUse

EC_ChangeEnableSetting_DevG EC_ChangeEnableSetting

External Variables

Variable

MC_Axis003

MC_Axis004 ExclusiveFlg

Data type _sAXIS_REF _sAXIS_REF BOOL

Constant ---

Comment
Axis variable for EtherCAT slave F Axis variable for EtherCAT slave G Instruction Exclusive Flag

NJ/NX-series Instructions Reference Manual (W502)

2-975

2 Instruction Descriptions

Accept execution condition trigger. Trigger2 Operating2End
Operating2

Operating2

Enable EtherCAT slave F. Operating2 ExclusiveFlg DoneHold_DevF

UINT#4 TRUE

EC_ChangeEnableSetting_DevF

EC_ChangeEnableSetting

Execute

Done

NodeAdr

Busy

IsEnable

Error

ErrorID

Exclusive control of instructions. Start enabling EtherCAT slave F and confirm completion.

EC_ChangeEnableSetting_DevF.Busy

ExclusiveFlg

S

EC_ChangeEnableSetting_DevF.Busy

ExclusiveFlg R

SlaveEnableDone_DevF

Change axis to used axis for EtherCAT slave F.
Operating2 SlaveEnableDone_DevF DoneHold_DevF MC_Axis003 _mcUsedAxis

MC_ChangeAxisUse_DevF

MC_ChangeAxisUse

Axis

Axis

Execute AxisUse

Done Busy CommandAborted Error ErrorID

Exclusive control of instructions. Confirm that all processing for EtherCAT slave F is completed. Operating2 AxisUseDone_DevF Operating2End DoneHold_DevF

AxisUseDone_DevF

DoneHold_DevF

Enable EtherCAT slave G. Operating2 DoneHold_DevF ExclusiveFlg DoneHold_DevG
1

EC_ChangeEnableSetting_DevG

EC_ChangeEnableSetting

SlaveEnableDone_DevG

1

Execute

Done

UINT#5 NodeAdr

Busy

TRUE

IsEnable

Error

ErrorID

2-976

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

EtherCAT Communications Instructions

Exclusive control of instructions. Start enabling EtherCAT slave G and confirm completion.

EC_ChangeEnableSetting_DevG.Busy

ExclusiveFlg

S

EC_ChangeEnableSetting_DevG.Busy

ExclusiveFlg R

Change axis to used axis for EtherCAT slave G.

MC_ChangeAxisUse_DevG

MC_ChangeAxisUse

Operating2 SlaveEnableDone_DevG DoneHold_DevG MC_Axis004 Axis

Axis

AxisUseDone_DevG

2

Execute _mcUsedAxis AxisUse

Done Busy

CommandAborted

Error

ErrorID

Exclusive control of instructions. Confirm that all processing for EtherCAT slave G is completed. Operating2 AxisUseDone_DevG Operating2End DoneHold_DevG

EC_ChangeEnableSetting

DoneHold_DevG

Confirm completion of processing for EtherCAT slave G

Operating2 DoneHold_DevG

Operating2End

Lighting installation completed lamp

Operating2End

Light2On

S

ST
Internal Variables

Variable

Operating2End

Trigger2 Operating2 Operating2Set

Light2On

DoneHold_DevF

DoneHold_DevG
ExclusiveFlgSet
ExclusiveFlgReset R_TRIG_instance2 RS_instance2 SR_instance2 MC_ChangeAxisUse_DevF
NJ/NX-series Instructions Reference Manual (W502)

Data type
BOOL BOOL BOOL BOOL BOOL
BOOL
BOOL
BOOL
BOOL R_TRIG RS SR MC_ChangeAxisUse

Initial value

Comment

FALSE FALSE FALSE FALSE FALSE
FALSE
FALSE
FALSE FALSE

Processing completed
Execution condition
Processing
Processing started
Lighting installation completed lamp
Holding completion of processing for EtherCAT slave F
Holding completion of processing for EtherCAT slave G
Instruction Exclusive Flag ON
Instruction Exclusive Flag OFF

2-977

2 Instruction Descriptions

Internal Variables

Variable
EC_ChangeEnableSetting_DevF R_TRIG_DevF F_TRIG_DevF RS_ExFlg_DevF RS_DevF MC_ChangeAxisUse_DevG EC_ChangeEnableSetting_DevG R_TRIG_DevG F_TRIG_DevG RS_ExFlg_DevG RS_DevG

Data type
EC_ChangeEnableSetting R_TRIG F_TRIG RS RS MC_ChangeAxisUse EC_ChangeEnableSetting R_TRIG F_TRIG RS RS

Initial value

Comment

External Variables

Variable

MC_Axis003

MC_Axis004 ExclusiveFlg

Data type _sAXIS_REF _sAXIS_REF BOOL

Constant ---

Comment
Axis variable for EtherCAT slave F Axis variable for EtherCAT slave G Instruction Exclusive Flag

// Accept execution condition trigger. R_TRIG_instance2(Trigger2, Operating2Set); RS_instance2(
Set :=Operating2Set, Reset1:=Operating2End, Q1 =>Operating2);
// Enable EtherCAT slave F. EC_ChangeEnableSetting_DevF(
Execute :=(Operating2 & NOT(ExclusiveFlg) & NOT(DoneHold_DevF)), NodeAdr :=UINT#4, IsEnable:=TRUE);
// Exclusive control of instructions. Start enabling EtherCAT slave F and confirm // completion. R_TRIG_DevF(EC_ChangeEnableSetting_DevF.Busy, ExclusiveFlgSet); F_TRIG_DevF(EC_ChangeEnableSetting_DevF.Busy, ExclusiveFlgReset); RS_ExFlg_DevF(
Set :=ExclusiveFlgSet, Reset1:=ExclusiveFlgReset, Q1 =>ExclusiveFlg);
// Change axis to used axis for EtherCAT slave F. MC_ChangeAxisUse_DevF(
Axis :=MC_Axis003, Execute:=(Operating2 & EC_ChangeEnableSetting_DevF.Done & NOT(DoneHold_DevF)), AxisUse:=_mcUsedAxis);
// Exclusive control of instructions. Confirm that all processing for EtherCAT // slave F is completed. RS_DevF(
Set :=(Operating2 & MC_ChangeAxisUse_DevF.Done), Reset1:=Operating2End, Q1 =>DoneHold_DevF);
// Enable EtherCAT slave G. EC_ChangeEnableSetting_DevG(

2-978

NJ/NX-series Instructions Reference Manual (W502)

EtherCAT Communications Instructions

2 Instruction Descriptions

Execute :=(Operating2 & DoneHold_DevF & NOT(ExclusiveFlg) & NOT(DoneHold_DevG)),
NodeAdr :=UINT#5, IsEnable:=TRUE);

// Exclusive control of instructions. Start enabling EtherCAT slave F and confirm // completion. R_TRIG_DevG(EC_ChangeEnableSetting_DevG.Busy, ExclusiveFlgSet); F_TRIG_DevG(EC_ChangeEnableSetting_DevG.Busy, ExclusiveFlgReset); RS_ExFlg_DevG(
Set :=ExclusiveFlgSet, Reset1:=ExclusiveFlgReset, Q1 =>ExclusiveFlg);

// Change axis to used axis for EtherCAT slave G.

2

MC_ChangeAxisUse_DevG(

Axis :=MC_Axis004,

Execute:=(Operating2 & EC_ChangeEnableSetting_DevG.Done & NOT(DoneHold_DevG)),

AxisUse:=_mcUsedAxis);

EC_ChangeEnableSetting

// Exclusive control of instructions. Confirm that all processing for EtherCAT // slave G is completed. RS_DevG(
Set :=(Operating2 & MC_ChangeAxisUse_DevG.Done), Reset1:=Operating2End, Q1 =>DoneHold_DevG);

// Confirm completion of processing for EtherCAT slave G Operating2End:=Operating2 & DoneHold_DevG;

// Lighting installation completed lamp SR_instance2(
Set1:=Operating2End, Q1 =>Light2On);

NJ/NX-series Instructions Reference Manual (W502)

2-979

2 Instruction Descriptions

NX_WriteObj

The NX_WriteObj instruction writes data to an NX object in an EtherCAT Coupler Unit or NX Unit.

Instruction NX_WriteObj

Name
Write NX Unit Object

FB/FUN FB

Graphic expression

NX_WriteObj_instance

NX_WriteObj

Execute UnitProxy Obj TimeOut WriteDat

Done Busy Error ErrorID ErrorIDEx

ST expression
NX_WriteObj_instance(Execute, UnitProxy, Obj, TimeOut, WriteDat, Done, Busy, Error, ErrorID, ErrorIDEx);

Variables

Name UnitProxy Obj TimeOut
WriteDat

Meaning Specified Unit Object parameter Timeout time

I/O Input

Write data

Description

Valid range

Unit to which to write data

---

Object parameter

Timeout time

0 to 60,000

If 0 is set, the timeout time is 2.0 s.

Data to write to NX object

Depends on data type.

* If you omit the input parameter, the default value is not applied. A building error will occur.

Unit ---
ms
---

Default * --2000 (2.0s)
*

Bit strings

Integers

Times, durations, dates, and text strings

Real numbers

Boolean BOOL

STRING DT TOD
DATE TIME

LREAL REAL

LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE

UnitProxy Obj TimeOut WriteDat

Refer to Function for details on the structure _sNXUNIT_ID. Refer to Function for details on the structure _sNXOBJ_ACCESS.
OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK
An array can also be specified.

Function
The NX_WriteObj instruction writes the contents of WriteDat to an NX object in an EtherCAT Coupler Unit, an NX Unit on the EtherCAT Coupler Unit, or an NX Unit connected to the NX bus of the CPU Unit. The Unit for which to write the data is specified with UnitProxy.
TimeOut specifies the timeout time. If a response does not return within the timeout time, it is assumed that communications failed. In that case, the data is not written.

2-980

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

EtherCAT Communications Instructions

The data type of UnitProxy is structure _sNXUNIT_ID. The meanings of the members are as follows:

Name

Meaning

Content

Data type

UnitProxy

Specified Unit Specified Unit

_sNXUNIT_ID

NodeAdr

Node address Node address of the

UINT

Communications Coupler Unit

IPAdr

IP address IP address of the Com- BYTE[5]

munications Coupler Unit

UnitNo

Unit number Unit number of specified Unit

UDINT

Path

Path

Path information to the BYTE[64]

specified Unit

2

PathLength Valid path

Valid path length

USINT

length

Pass the device variable that is assigned to the specified Unit to UnitProxy.

NX_WriteObj

The data type of Obj is structure _sNXOBJ_ACCESS. The meanings of the members are as follows:

Name Obj

Meaning
Object parameter

Index Subindex IsCompleteAccess*1

Index Subindex Complete access

Description Object parameter
Index Subindex Complete access

Data type _sNXOBJ _ACCESS UINT USINT BOOL

Valid range ---
Depends on data type. FALSE only

Unit Default --- ---
--- 0
FALSE

*1 This member is not used for this instruction. Always set the value to FALSE.

Related Instructions and Execution Procedure
Depending on the attributes of the data that you write to an EtherCAT Coupler Unit, an NX Unit on the EtherCAT Coupler Unit, or an NX Unit connected to the NX bus of the CPU Unit, you must execute this instruction along with other instructions. The procedures for each case are given below.
 Execution Procedure 1
Use the following procedure to write data with the following attributes. · Power OFF Retain attribute · The values are updated when the Unit is restarted.
1 Use the NX_ChangeWriteMode instruction (page 2-874) to change the Unit to a mode that
allows writing data.
2 Use the NX_WriteObj instruction to write data to the Unit. 3 Use the NX_SaveParam instruction (page 2-879) to save the data that you wrote. 4 Use the RestartNXUnit instruction (page 2-868) to restart the Unit.
 Execution Procedure 2
Use the following procedure to write data with the following attributes. · Power OFF Retain attribute · The values are updated as soon as they are written.

NJ/NX-series Instructions Reference Manual (W502)

2-981

2 Instruction Descriptions

1 Use the NX_WriteObj instruction to write data to the Unit. 2 Use the NX_SaveParam instruction (page 2-879) to save the data that you wrote.
 Execution Procedure 3
Use the following procedure to write data with the following attributes. · No Power OFF Retain attribute
1 Use the NX_WriteObj instruction to write data to the Unit.

Notation Example

The following notation example shows how to set the NX-OD4121 Digital Output Unit to hold the present value of the output when the load becomes disconnected.

A variable that is named `NX1' with a data type of _sNXUNIT_ID is assigned to the Unit to which to write the data.

For the NX-OD4121, the index of the Load OFF Output Setting parameter is UINT#16#5011 and the subindex is USINT#1.

To hold the present value, BYTE#16#01 is written to the Load Rejection Output Setting parameter.

LD

ST

NX_WriteObj_instance

A

NX_WriteObj

abc

Execute

Done

NX1 UnitProxy

Busy def

S_Obj Obj

Error ghi

UINT#0 TimeOut

ErrorID jkl

W_Dat WriteDat ErrorIDEx mno

NX_WriteObj_instance(A, NX1, S_Obj, UINT#0, W_Dat, abc, def, ghi, jkl, mno);

Built-in EtherCAT port

Contents of Object Parameter S_Obj

S_Obj.Index

UINT#16#5011

S_Obj.Subindex USINT#1

Contents of Write Data W_dat W_dat BYTE#16#01
NX1

The NX-OD4121 Digital Output Unit is set to hold the present value of the output when the load becomes disconnected.
EtherCAT Coupler Unit
NX-OD4121 Digital Output Unit

2-982

NJ/NX-series Instructions Reference Manual (W502)

EtherCAT Communications Instructions

2 Instruction Descriptions

Related System-defined Variables

Name

Meaning

Data type

Description

_EC_MBXSlavTbl[i]

Message Communica-

BOOL

"i" is the node address. tions Enabled Slave Table

This variable indicates whether communications are possible for each slave.
TRUE: Communications are possible.

FALSE: Communications are not possible.

NX Unit Message Enabled BOOL

This table indicates the slaves that can perform

_NXB_UnitMsgActiveTbl Status

message communications.

[i]

Use this variable to confirm that communications

with the relevant slave are possible.
2

NX_WriteObj

Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section (page 2-3) for a timing chart for Execute, Done, Busy, and Error.
· If WriteDat is an array, make sure that the overall size of the array is the same as the size of the NX object to write in the specified Unit.
· For UnitProxy, specify the device variable that is assigned to an EtherCAT Coupler Unit, an NX Unit on the EtherCAT Coupler Unit, or an NX Unit connected to the NX bus of the CPU Unit in the I/O Map of the Sysmac Studio. Refer to the Sysmac Studio Version 1 Operation Manual (Cat. No. W504-E107 or later) for details on assigning device variables.
· Always use a variable for the parameter to pass to WriteDat. A building error will occur if a constant is passed.
· To write and save data with a Power OFF Retain attribute, execute the NX_SaveParam instruction (page 2-879) after you execute the NX_WriteObj instruction. If you restart the Unit before you execute the NX_SaveParam instruction, the previous NX object data is restored.
· This instruction is related to NX Message Communications Errors. If too many instructions that are related to NX Message Communications Errors are executed at the same time, an NX Message Communications Error will occur. Refer to Instructions Related to NX Message Communications Errors (page A-25) for a list of the instructions that are related to NX Message Communications Errors.

NJ/NX-series Instructions Reference Manual (W502)

2-983

2 Instruction Descriptions

· Error is TRUE if an error occurred. The meanings of the values of ErrorID and ErrorIDEx are given in the following table.

Value of ErrorID 16#0400 16#0419 16#041B
16#2C00

Value of ErrorIDEx
16#0000 0000 16#0000 0000 16#0000 0000 16#0000 0401 16#0000 1001 16#0000 1002 16#0017 0000 16#0020 0000 16#0021 0000 16#0000 1010 16#0000 1101 16#0000 110B 16#0000 1110 16#0000 1111 16#0000 2101 16#0000 2110 16#0000 2210 16#0000 2213
16#0000 2230
16#0000 2231
16#0000 250F 16#0000 2601 16#0000 2602 16#0010 0000
16#0000 2603
16#0000 2621
16#0001 0000 16#0011 0000

Meaning
· The value of UnitProxy is outside of the valid range. · The value of TimeOut is outside of the valid range. · The data type of UnitProxy is not correct. · The data type of WriteDat is not correct. More than 2,048 bytes of data was specified for WriteDat. The specified Unit does not support the instruction. An input parameter, output parameter, or in-out parameter is incorrect. Confirm that the intended parameter is used for the input parameter, output parameter, or in-out parameter.
The data size of the specified NX object does not agree with the data size specified in WriteDat. The correct Unit was not specified. Check the Unit. The size of the read data is too large. Make sure that the read data specification is correct. There is no object that corresponds to the value of Obj.Index. There is no object that corresponds to the value of Obj.Subindex. The specified NX object cannot be written. The value of WriteDat exceeds the range of the values of the NX object to write. The specified Unit is not in a mode that allows writing data. Instruction execution was not possible because the specified Unit was performing an I/O check. Execute the instruction after the I/O check is completed. The status of the specified Unit does not agree with the value of the read source or write destination NX object. Take the following actions if the value of Obj.Index is between 0x6000 and 0x6FFF or between 0x7000 and 0x7FFF.
· Delete the read source or write designation NX object from the I/O allocation settings.
· Reset the error for the specified Unit. · Place the specified Unit in a mode that does not allow writing data. Instruction execution was not possible because the specified Unit was performing initialization. Wait for the Unit to start normal operation and then execute the instruction. Hardware access failed. Execute the instruction again. The specified Unit does not support this instruction. Check the version of the Unit.
Execution of the instruction failed. Execute the instruction again. Make sure that at least one channel is enabled in the selections of the channels to use. The NX Unit is not in a status in which it can acknowledge the instruction. Wait for a while and then execute the instruction again. The specified Unit does not exist. Make sure that the Unit configuration is correct. The specified port number does not exist. Make sure that the Unit configuration is correct.

2-984

NJ/NX-series Instructions Reference Manual (W502)

EtherCAT Communications Instructions

2 Instruction Descriptions

Value of ErrorID

Value of ErrorIDEx

Meaning

16#0012 0000 16#0013 0000

The value of UnitProxy is not correct. Set the variable that indicates the specified EtherCAT Coupler Unit

16#0015 0000 16#0016 0000

again.

16#0014 0000

The specified node address is not correct. Make sure that the Unit configuration is correct.

16#0030 0000 16#8001 0000

The specified Unit is busy. Execute the instruction again.

16#0031 0000

The specified Unit not supported for connection. Check the version of the Unit.

16#80000000 16#80050000

An error occurred in the communications network. Execute the instruction again.

2

16#81010000

NX_WriteObj

16#2C00

16#81020000 16#82020000 16#82030000 16#82060000 to

16#8FFF0000 16#90010000

to 16#FFFE0000

16#8002 0000 16#8003 0000

An error occurred in the communications network. Reduce the amount of communications traffic.

16#8103 0000 16#8200 0000

16#8004 0000

An error occurred in the communications network.

16#8100 0000 16#8201 0000

Check the Unit and cable connections. Make sure that the power supply to the Unit is ON.

16#8204 0000 16#8205 0000 16#9000 0000

16#2C01

16#0000 0000

The number of instructions that can be simultaneously executed was exceeded.

16#2C02

16#0000 0000

A timeout occurred during communications.

16#2C03

16#0000 0000

The size of the send message is not correct.

A CPU Unit with unit version 1.05 or later and Sysmac Studio version 1.06 or higher are required to use this instruction.

NJ/NX-series Instructions Reference Manual (W502)

2-985

2 Instruction Descriptions

Sample Programming
 Example for Writing Data with Power OFF Retain Attribute That Is Updated at Unit Restart for an NX Unit

The following programming sets the Ch1 Input Moving Average Time object parameter for an NXAD2203 AC Input Unit connected to an EtherCAT Coupler Unit to 500 s.
The node address of the EtherCAT Coupler Unit is 10.

The specifications of the Ch1 Input Moving Average Time object parameter are as follows:

Item Index Subindex Setting for 500 s

Value 16#5004 16#01 2

The Ch1 Input Moving Average Time object parameter has a Power OFF Retain Attribute and it is updated when the Unit is restarted. Therefore, the following procedure is used.

1 Use the NX_ChangeWriteMode instruction to change the Unit to a mode that allows writing
data.

2 Use the NX_WriteObj instruction to write data to the Unit.

3 Use the NX_SaveParam instruction to save the data that you wrote.

4 Use the RestartNXUnit instruction to restart the Unit.

LD

Internal Variables

Variable

Data type

Initial value

Comment

Trigger ChangeCondition WriteCondition SaveCondition RestartCondition NXUnitProxy NXUnitProxy_Coupler
NXObject
VarWriteData NX_ChangeWriteMode _instance NX_WriteObj_instance NX_SaveParam_instance RestartNXUnit_instance

BOOL BOOL BOOL BOOL BOOL _sNXUNIT_ID _sNXUNIT_ID
_sNXOBJ_ACCESS
UINT NX_ChangeWriteMode NX_WriteObj NX_SaveParam RestartNXUnit

FALSE FALSE FALSE FALSE FALSE
(Index:=0, Subindex:=0, IsCompleteAccess:=FALSE) 0

Execution condition Execution condition to change write mode Execution condition to write data Execution condition to save data Execution condition to restart Unit Unit designation for DC Input Unit Unit designation for EtherCAT Coupler Unit
Object parameter
Write data

External Variables

Variable

Constant

Data type

Comment

_EC_MBXSlavTbl

ARRAY[1..512] OF BOOL Message Communications Enabled Slave

*1

Table

*1 For the NX102 CPU Units, NX1P2 CPU Units, and NJ-series CPU Units, the data type is ARRAY [1..192] OF BOOL.

2-986

NJ/NX-series Instructions Reference Manual (W502)

EtherCAT Communications Instructions

2 Instruction Descriptions

Prepare object parameter.

Trigger

UINT#16#5004

@MOVE

EN

ENO

In

Out

NXObject.Index

USINT#16#01

@MOVE

EN

ENO

In

Out

NXObject.Subindex

Prepare write data. Trigger

@MOVE

EN

ENO

UINT#2 In

Out VarWriteData

2

Execute NX_ChangeWriteMode instruction. Trigger NX_ChangeWriteMode_instance.Done NX_ChangeWriteMode_instance.Error ChangeCondition

NX_WriteObj

ChangeCondition

ChangeCondition

_EC_MBXSlavTbl[10] NXUnitProxy

NX_ChangeWriteMode_instance

NX_ChangeWriteMode

Execute UnitProxy

Done Busy Error ErrorID ErrorIDEx

Execute NX_WriteObj instruction. NX_ChangeWriteMode_instance.Done NX_WriteObj_instance.Done NX_WriteObj_instance.Error

WriteCondition

WriteCondition

WriteCondition

_EC_MBXSlavTbl[10]
NXUnitProxy NXObject
UINT#2000 VarWriteData

NX_WriteObj_instance

NX_WriteObj

Execute UnitProxy Obj TimeOut WriteDat

Done Busy Error ErrorID ErrorIDEx

Execute NX_SaveParam instruction. NX_WriteObj_instance.Done NX_SaveParam_instance.Done NX_SaveParam_instance.Error SaveCondition

SaveCondition

SaveCondition

_EC_MBXSlavTbl[10]
NXUnitProxy UINT#2000

NX_SaveParam_instance

NX_SaveParam

Execute UnitProxy TimeOut

Done Busy Error ErrorID ErrorIDEx

NJ/NX-series Instructions Reference Manual (W502)

2-987

2 Instruction Descriptions

Execute RestartNXUnit instruction. NX_SaveParam_instance.Done RestartNXUnit_instance.Done RestartNXUnit_instance.Error

RestartCondition

RestartCondition

RestartCondition _EC_MBXSlavTbl[10] NXUnitProxy_Coupler

RestartNXUnit_instance

RestartNXUnit

Execute UnitProxy

Done Busy Error ErrorID ErrorIDEx

Processing after normal end. RestartNXUnit_instance.Done

Inline ST
1 // Processing after normal end. 2 ;

Processing after error end. NX_ChangeWriteMode_instance.Error
NX_WriteObj_instance.Error

Inline ST
1 // Processing after error end. 2 ;

NX_SaveParam_instance.Error

RestartNXUnit_instance.Error

2-988

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

EtherCAT Communications Instructions

ST

Internal Variables

Variable

Data type

Initial value

Comment

Trigger

BOOL

FALSE

Execution condition

ChangeCondition

BOOL

FALSE

Execution condition to change write mode

ChangeGo

BOOL

FALSE

Execution of change to write mode

WriteCondition

BOOL

FALSE

Execution condition to write data

WriteGo

BOOL

FALSE

Execution of data write

SaveCondition

BOOL

FALSE

Execution condition to save data

SaveGo

BOOL

FALSE

Execution of data save

RestartCondition RestartGo

BOOL BOOL

FALSE FALSE

Execution condition to restart Unit Execution of Unit restart

2

NXUnitProxy

_sNXUNIT_ID

Unit designation for DC Input Unit

NX_WriteObj

NXUnitProxy_Coupler _sNXUNIT_ID

Unit designation for EtherCAT Coupler Unit

NXObject

_sNXOBJ_ACCESS

(Index:=0, Subindex:=0, IsCompleteAccess:=FALSE)

Object parameter

VarWriteData

UINT

0

Write data

NormalEnd

UINT

0

Normal end

ErrorEnd

UINT

0

Error end

NX_ChangeWriteMode _instance

NX_ChangeWriteMode

NX_WriteObj_instance NX_WriteObj

NX_SaveParam_instance NX_SaveParam

RestartNXUnit_instance RestartNXUnit

R_Trig_instance

R_TRIG

External Variables

Variable

Constant

Data type

Comment

_EC_MBXSlavTbl

ARRAY[1..512] OF BOOL Message Communications Enabled

*1

Slave Table

*1 For the NX102 CPU Units, NX1P2 CPU Units, and NJ-series CPU Units, the data type is ARRAY [1..192] OF BOOL.

// Prepare object parameter and write data.

R_Trig_instance(Clk := Trigger);

IF (R_Trig_instance.Q=TRUE)THEN

NXObject.Index := UINT#16#5004;

NXObject.Subindex := USINT#1;

VarWriteData

:= UINT#2;

END_IF;

// Execute NX_ChangeWriteMode instruction. IF (Trigger = TRUE) THEN
ChangeCondition := TRUE; END_IF;

IF ((NX_ChangeWriteMode_instance.Done=TRUE) OR (NX_ChangeWriteMode_instance.Error=TRUE))THEN
ChangeCondition := FALSE; END_IF;

ChangeGo := ChangeCondition & _EC_MBXSlavTbl[10]; NX_ChangeWriteMode_instance(
Execute := ChangeGo, UnitProxy := NXUnitProxy);

NJ/NX-series Instructions Reference Manual (W502)

2-989

2 Instruction Descriptions

// Execute NX_WriteObj instruction. IF (NX_ChangeWriteMode_instance.Done=TRUE) THEN
WriteCondition := TRUE; END_IF;

IF ((NX_WriteObj_instance.Done=TRUE) OR (NX_WriteObj_instance.Error=TRUE))THEN WriteCondition := FALSE;
END_IF;

WriteGo := WriteCondition & _EC_MBXSlavTbl[10];

NX_WriteObj_instance(

Execute := WriteGo,

UnitProxy := NXUnitProxy,

Obj

:= NXObject,

TimeOut := UINT#2000,

WriteDat := VarWriteData);

// Execute NX_SaveParam instruction. IF (NX_WriteObj_instance.Done=TRUE) THEN
SaveCondition := TRUE; END_IF;

IF ((NX_SaveParam_instance.Done=TRUE) OR (NX_SaveParam_instance.Error=TRUE))THEN SaveCondition := FALSE;
END_IF;

SaveGo := SaveCondition & _EC_MBXSlavTbl[10]; NX_SaveParam_instance(
Execute := SaveGo, UnitProxy := NXUnitProxy, TimeOut := UINT#2000);

// Execute RestartNXUnit instruction. IF (NX_SaveParam_instance.Done=TRUE) THEN
RestartCondition := TRUE; END_IF;

IF ((RestartNXUnit_instance.Done=TRUE) OR (RestartNXUnit_instance.Error=TRUE)) THEN
RestartCondition := FALSE; END_IF;

RestartGo := RestartCondition & _EC_MBXSlavTbl[10]; RestartNXUnit_instance(
Execute := SaveGo, UnitProxy := NXUnitProxy_Coupler);

IF (RestartNXUnit_instance.Done=TRUE) THEN // Processing after normal end. NormalEnd := NormalEnd + UINT#1;
ELSIF ((NX_ChangeWriteMode_instance.Error=TRUE) OR (NX_WriteObj_instance.Error=TRUE)
OR (NX_SaveParam_instance.Error=TRUE) OR (RestartNXUnit_instance.Error=TRUE)) THEN
// Processing after error end. ErrorEnd := ErrorEnd + UINT#1; END_IF;

2-990

NJ/NX-series Instructions Reference Manual (W502)

EtherCAT Communications Instructions

2 Instruction Descriptions

 Example for Writing Data with Power OFF Retain Attribute That Is Updated after Writing the Data

The following programming sets the Ch1 Offset Value (One-point Correction) object parameter for an NX-TS2101 Temperature Input Unit connected to an EtherCAT Coupler Unit to 0.3°C.
The node address of the EtherCAT Coupler Unit is 10.

The specifications of the Ch1 Offset Value (One-point Correction) object parameter are as follows:

Item

Value

Index

16#5010

Subindex

16#01

2

Value to write

0.3

NX_WriteObj

The Ch1 Offset Value (One-point Correction) object parameter has a Power OFF Retain Attribute and it is updated after the data is written. Therefore, the following procedure is used.
1 Use the NX_WriteObj instruction to write data to the Unit. 2 Use the NX_SaveParam instruction to save the data that you wrote.

LD

Internal Variables

Variable
Trigger WriteCondition SaveCondition NXUnitProxy

NXUnitProxy_Coupler

Data type
BOOL BOOL BOOL _sNXUNIT_ID
_sNXUNIT_ID

NXObject

_sNXOBJ_ACCESS

VarWriteData NX_WriteObj_instance NX_SaveParam_instance

Real NX_WriteObj NX_SaveParam

Initial value

Comment

FALSE FALSE FALSE
(Index:=0, Subindex:=0, IsCompleteAccess:=FALSE) 0.0

Execution condition Execution condition to write data Execution condition to save data Unit designation for AC Input Unit Unit designation for EtherCAT Coupler Unit
Object parameter
Write data

External Variables

Variable

Constant

Data type

Comment

_EC_MBXSlavTbl

ARRAY[1..512] OF BOOL Message Communications Enabled

*1

Slave Table

*1 For the NX102 CPU Units, NX1P2 CPU Units, and NJ-series CPU Units, the data type is ARRAY [1..192] OF BOOL.

NJ/NX-series Instructions Reference Manual (W502)

2-991

2 Instruction Descriptions

Prepare object parameter. Trigger
UINT#16#5010

Prepare write data. Trigger

USINT#16#01 REAL#0.3

@MOVE

EN

ENO

In

Out

@MOVE

EN

ENO

In

Out

@MOVE

EN

ENO

In

Out

NXObject.Index NXObject.Subindex VarWriteData

Execute NX_WriteObj instruction.

Trigger

NX_WriteObj_instance.Done NX_WriteObj_instance.Error WriteCondition

WriteCondition

WriteCondition

_EC_MBXSlavTbl[10]
NXUnitProxy NXObject
UINT#2000 VarWriteData

NX_WriteObj_instance

NX_WriteObj

Execute UnitProxy Obj TimeOut WriteDat

Done Busy Error ErrorID ErrorIDEx

Execute NX_SaveParam instruction. NX_WriteObj_instance.Done NX_SaveParam_instance.Done NX_SaveParam_instance.Error SaveCondition

SaveCondition

SaveCondition

_EC_MBXSlavTbl[10]
NXUnitProxy UINT#2000

NX_SaveParam_instance

NX_SaveParam

Execute

Done

UnitProxy

Busy

TimeOut

Error

ErrorID

ErrorIDEx

Processing after normal end. NX_SaveParam_instance.Done
Processing after error end. NX_WriteObj_instance.Error
NX_SaveParam_instance.Error

Inline ST 1 // Processing after normal end. 2 ;
Inline ST 1 // Processing after error end. 2 ;

2-992

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

EtherCAT Communications Instructions

ST

Internal Variables

Variable
Trigger WriteCondition WriteGo SaveCondition SaveGo

NXUnitProxy

NXUnitProxy_Coupler

Data type
BOOL BOOL BOOL BOOL BOOL
_sNXUNIT_ID
_sNXUNIT_ID

NXObject

_sNXOBJ_ACCESS

VarWriteData NormalEnd ErrorEnd NX_WriteObj_instance NX_SaveParam_instance R_Trig_Instance

REAL UINT UINT NX_WriteObj NX_SaveParam R_TRIG

Initial value

Comment

FALSE

Execution condition

FALSE

Execution condition to write data

FALSE

Execution of data write

FALSE

Execution condition to save data

FALSE

Execution of data save

Unit designation for Temperature

Input Unit

Unit designation for EtherCAT Cou-

pler Unit

(Index:=0,

2

Subindex:=0, IsCompleteAc-

Object parameter

cess:=FALSE)

NX_WriteObj

0.0

Write data

0

Normal end

0

Error end

External Variables

Variable

Constant

Data type

Comment

_EC_MBXSlavTbl

ARRAY[1..512] OF BOOL Message Communications Enabled

*1

Slave Table

*1 For the NX102 CPU Units, NX1P2 CPU Units, and NJ-series CPU Units, the data type is ARRAY [1..192] OF BOOL.

// Prepare object parameter and write data.

R_Trig_instance(Clk := Trigger);

IF (R_Trig_instance.Q=TRUE)THEN

NXObject.Index := UINT#16#5004;

NXObject.Subindex := USINT#1;

VarWriteData

:= UINT#2;

END_IF;

// Execute NX_WriteObj instruction. IF (Trigger=TRUE) THEN
WriteCondition := TRUE; END_IF;

IF ((NX_WriteObj_instance.Done=TRUE) OR (NX_WriteObj_instance.Error=TRUE))THEN WriteCondition := FALSE;
END_IF;

WriteGo := WriteCondition & _EC_MBXSlavTbl[10];

NX_WriteObj_instance(

Execute := WriteGo,

UnitProxy := NXUnitProxy,

Obj

:= NXObject,

TimeOut := UINT#2000,

WriteDat := VarWriteData);

// Execute NX_SaveParam instruction. IF (NX_WriteObj_instance.Done=TRUE) THEN
SaveCondition := TRUE; END_IF;

IF ((NX_SaveParam_instance.Done=TRUE) OR (NX_SaveParam_instance.Error=TRUE))THEN

NJ/NX-series Instructions Reference Manual (W502)

2-993

2 Instruction Descriptions
SaveCondition := FALSE; END_IF;
SaveGo := SaveCondition & _EC_MBXSlavTbl[10]; NX_SaveParam_instance(
Execute := SaveGo, UnitProxy := NXUnitProxy, TimeOut := UINT#2000);
IF (NX_SaveParam_instance.Done=TRUE) THEN // Processing after normal end. NormalEnd := NormalEnd + UINT#1;
ELSIF ((NX_WriteObj_instance.Error=TRUE) OR (NX_SaveParam_instance.Error=TRUE)) THEN
// Processing after error end. ErrorEnd := ErrorEnd + UINT#1; END_IF;

2-994

NJ/NX-series Instructions Reference Manual (W502)

EtherCAT Communications Instructions

2 Instruction Descriptions

NX_ReadObj

The NX_ReadObj instruction reads data from an NX object in an EtherCAT Coupler Unit or NX Unit.

Instruction NX_ReadObj

Name
Read NX Unit Object

FB/FUN FB

Graphic expression

NX_ReadObj_instance

NX_ReadObj

Execute UnitProxy Obj TimeOut ReadDat

Done Busy Error ErrorID

ST expression NX_ReadObj_instance(Execute, UnitProxy, Obj, TimeOut, ReadDat, Done, Busy, Error, ErrorID, ErrorIDEx);
2

ErrorIDEx

NX_ReadObj

Variables

Name UnitProxy Obj
TimeOut

Meaning Specified Unit Object parameter Timeout time

I/O Input

Description Unit from which to read data Object parameter
Timeout time

Valid range ---
0 to 60,000

ReadDat Read data

In-out

If 0 is set, the timeout time is 2.0 s.

Data read from NX object

Depends on data type.

* If you omit the input parameter, the default value is not applied. A building error will occur.

Unit ---
ms ---

Default * ---
2000 (2.0 s) ---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE
Boolean BOOL

UnitProxy Obj TimeOut ReadDat

Refer to Function for details on the structure _sNXUNIT_ID. Refer to Function for details on the structure _sNXOBJ_ACCESS.
OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK
An array can also be specified.

Function
The NX_ReadObj instruction reads data from an NX object in an EtherCAT Coupler Unit, an NX Unit on the EtherCAT Coupler Unit, or an NX Unit connected to the NX bus of the CPU Unit and stores the data in ReadDat. The Unit from which the data is read is specified with UnitProxy.
TimeOut specifies the timeout time. If a response does not return within the timeout time, it is assumed that communications failed. In that case, the data is not read.

NJ/NX-series Instructions Reference Manual (W502)

2-995

2 Instruction Descriptions

The data type of UnitProxy is structure _sNXUNIT_ID. The meanings of the members are as follows:

Name UnitProxy
NodeAdr
IPAdr
UnitNo Path PathLength

Meaning Specified Unit Node address
IP address
Unit number Path Valid path length

Content
Specified Unit
Node address of the Communications Coupler Unit
IP address of the Communications Coupler Unit
Unit number of specified Unit
Path information to the specified Unit
Valid path length

Data type _sNXUNIT_ID UINT
BYTE[5]
UDINT BYTE[64] USINT

Pass the device variable that is assigned to the specified Unit to UnitProxy.

The data type of Obj is structure _sNXOBJ_ACCESS. The meanings of the members are as follows:

Name Obj

Meaning
Object parameter

Index Subindex IsCompleteAccess*1

Index Subindex Complete access

Content Object parameter
Index Subindex Complete access

Data type _sNXOBJ _ACCESS UINT USINT BOOL

Valid range ---
Depends on data type. FALSE only

Unit Default --- ---
--- 0
FALSE

*1 This member is not used for this instruction. Always set the value to FALSE.

Notation Example

The following notation example shows how to read the unit version from an NX-ID4342 Digital Input Unit.
The read data is stored in Rdat, which is a UDINT variable. A variable that is named `NX1' with a data type of _sNXUNIT_ID is assigned to the Unit from which to read the data.
For the NX-ID4342, the index of the Unit version is UINT#16#1000 and the subindex is USINT#6.

LD

ST

NX_ReadObj_instance

A

NX_ReadObj

abc

NX1 S_Obj UINT#0

Execute UnitProxy Obj TimeOut

Done Busy def Error ghi ErrorID jkl

Rdat

ReadDat ErrorIDEx

Rdat mno

NX_ReadObj_instance(A, NX1, S_Obj, UINT#0, Rdat, abc, def, ghi, jkl, mno);

2-996

NJ/NX-series Instructions Reference Manual (W502)

EtherCAT Communications Instructions

2 Instruction Descriptions

Contents of Object Parameter S_Obj

S_Obj.Index

UINT#4096

S_Obj.Subindex USINT#6

Built-in EtherCAT port NX1

The unit version is read from the NX-ID4342 Digital Input Unit and stored in Rdat (a DINT variable).

EtherCAT Coupler Unit

2

NX-ID4342 Digital Input Unit

NX_ReadObj

NJ/NX-series Instructions Reference Manual (W502)

2-997

2 Instruction Descriptions

Related System-defined Variables

Variable _EC_MBXSlavTbl[i] "i" is the node address.
_NXB_UnitMsgActiveTbl[i]

Name
Message Communications Enabled Slave Table

Data type
BOOL

NX Unit Message Enabled Status

BOOL

Description
This variable indicates whether communications are possible for each slave. TRUE: Communications are possible. FALSE: Communications are not possible. This table indicates the slaves that can perform message communications. Use this variable to confirm that communications with the relevant slave are possible.

Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section (page 2-3) for a timing chart for Execute, Done, Busy, and Error.
· If ReadDat is an array, make sure that the overall size of the array is the same as the size of the NX object to read in the specified Unit
· For UnitProxy, specify the device variable that is assigned to an EtherCAT Coupler Unit, an NX Unit on the EtherCAT Coupler Unit, or an NX Unit connected to the NX bus of the CPU Unit in the I/O Map of the Sysmac Studio. Refer to the Sysmac Studio Version 1 Operation Manual (Cat. No. W504-E107 or later) for details on assigning device variables.
· This instruction is related to NX Message Communications Errors. If too many instructions that are related to NX Message Communications Errors are executed at the same time, an NX Message Communications Error will occur. Refer to Instructions Related to NX Message Communications Errors (page A-25) for a list of the instructions that are related to NX Message Communications Errors.

2-998

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

EtherCAT Communications Instructions

· Error is TRUE if an error occurred. The meanings of the values of ErrorID and ErrorIDEx are given in the following table.

Value of ErrorID Value of ErrorIDEx

Meaning

16#0400

16#0000 0000

· The value of UnitProxy is outside of the valid range. · The value of TimeOut is outside of the valid range.

16#0410

16#0000 0000

ReadDat is STRING data and it does not end in a NULL character.

16#0419

16#0000 0000

· The data type of UnitProxy is not correct. · The data type of ReadDat is not correct.

16#041C

16#0000 0000

The size of ReadDat is not the same as the size of the NX object to read.

16#0000 0401

The specified Unit does not support the instruction.

16#0000 1001 16#0000 1002

An input parameter, output parameter, or in-out parameter is incorrect.

2

16#0017 0000 16#0020 0000

Confirm that the intended parameter is used for the input parameter, output parameter, or in-out parameter.

NX_ReadObj

16#0021 0000

16#0000 1010

The data size of the specified NX object does not agree with the data size specified in WriteDat.

16#0000 1101

The correct Unit was not specified. Check the Unit.

16#0000 110B

The size of the read data is too large. Make sure that the read data specification is correct.

16#0000 1110

There is no object that corresponds to the value of Obj.Index.

16#0000 1111

There is no object that corresponds to the value of Obj.Subindex.

16#0000 2101

The specified NX object cannot be written.

16#0000 2110

The value of WriteDat exceeds the range of the values of the NX object to write.

16#0000 2210

The specified Unit is not in a mode that allows writing data.

16#0000 2213

Instruction execution was not possible because the specified Unit was performing an I/O check. Execute the instruction after the I/O check is completed.

The status of the specified Unit does not agree with the value of the

16#2C00

read source or write destination NX object. Take the following actions if the value of Obj.Index is between 0x6000 and 0x6FFF or between 0x7000 and 0x7FFF.

16#0000 2230
16#0000 2231 16#0000 250F 16#0000 2601 16#0000 2602 16#0010 0000 16#0000 2603
16#0000 2621 16#0001 0000

· Delete the read source or write designation NX object from the I/O allocation settings.
· Reset the error for the specified Unit. · Place the specified Unit in a mode that does not allow writing
data. Instruction execution was not possible because the specified Unit was performing initialization. Wait for the Unit to start normal operation and then execute the instruction. Hardware access failed. Execute the instruction again. The specified Unit does not support this instruction. Check the version of the Unit.
Execution of the instruction failed. Execute the instruction again. Make sure that at least one channel is enabled in the selections of the channels to use. The NX Unit is not in a status in which it can acknowledge the instruction. Wait for a while and then execute the instruction again. The specified Unit does not exist. Make sure that the Unit configuration is correct.

NJ/NX-series Instructions Reference Manual (W502)

2-999

2 Instruction Descriptions

Value of ErrorID
16#2C00
16#2C01 16#2C02

Value of ErrorIDEx
16#0011 0000
16#0012 0000 16#0013 0000 16#0015 0000 16#0016 0000
16#0014 0000
16#0030 0000 16#8001 0000
16#0031 0000
16#80000000 16#80050000 16#81010000 16#81020000 16#82020000 16#82030000 16#82060000 to 16#8FFF0000 16#90010000 to 16#FFFE0000 16#8002 0000 16#8003 0000 16#8103 0000 16#8200 0000 16#8004 0000 16#8100 0000 16#8201 0000 16#8204 0000 16#8205 0000 16#9000 0000
16#0000 0000
16#0000 0000

Meaning The specified port number does not exist. Make sure that the Unit configuration is correct. The value of UnitProxy is not correct. Set the variable that indicates the specified EtherCAT Coupler Unit again.
The specified node address is not correct. Make sure that the Unit configuration is correct. The specified Unit is busy. Execute the instruction again. The specified Unit is not supported for connection. Check the version of the Unit. An error occurred in the communications network. Execute the instruction again.
An error occurred in the communications network. Reduce the amount of communications traffic.
An error occurred in the communications network. Check the Unit and cable connections. Make sure that the power supply to the Unit is ON.
The number of instructions that can be simultaneously executed was exceeded. A timeout occurred during communications.

Version Information
A CPU Unit with unit version 1.05 or later and Sysmac Studio version 1.06 or higher are required to use this instruction.

2-1000

NJ/NX-series Instructions Reference Manual (W502)

EtherCAT Communications Instructions

2 Instruction Descriptions

Sample Programming
This sample reads the value of the I/O Refresh Method 1 object parameter from an NX-ECC201 EtherCAT Coupler Unit. The node address of the EtherCAT Coupler Unit is 10.

The values of the index and subindex of the I/O Refresh Method 1 object parameter are as follows:

Item

Value

Index

16#4002

Subindex

16#01

2

NX_ReadObj

LD

Internal Variables

Variable

Trigger

ReadCondition

NXUnitProxy

NXObject

IoRefreshMethod NX_ReadObj_instance

Data type BOOL BOOL _sNXUNIT_ID _sNXOBJ_ACCESS USINT NX_ReadObj

Initial value

Comment

FALSE FALSE
(Index:=0, Subindex:=0, IsCompleteAccess:=FALSE) 0

Execution condition Execution condition to read data Unit designation
Object parameter
Read data

External Variables

Variable

Constant

Data type

Comment

_EC_MBXSlavTbl

ARRAY[1..512] OF BOOL Message Communications Enabled

*1

Slave Table

*1 For the NX102 CPU Units, NX1P2 CPU Units, and NJ-series CPU Units, the data type is ARRAY [1..192] OF BOOL.

NJ/NX-series Instructions Reference Manual (W502)

2-1001

2 Instruction Descriptions

Prepare object parameter. Trigger
UINT#16#4002
USINT#16#01

@MOVE

EN

ENO

In

Out

@MOVE

EN

ENO

In

Out

NXObject.Index NXObject.Subindex

Execute NX_ReadObj instruction.

Trigger

NX_ReadObj_instance.Done

NX_ReadObj_instance.Error

ReadCondition

ReadCondition

ReadCondition _EC_MBXSlavTbl[10]

NX_ReadObj_instance NX_ReadObj

NXUnitProxy NXObject
UINT#2000
IoRefreshMethod

Execute UnitProxy Obj TimeOut ReadDat

Done Busy Error ErrorID

Processing after normal end. NX_ReadObj_instance.Done

Inline ST

ErrorIDEx

1 // Processing after normal end. 2 ;

IoRefreshMethod

Processing after error end. NX_ReadObj_instance.Error

Inline ST
1 // Processing after error end. 2 ;

2-1002

NJ/NX-series Instructions Reference Manual (W502)

EtherCAT Communications Instructions

2 Instruction Descriptions

ST

Internal Variables

Variable

Data type

Initial value

Comment

Trigger

BOOL

FALSE

Execution condition

ReadCondition

BOOL

FALSE

Execution condition to read data

ReadGo

BOOL

FALSE

Execution of data read

NXUnitProxy

_sNXUNIT_ID

Unit designation

NXObject

_sNXOBJ_ACCESS

(Index:=0,

Subindex:=0, IsCompleteAc-

Object parameter

cess:=FALSE)

IoRefreshMethod

USINT

0

Read data

NormalEnd

UINT

0

Normal end

2

ErrorEnd

UINT

0

Error end

R_Trig_instance

R_Trig

NX_ReadObj_instance

NX_ReadObj

NX_ReadObj

External Variables

Variable

Constant

Data type

Comment

_EC_MBXSlavTbl

ARRAY[1..512] OF BOOL Message Communications Enabled

*1

Slave Table

*1 For the NX102 CPU Units, NX1P2 CPU Units, and NJ-series CPU Units, the data type is ARRAY [1..192] OF BOOL.

// Prepare object parameter. R_Trig_instance(Clk := Trigger); IF (R_Trig_instance.Q=TRUE)THEN
NXObject.Index := UINT#16#4002; NXObject.Subindex := USINT#1; END_IF;

// Execute NX_ReadObj instruction. IF (Trigger=TRUE) THEN
ReadCondition := TRUE; END_IF;

IF ( (NX_ReadObj_instance.Done=TRUE) OR (NX_ReadObj_instance.Error=TRUE) ) THEN ReadCondition := FALSE;
END_IF;

ReadGo := ReadCondition & _EC_MBXSlavTbl[10];

NX_ReadObj_instance(

Execute := ReadGo,

UnitProxy := NXUnitProxy,

Obj

:= NXObject,

TimeOut := UINT#2000,

ReadDat := IoRefreshMethod);

// Processing after instruction execution. IF (NX_ReadObj_instance.Done=TRUE) THEN
// Processing after normal end. NormalEnd := NormalEnd + UINT#1; ELSIF (NX_ReadObj_instance.Error=TRUE) THEN // Processing after error end. ErrorEnd := ErrorEnd + UINT#1; END_IF;

NJ/NX-series Instructions Reference Manual (W502)

2-1003

2 Instruction Descriptions

2-1004

NJ/NX-series Instructions Reference Manual (W502)

IO-Link Communications Instruction

2
IO-Link Communications Instruction

Instruction IOL_ReadObj IOL_WriteObj

Name Read IO-Link Device Object Write IO-Link Device Object

Page 2-1006 2-1015

NJ/NX-series Instructions Reference Manual (W502)

2 - 1005

2 Instruction Descriptions

IOL_ReadObj

The IOL_ReadObj instruction reads data from IO-Link device objects.

Instruction

Name

FB/ FUN

IOL_ReadObj

Read IO-Link Device Object

FB

Graphic expression

IOL_ReadObj_instance

IOL_ReadObj

Execute

Done

DevicePort

Busy

DeviceObj

Error

RetryCfg ReadDat

ErrorID

ErrorType ReadSize

ST expression
IOL_ReadObj_instance( Execute, DevicePort, DeviceObj, RetryCfg, ReadDat, Done, Busy, Error, ErrorID, ErrorType, ReadSize);

Version Information
A CPU Unit with unit version 1.12 or later and Sysmac Studio version 1.16 or higher are required to use this instruction.

Variables

Meaning

I/O

DevicePort Device port

DeviceObj RetryCfg

IO-Link device object parameter
Execution retry setting

Input

ReadDat Read data In-out

ErrorType ReadSize

Error type
Read data size

Output

Description
Object that represents a device port

Valid range ---

Specification for the IO-Link device object

---

Unit ---
---

Setting for the instruction execution retry
Data read from IO-Link device
Error code that is returned by IO-Link device is stored when ErrorID is 4800 hex.
Size of data stored in ReadDat

---

---

Depends on data type. ---

16#0000 to 16#FFFF ---

10#1 to 10#232

Bytes

Default -----
--0 -----

2-1006

NJ/NX-series Instructions Reference Manual (W502)

IO-Link Communications Instruction
STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

2 Instruction Descriptions

Bit strings

Integers

Times, durations, dates, and text strings

DevicePort

Refer to Function for details on the structure _sDEVICE_PORT.

DeviceObj

Refer to Function for details on the structure _sIOLOBJ_ACCESS.

RetryCfg

Refer to Function for details on the structure _sIOL_RETRY_CFG.

ReadDat

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK

2

An array can also be specified.

ErrorType

OK

ReadSize

OK

IOL_ReadObj

Function
The IOL_ReadObj instruction reads object data from IO-Link devices.

For the DevicePort input variable, set the IO-Link master unit and the port number to which the target IO-Link device for reading is connected.
The data type of the DevicePort input variable is structure _sDEVICE_PORT. The specifications are as follows:

Name DevicePort
DeviceType NxUnit EcatSlave OptBoard Reserved
PortNo

Meaning Device port
Device type
Specified Unit Specified slave Specified Option Board Reserved
Port number

Description Object that represents a device port
Type of the device to specify
NX Unit to control EtherCAT slave to control
Option Board to control
Reserved Port number 1: Port 1 2: Port 2 3: Port 3 4: Port 4 5: Port 5 6: Port 6 7: Port 7 8: Port 8

Data type _sDEVICE_PORT
_eDEVICE_TYPE
_sNXUNIT_ID _sECAT_ID _sOPTBOAR D_ID ---
USINT

Valid range --_DeviceNXUnit _DeviceEcatSlave _DeviceOptionBoard -----
-----
Depends on data type.

Unit ---
-----------
---

Default ---
-----------
---

NJ/NX-series Instructions Reference Manual (W502)

2-1007

2 Instruction Descriptions

Use DeviceType to specify the device type. Specify _DeviceNXUnit for an NX type of IO-Link master unit and _DeviceEcatSlave for a GX type of IO-Link master unit. The variable used to specify the device is determined by the specified device type.
For this instruction, it is determined as follows:
To specify the NX type, use NxUnit to specify the device. In this case, EcatSlave is not used. To NxUnit, pass the device variable that is assigned to the device to specify.
To specify the GX type, use EcatSlave to specify the device. In this case, NxUnit is not used. To EcatSlave, pass the device variable that is assigned to the device to specify.

Use PortNo to set the port number to which the IO-Link device is connected. The number of ports differs depending on the type of IO-Link master unit. NX type: 1 to 4 GX type: 1 to 8

The data type of DeviceType is enumerated type _eDEVICE_TYPE. The meanings of the enumerators of enumerated type _eDEVICE_TYPE are as follows:

Enumerator _DeviceNXUnit _DeviceEcatSlave

Meaning NX Unit is specified. EtherCAT slave is specified.

Use the DeviceObj input variable to specify the object parameter for the IO-Link device from which data is read.
The data type of the DeviceObj input variable is structure _sIOLOBJ_ACCESS. The specifications are as follows:

Name DeviceObj
Index Subindex

Meaning
IO-Link device object parameter

Description
Specification for the IOLink device object

Data type
_sIOLOBJ_ACCESS

Index

Index

UINT

Subindex

Set 0 to read from the entire index.

USINT

Valid range
---
Depends on data type. Depends on data type.

Unit Default

---

---

---

---

---

---

Use the RetryCfg input variable to set retry processing for instruction execution. The data type of RetryCfg is structure _sIOL_RETRY_CFG. The specifications are as follows:

Name RetryCfg
TimeOut
RetryNum

Meaning Execution retry setting
Timeout time
Number of retries

Description
Setting for the instruction execution retry
2.0 s when the timeout time is set to 0
3 times if the number of retries at timeout is set to 0

Data type _sIOL_RETRY_CFG TIME
UINT

Valid range ---
0 to 300 s
Depends on data type.

Unit Default

---

---

---

T#2.0s

Times 3

Data read from the IO-Link device is stored in the ReadDat in-out variable.

2-1008

NJ/NX-series Instructions Reference Manual (W502)

IO-Link Communications Instruction

2 Instruction Descriptions

Timing Charts
The following figures show the timing charts.

 Normal end

Execute TRUE FALSE

Busy TRUE

*1

FALSE

Done TRUE FALSE

Error TRUE

*2

2

FALSE

ErrorID

Cleared to 0. Updated to result. (16#0000: Normal)

IOL_ReadObj

ErrorType
*1 Reading completed. *2 Task period

Cleared to 0. Updated to result. (16#0000: Normal)

 Error end

Execute

TRUE FALSE

Busy

TRUE FALSE

Done

TRUE FALSE

Error

TRUE FALSE

ErrorID

*1 Cleared to 0. Updated to result. (16#****: Error)

ErrorType *1 Task period

Cleared to 0. Updated to result. (16#****: Error)

Related System-defined Variables

Name

Meaning

Data type

Description

_EC_MBXSlavTbl

Message Communications Enabled Slave Table

ARRAY[1..512] OF BOOL*1

This table indicates the slaves that can perform message communications.
Slaves are given in the table in the order of slave node addresses.
TRUE: Communications are possible.

FALSE: Communications are not possible.

*1 For the NX102 CPU Units, NX1P2 CPU Units, and NJ-series CPU Units, the data type is ARRAY [1..192] OF BOOL.

NJ/NX-series Instructions Reference Manual (W502)

2-1009

2 Instruction Descriptions
Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· For DevicePort.NxUnit and DevicePort.EcatSlave, specify the device variable that is assigned to the IO-Link master unit in the I/O Map of the Sysmac Studio. Refer to the Sysmac Studio Version 1 Operation Manual (Cat. No. W504-E1-07 or later) for details on assigning device variables.
· The size of the variable specified for ReadDat must be larger than the size of the object that is actually read.
· If ReadDat is STRING data, specify a variable whose size is the sum of the actually read string and a NULL character.
· If ReadDat is STRING data, the size that is output to ReadSize does not include the NULL character. · Always use a variable for the parameter to pass to ReadDat. A building error will occur if a constant is
passed. · You can execute only one instruction at a time for the IO-Link master unit regardless of its type (NX or
GX). · You cannot use this instruction in an event task. A compiling error will occur. · This instruction is executed when Execute changes to TRUE. The instruction is not executed when
Execute is always TRUE. · You can use a maximum of 64 instances for the IOL_ReadObj and IOL_WriteObj instructions. · An error will occur in the following cases.
· A value that is out of range was set for DevicePort.NxUnit or DevicePort.EcatSlave. · The size of the IO-Link device object to read is larger than the size of ReadDat. If this error occurs,
the read data is not stored in ReadDat. · An error response was received from the IO-Link device.
The upper eight bits represent ErrorCode, and lower eight bits represent AdditionalCode. For ErrorCode and AdditionalCode, refer to the Error type specifications of the IO-Link Communication Specification. You can obtain the Error type specifications from the IO-Link Consortium. http://www.io-link.com/ · The specified IO-Link master unit does not exist. · The maximum number of messages that the IO-Link master can process is exceeded. Instruction execution is not possible because the IO-Link master is processing the messages from other applications. · The specified IO-Link master unit is not in a condition to receive messages. · More than 32 of the following instructions were executed at the same time: EC_CoESDOWrite, EC_CoESDORead, EC_StartMon, EC_StopMon, EC_SaveMon, EC_CopyMon, EC_DisconnectSlave, EC_ConnectSlave, EC_ChangeEnableSetting, IOL_ReadObj, and IOL_WriteObj. · A timeout occurred during communications. · The specified port of the IO-Link master unit is not the IO-Link mode. The port is disabled or in the SIO mode. · The IO-Link device is not connected to the specified port on the IO-Link master unit. · The IO power is not supplied to the specified port of the IO-Link master unit. · The specified port of the IO-Link master unit had a verification error or communications error.

2-1010

NJ/NX-series Instructions Reference Manual (W502)

IO-Link Communications Instruction

2 Instruction Descriptions
Sample Programming
In this sample, an IO-Link master unit (NX-ILM400) is connected to an EtherCAT Coupler Unit (NXECC203).

Built-in EtherCAT port
2

IOL_ReadObj

EtherCAT Coupler Unit NX-ECC203
NX-series IO-Link Master Unit NX-ILM400
The error log (Index:37/Subindex:0) of 30 bytes is read from the photoelectric sensor (E3Z) connected to port 1 on the NX-ILM400. The read data is stored in DeviceErrorLog. The node address of the NX-ECC203 is 10.

LD

Internal Variables

Variable Trigger

ReadCondition

DevicePort

DeviceObject

DeviceErrorLog IOL_ReadObj_instance

Data type
BOOL BOOL _sDEVICE_PORT _sIOLOBJ_ACCESS ARRAY[1..30] OF BYTE IOL_ReadObj

Initial value

Comment

FALSE FALSE

Execution condition
Data reading execution condition

(Index:=0, Sub- Specification for the IO-Link

index:=0)

device object

Read data

External Vari-
ables

Variable

Constant

Initial value

Comment

_EC_MBXSlavTbl

ARRAY[1..512] OF BOOL*1

Message Communications Enabled Slave Table

IO_LINK_Unit

Set the device variable which specifies NX-ILM400 as the initial value of the structure member NxUnit.

*1 For the NX102 CPU Units, NX1P2 CPU Units, and NJ-series CPU Units, the data type is ARRAY [1..192] OF BOOL.

NJ/NX-series Instructions Reference Manual (W502)

2-1011

2 Instruction Descriptions

Prepare object parameter. Trigger
UINT#10#37
USINT#10#0
_DeviceNXUnit
IO_LINK_Unit
USINT#10#1

@MOVE

EN

ENO

In

Out

@MOVE

EN

ENO

In

Out

@MOVE

EN

ENO

In

Out

@MOVE

EN

ENO

In

Out

@MOVE

EN

ENO

In

Out

DeviceObject.Index DeviceObject.Subindex DevicePort.DeviceType DevicePort.NxUnit DevicePort.PortNo

Trigger IOL_ReadObj_instance.Done IOL_ReadObj_instance.Error ReadCondition

ReadCondition

ReadCondition

_EC_MBXSlavTbl[10]
DevicePort DeviceObject
DeviceErrorLog

IOL_ReadObj_instance

IOL_ReadObj

Execute

Done

DevicePort Busy DeviceObj Error

RetryCfg ErrorID

ReadDat

ErrorType ReadSize

DeviceErrorLog

Processing after normal end IOL_ReadObj_instance.Done
Processing after error end IOL_ReadObj_instance.Error

Inline ST 1 // Processing after normal end 2 ;
Inline ST 1 // Processing after error end 2 ;

2-1012

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

IO-Link Communications Instruction

ST

Internal Variables

Variable

Data type

Initial value

Comment

Trigger

BOOL

FALSE

Execution condition

ReadGo

BOOL

FALSE

Data reading execution

DevicePort

_sDEVICE_PORT

DeviceObject

_sIOLOBJ_ACCESS

(Index:=0, Sub- Specification for the IO-Link

index:=0)

device object

DeviceErrorLog

ARRAY[1..30] OF BYTE

Read data
2

NormalEnd

UINT

0

Normal end

ErrorEnd

UINT

0

Error end

R_Trig_instance

R_Trig

IOL_ReadObj_instance IOL_ReadObj

IOL_ReadObj

External Vari-
ables

Variable

Constant

Initial value

Comment

_EC_MBXSlavTbl

ARRAY[1..512] OF BOOL*1

Message Communications Enabled Slave Table

IO_LINK_Unit

Set the device variable which specifies NX-ILM400 as the initial value of the structure member NxUnit.

*1 For the NX102 CPU Units, NX1P2 CPU Units, and NJ-series CPU Units, the data type is ARRAY [1..192] OF BOOL.

// Prepare object parameter. R_Trig_instance(Clk := Trigger); IF (R_Trig_instance.Q=TRUE)THEN
DeviceObject.Index := UINT#10#37; DeviceObject.Subindex := USINT#0; DevicePort.DeviceType:= _eDEVICE_TYPE#_DeviceNXUnit; DevicePort.NxUnit:= IO_LINK_Unit; DevicePort.PortNo:= USINT#10#1; IF ( _EC_MBXSlavTbl[10] =TRUE)THEN
ReadGo := TRUE; END_IF; END_IF;

IF ( (IOL_ReadObj_instance.Done=TRUE) OR (IOL_ReadObj_instance.Error=TRUE) ) THEN ReadGo:= FALSE;
END_IF;

// Execute IOL_ReadObj instruction. IOL_ReadObj_instance(
Execute := ReadGo, DevicePort:= DevicePort, DeviceObj := DeviceObject, ReadDat :=DeviceErrorLog);

// Processing after instruction execution IF (IOL_ReadObj_instance.Done=TRUE) THEN
// Processing after normal end NormalEnd := NormalEnd + UINT#1;

NJ/NX-series Instructions Reference Manual (W502)

2-1013

2 Instruction Descriptions
ELSIF (IOL_ReadObj_instance.Error=TRUE) THEN // Processing after error end ErrorEnd := ErrorEnd + UINT#1;
END_IF;

2-1014

NJ/NX-series Instructions Reference Manual (W502)

IO-Link Communications Instruction

2 Instruction Descriptions

IOL_WriteObj

The IOL_WriteObj instruction writes data to IO-Link device objects.

Instruction

Name

FB/ FUN

IOL_WriteObj

Write IO-Link Device Object

FB

Graphic expression

ST expression

IOL_WriteObj_instance(

Execute,

IOL_WriteObj_instance

IOL_WriteObj

Execute

Done

DevicePort

Busy

DeviceObj

Error

RetryCfg

ErrorID

DevicePort,

DeviceObj,

2

RetryCfg,

WriteDat,

WriteSize,

Done,

IOL_WriteObj

WriteDat WriteSize

ErrorType

Busy, Error,

ErrorID,

ErrorType);

Version Information
A CPU Unit with unit version 1.12 or later and Sysmac Studio version 1.16 or higher are required to use this instruction.

Variables

Meaning

I/O

Description

Valid range

Unit

DevicePort Device port

Object that represents a device port

---

---

IO-Link

DeviceObj

device object

Specification for the IO-Link device object

---

---

parameter

RetryCfg

Execution retry setting

Input

Setting for the instruction execution retry

---

---

WriteDat Write data

Data written to IO-Link device

Depends on data type. ---

WriteSize

Write data size

Write data size*1

10#1 to 10#232

Bytes

ErrorType Error type Output

Error code that is returned by IO-Link device is stored 16#0000 to 16#FFFF --when ErrorID is 4800 hex.

*1 Input 1 if the written data is a BOOL data. Input the number of elements if the written data is a BOOL array.

Default -----
---------

NJ/NX-series Instructions Reference Manual (W502)

2-1015

2 Instruction Descriptions

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

Bit strings

Integers

Times, durations, dates, and text strings

DevicePort DeviceObj RetryCfg
WriteDat
WriteSize ErrorType

Refer to Function for details on the structure _sDEVICE_PORT. Refer to Function for details on the structure _sIOLOBJ_ACCESS. Refer to Function for details on the structure _sIOL_RETRY_CFG. OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK
An array can also be specified. OK OK

Function
The IOL_WriteObj instruction writes object data to IO-Link devices.

For the DevicePort input variable, set the IO-Link master unit and the port number to which the target IO-Link device for writing is connected.
The data type of the DevicePort input variable is structure _sDEVICE_PORT. The specifications are as follows:

Name DevicePort
DeviceType NxUnit EcatSlave OptBoard Reserved
PortNo

Meaning Device port
Device type
Specified Unit Specified slave Specified Option Board Reserved
Port number

Description Object that represents a device port
Type of the device to specify
NX Unit to control EtherCAT slave to control
Option Board to control
Reserved Port number 1: Port 1 2: Port 2 3: Port 3 4: Port 4 5: Port 5 6: Port 6 7: Port 7 8: Port 8

Data type _sDEVICE_PORT
_eDEVICE_TYPE
_sNXUNIT_ID _sECAT_ID _sOPTBOAR D_ID ---
USINT

Valid range --_DeviceNXUnit _DeviceEcatSlave _DeviceOptionBoard -----
-----
Depends on data type.

Unit ---
-----------
---

Default ---
-----------
---

2-1016

NJ/NX-series Instructions Reference Manual (W502)

IO-Link Communications Instruction

2 Instruction Descriptions

Use DeviceType to specify the device type. Specify _DeviceNXUnit for an NX type of IO-Link master unit and _DeviceEcatSlave for a GX type of IO-Link master unit. The variable used to specify the device is determined by the specified device type.
For this instruction, it is determined as follows:
To specify the NX type, use NxUnit to specify the device. In this case, EcatSlave is not used. To NxUnit, pass the device variable that is assigned to the device to specify.
To specify the GX type, use EcatSlave to specify the device. In this case, NxUnit is not used. To EcatSlave, pass the device variable that is assigned to the device to specify.

Use PortNo to set the port number to which the IO-Link device is connected.

The number of ports differs depending on the type of IO-Link master unit.

NX type: 1 to 4

2

GX type: 1 to 8

IOL_WriteObj

The data type of DeviceType is enumerated type _eDEVICE_TYPE. The meanings of the enumerators of enumerated type _eDEVICE_TYPE are as follows:

Enumerator _DeviceNXUnit _DeviceEcatSlave

Meaning NX Unit is specified. EtherCAT slave is specified.

Use the DeviceObj input variable to specify the object parameter for the IO-Link device to which data is written. The data type of the DeviceObj input variable is structure _sIOLOBJ_ACCESS. The specifications are as follows:

Name DeviceObj
Index Subindex

Meaning
IO-Link device object parameter

Description
Specification for the IOLink device object

Data type
_sIOLOBJ_ACCESS

Index

Index

UINT

Subindex

Set 0 to read from the entire index.

USINT

Valid range
---
Depends on data type. Depends on data type.

Unit Default

---

---

---

---

---

---

Use the RetryCfg input variable to set retry processing for instruction execution. The data type of RetryCfg is structure _sIOL_RETRY_CFG. The specifications are as follows:

Name RetryCfg
TimeOut
RetryNum

Meaning Execution retry setting
Timeout time
Number of retries

Description
Setting for the instruction execution retry
2.0 s when the timeout time is set to 0
3 times if the number of retries at timeout is set to 0

Data type _sIOL_RETRY_CFG TIME
UINT

Valid range ---
0 to 300 s
Depends on data type.

Unit Default

---

---

---

T#2.0s

Times 3

Use the WriteDat input variable to specify the data to write to the IO-Link device.

NJ/NX-series Instructions Reference Manual (W502)

2-1017

2 Instruction Descriptions

Timing Charts
The following figures show the timing charts.

 Normal end

Execute Busy Done Error

TRUE FALSE TRUE FALSE TRUE FALSE
TRUE FALSE

ErrorID

*1
*2 Cleared to 0. Updated to result. (16#0000: Normal)

ErrorType
*1 Writing completed. *2 Task period

 Error end

Execute Busy Done Error

TRUE FALSE TRUE FALSE TRUE FALSE TRUE FALSE

ErrorID

Cleared to 0. Updated to result. (16#0000: Normal)
*1 Cleared to 0. Updated to result. (16#****: Error)

ErrorType *1 Task period

Cleared to 0. Updated to result. (16#****: Error)

Related System-defined Variables

Name

Name

Data type

Description

_EC_MBXSlavTbl

Message Communications Enabled Slave Table

ARRAY[1..512] OF BOOL*1

This table indicates the slaves that can perform message communications.
Slaves are given in the table in the order of slave node addresses.
TRUE: Communications are possible.

FALSE: Communications are not possible. *1 For the NX102 CPU Units, NX1P2 CPU Units, and NJ-series CPU Units, the data type is ARRAY [1..192] OF BOOL.

2-1018

NJ/NX-series Instructions Reference Manual (W502)

IO-Link Communications Instruction

2 Instruction Descriptions

Precautions for Correct Use

· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.

· For DevicePort.NxUnit and DevicePort.EcatSlave, specify the device variable that is assigned to the IO-Link master unit in the I/O Map of the Sysmac Studio. Refer to the Sysmac Studio Version 1 Operation Manual (Cat. No. W504-E1-07 or later) for details on assigning device variables.

· Always use a variable for the parameter to pass to WriteDat. A building error will occur if a constant is passed.

· You can execute only one instruction at a time for the IO-Link master unit regardless of its type (NX or

GX).

2

· You cannot use this instruction in an event task. A compiling error will occur.

IOL_WriteObj

· This instruction is executed when Execute changes to TRUE. The instruction is not executed when Execute is always TRUE.

· You can use a maximum of 64 instances for the IOL_ReadObj and IOL_WriteObj instructions.

· An error will occur in the following cases.

· A value that is out of range was set for DevicePort.NxUnit or DevicePort.EcatSlave.

· The value of TimeOut is outside of the valid range.

· The data type of DevicePort is invalid.

· More than 232 bytes of data was specified for WriteDat.

· An error response was received from the IO-Link device. The upper eight bits represent ErrorCode, and lower eight bits represent AdditionalCode. For ErrorCode and AdditionalCode, refer to the Error type specifications of the IO-Link Communication Specification. You can obtain the Error type specifications from the IO-Link Consortium. http://www.io-link.com/

· The specified IO-Link master unit does not exist.

· The maximum number of messages that the IO-Link master can process is exceeded. Instruction execution is not possible because the IO-Link master is processing the messages from other applications.

· The specified IO-Link master unit is not in a condition to receive messages.

· More than 32 of the following instructions were executed at the same time: EC_CoESDOWrite, EC_CoESDORead, EC_StartMon, EC_StopMon, EC_SaveMon, EC_CopyMon, EC_DisconnectSlave, EC_ConnectSlave, EC_ChangeEnableSetting, IOL_ReadObj, and IOL_WriteObj.

· A timeout occurred during communications.

· The specified port of the IO-Link master unit is not the IO-Link mode. The port is disabled or in the SIO mode.

· The IO-Link device is not connected to the specified port on the IO-Link master unit.

· The IO power is not supplied to the specified port of the IO-Link master unit.

· The specified port of the IO-Link master unit had a verification error or communications error.

NJ/NX-series Instructions Reference Manual (W502)

2-1019

2 Instruction Descriptions
Sample Programming
In this sample, an IO-Link master unit (NX-ILM400) is connected to an EtherCAT Coupler Unit (NXECC203).
Built-in EtherCAT port

EtherCAT Coupler Unit NX-ECC203
NX-series IO-Link Master Unit NX-ILM400
The value 01 is written to the one-byte SwitchPoint Logic Output 1 (Index: 61/Subindex: 1) of the photoelectric sensor (E3Z) connected to port 1 on the NX-ILM400. The written data is stored in SwitchPoint. The node address of the NX-ECC203 is 10.

LD

Internal Variables

Variable Trigger

WriteCondition

DevicePort

DeviceObject

SwitchPoint IOL_WriteObj_instance

Data type
BOOL BOOL _sDEVICE_PORT _sIOLOBJ_ACCESS USINT IOL_WriteObj

Initial value

Comment

FALSE FALSE

Execution condition
Data writing execution condition

(Index:=0, Sub- Specification for the IO-Link

index:=0)

device object

USINT#01

Write data

External Vari-
ables

Variable

_EC_MBXSlavTbl

IO_LINK_Unit

Constant

Initial value

Comment

ARRAY[1..512] OF BOOL*1

Message Communications Enabled Slave Table

Set the device variable which specifies NX-ILM400 as the initial value of the structure member NxUnit.

*1 For the NX102 CPU Units, NX1P2 CPU Units, and NJ-series CPU Units, the data type is ARRAY [1..192] OF BOOL.

2-1020

NJ/NX-series Instructions Reference Manual (W502)

IO-Link Communications Instruction

2 Instruction Descriptions

Prepare object parameter. Trigger
UINT#10#61

@MOVE

EN

ENO

In

Out

DeviceObject.Index

USINT#10#1

@MOVE

EN

ENO

In

Out

DeviceObject.Subindex

@MOVE

EN

ENO

_DeviceNXUnit

In

Out

DevicePort.DeviceType

2

IOL_WriteObj

IO_LINK_Unit

@MOVE

EN

ENO

In

Out

DevicePort.NxUnit

USINT#10#1

@MOVE

EN

ENO

In

Out

DevicePort.PortNo

Trigger

IOL_WriteObj_instance.Done IOL_WriteObj_instance.Error WriteCondition

WriteCondition

WriteCondition

_EC_MBXSlavTbl[10]
DevicePort DeviceObject
SwitchPoint UINT#10#1

IOL_WriteObj_instance

IOL_WriteObj

Execute

Done

DevicePort

Busy

DeviceObj

Error

RetryCfg

ErrorID

WriteDat ErrorType

WriteSize

Processing after normal end IOL_WriteObj_instance.Done
Processing after error end IOL_WriteObj_instance.Error

Inline ST 1 // Processing after normal end 2 ;
Inline ST 1 // Processing after error end 2 ;

NJ/NX-series Instructions Reference Manual (W502)

2-1021

2 Instruction Descriptions

ST

Internal Variables

Variable
Trigger WriteGo DevicePort

DeviceObject

SwitchPoint NormalEnd ErrorEnd R_Trig_instance IOL_WriteObj_instance

Data type
BOOL BOOL _sDEVICE_PORT
_sIOLOBJ_ACCESS
USINT UINT UINT R_Trig IOL_WriteObj

Initial value

Comment

FALSE FALSE

Execution condition Data writing execution

(Index:=0, Sub- Specification for the IO-Link

index:=0)

device object

USINT#01

Write data

0

Normal end

0

Error end

External Vari-
ables

Variable

Constant

Initial value

Comment

_EC_MBXSlavTbl

ARRAY[1..512] OF BOOL*1

Message Communications Enabled Slave Table

IO_LINK_Unit

Set the device variable which specifies NX-ILM400 as the initial value of the structure member NxUnit.

*1 For the NX102 CPU Units, NX1P2 CPU Units, and NJ-series CPU Units, the data type is ARRAY [1..192] OF BOOL.

// Prepare object parameter. R_Trig_instance(Clk := Trigger); IF (R_Trig_instance.Q=TRUE)THEN
DeviceObject.Index := UINT#10#61; DeviceObject.Subindex := USINT#1; DevicePort.DeviceType:= _eDEVICE_TYPE#_DeviceNXUnit; DevicePort.NxUnit:= IO_LINK_Unit; DevicePort.PortNo:= USINT#10#1; IF ( _EC_MBXSlavTbl[10] =TRUE)THEN
WriteGo := TRUE; END_IF; END_IF;
IF ( (IOL_WriteObj_instance.Done=TRUE) OR (IOL_WriteObj_instance.Error=TRUE) ) THEN WriteGo := FALSE;
END_IF;
// Execute IOL_WriteObj instruction. IOL_WriteObj_instance(
Execute := WriteGo, DevicePort:= DevicePort, DeviceObj := DeviceObject, WriteDat := SwitchPoint, WriteSize := UINT#10#1);
// Processing after instruction execution IF (IOL_WriteObj_instance.Done=TRUE) THEN
// Processing after normal end

2-1022

NJ/NX-series Instructions Reference Manual (W502)

IO-Link Communications Instruction

NormalEnd := NormalEnd + UINT#1; ELSIF (IOL_WriteObj_instance.Error=TRUE) THEN
// Processing after error end ErrorEnd := ErrorEnd + UINT#1; END_IF;

2 Instruction Descriptions

2

IOL_WriteObj

NJ/NX-series Instructions Reference Manual (W502)

2-1023

2 Instruction Descriptions

2-1024

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

2
EtherNet/IP Communications Instructions

Instruction CIPOpen
CIPOpenWithDataSize
CIPRead

Name
Open CIP Class 3 Connection (Large_Forward_Open)
Open CIP Class 3 Connection with Specified Data Size
Read Variable Class 3 Explicit

Page

Instruction

2-1026 SktGetTCPStatus

2-1035 SktClose

2-1039 SktClearBuf

CIPWrite CIPSend

Write Variable Class 3 Explicit 2-1045 SktSetOption Send Explicit Message Class 3 2-1051 ModbusTCPCmd

CIPClose

Close CIP Class 3 Connection 2-1056 ModbusTCPRead

CIPUCMMRead

Read Variable UCMM Explicit 2-1059 ModbusTCPWrite

CIPUCMMWrite CIPUCMMSend SktUDPCreate SktUDPRcv SktUDPSend SktTCPAccept SktTCPConnect SktTCPRcv SktTCPSend

Write Variable UCMM Explicit Send Explicit Message UCMM Create UDP Socket UDP Socket Receive UDP Socket Send Accept TCP Socket Connect TCP Socket TCP Socket Receive TCP Socket Send

2-1064 2-1071 2-1081 2-1089 2-1092 2-1095 2-1098 2-1107 2-1110

ChangeIPAdr ChangeFTPAccount ChangeNTPServerAdr FTPGetFileList FTPGetFile FTPPutFile FTPRemoveFile FTPRemoveDir

Name Read TCP Socket Status

Page 2-1113

Close TCP/UDP Socket

2-1116

Clear TCP/UDP Socket Receive Buffer Set TCP Socket Option Send Modbus TCP General Command Send Modbus TCP Read Command Send Modbus TCP Write Command Change IP Address Change FTP Account Change NTP Server Address Get FTP Server File List Get File from FTP Server Put File onto FTP Server Delete FTP Server File Delete FTP Server Directory

2-1119
2-1122 2-1127
2-1135
2-1143
2-1151 2-1159 2-1163 2-1167 2-1184 2-1193 2-1204 2-1214

NJ/NX-series Instructions Reference Manual (W502)

2-1025

2 Instruction Descriptions

CIPOpen

Opens a CIP class 3 connection (Large_Forward_Open) with the specified remote node. The data length is set to 1,994 bytes.

Instruction CIPOpen

Name
Open CIP Class 3 Connection (Large_Forward_Open)

FB/ FUN
FB

Graphic expression

CIPOpen_instance

CIPOpen

Execute RoutePath TimeOut

Done Busy Error ErrorID ErrorIDEx Handle

ST expression
CIPOpen_instance(Execute, RoutePath, TimeOut, Done, Busy, Error, ErrorID, ErrorIDEx, Handle);

Variables

Name RoutePath
TimeOut

Meaning Route path
Timeout time

I/O Input

Description Route path
Timeout time

Handle

Handle

Output Handle

Bit strings

Integers

Valid range
Depends on data type.
1 to 65535

Unit
---
0.1 s

---

---

Default
---
20 (2 s)
---

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

RoutePath TimeOut Handle

OK OK Refer to Function for details on the structure _sCIP_HANDLE.

Function

The CIPOpen instruction opens a CIP class 3 connection (Large_Forward_Open) with a remote node on a CIP network. The remote node is specified with route path RoutePath. The data length is set to 1,994 bytes. Handle is output when the connection is open.
TimeOut specifies the connection timeout time. If a response does not return from the remote node within the connection timeout time after the CIPSend, CIPWrite, or CIPRead instruction is executed, it is assumed that communications failed. The connection timeout time is reset when the CIPRead, CIPWrite, or CIPSend instruction is executed and the remote node returns a response.

The data type of Handle is structure _sCIP_HANDLE. The specifications are as follows:

Name Handle
Handle

Meaning Handle
Handle

Description Handle
Handle

Data type
_sCIP_ HANDLE
UDINT

Valid range
---
Depends on data type.

Unit Default
--- ---
--- ---

2-1026

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

2 Instruction Descriptions

The following example is for when RoutePath is `02\192.168.250.2' and TimeOut is UINT#20. The Open CIP Class 3 Connection (Large_Forward_Open) instruction opens a CIP class 3 connection with the remote node with an IP address of 192.168.250.2. The timeout time is 2 s. The handle is assigned to variable pqr.

LD

ST

CIPOpen_instance(A, `2\192.168.250.2', UINT#20, abc,

CIPOpen_instance

def, ghi, jkl, mno, pqr);

A

CIPOpen

abc

Execute

Done

`02\192.168.250.2' RoutePath

Busy def

UINT#20 TimeOut

Error ghi

ErrorID jkl ErrorIDEx mno

2

Handle pqr

The Open CIP Class 3 Connection (Large_Forward_Open) instruction opens a CIP class 3 connection with a remote node on a CIP network. The remote node is specified with RoutePath.
IP address: 192.168.250.2
Controller that executed the instruction

CIPOpen

Handle=pqr

The connection timeout time for establishing a CIP

Class 3 connection (Large_Forward_Open) is 2 s.

The acquired handle is assigned to this variable.

If the value of ErrorID is WORD#16#1C00, the CIP message error code is stored in ErrorIDEx. The meaning and values of ErrorIDEx depend on the remote node. Refer to the manual for the remote node.

Related System-defined Variables

Name

Meaning

Data type

Description

_EIP_EtnOnlineSta*1 _EIP1_EtnOnlineSta*2 _EIP2_EtnOnlineSta*3 _EIPIn1_EtnOnlineSta*4

Online

BOOL

This variable indicates when built-in EtherNet/IP port communications can be used.
TRUE: Communications are possible.
FALSE: Communications are not possible.

*1 Use this variable name for an NJ-series CPU Unit.

*2 Use this variable name for port 1 on an NX-series CPU Unit, or for an NY-series Controller.

*3 Use this variable name for port 2 on an NX-series CPU Unit.

*4 Use this variable name for the internal port on an NY-series Controller.

Additional Information
· Refer to the following manuals for details on CIP communications. · NJ/NX-series CPU Unit Built-in EtherNet/IP Port User's Manual (Cat. No. W506) · NY-series Industrial Panel PC / Industrial Box PC Built-in EtherNet/IP Port User's Manual (Cat. No. W563)

NJ/NX-series Instructions Reference Manual (W502)

2-1027

2 Instruction Descriptions
· CJ-series EtherNet/IP Units Operation Manual for NJ-series CPU Unit (Cat. No. W495) · To establish a Forward Open connection or a connection with any given data length, use CIPOpen-
WithDataSize on page 2-1035.
Version Information
A CPU Unit with unit version 1.06 or later and Sysmac Studio version 1.07 or higher are required to use the CIPOpenWithDataSize instruction.
Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error. · You must execute this instruction or the CIPOpenWithDataSize instruction before you execute the
CIPRead, CIPWrite, or CIPSend instruction. · For this instruction, the first timeout time after a connection is established is 10 s even if the value of
TimeOut is set to less than 100 (10 s). · Use the CIPClose instruction to close connections that were opened with the CIPOpen instruction. · Even if the connection times out, the handle created by this instruction will remain. Always use the
CIPClose instruction to close the connection. · Handles that are created with this instruction are disabled when you change to PROGRAM mode. · You can create a maximum of 32 handles at the same time. · You can use this instruction only through a built-in EtherNet/IP port on an NY-series Controller or an
NJ/NX-series CPU Unit, or through a port on an EtherNet/IP Unit connected to an NJ-series CPU Unit. · An error occurs in the following cases. Error will change to TRUE. · The value of TimeOut is outside of the valid range. · The text string in RoutePath is not valid. · More than 32 CIP-related instructions were executed simultaneously. · An attempt was made to open a connection beyond the CIPClass connection resources (32 con-
nections). · A connection opened response was not received. · The remote node to which to open a connection does not support Large_Forward_Open. · There is a setting error for the local IP address. · A duplicated IP error occurred. · All TCP connections are already in use. · The instruction was executed when there was a BOOTP server error.
Version Information For CPU Unit version 1.10 or later, the value of Handle does not change even if Error changes to TRUE. For version 1.09 or earlier, the value of Handle changes to 0.

2-1028

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

CIPOpen

2 Instruction Descriptions

Sample Programming

This sample uses CIP class 3 messages to write a variable, read a variable, and send a message. The Controllers are connected to an EtherNet/IP network. The IP address of the remote node is 192.168.250.2. The following procedure is used.
1 The CIPOpen is used to open a class 3 connection (Large_Forward_Open). The timeout time is 2 s.
2 The CIPWrite instruction is used to write the value of a variable at a remote node. The variable name at the remote node is WritingDat and the contents of the WriteDat is written to it. WritingDat must be defined as a global variable at the remote node and the Network Publish attribute 2 must be set.
3 The CIPRead instruction is used to read the value of a variable at a remote node. The value of the variable OriginalDat at the other node is read and the read value is stored in the ReadDat variable. OriginalDat must be defined as a global variable at the remote node and the Network Publish attribute must be set.
4 The CIPSend instruction is used to send an explicit message to a remote node. The contents of the message is to read identity information (product name). The class ID, instance ID, attribute ID, and service code are as follows: The response data is stored in the ResDat variable.

Item

Value

Class ID

1

Instance ID

1

Attribute ID

7

Service code

16#0E

5 The CIPClose instruction is used to close the class 3 connection.

IP address: 192.168.250.2

Built-in EtherNet/IP port

Built-in EtherNet/IP port

Wr iteDat

Variable name: WritingValue of variable written. Dat, global variable with a
Network Publish attribute

ReadDat ResDat

Value of variable read.

Variable name: OriginalDat, global variable with a Network Publish attribute

Message sent to read identity information (product name).

Response

NJ/NX-series Instructions Reference Manual (W502)

2-1029

2 Instruction Descriptions

LD
Variable OperatingEnd Trigger Operating WriteDat ReadDat

Data type BOOL BOOL BOOL INT INT

ReqPath

_sREQUEST_PATH

ResDat Dummy RS_instance CIPOpen_instance CIPWrite_instance CIPRead_instance CIPSend_instance CIPClose_instance

ARRAY[0..10] OF BYTE BYTE RS CIPOpen CIPWrite CIPRead CIPSend CIPClose

Initial value FALSE FALSE FALSE 1234 0 (ClassID:=0, InstanceID:=0, isAttributeID:=FALSE, AttributeID:=0) [11(16#0)] 16#0

Comment Processing completed Execution condition Processing Write data Read data
Request path
Response data Dummy

Determine if instruction execution is completed.

CIPWrite_instance.Done

CIPSend_instance.Done

OperatingEnd

CIPOpen_instance.Done

CIPRead_instance.Done

CIPClose_instance.Done

CIPOpen_instance.Error

CIPWrite_instance.Error

CIPRead_instance.Error

CIPSend_instance.Error

CIPClose_instance.Error

Accept trigger.

Trigger CIPOpen_instance.Busy CIPWrite_instance.Busy CIPRead_instance.Busy 1

CIPSend_instance.Busy CIPClose_instance.Busy
1 OperatingEnd

RS_instance

RS

Set

Q1

Reset1

Operating

2-1030

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

EtherNet/IP Communications Instructions

CIPOpen

Instruction execution Operating
`02\192.168.250.2' UINT#20

CIPOpen_instance

CIPOpen

Execute RoutePath TimeOut

Done Busy Error ErrorID ErrorIDEx Handle

CIPOpen_instance.Done
CIPOpen_instance.Handle `WritingDat' UINT#1 WriteDat

CIPWrite_instance

CIPWrite

Execute Handle DstDat Size SrcDat

Done Busy Error ErrorID ErrorIDEx

CIPWrite_instance.Done
CIPOpen_instance.Handle `OriginalDat' UINT#1
ReadDat

CIPRead_instance

CIPRead

Execute Handle SrcDat Size DstDat

Done Busy Error ErrorID

ErrorIDEx RcvSize

ReadDat

CIPRead_instance.Done UINT#1

@MOVE

EN

ENO

In

Out

ReqPath.ClassID

UINT#1

@MOVE

EN

ENO

In

Out

ReqPath.InstanceID

TRUE

@MOVE

EN

ENO

In

Out

ReqPath.isAttributeID

UINT#7

@MOVE

EN

ENO

In

Out

ReqPath.AttributeID

CIPOpen_instance.Handle BYTE#16#0E ReqPath Dummy UINT#0
ResDat

CIPSend_instance

CIPSend

Execute

Done

Handle

Busy

ServiceCode

Error

RqPath

ErrorID

ServiceDat ErrorIDEx

Size

RespSize

RespServiceDat

CIPSend_instance.Done CIPOpen_instance.Handle

CIPClose_instance

CIPClose

Execute Handle

Done Busy Error ErrorID ErrorIDEx

NJ/NX-series Instructions Reference Manual (W502)

2
2-1031

2 Instruction Descriptions

Processing after normal end Operating CIPClose_instance.Done
Processing after error end Operating CIPOpen_instance.Error CIPWrite_instance.Error CIPRead_instance.Error
CIPSend_instance.Error CIPClose_instance.Error

Inline ST 1 // Processing after normal end 2 ;
Inline ST 1 // Processing after error end 2 ;

2-1032

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

EtherNet/IP Communications Instructions

CIPOpen

ST

Internal Variables

Variable

Data type

Initial value

Comment

Trigger

BOOL

FALSE

Execution condition

DoCIPTrigger

BOOL

FALSE

Processing

Stage

INT

0

Stage change

WriteDat

INT

0

Write data

ReadDat

INT

0

Read data

ReqPath

_sREQUEST_PATH

(ClassID:=0, InstanceID:=0, isAttributeID:=FALSE, AttributeID:=0)

Request path

ResDat Dummy

ARRAY[0..10] OF BYTE [11(16#0)]

BYTE

16#0

Response data

2

Dummy

CIPOpen_instance CIPOpen

CIPWrite_instance CIPWrite

CIPRead_instance CIPRead

CIPSend_instance CIPSend

CIPClose_instance CIPClose

External Variables

Variable

_EIP_EtnOnlineSta

Constant

Data type BOOL

Comment Online

// Start sequence when Trigger changes to TRUE.

IF ( (Trigger=TRUE) AND (DoCIPTrigger=FALSE) AND (_Eip_EtnOnlineSta=TRUE) ) THEN

DoCIPTrigger:=TRUE;

Stage

:=INT#1;

CIPOpen_instance(Execute :=FALSE);

// Initialize instance.

CIPWrite_instance(

Execute

:=FALSE,

// Initialize instance.

SrcDat

:=WriteDat); // Dummy

CIPRead_instance(

// Initialize instance.

Execute

:=FALSE,

// Dummy

DstDat

:=ReadDat); // Dummy

CIPSend_instance(

Execute

:=FALSE,

// Initialize instance.

ServiceDat

:= Dummy,

// Dummy

RespServiceDat

:=ResDat);

// Dummy

CIPClose_instance(Execute:=FALSE);

// Initialize instance.

END_IF;

IF (DoCIPTrigger=TRUE) THEN

CASE Stage OF

1 :

// Open CIP Class 3 Connection (Large_Forward_Open)

CIPOpen_instance(

Execute :=TRUE,

TimeOut :=UINT#20,

// Timeout time: 2.0 s

RoutePath :='02\192.168.250.2'); // Route path

IF (CIPOpen_instance.Done=TRUE) THEN

Stage:=INT#2;

// Normal end

ELSIF (CIPOpen_instance.Error=TRUE) THEN

Stage:=INT#10;

// Error end

END_IF;

2 :

// Request writing value of variable.

CIPWrite_instance(

Execute :=TRUE,

NJ/NX-series Instructions Reference Manual (W502)

2-1033

2 Instruction Descriptions

2-1034

Handle DstDat Size SrcDat

:=CIPOpen_instance.Handle,// Handle

:='WritingDat',

// Destination variable name

:=UINT#1,

// Number of elements to write

:=WriteDat);

// Write data

IF (CIPWrite_instance.Done=TRUE) THEN

Stage:=INT#3;

// Normal end

ELSIF (CIPWrite_instance.Error=TRUE) THEN

Stage:=INT#20;

// Error end

END_IF;

3 :

// Request reading value of variable.

CIPRead_instance(

Execute :=TRUE,

Handle :=CIPOpen_instance.Handle,// Handle

SrcDat :='OriginalDat',

// Destination variable name

Size :=UINT#1,

// Number of elements to read

DstDat :=ReadDat);

// Read data

IF (CIPRead_instance.Done=TRUE) THEN

Stage:=INT#4;

// Normal end

ELSIF (CIPRead_instance.Error=TRUE) THEN

Stage:=INT#30;

// Error end

END_IF;

4 :

// Send message

ReqPath.ClassID

:=UINT#01;

ReqPath.InstanceID :=UINT#01;

ReqPath.isAttributeID :=TRUE;

ReqPath.AttributeID :=UINT#07;

CIPSend_instance(

Execute

:=TRUE,

Handle

:=CIPOpen_instance.Handle,

ServiceCode :=BYTE#16#0E,

RqPath

:=ReqPath,

ServiceDat :=Dummy,

Size

:=UINT#0,

RespServiceDat:=ResDat);

// Handle // Service code // Request path // Service data // Number of elements // Response data

IF (CIPSend_instance.Done=TRUE) THEN Stage:=INT#5; // Normal end
ELSIF (CIPSend_instance.Error=TRUE) THEN Stage:=INT#40; // Error end
END_IF;

5 :

// Request closing CIP class 3 connection.

CIPClose_instance(

Execute :=TRUE,

Handle :=CIPOpen_instance.Handle);

// Handle

IF (CIPClose_instance.Done=TRUE) THEN Stage:=INT#0;
ELSIF (CIPClose_instance.Error=TRUE) THEN Stage:=INT#50;
END_IF;

0:

// Processing after normal end

DoCIPTrigger:=FALSE;

Trigger

:=FALSE;

ELSE // Processing after error end

DoCIPTrigger:=FALSE;

Trigger

:=FALSE;

END_CASE;

END_IF;

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

2 Instruction Descriptions

CIPOpenWithDataSize

The CIPOpenWithDataSize instruction opens a CIP class 3 connection with the specified remote node that allows class 3 explicit messages of the specified data length or shorter to be sent and received.

Instruction

Name

FB/ FUN

Graphic expression

ST expression

CIPOpenWith- Open CIP

FB

DataSize

Class 3 Con-

nection with

CIPOpenWithDataSize_instance CIPOpenWithDataSize

CIPOpen_instance(Execute, RoutePath, TimeOut, DataSize, Done, Busy, Error, ErrorID,

Specified Data Size

Execute RoutePath

Done Busy

ErrorIDEx, Handle);

2

TimeOut

Error

DataSize

ErrorID

ErrorIDEx

Handle

Variables

Name RoutePath
TimeOut DataSize Handle

Meaning Route path
Timeout time Data length Handle

I/O Input Output

Description Route path
Timeout time Data length Handle

Valid range Depends on data type.
1 to 65,535
6 to 8,192*1*2 ---

Unit ---
0.1 s Bytes ---

Default
---
20 (2s) 1994 ---

*1 The range is 6 to 1,994 for NX1P2 and NJ-series CPU Units.

*2 With a CPU Unit with unit version 1.10 or earlier or Sysmac Studio version 1.14 or lower, the minimum value is 10.

Bit strings

Integers

Times, durations, dates, and text strings

CIPOpenWithDataSize

Real numbers

Boolean BOOL

STRING DT TOD
DATE TIME

LREAL REAL

LINT DINT INT SINT ULINT UDINT

UINT

USINT

LWORD

DWORD

WORD BYTE

RoutePath TimeOut DataSize Handle

OK OK OK Refer to Function for details on the structure _sCIP_HANDLE.

Function

The CIPOpenWithDataSize instruction opens a CIP class 3 connection with a remote node on a CIP network. The remote node is specified with route path RoutePath. Data length DataSize specifies the data length of class 3 explicit messages that can be sent and received.
The class 3 connection service is determined by the value of DataSize as given in the following table.

Value of DataSize [bytes]

Service

509 or less

Forward_Open

510 to 8,192*1

Large_Forward_Open

*1 The range is 510 to 1,994 for NX1P2 and NJ-series CPU Units.

Handle is output when the connection is open.
NJ/NX-series Instructions Reference Manual (W502)

2-1035

2 Instruction Descriptions

TimeOut specifies the connection timeout time. If a response does not return from the remote node within the connection timeout time after the CIPSend, CIPWrite, or CIPRead instruction is executed, it is assumed that communications failed. The connection timeout time is reset when the CIPRead, CIPWrite, or CIPSend instruction is executed and the remote node returns a response.

The data type of Handle is structure _sCIP_HANDLE. The specifications are as follows:

Name Handle
Handle

Meaning Handle
Handle

Description Handle
Handle

Data type
_sCIP_ HANDLE
UDINT

Valid range ---
Depends on data type.

Unit Default --- ---
--- ---

The following example is for when RoutePath is `02\192.168.250.2' and TimeOut is UINT#20. The CIPOpenWithDataSize instruction opens a CIP class 3 connection with the remote node with an IP address of 192.168.250.2. The data length is 1,994 bytes and the timeout time is 2 s. The handle is assigned to variable pqr.

LD

A
`02\192.168.250.2' UINT#20
UINT#1994

CIPOpenWithDataSize_instance

CIPOpenWithDataSize

Execute RoutePath TimeOut DataSize

Done Busy Error ErrorID ErrorIDEx Handle

ST

abc
def ghi jkl mno pqr

CIPOpenWithDataSize_instance(A, '2\192.168.250.2', UINT#20, UINT#1994, abc, def, ghi, jkl, mno, pqr);

The CIPOpenWithDataSize instruction opens a CIP class 3 connection with a remote node on a CIP network. The remote node is specified with RoutePath.

Controller that executed the instruction

IP address: 192.168.250.2

Handle=pqr
CIP class 3 connection is opened with a timeout time of 2 s. The obtained handle is assigned to this variable.
If the value of ErrorID is WORD#16#1C00, the CIP message error code is stored in ErrorIDEx. The meaning and values of ErrorIDEx depend on the remote node. Refer to the manual for the remote node.

Related System-defined Variables

Name

Meaning

_EIP_EtnOnlineSta*1 _EIP1_EtnOnlineSta*2

Online

_EIP2_EtnOnlineSta*3 _EIPIn1_EtnOnlineSta*4

*1 Use this variable name for an NJ-series CPU Unit.

Data type
BOOL

Description
This variable indicates when built-in EtherNet/IP port communications can be used. TRUE: Communications are possible. FALSE: Communications are not possible.

2-1036

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

CIPOpenWithDataSize

2 Instruction Descriptions

*2 Use this variable name for port 1 on an NX-series CPU Unit, or for an NY-series Controller. *3 Use this variable name for port 2 on an NX-series CPU Unit. *4 Use this variable name for the internal port on an NY-series Controller.

Additional Information

· Refer to the following manuals for details on CIP communications.

· NJ/NX-series CPU Unit Built-in EtherNet/IP Port User's Manual (Cat. No. W506)

· NY-series Industrial Panel PC / Industrial Box PC Built-in EtherNet/IP Port User's Manual (Cat. No. W563)

· CJ-series EtherNet/IP Units Operation Manual for NJ-series CPU Unit (Cat. No. W495) · To use Large_Forward_Open as the class 3 connection service, you can also use the CIPOpen

2

instruction (page 2-1026).

Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section (page 2-3) for a timing chart for Execute, Done, Busy, and Error.
· You must execute this instruction or the CIPOpen instruction before you execute the CIPRead, CIPWrite, or CIPSend instruction.
· For this instruction, the first timeout time after a connection is established is 10 s even if the value of TimeOut is set to less than 100 (10 s).
· Use the CIPClose instruction to close connections that were opened with the CIPOpenWithDataSize instruction.
· Even if the connection times out, the handle created by this instruction will remain. Always use the CIPClose instruction to close the connection.
· Handles that are created with this instruction are disabled when you change to PROGRAM mode.
· You can create a maximum of 32 handles at the same time.
· You can use this instruction only through a built-in EtherNet/IP port on an NY-series Controller or an NJ/NX-series CPU Unit, or through a port on an EtherNet/IP Unit connected to an NJ-series CPU Unit.
· An error occurs in the following cases. Error will change to TRUE.
· The value of TimeOut is outside of the valid range.
· The text string in RoutePath is not valid.
· More than 32 CIP-related instructions were executed simultaneously.
· An attempt was made to open a connection beyond the CIPClass connection resources (32 connections).
· A connection opened response was not received.
· The value of DataSize is 510 to 1,994 and the remote node to which to open a connection does not support Large_Forward_Open.
· There is a setting error for the local IP address.
· A duplicated IP error occurred.
· All TCP connections are already in use.
· The instruction was executed when there was a BOOTP server error.

NJ/NX-series Instructions Reference Manual (W502)

2-1037

2 Instruction Descriptions
Version Information · A CPU Unit with unit version 1.06 or later and Sysmac Studio version 1.07 or higher are
required to use this instruction. · For CPU Unit version 1.10 or later, the value of Handle does not change even if Error changes
to TRUE. For version 1.09 or earlier, the value of Handle changes to 0.

2-1038

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

CIPRead

2 Instruction Descriptions

CIPRead

The CIPRead instruction uses a class 3 explicit message to read the value of a variable in another Controller on a CIP network.

Instruction CIPRead

Name
Read Variable Class 3 Explicit

FB/ FUN
FB

Graphic expression

CIPRead_instance

CIPRead

Execute Handle SrcDat Size DstDat

Done Busy Error ErrorID

ErrorIDEx RcvSize

ST expression

CIPRead_instance(Execute,

Handle, SrcDat, Size, DstDat,

Done, Busy, Error, ErrorID, ErrorIDEx, RcvSize);

2

Variables

Name Handle
SrcDat Size
DstDat

Meaning

I/O

Handle

Source variable name
Number of elements to read
Read data

Input In-out

Description Handle obtained with CIPOpen or CIPOpenWithDataSize instruction Name of variable to read in other Controller Number of elements to read
Read data value

RcvSize

Read data

Output Read data size

size

*1 The range is 0 to 1,988 for NX1P2 and NJ-series CPU Units.

Valid range
---
Depends on data type. 0 to 8,186*1
Depends on data type. 0 to 8,186*1

Unit
---
---
Bytes

Default
---
'' 1
-----

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

Handle SrcDat Size DstDat
RcvSize

Refer to Function for details on the structure _sCIP_HANDLE. OK
OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK
An enumeration, array, structure, structure member, or union member can also be specified.* OK

* You cannot specify a STRING array.

NJ/NX-series Instructions Reference Manual (W502)

2-1039

2 Instruction Descriptions

Function

The CIPRead instruction reads the value of the network variable specified with source variable name SrcDat from another Controller on a CIP network. The other Controller is specified with Handle. The read data value is stored in DstDat. Size specifies the number of elements to read. If SrcDat is an array, specify the number of elements to read with Size. If SrcDat is not an array, always specify 1 for Size. If the value of Size is 0, nothing is read regardless of whether SrcDat is an array or not. When the read operation is completed, the number of bytes of the data that was read is assigned to read data size RcvSize. The maximum size of the data that you can read depends on the instruction that established the connection and the data type of the data that is read as shown in the following table.

Instruction that established the connection CIPOpen
CIPOpenWithDataSize

Data type of read data
Structure STRING Other data type Structure STRING Other data type

Maximum size of data that you can read [bytes]
1984 1986 1988 DataSize in CIPOpenWithDataSize instruction - 10 DataSize in CIPOpenWithDataSize instruction - 8 DataSize in CIPOpenWithDataSize instruction - 6

The data type of Handle is structure _sCIP_HANDLE. The specifications are as follows:

Name Handle
Handle

Meaning Handle
Handle

Description Handle
Handle

Data type
_sCIP_ HANDLE
UDINT

Valid range
---
Depends on data type.

Unit Default
--- ---
--- ---

If the value of ErrorID is WORD#16#1C00, the CIP message error code is stored in ErrorIDEx.
In the following example, the value of variable abc in the remote Controller is read and stored in the variable def in the local Controller. The number of elements to read Size is UINT#1. The data type of abc and def is SINT. The size of SINT data is one byte, so the value of the read data size vwx is UINT#1.

LD

ST

A
cip_h `abc' UINT#1
def

CIPRead_instance

CIPRead

Execute Handle SrcDat Size DstDat

Done Busy Error ErrorID

ErrorIDEx RcvSize

ghi
jkl mno pqr
def stu vwx

CIPRead_instance(A, cip_h, `abc', UINT#1, def, ghi, jkl, mno, pqr, stu, vwx);

2-1040

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

CIPRead

2 Instruction Descriptions

The value of variable SrcDat in remote Controller on the CIP network specified by the handle Handle is assigned to variable DstDat in the local Controller. Size specifies the number of elements to read. The size of data that was read is assigned to RcvSize.

Controller that executed the instruction

Handle Handle = cip_h Controller.

DstDat=def SINT#123 =abc SINT#123
Value of variable abc in remote Controller is assigned to variable def in local Controller. RcvSize=vwx UINT#1

Read. Size UINT#1

SrcDat=abc SINT#123
2 Variable abc in remote Controller

The number of elements to read is 1.

The size of data that was read is assigned to variable vwx.

Reading Arrays

To read array data, pass a subscripted array element to ScrDat as the parameter. Also pass a subscripted array element to DstDat as the parameter.
The following example reads the four array variable elements abc[3] to abc[6] from the remote Controller and stores the results in array variable elements def[10] to def[13] in the local Controller. The data type of abc and def is INT. The size of INT data is two bytes, so the value of the read data size vwx is UINT#8.

LD

ST

A
cip_h `abc[3]' UINT#4
def[10]

CIPRead_instance

CIPRead

Execute Handle SrcDat Size DstDat

Done Busy Error ErrorID

ErrorIDEx RcvSize

ghi
jkl mno pqr
def[10] stu vwx

CIPRead_instance(A, cip_h, `abc[3]', UINT#4, def[10], ghi, jkl, mno, pqr, stu, vwx);

NJ/NX-series Instructions Reference Manual (W502)

2-1041

2 Instruction Descriptions

Values of array variable elements abc[3] to abc[6] in remote Controller are assigned to array variable elements def[10] to def[13] in local Controller.

Controller that executed the instruction

Handle Handle = cip_h Controller.

DstDat[0]=def[10] DstDat[1]=def[11] DstDat[2]=def[12] DstDat[3]=def[13]

INT#1234 =abc[3] INT#2345 =abc[4] INT#3456 =abc[5] INT#4567 =abc[6]

INT#1234 INT#2345 INT#3456 INT#4567

Read. Size UINT#4

SrcDat[0]=abc[3] SrcDat[1]=abc[4] SrcDat[2]=abc[5] SrcDat[3]=abc[6]

INT#1234 INT#2345 INT#3456 INT#4567

The number of elements to read is 4.
Values of array variable abc in remote Controller are assigned to array variable def in local Controller.

Array variable abc in remote Controller

RcvSize=vwx UINT#8

The size of data that was read, eight bytes, is assigned to variable vwx.

Related System-defined Variables

Name

Meaning

Data type

Description

_EIP_EtnOnlineSta*1 _EIP1_EtnOnlineSta*2 _EIP2_EtnOnlineSta*3 _EIPIn1_EtnOnlineSta*4

Online

BOOL

This variable indicates when built-in EtherNet/IP port communications can be used.
TRUE: Communications are possible.
FALSE: Communications are not possible.

*1 Use this variable name for an NJ-series CPU Unit.

*2 Use this variable name for port 1 on an NX-series CPU Unit, or for an NY-series Controller.

*3 Use this variable name for port 2 on an NX-series CPU Unit.

*4 Use this variable name for the internal port on an NY-series Controller.

Additional Information
Refer to the following manuals for details on CIP communications. · NJ/NX-series CPU Unit Built-in EtherNet/IP Port User's Manual (Cat. No. W506) · NY-series Industrial Panel PC / Industrial Box PC Built-in EtherNet/IP Port User's Manual (Cat. No.
W563) · CJ-series EtherNet/IP Units Operation Manual for NJ-series CPU Unit (Cat. No. W495)

Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error.
· Execute the CIPOpen or CIPOpenWithDataSize instruction to obtain the value for Handle before you execute this instruction.
· You can use this instruction only through a built-in EtherNet/IP port on an NY-series Controller or an NJ/NX-series CPU Unit, or through a port on an EtherNet/IP Unit connected to an NJ-series CPU Unit.

2-1042

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

CIPRead

2 Instruction Descriptions

· If a variable is read from an OMRON Controller, the variable must be published to the network. Publish the variable to the network in advance.
· You cannot specify an address in memory for CJ-series Units directly to read data. To read specific addresses in memory for CJ-series Units, use an AT specification in advance to assign the memory addresses to a variable.
· You cannot specify an address in local memory for CJ-series Units directly to store data. To store data in specific addresses in memory for CJ-series Units, use an AT specification in advance to assign the memory addresses to DstDat.
· The characters that can be used in SrcDat are specified in the following table.

Item

Specification

Maximum num- 127 bytes

ber of bytes

2

Character code UTF-8

Applicable char- Alphanumeric characters (not case sensitive), single-byte Katakana, multibyte characters,

acters

and `_' (underbars)

Prohibited text strings

· Any text string that starts with ASCII characters 0 to 9 (character codes 16#30 to 16#39) · A text string that consists of only a single _ (underbar) ASCII character

· Any text string that includes two or more consecutive _ (underbar) ASCII characters

· Any text string that starts with an _ (underbar) ASCII character · Any text string that ends with an _ (underbar) ASCII character · Any text string that starts with "P_"

· An error occurs in the following cases. Error will change to TRUE.

· The value of Size is outside of the valid range.

· The text string in SrcDat is not valid.

· The data type of the value that was read does not agree with the data type of DstDat.

· The size of data that was read exceeds the range of DstDat.

· A data type that is not supported was specified for DstDat.

· An error response defined by CIP was returned.

· The value of Handle.Handle is outside of the valid range.

· More than 32 CIP-related instructions were executed simultaneously.

· The connection that was established with the CIPOpen or CIPOpenWithDataSize instruction has timed out.

· The size of SrcDat exceeded the data size determined by the instruction that established the connection and the data type of the read data.

NJ/NX-series Instructions Reference Manual (W502)

2-1043

2 Instruction Descriptions

· For this instruction, expansion error code ErrorIDEx gives the CIP message error code. The meanings are as follows:

Value 16#02000000 16#04000000
16#05000000
16#08000000 16#0C008010 16#0C008011 16#11000000 16#1F000102 16#1F008007 16#20008017 16#20008018 16#26000000

Error Normal communications are not possible due to a high load at the remote node. The specified source variable is one of the following data types and it does not exist on the other Controller. · Basic data type · Enumeration · Structure · Union · Array The specified source variable is one of the following and it does not exist on the other Controller. · Enumeration enumerator · Structure member · Union member · Array element The requested service does not support. The specified source variable is being downloaded.
The value of Size is exceeds the data size that can currently be read. The variable to read is a variable that is not possible to read. The inaccessible variable is specified. The specified source variable is not an array and the number of elements to read is not 1. The specified source variable is an array and the number of elements to read exceeds the number of elements in the array. The specified destination variable contains only the NULL character.

Sample Programming
Refer to the sample programming that is provided for the CIPOpen instruction (page 2-1026).

2-1044

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

CIPWrite

2 Instruction Descriptions

CIPWrite

The CIPWrite instruction uses a class 3 explicit message to write the value of a variable in another Controller on a CIP network.

Instruction CIPWrite

Name
Write Variable Class 3 Explicit

FB/ FUN
FB

Graphic expression

CIPWrite_instance

CIPWrite

Execute

Done

Handle

Busy

DstDat

Error

Size

ErrorID

SrcDat ErrorIDEx

ST expression

CIPWrite_instance(Execute,

Handle, DstDat, Size, SrcDat,

Done, Busy, Error, ErrorID, ErrorIDEx);

2

Variables

Name

Meaning

I/O

Description

Valid range

Unit

Handle DstDat Size SrcDat

Handle

Destination variable name
Number of elements to write
Source data

Input

Handle obtained with CIPOpen ---

---

or CIPOpenWithDataSize

instruction

Name of variable to write in another Controller

Depends on data type.

0 to 8,178*1

Number of elements to write

---

Data value to write

Depends on data type.

*1 The range is 0 to 1,980 for NX1P2 and NJ-series CPU Units.

*2 If you omit an input parameter, the default value is not applied. A building error will occur.

Default
---
'' 1
*2

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

Handle DstDat Size SrcDat Handle

Refer to Function for details on the structure _sCIP_HANDLE. OK
OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK
An enumeration, array*, structure, structure member, or union member can also be specified.

* You cannot specify a STRING array.

Function
The CIPWrite instruction writes the value of the network variable specified with destination variable name DstDat at another Controller on a CIP network. The other Controller is specified with Handle. The content of source data ScrDat is written.

NJ/NX-series Instructions Reference Manual (W502)

2-1045

2 Instruction Descriptions

Size specifies the number of elements to write. If DstDat is an array, specify the number of elements to write with Size. If DstDat is not an array, always specify 1 for Size. If the value of Size is 0, nothing is written regardless of whether DstDat is an array or not.

The data type of Handle is structure _sCIP_HANDLE. The specifications are as follows:

Name Handle
Handle

Meaning Handle
Handle

Description Handle
Handle

Data type
_sCIP_ HANDLE
UDINT

Valid range
---
Depends on data type.

Unit Default
--- ---
--- ---

If the value of ErrorID is WORD#16#1C00, the CIP message error code is stored in ErrorIDEx.

The following example writes the value of variable def from the local Controller to the variable abc in the remote Controller. The number of elements to write Size is UINT#1.

LD

ST

A
cip_h `abc' UINT#1 def

CIPWrite_instance

CIPWrite

Execute Handle DstDat Size SrcDat

Done Busy Error ErrorID ErrorIDEx

ghi
jkl mno pqr stu

CIPWrite_instance(A, cip_h, `abc', UINT#1, def, ghi, jkl, mno, pqr, stu);

The value of variable SrcDat in the local Controller is assigned to variable DstDat in the remote Controller on the CIP network specified by the handle Handle. Size specifies the number of elements to write.
Handle Handle = cip_h Controller.
Controller that executed the instruction

SrcDat=def SINT#123

Written.

DstDat=abc SINT#123 =def SINT#123

Variable def in local Controller

Size UINT#1

Value of variable def in local Controller is assigned to variable abc in remote Controller.

The number of elements to write is 1.

Writing Arrays

To write array data, pass a subscripted array element to DstDat as the parameter. Also pass a subscripted array element to SrcDat as the parameter.
The following example stores the contents of array variable elements def[10] to def[13] in the four array variable elements abc[3] to abc[6].

LD

ST

A
cip_h `abc[3]' UINT#4 def[10]

CIPWrite_instance

CIPWrite

Execute Handle DstDat Size SrcDat

Done Busy Error ErrorID ErrorIDEx

ghi
jkl mno pqr stu

CIPWrite_instance(A, cip_h, `abc[3]', UINT#4, def, ghi[10], jkl, mno, pqr, stu);

2-1046

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

CIPWrite

2 Instruction Descriptions

Values of array variable elements def[10] to def[13] in local Controller are assigned to array variable elements abc[3] Ito abc[6] in remote Controller.

Controller that executed the instruction

Handle Handle = cip_h Controller.

SrcDat[0]=def[10] SrcDat[1]=def[11] SrcDat[2]=def[12] SrcDat[3]=def[13]

INT#1234 INT#2345 INT#3456 INT#4567

Written.

DstDat[0]=abc[3] INT#1234 =def[10] INT#1234

Size UINT#4

DstDat[1]=abc[4] INT#2345 =def[11] INT#2345 DstDat[2]=abc[5] INT#3456 =def[12] INT#3456

DstDat[3]=abc[6] INT#4567 =def[13] INT#4567 The number of elements to write is 4.

2

Array variable def in local Controller

Values of array variable def in local Controller are assigned to array variable abc in remote Controller.

Maximum Write Data Size
The maximum size of the data that you can write depends on the data type and variable name that are specified for DstDat, as given in the following table. Maximum write data size [bytes] = Base size - Size of variable name of DstDat

Item in above formula Base size

Meaning
Connections established with the CIPOpen instruction
· Data type of variable specified for DstDat is a structure: 1,984 bytes · Data type of variable specified for DstDat is a STRING: 1,986 bytes · Other data types: 1,988 bytes
Connections established with the CIPOpenWithDataSize instruction
· Use the following formula when the data type of variable specified for DstDat is a structure: Base size [bytes] = DataSize in CIPOpenWithDataSize instruction - 10
· Use the following formula when the data type of variable specified for DstDat is a STRING: Base size [bytes] = DataSize in CIPOpenWithDataSize instruction - 8
· Use the following formula for other data types. Base size [bytes] = DataSize in CIPOpenWithDataSize instruction - 6

NJ/NX-series Instructions Reference Manual (W502)

2-1047

2 Instruction Descriptions

Item in above formula
Size of variable name of DstDat

Meaning
· The size of the variable name is calculated as the total bytes for the ASCII characters in all structure levels plus two times the number of levels.
· If the number of bytes of ASCII characters in a level is an odd number, add 1.
· If a level in the structure is an array, add four times the number of dimensions in the array.
· Periods and commas in the structure and arrays are not included in the variable name size.
Example 1: When the Variable Name of DstDat Is aaa.bbbbb[1,2,3].cc
· The text string "aaa" in the first level is 3 bytes. It is an odd number, so 1 is added to make 4 bytes.
· The text string "bbbbb[1,2,3]" in the second level is 5 bytes. It is an odd number, so 1 is added to make 6 bytes.
· Also bbbbb[1,2,3] is a three-dimensional array, so 3 times 4, or 12, is added to make 18 bytes.
· The text string "cc" in the third level is 2 bytes. It is an even number, so 2 bytes is used in the calculation.
· If we add the number of levels 3 times 2, or 6, to 4 bytes for the first level, 18 bytes for the second level, and 2 bytes for the third level, the size of the variable name come to 30 bytes.
Example 2: When the Variable Name of DstDat Is val
· The text string "val" in the first level is 3 bytes. It is an odd number, so 1 is added to make 4 bytes.
· If we then add the number of levels 1 times 2, or 2, the size of the variable name is 6 bytes.
Example 3: When the Variable Name of DstDat Is array[8].
· The text string "array" in the first level is 5 bytes. It is an odd number, so 1 is added to make 6 bytes.
· It is a one-dimensional array. Therefore, 1 times 4, or 4, is added.
· If we then add the number of levels 1 times 2, or 2, the size of the variable name is 12 bytes.

Related System-defined Variables

Name

Meaning

Data type

Description

_EIP_EtnOnlineSta*1 _EIP1_EtnOnlineSta*2 _EIP2_EtnOnlineSta*3 _EIPIn1_EtnOnlineSta*4

Online

BOOL

This variable indicates when built-in EtherNet/IP port communications can be used.
TRUE: Communications are possible.
FALSE: Communications are not possible.

*1 Use this variable name for an NJ-series CPU Unit.

*2 Use this variable name for port 1 on an NX-series CPU Unit, or for an NY-series Controller.

*3 Use this variable name for port 2 on an NX-series CPU Unit.

*4 Use this variable name for the internal port on an NY-series Controller.

Additional Information
Refer to the following manuals for details on CIP communications. · NJ/NX-series CPU Unit Built-in EtherNet/IP Port User's Manual (Cat. No. W506) · NY-series Industrial Panel PC / Industrial Box PC Built-in EtherNet/IP Port User's Manual (Cat. No.
W563) · CJ-series EtherNet/IP Units Operation Manual for NJ-series CPU Unit (Cat. No. W495)

2-1048

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

EtherNet/IP Communications Instructions

CIPWrite

Precautions for Correct Use

· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.

· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error.

· Execute the CIPOpen or CIPOpenWithDataSize instruction to obtain the value for Handle before you execute this instruction.

· Always use a variable for the input parameter to pass to SrcDat. A building error will occur if a constant is passed.

· If SrcDat is an enumeration, you cannot directly pass an enumerator to it. A building error will occur if an enumerator is passed to it directly.

2

· You can use this instruction only through a built-in EtherNet/IP port on an NY-series Controller or an NJ/NX-series CPU Unit, or through a port on an EtherNet/IP Unit connected to an NJ-series CPU Unit.

· If a variable is written to an OMRON Controller, the variable must be published to the network. Publish the variable to the network in advance.

· You cannot specify an address in memory for CJ-series Units directly to write data. To write specific addresses in memory for CJ-series Units, use an AT specification in advance to assign the memory addresses to a variable.

· You cannot directly specify an address in local memory for CJ-series Units. To write specific addresses in memory for CJ-series Units, use an AT specification in advance to assign the memory addresses to SrcDat.

· The characters that can be used in DstDat are specified in the following table.

Item
Maximum number of bytes

127 bytes

Specification

Character code UTF-8

Applicable char- Alphanumeric characters (not case sensitive), single-byte Katakana, multibyte characters,

acters

and `_'(underbars)

Prohibited text strings

· Any text string that starts with ASCII characters 0 to 9 (character codes 16#30 to 16#39) · A text string that consists of only a single _ (underbar) ASCII character · Any text string that includes two or more consecutive _ (underbar) ASCII characters · Any text string that starts with an _ (underbar) ASCII character · Any text string that ends with an _ (underbar) ASCII character · Any text string that starts with "P_"

· An error occurs in the following cases. Error will change to TRUE.

· The value of Size is outside of the valid range.

· The text string in DstDat is not valid.

· The value of Size exceeds the range of SrcDat.

· A data type that is not supported was specified for SrcDat.

· An error response defined by CIP was returned.

· The value of Handle.Handle is outside of the valid range.

· More than 32 CIP-related instructions were executed simultaneously.

· The connection that was established with the CIPOpen or CIPOpenWithDataSize instruction has timed out.

· The total of the size in DstDat and the value of SrcDat exceeded the data size determined by the instruction that established the connection and the data type of the write data.

NJ/NX-series Instructions Reference Manual (W502)

2-1049

2 Instruction Descriptions

· For this instruction, expansion error code ErrorIDEx gives the CIP message error code. The meanings are as follows:

Value 16#02000000 16#04000000
16#05000000
16#08000000 16#0C008010 16#0C008011 16#1F000102 16#1F008007 16#20008017 16#20008018 16#20008028
16#26000000

Error
Normal communications are not possible due to a high load at the remote node.
The specified source variable is one of the following data types and it does not exist on the other Controller. · Basic data type · Enumeration · Structure · Union · Array
The specified source variable is one of the following and it does not exist on the other Controller. · Enumeration enumerator · Structure member · Union member · Array element
The requested service does not support.
The specified source variable is being downloaded.
· The specified destination variable has a Constant attribute, so it cannot be written. · The write data does not agree with the number of write elements.
The inaccessible variable is specified.
The specified destination variable is not an array and the number of elements to write is not 1.
The specified destination variable is an array and the number of elements to write exceeds the number of elements in the array.
· The specified destination variable is an enumeration and the write data is not the value of an enumerator.
· The specified destination variable has a Range Specification attribute and the write data is out of range.
The specified destination variable contains only the NULL character.

Sample Programming
Refer to the sample programming that is provided for the CIPOpen instruction (page 2-1026).

2-1050

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

CIPSend

2 Instruction Descriptions

CIPSend

The CIPSend instruction sends a class 3 CIP message to a specified device on a CIP network.

Instruction CIPSend

Name
Send Explicit Message Class 3

FB/ FUN
FB

Graphic expression

CIPSend_instance

CIPSend

Execute

Done

Handle

Busy

ServiceCode

Error

RqPath

ErrorID

ServiceDat ErrorIDEx

Size

RespSize

RespServiceDat

ST expression

CIPSend_instance(Execute,

Handle, ServiceCode, RqPath,

ServiceDat, Size,

RespServiceDat, Done, Busy,

Error, ErrorID,

2

ErrorIDEx, RespSize);

Variables

Name Handle

Meaning Handle

ServiceCode Service code

RqPath ServiceDat Size
RespServiceDat RespSize

Request path
Service data
Number of elements to send
Response data
Response size

I/O
Input
In-out Output

Description Handle obtained with CIPOpen or CIPOpenWithDataSize instruction Service code
Request path Service data to send Number of elements to send

Valid range
---
Depends on data type.
---
Depends on data type.

Response data Response data size

Depends on data type.
Depends on data type.

* If you omit an input parameter, the default value is not applied. A building error will occur.

Unit
---
---
Bytes

Default
---
*
-----

NJ/NX-series Instructions Reference Manual (W502)

2-1051

2 Instruction Descriptions

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

Bit strings

Integers

Times, durations, dates, and text strings

Handle

Refer to Function for details on the structure _sCIP_HANDLE.

ServiceCode

OK

RqPath

Refer to Function for details on the structure _sREQUEST_PATH or _sREQUEST_PATH_EX*1.

ServiceDat

OK OK OK OK OK OK OK OK OK OK OK OK OK OK

An array, structure member, or union member can also be specified.

Size

OK

RespServiceDat
RespSize

OK OK OK OK OK OK OK OK OK OK OK OK OK OK An array, structure member, or union member can also be specified. OK

*1 A CPU Unit with unit version 1.11 or later and Sysmac Studio version 1.15 or higher are required to specify _sREQUEST_PATH_EX type.

Function

The CIPSend instruction sends service data ServiceDat for the service specified with service code ServiceCode as a class 3 explicit message. The destination is specified with handle Handle. RqPath specifies the request path.
Size specifies the number of elements to send. If ServiceDat is an array, specify the number of elements to send with Size. If ServiceDat is not an array, always specify 1 for Size. If no service data is required, set Size to 0. The response data received later is stored in RespServiceDat. The number of bytes of the response data is stored in RespSize.

The data type of Handle is structure _sCIP_HANDLE. The specifications are as follows:

Name Handle
Handle

Meaning Handle
Handle

Description Handle
Handle

Data type
_sCIP_ HANDLE
UDINT

Valid range
---
Depends on data type.

Unit Default
--- ---
--- ---

The data type of RqPath is structure _sREQUEST_PATH or _sREQUEST_PATH_EX. Normally, use _sREQUEST_PATH. When you want to specify any logical format size, use _sREQUEST_PATH_EX. The specifications are as follows:

· _sREQUEST_PATH type

Name RqPath
ClassID InstanceID isAttributeID
AttributeID

Meaning Request path
Class ID Instance ID Attribute usage
Attribute ID

Description Request path
Class ID Instance ID TRUE:Attribute ID used. FALSE:Attribute ID not
used. Attribute ID

Data type _sREQUEST_PATH UINT UINT BOOL

Valid range
---
Depends on data type.

UINT

Note The logical format size of each ID in _sREQUEST_PATH type is 16 bits.

Unit Default
--- ---
0 --- FALSE
0

2-1052

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

CIPSend

2 Instruction Descriptions

· _sREQUEST_PATH_EX type

Name

Meaning

Description

Data type

Valid range Unit Default

RqPath

Request path Request path

_sREQUEST_ PATH_EX

---

--- ---

ClassIDLogica lFormat

Class ID logical format

Class ID data size

_eCIP_LOGIC AL_FORMAT

_8BIT

ClassID

Class ID

Class ID

UDINT

0

InstanceIDLog icalFormat

Instance ID logical format

Instance ID data size

_eCIP_LOGIC AL_FORMAT

_8BIT

InstanceID isAttributeID

Instance ID
Attribute usage

Instance ID
TRUE:Attribute ID used. FALSE:Attribute ID not
used.

UDINT BOOL

Depends on data type.

--- 0

2

FALSE

AttributeIDLogi Attribute ID

calFormat

logical format

Attribute ID data size

_eCIP_LOGIC AL_FORMAT

_8BIT

AttributeID

Attribute ID Attribute ID

UDINT

0

The data type of ClassIDLogicalFormat, InstanceIDLogicalFormat, and AttributeIDLogicalFormat is enumerated type _eCIP_LOGICAL_FORMAT.

The meanings of the enumerators of enumerated type _eCIP_LOGICAL_FORMAT are as follows:

Enumerator

Meaning

_8BIT

8 bits

_16BIT

16 bits

_32BIT

32 bits

If the value of ErrorID is WORD#16#1C00, the CIP message error code is stored in ErrorIDEx. The meaning and values of ErrorIDEx depend on the remote node. Refer to the manual for the remote node.

Sending and Receiving Arrays
If ServiceDat or RespServiceDat is an array, pass a subscripted array element to it as the parameter.

NJ/NX-series Instructions Reference Manual (W502)

2-1053

2 Instruction Descriptions

Maximum Read/Write Data Size

The maximum size of the data that you can read depends on whether the connection was opened with the CIPOpen instruction or the CIPOpenWithDataSize instruction as shown in the following table.

Instruction that opened the connection
CIPOpen
CIPOpenWithDataSize

Maximum size of data that you can read
1,990 bytes With 8,188*1 as the upper limit, responses returned by the server can be read.

*1 The maximum size is 1,990 for NX1P2 and NJ-series CPU Units.

The maximum size of the data that you can write depends on whether there is a request path attribute and the instruction that established the connection, as given below.

Maximum write data size [bytes] = Base size - Attribute usage

Item in above formula

Meaning

Base size Attribute usage*1

· Connection established with the CIPOpen instruction: 1,992 bytes · Connection established with the CIPOpenWithDataSize instruction: Data-
Size in CIPOpenWithDataSize instruction - 2
Attribute ID used: 14 bytes
Attribute ID not used: 10 bytes

*1 With a CPU Unit with unit version 1.10 or earlier or Sysmac Studio version 1.14 or lower, the values are as follows: Attribute ID used: 12 bytes Attribute ID not used: 8 bytes

Related System-defined Variables

Name

Meaning

Data type

Description

_EIP_EtnOnlineSta*1 _EIP1_EtnOnlineSta*2 _EIP2_EtnOnlineSta*3 _EIPIn1_EtnOnlineSta*4

Online

BOOL

This variable indicates when built-in EtherNet/IP port communications can be used.
TRUE: Communications are possible.
FALSE: Communications are not possible.

*1 Use this variable name for an NJ-series CPU Unit.

*2 Use this variable name for port 1 on an NX-series CPU Unit, or for an NY-series Controller.

*3 Use this variable name for port 2 on an NX-series CPU Unit.

*4 Use this variable name for the internal port on an NY-series Controller.

Additional Information
Refer to the following manuals for details on CIP communications. · NJ/NX-series CPU Unit Built-in EtherNet/IP Port User's Manual (Cat. No. W506) · NY-series Industrial Panel PC / Industrial Box PC Built-in EtherNet/IP Port User's Manual (Cat. No.
W563) · CJ-series EtherNet/IP Units Operation Manual for NJ-series CPU Unit (Cat. No. W495)

2-1054

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

CIPSend

2 Instruction Descriptions

Precautions for Correct Use

· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.

· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error.

· Execute the CIPOpen or CIPOpenWithDataSize instruction to obtain the value for Handle before you execute this instruction.

· Always use a variable for the input parameter to pass to ServiceDat. A building error will occur if a constant is passed.

· You can use this instruction only through a built-in EtherNet/IP port on an NY-series Controller or an NJ/NX-series CPU Unit, or through a port on an EtherNet/IP Unit connected to an NJ-series CPU

2

Unit.

· If a variable is written to an OMRON Controller, the variable must be published to the network. Publish the variable to the network in advance.

· An error occurs in the following cases. Error will change to TRUE.

· A value that is out of valid range is set for RqPath.ClassIDLogicalFormat or RqPath.AttributeIDLogicalFormat.

· A mismatch occurred between the following two variables: the size specified for RqPath.ClassIDLogicalFormat and the data size of RqPath.ClassID, the size specified for RqPath.InstanceIDLogicalFormat and the data size of RqPath.InstanceID, or the size specified for RqPath.AttributeIDLogicalFormat and the data size of RqPath.AttributeID.

· The value of Size exceeds the write data range.

· The value of Size exceeds the range of ServiceDat.

· The value of RespSize exceeds the range of RespServiceDat.

· A data type that is not supported was specified for ServiceDat.

· A data type that is not supported was specified for RespServiceDat.

· A variable whose data type is other than _sREQUEST_PATH or _sREQUEST_PATH_EX is specified for RqPath.

· An error response defined by CIP was returned.

· The value of Handle.Handle is outside of the valid range.

· More than 32 CIP-related instructions were executed simultaneously.

· The connection that was established with the CIPOpen or CIPOpenWithDataSize instruction has timed out.

· The total of the sizes of RqPath and ServiceDat exceeded the data size determined by the instruction that established the connection.

Sample Programming
Refer to the sample programming that is provided for the CIPOpen instruction (page 2-1026).

NJ/NX-series Instructions Reference Manual (W502)

2-1055

2 Instruction Descriptions

CIPClose

The CIPClose instruction closes the CIP class 3 connection to the specified handle.

Instruction CIPClose

Name
Close CIP Class 3 Connection

FB/ FUN
FB

Graphic expression

CIPClose_instance

CIPClose

Execute Handle

Done Busy Error ErrorID ErrorIDEx

ST expression
CIPClose_instance(Execute, Handle, Done, Busy, Error, ErrorID, ErrorIDEx);

Variables

Name Handle

Meaning Handle

I/O Input

Description
Handle obtained with CIPOpen or CIPOpenWithDataSize instruction

Valid range
---

Unit
---

Default
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

Handle

Refer to Function for details on the structure _sCIP_HANDLE.

Function

The CIPClose instruction closes the CIP class 3 connection specified with the handle Handle.

The data type of Handle is structure _sCIP_HANDLE. The specifications are as follows:

Name Handle

Meaning Handle

Description Handle

Data type _sCIP_

Valid range
---

Unit Default
--- ---

Handle

Handle

Handle

HANDLE UDINT

Depends on data type.

--- ---

The following figure shows a programming example. The CIPClose instruction closes the CIP class 3 connection specified with Handle (= cip_h).

LD

ST

A cip_h

CIPClose_instance

CIPClose

Execute Handle

Done Busy Error ErrorID ErrorIDEx

abc
def ghi jkl mno

CIPClose_instance(A, cip_h, abc, def, ghi, jkl, mno);

2-1056

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

2 Instruction Descriptions

The CIPClose instruction closes the CIP class 3 connection specified with Handle.

Controller that executed the instruction

Handle = cip_h Controller.

CIPClose

CIP class 3 connection is closed.

Related System-defined Variables

2

Name
_EIP_EtnOnlineSta*1 _EIP1_EtnOnlineSta*2 _EIP2_EtnOnlineSta*3 _EIPIn1_EtnOnlineSta*4

Meaning Online

Data type
BOOL

Description
This variable indicates when built-in EtherNet/IP port communications can be used. TRUE: Communications are possible. FALSE: Communications are not possible.

*1 Use this variable name for an NJ-series CPU Unit.

*2 Use this variable name for port 1 on an NX-series CPU Unit, or for an NY-series Controller.

*3 Use this variable name for port 2 on an NX-series CPU Unit.

*4 Use this variable name for the internal port on an NY-series Controller.

Additional Information
Refer to the following manuals for details on CIP communications. · NJ/NX-series CPU Unit Built-in EtherNet/IP Port User's Manual (Cat. No. W506) · NY-series Industrial Panel PC / Industrial Box PC Built-in EtherNet/IP Port User's Manual (Cat. No.
W563) · CJ-series EtherNet/IP Units Operation Manual for NJ-series CPU Unit (Cat. No. W495)

Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error. · Specify the handle that was obtained with the CIPOpen or CIPOpenWithDataSize instruction for Han-
dle. · You can use this instruction only through a built-in EtherNet/IP port on an NY-series Controller or an
NJ/NX-series CPU Unit, or through a port on an EtherNet/IP Unit connected to an NJ-series CPU Unit. · This instruction does not use ErrorIDEx. · An error occurs in the following cases. Error will change to TRUE. · The value of Handle.Handle is outside of the valid range. · More than 32 CIP-related instructions were executed simultaneously.

NJ/NX-series Instructions Reference Manual (W502)

2-1057

2 Instruction Descriptions
Sample Programming
Refer to the sample programming that is provided for the CIPOpen instruction (page 2-1026).

2-1058

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

CIPUCMMRead

2 Instruction Descriptions

CIPUCMMRead

The CIPUCMMRead instruction uses a UCMM explicit message to read the value of a variable in another Controller on the specified CIP network.

Instruction

Name

FB/ FUN

Graphic expression

ST expression

CIPUCMM Read

Read Variable FB UCMM Explicit

CIPUCMMRead_instance

CIPUCMMRead_instance(Execute,

CIPUCMMRead

RoutePath, TimeOut, SrcDat, Size,

Execute RoutePath

Done Busy

DstDat, Done, Busy, Error, ErrorID, ErrorIDEx, RcvSize);

2

TimeOut

Error

SrcDat

ErrorID

Size

ErrorIDEx

DstDat

RcvSize

Variables

Name

Meaning

RoutePath Route path

I/O

Description

Route path

TimeOut SrcDat Size
DstDat

Timeout time
Source variable name
Number of elements to read
Read data

Input In-out

Timeout time Name of variable to read in other Controller Number of elements to read
Read data value

RcvSize

Read data size

Output Read data size

Valid range
Depends on data type.
1 to 65535
Depends on data type.
0 to 496

Unit ---0.1 s
---

Depends on data type.
0 to 496

---
Bytes

Default
---
20 (2 s) '' 1
-----

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

RoutePath TimeOut SrcDat Size
DstDat
RcvSize

OK

OK

OK

OK

OK

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK

An enumeration, array, structure, structure member, or union member can also be specified.*

OK

* You cannot specify a STRING array.

NJ/NX-series Instructions Reference Manual (W502)

2-1059

2 Instruction Descriptions

Function

The CIPUCMMRead instruction reads the value of the network variable specified with source variable name SrcDat from another Controller on a CIP network. The other Controller is specified with route path RoutePath. The read data value is stored in DstDat.
Size specifies the number of elements to read. If SrcDat is an array, specify the number of elements to read with Size. If SrcDat is not an array, always specify 1 for Size. If the value of Size is 0, nothing is read regardless of whether SrcDat is an array or not. When the read operation is completed, the number of bytes of the data that was read is assigned to read data size RcvSize. The maximum size of the data that you can read depends on the data type of the variable as follows:
· Structure: 492 bytes
· STRING: 494 bytes
· Other data types: 496 bytes
TimeOut specifies the timeout time. If a response does not return within the timeout time, it is assumed that communications failed.
If the value of ErrorID is WORD#16#1C00, the CIP message error code is stored in ErrorIDEx.
In the following example, the value of variable abc in the remote Controller is read and stored in the variable def in the local Controller. The number of elements to read Size is UINT#1. The data type of abc and def is SINT. The size of SINT data is one byte, so the value of the read data size vwx is UINT#1.

LD

ST

A
`02\192.168.250.2' UINT#0 `abc' UINT#1
def

CIPUCMMRead_instance

CIPUCMMRead

Execute RoutePath TimeOut SrcDat Size DstDat

Done Busy Error ErrorID ErrorIDEx

RcvSize

ghi
jkl mno pqr stu
def vwx

CIPUCMMRead_instance(A, `2\192.168.250.2', UINT#0, `abc', UINT#1, def, ghi, jkl, mno, pqr, stu, vwx);

Value of variable SrcDat in remote Controller on the CIP network specified by the route path RoutePath is assigned to variable DstDat in local Controller. Size specifies the number of elements to read. The size of data that was read is assigned to RcvSize.

Controller that executed the instruction

IP address: 192.168.250.2

DstDat=def SINT#123 =abc SINT#123

Read.

SrcDat=abc SINT#123

Value of variable abc in remote

Size UINT#1

Controller is assigned to variable def in local Controller.

Variable abc in remote Controller

RcvSize=vwx UINT#1

The number of elements to read is 1.

The size of data that was read, one byte, is assigned to variable vwx.

2-1060

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

2 Instruction Descriptions

Reading Arrays

To read array data, pass a subscripted array element to ScrDat as the parameter. Also pass a subscripted array element to DstDat as the parameter.
The following example reads the four array variable elements abc[3] to abc[6] from the remote Controller and stores the results in array variable elements def[10] to def[13] in the local Controller. The data type of abc and def is INT. The size of INT data is two bytes, so the value of the read data size vwx is UINT#8.

LD

ST

A
`02\192.168.250.2' UINT#0 `abc[3]' UINT#4
def[10]

CIPUCMMRead_instance

CIPUCMMRead

Execute RoutePath TimeOut SrcDat Size DstDat

Done Busy Error ErrorID ErrorIDEx

RcvSize

ghi
jkl mno pqr stu
def[10] vwx

CIPUCMMRead_instance(A, `2\192.168.250.2',

UINT#0, `abc[3]', UINT#4,

2

def[10], ghi, jkl, mno, pqr,

stu, vwx);

Values of array variable elements abc[3] to abc[6] in remote Controller are assigned to array variable elements def[10] to def[13] in local Controller.
IP address: 192.168.250.2
Controller that executed the instruction

CIPUCMMRead

DstDat[0]=def[10] DstDat[1]=def[11] DstDat[2]=def[12] DstDat[3]=def[13]

INT#1234 =abc[3] INT#2345 =abc[4] INT#3456 =abc[5] INT#4567 =abc[6]

INT#1234 INT#2345 INT#3456 INT#4567

Read. Size UINT#4 The number of elements to read is 4.

Values of array variable abc in remote Controller are assigned to array variable def in local Controller.

SrcDat[0]=abc[3] SrcDat[1]=abc[4] SrcDat[2]=abc[5] SrcDat[3]=abc[6]

INT#1234 INT#2345 INT#3456 INT#4567

Array variable abc in remote Controller

RcvSize=vwx UINT#8 The size of data that was read, eight bytes, is assigned to variable vwx.

Related System-defined Variables

Name
_EIP_EtnOnlineSta*1 _EIP1_EtnOnlineSta*2 _EIP2_EtnOnlineSta*3 _EIPIn1_EtnOnlineSta*4

Meaning Online

Data type
BOOL

Description
This variable indicates when built-in EtherNet/IP port communications can be used. TRUE: Communications are possible. FALSE: Communications are not possible.

*1 Use this variable name for an NJ-series CPU Unit.

*2 Use this variable name for port 1 on an NX-series CPU Unit, or for an NY-series Controller.

*3 Use this variable name for port 2 on an NX-series CPU Unit.

*4 Use this variable name for the internal port on an NY-series Controller.

NJ/NX-series Instructions Reference Manual (W502)

2-1061

2 Instruction Descriptions

Additional Information
Refer to the following manuals for details on CIP communications. · NJ/NX-series CPU Unit Built-in EtherNet/IP Port User's Manual (Cat. No. W506) · NY-series Industrial Panel PC / Industrial Box PC Built-in EtherNet/IP Port User's Manual (Cat. No.
W563) · CJ-series EtherNet/IP Units Operation Manual for NJ-series CPU Unit (Cat. No. W495)

Precautions for Correct Use

· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.

· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error.

· This instruction can be used only for the built-in EtherNet/IP ports on NJ/NX-series CPU Units and NY-series Controllers.

· If a variable is read from an OMRON Controller, the variable must be published to the network. Publish the variable to the network in advance.

· You cannot specify an address in memory for CJ-series Units directly to read data. To read specific addresses in memory for CJ-series Units, use an AT specification in advance to assign the memory addresses to a variable.

· You cannot specify an address in local memory for CJ-series Units directly to store data. To store data in specific addresses in memory for CJ-series Units, use an AT specification in advance to assign the memory addresses to DstDat.

· The characters that can be used in SrcDat are specified in the following table.

Item
Maximum number of bytes

127 bytes

Specification

Character code UTF-8

Applicable char- Alphanumeric characters (not case sensitive), single-byte Katakana, multibyte characters,

acters

and `_' (underbars)

Prohibited text strings

· Any text string that starts with ASCII characters 0 to 9 (character codes 16#30 to 16#39) · A text string that consists of only a single _ (underbar) ASCII character · Any text string that includes two or more consecutive _ (underbar) ASCII characters · Any text string that starts with an _ (underbar) ASCII character · Any text string that ends with an _ (underbar) ASCII character · Any text string that starts with "P_"

· An error occurs in the following cases. Error will change to TRUE.

· The value of TimeOut is outside of the valid range.

· The value of Size is outside of the valid range.

· The text string in SrcDat is not valid.

· The data type of the value that was read does not agree with the data type of DstDat.

· The size of data that was read exceeds the range of DstDat.

· A data type that is not supported was specified for DstDat.

· An error response defined by CIP was returned.

· The text string in RoutePath is not valid.

· More than 32 CIP-related instructions were executed simultaneously.

· A response was not received even though the timeout time was exceeded.

2-1062

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

CIPUCMMRead

2 Instruction Descriptions

· There is a setting error for the local IP address.

· The instruction was executed when there was a BOOTP server error.

· A duplicated IP error occurred.

· For this instruction, expansion error code ErrorIDEx gives the CIP message error code. The meanings are as follows:

Value 16#02000000 16#04000000

Error
Normal communications are not possible due to a high load at the remote node.
The specified source variable is one of the following data types and it does not exist on the other Controller.

· Basic data type

· Enumeration

· Structure

2

· Union

· Array

16#05000000

The specified source variable is one of the following and it does not exist on the other Controller.

16#08000000 16#0C008010 16#0C008011 16#11000000 16#1F000102 16#1F008007 16#20008017 16#20008018
16#26000000

· Enumeration enumerator · Structure member · Union member · Array element The requested service does not support. The specified source variable is being downloaded.
The value of Size is exceeds the data size that can currently be read. The variable to read is a variable that is not possible to read. The inaccessible variable is specified. The specified source variable is not an array and the number of elements to read is not 1. The specified source variable is an array and the number of elements to read exceeds the number of elements in the array. The specified destination variable contains only the NULL character.

Sample Programming
Refer to the sample programming that is provided for the CIPUCMMSend instruction (page 2-1071).

NJ/NX-series Instructions Reference Manual (W502)

2-1063

2 Instruction Descriptions

CIPUCMMWrite

The CIPUCMMWrite instruction uses a UCMM explicit message to write the value of a variable in another Controller on a CIP network.

Instruction
CIPUCMM Write

Name
Write Variable UCMM Explicit

FB/ FUN
FB

Graphic expression

CIPUCMMWrite_instance

CIPUCMMWrite

Execute RoutePath TimeOut DstDat Size SrcDat

Done Busy Error ErrorID ErrorIDEx

ST expression
CIPUCMMWrite_instance(Execute, RoutePath, TimeOut, DstDat, Size, SrcDat, Done, Busy, Error, ErrorID, ErrorIDEx);

Variables

Name

Meaning

I/O

RoutePath Route path

TimeOut DstDat Size
SrcDat

Timeout time
Destination variable name
Number of elements to write
Source data

Input

Description Route path
Timeout time Name of variable to write in another Controller Number of elements to write
Data value to write

Valid range Depends on data type. 1 to 65535 Depends on data type. 0 to 488
Depends on data type.

* If you omit an input parameter, the default value is not applied. A building error will occur.

Unit --0.1 s
---

Default --20 (2 s) '' 1
*

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

RoutePath TimeOut DstDat Size
SrcDat

OK OK
OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK An enumeration, array*, structure, structure member, or union member can also be specified.

* You cannot specify a STRING array.

2-1064

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

CIPUCMMWrite

2 Instruction Descriptions

Function

The CIPUCMMWrite instruction writes the value of the network variable specified with destination variable name DstDat at another Controller on a CIP network. The other Controller is specified with route path RoutePath. The content of source data ScrDat is written. Size specifies the number of elements to write. If DstDat is an array, specify the number of elements to write with Size. If DstDat is not an array, always specify 1 for Size. If the value of Size is 0, nothing is written regardless of whether DstDat is an array or not.

TimeOut specifies the timeout time. If a response does not return within the timeout time, it is assumed

that communications failed. If the value of ErrorID is WORD#16#1C00, the CIP message error code is stored in ErrorIDEx.

2

The following example writes the value of variable def from the local Controller to the variable abc in the remote Controller. The number of elements to write Size is UINT#1.

LD

ST

A
`02\192.168.250.2' UINT#0 `abc' UINT#1 def

CIPUCMMWrite_instance

CIPUCMMWrite

Execute RoutePath TimeOut DstDat Size SrcDat

Done Busy Error ErrorID ErrorIDEx

ghi
jkl mno pqr stu

CIPUCMMWrite_instance(A, `2\192.168.250.2', UINT#0, `abc', UINT#1, def, ghi, jkl, mno, pqr, stu);

Value of variable ScrDat in local Controller is assigned to variable DstDat in remote Controller on the CIP network specified by the route path RoutePath. Size specifies the number of elements to write.

Controller that executed the instruction

IP address: 192.168.250.2

SrcDat=def SINT#123 Variable def in local Controller

Written.

DstDat=abc SINT#123 =def SINT#123

Size UINT#1

Value of variable def in local Controller is assigned to

variable abc in remote Controller.

The number of elements to write is 1. ]

NJ/NX-series Instructions Reference Manual (W502)

2-1065

2 Instruction Descriptions

Writing Arrays

To write array data, pass a subscripted array element to DstDat as the parameter. Also pass a subscripted array element to SrcDat as the parameter.
The following example stores the contents of array variable elements def[10] to def[13] in the four array variable elements abc[3] to abc[6].

LD

ST

A
`02\192.168.250.2' UINT#0 `abc[3]' UINT#4 def[10]

CIPUCMMWrite_instance

CIPUCMMWrite

Execute RoutePath TimeOut DstDat Size SrcDat

Done Busy Error ErrorID ErrorIDEx

ghi
jkl mno pqr stu

CIPUCMMWrite_instance(A, `2\192.168.250.2', UINT#0, `abc[3]', UINT#4, def[10], ghi, jkl, mno, pqr, stu);

0

]

Values of array variable elements def[10] to def[13] in local Controller are assigned to array variable elements abc[3] Ito abc[6] in remote Controller.
IP address: 192.168.250.2

Controller that executed the instruction

SrcDat[0]=def[10] SrcDat[1]=def[11] SrcDat[2]=def[12] SrcDat[3]=def[13]

INT#1234 INT#2345 INT#3456 INT#4567

Array variable def in local Controller

Written.

DstDat[0]=abc[3]

Size UINT#4

DstDat[1]=abc[4] DstDat[2]=abc[5]

DstDat[3]=abc[6]

The number of elements to write is 4.

INT#1234 =def[10] INT#2345 =def[11] INT#3456 =def[12] INT#4567 =def[13]

INT#1234 INT#2345 INT#3456 INT#4567

Values of array variable def in local Controller are assigned to array variable abc in remote Controller.

Maximum Write Data Size
The maximum size of the data that you can write depends on the data type and variable name that are specified for DstDat and the route path, as given in the following table. Maximum write data size [bytes] = Base size - Size of variable name of DstDat - Path information size

Item in above formula Base size

Meaning
· Data type of variable specified for DstDat is a structure: 492 bytes · Data type of variable specified for DstDat is a STRING: 494 bytes · Other data types: 496 bytes

2-1066

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

2 Instruction Descriptions

Item in above formula

Meaning

Size of variable name of DstDat · The size of the variable name is calculated as the total bytes for the ASCII characters in all structure levels plus two times the number of levels.

· If the number of bytes of ASCII characters in a level is an odd number, add 1.

· If a level in the structure is an array, add four times the number of dimensions in the array.

· Periods and commas in the structure and arrays are not included in the variable name size.

Example 1: When the Variable Name of DstDat Is aaa.bbbbb[1,2,3].cc

· The text string "aaa" in the first level is 3 bytes. It is an odd number, so 1 is

added to make 4 bytes. · The text string "bbbbb[1,2,3]" in the second level is 5 bytes. It is an odd

2

number, so 1 is added to make 6 bytes.

· Also bbbbb[1,2,3] is a three-dimensional array, so 3 times 4, or 12, is added to make 18 bytes.

· The text string "cc" in the third level is 2 bytes. It is an even number, so 2 bytes is used in the calculation.

· If we add the number of levels 3 times 2, or 6, to 4 bytes for the first level, 18 bytes for the second level, and 2 bytes for the third level, the size of the variable name come to 30 bytes.

Example 2: When the Variable Name of DstDat Is val

· The text string "val" in the first level is 3 bytes. It is an odd number, so 1 is added to make 4 bytes.

· If we then add the number of levels 1 times 2, or 2, the size of the variable name is 6 bytes.

Example 3: When the Variable Name of DstDat Is array[8].

· The text string "array" in the first level is 5 bytes. It is an odd number, so 1 is added to make 6 bytes.

· It is a one-dimensional array. Therefore, 1 times 4, or 4, is added.

· If we then add the number of levels 1 times 2, or 2, the size of the variable name is 12 bytes.

CIPUCMMWrite

NJ/NX-series Instructions Reference Manual (W502)

2-1067

2 Instruction Descriptions

Item in above formula Path information size

Meaning
· If there are no hops, the path information size is 0 bytes.* · If there are hops, the path information size is the route path size plus 12
bytes. · The route path size is the bytes size of the ASCII characters in the route
path. · However, the following precautions apply.
· If the address portion starts with "#", calculate the network and address portions as a total of 2 bytes.
· If the address portion does not start with "#", calculate the network portion as 2 bytes.
· If the address portion does not start with "#" and the number of bytes in the ASCII characters for the address portion is an odd number, add 1 byte.
· Do not include the level separator, "\", between levels of the route path in the route path size.
· Do not include the first hop in the route path size.
Example 1: When the Route Path Is 01\#11\02\192.168.250.2\01\#01
· The first hop in the route path size is not included, so ignore `01\#11' at the start of the path.
· The network type is `02', so use 2 bytes in the calculation. · The address portion is `192.168.250.2', so use 13 bytes in the calculation.
It is an odd number, so 1 is added to make 14 bytes. · For the following `01\#01', the address portion starts with "#", so the net-
work and address portions are calculated as a total of 2 bytes. · If you add all of the above sizes, the size of the route path is 18 bytes. · If we then add 12 bytes to the route path size, the path information size is
30 bytes.
Example 2: When the Route Path Is 02\192.168.250.2\01\#00
· The first hop in the route path size is not included, so ignore `02\192.168.250.2' at the start of the path.
· For the following `01#01', the address portion starts with "#", so the network and address portions are calculated as a total of 2 bytes.
· Therefore, the size of the route path is 2 bytes. · If we then add 12 bytes to the route path size, the path information size is
14 bytes.
Example 3: When the Route Path Is 02\192.168.250.2
· If there are no hops, the path information size is 0 bytes.

* A hop is routing between the sending node and receiving node. For example, if the route path is 02\192.168.250.2\01\#00, the message is first routed to the node with an IP address of 192.168.250.2 to send the message to unit address 00. This involves one hop.

Related System-defined Variables

Name
_EIP_EtnOnlineSta*1 _EIP1_EtnOnlineSta*2 _EIP2_EtnOnlineSta*3 _EIPIn1_EtnOnlineSta*4

Meaning Online

Data type
BOOL

Description
This variable indicates when built-in EtherNet/IP port communications can be used. TRUE: Communications are possible. FALSE: Communications are not possible.

*1 Use this variable name for an NJ-series CPU Unit.

*2 Use this variable name for port 1 on an NX-series CPU Unit, or for an NY-series Controller.

*3 Use this variable name for port 2 on an NX-series CPU Unit.

*4 Use this variable name for the internal port on an NY-series Controller.

2-1068

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

EtherNet/IP Communications Instructions

CIPUCMMWrite

Additional Information
Refer to the following manuals for details on CIP communications. · NJ/NX-series CPU Unit Built-in EtherNet/IP Port User's Manual (Cat. No. W506) · NY-series Industrial Panel PC / Industrial Box PC Built-in EtherNet/IP Port User's Manual (Cat. No.
W563) · CJ-series EtherNet/IP Units Operation Manual for NJ-series CPU Unit (Cat. No. W495)

Precautions for Correct Use

2

· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error.
· Always use a variable for the input parameter to pass to SrcDat. A building error will occur if a constant is passed.
· If SrcDat is an enumeration, you cannot directly pass an enumerator to it. A building error will occur if an enumerator is passed to it directly.
· You can use this instruction only through an NJ/NX-series CPU Unit, through a built-in EtherNet/IP port on an NY-series Controller, or through an EtherNet/IP Unit connected to an NJ-series CPU Unit.
· If a variable is written to an OMRON Controller, the variable must be published to the network. Publish the variable to the network in advance.
· You cannot specify an address in memory for CJ-series Units directly to write data. To write specific addresses in memory for CJ-series Units, use an AT specification in advance to assign the memory addresses to a variable.
· You cannot directly specify an address in local memory for CJ-series Units. To write specific addresses in memory for CJ-series Units, use an AT specification in advance to assign the memory addresses to SrcDat.
· The characters that can be used in DstDat are specified in the following table.

Item
Maximum number of bytes

127 bytes

Specification

Character code UTF-8

Applicable char- Alphanumeric characters (not case sensitive), single-byte Katakana, multibyte characters,

acters

and `_' (underbars)

Prohibited text strings

· Any text string that starts with ASCII characters 0 to 9 (character codes 16#30 to 16#39) · A text string that consists of only a single _ (underbar) ASCII character · Any text string that includes two or more consecutive _ (underbar) ASCII characters · Any text string that starts with an _ (underbar) ASCII character · Any text string that ends with an _ (underbar) ASCII character · Any text string that starts with "P_"

· An error occurs in the following cases. Error will change to TRUE.

· The value of TimeOut is outside of the valid range.

· The value of Size is outside of the valid range.

· The text string in DstDat is not valid.

· The value of Size exceeds the range of SrcDat.

· A data type that is not supported was specified for SrcDat.

NJ/NX-series Instructions Reference Manual (W502)

2-1069

2 Instruction Descriptions

· An error response defined by CIP was returned.

· The text string in RoutePath is not valid.

· More than 32 CIP-related instructions were executed simultaneously.

· A response was not received even though the timeout time was exceeded.

· There is a setting error for the local IP address.

· A duplicated IP error occurred.

· For this instruction, expansion error code ErrorIDEx gives the CIP message error code. The meanings are as follows:

Value 16#02000000 16#04000000

Error
Normal communications are not possible due to a high load at the remote node.
The specified source variable is one of the following data types and it does not exist on the other Controller.

16#05000000

· Basic data type · Enumeration · Structure · Union · Array The specified source variable is one of the following and it does not exist on the other Controller.

16#08000000 16#0C008010 16#0C008011 16#1F000102 16#1F008007 16#20008017 16#20008018
16#20008028
16#26000000

· Enumeration enumerator · Structure member · Union member · Array element The requested service does not support. The specified destination variable is being downloaded.
The specified destination variable has a Constant attribute, so it cannot be written. The inaccessible variable is specified. The specified destination variable is not an array and the number of elements to write is not 1. The specified destination variable is an array and the number of elements to write exceeds the number of elements in the array. · The specified destination variable is an enumeration and the write data is not the value of an
enumerator. · The specified destination variable has a Range Specification attribute and the write data is
out of range. The specified destination variable name is only the NULL character.

Sample Programming
Refer to the sample programming that is provided for the CIPUCMMSend instruction (page 2-1071).

2-1070

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

CIPUCMMSend

2 Instruction Descriptions

CIPUCMMSend

The CIPUCMMSend instruction sends a UCMM CIP message to a specified device on a CIP network.

Instruction
CIPUCMM Send

Name
Send Explicit Message UCMM

FB/ FUN
FB

Graphic expression

CIPUCMMSend_instance

CIPUCMMSend

Execute

Done

RoutePath

Busy

TimeOut

Error

ServiceCode ErrorID

RqPath

ErrorIDEx

ServiceDat RespSize

Size

RespServiceDat

ST expression

CIPUCMMSend_instance(Execute,

RoutePath, TimeOut, ServiceCode,

RqPath, ServiceDat, Size,

RespServiceDat, Done, Busy, Error,

ErrorID, ErrorIDEx, RespSize);

2

Variables

Name RoutePath TimeOut

Meaning Route path Timeout time

I/O

Description

Route path

Timeout time

Valid range

Unit

Depends on data type. ---

1 to 65535

0.1 s

ServiceCode RqPath ServiceDat
Size
RespServiceD at RespSize

Service code
Request path
Command data
Number of elements to send
Response data
Response size

Input
In-out Output

Service code Request path Data to send Number of elements to send
Response data Response data size

Depends on data type.
-----
Depends on data type.
Depends on data type. --Depends on data type. Bytes

* If you omit an input parameter, the default value is not applied. A building error will occur.

Default
---
20 (2.0 s)
---
*
1
---
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

RoutePath
TimeOut Service Code ReqPath
ServiceDat
Size

OK
OK OK
Refer to Function for details on the structure _sREQUEST_PATH or _sREQUEST_PATH_EX *1. OK OK OK OK OK OK OK OK OK OK OK OK OK OK
An array, structure member, or union member can also be specified. OK

NJ/NX-series Instructions Reference Manual (W502)

2-1071

2 Instruction Descriptions

numbers REAL

Boolean BOOL

Bit strings

Integers

Real

Times, durations, dates, and text strings

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

RespServiceDat
RespSize

OK OK OK OK OK OK OK OK OK OK OK OK OK OK An array, structure member, or union member can also be specified. OK

*1 A CPU Unit with unit version 1.11 or later and Sysmac Studio version 1.15 or higher are required to specify _sREQUEST_PATH_EX type.

Function
The CIPUCMMSend instruction sends command data ServiceDat for the service specified with service code ServiceCode as a UCMM explicit message. The destination is specified with route path RoutePath. RqPath specifies the request path.
Size specifies the number of elements to send. If ServiceDat is an array, specify the number of elements to send with Size. If ServiceDat is not an array, always specify 1 for Size. If no service data is required, set Size to 0.
The response data received later is stored in RespServiceDat. The number of bytes of the response data is stored in RespSize.
TimeOut specifies the timeout time. If a response does not return within the timeout time, it is assumed that communications failed.
The data type of RqPath is structure _sREQUEST_PATH or _sREQUEST_PATH_EX.
Normally, use _sREQUEST_PATH. When you want to specify the logical format size, use _sREQUEST_PATH_EX. The specifications are as follows:

· _sREQUEST_PATH type

Name RqPath

Meaning Request path

ClassID InstanceID isAttributeID

Class ID
Instance ID
Attribute usage

AttributeID

Attribute ID

Description Request path
Class ID Instance ID TRUE:Attribute ID used. FALSE:Attribute ID not
used. Attribute ID

Data type _sREQUEST_PATH UINT UINT BOOL
UINT

Valid range
---
Depends on data type.

Note The logical format size of each ID in _sREQUEST_PATH type is 16 bits.

Unit Default
--- ---
0 --- FALSE
0

2-1072

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

CIPUCMMSend

2 Instruction Descriptions

· _sREQUEST_PATH_EX type

Name

Meaning

Description

Data type

Valid range Unit Default

RqPath

Request path Request path

_sREQUEST_ PATH_EX

---

--- ---

ClassIDLogica Class ID

Class ID data size

lFormat

logical format

_eCIP_LOGIC AL_FORMAT

_8BIT

ClassID

Class ID

Class ID

UDINT

0

InstanceIDLog Instance ID Instance ID data size

icalFormat

logical format

_eCIP_LOGIC AL_FORMAT

_8BIT

InstanceID isAttributeID

Instance ID
Attribute usage

Instance ID
TRUE:Attribute ID used.
FALSE:Attribute ID not used.

UDINT BOOL

Depends on data type.

--- 0 FALSE

2

AttributeIDLogi Attribute ID Attribute ID data size

calFormat

logical format

_eCIP_LOGIC AL_FORMAT

_8BIT

AttributeID

Attribute ID Attribute ID

UDINT

0

The data type of ClassIDLogicalFormat, InstanceIDLogicalFormat, and AttributeIDLogicalFormat is enumerated type _eCIP_LOGICAL_FORMAT.
The meanings of the enumerators of enumerated type _eCIP_LOGICAL_FORMAT are as follows:

Enumerator
_8BIT _16BIT _32BIT

Meaning
8 bits 16 bits 32 bits

If the value of ErrorID is WORD#16#1C00, the CIP message error code is stored in ErrorIDEx. The meaning and values of ErrorIDEx depend on the remote node. Refer to the manual for the remote node.

Sending and Receiving Arrays
If ServiceDat or RespServiceDat is an array, pass a subscripted array element to it as the parameter.

Maximum Read/Write Data Size
You can read a maximum of 492 bytes of data. The maximum size of the data that you can write depends on whether there is a request path attribute and the route path that is used, as given below. Maximum write data size [bytes] = Base size - Attribute usage - Path information size

Item in above formula Base size Attribute usage*1

500 bytes Attribute ID used: 14 bytes Attribute ID not used: 10 bytes

Meaning

NJ/NX-series Instructions Reference Manual (W502)

2-1073

2 Instruction Descriptions

Item in above formula

Meaning

Path information size

· If there are no hops, the path information size is 0 bytes.*2 · If there are hops, the path information size is the route path size plus 12
bytes. · The route path size is the bytes size of the ASCII characters in the route
path. · However, the following precautions apply.
· If the address portion starts with "#", calculate the network and address portions as a total of 2 bytes.
· If the address portion does not start with "#", calculate the network portion as 2 bytes.
· If the address portion does not start with "#" and the number of bytes in the ASCII characters for the address portion is an odd number, add 1 byte.
· Do not include the level separator, "\", between levels of the route path in the route path size.
· Do not include the first hop in the route path size.
Example 1: When the Route Path Is 01\#11\02\192.168.250.2\01\#01
· The first hop in the route path size is not included, so ignore `01\#11' at the start of the path.
· The network type is `02', so use 2 bytes in the calculation.
· The address portion is `192.168.250.2', so use 13 bytes in the calculation. It is an odd number, so 1 is added to make 14 bytes.
· For the following `01\#01', the address portion starts with "#", so the network and address portions are calculated as a total of 2 bytes.
· If you add all of the above sizes, the size of the route path is 18 bytes. · If we then add 12 bytes to the route path size, the path information size is
30 bytes.
Example 2: When the Route Path Is 02\192.168.250.2\01\#00
· The first hop in the route path size is not included, so ignore `02\192.168.250.2' at the start of the path.
· For the following `01#01', the address portion starts with "#", so the network and address portions are calculated as a total of 2 bytes.
· Therefore, the size of the route path is 2 bytes.
· If we then add 12 bytes to the route path size, the path information size is 14 bytes.
Example 3: When the Route Path Is 02\192.168.250.2
· If there are no hops, the path information size is 0 bytes.

*1 With a CPU Unit with unit version 1.10 or earlier or Sysmac Studio version 1.14 or lower, the values are as follows: Attribute ID used: 12 bytes Attribute ID not used: 8 bytes
*2 A hop is routing between the sending node and receiving node. For example, if the route path is 02\192.168.250.2\01\#00, the message is first routed to the node with an IP address of 192.168.250.2 to send the message to unit address 00. This involves one hop.

2-1074

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

EtherNet/IP Communications Instructions

CIPUCMMSend

Related System-defined Variables

Name
_EIP_EtnOnlineSta*1 _EIP1_EtnOnlineSta*2 _EIP2_EtnOnlineSta*3 _EIPIn1_EtnOnlineSta*4

Meaning Online

Data type
BOOL

Description
This variable indicates when built-in EtherNet/IP port communications can be used. TRUE: Communications are possible. FALSE: Communications are not possible.

*1 Use this variable name for an NJ-series CPU Unit.

*2 Use this variable name for port 1 on an NX-series CPU Unit, or for an NY-series Controller.

*3 Use this variable name for port 2 on an NX-series CPU Unit.

2

*4 Use this variable name for the internal port on an NY-series Controller.

Additional Information
Refer to the following manuals for details on CIP communications. · NJ/NX-series CPU Unit Built-in EtherNet/IP Port User's Manual (Cat. No. W506) · NY-series Industrial Panel PC / Industrial Box PC Built-in EtherNet/IP Port User's Manual (Cat. No.
W563) · CJ-series EtherNet/IP Units Operation Manual for NJ-series CPU Unit (Cat. No. W495)

Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error.
· Always use a variable for the input parameter to pass to ServiceDat. A building error will occur if a constant is passed.
· You can use this instruction only through a built-in EtherNet/IP port on an NY-series Controller or an NJ/NX-series CPU Unit, or through a port on an EtherNet/IP Unit connected to an NJ-series CPU Unit.
· If a variable is written to an OMRON Controller, the variable must be published to the network. Publish the variable to the network in advance.
· An error occurs in the following cases. Error will change to TRUE.
· A value that is out of valid range is set for RqPath.ClassIDLogicalFormat or RqPath.AttributeIDLogicalFormat.
· A mismatch occurred between the following two variables: the size specified for RqPath.ClassIDLogicalFormat and the data size of RqPath.ClassID, the size specified for RqPath.InstanceIDLogicalFormat and the data size of RqPath.InstanceID, or the size specified for RqPath.AttributeIDLogicalFormat and the data size of RqPath.AttributeID.
· The value of TimeOut is outside of the valid range.
· The value of Size exceeds the write data range.
· The value of Size exceeds the range of ServiceDat.
· The value of RespSize exceeds the range of RespServiceDat.
· A data type that is not supported was specified for ServiceDat.
· A data type that is not supported was specified for RespServiceDat.
· A variable whose data type is other than _sREQUEST_PATH or _sREQUEST_PATH_EX is specified for RqPath.
· There is a setting error for the local IP address.

NJ/NX-series Instructions Reference Manual (W502)

2-1075

2 Instruction Descriptions

· A duplicated IP error occurred. · The instruction was executed when there was a BOOTP server error. · An error response defined by CIP was returned. · The text string in RoutePath is not valid. · More than 32 CIP-related instructions were executed simultaneously. · A response was not received even though the timeout time was exceeded.

Sample Programming

This sample uses CIP UCMM messages to write a variable, read a variable, and send a message. The Controllers are connected to an EtherNet/IP network. The IP address of the remote node is 192.168.250.2. The following procedure is used.
1 The CIPUCMMWrite instruction is used to write the value of a variable at a remote node. The variable name at the remote node is WritingDat and the contents of the WriteDat is written to it. WritingDat must be defined as a global variable at the remote node and the Network Publish attribute must be set.
2 The CIPUCMMRead instruction is used to read the value of a variable at a remote node. The value of the variable OriginalDat at the other node is read and the read value is stored in the ReadDat variable. OriginalDat must be defined as a global variable at the remote node and the Network Publish attribute must be set.
3 The CIPUCMMSend instruction is used to send an explicit message to a remote node. The contents of the message is to read identity information (product name). The class ID, instance ID, attribute ID, and service code are as follows: The response data is stored in the ResDat variable.

Item Class ID Instance ID Attribute ID Service code

1 1 7 16#0E

Value

IP address: 192.168.250.2

Built-in EtherNet/IP port

Built-in EtherNet/IP port

WriteDat

Value of variable written. Variable name: WritingDat, global variable with a Network Publish attribute

ReadDat

Value of variable read.

Variable name: OriginalDat, global variable with a Network Publish attribute

ResDat

Message sent to read identity information (product name).
Response

2-1076

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

CIPUCMMSend

2 Instruction Descriptions

LD

Variable OperatingEnd

Data type BOOL

Initial value FALSE

Comment Processing completed

Trigger

BOOL

FALSE

Execution condition

Operating WriteDat

BOOL INT

FALSE 1234

Processing Write data

ReadDat

INT

0

Read data

ReqPath

_sREQUEST_PATH

(ClassID:=0, InstanceID:=0,
isAttributeID:=FALSE, AttributeID:=0)

Request path

ResDat Dummy

ARRAY[0..10] OF BYTE [11(16#0)]

BYTE

16#0

Response data

2

Dummy

RS_instance

RS

CIPUCMMWrite_instance CIPUCMMWrite CIPUCMMRead_instance CIPUCMMRead

CIPUCMMSend_instance CIPUCMMSend

Determine if instruction execution is completed. CIPUCMMWrite_instance.Done CIPUCMMRead_instance.Done CIPUCMMSend_instance.Done OperatingEnd
CIPUCMMWrite_instance.Error CIPUCMMRead_instance.Error CIPUCMMSend_instance.Error

Accept trigger.

Trigger CIPUCMMWrite_instance.Busy CIPUSMMRead_instance.Busy CIPUCMMSend_instance.Busy 1

RS_instance RS

Operating

1

Set

Q1

OperatingEnd Reset1

NJ/NX-series Instructions Reference Manual (W502)

2-1077

2 Instruction Descriptions

Instruction execution Operating
`02\192.168.250.2' UINT#20
`WritingDat' UINT#1
WriteDat

CIPUCMMWrite_instance

CIPUCMMWrite

Execute RoutePath TimeOut DstDat Size SrcDat

Done Busy Error ErrorID ErrorIDEx

CIPUCMMWrite_instance.Done
`02\192.168.250.2' UINT#20
`OriginalDat' UINT#1
ReadDat

CIPUCMMRead_instance

CIPUCMMRead

Execute RoutePath TimeOut SrcDat Size DstDat

Done Busy Error ErrorID ErrorIDEx

RcvSize

ReadDat

CIPUCMMRead_instance.Done @MOVE

EN UINT#1 In

ENO Out

ReqPath.ClassID

UINT#1

@MOVE

EN

ENO

In

Out

ReqPath.InstanceID

TRUE

@MOVE

EN

ENO

In

Out

ReqPath.isAttributeID

UINT#7

@MOVE

EN

ENO

In

Out

ReqPath.AttributeID

`02\192.168.250.2' UINT#20
BYTE#16#0E ReqPath Dummy UINT#0
ResDat

CIPUCMMSend_instance

CIPUCMMSend

Execute

Done

RoutePath

Busy

TimeOut

Error

ServiceCode ErrorID

RqPath

ErrorIDEx

ServiceDat RespSize

Size

RespServiceDat

2-1078

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

EtherNet/IP Communications Instructions

CIPUCMMSend

Processing after normal end Operating CIPUCMMSend_instance.Done

Inline ST
1 // Processing after normal end 2 ;

Processing after error end Operating CIPUCMMWrite_instance.Error

Inline ST
1 // Processing after error end 2 ;

CIPUCMMRead_instance.Error

2

CIPUCMMSend_instance.Error

ST
Internal Variables

Variable
Trigger DoUCMMTrigger Stage WriteDat ReadDat

ReqPath

ResDat
Dummy
CIPUCMMWrite_instance
CIPUCMMRead_instance
CIPUCMMSend_instance

Data type

Initial value

BOOL

FALSE

BOOL

FALSE

INT

0

INT

0

INT

0

_sREQUEST_PATH

(ClassID:=0, InstanceID:=0,
isAttributeID:=FALSE, AttributeID:=0)

ARRAY[0..10] OF BYTE [11(16#0)]

BYTE

16#0

CIPUCMMWrite

CIPUCMMRead

CIPUCMMSend

Comment Execution condition Processing Stage change Write data Read data
Request path
Response data Dummy

External Variables

Variable _EIP_EtnOnlineSta

Constant

Data type BOOL

Comment Online

// Start sequence when Trigger changes to TRUE.

IF ( (Trigger=TRUE) AND (DoUCMMTrigger=FALSE) AND (_Eip_EtnOnlineSta=TRUE) ) THEN

DoUCMMTrigger:=TRUE;

Stage

:=INT#1;

CIPUCMMWrite_instance(

Execute

:=FALSE,

// Initialize instance.

SrcDat

:=WriteDat); // Dummy

CIPUCMMRead_instance(

// Initialize instance.

Execute

:=FALSE,

// Dummy

DstDat

:=ReadDat); // Dummy

CIPUCMMSend_instance(

Execute

:=FALSE,

// Initialize instance.

ServiceDat := Dummy,

// Dummy

RespServiceDat:=ResDat);

// Dummy

NJ/NX-series Instructions Reference Manual (W502)

2-1079

2 Instruction Descriptions

END_IF;

IF (DoUCMMTrigger=TRUE) THEN

CASE Stage OF

1 :

// Request writing value of variable.

CIPUCMMWrite_instance(

Execute :=TRUE,

RoutePath:='02\192.168.250.2', // Route path

TimeOut :=UINT#20,

// Timeout time

DstDat :='WritingDat',

// Destination variable name

Size

:=UINT#1,

// Number of elements to write

SrcDat :=WriteDat);

// Write data

IF (CIPUCMMWrite_instance.Done=TRUE) THEN Stage:=INT#2; // Normal end
ELSIF (CIPUCMMWrite_instance.Error=TRUE) THEN Stage:=INT#10; // Error end END_IF;

2 :

// Request reading value of variable.

CIPUCMMRead_instance(

Execute :=TRUE,

RoutePath:='02\192.168.250.2', // Route path

TimeOut :=UINT#20,

// Timeout time

SrcDat :='OriginalDat',

// Destination variable name

Size

:=UINT#1,

// Number of elements to read

DstDat :=ReadDat);

// Read data

IF (CIPUCMMRead_instance.Done=TRUE) THEN Stage:=INT#3; // Normal end
ELSIF (CIPUCMMRead_instance.Error=TRUE) THEN Stage:=INT#40; // Error end
END_IF;

3 :

// Send message

ReqPath.ClassID

:=UINT#01;

ReqPath.InstanceID :=UINT#01;

ReqPath.isAttributeID:=TRUE;

ReqPath.AttributeID :=UINT#07;

CIPUCMMSend_instance(

Execute

:=TRUE,

RoutePath

:='02\192.168.250.2',

TimeOut

:=UINT#20,

ServiceCode :=BYTE#16#0E,

RqPath

:=ReqPath,

ServiceDat :=Dummy,

Size

:=UINT#0,

RespServiceDat:=ResDat);

// Route path // Timeout time // Service code // Request path // Service data // Number of elements // Response data

IF (CIPUCMMSend_instance.Done=TRUE) THEN

Stage:=INT#0;

// Normal end

ELSIF (CIPUCMMSend_instance.Error=TRUE) THEN

Stage:=INT#30; // Error end

END_IF;

0:

// Processing after normal end

DoUCMMTrigger:=FALSE;

Trigger

:=FALSE;

ELSE // Processing after error end

DoUCMMTrigger:=FALSE;

Trigger

:=FALSE;

END_CASE;

END_IF;

2-1080

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

SktUDPCreate

2 Instruction Descriptions

SktUDPCreate

The SktUDPCreate instruction creates a UDP socket request to open a servo port for the built-in EtherNet/IP.

Instruction

Name

SktUDP Create Create UDP Socket

FB/ FUN
FB

Graphic expression

SktUDPCreate_instance

SktUDPCreate

Execute SrcUdpPort

Done Busy Error ErrorID Socket

ST expression

SktUDPCreate_instance(Execute,

SrcUdpPort, Done, Busy, Error,

ErrorID, Socket);

2

Variables

Name SrcUdpPort
Socket

Meaning
Local UDP port number
Socket

I/O Input
Output

Description Local UDP port number
Socket

Bit strings

Integers

Valid range 1 to 65535
---

Unit
---
---

Default 1
---

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

SrcUdpPort Socket

OK Refer to Function for details on the structure _sSOCKET.

Function
The SktUDPCreate instruction opens the port specified with the local UDP port number ScrUdpPort. To do this, it executes the Socket() and Bind() socket functions. Information on the socket that is opened is stored in Socket. The UDP port is open when the instruction is completed normally (i.e., when the value of Done changes to TRUE).

NJ/NX-series Instructions Reference Manual (W502)

2-1081

2 Instruction Descriptions

The data type of Socket is structure _sSOCKET. The specifications are as follows:

Name Socket
Handle
SrcAdr*1 PortNo IpAdr*1
DstAdr*1 PortNo*1 IpAdr*1

Meaning Socket Handle
Local address
Port number IP address
Destination address Port number IP address

Description
Socket
Handle for data communications
Local IP address and port number
Port number
IP address or host name. A DNS or Hosts setting is required to use a host name.
Destination IP address and port number
Port number
IP address or host name. A DNS or Hosts setting is required to use a host name.

Data type _sSOCKET UDINT
_sSOCKET_ ADDRESS UINT STRING
_sSOCKET_ ADDRESS UINT STRING

Valid range
---
Depends on data type.
---
1 to 65535 Depends on data type.
---
1 to 65535 Depends on data type.

*1 A value of 0 or NULL is output for these members.

Unit
-----

Default
---
0

--- ---

0

--- `'

--- ---
0 --- `'

Related System-defined Variables

Name

Meaning

Data type

Description

_EIP_EtnOnlineSta*1 _EIP1_EtnOnlineSta*2 _EIP2_EtnOnlineSta*3 _EIPIn1_EtnOnlineSta*4

Online

BOOL

This variable indicates when built-in EtherNet/IP port communications can be used.
TRUE: Communications are possible.
FALSE: Communications are not possible.

*1 Use this variable name for an NJ-series CPU Unit.

*2 Use this variable name for port 1 on an NX-series CPU Unit, or for an NY-series Controller.

*3 Use this variable name for port 2 on an NX-series CPU Unit.

*4 Use this variable name for the internal port on an NY-series Controller.

Additional Information
Refer to the NJ/NX-series CPU Unit Built-in EtherNet/IP Port User's Manual (Cat. No. W506) or NYseries Industrial Panel PC / Industrial Box PC Built-in EtherNet/IP Port User's Manual (Cat. No. W563) for details on socket services.

Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error. · This instruction can be used only for the built-in EtherNet/IP on NJ/NX-series CPU Units and NY-
series Controllers. · Use the SktClose instruction to close handles that are created with this instruction. · Handles that are created with this instruction are disabled when you change to PROGRAM mode.

2-1082

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

SktUDPCreate

2 Instruction Descriptions

· Except for NX102 CPU Units, you can execute a maximum of 32 of the following instructions at the same time: SktUDPCreate, SktUDPRcv, SktUDPSend, SktTCPAccept, SktTCPConnect, SktTCPRcv, SktTCPSend, SktGetTCPStatus, SktClose, SktClearBuf, SktSetOption, ModbusTCPCmd, ModbusTCPRead, and ModbusTCPWrite. For NX102 CPU Units, a maximum of 64 instructions can be executed.
· An error occurs in the following cases. Error will change to TRUE.
· There is a setting error for the local IP address.
· The value of SrcUdpPort is outside of the valid range.
· The port that is specified with SrcUdpPort is already open or close processing is in progress for it.
· The port that is specified with ScrUdpPort is already in use.

Version Information

2

· The number of sockets that you can open at the same time depends on the unit version of the CPU Unit as shown in the following table. These limits are the totals for both UDP and TCP sockets.

Unit version of CPU Unit 1.03 or higher 1.02 or lower

Number of sockets 30 max.*1 16 max.

*1 For NX102 CPU Units, a maximum of 60 instructions can be opened.

· For CPU Unit version 1.10 or later, the value of Socket does not change even if Error changes to TRUE. For version 1.09 or earlier, the value of Socket changes to 0.

Sample Programming

In this sample, the UDP socket service is used for data communications between the NJ/NX-series Controller and a remote node.

IP address: 192.168.250.1 UDP port number: 6000

IP address: 192.168.250.2 UDP port number: 6001

Data sent. Data received.

Remote node

Built-in EtherNet/IP port
Ethernet line
The processing procedure is as follows:
1 The SktUDPCreate instruction is used to request creating a UDP socket. 2 The SktUDPSend instruction is used to request sending data. The data in SendSocketDat[] is
sent.
3 The SktUDPRcv instruction is used to request receiving data. The received data is stored in RcvSocketDat[].
4 The SktClose instruction is used to close the socket.

NJ/NX-series Instructions Reference Manual (W502)

2-1083

2 Instruction Descriptions

ST
Internal Variables

Variable
Trigger DoSendAndRcv Stage

RcvSocketDat

Data type
BOOL BOOL INT ARRAY[0..1999] OF BYTE

WkSocket

_sSOCKET

SendSocketDat
SktUDPCreate_instance SktUDPSend_instance SktUDPRcv_instance SktClose_instance

ARRAY[0..1999] OF BYTE SktUDPCreate SktUDPSend SktUDPRcv SktClose

Initial value
FALSE FALSE 0
[2000(16#0)]
(Handle:=0, SrcAdr:=(PortNo:=0, IpAdr:=''), DstAdr:=(PortNo:=0, IpAdr:=''))
[2000(16#0)]

Comment Execution condition Processing Stage change Receive data
Socket
Send data

External Variables

Variable _EIP_EtnOnlineSta

Data type BOOL

Constant Online

Comment

// Start sequence when Trigger changes to TRUE.

IF ( (Trigger=TRUE) AND (DoSendAndRcv=FALSE) AND (_Eip_EtnOnlineSta=TRUE) ) THEN

DoSendAndRcv:=TRUE;

Stage

:=INT#1;

SktUDPCreate_instance(Execute:=FALSE);

// Initialize instance.

SktUDPSend_instance(

// Initialize instance.

Execute

:=FALSE,

SendDat

:=SendSocketDat[0]); // Dummy

SktUDPRcv_instance(

// Initialize instance.

Execute

:=FALSE,

RcvDat

:=RcvSocketDat[0]); // Dummy

SktClose_instance(Execute:=FALSE);

// Initialize instance.

END_IF;

IF (DoSendAndRcv=TRUE) THEN

CASE Stage OF

1 :

// Request creating socket.

SktUDPCreate_instance(

Execute :=TRUE,

SrcUdpPort:=UINT#6000, // Local UDP port number

Socket

=>WkSocket); // Socket

IF (SktUDPCreate_instance.Done=TRUE) THEN Stage:=INT#2; // Normal end
ELSIF (SktUDPCreate_instance.Error=TRUE) THEN Stage:=INT#10; // Error end
END_IF;

2 :

// Request sending data

WkSocket.DstAdr.PortNo:=UINT#6001;

WkSocket.DstAdr.IpAdr :='192.168.250.2';

SktUDPSend_instance(

Execute:=TRUE,

Socket :=WkSocket,

// Socket

SendDat:=SendSocketDat[0], // Send data

Size :=UINT#2000);

// Send data size

2-1084

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

SktUDPCreate

2 Instruction Descriptions

IF (SktUDPSend_instance.Done=TRUE) THEN Stage:=INT#3; // Normal end
ELSIF (SktUDPSend_instance.Error=TRUE) THEN Stage:=INT#20; // Error end
END_IF;

3 :

// Request receiving data.

SktUDPRcv_instance(

Execute:=TRUE,

Socket :=WkSocket,

// Socket

TimeOut:=UINT#0,

// Timeout time

Size :=UINT#2000,

// Receive data size

RcvDat :=RcvSocketDat[0]); // Receive data

2

IF (SktUDPRcv_instance.Done=TRUE) THEN Stage:=INT#4; // Normal end
ELSIF (SktUDPRcv_instance.Error=TRUE) THEN Stage:=INT#30; // Error end
END_IF;

4 :

// Request closing.

SktClose_instance(

Execute:=TRUE,

Socket :=WkSocket);

// Socket

IF (SktClose_instance.Done=TRUE) THEN

Stage:=INT#0;

// Normal end

ELSIF (SktClose_instance.Error=TRUE) THEN

Stage:=INT#40;

// Error end

END_IF;

0 :

// Normal end

DoSendAndRcv:=FALSE;

Trigger

:=FALSE;

ELSE // Interrupted by error.

DoSendAndRcv:=FALSE;

Trigger

:=FALSE;

END_CASE;

END_IF;

NJ/NX-series Instructions Reference Manual (W502)

2-1085

2 Instruction Descriptions
 Programming in the Remote Node
In this example, programming is also required in the remote node. The order of sending and receiving is reversed in comparison with the above procedure.
1 The SktUDPCreate instruction is used to request creating a UDP socket. 2 The SktUDPRcv instruction is used to request receiving data. The received data is stored in
RcvSocketDat[].
3 The SktUDPSend instruction is used to request sending data. The data in SendSocketDat[] is sent.
4 The SktClose instruction is used to close the socket.

2-1086

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

EtherNet/IP Communications Instructions

SktUDPCreate

ST

Internal Variables

Variable

Data type

Initial value

Comment

Trigger

BOOL

FALSE

Execution condition

DoSendAndRcv

BOOL

FALSE

Processing

Stage

INT

0

Stage change

RcvSocketDat

ARRAY[0..1999] OF BYTE

[2000(16#0)]

Receive data

(Handle:=0, SrcAdr:=(PortNo:=0,

WkSocket

_sSOCKET

IpAdr:=''), DstAdr:=(PortNo:=0,

Socket

SendSocketDat

ARRAY[0..1999] OF BYTE

IpAdr:='')) [2000(16#0)]

2
Send data

SktUDPCreate_instance SktUDPCreate

SktUDPSend_instance SktUDPSend

SktUDPRcv_instance

SktUDPRcv

SktClose_instance

SktClose

External Variables

Variable _EIP_EtnOnlineSta

Data type BOOL

Constant Online

Comment

// Start sequence when Trigger changes to TRUE.

IF ( (Trigger=TRUE) AND (DoSendAndRcv=FALSE) AND (_Eip_EtnOnlineSta=TRUE) ) THEN

DoSendAndRcv:=TRUE;

Stage

:=INT#1;

SktUDPCreate_instance(Execute:=FALSE); // Initialize instance.

SktUDPSend_instance(

// Initialize instance.

Execute :=FALSE,

SendDat :=SendSocketDat[0]); // Dummy

SktUDPRcv_instance(

// Initialize instance.

Execute :=FALSE,

RcvDat :=RcvSocketDat[0]); // Dummy

SktClose_instance(Execute:=FALSE);

// Initialize instance.

END_IF;

IF (DoSendAndRcv=TRUE) THEN

CASE Stage OF

1 :

// Request creating socket.

SktUDPCreate_instance(

Execute :=TRUE,

SrcUdpPort:=UINT#6001, // Local UDP port number

Socket

=>WkSocket); // Socket

IF (SktUDPCreate_instance.Done=TRUE) THEN Stage:=INT#2; // Normal end
ELSIF (SktUDPCreate_instance.Error=TRUE) THEN Stage:=INT#10; // Error end
END_IF;

2 :

// Request receiving data

SktUDPRcv_instance(

Execute:=TRUE,

Socket :=WkSocket,

TimeOut:=UINT#0,

Size :=UINT#2000,

RcvDat :=RcvSocketDat[0]);

// Socket // Timeout time // Receive data size // Receive data

NJ/NX-series Instructions Reference Manual (W502)

2-1087

2 Instruction Descriptions

IF (SktUDPRcv_instance.Done=TRUE) THEN Stage:=INT#3; // Normal end
ELSIF (SktUDPRcv_instance.Error=TRUE) THEN Stage:=INT#20; // Error end
END_IF;

3 :

// Request sending data.

WkSocket.DstAdr.PortNo:=UINT#6000;

WkSocket.DstAdr.IpAdr :='192.168.250.1';

SktUDPSend_instance(

Execute :=TRUE,

Socket :=WkSocket,

// Socket

SendDat :=SendSocketDat[0], // Send data

Size :=UINT#2000);

// Send data size

IF (SktUDPSend_instance.Done=TRUE) THEN Stage:=INT#4; // Normal end
ELSIF (SktUDPSend_instance.Error=TRUE) THEN Stage:=INT#30; // Error end
END_IF;

4 :

// Request closing.

SktClose_instance(

Execute:=TRUE,

Socket :=WkSocket);

// Socket

IF (SktClose_instance.Done=TRUE) THEN

Stage:=INT#0;

// Normal end

ELSIF (SktClose_instance.Error=TRUE) THEN

Stage:=INT#40;

// Error end

END_IF;

0 :

// Normal end

DoSendAndRcv:=FALSE;

Trigger

:=FALSE;

ELSE // Interrupted by error.

DoSendAndRcv:=FALSE;

Trigger

:=FALSE;

END_CASE;

END_IF;

2-1088

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

SktUDPRcv

2 Instruction Descriptions

SktUDPRcv

The SktUDPRcv instruction reads the data from the receive buffer for a UDP socket for the built-in EtherNet/IP.

Instruction SktUDPRcv

Name
UDP Socket Receive

FB/ FUN
FB

Graphic expression

SktUDPRcv_instance

SktUDPRcv

Execute Socket TimeOut Size RcvDat

Done Busy Error ErrorID

RcvSize SendNodeAdr

ST expression

SktUDPRcv_instance(Execute,

Socket, TimeOut, Size, RcvDat,

Done, Busy, Error, ErrorID, RcvSize, SendNodeAdr);

2

Variables

Name Socket TimeOut
Size

Meaning Socket Timeout time
Stored size

I/O Input

RcvDat[] (array) RcvSize
SendNodeA dr

Receive data
Receive data size Source node address

In-out Output

Description Socket 0: No timeouts 1 to 65535: 0.1 to 6553.5s The number of bytes to read from the receive buffer Receive data
The number of bytes actually stored in RcvDat[] Source node address

Valid range
---
Depends on data type.
0 to 2000

Unit
---
0.1 s
Bytes

Depends on data type.
0 to 2000

---
Bytes

---

---

Default
---
0 1
---
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

Socket

Refer to Function for details on the structure _sSOCKET.

TimeOut

OK

Size

OK

RcvDat[]

OK

(array)

RcvSize

OK

SendNodeAdr

Refer to Function for details on the structure _sSOCKET_ADDRESS.

NJ/NX-series Instructions Reference Manual (W502)

2-1089

2 Instruction Descriptions

Function

The SktUDPRcv instruction stores the data in the receive buffer for the socket that is specified with Socket in receive data RcvDat[]. The number of bytes to store is specified with Size. The number of bytes that is actually stored is assigned to RcvSize. The node address of the node that sent the data is stored in SendNodeAdr.
If there is no data in the receive buffer, the instruction waits for data for the time that is set with timeout time TimeOut. Storage of the data to RcvDat[] is completed when the instruction is completed normally (i.e., when the value of Done changes to TRUE).

The data type of Socket is structure _sSOCKET. The specifications are as follows:

Name Socket
Handle SrcAdr*
PortNo* IpAdr*
DstAdr* PortNo* IpAdr*

Meaning Socket Handle
Local address
Port number IP address
Destination address Port number IP address

Description
Socket
Handle for data communications
Local IP address and port number
Port number
IP address or host name. A DNS or Hosts setting is required to use a host name.
Destination IP address and port number
Port number
IP address or host name. A DNS or Hosts setting is required to use a host name.

* These members are not used for this instruction.

Data type _sSOCKET UDINT
_sSOCKET_ ADDRESS UINT STRING
_sSOCKET_ ADDRESS UINT STRING

Valid range
---
Depends on data type.
---
1 to 65535 Depends on data type.
---
1 to 65535 Depends on data type.

Unit
-----

Default
---
0

--- ---

0

---

`'

--- ---

0

---

`'

The data type of SendNodeAdr is structure _sSOCKET_ADDRESS. The specifications are as follows:

Name SendNodeAdr
PortNo
IpAdr

Meaning Source node address Port number
IP address

Description Source node address
UPD port number of the source node IP address of the source node

Data type _sSOCKET_ ADDRESS UINT
STRING

Valid range
---
1 to 65535
Depends on data type.

Unit Default
--- ---
--- ---

Related System-defined Variables

Name
_EIP_EtnOnlineSta*1 _EIP1_EtnOnlineSta*2 _EIP2_EtnOnlineSta*3 _EIPIn1_EtnOnlineSta*4

Meaning Online

Data type
BOOL

Description
This variable indicates when built-in EtherNet/IP port communications can be used. TRUE: Communications are possible. FALSE: Communications are not possible.

*1 Use this variable name for an NJ-series CPU Unit.

*2 Use this variable name for port 1 on an NX-series CPU Unit, or for an NY-series Controller.

*3 Use this variable name for port 2 on an NX-series CPU Unit.

*4 Use this variable name for the internal port on an NY-series Controller.

2-1090

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

SktUDPRcv

2 Instruction Descriptions

Additional Information
Refer to the NJ/NX-series CPU Unit Built-in EtherNet/IP Port User's Manual (Cat. No. W506) or NYseries Industrial Panel PC / Industrial Box PC Built-in EtherNet/IP Port User's Manual (Cat. No. W563) for details on socket services.

Precautions for Correct Use

· Execution of this instruction is continued until processing is completed even if the value of Execute

changes to FALSE or the execution time exceeds the task period. The value of Done changes to

TRUE when processing is completed. Use this to confirm normal completion of processing.

2

· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error.

· This instruction can be used only for the built-in EtherNet/IP on NJ/NX-series CPU Units and NYseries Controllers.

· Up to 2,000 bytes of data can be read from the receive buffer with one instruction.

· If the size of data that was received by the specified socket is smaller than the value of Size, then all of the received data is stored in RecDat[]. Then size of data that was stored is stored in RcvSize.

· If the size of data that was received by the specified socket is larger than the value of Size, then the size of received data specified by Size is stored in RecDat[].

· The receive data is not read if the value of Size is 0.

· If the SktClose instruction closes the connection when there is no data in the receive buffer, a normal end occurs without waiting to receive data even if a timeout has not occurred. The value of RcvSize is 0 in that case.

· Except for NX102 CPU Units, you can execute a maximum of 32 of the following instructions at the same time: SktUDPCreate, SktUDPRcv, SktUDPSend, SktTCPAccept, SktTCPConnect, SktTCPRcv, SktTCPSend, SktGetTCPStatus, SktClose, SktClearBuf, SktSetOption, ModbusTCPCmd, ModbusTCPRead, and ModbusTCPWrite. For NX102 CPU Units, a maximum of 64 instructions can be executed.

· An error occurs in the following cases. Error will change to TRUE.

· There is a setting error for the local IP address.

· Data reception is in progress for the socket specified with Socket.

· The socket specified with Socket is not open.

· The handle specified by Socket.Handle does not exist.

Sample Programming
Refer to the sample programming that is provided for the SktUDPCreate instruction (page 2-1081).

NJ/NX-series Instructions Reference Manual (W502)

2-1091

2 Instruction Descriptions

SktUDPSend

The SktUDPSend instruction sends data from a UDP port for the built-in EtherNet/IP.

Instruction SktUDPSend

Name
UDP Socket Send

FB/ FUN
FB

Graphic expression

SktUDPSend_instance

SktUDPSend

Execute Socket SendDat Size

Done Busy Error ErrorID

ST expression
SktUDPSend_instance(Execute, Socket, SendDat, Size, Done, Busy, Error, ErrorID);

Variables

Name Socket SendDat[] (array) Size

Meaning Socket Send data
Send data size

I/O Input

Description Socket Send data
Send data size

Bit strings

Integers

Valid range
---
Depends on data type. 0 to 2000

Unit
---
Bytes

Default
---
1

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

Socket

SendDat[]

OK

(array)

Size

Refer to Function for details on the structure _sSOCKET. OK

Function
The SktUDPSend instruction sends send data SendDat[] from the socket that is specified with Socket. The number of bytes to send is specified with Size. The remote node is specified with Socket.DstAdr. Transmission of SendDat[] to the send buffer is completed when the instruction is completed normally (i.e., when the value of Done changes to TRUE).

2-1092

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

EtherNet/IP Communications Instructions

SktUDPSend

The data type of Socket is structure _sSOCKET. The specifications are as follows:

Name Socket
Handle SrcAdr*
PortNo* IpAdr*
DstAdr PortNo IpAdr

Meaning

Description

Data type

Valid range Unit Default

Socket

Socket

_sSOCKET ---

--- ---

Handle

Handle for data commu- UDINT nications

Depends on data type.

--- 0

Local address Local IP address and port number

_sSOCKET_ --ADDRESS

--- ---

Port number Port number

UINT

1 to 65535

0

IP address

IP address or host

STRING

name. A DNS or Hosts

setting is required to use

Depends on data type.

---

`'

Destination address

a host name.

Destination IP address _sSOCKET_ ---

and port number

ADDRESS

--- ---

2

Port number Port number

UINT

1 to 65535

0

IP address

IP address or host

STRING

name. A DNS or Hosts

setting is required to use

Depends on data type.

---

`'

a host name.

* These members are not used for this instruction.

Related System-defined Variables

Name

Meaning

Data type

Description

_EIP_EtnOnlineSta*1 _EIP1_EtnOnlineSta*2 _EIP2_EtnOnlineSta*3 _EIPIn1_EtnOnlineSta*4

Online

BOOL

This variable indicates when built-in EtherNet/IP port communications can be used.
TRUE: Communications are possible.
FALSE: Communications are not possible.

*1 Use this variable name for an NJ-series CPU Unit.

*2 Use this variable name for port 1 on an NX-series CPU Unit, or for an NY-series Controller.

*3 Use this variable name for port 2 on an NX-series CPU Unit.

*4 Use this variable name for the internal port on an NY-series Controller.

Additional Information
Refer to the NJ/NX-series CPU Unit Built-in EtherNet/IP Port User's Manual (Cat. No. W506) or NYseries Industrial Panel PC / Industrial Box PC Built-in EtherNet/IP Port User's Manual (Cat. No. W563) for details on socket services.

Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error. · This instruction can be used only for the built-in EtherNet/IP on NJ/NX-series CPU Units and NY-
series Controllers. · Up to 2,000 bytes of data can be sent with one instruction. A maximum of 2,000 bytes is sent even if
the SendDat[] array is larger than 2,000 bytes. Only 1,472 bytes can be sent if the broadcast address is specified. · If the value of Size is 0, then 0 bytes of send data is transmitted on the line.

NJ/NX-series Instructions Reference Manual (W502)

2-1093

2 Instruction Descriptions
· Except for NX102 CPU Units, you can execute a maximum of 32 of the following instructions at the same time: SktUDPCreate, SktUDPRcv, SktUDPSend, SktTCPAccept, SktTCPConnect, SktTCPRcv, SktTCPSend, SktGetTCPStatus, SktClose, SktClearBuf, SktSetOption, ModbusTCPCmd, ModbusTCPRead, and ModbusTCPWrite. For NX102 CPU Units, a maximum of 64 instructions can be executed.
· An error occurs in the following cases. Error will change to TRUE. · There is a setting error for the local IP address. · The value of a member of Socket is outside of the valid range. · Data transmission is in progress for the socket specified with Socket. · The socket specified with Socket is not open. · The remote node for Socket was specified with a domain name and address resolution failed. · The handle specified by Socket.Handle does not exist. · The value of Size exceeds the number of elements in SendDat[].
Sample Programming
Refer to the sample programming that is provided for the SktUDPCreate instruction (page 2-1081).

2-1094

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

SktTCPAccept

2 Instruction Descriptions

SktTCPAccept

The SktTCPAccept instruction requests accepting a TCP socket for the built-in EtherNet/IP.

Instruction SktTCPAccept

Name
Accept TCP Socket

FB/ FUN
FB

Graphic expression

SktTCPAccept_instance

SktTCPAccept

Execute SrcTcpPort TimeOut

Done Busy Error ErrorID Socket

ST expression
SktTCPAccept_instance(Execute, SrcTcpPort, TimeOut, Done, Busy, Error, ErrorID, Socket);
2

Variables

Name SrcTcpPort
TimeOut

Meaning
Local TCP port number
Timeout time

I/O Input

Socket

Socket

Output

Description Local TCP port number
0: No timeouts 1 to 65535: 0.1 to 6553.5s Socket

Bit strings

Integers

Valid range 1 to 65535

Unit
---

Depends on data type.
---

0.1 s
---

Default 1 0
---

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

SrcTcpPort TimeOut Socket

OK OK Refer to Function for details on the structure _sSOCKET.

Function
The SktTCPAccept instruction requests accepting the port specified with the local TCP port number ScrTcpPort. To do this, it executes the Socket(), Bind(), Listen(), and Accept() socket functions. The instruction waits for the time set with timeout time TimeOut for a connection to be established with the remote node. The connection is established when the instruction is completed normally (i.e., when the value of Done changes to TRUE).

NJ/NX-series Instructions Reference Manual (W502)

2-1095

2 Instruction Descriptions

The data type of Socket is structure _sSOCKET. The specifications are as follows:

Name Socket
Handle
SrcAdr
PortNo IpAdr*1
DstAdr
PortNo IpAdr

Meaning Socket Handle
Local address
Port number IP address
Destination address Port number IP address

Description
Socket
Handle for data communications
Local IP address and port number
Port number
IP address or host name. A DNS or Hosts setting is required to use a host name.
Destination IP address and port number
Port number
IP address or host name. A DNS or Hosts setting is required to use a host name.

Data type _sSOCKET UDINT
_sSOCKET_ ADDRESS UINT STRING
_sSOCKET_ ADDRESS UINT STRING

Valid range
---
Depends on data type.
---
1 to 65535 Depends on data type.
---
1 to 65535 Depends on data type.

*1 NULL is output for this member.

Unit
-----

Default
---
0

--- ---

0

---

`'

--- ---

0

---

`'

Related System-defined Variables

Name
_EIP_EtnOnlineSta*1 _EIP1_EtnOnlineSta*2 _EIP2_EtnOnlineSta*3 _EIPIn1_EtnOnlineSta*4

Meaning Online

Data type
BOOL

Description
This variable indicates when built-in EtherNet/IP port communications can be used. TRUE: Communications are possible. FALSE: Communications are not possible.

*1 Use this variable name for an NJ-series CPU Unit.

*2 Use this variable name for port 1 on an NX-series CPU Unit, or for an NY-series Controller.

*3 Use this variable name for port 2 on an NX-series CPU Unit.

*4 Use this variable name for the internal port on an NY-series Controller.

Additional Information
· Refer to the NJ/NX-series CPU Unit Built-in EtherNet/IP Port User's Manual (Cat. No. W506) or NYseries Industrial Panel PC / Industrial Box PC Built-in EtherNet/IP Port User's Manual (Cat. No. W563) for details on socket services.
· You can execute this instruction more than once to open connections to more than one client with one local port number. A different socket is returned for each connection.

2-1096

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

SktTCPAccept

2 Instruction Descriptions

Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error. · This instruction can be used only for the built-in EtherNet/IP on NJ/NX-series CPU Units and NY-
series Controllers. · Use the SktClose instruction to close handles that are created with this instruction. · Handles that are created with this instruction are disabled when you change to PROGRAM mode.
· Except for NX102 CPU Units, you can execute a maximum of 32 of the following instructions at the 2
same time: SktUDPCreate, SktUDPRcv, SktUDPSend, SktTCPAccept, SktTCPConnect, SktTCPRcv, SktTCPSend, SktGetTCPStatus, SktClose, SktClearBuf, SktSetOption, ModbusTCPCmd, ModbusTCPRead, and ModbusTCPWrite. For NX102 CPU Units, a maximum of 64 instructions can be executed. · An error occurs in the following cases. Error will change to TRUE. · There is a setting error for the local IP address. · The value of SrcTcpPort is outside of the valid range. · Open processing is in progress for the socket specified with SrcTcpPort. · Close processing is in progress for the socket specified with SrcTcpPort. · A connection is not opened within the time that is specified with TimeOut.

Version Information

· The number of sockets that you can open at the same time depends on the unit version of the CPU Unit as shown in the following table. These limits are the totals for both UDP and TCP sockets.

Unit version of CPU Unit

Number of sockets

1.03 or higher

30 max.*1

1.02 or lower

16 max.

*1 For NX102 CPU Units, a maximum of 60 instructions can be opened.

· For CPU Unit version 1.10 or later, the value of Socket does not change even if Error changes to TRUE. For version 1.09 or earlier, the value of Socket changes to 0.

Sample Programming
Refer to the sample programming that is provided for the SktTCPConnect instruction (page 2-1098).

NJ/NX-series Instructions Reference Manual (W502)

2-1097

2 Instruction Descriptions

SktTCPConnect

The SktTCPConnect instruction connects to a remote TCP port from the built-in EtherNet/IP.

Instruction
SktTCP Connect

Name
Connect TCP Socket

FB/ FUN
FB

Graphic expression

SktTCPConnect_instance

SktTCPConnect

Execute SrcTcpPort DstAdr DstTcpPort

Done Busy Error ErrorID Socket

ST expression
SktTCPConnect_instance(Execute, SrcTcpPort, DstAdr, DstTcpPort, Done, Busy, Error, ErrorID, Socket);

Variables

Name

Meaning

I/O

Description

Valid range

Unit

SrcTcpPort Local TCP port number

Local TCP port number. If 0 is specified, an available TCP port that is 1024 or higher is automatically assigned. Well-

Depends on data type.

DstAdr

Destination address

Input

known port numbers are not

assigned.

---

Destination IP address or host 200 bytes max.

name

DstTcpPort

Destination TCP port number

Destination TCP port number 1 to 65,535

Socket

Socket

Output Socket

---

---

Default 0
---
1
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

SrcTcpPort DstAdr DstTcpPort Socket

OK OK
OK Refer to Function for details on the structure _sSOCKET.

2-1098

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

SktTCPConnect

2 Instruction Descriptions

Function

The SktTCPConnect instruction requests a connection between local TCP port number SrcTcpPort and destination TCP port number DstTcpPort at destination address DstAdr. To do this, it executes the Connect() socket function. The connection is established when the instruction is completed normally (i.e., when the value of Done changes to TRUE).

The data type of Socket is structure _sSOCKET. The specifications are as follows:

Name Socket
Handle
SrcAdr
PortNo IpAdr*1
DstAdr
PortNo IpAdr

Meaning

Description

Data type Valid range Unit Default

Socket

Socket

_sSOCKET ---

--- ---

Handle

Handle for data communica- UDINT

Depends on --- 0

tions Local address Local IP address and port

data type. _sSOCKET_ ---

--- ---

2

number

ADDRESS

Port number Port number

UINT

1 to 65535

0

IP address

IP address or host name. A STRING DNS or Hosts setting is required to use a host name.

Depends on data type.

---

`'

Destination address

Destination IP address and _sSOCKET_ ---

port number

ADDRESS

--- ---

Port number Port number

UINT

1 to 65535

0

IP address

IP address or host name. A STRING DNS or Hosts setting is required to use a host name.

Depends on data type.

---

`'

*1 NULL is output for this member.

Related System-defined Variables

Name
_EIP_EtnOnlineSta*1 _EIP1_EtnOnlineSta*2 _EIP2_EtnOnlineSta*3 _EIPIn1_EtnOnlineSta*4

Meaning Online

Data type
BOOL

Description
This variable indicates when built-in EtherNet/IP port communications can be used. TRUE: Communications are possible. FALSE: Communications are not possible.

*1 Use this variable name for an NJ-series CPU Unit. *2 Use this variable name for port 1 on an NX-series CPU Unit, or for an NY-series Controller. *3 Use this variable name for port 2 on an NX-series CPU Unit. *4 Use this variable name for the internal port on an NY-series Controller.

Additional Information
Refer to the NJ/NX-series CPU Unit Built-in EtherNet/IP Port User's Manual (Cat. No. W506) or NYseries Industrial Panel PC / Industrial Box PC Built-in EtherNet/IP Port User's Manual (Cat. No. W563) for details on socket services.

NJ/NX-series Instructions Reference Manual (W502)

2-1099

2 Instruction Descriptions

Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error. · This instruction can be used only for the built-in EtherNet/IP on NJ/NX-series CPU Units and NY-
series Controllers. · Use the SktClose instruction to close handles that are created with this instruction. · Handles that are created with this instruction are disabled when you change to PROGRAM mode. · Except for NX102 CPU Units, you can execute a maximum of 32 of the following instructions at the
same time: SktUDPCreate, SktUDPRcv, SktUDPSend, SktTCPAccept, SktTCPConnect, SktTCPRcv, SktTCPSend, SktGetTCPStatus, SktClose, SktClearBuf, SktSetOption, ModbusTCPCmd, ModbusTCPRead, and ModbusTCPWrite. For NX102 CPU Units, a maximum of 64 instructions can be executed. · An error occurs in the following cases. Error will change to TRUE. · There is a setting error for the local IP address. · The value of DstAdr is outside of the valid range. · The value of DstTcpPort is outside of the valid range. · The TCP port that is specified with SrcTcpPort is already open. · The remote node that is specified with DstAdr does not exist. · The remote node that is specified with DstAdr and DstTcpPort is not waiting for a connection. · Address resolution failed for the host name that is specified with DstAdr. · A connection is already open for the same client (IP address and TCP port).

Version Information

· The number of sockets that you can open at the same time depends on the unit version of the CPU Unit as shown in the following table. These limits are the totals for both UDP and TCP sockets.

Unit version of CPU Unit

Number of sockets

1.03 or higher

30 max.*1

1.02 or lower

16 max.

*1 For NX102 CPU Units, a maximum of 60 instructions can be opened.

· For CPU Unit version 1.10 or later, the value of Socket does not change even if Error changes to TRUE. For version 1.09 or earlier, the value of Socket changes to 0.

2-1100

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

2 Instruction Descriptions

Sample Programming

In this sample, the TCP socket service is used for data communications between the NJ/NX-series Controller and a remote node.

IP address: 192.168.250.1 TCP port number: Automatically assigned.

IP address: 192.168.250.2 TCP port number: 6000

Data sent.

Data received.

Remote node

2
Built-in EtherNet/IP port

Ethernet line
The processing procedure is as follows:
1 The SktTCPConnect instruction is used to request connecting to the TCP port on the remote node.
2 The SktClearBuf instruction is used to clear the receive buffer for a TCP socket. 3 The SktGetTCPStatus instruction is used to read the status of a TCP socket. 4 The SktTCPSend instruction is used to request sending data. The data in SendSocketDat[] is
sent.
5 The SktTCPRcv instruction is used to request receiving data. The received data is stored in RcvSocketDat[].
6 The SktClose instruction is used to close the socket.

SktTCPConnect

NJ/NX-series Instructions Reference Manual (W502)

2-1101

2 Instruction Descriptions

ST
Internal Variables

Variable
Trigger DoTCP Stage

RcvSocketDat

WkSocket

SendSocketDat
SktTCPConnect_instance SktClearBuf_instance SktGetTCPStatus_instance SktTCPSend_instance SktTCPRcv_instance SktClose_instance

Data type
BOOL BOOL INT ARRAY[0..1999] OF BYTE
_sSOCKET
ARRAY[0..1999] OF BYTE
SktTCPConnect
SktClearBuf
SktGetTCPStatus
SktTCPSend SktTCPRcv SktClose

Initial value
FALSE FALSE 0
[2000(16#0)]
(Handle:=0, SrcAdr:=(PortNo:=0, IpAdr:=''), DstAdr:=(PortNo:=0, IpAdr:=''))
[2000(16#0)]

Comment Execution condition Processing Stage change Receive data
Socket
Send data

External Variables

Variable _EIP_EtnOnlineSta

Data type BOOL

Constant Online

Comment

// Start sequence when Trigger changes to TRUE.

IF ( (Trigger=TRUE) AND (DoTCP=FALSE) AND (_Eip_EtnOnlineSta=TRUE) ) THEN

DoTCP :=TRUE;

Stage :=INT#1;

SktTCPConnect_instance(Execute:=FALSE); // Initialize instance.

SktClearBuf_instance(Execute:=FALSE); // Initialize instance.

SktGetTCPStatus_instance(Execute:=FALSE); // Initialize instance.

SktTCPSend_instance(

// Initialize instance.

Execute:=FALSE,

SendDat:=SendSocketDat[0]);

// Dummy

SktTCPRcv_instance(

// Initialize instance.

Execute:=FALSE,

RcvDat :=RcvSocketDat[0]);

// Dummy

SktClose_instance(Execute:=FALSE);

// Initialize instance.

END_IF;

IF (DoTCP=TRUE) THEN

CASE Stage OF

1 : // Request a connection.

SktTCPConnect_instance(

Execute :=TRUE,

SrcTcpPort:=UINT#0,

// Local TCP port number: Automatically assigned.

DstAdr :='192.168.250.2', // Remote IP address

DstTcpPort:=UINT#6000,

// Destination TCP port number

Socket =>WkSocket);

// Socket

IF (SktTCPConnect_instance.Done=TRUE) THEN Stage:=INT#2; // Normal end
ELSIF (SktTCPConnect_instance.Error=TRUE) THEN Stage:=INT#10; // Error end
END_IF;

2-1102

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

EtherNet/IP Communications Instructions

SktTCPConnect

2 : // Clear receive buffer. SktClearBuf_instance( Execute:=TRUE, Socket :=WkSocket); // Socket

IF (SktClearBuf_instance.Done=TRUE) THEN

Stage:=INT#3;

// Normal end

ELSIF (SktClearBuf_instance.Error=TRUE) THEN

Stage:=INT#20;

// Error end

END_IF;

3 : // Request reading status. SktGetTCPStatus_instance( Execute:=TRUE, Socket :=WkSocket); // Socket

IF (SktGetTCPStatus_instance.Done=TRUE) THEN

Stage:=INT#4;

// Normal end

ELSIF (SktGetTCPStatus_instance.Error=TRUE) THEN

Stage:=INT#30;

// Error end

END_IF;

4 : // Request sending data

SktTCPSend_instance(

Execute:=TRUE,

Socket :=WkSocket,

// Socket

SendDat:=SendSocketDat[0], // Send data

Size :=UINT#2000);

// Send data size

IF (SktTCPSend_instance.Done=TRUE) THEN

Stage:=INT#5;

// Normal end

ELSIF (SktTCPSend_instance.Error=TRUE) THEN

Stage:=INT#40;

// Error end

END_IF;

5 : // Request receiving data

SktTCPRcv_instance(

Execute:=TRUE,

Socket :=WkSocket,

// Socket

TimeOut:=UINT#0,

// Timeout time

Size :=UINT#2000,

// Receive data size

RcvDat :=RcvSocketDat[0]); // Receive data

IF (SktTCPRcv_instance.Done=TRUE) THEN

Stage:=INT#6;

// Normal end

ELSIF (SktTCPRcv_instance.Error=TRUE) THEN

Stage:=INT#50;

// Error end

END_IF;

6 : // Request closing. SktClose_instance( Execute:=TRUE, Socket :=WkSocket);

// Socket

IF (SktClose_instance.Done=TRUE) THEN

Stage:=INT#0;

// Normal end

ELSIF (SktClose_instance.Error=TRUE) THEN

Stage:=INT#40;

// Error end

END_IF;

0 : // Normal end DoTCP :=FALSE; Trigger :=FALSE;

NJ/NX-series Instructions Reference Manual (W502)

2
2-1103

2 Instruction Descriptions
ELSE // Interrupted by error. DoTCP :=FALSE; Trigger :=FALSE;
END_CASE;
END_IF;
 Programming in the Remote Node
In this example, programming is also required in the remote node. The order of sending and receiving is reversed in comparison with the above procedure.
1 The SktTCPAccept instruction is used to request accepting a TCP socket. 2 The SktTCPRcv instruction is used to request receiving data. The received data is stored in
RcvSocketDat[].
3 The SktTCPSend instruction is used to request sending data. The data in SendSocketDat[] is sent.
4 The SktClose instruction is used to close the socket.

2-1104

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

EtherNet/IP Communications Instructions

SktTCPConnect

ST

Internal Variables

Variable

Data type

Initial value

Comment

Trigger

BOOL

FALSE

Execution condition

DoTCP

BOOL

FALSE

Processing

Stage

INT

0

Stage change

RcvSocketDat

ARRAY[0..1999] OF BYTE

[2000(16#0)]

Receive data

(Handle:=0, SrcAdr:=(PortNo:=0,

WkSocket

_sSOCKET

IpAdr:=''), DstAdr:=(PortNo:=0,

Socket

SendSocketDat

ARRAY[0..1999] OF BYTE

IpAdr:='')) [2000(16#0)]

2
Send data

SktTCPAccept_instance SktTCPAccept

SktTCPSend_instance SktTCPSend

SktTCPRcv_instance

SktTCPRcv

SktClose_instance

SktClose

External Variables

Variable _EIP_EtnOnlineSta

Data type BOOL

Constant Online

Comment

// Start sequence when Trigger changes to TRUE.

IF ( (Trigger=TRUE) AND (DoTCP=FALSE) AND (_Eip_EtnOnlineSta=TRUE) ) THEN

DoTCP:=TRUE;

Stage:=INT#1;

SktTCPAccept_instance(Execute:=FALSE); // Initialize instance.

SktTCPSend_instance(

// Initialize instance.

Execute :=FALSE,

SendDat :=SendSocketDat[0]);

// Dummy

SktTCPRcv_instance(

// Initialize instance.

Execute :=FALSE,

RcvDat :=RcvSocketDat[0]);

// Dummy

SktClose_instance(Execute:=FALSE);

// Initialize instance.

END_IF;

IF (DoTCP=TRUE) THEN

CASE Stage OF

1 :

// Request accepting a socket connection.

SktTCPAccept_instance(

Execute :=TRUE,

SrcTcpPort:=UINT#6000, // Local TCP port number

TimeOut :=UINT#0,

// Timeout time

Socket

=>WkSocket); // Socket

IF (SktTCPAccept_instance.Done=TRUE) THEN

Stage:=INT#2;

// Normal end

ELSIF (SktTCPAccept_instance.Error=TRUE) THEN

Stage:=INT#10;

// Error end

END_IF;

2 :

// Request receiving data

SktTCPRcv_instance(

Execute:=TRUE,

Socket :=WkSocket,

TimeOut:=UINT#0,

Size :=UINT#2000,

RcvDat :=RcvSocketDat[0]);

// Socket // Timeout time // Receive data size // Receive data

NJ/NX-series Instructions Reference Manual (W502)

2-1105

2 Instruction Descriptions

IF (SktTCPRcv_instance.Done=TRUE) THEN

Stage:=INT#3;

// Normal end

ELSIF (SktTCPRcv_instance.Error=TRUE) THEN

Stage:=INT#20; // Error end

END_IF;

3 :

// Request sending data.

SendSocketDat:=RcvSocketDat;

SktTCPSend_instance(

Execute:=TRUE,

Socket :=WkSocket,

// Socket

SendDat:=SendSocketDat[0], // Send data

Size :=UINT#2000);

// Send data size

IF (SktTCPSend_instance.Done=TRUE) THEN Stage:=INT#4; // Normal end
ELSIF (SktTCPSend_instance.Error=TRUE) THEN Stage:=INT#30; // Error end
END_IF;

4 :

// Request closing.

SktClose_instance(

Execute:=TRUE,

Socket :=WkSocket);

// Socket

IF (SktClose_instance.Done=TRUE) THEN

Stage:=INT#0;

// Normal end

ELSIF (SktClose_instance.Error=TRUE) THEN

Stage:=INT#40;

// Error end

END_IF;

0 :

// Normal end

DoTCP :=FALSE;

Trigger:=FALSE;

ELSE // Interrupted by error. DoTCP :=FALSE; Trigger:=FALSE;
END_CASE;

END_IF;

2-1106

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

SktTCPRcv

2 Instruction Descriptions

SktTCPRcv

The SktTCPRcv instruction reads the data from the receive buffer for a TCP socket for the built-in EtherNet/IP.

Instruction SktTCPRcv

Name
TCP Socket Receive

FB/ FUN
FB

Graphic expression

SktTCPRcv_instance

SktTCPRcv

Execute Socket TimeOut Size RcvDat

Done Busy Error ErrorID

RcvSize

ST expression

SktTCPRcv_instance(Execute,

Socket, TimeOut, Size, RcvDat,

Done, Busy, Error, ErrorID, RcvSize);

2

Variables

Name Socket TimeOut
Size
RcvDat[] (array) RcvSize

Meaning Socket Timeout time
Stored size

I/O Input

Receive data In-out

Receive data Output size

Description Socket 0: No timeouts 1 to 65535: 0.1 to 6553.5s The number of bytes to read from the receive buffer Receive data
The number of bytes actually stored in RcvDat[]

Valid range
---
Depends on data type.
0 to 2000

Unit
---
0.1 s
Bytes

Depends on data type.
1 to 2000

---
Bytes

Default
---
0
1
---
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

Socket

TimeOut

Size

RcvDat[]

OK

(array)

RcvSize

Refer to Function for details on the structure _sSOCKET. OK OK
OK

NJ/NX-series Instructions Reference Manual (W502)

2-1107

2 Instruction Descriptions

Function

The SktTCPRcv instruction stores the data in the receive buffer for the socket that is specified with Socket in receive data RcvDat[]. The number of bytes to store is specified with Size. The number of bytes that is actually stored is assigned to RcvSize. If there is no data in the receive buffer, the instruction waits for data for the time that is set with timeout time TimeOut. Storage of the data to RcvDat[] is completed when the instruction is completed normally (i.e., when the value of Done changes to TRUE).

The data type of Socket is structure _sSOCKET. The specifications are as follows:

Name Socket
Handle SrcAdr*
PortNo* IpAdr*
DstAdr* PortNo* IpAdr*

Meaning Socket Handle
Local address
Port number IP address
Destination address Port number IP address

Description
Socket
Handle for data communications
Local IP address and port number
Port number
IP address or host name. A DNS or Hosts setting is required to use a host name.
Destination IP address and port number
Port number
IP address or host name. A DNS or Hosts setting is required to use a host name.

Data type _sSOCKET UDINT
_sSOCKET_ ADDRESS UINT STRING
_sSOCKET_ ADDRESS UINT STRING

Valid range
---
Depends on data type.
---
1 to 65535 Depends on data type.
---
1 to 65535 Depends on data type.

Unit
-----

Default
---
0

--- ---

0

---

`'

--- ---

0

---

`'

* These members are not used for this instruction.

Related System-defined Variables

Name
_EIP_EtnOnlineSta*1 _EIP1_EtnOnlineSta*2 _EIP2_EtnOnlineSta*3 _EIPIn1_EtnOnlineSta*4

Meaning Online

Data type
BOOL

Description
This variable indicates when built-in EtherNet/IP port communications can be used. TRUE: Communications are possible. FALSE: Communications are not possible.

*1 Use this variable name for an NJ-series CPU Unit.

*2 Use this variable name for port 1 on an NX-series CPU Unit, or for an NY-series Controller.

*3 Use this variable name for port 2 on an NX-series CPU Unit.

*4 Use this variable name for the internal port on an NY-series Controller.

Additional Information
Refer to the NJ/NX-series CPU Unit Built-in EtherNet/IP Port User's Manual (Cat. No. W506) or NYseries Industrial Panel PC / Industrial Box PC Built-in EtherNet/IP Port User's Manual (Cat. No. W563) for details on socket services.

2-1108

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

SktTCPRcv

2 Instruction Descriptions

Precautions for Correct Use

· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.

· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error.

· This instruction can be used only for the built-in EtherNet/IP on NJ/NX-series CPU Units and NYseries Controllers.

· Up to 2,000 bytes of data can be read with one instruction. A maximum of 2,000 bytes is read even if the RcvDat[] array is larger than 2,000 bytes.

· If the size of data that was received by the specified socket is smaller than the value of Size, then all of the received data is stored in RecDat[]. Then size of data that was stored is stored in RcvSize.

2

· If the size of data that was received by the specified socket is larger than the value of Size, then the size of received data specified by Size is stored in RecDat[].

· The receive data is not read if the value of Size is 0.

· If the SktClose instruction closes the connection when there is no data in the receive buffer, an error end occurs even if a timeout has not occurred.

· Except for NX102 CPU Units, you can execute a maximum of 32 of the following instructions at the same time: SktUDPCreate, SktUDPRcv, SktUDPSend, SktTCPAccept, SktTCPConnect, SktTCPRcv, SktTCPSend, SktGetTCPStatus, SktClose, SktClearBuf, SktSetOption, ModbusTCPCmd, ModbusTCPRead, and ModbusTCPWrite. For NX102 CPU Units, a maximum of 64 instructions can be executed.

· An error occurs in the following cases. Error will change to TRUE.

· There is a setting error for the local IP address.

· The value of a member of Socket is outside of the valid range.

· Data reception is in progress for the socket specified with Socket.

· The socket specified with Socket is not connected.

· The handle specified by Socket.Handle does not exist.

· Data was not received before the time that is specified with TimeOut expired.

· The socket was closed with the SktClose instruction.

Sample Programming
Refer to the sample programming that is provided for the SktTCPConnect instruction (page 2-1098).

NJ/NX-series Instructions Reference Manual (W502)

2-1109

2 Instruction Descriptions

SktTCPSend

The SktTCPSend instruction sends data from a TCP port for the built-in EtherNet/IP.

Instruction SktTCPSend

Name
TCP Socket Send

FB/ FUN
FB

Graphic expression

SktTCPSend_instance

SktTCPSend

Execute Socket SendDat Size

Done Busy Error ErrorID

ST expression
SktTCPSend_instance(Execute, Socket, SendDat, Size, Done, Busy, Error, ErrorID);

Variables

Name Socket SendDat[] (array) Size

Meaning Socket Send data
Send data size

I/O Input

Description Socket Send data
Send data size

Bit strings

Integers

Valid range
---
Depends on data type. 0 to 2000

Unit
---
Bytes

Default
---
1

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

Socket

SendDat[]

OK

(array)

Size

Refer to Function for details on the structure _sSOCKET. OK

Function
The SktTCPSend instruction sends send data SendDat[] from the socket that is specified with Socket. The number of bytes to send is specified with Size.

2-1110

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

EtherNet/IP Communications Instructions

SktTCPSend

The data type of Socket is structure _sSOCKET. The specifications are as follows:

Name Socket
Handle SrcAdr*
PortNo* IpAdr*
DstAdr* PortNo* IpAdr*

Meaning

Description

Data type

Valid range Unit Default

Socket

Socket

_sSOCKET ---

--- ---

Handle

Handle for data commu- UDINT nications

Depends on data type.

--- 0

Local address Local IP address and port number

_sSOCKET_ --ADDRESS

--- ---

Port number Port number

UINT

1 to 65535

0

IP address

IP address or host

STRING

name. A DNS or Hosts

setting is required to use

Depends on data type.

---

`'

Destination address

a host name.

Destination IP address _sSOCKET_ ---

and port number

ADDRESS

--- ---

2

Port number Port number

UINT

1 to 65535

0

IP address

IP address or host

STRING

name. A DNS or Hosts

setting is required to use

Depends on data type.

---

`'

a host name.

* These members are not used for this instruction.

Related System-defined Variables

Name

Meaning

Data type

Description

_EIP_EtnOnlineSta*1 _EIP1_EtnOnlineSta*2 _EIP2_EtnOnlineSta*3 _EIPIn1_EtnOnlineSta*4

Online

BOOL

This variable indicates when built-in EtherNet/IP port communications can be used.
TRUE: Communications are possible.
FALSE: Communications are not possible.

*1 Use this variable name for an NJ-series CPU Unit.

*2 Use this variable name for port 1 on an NX-series CPU Unit, or for an NY-series Controller.

*3 Use this variable name for port 2 on an NX-series CPU Unit.

*4 Use this variable name for the internal port on an NY-series Controller.

Additional Information
Refer to the NJ/NX-series CPU Unit Built-in EtherNet/IP Port User's Manual (Cat. No. W506) or NYseries Industrial Panel PC / Industrial Box PC Built-in EtherNet/IP Port User's Manual (Cat. No. W563) for details on socket services.
Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error. · This instruction can be used only for the built-in EtherNet/IP on NJ/NX-series CPU Units and NY-
series Controllers. · Up to 2,000 bytes of data can be sent with one instruction. A maximum of 2,000 bytes is sent even if
the SendDat[] array is larger than 2,000 bytes. · Data is not sent if the value of Size is 0.

NJ/NX-series Instructions Reference Manual (W502)

2-1111

2 Instruction Descriptions
· Except for NX102 CPU Units, you can execute a maximum of 32 of the following instructions at the same time: SktUDPCreate, SktUDPRcv, SktUDPSend, SktTCPAccept, SktTCPConnect, SktTCPRcv, SktTCPSend, SktGetTCPStatus, SktClose, SktClearBuf, SktSetOption, ModbusTCPCmd, ModbusTCPRead, and ModbusTCPWrite. For NX102 CPU Units, a maximum of 64 instructions can be executed.
· An error occurs in the following cases. Error will change to TRUE. · There is a setting error for the local IP address. · The value of a member of Socket is outside of the valid range. · Data transmission is in progress for the socket specified with Socket. · The socket specified with Socket is not connected. · The handle specified by Socket.Handle does not exist.
Sample Programming
Refer to the sample programming that is provided for the SktTCPConnect instruction (page 2-1098).

2-1112

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

SktGetTCPStatus

2 Instruction Descriptions

SktGetTCPStatus

The SktGetTCPStatus instruction reads the status of a TCP socket.

Instruction
SktGetTCP Status

Name
Read TCP Socket Status

FB/ FUN
FB

Graphic expression

SktGetTCPStatus_instance

SktGetTCPStatus

Execute Socket

Done Busy Error ErrorID TcpStatus DatRcvFlag

ST expression
SktGetTCPStatus_instance(Execute, Socket, Done, Busy, Error, ErrorID, TcpStatus, DatRcvFlag);
2

Variables

Name Socket TcpStatus
DatRcvFlag

Meaning
Socket
TCP connection status
Data Received Flag

I/O Input
Output

Description Socket TCP connection status
TRUE: Data is received. FALSE: Data is not received.

Valid range
---
*
Depends on data type.

Unit
---
---

Default
---
---

* _CLOSED, _LISTEN, _SYN_SENT, _SYN_RECEIVED, _ESTABLISHED, _CLOSE_WAIT, _FIN_WAIT1, _CLOSING, _LAST_ACK, _FIN_WAIT2, or _TIME_WAIT

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

Socket TcpStatus DatRcvFlag OK

Refer to Function for details on the structure _sSOCKET. Refer to Function for the enumerators of the enumerated type _eCONNECTION_STATE.

NJ/NX-series Instructions Reference Manual (W502)

2-1113

2 Instruction Descriptions

Function

The SktGetTCPStatus instruction gets the TCP connection status TcpStatus of the socket that is specified with Socket. If there is receive data in the receive buffer, the value of data received flag DatRecvFlag changes to TRUE. Storage of the data to TcpStatus and DatRcvFlag is completed when the instruction is completed normally (i.e., when the value of Done changes to TRUE).

The data type of Socket is structure _sSOCKET. The specifications are as follows:

Name Socket
Handle SrcAdr*
PortNo* IpAdr*
DstAdr* PortNo* IpAdr*

Meaning Socket Handle
Local address
Port number IP address
Destination address Port number IP address

Description
Socket
Handle for data communications
Local IP address and port number
Port number
IP address or host name. A DNS or Hosts setting is required to use a host name.
Destination IP address and port number
Port number
IP address or host name. A DNS or Hosts setting is required to use a host name.

Data type _sSOCKET UDINT
_sSOCKET_ ADDRESS UINT STRING
_sSOCKET_ ADDRESS UINT STRING

Valid range
---
Depends on data type.
---
1 to 65535 Depends on data type.
---
1 to 65535 Depends on data type.

Unit
-----

Default
---
0

--- ---

0

---

`'

--- ---

0

---

`'

* These members are not used for this instruction.
The data type of TcpStatus is enumerated type _eCONNECTION_STATE. The meanings of the enumerators of enumerated type _eCONNECTION_STATE are as follows:

Enumerators _CLOSED _LISTEN _SYN_SENT _SYN_RECEIVED _ESTABLISHED _CLOSE_WAIT _FIN_WAIT1 _CLOSING _LAST_ACK _FIN_WAIT2 _TIME_WAIT

Meaning CLOSED status LISTEN status SYN SENT status SYN RECEIVED status ESTABLISHED status CLOSE WAIT status FIN WAIT1 status CLOSING status LAST ACK status FIN WAIT2 status TIME WAIT status

Related System-defined Variables

Name
_EIP_EtnOnlineSta*1 _EIP1_EtnOnlineSta*2 _EIP2_EtnOnlineSta*3 _EIPIn1_EtnOnlineSta*4

Meaning Online

Data type
BOOL

Description
This variable indicates when built-in EtherNet/IP port communications can be used. TRUE: Communications are possible. FALSE: Communications are not possible.

*1 Use this variable name for an NJ-series CPU Unit.

*2 Use this variable name for port 1 on an NX-series CPU Unit, or for an NY-series Controller.

*3 Use this variable name for port 2 on an NX-series CPU Unit.

2-1114

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

2 Instruction Descriptions
*4 Use this variable name for the internal port on an NY-series Controller.
Additional Information
Refer to the NJ/NX-series CPU Unit Built-in EtherNet/IP Port User's Manual (Cat. No. W506) or NYseries Industrial Panel PC / Industrial Box PC Built-in EtherNet/IP Port User's Manual (Cat. No. W563) for details on socket services.
Precautions for Correct Use · Execution of this instruction is continued until processing is completed even if the value of Execute 2
changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing. · Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error. · This instruction can be used only for the built-in EtherNet/IP on NJ/NX-series CPU Units and NYseries Controllers. · Except for NX102 CPU Units, you can execute a maximum of 32 of the following instructions at the same time: SktUDPCreate, SktUDPRcv, SktUDPSend, SktTCPAccept, SktTCPConnect, SktTCPRcv, SktTCPSend, SktGetTCPStatus, SktClose, SktClearBuf, SktSetOption, ModbusTCPCmd, ModbusTCPRead, and ModbusTCPWrite. For NX102 CPU Units, a maximum of 64 instructions can be executed. · An error occurs in the following cases. Error will change to TRUE. · The value of a member of Socket is outside of the valid range. · The handle specified by Socket.Handle does not exist.
Sample Programming
Refer to the sample programming that is provided for the SktTCPConnect instruction (page 2-1098).

SktGetTCPStatus

NJ/NX-series Instructions Reference Manual (W502)

2-1115

2 Instruction Descriptions

SktClose

The SktClose instruction closes the specified TCP or UDP socket for the built-in EtherNet/IP.

Instruction SktClose

Name
Close TCP/UDP Socket

FB/ FUN
FB

Graphic expression

SktClose_instance

SktClose

Execute Socket

Done Busy Error ErrorID

ST expression
SktClose_instance(Execute, Socket, Done, Busy, Error, ErrorID);

Variables

Name Socket

Meaning Socket

I/O Input

Description Socket

Bit strings

Integers

Valid range
---

Unit
---

Default
---

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

Socket

Refer to Function for details on the structure _sSOCKET.

Function
The SktClose instruction closes the socket that is specified with Socket. If a TCP socket is specified, the socket is disconnected before it is closed. If the socket handle Socket.Handle is 0, all TCP and UDP ports that currently use the socket service are closed. Close processing for the TCPUDP sockets is completed when the instruction is completed normally (i.e., when the value of Done changes to TRUE).

2-1116

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

EtherNet/IP Communications Instructions

SktClose

The data type of Socket is structure _sSOCKET. The specifications are as follows:

Name Socket
Handle
SrcAdr* PortNo* IpAdr*
DstAdr* PortNo* IpAdr*

Meaning

Description

Data type

Valid range Unit Default

Socket

Socket

_sSOCKET ---

--- ---

Handle

Handle of the connection to close.

UDINT

Depends on data type.

--- 0

0: Closes all TCP connections that currently use the socket service.

Local address Local IP address and port number

_sSOCKET_ --ADDRESS

--- ---

Port number Port number

UINT

1 to 65535

0

IP address

IP address or host

STRING

name. A DNS or Hosts

setting is required to use

Depends on data type.

---

`'

2

a host name.

Destination address

Destination IP address _sSOCKET_ ---

and port number

ADDRESS

--- ---

Port number Port number

UINT

1 to 65535

0

IP address

IP address or host name. A DNS or Hosts setting is required to use a host name.

STRING

Depends on data type.

---

`'

* These members are not used for this instruction.

Related System-defined Variables

Name
_EIP_EtnOnlineSta*1 _EIP1_EtnOnlineSta*2 _EIP2_EtnOnlineSta*3 _EIPIn1_EtnOnlineSta*4

Meaning Online

Data type
BOOL

Description
This variable indicates when built-in EtherNet/IP port communications can be used. TRUE: Communications are possible. FALSE: Communications are not possible.

*1 Use this variable name for an NJ-series CPU Unit.

*2 Use this variable name for port 1 on an NX-series CPU Unit, or for an NY-series Controller.

*3 Use this variable name for port 2 on an NX-series CPU Unit.

*4 Use this variable name for the internal port on an NY-series Controller.

Additional Information
Refer to the NJ/NX-series CPU Unit Built-in EtherNet/IP Port User's Manual (Cat. No. W506) or NYseries Industrial Panel PC / Industrial Box PC Built-in EtherNet/IP Port User's Manual (Cat. No. W563) for details on socket services.
Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error. · This instruction can be used only for the built-in EtherNet/IP on NJ/NX-series CPU Units and NY-
series Controllers.

NJ/NX-series Instructions Reference Manual (W502)

2-1117

2 Instruction Descriptions
· If the SktUDPRcv or SktTCPRcv instruction is executed and then the SktClose instruction is executed while the socket for the specified handle is on standby to received data, the standby status is canceled.
· If more than one connection is open for the same local port number, only the connection for the specified socket is closed.
· If the value of the socket handle Socket.Handle is 0, all connections that are on standby for the SktTCPAccept instruction are canceled.
· Except for NX102 CPU Units, you can execute a maximum of 32 of the following instructions at the same time: SktUDPCreate, SktUDPRcv, SktUDPSend, SktTCPAccept, SktTCPConnect, SktTCPRcv, SktTCPSend, SktGetTCPStatus, SktClose, SktClearBuf, SktSetOption, ModbusTCPCmd, ModbusTCPRead, and ModbusTCPWrite. For NX102 CPU Units, a maximum of 64 instructions can be executed.
· An error occurs in the following cases. Error will change to TRUE. · There is a setting error for the local IP address. · The value of a member of Socket is outside of the valid range. · The handle specified by Socket.Handle does not exist.
Sample Programming
Refer to the sample programming for the following instructions: SktUDPCreate (page 2-1081) and SktTCPConnect (page 2-1098).

2-1118

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

SktClearBuf

2 Instruction Descriptions

SktClearBuf

The SktClearBuf instruction clears the receive buffer for the specified TCP or UDP socket for the builtin EtherNet/IP.

Instruction SktClearBuf

Name
Clear TCP/UDP Socket Receive Buffer

FB/ FUN
FB

Graphic expression

SktClearBuf_instance

SktClearBuf

Execute Socket

Done Busy Error ErrorID

ST expression

SktClearBuf_instance(Execute,

Socket, Done, Busy, Error,

ErrorID);

2

Variables

Name Socket

Meaning Socket

I/O Input

Description Socket

Bit strings

Integers

Valid range
---

Unit
---

Default
---

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

Socket

Refer to Function for details on the structure _sSOCKET.

Function
The SktClearBuf instruction clears the receive buffer for the socket that is specified with Socket. Clear processing of the receive buffer is completed when the instruction is completed normally (i.e., when the value of Done changes to TRUE).

NJ/NX-series Instructions Reference Manual (W502)

2-1119

2 Instruction Descriptions

The data type of Socket is structure _sSOCKET. The specifications are as follows:

Name Socket
Handle
SrcAdr* PortNo* IpAdr*
DstAdr* PortNo* IpAdr*

Meaning Socket Handle
Local address
Port number IP address
Destination address Port number IP address

Description
Socket
The handle of the socket to clear the receive buffer
Local IP address and port number
Port number
IP address or host name. A DNS or Hosts setting is required to use a host name.
Destination IP address and port number
Port number
IP address or host name. A DNS or Hosts setting is required to use a host name.

Data type _sSOCKET UDINT
_sSOCKET_ ADDRESS UINT STRING
_sSOCKET_ ADDRESS UINT STRING

Valid range
---
Depends on data type.
---
1 to 65535 Depends on data type.
---
1 to 65535 Depends on data type.

* These members are not used for this instruction.

Unit
-----

Default
---
0

--- ---

0

---

`'

--- ---

0

---

`'

Related System-defined Variables

Name

Meaning

Data type

Description

_EIP_EtnOnlineSta*1 _EIP1_EtnOnlineSta*2 _EIP2_EtnOnlineSta*3 _EIPIn1_EtnOnlineSta*4

Online

BOOL

This variable indicates when built-in EtherNet/IP port communications can be used. TRUE: Communications are possible. FALSE: Communications are not possible.

*1 Use this variable name for an NJ-series CPU Unit.

*2 Use this variable name for port 1 on an NX-series CPU Unit, or for an NY-series Controller.

*3 Use this variable name for port 2 on an NX-series CPU Unit.

*4 Use this variable name for the internal port on an NY-series Controller.

Additional Information
Refer to the NJ/NX-series CPU Unit Built-in EtherNet/IP Port User's Manual (Cat. No. W506) or NYseries Industrial Panel PC / Industrial Box PC Built-in EtherNet/IP Port User's Manual (Cat. No. W563) for details on socket services.
Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error. · This instruction can be used only for the built-in EtherNet/IP on NJ/NX-series CPU Units and NY-
series Controllers. · Except for NX102 CPU Units, you can execute a maximum of 32 of the following instructions at the
same time: SktUDPCreate, SktUDPRcv, SktUDPSend, SktTCPAccept, SktTCPConnect, SktTCPRcv, SktTCPSend, SktGetTCPStatus, SktClose, SktClearBuf, SktSetOption, ModbusTCPCmd, ModbusTCPRead, and ModbusTCPWrite. For NX102 CPU Units, a maximum of 64 instructions can be executed. · An error occurs in the following cases. Error will change to TRUE.

2-1120

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

2 Instruction Descriptions
· The value of a member of Socket is outside of the valid range. · The socket that is specified by Socket does not exist. · The handle specified by Socket.Handle does not exist.
Sample Programming
Refer to the sample programming that is provided for the SktTCPConnect instruction (page 2-1098).
2

SktClearBuf

NJ/NX-series Instructions Reference Manual (W502)

2-1121

2 Instruction Descriptions

SktSetOption

The SktSetOption instruction sets the option for TCP socket specified for the built-in EtherNet/IP.

Instruction SktSetOption

Name
Set TCP Socket Option

FB/ FUN
FB

Graphic expression

SktSetOption_instance

SktSetOption

Execute Socket OptionType OptionParam

Done Busy Error ErrorID

ST expression
SktSetOption_instance( Execute, Socket, OptionType, OptionParam, Done, Busy, Error, ErrorID);

Version Information
A CPU Unit with unit version 1.12 or later and Sysmac Studio version 1.16 or higher are required to use this instruction.
For an NX1P2 CPU Unit, a CPU Unit with unit version 1.14 or later and Sysmac Studio 1.18 or higher are required to use this instruction.

Variables

Name Socket OptionType
OptionParam

Meaning Socket Option type Option parameter

I/O Input

Description Socket Type of socket option Setting parameters according to the specified socket option

Valid range -----
---

Unit -----
---

Default -----
---

Bit strings

Integers

Times, durations, dates, and text strings

Real numbers

Boolean BOOL

STRING DT TOD
DATE TIME

LREAL REAL

LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE

Socket

Refer to Function for details on the structure _sSOCKET.

OptionType OptionParam OK*1

Refer to Function for the enumerators of the enumerated type _eSKT_OPTION_TYPE.

*1 A constant (literal) cannot be input. Specify a variable.

Function
The SktSetOption instruction sets the socket option for the socket specified with Socket. Done changes to TRUE when processing of the instruction is completed normally. The socket option setting is completed when processing of the instruction is completed normally.

2-1122

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

SktSetOption

2 Instruction Descriptions

The data type of Socket is structure _sSOCKET. The specifications are as follows:

Name

Meaning

Description

Data type

Valid range Unit Default

Socket

Socket

Socket

_sSOCKET ---

--- ---

Handle

Handle

The handle of the socket to clear the receive buf- UDINT fer

Depends on data type.

--- 0

SrcAdr(*)

Local address

Local IP address and port number

_sSOCKET_ADDRESS

---

--- ---

PortNo(*)

Port number Port number

UINT

1 to 65,535

0

IpAdr(*)

IP address

IP address or host name.
A DNS or Hosts setting is required to use a host

STRING

Depends on data type.

--`'

2

name.

DstAdr(*)

Destination address

Destination IP address and port number

_sSOCKET_ADDRESS

---

--- ---

PortNo(*)

Port number Port number

UINT

1 to 65,535

0

IpAdr(*)

IP address

IP address or host name.
A DNS or Hosts setting is required to use a host name.

STRING

Depends on data type.

--`'

* These members are not used for this instruction.

The following table shows the value of OptionType that you can specify and the data type of OptionParam that you can select for the specified OptionType. Also, the default operation when this instruction is not used is given by the default value below.

OptionType

OptionParam

Enumerator

Meaning

Selectable data
type

Meaning of value

Default

_TCP_NO DELAY

Specifies the TCP_NODELAY option. It can be used only for TCP socket.

BOOL

TRUE*1 : TCP_NODELAY option enabled FALSE: TCP_NODELAY option disabled

FALSE

*1 When it is set to TRUE, the Nagle algorithm is disabled. With this setting, even small data is not transmitted collectively.

NJ/NX-series Instructions Reference Manual (W502)

2-1123

2 Instruction Descriptions

Related System-defined Variables

Name

Meaning

Data type

Description

_EIP_EtnOnlineSta *1 _EIP1_EtnOnlineSta *2 _EIP2_EtnOnlineSta *3 _EIPIn1_EtnOnlineSta *4

Online

BOOL

This variable indicates when built-in EtherNet/IP port communications can be used. TRUE: Communications are possible. FALSE: Communications are not possible.

*1 Use this variable name for an NJ-series CPU Unit. *2 Use this variable name for port 1 on an NX-series CPU Unit, or for an NY-series Controller. *3 Use this variable name for port 2 on an NX-series CPU Unit. *4 Use this variable name for the internal port on an NY-series Controller.

Additional Information
Refer to the NJ/NX-series CPU Unit Built-in EtherNet/IP Port User's Manual (Cat. No. W506) or the NYseries Industrial Panel PC / Industrial Box PC Built-in EtherNet/IP Port User's Manual (Cat. No. W563) for details on the socket service functions.

Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error.
· This instruction can be used only for the built-in EtherNet/IP on the NJ/NX-series CPU Units and on the NY-series Controllers.
· You can use this instruction after the socket handle is opened by the SktTCPAccept, or SktTCPConnect instruction and before data transmission is started by SktTCPRcv, SktTCPSend, or SktClearBuf instruction. An error will occur if you execute this instruction after data transmission is started.
· You must set the socket option for each handle specified with Socket. The socket option that was set is enabled while the handle is open. After closing the handle with the SktClose instruction, execute the SktTCPAccept and SktTCPConnect instructions again to open the handle, and then execute this instruction to set the socket option.
· Except for NX102 CPU Units, you can execute a maximum of 32 of the following instructions at the same time: SktUDPCreate, SktUDPRcv, SktUDPSend, SktTCPAccept, SktTCPConnect, SktTCPRcv, SktTCPSend, SktGetTCPStatus, SktClose, SktClearBuf, SktSetOption, ModbusTCPCmd, ModbusTCPRead, and ModbusTCPWrite. For NX102 CPU Units, a maximum of 64 instructions can be executed.
· An error will occur in the following cases. Error will change to TRUE.
· The value of a member of Socket is outside of the valid range.
· The data type specified for OptionParam is not supported by OptionType.
· The specified handle socket already started transmission.
· The specified socket type is not supported by the handle type. Such a case includes when the TCP_NODELAY is executed for UDP socket.
· The handle specified by Socket.Handle does not exist.

2-1124

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

EtherNet/IP Communications Instructions

SktSetOption

Sample Programming

ST

Internal Variables

Variable

Data type

Initial value

Comment

Trigger

BOOL

FALSE

Execution condition

DoTCP

BOOL

FALSE

Processing

Stage

INT

0

State transition

(Handle:=0, SrcAdr:=(PortN

2

WkSocket

_sSOCKET

o:=0,IpAdr:=''), Socket

DstAdr:=(PortN

o:=0,IpAdr:=''))

SendSocketDat

ARRAY[0..1999] OF BYTE

Send data

Nodelay

BOOL

TRUE

NoDelay setting

SktTCPConnect_instance

SktTCPConnect

SktSetOption_instance SktSetOption

SktTCPSend_instance SktTCPSend

SktClose_instance

SktClose

// Start sequence when Trigger changes to TRUE. IF ((Trigger=TRUE) AND (DoTCP=FALSE) AND (_EIP_EtnOnlineSta=TRUE)) THEN
DoTCP:=TRUE; Nodelay:=TRUE; Stage:=INT#1; SktTCPConnect_instance(Execute:=FALSE);// Initialize instance. SktSetOption_instance( // Initialize instance.
Execute:=FALSE, OptionType:=_TCP_NODELAY, OptionParam:= Nodelay); SktSetOption_instance(Execute:=FALSE);// Initialize instance. SktTCPSend_instance(// Initialize instance. Execute:=FALSE, SendDat:=SendSocketDat[0]);// Dummy SktClose_instance(Execute:=FALSE);// Initialize instance. END_IF;
IF (DoTCP=TRUE) THEN CASE Stage OF 1 :// Request a connection. SktTCPConnect_instance( Execute:=TRUE, SrcTcpPort:=UINT#0,// Local UDP port number: Automatically assigned. DstAdr:='192.168.250.2',// Remote IP address DstTcpPort:=UINT#6000,// Destination TCP port number Socket =>WkSocket);// Socket IF (SktTCPConnect_instance.Done=TRUE) THEN Stage:=INT#2;// Normal end ELSIF (SktTCPConnect_instance.Error=TRUE) THEN Stage:= INT#10; // Error end

NJ/NX-series Instructions Reference Manual (W502)

2-1125

2 Instruction Descriptions
END_IF;
2 :// Set Socket Option SktSetOption_instance( Execute:=TRUE, Socket:=WkSocket);// Socket OptionType:=_TCP_NODELAY, // Option type OptionParam:= Nodelay); // NODELAY enabled IF (SktSetOption_instance.Done=TRUE) THEN Stage:=INT#3;// Normal end ELSIF (SktSetOption_instance.Error=TRUE) THEN Stage:=INT#20; // Error end END_IF;
3 :// Send request SktTCPSend_instance( Execute:=TRUE, Socket:=WkSocket);// Socket SendDat:=SendSocketDat[0],// Send data Size:=UINT#2000);// Send data size IF (SktTCPSend_instance.Done=TRUE) THEN Stage:=INT#4;// Normal end ELSIF (SktTCPSend_instance.Error=TRUE) THEN Stage:= INT#30; // Error end END_IF;
4 :// Request closing data. SktClose_instance( Execute:=TRUE, Socket:=WkSocket);// Socket IF (SktClose_instance.Done=TRUE) THEN Stage:=INT#0;// Normal end ELSIF (SktClose_instance.Error=TRUE) THEN Stage:= INT#40; // Error end END_IF;
0 :// Normal end DoTCP:=FALSE; Trigger:=FALSE;
ELSE// Interrupted by error. DoTCP:=FALSE; Trigger:=FALSE;
END_CASE; END_IF;

2-1126

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

ModbusTCPCmd

2 Instruction Descriptions

ModbusTCPCmd

The ModbusTCPCmd instruction sends general commands using Modbus-TCP protocol.

Instruction

Name

FB/ FUN

Graphic expression

ST expression

ModbusTCP Cmd

Send Modbus TCP General FB Command

ModbusTCPCmd_instance(

Execute,

Socket,

ModbusTCPCmd_instance

ModbusTCPCmd

Execute Socket

Done Busy

UnitIdentifier,

2

CmdDat,

CmdSize,

RespDat,

UnitIdentifier CmdDat CmdSize RespDat

Error ErrorID ErrorIDEx

TimeOut, Done, Busy, Error,

TimeOut

RespSize

ErrorID,

ErrorIDEx,

RespSize);

Version Information An NX102 CPU Unit is required to use this instruction.

Variables

Name

Meaning

I/O

Description

Valid range

Unit

Socket

Socket

Socket

---

---

UnitIdentifier Unit ID

Unit ID *1

Depends on data type.

---

CmdDat CmdSize

Command data
Command data size

Input

Command data Command data size

Depends on data type.
1 to 253

--Bytes

TimeOut

Timeout time

Specify the timeout time in 0.1 seconds. If 0 is specified, it will be treated as 2 seconds.

Depends on data type.

0.1 seconds

RespDat

Response data

In-out Response data

Depends on data type.

---

RespSize

Response size

Output Response data size

1 to 253

---

*1 When you send commands to Modbus-TCP slaves, the default value is used for operation.

Default --255 --1
20
-----

NJ/NX-series Instructions Reference Manual (W502)

2-1127

2 Instruction Descriptions

STRING DT TOD
DATE TIME LREAL Real numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE

Boolean

Bit strings

Integers

Times, durations, dates, and text strings

BOOL

Socket

UnitIdentifier

CmdDat[] (array)

OK

CmdSize

TimeOut

RespDat[] (array)

OK

RespSize

Refer to Function for details on the structure _sSOCKET. OK
OK OK
OK

Function
The ModbusTCPCmd instruction sends general commands to the destination socket that is established in advance using Modbus TCP protocol. This instruction ends normally when a normal response to the command is received.

The data type of Socket is structure _sSOCKET. The specifications are as follows:

Name

Meaning

Description

Socket

Socket

Socket

Handle

Handle

Handle of the socket to send and receive data

SrcAdr *1

Local address

Local IP address and port number

PortNo *1

Port number Port number

IpAdr *1

IP address

IP address or host name. A DNS or Hosts setting is required to use a host name.

DstAdr *1

Destination address

Destination IP address and port number

PortNo *1

Port number Port number

IpAdr *1

IP address

IP address or host name. A DNS or Hosts setting is required to use a host name.

*1 This member is not used for this instruction.

Data type _sSOCKET UDINT _sSOCKET_A DDRESS UINT
STRING
_sSOCKET_A DDRESS UINT
STRING

Valid range --Depends on data type. --1 to 65,535
Depends on data type.
--1 to 65,535
Depends on data type.

Unit Default --- ----- 0 --- ---
0
--`'
--- --0
--`'

2-1128

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

EtherNet/IP Communications Instructions

ModbusTCPCmd

This instruction stores the contents of the CmdDat[] input variable as long as the length of the CmdSize input variable in the command data.
CmdSize: 1 to 253 bytes

Transaction ID
2 bytes

Protocol ID 2 bytes

Field length 2 bytes

Unit

Command data

ID

CmdDat

Unit FancIdentifi- tion
er code
1 byte 1 byte

Data 0 to 252 bytes

Command header

Command data

2

Command
After the instruction sends general commands, it stores the response data received from the destination in the RespDat[] in-out variable.

RespSize: 1 to 253 bytes

Transaction ID
2 bytes

Protocol ID 2 bytes

Field length 2 bytes

Unit

Response data

ID

RespDat

Unit FancIdentifi- tion
er code
1 byte 1 byte

Data 0 to 252 bytes

Response header

Response data

Response
The instruction outputs, in bytes, the size of the response data contained in the received response to RespSize. In case of an error response, the values of RespDat[] and RespSize are not changed.
TimeOut input variable specifies the timeout time in 100 milliseconds. If a response does not return within the timeout time, it is determined as a timeout error.

Timing Charts
The following figures show the timing charts.

 Normal end

Execute Busy Done Error

TRUE FALSE TRUE FALSE TRUE FALSE TRUE FALSE

ErrorID

*2 *1
*3
Cleared to 0. Updated to result. (16#0000: Normal)

ErrorIDEx

Cleared to 0. Updated to result. (16#00000000: Normal)

*1 Processing with Modbus slave *2 A response to the command is received. *3 Task period

NJ/NX-series Instructions Reference Manual (W502)

2-1129

2 Instruction Descriptions

 Error end

Execute

TRUE FALSE

Busy

TRUE FALSE

Done

TRUE FALSE

Error

TRUE FALSE

ErrorID

*1
*2
Cleared to 0. Updated to result. (16#****: Error)

ErrorIDEx

Cleared to 0. Updated to result. (16#********: Error)

*1 Processing with Modbus slave *2 Task period

Related System-defined Variables

Name

Meaning

Data type

Description

_EIP_EtnOnlineSta *1 _EIP1_EtnOnlineSta *2 _EIP2_EtnOnlineSta *3 _EIPIn1_EtnOnlineSta *4

Online

BOOL

This variable indicates when built-in EtherNet/IP port communications can be used. TRUE: Communications are possible. FALSE: Communications are not possible.

*1 Use this variable name for an NJ-series CPU Unit. *2 Use this variable name for port 1 on an NX-series CPU Unit, or for an NY-series Controller. *3 Use this variable name for port 2 on an NX-series CPU Unit. *4 Use this variable name for the internal port on an NY-series Controller.

Additional Information
· Refer to the NJ/NX-series CPU Unit Built-in EtherNet/IP Port User's Manual (Cat. No. W506) or the NY-series Industrial Panel PC / Industrial Box PC Built-in EtherNet/IP Port User's Manual (Cat. No. W563) for details on the socket service functions.
· If you execute this instruction in the Simulator, when Execute changes from FALSE to TRUE, Done immediately changes to TRUE. Data will not be output to the communications line. The value of RespDat[] does not change, while the value of RespSize changes to 0.

Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is normally completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for timing charts for Execute, Done, Busy, and Error.
· A compiling error will occur if you use this instruction in an event task. Do not use this instruction in event tasks.
· This instruction can be used only for the built-in EtherNet/IP on NX102 CPU Units.
· For the destination to which to send general commands using this instruction, you need to use the SktTCPConnect instruction to establish a connection in advance. Input the Socket that you get there to this instruction. At this time, specify the port number on the Modbus TCP slave side (the port number is set to 502 by default).

2-1130

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

EtherNet/IP Communications Instructions

ModbusTCPCmd

· This instruction does not clear the receive buffer for a TCP socket. If you need to clear the buffer, execute the SktClearBuf instruction.
· When you want to set the socket option, execute the SktSetOption instruction.
· Except for NX102 CPU Units, you can execute a maximum of 32 of the following instructions at the same time: SktUDPCreate, SktUDPRcv, SktUDPSend, SktTCPAccept, SktTCPConnect, SktTCPRcv, SktTCPSend, SktGetTCPStatus, SktClose, SktClearBuf, SktSetOption, ModbusTCPCmd, ModbusTCPRead, and ModbusTCPWrite. For NX102 CPU Units, a maximum of 64 instructions can be executed.
· Error is TRUE if an error occurred. The meanings of the values of ErrorID and ErrorIDEx are given in the following table.

Value of ErrorID

Value of ErrorIDEx

Error

2

16#0400

16#00000000

The value of CmdSize is outside of the valid range.

16#0406

16#00000000

CmdSize exceeded the area of CmdDat[].

16#0407

16#00000000

The number of received bytes exceeded the received data area.

16#0C10

16#000000XX

A Exception Response was received by Modbus. XX of 000000xx in ErrorIDEx indicates the Exception Code. Refer to the Modbus Protocol for details on Exception Code.

16#0C11

16#00000000

The Modbus Response data is incorrect. · FuctionCode is incorrect. · Receive size is incorrect.

16#2003

16#00000000

· The socket is being processed. · The socket is closed.

16#2006

16#00000000

No response was received from the destination node within the timeout time.

16#2007

16#00000000

The handle value is out of range.

16#2008

16#00000000

More than 32*1 of the following instructions were executed at the same time: SktUDPCreate, SktUDPRcv, SktUDPSend, SktTCPAccept, SktTCPConnect, SktTCPRcv, SktTCPSend, SktGetTCPStatus, SktClose, SktClearBuf, SktSetOption, ModbusTCPCmd, ModbusTCPRead, and ModbusTCPWrite.

*1 For NX102 CPU Units, 64 instructions can be executed.

Sample Programming
This sample uses for an NX102 CPU Unit whose IP address is 192.168.250.1.
When Trigger changes to TRUE, the instruction clears the buffer and then sends a Modbus command to the destination Modbus TCP slave (192.168.250.10, port 502).
It reads a holding register from the read start address 32 (BYTE#16#0020) in the destination. General commands are used to read a variable.
The TCP-NODELAY option is specified in this sample programming because it is recommended in the Modbus Messaging on TCP/IP implementation guide V1.0b.

ST

Internal Variables

Variable

Trigger

DoModbusTrigger

Nodelay

Stage

Data type
BOOL BOOL BOOL INT

Initial value

Comment
Execution condition Processing NoDelay setting State transition

NJ/NX-series Instructions Reference Manual (W502)

2-1131

2 Instruction Descriptions

Internal Variables

Variable

Data type

Socket

_sSOCKET

ModbusCmdDat

ARRAY[0..4] OF BYTE

ModbusDatSize

UINT

ModbusRespDat

ARRAY[0..253] OF BYTE

ModbusRespSize

UINT

SktTCPConnect_instance SktTCPConnect

SktSetOption_instance SktTSetOption

SktClearBuf_instance

SktClearBuf

ModbusTCPCmd_instance

ModbusTCPCmd

SktClose_instance

SktClose

External Variables

Variable

_EIP1_EtnOnlineSta

Data type BOOL

Initial value

Comment Socket Command data Command data size Response data Response data size

Constant

Comment Online

2-1132

// Start sequence when Trigger changes to TRUE. IF (Trigger=TRUE) AND (DoModbusTrigger=FALSE) AND (_EIP1_EtnOnlineSta=TRUE) THEN
DoModbusTrigger:=TRUE; Nodelay:=TRUE;
SktTCPConnect_instance(Execute:= FALSE); SktSetOption_instance(
Execute:=FALSE, Socket:=Socket, OptionType:=_eSKT_OPTION_TYPE#_TCP_NODELAY, OptionParam:=Nodelay);
SktClearBuf_instance( Execute:=FALSE, Socket:=Socket);
ModbusTCPCmd_instance( Execute:=FALSE, Socket:=Socket, CmdDat:=ModbusCmdDat[0], CmdSize:=ModbusDatSize, RespDat:=ModbusRespDat[0]);
SktClose_instance( Execute:=FALSE, Socket:=Socket);
Stage:=1; // Initialization completed. END_IF;
IF (DoModbusTrigger=TRUE) THEN CASE Stage OF 1: // Socket connection request SktTCPConnect_instance( Execute:=TRUE, SrcTcpPort:=UINT#502, DstAdr:='192.168.250.10', DstTcpPort:=UINT#502, Socket=>Socket);
NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

EtherNet/IP Communications Instructions

ModbusTCPCmd

IF (SktTCPConnect_instance.Done=TRUE) THEN Stage:=2; // Socket connection is normal end.
ELSIF (SktTCPConnect_instance.Error=TRUE) THEN Stage:=99; // Socket connection is error end.
END_IF;
2: //TCP-NODELAY option request SktSetOption_instance( Execute:=TRUE, Socket:=Socket, OptionType:=_eSKT_OPTION_TYPE#_TCP_NODELAY, OptionParam:=Nodelay); IF (SktSetOption_instance.Done=TRUE) THEN Stage:=3; // Option setting is normal end. ELSIF (SktSetOption_instance.Error=TRUE) THEN Stage:=99; // Option setting is error end. END_IF;
3: // Buffer clear request SktClearBuf_instance( Execute:=TRUE, Socket:=Socket);
IF (SktClearBuf_instance.Done=TRUE) THEN Stage:=4; // Buffer clear is normal end.
ELSIF (SktClearBuf_instance.Error=TRUE) THEN Stage:=99; // Buffer clear is error end.
END_IF;
4: // Modbus Cmd send request ModbusCmdDat[0]:=BYTE#16#03; // Function code (read variable) ModbusCmdDat[1]:=BYTE#16#00; // Read start address (H) ModbusCmdDat[2]:=BYTE#16#20; // Read start address (L) ModbusCmdDat[3]:=BYTE#16#00; // Number of data (H) ModbusCmdDat[4]:=BYTE#16#01; // Number of data (L) ModbusDatSize:=5; ModbusTCPCmd_instance( Execute:=TRUE, Socket:=Socket, CmdDat:=ModbusCmdDat[0], CmdSize:=ModbusDatSize, RespDat:=ModbusRespDat[0], RespSize=>ModbusRespSize);
IF (ModbusTCPCmd_instance.Done=TRUE) THEN Stage:=5; // ModbusTCPWrite instruction is normal end.
ELSIF (ModbusTCPCmd_instance.Error=TRUE) THEN Stage:=99; // ModbusTCPWrite instruction is error end.
END_IF;
5: // Socket close request SktClose_instance( Execute:=TRUE, Socket:=Socket); IF (SktClose_instance.Done=TRUE) THEN Stage:=6; // Socket close is normal end. ELSIF (SktClose_instance.Error=TRUE) THEN Stage:=99; // Socket close is error end. END_IF;
6: // Processing after the ModbusTCPRead instruction is normal end. Trigger:=FALSE; DoModbusTrigger:=FALSE;
99: // Error Processing
NJ/NX-series Instructions Reference Manual (W502)

2
2-1133

2 Instruction Descriptions
Trigger:=FALSE; DoModbusTrigger:=FALSE; END_CASE; END_IF;

2-1134

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

ModbusTCPRead

2 Instruction Descriptions

ModbusTCPRead

The ModbusTCPRead instruction reads data that is requested by sending read commands using Modbus-TCP protocol.

Instruction

Name

FB/ FUN

Graphic expression

ST expression

ModbusTCP Read

Send Modbus

TCP Read

FB

Command

ModbusTCPRead_instance(

Execute,

ModbusTCPRead_instance

ModbusTCPRead

Execute Socket UnitIdentifier ReadCmd

Done Busy Error ErrorID

Socket,

2

UnitIdentifier,

ReadCmd,

ReadDat,

TimeOut,

Done,

ReadDat

Busy,

TimeOut

ErrorIDEx ReadSize

Error, ErrorID, ErrorIDEx,

ReadSize);

Version Information An NX102 CPU Unit is required to use this instruction.

Variables

Name

Meaning

I/O

Description

Valid range

Unit

Socket

Socket

Socket

---

---

UnitIdentifier Unit ID

Unit ID *1

Depends on data type.

---

ReadCmd

Read command

Input

Command data

Depends on data type.

---

TimeOut

Timeout time

Specify the timeout time in 0.1 seconds. If 0 is specified, it will be treated as 2 seconds.

Depends on data type.

0.1 seconds

ReadDat

Read data

In-out Read data

Depends on data type.

---

ReadSize Read size

Output Amount of read data

1 to 2000 *2 1 to 125 *3

Bits *2 Words *3

*1 When you send commands to Modbus-TCP slaves, the default value is used for operation. *2 Use this valid range when the data to read is output or input status (BOOL) *3 Use this valid range when the data to read is input register or holding register (WORD)

Default --255 ---
20
-----

NJ/NX-series Instructions Reference Manual (W502)

2-1135

2 Instruction Descriptions

STRING DT TOD
DATE TIME LREAL Real numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE

Boolean

Bit strings

Integers

Times, durations, dates, and text strings

BOOL

Socket

UnitIdentifier

ReadCmd

TimeOut

ReadDat[] (array)

OK

ReadSize

Refer to Function for details on the structure _sSOCKET. OK
Refer to Function for details on the structure _sMODBUS_READ. OK
OK
OK

Function
The ModbusTCPCmd instruction sends read commands to the destination socket that is established in advance using Modbus TCP protocol. This instruction stores the read data and the amount of read data in ReadDat and ReadSize respectively, and ends normally when a normal response to the command (i.e., requested data) is received. In case of an error response, the values of ReadDat and ReadSize do not change.

TimeOut input variable specifies the timeout time in 100 milliseconds. If a response does not return within the timeout time, it is determined as a timeout error.

The data type of Socket is structure _sSOCKET. The specifications are as follows:

Name

Meaning

Description

Socket

Socket

Socket

Handle

Handle

Handle of the socket to send and receive data

SrcAdr *1

Local address

Local IP address and port number

PortNo *1

Port number Port number

IpAdr *1

IP address

IP address or host name. A DNS or Hosts setting is required to use a host name.

DstAdr *1

Destination address

Destination IP address and port number

PortNo *1

Port number Port number

IpAdr *1

IP address

IP address or host name. A DNS or Hosts setting is required to use a host name.

*1 This member is not used for this instruction.

Data type _sSOCKET UDINT _sSOCKET_A DDRESS UINT
STRING
_sSOCKET_A DDRESS UINT
STRING

Valid range --Depends on data type. --1 to 65,535
Depends on data type.
--1 to 65,535
Depends on data type.

Unit Default --- ----- 0 --- ---
0
--`'
--- --0
--`'

2-1136

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

EtherNet/IP Communications Instructions

ModbusTCPRead

The data type of ReadCmd is structure _sMODBUS_READ. The specifications are as follows:

Name ReadCmd
Fun

Meaning
Read command

Description Command data

Function code Function code

ReadAdr

Read address Read start address

ReadSize

Read size

Read size

*1 This valid range includes the following: _MDB_READ_COILS _MDB_READ_DISCRETE_INPUTS _MDB_READ_HOLDING_REGISTERS _MDB__READ_INPUT_REGISTERS

Data type

Valid range Unit Default

_sMODBUS_ Depends on

READ

data type.

--- ---

_eMDB_FUN *1

_MDB_ --- READ_
COILS

UINT

Depends on data type.

--- 0

UINT

Depends on function code.

---

1

2

The data type of Fun is enumerated type _eMDB_FUN. The meanings of the enumerators of enumerated type _eMDB_FUN are as follows:

Enumerator _MDB_READ_COILS _MDB_READ_DISCRETE_INPUTS _MDB_READ_HOLDING_REGISTERS _MDB_READ_INPUT_REGISTERS

Meaning Read outputs (bit) Read inputs (bit) Read holding registers (word) Read input registers (word)

The valid range that you can specify with ReadSize varies depending on the function code. Each value is determined by the size of data that is read and the maximum command length. The specifications are as follows:

Function code _MDB_READ_COILS _MDB_READ_DISCRETE_INPUTS _MDB_READ_HOLDING_REGISTERS _MDB_READ_INPUT_REGISTERS

ReadSize 1 to 2,000 (bit) 1 to 2,000 (bit) 1 to 125 (word) 1 to 125 (word)

Use the ReadDat in-out variable to specify the variable to store the read data. The data type that you can use for ReadDat differs depending on the function code. The specifications are as follows:

Function code _MDB_READ_COILS _MDB_READ_DISCRETE_INPUTS _MDB_READ_HOLDING_REGISTERS _MDB_READ_INPUT_REGISTERS

Data type BOOL BOOL[] BOOL BOOL[] WORD WORD[] WORD WORD[]

NJ/NX-series Instructions Reference Manual (W502)

2-1137

2 Instruction Descriptions

Timing Charts
The following figures show the timing charts.

 Normal end

Execute

TRUE FALSE

Busy

TRUE FALSE

Done

TRUE FALSE

Error

TRUE FALSE

ErrorID

*2 *1
*3
Cleared to 0. Updated to result. (16#0000: Normal)

ErrorIDEx

Cleared to 0. Updated to result. (16#00000000: Normal)

*1 Processing with Modbus slave *2 A response to the command is received. *3 Task period

 Error end

Execute

TRUE FALSE

Busy

TRUE FALSE

Done

TRUE FALSE

Error

TRUE FALSE

ErrorID

*1
*2
Cleared to 0. Updated to result. (16#****: Error)

ErrorIDEx

Cleared to 0. Updated to result. (16#********: Error)

*1 Processing with Modbus slave *2 Task period

Related System-defined Variables

Name

Meaning

Data type

Description

_EIP_EtnOnlineSta *1 _EIP1_EtnOnlineSta *2 _EIP2_EtnOnlineSta *3 _EIPIn1_EtnOnlineSta *4

Online

BOOL

This variable indicates when built-in EtherNet/IP port communications can be used. TRUE: Communications are possible. FALSE: Communications are not possible.

*1 Use this variable name for an NJ-series CPU Unit. *2 Use this variable name for port 1 on an NX-series CPU Unit, or for an NY-series Controller. *3 Use this variable name for port 2 on an NX-series CPU Unit. *4 Use this variable name for the internal port on an NY-series Controller.

2-1138

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

ModbusTCPRead

2 Instruction Descriptions

Additional Information
· Refer to the NJ/NX-series CPU Unit Built-in EtherNet/IP Port User's Manual (Cat. No. W506) or the NY-series Industrial Panel PC / Industrial Box PC Built-in EtherNet/IP Port User's Manual (Cat. No. W563) for details on the socket service functions.
· If you execute this instruction in the Simulator, when Execute changes from FALSE to TRUE, Done immediately changes to TRUE. Data will not be output to the communications line. The value of ReadDat[] does not change, while the value of ReadSize changes to 0.

Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute 2
changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is normally completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for timing charts for Execute, Done, Busy, and Error.
· A compiling error will occur if you use this instruction in an event task. Do not use this instruction in event tasks.
· This instruction can be used only for the built-in EtherNet/IP on NX102 CPU Units.
· For the destination to which to send general commands using this instruction, you need to use the SktTCPConnect instruction to establish a connection in advance. Input the Socket that you get there to this instruction. At this time, specify the port number on the Modbus TCP slave side (the port number is set to 502 by default).
· This instruction does not clear the receive buffer for a TCP socket. If you need to clear the buffer, execute the SktClearBuf instruction.
· When you want to set the socket option, execute the SktSetOption instruction.
· Except for NX102 CPU Units, you can execute a maximum of 32 of the following instructions at the same time: SktUDPCreate, SktUDPRcv, SktUDPSend, SktTCPAccept, SktTCPConnect, SktTCPRcv, SktTCPSend, SktGetTCPStatus, SktClose, SktClearBuf, SktSetOption, ModbusTCPCmd, ModbusTCPRead, and ModbusTCPWrite. For NX102 CPU Units, a maximum of 64 instructions can be executed.
· Error is TRUE if an error occurred. The meanings of the values of ErrorID and ErrorIDEx are given in the following table.

Value of ErrorID 16#0400 16#0406 16#0407 16#0419
16#0C10
16#0C11
16#2003

Value of ErrorIDEx 16#00000000 16#00000000 16#00000000 16#00000000
16#000000XX
16#00000000
16#00000000

Error
The value of ReadCmd.Fun is outside of the valid range. The value of ReadCmd.ReadSize is outside of the valid range. ReadCmd.ReadSize exceeded the area of ReadDat[]. The number of received bytes exceeded the received data area. The data type that is specified with ReadDat[] does not match that of ReadCmd.Fun. A Exception Response was received by Modbus. XX of 000000xx in ErrorIDEx indicates the Exception Code. Refer to the Modbus Protocol for details on Exception Code. The Modbus Response data is incorrect. · FuctionCode is incorrect. · Receive size is incorrect. · The socket is being processed. · The socket is closed.

NJ/NX-series Instructions Reference Manual (W502)

2-1139

2 Instruction Descriptions

Value of ErrorID

Value of ErrorIDEx

Error

16#2006

16#00000000

No response was received from the destination node within the timeout time.

16#2007

16#00000000

The handle value is out of range.

16#2008

16#00000000

More than 32*1 of the following instructions were executed at the same time: SktUDPCreate, SktUDPRcv, SktUDPSend, SktTCPAccept, SktTCPConnect, SktTCPRcv, SktTCPSend, SktGetTCPStatus, SktClose, SktClearBuf, SktSetOption, ModbusTCPCmd, ModbusTCPRead, and ModbusTCPWrite.

*1 For NX102 CPU Units, 64 instructions can be executed.

Sample Programming
This sample uses for an NX102 CPU Unit whose IP address is 192.168.250.1.
When Trigger changes to TRUE, the instruction clears the buffer and then sends a Modbus command to the destination Modbus TCP slave (192.168.250.10, port 502).
It reads the status of an output from the read start address 19 in the destination. Read commands are used to read a variable.
The TCP-NODELAY option is specified in this sample programming because it is recommended in the Modbus Messaging on TCP/IP implementation guide V1.0b.

ST

Internal Variables

Variable

Data type

Trigger

BOOL

DoModbusTrigger

BOOL

Nodelay

BOOL

Stage

INT

Socket

_sSOCKET

ModbusReadCmd

_sMODBUS_READ

ModbusRespDat

BOOL

ModbusReadSize

UINT

SktTCPConnect_instance SktTCPConnect

SktSetOption_instance SktTSetOption

SktClearBuf_instance

SktClearBuf

ModbusTCPRead_instance

ModbusTCPRead

SktClose_instance

SktClose

Default

Comment
Execution condition Processing NoDelay setting State transition Socket
Read command
Read data Read data size

External Variables

Variable

_EIP1_EtnOnlineSta

Data type BOOL

Constant

Comment Online

// Start sequence when Trigger changes to TRUE. IF (Trigger=TRUE) AND (DoModbusTrigger=FALSE) AND (_EIP1_EtnOnlineSta=TRUE) THEN
DoModbusTrigger:=TRUE; Nodelay:=TRUE;

2-1140

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

EtherNet/IP Communications Instructions

ModbusTCPRead

SktTCPConnect_instance(Execute:= FALSE); SktSetOption_instance(
Execute:=FALSE, Socket:=Socket, OptionType:=_eSKT_OPTION_TYPE#_TCP_NODELAY, OptionParam:=Nodelay);
SktClearBuf_instance( Execute:=FALSE, Socket:=Socket);
ModbusTCPRead_instance( Execute:=FALSE, Socket:=Socket, ReadCmd:=ModbusReadCmd, ReadDat:=ModbusReadDat);
SktClose_instance( Execute:=FALSE, Socket:=Socket);
Stage:=1; // Initialization completed. END_IF;
IF (DoModbusTrigger=TRUE) THEN CASE Stage OF 1: // Socket connection request SktTCPConnect_instance( Execute:=TRUE, SrcTcPPort:=UINT#502, DstAdr:='192.168.250.10', DstTcpPort:=UINT#502, Socket=>Socket); IF (SktTCPConnect_instance.Done=TRUE) THEN Stage:=2; // Socket connection is normal end. ELSIF (SktTCPConnect_instance.Error=TRUE) THEN Stage:=99; // Socket connection is error end. END_IF;
2: //TCP-NODELAY option request SktSetOption_instance( Execute:=TRUE, Socket:=Socket, OptionType:=_eSKT_OPTION_TYPE#_TCP_NODELAY, OptionParam:=Nodelay);
IF (SktSetOption_instance.Done=TRUE) THEN Stage:=3; // Option setting is normal end.
ELSIF (SktSetOption_instance.Error=TRUE) THEN Stage:=99; // Option setting is error end.
END_IF;
3: // Buffer clear request SktClearBuf_instance( Execute:=TRUE, Socket:=Socket);
IF (SktClearBuf_instance.Done=TRUE) THEN Stage:=4; // Buffer clear is normal end.
ELSIF (SktClearBuf_instance.Error=TRUE) THEN Stage:=99; // Buffer clear is error end.
END_IF;
4: // Modbus Read request ModbusReadCmd.Fun:=_MDB_READ_COILS; // Function code ModbusReadCmd.ReadAdr:=19; // Read address
NJ/NX-series Instructions Reference Manual (W502)

2
2-1141

2 Instruction Descriptions
ModbusReadCmd.ReadSize:=1; // Read size
ModbusTCPRead_instance( Execute:=TRUE, Socket:=Socket, ReadCmd:=ModbusReadCmd, ReadDat:=ModbusReadDat, ReadSize=>ModbusReadSize);
IF (ModbusTCPRead_instance.Done=TRUE) THEN Stage:=5; // ModbusTCPWrite instruction is normal end.
ELSIF (ModbusTCPRead_instance.Error=TRUE) THEN Stage:=99; // ModbusTCPWrite instruction is error end.
END_IF;
5: // Socket close request SktClose_instance( Execute:=TRUE, Socket:=Socket); IF (SktClose_instance.Done=TRUE) THEN Stage:=6; // Socket close is normal end. ELSIF (SktClose_instance.Error=TRUE) THEN Stage:=99; // Socket close is error end. END_IF;
6: // Processing after the ModbusTCPRead instruction is normal end. Trigger:=FALSE; DoModbusTrigger:=FALSE;
99: // Error Processing Trigger:=FALSE; DoModbusTrigger:=FALSE;
END_CASE; END_IF;

2-1142

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

ModbusTCPWrite

2 Instruction Descriptions

ModbusTCPWrite

The ModbusTCPWrite instruction sends write commands using Modbus-TCP protocol.

Instruction

Name

FB/ FUN

Graphic expression

ST expression

ModbusTCPWr ite

Send Modbus TCP Write Command

FB

ModbusTCPWrite_instance(

Execute,

Socket,

ModbusTCPWrite_instance ModbusTCPWrite

UnitIdentifier,

2

WriteCmd,

Execute

Done

WriteDat,

Socket UnitIdentifier WriteCmd WriteDat TimeOut

Busy Error ErrorID ErrorIDEx

TimeOut, Done, Busy, Error,

ErrorID,

ErrorIDEx);

Version Information An NX102 CPU Unit is required to use this instruction.

Variables

Name

Meaning

I/O

Description

Valid range

Unit

Socket

Socket

Socket

---

---

UnitIdentifier Unit ID

WriteCmd

Write command

WriteDat

Write data

Input

Unit ID *1 Command data Write data

Depends on data type.

---

Depends on data type.

---

Depends on data type.

---

TimeOut

Timeout time

Specify the timeout time in 0.1 seconds. If 0 is specified, it will be treated as 2 seconds.

Depends on data type.

0.1 seconds

*1 When you send commands to Modbus-TCP slaves, the default value is used for operation.

Default --255 -----
20

NJ/NX-series Instructions Reference Manual (W502)

2-1143

2 Instruction Descriptions

STRING DT TOD
DATE TIME LREAL Real numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE

Boolean

Bit strings

Integers

Times, durations, dates, and text strings

BOOL

Socket

UnitIdentifier

WriteCmd

WriteDat[] (array)

OK

TimeOut

Refer to Function for details on the structure _sSOCKET. OK
Refer to Function for details on the structure _sMODBUS_WRITE.
OK
OK

Function
The ModbusTCPWrite instruction sends write commands to the destination socket that is established in advance using Modbus TCP protocol. This instruction ends normally when a normal response to the command (i.e., requested data) is received.

TimeOut input variable specifies the timeout time in 100 milliseconds. If a response does not return within the timeout time, it is determined as a timeout error.

The data type of Socket is structure _sSOCKET. The specifications are as follows:

Name

Meaning

Description

Socket

Socket

Socket

Handle

Handle

Handle of the socket to send and receive data

SrcAdr *1

Local address

Local IP address and port number

PortNo *1

Port number Port number

IpAdr *1

IP address

IP address or host name. A DNS or Hosts setting is required to use a host name.

DstAdr *1

Destination address

Destination IP address and port number

PortNo *1

Port number Port number

IpAdr *1

IP address

IP address or host name. A DNS or Hosts setting is required to use a host name.

*1 This member is not used for this instruction.

Data type _sSOCKET UDINT _sSOCKET_A DDRESS UINT
STRING
_sSOCKET_A DDRESS UINT
STRING

Valid range --Depends on data type. --1 to 65,535
Depends on data type.
--1 to 65,535
Depends on data type.

Unit Default --- ----- 0 --- ---
0
--`'
--- --0
--`'

2-1144

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

ModbusTCPWrite

2 Instruction Descriptions

The data type of WriteCmd is structure _sMODBUS_WRITE. The specifications are as follows:

Name WriteCmd
Fun

Meaning
Write command

Description Command data

Function code Function code

WriteAdr

Write address Write start address

WriteSize

Write size

Write size

*1 This valid range includes the following: _MDB_WRITE_SINGLE_COIL _MDB_WRITE_SINGLE_REGISTER _MDB_WRITE_MULTIPLE_COILS _MDB_WRITE_MULTIPLE_REGISTERS

Data type

Valid range Unit Default

_sMODBUS_ Depends on

WRITE

data type.

--- ---

_eMDB_FUN *1

_MDB_

---

WRITE_ SINGLE

_COIL

UINT

Depends on data type.

--- 0

UINT

Depends on function code.

---

1

2

The data type of Fun is enumerated type _eMDB_FUN. The meanings of the enumerators of enumerated type _eMDB_FUN are as follows:

Enumerator _MDB_WRITE_SINGLE_COIL _MDB_WRITE_SINGLE_REGISTER _MDB_WRITE_MULTIPLE_COILS _MDB_WRITE_MULTIPLE_REGISTERS

Meaning Write an output (bit) Write a holding register (word) Write multiple outputs (bit) Write multiple holding registers (word)

The valid range that you can specify with WriteSize varies depending on the function code. Each value is determined by the size of data that is written and the maximum command length. The specifications are as follows:

Function code _MDB_WRITE_SINGLE_COIL _MDB_WRITE_SINGLE_REGISTER _MDB_WRITE_MULTIPLE_COILS _MDB_WRITE_MULTIPLE_REGISTERS

WriteSize 1 (bit) 1 (word) 1 to 1,968 (bit) 1 to 123 (word)

NJ/NX-series Instructions Reference Manual (W502)

2-1145

2 Instruction Descriptions

Use the WriteDat input variable to specify the data to write. The data type that you can use for WriteDat differs depending on the function code. The specifications are as follows:

Function code _MDB_WRITE_SINGLE_COIL _MDB_WRITE_SINGLE_REGISTER _MDB_WRITE_MULTIPLE_COILS _MDB_WRITE_MULTIPLE_REGISTERS

Data type BOOL BOOL[] WORD WORD[] BOOL BOOL[] WORD WORD[]

Timing Charts
The following figures show the timing charts.

 Normal end

Execute

TRUE FALSE

Busy

TRUE FALSE

Done

TRUE FALSE

Error

TRUE FALSE

ErrorID

*2 *1
*3
Cleared to 0. Updated to result. (16#0000: Normal)

ErrorIDEx

Cleared to 0. Updated to result. (16#00000000: Normal)

*1 Processing with Modbus slave *2 A response to the command is received. *3 Task period

 Error end

Execute

TRUE FALSE

Busy

TRUE FALSE

Done

TRUE FALSE

Error

TRUE FALSE

ErrorID

*1
*2
Cleared to 0. Updated to result. (16#****: Error)

ErrorIDEx

Cleared to 0. Updated to result. (16#********: Error)

*1 Processing with Modbus slave *2 Task period

2-1146

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

ModbusTCPWrite

2 Instruction Descriptions

Related System-defined Variables

Name

Meaning

Data type

Description

_EIP_EtnOnlineSta *1 _EIP1_EtnOnlineSta *2 _EIP2_EtnOnlineSta *3 _EIPIn1_EtnOnlineSta *4

Online

BOOL

This variable indicates when built-in EtherNet/IP port communications can be used. TRUE: Communications are possible. FALSE: Communications are not possible.

*1 Use this variable name for an NJ-series CPU Unit.

*2 Use this variable name for port 1 on an NX-series CPU Unit, or for an NY-series Controller. *3 Use this variable name for port 2 on an NX-series CPU Unit.

2

*4 Use this variable name for the internal port on an NY-series Controller.

Additional Information
· Refer to the NJ/NX-series CPU Unit Built-in EtherNet/IP Port User's Manual (Cat. No. W506) or the NY-series Industrial Panel PC / Industrial Box PC Built-in EtherNet/IP Port User's Manual (Cat. No. W563) for details on the socket service functions.
· If you execute this instruction in the Simulator, when Execute changes from FALSE to TRUE, Done immediately changes to TRUE. Data will not be output to the communications line.

Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is normally completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for timing charts for Execute, Done, Busy, and Error.
· A compiling error will occur if you use this instruction in an event task. Do not use this instruction in event tasks.
· This instruction can be used only for the built-in EtherNet/IP on NX102 CPU Units.
· For the destination to which to send general commands using this instruction, you need to use the SktTCPConnect instruction to establish a connection in advance. Input the Socket that you get there to this instruction. At this time, specify the port number on the Modbus TCP slave side (the port number is set to 502 by default).
· This instruction does not clear the receive buffer for a TCP socket. If you need to clear the buffer, execute the SktClearBuf instruction.
· When you want to set the socket option, execute the SktSetOption instruction.
· Except for NX102 CPU Units, you can execute a maximum of 32 of the following instructions at the same time: SktUDPCreate, SktUDPRcv, SktUDPSend, SktTCPAccept, SktTCPConnect, SktTCPRcv, SktTCPSend, SktGetTCPStatus, SktClose, SktClearBuf, SktSetOption, ModbusTCPCmd, ModbusTCPRead, and ModbusTCPWrite. For NX102 CPU Units, a maximum of 64 instructions can be executed.
· Error is TRUE if an error occurred. The meanings of the values of ErrorID and ErrorIDEx are given in the following table.

NJ/NX-series Instructions Reference Manual (W502)

2-1147

2 Instruction Descriptions

Value of ErrorID

Value of ErrorIDEx

Error

16#0400 16#0406

16#00000000 16#00000000

The value of WriteCmd.Fun is outside of the valid range. The value of WriteCmd.WriteSize is outside of the valid range. WriteCmd.WriteSize exceeded the area of WriteDat[].

16#0419

16#00000000

The data type that is specified with WriteDat[] does not match that of WriteCmd.Fun.

16#0C10

16#000000XX

A Exception Response was received by Modbus. XX of 000000xx in ErrorIDEx indicates the Exception Code. Refer to the Modbus Protocol for details on Exception Code.

16#0C11

16#00000000

The Modbus Response data is incorrect. · FuctionCode is incorrect. · Receive size is incorrect.

16#2003

16#00000000

· The socket is being processed. · The socket is closed.

16#2006

16#00000000

No response was received from the destination node within the timeout time.

16#2007

16#00000000

The handle value is out of range.

16#2008

16#00000000

More than 32*1 of the following instructions were executed at the same time: SktUDPCreate, SktUDPRcv, SktUDPSend, SktTCPAccept, SktTCPConnect, SktTCPRcv, SktTCPSend, SktGetTCPStatus, SktClose, SktClearBuf, SktSetOption, ModbusTCPCmd, ModbusTCPRead, and ModbusTCPWrite.

*1 For NX102 CPU Units, 64 instructions can be executed.

Sample Programming
This sample uses for an NX102 CPU Unit whose IP address is 192.168.250.1.
When Trigger changes to TRUE, the instruction clears the buffer and then sends a Modbus command to the destination Modbus TCP slave (192.168.250.10, port 502).
An output starting from address 149 in write start address 1 is turned ON. Write commands are used to write a variable.
The TCP-NODELAY option is specified in this sample programming because it is recommended in the Modbus Messaging on TCP/IP implementation guide V1.0b.

ST

Internal Variables

Variable

Data type

Trigger

BOOL

DoModbusTrigger

BOOL

Nodelay

BOOL

Stage

INT

Socket

_sSOCKET

ModbusWriteCmd

_sMODBUS_WRITE

ModbusWriteDat

BOOL

SktTCPConnect_instance SktTCPConnect

SktSetOption_instance SktTSetOption

Default

Comment
Execution condition Processing NoDelay setting State transition Socket
Write command
Write data

2-1148

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

EtherNet/IP Communications Instructions

ModbusTCPWrite

Internal Variables

Variable

SktClearBuf_instance

ModbusTCPWrite_instance

SktClose_instance

Data type SktClearBuf ModbusTCPWrite SktClose

Default

Comment

External Variables

Variable

Data type

Constant

Comment

_EIP1_EtnOnlineSta

BOOL

Online

2

// Start sequence when Trigger changes to TRUE. IF (Trigger=TRUE) AND (DoModbusTrigger=FALSE) AND (_EIP1_EtnOnlineSta=TRUE) THEN
DoModbusTrigger:=TRUE; Nodelay:=TRUE;

SktTCPConnect_instance(Execute:= FALSE); SktSetOption_instance(
Execute:=FALSE, Socket:=Socket, OptionType:=_eSKT_OPTION_TYPE#_TCP_NODELAY, OptionParam:=Nodelay);

SktClearBuf_instance( Execute:=FALSE, Socket:=Socket);
ModbusTCPWrite_instance( Execute:=FALSE, Socket:=Socket, WriteCmd:=ModbusWriteCmd, WriteDat:=ModbusWriteDat);

SktClose_instance( Execute:=FALSE, Socket:=Socket);

Stage:=1; // Initialization completed. END_IF;

IF (DoModbusTrigger=TRUE) THEN CASE Stage OF 1: // Socket connection request SktTCPConnect_instance( Execute:=TRUE, SrcTcpPort:=UINT#502, DstAdr:='192.168.250.10', DstTcpPort:=UINT#502, Socket=>Socket); IF (SktTCPConnect_instance.Done=TRUE) THEN Stage:=2; // Socket connection is normal end. ELSIF (SktTCPConnect_instance.Error=TRUE) THEN Stage:=99; // Socket connection is error end. END_IF;

2: //TCP-NODELAY option request SktSetOption_instance( Execute:=TRUE, Socket:=Socket, OptionType:=_eSKT_OPTION_TYPE#_TCP_NODELAY, OptionParam:=Nodelay);

NJ/NX-series Instructions Reference Manual (W502)

2-1149

2 Instruction Descriptions
IF (SktSetOption_instance.Done=TRUE) THEN Stage:=3; // Option setting is normal end.
ELSIF (SktSetOption_instance.Error=TRUE) THEN Stage:=99; // Option setting is error end.
END_IF;
3: // Buffer clear request SktClearBuf_instance( Execute:=TRUE, Socket:=Socket);
IF (SktClearBuf_instance.Done=TRUE) THEN Stage:=4; // Buffer clear is normal end.
ELSIF (SktClearBuf_instance.Error=TRUE) THEN Stage:=99; // Buffer clear is error end.
END_IF;
4: // Modbus Write request ModbusWriteCmd.Fun:=_MDB_WRITE_SINGLE_COIL; // Function code ModbusWriteCmd.WriteAdr:=149; // Write address ModbusWriteCmd.WriteSize:=1; // Write size
ModbusTCPWrite_instance( Execute:=TRUE, Socket:=Socket, WriteCmd:=ModbusWriteCmd, WriteDat:=ModbusWriteDat);
IF (ModbusTCPWrite_instance.Done=TRUE) THEN Stage:=5; // ModbusTCPWrite instruction is normal end.
ELSIF (ModbusTCPWrite_instance.Error=TRUE) THEN Stage:=99; // ModbusTCPWrite instruction is error end.
END_IF;
5: // Socket close request SktClose_instance( Execute:=TRUE, Socket:=Socket); IF (SktClose_instance.Done=TRUE) THEN Stage:=6; // Socket close is normal end. ELSIF (SktClose_instance.Error=TRUE) THEN Stage:=99; // Socket close is error end. END_IF;
6: // Processing after the ModbusTCPWrite instruction is normal end. Trigger:=FALSE; DoModbusTrigger:=FALSE;
99: // Error Processing Trigger:=FALSE; DoModbusTrigger:=FALSE;
END_CASE; END_IF;

2-1150

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

EtherNet/IP Communications Instructions

ChangeIPAdr

ChangeIPAdr

The ChangeIPAdr instruction changes the IP address of the built-in EtherNet/IP port on a CPU Unit or the IP address of an EtherNet/IP Unit.

Instruction

Name

FB/ FUN

Graphic expression

ST expression

ChangeIPAdr Change IP

FB

Address

ChangeIPAdr_instance

ChangeIPAdr_instance( Execute,

ChangeIPAdr

Execute

Done

UnitNo, BootPControl,

2

UnitNo BootPControl

Busy Error

IPAdr,

IPAdr

ErrorID

SubnetMask,

SubnetMask DefaultGateway

DefaultGateway,

Done,

Busy,

Error, ErrorID);

Variables

Name UnitNo

Meaning Unit number

I/O Input

BootP Control
IPAdr[] (array)*7 Subnet Mask[] (array)*7 Default Gateway[] (array)*7

IP address assignment method and setting timing IP address
Subnet mask
Default gateway

Description Unit number for which to change the IP address
Method to obtain the IP address and the setting timing

Valid range
_CBU_CPU *1, _CBU_CPU_P ort1 *2, _CBU_CPU_P ort2 *3, _CBU_CPU_In Port1 *4, or _CBU_No00 to _CBU_No15 *5
0 to 3 *6

Unit ---

IP address

*8

Subnet mask

Default gateway

Default _CBU_No00
0 ---

*1 Specification is possible for an NJ-series CPU Unit.

*2 Specification is possible for port 1 on an NX-series CPU Unit or an NY-series Controller. You can specify _CBU_CPU instead of _CBU_CPU_Port1.

*3 Specification is possible for port 2 on an NX-series CPU Unit.

*4 Specification is possible for an NY-series Controller.

*5 Specification is possible for an NJ-series CPU Unit.

*6 The range is 0 to 2 for port 1 on an NX-series CPU Unit, for NJ-series CPU Unit, and for an NY-series Controller; 0 to 3 for port 2 on an NX-series CPU Unit; and 0 for the internal port on an NY-series Controller.

*7 This is a 4-element array with element numbers 0 to 3.

NJ/NX-series Instructions Reference Manual (W502)

2-1151

2 Instruction Descriptions

*8 The valid range depends on whether you specify the built-in EtherNet/IP port or an EtherNet/IP Unit for UnitNo (Unit number). Refer to Function, below, for details.

Bit strings

Integers

Times, durations, dates, and text strings

Real numbers

Boolean BOOL

STRING DT TOD
DATE TIME

LREAL REAL

LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE

UnitNo
BootP Control
IPAdr[] (array)
Subnet Mask[] (array)
BootP Control
Default Gateway[] (array)

Refer to Function for the enumerators of the enumerated type _eUnitNo. OK
OK Specify an array.
OK Specify an array.
OK
Specify an array.

Function

The ChangeIPAdr instruction changes the IP address of the built-in EtherNet/IP port, internal port, or EtherNet/IP Unit that is specified with UnitNo (Unit number) according to IP address assignment method and setting timing BootPControl.
If you specify the built-in EtherNet/IP port with UnitNo, the port goes to link OFF status when execution of the instruction ends and then goes to link ON status with the new IP address.
If the internal port is specified with UnitNo, the _EIPIn1_EtnOnlineSta system-defined variable changes to FALSE when execution of the instruction ends. Communications with the new IP address is enabled when the variable changes to TRUE. If you specify an EtherNet/IP Unit with UnitNo, the EtherNet/IP Unit is restarted when execution of the instruction ends. Communications with the new IP address is enabled when restarting the Unit ends.
You can use this instruction to change the IP address of the built-in EtherNet/IP port, internal port, or an EtherNet/IP Unit from an HMI.
The data type of UnitNo is enumerated type _eUnitNo. The meanings of the enumerators are as follows:

Enumerator _CBU_CPU*1 _CBU_CPU_Port1*2 _CBU_CPU_Port2*3 _CBU_CPU_InPort1*4 _CBU_No00 to _CBU_No15*5

Meaning Built-in EtherNet/IP port Built-in EtherNet/IP communications port 1 Built-in EtherNet/IP communications port 2
Internal port 1 Unit number 00 to 15 of the EtherNet/IP Unit

*1 Specification is possible for an NJ-series CPU Unit. *2 Specification is possible for an NX-series CPU Unit or an NY-series Controller. You can spec-
ify _CBU_CPU instead of _CBU_CPU_Port1. *3 Specification is possible for an NX-series CPU Unit. You cannot use it for CPU Units without
Communications Port 2. *4 Specification is possible for an NY-series Controller. *5 Specification is possible for an NJ-series CPU Unit.

2-1152

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

ChangeIPAdr

2 Instruction Descriptions

The value of BootPControl determines how to obtain the new IP address and when to set it, as described in the following table.

For BootPControl, you can specify a value in the range of 0 to 2 for port 1 on an NX-series CPU Unit, for NJ-series CPU Unit, and for an NY-series Controller. The range is 0 to 3 for port 2 on an NX-series CPU Unit. You can specify only 0 for internal port on an NY-series Controller.

Value of BootPControl

Method to obtain the IP address

When to change the IP address

0

The IP address is obtained from IP

The IP address is set only once each time

address IPAdr[], subnet mask

the instruction is executed (fixed setting).

SubnetMask[], and default gateway

DefaultGateway[].

1

The IP address is obtained from the

The IP address is set once when the instruc-

BOOTP server.

tion is executed and then once each time

2

the power supply to the Controller is turned

ON.

2

The IP address is obtained from the

The IP address is set only once each time

BOOTP server.

the instruction is executed (fixed setting).

3

The port is set to an unused port.

The IP address is set only once each time

Any existing IP address is deleted.

the instruction is executed (fixed setting).

Set the IP address, subnet mask, and default gateway in order in elements 0 to 3 of IPAdr[], SubnetMask[], and DefaultGateway[]. For example, if the new IP address is 130.58.17.32, set IPAdr[0] to BYTE#16#82, IPAdr[1] to BYTE#16#3A, IPAdr[2] to BYTE#16#11 and IPAdr[3] to BYTE#16#20.
The valid ranges of IPAdr[], SubnetMask[], and DefaultGateway[] depend on whether you specify the built-in EtherNet/IP port or an EtherNet/IP Unit for UnitNo, as shown below. The valid ranges of the values are valid only when the value of BootPControl is set to 0.

Setting of UnitNo Built-in EtherNet/IP port Internal port

Input variable IPAdr[] (array)

SubnetMask[] (array)
DefaultGateway[] (array)

Valid range The following IP addresses cannot be used. All other IP addresses are valid.
· IP addresses that start with 127, 0, or 255 · IP addresses with a host ID for which all bits are 0's or for
which all bits are 1's · Class D IP addresses (224.0.0.0 to 239.255.255.255) · Class E IP addresses (240.0.0.0 to 255.255.255.255) · IP addresses that are reserved for AutoIP*1 (169.254.0.0 to
169.254.255.255) · IP addresses of USB ports (192.168.255.0 to
192.168.255.255)*2 192.0.0.0 to 255.255.255.252
The following IP addresses cannot be used. All other IP addresses are valid.
· IP addresses that start with 127, 0, or 255 · There is only one address for which all bits are 1's · Class D IP addresses (224.0.0.0 to 239.255.255.255) · Class E IP addresses (240.0.0.0 to 255.255.255.255) · IP addresses that are reserved for AutoIP*1 (169.254.0.0 to
169.254.255.255) · IP addresses of USB ports (192.168.255.0 to
192.168.255.255)*2

NJ/NX-series Instructions Reference Manual (W502)

2-1153

2 Instruction Descriptions

Setting of UnitNo

Input variable

Valid range

EtherNet/IP Unit

IPAdr[] (array)

The following IP addresses cannot be used. All other IP addresses are valid.

· IP addresses that start with 127

· Class D IP addresses (224.0.0.0 to 239.255.255.255)

· Class E IP addresses (240.0.0.0 to 255.255.255.255)

SubnetMask[] (array)

· 0.0.0.0 · 192.0.0.0 to 255.255.255.252

DefaultGateway[] (array)

The following IP addresses cannot be used. All other IP addresses are valid.

· IP addresses that start with 127

· Class D IP addresses (224.0.0.0 to 239.255.255.255)

· Class E IP addresses (240.0.0.0 to 255.255.255.255)

*1 AutoIP is an automatic IP address assignment feature of Windows 98 and later operating systems.

*2 NX102 CPU Units, NX1P2 CPU Units, and NY-series Controllers have no USB port.

The values of IPAdr[], SubnetMask[], and DefaultGateway[] are ignored when the value of BootPControl is 1 or 2. Therefore, the values of IPAdr[], SubnetMask[], and DefaultGateway[] can be outside of the valid ranges.
If you specify the built-in EtherNet/IP port for UnitNo, you can use the _EIP_EtnOnlineSta, _EIP1_EtnOnlineSta, _EIP2_EtnOnlineSta, and _EIPIn1_EtnOnlineSta system-defined variables to see if communications are possible.
Here, _EIP_EtnOnlineSta is used as an example, but this information also applies to _EIP1_EtnOnlineSta, _EIP2_EtnOnlineSta and _EIPIn1_EtnOnlineSta.

When Busy changes to FALSE, _EIP_EtnOnlineSta changes to FALSE. When communications using the new IP address are enabled, _EIP_EtnOnlineSta changes to TRUE.

Execute

TRUE FALSE

Busy

TRUE FALSE

Done

TRUE FALSE

_EIP_EtnOnlineSta

TRUE FALSE

Instruction execution started.

The variable changes to FALSE when instruction execution ends.

The variable changes to TRUE when communications become possible.

The following example shows how to change the IP address of the EtherNet/IP Unit with unit number 00 to the IP address that is obtained from the BOOTP server each time the instruction is executed. If A (Execute) is changed to TRUE from an HMI or other device, the IP address is changed to the IP address that is obtained from the BOOTP server. Then, each time the power supply is turned ON, the IP address is changed to the IP address that is obtained from the BOOTP server.

2-1154

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

2 Instruction Descriptions

LD
A
_CBU_No00 UINT#1 Array0 Array1 Array2

ChangeIPAdr_instance

ChangeIPAdr

Execute UnitNo BootPControl IPAdr SubnetMask DefaultGateway

Done Busy Error ErrorID

B
Busy0 Error0 ErrorID0

ST
ChangeIPAdr_instance(A,_CBU_No00,UINT#1,Array0,Array1,Array2,B,Busy0,Error0,ErrorID0);
2
The IP address that was obtained from the BOOTP server is set for the EtherNet/IP Unit with a unit number of 00. Then, each time the power supply is turned ON, the IP address is reset to the IP address that is obtained from the BOOTP server.
EtherNet/IP Unit with unit number 00

ChangeIPAdr

IP address is changed to the value that was obtained from the BOOTP server.

Related System-defined Variables

Name
_EIP_EtnOnlineSta*1 _EIP1_EtnOnlineSta*2 _EIP2_EtnOnlineSta*3 _EIPIn1_EtnOnlineSta*4

Meaning Online

Data type
BOOL

Description
This variable indicates when built-in EtherNet/IP port communications can be used. TRUE: Communications are possible. FALSE: Communications are not possible.

*1 Use this variable name for an NJ-series CPU Unit.

*2 Use this variable name for port 1 on an NX-series CPU Unit, or for an NY-series Controller.

*3 Use this variable name for port 2 on an NX-series CPU Unit.

*4 Use this variable name for the internal port on an NY-series Controller.

Additional Information
· If you specify the built-in EtherNet/IP port with UnitNo, the following events are recorded in the event log when the instruction is executed. · Link OFF Detected · IP Address Fixed
· If you specify the internal port with UnitNo, the following events are recorded in the event log when the instruction is executed. · IP Address Fixed
· You can change the IP address with this instruction even if the CPU Unit is write protected.

NJ/NX-series Instructions Reference Manual (W502)

2-1155

2 Instruction Descriptions

Precautions for Correct Use

· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error.
· If you specify the built-in EtherNet/IP port with UnitNo, communications with the built-in EtherNet/IP port will be disabled temporarily when execution of the instruction ends. Confirm that the system will not be adversely affected even if the built-in EtherNet/IP port goes to link OFF status.
· If you specify an EtherNet/IP Unit with UnitNo, the EtherNet/IP Unit is restarted when execution of the instruction ends. Confirm that the system will not be adversely affected even if the EtherNet/IP Unit is restarted.
· You cannot use this instruction in an event task. A compiling error will occur.
· Error is TRUE if an error occurred. The meanings of the values of ErrorID are given in the following table.

Value of ErrorID 16#0400 16#2400
16#2402 16#240D

Error name Input Value Out of Range No Execution Right
Too Many Simultaneous Instruction Executions IP Address Setting Invalid

Description The value of an input variable is outside of the valid range.
The instruction was executed when changing the status was not possible. · While changing the settings was already in progress · While restarting the built-in EtherNet/IP port was in progress · While downloading tag data link settings from the Network
Configurator was in progress Too many ChangeIPAdr, ChangeFTPAccount, and ChangeNTPServerAdr instructions were executed at the same time.
The network address of the specified port is the same as the network address of another port.

Version Information
A CPU Unit with unit version 1.02 or later and Sysmac Studio version 1.03 or higher are required to use this instruction.

Sample Programming

This sample changes the IP address of the built-in EtherNet/IP port to the following fixed IP address.

Item IP address Subnet mask Default gateway

Value 192.168.250.10 255.255.255.0 0.0.0.0

LD

Variable ChangeTrigger SettingTrigger Done0 Error0 Busy0
ErrorID0

Data type BOOL BOOL BOOL BOOL BOOL
WORD

Initial value False False False False False
16#0

Comment Change Flag Changing IP Address Flag IP address changed Error in changing the IP address Changing IP address Error ID for changing the IP address

2-1156

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

ChangeIPAdr

2 Instruction Descriptions

Variable NewIPAddress NewSubnetMask NewDefaultGateway RS_instance ChangeIPAdr_instance

Data type ARRAY[0..3] OF BYTE ARRAY[0..3] OF BYTE ARRAY[0..3] OF BYTE RS ChangeIPAdr

Initial value [4(16#0)] [4(16#0)] [4(16#0)]

Comment IP address Subnet mask Default gateway

Check execution conditions. ChangeTrigger Busy0

RS_instance RS

SettingTrigger

Set

Q1

Reset1

Done0
2

Error0

Set IP address. SettingTrigger
16#C0 16#A8 16#FA 16#0A 16#FF 16#FF 16#FF 16#00 16#00 16#00 16#00 16#00

MOVE

EN

ENO

In

Out

MOVE

EN

ENO

In

Out

MOVE

EN

ENO

In

Out

MOVE

EN

ENO

In

Out

MOVE

EN

ENO

In

Out

MOVE

EN

ENO

In

Out

MOVE

EN

ENO

In

Out

MOVE

EN

ENO

In

Out

MOVE

EN

ENO

In

Out

MOVE

EN

ENO

In

Out

MOVE

EN

ENO

In

Out

MOVE

EN

ENO

In

Out

NewIPAddress[0] NewIPAddress[1] NewIPAddress[2] NewIPAddress[3] NewSubnetMask[0] NewSubnetMask[1] NewSubnetMask[2] NewSubnetMask[3] NewDefaultGateway[0] NewDefaultGateway[1] NewDefaultGateway[2] NewDefaultGateway[3]

NJ/NX-series Instructions Reference Manual (W502)

2-1157

2 Instruction Descriptions

Change IP address. SettingTrigger
_CBU_CPU UINT#0
NewIPAddress NewSubnetMask NewDefaultGateway

ChangeIPAdr_instance

ChangeIPAdr

Execute UnitNo BootPControl IPAdr SubnetMask DefaultGateway

Done Busy Error ErrorID

Done0
Busy0 Error0 ErrorID0

ST
Variable ChangeTrigger SettingTrigger Done0

Data type BOOL BOOL BOOL

Initial value False False False

Error0

BOOL

False

Busy0

BOOL

False

ErrorID0

WORD

16#0

NewIPAddress NewSubnetMask NewDefaultGateway RS_instance ChangeIPAdr_instance

ARRAY[0..3] OF BYTE ARRAY[0..3] OF BYTE ARRAY[0..3] OF BYTE RS ChangeIPAdr

[4(16#0)] [4(16#0)] [4(16#0)]

//Check execution conditions. IF((ChangeTrigger=TRUE)AND(Busy0=FALSE))THEN
SettingTrigger:= TRUE; END_IF;

Comment Change Flag Changing IP Address Flag IP address changed Error in changing the IP address Changing IP address Error ID for changing the IP address IP address Subnet mask Default gateway

IF((Done0=TRUE)OR(Error0=TRUE))THEN SettingTrigger:= FALSE;
END_IF;

//Set IP address.

IF(SettingTrigger=TRUE)THEN

NewIPAddress[0]

:= 16#C0;

NewIPAddress[1]

:= 16#A8;

NewIPAddress[2]

:= 16#FA;

NewIPAddress[3]

:= 16#0A;

NewSubnetMask[0] := 16#FF;

NewSubnetMask[1] := 16#FF;

NewSubnetMask[2] := 16#FF;

NewSubnetMask[3] := 16#00;

NewDefaultGateway[0]:= 16#00;

NewDefaultGateway[1]:= 16#00;

NewDefaultGateway[2]:= 16#00;

NewDefaultGateway[3]:= 16#00;

END_IF;

//Change IP address.

ChangeIPAdr_instance(

Execute

:= SettingTrigger,

UnitNo

:= _CBU_CPU,

BootPControl := UINT#0,

IPAdr

:= NewIPAddress,

SubnetMask

:= NewSubnetMask,

DefaultGateway := NewDefaultGateway,

Done

=>Done0,

Busy

=>Busy0,

Error

=>Error0,

ErrorID

=>ErrorID0);

2-1158

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

ChangeFTPAccount

2 Instruction Descriptions

ChangeFTPAccount

The ChangeFTPAccount instruction changes the FTP login name and password of the built-in EtherNet/IP port on a CPU Unit or those of an EtherNet/IP Unit.

Instruction

Name

FB/ FUN

Graphic expression

ST expression

ChangeFTP Account

Change FTP FB Account

ChangeFTPAccount_instance( Execute,

ChangeFTPAccount_instance ChangeFTPAccount

UnitNo, NewUserName,

2

Execute UnitNo NewUserName NewPassword

Done Busy Error ErrorID

NewPassword, Done, Busy,

Error,

ErrorID);

Variables

Name UnitNo

Meaning Unit number

New

Login name

UserName

New Password

Password

I/O Input

Description Unit number for which to change the FTP login name and password Login name
Password

Valid range
_CBU_CPU or _CBU_No00 to _CBU_No15*1
1 to 12 single-byte alphanumeric characters (case sensitive)
*2

Unit ---

Default _CBU_No00
---

*1 You can set _CBU_No00 to _CBU_No15 only for an NJ-series CPU Unit.

*2 The valid range depends on whether you specify the built-in EtherNet/IP port or an EtherNet/IP Unit for UnitNo (Unit number). Refer to Function, below, for details.

Bit strings

Integers

Times, durations, dates, and text strings

Real numbers

Boolean BOOL

STRING DT TOD
DATE TIME

LREAL REAL

LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE

UnitNo
New UserName
New Password

Refer to Function for the enumerators of the enumerated type _eUnitNo. OK OK

NJ/NX-series Instructions Reference Manual (W502)

2-1159

2 Instruction Descriptions

Function

The ChangeFTPAccount instruction changes the FTP login name and password of the built-in EtherNet/IP port or EtherNet/IP Unit that is specified with UnitNo (Unit number), to the values specified with FTP login name NewUserName and password NewPassword.

When Execute changes from FALSE to TRUE, the values of NewUserName and NewPassword are written as the FTP login name and password of the built-in EtherNet/IP port. The value of Busy remains TRUE during execution of the instruction, and the value of Done changes to TRUE when reception of the setting change request is completed. The settings are not applied yet when Done changes to TRUE.

If you specify an EtherNet/IP Unit with UnitNo, the EtherNet/IP Unit is restarted when execution of the instruction ends. The new login name and password are enabled when restarting the Unit ends.

You can use this instruction to change the FTP login name and password of the built-in EtherNet/IP port or an EtherNet/IP Unit from an HMI.

The data type of UnitNo is enumerated type _eUnitNo. The meanings of the enumerators are as follows:

Enumerator
_CBU_CPU
_CBU_No00 to _CBU_No15*1

Meaning Built-in EtherNet/IP port Unit number 00 to 15 of the EtherNet/IP Unit

*1 This can be set only for an NJ-series CPU Unit.

The valid range of the value of NewPassword depends on whether you specify the built-in EtherNet/IP port or an EtherNet/IP Unit for UnitNo (Unit number), as given below.

Setting of UnitNo Built-in EtherNet/IP port EtherNet/IP Unit

Valid range 8 to 32 single-byte alphanumeric characters (case sensitive) 1 to 8 single-byte alphanumeric characters (case sensitive)

The following example shows how to change the FTP login name and password of the EtherNet/IP Unit with unit number 00. If A (Execute) is changed to TRUE from an HMI or other device, the FTP login name is changed to `OMRON' and the password is changed to `omron0123'.

LD A

_CBU_No00 'OMRON'
'omron0123'

ChangeFTPAccount_instance

ChangeFTPAccount

Execute UnitNo NewUserName NewPassword

Done Busy Error ErrorID

B
Busy0 Error0 ErrorID0

ST ChangeFTPAccount_instance(A,_CBU_No00,'OMRON','omron0123',B,Busy0,Error0,ErrorID0);

The FTP login name is changed to `OMRON' and the password is changed to `omron0123' for the EtherNet/IP Unit with unit number 00.

EtherNet/IP Unit with unit number 00

2-1160

FTP login name: OMRON Password: omron0123

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

ChangeFTPAccount

2 Instruction Descriptions

Execute

TRUE FALSE

Busy

TRUE FALSE

Done

TRUE FALSE

_EIP_EtnOnlineSta

TRUE FALSE

Instruction execution started.

The variable changes to

FALSE when instruction execution ends.

The variable changes to TRUE when communications become possible.

2

Related System-defined Variables

Name _EIP_EtnOnlineSta*1 _EIP1_EtnOnlineSta*2 _EIP2_EtnOnlineSta*3 _EIPIn1_EtnOnlineSta*4

Meaning Online

Data type BOOL

Description
This variable indicates when built-in EtherNet/IP port communications can be used. TRUE: Communications are possible. FALSE: Communications are not possible.

*1 Use this variable name for an NJ-series CPU Unit. *2 Use this variable name for port 1 on an NX-series CPU Unit, or for an NY-series Controller. *3 Use this variable name for port 2 on an NX-series CPU Unit. *4 Use this variable name for the internal port on an NY-series Controller.

Additional Information
· You can change the FTP login name and password with this instruction even if the CPU Unit is write protected.
· Even if you change the FTP login name and password with this instruction during a file transfer, the file transfer will continue.

Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error. · You cannot use this instruction in an event task. A compiling error will occur. · Error is TRUE if an error occurred. The meanings of the values of ErrorID are given in the following
table.

NJ/NX-series Instructions Reference Manual (W502)

2-1161

2 Instruction Descriptions

Value of ErrorID 16#0400 16#2400
16#2402

Error name Input Value Out of Range No Execution Right
Too Many Simultaneous Instruction Executions

Description
· The value of an input variable is outside of the valid range. · The value of an input variable is incorrect.
The instruction was executed when changing the status was not possible.
· While changing the settings was already in progress · While restarting the built-in EtherNet/IP port was in progress · While downloading tag data link settings from the Network
Configurator is in progress
Too many ChangeIPAdr, ChangeFTPAccount, and ChangeNTPServerAdr instructions were executed at the same time.

Version Information
A CPU Unit with unit version 1.02 or later and Sysmac Studio version 1.03 or higher are required to use this instruction.

2-1162

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

ChangeNTPServerAdr

2 Instruction Descriptions

ChangeNTPServerAdr

The ChangeNTPServerAdr instruction changes the address of the NTP server of the built-in EtherNet/IP port on a CPU Unit or the address of an EtherNet/IP Unit.

Instruction
ChangeNTP ServerAdr

Name
Change NTP Server Address

FB/ FUN
FB

Graphic expression

ChangeNTPServerAdr_instance

ChangeNTPServerAdr

Execute UnitNo AdrType IPAdr HostName

Done Busy Error ErrorID

ST expression

ChangeNTPServerAdr_instance(

Execute,

UnitNo, AdrType,

2

IPAdr,

HostName,

Done,

Busy,

Error,

ErrorID);

Variables

Name UnitNo
AdrType

Meaning Unit number

I/O Input

Server setting method

Description

Valid range

Unit

Unit number for which to change _CBU_CPU or ---

the NTP server address

_CBU_No00 to

_CBU_No15*1

NTP Server Address Setting Method

Depends on data type.

Default _CBU_ No00
FALSE

TRUE: Host name

FALSE: IP address

IPAdr[]

IP address

IP address of the NTP server *3

---

(array)*2

HostName Host name

Host name of the address of the NTP server

1 to 200 singlebyte alphanumeric characters, "-" (hyphen), and "." (dot)*4

*1 You can set _CBU_No00 to _CBU_No15 only for an NJ-series CPU Unit.

*2 This is a 4-element array with element numbers 0 to 3.

*3 The valid range depends on whether you specify the built-in EtherNet/IP port or an EtherNet/IP Unit for UnitNo (Unit number). Refer to Function, below, for details.

*4 There can be between 1 and 63 single-byte alphanumeric characters between any two dots. The valid range of HostName is valid only when server setting method AdrType is FALSE.

Bit strings

Integers

Times, durations, dates, and text strings

Real numbers

Boolean BOOL

STRING DT TOD
DATE TIME

LREAL REAL

LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE

UnitNo

AdrType

OK

Refer to Function for the enumerators of the enumerated type _eUnitNo.

NJ/NX-series Instructions Reference Manual (W502)

2-1163

2 Instruction Descriptions

Real numbers

Boolean BOOL

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME

LREAL REAL

LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE

IPAdr[]

OK

(array)

Specify an array.

HostName

OK

Function

The ChangeNTPServerAdr instruction changes the address of the NTP server of the built-in EtherNet/IP port or EtherNet/IP Unit that is specified with unit number UnitNo. If server setting method AdrType is TRUE, the NTP server address is changed to IP address IPAdr[]. If server setting method AdrType is FALSE, the NTP server address is changed to host name HostName. When Execute changes from FALSE to TRUE, the values of IPAdr[] or HostName are written as the NTP server address. The value of Busy remains TRUE during execution of the instruction, and the value of Done changes to TRUE when reception of the setting change request is completed. The settings are not applied yet when Done changes to TRUE.

If you specify an EtherNet/IP Unit with UnitNo, the EtherNet/IP Unit is restarted when execution of the instruction ends. The new NTP server address is enabled when restarting the Unit ends.

You can use this instruction to change the NTP server address of the built-in EtherNet/IP port or an EtherNet/IP Unit from an HMI.

The data type of UnitNo is enumerated type _eUnitNo. The meanings of the enumerators are as follows:

Enumerator
_CBU_CPU
_CBU_No00 to _CBU_No15*1

Meaning Built-in EtherNet/IP port Unit number 00 to 15 of the EtherNet/IP Unit

*1 This can be set only for an NJ-series CPU Unit.

Set the IP address in order in elements 0 to 3 of IPAdr[]. For example, to change the NTP server address to IP address 130.58.17.32, set IPAdr[0] to BYTE#16#82, IPAdr[1] to BYTE#16#3A, IPAdr[2] to BYTE#16#11 and IPAdr[3] to BYTE#16#20.
The valid range of the value of IPAdr[] depends on whether you specify the built-in EtherNet/IP port or an EtherNet/IP Unit for unit number UnitNo, as given below. The valid ranges of the values are valid only when AdrType is TRUE.

Setting of UnitNo Built-in EtherNet/IP port
EtherNet/IP Unit

Valid range The following IP addresses cannot be used. All other IP addresses are valid. · IP addresses that start with 127, 0, or 255 · Class D IP addresses (224.0.0.0 to 239.255.255.255) · Class E IP addresses (240.0.0.0 to 255.255.255.255) · IP addresses that are reserved for AutoIP* (169.254.0.0 to 169.254.255.255) · IP addresses of USB ports (192.168.255.0 to 192.168.255.255) The following IP addresses cannot be used. All other IP addresses are valid. · IP addresses that start with 127 · Class D IP addresses (224.0.0.0 to 239.255.255.255) · Class E IP addresses (240.0.0.0 to 255.255.255.255)

* AutoIP is an automatic IP address assignment feature of Windows 98 and later operating systems.

2-1164

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

ChangeNTPServerAdr

2 Instruction Descriptions

The following example shows how to change the NTP server address of the EtherNet/IP Unit with unit number 00. If A (Execute) is changed to TRUE from an HMI or other device, the NTP server address is changed. For example, assume that IPAdr0[0] is BYTE#16#C0, IPAdr0[1] is BYTE#16#A8, IPAdr0[2] is BYTE#16#FA, and IPAdr0[3] is BYTE#16#0A. If Type (AdrType) is TRUE, the NTP server address is changed to IP address 192.168.250.10. If Type (AdrType) is FALSE, the NTP server address is changed to host name ServerA.

LD

ChangeNTPServerAdr_instance

A

ChangeNTPServerAdr

B

Execute

Done

_CBU_No00 UnitNo

Busy

Busy0

Type AdrType

Error

Error0

IPAdr0 IPAdr

ErrorID

ErrorID0

'ServerA' HostName

2

ST

ChangeNTPServerAdr_instance(A,_CBU_No00,Type,IPAdr0,'ServerA',B,Busy0,Error0,ErrorID0);

The NTP server address of the EtherNet/IP Unit with a unit number of 00 is changed to an IP address of 192.168.250.10.

EtherNet/IP Unit with unit number 00

NTP server address IP address192.168.250.10

IPAdr[0]=IPAdr0[0] IPAdr[1]=IPAdr0[1] IPAdr[2]=IPAdr0[2] IPAdr[3]=IPAdr0[3]

BYTE#16#C0 BYTE#16#A8 BYTE#16#FA BYTE#16#0A

You can use the _EIP_EtnOnlineSta, _EIP1_EtnOnlineSta, or _EIP2_EtnOnlineSta system-defined variable to see if the port is in link ON status.
Here, _EIP_EtnOnlineSta is used as an example, but this information also applies to _EIP1_EtnOnlineSta and _EIP2_EtnOnlineSta.
When Busy changes to FALSE, the port changes to link OFF status and _EIP_EtnOnlineSta changes to FALSE. When the port then changes to link ON status, _EIP_EtnOnlineSta changes to TRUE.

Execute

TRUE FALSE

Busy

TRUE FALSE

Done

TRUE FALSE

_EIP_EtnOnlineSta

TRUE FALSE

Instruction execution started.

When instruction

execution ends, the port goes to link OFF status and the variable changes to FALSE.

When the port goes to link ON status, the variable changes to TRUE.

NJ/NX-series Instructions Reference Manual (W502)

2-1165

2 Instruction Descriptions

Related System-defined Variables

Name _EIP_EtnOnlineSta*1 _EIP1_EtnOnlineSta*2 _EIP2_EtnOnlineSta*3

Meaning Online

Data type BOOL

Description
This variable indicates when built-in EtherNet/IP port communications can be used. TRUE: Communications are possible. FALSE: Communications are not possible.

*1 Use this variable name for an NJ-series CPU Unit. *2 Use this variable name for port 1 on an NX-series CPU Unit. *3 Use this variable name for port 2 on an NX-series CPU Unit.

Additional Information
· You can change the NTP server address with this instruction even if the CPU Unit is write protected. · If the NTP server whose address is to change is set to operate at a specified time interval, measuring
the specified time interval will start when execution of this instruction ends.

Precautions for Correct Use

· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error.
· You cannot use this instruction in an event task. A compiling error will occur.
· Error is TRUE if an error occurred. The meanings of the values of ErrorID are given in the following table.

Value of ErrorID 16#0400 16#2400
16#2402

Error name Input Value Out of Range No Execution Right
Too Many Simultaneous Instruction Executions

Description
The value of IPAdr[] or HostName is not correct*1
The instruction was executed when changing the status was not possible. · While changing the settings was already in progress · While restarting the built-in EtherNet/IP port was in progress · While downloading tag data link settings from the Network
Configurator is in progress Too many ChangeIPAdr, ChangeFTPAccount, and ChangeNTPServerAdr instructions were executed at the same time.

*1 The setting range is checked only for the specified AdrType.

Version Information
A CPU Unit with unit version 1.02 or later and Sysmac Studio version 1.03 or higher are required to use this instruction.

2-1166

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

FTPGetFileList

2 Instruction Descriptions

FTPGetFileList

The FTPGetFileList instruction gets a list of the files in the FTP server.

Instruction

Name

FB/FUN

FTPGetFileList

Get FTP Server File List

FB

Graphic expression

FTPGetFileList_instance

FTPGetFileList

Execute

Done

ConnectSvr

Busy

SvrDirName CommandCanceled

GetFileNum

Error

SortOrder

ErrorID

ExecOption

ErrorIDEx

RetryCfg

StoredNum

Cancel

FileList

ST expression

FTPGetFileList_instance(

Execute,

ConnectSvr,

SvrDirName,

GetFileNum, SortOrder,

2

ExecOption,

RetryCfg,

Cancel,

FileList,

Done,

Busy,

CommandCanceled,

Error,

ErrorID,

ErrorIDEx,

StoredNum);

Variables

Name

Meaning

I/O

Connect Svr

Connected FTP server settings

SvrDir Name

FTP server directory name

GetFile Num

Number of files to list

SortOrder*4 Sort order

Input

Exec Option
RetryCfg

FTP execution options
Execution retry settings

Cancel

Cancel

Description

Valid range

Unit

Setting parameters for the connected FTP server

---

Name of FTP server directory for which to get the file list

256 bytes max. (255 single-byte alphanumeric characters plus the final NULL character)*2

Number of files to list

1 to 1000

Order to sort the file list

_NAME_ASC, --_NAME_DESC, _DATE_ASC, _DATE_DESC

Options for FTP execution
Instruction execution retry settings
TRUE: Instruction execution is canceled. FALSE: Instruction execution is not canceled.

---
Depends on data type.

Default *1
''*3
1 _NAME _ASC ---
FALSE

NJ/NX-series Instructions Reference Manual (W502)

2-1167

2 Instruction Descriptions

Name

Meaning

I/O

Description

Valid range

Unit

FileList[] array*5*6*7

File details

In-out

Details for the obtained file list ---

---

Command- Cancel comCanceled pleted

TRUE: Canceling completed. FALSE: Canceling not completed.

Depends on data type.

Output

---

StoredNum

Number of files obtained in list

Number of files for which details were obtained

0 to 1000

Default *1
---

*1 If you omit an input parameter, the default value is not applied. A building error will occur. *2 You cannot use the following characters in FTP server directory names: * ? < > | " *3 The default is the home directory when you log onto the FTP server. *4 If the FTP server does not support sorting names, the names are in ascending order regardless of the value of SortOrder. *5 The array can have a maximum of 1,000 elements. *6 This is a one-dimensional array. If an array with more than one dimension is specified, a building error will occur. *7 The first array element number is 0. If a number other than 0 is specified for the first array element, a building error will
occur.

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT LWORD

DWORD WORD BYTE

ConnectSvr SvrDirName GetFileNum SortOrder ExecOption RetryCfg Cancel FileList[] array Command Canceled StoredNum

Refer to Function for details on the structure _sFTP_CONNECT_SVR. OK
OK Refer to Function for the enumerators of the enumerated type _eFILE_SORT_ORDER.
Refer to Function for details on the structure _sFTP_EXEC_OPTION. Refer to Function for details on the structure _sFTP_RETRY_CFG.
OK
Refer to Function for details on the structure _sFTP_FILE_DETAIL.
OK
OK

2-1168

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

FTPGetFileList

2 Instruction Descriptions

Function
The FTPGetFileList instruction gets a list of files and file details from the specified directory SvrDirName on the connected FTP server ConnectSvr. Specify the number of files to list in GetFileNum. Specify the order in which to sort the obtained file information in SortOrder.

The data type of ConnectSvr is structure _sFTP_CONNECT_SVR. The specifications are as follows:

Name

Meaning

Description

Data type

Valid range Unit Default

ConnectSvr

Connected FTP server settings

Setting parameters for the connected FTP server

_sFTP_CONN ECT_SVR

---

--- ---

2

Adr

Address

IP address or host name*1

STRING

1 to 200 bytes*2

PortNo UserName

Port number User name

TCP port number of FTP server control connection
User name on FTP server

UINT STRING

0 to 65535*3
33 bytes max.*4*5*6

--- ---

Password

Password

FTP server password STRING

33 bytes max.*4*5*6

*1 A separate DNS or Hosts setting is required to specify a host name.
*2 You can use the following single-byte characters: A to Z, a to z, 0 to 9, - (hyphen), . (period), and _ (underbar).
*3 If you specify 0, TCP port number 21 is used.
*4 You can use the following single-byte characters: A to Z, a to z, 0 to 9, - (hyphen), . (period), and _ (underbar). You can also use \ and @ for a CPU Unit with unit version 1.16 or later.
*5 The NULL character at the end must be counted in the number of bytes.
*6 For CPU Units with unit version 1.08, specify a text string of one character or more. An error will occur if you specify a text string that contains only the final NULL character.

The data type of SortOrder is enumerated type _eFILE_SORT_ORDER. The meanings of the enumerators are as follows:

Enumerator

Meaning

_NAME_ASC Ascending order of names

_NAME_DESC Descending order of names

_DATE_ASC

Ascending order of last modified dates

_DATE_DESC Descending order of last modified dates

The file details is stored in FileList[]. The number of files for which information was obtained is stored in StoredNum.

NJ/NX-series Instructions Reference Manual (W502)

2-1169

2 Instruction Descriptions

The data type of FileList[] is structure _sFTP_FILE_DETAIL. The specifications are as follows:

Name

Meaning

Description

Data type

Valid range Unit Default

FileList

File details

Details for the obtained file list

_sFTP_FILE _DETAIL

---

---

---

Name

File or folder name

File or folder name

STRING

256 bytes max. (255 single-byte alphanumeric characters plus the final NULL --character)

ModifiedDate Size

Last modified date
File size

The last modified data of the file or folder
The file size*1

DATE_AND_

TIME

---

ULINT

--Bytes

ReadOnly Folder

Read-only attribute
Folder

The read-only attribute of the file or folder
TRUE: Read only FALSE: Not read only
TRUE: Folder
FALSE: Not a folder

BOOL BOOL

Depends on data type.

---

*1 The file size is 0 for a folder.

Specifying Options for FTP Server Processing
The operation specified with ExecOption is performed to obtain the file list from the FTP server. The option settings are the same as those for the FTPGetFile instruction (page 2-1184). Refer to the specified page for details. However, the only option that is valid for this instruction is ExecOption.PassiveMode.

2-1170

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

FTPGetFileList

2 Instruction Descriptions

Specifying Retrying Connection Processing with the FTP Server
Connection processing with the FTP server times out and ends when the specified timeout time RetryCfg.TimeOut is exceeded before a connection is successfully established. If the FTP server rejects the connection, processing ends before reaching the timeout time. After failing to connect, connection processing is retried after the specified retry interval RetryInterval. If a connection with the FTP server is not established within the number of retries specified with RetryCfg.RetryNum, an instruction execution error occurs.

If, after a successful connection to the FTP server, a problem occurs on the network that interrupts file

transfer for longer than the time specified with RetryCfg.TimeOut, a timeout occurs and retry processing is not performed.

2

The data type of RetryCfg is structure _sFTP_RETRY_CFG. The specifications are as follows:

Name RetryCfg
TimeOut RetryNum RetryInterval

Meaning Execution retry settings
Timeout time
Number of retries
Retry interval

Description
Instruction execution retry settings
Timeout time for a connection to the FTP server
The number of retries when connection fails
The interval for retrying when connection fails

Data type _sFTP_RETR Y_CFG
UINT
UINT
UINT

*1 If 0 is set, the timeout time is 20 s. *2 If 0 is set, the retry interval is 1 s.

Valid range --0 to 60*1 0 to 3 0 to 65535*2

Unit --Seconds Times Seconds

Default --20 0 1

The following figure shows the relation between the timeout time, number of retries, and retry interval when an FTP client performs connection processing to a FTP server.

Timeout time
Connection request from FTP client to FTP server

1st retry

2nd retry

3rd retry

Connection Retry interval failed

Time

NJ/NX-series Instructions Reference Manual (W502)

2-1171

2 Instruction Descriptions

 Successfully Connecting to the FTP Server
When connection processing to the FTP server is successfully completed and the file list is obtained from the FTP server, the following processing is performed. · A value of 16#0000 is stored in ErrorID. · The obtained data is stored in the output data, such as FileList[]. · The value of Done is changed to TRUE.
The following timing chart is an example for successful connection processing to the FTP server.

Execute Busy

TRUE FALSE
TRUE FALSE

Done

TRUE FALSE

Error

TRUE FALSE

Cancel TRUE FALSE

CommandCanceled TRUE FALSE
ErrorID

Output data, such as FileList[]

16#0000
Data obtained from FTP server
Connection Processing, such as processing to to get the file list from FTP server FTP server Successful connection

2-1172

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

2 Instruction Descriptions

 Failing to Connect to the FTP Server
The following processing is performed when connection processing to the FTP server fails. · The error code is stored in ErrorID. · The value of Error is changed to TRUE. The following timing chart is an example for when connection processing to the FTP server fails.

Execute Busy Done Error

TRUE FALSE
TRUE FALSE
TRUE FALSE
TRUE FALSE

TRUE Cancel FALSE

CommandCanceled TRUE FALSE

ErrorID

2
16#2406

Output data, such as FileList[]

Connection processing

to FTP server

Connection failed

FTPGetFileList

NJ/NX-series Instructions Reference Manual (W502)

2-1173

2 Instruction Descriptions

Canceling Instruction Execution
If Cancel changes to TRUE during instruction execution, processing with the FTP server is forced to end. You can use it to end processing when obtaining the file list or connection processing to the FTP server is taking too much time.
 When Cancel Changes to TRUE during Processing with the FTP Server
The following occurs if Cancel changes to TRUE while the FTPGetFileList instruction is obtaining a file list from the FTP server.
Any file details that were obtained from the FTP server is stored in FileList[]. The number of files for which file details were correctly obtained is stored in StoredNum. The value of Done does not change to TRUE.
The value of CommandCanceled changes to TRUE when cancellation is completed. Use this to confirm normal completion of cancellation.

Execute Busy Done Error
Cancel CommandCanceled
ErrorID

TRUE FALSE TRUE FALSE
TRUE FALSE
TRUE FALSE
TRUE FALSE
TRUE FALSE

Cancellation processing
16#0000

Output data, such as FileList[]

Data obtained from FTP server Processing with FTP server in progress

2-1174

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

FTPGetFileList

2 Instruction Descriptions

 When Processing with the FTP Server Is Completed Before Cancellation Processing Is Started

Even if Cancel is changed to TRUE, Done changes to TRUE to indicate normal completion if processing with the FTP server is completed before cancellation processing is started. The value of CommandCanceled does not change to TRUE.

Execute

TRUE FALSE

Busy

TRUE FALSE

Done

TRUE FALSE

TRUE

2

Error

FALSE

Cancel

TRUE FALSE

CommandCanceled

TRUE FALSE

ErrorID

16#0000

Output data, such as FileList[]

Data obtained from FTP server
Processing with the FTP Server was completed before cancellation processing was started.

 When both Cancel and Execute Are TRUE
If both Cancel and Execute are TRUE, cancellation is given priority and processing is not performed with the FTP server. CommandCanceled changes to TRUE.

Execute Busy Done Error
Cancel CommandCanceled
ErrorID

TRUE FALSE TRUE FALSE
TRUE FALSE
TRUE FALSE
TRUE FALSE
TRUE FALSE

Output data, such as FileList[]

FALSE after 1 task period

NJ/NX-series Instructions Reference Manual (W502)

2-1175

2 Instruction Descriptions

Related System-defined Variables

Name
_EIP_EtnOnlineSta*1 _EIP1_EtnOnlineSta*2 _EIP2_EtnOnlineSta*3 _EIPIn1_EtnOnlineSta*4

Meaning Online

Data type
BOOL

Description
This variable indicates when built-in EtherNet/IP port communications can be used. TRUE: Communications are possible. FALSE: Communications are not possible.

*1 Use this variable name for an NJ-series CPU Unit. *2 Use this variable name for port 1 on an NX-series CPU Unit, or for an NY-series Controller. *3 Use this variable name for port 2 on an NX-series CPU Unit. *4 Use this variable name for the internal port on an NY-series Controller.

Precautions for Correct Use
· This instruction can be used only for the built-in EtherNet/IP ports on NJ/NX-series CPU Units and NY-series Controllers.
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section (page 2-3) for a timing chart for Execute, Done, Busy, and Error.
· If there are no files or subdirectories in the directory specified by the SvrDirName input variable, Done changes to TRUE to indicate a normal end. If 0 is stored in StoredNum, nothing is stored in FileList[].
· If the number of array elements in FileList[] is less than the number of files specified with the GetFileNum input variable, only the file information that will fit in FileList[] is stored and the file information that does not fit is not stored. In this case, Error does not change to TRUE.
· If a file name exceeds 255 characters, the first 255 characters are stored in Name in FileList[]. In this case, Error does not change to TRUE.
· It may be impossible to obtain some or all of the specified file details depending on FTP server specifications. The members of FileList[] take the following values for files for which details are not obtained. In this case, the value of Error is FALSE.

Member ModifiedDate Size ReadOnly Folder

Value DT#1970-01-01-00:00:00.000000000 0 FALSE FALSE

· You can execute a maximum of 3 of the following instructions at the same time: FTPGetFileList, FTPGetFile, FTPPutFile, FTPRemoveFile, and FTPRemoveDir.
· An error will occur in the following cases. Error will change to TRUE.
· The value of any input parameter is outside of the valid range.
· ".." is specified for a directory level in SvrDirName.
· An incorrect path such as "//" is specified for SvrDirName.
· The directory specified by SvrDirName does not exist on the FTP server.
· The FTP server specified by ConnectSvr does not exist on the network or the specified FTP server is not operating.
· More than 3 of the following instructions were executed at the same time: FTPGetFileList, FTPGetFile, FTPPutFile, FTPRemoveFile, and FTPRemoveDir.

2-1176

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

2 Instruction Descriptions

· File transfer processing was interrupted during FTP server connection processing by a problem on the network.
· For this instruction, expansion error code ErrorIDEx gives the FTP response code that was returned by the FTP server. The following table lists typical values of ErrorIDEx and describes the meanings of the errors and the corrections. For details, refer to FTP server specifications. An expansion error code is output to ErrorIDEx when the value of error code ErrorID is WORD#16#2407.

Value of ErrorIDEx

Meaning

Correction

16#000001A9 16#000001AA

It was not possible to establish a data If you use FTP communications with an FTP

connection.

server over the Internet, make sure that the

FTP open mode is not set to active.

The connection was closed. Data trans- Check the connection to the FTP server.

2

fer was aborted.

Make sure that the FTP server is operating.

16#000001C2

It was not possible to perform the

Make sure that the file is not open for any

requested file operation. Using the file other application.

was not possible, e.g., it is already open.

16#00000212

User login was not possible.

Check the FTP user name and password.

16#00000214

An account to save files is required.

Check the FTP user access rights.

16#00000226

Execution of the requested file operation was not possible because using the file was not possible, e.g., accessing it was not possible because it was not found.

Make sure that a file with the specified name exists in the directory on the FTP server. Check the access rights of the specified file.

16#00000229

Execution was not possible because the Check the access rights of the specified

file name was not correct.

directory.

Version Information
A CPU Unit with unit version 1.08 or later and Sysmac Studio version 1.09 or higher are required to use this instruction.

FTPGetFileList

NJ/NX-series Instructions Reference Manual (W502)

2-1177

2 Instruction Descriptions

Sample Programming

The following programming downloads a file from the /Recipe directory on the FTP server and stores it in the root directory of an SD Memory Card.
The file to download is the last file in the /Recipe directory on the FTP server when the files are sorted in ascending order of names.

FTP server

IP address: 192.168.250.2 TCP port number: 21 User name: FtpUser Password: 12345678

Ethernet

FTP client
A file is downloaded from the /Recipe directory on the FTP server.

Built-in EtherNet/IP port

The Controller is connected to the FTP server through an EtherNet/IP network. The settings of the parameters to connect to the FTP server are given in the following table.

Parameter IP address TCP port number User name Password

Value 192.168.250.2 21 FtpUser 12345678

The following procedure is used.
1 The FTPGetFileList instruction is used to get a file list from the FTP server. The following table gives the FTP server directory name, number of files to list, sort order, and variable to store file details.

Item

Specification

FTP server directory name

'/Recipe'

Number of files to list

1000

Sort order

Ascending order of names

Variable to store file details

FTPFileList[]

2 The FTPGetFile instruction is used to download the last file from the file list obtained in step 1

when the list is in ascending order of names. The file is stored in the root directory on the SD

Memory Card.

3 Normal end processing is executed if all processing ends normally. Processing for an error end

is performed if an error occurs.

2-1178

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

2 Instruction Descriptions

LD

Internal Variables

Variable

Data type

Initial value

Comment

FTPGetFileList_instance

FTPGetFileList

Instance of FTPGetFileList instruction

FTPGetFile_instance

FTPGetFile

Instance of FTPGetFile instruction

FTPAddr

_sFTP_CONNECT_SVR

(Adr := '', PortNo := 0, UserName := '', Password := '')

Connected FTP server settings

FTPFileList

ARRAY[0..999] OF _sFTP_FILE_DETAIL

[1000((Name := '', ModifiedDate := DT#1970-01-0100:00:00, Size := 0, ReadOnly := False, Folder := False))]

File details

2

GetResult

ARRAY[0..0] OF _sFTP_FILE_RESULT

[(Name := '', TxError := False, RemoveError := False, Reserved := [4(16#0)])]

Downloaded file results

FTPStoredNum UINT

0

Number of files obtained in file list

LastFileIndex

UINT

0

Index of last file when list is in ascending order of names

RS_instance

RS

Instance of RS instruction

OperatingEnd

BOOL

FALSE

Processing completed

Trigger

BOOL

FALSE

Execution condition

Operating

BOOL

FALSE

Processing

FTPGetFileList

NJ/NX-series Instructions Reference Manual (W502)

2-1179

2 Instruction Descriptions

Prepare connected FTP server settings.

P_First_RunMode

MOVE

MOVE

EN

ENO

EN

ENO

1

'192.168.250.2' In

Out FTPAddr.Adr UINT#21 In

Out FTPAddr.PortNo

MOVE

MOVE

1

EN

ENO

EN

ENO

'FTPUser' In

Out FTPAddr.UserName '12345678' In

Out FTPAddr.Password

Determine if instruction execution is completed. FTPGetFileList_instance.Done FTPGetFile_instance.Done

OperatingEnd

FTPGetFileList_instance.Error FTPGetFile_instance.Error

Accept trigger. Trigger FTPGetFileList_instance.Busy

FTPGetFile_instance.Busy

Execute FTPGetFileList instruction.

FTPGetFileList_instance

Operating

FTPGetFileList

FTPAddr '/Recipe'

Execute

Done

ConnectSvr

Busy

SvrDirName CommandCanceled

UINT#1000

GetFileNum SortOrder

Error ErrorID

ExecOption

ErrorIDEx

RetryCfg

StoredNum

Cancel

FTPFileList

FileList

OperatingEnd
FTPStoredNum FTPFileList

RS_instance

RS

Set

Q1

Reset1

Operating

FTPGetFileList_instance.Done

-

EN ENO

2

FTPStoredNum In1

LastFileIndex

UINT#1 In2

Execute FTPGetFile instruction.
2 FTPAddr '/Recipe' '/'
FTPFileList[LastFileIndex].Name
GetResult

FTPGetFile_instance

FTPGetFile

Execute

Done

ConnectSvr

Busy

SvrDirName CommandCanceled

LocalDirName

Error

FileName

ErrorID

ExecOption

ErrorIDEx

RetryCfg

GetNum

Cancel

GetFileResult

GetResult

2-1180

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

2 Instruction Descriptions

Processing after normal end Operating FTPGetFileList_instance.Done

FTPGetFile_instance.Done

Inline ST
1 // Processing after normal end 2 ;

Processing after error end Operating FTPGetFileList_instance.Error

Inline ST
1 // Processing after error end 2 ;

FTPGetFile_instance.Error
2

FTPGetFileList

NJ/NX-series Instructions Reference Manual (W502)

2-1181

2 Instruction Descriptions

ST

Internal Variables

Variable
R_TRIG_instance UP_Q FTPGetFile_instance FTPGetFileList_instance
FTPFileList
FTPStoredNum
DoFTPTrigger
FTPAddr
GetResult
Stage Trigger

Data type
R_TRIG BOOL FTPGetFile
FTPGetFileList
ARRAY[0..999] OF _sFTP_FILE_DETAIL
UINT
BOOL
_sFTP_CONNECT_SVR ARRAY[0..0] OF _sFTP_FILE_RESULT UINT BOOL

Initial value
FALSE
[1000((Name := '', ModifiedDate := DT#1970-01-0100:00:00, Size := 0, ReadOnly := False, Folder := False))] 0
FALSE
(Adr := '', PortNo := 0, UserName := '', Password := '') [(Name := '', TxError := False, RemoveError := False, Reserved := [4(16#0)])] 0 FALSE

Comment
Instance of R_TRIG instruction Trigger output Instance of FTPGetFile instruction Instance of FTPGetFileList instruction
File details
Number of files obtained in file list Execution condition for FTPGetFileList and FTPGetFile Connected FTP server settings
Downloaded file results
Instruction execution stage Execution condition

2-1182

// Prepare connected FTP server settings.

IF P_First_RunMode THEN

FTPAddr.Adr

:= '192.168.250.2'; // Address

FTPAddr.PortNo := UINT#21;

// Port number

FTPAddr.UserName := 'FtpUser';

// User name

FTPAddr.Password := '12345678';

// Password

END_IF;

Accept trigger.

R_TRIG_instance(Trigger, UP_Q);

IF ( (UP_Q = TRUE) AND (FTPGetFileList_instance.Busy = FALSE) AND

(FTPGetFile_instance.Busy = FALSE) ) THEN

DoFTPTrigger := TRUE;

Stage := INT#1;

FTPGetFileList_instance( // Initialize instance.

Execute := FALSE,

ConnectSvr := FTPAddr,

SvrDirName := '/Recipe',

GetFileNum := UINT#1000,

FileList := FTPFileList,

StoredNum => FTPStoredNum) ;

FTPGetFile_instance( // Initialize instance.

Execute

:= FALSE,

ConnectSvr := FTPAddr,

SvrDirName := '/Recipe',

LocalDirName := '/',

FileName

:= '',

GetFileResult := GetResult) ;

END_IF;

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

FTPGetFileList

2 Instruction Descriptions

IF (DoFTPTrigger = TRUE) THEN

CASE Stage OF

1 : // Execute FTPGetFileList instruction

FTPGetFileList_instance(

Execute := TRUE,

// Execution

ConnectSvr := FTPAddr,

// Connected FTP server

SvrDirName := '/Recipe',

// FTP server directory name

GetFileNum := UINT#1000,

// Number of files to list

FileList := FTPFileList, // File details

StoredNum => FTPStoredNum) ;// Number of files obtained in list

IF (FTPGetFileList_instance.Done = TRUE) THEN

Stage := INT#2;

// To next stage

ELSIF (FTPGetFileList_instance.Error = TRUE) THEN

Stage := INT#10;

// Error end

2

END_IF;

2 : // Execute FTPGetFile instruction.

FTPGetFile_instance(

Execute

:= TRUE,

// Execution

ConnectSvr := FTPAddr,

// Connected FTP server

SvrDirName := '/Recipe',

// FTP server directory name

LocalDirName := '/',

// Local directory name

FileName

:= FTPFileList[FTPStoredNum - 1].Name,

// File name

GetFileResult := GetResult) ;

// Downloaded file results

IF (FTPGetFile_instance.Done = TRUE) THEN

Stage := INT#0;

// Normal end

ELSIF (FTPGetFile_instance.Error = TRUE) THEN

Stage := INT#20;

// Error end

END_IF;

0: // Processing after normal end

DoFTPTrigger:=FALSE;

Trigger

:=FALSE;

ELSE // Processing after error end

DoFTPTrigger:=FALSE;

Trigger

:=FALSE;

END_CASE;

END_IF;

NJ/NX-series Instructions Reference Manual (W502)

2-1183

2 Instruction Descriptions

FTPGetFile

The FTPGetFile instruction downloads a file from the FTP server.

Instruction

Name

FB/FUN

Graphic expression

FTPGetFile

Get File from FTP Server

FB

FTPGetFile_instance

FTPGetFile

Execute

Done

ConnectSvr

Busy

SvrDirName CommandCanceled

LocalDirName

Error

FileName

ErrorID

ExecOption

ErrorIDEx

RetryCfg

GetNum

Cancel

GetFileResult

ST expression
FTPGetFile_instance( Execute, ConnectSvr, SvrDirName, LocalDirName, FileName, ExecOption, RetryCfg, Cancel, GetFileResult, Done, Busy, CommandCanceled, Error, ErrorID, ErrorIDEx, GetNum) ;

Variables

Name Connect Svr
SvrDir Name
LocalDir Name
FileName
Exec Option RetryCfg
Cancel

Meaning

I/O

Connected FTP server settings

FTP server directory name

Local directory name
Input
File name
FTP execution options Execution retry settings
Cancel

Description

Valid range

Unit

Setting parameters for the connected FTP server

---

Name of FTP server directory from which to download a file

256 bytes max. (255 single-byte alphanumeric characters plus the final NULL character)*2

256 bytes max.

Name of the directory in which to store the file downloaded from the FTP server

(255 single-byte alphanumeric characters plus the final NULL

character)

---

256 bytes max.

(255 single-byte

Name of file to download*4

alphanumeric characters plus

the final NULL

character)*5

Options for FTP execution
Instruction execution retry settings
TRUE: Instruction execution is canceled. FALSE: Instruction execution is not canceled.

---
Depends on data type.

Default *1 ''*3
'/' *1
--FALSE

2-1184

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

2 Instruction Descriptions

Name
GetFile Result[] array*6*7*8

Meaning
Downloaded file results

I/O In-out

CommandCanceled
GetNum

Cancel completed
Number of files to download

Output

Description
Downloaded file results
TRUE: Canceling completed. FALSE: Canceling not completed.
Number of files to download

Valid range

Unit

---

---

Depends on data type.
---
---

Default *1
---

*1 If you omit an input parameter, the default value is not applied. A building error will occur.

*2 You cannot use the following characters in FTP server directory names: * ? < > | "

2

*3 The default is the home directory when you log onto the FTP server.

*4 You can use wildcards in file names.

*5 You cannot use the following character in file names: |

*6 The array can have a maximum of 1,000 elements.

*7 This is a one-dimensional array. If an array with more than one dimension is specified, a building error will occur.

*8 The first array element number is 0. If a number other than 0 is specified for the first array element, a building error will occur.

Bit strings

Integers

Times, durations, dates, and text strings

FTPGetFile

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE
Boolean BOOL

ConnectSvr

Refer to Function for details on the structure _sFTP_CONNECT_SVR.

SvrDirName

OK

LocalDirName

OK

FileName

OK

ExecOption

Refer to Function for details on the structure _sFTP_EXEC_OPTION.

RetryCfg

Refer to Function for details on the structure _sFTP_RETRY_CFG.

Cancel

OK

GetFileResult[] array

Refer to Function for details on the structure _sFTP_FILE_RESULT.

Command Canceled

OK

GetNum

OK

Function
The FTPGetFile instruction downloads the file specified with FileName from the specified directory SvrDirName on the connected FTP server ConnectSvr to the directory specified with LocalDirName in the SD Memory Card. If the specified directory LocalDirName does not exist in the SD Memory Card, a new directory is created and the specified file is downloaded. You can use wildcards in FileName. This allows you to download more than one file at one time.

The results of downloading is stored in GetFileResult[] for each file. Store the number of files to download in GetNum. If you use a wildcard in FileName, store the number of files with names that match the wildcard.

NJ/NX-series Instructions Reference Manual (W502)

2-1185

2 Instruction Descriptions

If the actual number of transferred files is different, the value of GetFileResult[].TxError changes to TRUE. If an error occurs when deleting the source file after the download, the value of GetFileResult[].RemoveError changes to TRUE.
With an NY-series Controller, files are downloaded into the shared folder (Virtual SD Memory Card). Before downloading files to the Virtual SD Memory Card, you must make the settings for the Virtual SD Memory Card. Refer to the NY-series Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for details on a Virtual SD Memory Card.

The data type of ConnectSvr is structure _sFTP_CONNECT_SVR. The specifications are as follows:

Name

Meaning

Description

Data type

Valid range Unit Default

ConnectSvr

Connected FTP server settings

Setting parameters for the connected FTP server

_sFTP_CONN ECT_SVR

---

--- ---

Adr

Address

IP address or host name*1

STRING

1 to 200 bytes*2

PortNo UserName

Port number User name

TCP port number of FTP server control connection
User name on FTP server

UINT STRING

0 to 65535*3
33 bytes max.*4*5*6

--- ---

Password

Password

FTP server password STRING

33 bytes max.*4*5*6

*1 A separate DNS or Hosts setting is required to specify a host name.
*2 You can use the following single-byte characters: A to Z, a to z, 0 to 9, - (hyphen), . (period), and _ (underbar).
*3 If you specify 0, TCP port number 21 is used.
*4 You can use the following single-byte characters: A to Z, a to z, 0 to 9, - (hyphen), . (period), and _ (underbar). You can also use \ and @ for a CPU Unit with unit version 1.16 or later.
*5 The NULL character at the end must be counted in the number of bytes.
*6 For CPU Units with unit version 1.08, specify a text string of one character or more. An error will occur if you specify a text string that contains only the final NULL character.

The data type of GetFileResult[] is structure _sFTP_FILE_RESULT. The specifications are as follows:

Name GetFileResult
Name
TxError RemoveError Reserved

Meaning Downloaded file results
File name*1
Transfer error
Deletion error Reserved

Description Transferred file results

Data type
_sFTP_FILE_ RESULT

Transferred file name STRING

TRUE: Transfer ended in an error. FALSE: Transfer ended normally.

BOOL

TRUE: Deletion ended in an error. FALSE: Deletion ended normally.

BOOL

Reserved by the system.

ARRAY[0..3] Of Byte

Valid range Unit Default

---

--- ---

256 bytes max. (255 single-byte alphanumeric characters plus the final NULL character)

Depends on data type.

-----

---

0

*1 The file name extension is included.

2-1186

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

FTPGetFile

2 Instruction Descriptions

Using Wildcards to Specify File Names
You can use wildcards to specify the names of the files to download in FileName. As wildcards, you can specify "*" and "?". "*" represents one or more characters. "?" represents only one character. Examples of using wildcard specifications are given below.

Assume that the FTP server directory has the following file structure.

DataFiles (specified directory)

LogA01.log

LogA02.txt LogB.log

2

LogC.txt

ControlDataA1.csv

ControlDataA10.csv

ControlDataA100.csv

ControlDataB10.csv

ControlDataC100.csv

ControlSubDataFiles (subdirectory) SubData_A001.txt SubData_A002.txt

As shown in the following table, the way that the wildcards are used determines the files that are specified.

Wildcard specification Log*.log Log?.log Log?.* *Data*
* *.* ?.? ????.???

Specified files LogA01.log, LogB.log LogB.log LogB.log, LogC.txt ControlDataA1.csv, ControlDataA10.csv, ControlDataA100.csv, ControlDataB10.csv, ControlDataC100.csv, (ControlSubDataFiles)*1 All files except for those in the subdirectory All files except for those in the subdirectory No files LogB.log, LogC.txt

*1 Subdirectory files will also be included for some FTP server specifications.

If you specify wildcards, you can download up to 1,000 files.
If GetFileResult[].TxError or GetFileResult[].RemoveError is TRUE as the result of downloading files, Error changes to TRUE, the corresponding error code for the first error is stored in ErrorID and the error response from the FTP server is stored in ErrorIDEx.

NJ/NX-series Instructions Reference Manual (W502)

2-1187

2 Instruction Descriptions

Specifying Options for FTP Server Processing
The operation specified with ExecOption is performed to download files from the FTP server.

The data type of ExecOption is structure _sFTP_EXEC_OPTION. The specifications are as follows:

Name ExecOption
PassiveMode ASCIIMode FileRemove
OverWrite
Reserved

Meaning FTP execution options Passive mode specification ASCII mode specification File deletion after transfer specification*1
Overwrite specification
Reserved

Description
Options for FTP execution
TRUE: Passive mode FALSE: Active mode
TRUE: ASCII mode FALSE: Binary mode
TRUE: Delete files after transfer. FALSE: Do not delete files after transfer.
TRUE: Overwrite files at transfer destination. FALSE: Do not overwrite files at transfer destination.
Reserved by the system.

Data type _sFTP_EXEC_OPTION BOOL BOOL
BOOL
BOOL
ARRAY[0..7] Of Byte

*1 The transfer source files are not deleted when the transfer fails.

Valid range ---
Depends on data type.
---

Unit Default --- ---
FALSE ---
0

The meanings of the options are described next.

 PassiveMode (Passive Mode Specification)
The passive mode specification tells whether to use passive mode for the data connection request to the FTP server. If passive mode is not specified, active mode is used for the data connection request to the FTP server.
Refer to the NJ/NX-series CPU Unit Built-in EtherNet/IP Port User's Manual (Cat. No. W506) or NYseries Industrial Panel PC / Industrial Box PC Built-in EtherNet/IP Port User's Manual (Cat. No. W563) for details on connection request methods.
The values and their meanings for PassiveMode are given in the following table.

Set value TRUE
FALSE

Meaning
The data connection request with the FTP server is performed in passive mode. The data connection request is performed from the FTP client.
The data connection request with the FTP server is performed in active mode. The data connection request is performed from the FTP server.

2-1188

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

FTPGetFile

2 Instruction Descriptions

 ASCIIMode (ASCII Mode Specification)
The ASCII mode specification tells whether ASCII mode is used as the transfer mode from the transfer source system to the transfer destination system. If ASCII mode is not specified, binary mode is used as the transfer mode from the transfer source system to the transfer destination system.
The values and their meanings for ASCIIMode are given in the following table.

Set value

Meaning

TRUE ASCII mode is used as the transfer mode from the transfer source system to the transfer desti-

nation system.

Text line feed codes are converted from those for the transfer source system to those for the

transfer destination system.

2

FALSE Binary mode is used as the transfer mode from the transfer source system to the transfer desti-

nation system.

Text line feed codes are transferred as is from the transfer source system.

 FileRemove (File Deletion after Transfer Specification)
The file deletion after transfer specification tells whether to delete the transfer source files after they are transferred to the transfer destination.
The values and their meanings for FileRemove are given in the following table.

Set value TRUE FALSE

Meaning The transfer source files are deleted. The transfer source files are not deleted.

 OverWrite (Overwrite Specification)
The overwrite specification tells whether to overwrite files with the same name at the transfer destination when files are downloaded. If overwriting is not specified, files with the same name as those at the transfer destination are not transferred.
File names are not case sensitive.
The values and their meanings for OverWrite are given in the following table.

Set value TRUE FALSE

Meaning
The transfer destination files are overwritten.
The transfer destination files are not overwritten. The files are not transferred to the transfer destination.

Specifying Retrying Connection Processing with the FTP Server
You can specify retrying connection processing with the FTP server. The operation for the retry settings is the same as that for the FTPGetFileList instruction (page 2-1167). Refer to the specified page for details.
Canceling Instruction Execution
You can cancel execution of the FTPGetFile instruction after execution has started. The results of downloading files from the FTP server up to the point where it is canceled are stored in GetNum and GetFileResult[]. The operation for cancellation is the same as that for the FTPGetFileList instruction (page 2-1167). Refer to the specified page for details.

NJ/NX-series Instructions Reference Manual (W502)

2-1189

2 Instruction Descriptions

Related System-defined Variables

Name _EIP_EtnOnlineSta*1 _EIP1_EtnOnlineSta*2 _EIP2_EtnOnlineSta*3 _EIPIn1_EtnOnlineSta*4
_Card1Ready

Meaning Online
SD Memory Card Ready Flag

Data type
BOOL

Description
This variable indicates when built-in EtherNet/IP port communications can be used. TRUE: Communications are possible. FALSE: Communications are not possible.

BOOL

This variable indicates whether the SD Memory Card is recognized and usable. TRUE: Can be used. FALSE: Cannot be used.

*1 Use this variable name for an NJ-series CPU Unit. *2 Use this variable name for port 1 on an NX-series CPU Unit, or for an NY-series Controller. *3 Use this variable name for port 2 on an NX-series CPU Unit. *4 Use this variable name for the internal port on an NY-series Controller.

Precautions for Correct Use

· This instruction can be used only for the built-in EtherNet/IP ports on NJ/NX-series CPU Units and NY-series Controllers.
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section (page 2-3) for a timing chart for Execute, Done, Busy, and Error.
· If the number of downloaded file results to store exceeds the number of array elements in GetFileResult[], the results that will not fit are not stored. In this case, Error does not change to TRUE.
· If a file name exceeds 255 characters, the first 255 characters are stored in Name in GetFileResult[]. In this case, Error does not change to TRUE.
· You can execute a maximum of 3 of the following instructions at the same time: FTPGetFileList, FTPGetFile, FTPPutFile, FTPRemoveFile, and FTPRemoveDir.
· If a wildcard is used in the file name and an error occurs for more than one file, the results of the first file for which the value of GetFileResult[].TxError is TRUE of all the files for which results are stored in GetFileResult[] are stored in ErrorID and ErrorIDEx.
· File names are not case sensitive. Therefore, if the only difference between the names of the files at the transfer destination and the transfer files is in capitalization, the files are detected as having the same names. The following is performed in this case.

Value of OverWrite
TRUE FALSE

Overwrite specification

Processing

Overwrite The files are overwritten.

Do not over- The transfer destination files are not overwritten. The files are not

write.

transferred to the transfer destination.

· If the file specified by FileName does not exist in the specified directory on the FTP server, a transfer error occurs and the value of GetFileResult[].TxError changes to TRUE.
· If the name specified for FileName is actually the name of a directory, a transfer error occurs and the value of GetFileResult[].TxError changes to TRUE.
· If ExecOption.FileRemove is TRUE and the file specified with FileName has a read-only attribute, a deletion error occurs and GetFileResult[].RemoveError changes to TRUE.

2-1190

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

FTPGetFile

2 Instruction Descriptions

· An error will occur in the following cases. Error will change to TRUE.

· The value of any input parameter is outside of the valid range.

· ".." is specified for a directory level in SvrDirName or LocalDirName.

· An incorrect path such as "//" is specified for SvrDirName or LocalDirName.

· The directory specified by SvrDirName does not exist on the FTP server.

· More than 1,000 files to download exist in the FTP server directory specified with SvrDirName.

· The file directory specified with FileName does not exist in the download source directory on the FTP server.

· ExecOption.OverWrite is FALSE and a file with the same name as the specified file name FileName already exists in the specified directory SvrDirName.

· ExecOption.FileRemove is TRUE but a file with a name that matches FileName has a read-only attribute.

2

· The FTP server specified by ConnectSvr does not exist on the network or the specified FTP server is not operating.

· Accessing the file specified with FileName failed because there is no access right to the file or the file is corrupted.

· More than 3 of the following instructions were executed at the same time: FTPGetFileList, FTPGetFile, FTPPutFile, FTPRemoveFile, and FTPRemoveDir.

· The SD Memory Card is not in a usable condition.

· The SD Memory Card is write protected.

· There is insufficient space available on the SD Memory Card.

· The maximum number of files or directories was exceeded on the SD Memory Card.

· For this instruction, expansion error code ErrorIDEx gives the FTP response code that was returned by the FTP server. The following table lists typical values of ErrorIDEx and describes the meanings of the errors and the corrections. For details, refer to FTP server specifications. An expansion error code is output to ErrorIDEx when the value of error code ErrorID is WORD#16#2407.

Value of ErrorIDEx
16#000001A9
16#000001AA 16#000001C2
16#00000212 16#00000214 16#00000226
16#00000229

Meaning

Correction

It was not possible to establish a data connection.

If you use FTP communications with an FTP server over the Internet, make sure that the FTP open mode is not set to active.

The connection was closed. Data trans- Check the connection to the FTP server.

fer was aborted.

Make sure that the FTP server is operating.

It was not possible to perform the

Make sure that the file is not open for any

requested file operation. Using the file other application.

was not possible, e.g., it is already open.

User login was not possible.

Check the FTP user name and password.

An account to save files is required.

Check the FTP user access rights.

Execution of the requested file operation was not possible because using the file was not possible, e.g., accessing it was not possible because it was not found.

Make sure that a file with the specified name exists in the directory on the FTP server. Check the access rights of the specified file.

Execution was not possible because the Check the access rights of the specified

file name was not correct.

directory.

Version Information
A CPU Unit with unit version 1.08 or later and Sysmac Studio version 1.09 or higher are required to use this instruction.

NJ/NX-series Instructions Reference Manual (W502)

2-1191

2 Instruction Descriptions
Sample Programming
Refer to the sample programming for the FTPGetFileList instruction (page 2-1167).

2-1192

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

FTPPutFile

2 Instruction Descriptions

FTPPutFile

The FTPPutFile instruction uploads a file to the FTP server.

Instruction

Name

FB/FUN

Graphic expression

FTPPutFile

Put File onto FTP Server

FB

FTPPutFile_instance

FTPPutFile

Execute

Done

ConnectSvr

Busy

SvrDirName CommandCanceled

LocalDirName

Error

FileName

ErrorID

ExecOption

ErrorIDEx

RetryCfg

PutNum

Cancel

PutFileResult

ST expression

FTPPutFile_instance(

Execute,

ConnectSvr,

SvrDirName,

LocalDirName, FileName,

2

ExecOption,

RetryCfg,

Cancel,

PutFileResult,

Done,

Busy,

CommandCanceled,

Error,

ErrorID,

ErrorIDEx,

PutNum) ;

Variables

Name Connect Svr
SvrDir Name
LocalDir Name
FileName Exec Option RetryCfg
Cancel

Meaning

I/O

Connected FTP server settings

FTP server directory name

Local directory

name

Input

File name

FTP execution options
Execution retry settings

Cancel

Description

Valid range

Unit

Setting parameters for the connected FTP server

---

Name of FTP server directory to which to upload a file

256 bytes max. (255 single-byte alphanumeric characters plus the final NULL character)*2

Name of the directory in which to 256 bytes max.

store the file uploaded to the

(255 single-byte

FTP server

alphanumeric ---

characters plus

Name of file to upload*4

the final NULL character)

Options for FTP execution
Instruction execution retry settings
TRUE: Instruction execution is canceled. FALSE: Instruction execution is not canceled.

---
Depends on data type.

Default *1
''*3
'/' *1
--FALSE

NJ/NX-series Instructions Reference Manual (W502)

2-1193

2 Instruction Descriptions

Name
PutFile Result[] array*5*6*7

Meaning
Uploaded file results

I/O In-out

CommandC anceled
PutNum

Cancel completed
Number of files to upload

Output

Description
Uploaded file results
TRUE: Canceling completed. FALSE: Canceling not completed. Number of files to upload

Valid range

Unit

---

---

Depends on data type.
---
---

Default *1
---

*1 If you omit an input parameter, the default value is not applied. A building error will occur. *2 You cannot use the following characters in FTP server directory names: * ? < > | " *3 The default is the home directory when you log onto the FTP server. *4 You can use wildcards in file names. *5 The array can have a maximum of 1,000 elements. *6 This is a one-dimensional array. If an array with more than one dimension is specified, a building error will occur. *7 The first array element number is 0. If a number other than 0 is specified for the first array element, a building error will
occur.

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD BYTE

ConnectSvr

Refer to Function for details on the structure _sFTP_CONNECT_SVR.

SvrDirName

OK

LocalDirName

OK

FileName

OK

ExecOption

Refer to Function for details on the structure _sFTP_EXEC_OPTION.

RetryCfg

Refer to Function for details on the structure _sFTP_RETRY_CFG.

Cancel

OK

PutFileResult[] array

Refer to Function for details on the structure _sFTP_FILE_RESULT.

Command Canceled

OK

PutNum

OK

Function
The FTPPutFile instruction uploads the file specified with FileName in the specified directory LocalDirName in the SD Memory Card to the directory specified with SvrDirName on the connected FTP server ConnectSvr. If the specified directory SvrDirName does not exist on the FTP server, a new directory is created and the specified file is uploaded. You can use wildcards in FileName. This allows you to upload more than one file at one time.

The results of uploading is stored in PutFileResult[] for each file. Store the number of files to upload in PutNum. If you use a wildcard in FileName, store the number of files with names that match the wildcard.

If the actual number of transferred files is different, the value of PutFileResult[].TxError changes to TRUE.

2-1194

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

EtherNet/IP Communications Instructions

FTPPutFile

If an error occurs when deleting the source file after the upload, the value of PutFileResult[].RemoveError changes to TRUE.
With an NY-series Controller, files are downloaded into the shared folder (Virtual SD Memory Card). Before downloading files to the Virtual SD Memory Card, you must make the settings for the Virtual SD Memory Card. Refer to the NY-series Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for details on a Virtual SD Memory Card.

The data type of ConnectSvr is structure _sFTP_CONNECT_SVR. The specifications are as follows:

Name

Meaning

Description

Data type

Valid range Unit Default

ConnectSvr

Connected FTP server settings

Setting parameters for the connected FTP server

_sFTP_CONN ECT_SVR

---

--- ---

2

Adr

Address

IP address or host name*1

STRING

1 to 200 bytes*2

PortNo UserName

Port number User name

TCP port number of FTP server control connection
User name on FTP server

UINT STRING

0 to 65535*3
33 bytes max.*4*5*6

--- ---

Password

Password

FTP server password STRING

33 bytes max.*4*5*6

*1 A separate DNS or Hosts setting is required to specify a host name.
*2 You can use the following single-byte characters: A to Z, a to z, 0 to 9, - (hyphen), . (period), and _ (underbar).
*3 If you specify 0, TCP port number 21 is used.
*4 You can use the following single-byte characters: A to Z, a to z, 0 to 9, - (hyphen), . (period), and _ (underbar). You can also use \ and @ for a CPU Unit with unit version 1.16 or later.
*5 The NULL character at the end must be counted in the number of bytes.
*6 For CPU Units with unit version 1.08, specify a text string of one character or more. An error will occur if you specify a text string that contains only the final NULL character.

The data type of PutFileResult[] is structure _sFTP_FILE_RESULT. The specifications are as follows:

Name PutFileResult
Name
TxError RemoveError Reserved

Meaning Uploaded file results
File name*1
Transfer error
Deletion error Reserved

Description Transferred file results

Data type
_sFTP_FILE_ RESULT

Transferred file name STRING

TRUE: Transfer ended in an error. FALSE: Transfer ended normally.

BOOL

TRUE: Deletion ended in an error. FALSE: Deletion ended normally.

BOOL

Reserved by the system.

ARRAY[0..3] Of Byte

Valid range --256 bytes max. (255 single-byte alphanumeric characters plus the final NULL character)
Depends on data type.
---

Unit Default --- ---
-----
0

*1 The file name extension is included.

NJ/NX-series Instructions Reference Manual (W502)

2-1195

2 Instruction Descriptions

Using Wildcards to Specify File Names
You can use wildcards to specify the names of the files to upload. Wildcard specifications are the same as those for the FTPGetFile instruction (page 2-1184). Refer to the specified page for details.
Specifying Options for FTP Server Processing
You can specify FTP server processing options when you upload files. The option settings are the same as those for the FTPGetFile instruction (page 2-1184). Refer to the specified page for details.

Specifying Retrying Connection Processing with the FTP Server
You can specify retrying connection processing with the FTP server.
The operation for the retry settings is the same as that for the FTPGetFileList instruction (page 2-1167). Refer to the specified page for details.

Canceling Instruction Execution
You can cancel execution of the FTPPutFile instruction after execution has started.
The results of uploading files from the FTP server up to the point where it is canceled are stored in PutNum and PutFileResult[].
The operation for cancellation is the same as that for the FTPGetFileList instruction (page 2-1167). Refer to the specified page for details.

Related System-defined Variables

Name _EIP_EtnOnlineSta*1 _EIP1_EtnOnlineSta*2 _EIP2_EtnOnlineSta*3 _EIPIn1_EtnOnlineSta*4
_Card1Ready

Meaning Online
SD Memory Card Ready Flag

Data type
BOOL

Description
This variable indicates when built-in EtherNet/IP port communications can be used. TRUE: Communications are possible. FALSE: Communications are not possible.

BOOL

This variable indicates whether the SD Memory Card is recognized and usable. TRUE : Can be used. FALSE: Cannot be used.

*1 Use this variable name for an NJ-series CPU Unit. *2 Use this variable name for port 1 on an NX-series CPU Unit, or for an NY-series Controller. *3 Use this variable name for port 2 on an NX-series CPU Unit. *4 Use this variable name for the internal port on an NY-series Controller.

2-1196

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

FTPPutFile

2 Instruction Descriptions

Precautions for Correct Use

· This instruction can be used only for the built-in EtherNet/IP ports on NJ/NX-series CPU Units and NY-series Controllers.

· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.

· Refer to Using this Section (page 2-3) for a timing chart for Execute, Done, Busy, and Error.

· If the number of uploaded file results to store exceeds the number of array elements in PutFileResult[], the results that will not fit are not stored. In this case, Error does not change to TRUE.

· If a file name exceeds 255 characters, the first 255 characters are stored in Name in PutFileResult[].

In this case, Error does not change to TRUE.

2

· You can execute a maximum of 3 of the following instructions at the same time: FTPGetFileList, FTPGetFile, FTPPutFile, FTPRemoveFile, and FTPRemoveDir.

· If a wildcard is used in the file name and an error occurs for more than one file, the results of the first file for which the value of PutFileResult[].TxError is TRUE of all the files for which results are stored in PutFileResult[] are stored in ErrorID and ErrorIDEx.

· File names are not case sensitive. Therefore, if the only difference between the names of the files at the transfer destination and the transfer files is in capitalization, the files are detected as having the same names. The following is performed in this case.

·

Value of Over-

Overwrite

Write

specification

Processing

TRUE

Overwrite

If overwriting is not specified, the operation depends on the FTP server specifications.

FALSE

Do not over- The transfer destination files are not overwritten. The files are not trans-

write.

ferred to the transfer destination.

· If the file specified by FileName does not exist in the specified directory on the SD Memory Card, a transfer error occurs and the value of PutFileResult[].TxError changes to TRUE.
· If the name specified for FileName is actually the name of a directory, a transfer error occurs and the value of PutFileResult[].TxError changes to TRUE.
· If ExecOption.FileRemove is TRUE and the file specified with FileName has a read-only attribute, a deletion error occurs and the value of PutFileResult[].RemoveError changes to TRUE.

NJ/NX-series Instructions Reference Manual (W502)

2-1197

2 Instruction Descriptions

· An error will occur in the following cases. Error will change to TRUE.
· The value of any input parameter is outside of the valid range.
· ".." is specified for a directory level in SvrDirName or LocalDirName.
· An incorrect path such as "//" is specified for SvrDirName or LocalDirName.
· The directory specified by SvrDirName does not exist on the FTP server.
· The directory specified by LocalDirName does not exist on the FTP client.
· More than 1,000 files to upload exist in the directory specified with LocalDirName.
· The file directory specified with FileName does not exist in the upload source directory on the SD Memory Card.
· ExecOption.OverWrite is FALSE and a file with the same name as the specified file name FileName already exists in the specified directory SvrDirName.
· ExecOption.FileRemove is TRUE but a file with a name that matches FileName has a read-only attribute.
· The FTP server specified by ConnectSvr does not exist on the network or the specified FTP server is not operating.
· Accessing the file specified with FileName failed because there is no access right to the file or the file is corrupted.
· More than 3 of the following instructions were executed at the same time: FTPGetFileList, FTPGetFile, FTPPutFile, FTPRemoveFile, and FTPRemoveDir.
· The SD Memory Card is not in a usable condition.
· For this instruction, expansion error code ErrorIDEx gives the FTP response code that was returned by the FTP server. The following table lists typical values of ErrorIDEx and describes the meanings of the errors and the corrections. For details, refer to FTP server specifications. An expansion error code is output to ErrorIDEx when the value of error code ErrorID is WORD#16#2407.

Value of ErrorIDEx
16#000001A9
16#000001AA 16#000001C2
16#00000212 16#00000214 16#00000226
16#00000229

Meaning

Correction

It was not possible to establish a data connection.

If you use FTP communications with an FTP server over the Internet, make sure that the FTP open mode is not set to active.

The connection was closed. Data trans- Check the connection to the FTP server.

fer was aborted.

Make sure that the FTP server is operating.

It was not possible to perform the

Make sure that the file is not open for any

requested file operation. Using the file other application.

was not possible, e.g., it is already open.

User login was not possible.

Check the FTP user name and password.

An account to save files is required.

Check the FTP user access rights.

Execution of the requested file operation was not possible because using the file was not possible, e.g., accessing it was not possible because it was not found.

Make sure that a file with the specified name exists in the directory on the FTP server. Check the access rights of the specified file.

Execution was not possible because the Check the access rights of the specified

file name was not correct.

directory.

2-1198

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

FTPPutFile

2 Instruction Descriptions

Version Information
A CPU Unit with unit version 1.08 or later and Sysmac Studio version 1.09 or higher are required to use this instruction.

Sample Programming

This programming executes an SD Memory Card backup and then uploads all of the backup-related

files to the /Backup/yyyy-mm-dd directory on the FTP server.

2

FTP server

IP address: 192.168.250.2 TCP port number: 21 User name: FtpUser Password: 12345678

Ethernet

FTP client
The backup-related files are uploaded to the /Backup/yyyy-mm-dd directory on the FTP server.

Built-in EtherNet/IP port
The Controller is connected to the FTP server through an EtherNet/IP network. The settings of the parameters to connect to the FTP server are given in the following table.

Parameter IP address TCP port number User name Password

Value 192.168.250.2 21 FtpUser 12345678

The following procedure is used.
1 The BackupToMemoryCard instruction is used to save NJ/NX-series Controller backup-related files to the root directory on the SD Memory Card.
2 The FTPPutFile instruction is used to upload the backup-related files to the /Backup/yyyy-mmdd directory on the FTP server. The wildcard specification *.* is used to specify the names of the files to transfer.
3 Normal end processing is executed if all processing ends normally. Processing for an error end is performed if an error occurs.

NJ/NX-series Instructions Reference Manual (W502)

2-1199

2 Instruction Descriptions

LD

Internal Variables

Variable
FTPPutFile_instance FTPAddr
PutResult
RS_instance OperatingEnd Trigger Operating BackupToMemoryCard_instance

Data type
FTPPutFile
_sFTP_CONNECT_SVR ARRAY[0..0] OF _sFTP_FILE_RESULT RS BOOL BOOL BOOL BackupToMemoryCard

Initial value
(Adr := '', PortNo := 0, UserName := '', Password := '') [(Name := '', TxError := False, RemoveError := False, Reserved := [4(16#0)])]
FALSE FALSE FALSE

Comment
Instance of FTPPutFile instruction Connected FTP server settings
Uploaded file results
Instance of RS instruction Processing completed Execution condition Processing Instance of BackupToMemoryCard instruction

2-1200

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

FTPPutFile

2 Instruction Descriptions

Prepare connected FTP server settings.

P_First_RunMode

MOVE

MOVE

EN

ENO

EN

ENO

1

'192.168.250.2' In

Out FTPAddr.Adr UINT#21 In

Out FTPAddr.PortNo

MOVE

MOVE

1

EN

ENO

EN

ENO

'FTPUser' In

Out FTPAddr.UserName '12345678' In

Out FTPAddr.Password

Determine if instruction execution is completed.

BackupToMemoryCard_instance.Done FTPPutFile_instance.Done

OperatingEnd

2

BackupToMemoryCard_instance.Error

FTPPutFile_instance.Error

Accept trigger. Trigger BackupToMemoryCard_instance.Busy FTPPutFile_instance.Busy
OperatingEnd

RS_instance

RS

Set

Q1

Reset1

Operating

Execute BackupToMemoryCard and FTPPutFile instructions.

Operating

BackupToMemoryCard_instance BackupToMemoryCard

Execute DirName Cancel Option

Done Busy Error Canceled ErrorID

BackupToMemoryCard_instance.Done

FTPAddr '/Backup/yyyy-mm-dd'
'/' '*.*'

PutResult

FTPPutFile_instance

FTPPutFile

Execute

Done

ConnectSvr

Busy

SvrDirName CommandCanceled

LocalDirName

Error

FileName

ErrorID

ExecOption

ErrorIDEx

RetryCfg

PutNum

Cancel

PutFileResult

PutResult

Processing after normal end Operating BackupToMemoryCard_instance.Done FTPPutFile_instance.Done

Inline ST
1 // Processing after normal end 2 ;

Processing after error end Operating BackupToMemoryCard_instance.Error
FTPPutFile_instance.Error

Inline ST
1 // Processing after error end 2 ;

NJ/NX-series Instructions Reference Manual (W502)

2-1201

2 Instruction Descriptions

ST

Internal Variables

Variable

Data type

Initial value

R_TRIG_instance R_TRIG

UP_Q
FTPPutFile_instance

BOOL FTPPutFile

FALSE

DoFTPTrigger

BOOL

FALSE

FTPAddr PutResult

_sFTP_CONNECT_SVR
ARRAY[0..0] OF _sFTP_FILE_RESULT

(Adr := '', PortNo := 0, UserName := '', Password := '')
[(Name := '', TxError := False, RemoveError := False, Reserved := [4(16#0)])]

Stage

UINT

0

Trigger
BackupToMemoryCard_instance

BOOL
BackupToMemoryCard

FALSE

Comment
Instance of R_TRIG instruction Trigger output Instance of FTPPutFile instruction Execution condition for BackupToMemoryCard and FTPPutFile Connected FTP server settings
Uploaded file results
Instruction execution stage Execution condition Instance of BackupToMemoryCard instruction

2-1202

// Prepare connected FTP server settings.

IF P_First_RunMode THEN

FTPAddr.Adr

:= '192.168.250.2';// Address

FTPAddr.PortNo := UINT#21;

// Port number

FTPAddr.UserName := 'FtpUser';

// User name

FTPAddr.Password := '12345678';

// Password

END_IF;

// Accept trigger.

R_TRIG_instance(Trigger, UP_Q);

IF ( (UP_Q = TRUE) AND (BackupToMemoryCard_instance.Busy = FALSE) AND

(FTPPutFile_instance.Busy = FALSE) ) THEN

DoFTPTrigger := TRUE;

Stage := INT#1;

BackupToMemoryCard_instance( // Initialize instance.

Execute := FALSE) ;

FTPPutFile_instance( // Initialize instance.

Execute

:= FALSE,

ConnectSvr := FTPAddr,

SvrDirName := '/Backup/yyyy-mm-dd',

LocalDirName := '/',

FileName

:= '*.*',

PutFileResult := PutResult) ;

END_IF;

IF (DoFTPTrigger = TRUE) THEN CASE Stage OF 1: // Execute BackupToMemoryCard instruction. BackupToMemoryCard_instance( Execute := TRUE, // Execution IF (BackupToMemoryCard_instance.Done = TRUE) THEN Stage := INT#2; // To next stage ELSIF (BackupToMemoryCard_instance.Error = TRUE) THEN Stage := INT#10; // Error end END_IF; 2: // Execute FTPPutFile instruction.

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

2 Instruction Descriptions

FTPPutFile_instance(

Execute

:= TRUE,

// Execution

ConnectSvr := FTPAddr,

// Connected FTP server

SvrDirName := '/Backup/yyyy-mm-dd',// FTP server directory name

LocalDirName := '/',

// Local directory name

FileName

:= '*.*',

// File name

PutFileResult := PutResult) ;

// Uploaded file results

IF (FTPPutFile_instance.Done = TRUE) THEN

Stage := INT#0; // Normal end

ELSIF (FTPPutFile_instance.Error = TRUE) THEN

Stage := INT#20; // Error end

END_IF;

0: // Processing after normal end

DoFTPTrigger:=FALSE;

Trigger

:=FALSE;

2

ELSE // Processing after error end

DoFTPTrigger:=FALSE;

Trigger

:=FALSE;

END_CASE;

END_IF;

FTPPutFile

NJ/NX-series Instructions Reference Manual (W502)

2-1203

2 Instruction Descriptions

FTPRemoveFile

The FTPRemoveFile instruction deletes a file from the FTP server.

Instruction

Name

FB/FUN

Graphic expression

FTPRemove File

Delete FTP Server File

FB

FTPRemoveFile_instance

FTPRemoveFile

Execute

Done

ConnectSvr

Busy

SvrDirName CommandCanceled

FileName

Error

ExecOption

ErrorID

RetryCfg

ErrorIDEx

Cancel

RemoveNum

RemoveFileResult

ST expression
FTPRemoveFile_instance( Execute, ConnectSvr, SvrDirName, FileName, ExecOption, RetryCfg, Cancel, RemoveFileResult, Done, Busy, CommandCanceled, Error, ErrorID, ErrorIDEx, RemoveNum) ;

Variables

Name Connect Svr
SvrDir Name
FileName
Exec Option RetryCfg
Cancel

Meaning

I/O

Connected FTP server settings

FTP server directory name

File name

Input

FTP execution options Execution retry settings
Cancel

Description

Valid range

Unit

Setting parameters for the connected FTP server

---

Name of FTP server directory containing the file to delete
Name of file to delete*4

256 bytes max. (255 single-byte alphanumeric characters plus the final NULL character)*2
256 bytes max. (255 single-byte alphanumeric --characters plus the final NULL character)*5

Options for FTP execution
Instruction execution retry settings
TRUE: Instruction execution is canceled. FALSE: Instruction execution is not canceled.

---
Depends on data type.

Default *1 ''*3 *1
---

2-1204

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

2 Instruction Descriptions

Name
Remove FileResult []array*6*7*8

Meaning
Deleted file results

I/O In-out

Command Canceled
Remove Num

Cancel completed
Number of files to delete

Output

Description
Deleted file results
TRUE: Canceling completed. FALSE: Canceling not completed. Number of files to delete

Valid range

Unit

---

---

Depends on data type.
---
---

Default *1
---

*1 If you omit an input parameter, the default value is not applied. A building error will occur.

*2 You cannot use the following characters in FTP server directory names: * ? < > | "

*3 The default is the home directory when you log onto the FTP server.

2

*4 You can use wildcards in file names.

*5 You cannot use the following character in file names: |

*6 The array can have a maximum of 1,000 elements.

*7 This is a one-dimensional array. If an array with more than one dimension is specified, a building error will occur.

*8 The first array element number is 0. If a number other than 0 is specified for the first array element, a building error will occur.

Bit strings

Integers

Real

Times, durations, dates, and text strings

FTPRemoveFile

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT DINT INT SINT ULINT UDINT

UINT

USINT

LWORD

DWORD

WORD BYTE

ConnectSvr

Refer to Function for details on the structure _sFTP_CONNECT_SVR.

SvrDirName

OK

FileName

OK

ExecOption

Refer to Function for details on the structure _sFTP_EXEC_OPTION.

RetryCfg

Refer to Function for details on the structure _sFTP_RETRY_CFG.

Cancel

OK

Remove FileResult[] array

Refer to Function for details on the structure _sFTP_FILE_RESULT.

Command Canceled

OK

RemoveNum

OK

Function
The FTPRemoveFile instruction deletes the file specified by FileName in the specified directory SvrDirName on the connected FTP server ConnectSvr. You can use wildcards in FileName. This allows you to delete more than one file at one time.

The results of deleting files is stored by file in RemoveFileResult[]. Store the number of files to delete in RemoveNum. If you use a wildcard in FileName, store the number of files with names that match the wildcard.

If the actual number of deleted files is different, the value of RemoveFileResult[].RemoveError changes to TRUE.

NJ/NX-series Instructions Reference Manual (W502)

2-1205

2 Instruction Descriptions

The data type of ConnectSvr is structure _sFTP_CONNECT_SVR. The specifications are as follows:

Name ConnectSvr
Adr PortNo UserName Password

Meaning Connected FTP server settings Address
Port number
User name
Password

Description
Setting parameters for the connected FTP server
IP address or host name*1
TCP port number of FTP server control connection
User name on FTP server
FTP server password

Data type _sFTP_CONN ECT_SVR STRING
UINT
STRING STRING

Valid range Unit

---

---

1 to 200 bytes*2

0 to 65535*3 ---
33 bytes max.*4*5*6
33 bytes max.*4*5*6

Default ---
---

*1 A separate DNS or Hosts setting is required to specify a host name.
*2 You can use the following single-byte characters: A to Z, a to z, 0 to 9, - (hyphen), . (period), and _ (underbar).
*3 If you specify 0, TCP port number 21 is used.
*4 You can use the following single-byte characters: A to Z, a to z, 0 to 9, - (hyphen), . (period), and _ (underbar). You can also use \ and @ for a CPU Unit with unit version 1.16 or later.
*5 The NULL character at the end must be counted in the number of bytes.
*6 For CPU Units with unit version 1.08, specify a text string of one character or more. An error will occur if you specify a text string that contains only the final NULL character.

The data type of RemoveFileResult[] is structure _sFTP_FILE_RESULT. The specifications are as follows:

Name RemoveFile Result
Name
TxError
RemoveError Reserved

Meaning Deleted file results
File name*1
Transfer error
Deletion error Reserved

Description Transferred file results

Data type
_sFTP_FILE_ RESULT

Transferred file name STRING

TRUE: Transfer ended in an error. FALSE: Transfer ended normally.

BOOL

TRUE: Deletion ended in an error. FALSE: Deletion ended normally.

BOOL

Reserved by the system.

ARRAY[0..3] Of Byte

Valid range Unit Default

---

--- ---

256 bytes max. (255 single-byte alphanumeric characters plus the final NULL character)

Depends on data type.

-----

---

0

*1 The file name extension is included.

Using Wildcards to Specify File Names
You can use wildcards to specify the names of the files to delete.
Wildcard specifications are the same as those for the FTPGetFile instruction (page 2-1184). Refer to the specified page for details.

2-1206

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

EtherNet/IP Communications Instructions

FTPRemoveFile

Specifying Options for FTP Server Processing
The operation specified with ExecOption is performed to delete the files from the FTP server. The option settings are the same as those for the FTPGetFile instruction (page 2-1184). Refer to the specified page for details. However, the only option that is valid for this instruction is ExecOption.PassiveMode.

Specifying Retrying Connection Processing with the FTP Server
You can specify retrying connection processing with the FTP server.
The operation for the retry settings is the same as that for the FTPGetFileList instruction (page 2-1167). 2
Refer to the specified page for details.

Canceling Instruction Execution
You can cancel execution of the FTPRemoveFile instruction after execution has started.
The results of deleting files from the FTP server up to the point where it is canceled are stored in RemoveNum and RemoveFileResult[].
The operation for cancellation is the same as that for the FTPGetFileList instruction (page 2-1167). Refer to the specified page for details.

Related System-defined Variables

Name
_EIP_EtnOnlineSta*1 _EIP1_EtnOnlineSta*2 _EIP2_EtnOnlineSta*3 _EIPIn1_EtnOnlineSta*4

Meaning Online

Data type
BOOL

Description
This variable indicates when built-in EtherNet/IP port communications can be used. TRUE: Communications are possible. FALSE: Communications are not possible.

*1 Use this variable name for an NJ-series CPU Unit. *2 Use this variable name for port 1 on an NX-series CPU Unit, or for an NY-series Controller. *3 Use this variable name for port 2 on an NX-series CPU Unit. *4 Use this variable name for the internal port on an NY-series Controller.

Precautions for Correct Use
· This instruction can be used only for the built-in EtherNet/IP ports on the NJ/NX-series CPU Units and the NY-series Controllers.
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section (page 2-3) for a timing chart for Execute, Done, Busy, and Error.
· If the number of deleted files exceeds the number of array elements in RemoveFileResult[], the results that will not fit are not stored. In this case, Error does not change to TRUE.
· If a file name exceeds 255 characters, the first 255 characters are stored in Name in RemoveFileResult[]. In this case, Error does not change to TRUE.
· You can execute a maximum of 3 of the following instructions at the same time: FTPGetFileList, FTPGetFile, FTPPutFile, FTPRemoveFile, and FTPRemoveDir.

NJ/NX-series Instructions Reference Manual (W502)

2-1207

2 Instruction Descriptions

· If a wildcard is used in the file name and an error occurs for more than one file, the results of the first file for which the value of RemoveFileResult[].TxError is TRUE of all the files for which results are stored in RemoveFileResult[] are stored in ErrorID and ErrorIDEx.
· In the following cases, the value of RemoveFileResult[].RemoveError changes to TRUE.
· The file directory specified with FileName does not exist on the FTP server.
· A file specified with FileName has a read-only attribute.
· The name specified for FileName is actually the name of a directory.
· An error will occur in the following cases. Error will change to TRUE.
· The value of any input parameter is outside of the valid range.
· ".." is specified for a directory level in SvrDirName.
· An incorrect path such as "//" is specified for SvrDirName.
· The directory specified by SvrDirName does not exist on the FTP server.
· More than 1,000 files to delete exist in the directory specified with SvrDirName.
· A file that matches the file name specified with a wildcard in FileName does not exist in the directory on the FTP server.
· A file specified with FileName has a read-only attribute.
· The FTP server specified by ConnectSvr does not exist on the network or the specified FTP server is not operating.
· More than 3 of the following instructions were executed at the same time: FTPGetFileList, FTPGetFile, FTPPutFile, FTPRemoveFile, and FTPRemoveDir.
· For this instruction, expansion error code ErrorIDEx gives the FTP response code that was returned by the FTP server. The following table lists typical values of ErrorIDEx and describes the meanings of the errors and the corrections. For details, refer to FTP server specifications. An expansion error code is output to ErrorIDEx when the value of error code ErrorID is WORD#16#2407.

Value of ErrorIDEx
16#000001A9
16#000001AA 16#000001C2
16#00000212 16#00000214 16#00000226
16#00000229

Meaning

Correction

It was not possible to establish a data connection.

If you use FTP communications with an FTP server over the Internet, make sure that the FTP open mode is not set to active.

The connection was closed. Data trans- Check the connection to the FTP server.

fer was aborted.

Make sure that the FTP server is operating.

It was not possible to perform the

Make sure that the file is not open for any

requested file operation. Using the file other application.

was not possible, e.g., it is already open.

User login was not possible.

Check the FTP user name and password.

An account to save files is required.

Check the FTP user access rights.

Execution of the requested file operation was not possible because using the file was not possible, e.g., accessing it was not possible because it was not found.

Make sure that a file with the specified name exists in the directory on the FTP server. Check the access rights of the specified file.

Execution was not possible because the Check the access rights of the specified

file name was not correct.

directory.

Version Information
A CPU Unit with unit version 1.08 or later and Sysmac Studio version 1.09 or higher are required to use this instruction.

2-1208

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

FTPRemoveFile

2 Instruction Descriptions

Sample Programming
This programming deletes all of the files in the /Backup/yyyy-mm-dd directory on the FTP server. It then deletes the /Backup/yyyy-mm-dd directory too.

FTP server Files and directory
are deleted.

IP address: 192.168.250.2 TCP port number: 21

User name: FtpUser

Password: 12345678

Ethernet

2

All files in the /Backup/yyyy-mm-dd directory on the FTP server are deleted. The /Backup/yyyy-mm-dd directory is also deleted.

FTP client

Built-in EtherNet/IP port
The Controller is connected to the FTP server through an EtherNet/IP network. The settings of the parameters to connect to the FTP server are given in the following table.

Parameter IP address TCP port number User name Password

Value 192.168.250.2 21 FtpUser 12345678

The following procedure is used.
1 The FTPRemoveFile instruction is used to delete all of the files in the /Backup/yyyy-mm-dd directory on the FTP server. The wildcard specification *.* is used to specify the names of the files to delete.
2 The FTPRemoveDir instruction is used to delete the /Backup/yyyy-mm-dd directory from the FTP server.
3 Normal end processing is executed if all processing ends normally. Processing for an error end is performed if an error occurs.

NJ/NX-series Instructions Reference Manual (W502)

2-1209

2 Instruction Descriptions

LD

Internal Variables

Variable
FTPRemoveFile_instance FTPRemoveDir_instance

FTPAddr

RemoveResult
RS_instance OperatingEnd Trigger Operating

Data type

Initial value

Comment

FTPRemoveFile
FTPRemoveDir
_sFTP_CONNECT_SVR ARRAY[0..0] OF _sFTP_FILE_RESULT RS BOOL BOOL BOOL

(Adr := '', PortNo := 0, UserName := '', Password := '') [(Name := '', TxError := False, RemoveError := False, Reserved := [4(16#0)])]
FALSE FALSE FALSE

Instance of FTPRemoveFile instruction Instance of FTPRemoveDir instruction Connected FTP server settings
Deleted file results
Instance of RS instruction Processing completed Execution condition Processing

2-1210

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

EtherNet/IP Communications Instructions

FTPRemoveFile

Prepare connected FTP server settings.

P_First_RunMode

MOVE

MOVE

EN

ENO

EN

ENO

1

'192.168.250.2' In

Out FTPAddr.Adr UINT#21 In

Out FTPAddr.PortNo

MOVE

MOVE

1

EN

ENO

EN

ENO

'FTPUser' In

Out FTPAddr.UserName '12345678' In

Out FTPAddr.Password

Determine if instruction execution is completed.

FTPRemoveFile_instance.Done

FTPRemoveDir_instance.Done

OperatingEnd

2

FTPRemoveFile_instance.Error

FTPRemoveDir_instance.Error

Accept trigger. Trigger FTPRemoveFile_instance.Busy

FTPRemoveDir_instance.Busy OperatingEnd

RS_instance

RS

Set

Q1

Reset1

Execute FTPRemoveFile and FTPRemoveDir instructions.

FTPRemoveFile_instance

Operating

FTPRemoveFile

Execute

Done

FTPAddr ConnectSvr

Busy

'/Backup/yyyy-mm-dd' '*.*'

SvrDirName CommandCanceled

FileName

Error

ExecOption

ErrorID

RetryCfg

ErrorIDEx

Cancel

RemoveNum

RemoveFileResult RemoveResult

RemoveResult

Operating

FTPRemoveFile_instance.Done
Processing after normal end Operating FTPRemoveFile_instance.Done

FTPAddr '/Backup' 'yyyy-mm-dd'

FTPRemoveDir_instance

FTPRemoveDir

Execute

Done

ConnectSvr

Busy

SvrDirName

CommandCanceled

RemoveDirName

Error

RetryCfg

ErrorID

Cancel

ErrorIDEx

FTPRemoveDir_instance.Done

Inline ST
1 // Processing after normal end 2 ;

Processing after error end

Operating

FTPRemoveFile_instance.Error

FTPRemoveDir_instance.Error

Inline ST
1 // Processing after error end 2 ;

NJ/NX-series Instructions Reference Manual (W502)

2-1211

2 Instruction Descriptions

ST

Internal Variables

Variable

Data type

R_TRIG_instance R_TRIG

UP_Q
FTPRemoveFile_instance
FTPRemoveDir_instance

BOOL FTPRemoveFile FTPRemoveDir

DoFTPTrigger

BOOL

FTPAddr RemoveResult Stage Trigger

_sFTP_CONNECT_SVR ARRAY[0..0] OF _sFTP_FILE_RESULT
UINT
BOOL

Initial value
FALSE
FALSE (Adr := '', PortNo := 0, UserName := '', Password := '') [(Name := '', TxError := False, RemoveError := False, Reserved := [4(16#0)])] 0 FALSE

Comment
Instance of R_TRIG instruction Trigger output Instance of FTPRemoveFile instruction Instance of FTPRemoveDir instruction Execution condition for FTPRemoveFile and FTPRemoveDir Connected FTP server settings
Deleted file results
Instruction execution stage Execution condition

2-1212

// Prepare connected FTP server settings.

IF P_First_RunMode THEN

FTPAddr.Adr

:= '192.168.250.2';// Address

FTPAddr.PortNo := UINT#21;

// Port number

FTPAddr.UserName := 'FtpUser';

// User name

FTPAddr.Password := '12345678';

// Password

END_IF;

// Accept trigger.

R_TRIG_instance(Trigger, UP_Q);

IF ( (UP_Q = TRUE) AND (FTPRemoveFile_instance.Busy = FALSE) AND

(FTPRemoveDir_instance.Busy = FALSE) ) THEN

DoFTPTrigger := TRUE;

Stage := INT#1;

FTPRemoveFile_instance( // Initialize instance.

Execute

:= FALSE,

ConnectSvr

:= FTPAddr,

SvrDirName

:= '/Backup/yyyy-mm-dd',

FileName

:= '*.*',

RemoveFileResult := RemoveResult) ;

FTPRemoveDir_instance( // Initialize instance.

Execute

:= FALSE,

ConnectSvr := FTPAddr,

SvrDirName := '/Backup',

RemoveDirName := 'yyyy-mm-dd') ;

END_IF;

IF (DoFTPTrigger = TRUE) THEN

CASE Stage OF

1 : // Execute FTPRemoveFile instruction.

FTPRemoveFile_instance(

Execute

:= TRUE,

// Execution

ConnectSvr

:= FTPAddr,

// Connected FTP server

SvrDirName

:= '/Backup/yyyy-mm-dd', //FTP server directory name

FileName

:= '*.*',

// File name

RemoveFileResult := RemoveResult) ;

// Deleted file results

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

2 Instruction Descriptions

IF (FTPRemoveFile_instance.Done = TRUE) THEN

Stage := INT#2; // To next stage

ELSIF (FTPRemoveFile_instance.Error = TRUE) THEN

Stage := INT#10; // Error end

END_IF;

2 : // Execute FTPRemoveDir instruction.

FTPRemoveDir_instance(

Execute

:= TRUE,

// Execution

ConnectSvr := FTPAddr,

// Connected FTP server

SvrDirName := '/Backup',

// FTP server directory name

RemoveDirName := 'yyyy-mm-dd') ;// Directory to delete

IF (FTPRemoveDir_instance.Done = TRUE) THEN

Stage:=INT#0; // Normal end

ELSIF (FTPRemoveDir_instance.Error = TRUE) THEN Stage:=INT#20; // Error end

2

END_IF;

0 : // Processing after normal end

DoFTPTrigger:=FALSE;

Trigger

:=FALSE;

ELSE // Processing after error end

DoFTPTrigger:=FALSE;

Trigger

:=FALSE;

END_CASE;

END_IF;

FTPRemoveFile

NJ/NX-series Instructions Reference Manual (W502)

2-1213

2 Instruction Descriptions

FTPRemoveDir

The FTPRemoveDir instruction deletes a directory from the FTP server.

Instruction

Name FB/FUN

FTPRemove Dir

Delete FTP

Server

FB

Directory

Graphic expression

FTPRemoveDir_instance

FTPRemoveDir

Execute

Done

ConnectSvr

Busy

SvrDirName

CommandCanceled

RemoveDirName

Error

RetryCfg

ErrorID

Cancel

ErrorIDEx

ST expression
FTPRemoveDir_instance( Execute, ConnectSvr, SvrDirName, RemoveDirName, Cancel, RetryCfg, Done, Busy, CommandCanceled, Error, ErrorID, ErrorIDEx ) ;

Variables

Name

Meaning

I/O

Description

Valid range

Unit

Connect Svr

Connected FTP server settings

Setting parameters for the connected FTP server

---

SvrDir Name

FTP server directory name

Name of FTP server directory containing the directory to delete

256 bytes max. (255 single-byte alphanumeric characters plus the final NULL character)*2

RemoveDir- Directory to

Name

delete

Input

Directory to delete

256 bytes max. (255 single-byte --alphanumeric characters plus
the final NULL character)

RetryCfg

Execution retry settings

Instruction execution retry settings

---

Cancel

Cancel

TRUE: Instruction execution is canceled. FALSE: Instruction execution is not canceled.

Depends on data type.

Command- Cancel comCanceled pleted

Output

TRUE: Canceling completed. FALSE: Canceling not completed.

---

---

*1 If you omit an input parameter, the default value is not applied. A building error will occur. *2 You cannot use the following characters in FTP server directory names: * ? < > | " *3 The default is the home directory when you log onto the FTP server.

Default *1 ''*3
*1 --FALSE ---

2-1214

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions
STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

FTPRemoveDir

2 Instruction Descriptions

Bit strings

Integers

Times, durations, dates, and text strings

ConnectSvr

SvrDirName

RemoveDir Name

RetryCfg

Cancel

OK

Command Canceled

OK

Refer to Function for details on the structure _sFTP_CONNECT_SVR. Refer to Function for details on the structure _sFTP_RETRY_CFG.

OK
OK
2

Function
The FTPRemoveDir instruction deletes the specified directory RemoveDirName from the directory containing the directory to delete SvrDirName on the connected FTP server ConnectSvr.

When the value of Done in the instruction changes to TRUE, deletion of the specified directory is already completed. If the instruction fails to delete the directory, the value of Error changes to TRUE.

The data type of ConnectSvr is structure _sFTP_CONNECT_SVR. The specifications are as follows:

Name ConnectSvr
Adr PortNo UserName Password

Meaning Connected FTP server settings Address
Port number
User name
Password

Description
Setting parameters for the connected FTP server
IP address or host name*1
TCP port number of FTP server control connection
User name on FTP server
FTP server password

Data type _sFTP_CONN ECT_SVR STRING
UINT
STRING STRING

Valid range Unit

---

---

1 to 200 bytes*2

0 to 65535*3 ---
33 bytes max.*4*5*6
33 bytes max.*4*5*6

Default ---
---

*1 A separate DNS or Hosts setting is required to specify a host name.
*2 You can use the following single-byte characters: A to Z, a to z, 0 to 9, - (hyphen), . (period), and _ (underbar).
*3 If you specify 0, TCP port number 21 is used.
*4 You can use the following single-byte characters: A to Z, a to z, 0 to 9, - (hyphen), . (period), and _ (underbar). You can also use \ and @ for a CPU Unit with unit version 1.16 or later.
*5 The NULL character at the end must be counted in the number of bytes.
*6 For CPU Units with unit version 1.08, specify a text string of one character or more. An error will occur if you specify a text string that contains only the final NULL character.

NJ/NX-series Instructions Reference Manual (W502)

2-1215

2 Instruction Descriptions

Specifying Retrying Connection Processing with the FTP Server
You can specify retrying connection processing with the FTP server. The operation for retrying is the same as that for the FTPGetFileList instruction (page 2-1167). Refer to the specified page for details.

Canceling Instruction Execution
You can cancel execution of the FTPRemoveDir instruction after execution has started.
The operation for cancellation is the same as that for the FTPGetFileList instruction (page 2-1167). Refer to the specified page for details.

Related System-defined Variables

Name
_EIP_EtnOnlineSta*1 _EIP1_EtnOnlineSta*2 _EIP2_EtnOnlineSta*3 _EIPIn1_EtnOnlineSta*4

Meaning Online

Data type
BOOL

Description
This variable indicates when built-in EtherNet/IP port communications can be used. TRUE: Communications are possible. FALSE: Communications are not possible.

*1 Use this variable name for an NJ-series CPU Unit. *2 Use this variable name for port 1 on an NX-series CPU Unit, or for an NY-series Controller. *3 Use this variable name for port 2 on an NX-series CPU Unit. *4 Use this variable name for the internal port on an NY-series Controller.

Precautions for Correct Use
· This instruction can be used only for the built-in EtherNet/IP ports on the NJ/NX-series CPU Units and the NY-series Controllers.
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section (page 2-3) for a timing chart for Execute, Done, Busy, and Error.
· Even if you use Cancel to cancel the execution of this instruction, sometimes the directory on the FTP server is deleted depending on the timing of when Cancel changes to TRUE. Check the directory on the FTP server.
· You can execute a maximum of 3 of the following instructions at the same time: FTPGetFileList, FTPGetFile, FTPPutFile, FTPRemoveFile, and FTPRemoveDir.
· An error will occur in the following cases. Error will change to TRUE.
· The value of any input parameter is outside of the valid range.
· The directory specified by SvrDirName does not exist on the FTP server.
· ".." is specified for a directory level in SvrDirName or RemoveDirName.
· An incorrect path such as "//" is specified for SvrDirName or RemoveDirName.
· The directory specified by RemoveDirName does not exist on the FTP server.
· There are no files or subdirectories in the directory specified with RemoveDirName.
· The directory specified with RemoveDirName has a read-only attribute.
· The FTP server specified by ConnectSvr does not exist on the network or the specified FTP server is not operating.

2-1216

NJ/NX-series Instructions Reference Manual (W502)

EtherNet/IP Communications Instructions

FTPRemoveDir

2 Instruction Descriptions

· More than 3 of the following instructions were executed at the same time: FTPGetFileList, FTPGetFile, FTPPutFile, FTPRemoveFile, and FTPRemoveDir.
· For this instruction, expansion error code ErrorIDEx gives the FTP response code that was returned by the FTP server. The following table lists typical values of ErrorIDEx and describes the meanings of the errors and the corrections. For details, refer to FTP server specifications. An expansion error code is output to ErrorIDEx when the value of error code ErrorID is WORD#16#2407.

Value of ErrorIDEx

Meaning

Correction

16#000001A9 16#000001AA

It was not possible to establish a data If you use FTP communications with an FTP

connection.

server over the Internet, make sure that the

FTP open mode is not set to active.

The connection was closed. Data trans- Check the connection to the FTP server.

2

fer was aborted.

Make sure that the FTP server is operating.

16#000001C2

It was not possible to perform the

Make sure that the file is not open for any

requested file operation. Using the file other application.

was not possible, e.g., it is already open.

16#00000212

User login was not possible.

Check the FTP user name and password.

16#00000214

An account to save files is required.

Check the FTP user access rights.

16#00000226

Execution of the requested file operation was not possible because using the file was not possible, e.g., accessing it was not possible because it was not found.

Make sure that a file with the specified name exists in the directory on the FTP server. Check the access rights of the specified file.

16#00000229

Execution was not possible because the Check the access rights of the specified

file name was not correct.

directory.

Version Information A CPU Unit with unit version 1.08 or later and Sysmac Studio version 1.09 or higher are required to use this instruction.
Sample Programming
Refer to the sample programming for the FTPRemoveFile instruction (page 2-1204).

NJ/NX-series Instructions Reference Manual (W502)

2-1217

2 Instruction Descriptions

2-1218

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

2
Serial Communications Instructions

Instruction ExecPMCR SerialSend SerialRcv and SerialRcvNoClear
SendCmd NX_SerialSend NX_SerialRcv NX_ModbusRtuCmd
NX_ModbusRtuRead
NX_ModbusRtuWrite
NX_SerialSigCtl
NX_SerialSigRead NX_SerialStatusRead NX_SerialBufClear NX_SerialStartMon NX_SerialStopMon

Name Protocol Macro SCU Send Serial SCU Receive Serial and SCU Receive Serial without Receive Buffer Clear Send Command Send No-protocol Data Receive No-protocol Data Send Modbus RTU General Command Send Modbus RTU Read Command Send Modbus RTU Write Command Serial Control Signal ON/OFF Switching Read Serial Control Signal Read Serial Port Status Clear Buffer Start Serial Line Monitoring Stop Serial Line Monitoring

Page 2-1220 2-1233 2-1244
2-1259 2-1272 2-1285 2-1299
2-1310
2-1322
2-1334
2-1343 2-1348 2-1353 2-1363 2-1368

NJ/NX-series Instructions Reference Manual (W502)

2-1219

2 Instruction Descriptions

ExecPMCR

The ExecPMCR instruction requests execution of a communications sequence (protocol data) registered in a Serial Communications Unit.

Instruction ExecPMCR

Name

FB/ FUN

Protocol Macro FB

Graphic expression

ExecPMCR_instance

ExecPMCR

Execute Port SeqNo SrcDat DstDat

Done Busy Error ErrorID

ErrorIDEx

ST expression
ExecPMCR_instance(Execute, Port, SeqNo, SrcDat, DstDat, Done, Busy, Error, ErrorID, ErrorIDEx);

Precautions for Correct Use You cannot use this instruction in an NX-series CPU Unit.

Variables

Name Port
SeqNo
SrcDat[] (array) DstDat[] (array)

Meaning
Destination port
Communic ations sequence number
Send data array
Receive data array

I/O Input In-out

Description Destination port

Valid range
---

Communications sequence 0 to 999 number

Unit
---

Send data array Receive data array

Depends on data type. Depends on data type. ---

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default
---
0
* ---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

Port
SeqNo
SrcDat[] (array)
DstDat[] (array)

Refer to Function for details on the structure _sPORT. OK
OK
OK

2-1220

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Serial Communications Instructions

ExecPMCR

Function

The ExecPMCR instruction requests execution of the sequence that is specified with communications sequence number SeqNo from the specified destination port Port.
If data is sent, it is sent from the second element (SrcDat[1]) of send data array SrcDat[]. The number of array elements to send is specified in SrcDat[0].

If data is received successfully, the receive data is stored from the second element (DstDat[1]) of receive data array DstDat[]. The number of receive data elements is stored in DstDat[0].

If data is not received successfully, the contents of DstDat[] from before instruction execution is retained

for the number of elements specified in DstDat[0].

The data type of destination port Port is the structure _sPORT. The specifications are as follows:

2

Name Port
UnitNo

Meaning
Destination port
Unit number

PhysicPortNo Serial port number

Description Destination port

Data type _sPORT

Unit number of Serial Communications Unit
Serial port number on Serial Communications Unit

_eUnitNo USINT

Valid range
---

Unit Default
--- ---

_CBU_No00 to _CBU_No15

1 or 2

---

_CBU_ No00
1

The following figure shows a timing chart. Communications is performed to the end after the value of Done changes to TRUE.
The receive buffer is checked every task period. If data is received, it is stored in DstDat[].

Execute Busy Done Error

TRUE FALSE
TRUE FALSE
TRUE FALSE
TRUE FALSE

DstDat[]

SrcDat[]

Protocol Macro Execution TRUE

Flag

FALSE

Sequence End Completion TRUE

Flag

FALSE

Prepare SrcDat[] before Execute changes to TRUE.
Data communications started. The Protocol Macro Execution Flag changes to TRUE.

Data communications started. The Protocol Macro Execution Flag changes to TRUE and the Sequence End Completion Flag changes to FALSE.
Data communications ended. The Protocol Macro Execution Flag changes to FALSE and the Sequence End Completion Flag changes to TRUE.

NJ/NX-series Instructions Reference Manual (W502)

2-1221

2 Instruction Descriptions

Related System-defined Variables

Name _Port_numUsingPort _Port_isAvailable
_CJB_SCU##P1ChgSta, _CJB_SCU##P2ChgSta*

Meaning
Number of Used Ports
Network Communications Instruction Enabled Flag
Serial Communications Unit ## Port 1/2 Settings Changing Flag

Data type USINT BOOL
BOOL

* "##" denotes the unit number on the Serial Communications Unit.

Description This is the number of ports that are currently used. TRUE: A port is available. FALSE: A port is not available.
TRUE: The serial port settings are currently being changed. FALSE: The serial port settings are currently not being changed.

Related Semi-user-defined Variables

Name P#_PmrExecSta*
P#_PmrSeqEndSta*
P#_PmrSeqAbtSta*

Meaning Protocol Macro Execution Flag
Sequence End Completion Flag
Sequence Abort Completion Flag

Data type BOOL
BOOL
BOOL

* "#" denotes the port number on the Serial Communications Unit.

Description
TRUE: Protocol macro execution is in progress. FALSE: Protocol macro execution is not in progress or failed.
TRUE: The sequence was completed with an End. FALSE: The sequence was not completed with an End.
TRUE: The sequence was completed with an Abort. FALSE: The sequence was not completed with an Abort.

Additional Information
Refer to the SYSMAC CX-Protocol Operation Manual (Cat. No. W344) for details on protocol macros.

Precautions for Correct Use
· The ExecPMCR instruction starts execution of a protocol macro. Use the P#PmrExecSta (Protocol Macro Execution Flag) system-defined variable to check the status of protocol macro execution.
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error.
· An address in memory for CJ-series Units must be specified in the AT Specification attribute of DstDat[].
· Set the value of SrcDat[0] and DstDat[0] to 0 to use a direct specification and link word specification. An error occurs if you set any other constant or variable, and the instruction is not executed.
· If the value of DstDat[0] is 0 or 1 and reception fails, all elements in DstDat[] change to 0.
· The instruction is executed only when there is an available port. Therefore, use the system-defined variable _Port_isAvailable (Network Communications Instruction Enabled Flag) in an N.O. execution condition for the instruction.
· The instruction is not executed while Busy is TRUE. Therefore, use Busy in an N.C. execution condition for the instruction.

2-1222

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Serial Communications Instructions

ExecPMCR

· The Protocol Macro Execution Flag (semi-user-defined variable P#_PmrExecSta) changes to TRUE when instruction execution is started. It changes to FALSE after the communications sequence is completed and the receive data is stored in DstDat[]. You cannot execute this instruction for the same serial port while P#_PmrExecSta is TRUE. Therefore, use P#_PmrExecSta in an N.C. execution condition for the instruction.

· If the instruction is used in ST, make sure that the instruction is processed each task period as long as instruction execution continues. Otherwise, normal processing is sometimes not possible.

· An error occurs in the following cases. Error will change to TRUE.

· The serial communications mode is not set to Protocol Macro Mode when the instruction is executed.

· The value of _Port_isAvailable is FALSE.

· The value of SeqNo is outside of the valid range.

2

· The value of SeqNo is not registered to a Serial Communications Unit.

· The value of Port.UnitNo or Port.PhysicPortNo is outside of the valid range.

· There is no CJ-series Serial Communications Unit with the specified unit number.

· The value of SrcDat[0] exceeds the size of SrcDat[].

· The value of DstDat[0] exceeds the size of DstDat[].

· The value of SrcDat[0] or DstDat[0] exceeds 250 words.

· Communications fail.

· An address in memory for CJ-series Units is not specified in the AT Specification attribute of DstDat[].

· For this instruction, expansion error code ErrorIDEx gives the communications response code. The values and meanings are listed in the following table. An expansion error code is output to ErrorIDEx

when the value of error code ErrorID is WORD#16#0800.

Value 16#00000001
16#00000101 16#00000102 16#00000103 16#00000104
16#00000105 16#00000106 16#00000201 16#00000202 16#00000203
16#00000204
16#00000205 16#00000206

Error The communications service was interrupted.
The local node is not part of the network. A token timeout occurred.
The retry count was exceeded.
The allowable number of send frames was exceeded.
The IP address of the local node is out of range. The IP address of the local node is also used by another node in the network. The remote node is not part of the network. A Unit with the specified unit address does not exist at the destination. The third node is not part of the network.
The remote node is busy.
A response timeout occurred.
There is an error in the transmission path.

Correction
· Check the data link execution status.
· Check the capacity of the transfer destination area on the third node.
Make the local node part of the network.
Set the local node address to within the maximum node address.
Perform internode tests. If communications is not normal, check the operating environment.
Check the status of events in the network and reduce the number of events in each task period. Or, increase the number of allowable send frames.
Set the rotary switches on the Serial Communications Unit correctly.
Change one of the node addresses that are duplicated.
Make the remote node part of the network.
Correctly set the unit address for the destination network address.
· Check the address of the Unit that is the third node.
· Specify only one node for the third node.
Increase the setting of the number of retries or correct the system so that communications traffic is not concentrated on the remote node.
Check the settings of the communications parameters.
· Attempt retries.
· If this error occurs frequently, check for noise.

NJ/NX-series Instructions Reference Manual (W502)

2-1223

2 Instruction Descriptions

Value 16#00000301 16#00000302 16#00000303
16#00000304 16#00000401 16#00000402 16#00000501 16#00000502 16#00000503 16#00000504
16#00001001 16#00001002 16#00001003
16#00001004 16#00001005 16#00001101 16#00001102 16#00001103 16#00001104
16#00001106 16#00001109
16#0000110A
16#0000110B 16#0000110C 16#00002002 16#00002003 16#00002004 16#00002005 16#00002006

Error

Correction

A Communications Controller Error occurred. Refer to the operation manual for the relevant Unit and make suitable corrections.

There is an error in the CPU Unit at the remote node.

Refer to the manual for the CPU Unit at the remote node and remove the error.

There is an error in the relevant Controller and a response is not returned.

Check the communications status on the network and restart the relevant Controller. If the error still occurs, replace the relevant Controller.

The unit number setting is not correct.

Set the rotary switches on the Serial Communications Unit correctly.

The command that was sent is not supported.

Set the command array correctly.

The Unit model or version is not supported. Check the Unit model and version.

The remote address setting is wrong.

Set the destination address in the routing tables.

Routing tables are not registered.

Set the source node, destination node, and relay nodes in the routing tables.

There is an error in the routing tables.

Correct the settings in the routing tables.

There are too many relay points.

Restructure the networks or correct the routing tables so that commands are used within a three-layer range.

The command is too long.

Set the command array correctly.

The command is too short.

Set the command array correctly.

The number of write elements that is speci- Specify the same number of write elements fied in the command does not agree with the and write data. number of write data.

The command format is incorrect.

Set the command array correctly.

There is an error in the header.

Correct the settings in the routing tables.

The area type does not exist.

Refer to the command variables and parameter type codes and set the relevant codes.

An access size is wrong.

Correctly set the variable and parameter access sizes.

An out-of-range address was specified.

Specify an address that is within the process range.

The address range was exceeded.

· Specify an address that is within the process range.

· Correct the settings in the data link table.

A communications sequence number that is Correct the communications sequence num-

not registered was specified.

ber or add the sequence with the CX-Protocol.

An interrelationship error occurred.

· Correct the size relationships in the command data.

· Correct the settings in the data link table.

Data is redundant.

· Cancel the current process or wait for it to be completed before you execute the command.

· Correct the settings in the data link table.

The response is too long.

Set the number of elements in the command array correctly.

This is another parameter error.

Set the command array correctly.

The data is protected.

Execute the command again after clearing the protection.

There is no registered table.

Set the table correctly.

There is no data that matches the search data.

Set the search data correctly.

The relevant program number does not exist. Set a valid program number.

The relevant file does not exist.

Set the file name correctly, including the subdirectory names.

2-1224

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Serial Communications Instructions

ExecPMCR

Value

Error

Correction

16#00002007 A verification error occurred.

· Check the contents of memory and write the correct data.

· Check the contents of the file.

16#00002101

Access is not possible because the area is read-only.

Execute the command again after clearing the write protection.

16#00002102

The data is protected or the data link table cannot be written.

· Execute the command again after clearing the write protection.

· Set the system settings in the data link table.

16#00002103 Registration is not possible.

· Create the file after deleting unnecessary files or prepare new file memory.

· Execute the command again after closing

open files.

2

16#00002105 The relevant program number does not exist. Set a valid program number.

16#00002106 The relevant file does not exist.

Set the file name correctly, including the subdirectory names.

16#00002107 A file with the same name already exists.

Execute the command again after changing the name of the file to write.

16#00002108

The change is not possible because an error Correct the settings. occurred when trying to make it.

16#00002201

The operation was not possible because a protocol macros is already in execution.

Use an N.C. program input for the Protocol Macro Execution Flag.

16#00002202 The operating mode is wrong.

Check the operating mode.

16#00002203

The operating mode is wrong for the instruc- Check the operating mode of the Controller. tion (PROGRAM mode).

16#00002204

The operating mode is wrong for the instruc- Check the operating mode of the Controller. tion (DEBUG mode).

16#00002205

The operating mode is wrong for the instruc- Check the operating mode of the Controller. tion (MONITOR mode).

16#00002206

The operating mode is wrong for the instruc- Check the operating mode of the Controller. tion (RUN mode).

16#00002207

The specified mode is not the polling node. Confirm which node is the polling node of the network.

16#00002208

The operating mode is wrong for the instruc- Check step activation status. tion.

16#00002211 The Unit is busy.

Increase the setting of the number of retries or correct the system so that communications traffic is not concentrated on the relevant Unit.

16#00002301 The file device does not exist.

Insert the media. Or, format the EM.

16#00002302 There is no file memory.

Check the file memory device.

16#00002303 There is no built-in clock.

Check the specifications of the model.

16#00002401

A checksum error occurred in the protocol macro data or the data transfer is not yet completed.

Transfer the protocol macro data from the CXProtocol again.

16#00002502

There is an error in the part of memory for processing.

Transfer the correct data to memory.

16#00002503

The registered I/O Unit configuration does not agree with the physical Unit configuration.

Check the I/O Unit configuration.

16#00002504

There are too many local or remote I/O points.

Set the number of local and remote I/O points correctly.

16#00002505

An error occurred in a data transmission between the CPU Unit and a CPU Bus Unit.

Check the Units and the connecting cables. After removing the error, execute a command to reset the error.

16#00002506

The same rack number, unit number, or I/O Correct the settings so that each number is

address is set more than once.

unique.

16#00002507

An error occurred in a data transmission between the CPU Unit and an I/O Unit.

Check the Units and connecting cables. After removing the error, execute a command to reset the error.

NJ/NX-series Instructions Reference Manual (W502)

2-1225

2 Instruction Descriptions

Value 16#00002509
16#0000250A
16#0000250D 16#0000250F

Error There is an error in SYSMAC BUS/2 data transmission.
An error occurred in a CPU Bus Unit data transmission.
The same word setting is used more than once. There is an error in memory.

16#00002510 16#00002601 16#00002602 16#00002604

The end station setting is wrong. Protection is already cleared. The password was wrong. The data is protected.

16#00002605 The service is busy.

16#00002606 16#00002607

The service is stopped. You do not have the execution right.

16#00002608 16#00002609 16#0000260A

The environment is not set. The required items are not set. The specified number is already defined.

16#0000260B 16#00003001 16#00004001

The error cannot be reset. You do not have access rights. The service was interrupted.

Correction
Check the Units and connecting cables. After removing the error, execute a command to reset the error.
Check the Units and connecting cables. After removing the error, execute a command to reset the error.
Set the I/O words correctly.
· For internal memory, execute the command again after writing the correct data.
· For a Memory Card or EM file memory, execute the expansion memory format command.
· If the error cannot be reset with the above corrections, replace the memory.
Set the end station correctly.
You do not need to clear protection.
Specify the correct password.
· Execute the command again after clearing the write protection.
· Wait for the service that is currently in execution to end or stop the service, and then execute the command again.
Wait for the service that is currently in execution to end or stop the service, and then execute the command again.
Execute the relevant service as required.
· Execute the operation from the node that accessed the data link.
· If the error still occurs after restarting, replace the Controller.
Make the necessary settings.
Set the required items.
Execute the command again after changing the specified number to an action or transition number that is not already registered.
Remove the cause of the error and then execute the error reset command.
Wait for the access right to be cleared and then execute the command again.
Execute the command again after clearing the cause of the service interruption.

Note In addition to the codes in the above table, the values of bits 6, 7, and 15 in the end code can be TRUE. If the value of bit 6 or 7 is TRUE, there is an error in the CPU Unit at the destination. If the value of bit 15 is TRUE, an error occurred during a network relay.

2-1226

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

ExecPMCR

2 Instruction Descriptions

Sample Programming

In this sample, a CJ-series Serial Communications Unit is used for data communications with an OMRON Temperature Controller. The present value of the Temperature Controller is read with a protocol macro. CompoWay/F master sequence 610 (Read Variable Area) is used. The contents of send data array SendData[] is sent from the Controller. The data received from the Temperature Controller is stored in receive data array RecvData[].

The following communications specifications are used.

Item

Description

Unit used

Serial Communications Unit

Unit number Port number

2 1 (RS-422/485)

2

Communications

610 (Read Variable Area)

sequence number

Remote node number 3

Data to read

Present value

Serial Communications Unit with unit number 2

Send data Receive data

RS-422A/485

E5 N Temperature Controller, node 00

E5 N Temperature Controller, node 01

E5 N Temperature Controller, node 03

The communications data for sequence 610 (Read Variable Area) is allocated as shown below.

Send Data: WORD Array
SendData[0] Number of send data words SendData[1] Not used. Node No. SendData[2] Variable type SendData[3] Read start address SendData[4] Number of elements

Receive Data: WORD Array
RecvData[0] Number of receive data words RecvData[1] Response code RecvData[2] Receive data RecvData[3]

NJ/NX-series Instructions Reference Manual (W502)

2-1227

2 Instruction Descriptions

The contents of send data SendData[] and receive data RecvData[] are as follows: Send Data: WORD Array

Variable

Item

Contents

Value

SendData[0]

Number of send data words

Five words from SendData[0] to SendData[4] are sent.

WORD#16#0005

SendData[1] SendData[2] SendData[3]
SendData[4]

Node number
Variable type + Upper byte of read start address
Lower byte of read start address + BYTE#16#00 (fixed value)
Number of elements

Node 3 is used.
To read the present value, the variable type is BYTE#16#C0 and the read start address is WORD#16#00.
One element is read.

WORD#16#0003 WORD#16#C000 WORD#16#0000
WORD#16#0001

Receive Data: WORD Array

Variable RecvData[0]

Item
Number of receive data words

RecvData[1]

Response code

RecvData[2]

Receive data

RecvData[3]

Contents
Four words from RecvData[0] to RecvData[3] are received.
WORD#16#0000 is returned for a normal end.
The lower two bytes of the present value of the Temperature Controller are returned.
The upper two bytes of the present value of the Temperature Controller are returned.

Value WORD#16#0004

If the data is received successfully, the lower two bytes (RecvData[2]) and the upper two bytes (RecvData[3]) of the present value of the Temperature Controller are assigned to TmpData.
RecvData[2] RecvData[3]

Upper 2 bytes

Lower 2 bytes

TmpData
Definitions of Global Variables

Global Variables

Name

Data type

AT*1

Comment

SCU_P1_PmrSeqEndSta BOOL

IOBus://rack#0/slot#0/P1_PmrSta/P1_PmrSeqEndSta

Sequence End Completion Flag

SCU_P1_PmrSeqAbtSta BOOL

IOBus://rack#0/slot#0/P1_PmrSta/P1_PmrSeqAbtSta

Sequence Abort Completion Flag

SCU_P1_PmrExecSta

BOOL

IOBus://rack#0/slot#0/P1_PmrSta/P1_PmrExecSta

Protocol Macro Execution Flag

*1 AT when the Serial Communications Unit is mounted to slot number 0 in rack number 0

2-1228

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

ExecPMCR

2 Instruction Descriptions

LD
Internal Variables

Variable

Data type

Initial value

OperatingEnd Trigger Operating
InPort
SendData
RecvData TmpData RS_instance ExecPMCR_instance

BOOL BOOL BOOL
_sPORT
ARRAY[0..4 ] OF WORD ARRAY[0..3 ] OF WORD DINT RS ExecPMCR

FALSE FALSE FALSE (UnitNo:=_CBU_No00, PhysicPortNo:=0)
[5(16#0)]
[4(16#0)]
0

AT

Retain

Comment

Processing completed Execution condition Processing

Port settings

Send data

2

%D200

Receive data

Present value

External Variables

Variable
SCU_P1_PmrSeqEndSta SCU_P1_PmrSeqAbtSta SCU_P1_PmrExecSta _Port_isAvailable

Data type
BOOL BOOL BOOL BOOL

Comment
Sequence End Completion Flag Sequence Abort Completion Flag Protocol Macro Execution Flag Network Communications Instruction Enabled Flag

Determine if execution of the ExecPMCR instruction is completed.

ExecPMCR_instance.Done

OperatingEnd

ExecPMCR_instance.Error

Accept trigger. Trigger _Port_isAvailable SCU_P1_PmrExecSta ExecPMCR_instance.Busy
OperatingEnd

RS_instance

RS

Set

Q1

Reset1

Operating

Set communications parameters.

Operating

Inline ST

Note: The contents of the inline ST are given below at Contents of Inline ST1.

Execute ExecPMCR instruction.

Operating

ExecPMCR_instance ExecPMCR

InPort UINT#610 SendData[0]
RecvData[0]

Execute Port SeqNo SrcDat DstDat

Done Busy Error ErrorID

ErrorIDEx

NJ/NX-series Instructions Reference Manual (W502)

2-1229

2 Instruction Descriptions

Processing after normal end SCU_P1_PmrExecSta SCU_P1_PmrSeqEndSta

Inline ST Note: The contents of the inline ST are given below at Contents of Inline ST2.

Processing after error end ExecPMCR_instance.Error
SCU_P1_PmrExecSta SCU_P1_PmrSeqAbtSta

Inline ST
1 // Processing after error end 2 ;

Contents of Inline ST1

InPort.UnitNo

:=_CBU_No02; // Serial Communications Unit with unit number 2

InPort.PhysicPortNo:=USINT#1; // Port number 1

SendData[0]

:=WORD#16#0005;

SendData[1]

:=WORD#16#0003;

SendData[2]

:=WORD#16#C000;

SendData[3]

:=WORD#16#0000;

SendData[4]

:=WORD#16#0001;

RecvData[0]

:=WORD#16#0004;

Contents of Inline ST2
// Processing after normal end TmpData:=DWORD_TO_DINT(SHL(WORD_TO_DWORD(
RecvData[3]), 16) OR WORD_TO_DWORD(RecvData[2]) );

2-1230

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Serial Communications Instructions

ExecPMCR

ST

Internal Variables

Variable

Data type

Initial value

AT

Retain

Comment

State

INT

0

Current state

Trigger

BOOL

FALSE

Execution condition

LastTrigger

BOOL

FALSE

Value of Trigger from previous task period

InPort

_sPORT

(UnitNo:=_CBU_No00, PhysicPortNo:=0)

Port settings

SendData RecvData

ARRAY[0..4] OF WORD
ARRAY[0..3] OF WORD

[5(16#0)] [4(16#0)]

Send data

2

%D200

Receive data

End_ExecPMCR

BOOL

FALSE

Completion of ExecPMCR instruction execution

TmpData

DINT

0

Present value

RS_instance

RS

ExecPMCR_instance ExecPMCR

F_TRIG_instance

F_TRIG

External Variables

Variable
SCU_P1_PmrSeqEndSta SCU_P1_PmrSeqAbtSta SCU_P1_PmrExecSta _Port_isAvailable

Data type
BOOL BOOL BOOL BOOL

Comment
Sequence End Completion Flag Sequence Abort Completion Flag Protocol Macro Execution Flag Network Communications Instruction Enabled Flag

// Accept trigger. IF (State=INT#0) THEN
IF ( (Trigger=TRUE) AND (LastTrigger=FALSE) AND (_Port_isAvailable=TRUE) AND (SCU_P1_PmrExecSta<>TRUE) AND (ExecPMCR_instance.Busy<>TRUE) ) THEN State:=INT#1;
END_IF; END_IF; LastTrigger:=Trigger;

// Set communications parameters and initialize ExecPMCR instruction.

IF (State=INT#1) THEN

InPort.UnitNo

:=_CBU_No02; // Serial Communications Unit with unit number 2

InPort.PhysicPortNo :=USINT#1; // Port number 1

SendData[0]

:=WORD#16#0005;

SendData[1]

:=WORD#16#0003;

SendData[2]

:=WORD#16#C000;

SendData[3]

:=WORD#16#0000;

SendData[4]

:=WORD#16#0001;

RecvData[0]

:=WORD#16#0004;

ExecPMCR_instance(

Execute :=FALSE,

// Initialize ExecPMCR instruction.

SrcDat :=SendData[0], // Dummy

DstDat :=RecvData[0]);

State:=INT#2;

END_IF;

// Execute ExecPMCR instruction. IF (State=INT#2) THEN
ExecPMCR_instance( Execute :=TRUE,

NJ/NX-series Instructions Reference Manual (W502)

2-1231

2 Instruction Descriptions
Port :=InPort, SeqNo :=UINT#610, SrcDat :=SendData[0], DstDat :=RecvData[0]);
F_TRIG_instance(SCU_P1_PmrExecSta, End_ExecPMCR);
IF (End_ExecPMCR=TRUE) THEN End_ExecPMCR:=FALSE; State:=INT#3;
END_IF;
IF (ExecPMCR_instance.Error=TRUE) THEN State:=INT#5;
END_IF;
END_IF;
// Confirm completion of ExecPMCR instruction execution. IF (State=INT#3) THEN
IF (SCU_P1_PmrSeqEndSta=TRUE) THEN State:=INT#4;
END_IF; IF (SCU_P1_PmrSeqAbtSta=TRUE) THEN
State:=INT#5; END_IF; END_IF;
IF (State=INT#4) THEN // Processing after normal end. TmpData:=DWORD_TO_DINT(SHL(WORD_TO_DWORD(RecvData[3]), 16) OR WORD_TO_DWORD(RecvData[2])); State:=INT#0;
END_IF;
IF (State=INT#5) THEN // Processing after error end State:=INT#0;
END_IF;

2-1232

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

SerialSend

2 Instruction Descriptions

SerialSend

The SerialSend instruction sends data in No-protocol Mode from a serial port on a Serial Communications Unit.

Instruction SerialSend

Name
SCU Send Serial

FB/ FUN
FB

Graphic expression

SerialSend_instance

SerialSend

Execute

Done

Port

Busy

SrcDat

Error

SendSize ErrorID

ErrorIDEx

ST expression

SerialSend_instance(Execute,

Port, SrcDat, SendSize, Done,

Busy, Error, ErrorID, ErrorIDEx);

2

Precautions for Correct Use You cannot use this instruction in an NX-series CPU Unit.

Variables

Name Port
SrcDat[] (array) SendSize

Meaning
Destination port
Send data array
Send data size

I/O Input

Description Destination port

Valid range
---

Send data array

Depends on data type.

Data size to send from Src- 0 to 256 Dat[]

* If you omit an input parameter, the default value is not applied. A building error will occur.

Unit
---
Bytes

Default
---
*
1

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

Port

SrcDat[]

OK

(array)

SendSize

Refer to Function for details on the structure _sPORT. OK

NJ/NX-series Instructions Reference Manual (W502)

2-1233

2 Instruction Descriptions

Function

The SerialSend instruction sends data in No-protocol Mode from the port and the Serial Communications Unit specified with Port.
The data that is sent is contained in send data array SrcDat[]. The data size to send is specified in send data size SendSize.
To attach start and end codes to the send data, set them in the DM Area words that are assigned to the Special Unit.
If you add start and end codes, the maximum number of bytes to send is 259 (1-byte start code, 2-byte end code (for CR+LF specification), and 256 bytes of send data).

The data type of destination port Port is the structure _sPORT. The specifications are as follows:

Name Port
UnitNo

Meaning
Destination port
Unit number

PhysicPortNo Serial port number

Description Destination port

Data type _sPORT

Unit number of Serial Communications Unit
Serial port number on Serial Communications Unit

_eUnitNo USINT

Valid range
---

Unit Default
--- ---

_CBU_No00 to _CBU_No15

1 or 2

---

_CBU_ No00
1

The following figure shows a timing chart. Communications is performed to the end after the value of Done changes to TRUE.

Execute Busy Done Error
SrcDat[]

TRUE FALSE
TRUE FALSE
TRUE FALSE
TRUE FALSE

SerialSend Instruction Execution Flag

TRUE FALSE

Prepare SrcDat[] before Execute changes to TRUE.

Data transmission ended. SerialSend Instruction Execution Flag changes to FALSE.

Data transmission started. SerialSend Instruction Execution Flag changes to TRUE.

2-1234

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Serial Communications Instructions

SerialSend

Related System-defined Variables

Name _Port_numUsingPort _Port_isAvailable

Meaning
Number of Used Ports
Network Communications Instruction Enabled Flag

Data type USINT BOOL

Description This is the number of ports that are currently used. TRUE: A port is available. FALSE: A port is not available.

Related Semi-user-defined Variables

Name

Meaning

Data type

Description

2

P#_NopSerialSendExecSta* SerialSend Instruction BOOL Execution Flag

TRUE: Execution of the SerialSend instruction is in progress.

FALSE: Execution of the SerialSend instruction is not in progress.

P#_NopStartCodeYNCfg*

No-protocol Start Code BOOL Enable

TRUE: Start code FALSE: No start code

P#_NopEndCodeYNCfg*

No-protocol End Code BOOL Enable

TRUE: End code FALSE: No end code

P#_NopCRLFCfg*

No-protocol CR LF Specification

BOOL

TRUE: CR+LF FALSE: No CR+LF

P#_NopStartCodeCfg*

No-protocol Start Code USINT

16#00 to 16#FF

P#_NopEndCodeCfg*

No-protocol End Code USINT

16#00 to 16#FF

* "#" denotes the port number on the Serial Communications Unit.

Additional Information
Refer to the following manual for details on no-protocol communications. · CJ-series Serial Communications Units Operation Manual for NJ-series CPU Unit (Cat. No. W494)

Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error.
· You can use this instruction only for a Serial Communications Unit's serial port that is set to No-protocol Mode.
· Nothing is sent if the value of SendSize is 0. When the instruction is executed, the value of Done changes to TRUE.
· Even when attaching a start or end code, do not include it in the value of SendSize.
· The instruction is executed only when there is an available port. Therefore, use the system-defined variable _Port_isAvailable (Network Communications Instruction Enabled Flag) in an N.O. execution condition for the instruction.
· The instruction is not executed while Busy is TRUE. Therefore, use Busy in an N.C. execution condition for the instruction.
· You cannot execute this instruction while the SerialSend Instruction Executing Flag (semi-userdefined variable P#NopSerialSendExecSta) is TRUE. Use P#NopSerialSendExecSta in an N.C. execution condition for the instruction.
· If the instruction is used in ST, make sure that the instruction is processed each task period as long as instruction execution continues. Otherwise, normal processing is sometimes not possible.

NJ/NX-series Instructions Reference Manual (W502)

2-1235

2 Instruction Descriptions

· An error occurs in the following cases. Error will change to TRUE.

· The serial communications mode is not set to No-protocol Mode when the instruction is executed.

· The value of _Port_isAvailable is FALSE.

· The value of Port.UnitNo or Port.PhysicPortNo is outside of the valid range.

· There is no CJ-series Serial Communications Unit with the specified unit number.

· The value of SendSize is outside of the valid range.

· The value of SendSize exceeds the size of SrcDat[].

· Communications fail.

· The instruction is executed during a Unit restart.

· For this instruction, expansion error code ErrorIDEx gives the communications response code. The values and meanings are listed in the following table. An expansion error code is output to ErrorIDEx

when the value of error code ErrorID is WORD#16#0800.

Value 16#00000001
16#00000101 16#00000102 16#00000103 16#00000104
16#00000105 16#00000106 16#00000201 16#00000202 16#00000203
16#00000204
16#00000205 16#00000206
16#00000301 16#00000302 16#00000303
16#00000304 16#00000401 16#00000402

Error The communications service was interrupted.
The local node is not part of the network. A token timeout occurred.
The retry count was exceeded.
The allowable number of send frames was exceeded.
The IP address of the local node is out of range. The IP address of the local node is also used by another node in the network. The remote node is not part of the network. A Unit with the specified unit address does not exist at the destination. The third node is not part of the network.
The remote node is busy.
A response timeout occurred.
There is an error in the transmission path.
A Communications Controller Error occurred.
There is an error in the CPU Unit at the remote node. There is an error in the relevant Controller and a response is not returned.
The unit number setting is not correct.
The command that was sent is not supported. The Unit model or version is not supported.

Correction
· Check the data link execution status.
· Check the capacity of the transfer destination area on the third node.
Make the local node part of the network.
Set the local node address to within the maximum node address.
Perform internode tests. If communications is not normal, check the operating environment.
Check the status of events in the network and reduce the number of events in each task period. Or, increase the number of allowable send frames.
Set the rotary switches on the Serial Communications Unit correctly.
Change one of the node addresses that are duplicated.
Make the remote node part of the network.
Correctly set the unit address for the destination network address.
· Check the address of the Unit that is the third node.
· Specify only one node for the third node.
Increase the setting of the number of retries or correct the system so that communications traffic is not concentrated on the remote node.
Check the settings of the communications parameters.
· Attempt retries.
· If this error occurs frequently, check for noise.
Refer to the operation manual for the relevant Unit and make suitable corrections.
Refer to the manual for the CPU Unit at the remote node and remove the error.
Check the communications status on the network and restart the relevant Controller. If the error still occurs, replace the relevant Controller.
Set the rotary switches on the Serial Communications Unit correctly.
Set the command array correctly.
Check the Unit model and version.

2-1236

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Serial Communications Instructions

SerialSend

Value

Error

Correction

16#00000501 The remote address setting is wrong.

Set the destination address in the routing tables.

16#00000502 Routing tables are not registered.

Set the source node, destination node, and relay nodes in the routing tables.

16#00000503 There is an error in the routing tables.

Correct the settings in the routing tables.

16#00000504 There are too many relay points.

Restructure the networks or correct the routing tables so that commands are used within a three-layer range.

16#00001001 The command is too long.

Set the command array correctly.

16#00001002 The command is too short.

Set the command array correctly.

16#00001003 The number of write elements that is speci- Specify the same number of write elements

fied in the command does not agree with the and write data.

2

number of write data.

16#00001004 The command format is incorrect.

Set the command array correctly.

16#00001005 There is an error in the header.

Correct the settings in the routing tables.

16#00001101 The area type does not exist.

Refer to the command variables and parameter type codes and set the relevant codes.

16#00001102 An access size is wrong.

Correctly set the variable and parameter access sizes.

16#00001103 An out-of-range address was specified.

Specify an address that is within the process range.

16#00001104 The address range was exceeded.

· Specify an address that is within the process range.

· Correct the settings in the data link table.

16#00001106

A communications sequence number that is Correct the communications sequence num-

not registered was specified.

ber or add the sequence with the CX-Protocol.

16#00001109 An interrelationship error occurred.

· Correct the size relationships in the command data.

· Correct the settings in the data link table.

16#0000110A Data is redundant.

· Cancel the current process or wait for it to be completed before you execute the command.

· Correct the settings in the data link table.

16#0000110B The response is too long.

Set the number of elements in the command array correctly.

16#0000110C This is another parameter error.

Set the command array correctly.

16#00002002 The data is protected.

Execute the command again after clearing the protection.

16#00002003 There is no registered table.

Set the table correctly.

16#00002004

There is no data that matches the search data.

Set the search data correctly.

16#00002005 The relevant program number does not exist. Set a valid program number.

16#00002006 The relevant file does not exist.

Set the file name correctly, including the subdirectory names.

16#00002007 A verification error occurred.

· Check the contents of memory and write the correct data.

· Check the contents of the file.

16#00002101

Access is not possible because the area is read-only.

Execute the command again after clearing the write protection.

16#00002102

The data is protected or the data link table cannot be written.

· Execute the command again after clearing the write protection.

· Set the system settings in the data link table.

16#00002103 Registration is not possible.

· Create the file after deleting unnecessary files or prepare new file memory.

· Execute the command again after closing open files.

16#00002105 The relevant program number does not exist. Set a valid program number.

NJ/NX-series Instructions Reference Manual (W502)

2-1237

2 Instruction Descriptions

Value 16#00002106 16#00002107 16#00002108 16#00002201 16#00002202 16#00002203 16#00002204 16#00002205 16#00002206 16#00002207 16#00002208 16#00002211
16#00002301 16#00002302 16#00002303 16#00002401
16#00002502 16#00002503
16#00002504 16#00002505
16#00002506 16#00002507
16#00002509
16#0000250A
16#0000250D

Error The relevant file does not exist.
A file with the same name already exists.
The change is not possible because an error occurred when trying to make it. The operation was not possible because a protocol macros is already in execution. The operating mode is wrong. The operating mode is wrong for the instruction (PROGRAM mode). The operating mode is wrong for the instruction (DEBUG mode). The operating mode is wrong for the instruction (MONITOR mode). The operating mode is wrong for the instruction (RUN mode). The specified mode is not the polling node.
The operating mode is wrong for the instruction. The Unit is busy.
The file device does not exist. There is no file memory. There is no built-in clock. A checksum error occurred in the protocol macro data or the data transfer is not yet completed. There is an error in the part of memory for processing. The registered I/O Unit configuration does not agree with the physical Unit configuration. There are too many local or remote I/O points. An error occurred in a data transmission between the CPU Unit and a CPU Bus Unit.
The same rack number, unit number, or I/O address is set more than once. An error occurred in a data transmission between the CPU Unit and an I/O Unit.
There is an error in SYSMAC BUS/2 data transmission.
An error occurred in a CPU Bus Unit data transmission.
The same word setting is used more than once.

Correction Set the file name correctly, including the subdirectory names. Execute the command again after changing the name of the file to write. Correct the settings.
Use an N.C. program input for the Protocol Macro Execution Flag. Check the operating mode. Check the operating mode of the Controller.
Check the operating mode of the Controller.
Check the operating mode of the Controller.
Check the operating mode of the Controller.
Confirm which node is the polling node of the network. Check step activation status.
Increase the setting of the number of retries or correct the system so that communications traffic is not concentrated on the relevant Unit. Insert the media. Or, format the EM. Check the file memory device. Check the specifications of the model. Transfer the protocol macro data from the CXProtocol again.
Transfer the correct data to memory.
Check the I/O Unit configuration.
Set the number of local and remote I/O points correctly. Check the Units and the connecting cables. After removing the error, execute a command to reset the error. Correct the settings so that each number is unique. Check the Units and the connecting cables. After removing the error, execute a command to reset the error. Check the Units and the connecting cables. After removing the error, execute a command to reset the error. Check the Units and the connecting cables. After removing the error, execute a command to reset the error. Set the I/O words correctly.

2-1238

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

SerialSend

2 Instruction Descriptions

Value

Error

Correction

16#0000250F There is an error in memory.

· For internal memory, execute the command again after writing the correct data.

· For a Memory Card or EM file memory, execute the expansion memory format command.

· If the error cannot be reset with the above corrections, replace the memory.

16#00002510 The end station setting is wrong.

Set the end station correctly.

16#00002601 Protection is already cleared.

You do not need to clear protection.

16#00002602 The password was wrong.

Specify the correct password.

16#00002604 The data is protected.

· Execute the command again after clearing

the write protection.

2

· Wait for the service that is currently in exe-

cution to end or stop the service, and then

execute the command again.

16#00002605 The service is busy.

Wait for the service that is currently in execution to end or stop the service, and then execute the command again.

16#00002606 The service is stopped.

Execute the relevant service as required.

16#00002607 You do not have the execution right.

· Execute the operation from the node that accessed the data link.

· If the error still occurs after restarting, replace the Controller.

16#00002608 The environment is not set.

Make the necessary settings.

16#00002609 The required items are not set.

Set the required items.

16#0000260A The specified number is already defined.

Execute the command again after changing the specified number to an action or transition number that is not already registered.

16#0000260B The error cannot be reset.

Remove the cause of the error and then execute the error reset command.

16#00003001 You do not have access rights.

Wait for the access right to be cleared and then execute the command again.

16#00004001 The service was interrupted.

Execute the command again after clearing the cause of the service interruption.

Note In addition to the codes in the above table, the values of bits 6, 7, and 15 in the end code can be TRUE. If the value of bit 6 or 7 is TRUE, there is an error in the CPU Unit at the destination. If the value of bit 15 is TRUE, an error occurred during a network relay.

Sample Programming
In this sample, a no-protocol command is sent to the barcode reader that is connected to serial port 2 of a CJ-series Serial Communications Unit (unit number 0, device name `Barcode'). The scene number acquisition command (@READ) is sent. The send data is the contents of the array variable SendDat[]. There is no start code and the end code is 16#OD (CR).

NJ/NX-series Instructions Reference Manual (W502)

2-1239

2 Instruction Descriptions

Serial Communications Unit with unit number 0

Serial port 2

Command sent. Barcode reader

The settings of Serial Communications Unit are given in the following table.

Item Port 2: User-specified Setting Inclusion

Set value User settings

Port 2: Serial Communications Mode

No-protocol

Port 2: Data Length Port 2: Stop Bits

8 bits 1 bit

Port 2: Parity

No

Port 2: Baud Rate

38,400 bps

Port 2: No-Protocol End Code

D

Port 2: No-Protocol Start Code Inclusion Setting

No

Port 2: No-Protocol End Code Inclusion Setting

Yes (Specify a desired end code.)

The text string `@READ' is separated into individual characters and the character codes are stored in the array elements of SendDat[]. Therefore, BYTE#16#40 (@) is stored in SendDat[0], BYTE#16#52(R) is stored in SendData[1], etc. The StringToAry instruction is used to store the character codes.

BYTE array

STRING data StringToAry

SendDat[0] BYTE#16#40 SendDat[1] BYTE#16#52

`@READ'

SendDat[2] BYTE#16#45

SendDat[3] BYTE#16#41

SendDat[4] BYTE#16#44

Definitions of Global Variables

Global Variables

Name

Data type

AT*1

Comment

Barcode_P2_NopSerialSendExecSta

BOOL

IOBus://rack#0/slot#0/P2_NopSta SerialSend Instruction Execu-

/P2_NopSerialSendExecSta

tion Flag

*1 AT when the Serial Communications Unit is mounted to slot number 0 in rack number 0.

2-1240

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Serial Communications Instructions

SerialSend

LD

Internal Variables

Variable

Data type

Initial value

Comment

OperatingEnd

BOOL

FALSE

Processing completed

Trigger

BOOL

FALSE

Execution condition

Operating

BOOL

FALSE

Processing

InPort

_sPORT

(UnitNo:=_CBU_No00, PhysicPortNo:=0)

Port settings

SendDat

ARRAY[0..4] OF BYTE [5(16#0)]

Send data

RS_instance

RS

2

SerialSend_instance SerialSend

External Variables

Variable
_Port_isAvailable Barcode_P2_NopSerialSendExecSta

Data type BOOL BOOL

Comment Network Communications Instruction Enabled Flag SerialSend Instruction Execution Flag

Determine if execution of the SerialSend instruction is completed.

SerialSend_instance.Done

OperatingEnd

SerialSend_instance.Error

Accept trigger. Trigger _Port_isAvailable Barcode_P2_NopSerialSendExecSta SerialSend_instance.Busy
OperatingEnd

RS_instance

RS

Set

Q1

Reset1

Operating

Set communications parameters.

Operating

Inline ST

Note: The contents of the inline ST are given below.

Execute SerialSend instruction.

SerialSend_instance

Operating

SerialSend

Execute

Done

InPort Port

Busy

SendDat[0] SrcDat

Error

UINT#5 SendSize ErrorID

ErrorIDEx

Processing after normal end Operating SerialSend_instance.Done

Processing after error end Operating SerialSend_instance.Error

Inline ST 1 // Processing after normal end 2 ;
Inline ST 1 // Processing after error end 2 ;

NJ/NX-series Instructions Reference Manual (W502)

2-1241

2 Instruction Descriptions

Contents of Inline ST

StringToAry(In :='@READ', AryOut:=SendDat[0]); // Prepare SendDat[].

InPort.UnitNo

:=_CBU_No00;

// Serial Communications Unit with unit number 0

InPort.PhysicPortNo:=USINT#2;

// Serial port 2

2-1242

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

SerialSend

2 Instruction Descriptions

ST

Internal Variables

Variable

Data type

Initial value

Comment

Trigger

BOOL

FALSE

Execution condition

LastTrigger

BOOL

FALSE

Value of Trigger from previous task period

OperatingStart

BOOL

FALSE

Processing started

Operating

BOOL

FALSE

Processing

(UnitNo:=_CBU_-

InPort

_sPORT

No00, Phys-

Port settings

icPortNo:=0)

SendDat

ARRAY[0..4] OF BYTE [5(16#0)]

Send data

2

SerialSend_instance SerialSend

External Variables

Variable
_Port_isAvailable Barcode_P2_NopSerialSendExecSta

Data type BOOL BOOL

Comment Network Communications Instruction Enabled Flag SerialSend Instruction Execution Flag

// Detect when Trigger changes to TRUE. IF ( (Trigger=TRUE) AND (LastTrigger=FALSE) AND (_Port_isAvailable=TRUE)
AND (Barcode_P2_NopSerialSendExecSta=FALSE) AND (SerialSend_instance.Busy=FALSE) ) THEN OperatingStart:=TRUE; Operating :=TRUE; END_IF; LastTrigger:=Trigger;

// Set communications parameters and initialize SerialSend instruction.

IF (OperatingStart=TRUE) THEN

SerialSend_instance(

Execute:=FALSE,

SrcDat :=SendDat[0]);

StringToAry(In

:='@READ', AryOut:=SendDat[0]);

InPort.UnitNo

:=_CBU_No00; // Serial Communications Unit with unit number 0

InPort.PhysicPortNo :=USINT#2; // Serial port 2

OperatingStart

:=FALSE;

END_IF;

// Execute SerialSend instruction. IF (Operating=TRUE) THEN
SerialSend_instance( Execute :=TRUE, Port :=InPort, // Port settings SrcDat :=SendDat[0], // Send data SendSize :=UINT#5); // Send data size

IF (SerialSend_instance.Done=TRUE) THEN // Processing after normal end Operating:=FALSE;
END_IF;

IF (SerialSend_instance.Error=TRUE) THEN // Processing after error end
Operating:=FALSE; END_IF; END_IF;

NJ/NX-series Instructions Reference Manual (W502)

2-1243

2 Instruction Descriptions

SerialRcv and SerialRcvNoClear

The SerialRcv and SerialRcvNoClear instructions receive data in No-protocol Mode from a serial port on a Serial Communications Unit.

SerialRcv:

Clears the receive buffer after reading the data.

SerialRcvNoClear:

Does not clear the receive buffer after reading the data.

Instruction SerialRcv

Name
SCU Receive Serial

FB/ FUN
FB

SerialRcvNoClear

SCU Receive FB Serial without Receive Buffer Clear

Graphic expression

SerialRcv_instance

SerialRcv

Execute Port Size DstDat

Done Busy Error

ErrorID ErrorIDEx
RcvSize

SerialRcvNoClear_instance

SerialRcvNoClear

Execute Port Size DstDat

Done Busy Error

ErrorID ErrorIDEx
RcvSize

ST expression SerialRcv_instance(Execute, Port, Size, DstDat, Done, Busy, Error, ErrorID, ErrorIDEx, RcvSize);
SerialRcvNoClear_instance(Execute, Port, Size, DstDat, Done, Busy, Error, ErrorID, ErrorIDEx, RcvSize);

Precautions for Correct Use You cannot use this instruction in an NX-series CPU Unit.

Variables

Name Port
Size
DstDat[] (array) RcvSize

Meaning
Destination port
Receive data size
Receive data array
Receive data storage size

I/O Input In-out Output

Description Destination port

Valid range ---

Unit ---

Size of receive data stored in DstDat[]
Receive data array

0 to 256

Bytes

Depends on data type. ---

Size of receive data that was actually stored in DstDat[]

0 to 256

Bytes

Default --1
-----

2-1244

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

SerialRcv and SerialRcvNoClear

2 Instruction Descriptions

numbers REAL

Boolean BOOL

Bit strings

Integers

Real

Times, durations, dates, and text strings

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

Port

Refer to Function for details on the structure _sPORT.

Size

OK

DstDat[]

OK

(array)

2

RcvSize

OK

Function

First, data is received in No-protocol Mode from the serial port specified with Port and stored in the receive buffer in the Serial Communications Unit. This instruction transfers the number of bytes specified with receive data size Size from the receive buffer to receive data array DstDat[].
After the data is transferred, the number of array elements that was actually stored in DstDat[] is assigned to the receive data storage size RcvSize.
If the amount of data in the receive buffer is smaller than Size, all of the data in the receive buffer is transferred to DstDat[]. The data size that was actually stored in DstDat[] is assigned to RcvSize.

When the Data In the Receive Buffer Is the Same or Larger than Size

Receive buffer

DstDat[]

Data

Size Only Size amount of data is transferred.

RcvSize = Size

Data

When the Data In the Receive Buffer Is Less than Size

Receive buffer Size

Only the data in the receive buffer is transferred.

DstDat[] RcvSize < Size

NJ/NX-series Instructions Reference Manual (W502)

2-1245

2 Instruction Descriptions

Start Code and End Code in Receive Data

Device variables are used in the user program to recognize the start code and end code in the receive data. The start and end codes are deleted from the receive data before it is stored in DstDat[].

Code to attach Specified start code
Specified end code CR+LF as end code

Device variable for port 1 P1_NopStartCodeYNCfg P1_NopStartCodeCfg
P1_NopEndCodeYNCfg P1_NopCRLFCfg P1_NopEndCodeCfg
P1_NopEndCodeYNCfg P1_NopCRLFCfg

Value TRUE Start code (16#00 to 16#FF) TRUE FALSE End code (16#00 to 16#FF) TRUE TRUE

If you add start and end codes, the maximum number of bytes to receive is 259 (1-byte start code, 2byte end code (for CR+LF specification), and 256 bytes of send data).

Data Types of Destination Port Port

The data type of destination port Port is the structure _sPORT. The specifications are as follows:

Name Port
UnitNo

Meaning
Destination port
Unit number

PhysicPortNo Serial port number

Description Destination port

Data type _sPORT

Unit number of Serial Communications Unit
Serial port number on Serial Communications Unit

_eUnitNo USINT

Valid range
---

Unit Default
--- ---

_CBU_No00 to _CBU_No15

1 or 2

---

_CBU_ No00
1

2-1246

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Serial Communications Instructions

SerialRcv and SerialRcvNoClear

Timing Chart

The following figure shows a timing chart.

Execute Busy

TRUE FALSE
TRUE FALSE

TRUE Done FALSE

TRUE

Error FALSE

2

DstDat[]

Reception Completed Flag

TRUE FALSE

Received data it is stored in DstDat[]. Reception Completed Flag changes to FALSE.

Data reception ended. Reception Completed Flag changes to TRUE.

Difference between the SerialRcv and SerialRcvNoClear Instructions
The SerialRcv and SerialRcvNoClear instructions are different in whether the receive buffer is cleared after data is transferred from the receive buffer to DstDat[]. The SerialRcv instruction clears the receive buffer after it transfers the data. Therefore, if the data in the receive buffer is larger than Size, the remaining data is discarded after the transfer.

SerialRcv Instruction Receive buffer

Data

Size Only Size amount of data is transferred to DstDat[].

Remaining data

The receive data is cleared and the remaining data is discarded.

Remaining data

Discarded.

NJ/NX-series Instructions Reference Manual (W502)

2-1247

2 Instruction Descriptions

The SerialRcvNoClear instruction clears only the data that was transferred after the data transfer. The data that remains in the receive buffer is moved to the front of the receive buffer. If new data enters the receive buffer after that, it is stored after the data that was moved to the front of the buffer.

SerialRcvNoClear Instruction Receive buffer

Data

Size Only Size amount of data is transferred to DstDat[].
Remaining data

Data

Remaining data
Moved to the front.

The remaining data is moved to the front of the receive buffer.

Data

New data
New data is stored after the data that was moved to the front.

Related System-defined Variables

Name _Port_numUsingPort _Port_isAvailable

Meaning
Number of Used Ports
Network Communications Instruction Enabled Flag

Data type USINT BOOL

Description This is the number of ports that are currently used. TRUE: A port is available. FALSE: A port is not available.

Related Semi-user-defined Variables

Name P#_NopRcvOvfSta*
P#_NopRcvCompleteSta* P#_NopRcvCntSta* P#_NopStartCodeYNCfg* P#_NopEndCodeYNCfg* P#_NopCRLFCfg*

Meaning
Reception Overflow Flag

Data type BOOL

Reception Completed BOOL Flag

Reception Counter

UINT

No-protocol Start Code Enable
No-protocol End Code Enable
No-protocol CR LF Specification

BOOL BOOL BOOL

Description TRUE: The Unit received more than the speci-
fied amount of data (i.e., data was received after the Reception Completed Flag changed to TRUE).
FALSE: The Unit did no receive more than the specified number of bytes.
TRUE: Reception was completed.
FALSE: No data received or currently receiving data. 16#0000 to 16#0100: Number of bytes of receive data TRUE: Start code
FALSE: None TRUE: End code
FALSE: None TRUE: CR+LF
FALSE: No CR+LF

2-1248

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Serial Communications Instructions

SerialRcv and SerialRcvNoClear

Name P#_NopRcvDatSzCfg*
P#_NopStartCodeCfg* P#_NopEndCodeCfg* P#_TransErr*
P#_OverRunErr*

Meaning

Data type

Number of No-protocol USINT Receive Data Bytes

No-protocol Start Code No-protocol End Code Transmission Error

USINT USINT BOOL

Overrun Error

BOOL

* "#" denotes the port number on the Serial Communications Unit.

Description 16#01 to 16#FF: 1 to 255 bytes 16#00: 256 bytes 16#00 to 16#FF 16#00 to 16#FF TRUE: Error occurred. FALSE: No error occurred. TRUE: Error occurred. FALSE: No error occurred.

2 Additional Information

· The Reception Completed Flag (P#_NopRcvCompleteSta) changes to TRUE at the following times.
· The amount of data set in Number of No-protocol Receive Data Bytes (P#_NopRcvDatSzCfg) is received.
· The specified end code is received.
· A total of 256 bytes of data is received.
· The Reception Overflow Flag (P#_NopRcvOvfSta) changes to TRUE at the following times.
· Data is received when this instruction is not executed and the Reception Completed Flag (P#_NopRcvCompleteSta) is TRUE.
· More than the amount of data set in Number of No-protocol Receive Data Bytes (P#_NopRcvDatSzCfg) is received.
· Refer to the following manual for details on no-protocol communications.
· CJ-series Serial Communications Units Operation Manual for NJ-series CPU Unit (Cat. No. W494)

Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error.
· Execute the instruction only when the Reception Completed Flag (P#_NopRcvCompleteSta) is TRUE.
· When data is received, always execute this instruction to transfer the data in the receive buffer to DstDat[]. No more data is received until the previous data is transferred.
· Reception stops automatically after 259 bytes of data is received. If this instruction is not executed after that and more data is received, Overrun Error (P#_OverRunErr) changes to TRUE.
· Even when a start or end code is attached, do not include it in the value of Size.
· You can use this instruction only for a Serial Communications Unit's serial port that is set to No-protocol Mode.
· If the value of Size is 0, the data in the receive buffer is not transferred to DstDat[]. If that occurs, the Reception Completed Flag (P#_NopRcvCompleteSta) and Reception Overflow Flag (P#_NopRcvOvfSta) will change to FALSE. Also, the Reception Counter (P#_NopRcvCntSta) will be 0.
· The instruction is executed only when there is an available port. Therefore, use the system-defined variable _Port_isAvailable (Network Communications Instruction Enabled Flag) in an N.O. execution condition for the instruction.
· Execute the instruction only when the Reception Completed Flag (P#_NopRcvCompleteSta) is TRUE.

NJ/NX-series Instructions Reference Manual (W502)

2-1249

2 Instruction Descriptions

· The instruction is not executed while Busy is TRUE. Therefore, use Busy in an N.C. execution condition for the instruction.

· If the instruction is used in ST, make sure that the instruction is processed each task period as long as instruction execution continues. Otherwise, normal processing is sometimes not possible.

· The receive buffer in the Serial Communications Unit is cleared when the SerialRcv instruction is executed. Therefore, you cannot separate the data in the receive buffer to transfer it to DstDat[].

· For the SerialRcv instruction, any receive data that exceeds the size specified with Size is discarded the next time the SerialRcv instruction is executed.

· An error occurs in the following cases. Error will change to TRUE.

· The serial communications mode is not set to No-protocol Mode when the instruction is executed.

· The value of _Port_isAvailable is FALSE.

· The value of Port.UnitNo or Port.PhysicPortNo is outside of the valid range.

· There is no CJ-series Serial Communications Unit with the specified unit number.

· The value of Size is outside of the valid range.

· The value of Size exceeds the size of DstDat[].

· Communications fail.

· The instruction is executed during a Unit restart.

· For this instruction, expansion error code ErrorIDEx gives the communications response code. The values and meanings are listed in the following table. An expansion error code is output to ErrorIDEx

when the value of error code ErrorID is WORD#16#0800.

Value 16#00000001
16#00000101 16#00000102 16#00000103 16#00000104
16#00000105 16#00000106 16#00000201 16#00000202 16#00000203
16#00000204
16#00000205 16#00000206
16#00000301 16#00000302

Error The communications service was interrupted.
The local node is not part of the network. A token timeout occurred.
The retry count was exceeded.
The allowable number of send frames was exceeded.
The IP address of the local node is out of range. The IP address of the local node is also used by another node in the network. The remote node is not part of the network. A Unit with the specified unit address does not exist at the destination. The third node is not part of the network.
The remote node is busy.
A response timeout occurred.
There is an error in the transmission path.
A Communications Controller Error occurred.
There is an error in the CPU Unit at the remote node.

Correction
· Check the data link execution status.
· Check the capacity of the transfer destination area on the third node.
Make the local node part of the network.
Set the local node address to within the maximum node address.
Perform internode tests. If communications is not normal, check the operating environment.
Check the status of events in the network and reduce the number of events in each task period. Or, increase the number of allowable send frames.
Set the rotary switches on the Serial Communications Unit correctly.
Change one of the node addresses that are duplicated.
Make the remote node part of the network.
Correctly set the unit address for the destination network address.
· Check the address of the Unit that is the third node.
· Specify only one node for the third node.
Increase the setting of the number of retries or correct the system so that communications traffic is not concentrated on the remote node.
Check the settings of the communications parameters.
· Attempt retries.
· If this error occurs frequently, check for noise.
Refer to the operation manual for the relevant Unit and make suitable corrections.
Refer to the manual for the CPU Unit at the remote node and remove the error.

2-1250

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Serial Communications Instructions

SerialRcv and SerialRcvNoClear

Value

Error

Correction

16#00000303

There is an error in the relevant Controller and a response is not returned.

Check the communications status on the network and restart the relevant Controller. If the error still occurs, replace the relevant Controller.

16#00000304 The unit number setting is not correct.

Set the rotary switches on the Serial Communications Unit correctly.

16#00000401

The command that was sent is not supported.

Set the command array correctly.

16#00000402 The Unit model or version is not supported. Check the Unit model and version.

16#00000501 The remote address setting is wrong.

Set the destination address in the routing tables.

16#00000502 Routing tables are not registered.

Set the source node, destination node, and relay nodes in the routing tables.

2

16#00000503 There is an error in the routing tables.

Correct the settings in the routing tables.

16#00000504 There are too many relay points.

Restructure the networks or correct the routing tables so that commands are used within a three-layer range.

16#00001001 The command is too long.

Set the command array correctly.

16#00001002 The command is too short.

Set the command array correctly.

16#00001003

The number of write elements that is speci- Specify the same number of write elements fied in the command does not agree with the and write data. number of write data.

16#00001004 The command format is incorrect.

Set the command array correctly.

16#00001005 There is an error in the header.

Correct the settings in the routing tables.

16#00001101 The area type does not exist.

Refer to the command variables and parameter type codes and set the relevant codes.

16#00001102 An access size is wrong.

Correctly set the variable and parameter access sizes.

16#00001103 An out-of-range address was specified.

Specify an address that is within the process range.

16#00001104 The address range was exceeded.

· Specify an address that is within the process range.

· Correct the settings in the data link table.

16#00001106

A communications sequence number that is Correct the communications sequence num-

not registered was specified.

ber or add the sequence with the CX-Protocol.

16#00001109 An interrelationship error occurred.

· Correct the size relationships in the command data.

· Correct the settings in the data link table.

16#0000110A Data is redundant.

· Cancel the current process or wait for it to be completed before you execute the command.

· Correct the settings in the data link table.

16#0000110B The response is too long.

Set the number of elements in the command array correctly.

16#0000110C This is another parameter error.

Set the command array correctly.

16#00002002 The data is protected.

Execute the command again after clearing the protection.

16#00002003 There is no registered table.

Set the table correctly.

16#00002004

There is no data that matches the search data.

Set the search data correctly.

16#00002005 The relevant program number does not exist. Set a valid program number.

16#00002006 The relevant file does not exist.

Set the file name correctly, including the subdirectory names.

16#00002007 A verification error occurred.

· Check the contents of memory and write the correct data.

· Check the contents of the file.

NJ/NX-series Instructions Reference Manual (W502)

2-1251

2 Instruction Descriptions

Value 16#00002101 16#00002102
16#00002103
16#00002105 16#00002106 16#00002107 16#00002108 16#00002201 16#00002202 16#00002203 16#00002204 16#00002205 16#00002206 16#00002207 16#00002208 16#00002211
16#00002301 16#00002302 16#00002303 16#00002401
16#00002502 16#00002503
16#00002504 16#00002505
16#00002506 16#00002507
16#00002509

Error

Correction

Access is not possible because the area is read-only.

Execute the command again after clearing the write protection.

The data is protected or the data link table cannot be written.

· Execute the command again after clearing the write protection.

· Set the system settings in the data link table.

Registration is not possible.

· Create the file after deleting unnecessary files or prepare new file memory.

· Execute the command again after closing open files.

The relevant program number does not exist. Set a valid program number.

The relevant file does not exist.

Set the file name correctly, including the subdirectory names.

A file with the same name already exists.

Execute the command again after changing the name of the file to write.

The change is not possible because an error Correct the settings. occurred when trying to make it.

The operation was not possible because a protocol macros is already in execution.

Use an N.C. program input for the Protocol Macro Execution Flag.

The operating mode is wrong.

Check the operating mode.

The operating mode is wrong for the instruc- Check the operating mode of the Controller. tion (PROGRAM mode).

The operating mode is wrong for the instruc- Check the operating mode of the Controller. tion (DEBUG mode).

The operating mode is wrong for the instruc- Check the operating mode of the Controller. tion (MONITOR mode).

The operating mode is wrong for the instruc- Check the operating mode of the Controller. tion (RUN mode).

The specified mode is not the polling node. Confirm which node is the polling node of the network.

The operating mode is wrong for the instruc- Check step activation status. tion.

The Unit is busy.

Increase the setting of the number of retries or correct the system so that communications traffic is not concentrated on the relevant Unit.

The file device does not exist.

Insert the media. Or, format the EM.

There is no file memory.

Check the file memory device.

There is no built-in clock.

Check the specifications of the model.

A checksum error occurred in the protocol macro data or the data transfer is not yet completed.

Transfer the protocol macro data from the CXProtocol again.

There is an error in the part of memory for processing.

Transfer the correct data to memory.

The registered I/O Unit configuration does not agree with the physical Unit configuration.

Check the I/O Unit configuration.

There are too many local or remote I/O points.

Set the number of local and remote I/O points correctly.

An error occurred in a data transmission between the CPU Unit and a CPU Bus Unit.

Check the Units and the connecting cables. After removing the error, execute a command to reset the error.

The same rack number, unit number, or I/O Correct the settings so that each number is

address is set more than once.

unique.

An error occurred in a data transmission between the CPU Unit and an I/O Unit.

Check the Units and the connecting cables. After removing the error, execute a command to reset the error.

There is an error in SYSMAC BUS/2 data transmission.

Check the Units and the connecting cables. After removing the error, execute a command to reset the error.

2-1252

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

SerialRcv and SerialRcvNoClear

2 Instruction Descriptions

Value

Error

Correction

16#0000250A

An error occurred in a CPU Bus Unit data transmission.

Check the Units and the connecting cables. After removing the error, execute a command to reset the error.

16#0000250D

The same word setting is used more than once.

Set the I/O words correctly.

16#0000250F There is an error in memory.

· For internal memory, execute the command again after writing the correct data.

· For a Memory Card or EM file memory, execute the expansion memory format command.

16#00002510 The end station setting is wrong.

· If the error cannot be reset with the above

corrections, replace the memory. Set the end station correctly.

2

16#00002601 Protection is already cleared.

You do not need to clear protection.

16#00002602 The password was wrong.

Specify the correct password.

16#00002604 The data is protected.

· Execute the command again after clearing the write protection.

· Wait for the service that is currently in execution to end or stop the service, and then execute the command again.

16#00002605 The service is busy.

Wait for the service that is currently in execution to end or stop the service, and then execute the command again.

16#00002606 The service is stopped.

Execute the relevant service as required.

16#00002607 You do not have the execution right.

· Execute the operation from the node that accessed the data link.

· If the error still occurs after restarting, replace the Controller.

16#00002608 The environment is not set.

Make the necessary settings.

16#00002609 The required items are not set.

Set the required items.

16#0000260A The specified number is already defined.

Execute the command again after changing the specified number to an action or transition number that is not already registered.

16#0000260B The error cannot be reset.

Remove the cause of the error and then execute the error reset command.

16#00003001 You do not have access rights.

Wait for the access right to be cleared and then execute the command again.

16#00004001 The service was interrupted.

Execute the command again after clearing the cause of the service interruption.

Note In addition to the codes in the above table, the values of bits 6, 7, and 15 in the end code can be TRUE. If the value of bit 6 or 7 is TRUE, there is an error in the CPU Unit at the destination. If the value of bit 15 is TRUE, an error occurred during a network relay.

Version Information
A CPU Unit with unit version 1.03 or later, Sysmac Studio version 1.04 or higher, and a Serial Communications Unit with unit version 2.1 or later are required to use the SerialRcvNoClear instruction.

NJ/NX-series Instructions Reference Manual (W502)

2-1253

2 Instruction Descriptions

Sample Programming
In this sample, data that was read by the barcode reader that is connected to serial port 2 of a CJ-series Serial Communications Unit (unit number 0, device name `Barcode') is received. The receive data is stored in array variable RecvDat[]. There is no start code and the end code is 16#OD (CR).
Serial Communications Unit with unit number 0

Serial port 2

Read data received. Barcode reader

The settings of Serial Communications Unit are given in the following table.

Item

Set value

Port 2: User-specified Setting Inclusion Port 2: Serial Communications Mode

User settings No-protocol

Port 2: Data Length

8 bits

Port 2: Stop Bits

1 bit

Port 2: Parity

No

Port 2: Baud Rate

38,400 bps

Port 2: No-Protocol End Code

D

Port 2: No-Protocol Start Code Inclusion Setting

No

Port 2: No-Protocol End Code Inclusion Setting

Yes (Specify a desired end code.)

The number from the barcode reader is separated into individual characters and bit strings for the character codes are stored in RecvDat[]. One element of the RecvDat[] array corresponds to one character from the barcode. First, the AryToString instruction is used to convert the data to a text string (RecvStringDat). Then, the STRING_TO_ULINT instruction is used to convert the data to an ULINT integer (Code).

BYTE array

RecvDat[0] BYTE#16#34 RecvDat[1] BYTE#16#39 RecvDat[2] BYTE#16#30

AryToString

STRING data

RecvStringDat `4901

RecvDat[3] BYTE#16#31

:

:

Definitions of Global Variables

Global Variables

STRING_TO_ULINT

ULNIT data

'

Code ULINT#4901

Name

Data type

AT*1

Comment

Barcode_P2_NopRcvCompleteSta

BOOL

IOBus://rack#0/slot#0/P2_NopSta Reception Completed Flag /P2_NopRcvCompleteSta

*1 AT when the Serial Communications Unit is mounted to slot number 0 in rack number 0.

2-1254

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

SerialRcv and SerialRcvNoClear

2 Instruction Descriptions

LD

Internal Variables

Variable

Data type

Initial value

Comment

OperatingEnd

BOOL

FALSE

Processing completed

Trigger

BOOL

FALSE

Execution condition

Operating

BOOL

FALSE

Processing

InPort

_sPORT

(UnitNo:=_CBU_No00, PhysicPortNo:=0)

Port settings

RecvDat

ARRAY[0..12] OF BYTE [13(16#0)]

Receive data

RecvSize

UINT

0

RecvStringDat

STRING[255]

''

Receive data size

2

Barcode text string

Code

ULINT

0

Barcode integer

RS_instance

RS

SerialRcv_instance SerialRcv

External Variables

Variable

Data type

_Port_isAvailable

BOOL

Barcode_P2_NopRcvCompleteSta

BOOL

Comment Network Communications Instruction Enabled Flag Reception Completed Flag

Determine if execution of the SerialRcv instruction is completed.

SerialRcv_instance.Done

OperatingEnd

SerialRcv_instance.Error

Accept trigger. Trigger _Port_isAvailable Barcode_P2_NopRcvCompleteSta SerialRcv_instance.Busy
OperatingEnd

RS_instance

RS

Set

Q1

Reset1

Operating

Set communications parameters.

Operating

Inline ST

Note: The contents of the inline ST are given below.

Execute SerialRcv instruction.

Operating

SerialRcv_instance SerialRcv

InPort UINT#13
RecvDat[0]

Execute Port Size DstDat

Done Busy Error

ErrorID ErrorIDEx
RcvSize

RecvDat[0] RecvSize

NJ/NX-series Instructions Reference Manual (W502)

2-1255

2 Instruction Descriptions

Processing after normal end Operating SerialRcv_instance.Done
RecvDat[0] RecvSize

AryToString

EN

ENO

In

Size

RecvStringDat

RecvStringDat

STRING_TO_ULINT

EN

ENO

In

Code

Processing after error end Operating SerialRcv_instance.Error

Inline ST 1 // Processing after normal end 2 ;
Inline ST 1 // Processing after error end 2 ;

Contents of Inline ST

InPort.UnitNo

:=_CBU_No00;

InPort.PhysicPortNo:=USINT#2;

// Serial Communications Unit with unit number 0 // Serial port 2

2-1256

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Serial Communications Instructions

SerialRcv and SerialRcvNoClear

ST

Internal Variables

Variable

Data type

Initial value

Comment

Trigger

BOOL

FALSE

Execution condition

LastTrigger

BOOL

FALSE

Value of Trigger from previous task period

OperatingStart

BOOL

FALSE

Processing started

Operating

BOOL

FALSE

Processing

(UnitNo:=_CBU_-

InPort

_sPORT

No00, Phys-

Port settings

icPortNo:=0)

RecvDat

ARRAY[0..12] OF BYTE [13(16#0)]

Receive data

2

RecvSize

UINT

0

Receive data size

RecvStringDat

STRING[255]

''

Barcode text string

Code

ULINT

0

Barcode integer

SerialRcv_instance SerialRcv

External Variables

Variable

Data type

_Port_isAvailable

BOOL

Barcode_P2_NopRcvCompleteSta

BOOL

Comment Network Communications Instruction Enabled Flag Reception Completed Flag

// Detect when Trigger changes to TRUE. IF ( (Trigger=TRUE) AND (LastTrigger=FALSE) AND (_Port_isAvailable=TRUE)
AND (Barcode_P2_NopRcvCompleteSta=TRUE) AND (SerialRcv_instance.Busy=FALSE) ) THEN OperatingStart:=TRUE; Operating :=TRUE; END_IF; LastTrigger:=Trigger;

// Set communications parameters and initialize SerialRcv instruction.

IF (OperatingStart=TRUE) THEN

SerialRcv_instance(

Execute:=FALSE,

// Initialize instance.

Port :=InPort, // Port settings

Size :=UINT#13, // Receive data size

DstDat :=RecvDat[0], // Receive data

RcvSize=>RecvSize); // Data size that was actually received

InPort.UnitNo

:=_CBU_No00; // Serial Communications Unit with unit number 0

InPort.PhysicPortNo :=USINT#2; // Serial port 2

OperatingStart

:=FALSE;

END_IF;

// Execute SerialRcv instruction. IF (Operating=TRUE) THEN
SerialRcv_instance( Execute :=TRUE, Port :=InPort, Size :=UINT#13, DstDat :=RecvDat[0], RcvSize =>RecvSize);

IF (SerialRcv_instance.Done=TRUE) THEN

// Processing after normal end

RecvStringDat :=AryToString(In:=RecvDat[0], Size:=RecvSize); // Convert character codes to a text string.

Code

:=STRING_TO_ULINT(RecvStringDat);

// Convert text string to an integer.

Operating :=FALSE;

END_IF;

NJ/NX-series Instructions Reference Manual (W502)

2-1257

2 Instruction Descriptions
IF (SerialRcv_instance.Error=TRUE) THEN // Processing after error end Operating:=FALSE;
END_IF; END_IF;

2-1258

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

SendCmd

2 Instruction Descriptions

SendCmd

The SendCmd instruction uses a serial gateway and sends a command to a Serial Communications Unit. Or, it sends an explicit command to a DeviceNet Unit or CompoNet Master Unit.

Instruction SendCmd

Name
Send Command

FB/ FUN
FB

Graphic expression

SendCmd_instance

SendCmd

Execute

Done

DstNetAdr Busy

CommPort Error

CmdDat ErrorID

CmdSize ErrorIDEx

RespDat

Option

ST expression

SendCmd_instance(Execute,

DstNetAdr, CommPort, CmdDat,

CmdSize, RespDat, Option, Done, Busy, Error, ErrorID, ErrorIDEx);

2

Precautions for Correct Use
You cannot use this instruction in an NX-series CPU Unit to which CJ-series configuration Units cannot be connected.

Variables

Name DstNetAdr
CommPort
CmdDat[] (array) CmdSize

Meaning
Destination network address
Destination serial port
Command array
Command data size

I/O Input

Option
RespDat[] (array)

Response

Response

In-out

storage array

Description Destination network address

Valid range
---

Destination serial port

Only _NONE

Command to send Command data size
Response monitoring and retry specifications Array to store response

Depends on data type. 0 to maximum data length (depends on network type)
---
Depends on data type.

* If you omit an input parameter, the default value is not applied. A building error will occur.

Unit
---
Bytes
-----

Default
---
_NONE
*
2
-----

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

DstNetAdr

CommPort

CmdDat[]

OK

(array)

Refer to Function for details on the structure _sDNET_ADR. Refer to Function for the enumerators of the enumerated type _ePORT.

NJ/NX-series Instructions Reference Manual (W502)

2-1259

2 Instruction Descriptions

numbers REAL

Boolean BOOL

Bit strings

Integers

Real

Times, durations, dates, and text strings

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

CmdSize

Option

RespDat[]

OK

(array)

OK Refer to Function for details on the structure _sRESPONSE.

Function

The SendCmd instruction sends the contents of command array CmdDat[] to the destination specified with destination network address DstNetAdr and destination serial port CommPort. The command data size CmdSize specifies how many elements of CmdDat[] contain the command. The response that is returned is stored in response storage array RespDat[].

The data type of DstNetAdr is structure _sDNET_ADR. The specifications are as follows:

Name DstNetAdr
NetNo NodeNo UnitNo

Meaning
Destination network address
Network address
Node address

Description Destination network address
Network address
Node address

Unit address Unit address

Data type

Valid range

_sDNET_ADR ---

Unit Default
--- ---

USINT USINT BYTE

0 to 127
Depends on data type. Depends on data type.

0
---
16#00

The data type of CommPort is enumerated type _ePORT. The meanings of the enumerators of enumerated type _ePORT are as follows:

Enumerators

Meaning

_NONE

The destination is not a serial port in Host Link Mode.

The data type of Option is structure _sRESPONSE. The specifications are as follows:

Name Option
isNonResp

Meaning Response
No response

Description
Response monitoring and retry specifications
TRUE:Response is not required.

Data type Valid range Unit

_sRESPONSE ---

---

BOOL

---

Default
---
FALSE

TimeOut Retry

Timeout time Retry count

FALSE:Response is required.
Timeout time
0: 2.0 s Retry count

UINT USINT

Depends on data type.
0 to 15

0.1 s Times

20 (2.0 s) 0

If the value of the Response Not Necessary Flag (Option.isNonResp) is FALSE and the response does not return within the value set for the Timeout Time (Option.TimeOut), the command is resent until there is a response. Option.Retry specifies the number of retries. The timeout time is Option.TimeOut multiplied by 0.1 s. However, if the value of Option.TimeOut is 0, the timeout time is 2.0 s. The default value of Option.TimeOut is 2.0 s. No responses are received for broadcast data. Also, the command is not resent.

2-1260

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

SendCmd

2 Instruction Descriptions

Related System-defined Variables

Name _Port_numUsingPort _Port_isAvailable

Meaning
Number of Used Ports
Network Communications Instruction Enabled Flag

Description This is the number of ports that are currently used. TRUE: A port is available. FALSE: A port is not available.

Additional Information
· The command or response is sometimes lost during communications due to noise or other factors. 2
You can increase reliability by setting Option.Retry to a value higher than 0 to perform retry processing when a response is not returned. · To specify a serial port with the serial gateway function, specify the unit address of the serial port for DstNetAdr.UnitNo. The unit addresses of the ports on Serial Communications Units are as follows: · Port 1
Unit address = BYTE#16#80 + BYTE#16#04 × unit number (hex)
Example for Unit Number 1 BYTE#16#80+BYTE#16#04 × 1 = BYTE#16#84 · Port 2 Unit address = BYTE#16#81 + BYTE#16#04 × unit number (hex)
Example for Unit Number 2 BYTE#16#81+BYTE#16#04 × 2 = BYTE#16#89

Precautions for Correct Use
· The instruction is executed only when there is an available port. Therefore, use the system-defined variable _Port_isAvailable (Network Communications Instruction Enabled Flag) in an N.O. execution condition for the instruction.
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· If the instruction is used in ST, make sure that the instruction is processed each task period as long as instruction execution continues. Otherwise, normal processing is sometimes not possible.
· The command is not sent if the value of CmdSize is 0. When the instruction is executed, the value of Done changes to TRUE.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error. · An error occurs in the following cases. Error will change to TRUE.
· The value of CommPort is outside of the valid range. · The value of a member of DstNetAdr is outside of the valid range. · The value of CmdSize is outside of the valid range. · The value of a member of Option is outside of the valid range. · The value of CmdSize exceeds the size of CmdDat[]. · The response size exceeds the size of RespDat[]. · The value of _Port_isAvailable is FALSE. · Communications fail.

NJ/NX-series Instructions Reference Manual (W502)

2-1261

2 Instruction Descriptions

· For this instruction, expansion error code ErrorIDEx gives the communications response code. The values and meanings are listed in the following table. An expansion error code is output to ErrorIDEx when the value of error code ErrorID is WORD#16#0800.

Value 16#00000001
16#00000101 16#00000102 16#00000103 16#00000104
16#00000105 16#00000106 16#00000201 16#00000202 16#00000203
16#00000204
16#00000205 16#00000206
16#00000301 16#00000302 16#00000303
16#00000304 16#00000401 16#00000402 16#00000501 16#00000502 16#00000503 16#00000504
16#00001001 16#00001002

Error The communications service was interrupted.
The local node is not part of the network. A token timeout occurred.
The retry count was exceeded.
The allowable number of send frames was exceeded.
The IP address of the local node is out of range. The IP address of the local node is also used by another node in the network. The remote node is not part of the network. A Unit with the specified unit address does not exist at the destination. The third node is not part of the network.
The remote node is busy.
A response timeout occurred.
There is an error in the transmission path.
A Communications Controller Error occurred.
There is an error in the CPU Unit at the remote node. There is an error in the relevant Controller and a response is not returned.
The unit number setting is not correct.
The command that was sent is not supported. The Unit model or version is not supported. The remote address setting is wrong.
Routing tables are not registered.
There is an error in the routing tables. There are too many relay points.
The command is too long. The command is too short.

Correction
· Check the data link execution status.
· Check the capacity of the transfer destination area on the third node.
Make the local node part of the network.
Set the local node address to within the maximum node address.
Perform internode tests. If communications is not normal, check the operating environment.
Check the status of events in the network and reduce the number of events in each task period. Or, increase the number of allowable send frames.
Set the rotary switches on the Serial Communications Unit correctly.
Change one of the node addresses that are duplicated.
Make the remote node part of the network.
Correctly set the unit address for the destination network address.
· Check the address of the Unit that is the third node.
· Specify only one node for the third node.
Increase the setting of the number of retries or correct the system so that communications traffic is not concentrated on the remote node.
Check the settings of the communications parameters.
· Attempt retries.
· If this error occurs frequently, check for noise.
Refer to the operation manual for the relevant Unit and make suitable corrections.
Refer to the manual for the CPU Unit at the remote node and remove the error.
Check the communications status on the network and restart the relevant Controller. If the error still occurs, replace the relevant Controller.
Set the rotary switches on the Serial Communications Unit correctly.
Set the command array correctly.
Check the Unit model and version.
Set the destination address in the routing tables.
Set the source node, destination node, and relay nodes in the routing tables.
Correct the settings in the routing tables.
Restructure the networks or correct the routing tables so that commands are used within a three-layer range.
Set the command array correctly.
Set the command array correctly.

2-1262

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Serial Communications Instructions

SendCmd

Value

Error

Correction

16#00001003

The number of write elements that is speci- Specify the same number of write elements fied in the command does not agree with the and write data. number of write data.

16#00001004 The command format is incorrect.

Set the command array correctly.

16#00001005 There is an error in the header.

Correct the settings in the routing tables.

16#00001101 The area type does not exist.

Refer to the command variables and parameter type codes and set the relevant codes.

16#00001102 An access size is wrong.

Correctly set the variable and parameter access sizes.

16#00001103 An out-of-range address was specified.

Specify an address that is within the process range.

16#00001104 The address range was exceeded.

· Specify an address that is within the process

2

range.

· Correct the settings in the data link table.

16#00001106

A communications sequence number that is Correct the communications sequence num-

not registered was specified.

ber or add the sequence with the CX-Protocol.

16#00001109 An interrelationship error occurred.

· Correct the size relationships in the command data.

· Correct the settings in the data link table.

16#0000110A Data is redundant.

· Cancel the current process or wait for it to be completed before you execute the command.

· Correct the settings in the data link table.

16#0000110B The response is too long.

Set the number of elements in the command array correctly.

16#0000110C This is another parameter error.

Set the command array correctly.

16#00002002 The data is protected.

Execute the command again after clearing the protection.

16#00002003 There is no registered table.

Set the table correctly.

16#00002004

There is no data that matches the search data.

Set the search data correctly.

16#00002005 The relevant program number does not exist. Set a valid program number.

16#00002006 The relevant file does not exist.

Set the file name correctly, including the subdirectory names.

16#00002007 A verification error occurred.

· Check the contents of memory and write the correct data.

· Check the contents of the file.

16#00002101

Access is not possible because the area is read-only.

Execute the command again after clearing the write protection.

16#00002102

The data is protected or the data link table cannot be written.

· Execute the command again after clearing the write protection.

· Set the system settings in the data link table.

16#00002103 Registration is not possible.

· Create the file after deleting unnecessary files or prepare new file memory.

· Execute the command again after closing open files.

16#00002105 The relevant program number does not exist. Set a valid program number.

16#00002106 The relevant file does not exist.

Set the file name correctly, including the subdirectory names.

16#00002107 A file with the same name already exists.

Execute the command again after changing the name of the file to write.

16#00002108

The change is not possible because an error Correct the settings. occurred when trying to make it.

16#00002201

The operation was not possible because a protocol macros is already in execution.

Use an N.C. program input for the Protocol Macro Execution Flag.

16#00002202 The operating mode is wrong.

Check the operating mode.

NJ/NX-series Instructions Reference Manual (W502)

2-1263

2 Instruction Descriptions

Value 16#00002203 16#00002204 16#00002205 16#00002206 16#00002207 16#00002208 16#00002211
16#00002301 16#00002302 16#00002303 16#00002401
16#00002502 16#00002503
16#00002504 16#00002505
16#00002506 16#00002507
16#00002509
16#0000250A
16#0000250D 16#0000250F
16#00002510 16#00002601 16#00002602

Error The operating mode is wrong for the instruction (PROGRAM mode). The operating mode is wrong for the instruction (DEBUG mode). The operating mode is wrong for the instruction (MONITOR mode). The operating mode is wrong for the instruction (RUN mode). The specified mode is not the polling node.
The operating mode is wrong for the instruction. The Unit is busy.
The file device does not exist. There is no file memory. There is no built-in clock. A checksum error occurred in the protocol macro data or the data transfer is not yet completed. There is an error in the part of memory for processing. The registered I/O Unit configuration does not agree with the physical Unit configuration. There are too many local or remote I/O points. An error occurred in a data transmission between the CPU Unit and a CPU Bus Unit.
The same rack number, unit number, or I/O address is set more than once. An error occurred in a data transmission between the CPU Unit and an I/O Unit.
There is an error in SYSMAC BUS/2 data transmission.
An error occurred in a CPU Bus Unit data transmission.
The same word setting is used more than once. There is an error in memory.
The end station setting is wrong. Protection is already cleared. The password was wrong.

Correction Check the operating mode of the Controller.
Check the operating mode of the Controller.
Check the operating mode of the Controller.
Check the operating mode of the Controller.
Confirm which node is the polling node of the network. Check step activation status.
Increase the setting of the number of retries or correct the system so that communications traffic is not concentrated on the relevant Unit. Insert the media. Or, format the EM. Check the file memory device. Check the specifications of the model. Transfer the protocol macro data from the CXProtocol again.
Transfer the correct data to memory.
Check the I/O Unit configuration.
Set the number of local and remote I/O points correctly. Check the Units and the connecting cables. After removing the error, execute a command to reset the error. Correct the settings so that each number is unique. Check the Units and the connecting cables. After removing the error, execute a command to reset the error. Check the Units and the connecting cables. After removing the error, execute a command to reset the error. Check the Units and the connecting cables. After removing the error, execute a command to reset the error. Set the I/O words correctly.
· For internal memory, execute the command again after writing the correct data.
· For a Memory Card or EM file memory, execute the expansion memory format command.
· If the error cannot be reset with the above corrections, replace the memory.
Set the end station correctly. You do not need to clear protection. Specify the correct password.

2-1264

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

2 Instruction Descriptions

Value

Error

Correction

16#00002604 The data is protected.

· Execute the command again after clearing the write protection.

· Wait for the service that is currently in execution to end or stop the service, and then execute the command again.

16#00002605 The service is busy.

Wait for the service that is currently in execution to end or stop the service, and then execute the command again.

16#00002606 The service is stopped.

Execute the relevant service as required.

16#00002607 You do not have the execution right.

· Execute the operation from the node that accessed the data link.

· If the error still occurs after restarting, replace the Controller.

2

16#00002608 The environment is not set.

Make the necessary settings.

16#00002609 The required items are not set.

Set the required items.

16#0000260A The specified number is already defined.

Execute the command again after changing the specified number to an action or transition number that is not already registered.

16#0000260B The error cannot be reset.

Remove the cause of the error and then execute the error reset command.

16#00003001 You do not have access rights.

Wait for the access right to be cleared and then execute the command again.

16#00004001 The service was interrupted.

Execute the command again after clearing the cause of the service interruption.

Note In addition to the codes in the above table, the values of bits 6, 7, and 15 in the end code can be TRUE. If the value of bit 6 or 7 is TRUE, there is an error in the CPU Unit at the destination. If the value of bit 15 is TRUE, an error occurred during a network relay.

SendCmd

NJ/NX-series Instructions Reference Manual (W502)

2-1265

2 Instruction Descriptions

Sample Programming

In this sample, the SendCmd instruction sends an explicit message via a DeviceNet Unit. This sample reads the vendor ID from the slave with node address 16#0B through the DeviceNet Unit with unit address 16#10.
The following communications specifications are used.

Item

Description

Unit address of DeviceNet Unit Slave node address

16#10 16#0B

Service code

16#0E

Class ID

1

Instance ID

1

Attribute ID

1

Timeout time

2.0 s

Retry count

2

DeviceNet Unit with unit number 0 (unit address 16#10)

Explicit message

Slave with node address 16#0B
The contents of command array SendDat[] and response storage array RecvDat[] are as follows: Command Array: BYTE array

Array element SendDat[0] SendDat[1] SendDat[2] SendDat[3]

Item
Command code
Slave node address Service code

SendDat[4] SendDat[5] SendDat[6] SendDat[7] SendDat[8]

Class ID Instance ID Attribute ID

Content
The command code to send an explicit message is 16#2801.
The node address is 16#0B. The service code to read the value of a specified attribute (Get Attribute Single) is 16#0E.
The class ID of the Identity object is 16#0001.
---
The attribute ID of the vendor ID (Vendor ID) is 16#01.

Value BYTE#16#28 BYTE#16#01 BYTE#16#0B BYTE#16#0E
BYTE#16#00 BYTE#16#01 BYTE#16#00 BYTE#16#01 BYTE#16#01

Response Storage Array: BYTE Array

Array element RecvDat[0] RecvDat[1]

Item Command code

Content
The command code to send an explicit message is 16#2801.

2-1266

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

SendCmd

2 Instruction Descriptions

Array element RecvDat[2] RecvDat[3] RecvDat[4] RecvDat[5] RecvDat[6] RecvDat[7] RecvDat[8] RecvDat[9]

Item
Completion code
Number of bytes received after the slave node address Slave node address Service code
Vendor ID

Content The completion code is 16#0000 for a normal end.
4 bytes The node address is 16#0B for a normal end. The service code for a normal end is 16#8E. Slave vendor ID.

Definitions of Global Variables

Global Variables Name

Data type

AT*1

2
Comment

DeviceNet_OnlineSta

BOOL

IOBus://rack#0/slot#0/Unit2Sta /OnlineSta

Online

*1 AT when the Serial Communications Unit is mounted to slot number 0 in rack number 0.

LD
Internal Variables

Variable
OperatingEnd Trigger Operating

InDNetAdr

InOption
SendDat RecvDat RS_instance SendCmd_instance

Data type

Initial value

BOOL BOOL BOOL
_sDNET_ADR
_sRESPONSE
ARRAY[0..8] OF BYTE ARRAY[0..9] OF BYTE RS SendCmd

FALSE
FALSE
FALSE
(NetNo:=0, NodeNo:=0, UnitNo:=16#0)
(isNonResp:=FALSE, TimeOut:=0, Retry:=0)
[9(16#0)]
[10(16#0)]

Comment
Processing completed Execution condition Processing Destination network address
Response
Send data Receive data

External Variables

Variable _Port_isAvailable

Data type BOOL

Comment Network Communications Instruction Enabled Flag

NJ/NX-series Instructions Reference Manual (W502)

2-1267

2 Instruction Descriptions

Determine if execution of the SendCmd instruction is completed.

SendCmd_instance.Done

OperatingEnd

SendCmd_instance.Error

Accept trigger. Trigger _Port_isAvailable DeviceNet_OnlineSta

OperatingEnd

RS_instance

RS

Set

Q1

Reset1

Operating

Set communications parameters.

Operating

Inline ST

Note: The contents of the inline ST are given below.

Execute SendCmd instruction.

SendCmd_instance

Operating

SendCmd

InDNetAdr _NONE
SendDat[0] UINT#9
RecvDat[0] InOption

Execute

Done

DstNetAdr

Busy

CommPort Error

CmdDat

ErrorID

CmdSize ErrorIDEx

RespDat

Option

2-1268

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

2 Instruction Descriptions

Processing after normal end

Operating

SendCmd_instance.Done

Inline ST
1 // Processing after normal end 2 ;

Processing after error end

Operating

SendCmd_instance.Error

Inline ST

1 // Processing after error end

2 ;
2

Contents of Inline ST

InDNetAdr.NetNo :=USINT#0;

InDNetAdr.NodeNo :=USINT#0;

InDNetAdr.UnitNo :=BYTE#16#10;

InOption.isNonResp :=FALSE;

InOption.TimeOut :=UINT#20;

InOption.Retry

:=USINT#2;

SendDat[0]

:=BYTE#16#28;

SendDat[1]

:=BYTE#16#01;

SendDat[2]

:=BYTE#16#0B;

SendDat[3]

:=BYTE#16#0E;

SendDat[4]

:=BYTE#16#00;

SendDat[5]

:=BYTE#16#01;

SendDat[6]

:=BYTE#16#00;

SendDat[7]

:=BYTE#16#01;

SendDat[8]

:=BYTE#16#01;

// Set network address. // Set response. // Set command array.

SendCmd

NJ/NX-series Instructions Reference Manual (W502)

2-1269

2 Instruction Descriptions

ST
Internal Variables

Variable Trigger

LastTrigger

OperatingStart Operating

InDNetAdr

InOption
SendDat RecvDat SendCmd_instance

Data type

Initial value

Comment

BOOL BOOL BOOL BOOL
_sDNET_ADR
_sRESPONSE ARRAY[0..8] OF BYTE ARRAY[0..9] OF BYTE SendCmd

FALSE
FALSE
FALSE FALSE (NetNo:=0, NodeNo:=0, UnitNo:=16#0) (isNonResp:=FALSE, TimeOut:=0, Retry:=0) [9(16#0)] [10(16#0)]

Execution condition Value of Trigger from previous task period Processing started Processing
Destination network address
Response Send data Receive data

External Variables

Variable
DeviceNet_OnlineSta _Port_isAvailable

Data type
BOOL BOOL

Comment
Online Network Communications Instruction Enabled Flag

// Detect when Trigger changes to TRUE.

IF ( (Trigger=TRUE) AND (LastTrigger=FALSE) AND (_Port_isAvailable=TRUE)

AND (DeviceNet_OnlineSta=TRUE) ) THEN

OperatingStart:=TRUE;

Operating

:=TRUE;

END_IF;

LastTrigger:=Trigger;

// Set communications parameters and initialize SendCmd instruction.

IF (OperatingStart=TRUE) THEN

SendCmd_instance(

Execute :=FALSE,

DstNetAdr:=InDNetAdr,

CommPort :=_NONE,

CmdDat :=SendDat[0],

CmdSize :=UINT#9,

RespDat :=RecvDat[0],

Option :=InOption);

InDNetAdr.NetNo :=USINT#0;

// Set network address.

InDNetAdr.NodeNo :=USINT#0;

InDNetAdr.UnitNo :=BYTE#16#10;

InOption.isNonResp:=FALSE;

// Set response.

InOption.TimeOut :=UINT#20;

InOption.Retry :=USINT#2;

SendDat[0]

:=BYTE#16#28; // Set command array.

SendDat[1]

:=BYTE#16#01;

SendDat[2]

:=BYTE#16#0B;

SendDat[3]

:=BYTE#16#0E;

SendDat[4]

:=BYTE#16#00;

SendDat[5]

:=BYTE#16#01;

SendDat[6]

:=BYTE#16#00;

SendDat[7]

:=BYTE#16#01;

SendDat[8]

:=BYTE#16#01;

OperatingStart :=FALSE;

END_IF;

// Execute SendCmd instruction. IF (Operating=TRUE) THEN

2-1270

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

SendCmd_instance( Execute :=TRUE, DstNetAdr:=InDNetAdr, CommPort :=_NONE, CmdDat :=SendDat[0], CmdSize :=UINT#9, RespDat :=RecvDat[0], Option :=InOption);
IF (SendCmd_instance.Done=TRUE) THEN // Processing after normal end Operating:=FALSE;
END_IF;
IF (SendCmd_instance.Error=TRUE) THEN // Processing after error end Operating:=FALSE;
END_IF; END_IF;

2 Instruction Descriptions
2

SendCmd

NJ/NX-series Instructions Reference Manual (W502)

2-1271

2 Instruction Descriptions

NX_SerialSend

The NX_SerialSend instruction sends data in No-protocol Mode from a serial port on an NX-series Communications Interface Unit or Option Board.

Instruction

Name

FB/ FUN

NX_SerialSend

Send No-protocol Data

FB

Graphic expression

NX_SerialSend_instance

NX_SerialSend

Execute

Done

DevicePort

Busy

SendDat

CommandAborted

SendSize

Error

SendCfg

ErrorID

Option

Abort

ST expression
NX_SerialSend_instance( Execute, DevicePort, SendDat, SendSize, SendCfg, Option, Abort, Done, Busy, CommandAborted, Error, ErrorID);

Version Information
A CPU Unit with unit version 1.11 or later and Sysmac Studio version 1.15 or higher are required to use this instruction.

Variables

Name

Meaning

I/O

Description

Valid range

DevicePort Device port

Object that represents a device port

---

SendDat[] (array)

Send data array

Send data array

Depends on data type.

SendSize SendCfg

Send data size
Conditions attached to send data

Input

Send data size

0 to 4096

Conditions attached to send data ---

Option

Option

Option

---

Abort

Interruption

Interruption of instruction execu- Depends on

tion

data type.

CommandAborted

Interruption completion

Output

Interruption completion

Depends on data type.

*1 If you omit an input parameter, the default value is not applied. A building error will occur.

Unit ---
--Bytes -------
---

Default ---
*1 0 ----FALSE
---

2-1272

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Serial Communications Instructions

numbers REAL

Boolean BOOL

NX_SerialSend

Bit strings

Integers

Real

Times, durations, dates, and text strings

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

DevicePort

Refer to Function for details on the structure _sDEVICE_PORT.

SendDat[] (array)

OK

SendSize

OK

SendCfg

Refer to Function for details on the structure _sSERIAL_CFG.

2

Option

Refer to Function for details on the structure _sSERIAL_SEND_OPTION.

Abort

OK

CommandAborted

OK

Function
The NX_SerialSend instruction sends data in No-protocol Mode from the specified port on an NX-series Communications Interface Unit or Option Board.

The data type of the DevicePort input variable is structure _sDEVICE_PORT. The specifications are as follows:

Name DevicePort
DeviceType
NxUnit EcatSlave OptBoard Reserved PortNo

Meaning Device port
Device type
Specified Unit Specified slave Specified Option Board Reserved Port number

Description

Data type

Object that represents a device port

_sDEVICE_PORT

Type of the device to specify

_eDEVICE_TYPE

NX Unit to control
EtherCAT slave to control
Option Board to control
Reserved
Port number 1: Port 1 2: Port 2

_sNXUNIT_ID _sECAT_ID _sOPTBOARD_ID Reserved
USINT

Valid range
---
_DeviceNXUnit _DeviceEcatSlave _DeviceOptionBoard ---
---
---
---
Depends on data type.

Unit Default --- ---
--- ---
--- ----- ----- ----- ----- ---

Use DeviceType to specify the device type. Set this to _DeviceNXUnit for an NX Unit and _DeviceOptionBoard for an Option Board. The variable used to specify the device is determined by the specified device type.
To specify an NX Unit, use NxUnit to specify the device.
In this case, EcatSlave and OptBoard are not used.
To NxUnit, pass the device variable that is assigned to the node location information on the I/O Map for the device to specify.
To specify an Option Board, use OptBoard to specify the device.

NJ/NX-series Instructions Reference Manual (W502)

2-1273

2 Instruction Descriptions
In this case, NxUnit and EcatSlave are not used. To OptBoard, pass the device variable that is assigned to the node location information on the I/O Map for the device to specify. If you use this instruction, be sure to assign a device variable to the node location information. Do not assign device variables to any I/O ports following the node location information that are indicated by "W" under the R/W column. The figure below is an example of using this instruction for port 1 on an NX-CIF210.
Assign a variable.
Do not assign variables.

Refer to the Sysmac Studio Version 1 Operation Manual (Cat. No. W504-E1-07 or later) for details on assigning a device variable to the node location information.

Use PortNo to specify the port number. 1: Port 1 2: Port 2 For an NX Unit, set this to Port 1 or Port 2. For an Option Board, set this to Port 1.

The data type of DeviceType is enumerated type _eDEVICE_TYPE. The meanings of the enumerators of enumerated type _eDEVICE_TYPE are as follows:

Enumerator _DeviceNXUnit _DeviceEcatSlave _DeviceOptionBoard

Meaning NX Unit is specified. EtherCAT slave is specified. Option Board is specified.

In this instruction, you can specify _DeviceNXUnit or _DeviceOptionBoard.

Data of the size specified with the SendSize input variable is sent from the send data specified with the SendDat input variable. If the value of SendSize is 0, nothing is sent. When the instruction is executed, the value of Done changes to TRUE instead of Busy.

2-1274

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

NX_SerialSend

2 Instruction Descriptions

To attach start and end codes to the send data, set them in the SendCfg input variable.
The data type of the SendCfg input variable is structure _sSERIAL_CFG. The specifications are as follows:

Name

Meaning

Description

Data type

Valid range

Unit

Default

SendCfg

Conditions attached to send data

Conditions attached to send data

_sSERIAL_CFG

---

---

---

_SERIAL_START_NONE

StartTrig

Start code existence

Start code existence

_eSERIAL_STAR T

_SERIAL_START_STARTCODE1
_SERIAL_START_START-

---

_SERIAL_START_NONE

2

CODE2

StartCode Start code Start code BYTE[2] Depends on data type.

---

[2(16#0)]

_SERIAL_END_NONE

EndTrig

End code existence

End code existence

_eSERIAL_END

_SERIAL_END_ENDCODE1
_SERIAL_END_ENDCODE2 --_SERIAL_END_TERMINATION_CHAR

_SERIAL_END_NONE

_SERIAL_END_RCV_SIZE

EndCode End code End code BYTE[2] Depends on data type.

---

[2(16#0)]

RcvSizeCfg

Receive size

Not used in this instruc- UINT tion.

0 to 4096

Bytes 0

The data type of StartTrig is enumerated type _eSERIAL_START. The meanings of the enumerators of enumerated type _eSERIAL_START are as follows:

Enumerator _SERIAL_START_NONE _SERIAL_START_STARTCODE1 _SERIAL_START_STARTCODE2

Meaning None 1-byte code 2-byte code

The data type of EndTrig is enumerated type _eSERIAL_END. The meanings of the enumerators of enumerated type _sSERIAL_END are as follows:

Enumerator _SERIAL_END_NONE _SERIAL_END_ENDCODE1 _SERIAL_END_ENDCODE2 _SERIAL_END_TERMINATION_CHAR _SERIAL_END_RCV_SIZE

Meaning None 1-byte code 2-byte code Termination condition Receive size

Refer to Operation of Start Code and End Code on page 2-1289 for details on the operation of start code and end code.

NJ/NX-series Instructions Reference Manual (W502)

2-1275

2 Instruction Descriptions

To delay data transmission from the Controller to an NX-series Communications Interface Unit, set a delay time in units of 0.01 s with the Option.SendDelay input variable. The data type of the Option input variable is structure _sSERIAL_SEND_OPTION. The specifications are as follows:

Name Option
SendDelay

Meaning

Description

Option

Option

Send delay time

Send delay time

Data type _sSERIAL_SEND_OPTION
UINT

Valid range
---
Depends on data type.

Unit --0.01 s

Default --0

An error occurs if this instruction is executed for Units other than NX-series Communications Interface Units and Option Boards.

Operation of Start Code and End Code
Use SendCfg.StartTrig and SendCfg.EndTrig to specify the conditions of start and end codes that are attached to the send data. If you attach a start or end code to the send data, exclude it from the value set for the SendSize input variable. The operations of StartTrig and EndTrig are given below.

Value of StartTrig _SERIAL_START_NONE _SERIAL_START_STARTCODE1 _SERIAL_START_STARTCODE2

Operation --SendDat is sent with start code attached to its beginning. Example: STX

Value of EndTrig _SERIAL_END_NONE _SERIAL_END_ENDCODE1 _SERIAL_END_ENDCODE2 _SERIAL_END_TERMINATION_CHAR _SERIAL_END_RCV_SIZE

Operation --SendDat is sent with end code attached to its end. Example: ETX Error Error

Interruption of Instruction Execution
If Abort is changed to TRUE during instruction execution, the execution is interrupted. When the instruction execution is interrupted, CommandAborted changes to TRUE. The instruction is interrupted even when the data transmission is in progress. If the change of Abort is too late to interrupt the execution, Done changes to TRUE and the instruction ends normally. If both Abort and Execute are changed to TRUE, CommandAborted changes to TRUE.
The interruption operation only finishes the Busy processing, and it does not clear the send buffer. To clear the buffer, use the NX_SerialBufClear instruction.

2-1276

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

NX_SerialSend

2 Instruction Descriptions

Timing Charts
The following figures show the timing charts.

 Normal end (when SendDelay is 0 (0 s))
The operation is as follows when SendDelay is 0 (0 s).

Execute

TRUE FALSE

Abort

TRUE FALSE

Busy

TRUE FALSE

*2

2

Done

TRUE FALSE

*1

Error

TRUE FALSE

Command TRUE

Aborted FALSE

ErrorID

Cleared to 0. Updated to result. (16#0000: Normal)

*1 Sending processing *2 Sending completed

 Normal end (when SendDelay is 100 (1 s))
The operation is as follows when SendDelay is 100 (1 s).

Execute

TRUE FALSE

Abort

TRUE FALSE

Busy

TRUE FALSE

Done

TRUE FALSE

Error

TRUE FALSE

Command TRUE

Aborted FALSE

ErrorID
*1 The send delay time of 1 s *2 Sending processing *3 Sending completed

*1

*2

Cleared to 0.

*3 Updated to result. (16#0000: Normal)

NJ/NX-series Instructions Reference Manual (W502)

2-1277

2 Instruction Descriptions

 Interruption executed (when Busy is TRUE)
The operation is as follows if Abort is changed to TRUE while Busy is TRUE.

Execute

TRUE FALSE

Abort

TRUE FALSE

Busy

TRUE FALSE

Done

TRUE FALSE

Error

TRUE FALSE

Command TRUE Aborted FALSE

*1 *2

ErrorID

Cleared to 0.

*1 Interruption processing *2 Changes to FALSE after one task period.

 Interruption executed (when Execute is TRUE)
The operation is as follows if both Abort and Execute are changed to TRUE.

Execute

TRUE FALSE

Abort

TRUE FALSE

Busy

TRUE FALSE

Done

TRUE FALSE

Error

TRUE FALSE

Command TRUE

*1

Aborted FALSE

ErrorID

Cleared to 0.

*1 Changes to FALSE after one task period.

Related System-defined Variables

The following device variable name is created automatically for an EtherCAT Coupler Unit whose device name is E001.

Name _PLC_OptBoardSta
_NXB_UnitIOActiveTbl

Meaning Option Board Status
NX Unit I/O Data Active Status

Data type ARRAY[1..2] of _sOPTBOARD_ STA
ARRAY[0..8] OF BOOL

Description
· This stores the status of the Option Board.
· This status tells the NX Units whether I/O data communications can be processed.
· The subscript of the array corresponds to the NX Unit numbers. A subscript of 0 means the NX bus master.

2-1278

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

NX_SerialSend

2 Instruction Descriptions
Precautions for Correct Use
· When Abort remains FALSE, this instruction is executed until the completion of processing even if Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing. If Abort is changed to TRUE during instruction execution, CommandAborted or Done changes to TRUE.
· A compiling error will occur if you use this instruction in an event task. Do not use this instruction in event tasks.
· A CIF Unit Initialized error may occur when the NX-series Communications Interface Unit is restarted. Send or receive the data again, if necessary.
· If you use this instruction, do not assign device variables to any I/O ports that are indicated by "W" 2
under the R/W column on the I/O Map Tab Page in the Sysmac Studio for the applicable NX-series Communications Interface Unit. · An error will occur in the following cases. Error will change to TRUE. · A value that is out of range is set for SendSize, SendCfg.StartTrig, SendCfg.EndTrig, Device-
Port.DevicePortType, or DevicePort.PortNo. · The array variable specified with SendDat is smaller than the size specified with SendSize. · The Unit, Option Board, or port specified with DevicePort does not exist. · The data type of DevicePort is invalid. · If more than 32 instructions from the NX_SerialSend instruction, NX_SerialRcv instruction,
NX_ModbusRtuCmd instruction, NX_ModbusRtuRead instruction, NX_ModbusRtuWrite instruction, NX_SerialSigCtl instruction, NX_SerialSigRead instruction, NX_SerialStatusRead instruction, NX_SerialBufClear instruction, NX_SerialStartMon instruction and NX_SerialStopMon instruction are executed at the same time.
· This instruction is executed with a device port variable that is the same as the one specified for the instruction which is still being executed. In this case, the instruction which is still being executed is one of the followings. The NX_SerialSend instruction, NX_ModbusRtuCmd instruction, NX_ModbusRtuRead instruction, and NX_ModbusWrite instruction.
· This instruction is executed for Units other than NX-series Communications Interface Units and Option Boards.
· The serial communications mode of the specified Option Board is not No-protocol.

NJ/NX-series Instructions Reference Manual (W502)

2-1279

2 Instruction Descriptions
Sample Programming
In this sample, an NX-series Communications Interface Unit (NX-CIF210) is connected to an EtherCAT Coupler Unit (NX-ECC203). The unit number of the NX-CIF210 is set to 1.
Built-in EtherCAT port

EtherCAT Coupler Unit NX-ECC203
NX-series Communications Interface Unit NX-CIF210
A no-protocol command is sent to the barcode reader that is connected to serial port 2 of the NXCIF210. The send command is the scene number acquisition command (@READ).

For the send command, the StringToAry instruction is used to separate the text string `@READ' into individual characters and convert them to the character codes. The character codes are stored in the array elements of SendDat[].

STRING data StringToAry `@READ'

BYTE array
SendDat[0] BYTE#16#40 SendDat[1] BYTE#16#52 SendDat[2] BYTE#16#45 SendDat[3] BYTE#16#41 SendDat[4] BYTE#16#44

There is no start code. End code is 16#OD (CR).

The settings of NX-CIF210 are given in the following table.

Item Port 2: Baud Rate Port 2: Data Length Port 2: Parity Port 2: Stop Bits Port 2: Flow Control

Set value 38,400 bps 8 bits None 1 bit None

2-1280

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

NX_SerialSend

2 Instruction Descriptions

Definitions of Global Variables

Global Variables

Name

Data type

AT

Comment

E001_NX_Unit_I_O_Data_Active_Status_63

ARRAY[0..63] OF BOOL

ECAT://node#1/NX Unit I/O Data Active Status 125

Usage of I/O data for 63 NX Units.

N1_Node_location_information

_sNXUNIT_ID ---

Device variable to specify NX-CIF210*1

*1 On the Sysmac Studio, right-click an NX-series slave terminal unit, select Display Node Location Port, and

set the device variable. Refer to the Sysmac Studio Version 1 Operation Manual (Cat. No. W504-E1-07 or later) for details.

2

LD

Internal Variables

Variable

Data type

OperationEnd BOOL

Trigger Operating DevicePort SendDat SendSize RS_instance NX_SerialSend_instance SendCfg
StartTrig StartCode

BOOL BOOL _sDEVICE_PORT ARRAY [0..5] OF BYTE UINT RS
NX_SerialSend
_sSERIAL_SEND_CFG _eSERIAL_START BYTE[2]

EndTrig

_eSERIAL_END

EndCode

BYTE[2]

Initial value
FALSE FALSE FALSE
[6(16#0)] 0
_SERIAL_START_NONE [2(16#0)] _SERIAL_END_ENDCODE1 [16#0D,16#00]

Comment Processing completed Execution condition Processing Port settings Send data Send data size
Without start code
With end code 16#0D(CR)

External Vari-
ables

Variable

Data type

E001_NX_Unit_I_O_Data_Ac- ARRAY[0..63]

tive_Status_63

OF BOOL

N1_Node_location_information _sNXUNIT_ID

Comment
· Usage of I/O data for 63 NX Units. · If the relevant Unit number is 1, E001_NX-
_Unit_I_O_Data_Active_Status_63[1] is used. Device variable to specify NX-CIF210

NJ/NX-series Instructions Reference Manual (W502)

2-1281

2 Instruction Descriptions

Determine if execution of the NX_SerialSend instruction has ended.

NX_SerialSend_instance.Done

OperatingEnd

NX_SerialSend_instance.Error

Accept trigger. Trigger E001_NX_Unit_I_O_Data_Active_Status_63[1]

OperatingEnd

Set communications parameters.

Operating

Inline ST

Note: The contents of the inline ST are given below.

RS_instance

RS

Set

Q1

Reset1

Operating

Execute NX_SerialSend instruction.

Operating

NX_SerialSend_instance NX_SerialSend

Execute

Done

DevicePort SendDat[0]
SendSize

DevicePort SendDat SendSize

Busy Command
Aborted Error

SendCfg

SendCfg

ErrorID

Option

Abort

Processing after normal end Operating NX_SerialSend_instance.Done
Processing after error end Operating NX_SerialSend_instance.Error

Inline ST 1 // Processing after normal end 2 ;
Inline ST 1 // Processing after error end 2 ;

 Contents of Inline ST
DevicePort.DeviceType:=_eDEVICE_TYPE#_DeviceNXUnit; DevicePort.NxUnit:=N1_Node_location_information; DevicePort.PortNo:=2; StringToAry(In:='@READ', AryOut:=SendDat[0]); SendSize := UINT#10#5;

2-1282

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Serial Communications Instructions

NX_SerialSend

ST

Internal Variables

Variable

Data type

Initial value

Comment

Trigger

BOOL

FALSE

Execution condition

LastTrigger

BOOL

FALSE

Value of Trigger from previous task period

OperatingStart BOOL

FALSE

Processing started

Operating

BOOL

FALSE

Processing

DevicePort

_sDEVICE_PORT

Port settings

SendDat SendSize

ARRAY [0..5] of BYTE UINT

[6(16#0)] 0

Send data

2

Send data size

NX_SerialSend_instance

NX_SerialSend

SendCfg

_sSERIAL_CFG

StartTrig

_eSERIAL_START

_SERIAL_START_NONE

Without start code

StartCode

BYTE[2]

[2(16#0)]

EndTrig

_eSERIAL_END

_SERIAL_END_ENDCODE1 With end code

EndCode

BYTE[2]

[16#0D,16#00]

16#0D(CR)

External Vari-
ables

Variable

Data type

E001_NX_Unit_I_O_Data_Ac- ARRAY[0..63]

tive_Status_63

OF BOOL

N1_Node_location_information _sNXUNIT_ID

Comment
· Usage of I/O data for 63 NX Units. · If the relevant Unit number is 1, E001_NX-
_Unit_I_O_Data_Active_Status_63[1] is used. Device variable to specify NX-CIF210

// Detect when Trigger changes to TRUE. IF ( (Trigger=TRUE) AND (LastTrigger=FALSE)
AND (E001_NX_Unit_I_O_Data_Active_Status_63[1]) AND (NX_SerialSend_instance.Busy=FALSE) ) THEN
OperatingStart:=TRUE; Operating:=TRUE; DevicePort.DeviceType:=_eDEVICE_TYPE#_DeviceNXUnit; DevicePort.NxUnit:=N1_Node_location_information; DevicePort.PortNo:=2; END_IF; LastTrigger:=Trigger;
// Set communications parameters and initialize NX_SerialSend instruction. IF (OperatingStart=TRUE) THEN
NX_SerialSend_instance( Execute:=FALSE, DevicePort:=DevicePort; SendDat:=SendDat[0], SendSize:=UINT#1, SendCfg:=SendCfg);
StringToAry(In:='@READ', AryOut:=SendDat[0]); SendSize:=UINT#10#5; OperatingStart:=FALSE; END_IF;
// Execute NX_SerialSend instruction.

NJ/NX-series Instructions Reference Manual (W502)

2-1283

2 Instruction Descriptions

IF (Operating=TRUE) THEN

NX_SerialSend_instance(

Execute:=TRUE,

DevicePort:=DevicePort, // Port settings

SendDat:=SendDat[0], // Send data

SendSize:=SendSize,

// Send data size

SendCfg:=SendCfg);

// End code settings

IF (NX_SerialSend_instance.Done=TRUE) THEN

// Processing after normal end

Operating:=FALSE; END_IF;

IF (NX_SerialSend_instance.Error=TRUE) THEN // Processing after error end

Operating:=FALSE; END_IF; END_IF;

2-1284

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

NX_SerialRcv

2 Instruction Descriptions

NX_SerialRcv

The NX_SerialRcv instruction reads data in No-protocol Mode from a serial port on an NX-series Communications Interface Unit or Option Board.

Instruction

Name

FB/ FUN

Graphic expression

ST expression

NX_SerialRcv

Receive Noprotocol Data

FB

NX_SerialRcv_instance(

NX_SerialRcv_instance

NX_SerialRcv Execute

Done

DevicePort RcvDat

Busy RcvDat

Execute,

DevicePort,

2

RcvDat,

Size,

RcvCfg,

Option,

Size

CommandAborted

Abort,

RcvCfg

Error

Done,

Option

ErrorID

Busy,

Abort

RcvSize

CommandAborted,

Error,

ErrorID,

RcvSize);

Version Information
A CPU Unit with unit version 1.11 or later and Sysmac Studio version 1.15 or higher are required to use this instruction.

Variables

Name

Meaning

I/O

DevicePort Device port

Size RcvCfg Option

Storage size
Reception completion setting
Option

Input

Abort

Interruption

RcvDat[] (array)

Receive data

CommandAborted

Interruption completion

RcvSize

Receive size

In-out Output

Description Object that represents a device port
Size of RcvDat in bytes

Valid range --1 to 4096

Unit --Bytes

Reception completion setting
Option
Interruption of instruction execution
Variable to store data received from the receive buffer

---

---

---

---

---

---

Depends on data type. ---

Interruption completion

Depends on data type. ---

Size of data actually received from the receive buffer

0 to 4096

Bytes

Default --1 ----FALSE ---
---
---

NJ/NX-series Instructions Reference Manual (W502)

2-1285

2 Instruction Descriptions

numbers REAL

Boolean BOOL

Bit strings

Integers

Real

Times, durations, dates, and text strings

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

DevicePort

Size

RcvCfg

Option

Abort

OK

RcvDat[] (array)

OK

CommandAborted

OK

RcvSize

Refer to Function for details on the structure _sDEVICE_PORT. OK
Refer to Function for details on the structure _sSERIAL_CFG. Refer to Function for details on the structure _sSERIAL_RCV_OPTION.
OK

Function
The NX_SerialRcv instruction reads data in No-protocol Mode from the specified port on an NX-series Communications Interface Unit or Option Board.

The data type of the DevicePort input variable is structure _sDEVICE_PORT. The specifications are as follows:

Name DevicePort
DeviceType
NxUnit EcatSlave OptBoard Reserved PortNo

Meaning Device port
Device type
Specified Unit Specified slave Specified Option Board Reserved
Port number

Description Object that represents a device port
Type of the device to specify
NX Unit to control EtherCAT slave to control
Option Board to control
Reserved Port number 1: Port 1 2: Port 2

Data type _sDEVICE_PORT
_eDEVICE_TYPE
_sNXUNIT_ID _sECAT_ID _sOPTBOAR D_ID Reserved
USINT

Valid range
---
_DeviceNXUnit _DeviceEcatSlave _DeviceOptionBoard ---
---
---
---
Depends on data type.

Unit ---
---
-----------

Default ---
---
-----------

Use DeviceType to specify the device type. Set this to _DeviceNXUnit for an NX Unit and _DeviceOptionBoard for an Option Board. The variable used to specify the device is determined by the specified device type.
To specify an NX Unit, use NxUnit to specify the device.
In this case, EcatSlave and OptBoard are not used.
To NxUnit, pass the device variable that is assigned to the node location information on the I/O Map for the device to specify.

2-1286

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

2 Instruction Descriptions
To specify an Option Board, use OptBoard to specify the device. In this case, NxUnit and EcatSlave are not used. To OptBoard, pass the device variable that is assigned to the node location information on the I/O Map for the device to specify.
If you use this instruction, be sure to assign a device variable to the node location information. Do not assign device variables to any I/O ports following the node location information that are indicated by "W" under the R/W column. The figure below is an example of using this instruction for port 1 on an NX-CIF210.
Assign a variable.
2
Do not assign variables.

NX_SerialRcv

Refer to the Sysmac Studio Version 1 Operation Manual (Cat. No. W504-E1-07 or later) for details on assigning a device variable to the node location information.

Use PortNo to specify the port number. 1: Port 1 2: Port 2 For an NX Unit, set this to Port 1 or Port 2. For an Option Board, set this to Port 1.

The data type of DeviceType is enumerated type _eDEVICE_TYPE. The meanings of the enumerators of enumerated type _eDEVICE_TYPE are as follows:

Enumerator

Meaning

_DeviceNXUnit

NX Unit is specified.

_DeviceEcatSlave

EtherCAT slave is specified.

_DeviceOptionBoard

Option Board is specified.

In this instruction, you can specify _DeviceNXUnit or _DeviceOptionBoard.

First, data received by the Unit is stored in the receive buffer. Use the RcvDat in-out variable to specify the variable to store data received from the receive buffer. Use the Size input variable to set the size of RcvDat in bytes. The RcvSize output variable represents the size of data actually received from the receive buffer.

NJ/NX-series Instructions Reference Manual (W502)

2-1287

2 Instruction Descriptions

When the receive data includes start or end code, you must set the RcvCfg input variable. The data type of RcvCfg input variable is structure _sSERIAL_CFG. The specifications are as follows:

Name RcvCfg
StartTrig StartCode EndTrig EndCode RcvSizeCfg

Meaning
Reception completion setting

Description
Reception completion setting

Start code Start code exisexistence tence

Start code Start code

End code End code exisexistence tence

End code
Receive size

End code
Receive size specified when end code is _SERIAL_END_RCV_ SIZE

Data type _sSERIAL_CFG
_eSERIAL_START BYTE[2]
_eSERIAL_END
BYTE[2]
UINT

Valid range
---
_SERIAL_START_NONE _SERIAL_START_STARTCODE1 _SERIAL_START_STARTCODE2 Depends on data type. _SERIAL_END_NONE _SERIAL_END_ENDCODE1 _SERIAL_END_ENDCODE2 _SERIAL_END_TERMINATION_CHAR _SERIAL_END_RCV_SIZE Depends on data type.
0 to 4,096

Unit ---
--------Bytes

Default
---
_SERIAL_ START_NONE [2(16#0)]
_SERIAL_END_NONE
[2(16#0)]
0

The data type of StartTrig is enumerated type _eSERIAL_START. The meanings of the enumerators of enumerated type _eSERIAL_START are as follows:

Enumerator _SERIAL_START_NONE _SERIAL_START_STARTCODE1 _SERIAL_START_STARTCODE2

Meaning None 1-byte code 2-byte code

The data type of EndTrig is enumerated type _eSERIAL_END. The meanings of the enumerators of enumerated type _eSERIAL_END are as follows:

Enumerator _SERIAL_END_NONE _SERIAL_END_ENDCODE1 _SERIAL_END_ENDCODE2 _SERIAL_END_TERMINATION_CHAR _SERIAL_END_RCV_SIZE

Meaning None 1-byte code 2-byte code Termination condition Receive size

Refer to Operation of Start Code and End Code on page 2-1289 for details on the operation of start code and end code.

2-1288

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

NX_SerialRcv

2 Instruction Descriptions

To set options, use the Option input variable.
The data type of the Option input variable is structure _eSERIAL_RCV_OPTION. The specifications are as follows:

Name

Meaning

Description

Data type

Valid range Unit Default

Option

Option

Option

_sSERIAL_RCV_OP- --TION

--- ---

TimeOut*1

Timeout time Timeout time

UINT

Depends on data type.

0.1 s 20

LastDatRcv (Reserved)
ClearBuf (Reserved)

Last data reception
Receive buffer clear condition

Last data reception
Receive buffer clear condition

BOOL BOOL

FALSE *2

--- FALSE

2

Depends on data type. *3

--- FALSE

*1 An error occurs if the processing does not ends normally within the specified time. If TimeOut is set to 0, the completion of processing will be waited indefinitely.

*2 Always set the value to FALSE.

*3 Receive buffer clear is not executed even if either TRUE or FALSE is specified.

An error occurs if this instruction is executed for Units other than NX-series Communications Interface Units and Option Boards.

Operation of Start Code and End Code
Use the RcvCfg.StartTrig input variable to set the start code condition for the receive data, and use the RcvCfg.EndTrig input variable to set the end code condition for the receive data. The following table shows operation based on combination of StartTrig and EndTrig.

StartTrig _SERIAL_START_NONE

EndTrig _SERIAL_END_NONE
_SERIAL_END_ENDCODE1 _SERIAL_END_ENDCODE2 _SERIAL_END_TERMINATION_CHAR _SERIAL_END_RCV_SIZE

Operation
Data in the receive buffer is received. If there is no receive data in the receive buffer, 0 byte is output to the RcvSize output variable and the receive instruction ends normally.
If this condition is set, the data of the storage size that is remaining in the receive buffer is read.
The following range of data is received from the receive buffer: from the beginning to the end code.
Example: ETX
The following range of data is received from the receive buffer: from the beginning to the data detected as the end. *1
The following range of data is received from the receive buffer: from the beginning to the receive size specified in RcvSizeCfg.
Processing is performed only after the specified amount of data is accumulated in the buffer.

NJ/NX-series Instructions Reference Manual (W502)

2-1289

2 Instruction Descriptions

StartTrig

EndTrig

Operation

_SERIAL_START_STARTCODE1 _SERIAL_START_STARTCODE2

_SERIAL_END_NONE

The following range of data is received from the receive buffer: from the start code to the end of data.

_SERIAL_END_ENDCODE1 _SERIAL_END_ENDCODE2

The following range of data is received from the receive buffer: from the start code to the end code.

Example: ETX

_SERIAL_END_TERMINATION_CHAR

The following range of data is received from the receive buffer: from the start code to the data detected as the end. *1

_SERIAL_END_RCV_SIZE

The following range of data is received from the receive buffer: from the start code to the receive size specified in RcvSize.

Processing is performed only after the specified amount of data is accumulated in the buffer.

*1 If the number of characters detected as the end of data in the Communications Interface Unit is set to 0 (Do not detect the end), reception will continue until the data of the storage size specified in the Size input variable is received.

Precautions for Correct Use
If _SERIAL_END_TERMINATION_CHAR is selected when an Option Board is specified, an error will occur.

Operation When Receive Data Storage Is Insufficient
If the receive data storage specified in the Size input variable is smaller than the received data, operation is performed according to the combination of start and end codes, as shown below.

StartTrig _SERIAL_START_NONE

EndTrig _SERIAL_END_NONE _SERIAL_END_ENDCODE1 _SERIAL_END_ENDCODE2 _SERIAL_END_TERMINATION_CHAR _SERIAL_END_RCV_SIZE

_SERIAL_START_STARTCODE1 _SERIAL_START_STARTCODE2

_SERIAL_END_NONE _SERIAL_END_ENDCODE1 _SERIAL_END_ENDCODE2 _SERIAL_END_TERMINATION_CHAR _SERIAL_END_RCV_SIZE

*1 An error occurs if an Option Board is specified.

Operation Normal end Error end, but data is received. Example: ETX Error end, but data is received.*1
· Error end for an input value check error
· Data cannot be received. Error end, but data is received. Error end, but data is received. Example: ETX Error end, but data is received.*1
· Error end for an input value check error
· Data cannot be received.

Data of the size of the storage RcvDat is received and the rest of data is retained in the receive buffer. The retained data can be received when the next SerialRcv instruction is executed.

2-1290

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

NX_SerialRcv

2 Instruction Descriptions

For example, when 10-byte data exists in the receive buffer and the capacity of the receive data storage RcvDat is 5 bytes, 5-byte data is received and other 5-byte data is retained in the receive buffer. The value of the RcvSize output variable will be 5 bytes, which represents the size of data that is stored.

Receive buffer

Receive data storage RcvDat[ ]

1st byte

Receive processing is performed. 1

2nd byte

2

3rd byte

3

4th byte

4

5th byte

5

6th byte

Cannot be stored in RcvDat. Data ---

2

7th byte

is retained in the receive buffer.

8th byte

Receive processing for the data is performed when the next

9th byte

NX_SerialRcv instruction is exe-

10th byte

cuted.

Interruption of Instruction Execution
If Abort is changed to TRUE during instruction execution, the execution is interrupted. When the instruction execution is interrupted, CommandAborted changes to TRUE. If the change of Abort is too late to interrupt the execution, Done changes to TRUE and the instruction ends normally. If both Abort and Execute are changed to TRUE, CommandAborted changes to TRUE.
This interruption operation only finishes the Busy processing, and it does not clear the receive buffer. To clear the buffer, use the NX_SerialBufClear instruction.

Timing Charts
The following figures show the timing charts.

 Normal end

Execute

TRUE FALSE

Abort

TRUE FALSE

Busy

TRUE FALSE

*2

Done

TRUE FALSE

*1

Error

TRUE FALSE

Command TRUE

Aborted FALSE

ErrorID

Cleared to 0. Updated to result. (16#0000: Normal)

*1 Receive processing *2 Data is received in No-protocol mode.

NJ/NX-series Instructions Reference Manual (W502)

2-1291

2 Instruction Descriptions

 Interruption executed (when Busy is TRUE)
The operation is as follows if Abort is changed to TRUE while Busy is TRUE.

Execute

TRUE FALSE

Abort

TRUE FALSE

Busy

TRUE FALSE

Done

TRUE FALSE

Error

TRUE FALSE

Command TRUE

Aborted FALSE

*1 *2

ErrorID

Cleared to 0.

*1 Interruption processing *2 Changes to FALSE after one task period.

 Interruption executed (when Execute is TRUE)
The operation is as follows if both Abort and Execute are changed to TRUE.

Execute

TRUE FALSE

Abort

TRUE FALSE

Busy

TRUE FALSE

Done

TRUE FALSE

Error

TRUE FALSE

Command TRUE

*1

Aborted FALSE

ErrorID

Cleared to 0.

*1 Changes to FALSE after one task period.

Related System-defined Variables

Name _PLC_OptBoardSta
_NXB_UnitIOActiveTbl

Meaning Option Board Status
NX Unit I/O Data Active Status

Data type ARRAY[1..2] of _sOPTBOARD_ STA
ARRAY[0..8] OF BOOL

Description
· This stores the status of the Option Board.
· This status tells the NX Units whether I/O data communications can be processed.
· The subscript of the array corresponds to the NX Unit numbers. A subscript of 0 means the NX bus master.

2-1292

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

NX_SerialRcv

2 Instruction Descriptions

Precautions for Correct Use

· When Abort remains FALSE, this instruction is executed until the completion of processing even if Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing. If Abort is changed to TRUE during instruction execution, CommandAborted or Done changes to TRUE.

· Data is not received when RcvCfg.EndTrig is _SERIAL_END_RCV_SIZE and the value of the RcvCfg.RcvSizeCfg input variable is 0. In this case, the value of Done changes to TRUE at instruction execution.

· A compiling error will occur if you use this instruction in an event task. Do not use this instruction in

event tasks.

2

· A CIF Unit Initialized error may occur when the NX-series Communications Interface Unit is

restarted. Send or receive the data again, if necessary.

· If you use this instruction, do not assign device variables to any I/O ports that are indicated by "W" under the R/W column on the I/O Map Tab Page in the Sysmac Studio for the applicable NX-series Communications Interface Unit.

· An error will occur in the following cases. Error will change to TRUE.

· A value that is out of range is set for RcvCfg.RcvSizeCfg while RcvCfg.EndTrig is set to _SERIAL_END_RCV_SIZE.

· A value that is out of range is set for Size, DevicePort.DevicePortType or DevicePort.PortNo.

· Option.LastDatRcv is TRUE.

· The array variable specified with the RcvDat in-out variable is smaller than the size specified with the Size input variable.

· The storage size that is specified by Size for saving the data in RcvDat is smaller than the actually received data.

· The Unit, Option Board, or port specified with DevicePort does not exist.

· The data type of DevicePort is invalid.

· _SERIAL_END_TERMINATION_CHAR is selected with RcvCfg.EndTrig when an Option Board is specified with DevicePort.

· If more than 32 instructions from the NX_SerialSend instruction, NX_SerialRcv instruction, NX_ModbusRtuCmd instruction, NX_ModbusRtuRead instruction, NX_ModbusRtuWrite instruction, NX_SerialSigCtl instruction, NX_SerialSigRead instruction, NX_SerialStatusRead instruction, NX_SerialBufClear instruction, NX_SerialStartMon instruction and NX_SerialStopMon instruction are executed at the same time.

· The receive buffer is full.

· This instruction is executed with a device port variable that is the same as the one specified for the instruction which is still being executed. In this case, the instruction which is still being executed is one of the followings. The NX_SerialRcv instruction, NX_ModbusRtuCmd instruction, NX_ModbusRtuRead instruction, and NX_ModbusRtuWrite instruction.

· A parity error occurred in the data received.

· A framing error occurred in the data received.

· An overrun error occurred in the data received.

· Timeout time elapsed.

· This instruction is executed for Units other than NX-series Communications Interface Units and Option Boards.

· The serial communications mode of the specified Option Board is not No-protocol.

NJ/NX-series Instructions Reference Manual (W502)

2-1293

2 Instruction Descriptions
Sample Programming
In this sample, an NX-series Communications Interface Unit (NX-CIF210) is connected to an EtherCAT Coupler Unit (NX-ECC203). The unit number of the NX-CIF210 is set to 1.
Built-in EtherCAT port

EtherCAT Coupler Unit NX-ECC203
NX-series Communications Interface Unit NX-CIF210
Data that was read by the barcode reader which is connected to serial port 2 of the NX-CIF210 is obtained. The receive data is stored in the RecvDat in-out variable. There is no start code. End code is 16#OD (CR).

The settings of NX-CIF210 are given in the following table.

Item Port 2: Baud Rate Port 2: Data Length Port 2: Parity Port 2: Stop Bits Port 2: Flow Control

Set value 38,400 bps 8 bits None 1 bit None

Definitions of Global Variables

Global Variables

Name

Data type

AT

Comment

E001_NX_Unit_I_O_Data_Active_Status_63

ARRAY[0..63] OF BOOL

ECAT://node#1/NX Unit I/O Data Active Status 125

Usage of I/O data for 63 NX Units.

N1_Node_location_information

_sNXUNIT_ID

---

Device variable to specify NX-CIF210*1

*1 On the Sysmac Studio, right-click an NX-series slave terminal unit, select Display Node Location Port, and set the device variable. Refer to the Sysmac Studio Version 1 Operation Manual (Cat. No. W504-E1-07 or later) for details.

2-1294

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

NX_SerialRcv

2 Instruction Descriptions

LD

Internal Variables

Variable

Data type

Initial value

Comment

OperationEnd BOOL

FALSE

Processing completed

Trigger

BOOL

FALSE

Execution condition

Operating

BOOL

FALSE

Processing

DevicePort

_sDEVICE_PORT

Port settings

RecvDat

ARRAY [0..255] of BYTE

[256(16#0)]

Receive data

RecvSize

UINT

0

RecvStringDat STRING[257]

`'

Receive data size

2

Code

ULINT

0

Barcode (integer)

RS_instance

RS

NX_SerialRcv_instance

NX_SerialRcv

RcvCfg

_sSERIAL_CFG

Reception completion setting

StartTrig

_eSERIAL_START

_SERIAL_START_NONE

Without start code

StartCode

BYTE[2]

[2(16#0)]

EndTrig

_eSERIAL_END

_SERIAL_END_ENDCODE1 With end code

EndCode

BYTE[2]

[16#0D,16#00]

16#0D(CR)

RcvSizeCfg

UINT

0

Option

_sSERIAL_RCV_OPTION

Option

TimeOut

TIME

TIME#0s

LastDatRcv

BOOL

FALSE

External Vari-
ables

Variable

Data type

E001_NX_Unit_I_O_Data_Ac- ARRAY[0..63]

tive_Status_63

OF BOOL

N1_Node_location_information _sNXUNIT_ID

Comment
· Usage of I/O data for 63 NX Units. · If the relevant Unit number is 1, E001_NX-
_Unit_I_O_Data_Active_Status_63[1] is used. Device variable to specify NX-CIF210

NJ/NX-series Instructions Reference Manual (W502)

2-1295

2 Instruction Descriptions

Determine if execution of the NX_SerialRcv instruction has ended.

NX_SerialRcv_instance.Done

OperatingEnd

NX_SerialRcv_instance.Error

Accept trigger. Trigger E001_NX_Unit_I_O_Data_Active_Status_63[1]

OperatingEnd

RS_instance

RS

Set

Q1

Reset1

Operating

Inline ST Note: The contents of the inline ST are given below.

Execute NX_SerialRcv instruction.

Operating

NX_SerialRcv_instance NX_SerialRcv

Execute

Done

DevicePort RcvDat[0]

DevicePort RcvDat

Busy RcvDat

UINT#256

Size

CommandAborted

RcvCfg RcvCfg

Error

Option Option

ErrorID

Abort

RcvSize

RecvSize

Processing after normal end Operating NX_SerialRcv_instance.Done
RecvDat[0] RecvSize

AryToString

EN

ENO

In

Size

RecvStringDat

RecvStringDat

STRING_TO_ULINT

EN

ENO

In

Code

Inline ST
1 // Processing after normal end 2 ;

Processing after error end Operating NX_SerialRcv_instance.Error

Inline ST
1 // Processing after error end 2 ;

 Contents of Inline ST
DevicePort.DeviceType:=_eDEVICE_TYPE#_DeviceNXUnit; DevicePort.NxUnit:=N1_Node_location_information; DevicePort.PortNo:=2;

2-1296

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Serial Communications Instructions

NX_SerialRcv

ST

Internal Variables

Variable

Data type

Initial value

Comment

Trigger

BOOL

FALSE

Execution condition

LastTrigger

BOOL

FALSE

Value of Trigger from previous task period

OperatingStart

BOOL

FALSE

Processing started

Operating

BOOL

FALSE

Processing

DevicePort

_sDEVICE_PORT

Port settings

RecvDat

ARRAY [0..255] of BYTE

[256(16#0)]

Receive data

2

RecvSize

UINT

0

Receive data size

RecvStringDat

STRING[257]

`'

Code

ULINT

0

Barcode (integer)

NX_SerialRcv_instance

NX_SerialRcv

RcvCfg

_sSERIAL_CFG

Reception completion setting

StartTrig

_eSERIAL_START

_SERIAL_START_NONE Without start code

StartCode

BYTE[2]

[2(16#0)]

EndTrig

_eSERIAL_END

_SERIAL_END_ENDCODE1

With end code

EndCode

BYTE[2]

[16#0D,16#00]

16#0D(CR)

RcvSizeCfg

UINT

0

Option

_sSERIAL_RCV_OPTION

Option

TimeOut

TIME

TIME#0s

LastDatRcv

BOOL

FALSE

External Vari-
ables

Variable
E001_NX_Unit_I_O_Data_Active_Status_63 N1_Node_location_information

Data type
ARRAY[0..63] OF BOOL
_sNXUNIT_ID

Comment
· Usage of I/O data for 63 NX Units. · If the relevant Unit number is 1, E001_NX_Unit_I_O_-
Data_Active_Status_63[1] is used.
Device variable to specify NX-CIF210

// Detect when Trigger changes to TRUE. IF ( (Trigger=TRUE) AND (LastTrigger=FALSE)
AND(E001_NX_Unit_I_O_Data_Active_Status_63[1]) AND (SerialRcv_instance.Busy=FALSE) ) THEN
OperatingStart:=TRUE; Operating:=TRUE; DevicePort.DeviceType:=_eDEVICE_TYPE#_DeviceNXUnit; DevicePort.NxUnit:=N1_Node_location_information; DevicePort.Port.PortNo:=2; END_IF; LastTrigger:=Trigger;
// Set communications parameters and initialize SerialRcv instruction.
NJ/NX-series Instructions Reference Manual (W502)

2-1297

2 Instruction Descriptions

IF (OperatingStart=TRUE) THEN

NX_SerialRcv_instance(

Execute:=FALSE,

// Initialize instance.

DevicePort:=DevicePort, // Port settings

Size:=UINT#256,,

// Receive data size

RcvDat:=RecvDat,

// Receive data

RcvSize=>RecvSize);

// Data size that was actu-

ally received

OperatingStart:=FALSE;

END_IF;

// Execute NX_SerialRcv instruction.

IF (Operating=TRUE) THEN

NX_SerialRcv_instance(

Execute:=TRUE,

DevicePort:=DevicePort,

Size:=UINT#256,

RcvDat:=RecvDat,

RcvSize=>RecvSize);

IF (NX_SerialRcv_instance.Done=TRUE) THEN

// Processing after normal end

RecvStringDat:=AryToString(In:=RecvDat[0],Size:=RecvSize); // Con-

vert character codes to a text string.

Code:=STRING_TO_ULINT(RecvDat); // Convert text string to an inte-

ger.

END_IF;

Operating:=FALSE; END_IF; IF (NX_SerialRcv_instance.Error=TRUE) THEN
// Processing after error end Operating:=FALSE; END_IF;

2-1298

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Serial Communications Instructions

NX_ModbusRtuCmd

NX_ModbusRtuCmd

The NX_ModbusRtuCmd instruction sends general commands from a serial port on an NX-series Communications Interface Unit or Option Board to Modbus-RTU slaves using Modbus-RTU protocol.

Instruction

Name

FB/ FUN

Graphic expression

ST expression

Send Mod-

NX_ModbusR- bus RTU

tuCmd

General

FB

Command

NX_ModbusRtuCmd_instance(

NX_ModbusRtuCmd_instance NX_ModbusRtuCmd

Execute,

DevicePort, SlaveAdr,

2

Execute

Done

CmdDat,

DevicePort

Busy

CmdSize,

SlaveAdr

CommandAborted

RespDat,

CmdDat

Error

Option,

CmdSize RespDat
Option

ErrorID RespDat
ErrorIDEx

Abort, Done, Busy,

Abort

RespSize

CommandAborted, Error, ErrorID,

ErrorIDEx, RespSize);

Version Information
A CPU Unit with unit version 1.11 or later and Sysmac Studio version 1.15 or higher are required to use this instruction.

Variables

Name

Meaning

I/O

Description

DevicePort Device port

Object that represents a device port

SlaveAdr

Slave address

Address of Modbus-RTU slave*1

CmdDat[] (array)

Command

data

Input

Command data

CmdSize

Command data size

Command data size

Option

Option

Option

Abort

Interruption

Interruption of instruction execution

RespDat[] (array)

Read data

In-out

Variable that stores read data

CommandAborted
RespSize

Interruption completion
Receive size

Output

Interruption completion Receive data size

*1 If 0 is set, you can broadcast commands to Modbus-RTU slaves.

Valid range ---

Unit ---

0 to 247

---

Depends on data type. ---

1 to 253

Bytes

---

---

Depends on data type. ---

Depends on data type. ---

Depends on data type. ---

1 to 253

Bytes

Default --1 *2 *2*3 --FALSE ---
---
*4

NJ/NX-series Instructions Reference Manual (W502)

2-1299

2 Instruction Descriptions

*2 If you omit an input parameter, the default value is not applied. A building error will occur. *3 Set the total number of bytes for the function code and command data. The number of bytes for the function code is one. *4 The total number of bytes for the function code and read data is stored. The number of bytes for the function code is one.

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

DevicePort

SlaveAdr

CmdDat[] (array)

OK

CmdSize

Option

Abort

OK

RespDat[]array

OK

CommandAborted

OK

RespSize

Refer to Function for details on the structure _sDEVICE_PORT. OK OK
Refer to Function for details on the structure _sSERIAL_MODBUSRTU_OPTION.
OK

Function
The NX_ModbusRtuCmd instruction sends general commands from a serial port on an NX-series Communications Interface Unit or Option Board to Modbus-RTU slaves using Modbus-RTU protocol. This instruction ends normally when a normal response to the sent command is received. When a command is broadcasted, this instruction ends normally without waiting for responses from slaves.

The data type of the DevicePort input variable is structure _sDEVICE_PORT. The specifications are as follows:

Name DevicePort
DeviceType
NxUnit EcatSlave OptBoard Reserved PortNo

Meaning Device port

Description

Data type

Object that represents a device port

_sDEVICE_PORT

Device type

Type of the device to specify

_eDEVICE_TYPE

Specified Unit NX Unit to control

Specified slave

EtherCAT slave to control

Specified

Option Board to

Option Board control

Reserved

Reserved

Port number

Port number 1: Port 1

2: Port 2

_sNXUNIT_ID _sECAT_ID _sOPTBOARD_ID Reserved
USINT

Valid range
---
_DeviceNXUnit _DeviceEcatSlave _DeviceOptionBoard ---
---
---
---
Depends on data type.

Unit Default --- ---
--- ---
--- ----- ----- ----- ----- ---

2-1300

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

2 Instruction Descriptions

Use DeviceType to specify the device type. Set this to _DeviceNXUnit for an NX Unit and _DeviceOptionBoard for an Option Board. The variable used to specify the device is determined by the specified device type.

To specify an NX Unit, use NxUnit to specify the device.

In this case, EcatSlave and OptBoard are not used.

To NxUnit, pass the device variable that is assigned to the node location information on the I/O Map for the device to specify.

To specify an Option Board, use OptBoard to specify the device.

In this case, NxUnit and EcatSlave are not used.

To OptBoard, pass the device variable that is assigned to the node location information on the I/O Map

for the device to specify.

2

If you use this instruction, be sure to assign a device variable to the node location information. Do not assign device variables to any I/O ports following the node location information that are indicated by "W" under the R/W column. The figure below is an example of using this instruction for port 1 on an NX-CIF210.
Assign a variable.

Do not assign variables.

NX_ModbusRtuCmd

Refer to the Sysmac Studio Version 1 Operation Manual (Cat. No. W504-E1-07 or later) for details on assigning a device variable to the node location information.

Use PortNo to specify the port number. 1: Port 1 2: Port 2 For an NX Unit, set this to Port 1 or Port 2. For an Option Board, set this to Port 1.

The data type of DeviceType is enumerated type _eDEVICE_TYPE. The meanings of the enumerators of enumerated type _eDEVICE_TYPE are as follows:

Enumerator _DeviceNXUnit _DeviceEcatSlave _DeviceOptionBoard

Meaning NX Unit is specified. EtherCAT slave is specified. Option Board is specified.

In this instruction, you can specify _DeviceNXUnit or _DeviceOptionBoard.

NJ/NX-series Instructions Reference Manual (W502)

2-1301

2 Instruction Descriptions

Use the SlaveAdr input variable to specify the address of a Modbus-RTU slave. To broadcast commands to Modbus-RTU slaves, set the SlaveAdr input variable to 0.

Set the command data with the CmdDat input variable, and set the size of command data with the CmdSize input variable. CRC is attached by the instruction. Use the RespDat in-out variable to specify the variable to store the read data. The RespSize output variable represents the size of received data.

To set options, use the Option input variable.
The data type of the Option input variable is structure _sSERIAL_MODBUSRTU_OPTION. The specifications are as follows:

Name Option
SendDelay TimeOut
NoResponse
Retry

Meaning Option Send delay time Timeout time
No response
Retry count

Description
Option
Send delay time in units of 0.01 s
2.0 s when the timeout time is set to 0
· Set TRUE when no response is waited for the send command.
· If TRUE is set, this instruction sends a command and ends normally without waiting for the elapse of the timeout time.
Retry count

Data type _sSERIAL_MODBUSRTU_OPTION UINT UINT
BOOL
USINT

Valid range --Depends on data type. Depends on data type.
Depends on data type.
0 to 15

Unit Default

---

---

0.01 s 0 0.1 s 20

---

FALSE

---

0

An error occurs if this instruction is executed for Units other than NX-series Communications Interface Units and Option Boards.

Interruption of Instruction Execution
If Abort is changed to TRUE during instruction execution, the execution is interrupted. When the instruction execution is interrupted, CommandAborted changes to TRUE. If the change of Abort is too late to interrupt the execution, Done changes to TRUE and the instruction ends normally. If both Abort and Execute are changed to TRUE, CommandAborted changes to TRUE.
This interruption operation only finishes the Busy processing, and it does not clear the send or receive buffer. To clear the buffer, use the NX_SerialBufClear instruction.

2-1302

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

NX_ModbusRtuCmd

2 Instruction Descriptions

Timing Charts
The following figures show the timing charts.

 Normal end (when SendDelay is 0 (0 s))
The operation is as follows when SendDelay is 0 (0 s).

Execute

TRUE FALSE

Abort

TRUE FALSE

Busy

TRUE FALSE

*2

2

Done

TRUE FALSE

*1

Error

TRUE FALSE

Command TRUE

Aborted FALSE

ErrorID ErrorIDEx

Cleared to 0. Updated to result. (16#0000: Normal)

*1 Processing with Modbus-RTU slave

*2 A response to the command is received.

 Normal end (when SendDelay is 100 (1 s))
The operation is as follows when SendDelay is 100 (1 s).

Execute TRUE FALSE
Abort TRUE FALSE
Busy TRUE FALSE
Done TRUE FALSE
Error TRUE FALSE
Command TRUE Aborted FALSE ErrorID
ErrorIDEx

*3

*1

*2

Cleared to 0.

Updated to result. (16#0000: Normal)

*1 The send delay time of 1 s *2 A command is sent to a Modbus-RTU slave, and a response is received from the Modbus-RTU slave. *3 A response to the command is received.

NJ/NX-series Instructions Reference Manual (W502)

2-1303

2 Instruction Descriptions

 Interruption executed (when Busy is TRUE)
The operation is as follows if Abort is changed to TRUE while Busy is TRUE.

Execute TRUE FALSE
Abort TRUE FALSE
Busy TRUE FALSE
Done TRUE FALSE
Error TRUE FALSE
Command TRUE Aborted FALSE ErrorID
ErrorIDEx

*1 *2 Cleared to 0.

*1 Interruption processing

*2 Changes to FALSE after one task period.

 Interruption executed (when Execute is TRUE)
The operation is as follows if both Abort and Execute are changed to TRUE.

Execute TRUE FALSE
Abort TRUE FALSE
Busy TRUE FALSE
Done TRUE FALSE
Error TRUE FALSE
Command TRUE Aborted FALSE ErrorID
ErrorIDEx

*1 Cleared to 0.

*1 Changes to FALSE after one task period.

Related System-defined Variables

Name _PLC_OptBoardSta
_NXB_UnitIOActiveTbl

Meaning Option Board Status
NX Unit I/O Data Active Status

Data type ARRAY[1..2] of _sOPTBOARD_ STA
ARRAY[0..8] OF BOOL

Description
· This stores the status of the Option Board.
· This status tells the NX Units whether I/O data communications can be processed.
· The subscript of the array corresponds to the NX Unit numbers. A subscript of 0 means the NX bus master.

2-1304

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Serial Communications Instructions

NX_ModbusRtuCmd

Additional Information
The frame format used in Modbus-RTU mode is as follows.

Slaves Function Address Code

Data

CRC

1 byte 1 byte

0 to 252 bytes

2 bytes*

* In CRC code, the low byte comes first, and the high byte comes second.

Refer to the MODBUS Application Protocol Specification for the specifications of the MODBUS communications protocol.

You can obtain MODBUS Application Protocol Specification from Modbus Organization, Inc.

http://www.modbus.org/

2

Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing. If Abort is changed to TRUE during instruction execution, CommandAborted or Done changes to TRUE.
· A compiling error will occur if you use this instruction in an event task. Do not use this instruction in event tasks.
· A CIF Unit Initialized error may occur when the NX-series Communications Interface Unit is restarted. Send or receive the data again, if necessary.
· If you use this instruction, do not assign device variables to any I/O ports that are indicated by "W" under the R/W column on the I/O Map Tab Page in the Sysmac Studio for the applicable NX-series Communications Interface Unit.
· Data may still remain in the buffer of the target device port in the following cases. To clear the buffer, execute the NX_SerialBufClear instruction before executing the following instruction: NX_ModbusRtuCmd instruction, NX_ModbusRtuRead instruction, or NX_ModbusRtuWrite instruction.
· After the operation starts or when you change the operating mode to RUN mode.
· The retry was set (i.e., Option.Retry is not 0) in the previous instruction execution.
· The previous instruction execution is interrupted (i.e., the CommandAborted output variable is TRUE).
· An error occurred (i.e., Error is TRUE) in the previous instruction execution.
· An error will occur in the following cases. Error will change to TRUE.
· A value that is out of range was set for CmdSize, Option.Retry, DevicePort.DevicePortType, DevicePort.PortNo, or SlaveAdr.
· The variable specified with CmdDat is smaller than the size specified with CmdSize.
· The size of the received data is larger than the size of the variable set in RespDat.
· The Unit or port specified with DevicePort does not exist.
· The data type of DevicePort is invalid.
· If more than 32 instructions from the NX_SerialSend instruction, NX_SerialRcv instruction, NX_ModbusRtuCmd instruction, NX_ModbusRtuRead instruction, NX_ModbusRtuWrite instruction, NX_SerialSigCtl instruction, NX_SerialSigRead instruction, NX_SerialStatusRead instruction, NX_SerialBufClear instruction, NX_SerialStartMon instruction and NX_SerialStopMon instruction are executed at the same time.
· This instruction is executed with a device port variable that is the same as the one specified for the instruction which is still being executed. In this case, the instruction which is still being executed is one of the followings. The NX_SerialSend instruction, NX_SerialRcv instruction, NX_ModbusRtuCmd instruction, NX_ModbusRtuRead instruction, and NX_ModbusRtuWrite instruction.
· A parity error occurred in the data received.

NJ/NX-series Instructions Reference Manual (W502)

2-1305

2 Instruction Descriptions
· A framing error occurred in the data received. · An overrun error occurred in the data received. · CRC mismatch occurred for the received data. · Timeout time elapsed. · This instruction is executed for Units other than NX-series Communications Interface Units and
Option Boards. · An Exception Response was received from a Modbus-RTU slave. You can check Exception
Codes with the ErrorIDEx output variable. · There was an invalid function code, receive size, etc. in the response data from a Modbus-RTU
slave. · The serial communications mode of the specified Option Board is not Modbus-RTU master. · In this instruction, the expansion error code ErrorIDEx is displayed when an error is detected in a Modbus-RTU slave. An expansion error code is output to ErrorIDEx when the value of error code ErrorID is WORD#16#0C10. The display format is ErrorIDEx=000000XX. For the value XX, refer to the Exception Code specifications of the MODBUS communications protocol. Refer to the MODBUS Application Protocol Specification for the Exception Code specifications of the MODBUS communications protocol. You can obtain MODBUS Application Protocol Specification from Modbus Organization, Inc. http://www.modbus.org/

2-1306

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

2 Instruction Descriptions
Sample Programming
In this sample, an NX-series Communications Interface Unit (NX-CIF210) is connected to an EtherCAT Coupler Unit (NX-ECC203). The unit number of the NX-CIF210 is set to 1. For the Unit operation settings of the NX-CIF210, set Ch2 Number of Characters to Determine the End to 35. The number of characters is regarded as 3.5 during operation because the unit for setting the Number of Characters to Determine the End is 0.1 character.
2
Built-in EtherCAT port

NX_ModbusRtuCmd

EtherCAT Coupler Unit NX-ECC203
NX-series Communications Interface Unit NX-CIF210
When Trigger changes to TRUE, the instruction clears the buffer of the serial port 2 on the NX-CIF210 and then sends a Modbus-RTU command. It reads a holding register from the read start address 32 (BYTE#16#0020) in slave address 1. General commands are sent/received to read a variable.

Internal Variables

Variable
Stage Trigger DevicePort NX_SerialBufClear_ins tance ClearDone ClearError NX_ModbusRtuCmd_i nstance ModbusSlaveAdr
ModbusCmdDat

Data type
INT BOOL _sDEVICE_PORT
NX_SerialBufClear
BOOL BOOL
NX_ModbusRtuCmd
UINT ARRAY[0..19] OF BYTE

ModbusDatSize

UINT

ModbusRespDat
ModbusDone ModbusCommandAbor ted

ARRAY[0..275] OF BYTE BOOL
BOOL

Initial value 0 FALSE
UINT#0 UINT#0

Comment
Execution condition Port settings Clear buffer
Slave address Modbus command data Modbus command data total size (byte) Received data storage area

NJ/NX-series Instructions Reference Manual (W502)

2-1307

2 Instruction Descriptions

Internal Variables

Variable

ModbusError

ModbusRspSize

DoModbusTrigger

Data type BOOL UINT BOOL

Initial value

Comment

Actually received data size (byte)

External Variables

Variable

N1_Node_location_information

Data type _sNXUNIT_ID

Constant

Comment

// Start sequence when Trigger changes to TRUE. IF (Trigger=TRUE) AND (DoModbusTrigger=FALSE) THEN
DoModbusTrigger := TRUE;

NX_SerialBufClear_instance(Execute := FALSE,

DevicePort:=DevicePort );

NX_ModbusRtuCmd_instance(Execute:= FALSE,

DevicePort:=DevicePort,

CmdDat:=ModbusCmdDat[1],

CmdSize:=ModbusDatSize,

RespDat:=ModbusRespDat[0] );

Stage := 1;

// Initialization completed.

END_IF;

IF (DoModbusTrigger=TRUE) THEN CASE Stage OF 1: // Buffer clear request DevicePort.DeviceType:=_eDEVICE_TYPE#_DeviceNXUnit; DevicePort.NxUnit:=N1_Node_location_information; DevicePort.PortNo:=2;

NX_SerialBufClear_instance(Execute := TRUE, DevicePort:=DevicePort, Done => ClearDone, Error => ClearError);

IF (ClearDone = TRUE) THEN

Stage := 2;

// Buffer clear is normal end.

ELSIF ( ClearError = TRUE ) THEN

Stage := 99;

// Buffer clear is error end.

END_IF;

2: // Modbus Cmd send request ModbusSlaveAdr := 1; ModbusCmdDat[1]:=BYTE#16#03; ModbusCmdDat[2]:=BYTE#16#00; ModbusCmdDat[3]:=BYTE#16#20; ModbusCmdDat[4]:=BYTE#16#00; ModbusCmdDat[5]:=BYTE#16#01; ModbusDatSize:=5;

// Slave address // Function code (read variable) // Read start address (H) // Read start address (L) // Number of data (H) // Number of data (L)

NX_ModbusRtuCmd_instance(Execute:= TRUE, DevicePort:=DevicePort, SlaveAdr:=ModbusSlaveAdr, CmdDat:=ModbusCmdDat[1],

2-1308

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

2 Instruction Descriptions

CmdSize:=ModbusDatSize, RespDat:=ModbusRespDat[0], Done=>ModbusDone, CommandAborted=>ModbusCommandAborted, Error=>ModbusError, RespSize=>ModbusRspSize);

IF (ModbusDone = TRUE) THEN

Stage := 3;

// The NX_ModbusRtuCmd instruction is normal end.

ELSIF (ModbusError=TRUE) OR (ModbusCommandAborted=TRUE) THEN

Stage :=99;

// The NX_ModbusRtuCmd instruction is error end or

Abort.

END_IF;

2

3: // Processing after the NX_ModbusRtuCmd instruction is normal end. Trigger := FALSE; DoModbusTrigger := FALSE;

99: // Error Processing Trigger := FALSE; DoModbusTrigger := FALSE;
END_CASE; END_IF;

NX_ModbusRtuCmd

NJ/NX-series Instructions Reference Manual (W502)

2-1309

2 Instruction Descriptions

NX_ModbusRtuRead

The NX_ModbusRtuRead instruction sends read commands from a serial port on an NX-series Communications Interface Unit or Option Board to Modbus-RTU slaves using Modbus-RTU protocol.

Instruction

Name

FB/ FUN

Send Mod-

NX_ModbusR- bus RTU

tuRead

Read Com-

FB

mand

Graphic expression

NX_ModbusRtuRead_instance

NX_ModbusRtuRead

Execute

Done

DevicePort

Busy

SlaveAdr

CommandAborted

ReadCmd ReadDat

Error ReadDat

Option Abort

ErrorID ErrorIDEx ReadSize

ST expression
NX_ModbusRtuRead_instance( Execute, DevicePort, SlaveAdr, ReadCmd, ReadDat, Option,
Abort, Done, Busy,
CommandAborted, Error, ErrorID, ErrorIDEx, ReadSize);

Version Information
A CPU Unit with unit version 1.11 or later and Sysmac Studio version 1.15 or higher are required to use this instruction.

Variables

Name

Meaning

I/O

Description

Valid range

DevicePort Device port

Object that represents a device port

---

SlaveAdr

Slave address

Address of Modbus-RTU slave*1

1 to 247

ReadCmd

Read com- Input mand

Read command

---

Option

Option

Option

---

Abort

Interruption

Interruption of instruction execution

Depends on data type.

ReadDat[] (array)

Read data

In-out

Variable that stores read data

Depends on data type.

CommandAborted
ReadSize

Interruption completion
Receive size

Output

Interruption completion Receive data size

Depends on data type. 1 to 2,000*3

*1 An error occurs if 0 is set.

*2 If you omit an input parameter, the default value is not applied. A building error will occur.

*3 If receive data is WORD data, the upper limit value is 125.

*4 The unit is the same as the unit of read data specified with ReadCmd.Fun.

Unit -------------
---
---*4

Default --1 *2 --FALSE ---
---
---

2-1310

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Serial Communications Instructions

numbers REAL

Boolean BOOL

NX_ModbusRtuRead

Bit strings

Integers

Real

Times, durations, dates, and text strings

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

DevicePort

Refer to Function for details on the structure _sDEVICE_PORT.

SlaveAdr

OK

ReadCmd

Refer to Function for details on the structure _sSERIAL_MODBUSRTU_READ.

Option

Refer to Function for details on the structure _sSERIAL_MODBUSRTU_OPTION.

2

Abort

OK

ReadDat[] OK

OK

(array)

An array can also be specified.

CommandAborted

OK

ReadSize

OK

Function
The NX_ModbusRtuRead instruction sends read commands from a serial port on an NX-series Communications Interface Unit or Option Board to Modbus-RTU slaves using Modbus-RTU protocol. The requested data is read from the Modbus-RTU slaves. This instruction ends normally when a normal response to the sent command is received.

The data type of the DevicePort input variable is structure _sDEVICE_PORT. The specifications are as follows:

Name DevicePort
DeviceType
NxUnit EcatSlave OptBoard Reserved PortNo

Meaning Device port
Device type
Specified Unit Specified slave Specified Option Board Reserved
Port number

Description Object that represents a device port
Type of the device to specify
NX Unit to control EtherCAT slave to control
Option Board to control
Reserved Port number 1: Port 1 2: Port 2

Data type _sDEVICE_PORT
_eDEVICE_TYPE
_sNXUNIT_ID _sECAT_ID _sOPTBOAR D_ID Reserved
USINT

Valid range
---
_DeviceNXUnit _DeviceEcatSlave _DeviceOptionBoard ---
---
---
---
Depends on data type.

Unit ---
---
-----------

Default ---
---
-----------

Use DeviceType to specify the device type. Set this to _DeviceNXUnit for an NX Unit and _DeviceOptionBoard for an Option Board. The variable used to specify the device is determined by the specified device type.
To specify an NX Unit, use NxUnit to specify the device.
In this case, EcatSlave and OptBoard are not used.

NJ/NX-series Instructions Reference Manual (W502)

2-1311

2 Instruction Descriptions
To NxUnit, pass the device variable that is assigned to the node location information on the I/O Map for the device to specify. To specify an Option Board, use OptBoard to specify the device. In this case, NxUnit and EcatSlave are not used. To OptBoard, pass the device variable that is assigned to the node location information on the I/O Map for the device to specify.
If you use this instruction, be sure to assign a device variable to the node location information. Do not assign device variables to any I/O ports following the node location information that are indicated by "W" under the R/W column. The figure below is an example of using this instruction for port 1 on an NX-CIF210.
Assign a variable.
Do not assign variables.

Refer to the Sysmac Studio Version 1 Operation Manual (Cat. No. W504-E1-07 or later) for details on assigning a device variable to the node location information.

Use PortNo to specify the port number. 1: Port 1 2: Port 2 For an NX Unit, set this to Port 1 or Port 2. For an Option Board, set this to Port 1.

The data type of DeviceType is enumerated type _eDEVICE_TYPE. The meanings of the enumerators of enumerated type _eDEVICE_TYPE are as follows:

Enumerator _DeviceNXUnit _DeviceEcatSlave _DeviceOptionBoard

Meaning NX Unit is specified. EtherCAT slave is specified. Option Board is specified.

In this instruction, you can specify _DeviceNXUnit or _DeviceOptionBoard.

Use the SlaveAdr input variable to specify the address of a Modbus-RTU slave.
If 0 is set for the SlaveAdr input variable, an error occurs and you cannot broadcast commands to Modbus-RTU slaves.

2-1312

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

NX_ModbusRtuRead

2 Instruction Descriptions

Use the ReadCmd input variable to specify the read command.
CRC is attached by the instruction.
The data type of ReadCmd input variable is structure _sSERIAL_MODBUSRTU_READ. The specifications are as follows:

Name

Meaning

Description

Data type

Valid range Unit Default

ReadCmd

Read command

Read command

_sSERIAL_MODBUSR- --TU_READ

--- ---

_MDB_READ_ COILS

_MDB_READ_ DISCRETE_

2

Fun

Function code Function code

INPUTS

_eMDB_FUN

_MDB_READ_ HOLDING_

---

REGISTERS

_MDB_ READ_COILS

_MDB_READ_INPUT_REGISTE RS

ReadAdr

Read address Read start address

UINT

Depends on data type.

--- 0

ReadSize

Read size

Read size

UINT

Depends on function code.

---*1 1

*1 The unit is the same as the unit of read data specified with ReadCmd.Fun.

The data type of Fun is enumerated type _eMDB_FUN. The meanings of the enumerators of enumerated type _eMDB_FUN are as follows:

Enumerator _MDB_READ_COILS _MDB_READ_DISCRETE_INPUTS _MDB_READ_HOLDING_REGISTERS _MDB_READ_INPUT_REGISTERS

Meaning Read outputs (bit) Read inputs (bit) Read holding registers (word) Read input registers (word)

The valid range that you can specify with ReadSize varies depending on the function code. Each value is determined by the size of data that is read and the maximum command length. The specifications are as follows:

Function code _MDB_READ_COILS _MDB_READ_DISCRETE_INPUTS _MDB_READ_HOLDING_REGISTERS _MDB_READ_INPUT_REGISTERS

ReadSize 1 to 2,000 (bit) 1 to 2,000 (bit) 1 to 125 (word) 1 to 125 (word)

Use the ReadDat in-out variable to specify the variable to store the read data. The data type that you can use for ReadDat differs depending on the function code. The specifications are as follows:

NJ/NX-series Instructions Reference Manual (W502)

2-1313

2 Instruction Descriptions

Function code _MDB_READ_COILS _MDB_READ_DISCRETE_INPUTS _MDB_READ_HOLDING_REGISTERS _MDB_READ_INPUT_REGISTERS

Data type BOOL BOOL[] BOOL BOOL[] WORD WORD[] WORD WORD[]

The ReadSize output variable represents the size of data that was read.

To set options, use the Option input variable.
The data type of the Option input variable is structure _sSERIAL_MODBUSRTU_OPTION. The specifications are as follows:

Name Option
SendDelay TimeOut NoResponse Retry

Meaning
Option
Send delay time Timeout time No response Retry count

Description
Option
Send delay time 2.0 s when the timeout time is set to 0 Not used in this instruction. Retry count

Data type _sSERIAL_ MODBUSRTU_ OPTION
UINT
UINT
BOOL
USINT

Valid range
---
Depends on data type. Depends on data type. Depends on data type. 0 to 15

Unit Default

---

---

0.01 s 0

0.1 s 20

---

FALSE

---

0

An error occurs if this instruction is executed for Units other than NX-series Communications Interface Units and Option Boards.

Interruption of Instruction Execution
If Abort is changed to TRUE during instruction execution, the execution is interrupted. When the instruction execution is interrupted, CommandAborted changes to TRUE. If the change of Abort is too late to interrupt the execution, Done changes to TRUE and the instruction ends normally. If both Abort and Execute are changed to TRUE, CommandAborted changes to TRUE.
This interruption operation only finishes the Busy processing for the instruction, and it does not clear the send or receive buffer. To clear the buffer, use the NX_SerialBufClear instruction.

2-1314

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

NX_ModbusRtuRead

2 Instruction Descriptions

Timing Charts
The following figures show the timing charts.

 Normal end (when SendDelay is 0 (0 s))
The operation is as follows when SendDelay is 0 (0 s).

Execute TRUE FALSE

Abort TRUE FALSE

Busy TRUE

*2

FALSE

2

Done TRUE

*1

FALSE

Error TRUE FALSE

Command TRUE

Aborted FALSE

ErrorID

Cleared to 0. Updated to result. (16#0000: Normal)

ErrorIDEx

Cleared to 0. Updated to result. (16#0000 0000: Normal)

*1 Processing with Modbus-RTU slave

*2 A response to the command is received.

 Normal end (when SendDelay is 100 (1 s))
The operation is as follows when SendDelay is 100 (1 s).

Execute TRUE FALSE
Abort TRUE FALSE
Busy TRUE FALSE
Done TRUE FALSE
Error TRUE FALSE
Command TRUE Aborted FALSE
ErrorID

*3

*1

*2

Cleared to 0.

Updated to result. (16#0000: Normal)

ErrorIDEx

Cleared to 0.

Updated to result. (16#0000 0000: Normal)

*1 The send delay time of 1 s

*2 A read command is sent to Modbus-RTU slave, and a response is received from Modbus-RTU slave.

*3 A response to the command is received.

NJ/NX-series Instructions Reference Manual (W502)

2-1315

2 Instruction Descriptions

 Interruption executed (when Busy is TRUE)
The operation is as follows if Abort is changed to TRUE while Busy is TRUE.

Execute

TRUE FALSE

Abort

TRUE FALSE

Busy

TRUE FALSE

Done

TRUE FALSE

Error

TRUE FALSE

Command TRUE

Aborted FALSE

ErrorID

*1 *2 Cleared to 0.

ErrorIDEx

Cleared to 0.

*1 Interruption processing *2 Changes to FALSE after one task period.

 Interruption executed (when Execute is TRUE)
The operation is as follows if both Abort and Execute are changed to TRUE.

Execute

TRUE FALSE

Abort

TRUE FALSE

Busy

TRUE FALSE

Done

TRUE FALSE

Error

TRUE FALSE

Command TRUE

Aborted FALSE

ErrorID

*1 Cleared to 0.

ErrorIDEx

Cleared to 0.

*1 Changes to FALSE after one task period.

Related System-defined Variables

Name _PLC_OptBoardSta
_NXB_UnitIOActiveTbl

Meaning Option Board Status
NX Unit I/O Data Active Status

Data type ARRAY[1..2] of _sOPTBOARD_ STA
ARRAY[0..8] OF BOOL

Description
· This stores the status of the Option Board.
· This status tells the NX Units whether I/O data communications can be processed.
· The subscript of the array corresponds to the NX Unit numbers. A subscript of 0 means the NX bus master.

2-1316

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Serial Communications Instructions

NX_ModbusRtuRead

Additional Information
Refer to the MODBUS Application Protocol Specification for the specifications of the MODBUS communications protocol. You can obtain MODBUS Application Protocol Specification from Modbus Organization, Inc. http://www.modbus.org/

Precautions for Correct Use

· Execution of this instruction is continued until processing is completed even if the value of Execute

changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing. If Abort is

2

changed to TRUE during instruction execution, CommandAborted or Done changes to TRUE.

· A compiling error will occur if you use this instruction in an event task. Do not use this instruction in event tasks.

· A CIF Unit Initialized error may occur when the NX-series Communications Interface Unit is restarted. Send or receive the data again, if necessary.
· If you use this instruction, do not assign device variables to any I/O ports that are indicated by "W" under the R/W column on the I/O Map Tab Page in the Sysmac Studio for the applicable NX-series Communications Interface Unit.
· Data may still remain in the buffer of the target device port in the following cases. To clear the buffer, execute the NX_SerialBufClear instruction before executing the following instruction: NX_ModbusRtuCmd instruction, NX_ModbusRtuRead instruction, or NX_ModbusRtuWrite instruction.

· After the operation starts or when you change the operating mode to RUN mode.

· The retry was set (i.e., Option.Retry is not 0) in the previous instruction execution.

· The previous instruction execution is interrupted (i.e., the CommandAborted output variable is TRUE).
· An error occurred (i.e., Error is TRUE) in the previous instruction execution.
· An error will occur in the following cases. Error will change to TRUE.

· A value that is out of range was set for SlaveAdr, ReadCmd.ReadSize, ReadCmd.Fun, Option.Retry, DevicePort.DevicePortType, or DevicePort.PortNo.

· The variable specified with ReadDat is smaller than the size specified with ReadCmd.ReadSize.

· The Unit or port specified with DevicePort does not exist.

· The data type of DevicePort or RespDat is invalid.

· If more than 32 instructions from the NX_SerialSend instruction, NX_SerialRcv instruction, NX_ModbusRtuCmd instruction, NX_ModbusRtuRead instruction, NX_ModbusRtuWrite instruction, NX_SerialSigCtl instruction, NX_SerialSigRead instruction, NX_SerialStatusRead instruction, NX_SerialBufClear instruction, NX_SerialStartMon instruction and NX_SerialStopMon instruction are executed at the same time.

· This instruction is executed with a device port variable that is the same as the one specified for the instruction which is still being executed. In this case, the instruction which is still being executed is one of the followings. The NX_SerialSend instruction, NX_SerialRcv instruction, NX_ModbusRtuCmd instruction, NX_ModbusRtuRead instruction, and NX_ModbusRtuWrite instruction.
· A parity error occurred in the data received.
· A framing error occurred in the data received.
· An overrun error occurred in the data received.

· CRC mismatch occurred for the received data.

· Timeout time elapsed. (When the retry is set, timeout time is multiplied by the number of retries.)

· This instruction is executed for Units other than NX-series Communications Interface Units and Option Boards.

NJ/NX-series Instructions Reference Manual (W502)

2-1317

2 Instruction Descriptions
· An Exception Response was received from a Modbus-RTU slave. You can check Exception Codes with the ErrorIDEx output variable.
· There was an invalid function code, receive size, etc. in the response data from a Modbus-RTU slave.
· The serial communications mode of the specified Option Board is not Modbus-RTU master. · In this instruction, the expansion error code ErrorIDEx is displayed when an error is detected in a
Modbus-RTU slave. An expansion error code is output to ErrorIDEx when the value of error code ErrorID is WORD#16#0C10. The display format is ErrorIDEx=000000XX. For the value XX, refer to the Exception Code specifications of the MODBUS communications protocol. Refer to the MODBUS Application Protocol Specification for the Exception Code specifications of the MODBUS communications protocol. You can obtain MODBUS Application Protocol Specification from Modbus Organization, Inc. http://www.modbus.org/

2-1318

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

NX_ModbusRtuRead

2 Instruction Descriptions
Sample Programming
In this sample, an NX-series Communications Interface Unit (NX-CIF210) is connected to an EtherCAT Coupler Unit (NX-ECC203). The unit number of the NX-CIF210 is set to 1. For the Unit operation settings of the NX-CIF210, set Ch2 Number of Characters to Determine the End to 35. The number of characters is regarded as 3.5 during operation because the unit for setting the Number of Characters to Determine the End is 0.1 character.
2
Built-in EtherCAT port

EtherCAT Coupler Unit NX-ECC203
NX-series Communications Interface Unit NX-CIF210
When Trigger changes to TRUE, the instruction clears the buffer of the serial port 2 on the NX-CIF210 and then sends a Modbus-RTU command. It reads the status of an output from the read start address 19 in slave address 1. A read command is sent to read a variable.

Internal Variables

Variable
Stage Trigger DevicePort NX_SerialBufClear_inst ance ClearDone ClearError NX_ModbusRtuRead_in stance ModbusSlaveAdr ModbusDone ModbusCommandAbort ed ModbusError

Data type INT BOOL _sDEVICE_PORT
NX_SerialBufClear
BOOL BOOL
NX_ModbusRtuRead
UINT BOOL
BOOL
BOOL

ModbusReadSize

UINT

Initial value 0 FALSE
UINT#0

Comment Execution condition Port settings Clear buffer
Slave address
Actually received data size (byte)

NJ/NX-series Instructions Reference Manual (W502)

2-1319

2 Instruction Descriptions

Internal Variables

Variable
DoModbusTrigger ModbusReadDat

ModbusReadCmd

Data type
BOOL BOOL _sSERIAL_MODBUSR TU_READ

Initial value

External Variables

Variable

N1_Node_location_information

Data type _sNXUNIT_ID

Constant

Comment Comment

// Start sequence when Trigger changes to TRUE. IF (Trigger=TRUE) AND (DoModbusTrigger=FALSE) THEN
DoModbusTrigger := TRUE;

NX_SerialBufClear_instance(Execute := FALSE,

DevicePort:=DevicePort);

NX_ModbusRtuRead_instance(Execute:= FALSE,

DevicePort:=DevicePort,

ReadDat:=ModbusReadDat);

Stage := 1;

// Initialization completed.

END_IF;

IF (DoModbusTrigger=TRUE) THEN CASE Stage OF 1: // Buffer clear request DevicePort.DeviceType:=_eDEVICE_TYPE#_DeviceNXUnit; DevicePort.NxUnit:=N1_Node_location_information; DevicePort.PortNo:=2;

NX_SerialBufClear_instance(Execute := TRUE, DevicePort:=DevicePort, Done => ClearDone, Error => ClearError);

IF (ClearDone = TRUE) THEN

Stage := 2;

// Buffer clear is normal end.

ELSIF (ClearError = TRUE) THEN

Stage := 99;

// Buffer clear is error end.

END_IF;

2: // Modbus read request ModbusSlaveAdr := 1; ModbusReadCmd.Fun:=_MDB_READ_COILS; ModbusReadCmd.ReadAdr:=19; ModbusReadCmd.ReadSize:=1;

// Slave address // Function code // Read address // Read size

NX_ModbusRtuRead_instance(Execute:= TRUE, DevicePort:=DevicePort, SlaveAdr:=ModbusSlaveAdr, ReadCmd:=ModbusReadCmd, ReadDat:=ModbusReadDat, Done=>ModbusDone, CommandAborted=>ModbusCommandAborted, Error=>ModbusError, ReadSize=>ModbusReadSize);

IF (ModbusDone = TRUE) THEN

2-1320

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

2 Instruction Descriptions

Abort.

Stage := 3;

// The NX_ModbusRead instruction is normal end.

ELSIF (ModbusError=TRUE) OR (ModbusCommandAborted=TRUE) THEN

Stage :=99;

// The NX_ModbusRead instruction is error end or

END_IF;

3: // Processing after the NX_ModbusRead instruction is normal end. Trigger := FALSE; DoModbusTrigger := FALSE;

99: // Error Processing

Trigger := FALSE;

DoModbusTrigger := FALSE; END_CASE;

2

END_IF;

NX_ModbusRtuRead

NJ/NX-series Instructions Reference Manual (W502)

2-1321

2 Instruction Descriptions

NX_ModbusRtuWrite

The NX_ModbusRtuWrite instruction sends write commands from a serial port on an NX-series Communications Interface Unit or Option Board to Modbus-RTU slaves using Modbus-RTU protocol.

Instruction

Name

FB/ FUN

Send Mod-

NX_ModbusR- bus RTU

tuWrite

Write Com-

FB

mand

Graphic expression

NX_ModbusRtuWrite_instance

NX_ModbusRtuWrite

Execute

Done

DevicePort

Busy

SlaveAdr

CommandAborted

WriteCmd

Error

WriteDat

ErrorID

Option

ErrorIDEx

Abort

ST expression
NX_ModbusRtuWrite_instance( Execute, DevicePort, SlaveAdr, WriteCmd, WriteDat, Option, Abort, Done, Busy, CommandAborted, Error, ErrorID, ErrorIDEx);

Version Information
A CPU Unit with unit version 1.11 or later and Sysmac Studio version 1.15 or higher are required to use this instruction.

Variables

Name

Meaning

I/O

Description

Valid range

Unit

DevicePort Device port

Object that represents a device port

---

---

SlaveAdr

Slave address

Address of Modbus-RTU slave*1

0 to 247

---

WriteCmd

Write com-

mand

Input

Write command

---

---

WriteDat[] (array)

Write data

Write data

Depends on data type. ---

Option

Option

Option

---

---

Abort

Interruption

Interruption of instruction execution

Depends on data type. ---

CommandAborted

Interruption completion

Output

Interruption completion

Depends on data type. ---

*1 If 0 is set, you can broadcast commands to Modbus-RTU slaves.

*2 If you omit an input parameter, the default value is not applied. A building error will occur.

Default --1 *2 *2 --FALSE
---

2-1322

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Serial Communications Instructions

numbers REAL

Boolean BOOL

NX_ModbusRtuWrite

Bit strings

Integers

Real

Times, durations, dates, and text strings

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

DevicePort

Refer to Function for details on the structure _sDEVICE_PORT.

SlaveAdr

OK

WriteCmd

Refer to Function for details on the structure _sSERIAL_MODBUSRTU_WRITE.

WriteDat[] OK

OK

(array)

An array can also be specified.

2

Option

Refer to Function for details on the structure _sSERIAL_MODBUSRTU_OPTION.

Abort

OK

CommandAborted

OK

Function
The NX_ModbusRtuWrite instruction sends write commands from a serial port on an NX-series Communications Interface Unit or Option Board to Modbus-RTU slaves using Modbus-RTU protocol. This instruction ends normally when a normal response to the sent command is received. When a command is broadcasted, this instruction ends normally without waiting for responses from slaves.

The data type of the DevicePort input variable is structure _sDEVICE_PORT. The specifications are as follows:

Name DevicePort
DeviceType
NxUnit EcatSlave OptBoard Reserved PortNo

Meaning Device port
Device type
Specified Unit Specified slave Specified Option Board Reserved
Port number

Description Object that represents a device port
Type of the device to specify
NX Unit to control EtherCAT slave to control
Option Board to control
Reserved Port number 1: Port 1 2: Port 2

Data type _sDEVICE_PORT
_eDEVICE_TYPE
_sNXUNIT_ID _sECAT_ID _sOPTBOAR D_ID Reserved
USINT

Valid range
---
_DeviceNXUnit _DeviceEcatSlave _DeviceOptionBoard ---
---
---
---
Depends on data type.

Unit ---
---
-----------

Default ---
---
-----------

Use DeviceType to specify the device type. Set this to _DeviceNXUnit for an NX Unit and _DeviceOptionBoard for an Option Board. The variable used to specify the device is determined by the specified device type.
To specify an NX Unit, use NxUnit to specify the device.
In this case, EcatSlave and OptBoard are not used.

NJ/NX-series Instructions Reference Manual (W502)

2-1323

2 Instruction Descriptions
To NxUnit, pass the device variable that is assigned to the node location information on the I/O Map for the device to specify. To specify an Option Board, use OptBoard to specify the device. In this case, NxUnit and EcatSlave are not used. To OptBoard, pass the device variable that is assigned to the node location information on the I/O Map for the device to specify.
If you use this instruction, be sure to assign a device variable to the node location information. Do not assign device variables to any I/O ports following the node location information that are indicated by "W" under the R/W column. The figure below is an example of using this instruction for port 1 on an NX-CIF210.
Assign a variable.
Do not assign variables.

Refer to the Sysmac Studio Version 1 Operation Manual (Cat. No. W504-E1-07 or later) for details on assigning a device variable to the node location information.

Use PortNo to specify the port number. 1: Port 1 2: Port 2 For an NX Unit, set this to Port 1 or Port 2. For an Option Board, set this to Port 1.

The data type of DeviceType is enumerated type _eDEVICE_TYPE. The meanings of the enumerators of enumerated type _eDEVICE_TYPE are as follows:

Enumerator _DeviceNXUnit _DeviceEcatSlave _DeviceOptionBoard

Meaning NX Unit is specified. EtherCAT slave is specified. Option Board is specified.

In this instruction, you can specify _DeviceNXUnit or _DeviceOptionBoard.

Use the SlaveAdr input variable to specify the address of a Modbus-RTU slave. To broadcast commands to Modbus-RTU slaves, set the SlaveAdr input variable to 0. Use the WriteCmd input variable to specify the write command. CRC is attached by the instruction.

2-1324

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

NX_ModbusRtuWrite

2 Instruction Descriptions

The data type of WriteCmd input variable is structure _sSERIAL_MODBUSRTU_WRITE. The specifications are as follows:

Name WriteCmd
Fun
WriteAdr WriteSize

Meaning
Write command

Description Write command

Function code Function code

Write address Write start address

Write size

Write size

Data type

Valid range Unit Default

_sSERIAL_MODBUSR- --TU_WRITE

--- ---

_MDB_WRITE_ SINGLE_COIL

_MDB_

WRITE_SIN-

_MD-

GLE_ _eMDB_FUN REGISTER

B_WRIT

2

--- E_SIN-

_MDB_

GLE_-

WRITE_MULTI-

COIL

PLE_COILS

_MDB_WRITE _MULTIPLE_ REGISTERS

UINT

Depends on data type.

--- 0

UINT

Depends on function code.

---

1

The data type of Fun is enumerated type _eMDB_FUN. The meanings of the enumerators of enumerated type _eMDB_FUN are as follows:

Enumerator _MDB_WRITE_SINGLE_COIL _MDB_WRITE_SINGLE_REGISTER _MDB_WRITE_MULTIPLE_COILS _MDB_WRITE_MULTIPLE_REGISTERS

Meaning Write an output (bit) Write a holding register (word) Write multiple outputs (bit) Write multiple holding registers (word)

The valid range that you can specify with WriteSize varies depending on the function code. Each value is determined by the size of data that is written and the maximum command length. The specifications are as follows:

Function code _MDB_WRITE_SINGLE_COIL _MDB_WRITE_SINGLE_REGISTER _MDB_WRITE_MULTIPLE_COILS _MDB_WRITE_MULTIPLE_REGISTERS

WriteSize 1 (bit) 1 (word) 1 to 1,968 (bit) 1 to 123 (word)

NJ/NX-series Instructions Reference Manual (W502)

2-1325

2 Instruction Descriptions

Use the WriteDat input variable to specify the data to write. The data type that you can use for WriteDat differs depending on the function code. The specifications are as follows:

Function code _MDB_WRITE_SINGLE_COIL _MDB_WRITE_SINGLE_REGISTER _MDB_WRITE_MULTIPLE_COILS _MDB_WRITE_MULTIPLE_REGISTERS

Data type BOOL BOOL[] WORD WORD[] BOOL BOOL[] WORD WORD[]

To set options, use the Option input variable. The specifications are as follows:
The data type of the Option input variable is structure _sSERIAL_MODBUS_OPTION. The specifications are as follows:

Name Option
SendDelay TimeOut NoResponse Retry

Meaning
Option
Send delay time Timeout time No response Retry count

Description
Option
Send delay time 2.0 s when the timeout time is set to 0 Not used in this instruction. Retry count

Data type _sSERIAL_ MODBUSRTU_ OPTION
UINT
UINT
BOOL
USINT

Valid range
---
Depends on data type. Depends on data type. Depends on data type. 0 to 15

Unit Default

---

---

0.01 s 0

0.1 s 20

---

FALSE

---

0

An error occurs if this instruction is executed for Units other than NX-series Communications Interface Units and Option Boards.

Interruption of Instruction Execution
If Abort is changed to TRUE during instruction execution, the execution is interrupted. When the instruction execution is interrupted, CommandAborted changes to TRUE. If the change of Abort is too late to interrupt the execution, Done changes to TRUE and the instruction ends normally. If both Abort and Execute are changed to TRUE, CommandAborted changes to TRUE.
This interruption operation only finishes the Busy processing for the instruction, and it does not clear the send or receive buffer. To clear the buffer, use the NX_SerialBufClear instruction.

2-1326

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

NX_ModbusRtuWrite

2 Instruction Descriptions

Timing Charts
The following figures show the timing charts.

 Normal end (when SendDelay is 0 (0 s))
The operation is as follows when SendDelay is 0 (0 s).

Execute

TRUE FALSE

Abort

TRUE FALSE

Busy

TRUE FALSE

*2

2

Done

TRUE FALSE

*1

Error

TRUE FALSE

Command TRUE

Aborted FALSE

ErrorID

Cleared to 0. Updated to result. (16#0000: Normal)

ErrorIDEx

Cleared to 0. Updated to result. (16#0000 0000: Normal)

*1 Processing with Modbus-RTU slave

*2 A response to the command is received.

 Normal end (when SendDelay is 100 (1 s))
The operation is as follows when SendDelay is 100 (1 s).

Execute

TRUE FALSE

Abort

TRUE FALSE

Busy

TRUE FALSE

Done

TRUE FALSE

Error

TRUE FALSE

Command TRUE

Aborted FALSE

ErrorID

*3

*1

*2

Cleared to 0.

Updated to result. (16#0000: Normal)

ErrorIDEx

Cleared to 0.

Updated to result. (16#0000 0000: Normal)

*1 The send delay time of 1 s

*2 A write command is sent to Modbus-RTU slave, and a response is received from Modbus-RTU slave.

*3 A response to the command is received.

NJ/NX-series Instructions Reference Manual (W502)

2-1327

2 Instruction Descriptions

 Interruption executed (when Busy is TRUE)
The operation is as follows if Abort is changed to TRUE while Busy is TRUE.

Execute

TRUE FALSE

Abort

TRUE FALSE

Busy

TRUE FALSE

Done

TRUE FALSE

Error

TRUE FALSE

Command TRUE

Aborted FALSE

ErrorID

*1 *2 Cleared to 0.

ErrorIDEx

Cleared to 0.

*1 Interruption processing *2 Changes to FALSE after one task period.

 Interruption executed (when Execute is TRUE)
The operation is as follows if both Abort and Execute are changed to TRUE.

Execute TRUE FALSE
Abort TRUE FALSE
Busy TRUE FALSE
Done TRUE FALSE
Error TRUE FALSE
Command TRUE Aborted FALSE
ErrorID

*1 Cleared to 0.

ErrorIDEx

Cleared to 0.

*1 Changes to FALSE after one task period.

Related System-defined Variables

Name _PLC_OptBoardSta
_NXB_UnitIOActiveTbl

Meaning Option Board Status
NX Unit I/O Data Active Status

Data type ARRAY[1..2] of _sOPTBOARD_ STA
ARRAY[0..8] OF BOOL

Description
· This stores the status of the Option Board.
· This status tells the NX Units whether I/O data communications can be processed.
· The subscript of the array corresponds to the NX Unit numbers. A subscript of 0 means the NX bus master.

2-1328

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Serial Communications Instructions

NX_ModbusRtuWrite

Additional Information
Refer to the MODBUS Application Protocol Specification for the specifications of the MODBUS communications protocol. You can obtain MODBUS Application Protocol Specification from Modbus Organization, Inc. http://www.modbus.org/

Precautions for Correct Use

· Execution of this instruction is continued until processing is completed even if the value of Execute

changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing. If Abort is

2

changed to TRUE during instruction execution, CommandAborted or Done changes to TRUE.

· A compiling error will occur if you use this instruction in an event task. Do not use this instruction in event tasks.

· A CIF Unit Initialized error may occur when the NX-series Communications Interface Unit is restarted. Send or receive the data again, if necessary.
· If you use this instruction, do not assign device variables to any I/O ports that are indicated by "W" under the R/W column on the I/O Map Tab Page in the Sysmac Studio for the applicable NX-series Communications Interface Unit.
· Data may still remain in the buffer of the target device port in the following cases. To clear the buffer, execute the NX_SerialBufClear instruction before executing the following instruction: NX_ModbusRtuCmd instruction, NX_ModbusRtuRead instruction, or NX_ModbusRtuWrite instruction.

· After the operation starts or when you change the operating mode to RUN mode.

· The retry was set (i.e., Option.Retry is not 0) in the previous instruction execution.

· The previous instruction execution is interrupted (i.e., the CommandAborted output variable is TRUE).
· An error occurred (i.e., Error is TRUE) in the previous instruction execution.
· An error will occur in the following cases. Error will change to TRUE.

· A value that is out of range was set for SlaveAdr, WriteCmd.Fun, WriteCmd.WriteSize, Option.Retry, DevicePort.DevicePortType, or DevicePort.PortNo.

· The variable specified with WriteDat is smaller than the size specified with WriteCmd.WriteSize.

· The Unit or port specified with DevicePort does not exist.

· The data type of DevicePort or WriteDat is invalid.

· If more than 32 instructions from the NX_SerialSend instruction, NX_SerialRcv instruction, NX_ModbusRtuCmd instruction, NX_ModbusRtuRead instruction, NX_ModbusRtuWrite instruction, NX_SerialSigCtl instruction, NX_SerialSigRead instruction, NX_SerialStatusRead instruction, NX_SerialBufClear instruction, NX_SerialStartMon instruction and NX_SerialStopMon instruction are executed at the same time.

· This instruction is executed with a device port variable that is the same as the one specified for the instruction which is still being executed. In this case, the instruction which is still being executed is one of the followings. The NX_SerialSend instruction, NX_SerialRcv instruction, NX_ModbusRtuCmd instruction, NX_ModbusRtuRead instruction, and NX_ModbusRtuWrite instruction.
· A parity error occurred in the data received.
· A framing error occurred in the data received.
· An overrun error occurred in the data received.

· CRC mismatch occurred for the received data.

· Timeout time elapsed.

· This instruction is executed for Units other than NX-series Communications Interface Units and Option Boards.

NJ/NX-series Instructions Reference Manual (W502)

2-1329

2 Instruction Descriptions
· An Exception Response was received from a Modbus-RTU slave. You can check Exception Codes with the ErrorIDEx output variable.
· There was an invalid function code, receive size, etc. in the response data from a Modbus-RTU slave.
· The serial communications mode of the specified Option Board is not Modbus-RTU master. · In this instruction, the expansion error code ErrorIDEx is displayed when an error is detected in a
Modbus-RTU slave. An expansion error code is output to ErrorIDEx when the value of error code ErrorID is WORD#16#0C10. The display format is ErrorIDEx=000000XX. For the value XX, refer to the Exception Code specifications of the MODBUS communications protocol. Refer to the MODBUS Application Protocol Specification for the Exception Code specifications of the MODBUS communications protocol. You can obtain MODBUS Application Protocol Specification from Modbus Organization, Inc. http://www.modbus.org/

2-1330

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

2 Instruction Descriptions
Sample Programming
In this sample, an NX-series Communications Interface Unit (NX-CIF210) is connected to an EtherCAT Coupler Unit (NX-ECC203). The unit number of the NX-CIF210 is set to 1. For the Unit operation settings of the NX-CIF210, set Ch2 Number of Characters to Determine the End to 35. The number of characters is regarded as 3.5 during operation because the unit for setting the Number of Characters to Determine the End is 0.1 character.
2
Built-in EtherCAT port

NX_ModbusRtuWrite

EtherCAT Coupler Unit NX-ECC203
NX-series Communications Interface Unit NX-CIF210
When Trigger changes to TRUE, the instruction clears the buffer of the serial port 2 on the NX-CIF210 and then sends a Modbus-RTU command. It changes an output from the write start address 149 in slave address 1. Write commands are sent/received to write a variable.

Internal Variables

Variable
Stage Trigger DevicePort NX_SerialBufClear_inst ance ClearDone ClearError NX_ModbusRtuWrite_in stance ModbusSlaveAdr ModbusDone ModbusCommandAbort ed ModbusError DoModbusTrigger ModbusWriteDat
ModbusWriteCmd

Data type
INT BOOL _sDEVICE_PORT
NX_SerialBufClear
BOOL BOOL
NX_ModbusRtuWrite
UINT BOOL
BOOL
BOOL BOOL ARRAY[0..5] OF BOOL _sSERIAL_MODBUSR TU_WRITE

Initial value 0 FALSE
UINT#0
[6(FALSE)]

Comment Execution condition Port settings Clear buffer
Slave address

NJ/NX-series Instructions Reference Manual (W502)

2-1331

2 Instruction Descriptions

External Variables

Variable

N1_Node_location_information

Data type _sNXUNIT_ID

Constant

Comment

// Start sequence when Trigger changes to TRUE. IF (Trigger=TRUE) AND (DoModbusTrigger=FALSE) THEN
DoModbusTrigger := TRUE;

NX_SerialBufClear_instance(Execute := FALSE,

DevicePort:=DevicePort);

NX_ModbusRtuWrite_instance(Execute:= FALSE,

DevicePort:=DevicePort,

WriteDat:=ModbusWriteDat);

Stage := 1;

// Initialization completed.

END_IF;

IF (DoModbusTrigger=TRUE) THEN CASE Stage OF 1: // Buffer clear request DevicePort.DeviceType:=_eDEVICE_TYPE#_DeviceNXUnit; DevicePort.NxUnit:=N1_Node_location_information; DevicePort.PortNo:=2;

NX_SerialBufClear_instance(Execute := TRUE, DevicePort:=DevicePort, Done => ClearDone, Error => ClearError);

IF (ClearDone = TRUE) THEN

Stage := 2;

// Buffer clear is normal end.

ELSIF (ClearError = TRUE) THEN

Stage := 99;

// Buffer clear is error end.

END_IF;

2: /// Modbus write request ModbusSlaveAdr := 1; ModbusWriteCmd.Fun:=_MDB_WRITE_SINGLE_COIL; ModbusWriteCmd.WriteAdr:=149; ModbusWriteCmd.WriteSize:=1;

// Slave address // Function code // Write address // Write size

NX_ModbusRtuWrite_instance(Execute:= TRUE, DevicePort:=DevicePort, SlaveAdr:=ModbusSlaveAdr, WriteCmd:=ModbusWriteCmd, WriteDat:=ModbusWriteDat, Done=>ModbusDone, CommandAborted=>ModbusCommandAborted, Error=>ModbusError);

Abort.

IF (ModbusDone = TRUE) THEN

Stage := 3;

// The NX_ModbusRtuWrite instruction is normal end.

ELSIF (ModbusError=TRUE) OR (ModbusCommandAborted=TRUE) THEN

Stage :=99;

// The NX_ModbusRtuWrite instruction is error end or

END_IF;

3: // Processing after the NX_ModbusRtuWrite instruction is normal end. Trigger := FALSE;

2-1332

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

DoModbusTrigger := FALSE;
99: // Error Processing Trigger := FALSE; DoModbusTrigger := FALSE;
END_CASE; END_IF;

2 Instruction Descriptions
2

NX_ModbusRtuWrite

NJ/NX-series Instructions Reference Manual (W502)

2-1333

2 Instruction Descriptions

NX_SerialSigCtl

The NX_SerialSigCtl instruction turns ON or OFF the ER or RS signal of a serial port on an NX-series Communications Interface Unit or Option Board.

Instruction

Name

FB/ FUN

NX_SerialSigCtl

Serial Con-

trol Signal ON/OFF

FB

Switching

Graphic expression

NX_SerialSigCtl_instance

NX_SerialSigCtl

Execute

Done

DevicePort

Busy

Kind

Error

Sig

ErrorID

TimeOut

ST expression
NX_SerialSigCtl_instance( Execute, DevicePort, Kind, Sig, TimeOut, Done, Busy, Error, ErrorID);

Version Information
A CPU Unit with unit version 1.11 or later and Sysmac Studio version 1.15 or higher are required to use this instruction.

Variables

Name

Meaning

I/O

DevicePort Device port

Kind Sig TimeOut

Signal command
ON/OFF command
Timeout time

Input

Description Object that represents a device port
Signal command
ON/OFF command
2.0 s when the timeout time is set to 0

Valid range

Unit

---

---

_RS_SIG

_ER_SIG*1

---

Depends on data type. ---

Depends on data type. 0.1 s

Default --*2 *2 0

*1 You cannot use _CS_SIG or _DR_SIG. If either of them is specified, an error will occur when the instruction is executed. *2 If you omit an input parameter, the default value is not applied. A building error will occur.

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

DevicePort

Kind

Sig

OK

TimeOut

Refer to Function for details on the structure _sDEVICE_PORT. Refer to Function for the enumerators of the enumerated type _eSERIAL_SIG.
OK

2-1334

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

NX_SerialSigCtl

2 Instruction Descriptions

Function
The NX_SerialSigCtl instruction turns ON or OFF the ER or RS signal of a serial port on an NX-series Communications Interface Unit or Option Board.

The data type of the DevicePort input variable is structure _sDEVICE_PORT. The specifications are as follows:

Name

Meaning

Description

Data type

Valid range Unit Default

DevicePort

Device port

Object that represents a _sDE-

device port

VICE_PORT

---

--- ---

_DeviceNXUnit

2

DeviceType

Device type

Type of the device to specify

_eDEVICE_TYPE

_DeviceEcatSlave

---

---

_DeviceOption-

Board

NxUnit

Specified Unit NX Unit to control

_sNXUNIT_ID ---

--- ---

EcatSlave

Specified slave

EtherCAT slave to control

_sECAT_ID

---

--- ---

OptBoard

Specified Option Board

Option Board to control

_sOPTBOAR D_ID

---

--- ---

Reserved

Reserved

Reserved

Reserved

---

--- ---

PortNo

Port number

Port number 1: Port 1 2: Port 2

USINT

Depends on data type.

--- ---

Use DeviceType to specify the device type. Set this to _DeviceNXUnit for an NX Unit and _DeviceOptionBoard for an Option Board. The variable used to specify the device is determined by the specified device type.
To specify an NX Unit, use NxUnit to specify the device.
In this case, EcatSlave and OptBoard are not used.
To NxUnit, pass the device variable that is assigned to the node location information on the I/O Map for the device to specify.
To specify an Option Board, use OptBoard to specify the device.
In this case, NxUnit and EcatSlave are not used.
To OptBoard, pass the device variable that is assigned to the node location information on the I/O Map for the device to specify.

NJ/NX-series Instructions Reference Manual (W502)

2-1335

2 Instruction Descriptions
If you use this instruction, be sure to assign a device variable to the node location information. Do not assign device variables to any I/O ports following the node location information that are indicated by "W" under the R/W column. The figure below is an example of using this instruction for port 1 on an NX-CIF210.
Assign a variable.
Do not assign variables.

Refer to the Sysmac Studio Version 1 Operation Manual (Cat. No. W504-E1-07 or later) for details on assigning a device variable to the node location information.

Use PortNo to specify the port number. 1: Port 1 2: Port 2 For an NX Unit, set this to Port 1 or Port 2. For an Option Board, set this to Port 1.

The data type of DeviceType is enumerated type _eDEVICE_TYPE. The meanings of the enumerators of enumerated type _eDEVICE_TYPE are as follows:

Enumerator _DeviceNXUnit _DeviceEcatSlave _DeviceOptionBoard

Meaning NX Unit is specified. EtherCAT slave is specified. Option Board is specified.

In this instruction, you can specify _DeviceNXUnit or _DeviceOptionBoard.

Use the Kind input variable to select the ER or RS signal.

When the Sig input variable is TRUE, the ER or RS signal turns ON. When the Sig input variable is FALSE, the ER or RS signal turns OFF.

2-1336

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Serial Communications Instructions

NX_SerialSigCtl

The data type of Kind is enumerated type _eSERIAL_SIG. The meanings of the enumerators of enumerated type _eSERIAL_SIG are as follows:

Enumerator _RS_SIG _ER_SIG _CS_SIG _DR_SIG

Meaning RS signal ER signal CS signal DR signal

An error occurs if this instruction is executed for Units other than NX-series Communications Interface Units and Option Boards.
2 Timing Charts
The following figures show the timing charts.

 Normal end

Execute

TRUE FALSE

Busy

TRUE FALSE

*1

Done

TRUE FALSE

Error

TRUE FALSE

ErrorID

Cleared to 0. Updated to result. (16#0000: Normal)

*1 Signal ON/OFF control is completed.

 Error end

Execute

TRUE FALSE

Busy

TRUE FALSE

Done

TRUE FALSE

Error

TRUE FALSE

ErrorID

Cleared to 0. Updated to result. (16#****: Error)

Related System-defined Variables

Name _PLC_OptBoardSta
_NXB_UnitIOActiveTbl

Meaning Option Board Status
NX Unit I/O Data Active Status

Data type ARRAY[1..2] of _sOPTBOARD_ STA
ARRAY[0..8] OF BOOL

Description
· This stores the status of the Option Board.
· This status tells the NX Units whether I/O data communications can be processed.
· The subscript of the array corresponds to the NX Unit numbers. A subscript of 0 means the NX bus master.

NJ/NX-series Instructions Reference Manual (W502)

2-1337

2 Instruction Descriptions
Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· A compiling error will occur if you use this instruction in an event task. Do not use this instruction in event tasks.
· This instruction does not check the communications protocol and wiring conditions. Check the wiring conditions and communications protocol before you use this instruction.
· A CIF Unit Initialized error may occur when the NX-series Communications Interface Unit is restarted. Send or receive the data again, if necessary.
· If you use this instruction, do not assign device variables to any I/O ports that are indicated by "W" under the R/W column on the I/O Map Tab Page in the Sysmac Studio for the applicable NX-series Communications Interface Unit.
· An error will occur in the following cases. Error will change to TRUE. · A value that is out of range was set for Kind, DevicePort.DevicePortType, or DevicePort.PortNo. · The Unit, Option Board, or port specified with DevicePort does not exist. · If an RS-422A/485 serial port is specified for DevicePort. · When RS/CS flow control is selected for the flow control setting of the NX-series Communications Interface Unit and this instruction sends "RS Signal ON" or "RS Signal OFF". · If more than 32 instructions from the NX_SerialSend instruction, NX_SerialRcv instruction, NX_ModbusRtuCmd instruction, NX_ModbusRtuRead instruction, NX_ModbusRtuWrite instruction, NX_SerialSigCtl instruction, NX_SerialSigRead instruction, NX_SerialStatusRead instruction, NX_SerialBufClear instruction, NX_SerialStartMon instruction and NX_SerialStopMon instruction are executed at the same time.
· This instruction is executed with a device port variable that is the same as the one specified for the instruction which is still being executed. In this case, the instruction which is still being executed is one of the followings. The NX_SerialSigRead instruction, NX_SerialStatusRead instruction, NX_SerialSigCtl instruction, NX_SerialBufClear instruction, NX_SerialStartMon instruction, and NX_SerialStopMon instruction.
· Timeout time elapsed during serial communications. · This instruction is executed for Units other than NX-series Communications Interface Units and
Option Boards. · The serial communications mode of the specified Option Board is not No-protocol or Modbus-
RTU master.

2-1338

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

NX_SerialSigCtl

2 Instruction Descriptions
Sample Programming
In this sample, an NX-series Communications Interface Unit (NX-CIF210) is connected to an EtherCAT Coupler Unit (NX-ECC203). The unit number of the NX-CIF210 is set to 1.

Built-in EtherCAT port
2

EtherCAT Coupler Unit NX-ECC203
NX-series Communications Interface Unit NX-CIF210
The ER signal is turned ON if the SetER signal is turned ON for a no-protocol remote node that is connected to serial port 2 of the NX-CIF210. The ER signal is turned OFF if the ResetER signal is turned ON for the same remote node.

Definitions of Global Variables

Global Variables

Name

Data type

AT

Comment

E001_NX_Unit_I_O_Data_Active_Status_63

ARRAY[0..63] OF BOOL

ECAT://node#1/NX Unit I/O Data Active Status 125

Usage of I/O data for 63 NX Units.

N1_Node_location_information

_sNXUNIT_ID ---

Device variable to specify NX-CIF210*1

*1 On the Sysmac Studio, right-click an NX-series slave terminal unit, select Display Node Location Port, and set the device variable. Refer to the Sysmac Studio Version 1 Operation Manual (Cat. No. W504-E1-07 or later) for details.

NJ/NX-series Instructions Reference Manual (W502)

2-1339

2 Instruction Descriptions

LD

Internal Variables

Variable OperationEnd

SetER

Data type BOOL BOOL

Initial value FALSE FALSE

ResetER

BOOL

FALSE

Operating DevicePort RS_instance

BOOL _sDEVICE_PORT RS

FALSE ---

CfgValue

RS

---

NX_SerialSigCtl_instance

NX_SerialSigCtl

---

Comment
Processing completed ER signal ON execution condition ER signal OFF execution condition Processing Port settings Operating retained Value determined by SetER or ResetER

External Vari-
ables

Variable

Data type

E001_NX_Unit_I_O_Data_Ac- ARRAY[0..63]

tive_Status_63

OF BOOL

N1_Node_location_information _sNXUNIT_ID

Comment
· Usage of I/O data for 63 NX Units. · If the relevant Unit number is 1, E001_NX-
_Unit_I_O_Data_Active_Status_63[1] is used. Device variable to specify NX-CIF210

2-1340

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Serial Communications Instructions

NX_SerialSigCtl

Determine if execution of the NX_SerialSigCtl instruction has ended.

NX_SerialSigCtl_instance.Done

OperationEnd

NX_SerialSigCtl_instance.Error

SetER

E001_NX_Unit_I_O_Data_Active_Status_63[1]

RS_instance RS

Operating

OperationEnd

Set

Q1

Reset1

2

ResetER

Operating

Inline ST Note: The contents of the inline ST are given below.

SetER

ResetER

CfgValue

RS

Set

Q1

Reset1

Execute NX_SerialSigCtl instruction.
Operating
DevicePort _eCIF_SIG#_ER_SIG
CfgValue.Q1

NX_SerialSigCtl_instance

NX_SerialSigCtl

Execute DevicePort Kind Sig TimeOut

Done Busy Error ErrorID

Enter Variable Enter Variable Enter Variable

 Contents of Inline ST
DevicePort.DeviceType:=_eDEVICE_TYPE#_DeviceNXUnit; DevicePort.NxUnit:=N1_Node_location_information; DevicePort.PortNo:=2;

ST

Internal Variables

Variable OperatingStart

SetER

Data type BOOL BOOL

Initial value FALSE FALSE

ResetER

BOOL

FALSE

DevicePort

_sDEVICE_PORT

CfgValue

RS

---

NX_SerialSigCtl_instance

NX_SerialSigCtl

---

Comment
Processing started ER signal ON execution condition ER signal OFF execution condition Port settings Value determined by SetER or ResetER

NJ/NX-series Instructions Reference Manual (W502)

2-1341

2 Instruction Descriptions

External Vari-
ables

Name

Data type

E001_NX_Unit_I_O_Data_Ac- ARRAY[0..63]

tive_Status_63

OF BOOL

N1_Node_location_information _sNXUNIT_ID

Comment
· Usage of I/O data for 63 NX Units. · If the relevant Unit number is 1, E001_NX-
_Unit_I_O_Data_Active_Status_63[1] is used. Device variable to specify NX-CIF210

// Detection of SetER or ResetER IF (NX_SerialSigCtl_instance.Done OR NX_SerialSigCtl_instance.Error) THEN
OperatingStart:=FALSE; ELSE_IF
OperatingStart:=(SetER OR ResetER) AND E001_NX_Unit_I_O_Data_Active_Sta-
tus_63[1] AND NOT(P_FirstRun);
DevicePort.DeviceType:=_eDEVICE_TYPE#_DeviceNXUnit; DevicePort.NxUnit:=N1_Node_location_information; DevicePort.PortNo:=2; END_IF;
// ER signal value is determined. CfgValue(Set:=SetER, Reset1:=ResetER);
// NX_SerialSigCtl instruction is executed. NX_SerialSigCtl_instance(Execute:=OperatingStart,
DevicePort:=DevicePort, Kind:=_eSERIAL_SIG#_SIG_ER, Sig:=CfgValue.Q1);

2-1342

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

NX_SerialSigRead

2 Instruction Descriptions

NX_SerialSigRead

The NX_SerialSigRead instruction reads the CS or DR signal of a serial port on an Option Board.

Instruction

Name

FB/ FUN

Graphic expression

ST expression

NX_SerialSig Read

Read Serial Control Signal

FB

NX_SerialSigRead_instance(

NX_SerialSigRead_instance

Execute, DevicePort,

NX_SerialSigRead

Execute

Done

Kind, TimeOut,

2

DevicePort Kind TimeOut

Busy Error ErrorID
Sig

Done, Busy, Error, ErrorID,

Sig);

Precautions for Correct Use You can use this instruction for an Option Board for the NX1P2 CPU Unit only.

Variables

Name

Meaning

I/O

Description

Valid range

Unit

Default

DevicePort Device port

Object that represents a device port

---

---

---

Kind

Signal command Input

Signal command

_CS_SIG _DR_SIG *1

---

*2

TimeOut

Timeout time

2.0 s when the timeout time is set to 0

Depends on data type.

0.1 s

0

Sig

Signal

Output

Outputs the signal that was Depends on

read.

data type.

---

---

*1 You cannot use _RS_SIG or _ER_SIG. If either of them is specified, an error will occur when the instruction is executed.

*2 If you omit an input parameter, the default value is not applied. A building error will occur.

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

DevicePort

Kind

TimeOut

Sig

OK

Refer to Function for details on the structure _sDEVICE_PORT. Refer to Function for the enumerators of the enumerated type _eSERIAL_SIG.
OK

NJ/NX-series Instructions Reference Manual (W502)

2-1343

2 Instruction Descriptions

Function
The NX_SerialSigRead instruction reads the CS or DR signal of a serial port on an Option Board. If a signal that was read is ON, the Sig output variable is TRUE. If the signal is OFF, Sig is FALSE. The data type of the DevicePort input variable is structure _sDEVICE_PORT. The specifications are as follows:

Name DevicePort
DeviceType
NxUnit EcatSlave OptBoard Reserved PortNo

Meaning Device port
Device type
Specified Unit Specified slave Specified Option Board Reserved Port number

Description
Object that represents a device port

Data type _sDEVICE_PORT

Type of the device to specify

_eDEVICE_TYPE

NX Unit to control
EtherCAT slave to control
Option Board to control
Reserved
Port number 1: Port 1 2: Port 2

_sNXUNIT_ID _sECAT_ID _sOPTBOARD_ID Reserved USINT

Valid range Unit Default

---

--- ---

_DeviceNXUnit

_DeviceEcatSla

ve

--- ---

_DeviceOptionB

oard

---

--- ---

---

--- ---

---
---
Depends on data type.

--- ----- ----- ---

Use DeviceType to specify the device type. For an Option Board, set this to _DeviceOptionBoard. The variable used to specify the device is determined by the specified device type.
To specify an Option Board, use OptBoard to specify the device.
In this case, NxUnit and EcatSlave are not used.
To OptBoard, pass the device variable that is assigned to the node location information on the I/O Map for the device to specify.

2-1344

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

2 Instruction Descriptions
If you use this instruction, be sure to assign a device variable to the node location information. Do not assign device variables to any I/O ports following the node location information that are indicated by "W" under the R/W column. The figure below is an example of using this instruction for port 1 on an NX-CIF210.
Assign a variable.
Do not assign variables.
2

NX_SerialSigRead

Refer to the Sysmac Studio Version 1 Operation Manual (Cat. No. W504-E1-07 or later) for details on assigning a device variable to the node location information.

Use PortNo to specify the port number. 1: Port 1 2: Port 2 For an Option Board, set this to Port 1.

The data type of DeviceType is enumerated type _eDEVICE_TYPE. The meanings of the enumerators of enumerated type _eDEVICE_TYPE are as follows:

Enumerator _DeviceNXUnit _DeviceEcatSlave _DeviceOptionBoard

Meaning NX Unit is specified. EtherCAT slave is specified. Option Board is specified.

In this instruction, you can specify _DeviceOptionBoard.

Use the Kind input variable to select the CS or DR signal.

The data type of Kind is enumerated type _eSERIAL_SIG. The meanings of the enumerators of enumerated type _eSERIAL_SIG are as follows:

Enumerator _RS_SIG _ER_SIG _CS_SIG _DR_SIG

Meaning RS signal ER signal CS signal DR signal

NJ/NX-series Instructions Reference Manual (W502)

2-1345

2 Instruction Descriptions

Timing Charts
The following figures show the timing charts.

 Normal end

Execute

TRUE FALSE

Busy

TRUE FALSE

*1

Done

TRUE FALSE

Error

TRUE FALSE

ErrorID

Cleared to 0. Updated to result. (16#0000: Normal)

*1. Signal reading is completed.

 Error end

Execute Busy Done Error

TRUE FALSE TRUE FALSE TRUE FALSE TRUE FALSE

ErrorID

Cleared to 0. Updated to result. (16#****: Error)

Related System-defined Variables

Name _PLC_OptBoardSta

Meaning Option Board Status

Data type
ARRAY[1..2] of _sOPTBOARD_ STA

Description
· This stores the status of the Option Board.

2-1346

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

NX_SerialSigRead

2 Instruction Descriptions
Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· A compiling error will occur if you use this instruction in an event task. Do not use this instruction in event tasks.
· This instruction does not check the communications protocol and wiring conditions. Check the wiring conditions and communications protocol before you use this instruction.
· A CIF Unit Initialized error may occur when the NX-series Communications Interface Unit is restarted. Send or receive the data again, if necessary.
· If you use this instruction, do not assign device variables to any I/O ports that are indicated by "W" 2
under the R/W column on the I/O Map Tab Page in the Sysmac Studio for the applicable NX-series Communications Interface Unit. · An error will occur in the following cases. Error will change to TRUE. · A value that is out of range was set for Kind, DevicePort.DevicePortType, or DevicePort.PortNo. · The Unit, Option Board, or port specified with DevicePort does not exist. · An RS-422A/485 serial port is specified with DevicePort. · If more than 32 instructions from the NX_SerialSend instruction, NX_SerialRcv instruction,
NX_ModbusRtuCmd instruction, NX_ModbusRtuRead instruction, NX_ModbusRtuWrite instruction, NX_SerialSigCtl instruction, NX_SerialSigRead instruction, NX_SerialStatusRead instruction, NX_SerialBufClear instruction, NX_SerialStartMon instruction and NX_SerialStopMon instruction are executed at the same time. · This instruction is executed with a device port variable that is the same as the one specified for the instruction which is still being executed. In this case, the instruction which is still being executed is one of the followings. The NX_SerialSigCtl instruction, NX_SerialSigRead instruction, NX_SerialStatusRead instruction, NX_SerialBufClear instruction, NX_SerialStartMon instruction, and NX_SerialStopMon instruction. · Timeout time elapsed during serial communications. · The instruction is executed for other than Option Boards. · The serial communications mode of the specified Option Board is not No-protocol or ModbusRTU master.
Sample Programming
Refer to the sample programming for NX_SerialSigCtl on page 2-1334.

NJ/NX-series Instructions Reference Manual (W502)

2-1347

2 Instruction Descriptions

NX_SerialStatusRead

The NX_SerialStatusRead instruction reads the status of a serial port on an Option Board.

Instruction

Name

FB/ FUN

NX_SerialStatu Read Serial

sRead

Port Status

FB

Graphic expression

NX_SerialStatusRead_instance

NX_SerialStatusRead

Execute

Done

DevicePort

Busy

TimeOut

Error

ErrorID

PortStatus

ST expression
NX_SerialStatusRead_instance( Execute, DevicePort, TimeOut, Done, Busy, Error, ErrorID, PortStatus);

Precautions for Correct Use You can use this instruction for an Option Board for the NX1P2 CPU Unit only.

Variables

Name DevicePort

Meaning Device port

TimeOut

Timeout time

PortStatus Port status

I/O Input Output

Description
Object that represents a device port
2.0 s when the timeout time is set to 0
Outputs the port status that was read.

Valid range
---
Depends on data type.
---

Unit --0.1 s ---

Default --0 ---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

DevicePort TimeOut PortStatus

Refer to Function for details on the structure _sDEVICE_PORT. OK
Refer to Function for details on the structure _sSERIAL_PORT_STATUS.

Function
The NX_SerialStatusRead instruction reads the status of a serial port on an Option Board.

2-1348

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

NX_SerialStatusRead

2 Instruction Descriptions

The data type of the DevicePort input variable is structure _sDEVICE_PORT. The specifications are as follows:

Name

Meaning

Description

Data type

Valid range Unit Default

DevicePort

Device port

Object that represents a device _sDEVICE_PORT --port

--- ---

_DeviceNXUnit

DeviceType Device type

Type of the device to specify

_eDEVICE_TYPE

_DeviceEcatSla

ve

---

_DeviceOptionB

---

NxUnit

Specified Unit NX Unit to control _sNXUNIT_ID

oard ---

--- ---

2

EcatSlave

Specified slave

EtherCAT slave to control

_sECAT_ID

---

--- ---

OptBoard

Specified Option Board

Option Board to control

_sOPTBOARD_ID ---

--- ---

Reserved Reserved

Reserved

Reserved

---

--- ---

PortNo

Port number

Port number 1: Port 1 2: Port 2

USINT

Depends on data type.

--- ---

Use DeviceType to specify the device type. For an Option Board, set this to _DeviceOptionBoard. The variable used to specify the device is determined by the specified device type. To specify an Option Board, use OptBoard to specify the device. In this case, NxUnit, EcatSlave, and Reserved are not used. To OptBoard, pass the device variable that is assigned to the node location information on the I/O Map for the device to specify.
If you use this instruction, be sure to assign a device variable to the node location information. Do not assign device variables to any I/O ports following the node location information that are indicated by "W" under the R/W column. The figure below is an example of using this instruction for port 1 on an NX-CIF210.
Assign a variable.

Do not assign variables.

Refer to the Sysmac Studio Version 1 Operation Manual (Cat. No. W504-E1-07 or later) for details on assigning a device variable to the node location information.

NJ/NX-series Instructions Reference Manual (W502)

2-1349

2 Instruction Descriptions

Use PortNo to specify the port number. 1: Port 1 2: Port 2 For an Option Board, set this to Port 1.

The data type of DeviceType is enumerated type _eDEVICE_TYPE. The meanings of the enumerators of enumerated type _eDEVICE_TYPE are as follows:

Enumerator _DeviceNXUnit _DeviceEcatSlave _DeviceOptionBoard

Meaning NX Unit is specified. EtherCAT slave is specified. Option Board is specified.

In this instruction, you can specify _DeviceOptionBoard.

The data type of PortStatus output variable is structure _sSERIAL_PORT_STATUS. The specifications are as follows:

Name

Meaning

Description

PortStatus Port status

Outputs the port status that was read.

FullRcvBuf

Data discarded due to full receive buffer

TRUE: Data was discarded.*1 FALSE: Data was not discarded.

Reserved Reserved

Reserved

*1 Data In the receive buffer may not be complete.

Data type _sSERIAL _PORT_S TATUS
BOOL
Reserved

Valid range ---
Depends on data type. ---

Unit Default --- ---
--- ----- ---

Timing Charts
The following figures show the timing charts.

 Normal end

Execute

TRUE FALSE

Busy

TRUE FALSE

*1

Done

TRUE FALSE

Error

TRUE FALSE

ErrorID

Cleared to 0. Updated to result. (16#0000: Normal)

*1. Port status reading is completed.

2-1350

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Serial Communications Instructions

NX_SerialStatusRead

 Error end

Execute Busy Done Error

TRUE FALSE TRUE FALSE TRUE FALSE TRUE FALSE

ErrorID

Cleared to 0. Updated to result. (16#****: Error)

Related System-defined Variables

2

Name _PLC_OptBoardSta

Meaning Option Board Status

Data type
ARRAY[1..2] of _sOPTBOARD_ STA

Description
· This stores the status of the Option Board.

Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· A compiling error will occur if you use this instruction in an event task. Do not use this instruction in event tasks.
· This instruction does not check the communication protocol and wiring conditions. Before use, check the wiring conditions and communication protocol.
· A CIF Unit Initialized error may occur when the NX-series Communications Interface Unit is restarted. Send or receive the data again, if necessary.
· If you use this instruction, do not assign device variables to any I/O ports that are indicated by "W" under the R/W column on the I/O Map Tab Page in the Sysmac Studio for the applicable NX-series Communications Interface Unit.
· An error will occur in the following cases. Error will change to TRUE.
· A value that is out of range was set for Kind, DevicePort.DevicePortType, or DevicePort.PortNo.
· The Unit, Option Board, or port specified with DevicePort does not exist.
· If more than 32 instructions from the NX_SerialSend instruction, NX_SerialRcv instruction, NX_ModbusRtuCmd instruction, NX_ModbusRtuRead instruction, NX_ModbusRtuWrite instruction, NX_SerialSigCtl instruction, NX_SerialSigRead instruction, NX_SerialStatusRead instruction, NX_SerialBufClear instruction, NX_SerialStartMon instruction and NX_SerialStopMon instruction are executed at the same time.
· This instruction is executed with a device port variable that is the same as the one specified for the instruction which is still being executed. In this case, the instruction which is still being executed is one of the followings. NX_SerialSigCtl instruction, NX_SerialSigRead instruction, NX_SerialStatusRead instruction, NX_SerialBufClear instruction, NX_SerialStartMon instruction, and NX_SerialStopMon instruction.
· Timeout time elapsed during serial communications.
· The instruction is executed for other than Option Boards.
· The serial communications mode of the specified Option Board is not No-protocol or ModbusRTU master.

NJ/NX-series Instructions Reference Manual (W502)

2-1351

2 Instruction Descriptions
Sample Programming
Refer to the sample programming for NX_SerialSigCtl on page 2-1334.

2-1352

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

NX_SerialBufClear

2 Instruction Descriptions

NX_SerialBufClear

The NX_SerialBufClear instruction clears the send or receive buffer.

Instruction

Name

FB/ FUN

Graphic expression

ST expression

NX_SerialBufClear

Clear Buffer

FB

NX_SerialBufClear_instance(

NX_SerialBufClear_instance

Execute DevicePort,

NX_SerialBufClear

Execute

Done

BufKind, TimeOut,

2

DevicePort BufKind TimeOut

Busy Error ErrorID

Done, Busy, Error,

ErrorID);

Version Information
A CPU Unit with unit version 1.11 or later and Sysmac Studio version 1.15 or higher are required to use this instruction.

Variables

Name

Meaning

I/O

DevicePort Device port

BufKind

Buffer type Input

TimeOut

Timeout time

Description Object that represents a device port
Type (send or receive) of buffer
2.0 s when the timeout time is set to 0

Valid range

Unit

---

---

_BUF_SENDRCV

_BUF_SEND

---

_BUF_RCV

Depends on data type. 0.1 s

Default
---
_BUFSENDRCV
0

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

DevicePort BufKind TimeOut

Refer to Function for details on the structure _sDEVICE_PORT. Refer to Function for the enumerators of the enumerated type _eSERIAL_BUF_KIND.
OK

Function
The NX_SerialBufClear clears data in a buffer according to the setting of type of the port and buffer. The instruction ends normally when the clear processing is completed.

NJ/NX-series Instructions Reference Manual (W502)

2-1353

2 Instruction Descriptions

The data type of the DevicePort input variable is structure _sDEVICE_PORT. The specifications are as follows:

Name DevicePort
DeviceType
NxUnit EcatSlave OptBoard Reserved PortNo

Meaning Device port

Description
Object that represents a device port

Device type

Type of the device to specify

Specified Unit NX Unit to control

Specified slave

EtherCAT slave to control

Specified Option Board

Option Board to control

Reserved

Reserved

Port number

Port number 1: Port 1

2: Port 2

Data type _sDEVICE_PORT
_eDEVICE_TYPE
_sNXUNIT_ID _sECAT_ID _sOPTBOAR D_ID Reserved
USINT

Valid range
---
_DeviceNXUnit _DeviceEcatSlave _DeviceOptionBoard ---
---
---
---
Depends on data type.

Unit ---
---
-----------

Default ---
---
-----------

Use DeviceType to specify the device type. Set this to _DeviceNXUnit for an NX Unit and _DeviceOptionBoard for an Option Board. The variable used to specify the device is determined by the specified device type.
To specify an NX Unit, use NxUnit to specify the device.
In this case, EcatSlave and OptBoard are not used.
To NxUnit, pass the device variable that is assigned to the node location information on the I/O Map for the device to specify.
To specify an Option Board, use OptBoard to specify the device.
In this case, NxUnit and EcatSlave are not used.
To OptBoard, pass the device variable that is assigned to the node location information on the I/O Map for the device to specify.

2-1354

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

NX_SerialBufClear

2 Instruction Descriptions
If you use this instruction, be sure to assign a device variable to the node location information. Do not assign device variables to any I/O ports following the node location information that are indicated by "W" under the R/W column. The figure below is an example of using this instruction for port 1 on an NX-CIF210.
Assign a variable.
Do not assign variables.
2

Refer to the Sysmac Studio Version 1 Operation Manual (Cat. No. W504-E1-07 or later) for details on assigning a device variable to the node location information.

Use PortNo to specify the port number. 1: Port 1 2: Port 2 For an NX Unit, set this to Port 1 or Port 2. For an Option Board, set this to Port 1.

The data type of DeviceType is enumerated type _eDEVICE_TYPE. The meanings of the enumerators of enumerated type _eDEVICE_TYPE are as follows:

Enumerator _DeviceNXUnit _DeviceEcatSlave _DeviceOptionBoard

Meaning NX Unit is specified. EtherCAT slave is specified. Option Board is specified.

In this instruction, you can specify _DeviceNXUnit or _DeviceOptionBoard.

Specify the port with Port, and specify the buffer to clear with BufKind.

Data is not cleared if it is the data that the NX-series Communications Interface Unit received from the external devices after the receive buffer is cleared.

NJ/NX-series Instructions Reference Manual (W502)

2-1355

2 Instruction Descriptions

The data type of BufKind is enumerated type _eSERIAL_BUF_KIND. The meanings of the enumerators of enumerated type _eSERIAL_BUF_KIND are as follows:

Enumerator _BUF_SENDRCV
_BUF_SEND _BUF_RCV

Meaning
Send buffer and receive buffer
Send buffer
Receive buffer

An error occurs if this instruction is executed for Units other than NX-series Communications Interface Units and Option Boards.

Timing Charts
The following figures show the timing charts.

 Normal end

Execute

TRUE FALSE

Busy

TRUE FALSE

Done

TRUE FALSE

Error

TRUE FALSE

ErrorID

*1 Cleared to 0. Updated to result. (16#0000: Normal)

*1 Buffer clear processing is completed.

 Error end

Execute

TRUE FALSE

Busy

TRUE FALSE

Done

TRUE FALSE

Error

TRUE FALSE

ErrorID

Cleared to 0. Updated to result. (16#****: Error)

Related System-defined Variables

Name _PLC_OptBoardSta
_NXB_UnitIOActiveTbl

Meaning Option Board Status
NX Unit I/O Data Active Status

Data type ARRAY[1..2] of _sOPTBOARD_ STA
ARRAY[0..8] OF BOOL

Description
· This stores the status of the Option Board.
· This status tells the NX Units whether I/O data communications can be processed.
· The subscript of the array corresponds to the NX Unit numbers. A subscript of 0 means the NX bus master.

2-1356

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

NX_SerialBufClear

2 Instruction Descriptions
Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· A compiling error will occur if you use this instruction in an event task. Do not use this instruction in event tasks.
· This instruction does not check the communication protocol and wiring conditions. Before use, check the wiring conditions and communication protocol.
· A CIF Unit Initialized error may occur when the NX-series Communications Interface Unit is restarted. Send or receive the data again, if necessary.
· If you use this instruction, do not assign device variables to any I/O ports that are indicated by "W" 2
under the R/W column on the I/O Map Tab Page in the Sysmac Studio for the applicable NX-series Communications Interface Unit. · An error will occur in the following cases. Error will change to TRUE. · A value that is out of range was set for BufKind, DevicePort.DevicePortType, or Device-
Port.PortNo. · The Unit, Option Board, or port specified with DevicePort does not exist. · If more than 32 instructions from the NX_SerialSend instruction, NX_SerialRcv instruction,
NX_ModbusRtuCmd instruction, NX_ModbusRtuRead instruction, NX_ModbusRtuWrite instruction, NX_SerialSigCtl instruction, NX_SerialSigRead instruction, NX_SerialStatusRead instruction, NX_SerialBufClear instruction, NX_SerialStartMon instruction and NX_SerialStopMon instruction are executed at the same time.
· This instruction is executed with a device port variable that is the same as the one specified for the instruction which is still being executed. In this case, the instruction which is still being executed is one of the followings. The NX_SerialSend instruction, NX_SerialRcv instruction, NX_ModbusRtuCmd instruction, NX_ModbusRtuRead instruction, NX_ModbusRtuWrite instruction, NX_SerialSigCtl instruction, NX_SerialSigRead instruction, NX_SerialStatusRead instruction, NX_SerialBufClear instruction, NX_SerialStartMon instruction, and NX_SerialStopMon instruction.
· Timeout time elapsed during serial communications. · This instruction is executed for Units other than NX-series Communications Interface Units and
Option Boards. · The serial communications mode of the specified Option Board is not No-protocol or Modbus-
RTU master.

NJ/NX-series Instructions Reference Manual (W502)

2-1357

2 Instruction Descriptions
Sample Programming
In this sample, an NX-series Communications Interface Unit (NX-CIF210) is connected to an EtherCAT Coupler Unit (NX-ECC203). The unit number of the NX-CIF210 is set to 1.
Built-in EtherCAT port

EtherCAT Coupler Unit NX-ECC203
NX-series Communications Interface Unit NX-CIF210
This instruction clears the receive buffer of serial port 2 on NX-CIF210. When clear processing is completed, the instruction waits for data that does not have start code and has the CR end code.

Definitions of Global Variables

Global Variables

Name

Data type

AT

Comment

E001_NX_Unit_I_O_Data_Active_Status_63

ARRAY[0..63] OF BOOL

ECAT://node#1/NX Unit I/O Data Active Status 125

Usage of I/O data for 63 NX Units.

N1_Node_location_information

_sNXUNIT_ID

---

Device variable to specify NX-CIF210*1

*1 On the Sysmac Studio, right-click an NX-series slave terminal unit, select Display Node Location Port, and set the device variable. Refer to the Sysmac Studio Version 1 Operation Manual (Cat. No. W504-E1-07 or later) for details.

2-1358

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

NX_SerialBufClear

2 Instruction Descriptions

LD

Internal Variables

Variable

OperatingEnd

Trigger

Operating
SelectSendBuf SelectRcvBuf BufKind DevicePort NX_SerialBufClear_instance
RcvingEnd

Rcving

RcvCfg

StartTrig
StartCode
EndTrig
EndCode RcvSizeCfg Option TimeOut LastDatRcv ClearBuf

Data type

Initial value

Comment

BOOL

FALSE

Buffer clear processing finished

BOOL

FALSE

Buffer clear execution condition

BOOL

FALSE

Buffer clear processing in progress

BOOL BOOL

FALSE FALSE

Send buffer selection

Receive buffer selection

2

_eSERIAL_BUF_KIND

_BUF_SENDRCV Buffer setting

_sDEVICE_PORT

Port settings

NX_SerialBufClear

---

BOOL
BOOL
_sSERIAL_CFG
_eSERIAL_START ARRAY[0..1] OF BYTE _eSERIAL_END ARRAY[0..1] OF BYTE UINT _sSERIAL_RCV_OPTION TIME BOOL BOOL

_SERIAL_START_NONE
[2(16#0)]
_SERIAL_END_CODE1
[16#0D,16#00]
0

Receive processing completed Receive processing in progress Reception completion setting
End code: CR

TIME#0s FALSE FALSE

External Vari-
ables

Variable

Data type

E001_NX_Unit_I_O_Data_Ac- ARRAY[0..63]

tive_Status_63

OF BOOL

N1_Node_location_information _sNXUNIT_ID

Comment
· Usage of I/O data for 63 NX Units. · If the relevant Unit number is 1, E001_NX-
_Unit_I_O_Data_Active_Status_63[1] is used. Device variable to specify NX-CIF210

NJ/NX-series Instructions Reference Manual (W502)

2-1359

2 Instruction Descriptions

Determine if execution of the NX_SerialBufClear instruction has ended. NX_SerialBufClear_instance.Done
NX_SerialBufClear_instance.Error

OperatingEnd

Accept trigger. Trigger E001_NX_Unit_I_O_Data_Active_Status_63[1]
Operating

OperatingEnd Operating

Operating SelectSendBuf SelectRcvBuf _eCIF_BUF_KIND#_BUF_SEND
SelectSendBuf SelectRcvBuf _eCIF_BUF_KIND#_BUF_RCV
SelectSendBuf SelectRcvBuf _eCIF_BUF_KIND#_BUF_SENRCV
SelectSendBuf SelectRcvBuf _eCIF_BUF_KIND#_BUF_SENRCV

Operating

Inline ST Note: The contents of the inline ST are given below.

MOVE

EN

ENO

In

Out

MOVE

EN

ENO

In

Out

MOVE

EN

ENO

In

Out

MOVE

EN

ENO

In

Out

Buf_Kind Buf_Kind Buf_Kind Buf_Kind

Operating

DevicePort BufKind

NX_SerialBufClear_instance

NX_SerialBufClear

Execute

Done

DevicePort

Busy

BufKind

Error

TimeOut

ErrorID

Enter Variable Enter Variable Enter Variable

Determine if execution of the NX_SerialRcv instruction has ended. NX_SerialRcv_instance.Done

RcvingEnd

NX_SerialRcv_instance.Error

NX_SerialBufClear_instance.Done

E001_NX_Unit_I_O_ Data_Active_Status_63

RcvingEnd Rcving

Rcving

2-1360

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

NX_SerialBufClear

2 Instruction Descriptions

Execute NX_SerialRcv instruction.
Rcving
DevicePort RcvDat[0]
Size RcvCfg Option

NX_SerialRcv_instance

NX_SerialRcv Execute

Done

DevicePort RcvDat

Busy RcvDat

Size RcvCfg Option Abort

CommandAborted Error
ErrorID RcvSize

Enter Variable
Enter Variable Enter Variable Enter Variable Enter Variable

 Contents of Inline ST

DevicePort.DeviceType:=_eDEVICE_TYPE#_DeviceNXUnit;

2

DevicePort.NxUnit:=N1_Node_location_information;

DevicePort.PortNo:=2;

ST

Internal Variables

Variable

OperatingEnd

Trigger

Operating
SelectSendBuf SelectRcvBuf BufKind DevicePort NX_SerialBufClear_instance
RcvingEnd

Rcving

RcvCfg

StartTrig
StartCode
EndTrig
EndCode RcvSizeCfg Option TimeOut LastDatRcv ClearBuf

Data type

Initial value

Comment

BOOL
BOOL
BOOL BOOL BOOL _eSERIAL_BUF_KIND _sDEVICE_PORT

FALSE
FALSE
FALSE FALSE FALSE _BUF_SENDRCV

Buffer clear processing finished
Buffer clear execution condition
Buffer clear processing in progress
Send buffer selection
Receive buffer selection
Buffer setting
Port settings

NX_SerialBufClear

---

BOOL
BOOL
_sSERIAL_CFG
_eSERIAL_START ARRAY[0..1] OF BYTE _eSERIAL_END ARRAY[0..1] OF BYTE UINT _sSERIAL_RCV_OPTION TIME BOOL BOOL

_SERIAL_START_NONE
[2(16#0)]
_SERIAL_END_CODE1
[16#0D,16#00]
0

Receive processing completed Receive processing in progress Reception completion setting
End code: CR

TIME#0s FALSE FALSE

NJ/NX-series Instructions Reference Manual (W502)

2-1361

2 Instruction Descriptions

External Vari-
ables

Variable

Data type

E001_NX_Unit_I_O_Data_Ac- ARRAY[0..63]

tive_Status_63

OF BOOL

N1_Node_location_information _sNXUNIT_ID

Comment
· Usage of I/O data for 63 NX Units. · If the relevant Unit number is 1, E001_NX-
_Unit_I_O_Data_Active_Status_63[1] is used. Device variable to specify NX-CIF210

// Condition setting RS_instance1(Set:=Trigger AND E001_NX_Unit_I_O_Data_Active_Status_63[1]
Reset1:=OperatingEnd, Q1=>Operating); R_Trigger_instance(Clk:=Operating); IF ( (R_Trigger_instance.Q=TRUE) ) THEN DevicePort.DeviceType:=_eDEVICE_TYPE#_DeviceNXUnit; DevicePort.NxUnit:=N1_Node_location_information; DevicePort.PortNo:=2; IF( (SelectSendBuf=TRUE) THEN
IF(SelectRcvBuf=TRUE) THEN BufKind:=_eSERIAL_BUF_KIND#_BUF_SENDRCV;
ELSE BufKind:=_eSERIAL_BUF_KIND#_BUF_SEND;
END_IF; ELSE
IF (SelectRcvBuf=TRUE) THEN BufKind:=_eSERIAL_BUF_KIND#_BUF_RCV;
ELSE BufKind:=_eSERIAL_BUF_KIND#_BUF_SENDRCV;
END_IF END_IF; END_IF;
// Execute buffer clear NX_SerialBufClear_instance(Execute:=Operating,
DevicePort:=DevicePort, BufKind:=BufKind);
// RS_instane2(Set:=NX_SerialBufClear.Done AND E001_NX_Unit_I_O_Data_Active_Status_63[1],
Reset1:=NX_SerialRcv_instance.Done OR NX_SerialRcv_instance.Error, Q1=>Rcving);
// NX_SerialRcv_instance(Execute:=Rcving,
DevicePort:=DevicePort, RcvDat:=RcvDat[0], Size:=Size, RcvCfg:=RcvCfg, Option:=Option);

2-1362

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

NX_SerialStartMon

2 Instruction Descriptions

NX_SerialStartMon

The NX_SerialStartMon instruction starts serial line monitoring of an NX-series Communications Interface Unit.

Instruction

Name

FB/ FUN

Graphic expression

ST expression

NX_SerialStartMon

Start Serial Line Monitoring

FB

NX_SerialStartMon_instance(

NX_SerialStartMon_instance NX_SerialStartMon

Execute,

DevicePort, Continuous,

2

Execute DevicePort Continuous TimeOut

Done Busy Error ErrorID

TimeOut, Done, Busy, Error,

ErrorID);

Precautions for Correct Use You cannot use this instruction for an Option Board for the NX1P2 CPU Unit.

Version Information
A CPU Unit with unit version 1.11 or later and Sysmac Studio version 1.15 or higher are required to use this instruction.

Variables

Name

Meaning

I/O

DevicePort Device port

ContinuContinuous ous moni-
toring

Input

TimeOut

Timeout time

Description
Object that represents a device port
Serial line monitor operation method TRUE: Continuous FALSE: One-shot
2.0 s when the timeout time is set to 0

Valid range ---

Unit ---

Depends on data type. ---

Depends on data type. 0.1 s

Default ---
FALSE
0

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

DevicePort Continuous OK TimeOut

Refer to Function for details on the structure _sDEVICE_PORT. OK

NJ/NX-series Instructions Reference Manual (W502)

2-1363

2 Instruction Descriptions

Function
The NX_SerialStartMon instruction starts serial line monitoring of an NX-series Communications Interface Unit. This instruction ends normally after serial line monitoring starts.

The data type of the DevicePort input variable is structure _sDEVICE_PORT. The specifications are as follows:

Variables DevicePort
DeviceType
NxUnit EcatSlave OptBoard Reserved PortNo

Meaning Device port

Description
Object that represents a device port

Device type

Type of the device to specify

Specified Unit NX Unit to control

Specified slave

EtherCAT slave to control

Specified Option Board

Option Board to control

Reserved

Reserved

Port number

Port number 1: Port 1

2: Port 2

Data type _sDEVICE_PORT
_eDEVICE_TYPE
_sNXUNIT_ID _sECAT_ID _sOPTBOAR D_ID Reserved
USINT

Valid range
---
_DeviceNXUnit _DeviceEcatSlave _DeviceOptionBoard ---
---
---
---
Depends on data type.

Unit ---
---
-----------

Default ---
---
-----------

Use DeviceType to specify the device type. Set this to _DeviceNXUnit for an NX Unit. The variable used to specify the device is determined by the specified device type.
In this instruction, NxUnit is used to specify the device. EcatSlave and OptBoard are not used.
To NxUnit, pass the device variable that is assigned to the node location information on the I/O Map for the device to specify.

2-1364

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

NX_SerialStartMon

2 Instruction Descriptions
If you use this instruction, be sure to assign a device variable to the node location information. Do not assign device variables to any I/O ports following the node location information that are indicated by "W" under the R/W column. The figure below is an example of using this instruction for port 1 on an NX-CIF210.
Assign a variable.
Do not assign variables.
2

Refer to the Sysmac Studio Version 1 Operation Manual (Cat. No. W504-E1-07 or later) for details on assigning a device variable to the node location information.

Use PortNo to specify the port number. 1: Port 1 2: Port 2

The data type of DeviceType is enumerated type _eDEVICE_TYPE. The meanings of the enumerators of enumerated type _eDEVICE_TYPE are as follows:

Enumerator _DeviceNXUnit _DeviceEcatSlave _DeviceOptionBoard

Meaning NX Unit is specified. EtherCAT slave is specified. Option Board is specified.

In this instruction, you can specify _DeviceNXUnit.

When the Continuous input variable is TRUE, continuous monitoring is selected and the monitoring is continued until the NX_SerialStopMon instruction is executed.
When the Continuous input variable is FALSE, one-shot monitoring is selected and serial line monitoring is continued until the buffer becomes full or the NX_SerialStopMon instruction is executed.

An error occurs if this instruction is executed for Units other than NX-series Communications Interface Units.

NJ/NX-series Instructions Reference Manual (W502)

2-1365

2 Instruction Descriptions

Timing Charts
The following figures show the timing charts.

 Normal end

Execute

TRUE FALSE

Busy

TRUE FALSE

Done

TRUE FALSE

Error

TRUE FALSE

ErrorID

Cleared to 0.

*1 Serial line monitoring is started.

*1 Updated to result. (16#0000: Normal)

 Error end

Execute

TRUE FALSE

Busy

TRUE FALSE

Done

TRUE FALSE

Error

TRUE FALSE

ErrorID

Cleared to 0. Updated to result. (16#****: Error)

Related System-defined Variables

Name _NXB_UnitIOActiveTbl

Meaning
NX Unit I/O Data Active Status

Data type
ARRAY[0..8] OF BOOL

Description
· This status tells the NX Units whether I/O data communications can be processed.
· The subscript of the array corresponds to the NX Unit numbers. A subscript of 0 means the NX bus master.

2-1366

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

2 Instruction Descriptions

Precautions for Correct Use

· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.

· A compiling error will occur if you use this instruction in an event task. Do not use this instruction in event tasks.

· A CIF Unit Initialized error may occur when the NX-series Communications Interface Unit is restarted. Send or receive the data again, if necessary.

· If you use this instruction, do not assign device variables to any I/O ports that are indicated by "W"

under the R/W column on the I/O Map Tab Page in the Sysmac Studio for the applicable NX-series

Communications Interface Unit.

2

· An error will occur in the following cases. Error will change to TRUE.

· A value that is out of range was set for DevicePort.DevicePortType or DevicePort.PortNo.

· The Unit, Option Board, or port specified with DevicePort does not exist.

· If more than 32 instructions from the NX_SerialSend instruction, NX_SerialRcv instruction, NX_ModbusRtuCmd instruction, NX_ModbusRtuRead instruction, NX_ModbusRtuWrite instruction, NX_SerialSigCtl instruction, NX_SerialSigRead instruction, NX_SerialStatusRead instruction, NX_SerialBufClear instruction, NX_SerialStartMon instruction and NX_SerialStopMon instruction are executed at the same time.

· This instruction is executed with a device port variable that is the same as the one specified for the instruction which is still being executed. In this case, the instruction which is still being executed is one of the followings. The NX_SerialSigCtl instruction, NX_SerialSigRead instruction, NX_SerialStatusRead instruction, NX_SerialBufClear instruction, NX_SerialStartMon instruction, and NX_SerialStopMon instruction.
· Timeout time elapsed during serial communications.
· This instruction is executed for Units other than NX-series Communications Interface Units.

NX_SerialStartMon

NJ/NX-series Instructions Reference Manual (W502)

2-1367

2 Instruction Descriptions

NX_SerialStopMon

The NX_SerialStopMon instruction stops serial line monitoring of an NX-series Communications Interface Unit.

Instruction

Name

FB/ FUN

NX_SerialStopMon

Stop Serial Line Monitoring

FB

Graphic expression

NX_SerialStopMon_instance

NX_SerialStopMon

Execute

Done

DevicePort

Busy

TimeOut

Error ErrorID

ST expression
NX_SerialStopMon_instance( Execute, DevicePort, TimeOut, Done, Busy, Error, ErrorID);

Precautions for Correct Use You cannot use this instruction for an Option Board for the NX1P2 CPU Unit.

Version Information
A CPU Unit with unit version 1.11 or later and Sysmac Studio version 1.15 or higher are required to use this instruction.

Variables

Name

Meaning

I/O

DevicePort TimeOut

Device port
Timeout time

Input

Description
Object that represents a device port
2.0 s when the timeout time is set to 0

Valid range ---

Unit ---

Depends on data type. 0.1 s

Default --0

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

DevicePort TimeOut

Refer to Function for details on the structure _sDEVICE_PORT. OK

Function
The NX_SerialStopMon instruction stops serial line monitoring of an NX-series Communications Interface Unit. This instruction ends normally after serial line monitoring stops.

2-1368

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

NX_SerialStopMon

2 Instruction Descriptions

The data type of the DevicePort input variable is structure _sDEVICE_PORT. The specifications are as follows:

Variables

Meaning

Description

Data type

Valid range Unit Default

DevicePort

Device port

Object that represents a _sDE-

device port

VICE_PORT

---

--- ---

_DeviceNXUnit

DeviceType

Device type

Type of the device to specify

_eDEVICE_TYPE

_DeviceEcatSlave

---

---

_DeviceOption-

Board

NxUnit EcatSlave

Specified Unit NX Unit to control

Specified slave

EtherCAT slave to control

_sNXUNIT_ID --_sECAT_ID ---

--- ---

2

--- ---

OptBoard

Specified Option Board

Option Board to control

_sOPTBOAR D_ID

---

--- ---

Reserved

Reserved

Reserved

Reserved

---

--- ---

PortNo

Port number

Port number 1: Port 1 2: Port 2

USINT

Depends on data type.

--- ---

Use DeviceType to specify the device type. Set this to _DeviceNXUnit for an NX Unit. The variable used to specify the device is determined by the specified device type. In this instruction, NxUnit is used to specify the device. EcatSlave and OptBoard are not used. To NxUnit, pass the device variable that is assigned to the node location information on the I/O Map for the device to specify.
If you use this instruction, be sure to assign a device variable to the node location information. Do not assign device variables to any I/O ports following the node location information that are indicated by "W" under the R/W column. The figure below is an example of using this instruction for port 1 on an NX-CIF210.
Assign a variable.

Do not assign variables.

Refer to the Sysmac Studio Version 1 Operation Manual (Cat. No. W504-E1-07 or later) for details on assigning a device variable to the node location information.

NJ/NX-series Instructions Reference Manual (W502)

2-1369

2 Instruction Descriptions

Use PortNo to specify the port number. 1: Port 1 2: Port 2

The data type of DeviceType is enumerated type _eDEVICE_TYPE. The meanings of the enumerators of enumerated type _eDEVICE_TYPE are as follows:

Enumerator _DeviceNXUnit _DeviceEcatSlave _DeviceOptionBoard

Meaning NX Unit is specified. EtherCAT slave is specified. Option Board is specified.

In this instruction, you can specify _DeviceNXUnit.

An error occurs if this instruction is executed for Units other than NX-series Communications Interface Units.

Timing Charts
The following figures show the timing charts.

 Normal end

Execute

TRUE FALSE

Busy

TRUE FALSE

Done

TRUE FALSE

Error

TRUE FALSE

ErrorID

Cleared to 0.

*1 Serial line monitoring is stopped.

*1 Updated to result. (16#0000: Normal)

 Error end

Execute

TRUE FALSE

Busy

TRUE FALSE

Done

TRUE FALSE

Error

TRUE FALSE

ErrorID

Cleared to 0. Updated to result. (16#****: Error)

2-1370

NJ/NX-series Instructions Reference Manual (W502)

Serial Communications Instructions

NX_SerialStopMon

2 Instruction Descriptions

Related System-defined Variables

Name

Meaning

Data type

Description

_NXB_UnitIOActiveTbl

NX Unit I/O Data Active Status

ARRAY[0..8] OF BOOL

· This status tells the NX Units whether I/O data communications can be processed.
· The subscript of the array corresponds to the NX Unit numbers. A subscript of 0 means the NX bus master.

2 Precautions for Correct Use

· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· A compiling error will occur if you use this instruction in an event task. Do not use this instruction in event tasks.
· A CIF Unit Initialized error may occur when the NX-series Communications Interface Unit is restarted. Send or receive the data again, if necessary.
· If you use this instruction, do not assign device variables to any I/O ports that are indicated by "W" under the R/W column on the I/O Map Tab Page in the Sysmac Studio for the applicable NX-series Communications Interface Unit.
· An error will occur in the following cases. Error will change to TRUE.
· A value that is out of range was set for DevicePort.DevicePortType or DevicePort.PortNo.
· The Unit, Option Board, or port specified with DevicePort does not exist.
· If more than 32 instructions from the NX_SerialSend instruction, NX_SerialRcv instruction, NX_ModbusRtuCmd instruction, NX_ModbusRtuRead instruction, NX_ModbusRtuWrite instruction, NX_SerialSigCtl instruction, NX_SerialSigRead instruction, NX_SerialStatusRead instruction, NX_SerialBufClear instruction, NX_SerialStartMon instruction and NX_SerialStopMon instruction are executed at the same time.
· This instruction is executed with a device port variable that is the same as the one specified for the instruction which is still being executed. In this case, the instruction which is still being executed is one of the followings. The NX_SerialSigCtl instruction, NX_SerialSigRead instruction, NX_SerialStatusRead instruction, NX_SerialBufClear instruction, NX_SerialStartMon instruction, and NX_SerialStopMon instruction.
· Timeout time elapsed during serial communications.
· This instruction is executed for Units other than NX-series Communications Interface Units.

NJ/NX-series Instructions Reference Manual (W502)

2-1371

2 Instruction Descriptions

2-1372

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

2
SD Memory Card Instructions

Instruction FileWriteVar FileReadVar FileOpen FileClose FileSeek FileRead FileWrite FileGets FilePuts FileCopy FileRemove FileRename DirCreate DirRemove BackupToMemoryCard

Name Write Variable to File Read Variable from File Open File Close File Seek File Read File Write File Get Text String Put Text String Copy File Delete File Change File Name Create Directory Delete Directory SD Memory Card Backup

Page 2-1374 2-1379 2-1384 2-1388 2-1391 2-1395 2-1403 2-1411 2-1419 2-1428 2-1437 2-1442 2-1447 2-1450 2-1453

NJ/NX-series Instructions Reference Manual (W502)

2-1373

2 Instruction Descriptions

FileWriteVar

The FileWriteVar instruction writes the value of a variable to the specified file in the SD Memory Card. The value is written in binary format.

Instruction FileWriteVar

Name
Write Variable to File

FB/FUN FB

Graphic expression

FileWriteVar_instance

FileWriteVar

Execute FileName WriteVar OverWrite

Done Busy Error ErrorID

ST expression
FileWriteVar_instance(Execute, FileName, WriteVar, OverWrite, Done, Busy, Error, ErrorID);

Variables

Name

Meaning

I/O

FileName File name

WriteVar OverWrite

Variable
Overwrite enable

Input

Description Name of file to which to write variable
Variable to write TRUE: Enable overwrite. FALSE: Prohibit overwrite.

Valid range

Unit

66 bytes max. (65 sin-

gle-byte alphanumeric

characters plus the final

NULL character)

---

Depends on data type.

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default ''
* FALSE

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

FileName WriteVar OverWrite

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK
An enumeration, array, array element, structure, or structure member can also be specified. OK

Function

The FileWriteVar instruction writes the value of variable WriteVar to the file specified by FileName in the SD Memory Card. The value is written in binary format. You can specify an enumeration, array, array element, structure, or structure member for WriteVar.
If a file with the name FileName does not exist on the SD Memory Card, it is created. FileName includes the path. If a specified directory does not exist in the SD Memory Card, it is created. However, the directory is created only when only the lowest directory level of the specified path does not exist.
If a file with the name FileName already exists in the SD Memory Card, the following processing is performed depending on the value of overwrite enable OverWrite.

Value of OverWrite

Processing

TRUE (Enable overwrite.)

The existing file is overwritten.

FALSE (Prohibit overwrite.)

The file is not overwritten and an error occurs.

2-1374

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

SD Memory Card Instructions

FileWriteVar

The following figure shows a programming example. The contents of array variable abc[0] is written to a file named `Temp/f_name.bin.' Variable abc is an INT array variable with three elements.

LD

ST

A
`Temp/f_name.bin' abc
TRUE

FileWriteVar_instance

FileWriteVar

Execute FileName WriteVar OverWrite

Done Busy Error ErrorID

def
ghi jkl mno

FileWriteVar_instance(A, `Temp/f_name.bin', abc, TRUE, def, ghi, jkl, mno);

2

The FileWriteVar instruction writes the value of variable WriteVar to the file specified by FileName in the SD Memory Card. The value is written in binary format.
File FileName = `Temp/f_name.bin'

WriteVar[0]=abc[0] WriteVar[1]=abc[1] WriteVar[2]=abc[2]

INT#1234 INT#2345 INT#3456

Written.

INT#1234 INT#2345 INT#3456

Related System-defined Variables

Name _Card1Ready _Card1Protect*2 _Card1Err*2
_Card1Access*2 _Card1PowerFail

Meaning SD Memory Card Ready Flag
SD Memory Card Write Protected Flag
SD Memory Card Error Flag
SD Memory Card Access Flag
SD Memory Card Power Interruption Flag

Data type BOOL BOOL BOOL
BOOL BOOL

Description
This flag indicates if the SD Memory Card can be accessed by instructions and communications commands.*1 TRUE: Can be used. FALSE: Cannot be used.
This flag indicates if the SD Memory Card is write protected when it is inserted and ready to use. TRUE: Write protected. FALSE: Not write protected.
This flag indicates if an unspecified SD Memory Card (e.g., an SDHC card) is mounted or if the format is incorrect (i.e., not FAT16 or corrupted). TRUE: Error. FALSE: No error.
This flag indicates if the SD Memory Card is currently being accessed. TRUE: Being accessed. FALSE: Not being accessed.
This flag indicates if an error occurred in completing processing when power was interrupted during access*3. This flag is not cleared automatically. TRUE: Error. FALSE: No error.

*1 For the NJ/NX-series, it is a precondition that the SD Memory Card is physically inserted and mounted normally. For an NY-series Controller, it is a precondition that the shared folder is detected by the Controller.
*2 These variables are not used for the NY-series Controller. They are fixed to FALSE.
*3 For the NJ/NX-series, this indicates an access to the SD Memory Card. For an NY-series Controller, this indicates an access to the shared folder.

NJ/NX-series Instructions Reference Manual (W502)

2-1375

2 Instruction Descriptions
Additional Information
The root directory of the file name is the top level of the SD Memory Card.
Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error. · Always use a variable for the input parameter to pass to WriteVar. A building error will occur if a con-
stant is passed. · If WriteVar is an enumeration, you cannot directly pass an enumerator to it. A building error will occur
if an enumerator is passed to it directly. · If the specified file is larger than the size of WriteVar, an error does not occur and only data that cor-
responds to the size of WriteVar is written. Once this instruction is executed, the specified file is reduced to the size of WriteVar. · Data is written in byte increments. The lower bytes are written before the upper bytes (little endian). · If WriteVar is a structure, adjustment areas between members may be inserted depending on the composition. · Do not simultaneously access the same file. Perform exclusive control of SD Memory Card instructions in the user program. · An error occurs in the following cases. Error will change to TRUE. · The SD Memory Card is not in a usable condition. · The SD Memory Card is write protected. · There is insufficient space available on the SD Memory Card. · The value of FileName is not a valid file name. · The maximum number of files or directories is exceeded. · A file with the name FileName already exits and the file is being accessed. · A file with the name FileName already exits and the value of OverWrite is FALSE. · A file with the name FileName already exits and the file is write protected. · If more than four SD Memory Card instructions that do not have a FileID variable (i.e., FileWrite-
Var, FileReadVar, FileCopy, DirCreate, FileRemove, DirRemove, and FileRename) are executed at the same time. · The value of FileName exceeds the maximum number of bytes allowed in a file name. · An error that prevents access occurs during SD Memory Card access.

2-1376

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

FileWriteVar

2 Instruction Descriptions

Sample Programming

This sample writes all of array variable Var1[] to the file `File1.dat.'

LD

Internal Variables

Variable
OperatingEnd Trigger Operating

Var1

RS_instance FileWriteVar_instance

Data type
BOOL BOOL BOOL ARRAY[0..999] OF INT RS FileWriteVar

Initial value
FALSE FALSE FALSE
[1000(0)]

Comment

Processing completed. Execution condition Processing

Write data

2

External Variables

Variable _Card1Ready

Data type BOOL

Comment SD Memory Card Ready Flag

Determine if execution of the FileWriteVar instruction is completed.

FileWriteVar_instance.Done

OperatingEnd

FileWriteVar_instance.Error

Accept trigger. Trigger _Card1Ready
OperatingEnd

RS_instance

RS

Set

Q1

Reset1

Operating

Execute FileWriteVar instruction.

FileWriteVar_instance

Operating

FileWriteVar

`File1.dat' Var1
TRUE

Execute FileName WriteVar OverWrite

Done Busy Error ErrorID

Processing after normal end. Operating FileWriteVar_instance.Done

Inline ST
1 // Processing after normal end. 2 ;

Processing after error end. Operating FileWriteVar_instance.Error

Inline ST
1 // Processing after error end. 2 ;

NJ/NX-series Instructions Reference Manual (W502)

2-1377

2 Instruction Descriptions

ST
Internal Variables

Variable Trigger LastTrigger OperatingStart Operating Var1 FileWriteVar_instance

Data type BOOL

Initial value
FALSE

BOOL

FALSE

BOOL
BOOL
ARRAY[0..999] OF INT
FileWriteVar

FALSE FALSE
[1000(0)]

Comment
Execution condition Value of Trigger from previous task period Processing started. Processing
Variable

External Variables

Variable _Card1Ready

Data type BOOL

Comment SD Memory Card Ready Flag

// Detect when Trigger changes to TRUE.

IF ( (Trigger=TRUE) AND (LastTrigger=FALSE) AND (_Card1Ready=TRUE) ) THEN

OperatingStart:=TRUE;

Operating

:=TRUE;

END_IF;

LastTrigger:=Trigger;

// Initialize FileWriteVar instruction. IF (OperatingStart=TRUE) THEN
FileWriteVar_instance( Execute :=FALSE, WriteVar :=Var1);
OperatingStart :=FALSE; END_IF;

// Execute FileWriteVar instruction.

IF (Operating=TRUE) THEN

FileWriteVar_instance(

Execute :=TRUE,

FileName :='File1.dat', // File name

WriteVar :=Var1,

// Variable

OverWrite:=TRUE);

// Enable overwrite.

IF (FileWriteVar_instance.Done=TRUE) THEN // Processing after normal end. Operating:=FALSE;
END_IF;
IF (FileWriteVar_instance.Error=TRUE) THEN // Processing after error end. Operating:=FALSE;
END_IF; END_IF;

2-1378

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

FileReadVar

2 Instruction Descriptions

FileReadVar

The FileReadVar instruction reads the contents of the specified file on the SD Memory Card as binary data and writes it to a variable.

Instruction

Name

FB/FUN

Graphic expression

ST expression

FileReadVar

Read Variable from FB File

FileReadVar_instance

FileReadVar

Execute

Done

FileReadVar_instance(Execute, FileName, ReadVar, Done, Busy, Error, ErrorID);

FileName ReadVar

Busy

2

Error ErrorID

Variables

Name FileName

Meaning

I/O

File name Input

ReadVar

Variable to In-out write

Description

Valid range

Unit

Name of file to read

66 bytes max. (65 sin- --gle-byte alphanumeric characters plus the final NULL character)

Variable to which to write the Depends on data type. --value that was read

Default ''
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

FileName ReadVar

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK
An enumeration, array, array element, structure, or structure member can also be specified.

Function
The FileReadVar instruction reads the contents of the file specified by FileName from the SD Memory Card as binary data. The contents that is read is assigned to variable to write ReadVar. You can specify an enumeration, array, array element, structure, or structure member for ReadVar.

NJ/NX-series Instructions Reference Manual (W502)

2-1379

2 Instruction Descriptions

The following figure shows a programming example. Here, the contents of the file called `Temp/f_name.bin' is read and written to the array variable abc[]. Variable abc is an INT array variable with three elements.

LD

ST

A 'Temp/f_name.bin' abc

FileReadVar_instance

FileReadVar

Execute FileName ReadVar

Done Busy

Error ErrorID

def
ghi
abc jkl mno

FileReadVar_instance(A, `Temp/f_name.bin', abc, def, ghi, jkl, mno);

The FileReadVar instruction reads the contents of the file specified by FileName from the SD Memory Card as binary data and assigns it to variable ReadVar.

ReadVar[0]=abc[0] ReadVar[1]=abc[1] ReadVar[2]=abc[2]

INT#1234 INT#2345 INT#3456

Read.

File FileName = `Temp/f_name.bin'
INT#1234 INT#2345 INT#3456

Related System-defined Variables

Name _Card1Ready _Card1Protect*2 _Card1Err*2
_Card1Access*2 _Card1PowerFail

Meaning
SD Memory Card Ready Flag

Data type BOOL

SD Memory Card Write BOOL Protected Flag
SD Memory Card Error BOOL Flag

SD Memory Card Access Flag

BOOL

SD Memory Card

BOOL

Power Interruption Flag

Description
This flag indicates if the SD Memory Card can be accessed by instructions and communications commands.*1 TRUE: Can be used. FALSE: Cannot be used.
This flag indicates if the SD Memory Card is write protected when it is inserted and ready to use. TRUE: Write protected. FALSE: Not write protected.
This flag indicates if an unspecified SD Memory Card (e.g., an SDHC card) is mounted or if the format is incorrect (i.e., not FAT16 or corrupted). TRUE: Error. FALSE: No error.
This flag indicates if the SD Memory Card is currently being accessed. TRUE: Being accessed. FALSE: Not being accessed.
This flag indicates if an error occurred in completing processing when power was interrupted during access*3. This flag is not cleared automatically. TRUE: Error. FALSE: No error.

*1 For the NJ/NX-series, it is a precondition that the SD Memory Card is physically inserted and mounted normally. For an NY-series Controller, it is a precondition that the shared folder is detected by the Controller.
*2 These variables are not used for the NY-series Controller. They are fixed to FALSE.
*3 For the NJ/NX-series, this indicates an access to the SD Memory Card. For an NY-series Controller, this indicates an access to the shared folder.

2-1380

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

SD Memory Card Instructions

FileReadVar

Additional Information
The root directory of the file name is the top level of the SD Memory Card.

Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error.
· If the specified file is larger than the size of ReadVar, an error does not occur and only data that cor- 2
responds to the size of ReadVar is read.
· If the specified file is smaller than the size of ReadVar, an error does not occur and only data that corresponds to the size of the specified file is read. The remaining area in ReadVar will retain the values from before execution of this instruction.
· Data is read in byte increments. The lower bytes are read before the upper bytes (little endian).
· If ReadVar is a structure, adjustment areas between members may be inserted depending on the composition.
· Do not simultaneously access the same file. Perform exclusive control of SD Memory Card instructions in the user program.
· You cannot specify a device variable for ReadVar. If you specify a device variable, the value that was read is not assigned to ReadVar.
· An error occurs in the following cases. Error will change to TRUE.
· The SD Memory Card is not in a usable condition.
· The file specified by FileName does not exist.
· The value of FileName is not a valid file name.
· The file specified by FileName is being accessed.
· If more than four SD Memory Card instructions that do not have a FileID variable (i.e., FileWriteVar, FileReadVar, FileCopy, DirCreate, FileRemove, DirRemove, and FileRename) are executed at the same time.
· The value of FileName exceeds the maximum number of bytes allowed in a file name.
· An error that prevents access occurs during SD Memory Card access.

Sample Programming

This sample reads the contents of the file `File1.dat' and stores it in array variable Var1.

LD

Internal Variables

Variable
OperatingEnd Trigger Operating

Var1

RS_instance FileReadVar_instance

Data type
BOOL BOOL BOOL ARRAY[0..999] OF INT RS FileReadVar

Initial value
FALSE FALSE FALSE
[1000(0)]

Comment
Processing completed. Execution condition Processing
Read data

External Variables

Variable _Card1Ready

Data type BOOL

Comment SD Memory Card Ready Flag

NJ/NX-series Instructions Reference Manual (W502)

2-1381

2 Instruction Descriptions

Determine if execution of the FileReadVar instruction is completed.

FileReadVar_instance.Done

OperatingEnd

FileReadVar_instance.Error

Accept trigger. Trigger _Card1Ready
OperatingEnd

RS_instance

RS

Set

Q1

Reset1

Operating

Execute FileReadVar instruction.

FileReadVar_instance

Operating

FileReadVar

`File1.dat' Var1

Execute FileName ReadVar

Processing after normal end.

Done Busy
Error ErrorID

Operating FileReadVar_instance.Done

Inline ST
1 // Processing after normal end. 2 ;

Processing after error end. Operating FileReadVar_instance.Error

Inline ST
1 // Processing after error end. 2 ;

2-1382

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

FileReadVar

2 Instruction Descriptions

ST

Internal Variables

Variable

Data type

Initial value

Comment

Trigger

BOOL

FALSE Execution condition

LastTrigger

BOOL

FALSE

Value of Trigger from previous task period

OperatingStart

BOOL

FALSE Processing started.

Operating

BOOL

FALSE Processing

Var1

ARRAY[0..999] OF INT

[1000(0)]

Variable to read

FileReadVar_instance FileReadVar

2

External Variables

Variable _Card1Ready

Data type BOOL

Comment SD Memory Card Ready Flag

// Detect when Trigger changes to TRUE.

IF ( (Trigger=TRUE) AND (LastTrigger=FALSE) AND (_Card1Ready=TRUE) ) THEN

OperatingStart:=TRUE;

Operating

:=TRUE;

END_IF;

LastTrigger:=Trigger;

// Initialize FileReadVar instruction. IF (OperatingStart=TRUE) THEN
FileReadVar_instance( Execute :=FALSE, ReadVar :=Var1);
OperatingStart:=FALSE; END_IF;

// Execute FileReadVar instruction.

IF (Operating=TRUE) THEN

FileReadVar_instance(

Execute :=TRUE,

FileName :='File1.dat', // File name

ReadVar :=Var1);

// Variable to read

IF (FileReadVar_instance.Done=TRUE) THEN // Processing after normal end. Operating:=FALSE;
END_IF;

IF (FileReadVar_instance.Error=TRUE) THEN // Processing after error end. Operating:=FALSE;
END_IF; END_IF;

NJ/NX-series Instructions Reference Manual (W502)

2-1383

2 Instruction Descriptions

FileOpen

The FileOpen instruction opens the specified file in the SD Memory Card.

Instruction FileOpen

Name Open File

FB/FUN FB

Graphic expression

FileOpen_instance

FileOpen

Execute FileName Mode

Done Busy Error ErrorID FileID

ST expression
FileOpen_instance(Execute, FileName, Mode, Done, Busy, Error, ErrorID, FileID);

Variables

Name

Meaning

I/O

FileName File name

Mode FileID

Input Open mode

File ID

Output

Description Name of file to open
Mode in which to open file

Valid range

Unit

66 bytes max. (65 sin-

gle-byte alphanumeric

characters plus the final

NULL character)

---

*

ID of file that was opened Depends on data type. ---

Default ''
_READ_ EXIST
---

* _READ_EXIST, _RDWR_EXIST, _WRITE_CREATE, _RDWR_CREATE, _WRITE_APPEND and _RDWR_APPEND

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

FileName Mode FileID

OK Refer to Function for the enumerators for the enumerated type _eFOPEN_MODE.
OK

Function

The FileOpen instruction opens the file specified by FileName in the SD Memory Card in the mode specified by Mode. The result is output to file ID FileID. FileID is used to specify the file in other instructions, such as FileRead and FileWrite.
The data type of Mode is enumerated type _eFOPEN_MODE. The meanings of the enumerators are as follows:

Enumerator _READ_EXIST _RDWR_EXIST
_WRITE_CREATE

Meaning
Use this value to open a text file to read it. The file is read from the beginning.
Use this value to open a file to read and write it. The file is read and written from the beginning.
Use this value to open a file to write it. If the file already exists, the contents is discarded and the file size is set to 0. If the file does not exist, a new file is created. The file is written from the beginning. However, if the file already exists and it is write-protected, an error occurs and the file is not opened.

2-1384

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

FileOpen

2 Instruction Descriptions

Enumerator _RDWR_CREATE
_WRITE_APPEND
_RDWR_APPEND

Meaning
Use this value to open a file to read and write it. If the file already exists, the contents is discarded and the file size is set to 0. If the file does not exist, a new file is created. The file is read and written from the beginning.
Use this value to open a file to append data to it. If the file does not exist, a new file is created. The data is appended to the end of the file. However, if the file already exists and it is write-protected, an error occurs and the file is not opened.
Use this value to open a file to read and append data to it. If the file does not exist, a new file is created. The file is read from the beginning. The data is appended to the end of the file.

The following figure shows a programming example. The file named 'Temp/f_name.bin' is opened to

append data to it. The file ID is assigned to variable mno.

2

LD

ST

A
'Temp/f_name.bin' _WRITE_APPEND

FileOpen_instance

FileOpen

Execute FileName Mode

Done Busy Error ErrorID FileID

abc
def ghi jkl mno

FileOpen_instance(A, `Temp/f_name.bin', _WRITE_APPEND, abc, def, ghi, jkl, mno);

The FileOpen instruction opens the file specified by FileName from the SD Memory Card to append data to it. The file ID is assigned to variable FileID.
File FileName = `Temp/f_name.bin' File is opened to append data to it. Mode = _WRITE_APPEND
FileID = mno
The file ID is assigned.

NJ/NX-series Instructions Reference Manual (W502)

2-1385

2 Instruction Descriptions

Related System-defined Variables

Name _Card1Ready
_Card1Protect*2 _Card1Err*2
_Card1Access*2 _Card1PowerFail

Meaning
SD Memory Card Ready Flag

Data type BOOL

SD Memory Card Write BOOL Protected Flag
SD Memory Card Error BOOL Flag

SD Memory Card Access Flag

BOOL

SD Memory Card

BOOL

Power Interruption Flag

Description
This flag indicates if the SD Memory Card can be accessed by instructions and communications commands.*1
TRUE: Can be used. FALSE: Cannot be used.
This flag indicates if the SD Memory Card is write protected when it is inserted and ready to use.
TRUE: Write protected. FALSE: Not write protected.
This flag indicates if an unspecified SD Memory Card (e.g., an SDHC card) is mounted or if the format is incorrect (i.e., not FAT16 or corrupted). TRUE: Error. FALSE: No error.
This flag indicates if the SD Memory Card is currently being accessed. TRUE: Being accessed. FALSE: Not being accessed.
This flag indicates if an error occurred in completing processing when power was interrupted during access*3. This flag is not cleared automatically. TRUE: Error. FALSE: No error.

*1 For the NJ/NX-series, it is a precondition that the SD Memory Card is physically inserted and mounted normally. For an NY-series Controller, it is a precondition that the shared folder is detected by the Controller.
*2 These variables are not used for the NY-series Controller. They are fixed to FALSE.
*3 For the NJ/NX-series, this indicates an access to the SD Memory Card. For an NY-series Controller, this indicates an access to the shared folder.

Additional Information
The root directory of the file name is the top level of the SD Memory Card.

Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error.
· This instruction must be executed before any of the following instructions: FileSeek, FileRead, FileWrite, FileGets, and FilePuts.
· You must use the FileClose instruction to close any file that is opened with this instruction after you finish using it.
· A value is stored in FileID when the instruction is completed. Specifically, it is stored when the value of Done changes from FALSE to TRUE.
· If a file is open when the operating mode of the CPU Unit is changed to PROGRAM mode or when a major fault level Controller error occurs, the file is closed by the system. Any read/write operations that are in progress are completed to the end.

2-1386

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

FileOpen

2 Instruction Descriptions

· For an NJ/NX-series CPU Unit, if a file is open when the power supply is stopped with the SD Memory Card power supply switch, the file is not corrupted. However, use the FileClose instruction to close the file, since the file remains open.

· For an NJ/NX-series CPU Unit, if a file is open and the SD Memory Card is removed before the SD Memory Card power supply switch is pressed, the contents of the file will sometimes be corrupted. Always turn OFF the power supply before removing the SD Memory Card.

· For an NJ/NX-series CPU Unit, if a file is open and the SD Memory Card is removed before the SD Memory Card power supply switch is pressed, the file will remain open. Use the FileClose instruction to close the file.

· For an NJ/NX-series CPU Unit, if a file is open when the power supply is stopped or the SD Memory

Card is removed, the file will remain open, but it will not be possible to read or write the file even if the

SD Memory Card is inserted again. To read/write the file, close the file and then open it again. · Do not simultaneously access the same file. Perform exclusive control of SD Memory Card instruc-

2

tions in the user program.

· An error occurs in the following cases. Error will change to TRUE.

· The SD Memory Card is not in a usable condition.

· The SD Memory Card is write protected.

· The value of Mode is _READ_EXIST or _RDWR_EXIST and the file specified with FileName does not exist.

· The value of FileName is not a valid file name.

· The maximum number of files or directories is exceeded.

· The file specified by FileName is being accessed.

· The file specified by FileName is write protected.

· An attempt was made to open more than five files at the same time.

· The value of FileName exceeds the maximum number of bytes allowed in a file name.

· An error that prevents access occurs during SD Memory Card access.

· The value of Mode is outside of the valid range.

· For CPU Unit version 1.10 or later, if you try to open a file that is already open, a File Already in Use error occurs and the file ID of the open file is stored in the FileID output variable. The FileID output variable does not change if any other error occurs. For CPU Unit version 1.09 or earlier, 0 is stored in the FileID output variable if an error occurs.

Sample Programming
Refer to the sample programming for the following instructions: FileRead (page 2-1395), FileWrite (page 2-1403), FileGets (page 2-1411), and FilePuts (page 2-1419).

NJ/NX-series Instructions Reference Manual (W502)

2-1387

2 Instruction Descriptions

FileClose

The FileClose instruction closes the specified file in the SD Memory Card.

Instruction FileClose

Name Close File

FB/FUN FB

Graphic expression

FileClose_instance

FileClose

Execute FileID

Done Busy Error ErrorID

ST expression
FileClose_instance(Execute, FileID, Done, Busy, Error, ErrorID);

Variables

Name FileID

Meaning

I/O

File ID

Input

Description ID of file to close

Valid range

Unit

Depends on data type. ---

Default 0

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

FileID

OK

Function

The FileClose instruction closes the file specified by FileID in the SD Memory Card.
The following figure shows a programming example. Here, the file whose file ID is the value of variable abc is closed.

LD

ST

A abc

FileClose_instance

FileClose

Execute FileID

Done Busy Error ErrorID

def
ghi jkl mno

FileClose_instance(A, abc, def, ghi, jkl, mno);

The FileClose instruction closes the file specified by FileID in the SD Memory Card.

The file is closed.

File FileID = abc

2-1388

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

SD Memory Card Instructions

FileClose

Related System-defined Variables

Name _Card1Ready
_Card1Protect*2 _Card1Err*2
_Card1Access*2 _Card1PowerFail

Meaning

Data type

Description

SD Memory Card Ready Flag

BOOL

This flag indicates if the SD Memory Card can be accessed by instructions and communications commands.*1

TRUE: Can be used.

FALSE: Cannot be used.

SD Memory Card Write BOOL Protected Flag

This flag indicates if the SD Memory Card is write pro-

tected when it is inserted and ready to use.

TRUE: Write protected.

2

FALSE: Not write protected.

SD Memory Card Error BOOL Flag

This flag indicates if an unspecified SD Memory Card (e.g., an SDHC card) is mounted or if the format is incorrect (i.e., not FAT16 or corrupted).

TRUE: Error.

FALSE: No error.

SD Memory Card Access Flag

BOOL

This flag indicates if the SD Memory Card is currently being accessed.

TRUE: Being accessed.

FALSE: Not being accessed.

SD Memory Card

BOOL

Power Interruption Flag

This flag indicates if an error occurred in completing processing when power was interrupted during access*3. This flag is not cleared automatically.

TRUE: Error.

FALSE: No error.

*1 For the NJ/NX-series, it is a precondition that the SD Memory Card is physically inserted and mounted normally. For an NY-series Controller, it is a precondition that the shared folder is detected by the Controller.
*2 These variables are not used for the NY-series Controller. They are fixed to FALSE.
*3 For the NJ/NX-series, this indicates an access to the SD Memory Card. For an NY-series Controller, this indicates an access to the shared folder.

Additional Information
You must open files with the FileOpen instruction for the following instructions: FileSeek, FileRead, FileWrite, FileGets, and FilePuts.
Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error. · You must use the FileOpen instruction in advance to obtain the value for FileID. · You must use this instruction to close any file that is opened with the FileOpen instruction after you
finish using it. · If a file is open when the operating mode of the CPU Unit is changed to PROGRAM mode or when a
major fault level Controller error occurs, the file is closed by the system. Any read/write operations that are in progress are completed to the end.

NJ/NX-series Instructions Reference Manual (W502)

2-1389

2 Instruction Descriptions
· For an NJ/NX-series CPU Unit, if a file is open when the power supply is stopped with the SD Memory Card power supply switch, the file is not corrupted. However, use the FileClose instruction to close the file, since the file remains open.
· For an NJ/NX-series CPU Unit, if a file is open and the SD Memory Card is removed before the SD Memory Card power supply switch is pressed, the contents of the file will sometimes be corrupted. Always turn OFF the power supply before removing the SD Memory Card.
· For an NJ/NX-series CPU Unit, if a file is open and the SD Memory Card is removed before the SD Memory Card power supply switch is pressed, the file will remain open. Use the FileClose instruction to close the file.
· For an NJ/NX-series CPU Unit, if a file is open when the power supply is stopped or the SD Memory Card is removed, the file will remain open, but it will not be possible to read or write the file even if the SD Memory Card is inserted again. To read/write the file, close the file and then open it again.
· Do not simultaneously access the same file. Perform exclusive control of SD Memory Card instructions in the user program.
· An error occurs in the following cases. Error will change to TRUE. · The file specified by FileID does not exist. · The file specified by FileID is already closed. · The file specified by FileID is being accessed. · An error that prevents access occurs during SD Memory Card access. · The SD Memory Card is not in a usable condition.
Sample Programming
Refer to the sample programming for the following instructions: FileRead (page 2-1395), FileWrite (page 2-1403), FileGets (page 2-1411), and FilePuts (page 2-1419).

2-1390

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

FileSeek

2 Instruction Descriptions

FileSeek

The FileSeek instruction sets a file position indicator in the specified file in the SD Memory Card.

Instruction FileSeek

Name Seek File

FB/FUN FB

Graphic expression

ST expression

FileSeek_instance

FileSeek

Execute FileID Offset Origin

Done Busy Error ErrorID

FileSeek_instance(Execute, FileID, Offset, Origin, Done, Busy, Error, ErrorID);
2

Variables

Name

Meaning

I/O

FileID

File ID

Offset Origin

Offset
Reference position

Input

Description
ID of file in which to set file position indicator
Offset from Origin
Reference position for file position indicator

Valid range
Depends on data type.
_SEEK_SET, _SEEK_CUR, or _SEEK_END

Unit
---
Bytes
---

Default
0
_SEEK _SET

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

FileID Offset Origin

OK OK
Refer to Function for the enumerators for the enumerated type _eFSEEK_ORIGIN.

Function

The FileSeek instruction sets a file position indicator in the file specified by file ID FileID in the SD Memory Card. A file position indicator is the position in a file at which to start reading or writing when an instruction such as the FileRead or FileWrite instruction is executed. For example, to read from the beginning of a file, set a file position indicator at the beginning of the file with the FileSeek instruction, and then execute the FileRead instruction. The file position indicator is set at offset Offset from reference position Origin.
The data type of Origin is enumerated type _eFSEEK_ORIGIN. The meanings of the enumerators are as follows:

Enumerator

Meaning

_SEEK_SET Beginning of file

_SEEK_CUR Location of current file position indicator

_SEEK_END End of file

NJ/NX-series Instructions Reference Manual (W502)

2-1391

2 Instruction Descriptions

The following figure shows a programming example. A file position indicator is set at 100 bytes from the beginning of the file.

LD

ST

A
abc DINT#100 _SEEK_SET

FileSeek_instance

FileSeek

Execute FileID Offset Origin

Done Busy Error ErrorID

def
ghi jkl mno

FileSeek_instance(A, abc, DINT#100, _SEEK_SET, def, ghi, jkl, mno);

The FileSeek instruction sets a file position indicator in the file specified by FileID in the SD Memory Card. The file position indicator is at the position that is Offset from the beginning of the file.

Reference position Origin = _SEEK_SET
The reference position is at the beginning of the file.

File FileID = abc

The position that is 100 bytes from the beginning of the file.

The offset Offset = DINT#100 The offset is 100 bytes.

File position indicator

2-1392

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

SD Memory Card Instructions

FileSeek

Related System-defined Variables

Name _Card1Ready
_Card1Protect*2 _Card1Err*2
_Card1Access*2 _Card1PowerFail

Meaning

Data type

Description

SD Memory Card Ready Flag

BOOL

This flag indicates if the SD Memory Card can be accessed by instructions and communications commands.*1

TRUE: Can be used.

FALSE: Cannot be used.

SD Memory Card Write BOOL Protected Flag

This flag indicates if the SD Memory Card is write

protected when it is inserted and ready to use.

TRUE: Write protected.

2

FALSE: Not write protected.

SD Memory Card Error BOOL Flag

This flag indicates if an unspecified SD Memory Card (e.g., an SDHC card) is mounted or if the format is incorrect (i.e., not FAT16 or corrupted).

TRUE: Error.

FALSE: No error.

SD Memory Card Access Flag

BOOL

This flag indicates if the SD Memory Card is currently being accessed.

TRUE: Being accessed.

FALSE: Not being accessed.

SD Memory Card

BOOL

Power Interruption Flag

This flag indicates if an error occurred in completing processing when power was interrupted during access*3. This flag is not cleared automatically.

TRUE: Error.

FALSE: No error.

*1 For the NJ/NX-series, it is a precondition that the SD Memory Card is physically inserted and mounted normally. For an NY-series Controller, it is a precondition that the shared folder is detected by the Controller.
*2 These variables are not used for the NY-series Controller. They are fixed to FALSE.
*3 For the NJ/NX-series, this indicates an access to the SD Memory Card. For an NY-series Controller, this indicates an access to the shared folder.

Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error. · You must use the FileOpen instruction to obtain the value for FileID before you execute this instruc-
tion. · Do not simultaneously access the same file. Perform exclusive control of SD Memory Card instruc-
tions in the user program. · An error occurs in the following cases. Error will change to TRUE.
· The value of Origin is outside of the valid range. · The SD Memory Card is not in a usable condition. · The file specified by FileID does not exist. · The file specified by FileID is being accessed. · The position specified by Origin and Offset exceeds the file size. · An error that prevents access occurs during SD Memory Card access.

NJ/NX-series Instructions Reference Manual (W502)

2-1393

2 Instruction Descriptions
Sample Programming
Refer to the sample programming for the following instructions: FileRead (page 2-1395) and FileWrite (page 2-1403).

2-1394

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

FileRead

2 Instruction Descriptions

FileRead

The FileRead instruction reads the data from the specified file in the SD Memory Card.

Instruction FileRead

Name Read File

FB/FUN FB

Graphic expression

ST expression

FileRead_instance

FileRead

Execute FileID

Done Busy

FileRead_instance(Execute, FileID, ReadBuf, Size, Done, Busy, Error, ErrorID, ReadSize, EOF);

ReadBuf
2

Size

Error

ErrorID

ReadSize

EOF

Variables

Name FileID Size
ReadBuf[] (array) ReadSize
EOF

Meaning

I/O

File ID

Number of Input elements to read

Read buffer In-out

Number of read elements
End of file

Output

Description

Valid range

Unit

ID of file to read

Number of elements to read Depends on data type. ---

Buffer in which to write data Depends on data type. --that was read
Number of elements that were actually read

Whether end of file was reached
TRUE: Reached.
FALSE: Not reached.

Depends on data type. ---

Default 0 1
---
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

FileID Size ReadBuf[] (array)
ReadSize EOF

OK OK
OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK Arrays enumerations or structures can also be specified. OK
OK

NJ/NX-series Instructions Reference Manual (W502)

2-1395

2 Instruction Descriptions

Function

The FileRead instruction reads the data from position of the file position indicator in the file specified by file ID FileID in the SD Memory Card. It then stores the data in read buffer ReadBuf[]. The file position indicator is set at the desired location in advance with the FileSeek instruction. The amount of data that is read is the size of the data type of ReadBuf[] times Size. You can specify an array of enumerations or structures for ReadBuf[]. The actual number of elements that were read is stored in ReadSize. Normally, Size and ReadSize will have the same values. If the amount of data from the file position indicator to the end of the file is smaller than Size, an error will not occur and the data to the end of the file is stored in ReadBuf[]. If that occurs, the value of ReadSize will be smaller than the value of Size. If data is read to the end of the file, end of file EOF changes to TRUE. Otherwise, the value of EOF will be FALSE.
The following figure shows a programming example. If the read buffer def[] is a BYTE array, 100 bytes of data is read from the file.

LD

ST

FileRead_instance

A

FileRead

ghi

abc def[0]

Execute FileID ReadBuf

Done Busy

jkl def[0]

UINT#100 Size

Error mno ErrorID pqr ReadSize stu
EOF vwx

FileRead_instance(A, abc, def[0], UINT#100, ghi, jkl, mno, pqr, stu, vwx);

The FileRead instruction reads Size elements from the position of the file position indicator in the file specified by FileID in the SD Memory Card. It then stores the data in read buffer ReadBuf[]. The actual data size that was read is output to ReadSize.
File FileID = abc

File position indicator

00AB 24

Read.

ReadBuf[0] =def[0]

ReadBuf[1] =def[1]

:

:

ReadBuf[99]=def[99]

BYTE#16#00 BYTE#16#AB
: BYTE#16#24

ReadSize UINT#100

Size UINT#100

From the position of the file position indicator, 100 elements are read. The def[] array is a BYTE array, so 100 bytes are read.

The data that was actually read was 100 bytes.

Related System-defined Variables

Name _Card1Ready

Meaning
SD Memory Card Ready Flag

Data type BOOL

Description
This flag indicates if the SD Memory Card can be accessed by instructions and communications commands.*1
TRUE: Can be used.
FALSE: Cannot be used.

2-1396

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

SD Memory Card Instructions

FileRead

Name _Card1Protect*2 _Card1Err*2
_Card1Access*2 _Card1PowerFail

Meaning

Data type

Description

SD Memory Card Write BOOL Protected Flag

This flag indicates if the SD Memory Card is write protected when it is inserted and ready to use.

TRUE: Write protected.

FALSE: Not write protected.

SD Memory Card Error BOOL Flag

This flag indicates if an unspecified SD Memory Card (e.g., an SDHC card) is mounted or if the format is incorrect (i.e., not FAT16 or corrupted).

TRUE: Error.

FALSE: No error.

SD Memory Card Access Flag

BOOL

This flag indicates if the SD Memory Card is cur-

rently being accessed.

2

TRUE: Being accessed.

FALSE: Not being accessed.

SD Memory Card

BOOL

Power Interruption Flag

This flag indicates if an error occurred in completing processing when power was interrupted during access*3. This flag is not cleared automatically.

TRUE: Error.

FALSE: No error.

*1 For the NJ/NX-series, it is a precondition that the SD Memory Card is physically inserted and mounted normally. For an NY-series Controller, it is a precondition that the shared folder is detected by the Controller.
*2 These variables are not used for the NY-series Controller. They are fixed to FALSE.
*3 For the NJ/NX-series, this indicates an access to the SD Memory Card. For an NY-series Controller, this indicates an access to the shared folder.

Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error.
· If the data is read to the end of the file and the size of the data is not evenly divisible by the size of the data type of ReadBuf[], the data that is insufficient for the data size of ReadBuf[] is discarded. The file position indicator advances to the end of the file, and the value of EOF changes to TRUE.
· Elements beyond Size times ReadBuf[] (i.e., the elements not overwritten when data is read) will retain the values from before execution of this instruction.
· You must use the FileOpen instruction to obtain the value for FileID before you execute this instruction.
· Data is read in byte increments. The lower bytes are read before the upper bytes (little endian).
· A value is stored in EOF when the instruction is completed. Specifically, it is stored when the value of Done changes from FALSE to TRUE.
· If ReadBuf[] is an array of structures, adjustment areas between members may be inserted depending on the composition.
· If the operating mode of the CPU Unit is changed to PROGRAM mode or when a major fault level Controller error occurs during instruction execution, the file is closed by the system. Any read/write operations that are in progress are completed to the end.
· Do not simultaneously access the same file. Perform exclusive control of SD Memory Card instructions in the user program.
· You cannot specify a device variable for ReadBuf[]. If you specify a device variable, the data that was read is not assigned to ReadBuf[].
· An error occurs in the following cases. Error will change to TRUE.

NJ/NX-series Instructions Reference Manual (W502)

2-1397

2 Instruction Descriptions

· The number of array elements in ReadBuf[] is smaller than the value of Size. · The SD Memory Card is not in a usable condition. · The file specified by FileID does not exist. · The file specified by FileID is being accessed. · The file specified by FileID was not opened in a reading mode. · An error that prevents access occurs during SD Memory Card access.

Sample Programming

In this sample, four bytes of data are read from the second byte from beginning of the file named 'ABC.bin.' The data is written to BYTE array variable InDat[]. The processing procedure is as follows:
1 The FileOpen instruction is used to open the file `ABC.bin.'

2 The FileSeek instruction is used to set a file position indicator at the second byte from the begin-
ning of the file.

3 The FileRead instruction is used to read four bytes of data from the position of the file position
indicator and store it in array variable InDat[].

4 The FileClose instruction is used to close the file `ABC.bin.'

LD
Internal Variables

Variable
OperatingEnd Trigger Operating Fid

InDat

RS_instance FileOpen_instance FileSeek_instance FileRead_instance FileClose_instance

Data type
BOOL BOOL BOOL DWORD ARRAY[0..999] OF BYTE RS FileOpen FileSeek FileRead FileClose

Initial value
FALSE FALSE FALSE 16#0
[1000(16#0)]

Comment
Processing completed. Execution condition Processing File ID
Read data

External Variables

Variable _Card1Ready

Data type BOOL

Comment SD Memory Card Ready Flag

2-1398

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

2 Instruction Descriptions

Determine if instruction execution is completed.

FileClose_instance.Done

OperatingEnd

FileOpen_instance.Error

FileSeek_instance.Error

FileRead_instance.Error

2

FileClose_instance.Error

Accept trigger. Trigger _Card1Ready
OperatingEnd

RS_instance

RS

Set

Q1

Reset1

Operating

Execute FileOpen instruction. Operating

FileOpen_instance FileOpen

Execute Done

`ABC.bin' FileName Busy

_READ_EXIST Mode

Error

ErrorID

FileID Fid

FileOpen_instance.Error

Inline ST
1 // Processing after error end. 2 ;

FileRead

NJ/NX-series Instructions Reference Manual (W502)

2-1399

2 Instruction Descriptions

Execute FileSeek instruction. Operating FileOpen_instance.Done

Fid DINT#2 _SEEK_SET

FileSeek_instance

FileSeek

Execute FileID Offset Origin

Done Busy Error ErrorID

FileSeek_instance.Error

Inline ST
1 // Processing after error end. 2 ;

Execute FileRead instruction. Operating FileSeek_instance.Done

Fid
InDat[0] UINT#4

FileRead_instance

FileRead

Execute FileID ReadBuf

Done Busy

Size

Error

ErrorID

ReadSize

EOF

FileRead_instance.Error

Inline ST
1 // Processing after error end. 2 ;

Execute FileClose instruction. Operating FileRead_instance.Done

FileClose_instance

FileClose

Execute

Done

Fid FileID

Busy

Error

ErrorID

FileClose_instance.Error

Inline ST
1 // Processing after error end. 2 ;

Processing after normal end. Operating FileRead_instance.Done FileClose_instance.Done

Inline ST
1 // Processing after normal end. 2 ;

2-1400

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

SD Memory Card Instructions

FileRead

ST

Internal Variables

Variable

Data type

Initial value

Comment

Trigger

BOOL

FALSE

Execution condition

LastTrigger

BOOL

FALSE

Value of Trigger from previous task period

OperatingStart

BOOL

FALSE

Processing started.

Operating

BOOL

FALSE

Processing

InDat

ARRAY[0..999] OF BYTE

[1000(16#0)]

Read data

Stage

INT

0

Stage change

2

Fid

DWORD

16#0

File ID

FileOpen_instance

FileOpen

FileSeek_instance

FileSeek

FileRead_instance

FileRead

FileClose_instance

FileClose

External Variables

Variable _Card1Ready

Data type BOOL

Comment SD Memory Card Ready Flag

// Start sequence when Trigger changes to TRUE. IF ( (Trigger=TRUE) AND (LastTrigger=FALSE) AND (_Card1Ready=TRUE) ) THEN
OperatingStart:=TRUE; Operating :=TRUE; END_IF; LastTrigger:=Trigger;

// Initialize instance.

IF (OperatingStart=TRUE) THEN

FileOpen_instance(Execute:=FALSE);

FileSeek_instance(Execute:=FALSE);

FileRead_instance(

Execute:=FALSE,

ReadBuf:=InDat[0]);

FileClose_instance(Execute:=FALSE);

Stage

:=INT#1;

OperatingStart:=FALSE;

END_IF;

// Initialize instance. // Initialize instance.
// Initialize instance. // Dummy // Initialize instance.

// Execute instructions.

IF (Operating=TRUE) THEN

CASE Stage OF

1 : // Open file.

FileOpen_instance(

Execute:=TRUE,

FileName:='ABC.bin', // File name

Mode :=_READ_EXIST, // Read file.

FileID =>Fid);

// File ID

IF (FileOpen_instance.Done=TRUE) THEN

Stage:=INT#2;

// Normal end

END_IF;

IF (FileOpen_instance.Error=TRUE) THEN

Stage:=INT#99;

// Error end

END_IF;

NJ/NX-series Instructions Reference Manual (W502)

2-1401

2 Instruction Descriptions

2 : // Seek file.

FileSeek_instance(

Execute:=TRUE,

FileID :=Fid,

// File ID

Offset :=DINT#2, // File position indicator goes to second byte from the beginning.

Origin :=_SEEK_SET);

IF (FileSeek_instance.Done=TRUE) THEN Stage:=INT#3; // Normal end
END_IF;

IF (FileSeek_instance.Error=TRUE) THEN Stage:=INT#99; // Error end
END_IF;

3 : // Read file. FileRead_instance( Execute :=TRUE, FileID :=Fid, // File ID ReadBuf :=InDat[0],// Read buffer Size :=UINT#4); // Number of elements to read: 4 bytes

IF (FileRead_instance.Done=TRUE) THEN

Stage:=INT#4;

// Normal end

END_IF;

IF (FileRead_instance.Error=TRUE) THEN Stage:=INT#99; // Error end
END_IF;

4 : // Close file. FileClose_instance( Execute:=TRUE, FileID :=Fid);

// File ID

IF (FileClose_instance.Done=TRUE) THEN Operating:=FALSE; // Normal end
END_IF;

IF (FileClose_instance.Error=TRUE) THEN Stage:=INT#99; // Error end
END_IF;

99 : Operating:=FALSE;
END_CASE; END_IF;

// Processing after error end.

2-1402

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

FileWrite

2 Instruction Descriptions

FileWrite

The FileWrite instruction writes data to the specified file in the SD Memory Card.

Instruction FileWrite

Name Write File

FB/FUN FB

Graphic expression

FileWrite_instance

FileWrite

Execute

Done

FileID

Busy

WriteBuf Error

Size

ErrorID

WriteSize

ST expression
FileWrite_instance(Execute, FileID, WriteBuf, Size, Done, Busy, Error, ErrorID, WriteSize);
2

Variables

Name

Meaning

I/O

Description

Valid range

Unit

FileID WriteBuf[] (array) Size
WriteSize

File ID Write buffer

Number of elements to write
Number of written elements

Input Output

ID of file to write Write data
Depends on data type. --Number of elements to write

Number of elements that were actually written

Depends on data type. ---

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default 0 * 1
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

FileID
WriteBuf[] (array)
Size WriteSize

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK
Arrays of enumerations or structures can also be specified. OK OK

Function
The FileWrite instruction writes data to the position of the file position indicator in the file specified by file ID FileID in the SD Memory Card. The file position indicator is set at the desired location in advance with the FileSeek instruction. The contents of the write buffer WriteBuf[] is written to the file. The amount of data that is written is the size of the data type of WriteBuf[] times Size. You can specify an array of enumerations or structures for WriteBuf[]. The data size that is actually written is output to WriteSize.

NJ/NX-series Instructions Reference Manual (W502)

2-1403

2 Instruction Descriptions

The following figure shows a programming example. If the write buffer def[] is BYTE data, 100 bytes of data is written to the file.

LD

ST

A
abc def[0] UINT#100

FileWrite_instance

FileWrite

Execute

Done

FileID

Busy

WriteBuf Error

Size

ErrorID

WriteSize

ghi
jkl mno pqr stu

FileWrite_instance(A, abc, def[0], UINT#100, ghi, jkl, mno, pqr, stu);

The FileWrite instruction writes the contents of the write buffer WriteBuf[] to the position of the file position indicator in the file specified by FileID in the SD Memory Card. Then the data size that is actually written is output to WriteSize.
File FileID = abc

WriteBuf[0] =def[0]

WriteBuf[1] =def[1]

:

:

WriteBuf[99]=def[99]

BYTE#16#00 BYTE#16#AB
: BYTE#16#24

Written.

00AB 24

Size UINT#100

File position indicator

Writing is performed for 100 elements.

One-hundred elements are written to the position of the file position indicator. The def[] array is a BYTE array, so 100 bytes are written.
WriteSize UINT#100

The data that was actually written was 100 bytes.

Related System-defined Variables

Name _Card1Ready
_Card1Protect*2

Meaning SD Memory Card Ready Flag
SD Memory Card Write Protected Flag

Data type BOOL
BOOL

Description
This flag indicates if the SD Memory Card can be accessed by instructions and communications commands.*1 TRUE: Can be used. FALSE: Cannot be used.
This flag indicates if the SD Memory Card is write protected when it is inserted and ready to use. TRUE: Write protected. FALSE: Not write protected.

2-1404

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

FileWrite

2 Instruction Descriptions

Name

Meaning

Data type

Description

_Card1Err*2

SD Memory Card Error BOOL Flag

This flag indicates if an unspecified SD Memory Card (e.g., an SDHC card) is mounted or if the format is incorrect (i.e., not FAT16 or corrupted).

TRUE: Error.

FALSE: No error.

_Card1Access*2

SD Memory Card Access Flag

BOOL

This flag indicates if the SD Memory Card is currently being accessed.

TRUE: Being accessed.

FALSE: Not being accessed.

_Card1PowerFail SD Memory Card Power BOOL Interruption Flag

This flag indicates if an error occurred in completing process-

ing when power was interrupted during access*3. This flag is

2

not cleared automatically.

TRUE: Error.

FALSE: No error.

*1 For the NJ/NX-series, it is a precondition that the SD Memory Card is physically inserted and mounted normally. For an NY-series Controller, it is a precondition that the shared folder is detected by the Controller.
*2 These variables are not used for the NY-series Controller. They are fixed to FALSE.
*3 For the NJ/NX-series, this indicates an access to the SD Memory Card. For an NY-series Controller, this indicates an access to the shared folder.

Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error. · You must use the FileOpen instruction to obtain the value for FileID before you execute this instruc-
tion. · Data is written in byte increments. The lower bytes are written before the upper bytes (little endian). · If WriteBuf[] is an array of structures, adjustment areas between members may be inserted depend-
ing on the composition. · If the operating mode of the CPU Unit is changed to PROGRAM mode or when a major fault level
Controller error occurs during instruction execution, the file is closed by the system. Any read/write operations that are in progress are completed to the end. · Do not simultaneously access the same file. Perform exclusive control of SD Memory Card instructions in the user program. · An error occurs in the following cases. Error will change to TRUE. · The number of array elements in WriteBuf[] is smaller than the value of Size. · The SD Memory Card is not in a usable condition. · The SD Memory Card is write protected. · There is insufficient space available on the SD Memory Card. · The file specified by FileID does not exist. · The file specified by FileID is being accessed. · The file specified by FileID was not opened in a writing mode. · An error that prevents access occurs during SD Memory Card access.

NJ/NX-series Instructions Reference Manual (W502)

2-1405

2 Instruction Descriptions
Sample Programming
Here, four bytes of data are written from the second byte from the beginning of the file 'ABC.bin.' The contents of the BYTE array variable OutDat[] is written to the file. The processing procedure is as follows:
1 The FileOpen instruction is used to open the file `ABC.bin.' 2 The FileSeek instruction is used to set a file position indicator at the second byte from the begin-
ning of the file.
3 The FileWrite instruction is used to write four bytes from array variable OutDat[] to the position
of the file position indicator.
4 The FileClose instruction is used to close the file `ABC.bin.'

2-1406

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

SD Memory Card Instructions

FileWrite

LD
Internal Variables

Variable
OperatingEnd Trigger Operating Fid

OutDat

RS_instance FileOpen_instance FileSeek_instance FileWrite_instance FileClose_instance

Data type
BOOL BOOL BOOL DWORD ARRAY[0..999] OF BYTE RS FileOpen FileSeek FileWrite FileClose

Initial value
FALSE FALSE FALSE 16#0
[1000(16#0)]

Comment Processing completed. Execution condition Processing File ID Write data
2

External Variables

Variable _Card1Ready

Data type BOOL

Comment SD Memory Card Ready Flag

Determine if instruction execution is completed.

FileClose_instance.Done

OperatingEnd

FileOpen_instance.Error

FileSeek_instance.Error

FileWrite_instance.Error

FileClose_instance.Error

Accept trigger. Trigger _Card1Ready
OperatingEnd

RS_instance

RS

Set

Q1

Reset1

Operating

Execute FileOpen instruction. Operating

FileOpen_instance FileOpen

Execute Done

`ABC.bin' FileName Busy

_RDWR_CREATE Mode

Error

ErrorID

FileID Fid

FileOpen_instance.Error

Inline ST
1 // Processing after error end. 2 ;

NJ/NX-series Instructions Reference Manual (W502)

2-1407

2 Instruction Descriptions

Execute FileSeek instruction. Operating FileOpen_instance.Done

Fid DINT#2 _SEEK_SET

FileSeek_instance

FileSeek

Execute FileID Offset Origin

Done Busy Error ErrorID

FileSeek_instance.Error

Inline ST
1 // Processing after error end. 2 ;

Execute FileWrite instruction. Operating FileSeek_instance.Done

Fid OutDat[0]
UINT#4

FileWrite_instance

FileWrite

Execute

Done

FileID

Busy

WriteBuf Error

Size

ErrorID

WriteSize

FileWrite_instance.Error

Inline ST
1 // Processing after error end. 2 ;

Execute FileClose instruction. Operating FileWrite_instance.Done

FileClose_instance

FileClose

Execute

Done

Fid FileID

Busy

Error

ErrorID

FileClose_instance.Error

Inline ST
1 // Processing after error end. 2 ;

Processing after normal end. Operating FileWrite_instance.Done FileClose_instance.Done

Inline ST
1 // Processing after normal end. 2 ;

2-1408

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

SD Memory Card Instructions

FileWrite

ST

Internal Variables

Variable

Data type

Initial value

Comment

Trigger

BOOL

FALSE

Execution condition

LastTrigger

BOOL

FALSE

Value of Trigger from previous task period

OperatingStart

BOOL

FALSE

Processing started.

Operating

BOOL

FALSE

Processing

OutDat

ARRAY[0..999] OF BYTE

[1000(16#0)]

Write data

Stage

INT

0

Stage change

2

Fid

DWORD

16#0

File ID

FileOpen_instance

FileOpen

FileSeek_instance

FileSeek

FileWrite_instance

FileWrite

FileClose_instance

FileClose

External Variables

Variable _Card1Ready

Data type BOOL

Comment SD Memory Card Ready Flag

// Start sequence when Trigger changes to TRUE. IF ( (Trigger=TRUE) AND (LastTrigger=FALSE) AND (_Card1Ready=TRUE) ) THEN
OperatingStart:=TRUE; Operating :=TRUE; END_IF; LastTrigger:=Trigger;

// Initialize instance.

IF (OperatingStart=TRUE) THEN

FileOpen_instance(Execute:=FALSE);

FileSeek_instance(Execute:=FALSE);

FileWrite_instance(

Execute :=FALSE,

WriteBuf :=OutDat[0]);

FileClose_instance(Execute:=FALSE);

Stage

:=INT#1;

OperatingStart:=FALSE;

END_IF;

// Execute instructions.

IF (Operating=TRUE) THEN

CASE Stage OF

1 : // Open file.

FileOpen_instance(

Execute :=TRUE,

FileName:='ABC.bin', // File name

Mode :=_RDWR_CREATE, // Read file and write.

FileID =>Fid);

// File ID

IF (FileOpen_instance.Done=TRUE) THEN Stage:=INT#2; // Normal end
END_IF;

IF (FileOpen_instance.Error=TRUE) THEN Stage:=INT#99; // Error end
END_IF;

NJ/NX-series Instructions Reference Manual (W502)

2-1409

2 Instruction Descriptions

2 : // Seek file. FileSeek_instance( Execute :=TRUE, FileID :=Fid, // File ID Offset :=DINT#2, // File position indicator goes to second byte from the beginning. Origin :=_SEEK_SET);

IF (FileSeek_instance.Done=TRUE) THEN Stage:=INT#3; // Normal end
END_IF;

IF (FileSeek_instance.Error=TRUE) THEN Stage:=INT#99; // Error end
END_IF;

3 : // Write file.

FileWrite_instance(

Execute :=TRUE,

FileID :=Fid,

// File ID

WriteBuf:=OutDat[0], // Write buffer

Size :=UINT#4); // Number of elements to write: 4 bytes

IF (FileWrite_instance.Done=TRUE) THEN Stage:=INT#4; // Normal end
END_IF;

IF (FileWrite_instance.Error=TRUE) THEN Stage:=INT#99; // Error end
END_IF;

4 : // Close file. FileClose_instance( Execute:=TRUE, FileID :=Fid);

// File ID

IF (FileClose_instance.Done=TRUE) THEN Operating:=FALSE; // Normal end
END_IF;

IF (FileClose_instance.Error=TRUE) THEN Stage:=INT#99; // Error end
END_IF;

99 : Operating:=FALSE;
END_CASE; END_IF;

// Processing after error end.

2-1410

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

FileGets

2 Instruction Descriptions

FileGets

The FileGets instruction reads a text string of one line from the specified file in the SD Memory Card.

Instruction FileGets

Name Get Text String

FB/FUN FB

Graphic expression

ST expression

FileGets_instance

FileGets

Execute FileID TrimLF

Done Busy Error ErrorID Out EOF

FileGets_instance(Execute, FileID, TrimLF, Done, Busy, Error, ErrorID, Out, EOF);
2

Variables

Name FileID TrimLF

Meaning
File ID
Line feed designation

I/O Input

Out EOF

Read text string
End of file

Output

Description
ID of file to read
Handling of the line feed code of text string that was read TRUE: Delete. FALSE: Do not delete.
Text string that was read

Valid range

Unit

Depends on data type. ---

Whether end of file was reached
TRUE: Reached.
FALSE: Not reached.

Depends on data type. ---

Default 0 FALSE
---

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

FileID

OK

TrimLF

OK

Out

OK

EOF

OK

Function
The FileGets instruction reads a text string of one line from the position of the file position indicator in the file specified by file ID FileID in the SD Memory Card. The file position indicator is set at the desired location in advance with the FileSeek instruction. Line endings are determined by a line feed code. The text string that is read is written to read text string Out. The following three line feeds are automatically detected: CR, LF, and CR+LF. If line feed designation TrimLF is TRUE, the line feed code is deleted from the text string before it is written to Out. If data is read to the end of the file, end of file EOF changes to TRUE. Otherwise, the value of EOF will be FALSE.

NJ/NX-series Instructions Reference Manual (W502)

2-1411

2 Instruction Descriptions

The following figure shows a programming example. Here, a text string of one line is read from a file, the line feed code is deleted, and the result is written to pqr.

LD

ST

A
abc TRUE

FileGets_instance

FileGets

Execute FileID TrimLF

Done Busy Error ErrorID Out EOF

def
ghi jkl mno pqr stu

FileGets_instance(A, abc, TRUE, def, ghi, jkl, mno, pqr, stu);

The FileGets instruction reads a text string of one line from the position of the file position indicator in the file specified by FileID in the SD Memory Card and stores it in the read text string Out. The line feed code is deleted.
File FileID = abc

File position indicator

ABCXYZ CR

One line is read. Out=pqr 'ABCXYZ'

TrimLF TRUE Line feed code is deleted.

Related System-defined Variables

Name _Card1Ready
_Card1Protect*2

Meaning
SD Memory Card Ready Flag

Data type BOOL

SD Memory Card Write BOOL Protected Flag

Description
This flag indicates if the SD Memory Card can be accessed by instructions and communications commands.*1
TRUE: Can be used.
FALSE: Cannot be used.
This flag indicates if the SD Memory Card is write protected when it is inserted and ready to use.
TRUE: Write protected.
FALSE: Not write protected.

2-1412

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

FileGets

2 Instruction Descriptions

Name _Card1Err*2
_Card1Access*2 _Card1PowerFail

Meaning

Data type

Description

SD Memory Card Error BOOL Flag

This flag indicates if an unspecified SD Memory Card (e.g., an SDHC card) is mounted or if the format is incorrect (i.e., not FAT16 or corrupted).

TRUE: Error.

FALSE: No error.

SD Memory Card Access Flag

BOOL

This flag indicates if the SD Memory Card is currently being accessed.

TRUE: Being accessed.

FALSE: Not being accessed.

SD Memory Card

BOOL

Power Interruption Flag

This flag indicates if an error occurred in com-

2

pleting processing when power was interrupted

during access*3. This flag is not cleared auto-

matically.

TRUE: Error.

FALSE: No error.

*1 For the NJ/NX-series, it is a precondition that the SD Memory Card is physically inserted and mounted normally. For an NY-series Controller, it is a precondition that the shared folder is detected by the Controller.
*2 These variables are not used for the NY-series Controller. They are fixed to FALSE.
*3 For the NJ/NX-series, this indicates an access to the SD Memory Card. For an NY-series Controller, this indicates an access to the shared folder.

Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error.
· If the length of the one-line text string exceeds 1,986 bytes (with UTF-8 character codes, including the final NULL character), the first 1,985 bytes of the text string are stored in Out with a NULL character attached.
· You must use the FileOpen instruction to obtain the value for FileID before you execute this instruction.
· If the operating mode of the CPU Unit is changed to PROGRAM mode or when a major fault level Controller error occurs during instruction execution, the file is closed by the system. Any read/write operations that are in progress are completed to the end.
· Do not simultaneously access the same file. Perform exclusive control of SD Memory Card instructions in the user program.
· An error occurs in the following cases. Error will change to TRUE.
· The SD Memory Card is not in a usable condition.
· The file specified by FileID does not exist.
· The file specified by FileID is being accessed.
· The file specified by FileID was not opened in a reading mode.
· An error that prevents access occurs during SD Memory Card access.

NJ/NX-series Instructions Reference Manual (W502)

2-1413

2 Instruction Descriptions

Sample Programming

Here, multiple text strings that are separated by CR codes are stored in a file named `ABC.csv.' All of them are text strings of numbers. One line at a time is read from the file, the text strings are converted to integers, and the results are stored in INT array variable InDat[]. Processing is ended when all of the data to the end of the file is read. It is assumed that this sample programming is in a periodic task.

`ABC.csv' file
1234 CR 9876 CR 5678 CR .... . .... . .... . .... . .... . .... . EOF

One line read at a time and converted to a number.

in_data[0] 1234
in_data[1] 9876 in_data[2] 5678
. . . . . . .

The processing procedure is as follows:
1 The FileOpen instruction is used to open the file `ABC.csv.' 2 The FileGets instruction is used to read one line from the file.
3 The STRING_TO_INT instruction is used to convert the text string that was read to an integer
and store it in InDat[].
4 Steps 2 and 3 are repeated until the EOF (end of file).
5 The FileClose instruction is used to close the file.

2-1414

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

SD Memory Card Instructions

FileGets

LD
Internal Variables

Variable
OperatingEnd Trigger Operating Index Fid

InDat

RS_instance FileOpen_instance FileGets_instance FileClose_instance

Data type
BOOL BOOL BOOL INT DWORD ARRAY[0..999] OF INT RS FileOpen FileGets FileClose

Initial value
FALSE FALSE FALSE 0 16#0
[1000(0)]

Comment
Processing completed. Execution condition Processing InDat[] element index File ID
Integer data
2

External Variables

Variable _Card1Ready

Data type BOOL

Comment SD Memory Card Ready Flag

Determine if instruction execution is completed.

FileClose_instance.Done

OperatingEnd

FileOpen_instance.Error

FileGets_instance.Error

FileClose_instance.Error

Accept trigger. Trigger _Card1Ready
OperatingEnd

RS_instance

RS

Set

Q1

Reset1

Operating

Initialize InDat[] element index.

Operating

Inline ST 1 Index:=INT#0;

Execute FileOpen instruction. Operating

FileOpen_instance FileOpen

Execute Done

`ABC.csv' FileName Busy

_READ_EXIST Mode

Error

ErrorID

FileID Fid

FileOpen_instance.Error

Inline ST
1 // Processing after error end. 2 ;

NJ/NX-series Instructions Reference Manual (W502)

2-1415

2 Instruction Descriptions

Execute FileGets instruction. Operating FileOpen_instance.Done FileGets_instance.Busy FileClose_instance.Busy

FileGets_instance FileGets

Fid TRUE

Execute FileID TrimLF

Done Busy Error ErrorID Out EOF

FileGets_instance.Error Inline ST

Execute STRING_TO_INT instruction.

1 // Processing after error end. 2 ;

Operating FileGets_instance.Done

STRING_TO_INT

EN FileGets_instance.Out In

ENO

InDat[Index]

Index

Inc
EN ENO InOut

Execute FileClose when EOF is detected. Operating FileGets_instance.EOF

FileClose_instance

FileClose

Execute

Done

Fid FileID

Busy

Error

ErrorID

FileClose_instance.Error

Inline ST
1 // Processing after error end. 2 ;

Processing after normal end.

Operating

FileClose_instance.Done

Inline ST
1 // Processing after normal end. 2 ;

2-1416

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

SD Memory Card Instructions

FileGets

ST

Internal Variables

Variable

Data type

Initial value

Comment

Trigger

BOOL

FALSE

Execution condition

LastTrigger

BOOL

FALSE

Value of Trigger from previous task period

OperatingStart

BOOL

FALSE

Processing started.

Operating

BOOL

FALSE

Processing

InDat

ARRAY[0..999] OF INT

[1000(0)]

Integer data

Stage

INT

0

Stage change

2

Index

INT

0

InDat[] element index

Fid

DWORD

16#0

File ID

FileOpen_instance

FileOpen

FileGets_instance

FileGets

FileClose_instance

FileClose

External Variables

Variable _Card1Ready

Data type BOOL

Comment SD Memory Card Ready Flag

// Start sequence when Trigger changes to TRUE.

IF ( (Trigger=TRUE) AND (LastTrigger=FALSE) AND (_Card1Ready=TRUE) ) THEN

OperatingStart:=TRUE;

Operating

:=TRUE;

END_IF;

LastTrigger:=Trigger;

// Initialize instance. IF (OperatingStart=TRUE) THEN
FileOpen_instance(Execute:=FALSE); FileGets_instance(Execute:=FALSE); FileClose_instance(Execute:=FALSE); Stage :=INT#1; Index :=INT#0; OperatingStart:=FALSE; END_IF;

// Execute instructions.

IF (Operating=TRUE) THEN

CASE Stage OF

1 :

// Open file.

FileOpen_instance(

Execute:=TRUE,

FileName:='ABC.csv',

Mode :=_READ_EXIST,

FileID =>Fid);

// File name // Read file. // File ID

IF (FileOpen_instance.Done=TRUE) THEN Stage:=INT#2; // Normal end
END_IF;

IF (FileOpen_instance.Error=TRUE) THEN Stage:=INT#99; // Error end
END_IF;

2 :

// Read text string.

FileGets_instance(

Execute:=TRUE,

NJ/NX-series Instructions Reference Manual (W502)

2-1417

2 Instruction Descriptions

FileID :=Fid, TrimLF :=TRUE);

IF (FileGets_instance.Done=TRUE) THEN // Convert the text string that was read to an integer. InDat[Index]:=STRING_TO_INT(FileGets_instance.Out); Index:=Index+INT#1;

// Reached end of file. IF (FileGets_instance.EOF=TRUE) THEN
Stage:=INT#3; // Normal end ELSE
FileGets_instance(Execute:=FALSE); END_IF; END_IF;

IF (FileGets_instance.Error=TRUE) THEN

Stage:=INT#99;

// Error end

END_IF;

3 :

// Close file.

FileClose_instance(

Execute:=TRUE,

FileID :=Fid);

// File ID

IF (FileClose_instance.Done=TRUE) THEN Operating:=FALSE; // Normal end
END_IF;

IF (FileClose_instance.Error=TRUE) THEN Stage:=INT#99; // Error end
END_IF;

99 :

// Processing after error end.

Operating:=FALSE;

END_CASE;

END_IF;

2-1418

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

FilePuts

2 Instruction Descriptions

FilePuts

The FilePuts instruction writes a text string to the specified file in the SD Memory Card.

Instruction FilePuts

Name Put Text String

FB/FUN FB

Graphic expression

ST expression

FilePuts_instance

FilePuts

Execute FileID In

Done Busy Error ErrorID

FilePuts_instance(Execute, FileID, In, Done, Busy, Error, ErrorID);
2

Variables

Name FileID In

Meaning
File ID
Write text string

I/O Input

Description ID of file to write Text string to write

Valid range

Unit

Depends on data type. ---

Default 0 ''

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

FileID

OK

In

OK

Function

The FilePuts instruction writes a text string to the position of the file position indicator in the file specified by file ID FileID in the SD Memory Card. The file position indicator is set at the desired location in advance with the FileSeek instruction. The contents of write text string In is written to the file.
The following figure shows a programming example. Here, the contents of array element def[0] is written to the file.

LD

ST

A
abc def[0]

FilePuts_instance

FilePuts

Execute FileID In

Done Busy Error ErrorID

ghi
jkl mno pqr

FilePuts_instance(A, abc, def[0], ghi, jkl, mno, pqr);

NJ/NX-series Instructions Reference Manual (W502)

2-1419

2 Instruction Descriptions

The FilePuts instruction writes the contents of the write text string In to the position of the file position indicator in the file specified by FileID in the SD Memory Card.
File FileID = abc

In=def[0] 'ABCXYZ CR'

Written.

ABCXYZ CR

File position indicator

Related System-defined Variables

Name _Card1Ready
_Card1Protect*2 _Card1Err*2
_Card1Access*2 _Card1PowerFail

Meaning
SD Memory Card Ready Flag

Data type BOOL

SD Memory Card Write BOOL Protected Flag
SD Memory Card Error BOOL Flag

SD Memory Card Access Flag

BOOL

SD Memory Card

BOOL

Power Interruption Flag

Description
This flag indicates if the SD Memory Card can be accessed by instructions and communications commands.*1 TRUE: Can be used.
FALSE: Cannot be used.
This flag indicates if the SD Memory Card is write protected when it is inserted and ready to use. TRUE: Write protected.
FALSE: Not write protected.
This flag indicates if an unspecified SD Memory Card (e.g., an SDHC card) is mounted or if the format is incorrect (i.e., not FAT16 or corrupted). TRUE: Error. FALSE: No error.
This flag indicates if the SD Memory Card is currently being accessed. TRUE: Being accessed. FALSE: Not being accessed.
This flag indicates if an error occurred in completing processing when power was interrupted during access*3. This flag is not cleared automatically.
TRUE: Error. FALSE: No error.

*1 For the NJ/NX-series, it is a precondition that the SD Memory Card is physically inserted and mounted normally. For an NY-series Controller, it is a precondition that the shared folder is detected by the Controller.
*2 These variables are not used for the NY-series Controller. They are fixed to FALSE.
*3 For the NJ/NX-series, this indicates an access to the SD Memory Card. For an NY-series Controller, this indicates an access to the shared folder.

Additional Information
To create a line feed after you write the text sting, add a line feed code to the end of In.

2-1420

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

2 Instruction Descriptions

Precautions for Correct Use

· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.

· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error.

· You must use the FileOpen instruction to obtain the value for FileID before you execute this instruction.

· If the operating mode of the CPU Unit is changed to PROGRAM mode or when a major fault level

Controller error occurs during instruction execution, the file is closed by the system. Any read/write

operations that are in progress are completed to the end. · Do not simultaneously access the same file. Perform exclusive control of SD Memory Card instruc-

2

tions in the user program.

· An error occurs in the following cases. Error will change to TRUE.

· The SD Memory Card is not in a usable condition.

· The SD Memory Card is write protected.

· There is insufficient space available on the SD Memory Card.

· The file specified by FileID does not exist.

· The file specified by FileID is being accessed.

· The file specified by FileID was not opened in a writing mode.

· An error that prevents access occurs during SD Memory Card access.

FilePuts

NJ/NX-series Instructions Reference Manual (W502)

2-1421

2 Instruction Descriptions

Sample Programming

Here, 100 lines of the contents of INT array variable Dat[0..9,0..99] are stored in a file named 'ABC.csv' in CSV file format. Each line contains ten text strings of numbers. Commas are inserted between them. A CR+LF code is added to the end of the line. The procedure is as follows:
1 One element of Dat[] is converted to one text string and stored in the STRING variable Temp.
2 Except at the end of a line, a comma is added to the end of Temp. At the end of the line, a
CR+LF code is added to the end of Temp. These are joined in the STRING variable StrDat.
3 When the end of the line is reached, StrDat is written to the file.
4 Steps 1 to 3 are repeated for 100 lines.
INT array

Dat[0,0] 16#1234 Dat[1,0] 16#08B4

Dat[0,1] 16#8487 Dat[1,1] 16#9256

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

Dat[0,99] 16#F596 Dat[1,99] 16#A511

Dat[9,0] 16#3966 Dat[9,1] 16#1211
. . . . . . .
Dat[9,99] 16#22AB

Converted to STRING data one at a time.

STRING variable Temp 9256

Commas are added between text strings, a CR code is added to the end, and the results are joined.
STRING variable StrDat 8487,9256
The line is written to the file when the end of the line is reached.

`ABC.csv' file

100 lines

1234,08B4,. . . . . 3966 CR

. . . . . . . . . .

.

. . . . . . . . . .

.

. . . . . . . . . .

.

. . . . . . . . . .

.

. . . . . . . . . .

.

. . . . . . . . . .

.

. . . . . . . . . .

.

. . . . . . . . . .

.

2-1422

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

2 Instruction Descriptions

LD
Internal Variables

Variable
OperatingEnd Trigger Operating Index0 Index1 Fid StrDat

Dat

Temp RS_instance FileOpen_instance FilePuts_instance FileClose_instance

Data type

Initial value

BOOL BOOL BOOL INT INT DWORD STRING[255] ARRAY[0..99,0.. 9] OF INT STRING[255] RS FileOpen FilePuts FileClose

FALSE FALSE FALSE 0 0 16#0 ''
[1000(0)]
''

Comment

Processing completed.

Execution condition

Processing

Column index

Row index

File ID

Text string data

Numeric data

2

Temporary data

External Variables

Variable _Card1Ready

Data type BOOL

Comment SD Memory Card Ready Flag

FilePuts

NJ/NX-series Instructions Reference Manual (W502)

2-1423

2 Instruction Descriptions

Determine if instruction execution is completed.

FileClose_instance.Done

OperatingEnd

FileOpen_instance.Error

FilePuts_instance.Error

FileClose_instance.Error

Accept trigger. Trigger _Card1Ready
OperatingEnd

RS_instance

RS

Set

Q1

Reset1

Operating

Initialize row index.

Operating

Inline ST 1 Index1:=INT#0;

Execute FileOpen instruction. Operating

FileOpen_instance FileOpen

Execute Done

`ABC.csv' FileName Busy

_RDWR_CREATE Mode

Error

ErrorID

FileID Fid

FileOpen_instance.Error

Inline ST
1 // Processing after error end. 2 ;

2-1424

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

FilePuts

2 Instruction Descriptions

Create a text string for one line. Operating FileOpen_instance.Done FilePuts_instance.Busy
1

FileClose_instance.Busy Inline ST

1

Note: The contents of the inline ST are given below.

Write a text string for one line to the file.

FilePuts_instance

Operating FileOpen_instance.Done FilePuts_instance.Busy FileClose_instance.Busy

FilePuts

Execute

Done

2

Fid FileID

Busy

StrDat In

Error

ErrorID

Increment the line index. Operating FilePuts_instance.Done
Index1

Inc
EN ENO InOut

FilePuts_instance.Error Inline ST
1 // Processing after error end. 2 ;

Execute the FileClose instruction after 100 lines are written.

Operating

>

EN

Index1 In1

Fid

INT#99 In2

FileClose_instance

FileClose

Execute FileID

Done Busy Error ErrorID

Operating FileClose_instance.Done

FileClose_instance.Error

Inline ST
1 // Processing after error end. 2 ;

Inline ST
1 // Processing after normal end. 2 ;

Contents of Inline ST
StrDat:='';
// Concatenate text strings 0 to 8. FOR Index0:=INT#0 TO INT#8 BY INT#1 DO
Temp :=INT_TO_STRING(Dat[Index1, Index0]); Temp :=CONCAT(In1:=Temp, In2:=','); StrDat:=CONCAT(In1:=StrDat, In2:=Temp); END_FOR;
// Concatenate text string 9 and add CR+LF. Temp :=INT_TO_STRING(Dat[Index1, Index0]); Temp :=CONCAT(In1:=Temp, In2:='$r$l'); // CR+LF StrDat:=CONCAT(In1:=StrDat, In2:=Temp);

NJ/NX-series Instructions Reference Manual (W502)

2-1425

2 Instruction Descriptions

ST
Internal Variables

Variable Trigger

LastTrigger

OperatingStart Operating Stage Index0 Index1 Fid StrDat

Dat

Temp FileOpen_instance FilePuts_instance FileClose_instance

Data type

Initial value

Comment

BOOL

FALSE

BOOL

FALSE

BOOL

FALSE

BOOL

FALSE

INT

0

INT

0

INT

0

DWORD

16#0

STRING[255] ''

ARRAY[0..99,0. .9] OF INT

[1000(0)]

STRING[255] ''

FileOpen

FilePuts

FileClose

Execution condition Value of Trigger from previous task period Processing started. Processing Stage change Column index Row index File ID Text string data
Numeric data
Temporary data

External Variables

Variable _Card1Ready

Data type BOOL

Comment SD Memory Card Ready Flag

// Start sequence when Trigger changes to TRUE.

IF ( (Trigger=TRUE) AND (LastTrigger=FALSE) AND (_Card1Ready=TRUE) ) THEN

OperatingStart:=TRUE;

Operating

:=TRUE;

END_IF;

LastTrigger:=Trigger;

// Initialize instance. IF (OperatingStart=TRUE) THEN
FileOpen_instance(Execute:=FALSE); FilePuts_instance(Execute:=FALSE); FileClose_instance(Execute:=FALSE); Stage :=INT#1; Index1 :=INT#0; // Initialize row index. OperatingStart:=FALSE; END_IF;

// Execute instructions.

IF (Operating=TRUE) THEN

CASE Stage OF

1 :

// Open file.

FileOpen_instance(

Execute :=TRUE,

FileName:='ABC.csv', // File name

Mode :=_RDWR_CREATE, // Read file

FileID =>Fid);

// File ID

IF (FileOpen_instance.Done=TRUE) THEN Stage:=INT#2; // Normal end
END_IF;

IF (FileOpen_instance.Error=TRUE) THEN Stage:=INT#99; // Error end
END_IF;

2-1426

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

FilePuts

2 Instruction Descriptions

2 :

// Create a text string for one line.

StrDat:='';

// Concatenate text strings 0 to 8. FOR Index0 :=INT#0 TO INT#8 BY INT#1 DO
Temp :=INT_TO_STRING(Dat[Index1, Index0]); Temp :=CONCAT(In1:=Temp, In2:=','); StrDat:=CONCAT(In1:=StrDat, In2:=Temp); END_FOR;

// Concatenate text string 9 and add CR+LF.

Temp :=INT_TO_STRING(Dat[Index1, Index0]);

Temp :=CONCAT(In1:=Temp, In2:='$r$l'); StrDat:=CONCAT(In1:=StrDat, In2:=Temp);

2

Stage:=INT#3;

3 :

// Write text string.

FilePuts_instance(

Execute:=TRUE,

FileID :=Fid,

In

:=StrDat);

IF (FilePuts_instance.Done=TRUE) THEN Index1:=Index1+INT#1;

IF (Index1>INT#99) THEN // If 100 lines were written... Stage:=INT#4;
ELSE FilePuts_instance(Execute:=FALSE); Stage:=INT#2;
END_IF; END_IF;

IF (FilePuts_instance.Error=TRUE) THEN Stage:=INT#99; // Error end
END_IF;

4 :

// Close file.

FileClose_instance(

Execute:=TRUE,

FileID :=Fid);

// File ID

IF (FileClose_instance.Done=TRUE) THEN Operating:=FALSE; // Normal end
END_IF;

IF (FileClose_instance.Error=TRUE) THEN Stage:=INT#99; // Error end
END_IF;

99 :

// Processing after error end.

Operating:=FALSE;

END_CASE;

END_IF;

NJ/NX-series Instructions Reference Manual (W502)

2-1427

2 Instruction Descriptions

FileCopy

The FileCopy instruction copies the specified file in the SD Memory Card.

Instruction FileCopy

Name Copy File

FB/FUN FB

Graphic expression

FileCopy_instance

FileCopy

Execute

Done

SrcFileName Busy

DstFileName Error

OverWrite ErrorID

ST expression
FileCopy_instance(Execute, SrcFileName, DstFileName, OverWrite, Done, Busy, Error, ErrorID);

Variables

Name
SrcFile Name
DstFile Name
OverWrite

Meaning

I/O

Source file

Destination file
Overwrite enable

Input

Description Name of file to copy
Name of destination file
TRUE: Enable overwrite. FALSE: Prohibit overwrite.

Valid range

Unit

66 bytes max. (65 sin-

gle-byte alphanumeric

characters plus the final

NULL character)

---

Depends on data type.

Default ''
FALSE

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

SrcFile

OK

Name

DstFile

OK

Name

OverWrite OK

Function

The FileCopy instruction copies the file specified by source file SrcFileName to designation file DstFileName in the SD Memory Card.
If a file with the name DstFileName already exists in the SD Memory Card, the following processing is performed depending on the value of overwrite enable OverWrite.

Value of OverWrite

Treatment

TRUE (Enable overwrite.)

The existing file is overwritten.

FALSE (Prohibit overwrite.)

The file is not overwritten and an error occurs.

2-1428

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

2 Instruction Descriptions

The following figure shows a programming example. Here, the file `DEF.bin' is overwritten with the file `ABC.bin.'

LD

ST

A
`ABC.bin' `DEF.bin'
TRUE

FileCopy_instance

FileCopy

Execute

Done

SrcFileName Busy

DstFileName Error

OverWrite ErrorID

abc
def ghi jkl

FileCopy_instance(A, 'ABC.bin', `DEF.bin', TRUE, abc, def, ghi, jkl);

2
The FileCopy instruction overwrites the file specified by source file SrcFileName to designation file DstFileName in the SD Memory Card.

SrcFileName 'ABC.bin'

DstFileName 'DEF.bin'

Overwritten.

FileCopy

OverWrite TRUE Overwriting is enabled.

Related System-defined Variables

Name _Card1Ready
_Card1Protect*2 _Card1Err*2
_Card1Access*2 _Card1PowerFail

Meaning
SD Memory Card Ready Flag

Data type BOOL

SD Memory Card Write BOOL Protected Flag
SD Memory Card Error BOOL Flag

SD Memory Card Access Flag

BOOL

SD Memory Card

BOOL

Power Interruption Flag

Description
This flag indicates if the SD Memory Card can be accessed by instructions and communications commands.*1 TRUE: Can be used. FALSE: Cannot be used.
This flag indicates if the SD Memory Card is write protected when it is inserted and ready to use. TRUE: Write protected. FALSE: Not write protected.
This flag indicates if an unspecified SD Memory Card (e.g., an SDHC card) is mounted or if the format is incorrect (i.e., not FAT16 or corrupted). TRUE: Error.
FALSE: No error.
This flag indicates if the SD Memory Card is currently being accessed. TRUE: Being accessed.
FALSE: Not being accessed.
This flag indicates if an error occurred in completing processing when power was interrupted during access*3. This flag is not cleared automatically. TRUE: Error.
FALSE: No error.

NJ/NX-series Instructions Reference Manual (W502)

2-1429

2 Instruction Descriptions
*1 For the NJ/NX-series, it is a precondition that the SD Memory Card is physically inserted and mounted normally. For an NY-series Controller, it is a precondition that the shared folder is detected by the Controller.
*2 These variables are not used for the NY-series Controller. They are fixed to FALSE. *3 For the NJ/NX-series, this indicates an access to the SD Memory Card. For an NY-series Controller, this indicates an
access to the shared folder.
Additional Information
The root directory of the file name is the top level of the SD Memory Card.
Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error. · If the copy operation fails, the file specified by DstFileName may remain in an incomplete state in the
SD Memory Card. · If a file is open when the operating mode of the CPU Unit is changed to PROGRAM mode or when a
major fault level Controller error occurs, the file is closed by the system. Any read/write operations that are in progress are completed to the end. · For an NJ/NX-series CPU Unit, if a file is open when the power supply is stopped with the SD Memory Card power supply switch, the file is not corrupted. · For an NJ/NX-series CPU Unit, if a file is open and the SD Memory Card is removed before the SD Memory Card power supply switch is pressed, the contents of the file will sometimes be corrupted. Always turn OFF the power supply before removing the SD Memory Card. · For an NJ/NX-series CPU Unit, if a file is open when the power supply is stopped or the SD Memory Card is removed, it will not be possible to read or write the file even if the SD Memory Card is inserted again. · Do not simultaneously access the same file. Perform exclusive control of SD Memory Card instructions in the user program. · An error occurs in the following cases. Error will change to TRUE. · The SD Memory Card is not in a usable condition. · The SD Memory Card is write protected. · There is insufficient space available on the SD Memory Card. · The file specified by SrcFileName does not exist. · The value of SrcFileName is not a valid file name. · The value of DstFileName is not a valid file name. · The maximum number of files or directories is exceeded. · The file specified by SrcFileName or DstFileName is already being accessed. · A file with the name DstFileName already exits and the value of OverWrite is FALSE. · A file with the name DstFileName already exits and the file is write protected. · If more than four SD Memory Card instructions that do not have a FileID variable (i.e., FileWrite-
Var, FileReadVar, FileCopy, DirCreate, FileRemove, DirRemove, and FileRename) are executed at the same time. · The value of DstFileName exceeds the maximum number of bytes allowed in a file name. · An error that prevents access occurs during SD Memory Card access.

2-1430

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

2 Instruction Descriptions

Sample Programming

The following procedure is used to move a file.
1 The DirCreate instruction is used to create a directory called 'Dir1' in the SD Memory Card.

2 The FileCopy instruction is used to copy the file named 'ABC.bin' in the existing directory 'Dir0'
to the directory 'Dir1.'

3 The DirRemove instruction is used to delete the directory `Dir0' (the source of the copy).

1. Create directory.

'Dir1'

2

2. Copy file. 'Dir0'
ABC.bin
3. Delete directory. 'Dir0'
ABC.bin

'Dir1' ABC.bin
'Dir1' ABC.bin

FileCopy

NJ/NX-series Instructions Reference Manual (W502)

2-1431

2 Instruction Descriptions

LD
Internal Variables

Variable
OperatingEnd Trigger Operating RS_instance DirCreate_instance FileCopy_instance DirRemove_instance

External Variables

Variable _Card1Ready

Data type
BOOL BOOL BOOL RS DirCreate FileCopy DirRemove

Initial value
FALSE FALSE FALSE

Comment
Processing completed. Execution condition Processing

Data type BOOL

Comment SD Memory Card Ready Flag

2-1432

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

FileCopy

2 Instruction Descriptions

Determine if instruction execution is completed.

DirRemove_instance.Done

OperatingEnd

DirCreate_instance.Error

FileCopy_instance.Error

DirRemove_instance.Error

2

Accept trigger. Trigger _Card1Ready
OperatingEnd

RS_instance

RS

Set

Q1

Reset1

Operating

Execute DirCreate instruction. Operating
`Dir1'

DirCreate_instance

DirCreate

Execute DirName

Done Busy Error ErrorID

DirCreate_instance.Error

Inline ST
1 // Processing after error end. 2 ;

Execute FileCopy instruction.

Operating

DirCreate_instance.Done

`Dir0/ABC.bin' `Dir1/ABC.bin'
FALSE

FileCopy_instance

FileCopy

Execute

Done

SrcFileName Busy

DstFileName Error

OverWrite ErrorID

FileCopy_instance.Error

Inline ST
1 // Processing after error end. 2 ;

NJ/NX-series Instructions Reference Manual (W502)

2-1433

2 Instruction Descriptions

Execute DirRemove instruction. Operating FileCopy_instance.Done

`Dir0' TRUE

DirRemove_instance

DirRemove

Execute DirName All

Done Busy Error ErrorID

DirRemove_instance.Error

Inline ST
1 // Processing after error end. 2 ;

Processing after normal end. Operating FileCopy_instance.Done DirRemove_instance.Done

Inline ST
1 // Processing after normal end. 2 ;

2-1434

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

SD Memory Card Instructions

FileCopy

ST

Internal Variables

Variable

Data type

Initial value

Comment

Trigger

BOOL

FALSE

Execution condition

LastTrigger

BOOL

FALSE

Value of Trigger from previous task period

OperatingStart

BOOL

FALSE

Processing started.

Operating

BOOL

FALSE

Processing

Stage

INT

0

Stage change

DirCreate_instance

DirCreate

FileCopy_instance

FileCopy

2

DirRemove_instance DirRemove

External Variables

Variable _Card1Ready

Data type BOOL

Comment SD Memory Card Ready Flag

// Start sequence when Trigger changes to TRUE.

IF ( (Trigger=TRUE) AND (LastTrigger=FALSE) AND (_Card1Ready=TRUE) ) THEN

OperatingStart:=TRUE;

Operating

:=TRUE;

END_IF;

LastTrigger:=Trigger;

// Initialize instance.

IF (OperatingStart=TRUE) THEN

DirCreate_instance(Execute:=FALSE);

FileCopy_instance(Execute:=FALSE);

DirRemove_instance(Execute:=FALSE);

Stage

:=INT#1;

OperatingStart:=FALSE;

END_IF;

// Execute instructions.

IF (Operating=TRUE) THEN

CASE Stage OF

1 :

// Create directory.

DirCreate_instance(

Execute:=TRUE,

DirName:='Dir1'); // Directory name

IF (DirCreate_instance.Done=TRUE) THEN

Stage:=INT#2;

// Normal end

END_IF;

IF (DirCreate_instance.Error=TRUE) THEN

Stage:=INT#99;

// Error end

END_IF;

2 :

// Copy file.

FileCopy_instance(

Execute :=TRUE,

SrcFileName:='Dir0/ABC.bin',

DstFileName:='Dir1/ABC.bin',

OverWrite :=FALSE);

// Name of file to copy // Name of destination file // Prohibit overwrite.

IF (FileCopy_instance.Done=TRUE) THEN Stage:=INT#3;
END_IF;

NJ/NX-series Instructions Reference Manual (W502)

2-1435

2 Instruction Descriptions

IF (FileCopy_instance.Error=TRUE) THEN Stage:=INT#99;
END_IF;

3 :

// Delete directory.

DirRemove_instance(

Execute :=TRUE,

DirName :='Dir0', // Directory name

All

:=TRUE); // Delete files and subdirectories.

IF (DirRemove_instance.Done=TRUE) THEN Operating:=FALSE; // Normal end
END_IF;

IF (DirRemove_instance.Error=TRUE) THEN

Stage:=INT#99;

// Error end

END_IF;

99 :

// Processing after error end.

Operating:=FALSE;

END_CASE;

END_IF;

2-1436

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

FileRemove

2 Instruction Descriptions

FileRemove

The FileRemove instruction deletes the specified file from the SD Memory Card.

Instruction FileRemove

Name Delete File

FB/FUN FB

Graphic expression

ST expression

FileRemove_instance

FileRemove

Execute

Done

FileRemove_instance(Execute, FileName, Done, Busy, Error, ErrorID);

FileName

Busy

Error ErrorID

2

Variables

Name FileName

Meaning

I/O

File name Input

Description Name of file to delete

Valid range

Unit

66 bytes max. (65 sin- --gle-byte alphanumeric characters plus the final NULL character)

Default ''

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

FileName

OK

Function

The FileRemove instruction deletes the file specified by file name FileName from the SD Memory Card. The following figure shows a programming example. Here, the file named `ABC.bin' is deleted.

LD

ST

A `ABC.bin'

FileRemove_instance

FileRemove

Execute FileName

Done Busy Error ErrorID

abc
def ghi jkl

FileRemove_instance(A, 'ABC.bin', abc, def, ghi, jkl);

The FileRemove instruction deletes the file specified by FileName from the SD Memory Card.

File is deleted.

FileName 'ABC.bin'

NJ/NX-series Instructions Reference Manual (W502)

2-1437

2 Instruction Descriptions

Related System-defined Variables

Name _Card1Ready
_Card1Protect*2 _Card1Err*2
_Card1Access*2 _Card1PowerFail

Meaning
SD Memory Card Ready Flag

Data type BOOL

SD Memory Card Write BOOL Protected Flag
SD Memory Card Error BOOL Flag

SD Memory Card Access Flag

BOOL

SD Memory Card

BOOL

Power Interruption Flag

Description
This flag indicates if the SD Memory Card can be accessed by instructions and communications commands.*1
TRUE: Can be used. FALSE: Cannot be used.
This flag indicates if the SD Memory Card is write protected when it is inserted and ready to use.
TRUE: Write protected. FALSE: Not write protected.
This flag indicates if an unspecified SD Memory Card (e.g., an SDHC card) is mounted or if the format is incorrect (i.e., not FAT16 or corrupted). TRUE: Error. FALSE: No error.
This flag indicates if the SD Memory Card is currently being accessed. TRUE: Being accessed. FALSE: Not being accessed.
This flag indicates if an error occurred in completing processing when power was interrupted during access*3. This flag is not cleared automatically. TRUE: Error. FALSE: No error.

*1 For the NJ/NX-series, it is a precondition that the SD Memory Card is physically inserted and mounted normally. For an NY-series Controller, it is a precondition that the shared folder is detected by the Controller.
*2 These variables are not used for the NY-series Controller. They are fixed to FALSE.
*3 For the NJ/NX-series, this indicates an access to the SD Memory Card. For an NY-series Controller, this indicates an access to the shared folder.

Additional Information
The root directory of the file name is the top level of the SD Memory Card.

Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error.
· If a file is open when the operating mode of the CPU Unit is changed to PROGRAM mode or when a major fault level Controller error occurs, the file is closed by the system. Any read/write operations that are in progress are completed to the end.
· For an NJ/NX-series CPU Unit, if a file is open when the power supply is stopped with the SD Memory Card power supply switch, the file is not corrupted.
· For an NJ/NX-series CPU Unit, if a file is open and the SD Memory Card is removed before the SD Memory Card power supply switch is pressed, the contents of the file will sometimes be corrupted. Always turn OFF the power supply before removing the SD Memory Card.

2-1438

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

FileRemove

2 Instruction Descriptions

· For an NJ/NX-series CPU Unit, if a file is open when the power supply is stopped or the SD Memory Card is removed, it will not be possible to read or write the file even if the SD Memory Card is inserted again.

· Do not simultaneously access the same file. Perform exclusive control of SD Memory Card instructions in the user program.

· An error occurs in the following cases. Error will change to TRUE.

· The SD Memory Card is not in a usable condition.

· The SD Memory Card is write protected.

· The file specified by FileName does not exist.

· The file specified by FileName is being accessed.

· A file with the name FileName already exits and the file is write protected. · If more than four SD Memory Card instructions that do not have a FileID variable (i.e., FileWrite-

2

Var, FileReadVar, FileCopy, DirCreate, FileRemove, DirRemove, and FileRename) are executed

at the same time.

· The value of FileName exceeds the maximum number of characters allowed in a file name.

· An error that prevents access occurs during SD Memory Card access.

Sample Programming

In this sample, the file named 'ABC.bin' is deleted from the SD Memory Card.

LD

Internal Variables

Variable
OperatingEnd Trigger Operating RS_instance FileRemove_instance

Data type
BOOL BOOL BOOL RS FileRemove

Initial value
FALSE FALSE FALSE

Comment
Processing completed. Execution condition Processing

External Variables

Variable _Card1Ready

Data type BOOL

Comment SD Memory Card Ready Flag

NJ/NX-series Instructions Reference Manual (W502)

2-1439

2 Instruction Descriptions

Determine if execution of the FileRemove instruction is completed.

FileRemove_instance.Done

OperatingEnd

FileRemove_instance.Error

Accept trigger. Trigger _Card1Ready
OperatingEnd

RS_instance

RS

Set

Q1

Reset1

Operating

Execute FileRemove instruction.

FileRemove_instance

Operating

FileRemove

`ABC.bin'

Execute FileName

Done Busy Error ErrorID

Processing after normal end. Operating FileRemove_instance.Done

Inline ST
1 // Processing after normal end. 2 ;

Processing after error end. Operating FileRemove_instance.Error

Inline ST
1 // Processing after normal end. 2 ;

2-1440

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

FileRemove

2 Instruction Descriptions

ST
Internal Variables

Variable Trigger

Data type BOOL

LastTrigger

BOOL

OperatingStart Operating FileRemove_instance

BOOL BOOL FileRemove

Initial value

Comment

FALSE FALSE FALSE FALSE

Execution condition Value of Trigger from previous task period Processing started. Processing

External Variables

Variable

Data type

Comment

2

_Card1Ready

BOOL

SD Memory Card Ready Flag

// Start sequence when Trigger changes to TRUE.

IF ( (Trigger=TRUE) AND (LastTrigger=FALSE) AND (_Card1Ready=TRUE) ) THEN

OperatingStart:=TRUE;

Operating

:=TRUE;

END_IF;

LastTrigger:=Trigger;

// Initialize instance. IF (OperatingStart=TRUE) THEN
FileRemove_instance(Execute:=FALSE); OperatingStart:=FALSE; END_IF;

// Execute FileRemove instruction. IF (Operating=TRUE) THEN
FileRemove_instance( Execute :=TRUE, FileName:='ABC.bin'); // File name

IF (FileRemove_instance.Done=TRUE) THEN

Operating:=FALSE;

// Normal end

END_IF;

IF (FileRemove_instance.Error=TRUE) THEN

Operating:=FALSE;

// Error end

END_IF;

END_IF;

NJ/NX-series Instructions Reference Manual (W502)

2-1441

2 Instruction Descriptions

FileRename

The FileRename instruction changes the name of the specified file or directory in the SD Memory Card.

Instruction FileRename

Name

FB/FUN

Change File Name FB

Graphic expression

FileRename_instance

FileRename

Execute FileName NewName OverWrite

Done Busy Error ErrorID

ST expression
FileRename_instance(Execute, FileName, NewName, OverWrite, Done, Busy, Error, ErrorID);

Variables

Name FileName
NewName
OverWrite

Meaning
Original file name
New file name
Overwrite enable

I/O Input

Description Original file name
New file name
TRUE: Enable overwrite. FALSE: Prohibit overwrite.

Valid range

Unit

66 bytes max. (65 sin-

gle-byte alphanumeric

characters plus the final

NULL character)

---

Depends on data type.

Default '' FALSE

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

FileName

OK

NewName

OK

OverWrite OK

Function

The FileRename instruction changes the name of the file or directory specified by original file name FileName to new file name NewName in the SD Memory Card.
If a file or directory with the name NewName already exists in the SD Memory Card, the following processing is performed depending on the value of overwrite enable OverWrite.

Value of OverWrite TRUE (Enable overwrite.)

Treatment The existing file or directory is overwritten.

FALSE (Prohibit overwrite.)

The file or directory is not overwritten and an error occurs.

2-1442

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

2 Instruction Descriptions

The following figure shows a programming example. Here, the name of the file `ABC.bin' is changed to `DEF.bin.'

LD

ST

A
`ABC.bin' `DEF.bin'
TRUE

FileRename_instance

FileRename

Execute FileName NewName OverWrite

Done Busy Error ErrorID

abc
def ghi jkl

FileRename_instance(A, 'ABC.bin', `DEF.bin', TRUE, abc, def, ghi, jkl);

2
The FileRename instruction changes the name of the file specified by original file name

FileName to new file name NewName in the SD Memory Card. If the file already exists, it is overwritten.

File name is changed.

FileName 'ABC.bin'

NewName 'DEF.bin'

FileRename

OverWrite TRUE Overwriting is enabled.

Related System-defined Variables

Name _Card1Ready
_Card1Protect*2 _Card1Err*2
_Card1Access*2 _Card1PowerFail

Meaning
SD Memory Card Ready Flag

Data type BOOL

SD Memory Card Write BOOL Protected Flag
SD Memory Card Error BOOL Flag

SD Memory Card Access Flag

BOOL

SD Memory Card

BOOL

Power Interruption Flag

Description
This flag indicates if the SD Memory Card can be accessed by instructions and communications commands.*1 TRUE: Can be used. FALSE: Cannot be used.
This flag indicates if the SD Memory Card is write protected when it is inserted and ready to use. TRUE: Write protected. FALSE: Not write protected.
This flag indicates if an unspecified SD Memory Card (e.g., an SDHC card) is mounted or if the format is incorrect (i.e., not FAT16 or corrupted). TRUE: Error.
FALSE: No error.
This flag indicates if the SD Memory Card is currently being accessed. TRUE: Being accessed.
FALSE: Not being accessed.
This flag indicates if an error occurred in completing processing when power was interrupted during access*3. This flag is not cleared automatically. TRUE: Error.
FALSE: No error.

NJ/NX-series Instructions Reference Manual (W502)

2-1443

2 Instruction Descriptions
*1 For the NJ/NX-series, it is a precondition that the SD Memory Card is physically inserted and mounted normally. For an NY-series Controller, it is a precondition that the shared folder is detected by the Controller.
*2 These variables are not used for the NY-series Controller. They are fixed to FALSE. *3 For the NJ/NX-series, this indicates an access to the SD Memory Card. For an NY-series Controller, this indicates an
access to the shared folder.
Additional Information
The root directory of the file name is the top level of the SD Memory Card.
Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error. · If the directories are different for FileName and NewName, the file is moved to the directory that is
specified with NewName. · If a file is open when the operating mode of the CPU Unit is changed to PROGRAM mode or when a
major fault level Controller error occurs, the file is closed by the system. Any read/write operations that are in progress are completed to the end. · For an NJ/NX-series CPU Unit, if a file is open when the power supply is stopped with the SD Memory Card power supply switch, the file is not corrupted. · For an NJ/NX-series CPU Unit, if a file is open and the SD Memory Card is removed before the SD Memory Card power supply switch is pressed, the contents of the file will sometimes be corrupted. Always turn OFF the power supply before removing the SD Memory Card. · For an NJ/NX-series CPU Unit, if a file is open when the power supply is stopped or the SD Memory Card is removed, it will not be possible to read or write the file even if the SD Memory Card is inserted again. · Do not simultaneously access the same file. Perform exclusive control of SD Memory Card instructions in the user program. · An error occurs in the following cases. Error will change to TRUE. · The SD Memory Card is not in a usable condition. · The SD Memory Card is write protected. · The file directory specified with FileName does not exist. · The value of FileName or NewName is not a valid file name or directory name. · The file specified by FileName is being accessed. · There is a subdirectory in the directory that was specified for FileName and the value of OverWrite
is TRUE. · A file with the name NewName already exits and the value of OverWrite is FALSE. · A file with the name NewName already exits, the file is write protected, and the value of OverWrite
is TRUE. · If more than four SD Memory Card instructions that do not have a FileID variable (i.e., FileWrite-
Var, FileReadVar, FileCopy, DirCreate, FileRemove, DirRemove, and FileRename) are executed at the same time. · The value of NewName exceeds the maximum number of characters allowed in a file name or directory name. · An error that prevents access occurs during SD Memory Card access. · The maximum number of directories is exceeded.

2-1444

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

FileRename

2 Instruction Descriptions

Sample Programming

In this sample, the name of the file 'ABC.bin' is changed to 'DEF.bin' on the SD Memory Card.

LD

Internal Variables

Variable
OperatingEnd Trigger Operating RS_instance FileRename_instance

Data type
BOOL BOOL BOOL RS FileRename

Initial value
FALSE FALSE FALSE

Comment
Processing completed. Execution condition Processing
2

External Variables

Variable _Card1Ready

Data type BOOL

Comment SD Memory Card Ready Flag

Determine if execution of the FileRename instruction is completed.

FileRename_instance.Done

OperatingEnd

FileRename_instance.Error

Accept trigger. Trigger _Card1Ready
OperatingEnd

RS_instance

RS

Set

Q1

Reset1

Operating

Execute FileRename instruction.

FileRename_instance

Operating

FileRename

`ABC.bin' `DEF.bin'
FALSE

Execute FileName NewName OverWrite

Done Busy Error ErrorID

Processing after normal end. Operating FileRename_instance.Done

Inline ST
1 // Processing after normal end. 2 ;

Processing after error end. Operating FileRename_instance.Error

Inline ST
1 // Processing after normal end. 2 ;

NJ/NX-series Instructions Reference Manual (W502)

2-1445

2 Instruction Descriptions

ST
Internal Variables

Variable Trigger

Data type BOOL

LastTrigger

BOOL

OperatingStart Operating FileRename_instance

BOOL BOOL FileRename

Initial value

Comment

FALSE FALSE FALSE FALSE

Execution condition Value of Trigger from previous task period Processing started. Processing

External Variables

Variable _Card1Ready

Data type BOOL

Comment SD Memory Card Ready Flag

// Start sequence when Trigger changes to TRUE.

IF ( (Trigger=TRUE) AND (LastTrigger=FALSE) AND (_Card1Ready=TRUE) ) THEN

OperatingStart:=TRUE;

Operating

:=TRUE;

END_IF;

LastTrigger:=Trigger;

// Initialize instance. IF (OperatingStart=TRUE) THEN
FileRename_instance(Execute:=FALSE); OperatingStart:=FALSE; END_IF;

// Execute FileRename instruction.

IF (Operating=TRUE) THEN

FileRename_instance(

Execute :=TRUE,

FileName :='ABC.bin', // Original file name

NewName :='DEF.bin', // New file name

OverWrite:=FALSE);

// Prohibit overwrite.

IF (FileRename_instance.Done=TRUE) THEN

Operating:=FALSE;

// Normal end

END_IF;

IF (FileRename_instance.Error=TRUE) THEN

Operating:=FALSE;

// Error end

END_IF;

END_IF;

2-1446

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

DirCreate

2 Instruction Descriptions

DirCreate

The DirCreate instruction creates a directory with the specified name in the SD Memory Card.

Instruction

Name

FB/FUN

Graphic expression

ST expression

DirCreate

Create Directory FB

DirCreate_instance

DirCreate

Execute

Done

DirCreate_instance(Execute, DirName, Done, Busy, Error, ErrorID);

DirName Busy

Error ErrorID

2

Variables

Name DirName

Meaning
Directory to create

I/O Input

Description Name of directory to create

Valid range

Unit

66 bytes max. (65 sin- --gle-byte alphanumeric characters plus the final NULL character)

Default ''

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

DirName

OK

Function

The DirCreate instruction creates a directory with the name specified by directory to create Dir in the SD Memory Card.
The following figure shows a programming example. Here, a directory named `Dir0' is created.

LD

ST

DirCreate_instance

A

DirCreate

abc

Execute

Done

`Dir0' DirName

Busy def

Error ghi

ErrorID jkl

DirCreate_instance(A, 'Dir0', abc, def, ghi, jkl);

NJ/NX-series Instructions Reference Manual (W502)

2-1447

2 Instruction Descriptions
The DirCreate instruction creates a directory with the name specified by DirName in the SD Memory Card.
DirName 'Dir0' Directory is created.

Related System-defined Variables

Name _Card1Ready
_Card1Protect*2 _Card1Err*2
_Card1Access*2 _Card1PowerFail

Meaning
SD Memory Card Ready Flag

Data type BOOL

SD Memory Card Write BOOL Protected Flag
SD Memory Card Error BOOL Flag

SD Memory Card Access Flag

BOOL

SD Memory Card

BOOL

Power Interruption Flag

Description
This flag indicates if the SD Memory Card can be accessed by instructions and communications commands.*1 TRUE: Can be used.
FALSE: Cannot be used.
This flag indicates if the SD Memory Card is write protected when it is inserted and ready to use. TRUE: Write protected.
FALSE: Not write protected.
This flag indicates if an unspecified SD Memory Card (e.g., an SDHC card) is mounted or if the format is incorrect (i.e., not FAT16 or corrupted).
TRUE: Error. FALSE: No error.
This flag indicates if the SD Memory Card is currently being accessed.
TRUE: Being accessed. FALSE: Not being accessed.
This flag indicates if an error occurred in completing processing when power was interrupted during access*3. This flag is not cleared automatically.
TRUE: Error. FALSE: No error.

*1 For the NJ/NX-series, it is a precondition that the SD Memory Card is physically inserted and mounted normally. For an NY-series Controller, it is a precondition that the shared folder is detected by the Controller.
*2 These variables are not used for the NY-series Controller. They are fixed to FALSE.
*3 For the NJ/NX-series, this indicates an access to the SD Memory Card. For an NY-series Controller, this indicates an access to the shared folder.

Additional Information
The root directory of the file name is the top level of the SD Memory Card.

Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error.

2-1448

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

DirCreate

2 Instruction Descriptions

· If a file is open when the operating mode of the CPU Unit is changed to PROGRAM mode or when a major fault level Controller error occurs, the file is closed by the system. Any read/write operations that are in progress are completed to the end.

· For an NJ/NX-series CPU Unit, if a file is open when the power supply is stopped with the SD Memory Card power supply switch, the file is not corrupted.

· For an NJ/NX-series CPU Unit, if a file is open and the SD Memory Card is removed before the SD Memory Card power supply switch is pressed, the contents of the file will sometimes be corrupted. For an NJ/NX-series CPU Unit, if a file is open and the SD Memory Card is removed before the SD Memory Card power supply switch is pressed, the contents of the file will sometimes be corrupted. Always turn OFF the power supply before removing the SD Memory Card.

· For an NJ/NX-series CPU Unit, if a file is open when the power supply is stopped or the SD Memory

Card is removed, it will not be possible to read or write the file even if the SD Memory Card is inserted again.

2

· Do not simultaneously access the same file. Perform exclusive control of SD Memory Card instructions in the user program.

· An error occurs in the following cases. Error will change to TRUE.

· The SD Memory Card is not in a usable condition.

· The SD Memory Card is write protected.

· There is insufficient space available on the SD Memory Card.

· The maximum number of directories is exceeded.

· The directory specified by DirName already exists.

· If more than four SD Memory Card instructions that do not have a FileID variable (i.e., FileWriteVar, FileReadVar, FileCopy, DirCreate, FileRemove, DirRemove, and FileRename) are executed at the same time.

· The value of DirName is not a valid directory name.

· The value of DirName exceeds the maximum number of characters allowed in a directory name.

· An error that prevents access occurs during SD Memory Card access.

· The file specified by FileName is being accessed.

Sample Programming
Refer to the sample programming that is provided for the FileCopy instruction (page 2-1428).

NJ/NX-series Instructions Reference Manual (W502)

2-1449

2 Instruction Descriptions

DirRemove

The DirRemove instruction deletes the specified directory from the SD Memory Card.

Instruction DirRemove

Name Delete Directory

FB/FUN FB

Graphic expression

DirRemove_instance

DirRemove

Execute DirName All

Done Busy Error ErrorID

ST expression
DirRemove_instance(Execute, DirName, All, Done, Busy, Error, ErrorID);

Variables

Name

Meaning

I/O

DirName

Directory to delete

All

All designation

Input

Description

Valid range

Unit

Directory to delete

66 bytes max. (65 single-byte alphanumeric characters plus the final NULL character)

Specifies whether to delete

files and subdirectories

---

inside specified directory TRUE: Delete files and sub- Depends on data type.

directories.

FALSE: Do not delete.

Default ''
FALSE

Bit strings

Integers

Real

Times, durations, dates, and text strings

numbers REAL

Boolean BOOL

STRING

DT

TOD

DATE

TIME

LREAL

LINT

DINT

INT

SINT

ULINT

UDINT

UINT

USINT

LWORD

DWORD

WORD

BYTE

DirName

OK

All

OK

Function

The DirRemove instruction deletes the directory with the name specified by directory to delete Dir from the SD Memory Card.
If there are files or subdirectories in the specified directory, the following processing is performed according to the value of all designation All.

Value of All

Treatment

TRUE

All files and subdirectories are deleted along with the specified directory.

FALSE

The specified directory is not deleted and an error occurs.

2-1450

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

2 Instruction Descriptions

The following figure shows a programming example. Here, a directory named `Dir1' is deleted.

LD

ST

DirRemove_instance

A

DirRemove

abc

Execute

Done

`Dir1' DirName

Busy def

TRUE All

Error ghi

ErrorID jkl

DirRemove_instance(A, 'Dir1', TRUE, abc, def, ghi, jkl);

The DirRemove instruction deletes the directory with the name specified by DirName from the

SD Memory Card. Files and subdirectories inside specified directory are deleted too.

2

DirName 'Dir0'

Directory is deleted.

DirRemove

All TRUE Specifies deletion of the files and subdirectories inside the specified directory.
Related System-defined Variables

Name _Card1Ready
_Card1Protect*2 _Card1Err*2
_Card1Access*2 _Card1PowerFail

Meaning
SD Memory Card Ready Flag

Data type BOOL

SD Memory Card Write BOOL Protected Flag
SD Memory Card Error BOOL Flag

SD Memory Card Access Flag

BOOL

SD Memory Card

BOOL

Power Interruption Flag

Description
This flag indicates if the SD Memory Card can be accessed by instructions and communications commands.*1 TRUE: Can be used. FALSE: Cannot be used.
This flag indicates if the SD Memory Card is write protected when it is inserted and ready to use. TRUE: Write protected. FALSE: Not write protected.
This flag indicates if an unspecified SD Memory Card (e.g., an SDHC card) is mounted or if the format is incorrect (i.e., not FAT16 or corrupted). TRUE: Error.
FALSE: No error.
This flag indicates if the SD Memory Card is currently being accessed. TRUE: Being accessed.
FALSE: Not being accessed.
This flag indicates if an error occurred in completing processing when power was interrupted during access*3. This flag is not cleared automatically. TRUE: Error.
FALSE: No error.

*1 For the NJ/NX-series, it is a precondition that the SD Memory Card is physically inserted and mounted normally. For an NY-series Controller, it is a precondition that the shared folder is detected by the Controller.
*2 These variables are not used for the NY-series Controller. They are fixed to FALSE.
*3 For the NJ/NX-series, this indicates an access to the SD Memory Card. For an NY-series Controller, this indicates an access to the shared folder.

NJ/NX-series Instructions Reference Manual (W502)

2-1451

2 Instruction Descriptions
Additional Information
The root directory of the file name is the top level of the SD Memory Card.
Precautions for Correct Use
· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.
· Refer to Using this Section on page 2-3 for a timing chart for Execute, Done, Busy, and Error. · If a file is open when the operating mode of the CPU Unit is changed to PROGRAM mode or when a
major fault level Controller error occurs, the file is closed by the system. Any read/write operations that are in progress are completed to the end. · For an NJ/NX-series CPU Unit, if a file is open when the power supply is stopped with the SD Memory Card power supply switch, the file is not corrupted. · For an NJ/NX-series CPU Unit, if a file is open and the SD Memory Card is removed before the SD Memory Card power supply switch is pressed, the contents of the file will sometimes be corrupted. Always turn OFF the power supply before removing the SD Memory Card. · For an NJ/NX-series CPU Unit, if a file is open when the power supply is stopped or the SD Memory Card is removed, it will not be possible to read or write the file even if the SD Memory Card is inserted again. · If the directory that is specified with DirName is write protected, an error occurs and the directory is not deleted. However, any files or directories that are not write-protected inside that directory are deleted. · Do not simultaneously access the same file. Perform exclusive control of SD Memory Card instructions in the user program. · An error occurs in the following cases. Error will change to TRUE. · The SD Memory Card is not in a usable condition. · The SD Memory Card is write protected. · If the value of All is TRUE and the directory specified with DirName is being accessed by another
instruction. · If the value of All is FALSE and the directory specified with DirName contains a file or directory. · The directory specified by DirName is write-protected. · The directory that is specified with DirName contains write-protected files or write-protected direc-
tories. · If more than four SD Memory Card instructions that do not have a FileID variable (i.e., FileWrite-
Var, FileReadVar, FileCopy, DirCreate, FileRemove, DirRemove, and FileRename) are executed at the same time. · The directory specified by DirName does not exist. · The value of DirName exceeds the maximum number of characters allowed in a directory name. · An error that prevents access occurs during SD Memory Card access.
Sample Programming
Refer to the sample programming that is provided for the FileCopy instruction (page 2-1428).

2-1452

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

BackupToMemoryCard

2 Instruction Descriptions

BackupToMemoryCard

The BackupToMemoryCard instruction backs up data to an SD Memory Card.

Instruction

Name

FB/ FUN

Graphic expression

ST expression

BackupToMemoryCard

_instance(Execute,

BackupToMemoryCard_instance

DirName,

BackupTo MemoryCard

SD Memory Card Backup

FB

BackupToMemoryCard

Execute DirName

Done Busy

Cancel, Option, Done,

2

Cancel

Error

Busy,

Option

Canceled

Error,

ErrorID

Canceled,

ErrorID);

Variables

Name DirName Cancel Option Canceled

Meaning

I/O

Description

Valid range

Unit

Directory to save in

Name of directory in which to save the backup data

64 bytes max. (63 single-byte alphanumeric characters plus the final NULL character)

Cancel

Input

Canceling the backup TRUE: Cancel FALSE: Do not cancel

Depends on

---

data type.

For future expansion

This variable is for future expan-

sion. It is not necessary to connect a

---

parameter.

A flag that indicates if canceling

Cancel completed

Output

was completed TRUE: Canceling completed

Depends on data type.

---

FALSE: Canceling failed

Default '' FALSE -----

Bit strings

Integers

Times, durations, dates, and text strings

Real numbers

Boolean BOOL

STRING DT TOD
DATE TIME

LREAL REAL

LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE

DirName

OK

Cancel

OK

Option

For future expansion. It is not necessary to connect a parameter.

Canceled

OK

NJ/NX-series Instructions Reference Manual (W502)

2-1453

2 Instruction Descriptions

Function
The BackupToMemoryCard instruction backs up data to an SD Memory Card. This instruction performs the same processing as the processing that is performed for the front panel switch on the CPU Unit, the _Card1BkupCmd system-defined variable, or the SD Memory Card backup performed from the SD Memory Card Window on the Sysmac Studio.

Specify the name of the directory in which to save the backup data with DirName.
If the value of DirName is " " (i.e., a text string with a length of 0 characters), the backup data is saved in the root directory of the SD Memory Card.
DirName can be omitted. If you omit DirName, the following data is save in the following directory.

Instruction execution 1st execution
2nd execution and beyond

Directory to save in
Root directory
The previously specified directory

If the directory that is specified with DirName does not exist in the SD Memory Card, a new directory is created and the backup data is saved in it.
If a file with the same name as the backup file already exists in the directory specified with DirName, the backup file is overwritten.

If the value of Cancel changes to TRUE during backup processing, the backup processing is canceled. If backup processing is canceled, the backup file will not be created. If a backup file already exists in the directory specified with DirName, the backup file is not overwritten and remains unchanged.
You can cancel only the backup processing that is being executed for the same function block instance.
When canceling is completed, the value of Canceled changes to TRUE. Depending on when the value of Cancel changes to TRUE, it might be too late to cancel processing, and backup processing may be competed to the end. If canceling was not performed in time, the value of Canceled will be FALSE and the value of Done will be TRUE.

If the value of Cancel is TRUE, backup processing is not performed even if the value of Execute is TRUE.

Option is for future expansion. Do not connect a parameter to it.

2-1454

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

2 Instruction Descriptions

Timing Chart for Canceling
Timing charts for the instruction variables are provided below for canceling.

 When Canceling Is Successful, and Execute Changes to FALSE Before Canceled Changes to TRUE

· Backup processing is executed when the value of Execute changes to TRUE. The value of Busy changes to TRUE.

· Backup processing is canceled when the value of Cancel changes to TRUE.

· When canceling is completed, the value of Busy changes to FALSE and the value of Canceled changes to TRUE.

2

· The value of Execute is changed to FALSE before the value of Canceled changes to TRUE.

· The value of Canceled changes to FALSE after one task period.

· Because canceling was successful, the value of Done changes to FALSE.

Task period

Execute Cancel Busy Canceled Done Error

TRUE FALSE
TRUE FALSE
TRUE FALSE
TRUE FALSE
TRUE FALSE TRUE FALSE

Canceled changes to TRUE for one task period.

BackupToMemoryCard

NJ/NX-series Instructions Reference Manual (W502)

2-1455

2 Instruction Descriptions

 When Canceling Is Successful, and Execute Changes to FALSE After Canceled Changes to TRUE
· Backup processing is executed when the value of Execute changes to TRUE. The value of Busy changes to TRUE.
· Backup processing is canceled when the value of Cancel changes to TRUE.
· When canceling is completed, the value of Busy changes to FALSE and the value of Canceled changes to TRUE.
· The value of Execute is changed to FALSE after the value of Canceled changes to TRUE.
· The value of Canceled remains TRUE until the value of Execute changes to FALSE.
· Because canceling was successful, the value of Done changes to FALSE.

Task period

Execute Cancel Busy Canceled Done Error

TRUE FALSE
TRUE FALSE
TRUE FALSE
TRUE FALSE
TRUE FALSE TRUE FALSE

Canceled remains TRUE until Execute changes to FALSE.

 When Canceling Is Not Performed in Time
· Backup processing is executed when the value of Execute changes to TRUE. The value of Busy changes to TRUE.
· The value of Cancel is changed to TRUE. Backup processing continues because canceling was not performed in time.
· When backup processing is completed, the value of Busy changes to FALSE. · Backup processing was completed to the end, so the value of Done changes to TRUE. · Canceling was not performed in time, so the value of Canceled remains FALSE.
Task period

Execute Cancel Busy Canceled Done Error

TRUE FALSE
TRUE FALSE
TRUE FALSE
TRUE FALSE
TRUE FALSE TRUE FALSE

Canceling was not performed in time, so Canceled remains FALSE.

Backup processing was completed to the end, so Done changes to TRUE.

2-1456

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

BackupToMemoryCard

2 Instruction Descriptions

 When the Value of Execute Is Changed to TRUE While the Value of Cancel Is TRUE
· The value of Cancel is changed to TRUE. · Backup processing is not executed even if the value of Execute is changed to TRUE. Therefore,
the value of Busy remains FALSE. · It is assumed that backup processing was canceled, so the value of Canceled changes to TRUE. · When the value of Execute is changed to FALSE, the value of Canceled changes to FALSE.

Task period

Execute Cancel

TRUE FALSE
TRUE FALSE

2

Busy

TRUE FALSE

Canceled

TRUE FALSE

Done Error

TRUE FALSE
TRUE FALSE

It is assumed that backup processing was canceled, so Canceled changes to TRUE.

Backup processing is not performed, so the value of Busy remains FALSE.

Notation Example

The following figure shows a programming example. The backup file is saved in a directory called Dir1.

LD

ST

A
'Dir1' FALSE

BackupToMemoryCard_instance

BackupToMemoryCard

Execute DirName Cancel Option

Done Busy Error Canceled ErrorID

abc
def ghi jkl mno

BackupToMemoryCard_instance(A, 'Dir1', FALSE, , abc, def, ghi, jkl, mno);

NJ/NX-series Instructions Reference Manual (W502)

2-1457

2 Instruction Descriptions

Related System-defined Variables

Variable _Card1Ready
_Card1Protect*2 _Card1Err*2 _Card1Access*2 _Card1Deteriorated*2 _Card1PowerFail
_BackupBusy

Name
SD Memory Card Ready Flag

Data type
BOOL

SD Memory Card Write BOOL Protected Flag
SD Memory Card Error BOOL Flag

SD Memory Card Access Flag

BOOL

SD Memory Card Life BOOL Warning Flag

SD Memory Card

BOOL

Power Interruption Flag

Backup Function Busy BOOL Flag

Description
This flag indicates if the SD Memory Card can be accessed by instructions and communications commands.*1 TRUE: Can be used. FALSE: Cannot be used.
This flag indicates if the SD Memory Card is write protected when it is inserted and ready to use. TRUE: Write protected. FALSE: Not write protected.
This flag indicates if an unspecified SD Memory Card (e.g., an SDHC card) is mounted or if the format is incorrect (i.e., not FAT16 or corrupted). TRUE: Error. FALSE: No error.
This flag indicates if the SD Memory Card is currently being accessed.
TRUE: Being accessed.
FALSE: Not being accessed.
This flag indicates if the end of the life of the SD Memory Card is detected. TRUE: End of life detected. FALSE: Not detected.
This flag indicates if an error occurred in completing processing when power was interrupted during access*3. This flag is not cleared automatically. TRUE: Error. FALSE: No error.
This flag indicates if a backup, restoration, or verification is in progress.
TRUE: Backup, restore, or compare operation is in progress. FALSE: Backup, restore, or compare operation is not in progress.

*1 For the NJ/NX-series, it is a precondition that the SD Memory Card is physically inserted and mounted normally. For an NY-series Controller, it is a precondition that the shared folder is detected by the Controller.
*2 These variables are not used for the NY-series Controller. They are fixed to FALSE.
*3 For the NJ/NX-series, this indicates an access to the SD Memory Card. For an NY-series Controller, this indicates an access to the shared folder.

Additional Information
· Refer to the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) or NY-series Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for details on the backup functions.
· The root directory of the file name is the top level of the SD Memory Card.

2-1458

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

BackupToMemoryCard

2 Instruction Descriptions

Precautions for Correct Use

· Execution of this instruction is continued until processing is completed even if the value of Execute changes to FALSE or the execution time exceeds the task period. The value of Done changes to TRUE when processing is completed. Use this to confirm normal completion of processing.

· Refer to Using this Section (page 2-3) for a timing chart for Execute, Done, Busy, and Error.

· For an NJ/NX-series CPU Unit, if a file is open and the SD Memory Card is removed before the SD Memory Card power supply switch is pressed, the contents of the file will sometimes be corrupted. Always turn OFF the power supply before removing the SD Memory Card.

· Even if data backup to the SD Memory Card is prohibited, you can execute this instruction to backup the data. No error will occur.

2

· The values of the following system-defined variables that are related to backup do not change when this instruction is executed.

· SD Memory Card Backup Command: _CardBkupCmd

· SD Memory Card Backup Status: _Card1BkupSta

· Do not read or write backup-related files during execution of this instruction. If you read a file that is being written, unexpected processing may occur.

· Backup processing will continue even if the operating mode of the CPU Unit is changed during execution of this instruction. If you change the operating mode from RUN mode to PROGRAM mode and then back to RUN mode, the value of Busy will be FALSE even if backup processing is in progress. If you cancel backup processing under that condition, the value of Canceled will change to TRUE.

· An error will occur in the following cases. Error will change to TRUE.

· The SD Memory Card is not in a usable condition.

· The SD Memory Card is write protected.

· There is insufficient space available on the SD Memory Card.

· The maximum number of files or directories is exceeded.

· A file already exists with the same name as the name specified with DirName.

· The value of DirName is not a valid directory name.

· An error that prevents access occurs during SD Memory Card access.

· Another backup operation is already in progress.

· Backup processing failed.

Version Information
A CPU Unit with unit version 1.08 or later and Sysmac Studio version 1.09 or higher are required to use this instruction.

NJ/NX-series Instructions Reference Manual (W502)

2-1459

2 Instruction Descriptions

Sample Programming
In this example, the BackupToMemoryCard instruction backs up data to an SD Memory Card every day just after midnight. The backup-related files are stored in directories named /Backup/yyyy-mm-dd in the SD Memory Card. The directory name gives the date when the backup was executed. "yyyy" is the year, "mm" is the month, and "dd" is the day of the month.

Touch Panel Specifications
This example assumes that a touch panel is connected to the Controller. The touch panel has the following lamps.

Lamp name Backup normal end lamp Backup canceled lamp Backup error end lamp SD Memory Card life warning lamp SD Memory Card power interrupted lamp

Description Lights when backup processing ends normally. Lights when backup processing is successfully canceled. Lights when backup processing ends in an error. Lights when the life of the SD Memory Card was exceeded. Lights when power to the SD Memory Card was interrupted during backup processing.

The touch panel also has the following buttons.

Button name Lamps OFF button
Cancel button

Operation when button is pressed
Turns OFF the Backup Normal End Lamp, Backup Canceled Lamp, Backup Error End Lamp, and SD Memory Card Power Interrupted Lamp.
Cancels the backup.

2-1460

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

BackupToMemoryCard

2 Instruction Descriptions

Global Variables

Variable

Data type

Initial value

Comment

PTOut_Warning_SDLife

BOOL

FALSE

Output to SD Memory Card life warning lamp

PTOut_Warning_PwrFail_onBackup PTOut_Done

BOOL BOOL

FALSE FALSE

Output to SD Memory Card power interrupted lamp
Output to backup normal end lamp

PTOut_Cancel

BOOL

FALSE Output to backup canceled lamp

PTOut_Error PTIn_Check_Backup PTIn_Cancel

BOOL

FALSE Output to backup error end lamp

BOOL BOOL

FALSE FALSE

Input from lamps OFF button Input from cancel button

2

LD
Internal Variables

Variable CardOK

Backup_inst

PreviousDay

CurrentDT

Current_sDt

BackupCondition tmpString
tmpString2
BackupPath Cancel

Data type

Initial value

Comment

BOOL BackupToMemoryCard USINT DATE_AND_TIME
_sDT
BOOL STRING[256]
STRING[256]
STRING[64] BOOL

FALSE

SD Memory Card Normal Flag

Instance of BackupToMemoryCard instruction

0

Date of previous task

period

ST#1970-010100:00:00.00000 0000

Current date and time

(Year:=0, Month:=0, Day:=0, Hour:=0, Min:=0, Sec:=0, NSec:=0)

The current date and time separated into the year, month, day, hour, minutes, seconds, and nanoseconds.

FALSE

Backup Condition Established Flag

''

Temporary text string used

when creating directory

name

''

Temporary text string used

when creating directory

name

''

Directory name

FALSE

Cancel Conditions Established Flag.

NJ/NX-series Instructions Reference Manual (W502)

2-1461

2 Instruction Descriptions

External Variables

Variable _Card1Ready

_Card1Protect

_Card1Err

_Card1Deteriorated

_Card1PowerFail

_BackupBusy PTOut_Warning_SDLife

PTOut_Warning_PwrFail_onBackup PTOut_Done PTOut_Cancel PTOut_Error PTIn_Check_Backup PTIn_Cancel

Data type BOOL BOOL BOOL BOOL BOOL
BOOL BOOL
BOOL
BOOL BOOL BOOL BOOL BOOL

Constant
---
---------------

Comment
SD Memory Card Ready Flag
SD Memory Card Write Protected Flag
SD Memory Card Error Flag
SD Memory Card Life Warning Flag
SD Memory Card Power Interruption Flag Backup Function Busy Flag
Output to SD Memory Card life warning lamp Output to SD Memory Card power interrupted lamp Output to backup normal end lamp Output to backup canceled lamp Output to backup error end lamp Input from lamps OFF button Input from cancel button

2-1462

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

2 Instruction Descriptions

Check status of SD Memory Card. _Card1Ready _Card1Protect _Card1Err

CardOK

_Card1Deteriorated

PTOut_Warning_SDLife

_Card1PowerFail

PTIn_Check_Backup PTOut_Warning_PwrFail_onBackup

2
PTOut_Warning_PwrFail_onBackup

Light the Backup Normal End Lamp, Canceled Lamp, or Error End Lamp as required.

Backup_inst.Done PTIn_Check_Backup

PTOut_Done

PTOut_Done

Backup_inst.Canceled PTIn_Check_Backup PTOut_Cancel

PTOut_Cancel

Backup_inst.Error

PTIn_Check_Backup

PTOut_Error

PTOut_Error

BackupToMemoryCard

NJ/NX-series Instructions Reference Manual (W502)

2-1463

2 Instruction Descriptions

See if date has changed.

Current_sDt.Day

MOVE

EN

ENO

In

Out

PreviousDay

GetTime

EN

ENO

CurrentDT CurrentDT

DtToDateStruct

EN

ENO

In

DateStruct

Current_sDt

P_First_RunMode

<>

Backup_inst.Done Backup_inst.Canceled

EN

1

Current_sDt.Day In1

PreviousDay In2

BackupCondition

Backup_inst.Error 1

BackupCondition

Create directory name.

BackupCondition

DtToString

LEFT

EN CurrentDT In

ENO

EN

ENO

2

tmpString tmpString In

tmpString2

SINT#10 L

CONCAT

2

EN

'/Backup/' In1

tmpString2 In2

ENO BackupPath

Detect pressing of the Cancel Button.

PTIn_Cancel

Backup_inst.Busy

Backup_inst.Done Backup_inst.Canceled Backup_inst.Error

Cancel

Cancel

Execute BackupToMemoryCard instruction.

BackupCondition

CardOK

_BackupBusy
BackupPath Cancel

Backup_inst

BackupToMemoryCard

Execute DirName Cancel Option

Done Busy Error Canceled ErrorID

2-1464

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

BackupToMemoryCard

2 Instruction Descriptions

ST
Internal Variables

Variable CardOK

Backup_inst

PreviousDay

CurrentDT

Current_sDt

BackupCondition tmpString
tmpString2
BackupPath Cancel RS1 RS2 RS3 RS4 RS5 RS6

Data type

Initial value

Comment

BOOL

FALSE

SD Memory Card Normal Flag

BackupToMemoryCard

Instance of BackupToMemoryCard instruction

USINT

0

Date of previous task period

DATE_AND_TIME ST#1970-01- Current date and time

01-

00:00:00.00000 0000

2

_sDT

(Year:=0, Month:=0, Day:=0, Hour:=0, Min:=0, Sec:=0, NSec:=0)

The current date and time separated into the year, month, day, hour, minutes, seconds, and nanoseconds.

BOOL

FALSE

Backup Condition Established Flag

STRING[256]

''

Temporary text string used when creating directory name

STRING[256]

''

Temporary text string used when creating directory name

STRING[64]

''

Directory name

BOOL

FALSE

Cancel Conditions Established Flag

RS

Instance 1 of Reset-Prior-

ity Keep instruction

RS

Instance 2 of Reset-Prior-

ity Keep instruction

RS

Instance 3 of Reset-Prior-

ity Keep instruction

RS

Instance 4 of Reset-Prior-

ity Keep instruction

RS

Instance 5 of Reset-Prior-

ity Keep instruction

RS

Instance 6 of Reset-Prior-

ity Keep instruction

NJ/NX-series Instructions Reference Manual (W502)

2-1465

2 Instruction Descriptions

External Variables

Variable _Card1Ready

_Card1Protect

_Card1Err

_Card1Deteriorated

_Card1PowerFail

_BackupBusy PTOut_Warning_SDLife

PTOut_Warning_PwrFail_onBackup PTOut_Done PTOut_Cancel PTOut_Error PTIn_Check_Backup PTIn_Cancel

Data type BOOL BOOL BOOL BOOL BOOL
BOOL BOOL
BOOL
BOOL BOOL BOOL BOOL BOOL

Constant
---
---------------

Comment
SD Memory Card Ready Flag
SD Memory Card Write Protected Flag
SD Memory Card Error Flag
SD Memory Card Life Warning Flag
SD Memory Card Power Interruption Flag Backup Function Busy Flag
Output to SD Memory Card life warning lamp Output to SD Memory Card power interrupted lamp Output to backup normal end lamp Output to backup canceled lamp Output to backup error end lamp Input from lamps OFF button Input from cancel button

2-1466

// Check status of SD Memory Card. CardOK := _Card1Ready OR NOT(_Card1Protect) OR NOT(_Card1Err); PTOut_Warning_SDCardLife := _Card1Deteriorated; RS1(Set := _Card1PowerFail, Reset1 := PTIn_Check_Backup, Q1=>PTOut_Warning_PwrFail_onBackup);

// Light the Backup Normal End Lamp, Canceled Lamp, or Error End Lamp as

required.

RS2(Set := Backup_inst.Done,

Reset1 := PTIn_Check_Backup,

Q1

=> PTOut_Done);

RS3(Set := Backup_inst.Canceled,

Reset1 := PTIn_Check_Backup,

Q1

=> PTOut_Cancel);

RS4(Set := Backup_inst.Error,

Reset1 := PTIn_Check_Backup,

Q1

=> PTOut_Error);

// See if date has changed.

PreviousDay := Current_sDT.Day;

CurrentDT:=GetTime();

DtToDateStruct(In := CurrentDT,DateStruct=>Current_sDT);

RS5(Set := ( NOT (P_First_RunMode) & (Current_sDT.Day<>PreviousDay),

Reset1 := (Backup_inst.Done OR Backup_inst.Canceled OR Backup_inst.Error),

Q1

=> BackupCondition);

// Create directory name. IF(BackupCondition) THEN
BackupPath := CONCAT('/Backup/', Left(In:= DtToString(CurrentDT), L:=SINT#10));
END_IF;

// Detect pressing of the Cancel Button.

RS6(Set := (PTIn_Cancel &Backup_inst.Busy),

Reset1 := (Backup_inst.Done OR Backup_inst.Canceled OR Backup_inst.Error),

Q1

=> Cancel);

NJ/NX-series Instructions Reference Manual (W502)

SD Memory Card Instructions

2 Instruction Descriptions
// Execute BackupToMemoryCard instruction. Backup_inst(Execute := (BackupCondition & CardOK & NOT (_BackupBusy)),
DirName := BackupPath, Cancel := Cancel);
2

BackupToMemoryCard

NJ/NX-series Instructions Reference Manual (W502)

2-1467

2 Instruction Descriptions

2-1468

NJ/NX-series Instructions Reference Manual (W502)

Time Stamp Instructions

2
Time Stamp Instructions

Instruction NX_DOutTimeStamp NX_AryDOutTimeStamp

Name Write Digital Output with Specified Time Stamp Write Digital Output Array with Specified Time Stamp

Page 2-1470 2-1476

NJ/NX-series Instructions Reference Manual (W502)

2-1469

2 Instruction Descriptions

NX_DOutTimeStamp

The NX_DOutTimeStamp instruction writes a value to the output bit of a Digital Output Unit that supports time stamp refreshing.

Instruction

Name

NX_DOutTimeStamp

Write Digital Output with Specified Time Stamp

FB/ FUN
FB

Graphic expression

NX_DOutTimeStamp_instance

NX_DOutTimeStamp

Enable SetDOut SetTimeStamp SyncOutTime DOut

ENO

ST expression
NX_DOutTimeStamp_instance( Enable, SetDOut, SetTimeStamp, SyncOutTime, DOut, TimeStamp);

TimeStamp

Variables

Name

Meaning

I/O

Enable

Enable

SetDOut SetTimeStamp
SyncOut Time

Output value Specified time Input stamp
Time stamp of synchronous output

DOut

DOut Unit output bit

In-out

TimeStamp Time stamp

Description

Valid range

Unit

TRUE: Value of SetDOut is output.

FALSE: Output changes to

---

FALSE when Enable changes to

FALSE.

Output value Time to output value

Depends on data type.

The Time Stamp of

Synchronous Output device

ns

variable of the EtherCAT

Coupler Unit or an NX Unit on

the CPU Unit

The Output Bit ** device variable

of the Digital Output Unit that

---

supports time stamp refreshing

Depends on

The Output Bit ** Time Stamp data type.

device variable of the Digital Output Unit that supports time

ns

stamp refreshing

* If you omit an input parameter, the default value is not applied. A building error will occur.

Default FALSE 0 (*)
---

2-1470

NJ/NX-series Instructions Reference Manual (W502)

Time Stamp Instructions

2 Instruction Descriptions

Real numbers

Boolean BOOL

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME

LREAL REAL

LINT DINT INT SINT

ULINT

UDINT UINT USINT LWORD

DWORD WORD BYTE

Enable

OK

SetDOut

OK

SetTime-

OK

Stamp

SyncOut

OK

2

Time

DOut

OK

TimeStamp

OK

NX_DOutTimeStamp

Function
When the value of Enable is TRUE, the NX_DOutTimeStamp instruction writes output value SetDOut to the output bit of a Digital Output Unit that supports time stamp refreshing at the specified time. When Enable changes to FALSE, the value of the output bit changes to FALSE from the next task period. The error between the specified time and the output time is ±1 s max.
SyncOutTime (Time stamp of synchronous output) is based on the clock information in the EtherCAT Coupler Unit or NX Unit connected to the NX bus on the CPU Unit under which the Digital Output Unit that supports time stamp refreshing is connected. Specify the Time Stamp of Synchronous Output device variable of the EtherCAT Coupler Unit or NX Unit connected to the NX bus on the CPU Unit under which the Digital Output Unit is connected. However, you must add 0x200A:02 (Time Stamp of Synchronous Output) to the I/O entries for the EtherCAT Coupler Unit.
Set the DOut Unit output bit DOut to the Output Bit ** device variable that is assigned to the output bit of the Digital Output Unit that supports time stamp refreshing.
Set time stamp TimeStamp to the Output Bit ** Time Stamp device variable that is assigned to the output bit time stamp of the Digital Output Unit that supports time stamp refreshing.

Specifying the Output Time
Use the following procedure to specify the output time.
1 Get the device variable that is assigned to the clock information that is to serve as the reference
time for the Unit bit.
2 Calculate the difference between the obtained clock information and the time to write the data to
the output bit in nanoseconds and add it to the device variable from step 1.
3 Pass the results of adding the time difference to specified time stamp SetTimeStamp in the
NX_DOutTimeStamp instruction.
For details, refer to the sample programming that is provided for this instruction.

NJ/NX-series Instructions Reference Manual (W502)

2-1471

2 Instruction Descriptions

Precautions for Correct Use
· You can execute this instruction only for a Digital Output Unit that supports time stamp refreshing. However, an error will not occur even if you execute this instruction when no Digital Output Unit that supports time stamp refreshing is connected.
· If an EtherCAT communications error occurs or if the task period is exceeded, the writing may not occur at the specified time. In that case, the value is output in the next task period or later.
· If the device variables that are used with this instruction are used with other instructions in the same or a different program, perform exclusive control processing.
· Set SyncOutTime to the Time Stamp of Synchronous Output device variable of the EtherCAT Coupler Unit or NX Unit connected to the NX bus on the CPU Unit under which the Digital Output Unit that supports time stamp refreshing is connected. However, an error will not occur even if another variable is specified.
· Set DOut and TimeStamp to the device variables of the Digital Output Unit that supports time stamp refreshing where the bit value is to be output. However, an error will not occur even if other variables are specified.
· Set DOut and TimeStamp to the device variables for the same channel of the same Unit. However, an error will not occur even if other variables are specified.
· The value of TimeStamp is 0 if it shows a previous time. In this case, the output bit of a Digital Output Unit that supports time stamp refreshing will be refreshed immediately. Refer to the NX-series Digital I/O Units User's Manual (Cat. No. W521) for details.
Version Information
A CPU Unit with unit version 1.06 or later and Sysmac Studio version 1.07 or higher are required to use this instruction.

Sample Programming

In this sample, 10 ms after the value of input bit 00 of a Digital Input Unit that supports time stamp refreshing changes to TRUE, output bit 00 of a Digital Output Unit that supports time stamp refreshing changes to TRUE.
It is assumed that the value of input bit 00 is TRUE for longer than the I/O refresh period of the NX bus. A change to TRUE in input bit 00 is used as the input trigger in this sample. If the value of input bit 00 is TRUE for less than the I/O refresh period of the NX bus, the change to TRUE in input bit 00 is sometimes not detected. To solve that problem, for example, you could change the programming to use a change in the time that input bit 00 changes as the input trigger. Refer to the NX-series Digital I/O Units User's Manual (Cat. No. W521) for sample programming that turns ON an output after a specified time period expires after a change in a sensor input.

Input bit 00 of a Digital Input Unit that supports time stamp refreshing
Output bit 00 of a Digital Output Unit that supports time stamp refreshing

TRUE FALSE
TRUE FALSE

10 ms

2-1472

NJ/NX-series Instructions Reference Manual (W502)

Time Stamp Instructions

2 Instruction Descriptions

Network Configuration
The configuration of the network is given in the following table. A Slave Terminal with the following configuration is connected at EtherCAT node address 1. The device names that are given in the following table are used.

Unit number 0 1 2

Model number NX-ECC201 NX-ID3344 NX-OD2154

Unit EtherCAT Coupler Unit Digital Input Unit that supports time stamp refreshing Digital Output Unit that supports time stamp refreshing

Device name E001 N1 N2

Unit Operation Settings

2

The Unit operation settings of the Digital Input Unit that supports time stamp refreshing are given in the following table.

NX_DOutTimeStamp

Item
Time Stamp (Trigger Setting): Input Bit 00 Trigger Setting
Time Stamp (Mode Setting): Input Bit 00 Mode Setting

Set value

Meaning

FALSE Edge to read input changed time: Rising edge

TRUE

Operating mode to read input changed time: One-shot (First changed time)

I/O Map
The following I/O map settings are used.

Position
Node1

Port
Time Stamp of Synchronous Output

Unit1 Input Bit 00

Unit1 Unit2 Unit2

Input Bit 00 Time Stamp
Output Bit 00 Time Stamp
Output Bit 00

Description
Contains the time stamp for the timing of synchronous outputs from the connected NX Unit. (Unit: ns) Input bit 00

R/W

Data type

R ULINT

R BOOL

Input changed time for input R bit 00

Specified time for output bit W 00

Output bit 00

W

ULINT ULINT BOOL

Variable
E001_Time_Stamp_of_Synchronous_Output

Variable type
Global variable

N1_Input_Bit_00
N1_Input_Bit_00_Time_Stamp N2_Output_Bit_00_ Time_Stamp N2_Output_Bit_00

Global variable
Global variable
Global variable
Global variable

NJ/NX-series Instructions Reference Manual (W502)

2-1473

2 Instruction Descriptions

LD

Internal Variables

Variable
SetTimeStamp SetDOut NX_DOutTimeStamp _instance

Data type

Initial value

ULINT BOOL NX_DOutTimeStamp

0 FALSE

Comment
Specified time stamp Output value

External Vari-
ables

Variable
N1_Input_Bit_00 N1_Input_Bit_00_Time_Stamp E001_Time_Stamp_of_Synchronous_O utput N2_Output_Bit_00 N2_Output_Bit_00_Time_Stamp

Data type
BOOL ULINT ULINT
BOOL ULINT

Constant

Comment

---

Input bit 00

---

Input changed time for input bit 00

---

Time stamp for the timing of synchronous

outputs from the connected NX Unit

---

Output bit 00

---

Specified time for output bit 00

Specify the output time stamp. N1_Input_Bit_00
N1_Input_Bit_00_Time_Stamp ULINT#10000000

ADD
EN ENO In1 In2

SetDOut
S SetTimeStamp

Output
SetDOut SetTimeStamp E001_Time_Stamp_of_Synchronous_Output N2_Output_Bit_00 N2_Output_Bit_00_Time_Stamp

NX_DOutTimeStamp_instance

NX_DOutTimeStamp

Enable SetDOut SetTimeStamp SyncOutTime DOut

ENO

TimeStamp

N2_Output_Bit_00 N2_Output_Bit_00_Time_Stamp

2-1474

NJ/NX-series Instructions Reference Manual (W502)

Time Stamp Instructions

2 Instruction Descriptions

ST

Internal Variables

Variable
SetEN SetTimeStamp SetDOut R_TRIG_instance NX_DOutTimeStamp _instance

Data type

Initial value

BOOL ULINT BOOL R_TRIG NX_DOutTimeStamp

FALSE 0 FALSE

Comment
Execution condition Specified time stamp Output value

External Vari-
ables

Variable

Data type

Constant

Comment

2

N1_Input_Bit_00

BOOL

---

Input bit 00

N1_Input_Bit_00_Time_Stamp

ULINT

---

Input changed time for input bit 00

E001_Time_Stamp_of_Synchronous_O ULINT

---

Time stamp for the timing of synchronous

utput

outputs from the connected NX Unit

N2_Output_Bit_00

BOOL

---

Output bit 00

N2_Output_Bit_00_Time_Stamp

ULINT

---

Specified time for output bit 00

NX_DOutTimeStamp

// Execution trigger input R_TRIG_instance( N1_Input_Bit_00, SetEN);

// Specify the output time stamp.

IF ( SetEN = TRUE ) THEN

SetDOut

:= TRUE;

SetTimeStamp := N1_Input_Bit_00_Time_Stamp + ULINT#10000000;

END_IF;

// Output

NX_DOutTimeStamp_instance(

Enable

:= TRUE,

SetDOut

:= SetDOut,

SetTimeStamp := SetTimeStamp,

SyncOutTime := E001_Time_Stamp_of_Synchronous_Output,

DOut

:= N2_Output_Bit_00,

TimeStamp := N2_Output_Bit_00_Time_Stamp);

NJ/NX-series Instructions Reference Manual (W502)

2-1475

2 Instruction Descriptions

NX_AryDOutTimeStamp

The NX_AryDOutTimeStamp instruction outputs pulses from a Digital Output Unit that supports time stamp refreshing.

Instruction
NX_AryDOutTimeStamp

Name
Write Digital Output Array with Specified Time Stamp

FB/ FUN
FB

Graphic expression
NX_AryDOutTimeStamp_instance NX_AryDOutTimeStamp
Enable SetDOut

ST expression
NX_AryDOutTimeStamp _instance(Enable, SetDOut, SyncOutTime, DOut, TimeStamp); ENO

SyncOutTime DOut

TimeStamp

Variables

Name

Meaning

I/O

Enable

Enable

SyncOut Time

Input
Time stamp of synchronous output

SetDOut DOut

Output pulses
DOut Unit output bit
In-out

TimeStamp Time stamp

Description

Valid range

Unit

TRUE: Output changes according to the setting of SetDOut.

FALSE: Output changes to

---

FALSE when Enable changes to

FALSE.

Depends on

The Time Stamp of

data type.

Synchronous Output device

variable of the EtherCAT

ns

Coupler Unit or an NX Unit on

the CPU Unit

Output pulses

---

The Output Bit ** device variable

---

of the Digital Output Unit that

supports time stamp refreshing

Depends on

The Output Bit ** Time Stamp data type.

device variable of the Digital Output Unit that supports time

ns

stamp refreshing

* If you omit the input parameter, the default value is not applied. A building error will occur.

Default FALSE (*)
---

Bit strings

Integers

Times, durations, dates, and text strings

Real numbers

LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

STRING DT TOD
DATE TIME

LREAL REAL

Enable

OK

SyncOut Time

SetDOut

DOut

OK

TimeStamp

2-1476

OK Refer to Function for details on the structure _sOUTPUT_REF.
OK
NJ/NX-series Instructions Reference Manual (W502)

Time Stamp Instructions

NX_AryDOutTimeStamp

2 Instruction Descriptions
Function
When the value of Enable is TRUE, the NX_AryDOutTimeStamp instruction outputs the pulses set with output pulses SetDOut from a Digital Output Unit that supports time stamp refreshing at the specified times. When the value of Enable changes to FALSE, the NX_AryDOutTimeStamp instruction outputs FALSE to the Digital Output Unit that supports time stamp refreshing. The error between the specified time and the output time is ±1 s max.
SyncOutTime (Time stamp of synchronous output) is based on the clock information in the EtherCAT Coupler Unit or NX Unit connected to the NX bus on the CPU Unit under which the Digital Output Unit
that supports time stamp refreshing is connected. Specify the Time Stamp of Synchronous Output 2
device variable of the EtherCAT Coupler Unit or NX Unit connected to the NX bus on the CPU Unit under which the Digital Output Unit is connected. However, you must add 0x200A:02 (Time Stamp of Synchronous Output) to the I/O entries for the EtherCAT Coupler Unit.
Set the DOut Unit output bit DOut to the Output Bit ** device variable that is assigned to the output bit of the Digital Output Unit that supports time stamp refreshing.
Set time stamp TimeStamp to the Output Bit ** Time Stamp device variable that is assigned to the output bit time stamp of the Digital Output Unit that supports time stamp refreshing.
Specifying the Output Time
Use the following procedure to specify the output time.
1 Get the device variable that is assigned to the clock information that is to serve as the reference
time for the Unit bit.
2 Calculate the difference between the obtained clock information and the time to turn ON the out-
put bit in nanoseconds and add it to the device variable from step 1.
3 Pass the results of adding the time difference to SetDOut.OnTime[] in the NX_AryDOutTime-
Stamp instruction.
4 In the same way as in step 2, calculate the difference between the obtained clock information
and the time to turn OFF the output bit in nanoseconds and add it to the device variable from step 1.
5 Pass the results of adding the time difference to SetDOut.OffTime[] in the NX_AryDOutTime-
Stamp instruction.

NJ/NX-series Instructions Reference Manual (W502)

2-1477

2 Instruction Descriptions

Specifying the Output Pulses

The data type of output pulses SetDOut is structure _sOUTPUT_REF. The specifications are as follows:

Name SetDOut

Meaning

Description

Output pulses Output pulses

Output enable flag

Data type
_sOUTPUT _REF

Valid range ---

Unit Default --- ---

EnableOut

TRUE: Enable OnTime Output enable and OffTime settings. BOOL

--- FALSE

OnTime[] array ON times OffTime[] array OFF times

FALSE: Disable OnTime and OffTime settings.
Times at which to turn ON the output bit
Times at which to turn OFF the output bit

ARRAY[0..15] OF ULINT
ARRAY[0..15] OF ULINT

Depends on data type.

0 for all ns ele-
ments

The ON times OnTime[] and OFF times OffTime[] arrays each have 16 elements. The values of the elements with the same element numbers in both arrays are the ON time and OFF time for one pulse. Therefore, you can specify up to 16 pulses. If the value of the same element in both arrays is 0, the values of all of the elements past them are disabled.
For example, the following figure shows the output operation for the following values of the elements of OnTime[] and OffTime[]. The times specified in the following table indicate the number of milliseconds after the reference time.

Name 0

Element numbers

1

2

3

OnTime[] 10 ms later 30 ms later 60 ms later 0

OffTime[] 20 ms later 35 ms later 80 ms later 0

Reference time

Output

TRUE FALSE

10 ms

20 ms

30 ms 35 ms

60 ms 80 ms

4 90 ms later 100 ms later

The values of the elements of OnTime[] and OffTime[] do not need to be in chronological order. For example, the output operation for the following values of the elements of OnTime[] and OffTime[] would be the same as the one shown above.

Name
OnTime[] OffTime[]

Element numbers

0

1

2

3

30 ms later 60 ms later 10 ms later 0

35 ms later 80 ms later 20 ms later 0

4 90 ms later 100 ms later

2-1478

NJ/NX-series Instructions Reference Manual (W502)

Time Stamp Instructions

2 Instruction Descriptions

 EnableOut (Output Enable)
Output enable EnableOut enables the settings in OnTime[] and OffTime[]. If the value of EnableOut is FALSE, the output value is FALSE regardless of the values in OnTime[] and OffTime[].

You can change the value of EnableOut during execution of the instruction.

When the value of EnableOut changes to FALSE, the output value changes to FALSE.

Settings in OnTime[] and OffTime[]

TRUE FALSE

EnableOut TRUE FALSE

Output TRUE

2

FALSE

NX_AryDOutTimeStamp

When the value of EnableOut changes to TRUE, the values in OnTime[] and OffTime[] are enabled.

TRUE Settings in OnTime[] and OffTime[] FALSE

EnableOut

TRUE FALSE

Output

TRUE FALSE

 Minimum Output Pulse Width

To output pulses with a time accuracy of 1 s, set each of the interval between OnTime[] and OffTime[] to at least twice the task period. If the interval is less than two task periods, the pulse will be delayed from the specified ON/OFF time by one task period when the pulse is not output as specified.

At least twice the task period

OnTime[0], OffTime[0]

TRUE FALSE

OnTime[1], OffTime[1]

TRUE FALSE

Refer to the following description for details on the operation.

 Setting the Same Value for the Same Elements of OnTime[] and OffTime[]
If you set the same value for the same elements of OnTime[] and OffTime[], the output will remain FALSE. Therefore, the following figure shows the output operation for the following values of the elements of the two arrays.

Name

Element numbers

0

1

2

OnTime[] 10 ms later 30 ms later 0

OffTime[] 20 ms later 30 ms later 0

Reference time

Output

TRUE FALSE

10 ms

20 ms

30 ms

Remains FALSE.

NJ/NX-series Instructions Reference Manual (W502)

2-1479

2 Instruction Descriptions

 When Value in OnTime[] Is Larger Than Value in OffTime[] for the Same Element
If the value in OnTime[] is larger than value in OffTime[] for the same element, the output value will change to FALSE first and then change to TRUE.
Also, if the lowest value of the elements of OnTime[] is larger than the lowest value of the elements of OffTime[], the output value will change to TRUE immediately after the instruction is executed. Also, if the highest value of the elements of OnTime[] is larger than the highest value of the elements of OffTime[], the output value will remain TRUE after the instruction is executed.
Therefore, the following figure shows the output operation for the following values of the elements of the two arrays.

Name

Element numbers

0

1

2

OnTime[] 20 ms later

35 ms later

0

OffTime[] 10 ms later

30 ms later

0

Reference time

Output

TRUE FALSE

10 ms

20 ms

30 ms 35 ms

 When Value of One Element in OnTime[] and OffTime[] Is 0
If the value of the element in OnTime[] or OffTime[] is 0, the value of the output will change to TRUE or FALSE immediately after execution of the instruction.
If the only the value of the element in OnTime[] is 0, the value of the output will change to TRUE immediately after execution of the instruction. Therefore, the following figure shows the output operation for the following values of the elements of the two arrays.

Name

Element numbers

0

1

2

OnTime[] 0

30 ms later

0

OffTime[] 20 ms later

35 ms later

0

Reference time

Output

TRUE FALSE

20 ms 30 ms 35 ms

If the only the value of the element in OffTime[] is 0, the value of the output will change to FALSE immediately after execution of the instruction. Therefore, the following figure shows the output operation for the following values of the elements of the two arrays.

Name

Element numbers

0

1

2

OnTime[] 10 ms later

35 ms later

0

OffTime[] 0

30 ms later

0

2-1480

NJ/NX-series Instructions Reference Manual (W502)

Time Stamp Instructions

2 Instruction Descriptions

Reference time

Output

TRUE FALSE

10 ms

30 ms 35 ms

 When, in the Same Task Period, the Output Value Is Consecutively Set to

TRUE and FALSE

2

If the output value is consecutively set to TRUE and FALSE in the same tack period, the value of the

output will not change.

Task period

NX_AryDOutTimeStamp

Settings in OnTime[] and OffTime[] TRUE FALSE
Output TRUE FALSE

Remains FALSE.

 Changing the Values in OnTime[] or OffTime[] While the Instruction Is Enabled
You can change the values in OnTime[] and OffTime[] while the instruction is enabled. The changes are valid the next time the instruction is executed.

Settings in OnTime[] and OffTime[] before change

TRUE FALSE

Settings in OnTime[] and OffTime[] after change

TRUE FALSE

OutputTRUE FALSE

New OffTime[] value.
The changed values in OffTime[] are used when the instruction is executed.

 Overlapping TRUE Settings for an Output Value
If TRUE settings for an output value overlap, an error will not occur and the output value will remain TRUE. The same logic applies when the FALSE settings for an output value overlap. Therefore, the following figure shows the output operation for the following values of the elements of the two arrays.

Name

Element numbers

0

1

2

OnTime[] 10 ms later 20 ms later 0

OffTime[] 30 ms later 40 ms later 0

NJ/NX-series Instructions Reference Manual (W502)

2-1481

2 Instruction Descriptions

Reference time

Settings in OnTime[0] TRUE

and OffTime[0]

FALSE

Settings in OnTime[1] TRUE

and OffTime[1]

FALSE

Output TRUE FALSE

10 ms 20 ms 30 ms 40 ms

The output value is already TRUE so it remains TRUE.
The output value is already FALSE so it remains FALSE.

 Simultaneous TRUE and FALSE Settings for an Output Value
If there are TRUE and FALSE settings at the same time for an output value, an error will not occur and the setting for the element in OnTime[] and OffTime[] with the lower element number is given priority. Therefore, the following figure shows the output operation for the following values of the elements of the two arrays.

Name

Element numbers

0

1

2

OnTime[] 10 ms later 20 ms later 0

OffTime[] 20 ms later 30 ms later 0

Reference time

Settings in OnTime[0] TRUE

and OffTime[0]

FALSE

Settings in OnTime[1] TRUE

and OffTime[1]

FALSE

Output TRUE FALSE

10 ms 20 ms 30 ms

The setting of OffTime[0] is given priority over the setting of OnTime[1], so the output value changes to FALSE.

Additional Information
This instruction is used with the MC_DigitalCamSwitch instruction. For details on the MC_DigitalCamSwitch instruction, refer to the NJ/NX-series Motion Control Instructions Reference Manual (Cat. No. W508) or NY-series Motion Control Instructions Reference Manual (Cat. No. W561).

Precautions for Correct Use
· You can execute this instruction only for a Digital Output Unit that supports time stamp refreshing. However, an error will not occur even if you execute this instruction when no Digital Output Unit that supports time stamp refreshing is connected.
· If an EtherCAT communications error occurs or if the task period is exceeded, the output may not occur at the specified time. In that case, the value is output in the next task period or later.
· If the device variables that are used with this instruction are used with other instructions in the same or a different program, perform exclusive control processing.
· Set SyncOutTime to the Time Stamp of Synchronous Output device variable of the EtherCAT Coupler Unit or NX Unit connected to the NX bus on the CPU Unit under which the Digital Output Unit that supports time stamp refreshing is connected. However, an error will not occur even if other variables are specified.

2-1482

NJ/NX-series Instructions Reference Manual (W502)

Time Stamp Instructions

2 Instruction Descriptions
· Set DOut and Timestamp to the device variables of the Digital Output Unit that supports time stamp refreshing where the bit value is to be output. However, an error will not occur even if other variables are specified.
· Set DOut and Timestamp to the device variables for the same channel of the same Unit. However, an error will not occur even if other variables are specified.
· The value of TimeStamp is 0 if it shows a previous time. In this case, the output bit of a Digital Output Unit that supports time stamp refreshing will be refreshed immediately. Refer to the NX-series Digital I/O Units User's Manual (Cat. No. W521) for details.
Version Information
A CPU Unit with unit version 1.06 or later and Sysmac Studio version 1.07 or higher are required 2
to use this instruction.
Sample Programming
For sample programming, refer to the description of the MC_DigitalCamSwitch in the NJ/NX-series Motion Control Instructions Reference Manual (Cat. No. W508) or NY-series Motion Control Instructions Reference Manual (Cat. No. W561).

NX_AryDOutTimeStamp

NJ/NX-series Instructions Reference Manual (W502)

2-1483

2 Instruction Descriptions

2-1484

NJ/NX-series Instructions Reference Manual (W502)

Other Instructions

2
Other Instructions

Instruction ReadNbit_** WriteNbit_** ChkRange GetMyTaskStatus GetMyTaskInterval Task_IsActive Lock and Unlock ActEventTask Get**Clk Get**Cnt

Name N-bit Read Group N-bit Write Group Check Subrange Variable Read Current Task Status Read Current Task Period Determine Task Status Lock Tasks/Unlock Tasks Activate Event Task Get Clock Pulse Group Get Incrementing Free-running Counter Group

Page 2-1486 2-1488 2-1490 2-1492 2-1495 2-1498 2-1500 2-1507 2-1513 2-1514

NJ/NX-series Instructions Reference Manual (W502)

2-1485

2 Instruction Descriptions

ReadNbit_**

The ReadNbit_** instructions read zero or more bits from a bit string.

Instruction ReadNbit_**

Name N-bit Read Group

FB/FUN FUN

Graphic expression

(@)ReadNbit_**

EN

ENO

In

Out

Pos

Size

"**" must be a bit string data type.

ST expression Out:=ReadNbit_**(In, Pos, Size);
"**" must be a bit string data type.

Variables

Name In
Pos
Size Out

Meaning

I/O

Read source

Read position

Input

Read size

Read result Output

Description Bit string to read
Bit position to read
Number of bits to read Read result

Valid range

Unit

Depends on data type.

0 to No. of bits in In -1 ---

0 to No. of bits in In Depends on data type. ---

Default
0
1 ---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK OK OK OK

Pos

OK

Size

OK

Out

Must be same data type as In

Function
A ReadNbit_** instruction reads the values of the upper Size bits from read position Pos in source bit string In. It assigns the values to read result Out. The name of the instruction is determined by the data types of In and Out. For example, if In and Out are the WORD data type, the instruction is ReadNbit_WORD.

2-1486

NJ/NX-series Instructions Reference Manual (W502)

Other Instructions

2 Instruction Descriptions

The following example shows the ReadNbit_BYTE instruction when In is BYTE#16#89, Pos is USINT#2 and Size is USINT#4.

LD

ST

BYTE#16#89 USINT#2 USINT#4

ReadNbit_BYTE

EN

ENO

In

Pos

Size

abc:=ReadNbit_BYTE(BYTE#16#89, USINT#2, USINT#4);
abc

Size=USINT#4
2

Bit 7

Bit 0

In 1 0 0 0 1 0 0 1

ReadNbit_**

Bit 7

Pos=USINT#2 Bit 0

Out=abc 0 0 0 0 0 0 1 0

Additional Information
Use a WriteNbit_** instruction to write zero or more bits to a bit string.

Precautions for Correct Use
· The data types of In and Out must be the same. · If the value of Size is 0, the value of Out is 16#0. · An error occurs in the following cases. ENO will be FALSE, and Out will not change.
· The value of Size is outside of the valid range. · The value of Pos is outside of the valid range. · The bit string in In does not have enough bits for the number of bits specified by Size from the
position specified by Pos.

NJ/NX-series Instructions Reference Manual (W502)

2-1487

2 Instruction Descriptions

WriteNbit_**

The WriteNbit_** instructions write zero or more bits to a bit string.

Instruction WriteNbit_**

Name

FB/FUN

N-bit Write Group FUN

Graphic expression

(@)WriteNbit_**

EN

ENO

In

Out

InOut

Pos Size
"**" must be a bit string data type.

ST expression WriteNbit_**(In, Pos, Size, InOut);
"**" must be a bit string data type.

Variables

Name In
Pos
Size InOut Out

Meaning

I/O

Read source

Write position

Input

Write size

Write target In-out

Return value

Output

Description

Valid range

Unit

Bit string from which to read Depends on data type. bits to write to InOut

Bit position to which to write 0 to No. of bits in InOut ---1

Number of bits to write

0 to No. of bits in In

Write result

Depends on data type. ---

Always TRUE

TRUE only

---

Default
0
1
-----

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In Pos Size InOut Out

OK OK OK OK OK OK
OK

Must be same data type as In

Function
A WriteNbit_** instruction first reads the lower Size bits from read source In. Then it writes the values that it read to write position Pos in write target InOut. The name of the instruction is determined by the data types of In and Out. For example, if In and Out are the WORD data type, the instruction is WriteNbit_WORD.

2-1488

NJ/NX-series Instructions Reference Manual (W502)

Other Instructions

2 Instruction Descriptions

The following example shows the WriteNbit_BYTE instruction when In is BYTE#16#89, Pos is USINT#2 and Size is USINT#4.

LD

ST

WriteNbit_BYTE(BYTE#16#89, abc, USINT#2, USINT#4);

WriteNbit_BYTE

BYTE#16#89 abc

EN In InOut

ENO abc

USINT#2 Pos USINT#4 Size
2

Size=USINT#4

Bit 7

Bit 0

In 1 0 0 0 1 0 0 1

WriteNbit_**

Bit 7

Bit 0

InOut=abc 0 0 1 0 0 1 0 0

Pos=USINT#2

Additional Information
Use a ReadNbit_** instruction to read zero or more bits from a bit string.

Precautions for Correct Use
· The data types of In and InOut must be the same. · The value of InOut does not change if the value of Size is 0. · Return value Out is not used when the instruction is used in ST. · An error occurs in the following cases. ENO will be FALSE, and InOut will not change.
· The value of Size is outside of the valid range. · The value of Pos is outside of the valid range. · The bit string in InOut does not have enough bits for the number of bits specified by Size from the
position specified by Pos.

NJ/NX-series Instructions Reference Manual (W502)

2-1489

2 Instruction Descriptions

ChkRange

The ChkRange instruction determines if the value of a variable is within the valid range of the range type specification.

Instruction ChkRange

Name
Check Subrange Variable

FB/FUN FUN

Graphic expression

(@)ChkRange

EN

Out

In

Val

ST expression Out:=ChkRange(In, Val);

Variables

Name In
Val

Meaning
Variable to check
Range specificatio n variable

I/O Input

Description Variable to check

Valid range Depends on data type.

Range specification variable Depends on the range specification.

Out

Check

Output

Check result

result

Depends on data type.

* If you omit the input parameter, the default value is not applied. A building error will occur.

Unit -----

Default * ---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

In

OK OK OK OK OK OK OK OK

Val

The basic data type that is the basis for the range specification must be the same as In.

Out

OK

Function
The ChkRange instruction determines if the value of variable to check In is within the valid range of the range specification variable Val. If the value is within the valid range, check result Out is TRUE. If the value is not within the valid range, check result Out is FALSE.

Additional Information
You can define the range type specification for integer variables (USINT, UINT, UDINT, ULINT, SINT, INT, DINT, and LINT).

2-1490

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Other Instructions

Precautions for Correct Use
· If In is not a range specification variable, the value of Out changes to TRUE. · If this instruction is used in a ladder diagram, the value of Out changes to FALSE if an error occurs in
the previous instruction on the rung.

Sample Programming

Here, the result of addition i is checked to see if it is within the valid range (10 to 99) of the range speci-
fication variable x. If it is not within the valid range, the value of variable Correct is assigned to variable 2
x.
LD

ChkRange

Variable Data type Initial value

i

INT

0

abc

INT

0

def

INT

0

x

INT(10..99) 10

Correct

INT

0

P_On

ADD

EN ENO

abc In1

i

def In2

ChkRange
EN i In x Val

MOVE

EN i In

ENO Out x

MOVE

EN Correct In

ENO Out x

ST

Variable Data type Initial value

i

INT

0

abc

INT

0

def

INT

0

Chk

BOOL

FALSE

x

INT(10..99) 10

Correct

INT

0

i := abc+def; Chk:=ChkRange(i, x); // Check subrange variable.

IF (Chk=TRUE) THEN x := i;
ELSE x := Correct;
END_IF;

// Assign i to x if value of i is in range. // Assign Correct to x if value of i is out of range.

NJ/NX-series Instructions Reference Manual (W502)

2-1491

2 Instruction Descriptions

GetMyTaskStatus

The GetMyTaskStatus reads the status of the current task.

Instruction GetMyTaskStatus

Name
Read Current Task Status

FB/FUN FUN

Graphic expression

(@)GetMyTaskStatus

EN

ENO

Out

LastExecTime

MaxExecTime

MinExecTime

ExecCount

Exceeded

ExceedCount

ST expression
GetMyTaskStatus( LastExecTime, MaxExecTime, MinExecTime, ExecCount, Exceeded, ExceedCount);

Variables

Name Out LastExec Time MaxExec Time MinExec Time ExecCount
Exceeded

Meaning
Return value
Last task execution time
Maximum task execution time
Minimum task execution time
Task execution count
Task period exceeded flag

I/O Output

ExceedCount

Task period exceeded count

* Negative numbers are excluded.

Description

Valid range

Unit

Always TRUE

TRUE only

---

Last task execution time of the current task

Maximum task execution time of the current task

Depends on data type.* ns

Minimum task execution time of the current task

Number of task executions of the current task

TRUE: The last execution of

the current task was not

completed within the task

period. FALSE: The last execution

Depends on data type. ---

of the current task was com-

pleted within the task period.

The number of times the current task has exceeded the task period.

Default
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

Out LastExec Time MaxExec Time MinExec Time
2-1492

OK OK OK OK
NJ/NX-series Instructions Reference Manual (W502)

Other Instructions
STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

2 Instruction Descriptions

Bit strings

Integers

Times, durations, dates, and text strings

ExecCount

OK

Exceeded OK

Exceed-

OK

Count

2

Function

The GetMyTaskStatus reads the status of the current task. The task status includes the last task execution time LastExecTime, maximum task execution time MaxExecTime, minimum task execution time MinExecTime, task execution count ExecCount, task period exceeded flag Exceeded, and task period exceeded count ExceedCount.

GetMyTaskStatus

Additional Information
MaxExecTime, MinExecTime, ExecCount, and ExceedCount are reset at the following times. · When operation is started · When a reset operation is executed from the Task Execution Time Monitor of the Sysmac Studio.

Precautions for Correct Use
· When the value of ExecCount or ExceedCount exceeds the maximum value of UDINT data (4,294,967,295), it returns to 0.
· Return value Out is not used when the instruction is used in ST.

Sample Programming
In this sample, the GetMyTaskStatus reads the status of the current task. If the previous task execution time exceeds 400 s (400000 ns), the value of the Warning variable changes to TRUE.

NJ/NX-series Instructions Reference Manual (W502)

2-1493

2 Instruction Descriptions

LD Variable
ExecTime_t ExecTime_ns Warning

Data type TIME INT BOOL

Initial value

Comment

T#0s

Previous task execution time (TIME data)

0

Previous task execution time (nanoseconds LINT data)

FALSE

Warning

P_On

GetMyTaskStatus

EN

ENO

LastExecTime MaxExecTime MinExecTime
ExecCount Exceeded ExceedCount

ExecTime_t

ExecTime_t

TimeToNanoSec

EN

ENO

In

ExecTime_ns

ExecTime_ns LINT#400000

>
EN In1 In2

Warning

ST Variable
ExecTime_t ExecTime_ns Warning

Data type TIME LINT BOOL

Initial value

Comment

T#0s

Previous task execution time (TIME data)

0

Previous task execution time (nanoseconds LINT data)

FALSE

Warning

GetMyTaskStatus(LastExecTime=>ExecTime_t); // Get previous task period.

ExecTime_ns:=TimeToNanoSec(ExecTime_t); // Convert previous task period from TIME data to nanoseconds.

IF (ExecTime_ns>DINT#400000) THEN

// If previous task period exceeds 400,000 ns...

Warning:=TRUE;

// Assign TRUE to Warning variable.

ELSE

Warning:=FALSE;

END_IF;

2-1494

NJ/NX-series Instructions Reference Manual (W502)

Other Instructions

2 Instruction Descriptions

GetMyTaskInterval

The GetMyTaskInterval instruction reads the task period of the current task.

Instruction

Name

FB/FUN

Graphic expression

ST expression

GetMyTask Interval

Read Current FUN Task Period

(@)GetMyTaskInterval

EN

ENO

Out

Out:=GetMyTaskInterval();

2

GetMyTaskInterval

Variables

Name Out

Meaning Task period

I/O Output

Description Task period of current task

*1 Negative numbers are excluded.

Valid range
Depends on data type.*1

Unit ms

Default ---

Bit strings

Integers

Times, durations, dates, and text strings

Real numbers

Boolean BOOL

STRING DT TOD
DATE TIME

LREAL REAL

LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE

Out

OK

Function
The GetMyTaskInterval instruction reads the task period of the current task and stores it in task period Out if the task that executes the instruction is the primary periodic task or a periodic task.

If an event task executes the instruction, the value of Out will be T#0s.

The following figure shows a programming example. If the task period of the current task is 1 ms, the value of abc will be T#1ms.

LD

ST

abc:=GetMyTaskInterval();

GetMyTaskInterval

EN

ENO

abc

NJ/NX-series Instructions Reference Manual (W502)

2-1495

2 Instruction Descriptions
Version Information A CPU Unit with unit version 1.08 or later and Sysmac Studio version 1.09 or higher are required to use this instruction.

2-1496

NJ/NX-series Instructions Reference Manual (W502)

Other Instructions

2 Instruction Descriptions

Sample Programming
This example reads the task period of the current task when this program is first executed after operation starts. Then the task period that was read is converted from TIME data to LREAL data in milliseconds. This sample programming can be used, for example, to calculate the axis target position for each task period.

The following procedure is used to convert TIME data to LREAL data in milliseconds.

1 The GetMyTaskInterval instruction is used to read the task period as TIME data.

2 The TimeToNanoSec instruction is used to convert TIME data to LINT data in nanoseconds.

2

3 The LINT_TO_LREAL instruction is used to convert LINT data in nanoseconds to LREAL data
in nanoseconds.
4 The DIV instruction is used to divide the result of step 3 by 1,000,000 to convert to milliseconds.

GetMyTaskInterval

LD
Variable Intv_tm Intv_ns Intv

Data type TIME LINT LREAL

Default T#0s 0 0

Comment Task period as TIME data Task period as LINT data in nanoseconds Task period as LREAL data in milliseconds

P_First_RunMode

GetMyTaskInterval

EN

ENO

Intv_tm

Intv_tm

TimeToNanoSec

EN

ENO

In

Intv_ns

LINT_TO_LREAL

DIV

EN Intv_ns In

ENO

EN ENO

Intv

Intv In1

Intv

LREAL#1000000.0 In2

ST
Variable Intv

Data type LREAL

Default 0

Comment Task period as LREAL data in milliseconds

IF P_First_RunMode = TRUE THEN Intv := LINT_TO_LREAL(TimeToNanoSec(GetMyTaskInterval()))/1000000;
END_IF;

NJ/NX-series Instructions Reference Manual (W502)

2-1497

2 Instruction Descriptions

Task_IsActive

The Task_IsActive instruction determines if the specified task is currently in execution.

Instruction Task_IsActive

Name
Determine Task Status

FB/FUN FUN

Graphic expression

(@)Task_IsActive

EN

Out

TaskName

ST expression
Out:=Task_IsActive( TaskName);

Variables

Name

Meaning

I/O

TaskName Task name Input

Out

Judgement Output

Description

Valid range

Unit

Task name

64 bytes max. (63 sin- --gle-byte alphanumeric characters plus the final NULL character)

TRUE: Task is in execution Depends on data type. --or on standby.

FALSE: Not active

Default ''
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

TaskName

OK

Out

OK

Function
The Task_IsActive instruction determines if the task specified with TaskName is currently in execution or on standby. "On standby" means that a high-priority task was started after this task was started, so processing has been interrupted. If it is being executed or on standby, the value of judgment Out is TRUE. If it is not being executed, the value of Out is FALSE.
Precautions for Correct Use
· You cannot use a variable to which a text string was assigned for TaskName. Directly specify a text string.
· If this instruction is used in a ladder diagram, the value of Out changes to FALSE if an error occurs in the previous instruction on the rung.
· An error occurs in the following case. The value of Out does not change. · The task specified with TaskName does not exist.

2-1498

NJ/NX-series Instructions Reference Manual (W502)

Other Instructions

2 Instruction Descriptions

Sample Programming

In this sample, the instruction determines whether periodic task Tc2 is active when the value of variable A changes to TRUE. If it is active, the value of variable B changes to TRUE.
LD

Variable A

Data type Initial value

BOOL

FALSE

Comment

B Tc2_Run

BOOL BOOL

FALSE FALSE

Task Tc2 execution status

2

A 'Tc2'

Task_IsActive
EN TaskName

A

Tc2_Run

Tc2_Run B

Task_IsActive

ST Variable
A B Tc2_Run

Data type BOOL BOOL BOOL

Initial value

Comment

FALSE

FALSE

FALSE

Task Tc2 execution status

IF (A=TRUE) THEN // Determine task status. Tc2_Run:=Task_IsActive('Tc2'); // Make variable B TRUE if Tc2 is running. IF (Tc2_Run=TRUE) THEN B := TRUE; END_IF;

END_IF;

NJ/NX-series Instructions Reference Manual (W502)

2-1499

2 Instruction Descriptions

Lock and Unlock

Lock: Unlock:

Starts an exclusive lock between tasks. Execution of any other task with a lock region with the same lock number is disabled.
Stops an exclusive lock between tasks.

Instruction Lock

Name Lock Tasks

FB/FUN FUN

Unlock

Unlock Tasks

FUN

Graphic expression

(@)Lock

EN

ENO

Index

Out

(@)Unlock

EN

ENO

Index

Out

ST expression Lock(Index);
Unlock(Index);

Variables

Name Index
Out

Meaning
Lock number
Return value

I/O Input
Output

Description Lock number
Always TRUE

Valid range

Unit

Depends on data type. ---

TRUE only

---

Default 0
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

Index

OK

Out

OK

Function
The Lock and Unlock instructions create lock regions. If a lock region in one task is being executed, the lock regions with the same lock number in other tasks are not executed. Specify the lock number with Index. The following figure shows a programming example. Both task T1 and task T2 contain a lock region with Index set to 1. If the Lock instruction in T2 is executed first, the lock region in T1 is not executed until the Unlock instruction is executed in T2.

2-1500

NJ/NX-series Instructions Reference Manual (W502)

Other Instructions

2 Instruction Descriptions

Execution priority High Task T1

Lock(1)

Unlock(1)

Low Task T2

Lock(1)

Unlock(1)

Normal execution Lock region Execution interrupted.

The priority of T1 is higher than the priority of T2, so T2 is interrupted

Execution of T2 is started again after T1 completes execution.

2

and execution of T1 is started.

Lock and Unlock

T2 executes a Lock instruction with the same Index value as the Lock instruction in T1. Therefore, execution of T1 is interrupted until the Unlock instruction is executed in T2.
When the Unlock instruction is executed in T2, execution of T1 is started again, and execution of T2 is interrupted.
Lock regions with different values for Index do not affect each other.

Additional Information
· The Lock and Unlock instructions are used when the same data is read/written from more than one task. They are used to prevent other tasks from reading/writing the data while a certain task is reading/writing the data.
· As long as the Index values are different, more than one pair of Lock and Unlock instructions can be placed in the same POU. The instruction pairs can also be nested.

Precautions for Correct Use
· Do not make lock regions any longer than necessary. If the lock region is too long, the task execution period may be exceeded.
· Always use the Lock and Unlock instructions together as a set in the same section of the same POU. · You can set a maximum of 16,777,215 lock regions at the same time.

NJ/NX-series Instructions Reference Manual (W502)

2-1501

2 Instruction Descriptions

· If Lock instructions are used in more than one task, a deadlock may occur if they are positioned poorly. A Task Execution Timeout Error will occur if there is a deadlock and a total stop is performed.

Execution priority High Task T1
Low Task T2

Normal execution Lock region Execution interrupted.

Lock(1) Lock(2)

Lock(2)

Lock(1)

Here, restarting the execution of both of the tasks must wait until the Unlock instruction is executed in the other task, i.e., they are deadlocked.

The priority of T1 is higher than the priority of T2, so T2 is interrupted and execution of T1 is started.
T1 executes a Lock instruction with an Index value of 2. Therefore, execution of T1 is interrupted until the Unlock instruction is executed in T2.
T2 executes a Lock instruction with an Index value of 1. Therefore, execution of T2 is interrupted until the Unlock instruction is executed in T1.
· An error occurs in the following case. The value of Out does not change. · There are more than 16,777,215 lock region at the same time.

Sample Programming

Here, program P1 in task T1 and program P2 in task T2 both access the same global variable GTable1. When the value of write request WriteReq changes to TRUE, P1 writes one record to record array GTable1.Record[] and increments GTable1.Index. When read request ReadReq changes to TRUE, P2 decrements GTable1.Index and reads one record from GTable1.Record[]. The Lock instruction is used so that reading and writing do not occur at the same time.

Program P1 Task T1

Record written.

GTabel1
Record 0 Record 1
: Record n

Record read.

Program P2 Task T2

Definition of Global Variable GTable

Data type

Variable USERTABLE Index Record

Data type STRUCT INT ARRAY[0..99] OF LREAL

Comment Record storage structure Index Record array

Global Variables

Variable

Data type

GTable1 USERTABLE

Initial value

Comment

(Index:=0,Record:=[100(0.0)]) Record storage structure

2-1502

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Other Instructions

Program P1

LD

Internal Variables

Variable
WriteReq InDat

Data type

Initial value

BOOL LREAL

FALSE 0.0

Comment
Write request Write data

External Variables

Variable GTable1

Data type USERTABLE

Comment Record storage structure

2

WriteReq USINT#1

Lock

EN

ENO

Index

Lock and Unlock

INT#100 GTable1.Index

>
EN In1 In2

InDat

MOVE

EN

ENO

In

Out

GTable1.Record[GTable1.index]

GTable1.Index

Inc
EN ENO InOut

USINT#1

Unlock

EN

ENO

Index

WriteReq R

ST
Internal Variables

Variable
WriteReq InDat

Data type

Initial value

BOOL LREAL

FALSE 0.0

Comment
Write request Write data

External Variables

Variable GTable1

Data type USERTABLE

Comment Record storage structure

// Detect write request. IF (WriteReq=TRUE) THEN

// Execute Lock instruction. Lock(USINT#1);

IF (INT#100>GTable1.Index) THEN

GTable1.Record[GTable1.Index]:=InDat;

GTable1.Index

:=GTable1.Index+INT#1;

END_IF;

// Execute Unlock instruction.

NJ/NX-series Instructions Reference Manual (W502)

2-1503

2 Instruction Descriptions
Unlock(USINT#1); WriteReq:=FALSE; END_IF;

2-1504

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Other Instructions

Program P2

LD

Internal Variables

Variable
ReadReq OutDat

Data type

Initial value

BOOL LREAL

FALSE 0.0

Comment
Read request Read data

External Variables

Variable GTable1

Data type USERTABLE

Comment Record storage structure

2

ReadReq USINT#1

Lock

EN

ENO

Index

Lock and Unlock

GTable1.Index INT#0

>
EN In1 In2

GTable1.Index

Dec
EN ENO InOut

GTable1.Record[GTable1.index]

MOVE

EN

ENO

In

Out

OutDat

USINT#1

Unlock

EN

ENO

Index

ReadReq R

ST
Internal Variables

Variable
ReadReq OutDat

Data type

Initial value

BOOL LREAL

FALSE 0.0

Comment
Read request Read data

External Variables

Variable GTable1

Data type USERTABLE

Comment Record storage structure

// Detect read request. IF (ReadReq=TRUE) THEN

// Execute Lock instruction. Lock(USINT#1);

IF (GTable1.Index>INT#0) THEN

GTable1.Index:=GTable1.Index-INT#1;

OutDat

:=GTable1.Record[GTable1.Index];

END_IF;

NJ/NX-series Instructions Reference Manual (W502)

2-1505

2 Instruction Descriptions
// Execute Unlock instruction. Unlock(USINT#1); ReadReq:=FALSE; END_IF;

2-1506

NJ/NX-series Instructions Reference Manual (W502)

Other Instructions

2 Instruction Descriptions

ActEventTask

The ActEventTask instruction activates an event task.

Instruction ActEventTask

Name
Activate Event Task

FB/ FUN
FUN

Graphic expression

(@)ActEventTask

EN

ENO

TaskName

Out

ST expression ActEventTask(TaskName);

2 Variables

ActEventTask

Name

Meaning

I/O

Description

Valid range

Unit

TaskName Task name Input

The name of the event task to activate

64 bytes max. --(63 single-byte alphanumeric characters plus the final NULL character)

Out

Return value Output TRUE: The instruction was exe- Depends on

---

cuted without any errors.

data type.

FALSE: The instruction was not executed or an error occurred.

Default ''
---

Bit strings

Integers

Times, durations, dates, and text strings

Real numbers

Boolean BOOL

STRING DT TOD
DATE TIME

LREAL REAL

LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE

TaskName

OK

Out

OK

Function
The ActEventTask instruction activates the event task with task name TaskName. The event task operates according to its task execution priority.
If an event task is started that has an execution priority that is lower than the execution priority of the task in which this instruction was executed, the event task is executed after completion of the execution of the task in which this instruction was executed. For example, assume that the execution priority of event task T2 is lower than the execution priority of periodic task T1. If the ActEventTask instruction is executed for T2 in T1, the execution of T1 is completed before T2 is executed.

Execution priority High Periodic task T1

Task period ActEventTask('T2')

Task period

Execution of task processing

Event Low task T2
T2 is executed after the execution of T1 is completed.

Time

NJ/NX-series Instructions Reference Manual (W502)

2-1507

2 Instruction Descriptions

If an event task is started that has an execution priority that is higher than the execution priority of the task in which this instruction was executed, the execution of the task in which this instruction was executed is paused and the event task is executed. For example, assume that the execution priority of periodic task T2 is lower than the execution priority of event task T1. If the ActEventTask instruction is executed for T1 in T2, the execution of T2 is paused to execute T1.

Execution priority High Event task T1

Execution of task processing
Pausing of task processing T1 is executed immediately after execution of the ActEventTask instruction.

Task period

Task period

Low Periodic task T2

ActEventTask('T1')

Time

The following figure shows a programming example. When the value of variable A is TRUE, event task `Te' is executed.

LD

A

@ActEventTask

EN 'Te' TaskName

ENO

ST IF A=TRUE THEN ActEventTask('Te'); END_IF;

Assume that the program with these instructions is assigned to periodic task T1 and that the execution priority of Te is lower than that of T1. If this instruction is executed in T1, the execution of T1 is completed before Te is executed.

Execution priority High Periodic task T1

Task period ActEventTask('Te')

Task period

Execution of task processing

Event Low task Te
Te is executed after the execution of T1 is completed.

Time

Related System-defined Variables

Name

Meaning

Data type

Description

_**_Active*1

Task Active Flag

BOOL

This variable indicates the execution status of the task.*2

TRUE: Execution processing is in progress.

FALSE: Stopped.

*1 The asterisks (**) are replaced with the task name.

*2 Refer to the NJ/NX-series CPU Unit Software User's Manual (Cat. No. W501) or NY-series Industrial Panel PC / Industrial Box PC Software User's Manual (Cat. No. W558) for details.

2-1508

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions

Other Instructions

Additional Information

Operation of _**_Active System-defined Variable

· When this instruction is executed, the _**_Active system-defined variable for the specified event task

will change to TRUE. It will change to FALSE when execution of the event task is completed. For

example, assume that the execution priority of event task T2 is lower than the execution priority of

periodic task T1. When the ActEventTask instruction is executed for T2 in T1, the system-defined

variable _T2_Active will change as shown in the following figure.

2

Execution of task processing

Pausing of task processing

ActEventTask

Task period Task period Task period

Execution priority High Periodic task T1 ActEventTask('T2')

Event Low task T2

_T2_Active

TRUE FALSE

Time

· The event task will not be executed even if this instruction is executed while the system-defined variable _**_Active for the event task is TRUE.

Execution of task processing Pausing of task processing

Task period Task period Task period

Execution priority High Periodic task T1

ActEventTask('T2')

ActEventTask('T2')

ActEventTask('T2')

Low

Event task T2

The event task is not executed.

_T2_Active

TRUE FALSE

Time

Executing an Event Task Only Once and Executing It Repeatedly
Use the following type of programming when you want to execute an event task only once when the value of a specified variable changes and when you want to execute an event task repeatedly as long as the variable has a specific value. Example 1: Executing an Event Task Only Once When the Value of a Specified Variable Changes If you use an upward differentiation instruction option for the instruction as shown below, event task `Task1' will be executed only once when the value of BOOL variable BoolVar changes from FALSE to TRUE.

NJ/NX-series Instructions Reference Manual (W502)

2-1509

2 Instruction Descriptions

BoolVar 'Task1'

@ActEventTask

EN TaskName

ENO

Execution priority High

Task period Task period

Task period Task period

Task processing is in progress. Task processing is paused. Task period

Periodic task T1
ActEventTask('Task1')

Event task T1
Low TRUE
BoolVar FALSE

Event task `Task1' is executed only once. Time

Example 2: Executing an Event Task Repeatedly as Long as a Variable Has a Specific Value If you do not use an upward differentiation instruction option for the instruction as shown below, event task `Task1' will be executed repeatedly as long as the value of BOOL variable BoolVar is TRUE. However, if this instruction is executed for Task1 while Task1 execution is in progress, it will be ignored.

BoolVar 'Task1'

ActEventTask

EN TaskName

ENO

Execution priority High

Task period Task period Task period

Task period

Task processing is in progress. Task processing is paused.
Task period

Periodic task T1
ActEventTask ('Task1')

Event task T1

Event task `Task1' is executed repeatedly as long as the value of BoolVar is TRUE. If execution of Task1 is already in progress, any ActEvent-
Task instruction that specifies Task1 will be ignored. Low

BoolVar

TRUE FALSE

Time

2-1510

NJ/NX-series Instructions Reference Manual (W502)

Other Instructions

2 Instruction Descriptions

Precautions for Correct Use
· To reduce the instruction execution time, execute this instruction only when it is necessary to execute the event task. If the instruction is executed while the system-defined variable _**_Active is TRUE, processing time is required even if the event task is not executed.
· An error will occur if the event task that is specified with TaskName does not exist. ENO will be FALSE.

Version Information

A CPU Unit with unit version 1.03 or later and Sysmac Studio version 1.04 or higher are required

to use this instruction.

2

ActEventTask

Sample Programming
 Example of Executing an Event Task When the Value of a Variable Meets the Specified Condition
Event task `Te' is executed only once when the value of variable RcdNum changes from less than the value of the variable MaxRcdNum to greater than or equal to the value of MaxRcdNum.

LD
Variable RcdNum MaxRcdNum

Data type INT INT

Initial value 0 100

RcdNum MaxRcdNum

>=
EN In1 In2

@ActEventTask

EN 'Te' TaskName

ENO

ST
Variable RcdNum MaxRcdNum met

Data type INT INT BOOL

Initial value 0 100 FALSE

IF (RcdNum>=MaxRcdNum) THEN IF (met=FALSE) THEN ActEventTask('Te'); met:=TRUE; END_IF;
ELSE met:=FALSE;
END_IF;

NJ/NX-series Instructions Reference Manual (W502)

2-1511

2 Instruction Descriptions

 Example of Confirming Completion of Event Task before Proceeding
In this example, event task `Task1' is executed each time the value of Trigger changes to TRUE. The Task_IsActive instruction is used to see when execution of Task 1 is completed.

LD
Name Trigger Operating Active

Data type BOOL BOOL BOOL

Initial value FALSE FALSE FALSE

Comment Execution condition Checking event task execution in progress Event task execution in progress

Trigger is received and ActEventTask is executed.

Trigger

ActEventTask

EN 'Task1' TaskName

ENO

Operating S

Task_IsActive is used to see if Task1 execution is in progress.

Operating

Task_IsActive

Active

EN 'Task1' TaskName

Active

Inline ST
1 // Processing after completion of execution 2 ;

Operating R

ST
Name Trigger LastTrigger Operating Active

Data type BOOL BOOL BOOL BOOL

Initial value FALSE FALSE FALSE FALSE

Comment Execution condition Value of Trigger from previous task period Checking event task execution in progress Event task execution in progress

// Start sequence when Trigger changes to TRUE.

IF ( (Trigger=TRUE) AND (LastTrigger=FALSE) ) THEN

ActEventTask('Task1');

// Execute event task 'Task1'.

Operating:=TRUE;

END_IF;

LastTrigger:=Trigger;

// See if Task1 execution is in progress. IF (Operating=TRUE) THEN
Active:=Task_IsActive('Task1');

IF (Active=FALSE) THEN Operating:=FALSE;
END_IF;

// Task1 execution completed.

END_IF;

2-1512

NJ/NX-series Instructions Reference Manual (W502)

Other Instructions

2 Instruction Descriptions

Get**Clk

The Get**Clk instruction outputs a clock pulse at the specified cycle.

Instruction

Name

FB/FUN

Graphic expression

ST expression

Get**Clk

Get Clock Pulse FUN Group

Get**Clk

Out:=Get**Clk();

EN

Out

"**" must be 100 us, 1 ms,

"**" must be 100 us, 1 ms, 10 ms, 20 ms, 10 ms, 20 ms, 100 ms, 1 s,

100 ms, 1 s, or 1 min.

or 1 min.

2

Variables

Get**Clk

Name Out

Meaning

I/O

Clock pulse Output

Description Clock pulse

Valid range

Unit

Depends on data type. ---

Default
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

Out

OK

Function

The Get**Clk instruction outputs a clock pulse at the specified cycle. The clock pulse period is 100 us, 1 ms, 10 ms, 20 ms, 100 ms, 1 s, or 1 min.
The name of the instruction is determined by the period of the clock pulse. For example, if the period of the clock pulse is 10 ms, the instruction name is Get10msClk.
The following example is for the Get1sClk instruction.

LD

ST

abc:=Get1sClk();

Get1sClk

abc

EN

Out=abc

TRUE FALSE

1 s

Precautions for Correct Use
· When the instruction is executed, the first value of Out may be TRUE or it may be FALSE. · If this instruction is used in a ladder diagram, the value of Out changes to FALSE if an error occurs in
the previous instruction on the rung.

NJ/NX-series Instructions Reference Manual (W502)

2-1513

2 Instruction Descriptions

Get**Cnt

The Get**Cnt instruction gets the values of free-running counters of the specified cycle.

Instruction Get**Cnt

Name
Get Incrementing Free-running Counter Group

FB/FUN FUN

Graphic expression

Get**Cnt

EN

ENO

Out

"**" must be 100 ns, 1us, 1 ms, 10 ms, 100 ms, or 1 s.

ST expression Out:=Get**Cnt();
"**" must be 100 ns, 1 us, 1 ms, 10 ms, 100 ms, or 1 s.

Variables

Name Out

Meaning

I/O

Count

Output

Description
Value of free-running counter

Valid range

Unit

Depends on data type. ---

Default
---

Bit strings

Integers

Times, durations, dates, and text strings

STRING DT TOD
DATE TIME Real LREAL numbers REAL LINT DINT INT SINT ULINT UDINT UINT USINT LWORD DWORD WORD BYTE Boolean BOOL

Out

OK

Function

The Get**Cnt instruction gets the values of free-running counters of the specified cycle. A free-running counter is a counter that is incremented at a specific period. Out is the current value of the count. The counter period is 100 ns, 1 us, 1 ms, 10 ms, 100 ms, or 1 s.
The name of the instruction is determined by counter period. For example, if the counter period is 10 ms, the instruction name is Get10msCnt.
The following example is for the Get1sCnt instruction.

LD

ST

abc:=Get1sCnt();

Get1sCnt

EN

ENO

abc

16
15 Out=abc 14

13

12

1 s

2-1514

NJ/NX-series Instructions Reference Manual (W502)

2 Instruction Descriptions
Precautions for Correct Use
· Free-running counters start counting as soon as the power supply is turned ON. When the count exceeds the valid range of ULINT data (18,446,744,073,709,551,615), it returns to 0 and counting continues.
· This instruction only gets the current value of the free-running counter. It does not reset the counter to 0.
· The first value of Out cannot be predicted. It will not necessarily start from 0.
2

Other Instructions

Get**Cnt

NJ/NX-series Instructions Reference Manual (W502)

2-1515

2 Instruction Descriptions

2-1516

NJ/NX-series Instructions Reference Manual (W502)

Appendices A
A-1 Error Codes That You Can Check with ErrorID . . . . . . . . . . . . . . . . . . . . . . A-2 A-2 Error Codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-22 A-3 Instructions You Cannot Use in Event Tasks . . . . . . . . . . . . . . . . . . . . . . A-23 A-4 Instructions Related to NX Message Communications Errors . . . . . . . . A-25 A-5 SDO Abort Codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-26 A-6 Version Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-27

NJ/NX-series Instructions Reference Manual (W502)

A-1

Appendices

A-1 Error Codes That You Can Check with ErrorID
Error codes are assigned to the errors that can occur when instructions are executed. When you use instructions that have an error code output variable (ErrorID), you can use the error codes to program error processing. The following table lists the instructions with ErrorID and the error codes that can occur for those instructions. Refer to the NJ/NX-series Troubleshooting Manual (Cat. No. W503) for the meanings of the error codes.
Additional Information You can check for errors for instructions that do not have ErrorID in the events in the event log.

Type
Analog Control Instructions

Instruction
PIDAT

PIDAT_HeatCool

System Control Instructions

AC_StepProgram
ResetPLCError ResetCJBError

ResetMCError ResetECError
GetNXUnitError

ResetUnit RestartNXUnit

A-2

Name
PID Control with Autotuning Heating/Cooling PID with Autotuning Step Program Reset PLC Controller Error Reset I/O Bus Error Reset Motion Control Error Reset EtherCAT Error Get NX Unit Error Status
Restart Unit
Restart NX Unit

Error code
16#0400
16#0401 16#0400
16#0401 16#0400
--16#0400
16#040D --16#041A
16#0400
16#041A
16#2C00 16#2C02 16#0400
16#040D 16#040F 16#0400
16#0419 16#2C00 16#2C01
16#2C02 16#2C05
16#2C06
16#2C07

Error name
Input Value Out of Range
Input Mismatch
Input Value Out of Range
Input Mismatch
Input Value Out of Range
---
Input Value Out of Range
Illegal Unit Specified
---
Multi-execution of Instructions
Input Value Out of Range
Multi-execution of Instructions
NX Message Error
NX Message Timeout
Input Value Out of Range
Illegal Unit Specified
Unit Restart Failed
Input Value Out of Range
Incorrect Data Type
NX Message Error
NX Message Resource Overflow
NX Message Timeout
NX Message EtherCAT Network Error
External Restart Already Executed for Specified NX Units
Unapplicable Unit Specified for Instruction

NJ/NX-series Instructions Reference Manual (W502)

Appendices

A-1 Error Codes That You Can Check with ErrorID

Type

Instruction

Name

Error code

Error name

System Control Instructions

NX_ChangeWriteMode

Change to NX Unit Write Mode

16#0400

Input Value Out of Range

16#0419

Incorrect Data Type

16#2C00

NX Message Error

16#2C01

NX Message Resource Overflow

16#2C02

NX Message Timeout

16#2C05

NX Message EtherCAT Network Error

16#2C07

Unapplicable Unit Specified for Instruction

NX_SaveParam

Save NX Unit Parameters

16#0400

Input Value Out of Range

16#0419

Incorrect Data Type

16#2C00 16#2C01

NX Message Error

NX Message Resource

A

Overflow

16#2C02

NX Message Timeout

16#0400

Input Value Out of Range

16#0419

Incorrect Data Type

16#2C00

NX Message Error

NX_ReadTotalPowerOnTime Read NX Unit Total Power ON Time

16#2C01

NX Message Resource Overflow

16#2C02

NX Message Timeout

16#2C08

Invalid Total Power ON Time Record

EtherCAT Communications Instructions

EC_CoESDOWrite

Write EtherCAT CoE SDO

16#0400 16#1800

Input Value Out of Range
EtherCAT Communications Error

16#1801

EtherCAT Slave Does Not Respond

16#1802

EtherCAT Timeout

16#1804

SDO Abort Error

16#1808

Communications Resource Overflow

EC_CoESDORead

Read EtherCAT CoE SDO

16#0400

Input Value Out of Range

16#1800

EtherCAT Communications Error

16#1801

EtherCAT Slave Does Not Respond

16#1802

EtherCAT Timeout

16#1803

Reception Buffer Overflow

16#1804

SDO Abort Error

16#1808

Communications Resource Overflow

EC_StartMon

Start EtherCAT Packet Monitor

16#1805

Saving Packet Monitor File

16#1807

Packet Monitoring Function in Operation

16#1808

Communications Resource Overflow

EC_StopMon

Stop EtherCAT Packet Monitor

16#1806

Packet Monitoring Function Not Started

16#1808

Communications Resource Overflow

NJ/NX-series Instructions Reference Manual (W502)

A-3

Appendices

Type
EtherCAT Communications Instructions

Instruction
EC_SaveMon

Name
Save EtherCAT Packets

EC_CopyMon

Transfer EtherCAT Packets

EC_DisconnectSlave

Disconnect EtherCAT Slave

EC_ConnectSlave

Connect EtherCAT Slave

EC_ChangeEnableSetting

Enable/Disable EtherCAT Slave

NX_WriteObj

Write NX Unit Object

Error code
16#1805 16#1807 16#1808 16#0400 16#1400 16#1401 16#1402 16#1403 16#1404 16#1405 16#140A 16#140B 16#140D 16#140E 16#1808 16#1800 16#1801 16#1808 16#1800 16#1801 16#1808 16#1800 16#1801 16#1808 16#0400 16#0419 16#041B 16#2C00 16#2C01 16#2C02 16#2C03

Error name
Saving Packet Monitor File
Packet Monitoring Function in Operation
Communications Resource Overflow
Input Value Out of Range
SD Memory Card Access Failure
SD Memory Card Write-protected
SD Memory Card Insufficient Capacity
File Does Not Exist
Too Many Files/ Directories
File Already in Use
Write Access Denied
Too Many Files Open
File or Directory Name Is Too Long
SD Memory Card Access Failed
Communications Resource Overflow
EtherCAT Communications Error
EtherCAT Slave Does Not Respond
Communications Resource Overflow
EtherCAT Communications Error
EtherCAT Slave Does Not Respond
Communications Resource Overflow
EtherCAT Communications Error
EtherCAT Slave Does Not Respond
Communications Resource Overflow
Input Value Out of Range
Incorrect Data Type
Data Capacity Exceeded
NX Message Error
NX Message Resource Overflow
NX Message Timeout
Incorrect NX Message Length

A-4

NJ/NX-series Instructions Reference Manual (W502)

A-1 Error Codes That You Can Check with ErrorID

Appendices

Type
EtherCAT Communications Instructions

Instruction
NX_ReadObj

Name
Read NX Unit Object

IO-Link Communications Instructions

IOL_ReadObj

Read IO-Link Device Object

IOL_WriteObj

Write IO-Link Device Object

Error code

Error name

16#0400

Input Value Out of Range

16#0410

Text String Format Error

16#0419

Incorrect Data Type

16#041C

Different Data Sizes

16#2C00

NX Message Error

16#2C01

NX Message Resource Overflow

16#2C02

NX Message Timeout

16#0400

Input Value Out of Range

16#0410

Text String Format Error

16#0419

Incorrect Data Type

16#041C 16#4800

Different Data Sizes

Device Error Received

A

16#4801

Specified Unit Does Not Exist

16#4802

Message Processing Limit Exceeded

16#4803

Specified Unit Status Error

16#4804

Too Many Simultaneous Instruction Executions

16#4805

Communications Timeout

16#4806

Invalid Mode

16#4807

I/O Power OFF Status

16#4808

Verification Error

16#0400

Input Value Out of Range

16#0419

Incorrect Data Type

16#041B

Data Capacity Exceeded

16#4800

Device Error Received

16#4801

Specified Unit Does Not Exist

16#4802

Message Processing Limit Exceeded

16#4803

Specified Unit Status Error

16#4804

Too Many Simultaneous Instruction Executions

16#4805

Communications Timeout

16#4806

Invalid Mode

16#4807

I/O Power OFF Status

16#4808

Verification Error

NJ/NX-series Instructions Reference Manual (W502)

A-5

Appendices

Type
EtherNet/IP Communications Instructions

Instruction
CIPOpen

CIPOpenWithDataSize

CIPRead CIPWrite

Name
Open CIP Class 3 Connection (Large_Forward_Open)

Error code
16#0400
16#1C00 16#1C01 16#1C03

16#1C04 16#1C05

16#2000

16#2004

Open CIP Class 3 Connection with Specified Data Size

16#0400
16#1C00 16#1C01 16#1C03

16#1C04 16#1C05

16#2000

16#2004

Read Variable Class 3 Explicit

16#0400

16#0407 16#0419 16#1C00 16#1C02

16#1C03

16#1C04 16#1C06

Write Variable Class 3 Explicit

16#0400

16#0406

16#0407 16#0419 16#1C00 16#1C02

16#1C03

16#1C04 16#1C06

Error name
Input Value Out of Range
Explicit Message Error
Incorrect Route Path
CIP Communications Resource Overflow
CIP Timeout
Class-3 Connection Not Established
Local IP Address Setting Error
Local IP Address Not Set
Input Value Out of Range
Explicit Message Error
Incorrect Route Path
CIP Communications Resource Overflow
CIP Timeout
Class-3 Connection Not Established
Local IP Address Setting Error
Local IP Address Not Set
Input Value Out of Range
Data Range Exceeded
Incorrect Data Type
Explicit Message Error
CIP Handle Out of Range
CIP Communications Resource Overflow
CIP Timeout
CIP Communications Data Size Exceeded
Input Value Out of Range
Illegal Data Position Specified
Data Range Exceeded
Incorrect Data Type
Explicit Message Error
CIP Handle Out of Range
CIP Communications Resource Overflow
CIP Timeout
CIP Communications Data Size Exceeded

A-6

NJ/NX-series Instructions Reference Manual (W502)

A-1 Error Codes That You Can Check with ErrorID

Appendices

Type
EtherNet/IP Communications Instructions

Instruction
CIPSend

Name
Send Explicit Message Class 3

CIPClose CIPUCMMRead

Close CIP Class 3 Connection Read Variable UCMM Explicit

CIPUCMMWrite

Write Variable UCMM Explicit

Error code

Error name

16#0400

Input Value Out of Range

16#0401

Input Mismatch

16#0406

Illegal Data Position Specified

16#0407

Data Range Exceeded

16#0419

Incorrect Data Type

16#1C00

Explicit Message Error

16#1C02

CIP Handle Out of Range

16#1C03

CIP Communications Resource Overflow

16#1C04

CIP Timeout

16#1C06

CIP Communications Data Size Exceeded

16#1C02

CIP Handle Out of

Range

A

16#1C03

CIP Communications Resource Overflow

16#0400

Input Value Out of Range

16#0407

Data Range Exceeded

16#0419

Incorrect Data Type

16#1C00

Explicit Message Error

16#1C01

Incorrect Route Path

16#1C03

CIP Communications Resource Overflow

16#1C04

CIP Timeout

16#2000

Local IP Address Setting Error

16#2004

Local IP Address Not Set

16#0400

Input Value Out of Range

16#0406

Illegal Data Position Specified

16#0419

Incorrect Data Type

16#1C00

Explicit Message Error

16#1C01

Incorrect Route Path

16#1C03

CIP Communications Resource Overflow

16#1C04

CIP Timeout

16#2000

Local IP Address Setting Error

16#2004

Local IP Address Not Set

NJ/NX-series Instructions Reference Manual (W502)

A-7

Appendices

Type
EtherNet/IP Communications Instructions

Instruction
CIPUCMMSend

Name
Send Explicit Message UCMM

SktUDPCreate

Create UDP Socket

SktUDPRcv

UDP Socket Receive

SktUDPSend

UDP Socket Send

Error code
16#0400
16#0401 16#0406
16#0407 16#0419 16#1C00 16#1C01 16#1C03
16#1C04 16#2000
16#2004
16#0400
16#2000
16#2001
16#2003 16#2004
16#2008
16#0400
16#0407 16#0419 16#2003 16#2006 16#2007
16#2008
16#0400
16#0406 16#0419 16#2002
16#2003 16#2007
16#2008

Error name
Input Value Out of Range
Input Mismatch
Illegal Data Position Specified
Data Range Exceeded
Incorrect Data Type
Explicit Message Error
Incorrect Route Path
CIP Communications Resource Overflow
CIP Timeout
Local IP Address Setting Error
Local IP Address Not Set
Input Value Out of Range
Local IP Address Setting Error
TCP/UDP Port Already in Use
Socket Status Error
Local IP Address Not Set
Socket Communications Resource Overflow
Input Value Out of Range
Data Range Exceeded
Incorrect Data Type
Socket Status Error
Socket Timeout
Socket Handle Out of Range
Socket Communications Resource Overflow
Input Value Out of Range
Data Range Exceeded
Incorrect Data Type
Address Resolution Failed
Socket Status Error
Socket Handle Out of Range
Socket Communications Resource Overflow

A-8

NJ/NX-series Instructions Reference Manual (W502)

Type
EtherNet/IP Communications Instructions

Instruction
SktTCPAccept

Name
Accept TCP Socket

SktTCPConnect

Connect TCP Socket

SktTCPRcv

TCP Socket Receive

SktTCPSend

TCP Socket Send

SktGetTCPStatus

Read TCP Socket Status

SktClose

Close TCP/UDP Socket

NJ/NX-series Instructions Reference Manual (W502)

Appendices

Error code

Error name

16#0400

Input Value Out of Range

16#2000

Local IP Address Setting Error

16#2001

TCP/UDP Port Already in Use

16#2002

Address Resolution Failed

16#2003

Socket Status Error

16#2004

Local IP Address Not Set

16#2006

Socket Timeout

16#2008

Socket Communications Resource Overflow

16#0400 16#2000

Input Value Out of

Range

A

Local IP Address Set-

ting Error

16#2001

TCP/UDP Port Already in Use

16#2002

Address Resolution Failed

16#2003

Socket Status Error

16#2004

Local IP Address Not Set

16#2006

Socket Timeout

16#2008

Socket Communications Resource Overflow

16#0400

Input Value Out of Range

16#0407

Data Range Exceeded

16#0419

Incorrect Data Type

16#2003

Socket Status Error

16#2006

Socket Timeout

16#2007

Socket Handle Out of Range

16#2008

Socket Communications Resource Overflow

16#0400

Input Value Out of Range

16#0406

Data Range Exceeded

16#0419

Incorrect Data Type

16#2003

Socket Status Error

16#2006

Socket Timeout

16#2007

Socket Handle Out of Range

16#2008

Socket Communications Resource Overflow

16#2003

Socket Status Error

16#2007

Socket Handle Out of Range

16#2008

Socket Communications Resource Overflow

16#2007

Socket Handle Out of Range

16#2008

Socket Communications Resource Overflow

A-9

A-1 Error Codes That You Can Check with ErrorID

Appendices

Type
EtherNet/IP Communications Instructions

Instruction
SktClearBuf

SktSetOption

ModbusTCPCmd

ModbusTCPRead

Name

Error code

Clear TCP/UDP Socket Receive Buffer 16#2007

16#2008

Set TCP Socket Option

16#0400
16#0419 16#2003 16#2007
16#2008

Send Modbus TCP General Command 16#0400
16#0406
16#0407 16#0C10
16#0C11
16#2003 16#2006 16#2007
16#2008

Send Modbus TCP Read Command

16#0400
16#0406
16#0407 16#0419 16#0C10
16#0C11
16#2003 16#2006 16#2007
16#2008

Error name
Socket Handle Out of Range
Socket Communications Resource Overflow
Input Value Out of Range
Incorrect Data Type
Socket Status Error
Socket Handle Out of Range
Socket Communications Resource Overflow
Input Value Out of Range
Illegal Data Position Specified
Data Range Exceeded
Exceptional Modbus Response
Invalid Modbus Response
Socket Status Error
Socket Timeout
Socket Handle Out of Range
Socket Communications Resource Overflow
Input Value Out of Range
Illegal Data Position Specified
Data Range Exceeded
Incorrect Data Type
Exceptional Modbus Response
Invalid Modbus Response
Socket Status Error
Socket Timeout
Socket Handle Out of Range
Socket Communications Resource Overflow

A-10

NJ/NX-series Instructions Reference Manual (W502)

A-1 Error Codes That You Can Check with ErrorID

Appendices

Type
EtherNet/IP Communications Instructions

Instruction
ModbusTCPWrite

ChangeIPAdr ChangeFTPAccount ChangeNTPServerAdr FTPGetFileList
FTPGetFile

Name

Error code

Error name

Send Modbus TCP Write Command

16#0400

Input Value Out of Range

16#0406

Illegal Data Position Specified

16#0419

Incorrect Data Type

16#0C10

Exceptional Modbus Response

16#0C11

Invalid Modbus Response

16#2003

Socket Status Error

16#2006

Socket Timeout

16#2007

Socket Handle Out of Range

Change IP Address

16#2008 16#0400

Socket Communica-

tions Resource Over-

flow

Input Value Out of

A

Range

16#040D

Illegal Unit Specified

16#2400

No Execution Right

Change FTP Account

16#0400

Input Value Out of Range

16#040D

Illegal Unit Specified

16#2400

No Execution Right

Change NTP Server Address

16#0400

Input Value Out of Range

16#040D

Illegal Unit Specified

16#2400

No Execution Right

Get FTP Server File List

16#0400

Input Value Out of Range

16#2403

FTP Client Execution Limit Exceeded

16#2405

Directory Does Not Exist (FTP)

16#2406

FTP Server Connection Error

16#2407

Destination FTP Server Execution Failure

Get File from FTP Server

16#0400

Input Value Out of Range

16#2403

FTP Client Execution Limit Exceeded

16#2404

File Number Limit Exceeded

16#2405

Directory Does Not Exist (FTP)

16#2406

FTP Server Connection Error

16#2407

Destination FTP Server Execution Failure

16#2408

SD Memory Card Access Failed for FTP

16#2409

Specified File Does Not Exist

16#240A

Specified File Is Write Protected

16#240C

Specified File Access Failed

NJ/NX-series Instructions Reference Manual (W502)

A-11

Appendices

Type
EtherNet/IP Communications Instructions

Instruction
FTPPutFile

Name
Put File onto FTP Server

FTPRemoveFile

Delete FTP Server File

FTPRemoveDir

Delete FTP Server Directory

Error code
16#0400 16#2403 16#2404 16#2405 16#2406 16#2407 16#2408 16#2409 16#240A 16#240B 16#240C 16#0400 16#2403 16#2404 16#2405 16#2406 16#2407 16#2409 16#0400 16#2405 16#2406 16#2407

Error name
Input Value Out of Range
FTP Client Execution Limit Exceeded
File Number Limit Exceeded
Directory Does Not Exist (FTP)
FTP Server Connection Error
Destination FTP Server Execution Failure
SD Memory Card Access Failed for FTP
Specified File Does Not Exist
Specified File Is Write Protected
Failed To Delete Specified File
Specified File Access Failed
Input Value Out of Range
FTP Client Execution Limit Exceeded
File Number Limit Exceeded
Directory Does Not Exist (FTP)
FTP Server Connection Error
Destination FTP Server Execution Failure
Specified File Does Not Exist
Input Value Out of Range
Directory Does Not Exist (FTP)
FTP Server Connection Error
Destination FTP Server Execution Failure

A-12

NJ/NX-series Instructions Reference Manual (W502)

A-1 Error Codes That You Can Check with ErrorID

Type
Serial Communications Instructions

Instruction
ExecPMCR

Name
Protocol Macro

SerialSend

SCU Send Serial

SerialRcv

SCU Receive Serial

Appendices

Error code

Error name

16#0400

Input Value Out of Range

16#0406

Illegal Data Position Specified

16#0407

Data Range Exceeded

16#040D

Illegal Unit Specified

16#0413

Undefined CJ-series Memory Address

16#0419

Incorrect Data Type

16#0C00

Illegal Serial Communications Mode

16#0800

FINS Error

16#0801

FINS Port Already in Use

16#0400 16#0406

Input Value Out of

Range

Illegal Data Position

A

Specified

16#040D

Illegal Unit Specified

16#0419

Incorrect Data Type

16#0C00

Illegal Serial Communications Mode

16#0800

FINS Error

16#0801

FINS Port Already in Use

16#0400

Input Value Out of Range

16#0407

Data Range Exceeded

16#040D

Illegal Unit Specified

16#0419

Incorrect Data Type

16#0C00

Illegal Serial Communications Mode

16#0800

FINS Error

16#0801

FINS Port Already in Use

NJ/NX-series Instructions Reference Manual (W502)

A-13

Appendices

Type
Serial Communications Instructions

Instruction
SerialRcvNoClear

SendCmd

NX_SerialSend

NX_SerialRcv

Name
SCU Receive Serial without Receive Buffer Clear
Send Command
Send No-protocol Data
Receive No-protocol Data

Error code
16#0400
16#0407 16#040D 16#0419 16#0C00
16#0800 16#0801
16#0400
16#0406
16#0407 16#0419 16#0800 16#0801
16#0400
16#0406
16#040D 16#0419 16#041D
16#0C04
16#0C0C
16#0C0D 16#0400
16#0406
16#0407 16#040D 16#0419 16#041D
16#0C03 16#0C04
16#0C05 16#0C06 16#0C07 16#0C0B
16#0C0C
16#0C0D

Error name
Input Value Out of Range
Data Range Exceeded
Illegal Unit Specified
Incorrect Data Type
Illegal Serial Communications Mode
FINS Error
FINS Port Already in Use
Input Value Out of Range
Illegal Data Position Specified
Data Range Exceeded
Incorrect Data Type
FINS Error
FINS Port Already in Use
Input Value Out of Range
Illegal Data Position Specified
Illegal Unit Specified
Incorrect Data Type
Too Many Simultaneous Instruction Executions
Multi-execution of Ports
Instruction Executed to Inapplicable Port
CIF Unit Initialized
Input Value Out of Range
Illegal Data Position Specified
Data Range Exceeded
Illegal Unit Specified
Incorrect Data Type
Too Many Simultaneous Instruction Executions
Full Reception Buffer
Multi-execution of Ports
Parity Error
Framing Error
Overrun Error
Serial Communications Timeout
Instruction Executed to Inapplicable Port
CIF Unit Initialized

A-14

NJ/NX-series Instructions Reference Manual (W502)

A-1 Error Codes That You Can Check with ErrorID

Appendices

Type
Serial Communications Instructions

Instruction
NX_ModbusRtuCmd

NX_ModbusRtuRead

Name

Error code

Error name

Send Modbus-RTU General Command 16#0400

Input Value Out of Range

16#0406

Illegal Data Position Specified

16#0407

Data Range Exceeded

16#040D

Illegal Unit Specified

16#0419

Incorrect Data Type

16#041D

Too Many Simultaneous Instruction Executions

16#0C03

Full Reception Buffer

16#0C04

Multi-execution of Ports

16#0C05

Parity Error

16#0C06

Framing Error

16#0C07

Overrun Error

16#0C08

CRC Mismatch

A

16#0C0B

Serial Communications Timeout

16#0C0C

Instruction Executed to Inapplicable Port

16#0C0D

CIF Unit Initialized

16#0C10

Exceptional Modbus Response

16#0C11

Invalid Modbus Response

Send Modbus-RTU Read Command

16#0400

Input Value Out of Range

16#0406

Illegal Data Position Specified

16#040D

Illegal Unit Specified

16#0419

Incorrect Data Type

16#041D

Too Many Simultaneous Instruction Executions

16#0C03

Full Reception Buffer

16#0C04

Multi-execution of Ports

16#0C05

Parity Error

16#0C06

Framing Error

16#0C07

Overrun Error

16#0C08

CRC Mismatch

16#0C0B

Serial Communications Timeout

16#0C0C

Instruction Executed to Inapplicable Port

16#0C0D

CIF Unit Initialized

16#0C10

Exceptional Modbus Response

16#0C11

Invalid Modbus Response

NJ/NX-series Instructions Reference Manual (W502)

A-15

Appendices

Type
Serial Communications Instructions

Instruction
NX_ModbusRtuWrite

NX_SerialSigCtl NX_SerialSigRead

Name
Send Modbus-RTU Write Command

Error code
16#0400
16#0406
16#040D 16#0419 16#041D

16#0C03 16#0C04
16#0C05 16#0C06 16#0C07 16#0C08 16#0C0B
16#0C0C
16#0C0D 16#0C10
16#0C11
Serial Control Signal ON/OFF Switching 16#0400
16#040D 16#0419 16#041D

Read Serial Control Signal

16#0C04
16#0C0B
16#0C0C
16#0C0D 16#0400
16#040D 16#0419 16#041D

16#0C04 16#0C0B 16#0C0C 16#0C0D

Error name
Input Value Out of Range
Illegal Data Position Specified
Illegal Unit Specified
Incorrect Data Type
Too Many Simultaneous Instruction Executions
Full Reception Buffer
Multi-execution of Ports
Parity Error
Framing Error
Overrun Error
CRC Mismatch
Serial Communications Timeout
Instruction Executed to Inapplicable Port
CIF Unit Initialized
Exceptional Modbus Response
Invalid Modbus Response
Input Value Out of Range
Illegal Unit Specified
Incorrect Data Type
Too Many Simultaneous Instruction Executions
Multi-execution of Ports
Serial Communications Timeout
Instruction Executed to Inapplicable Port
CIF Unit Initialized
Input Value Out of Range
Illegal Unit Specified
Incorrect Data Type
Exceeded Simultaneous Instruction Executed Resources
Multi-execution of Ports
Serial Communications Timeout
Instruction Executed to Inapplicable Port
CIF Unit Initialized

A-16

NJ/NX-series Instructions Reference Manual (W502)

A-1 Error Codes That You Can Check with ErrorID

Appendices

Type
Serial Communications Instructions

Instruction
NX_SerialStatusRead

Name
Read Serial Port Status

NX_SerialBufClear

Clear Buffer

NX_SerialStartMon

Start Serial Line Monitoring

NX_SerialStopMon

Stop Serial Line Monitoring

Error code

Error name

16#0400

Input Value Out of Range

16#040D

Illegal Unit Specified

16#0419

Incorrect Data Type

16#041D

Exceeded Simultaneous Instruction Executed Resources

16#0C04

Multi-execution of Ports

16#0C0B

Serial Communications Timeout

16#0C0C

Instruction Executed to Inapplicable Port

16#0C0D

CIF Unit Initialized

16#0400
16#040D 16#0419

Input Value Out of

Range

Illegal Unit Specified

A

Incorrect Data Type

16#041D

Too Many Simultaneous Instruction Executions

16#0C04

Multi-execution of Ports

16#0C0B

Serial Communications Timeout

16#0C0C

Instruction Executed to Inapplicable Port

16#0C0D

CIF Unit Initialized

16#0400

Input Value Out of Range

16#040D

Illegal Unit Specified

16#0419

Incorrect Data Type

16#041D

Too Many Simultaneous Instruction Executions

16#0C04

Multi-execution of Ports

16#0C0B

Serial Communications Timeout

16#0C0C

Instruction Executed to Inapplicable Port

16#0C0D

CIF Unit Initialized

16#0400

Input Value Out of Range

16#040D

Illegal Unit Specified

16#0419

Incorrect Data Type

16#041D

Too Many Simultaneous Instruction Executions

16#0C04

Multi-execution of Ports

16#0C0B

Serial Communications Timeout

16#0C0C

Instruction Executed to Inapplicable Port

16#0C0D

CIF Unit Initialized

NJ/NX-series Instructions Reference Manual (W502)

A-17

Appendices

Type
SD Memory Card Instructions

Instruction
FileWriteVar

FileReadVar
FileOpen FileOpen FileClose FileSeek
A-18

Name
Write Variable to File
Read Variable from File Open File Open File Close File Seek File

Error code
16#0400
16#1400
16#1401
16#1402
16#1403 16#1404
16#1405 16#1409
16#140A 16#140B 16#140D
16#140E
16#0400
16#1400
16#1403 16#1405 16#140B 16#140D
16#140E
16#0400
16#1400
16#1401
16#1403 16#1404
16#1405 16#140A 16#140B 16#140D
16#140E
16#1400
16#1403 16#1405 16#140E
16#0400
16#1400
16#1403 16#1405 16#1407 16#140E

Error name
Input Value Out of Range
SD Memory Card Access Failure
SD Memory Card Write-protected
SD Memory Card Insufficient Capacity
File Does Not Exist
Too Many Files/ Directories
File Already in Use
That File Name Already Exists
Write Access Denied
Too Many Files Open
File or Directory Name Is Too Long
SD Memory Card Access Failed
Input Value Out of Range
SD Memory Card Access Failure
File Does Not Exist
File Already in Use
Too Many Files Open
File or Directory Name Is Too Long
SD Memory Card Access Failed
Input Value Out of Range
SD Memory Card Access Failure
SD Memory Card Write-protected
File Does Not Exist
Too Many Files/ Directories
File Already in Use
Write Access Denied
Too Many Files Open
File or Directory Name Is Too Long
SD Memory Card Access Failed
SD Memory Card Access Failure
File Does Not Exist
File Already in Use
SD Memory Card Access Failed
Input Value Out of Range
SD Memory Card Access Failure
File Does Not Exist
File Already in Use
Offset Out of Range
SD Memory Card Access Failed

NJ/NX-series Instructions Reference Manual (W502)

Type
SD Memory Card Instructions

Instruction
FileRead

Read File

Name

FileWrite

Write File

FileGets FilePuts

Get Text String Put Text String

FilePuts FileCopy

Put Text String Copy File

NJ/NX-series Instructions Reference Manual (W502)

Appendices

Error code

Error name

16#0406

Illegal Data Position Specified

16#0419

Incorrect Data Type

16#1400

SD Memory Card Access Failure

16#1403

File Does Not Exist

16#1405

File Already in Use

16#1406

Open Mode Mismatch

16#140E

SD Memory Card Access Failed

16#0406

Illegal Data Position Specified

16#0419

Incorrect Data Type

16#1400

SD Memory Card Access Failure

16#1401

SD Memory Card

Write-protected

A

16#1402

SD Memory Card Insufficient Capacity

16#1403

File Does Not Exist

16#1405

File Already in Use

16#1406

Open Mode Mismatch

16#140E

SD Memory Card Access Failed

16#1400

SD Memory Card Access Failure

16#1403

File Does Not Exist

16#1405

File Already in Use

16#1406

Open Mode Mismatch

16#140E

SD Memory Card Access Failed

16#1400

SD Memory Card Access Failure

16#1401

SD Memory Card Write-protected

16#1402

SD Memory Card Insufficient Capacity

16#1403

File Does Not Exist

16#1405

File Already in Use

16#1406

Open Mode Mismatch

16#140E

SD Memory Card Access Failed

16#0400

Input Value Out of Range

16#1400

SD Memory Card Access Failure

16#1401

SD Memory Card Write-protected

16#1402

SD Memory Card Insufficient Capacity

16#1403

File Does Not Exist

16#1404

Too Many Files/ Directories

16#1405

File Already in Use

16#1409

That File Name Already Exists

16#140A

Write Access Denied

16#140B

Too Many Files Open

16#140D

File or Directory Name Is Too Long

16#140E

SD Memory Card Access Failed

A-19

A-1 Error Codes That You Can Check with ErrorID

Appendices

Type
SD Memory Card Instructions

Instruction
FileRemove

Delete File

Name

FileRename

Change File Name

DirCreate

Create Directory

Error code
16#0400
16#1400
16#1401
16#1403 16#1405 16#140A 16#140B 16#140D
16#140E
16#0400
16#1400
16#1401
16#1403 16#1404
16#1405 16#1408 16#1409
16#140A 16#140B 16#140D
16#140E
16#0400
16#1400
16#1401
16#1402
16#1404
16#1405 16#1409
16#140B 16#140C
16#140D
16#140E

Error name
Input Value Out of Range
SD Memory Card Access Failure
SD Memory Card Write-protected
File Does Not Exist
File Already in Use
Write Access Denied
Too Many Files Open
File or Directory Name Is Too Long
SD Memory Card Access Failed
Input Value Out of Range
SD Memory Card Access Failure
SD Memory Card Write-protected
File Does Not Exist
Too Many Files/ Directories
File Already in Use
Directory Not Empty
That File Name Already Exists
Write Access Denied
Too Many Files Open
File or Directory Name Is Too Long
SD Memory Card Access Failed
Input Value Out of Range
SD Memory Card Access Failure
SD Memory Card Write-protected
SD Memory Card Insufficient Capacity
Too Many Files/ Directories
File Already in Use
That File Name Already Exists
Too Many Files Open
Directory Does Not Exist
File or Directory Name Is Too Long
SD Memory Card Access Failed

A-20

NJ/NX-series Instructions Reference Manual (W502)

A-1 Error Codes That You Can Check with ErrorID

Type
SD Memory Card Instructions

Instruction
DirRemove

Name
Delete Directory

BackupToMemoryCard

SD Memory Card Backup

Appendices

Error code

Error name

16#0400

Input Value Out of Range

16#1400

SD Memory Card Access Failure

16#1401

SD Memory Card Write-protected

16#1405

File Already in Use

16#1408

Directory Not Empty

16#140A

Write Access Denied

16#140B

Too Many Files Open

16#140C

Directory Does Not Exist

16#140D

File or Directory Name Is Too Long

16#140E

SD Memory Card

Access Failed

16#0400

Input Value Out of

A

Range

16#1400

SD Memory Card Access Failure

16#1401

SD Memory Card Write-protected

16#1402

SD Memory Card Insufficient Capacity

16#1404

Too Many Files/ Directories

16#1409

That File Name Already Exists

16#140C

Directory Does Not Exist

16#140E

SD Memory Card Access Failed

16#140F

Backup Operation Already in Progress

16#1410

Cannot Execute Backup

16#1411

Unit/Slave Backup Failed

NJ/NX-series Instructions Reference Manual (W502)

A-21

Appendices
A-2 Error Codes
The lower four digits of the event code give the error code for the instruction. For descriptions of the error codes, refer to the descriptions of the corresponding event codes. For example, if the error code of the instruction is 16#0400, refer to the description of the event with event code 54010400 hex. Refer to the NJ/NX-series Troubleshooting Manual (Cat. No. W503-E1-19 or later) for event codes.
Version Information Event codes for instructions are supported by CPU Units with unit version 1.02 or later.

A-22

NJ/NX-series Instructions Reference Manual (W502)

Appendices

A-3 Instructions You Cannot Use in Event Tasks

A-3 Instructions You Cannot Use in Event Tasks

An event task is executed only once when the specified execution condition is met. They are not executed repeatedly each task period. Therefore, programs that contain instructions that are executed over more than one task period cannot be assigned to event tasks.

The instructions in the following table are executed over more than one task. Do not use these instructions in programs that are assigned to an event task. If you do, a building error will occur.

Type

Instruction

Name

Page

Stack and Table Instructions

RecSort

Record Sort

2-524

Analog Control Instructions

PIDAT PIDAT_HeatCool

PID Control with Autotuning Heating/Cooling PID with Autotuning

2-672

2-697

A

AC_StepProgram

Step Program

2-779

System Control Instructions

ResetPLCError ResetCJBError

Reset PLC Controller Error Reset I/O Bus Error

2-825 2-830

ResetMCError

Reset Motion Control Error

2-836

ResetECError

Reset EtherCAT Error

2-843

ResetNXBError

Reset NX Bus Error

2-848

GetNXUnitError

Get NX Unit Error Status

2-852

ResetUnit

Restart Unit

2-862

RestartNXUnit

Restart NX Unit

2-868

NX_ChangeWriteMode Change to NX Unit Write Mode

2-874

NX_SaveParam

Save NX Unit Parameters

2-879

NX_ReadTotalPower OnTime

Read NX Unit Total Power ON Time

2-885

EtherCAT Communications Instructions

EC_CoESDOWrite EC_CoESDORead EC_StartMon

Write EtherCAT CoE SDO Read EtherCAT CoE SDO Start EtherCAT Packet Monitor

2-934 2-937 2-942

EC_StopMon

Stop EtherCAT Packet Monitor

2-948

EC_SaveMon

Save EtherCAT Packets

2-950

EC_CopyMon

Transfer EtherCAT Packets

2-952

EC_DisconnectSlave

Disconnect EtherCAT Slave

2-954

EC_ConnectSlave

Connect EtherCAT Slave

2-961

EC_ChangeEnableSetting Enable/Disable EtherCAT Slave

2-963

NX_WriteObj

Write NX Unit Object

2-980

NX_ReadObj

Read NX Unit Object

2-995

IO-Link Communications Instructions

IOL_ReadObj IOL_WriteObj

Read IO-Link Device Object Write IO-Link Device Object

2-1006 2-1015

EtherNet/IP Communications

CIPOpen

Open CIP Class 3 Connection (Large_Forward_Open)

2-1026

Instructions

CIPOpenWithDataSize

Open CIP Class 3 Connection with Specified Data Size

2-1035

CIPRead

Read Variable Class 3 Explicit

2-1039

CIPWrite

Write Variable Class 3 Explicit

2-1045

CIPSend

Send Explicit Message Class 3

2-1051

CIPClose

Close CIP Class 3 Connection

2-1056

CIPUCMMRead

Read Variable UCMM Explicit

2-1059

CIPUCMMWrite

Write Variable UCMM Explicit

2-1064

CIPUCMMSend

Send Explicit Message UCMM

2-1071

NJ/NX-series Instructions Reference Manual (W502)

A-23

Appendices

Type EtherNet/IP Communications Instructions
Serial Communications Instructions
SD Memory Card Instructions
Time Stamp Instructions

Instruction SktUDPCreate SktUDPRcv SktUDPSend SktTCPAccept SktTCPConnect SktTCPRcv SktTCPSend SktGetTCPStatus SktClose SktClearBuf SktSetOption ChangeIPAdr ChangeFTPAccount ChangeNTPServerAdr FTPGetFileList FTPGetFile FTPPutFile FTPRemoveFile FTPRemoveDir ExecPMCR SerialSend SerialRcv SerialRcvNoClear SendCmd NX_SerialSend NX_SerialRcv NX_ModbusRtuCmd NX_ModbusRtuRead NX_ModbusRtuWrite NX_SerialSigCtl NX_SerialSigRead NX_SerialStatusRead NX_SerialBufClear NX_SerialStartMon NX_SerialStopMon FileWriteVar FileReadVar FileOpen FileClose FileSeek FileRead FileWrite FileGets FilePuts FileCopy FileRemove FileRename DirCreate DirRemove BackupToMemoryCard NX_DOutTimeStamp NX_AryDOutTimeStamp

Name Create UDP Socket UDP Socket Receive UDP Socket Send Accept TCP Socket Connect TCP Socket TCP Socket Receive TCP Socket Send Read TCP Socket Status Close TCP/UDP Socket Clear TCP/UDP Socket Receive Buffer Set TCP Socket Option Change IP Address Change FTP Account Change NTP Server Address Get FTP Server File List Get File from FTP Server Put File onto FTP Server Delete FTP Server File Delete FTP Server Directory Protocol Macro SCU Send Serial SCU Receive Serial SCU Receive Serial without Receive Buffer Clear Send Command Send No-protocol Data Receive No-protocol Data Send Modbus RTU General Command Send Modbus RTU Read Command Send Modbus RTU Write Command Serial Control Signal ON/OFF Switching Read Serial Control Signal Read Serial Port Status Clear Buffer Start Serial Line Monitoring Stop Serial Line Monitoring Write Variable to File Read Variable from File Open File Close File Seek File Read File Write File Get Text String Put Text String Copy File Delete File Change File Name Create Directory Delete Directory SD Memory Card Backup Write Digital Output with Specified Time Stamp Write Digital Output Array with Specified Time Stamp

Page 2-1081 2-1089 2-1092 2-1095 2-1098 2-1107 2-1110 2-1113 2-1116 2-1119 2-1122 2-1151 2-1159 2-1163 2-1167 2-1184 2-1193 2-1204 2-1214 2-1220 2-1233 2-1244 2-1244 2-1259 2-1272 2-1285 2-1299 2-1310 2-1322 2-1334 2-1343 2-1348 2-1353 2-1363 2-1368 2-1374 2-1379 2-1384 2-1388 2-1391 2-1395 2-1403 2-1411 2-1419 2-1428 2-1437 2-1442 2-1447 2-1450 2-1453 2-1470 2-1476

A-24

NJ/NX-series Instructions Reference Manual (W502)

A-4 Instructions Related to NX Message Communications Errors

Appendices

A-4 Instructions Related to NX Message Communications Errors

If too many of the following instructions are executed at the same time, an NX Message Communications Error may occur. If an NX Message Communications Error occurs, reduce the number of the following instructions that are executed. The conditions for an NX Message Communications Error depends on factors such as the communications traffic.

Classification System Control Instructions
EtherCAT Communications Instructions
IO-Link Communications Instructions

Instruction RestartNXUnit NX_ChangeWriteMode NX_SaveParam NX_ReadTotalPowerOnTime EC_CoESDOWrite EC_CoESDORead EC_StartMon EC_StopMon EC_SaveMon EC_CopyMon EC_DisconnectSlave EC_ConnectSlave EC_ChangeEnableSetting NX_WriteObj NX_ReadObj IOL_ReadObj IOL_WriteObj

Name Restart NX Unit Change to NX Unit Write Mode Save NX Unit Parameters Read NX Unit Total Power ON Time
Write EtherCAT CoE SDO Read EtherCAT CoE SDO Start EtherCAT Packet Monitor Stop EtherCAT Packet Monitor Save EtherCAT Packets Transfer EtherCAT Packets Disconnect EtherCAT Slave Connect EtherCAT Slave Enable/Disable EtherCAT Slave
Write NX Unit Object Read NX Unit Object Read IO-Link Device Object Write IO-Link Device Object

Page 2-868 2-874 2-879 2-885
A
2-934 2-937 2-942 2-948 2-950 2-952 2-954 2-961 2-963
2-980 2-995 2-1006 2-1015

Version Information
A CPU Unit with unit version 1.05 or later and Sysmac Studio version 1.06 or higher are required for an NX Message Communications Error to occur.

NJ/NX-series Instructions Reference Manual (W502)

A-25

Appendices

A-5 SDO Abort Codes

As reference information, the following table lists the SDO abort codes for EtherCAT communications. The abort codes that are used in actual communications are specified by the slaves. Refer to the slave manuals when programming communications.

Value 16#05030000 16#05040000 16#05040001 16#05040005 16#06010000 16#06010001 16#06010002 16#06020000 16#06040041 16#06040042
16#06040043 16#06040047 16#06060000 16#06070010 16#06070012 16#06070013 16#06090011 16#06090030 16#06090031 16#06090032 16#06090036 16#08000000 16#08000020 16#08000021 16#08000022
16#08000023

Meaning Toggle bit not changed SDO protocol timeout Client/Server command specifier not valid or unknown Out of memory Unsupported access to an object Attempt to read to a write only object Attempt to write to a read only object The object does not exist in the object directory The object cannot be mapped into the PDO The number and length of the objects to be mapped would exceed the PDO length General parameter incompatibility reason General internal incompatibility in the device Access failed due to a hardware error Data type does not match, length of service parameter does not match Data type does not match, length of service parameter too high Data type does not match, length of service parameter too low Subindex does not exist Value range of parameter exceeded (only for write access) Value of parameter written too high Value of parameter written too low Maximum value is less than minimum value General error Data cannot be transferred or stored to the application Data cannot be transferred or stored to the application because of local control* Data cannot be transferred or stored to the application because of the present device state Object dictionary dynamic generation failed or no object dictionary is present

* This is internal status that is unique to the slave.

Source:

EtherCAT Specification Part 6 Application Layer Protocol Specification.

Document No.: ETG.1000.6 S (R) V1.0.2

A-26

NJ/NX-series Instructions Reference Manual (W502)

Appendices

A-6 Version Information

Instructions with Specifications Changes and New Instructions for Version Upgrades

A-6 Version Information

This appendix lists the instructions for which specifications were changed and instructions that were added for different unit versions of the CPU Units and for different versions of the Sysmac Studio.
It also describes the actions to take if the following error message is displayed for Sysmac Studio version 1.02: The instruction may cause unintended operations.

Instructions with Specifications Changes and New Instructions for Version Upgrades

The instructions that are supported and their specifications depend on the unit version of the CPU Unit

and the version of the Sysmac Studio. These are given in the following table.

If a version is given for both the CPU Unit and Sysmac Studio, both versions are required.

A

Type

Instruction

ST Statement Instructions Sequence Input Instructions Sequence Output Instructions
Comparison Instructions

FOR
R_TRIG
RS
SR EQ,= NE,<> LT,< LE,<=

GT,> GE,>=

Counter Instructions

ZoneCmp CTD CTD_**

CTU CTU_**

CTUD CTUD_**

Math Instructions
Data Type Conversion Instructions

EXPT (**) EnumToNum
NumToEnum

Selection Instructions

SEL MUX AryMax AryMin ArySerach

Name Repeat Start

New/Changed Changed

Versions

CPU Unit

Sysmac Studio

---

Ver. 1.08

Up Trigger

Changed

Ver. 1.02 ---

Reset-Priority Keep Set-Priority Keep Equal Not Equal Less Than Less Than Or Equal Greater Than Greater Than Or Equal Zone Comparison Down-counter Down-counter Group Up-counter Up-counter Group Up-down Counter Up-down Counter Group Exponentiation Enumeration-toInteger Integer-toEnumeration Binary Selection Multiplexer Array Maximum Array Minimum Array Search

Changed
Changed Changed Changed Changed Changed
Changed Changed
Changed Changed Changed
Changed Changed
Changed Changed
Changed New
New
Changed Changed Changed Changed Changed

---

Ver. 1.03

---

Ver. 1.03

---

Ver. 1.02

---

Ver. 1.02

---

Ver. 1.02

---

Ver. 1.02

---

Ver. 1.02

---

Ver. 1.02

Ver. 1.01 -----

Ver. 1.02 Ver. 1.03 Ver. 1.03

---

Ver. 1.03

---

Ver. 1.03

---

Ver. 1.03

---

Ver. 1.03

Ver. 1.16 Ver. 1.02

Ver. 1.20 Ver. 1.03

Ver. 1.02 Ver. 1.03

Ver. 1.02 Ver. 1.02 Ver. 1.01 Ver. 1.01 Ver. 1.01

Ver. 1.03 Ver. 1.03 Ver. 1.02 Ver. 1.02 Ver. 1.02

Page
2-42
2-44
2-50
2-53 2-92 2-94 2-97 2-97
2-97 2-97
2-109 2-146 2-148
2-150 2-152
2-155 2-159
2-211 2-312
2-314
2-332 2-334 2-347 2-347 2-350

NJ/NX-series Instructions Reference Manual (W502)

A-27

Appendices

Type

Instruction

Name

New/Changed

Shift Instructions Conversion Instructions
Stack and Table Instructions
Text String Instructions Time and Time of Day Instructions

SHL SHR ROL ROR
UTF8ToSJIS
SJISToUTF8
PWLApproxNo LineChk
PWLLineChk
PackWord PackDword LOWER_BOUND UPPER_BOU ND RecSearch RecRange Search RecSort RecNum
RecMax
RecMin
AddDelimiter
SubDelimiter
TruncTime TruncDt
TruncTod

N-bit Left Shift
N-bit Right Shift
Rotate N-bits Left
Rotate N-bits Right
UTF-8 to SJIS Character Code Conversion
SJIS to UTF-8 Character Code Conversion
Broken Line Approximation without Broken Line Data Check
Broken Line Data Check
2-byte Join
4-byte Join
Get First Number of Array
Get Last Number of Array
Record Search
Range Record Search
Record Sort
Get Number of Records
Maximum Record Search
Minimum Record Search
Put Text Strings with Delimiters
Get Text Strings Minus Delimiters
Truncate Time
Truncate Date and Time
Truncate Time of Day

Changed Changed Changed Changed New
New
New
New New New New New Changed Changed Changed Changed
Changed Changed New New New New New

Versions

CPU Unit

Sysmac Studio

Ver. 1.02 Ver. 1.03

Ver. 1.02 Ver. 1.03

Ver. 1.02 Ver. 1.03

Ver. 1.02 Ver. 1.03

Ver. 1.01 Ver. 1.02

Ver. 1.01 Ver. 1.02

Ver. 1.03 Ver. 1.04

Ver. 1.03 Ver. 1.04

Ver. 1.12 Ver. 1.12 Ver. 1.18

Ver. 1.16 Ver. 1.16 Ver. 1.22

Ver. 1.18 Ver. 1.22

Ver. 1.01 Ver. 1.01

Ver. 1.02 Ver. 1.02

Ver. 1.01 Ver. 1.01 Ver. 1.02 Ver. 1.01

Ver. 1.02 Ver. 1.02 Ver. 1.03 Ver. 1.02

Ver. 1.01 Ver. 1.02

Ver. 1.02 Ver. 1.03

Ver. 1.02 Ver. 1.03

Ver. 1.01 Ver. 1.01

Ver. 1.02 Ver. 1.02

Ver. 1.01 Ver. 1.02

Page 2-396 2-396 2-400 2-400 2-422
2-424
2-426
2-432 2-487 2-489 2-491 2-491 2-514 2-519 2-524 2-530
2-532 2-532 2-577 2-588 2-658 2-662 2-666

A-28

NJ/NX-series Instructions Reference Manual (W502)

A-6 Version Information

Instructions with Specifications Changes and New Instructions for Version Upgrades

Appendices

Versions

Type

Instruction

Name

New/Changed

CPU Unit

Sysmac Studio

Page

Analog Control Instructions

PIDAT_Heat Cool

Heating/Cooling New PID with Autotuning

Ver. 1.08 Ver. 1.09 2-697

TimeProportionalOut

Time-proportional Output

New

Ver. 1.02 Ver. 1.03 2-735

LimitAlarm_**

Upper/Lower Limit Alarm Group

New

Ver. 1.02 Ver. 1.03 2-752

LimitAlarmDv_**

Upper/Lower Deviation Alarm Group

New

Ver. 1.02 Ver. 1.03 2-756

LimitAlarmDvStbySeq_**

Upper/Lower Deviation Alarm with Standby Sequence Group

New

Ver. 1.02 ---

2-761
A

ScaleTrans

Scale Transformation

New

Ver. 1.05 Ver. 1.06 2-776

Analog Control Instructions

AC_StepPro- Step Program gram

New

Ver. 1.06 Ver. 1.07 2-779

System Control ResetMCError Reset Motion

Instructions

Control Error

Changed

Ver. 1.02 Ver. 1.10

Ver. 1.03 Ver. 1.12

2-836

GetECError

Get EtherCAT Error Status

Changed

Ver. 1.02 Ver. 1.03 2-845

ResetNXBEr- Reset NX Bus

ror

Error

New

Ver. 1.13 Ver. 1.17 2-848

GetNXBError Get NX Bus Error New Status

Ver. 1.13 Ver. 1.17 2-850

GetNXUnitEr- Get NX Unit Error New

ror

Status

Ver. 1.13 Ver. 1.17 2-852

RestartNXUnit Restart NX Unit New

Ver. 1.05 Ver. 1.06 2-868

Changed

Ver. 1.07 Ver. 1.08

NX_Change WriteMode

Change to NX

New

Unit Write Mode

Ver. 1.05 Ver. 1.06 2-874

NX_SaveParam

Save NX Unit Parameters

New

Ver. 1.05 Ver. 1.06 2-879

NX_ReadTotal- Read NX Unit PowerOnTime Total Power ON
Time

New

Ver. 1.10 Ver. 1.12 2-885

PLC_ReadTotalPowerOnTime

Read PLC Total Power ON Time

New

Ver. 1.13 Ver. 1.17 2-893

Program Control PrgStart

Instructions

PrgStop

Enable Program New Disable Program New

Ver. 1.08 Ver. 1.08

Ver. 1.09 Ver. 1.09

2-898 2-907

PrgStatus

Read Program Status

New

Ver. 1.08 Ver. 1.09 2-927

NJ/NX-series Instructions Reference Manual (W502)

A-29

Appendices

Type

Instruction

Name

EtherCAT Communications Instructions

EC_StartMon EC_StopMon

EC_SaveMon

EC_CopyMon

EC_ChangeEnableSetting
NX_WriteObj

NX_ReadObj

IO-Link Commu- IOL_ReadObj

nications Instruc-

tions

IOL_WriteObj

Start EtherCAT Packet Monitor Stop EtherCAT Packet Monitor Save EtherCAT Packets Transfer EtherCAT Packets Enable/Disable EtherCAT Slave
Write NX Unit Object Read NX Unit Object Read IO-Link Device Object Write IO-Link Device Object

New/Changed Changed

Versions

CPU Unit

Sysmac Studio

Ver. 1.10 Ver. 1.12*1

Page 2-942

Changed

Ver. 1.10 Ver. 1.12*1 2-948

Changed

Ver. 1.10 Ver. 1.12*1 2-950

Changed

Ver. 1.10 Ver. 1.12*1 2-952

New

Ver. 1.04 Ver. 1.05 2-963

New New New New

Ver. 1.05 Ver. 1.06 2-980 Ver. 1.05 Ver. 1.06 2-995 Ver. 1.12 Ver. 1.16 2-1006 Ver. 1.12 Ver. 1.16 2-1015

A-30

NJ/NX-series Instructions Reference Manual (W502)

A-6 Version Information

Instructions with Specifications Changes and New Instructions for Version Upgrades

Appendices

Versions

Type

Instruction

Name

New/Changed

CPU Unit

Sysmac Studio

Page

EtherNet/IP Communications Instructions

CIPOpenWithDataSize

Open CIP Class 3 Connection with Specified Data Size

New

Ver. 1.06 Ver. 1.07 2-1035

CIPSend

Send Explicit

Changed

Message Class 3

Ver. 1.11 Ver. 1.15 2-1051

CIPUCMMSend

Send Explicit

Changed

Message UCMM

Ver. 1.11 Ver. 1.15 2-1071

SktUDPCreate Create UDP Socket

Changed Changed

Ver. 1.03 Ver. 1.10

--Ver. 1.13

2-1081

SktTCPAccept Accept TCP Socket

Changed

Ver. 1.03 ---

2-1095

SktTCPConnect

Connect TCP Socket

Changed

Ver. 1.03 ---

2-1098
A

SktSetOption Set TCP Socket New Option

Ver. 1.12*2 Ver. 1.16*2 2-1122

ModbusTCPCmd

Send Modbus TCP General Command

New

Ver. 1.30 Ver. 1.23 2-1127

ModbusTCPRead

Send Modbus TCP Read Command

New

Ver. 1.30 Ver. 1.23 2-1135

ModbusTCPWrite

Send Modbus TCP Write Command

New

Ver. 1.30 Ver. 1.23 2-1143

ChangeIPAdr Change IP Address

New Changed

Ver. 1.02 Ver. 1.10

Ver. 1.03 Ver. 1.13

2-1151

ChangeFTPAc Change FTP

count

Account

New Changed

Ver. 1.02 Ver. 1.10

Ver. 1.03 Ver. 1.13

2-1159

ChangeNTPSe Change NTP

rverAdr

Server Address

New Changed

Ver. 1.02 Ver. 1.10

Ver. 1.03 Ver. 1.13

2-1163

FTPGetFileList Get FTP Server File List

New Changed

Ver. 1.08 Ver. 1.09

Ver. 1.09 Ver. 1.10

2-1167

Changed

Ver. 1.16 ---

FTPGetFile

Get File from FTP New

Server

Changed

Ver. 1.08 Ver. 1.09

Ver. 1.09 Ver. 1.10

2-1184

Changed

Ver. 1.16 ---

FTPPutFile

Put File onto FTP New

Server

Changed

Ver. 1.08 Ver. 1.09

Ver. 1.09 Ver. 1.10

2-1193

Changed

Ver. 1.16 ---

FTPRemove- Delete FTP

File

Server File

New Changed

Ver. 1.08 Ver. 1.09

Ver. 1.09 Ver. 1.10

2-1204

Changed

Ver. 1.16 ---

FTPRemove- Delete FTP

New

Dir

Server Directory Changed

Ver. 1.08 Ver. 1.09

Ver. 1.09 Ver. 1.10

2-1214

Changed

Ver. 1.16 ---

NJ/NX-series Instructions Reference Manual (W502)

A-31

Appendices

Type

Instruction

Name

New/Changed

Versions

CPU Unit

Sysmac Studio

Page

Serial Communications Instructions

SerialRcvNo Clear *3

SCU Receive Serial without Receive Buffer Clear

New

Ver. 1.03 Ver. 1.04 2-1244

NX_SerialSend

Send No-protocol Data

New

Ver. 1.11 Ver. 1.15 2-1272

NX_SerialRcv Receive No-pro- New tocol Data

Ver. 1.11 Ver. 1.15 2-1285

NX_ModbusR- Send Modbus

tuCmd

RTU General

Command

New

Ver. 1.11 Ver. 1.15 2-1299

NX_ModbusR- Send Modbus

tuRead

RTU Read Com-

mand

New

Ver. 1.11 Ver. 1.15 2-1299

NX_ModbusR- Send Modbus

tuWrite

RTU Write Com-

mand

New

Ver. 1.11 Ver. 1.15 2-1322

NX_SerialSigCtl

Serial Control Signal ON/OFF Switching

New

Ver. 1.11 Ver. 1.15 2-1334

NX_SerialSig- Read Serial Con- New

Read

trol Signal

Ver. 1.13 Ver. 1.17 2-1343

NX_SerialSta- Read Serial Port New

tusRead

Status

Ver. 1.13 Ver. 1.17 2-1348

NX_SerialBuf- Clear Buffer Clear

New

Ver. 1.11 Ver. 1.15 2-1353

NX_SerialStartMon

Start Serial Line New Monitoring

Ver. 1.11 Ver. 1.15 2-1363

NX_SerialStopMon

Stop Serial Line New Monitoring

Ver. 1.11 Ver. 1.15 2-1368

SD Memory Card BackupTo

Instructions

MemoryCard

SD Memory Card New Backup

Ver.1.08 Ver.1.09 2-1453

Time Stamp Instructions

NX_DOutTimeStamp

Write Digital Out- New put with Specified Time Stamp

Ver. 1.06 Ver. 1.07 2-1470

NX_AryDOutTimeStamp

Write Digital Output Array with Specified Time Stamp

New

Ver. 1.06 Ver. 1.07 2-1476

Other Instructions

GetMyTask Interval

Read Current Task Period

New

Ver.1.08 Ver.1.09 2-1495

ActEventTask Activate Event Task

New

Ver. 1.03 Ver. 1.04 2-1507

*1 For an NJ101 CPU Unit, Sysmac Studio version 1.13 or higher is required.

*2 For an NX1P2 CPU Unit, a CPU Unit with unit version 1.14 or later and Sysmac Studio version 1.18 or higher are required.

*3 A CPU Unit with unit version 1.03 or later, Sysmac Studio version 1.04 or higher, and a Serial Communications Unit with unit version 2.1 or later are required to use the SerialRcvNoClear instruction.

A-32

NJ/NX-series Instructions Reference Manual (W502)

A-6 Version Information

What to Do If An Error Message Says the Instruction May Cause Unintended Operations

Appendices

What to Do If An Error Message Says the Instruction May Cause Unintended Operations
The Sysmac Studio may display the following error message:
The instruction may cause unintended operations. Refer to the Instruction Reference Manual for details.
The message is the results of restrictions in the user program. The user program may need to be corrected.
This appendix describes the conditions under which this error message may be displayed and how to correct the user program.

Version Information

This error message is displayed only for Sysmac Studio version 1.02.

A

Conditions for Display of the Error Message
The error message is displayed when an in-out variable in a function or function block is passed to a specific variable of a specific instruction within the same function or function block.
A table of the instructions and variables for which the error message is displayed is given later in this appendix.
Programming Example for Which the Error Message Is Displayed

P_On
UINT#10 TableData[0] TablePosition

MyFUNCTION

EN DataSize InOut

ENO

DataPos

Output

InOut[0] DataSize
DataPos

AryMax

EN In Size InOutPos

ENO Num

The AryMax instruction is contained in the MyFUNCTION function.

In this example, the InOut in-out variable of MyFUNCTION is passed to the In variable of the AryMax instruction.

NJ/NX-series Instructions Reference Manual (W502)

A-33

Appendices

Instructions and Variables for Which the Error Message Is Displayed
This error message is displayed only for specific variables of specific instructions. These are listed in the following table.

Type
Comparison Instructions

Instruction TableCmp AryCmpEQ AryCmpNE AryCmpLT AryCmpLE

AryCmpGT AryCmpGE

AryCmpEQV AryCmpNEV AryCmpLTV AryCmpLEV

AryCmpGTV

AryCmpGEV

Math Instructions
BCD Conversion Instructions Bit String Processing Instructions
Selection Instructions Data Movement Instructions
Shift Instructions

AryAdd AryAddV ArySub ArySubV AryMean ArySD AryToBCD AryToBin AryAnd AryOr AryXor AryXorN AryMax AryMin ArySearch TransBits AryExchange AryMove Clear AryShiftReg AryShiftRegLR ArySHL ArySHR NSHLC NSHRC

Name Table Comparison Array Comparison Equal Array Comparison Not Equal Array Comparison Less Than Array Comparison Less Than Or Equal Array Comparison Greater Than Array Comparison Greater Than Or Equal Array Value Comparison Equal Array Value Comparison Not Equal Array Value Comparison Less Than Array Value Comparison Less Than Or Equal Array Value Comparison Greater Than Array Value Comparison Greater Than Or Equal Array Addition Array Value Addition Array Subtraction Array Value Subtraction Array Mean Array Element Standard Deviation Array BCD Conversion Array Unsigned Integer Conversion Array Logical AND Array Logical OR Array Logical Exclusive OR Array Logical Exclusive NOR Array Maximum Array Minimum Array Search Move Bits Array Data Exchange Array Move Initialize Shift Register Reversible Shift Register Array N-element Left Shift Array N-element Right Shift Shift N-bits Left with Carry Shift N-bits Right with Carry

Function Table and AryOut In1, In2, and AryOut In1, In2, and AryOut In1, In2, and AryOut In1, In2, and AryOut

Page 2-111 2-114 2-114 2-116 2-116

In1, In2, and AryOut 2-116 In1, In2, and AryOut 2-116

In1 and AryOut In1 and AryOut In1 and AryOut In1 and AryOut

2-119 2-119 2-121 2-121

In1 and AryOut

2-121

In1 and AryOut

2-121

In1, In2, and AryOut In1 and AryOut In1, In2, and AryOut In1 and AryOut In In In and AryOut In and AryOut In1, In2, and AryOut In1, In2, and AryOut In1, In2, and AryOut In1, In2, and AryOut In In In InOut InOut1 and InOut2 In and AryOut InOut InOut InOut InOut InOut InOut InOut

2-221 2-223 2-225 2-227 2-229 2-231 2-256 2-258 2-327 2-327 2-327 2-327 2-347 2-347 2-350 2-357 2-369 2-371 2-373 2-388 2-390 2-393 2-393 2-398 2-398

A-34

NJ/NX-series Instructions Reference Manual (W502)

Appendices

A-6 Version Information

What to Do If An Error Message Says the Instruction May Cause Unintended Operations

Type

Instruction

Name

Function

Page

Conversion Instructions

Decoder Encoder

Bit Decoder Bit Encoder

InOut In

2-407 2-410

ColmToLine_**

Column to Line Conversion Group In

2-413

LineToColm

Line to Column Conversion

InOut

2-415

PWLApprox

Broken Line Approximation

Line

2-426

MovingAverage

Moving Average

Buf

2-435

StringToAry

Text String-to-Array Conversion

AryOut

2-463

AryToString

Array-to-Text String Conversion

In

2-465

DispartDigit

Four-bit Separation

AryOut

2-467

UniteDigit_**

Four-bit Join Group

In

2-469

Dispart8Bit

Byte Data Separation

AryOut

2-471

Unite8Bit_**

Byte Data Join Group

In

2-473

ToAryByte

Conversion to Byte Array

In and AryOut

2-475

AryByteTo SizeOfAry

Conversion from Byte Array Get Number of Array Elements

In and OutVal In

2-480

2-485

A

Stack and Table Instructions

StackPush StackFIFO

Push onto Stack First In First Out

InOut InOut and OutVal

2-498 2-507

StackLIFO

Last In First Out

InOut and OutVal 2-507

StackIns

Insert into Stack

InOut

2-510

StackDel

Delete from Stack

InOut

2-512

RecSearch

Record Search

In, Member, and InOutPos

2-514

RecRangeSearch Range Record Search

In, Member, and InOutPos

2-519

RecSort

Record Sort

InOut and Member 2-524

RecNum

Get Number of Records

In and Member

2-530

RecMax

Maximum Record Search

In, Member, and InOutPos

2-532

RecMin

Minimum Record Search

In, Member, and InOutPos

2-532

FCS Instructions AryLRC_**

Calculate Array LRC Group

In

2-546

AryCRCCCITT

Calculate Array CRC-CCITT

In

2-548

AryCRC16

Calculate Array CRC-16

In

2-550

System Control Instructions

SetAlarm SetInfo

Create User-defined Error Create User-defined Information

Info1 and Info2 Info1 and Info2

2-816 2-860

EtherCAT Commu- EC_CoESDOWrite Write EtherCAT CoE SDO

nications Instructions

EC_CoESDORead Read EtherCAT CoE SDO

WriteDat ReadDat

2-934 2-937

EtherNet/IP Communications Instructions

CIPRead CIPWrite CIPSend

Read Variable Class 3 Explicit Write Variable Class 3 Explicit Send Explicit Message Class 3

DstDat
SrcDat
ServiceDat and RespServiceDat

2-1039 2-1045 2-1051

CIPUCMMRead Read Variable UCMM Explicit

DstDat

2-1059

CIPUCMMWrite

Write Variable UCMM Explicit

SrcDat

2-1064

CIPUCMMSend

Send Explicit Message UCMM

ServiceDat and RespServiceDat

2-1071

SktUDPRcv

UDP Socket Receive

RcvDat

2-1089

SktUDPSend

UDP Socket Send

SendDat

2-1092

SktTCPRcv

TCP Socket Receive

RcvDat

2-1107

SktTCPSend

TCP Socket Send

SendDat

2-1110

Serial Communica- ExecPMCR tions Instructions SerialSend

Protocol Macro SCU Send Serial

SrcDat and DstDat 2-1220

SrcDat

2-1233

SerialRcv

SCU Receive Serial

DstDat

2-1244

SendCmd

Send Command

CmdDat and RespDat

2-1259

NJ/NX-series Instructions Reference Manual (W502)

A-35

Appendices

Type

Instruction

Name

Function

SD Memory Card FileWriteVar

Instructions

FileReadVar

Write Variable to File Read Variable from File

WriteVar ReadVar

FileRead

Read File

ReadBuf

FileWrite

Write File

WriteBuf

Motion Control Instructions

MC_SetCamTable Set Cam Table Properties Property

CamTable

MC_SaveCam Table

Save Cam Table

CamTable

MC_Write

Write MC Setting

Target and SettingValue

MC_CamIn

Start Cam Operation

CamTable

MC_ChangeAxes Change Axes in Group InGroup

Axes

Other Instructions ChkRange

Check Subrange Variable

Val

* Refer to the NJ/NX-series Motion Control Instructions Reference Manual (Cat. No. W508) for details.

Page 2-1374 2-1379 2-1395 2-1403 *
*
*
* *
2-1490

A-36

NJ/NX-series Instructions Reference Manual (W502)

A-6 Version Information

What to Do If An Error Message Says the Instruction May Cause Unintended Operations

Appendices

Correcting the User Program
The user program must be corrected so that the error message is not displayed. There are two ways to correct the user program. · Copy the in-out variable to an internal variable in the function or function block and then pass the
internal variable to the instruction. · Place the instruction outside of the function or function block. Both of these methods are described below.
 Passing the In-Out Variable to an Internal Variable
Do not pass the in-out variable of the function or function block directly to the instruction. Copy it to an internal variable first. If the value of the internal variable changes when the instruction is executed, the internal variable is then copied back to the in-out variable after the instruction is executed.
However, this method cannot be used for the Clear instruction. To use the Clear instruction, place it out- A
side the function or function block.

P_On
UINT#10 TableData[0] TablePosition

MyFUNCTION

EN DataSize InOut

ENO

DataPos

Output

Here, the InOut[0] element of the InOut in-out variable of MyFUNCTION is passed directly to the In variable of the AryMax instruction.

P_On
InOut[0] DataSize DataPos

AryMax

EN

ENO

In

Size

Num

InOutPos

Correction

Move the InOut in-out variable of MyFUNCTION to the InOutTmp internal variable and then pass InOutTmp[0] to the In variable of the AryMax instruction.

P_On InOut

MOVE

EN

ENO

In

Out

InOutTmp

InOutTmp[0] DataSize
DataPos

AryMax

EN

ENO

In

Size

Num

InOutPos

InOutTmp

MOVE

EN

ENO

In

Out

InOut

After the AryMax instruction is executed, return the contents of InOutTmp to InOut.

NJ/NX-series Instructions Reference Manual (W502)

A-37

Appendices

 Placing the Instruction Outside of the Function or Function Block
You can correct the problem by placing the instruction outside of the function or function block instead of inside it.

The AryMax instruction is contained in the MyFUNCTION.

Place the AryMax instruction outside of MyFUNCTION.

P_On
UINT#10 TableData[0] TablePosition

MyFUNCTION

EN DataSize InOut

ENO

DataPos

Output Correction

P_On
TableData[0] UINT#10
TablePosition

AryMax

EN In Size InOutPos

ENO Num

InOut[0] DataSize
DataPos

AryMax

EN In Size InOutPos

ENO Num

UINT#10 TableData[0] TablePosition

MyFUNCTION

EN DataSize InOut

ENO

DataPos

Output1 Output2

When the Error Message Can Be Ignored
Even if the error message is displayed, there are cases when the instruction can be used without any problems. Whether the instruction can be used depends on the parameter that is passed to the in-out variable of the function of function block. These conditions are listed in the following table.

Applicability of instruction
Can be used.
Cannot be used.

Parameter passed to in-out variable of function of function block
Basic data type, enumeration, array, structure, or union One element of an array, or one member of a structure or union

A-38

NJ/NX-series Instructions Reference Manual (W502)

A-6 Version Information

What to Do If An Error Message Says the Instruction May Cause Unintended Operations

Appendices

 Example in Which the Instruction Can Be Used
In this example, an array is passed to the in-out variable of a function or function block and then used in an instruction inside the function or function block.

Variables Called by MyFUNCTION

Variable

Data type

DintArray ARRAY[0..9] OF DINT

Variables in MyFUNCTION

Variable

Data type

InOut

ARRAY[0..9] OF DINT

A

P_On DintArray

MyFUNCTION

EN InOut

ENO

Output

The entire array is passed to the InOut in-out variable of MyFUNCTION.

In this example, an structure is passed to the in-out variable of a function or function block and then used in an instruction inside the function or function block.

Variable Called by MyFUNCTION

Variable

Data type

StructVar STRUCT

Variable in MyFUNCTION

Variable

Data type

InOut

STRUCT

P_On StructVar

MyFUNCTION

EN InOut

ENO

Output

The entire structure is passed to the InOut in-out variable of MyFUNCTION.

NJ/NX-series Instructions Reference Manual (W502)

A-39

Appendices

 Example in Which the Instruction Cannot Be Used
In the following example, one element of an array is passed to the in-out variable of a function or function block, so the instruction cannot be used inside the function or function block.

Variable Called by MyFUNCTION

Variable

Data type

DintArray ARRAY[0..9] OF DINT

Variable in MyFUNCTION

Variable

Data type

InOut

DINT

P_On DintArray[0]

MyFUNCTION

EN InOut

ENO

Output

One element of the array is passed to the InOut in-out variable of MyFUNCTION.
In the following example, one member of a structure is passed to the in-out variable of a function or function block, so the instruction cannot be used inside the function or function block.

Variable Called by MyFUNCTION

Variable

Data type

StructVar STRUCT

Variable in MyFUNCTION

Variable

Data type

InOut

DINT

P_On StructVar.member1

MyFUNCTION

EN InOut

ENO

Output

One member of the structure is passed to the InOut in-out variable of MyFUNCTION.
Option Setting for Error Detection
As described above, there are cases when the instruction can be used even if the error message is displayed. There is an option in the Sysmac Studio that you can use to enable or disable detection of this error.

A-40

NJ/NX-series Instructions Reference Manual (W502)

A-6 Version Information

Appendices
To prevent detection of this error, display the option settings on the Sysmac Studio and clear the selection of the Detect an error when an in-out variable is passed to a specific instruction argument Check Box in the Program Check Area. Refer to the Sysmac Studio Version 1 Operation Manual (Cat. No. W504-E1-03 or later) for the specific procedure. However, before you disable detection of this error, make sure that all of the instructions in the user program can be used. Even if detection of this error is disabled, the same message will be displayed as a warning.

Caution

A

If you clear the selection of this option, unexpected operation may occur for the instructions and the system may be affected. Always confirm that the conditions for use that are given in When the When the Error Message Can Be Ignored on page A-38 are met before you clear the selection of this option.

Version Information
This error message is displayed and the above option setting is available only for Sysmac Studio version 1.02.

What to Do If An Error Message Says the Instruction May Cause Unintended Operations

NJ/NX-series Instructions Reference Manual (W502)

A-41

Appendices

A-42

NJ/NX-series Instructions Reference Manual (W502)

Index
I

NJ/NX-series Instructions Reference Manual (W502)

Index-1

Index

Index

Symbols
- (Subtraction) ............................................................ 2-174 -OU (Subtraction with Overflow Check) .................... 2-177 * (Multiplication) ......................................................... 2-181 ** (Exponentiation) .................................................... 2-211 **_BCD_TO_***
(BCD-to-Unsigned Integer Conversion Group) ....... 2-242 **_TO_***
(Bit String-to-Bit String Conversion Group) ............ 2-272 **_TO_***
(Bit String-to-Integer Conversion Group) ................ 2-270 **_TO_***
(Bit String-to-Real Number Conversion Group) ...... 2-274 **_TO_***
(Integer-to-Bit String Conversion Group) ................ 2-265 **_TO_***
(Integer-to-Integer Conversion Group) ................... 2-262 **_TO_***
(Integer-to-Real Number Conversion Group) ......... 2-268 **_TO_***
(Real Number-to-Bit String Conversion Group) ...... 2-279 **_TO_***
(Real Number-to-Integer Conversion Group) ......... 2-276 **_TO_*** (Real Number-to-Real Number
Conversion Group) ................................................. 2-281 **_TO_BCD_***
(Unsigned Integer-to-BCD Conversion Group) ....... 2-245 **_TO_STRING
(Bit String-to-Text String Conversion Group) .......... 2-285 **_TO_STRING
(Integer-to-Text String Conversion Group) ............. 2-283 **_TO_STRING
(Real Number-to-Text String Conversion Group) ... 2-287 / (Division) ................................................................. 2-189 & (Logical AND) ......................................................... 2-320 + (Addition) ................................................................ 2-166 +OU (Addition with Overflow Check) ......................... 2-170 < (Less Than) .............................................................. 2-97 <= (Less Than Or Equal) ............................................. 2-97 <> (Not Equal) ............................................................. 2-94 = (Equal) ...................................................................... 2-92 > (Greater Than) ......................................................... 2-97 >= (Greater Than Or Equal) ........................................ 2-97
Numerics
2-byte Join ................................................................. 2-487 4-byte Join ................................................................. 2-489
A
ABS (Absolute Value) ................................................ 2-194 Absolute Value .......................................................... 2-194
Index-2

Accept TCP Socket ................................................. 2-1095 Accumulation Timer ................................................... 2-138 AccumulationTimer (Accumulation Timer) ................ 2-138 ACOS (Principal Arc Cosine) .................................... 2-201 AC_StepProgram (Step Program) ............................. 2-779 ActEventTask (Activate Event Task) ....................... 2-1507 Activate Event Task ................................................. 2-1507 ADD (Addition) .......................................................... 2-166 Add Time ................................................................... 2-600 Add Time to Date and Time ...................................... 2-604 Add Time to Time of Day ........................................... 2-602 AddDelimiter (Put Text Strings with Delimiters) ........ 2-577 ADD_DT_TIME (Add Time to Date and Time) .......... 2-604 Addition ..................................................................... 2-166 Addition with Overflow Check .................................... 2-170 AddOU (Addition with Overflow Check) .................... 2-170 ADD_TIME (Add Time) ............................................. 2-600 ADD_TOD_TIME (Add Time to Time of Day) ........... 2-602 AND ............................................................................. 2-18 AND (AND) .................................................................. 2-18 AND (Logical AND) ................................................... 2-320 AND NOT .................................................................... 2-18 ANDN (AND NOT) ....................................................... 2-18 Array Addition ............................................................ 2-221 Array BCD Conversion .............................................. 2-256 Array Comparison Equal ........................................... 2-114 Array Comparison Greater Than ............................... 2-116 Array Comparison Greater Than Or Equal ................ 2-116 Array Comparison Less Than .................................... 2-116 Array Comparison Less Than Or Equal .................... 2-116 Array Comparison Not Equal ..................................... 2-114 Array Data Exchange ................................................ 2-369 Array Element Standard Deviation ............................ 2-231 Array Logical AND ..................................................... 2-327 Array Logical Exclusive NOR .................................... 2-327 Array Logical Exclusive OR ....................................... 2-327 Array Logical OR ....................................................... 2-327 Array Maximum ......................................................... 2-347 Array Mean ................................................................ 2-229 Array Minimum .......................................................... 2-347 Array Move ................................................................ 2-371 Array N-element Left Shift ......................................... 2-393 Array N-element Right Shift ....................................... 2-393 Array Search ............................................................. 2-350 Array Subtraction ....................................................... 2-225 Array Unsigned Integer Conversion .......................... 2-258 Array Value Addition .................................................. 2-223 Array Value Comparison Equal ................................. 2-119 Array Value Comparison Greater Than ..................... 2-121 Array Value Comparison Greater Than Or Equal ...... 2-121 Array Value Comparison Less Than ......................... 2-121 Array Value Comparison Less Than Or Equal .......... 2-121 Array Value Comparison Not Equal .......................... 2-119 Array Value Subtraction ............................................ 2-227 Array-to-Text String Conversion ................................ 2-465
NJ/NX-series Instructions Reference Manual (W502)

Index

AryAdd (Array Addition) ............................................ 2-221 AryAddV (Array Value Addition) ................................ 2-223 AryAnd (Array Logical AND) ..................................... 2-327 AryByteTo (Conversion from Byte Array) .................. 2-480 AryCmpEQ (Array Comparison Equal) ..................... 2-114 AryCmpEQV (Array Value Comparison Equal) ......... 2-119 AryCmpGE
(Array Comparison Greater Than Or Equal) .......... 2-116 AryCmpGEV
(Array Value Comparison Greater Than Or Equal) 2-121 AryCmpGT (Array Comparison Greater Than) ......... 2-116 AryCmpGTV
(Array Value Comparison Greater Than) ............... 2-121 AryCmpLE
(Array Comparison Less Than Or Equal) ............... 2-116 AryCmpLEV
(Array Value Comparison Less Than Or Equal) ..... 2-121 AryCmpLT (Array Comparison Less Than) ............... 2-116 AryCmpLTV (Array Value Comparison Less Than) .. 2-121 AryCmpNE (Array Comparison Not Equal) ............... 2-114 AryCmpNEV (Array Value Comparison Not Equal) .. 2-119 AryCRC16 (Calculate Array CRC-16) ....................... 2-550 AryCRCCCITT (Calculate Array CRC-CCITT) .......... 2-548 AryExchange (Array Data Exchange) ....................... 2-369 AryLRC_** (Calculate Array LRC Group) ................. 2-546 AryMax (Array Maximum) ......................................... 2-347 AryMean (Array Mean) .............................................. 2-229 AryMin (Array Minimum) ........................................... 2-347 AryMove (Array Move) .............................................. 2-371 AryOr (Array Logical OR) .......................................... 2-327 ArySD (Array Element Standard Deviation) .............. 2-231 ArySearch (Array Search) ......................................... 2-350 AryShiftReg (Shift Register) ...................................... 2-388 AryShiftRegLR (Reversible Shift Register) ............... 2-390 ArySHL (Array N-element Left Shift) ......................... 2-393 ArySHR (Array N-element Right Shift) ...................... 2-393 ArySub (Array Subtraction) ....................................... 2-225 ArySubV (Array Value Subtraction) .......................... 2-227 AryToBCD (Array BCD Conversion) ......................... 2-256 AryToBin (Array Unsigned Integer Conversion) ........ 2-258 AryToString (Array-to-Text String Conversion) ......... 2-465 AryXor (Array Logical Exclusive OR) ........................ 2-327 AryXorN (Array Logical Exclusive NOR) ................... 2-327 ASIN (Principal Arc Sine) .......................................... 2-201 ATAN (Principal Arc Tangent) ................................... 2-201
B
BackupToMemoryCard (SD Memory Card Backup) 2-1453 Band (Deadband Control) ......................................... 2-339 BCD Data Type-to-Unsigned Integer
Conversion Group .................................................. 2-247 BCDsToBin
(Signed BCD-to-Signed Integer Conversion) ......... 2-250 BCD_TO_** (BCD Data Type-to-Unsigned Integer
Conversion Group) ................................................. 2-247 BCD-to-Unsigned Integer Conversion Group ........... 2-242 Binary Code-to-Gray Code Conversion .................... 2-461 Binary Selection ........................................................ 2-332

BinToBCDs_** (Signed Integer-to-BCD Conversion Group) .......... 2-253
BinToGray_** (Binary Code-to-Gray Code Conversion) ............... 2-461
Bit Counter ................................................................ 2-412 Bit Decoder ............................................................... 2-407 Bit Encoder ............................................................... 2-410 Bit Pattern Copy
(Bit String to Real Number) Group ......................... 2-377 Bit Pattern Copy
(Bit String to Signed Integer) Group ....................... 2-375 Bit Pattern Copy
(Real Number to Bit String) Group ......................... 2-383 Bit Pattern Copy
(Real Number to Signed Integer) Group ................ 2-385 Bit Pattern Copy
(Signed Integer to Bit String) Group ....................... 2-379 Bit Pattern Copy
(Signed Integer to Real Number) Group ................ 2-381 Bit Reversal ............................................................... 2-325
I Bit String Conversion Group ..................................... 2-308
Bit String-to-Bit String Conversion Group ................. 2-272 Bit String-to-Integer Conversion Group ..................... 2-270 Bit String-to-Real Number Conversion Group ........... 2-274 Bit String-to-Text String Conversion Group .............. 2-285 BitCnt (Bit Counter) ................................................... 2-412 Block Set ................................................................... 2-365 BREAK (Break Loop) .................................................. 2-89 Break Down Date and Time ...................................... 2-654 Break Loop .................................................................. 2-89 Broken Line Approximation
with Broken Line Data Check ................................. 2-426 Broken Line Approximation
without Broken Line Data Check ............................ 2-426 Broken Line Data Check ........................................... 2-432 Byte Data Join Group ................................................ 2-473 Byte Data Separation ................................................ 2-471
C
Calculate Array CRC-16 ........................................... 2-550 Calculate Array CRC-CCITT ..................................... 2-548 Calculate Array LRC Group ...................................... 2-546 Calculate Text String CRC-16 ................................... 2-544 Calculate Text String CRC-CCITT ............................ 2-542 Calculate Text String LRC ........................................ 2-540 Case ............................................................................ 2-30 CASE (Case) .............................................................. 2-30 Change File Name .................................................. 2-1442 Change FTP Account .............................................. 2-1159 Change IP Address ................................................. 2-1151 Change NTP Server Address ................................. 2-1163 Change to NX Unit Write Mode ................................. 2-874 ChangeFTPAccount (Change FTP Account) .......... 2-1159 ChangeIPAdr (Change IP Address) ........................ 2-1151 ChangeNTPAdr (Change NTP Server Address) ..... 2-1163 Check for Leap Year ................................................. 2-645 Check Subrange Variable ....................................... 2-1490 CheckReal (Real Number Check) ............................. 2-237

NJ/NX-series Instructions Reference Manual (W502)

Index-3

Index

Checksum Calculation ............................................... 2-538 ChkLeapYear (Check for Leap Year) ........................ 2-645 ChkRange (Check Subrange Variable) ................... 2-1490 CIPClose (Close CIP Class 3 Connection) ............. 2-1056 CIPOpen (Open CIP Class 3 Connection) .............. 2-1026 CIPOpenWithDataSize (Open CIP Class 3 Connection
with Specified Data Size) ...................................... 2-1035 CIPRead (Read Variable Class 3 Explicit) .............. 2-1039 CIPSend (Send Explicit Message Class 3) ............. 2-1051 CIPUCMM Read (Read Variable UCMM Explicit) ... 2-1059 CIPUCMM Send (Send Explicit Message UCMM) .. 2-1071 CIPUCMM Write (Write Variable UCMM Explicit) ... 2-1064 CIPWrite (Write Variable Class 3 Explicit) ............... 2-1045 Clear (Initialize) ......................................................... 2-373 Clear Buffer ............................................................. 2-1353 Clear String ............................................................... 2-571 Clear TCP/UDP Socket Receive Buffer .................. 2-1119 ClearString (Clear String) .......................................... 2-571 Close CIP Class 3 Connection ................................ 2-1056 Close File ................................................................ 2-1388 Close TCP/UDP Socket .......................................... 2-1116 Cmp (Compare) ......................................................... 2-107 ColmToLine_**
(Column to Line Conversion Group) ....................... 2-413 Column to Line Conversion Group ............................ 2-413 Combine Real Number Mantissa and Exponent ....... 2-444 Compare .................................................................... 2-107 CONCAT (Concatenate String) ................................. 2-554 CONCAT_DATE _TOD
(Concatenate Date and Time of Day) ..................... 2-620 Concatenate Date and Time of Day .......................... 2-620 Concatenate String .................................................... 2-554 Connect EtherCAT Slave .......................................... 2-961 Connect TCP Socket ............................................... 2-1098 Conversion from Byte Array ...................................... 2-480 Conversion to Byte Array .......................................... 2-475 Convert Date and Time to Seconds .......................... 2-630 Convert Date to Seconds .......................................... 2-632 Convert Days to Month .............................................. 2-648 Convert Nanoseconds to Time .................................. 2-642 Convert Seconds to Date .......................................... 2-636 Convert Seconds to Date and Time .......................... 2-634 Convert Seconds to Time .......................................... 2-643 Convert Seconds to Time of Day .............................. 2-638 Convert Time of Day to Seconds .............................. 2-633 Convert Time to Nanoseconds .................................. 2-640 Convert Time to Seconds .......................................... 2-641 Convert to Lowercase ............................................... 2-573 Convert to Uppercase ............................................... 2-573 Copy File ................................................................. 2-1428 Copy**To*** (Bit Pattern Copy
(Bit String to Real Number) Group) ........................ 2-377 Copy**To*** (Bit Pattern Copy
(Real Number to Bit String) Group) ........................ 2-383 Copy**ToNum (Bit Pattern Copy
(Bit String to Signed Integer) Group) ...................... 2-375 Copy**ToNum (Bit Pattern Copy
(Real Number to Signed Integer) Group) ............... 2-385

CopyNumTo** (Bit Pattern Copy (Signed Integer to Bit String) Group) ...................... 2-379
CopyNumTo** (Bit Pattern Copy (Signed Integer to Real Number) Group) ............... 2-381
COS (Cosine in Radians) .......................................... 2-198 Cosine in Radians ..................................................... 2-198 Create Directory ...................................................... 2-1447 Create UDP Socket ................................................. 2-1081 Create User-defined Error ......................................... 2-816 Create User-defined Information ............................... 2-860 CTD (Down-counter) ................................................. 2-146 CTD_** (Down-counter Group) ................................. 2-148 CTU (Up-counter) ...................................................... 2-150 CTU_** (Up-counter Group) ...................................... 2-152 CTUD (Up-down Counter) ......................................... 2-155 CTUD_** (Up-down Counter Group) ......................... 2-159
D
Data Exchange .......................................................... 2-367 Data Trace Sampling ................................................. 2-806 Data Trace Trigger .................................................... 2-809 Date and Time-to-Text String Conversion ................. 2-456 DateStructToDt (Join Time) ....................................... 2-656 DateToSec (Convert Date to Seconds) ..................... 2-632 DateToString (Date-to-Text String Conversion) ........ 2-458 Date-to-Text String Conversion ................................. 2-458 DaysToMonth (Convert Days to Month) .................... 2-648 Dead Zone Control .................................................... 2-342 Deadband Control ..................................................... 2-339 Dec (Decrement) ....................................................... 2-217 Decoder (Bit Decoder) ............................................... 2-407 Decrement ................................................................. 2-217 Degrees to Radians ................................................... 2-196 DegToRad (Degrees to Radians) .............................. 2-196 DELETE (Delete String) ............................................ 2-565 Delete Directory ....................................................... 2-1450 Delete File ............................................................... 2-1437 Delete from Stack ...................................................... 2-512 Delete String .............................................................. 2-565 Determine Task Status ............................................ 2-1498 DirCreate (Create Directory) ................................... 2-1447 DirRemove (Delete Directory) ................................. 2-1450 Disable Program ........................................................ 2-907 Disconnect EtherCAT Slave ...................................... 2-954 Dispart8Bit (Byte Data Separation) ........................... 2-471 DispartDigit (Four-bit Separation) .............................. 2-467 DispartReal (Separate Mantissa and Exponent) ....... 2-441 DIV (Division) ............................................................ 2-189 Divide Time ............................................................... 2-618 Division ...................................................................... 2-189 DIVTIME (Divide Time) ............................................. 2-618 Down (Down Trigger) .................................................. 2-44 Down Trigger ............................................................... 2-44 Down-counter ............................................................ 2-146 Down-counter Group ................................................. 2-148 DT_TO_DATE (Extract Date from Date and Time) ... 2-624 DtToDateStruct (Break Down Date and Time) .......... 2-654 DtToSec (Convert Date and Time to Seconds) ......... 2-630

Index-4

NJ/NX-series Instructions Reference Manual (W502)

Index

DtToString (Date and Time-to-Text String Conversion) ........... 2-456
DT_TO_TOD (Extract Time of Day from Date and Time) ............ 2-622
E
EC_ChangeEnableSetting (Enable/Disable EtherCAT Slave) ..................................................................... 2-963
EC_CoESDORead (Read EtherCAT CoE SDO) ...... 2-937 EC_CoESDOWrite (Write EtherCAT CoE SDO) ...... 2-934 EC_ConnectSlave (Connect EtherCAT Slave) ......... 2-961 EC_CopyMon (Transfer EtherCAT Packets) ............ 2-952 EC_DisconnectSlave (Disconnect EtherCAT Slave) 2-954 EC_SaveMon (Save EtherCAT Packets) .................. 2-950 EC_StartMon (Start EtherCAT Packet Monitor) ........ 2-942 EC_StopMon (Stop EtherCAT Packet Monitor) ........ 2-948 Enable Program ........................................................ 2-898 Encoder (Bit Encoder) ............................................... 2-410 End .............................................................................. 2-66 End (End) .................................................................... 2-66 Enumeration-to-Integer ............................................. 2-312 EnumToNum (Enumeration-to-Integer) .................... 2-312 EQ (Equal) .................................................................. 2-92 EQascii (Text String Comparison Equal) .................. 2-100 Equal ........................................................................... 2-92 Exchange (Data Exchange) ...................................... 2-367 ExecPMCR (Protocol Macro) .................................. 2-1220 EXP (Natural Exponential Operation) ....................... 2-209 Exponentiation .......................................................... 2-211 EXPT (Exponentiation) ............................................. 2-211 Extract Date from Date and Time ............................. 2-624 Extract Time of Day from Date and Time .................. 2-622
F
FileClose (Close File) .............................................. 2-1388 FileCopy (Copy File) ............................................... 2-1428 FileGets (Get Text String) ....................................... 2-1411 FileOpen (Open File) .............................................. 2-1384 FilePuts (Put Text String) ........................................ 2-1419 FileRead (Read File) ............................................... 2-1395 FileReadVar (Read Variable from File) ................... 2-1379 FileRemove (Delete File) ........................................ 2-1437 FileRename (Change File Name) ........................... 2-1442 FileSeek (Seek File) ................................................ 2-1391 FileWrite (Write File) ............................................... 2-1403 FileWriteVar (Write Variable to File) ....................... 2-1374 FIND (Find String) ..................................................... 2-560 Find String ................................................................. 2-560 First In First Out ........................................................ 2-507 Fixed-decimal Number-to-Text String Conversion .... 2-451 Fixed-length Decimal Text String Conversion ........... 2-446 Fixed-length Hexadecimal Text String Conversion ... 2-446 FixNumToString
(Fixed-decimal Number-to-Text String Conversion) 2-451 FOR (Repeat Start) ..................................................... 2-82 Four-bit Join Group ................................................... 2-469 Four-bit Separation ................................................... 2-467
NJ/NX-series Instructions Reference Manual (W502)

Fraction (Real Number Fraction) .............................. 2-235 FTPGetFile (Get File from FTP Server) .................. 2-1184 FTPGetFileList (Get FTP Server File List) .............. 2-1167 FTPPutFile (Put File onto FTP Server) ................... 2-1193 FTPRemoveDir (Delete FTP Server Directory) ....... 2-1214 FTPRemoveFile (Delete FTP Server File) .............. 2-1204 F_TRIG (Down Trigger) .............................................. 2-44
G

GE (Greater Than Or Equal) ....................................... 2-97

GEascii

(Text String Comparison Greater Than or Equal) .. 2-104

Get Byte Length ........................................................ 2-569

Get Clock Pulse Group ........................................... 2-1513

Get Days in Month .................................................... 2-646

Get EtherCAT Error Status ....................................... 2-845

Get EtherNet/IP Error Status .................................... 2-834

Get First Number of Array ......................................... 2-491

Get I/O Bus Error Status ........................................... 2-832

Get Incrementing Free-running Counter Group ...... 2-1514

I

Get Last Number of Array ......................................... 2-491

Get Motion Control Error Status ................................ 2-841

Get Number of Array Elements ................................. 2-485

Get Number of Records ............................................ 2-530

Get NX Bus Error Status ........................................... 2-850

Get NX Unit Error Status ........................................... 2-852

Get PLC Controller Error Status ............................... 2-828

Get String Any ........................................................... 2-558

Get String Left ........................................................... 2-556

Get String Right ........................................................ 2-556

Get Text String ........................................................ 2-1411

Get Text Strings Minus Delimiters ............................ 2-588

Get Time of Day ........................................................ 2-628

Get User-defined Error Status .................................. 2-823

Get**Clk (Get Clock Pulse Group) .......................... 2-1513

Get**Cnt

(Get Incrementing Free-running Counter Group) . 2-1514

GetAlarm (Get User-defined Error Status) ................ 2-823

GetByteLen (Get Byte Length) .................................. 2-569

GetCJBError (Get I/O Bus Error Status) ................... 2-832

GetDayOfWeek (Get Day of Week) .......................... 2-650

GetDaysOfMonth (Get Days in Month) ..................... 2-646

GetECError (Get EtherCAT Error Status) ................. 2-845

GetEIPError (Get EtherNet/IP Error Status) ............. 2-834

GetMCError (Get Motion Control Error Status) ......... 2-841

GetMyTaskInterval (Read Current Task Period) ..... 2-1495

GetMyTaskStatus (Read Current Task Status) ...... 2-1492

GetNTPStatus (Read NTP Status) ........................... 2-866

GetNXBError (Get NX Bus Error Status) .................. 2-850

GetNXUnitError (Get NX Unit Error Status) .............. 2-852

GetPLCError (Get PLC Controller Error Status) ....... 2-828

GetTime (Get Time of Day) ....................................... 2-628

GetTraceStatus (Read Data Trace Status) ............... 2-812

GetWeekOfYear (Get Week Number) ...................... 2-652

Gray (Gray Code Conversion) .................................. 2-417

Gray Code Conversion ............................................. 2-417

Gray Code-to-Binary Code Conversion Group ......... 2-461

Index-5

Index

GrayToBin_** (Gray Code-to-Binary Code Conversion Group) .... 2-461
Greater Than ............................................................... 2-97 Greater Than Or Equal ................................................ 2-97 GT (Greater Than) ....................................................... 2-97 GTascii (Text String Comparison Greater Than) ....... 2-104
H
Hexadecimal Text String-to-Number Conversion Group .................................................. 2-449
HexStringToNum_** (Hexadecimal Text String-to-Number Conversion Group) ..................... 2-449
Hundred-ms Timer .................................................... 2-141
I
If .................................................................................. 2-26 IF (If) ............................................................................ 2-26 Inc (Increment) .......................................................... 2-217 Increment .................................................................. 2-217 Initialize ..................................................................... 2-373 INSERT (Insert String) .............................................. 2-567 Insert into Stack ......................................................... 2-510 Insert String ............................................................... 2-567 Integer Conversion Group ......................................... 2-306 Integer-to-Bit String Conversion Group ..................... 2-265 Integer-to-Enumeration ............................................. 2-314 Integer-to-Integer Conversion Group ........................ 2-262 Integer-to-Real Number Conversion Group .............. 2-268 Integer-to-Text String Conversion Group .................. 2-283 IOL_ReadObj (Read IO-Link Device Object) .......... 2-1006 IOL_WriteObj (Write IO-Link Device Object) ........... 2-1015
J
JMP (Jump) ................................................................. 2-80 Join Time ................................................................... 2-656 Jump ............................................................................ 2-80
L
Last In First Out ......................................................... 2-507 LD (Load) .................................................................... 2-16 LDN (Load NOT) ......................................................... 2-16 LE (Less Than Or Equal) ............................................. 2-97 LEascii
(Text String Comparison Less Than or Equal) ....... 2-104 LEFT (Get String Left) ............................................... 2-556 LEN (String Length) ................................................... 2-562 Less Than .................................................................... 2-97 Less Than Or Equal .................................................... 2-97 LIMIT (Limiter) ........................................................... 2-337 LimitAlarm_**
(Upper/Lower Limit Alarm Group) ........................... 2-752 LimitAlarmDv_**
(Upper/Lower Deviation Alarm Group) ................... 2-756 LimitAlarmDvStbySeq_** (Upper/Lower Deviation Alarm
with Standby Sequence Group) .............................. 2-761
Index-6

Limiter ........................................................................ 2-337 Line to Column Conversion ....................................... 2-415 LineToColm (Line to Column Conversion) ................ 2-415 LN (Natural Logarithm) .............................................. 2-206 Load ............................................................................ 2-16 Load NOT .................................................................... 2-16 Lock (Lock Tasks) ................................................... 2-1500 Lock Tasks .............................................................. 2-1500 LOG (Logarithm Base 10) ......................................... 2-206 Logarithm Base 10 .................................................... 2-206 Logical AND .............................................................. 2-320 Logical Exclusive OR ................................................ 2-320 Logical OR ................................................................. 2-320 LOWER_BOUND (Get First Number of Array) .......... 2-491 LrealToFormatString
(LREAL-to-Formatted Text String) .......................... 2-294 LREAL-to-Formatted Text String ............................... 2-294 LT (Less Than) ............................................................ 2-97 LTascii (Text String Comparison Less Than) ............ 2-104
M
Master Control End ..................................................... 2-68 Master Control Start .................................................... 2-68 MAX (Maximum) ........................................................ 2-345 Maximum ................................................................... 2-345 Maximum Record Search .......................................... 2-532 MC (Master Control Start) ........................................... 2-68 MCR (Master Control End) .......................................... 2-68 MemCopy (Memory Copy) ........................................ 2-363 Memory Copy ............................................................ 2-363 MID (Get String Any) ................................................. 2-558 MIN (Minimum) .......................................................... 2-345 Minimum .................................................................... 2-345 Minimum Record Search ........................................... 2-532 MOD (Modulo-division) .............................................. 2-192 ModbusTCP Read
(Send Modbus TCP Read Command) .................. 2-1135 ModbusTCPWrite
(Send Modbus TCP Write Command) .................. 2-1143 ModReal (Real Number Modulo-division) ................. 2-233 Modulo-division ......................................................... 2-192 Move .......................................................................... 2-354 MOVE (Move) ............................................................ 2-354 Move Bit .................................................................... 2-357 Move Bits ................................................................... 2-361 Move Digit ................................................................. 2-359 MoveBit (Move Bit) .................................................... 2-357 MoveDigit (Move Digit) .............................................. 2-359 Moving Average ........................................................ 2-435 MovingAverage (Moving Average) ............................ 2-435 MUL (Multiplication) ................................................... 2-181 MulOU
(Multiplication with Overflow Check) ....................... 2-185 MULTIME (Multiply Time) .......................................... 2-616 Multiplexer ................................................................. 2-334 Multiplication .............................................................. 2-181 Multiplication with Overflow Check ............................ 2-185 Multiply Time ............................................................. 2-616
NJ/NX-series Instructions Reference Manual (W502)

Index

MUX (Multiplexer) ..................................................... 2-334
N
NanoSecToTime (Convert Nanoseconds to Time) ... 2-642 Natural Exponential Operation .................................. 2-209 Natural Logarithm ..................................................... 2-206 N-bit Left Shift ........................................................... 2-396 N-bit Right Shift ......................................................... 2-396 NE (Not Equal) ............................................................ 2-94 NEascii (Text String Comparison Not Equal) ............ 2-102 Neg (Reverse Sign) .................................................. 2-405 NEXT (Repeat End) .................................................... 2-82 NOT (Bit Reversal) .................................................... 2-325 Not Equal .................................................................... 2-94 NSHLC (Shift N-bits Left with Carry) ......................... 2-398 NSHRC (Shift N-bits Right with Carry) ...................... 2-398 NumToDecString
(Fixed-length Decimal Text String Conversion) ..... 2-446 NumToEnum (Integer-to-Enumeration) .................... 2-314 NumToHexString (Fixed-length Hexadecimal Text
String Conversion) ................................................. 2-446 NX_AryDOutTimeStamp (Write Digital Output Array with
Specified Time Stamp) ......................................... 2-1476 NX_ChangeWriteMode
(Change to NX Unit Write Mode) ........................... 2-874 NX_DOutTimeStamp (Write Digital Output with Specified
Time Stamp) ......................................................... 2-1470 NX_ModbusRtuCmd (Send Modbus RTU General
Command) ........................................................... 2-1299 NX_ModbusRtuRead (Send Modbus RTU Read
Command) ........................................................... 2-1310 NX_ModbusRtuWrite
(Send Modbus RTU Write Command) ................. 2-1322 NX_Read TotalPower OnTime
(Read NX Unit Total Power ON Time) ................... 2-885 NX_ReadObj (Read NX Unit Object) ........................ 2-995 NX_SaveParam (Save NX Unit Parameters) ............ 2-879 NX_SerialBufClear (Clear Buffer) ........................... 2-1353 NX_SerialRcv (Receive No-protocol Data) ............. 2-1285 NX_SerialSend (Send No-protocol Data) ............... 2-1272 NX_SerialSigCtl
(Serial Control Signal ON/OFF Switching) ........... 2-1334 NX_SerialSigRead (Read Serial Control Signal) .... 2-1343 NX_SerialStartMon (Start Serial Line Monitoring) .. 2-1363 NX_SerialStatusRead (Read Serial Port Status) .... 2-1348 NX_SerialStopMon (Stop Serial Line Monitoring) ... 2-1368 NX_WriteObj (Write NX Unit Object) ........................ 2-980
O
Off-Delay Timer ......................................................... 2-132 On-Delay Timer ......................................................... 2-126 Open File ................................................................ 2-1384 OR ............................................................................... 2-20 OR (Logical OR) ....................................................... 2-320 OR (OR) ...................................................................... 2-20 OR NOT ...................................................................... 2-20 ORN (OR NOT) ........................................................... 2-20
NJ/NX-series Instructions Reference Manual (W502)

Out (Output) ................................................................ 2-22 OutABit (Output A Bit) ................................................. 2-63 OutNot (Output NOT) .................................................. 2-22 Output ......................................................................... 2-22 Output A Bit ................................................................. 2-63 Output NOT ................................................................. 2-22
P
PackDword (4-byte Join) ........................................... 2-489 PackWord (2-byte Join) ............................................ 2-487 PID Control with Autotuning ...................................... 2-672 PIDAT (PID Control with Autotuning) ........................ 2-672 PIDAT _HeatCool ..................................................... 2-697 PLC_ReadTotalPowerOnTime
(Read PLC Total Power ON Time) ......................... 2-893 PrgStart (Enable Program) ....................................... 2-898 PrgStatus (Read Program Status) ............................ 2-927 PrgStop (Disable Program) ....................................... 2-907 Principal Arc Cosine .................................................. 2-201
I Principal Arc Sine ...................................................... 2-201
Principal Arc Tangent ................................................ 2-201 Protocol Macro ........................................................ 2-1220 Push onto Stack ........................................................ 2-498 Put Text String ........................................................ 2-1419 Put Text Strings with Delimiters ................................ 2-577 PWLApprox (Broken Line Approximation
with Broken Line Data Check) ................................ 2-426 PWLApproxNoLineChk (Broken Line Approximation
without Broken Line Data Check) ........................... 2-426 PWLLineChk (Broken Line Data Check) ................... 2-432
R
Radians to Degrees .................................................. 2-196 RadToDeg (Radians to Degrees) ............................. 2-196 Rand (Random Number) ........................................... 2-219 Random Number ....................................................... 2-219 Range Record Search .............................................. 2-519 Read Current Task Period ...................................... 2-1495 Read Current Task Status ...................................... 2-1492 Read Data Trace Status ........................................... 2-812 Read EtherCAT CoE SDO ........................................ 2-937 Read File ................................................................. 2-1395 Read IO-Link Device Object ................................... 2-1006 Read NTP Status ...................................................... 2-866 Read NX Unit Object ................................................. 2-995 Read NX Unit Total Power ON Time ........................ 2-885 Read PLC Total Power ON Time .............................. 2-893 Read Program Status ............................................... 2-927 Read Serial Control Signal ...................................... 2-1343 Read Serial Port Status .......................................... 2-1348 Read TCP Socket Status ........................................ 2-1113 Read Variable Class 3 Explicit ................................ 2-1039 Read Variable from File .......................................... 2-1379 Read Variable UCMM Explicit ................................. 2-1059 ReadNbit_** (N-bit Read Group) ............................. 2-1486 Real Number Check .................................................. 2-237 Real Number Conversion Group ............................... 2-310
Index-7

Index

Real Number Fraction ............................................... 2-235 Real Number Modulo-division ................................... 2-233 Real Number-to-Bit String Conversion Group ........... 2-279 Real Number-to-Integer Conversion Group .............. 2-276 Real Number-to-Real Number Conversion Group .... 2-281 Real Number-to-Text String Conversion Group ........ 2-287 RealToFormatString
(REAL-to-Formatted Text String) ............................ 2-289 REAL-to-Formatted Text String ................................. 2-289 Receive No-protocol Data ....................................... 2-1285 RecMax (Maximum Record Search) ......................... 2-532 RecMin (Minimum Record Search) ........................... 2-532 RecNum (Get Number of Records) ........................... 2-530 Record Search .......................................................... 2-514 Record Sort ............................................................... 2-524 RecRangeSearch (Range Record Search) ............... 2-519 RecSearch (Record Search) ..................................... 2-514 RecSort (Record Sort) ............................................... 2-524 Repeat ......................................................................... 2-36 REPEAT (Repeat) ....................................................... 2-36 Repeat End ................................................................. 2-82 Repeat Start ................................................................ 2-82 REPLACE (Replace String) ....................................... 2-563 Replace String ........................................................... 2-563 Reset ........................................................................... 2-56 Reset (Reset) .............................................................. 2-56 Reset A Bit .................................................................. 2-61 Reset Bits .................................................................... 2-59 Reset EtherCAT Error ............................................... 2-843 Reset Motion Control Error ........................................ 2-836 Reset NX Bus Error ................................................... 2-848 Reset PLC Controller Error ....................................... 2-825 Reset User-defined Error .......................................... 2-821 ResetABit (Reset A Bit) ............................................... 2-61 ResetAlarm (Reset User-defined Error) .................... 2-821 ResetBits (Reset Bits) ................................................. 2-59 ResetCJBError (Reset I/O Bus Error) ....................... 2-830 ResetECError (Reset EtherCAT Error) ..................... 2-843 ResetMCError (Reset Motion Control Error) ............. 2-836 ResetNXBError (Reset NX Bus Error) ....................... 2-848 ResetPLCError (Reset PLC Controller Error) ............ 2-825 Reset-Priority Keep ..................................................... 2-50 ResetUnit (Restart Unit) ............................................ 2-862 Restart NX Units ........................................................ 2-868 Restart Unit ............................................................... 2-862 RestartNXUnit (Restart NX Units) ............................. 2-868 Return .......................................................................... 2-67 RETURN (Return) ....................................................... 2-67 Reverse Sign ............................................................. 2-405 Reversible Shift Register ........................................... 2-390 RIGHT (Get String Right) .......................................... 2-556 ROL (Rotate N-bits Left) ............................................ 2-400 ROR (Rotate N-bits Right) ......................................... 2-400 Rotate N-bits Left ...................................................... 2-400 Rotate N-bits Right .................................................... 2-400 Round (Round Off Real Number) .............................. 2-316 Round Off Real Number ............................................ 2-316 Round Up Real Number ............................................ 2-316 RoundUp (Round Up Real Number) ......................... 2-316

RS (Reset-Priority Keep) ............................................. 2-50 R_TRIG (Up Trigger) ................................................... 2-44
S
Save EtherCAT Packets ............................................ 2-950 Save NX Unit Parameters ......................................... 2-879 ScaleTrans (Scale Transformation) ........................... 2-776 SCU Receive Serial ................................................. 2-1244 SCU Receive Serial without Receive Buffer Clear .. 2-1244 SCU Send Serial ..................................................... 2-1233 SD Memory Card Backup ........................................ 2-1453 SecToDate (Convert Seconds to Date) ..................... 2-636 SecToDt (Convert Seconds to Date and Time) ......... 2-634 SecToTime (Convert Seconds to Time) .................... 2-643 SecToTod (Convert Seconds to Time of Day) .......... 2-638 Seek File ................................................................. 2-1391 SEL (Binary Selection) .............................................. 2-332 Send Command ...................................................... 2-1259 Send Explicit Message Class 3 ............................... 2-1051 Send Explicit Message UCMM ................................ 2-1071 Send Modbus RTU General Command .................. 2-1299 Send Modbus RTU Read Command ....................... 2-1310 Send Modbus RTU Write Command ....................... 2-1322 Send Modbus TCP Read Command ....................... 2-1135 Send Modbus TCP Write Command ....................... 2-1143 Send No-protocol Data ............................................ 2-1272 SendCmd (Send Command) ................................... 2-1259 Separate Mantissa and Exponent ............................. 2-441 Serial Control Signal ON/OFF Switching ................. 2-1334 SerialRcv (SCU Receive Serial) .............................. 2-1244 SerialRcvNoClear (SCU Receive Serial
without Receive Buffer Clear) ............................... 2-1244 SerialSend (SCU Send Serial) ................................ 2-1233 Set ............................................................................... 2-56 Set (Set) ...................................................................... 2-56 Set A Bit ...................................................................... 2-61 Set Bits ........................................................................ 2-59 Set TCP Socket Option ........................................... 2-1122 Set Time .................................................................... 2-626 SetABit (Set A Bit) ....................................................... 2-61 SetAlarm (Create User-defined Error) ....................... 2-816 SetBits (Set Bits) ......................................................... 2-59 SetBlock (Block Set) .................................................. 2-365 SetInfo (Create User-defined Information) ................ 2-860 Set-Priority Keep ......................................................... 2-53 SetTime (Set Time) ................................................... 2-626 Shift N-bits Left with Carry ......................................... 2-398 Shift N-bits Right with Carry ...................................... 2-398 Shift Register ............................................................. 2-388 SHL (N-bit Left Shift) ................................................. 2-396 SHR (N-bit Right Shift) .............................................. 2-396 Signed BCD-to-Signed Integer Conversion ............... 2-250 Signed Integer-to-BCD Conversion Group ................ 2-253 SIN (Sine in Radians) ................................................ 2-198 Sine in Radians ......................................................... 2-198 SizeOfAry (Get Number of Array Elements) .............. 2-485 SJIS to UTF-8 Character Code Conversion .............. 2-424

Index-8

NJ/NX-series Instructions Reference Manual (W502)

Index

SJISToUTF8 (SJIS to UTF-8 Character Code Conversion) ........ 2-424
SktClearBuf (Clear TCP/UDP Socket Receive Buffer) ............. 2-1119
SktClose (Close TCP/UDP Socket) ........................ 2-1116 SktGetTCP Status (Read TCP Socket Status) ....... 2-1113 SktSetOption (Set TCP Socket Option) .................. 2-1122 SktTCP Connect (Connect TCP Socket) ................ 2-1098 SktTCPAccept (Accept TCP Socket) ...................... 2-1095 SktTCPRcv (TCP Socket Receive) ......................... 2-1107 SktTCPSend (TCP Socket Send) ........................... 2-1110 SktUDP Create (Create UDP Socket) ..................... 2-1081 SktUDPRcv (UDP Socket Receive) ........................ 2-1089 SktUDPSend (UDP Socket Send) .......................... 2-1092 SQRT (Square Root) ................................................ 2-204 Square Root .............................................................. 2-204 SR (Set-Priority Keep) ................................................ 2-53 StackDel (Delete from Stack) .................................... 2-512 StackFIFO (First In First Out) .................................... 2-507 StackIns (Insert into Stack) ....................................... 2-510 StackLIFO (Last In First Out) .................................... 2-507 StackPush (Push onto Stack) ................................... 2-498 Start EtherCAT Packet Monitor ................................. 2-942 Start Serial Line Monitoring ..................................... 2-1363 Stop EtherCAT Packet Monitor ................................. 2-948 Stop Serial Line Monitoring ..................................... 2-1368 String Length ............................................................. 2-562 StringCRC16 (Calculate Text String CRC-16) .......... 2-544 StringCRCCCITT
(Calculate Text String CRC-CCITT) ....................... 2-542 StringLRC (Calculate Text String LRC) .................... 2-540 StringSum (Checksum Calculation) .......................... 2-538 STRING_TO_**
(Text String-to-Bit String Conversion Group) ......... 2-301 STRING_TO_**
(Text String-to-Integer Conversion Group) ............. 2-299 STRING_TO_**
(Text String-to-Real Number Conversion Group) ... 2-303 StringToAry (Text String-to-Array Conversion) ......... 2-463 StringToFixNum
(Text String-to-Fixed-decimal Conversion) ............ 2-453 SUB (Subtraction) ..................................................... 2-174 SUB_DATE_DATE (Subtract Date) .......................... 2-611 SubDelimiter (Get Text Strings Minus Delimiters) .... 2-588 SUB_DT_DT (Subtract Date and Time) .................... 2-612 SUB_DT_TIME (Subtract Time from Date and Time) 2-614 SubOU
(Subtraction with Overflow Check) ......................... 2-177 SUB_TIME (Subtract Time) ...................................... 2-606 SUB_TOD_TIME (Subtract Time from Time of Day) 2-608 SUB_TOD_TOD (Subtract Time of Day) .................. 2-610 Subtract Date ............................................................ 2-611 Subtract Date and Time ............................................ 2-612 Subtract Time ............................................................ 2-606 Subtract Time from Date and Time ........................... 2-614 Subtract Time from Time of Day ............................... 2-608 Subtract Time of Day ................................................ 2-610 Subtraction ................................................................ 2-174 Subtraction with Overflow Check .............................. 2-177

Swap (Swap Bytes) ................................................... 2-404 Swap Bytes ............................................................... 2-404
T
Table Comparison ..................................................... 2-111 TableCmp (Table Comparison) ................................. 2-111 TAN (Tangent in Radians) ........................................ 2-198 Tangent in Radians ................................................... 2-198 Task_IsActive (Determine Task Status) .................. 2-1498 TCP Socket Receive ............................................... 2-1107 TCP Socket Send ................................................... 2-1110 Test A Bit .................................................................... 2-47 Test A Bit NOT ............................................................ 2-47 TestABit (Test A Bit) ................................................... 2-47 TestABitN (Test A Bit NOT) ........................................ 2-47 Text String Comparison Equal .................................. 2-100 Text String Comparison Greater Than ...................... 2-104 Text String Comparison Greater Than or Equal ....... 2-104 Text String Comparison Less Than .......................... 2-104
I Text String Comparison Less Than or Equal ............ 2-104
Text String Comparison Not Equal ........................... 2-102 Text String-to-Array Conversion ............................... 2-463 Text String-to-Bit String Conversion Group .............. 2-301 Text String-to-Fixed-decimal Conversion .................. 2-453 Text String-to-Integer Conversion Group .................. 2-299 Text String-to-Real Number Conversion Group ........ 2-303 Time of Day-to-Text String Conversion ..................... 2-459 Time-proportional Output .......................................... 2-735 TimeProportionalOut (Time-proportional Output) ..... 2-735 Timer (Hundred-ms Timer) ....................................... 2-141 Timer Pulse ............................................................... 2-135 TimeToNanoSec (Convert Time to Nanoseconds) ... 2-640 TimeToSec (Convert Time to Seconds) .................... 2-641 TO_** (Bit String Conversion Group) ........................ 2-308 TO_** (Integer Conversion Group) ........................... 2-306 TO_** (Real Number Conversion Group) ................. 2-310 ToAryByte (Conversion to Byte Array) ...................... 2-475 TodToSec (Convert Time of Day to Seconds) .......... 2-633 TodToString
(Time of Day-to-Text String Conversion) ............... 2-459 TOF (Off-Delay Timer) .............................................. 2-132 ToLCase (Convert to Lowercase) ............................. 2-573 TON (On-Delay Timer) .............................................. 2-126 ToUCase (Convert to Uppercase) ............................ 2-573 TP (Timer Pulse) ....................................................... 2-135 TraceSamp (Data Trace Sampling) .......................... 2-806 TraceTrig (Data Trace Trigger) ................................. 2-809 TransBits (Move Bits) ................................................ 2-361 Transfer EtherCAT Packets ...................................... 2-952 Trim String Left ......................................................... 2-575 Trim String Right ....................................................... 2-575 TrimL (Trim String Left) ............................................. 2-575 TrimR (Trim String Right) .......................................... 2-575 TRUNC (Truncate) .................................................... 2-316 Truncate .................................................................... 2-316 Truncate Date and Time ........................................... 2-662 Truncate Time ........................................................... 2-658 Truncate Time of Day ............................................... 2-666

NJ/NX-series Instructions Reference Manual (W502)

Index-9

Index
TruncDt (Truncate Date and Time) ........................... 2-662 TruncTime (Truncate Time) ....................................... 2-658 TruncTod (Truncate Time of Day) ............................. 2-666
U
UDP Socket Receive ............................................... 2-1089 UDP Socket Send ................................................... 2-1092 Unite8Bit_** (Byte Data Join Group) ......................... 2-473 UniteDigit_** (Four-bit Join Group) ............................ 2-469 UniteReal
(Combine Real Number Mantissa and Exponent) .. 2-444 Unlock (Unlock Tasks) ............................................ 2-1500 Unlock Tasks ........................................................... 2-1500 Unsigned Integer-to-BCD Conversion Group ............ 2-245 Up (Up Trigger) ........................................................... 2-44 Up Trigger ................................................................... 2-44 Up-counter ................................................................. 2-150 Up-counter Group ...................................................... 2-152 Up-down Counter ...................................................... 2-155 Up-down Counter Group ........................................... 2-159 Upper/Lower Deviation Alarm Group ........................ 2-756 Upper/Lower Deviation Alarm with Standby Sequence
Group ...................................................................... 2-761 Upper/Lower Limit Alarm Group ................................ 2-752 UPPER_BOUND (Get Last Number of Array) ........... 2-491 UTF-8 to SJIS Character Code Conversion .............. 2-422 UTF8ToSJIS
(UTF-8 to SJIS Character Code Conversion) ......... 2-422
W
While ........................................................................... 2-34 WHILE (While) ............................................................. 2-34 Write EtherCAT CoE SDO ........................................ 2-934 Write File ................................................................. 2-1403 Write IO-Link Device Object .................................... 2-1015 Write NX Unit Object ................................................. 2-980 Write Variable Class 3 Explicit ................................ 2-1045 Write Variable to File ............................................... 2-1374 Write Variable UCMM Explicit ................................. 2-1064 WriteNbit_** (N-bit Write Group) ............................. 2-1488
X
XOR (Logical Exclusive OR) ..................................... 2-320 XORN (Logical Exclusive NOR) ................................ 2-323
Z
Zone (Dead Zone Control) ........................................ 2-342 Zone Comparison ...................................................... 2-109 ZoneCmp (Zone Comparison) ................................... 2-109

Index-10

NJ/NX-series Instructions Reference Manual (W502)

OMRON AUTOMATION AMERICAS HEADQUARTERS · Chicago, IL USA · 847.843.7900 · 800.556.6766 · www.omron247.com

OMRON CANADA, INC. · HEAD OFFICE Toronto, ON, Canada · 416.286.6465 · 866.986.6766 · www.omron247.com
OMRON ELECTRONICS DE MEXICO · HEAD OFFICE México DF · 52.55.59.01.43.00 · 01-800-226-6766 · mela@omron.com
OMRON ELECTRONICS DE MEXICO · SALES OFFICE Apodaca, N.L. · 52.81.11.56.99.20 · 01-800-226-6766 · mela@omron.com
OMRON ELETRÔNICA DO BRASIL LTDA · HEAD OFFICE São Paulo, SP, Brasil · 55.11.2101.6300 · www.omron.com.br

OMRON ARGENTINA · SALES OFFICE Cono Sur · 54.11.4783.5300
OMRON CHILE · SALES OFFICE Santiago · 56.9.9917.3920
OTHER OMRON LATIN AMERICA SALES 54.11.4783.5300

OMRON EUROPE B.V. · Wegalaan 67-69, NL-2132 JD, Hoofddorp, The Netherlands. · +31 (0) 23 568 13 00 · www.industrial.omron.eu

Authorized Distributor:

Controllers & I/O · Machine Automation Controllers (MAC) · Motion Controllers · Programmable Logic Controllers (PLC) · Temperature Controllers · Remote I/O
Robotics · Industrial Robots · Mobile Robots
Operator Interfaces · Human Machine Interface (HMI)
Motion & Drives · Machine Automation Controllers (MAC) · Motion Controllers · Servo Systems · Frequency Inverters
Vision, Measurement & Identification · Vision Sensors & Systems · Measurement Sensors · Auto Identification Systems
Sensing · Photoelectric Sensors · Fiber-Optic Sensors · Proximity Sensors · Rotary Encoders · Ultrasonic Sensors
Safety · Safety Light Curtains · Safety Laser Scanners · Programmable Safety Systems · Safety Mats and Edges · Safety Door Switches · Emergency Stop Devices · Safety Switches & Operator Controls · Safety Monitoring/Force-guided Relays
Control Components · Power Supplies · Timers · Counters · Programmable Relays · Digital Panel Meters · Monitoring Products
Switches & Relays · Limit Switches · Pushbutton Switches · Electromechanical Relays · Solid State Relays
Software · Programming & Configuration · Runtime

W502I-E3-24 Note: Specifications are subject to change.

© 2018 Omron. All Rights Reserved.

Printed on recycled paper.

Printed in U.S.A.