iNspect Express
Scripting Guide
iNspect Express Scripting Guide 1 Version 1.6; 2019-4-29
Notice
iNspect Express Scripting Guide
Document Number 405-00037-00
Copyright 2019 Teledyne Imaging.
All rights reserved.
All copyrights in this manual, and the hardware and software described in it, are the
exclusive property of Teledyne Imaging and its licensors. Claim of copyright does
not imply waiver of Teledyne Imaging or its licensors other rights in the work. See
the following Notice of Proprietary Rights.
NOTICE OF PROPRIETARY RIGHTS
This manual and the related products are confidential trade secrets and the
property of Teledyne Imaging and its licensors. Use, examination, reproduction,
copying, transfer and/or disclosure to others of all or any part of this manual and
the related documentation are prohibited except with the express written consent of
Teledyne Imaging
The information in this document is subject to change without notice. Teledyne
Imaging makes no representations or warranties with respect to the contents of this
manual and specifically disclaims any implied warranties of merchantability or
fitness for a particular purpose. Teledyne Imaging assumes no responsibility for
errors or omissions in this document.
iNspect, Sherlock, and the Teledyne Imaging logo are trademarks of Teledyne
Imaging. All other trademarks are the property of their respective owners.
Teledyne Digital Imaging US, Inc.
Information:
[email protected] Support:
[email protected] Web: http://www.teledynedalsa.com/visionsystems
700 Technology Park Drive
Billerica, MA, USA 01821
Tel 1.978.670.2002 Fax 1.978.670.2010
iNspect Express Scripting Guide 2 Version 1.6; 2019-4-29
Table Of Contents
Introduction About Scripting in iNspect Express ……………………...... 5
Product Support ……………………...... 5
The Script Panel Accessing the Script Tool ……………………...... 6
Variable Tree List ……………………...... 7
Function List ……………………...... 8
Basic Script Editor ……………………...... 9
Full Script Editor ……………………...... 10
Scripting Basics ……………………...... 11
About Variables Special Global Variables ……………………...... 12
Persistent Variables ……………………...... 13
Variable Basics ……………………...... 13
Variable Listing ……………………...... 14
About Functions Pre-ordered Functions ……………………...... 15
Event Functions ……………………….. 15
Periodic Function ……………………...... 16
User Function ……………………...... 17
Delayed Event Function ……………………...... 17
PLC Change of State Function ……………………….. 17
Input State Change Function ……………………….. 18
Com Tcp/IP Command Handler Function ……………………….. 18
Function Timing ……………………….. 19
Function Listing ……………………….. 20
- Math Functions ……………………….. 20
- String and Character Functions ……………………….. 20
- Tool Statistics & Attribute Functions ……………………….. 21
- Digital IO & Acquisition Control Functions ……………………….. 23
- Logging Functions ……………………….. 26
- Comm / TCP IO Functions ……………………….. 27
iNspect Express Scripting Guide 3 Version 1.6; 2019-4-29
Bit Functions ……………………...... 27
System & Misc. Functions ……………………...... 28
String Editor String Edit Window ……………………...... 31
String Formatting Reference ……………………...... 32
Script Examples Manipulating Outputs ……………………...... 34
Solution Switching ……………………...... 36
Trigger Control ……………………...... 38
ReTrigger Example ……………………...... 39
Customizing Text in the Monitor ……………………...... 40
Manipulating Text in the Graphics Tool ……………………...... 43
Hide and Show Variables ……………………...... 44
Disable and Enable Tools ……………………...... 44
Sensor Control ……………………...... 45
Image Logging ……………………...... 47
Result (data) Logging ……………………...... 48
Using the Start and Stop Functions ……………………...... 50
Communicating using Strings ……………………...... 52
Using Arrays ……………………...... 54
Using Arrays for Communication ……………………...... 57
Manipulating Bits ……………………...... 58
Subtracting Images 60
iNspect Express Scripting Guide 4 Version 1.6; 2019-4-29
Introduction
About Scripting in iNspect Express
Scripting offers greater application flexibility by allowing users to define or manipulate
system control and integration features. The Script Tool differs from the rest of the
iNspect Express GUI in that it supports the use of functions and more traditional
programming constructs.
Scripting is not always required for basic applications that only require a pass/fail
decision output, but it is widely used for communicating with 3rd party devices over
Ethernet or serial RS-232.
An in-depth knowledge of software design is not a prerequisite for using the Scripting
Tool, but a basic understanding of process control is essential.
Support
In addition to this user manual, help with scripting is available from the following:
1. Online help: Fingertip help is available on every screen (panel) of the iNspect
Express User Interface
2. Self help material and sample job files are included on the BOA CD
3. Call, fax or email your local Teledyne Imaging representative who sold you the
product
4. Factory support is available at [email protected]
iNspect Express Scripting Guide 5 Version 1.6; 2019-4-29
The Script Panel
Accessing the Script Tool
The Script Tool is mostly used for control and communication, which is why it is accessed
through the control panel after the tools have been defined. Simply follow the clicks as
shown below:
iNspect Express Scripting Guide 6 Version 1.6; 2019-4-29
Inside the script panel there are 3 sections. The control panel on the left side contains a
variable tree list, a function list and a basic script editor. On the right side are the image
window and the function equation manager.
The Variable Tree List
The variable tree at the top of the control panel lists all of the variables available to the
script tool, namely:
• Tool outputs from user-defined measurements (i.e. MS1.Result)
• Predefined keywords (control words such as SOLUTION)
• Discrete I/O (physical inputs and outputs available to the device )
• PLC or communication registers. (user defined connections)
• User variables
Variables can have Boolean meaning, such as TRUE/FALSE or ON/OFF, or they can
store numbers or strings of user defined information.
iNspect Express Scripting Guide 7 Version 1.6; 2019-4-29
The Function List
The Function list is available in the middle of the control panel in the form of a drop-down
list. By default it contains predefined functions for solution initialization, as well as pre and
post processing. These functions are empty when starting a new solution, meaning they
do nothing until you add something to them.
To edit a function, select it in the function drop down list and add instructions using the
basic or full script editors available.
To add functions, click the “New” button and follow instructions in the popup menu. Added
functions will appear in the drop down list above. Similarly, remove unwanted functions by
selecting them in the drop down list and clicking the “Del” button.
The “New Function” interface shown above will be described in a later section.
iNspect Express Scripting Guide 8 Version 1.6; 2019-4-29
The Basic Script Editor
Users new to programming can start with the simple script editor provided at the bottom
of the control panel. It provides the basic means to add instructions to a function. Simply
select the function to edit from the function drop down list, enter the condition, variable
name and value, then click “Add Equation”. The new instruction will be added to the
selected function and displayed in the Equation Manager on the right side of the panel
(shown at the bottom of this page).
The above example shows how to add an instruction to the “Post Image Process”
function. This instruction will send the cumulative pass count to a predefined TCP/IP
connection if the current inspection result = pass.
When using the basic script editor, variables may be selected from the variable tree and
dragged into the active edit boxes. Clicking the “New Name” button will add a user
defined variable (i.e. User0) that is not currently defined in the function. Clicking the
“Evaluate” button will process the equation and show you the result.
iNspect Express Scripting Guide 9 Version 1.6; 2019-4-29
The Full Script Editor
The full script editor is accessed by clicking the “Free Edit” button at the bottom of the
Equation Manager. When clicked, the free editor panel will pop-up as shown at the
bottom of this page.
Click to open full script
editor
Equations associated with a function can be exported to a user defined text file by
clicking the “Export” button. Similarly, equations stored in a local text file can be imported
into a selected function by clicking the “Import” button. This is a convenient method of
sharing scripts or script snippets (application specific code) across solutions.
The full script editor offers much more flexibility for designing and editing scripts. Most
users quickly migrate to this method over the basic editor described previously.
iNspect Express Scripting Guide 10 Version 1.6; 2019-4-29
The full editor provides drop-down menus for quick access to functions, variables,
equation operators and program flow commands. A string editor is also included to
simplify the formatting of communication strings to external devices. Clicking on a drop-
down feature from the list will add it to the script. Manually add parameters and
associated control statements to each script as required.
The “Check Syntax” button checks the “programmatic grammar” of the individual strings,
but cannot parse the statements for runtime context errors that may occur outside this
window. The bottom pane may show syntax error messages. You can click on a message
to highlight the related line of code in the upper pane.
Scripting Basics
1. Comment your code. This will make it much easier for you to debug should you need
to come back to the solution at a later time. You can add comment lines using the
prefix "//" (two forward slashes) for example: // Initialize the x array
2. All of your expressions, equations, and variables are saved in the Solution file, and
persist when the Solution file is reloaded.
3. Statements are formed in a plain algebraic format, for example: a = b+c
4. Functions are called simply in the form: z = aFunctionName(param1, param2)
5. Variable names have a limit of 60 characters
6. A line of script has a limit of 256 characters. Numbers of lines are only limited by
available memory.
7. Max time for the Pre-image Process function is 100ms
8. Max time for Post Image Process function is 300ms on BOA (1000ms on other
platforms)
9. Max time all other functions are 1000ms.
10. The time a Script takes can be reduced significantly by sending an array of data
verses multiple read/writes (time to send an array is the same as a single piece of
data). Bit functions can also be used.
11. It is good practice to always close “If” statements with “Endif”, even though this is not
required for single command statements. This makes code easier to read and debug.
12. Once created, script variables will persist even if you delete them inside a script. A
variable can be selected and deleted from the variable tree list or by starting a new
solution.
IMPORTANT: Editing Scripts and measurement tools changes the "run mode", and
disables solution switching. In some cases, editing scripts can interrupt normal
communication with PLCs and peripherals. Save your Solution and then reload it (same
solution) if you encounter problems. Loading a solution resets the run mode; unless you
select the "Load for Edit/Disable switching" option.
iNspect Express Scripting Guide 11 Version 1.6; 2019-4-29
About Variables
There are 3 classes or types of variables that can be used in a script:
1. Global device variables – variables associated with external hardware such as I/O
2. Global control variables – variables that provide system wide status or control
3. Local user variables – variables associated with tools or functions defined by the user
Special Global Variables
Some special variables are not visible in the variable tree or the free editor. These
variables are as follows:
• Solution – Global variable that contains the current solution number.
• RelearnIndex - Specifies an external input that is sampled when a trigger occurs to
initiate a runtime tool relearn.
• ShowPreprocessed - Enables (=1) or disables (=0) display of preprocessing in ROI
at runtime
• RelearnIndex - uses one of the General Purpose Inputs to trigger retraining or
relearning specific tools (Match, Barcode, 2D-Code, Locator). RelearnIndex=1 will
execute a relearn (in the next acquired image) when GPI(1) is asserted. This statement
should be added in the Solution Initialize function. To assign a tool to relearn, create a
new Relearn variable. For example, to assign Barcode1 to be retrained,
Bar1.Relearn=1. The Barcode tool will be retrained (in the next image) when the input
assigned by RelearnIndex GPI(1) is asserted.
NOTE: The inputs on the BOA read 1 when nothing is connected, or when the input is
lower than the logic threshold. You must be careful to connect the input so that GPI(1) will
only read 1 when relearn is desired, or use the RelearnOnZero variable.
• RelearnOnZero - RelearnOnZero =1 forces relearn to occur when the defined Relearn
input (RelearnIndex) is 0, not 1. This statement should be added in the Solution
Initialize function. NOTE: GPI(0) is the BOA trigger input. GPI(1) is the BOA IN0.
The Result variable returns the result from each defined camera, as well as the overall
inspection result. Result.0 variables return the result before an action is decided (i.e. it is
made available so that user-defined functions can use it to define actions).
iNspect Express Scripting Guide 12 Version 1.6; 2019-4-29
Result=1 (PASS)
Result=2 (RECYCLE)
Result=3 (FAIL)
You can override (not typical for most applications) the composite result, by adding
variables "PASS", "RECYCLE", "FAIL", (must be all capitals) and setting their values
to 1 (for TRUE) or 0 (for FALSE).
NOTE: In formation of (creating or composing) the final Result, FAIL supersedes
RECYCLE, and RECYCLE supersedes PASS. Put your tests for PASS, FAIL,
RECYCLE in the "Post Image Processing" function.
Persistent Variables
When a solution is saved, any associated variables are saved also. When a solution is
loaded, only its associated variables are loaded. This means that variables
associated with the previous solution will be deleted unless they are also saved in
the new solution. The exception to this rule is Persistent Variables. These special
variables will persist even if the solution that created them is replaced by a different
solution. Persistent variables are therefore used more for system (BOA) variables as
opposed to solution specific variables. Persistent variables will persist until the BOA
camera is power cycled. Persistent variables are defined with a Prog prefix and can
also be saved in a solution file (i.e. Prog.myvariable)
Variable Basics
1. Use square brackets for variable names, especially names with spaces in them.
Notice that variable names inserted or dragged into a field, are enclosed in brackets.
2. All of your expressions, equations, and variables are saved in the Solution file, and
persist when the Solution file is reloaded.
3. User added variables belong to the current Solution. Loading a different Solution will
cause your user variable set to be replaced with the set belonging to that new Solution.
4. There are many pre-defined variables with special meaning for use in scripts. You can
also create your own variables. Referencing a variable automatically creates or
instantiates that variable. A separate step for creating or declaring, is not necessary.
5. A complete listing of predefined variables follows on the next page
iNspect Express Scripting Guide 13 Version 1.6; 2019-4-29
Variable Listing
• Result.0 - the value of Result, before it is output. This allows equations to evaluate the
Result, before the decision is sent to the monitor, decision I/O and other mechanisms.
Result.0 returns 3 values: 1=Pass, 2=Recycle, 3=Reject.
• Result - the result of all measurements (the "composite result"). This result is sent to
the Monitor, decision I/O and other communication mechanisms (such as PLC,
Ethernet, serial port, etc.). Result returns 3 values: 1=Pass, 2=Recycle, 3=Reject. Each
measurement also has a Result (i.e. L1.Result).
• Global.GPI[#] - a general purpose input. The Camera treats and evaluates all inputs as
a steady state logic input. NOTE: GPI(0) is the BOA Trigger input. GPI(1) is the BOA
IN0 input. When using the PL-200, GPI(8) is the Trigger input.
• Global.GPO[#] - a general purpose output. Normally, the outputs are held high or low,
until the next result is available. (The Pass/Recycle/Fail decision outputs are pulsed.)
You can use the pulse function or use the Delayed Event Function to create a pulse
output.
• Global.RunMode - the current run-state or running mode. 0=running, 1=stopped.
• Global.FrameCount - number of frames or images acquired since a Solution was
loaded, or since the statistics was reset ("Reset Statistics" button on the Monitor panel).
• Global.Missed - number of missed parts or frames.
• Global.ContinuousMissed - number of parts or frames missed in a row, or one after
another.
• Global.PassCount - the value of the Pass counter, or the number of Passed parts.
• Global.FailCount - the value of the Fail counter, or the number of Failed parts.
• Global.RecycleCount - the value of the Recycle counter, or the number of Recycled
parts.
• Global.ContinuousPassCount - the number of parts or frames passed in a row, or
one after another.
• Global.ContinuousFailCount - the number of parts failed in a row, or one after
another.
• SolutionPollRate – used with the PL-200. Polls the solution index inputs at the
specified frequency to determine if a solution switch is requested.
• CameraSrcId – used only with multiple camera configurations (PCs or Vision Systems),
not with the BOA series. Only appears in Asynchronous (ASYNC) acquisition mode.
Identifies which camera supplied the current image.
iNspect Express Scripting Guide 14 Version 1.6; 2019-4-29
About Functions
Variables are manipulated using functions. Functions are made up of equations or
instructions that affect an outcome or result. Most functions can be shared or called by
other functions (like subroutines). Some functions are executed in order (pre-ordered
functions), while others are based on a user defined event, such as a time interval or
transition on a Global Input. Pre-ordered functions are a special class of functions that
execute in a pre-defined order. They can call other functions, but can not be called by
other functions.
iNspect Express includes a library of pre-defined functions for analysis, system control
and communication. A complete listing of predefined functions starts on page 20.
Pre-Ordered Functions
Every solution has 3 pre-ordered functions which execute in the order below:
1. Solution Initialize – called immediately after a solution is loaded. Typically used to
initialize variables to a known state
2. Pre-Image Processing – called immediately after a new image is received, but before
processing begins. Can be used to handshake with other devices or control external
I/O.
3. Post-Image Processing – Called immediately after processing. Typically used to
formulate results and communicate with external devices.
Event Functions
Event functions offer design flexibility and control for applications that are based on
asynchronous events, such as state changes in PLC registers or transition changes on
input pins. Event functions do not execute in a predefined order (except for delay
functions), but get called when the defining event occurs. When using event functions,
care should be taken to avoid unintended conditions associated with asynchronous
events.
Click on the button next to the function list to open the “New Function” setup
screen.
iNspect Express Scripting Guide 15 Version 1.6; 2019-4-29
The scripting interface supports 6 types of event functions. Simply define the event that
best suits your application need and click the “Add” button. The new empty function will
then appear in the function list ready for editing.
If the “Make Added Function Global” is checked when you create a new function, that
function becomes available or common to, all new solutions created after. It is not
available to solutions created before. Edits are shared across solutions. You can only
delete a Global function in the solution it was originally created in.
Periodic Function
This is a function that is called at a fixed user defined time interval. The Periodic function
is often used to sample external Inputs or PLC registers for the following:
• Checking for a solution switch action
• Providing a system online heartbeat
• Reset variables or restart inspection in the event of a STOP condition
NOTE: Accessing PLC registers can be slow (20ms per register is not unrealistic). As a
consequence, we recommend defining a periodic interval greater than 100ms for most
applications.
iNspect Express Scripting Guide 16 Version 1.6; 2019-4-29
User Function
The user function is called on demand from other functions, such as the image pre and
post processing functions. User functions perform the following purpose:
•They define application specific processing functions with parameter passing
•They provide a means to partition code into smaller, more manageable subroutines
NOTE: Every user function must include a “return()” statement
Delayed Event Function
These functions are called after a special image event occurs:
• New image is received into memory
• Processing of the current image is complete
• On a software trigger
Delayed event functions are typically used to complete I/O events that were initiated
during the image pre and post process functions. These functions are time synchronized
with pre and post image processing functions.
PLC Change of State Function
These functions are called when a change of PLC register value or state is detected. A
PLC has to be defined for this function to work. This applies only to Ethernet/IP and
Modbus Slave PLCs (not a Modbus Master). These functions can be used for the
following:
• Handshaking and control of 3rd party equipment
• Triggering BOA to take a picture under PLC control when the object to be inspected is
in place
iNspect Express Scripting Guide 17 Version 1.6; 2019-4-29
The Input State Change Function
These functions are called when a selected Input line changes state i.e. from low to high
or high to low. These functions can be used for the following:
• I/O control
• Solution switching
• Triggering using an input line to generate a software trigger
The COM Tcp/IP Command Handler Function
Defines a group of functions or statements that are called to handle a specific command
received on a specific COM Port or TCP/IP Connection.
When the Command Handler Functions are used, the command format used on the
connection must follow the following rules:
• All commands are ASCII text (binary data is not allowed).
• The Command format is:
command [optional parameters separated by spaces] (carriage return and
/or line feed)
Note:
"\r" = carriage Return character.
"\n" = Line Feed character.
The Command Handler function is added in the "New Function" menu, and is associated
with the specified connection and command. Where "Variable Name" specifies the
connection, and "Command" specifies the command.
There are 3 special variables which can be used in the command handler function:
argc - the number of command parameters received.
argv - an array of strings which contain the parameters received.
comvar - a special variable which can be passed to the function WriteString to
specify a destination which is the same as the source of the command
received.
The checkbox “Use As Prefix” makes the “command” a prefix to the value. This is to
accommodate some devices with specialized syntax. If the command name is read, and
the value is ID, “as prefix” means a command would be “readID”, instead of “read ID”.
iNspect Express Scripting Guide 18 Version 1.6; 2019-4-29
Function Timing
Image Acquire Image Pre Process Process Image Post Process
Pre-Ordered Functions
time
Sync Event Functions
Image receive delay Image process delay
start end
Asynchronous Periodic, I/O or PLC Event Functions
The above diagram depicts the timing associated with functions. Pre-ordered functions
are synchronized to the start and of end of each inspection. The special event functions
image receive delay and image process delay are also synchronized. Other functions
shown in the blue box may be used to control asynchronous events.
iNspect Express Scripting Guide 19 Version 1.6; 2019-4-29
Function Listing
Function Listing
Note: Please consult the On-Line Help for the most up-to-date listing.
Math Functions
• sin(radians) - result is the sine of the argument radians. The argument must be in
radians.
• cos(radians) - result is the cosine of the argument radians. The argument must be in
radians.
• tan(radians) - result is the tangent of the argument radians. The argument must be in
radians.
• asin(x) - result is the arcsine of x in the range -p/2 to p/2 radians, where: -1 <= x <= 1.
• acos(x) - result is the arccosine of x in the range -p/2 to p/2 radians, where: -1 <=x <=1.
• atan(x) - result is the arctangent of x in the range -p/2 to p/2 radians.
• atan2(y, x) - result is the arctangent of y/x in the range -p to p radians.
• exp(x) - result is the exponential value of x.
• logn(x) - result is the natural logarithm of x.
• sqrt(x) - result is the square root of x.
• pow(x, y) - result is x raised to the power of y.
String and Character Functions
The following String functions were added to find numeric characters in a string (the
result of a OCR, barcode or 2-D code read), and convert to numbers (for passing to other
equations or peripherals). Other uses are possible.
• Find(substring, inString) - finds the first occurrence of substring in the input inString,
and returns the zero-based index location of the first matching character. Returns -1 if
no match was found. Spaces are counted.
Example: idx = find("00", "SM WRA 0057 4321") returns 7, or sets idx = 7.
• Substring(string, startIndex, length) - forms a sub-string from the input string,
beginning at startIndex (zero-based) of length characters. If length = 0 all characters to
the end of the string are included in the sub-string.
Example: s2 = substring("SM WRA 0057 4321" , 9, 0) returns string "57 4321" in s2.
• StrLen(string) - returns the number of characters in a string.
• GetChar(string, index) - returns the character located at index (zero-based) in the
string.
• SetChar(string, index, char) - sets the character in string, located at index (zero-based),
to char.
• int(string) - converts the input string (of numbers) to an integer value.
Example: x = int("33") sets x = 33
iNspect Express Scripting Guide 20 Version 1.6; 2019-4-29
• float(string) - converts the input string (of numbers) to a floating point value.
Example: x = float("57.499") sets x = 57.499
• char(int) - converts the input integer int to a character.
• string(int) - converts the input number to a string, such as an integer int(base 10) or a
floating point number. A floating point uses same formatting as WriteFormatString.
Example: LengthStr = string(“[L%0.3f]”)
• FormatString(stringForm) – returns a formatted string, using the format in the
argument stringForm. stringForm can be composed with the String Editor.
Example: the statement str1 = FormatString(“[IntenAvg%.4f]”) results in a string
“55.7015” (returned in str1).
Tool Statistics and Attribute Functions
• GetMean(measurementVar) - returns the arithmetic mean for the specified
measurement.
Example: L1Mean = GetMean ( L1 )
• GetStdDev(measurementVar) - returns the standard deviation for the specified
measurement.
Example: L1StdDev = GetStdDev ( L1 )
• GetMin(measurementVar) - returns the minimum value which has occurred for the
specified measurement.
Example: L1Min = GetMin ( L1 )
• GetMax(measurementVar) - returns the maximum value which has occurred for the
specified measurement.
Example: L1Max = GetMax ( L1 )
• ResetVarStats(measurementVar) - resets the measurement statistics (min, max, mean,
std dev) for the specified measurement. All prior data samples for the measurement are
cleared out for the statistical calculations.
Example: ResetVarStats ( L1 )
• GetToolType(measurementVar) - returns a number indicating the type of measurement
tool, for the specified variable.
Example: L1type = GetToolType( L1 ) variable L1type returns the value 6.
• GetNthToolType(varIndex, CamID) - returns a number indicating the type of
measurement tool, for the specified variable index and camera ID. Returns zero if no
tool exists for varIndex and camID (0 for BOA)
varIndex – 0 to (number of tools minus 1) which exist, for the specified camera.
• GetToolName(varIndex, camID) - returns the simple name (no camera prefix) of the
measurement tool, for the specified variable index and camera ID (0 for BOA)
varIndex – 0 to (number of tools minus 1) which exist, for the specified camera.
iNspect Express Scripting Guide 21 Version 1.6; 2019-4-29
• RequestRelearn(measurementVar) - causes measurementVar to be relearned on the
next image.
BOA Example: RequestRelearn(Bar)
Vision System Example: RequestRelearn([Camera01.Bar)
• SetTolerances(measurementVar, toleranceArrayIn) - sets the 5 tolerance "pivot points"
for the specified measurement variable.
measurementVar – variable name.
toleranceArrayIn – 5 element array of tolerance values. (as shown below,
underGetTolerances).
• GetTolerances(measurementVar, toleranceArrayOut) - gets the 5 tolerance "pivot
points" for the specified measurement variable.
measurementVar – variable name.
toleranceArrayOut – 5 element array of tolerance values:
Index Content with Recycle Enabled Content with Recycle Disabled
0 Minimum recycle value Minimum pass value
1 Minimum pass value 0
2 Perfect value Perfect value
3 Maximum pass value 0
4 Maximum recycle value Maximum pass value
• SetMatchString(measurementVar, perfectMatch) – set a string measruementVar to a
new value perfectMatch. Used only for measurements that return a string (barcode, 2D
barcode, OCR) to set a new “perfect” value.
• SetNthTolerances(varIndex, camID, toleranceArrayIn) - sets the 5 tolerance "pivot
points" for the specified variable index and camera ID (0 for BOA)
varIndex – 0 to (number of tools minus 1) which exist, for the specified camera.
toleranceArrayIn – 5 element array of tolerance values. (as shown above, under
GetTolerances).
• GetNthTolerances(varIndex, camID, toleranceArrayIn) - gets the 5 tolerance "pivot
points" for the specified variable index and camera ID (0 for BOA)
varIndex – 0 to (number of tools minus 1) that exist
toleranceArrayOut – 5 element array of tolerance values. (as shown above, under
GetTolerances).
• GetToolValue(toolName) - returns the measurement value for the tool. The simple tool
name ("L1") is passed.
Example: value = GetToolValue ( "L1" )
• GetToolResult(toolName) - returns the Result value for the tool. The simple tool name
("L1) is passed.
Example: value = GetToolResult ( "L1" )
iNspect Express Scripting Guide 22 Version 1.6; 2019-4-29
• GetVarDimension(varName) - returns the number of children variables of the variable
varName.
• SetToolText(toolName, toolText) – sets or changes the text toolText shown in the
Graphics Tool toolName (Express only).
• SetToolPenColor(toolName, red, green, blue) – set or change the outline of the
Graphics Tool toolName to the value of red, green, blue. Express only.
• SetToolFill(toolName, red, green, blue) – set or change the fill color in the Graphics
Tool toolName to the value of red, green, blue. Express only.
• WriteVar(narName, value) - write a value to a script variable.
varName - the name of the variable to write to.
value - the value to write to the variable. Example: WriteVar("InputThreshold", 4.5)
• Sort(keyVarName, ascend, followVarNames) – sort the array specified by keyVarName
in the direction of ascend.
ascend – 0 = sort in descending order. 1 = sort in ascending order.
followVarNames – an optional list of the names of array variables which are to be
sorted in the same remapping as keyVarName. Example if keyVarName’s 0 index
value was relocated to index 5, then the same re-mapping will occur for all of the
followVarNames arrays.
• ReadVar(varName) - Read a script variable's value.
varName - the name of a script variable.
• DeleteVar(varName) – delete the variable varName. This is useful to remove variable
left by a previous script or function.
• GetNumElements(varName) – get the actual dimension or number of elements for a
measurement varName that creates an array of values.
• EnableFormat(varName, enable) – enable or disable the output of measurement
varName to the output log or script output.
enable – 0 = do not output varName. 1 = allow output of varName.
Digital IO / Acquisition Control Functions
• pulse(activeVal, offsetMillisec, durationMillisec) - generates a pulse output.
activeVal – 1=active-high pulse, 0=active low-pulse.
offsetMillisec – offset or delay from the moment this statement executes, in
milliseconds.
durationMillisec – duration of the pulse, in milliseconds.
Example: Global.GPO[1] = pulse(1,5,10)
outputs on GPO1 an active-high pulse of 10 ms duration and offset 5 ms after the
statement executes.
iNspect Express Scripting Guide 23 Version 1.6; 2019-4-29
• trigger( ) - generate an image trigger signal. The Sensor Trigger must be set to
“Software Trigger" when using this function.
• triggerCam(camID) – generates a software trigger for individual cameras when using
Asynchronous acquisition mode on a PC or vision system. Does not apply to BOAs.
camID – camera ID number: 0 to (the number of cameras minus 1).
• ReTrigger(camID) - causes re-processing the last image on the indicated camID.
camID – always 0 for the BOA.
• TriggerSource(source) - set the trigger source or trigger mode. Do not use in Solution
Initialization function. It gets overwritten by the Solution settings.
source –1=internal timer, 2=external trigger, 3=software
• NewImagesReady(CamsReady) – returns 1 if new images are ready on all cameras.
Subsequent calls retun 0 until a further new image has arrived on all cameras.
CamsReady – optional parameter to receive an array of individual cameras’ image
ready state. Sets the array element to 0 if the corresponding camera image is ready.
• SetExposure(exposureTimeMilliseconds) - sets the image exposure time in
milliseconds.
Example: SetExposure(9.6) sets the exposure time to 9.6 milliseconds.
• SetCamExposure(expoMillisec, camID) – sets the image exposure in milliseconds for
the specified camera in a multi-camera vision system.
• SetBrightness(percentX100) - sets the image brightness. The value is a percent, times
100: a value of 60 is 60%.
• SetCamBrightness(brightness, camID) – sets the image brightness for the specified
camera in a multi-camera vision system. brightness range 1 to 100 (1% to 100%).
• SetContrast(percentX100) - sets the image contrast. The value is a percent, times 100:
a value of 60 is 60%.
• GetExposure() - returns the current value of exposure, in milliseconds.
• GetCamExposure(camID) – returns the current value of exposure in milliseconds for
the specified camera in a multi-camera vision system.
• GetBrightness() - returns the current value of brightness.
• GetCamBrightness(camID) – returns the current value of brightness for the specified
camera in a multi-camera vision system.
• GetContrast() - returns the current value of contrast.
• GetNumCameras() – returns the number of cameras connected to a Vision System.
• GetSrcCamID() – Does not apply to BOA. Used in Asynchronous acquire mode;
returns the camera ID of the camera which sourced the current image. Returns 0 for the
first camera, 1 for second camera, etc. This function should only be called from the
Post Image Process function.
iNspect Express Scripting Guide 24 Version 1.6; 2019-4-29
• SetDisplayCam(camID) – does not apply to BOA. Sets the camera to be displayed
(intended for use with Asynchronous acquisition.
camID – display mode or the camera index:
-2 = display the camera which provided the last image.
-1 = display the user selected camera.
0 = display the first camera.
1 = display the second camera
7 = display the eighth camera. “Extended” license supports up to 8 cameras.
• SetImageSource(imageSource) - sets the source of images to be processed.
imageSource - 0 = image source is the acquisition device.
1 = image source is the image file store, the subdirectory \Images in BOA.
• SetStrobeEnable(enableOrDisable) – enable or disable the strobe output.
enableOrDisable – 0 = disable strobe output, 1 = enable strobe output.
• SaveImage(fileName) – save current image to a temporary file store, for ImageSub,
ImageMin, ImageMax and TriggerOnFile. The file store is not available to other
functions.
• DeleteImage(fileName) – delete fileName in the temporary file store.
• ImageSub(inFile1, inFile2, outFile) – subtract (pixel by pixel) image inFile2 from inFile1
and save the absolute difference result to outFile in the temporary file store.
inFile1, inFile2 – use a file name or “current” for the current image.
outFile – receives the absolute difference image.
• ImageMin(inFile1, inFile2, outFile) – compare inFile1 and inFile2 and outputs the
minimum pixel values to outFile in the temporary file store.
inFile1, inFile2 – use a file name or “current” for the current image.
outFile – receives the minimum pixel image.
• ImageMax(inFile1, inFile2, outFile) – compare inFile1 and inFile2 and output the
maximum pixel values to outFile in the temporary file store.
inFile1, inFile2 – use a file name or “current” for the current image.
outFile – receives the maximum pixel image.
• TriggerOnFile(trigFile) – trigger on a specified image file. The next Post Image Process
call will have this image’s processed results.
trigFile – name of a file in the temporary file store, usually the output of ImageSub,
ImageMin or ImageMax.
• GetImageFileName(camID) – in Emulation mode, returns the full path and name of the
file that provided the current image. camID – always 0 for BOA.
• GetFrameTime(camID) – returns the timestamp in milliseconds for the latest frame
delivered by the specified camera.
iNspect Express Scripting Guide 25 Version 1.6; 2019-4-29
Logging Functions
• AppendFile(fileName, textToWrite, onClient) – append text to the end of a file.
fileName –full path name of the file to append text to.
textToWrite – the text to append to the file.
onClient – the location of the file: (Always 1 for BOA)
0 = file on the server (not supported by BOA), 1 = file on the client.
• DriveConnect(Password, UserName, ServerPath) - connect to a XP server share drive
that requires a user name and password login to access. DriveConnect should be
called before each WriteImageFile or WriteImageTools call, to ensure the remote
drive stays connected. Supported on Windows XP Only. For all other OS use FTP.
• GetFtpFileStatus() - returns the status of a file on the FTP device:
0 = idle, 1 = busy transferring file, 2 = error in ftp connection.
NOTE: The iNspect software supports ftp file logging, where iNspect is the ftp Client
logging to an ftp Server. The ftp File Name syntax is:
ftp://userName:password@host/path
The userName and password are optional in iNspect, may be required by your server.
• LogStart(fileName, onClient) - Start logging the processed frame data to the specified
CSV (comma separated values) file.
fileName – full path and file name to save CSV data to. For Example,
C:\Logs\iHistlog119200614.csv
onClient – if 0, save to file on server (not supported by BOA); if 1, save to file on client
(always 1 for the BOA).
• LogStop( ) - Stop logging data that was started by a logstart call.
• LogImage(fileName) - saves the image to a file. Only works if image logging is
enabled. Allows you to substitute a different name for one image. The image log reverts
to the name defined in the Setup Image Logging panel after one image.
fileName – a file name to save the image to.
PC or BOA Emulator: The paths and extension are taken from Setup Image Logging.
BOA: Full path, name and extension required. Directory must exist already.
• WriteImageFile(fileName, camID) - To be called only from the "Post Image Process"
function, will write the current image from the camera specified by camID to the
fileName specified.
camID – always 0 for the BOA.
fileName – full path of file to save.
• WriteImageTools(fileName, camID) - writes an image file including the tool graphics.
fileName – full path of file to save.
camID – always 0 for the BOA.
iNspect Express Scripting Guide 26 Version 1.6; 2019-4-29
Comm / TCP IO Functions
• Disconnect(comVar) – force a disconnect on the connection specified by comVar.
• IsConnected(comVar) - Determines the connection state of the TCP/IP connection
specified by comvar. Returns 1 if connected. Returns 0 if disconnected.
• ReadByte(comVar) - Reads the next byte from the TCP/IP connection specified by
comVar if one is available, otherwise returns 0 immediately.
• ReadString(comVar, endingChar) - Reads a string from the TCP/IP connection
specified by comVar if one is available, otherwise returns an empty string immediately.
endingChar – Specifies the char which must have been received to signal the end of a
received string.
• SendEmail(ToEmailAddress, Subject, MsgBody) – send an email to the
ToEmailAddress. You must set your local email information with SetEmailInfo before
using this function.
• SendEmailInfo(smtpServer, myEmailAddress) – set your local email information. This
information must be set before calling the SendEmail function.
• WriteBytes(comVar, byteArray, numBytes) - Writes a byte array to the TCP/IP
connection specified by comVar.
• WriteFormatString(commVar, formatString) - Writes a formatted string to the TCP/IO
connection specified by comVar. See also string formatting reference.
Example: WriteFormatString( TcpP5025 ,"\n\rLC1 = [LC1]")
Example: WriteFormatString( TcpP5025 , "\n\rLC1 = [LC1%0.3f], L1 = [L1%d]" )
• WriteString(comVar, String) - Writes a string to the TCP/IO connection specified by
comVar. Unlike WriteFormatString, WriteString does not perform embedded variable
evaluations. See string formatting reference for special characters supported.
Example: WriteString( TcpP5025 ,"\n\rThe measurement is correct")
Bit Functions
• ClearBit(value, bitPosition) - Clears the bit at bitPosition in value. Returns the new
value.
value – a valid number (or variable) to be manipulated on a bit level.
bitPosition – location of the bit to be cleared.
• GetBit(value, bitPosition) - tests and returns the state of the bit at bitPosition in value.
Returns the bit state.
value – a valid number (or variable) to be manipulated on a bit level.
bitPosition – location of the bit to be tested.
• SetBit(value, bitPosition) - Sets the bit at bitPosition in value. Returns the new value.
value – a valid number (or variable) to be manipulated on a bit level.
bitPosition – location of the bit to be set.
iNspect Express Scripting Guide 27 Version 1.6; 2019-4-29
System / Misc. Functions
• AutoSaveEnable( enable ) - Turn solution auto-save on or off. If auto-save is on, when
a user exits the top level (main) setup panel, the solution is automatically re-saved, and
solution switching is automatically re-enabled.
enable = 0 – turn off auto-save. 1 – turn on auto-save.
• ChangeSolution(requestedSolutionID) – Load a Solution file. If the
requestedSolutionID does not exist, the current solution continues running without
flagging an error.
• ChangeStartupSolution(startupSolutionID) – changes the Solution number that will
automatically load on startup or reboot. This change will persist through a system
reboot or power cycle, until changed again. If the startupSolutionID does not exist, the
system will start with Solution 00 if it exists.
• Copy(source, dest, numElements) - Copy numElements from source (an array of
elements) to dest (an array of elements. The copy function can be used to cause
multiple PLC registers to be updated in a single transaction.
• Delay(milliseconds) – creates a delay or wait in a script. This is more efficient that
looping on a time stamp. Adding delay increases execution time. Do not add a delay
larger than your average acquisition time or the time between triggers. Only use Delay()
in a Periodic function, it is ignored in all other function groups.
• FormatTime(timeVal) - converts a time value in milliseconds since January 1, 1601 to a
string representing the current date and time.
Example: time1 = GetTime()
• GetColor( colorID, pixelValue ) - Returns the specified primary color value.
colorID - Specifies primary color desired: 0 = Blue, 1 = Green, 2 = Red.
pixelValue - Value for a color pixel, for example a value returned by GetPixel.
Example: centerPix = GetPixel(0, 320, 240)
centerRed = GetColor( 2, centerPix)
• GetInspectTime() – Returns the previous execution’s Inspect Time. If called in the Post
Image Process function, it is the current execution.
• GetMaxInspectTime() – Returns the maximum Inspect Time since the last reset.
• GetMinInspectTime() – Returns the minimum Inspect Time since the last reset.
• GetPixel( camID, x, y ) - Returns the value for the pixel specified by camID, x, and y. If
the pixel is color, pass the returned value to GetColor to get a red, green or blue value.
camID - always 0 for a BOA. 0 to (number of cameras minus one) for a vision system.
x - the x coordinate. 0 = left most column.
y - the y coordinate. 0 = top row.
Example: centerPix = GetPixel(0, 320, 240)
iNspect Express Scripting Guide 28 Version 1.6; 2019-4-29
• GetSolutionID() - returns the current solution ID number.
• GetTime( ) - returns a value representing the current date and time. The value returned
equals the number of milliseconds since January 1, 1601 (in the local time zone). See
function FormatTime (previous page).
Note: GetTime is not accurate enough for calculating your cycle time to milliseconds.
Use the function TimeMillisec for these calculations.
• GetTimeString( ) - returns a string value representing the current date and time (local
time zone).
Example: now = GetTimeString() sets "now" to a string value "7/9/2009
16:25:28:429"
dateString = FormatTime(time1) sets "dateString" to a string value "7/9/2009
15:25:28:429"
• GetUserName() – returns the user name for the currently logged in user.
• GetVersion() - returns the firmware version of the BOA (same as the software version
of iNspect.
• ImageProcess(DllFileName, functionName, numVars, VarArray) – call a function
functionName, exported by the DLL DllFileName.
numVars – the number of elements in the array VarArray.
VarArray – array of parameters up to 20 elements in size. Parameters can be used as
In and/or Out.
• Print(string, endOfFile) – send a string of data to the default printer. Does not perform
embedded variable evaluations. See also string formatting reference for special
characters supported.
endOfFile – 0 = string is buffered until a subsequent call to print is made with
endOfFile equal 1.
1 = all accumulated text from prior calls to print and the passed string are
immediately sent to the printer. NOTE: Use this function sparingly, as each call t print
with endOfFile =1 will cause at least one page to print.
• ReadCell(excelFileName, row, column) – Does Not apply to the BOA. Read a cell from
an Excel file. A runtime or executable of Excel must be installed on the Vision System.
Use numbers for the row and column, do not use letters.
excelFileName – a file in the iNspect directory, or a full path and file name.
• RefreshExcel(excelFileName) – Does Not apply to the BOA. Refresh an Excel file
database to catch changed cell values. A runtime or executable of Excel must be
installed on the Vision System.
excelFileName – a file in the iNspect directory, or a full path and file name.
• ResetHistory( ) - clears the history log of stored images and data.
• ResetStatistics( ) - clears the pass/recycle/reject counters.
iNspect Express Scripting Guide 29 Version 1.6; 2019-4-29
• SetDisplayStatus(statusMsg, color) - Sets the message to be displayed in the
Inspection Status box (in the Configuration and Status panel associated with the
Monitor panel). This overrides the display of "Pass" or "Fail".
statusMsg – the string that will be displayed. For multiple lines, add the character \n to
indicate a new line. Message text is automatically sized to be the largest possible yet
be contained by the Inspection Status box. String formatting information for variables
of the form [Var%FormatData] is also supported. msg1="[L1%0.2f]" means display
the value of L1 with 2 digits to the right of the decimal point. See also string
formatting reference.
color – The string name of the color the message text is to appear in. Possible values
are: "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "darkred",
"darkgreen", "darkyellow", "darkblue", "darkmagenta", "darkcyan", "lightgray1",
"moneygreen", "skyblue", "cream", "lightgray2", "mediumgray"StartInspect( ) - start
image inspection.
• SetAppButton(buttonNumber, buttonName) – creates a custom button in the Run or
Monitor panel. Up to 4 buttons may be added. A “user” group of functions appears, with
a “Button X Clicked” for each button defined.
• SetImageEncode( encodeMethod ) - Change the image encoding used to compress
images sent to a connected client.
encodeMethod - 0 = No compression.
1 = JPEG compression (default for color).
2 = Proprietary high speed compression (default for mono).
• StartInspect( ) - start image inspection.
• StopInspect( ) - stop image inspection. Note: Use this in a Periodic Function; must not
be used in the Post Image Processing function.
• SwitchingIsEnabled( ) - Returns 1 if the Solution switching is enabled. Returns 0 if
Solution switching is not enabled.
• TimeMillisec( ) - returns the current time in milliseconds.
• WriteCell(excelFileName, row, column, value) – Does Not apply to the BOA. Write a
cell to an Excel file. A runtime or executable of Excel must be installed on the Vision
System.
excelFileName – a file in the iNspect directory, or a full path and file name. For
Example: “c:\Data\FaultsNov08_2012.xls”
row, column – use numbers for the row and column. Do not use letters.
• return(FunctionReturnValue) - Returns the specified value FunctionReturnValue from a
User defined function.
Example: Return( (p1 + p2) /2 ) .
iNspect Express Scripting Guide 30 Version 1.6; 2019-4-29
Scripting Examples
The String Editor
The string editor simplifies construction of output strings. The GUI is accessed through
the “Free Edit” script tool and allows users to define strings without writing code. Each
string is composed of user text, formatted program variables and delimiting characters.
Strings can be written to the function being edited and attached directly to a predefined
communication port:
Strings are constructed by entering text or dragging variables into the string command
line. The above example generates the following lines of code in the function being
edited (typically the Post Image Process function):
str1 = "OCR_String=[OCR%s][OCR1%s][OCR2%s][OCR3%s][13][10]"
WriteFormatString(TcpP5024, str1)
iNspect Express Scripting Guide 31 Version 1.6; 2019-4-29
String Formatting Reference
• Special Characters used in strings
\n - Line feed
\r - Carriage return
\t - Horizontal tab
\f - Form feed
\v - Vertical tab
\xhh - specify a hex byte, for example \xa6 Use the byte value a6.
Other control or non-printing characters can be formed using the \x with the hex
value for the ascii character. For example \x04 for EOT, \x07 for Bell, \x00 for Null.
• Formatting Variables used in the WriteFormatString function
The general form follows this pattern. Please note items inside braces { } are
optional.
[VariableName %{width} {.precision} type ] Example: [LC1 %4.3f]
The optional fields, which appear before the type character, control other aspects
of the formatting, as described below.
• Type
A required character that determines whether the associated argument is
interpreted as a character, a string, or a number. Supported character types:
c specifies a single-byte character.
d Signed decimal integer.
i Signed decimal integer
u Unsigned decimal integer.
x Unsigned hexadecimal integer, using "abcdef".
X unsigned hexadecimal integer, using "ABCDEF".
e Signed value having the form [–]d.dddd e [sign]dd[d[ where d is a single decimal
digit, dddd is one or more decimal digits, dd[d] is two or three decimal digits
depending on the output format and size of the exponent, and sign is + or -.
f Signed value having the form [–]dddd.dddd, where dddd is one or more decimal
digits. The number of digits before the decimal point depends on the magnitude of
the number, and the number of digits after the decimal point depends on the
precision.
iNspect Express Scripting Guide 32 Version 1.6; 2019-4-29
g Signed value printed in f or e format, whichever is more compact for the given
value and precision. The e format is used only when the exponent of the value is less
than -4 or greater than or equal to the precision argument. Trailing zeros are
truncated, and the decimal point appears only if one or more digits follow it.
G Identical to the g format, except that E, rather than e introduces the exponent
(where appropriate).
s specifies a single-byte character string. Characters are printed up to the first null
character or until the precision value is reached.
• width
Optional number that specifies the minimum number of characters output.
The width argument is a nonnegative decimal integer controlling the minimum
number of characters printed. If the number of characters in the output value is less
than the specified width, blanks are added to the left until the minimum width is
reached. If width is prefixed with 0, zeros are added until the minimum width is
reached.
• precision
Optional number that specifies the maximum number of characters printed for all or
part of the output field, or the minimum number of digits printed for integer values.
For types: d, i, u, o, x, X
The precision specifies the minimum number of digits to be printed. If the number of
digits in the argument is less than precision, the output value is padded on the left
with zeros. The value is not truncated when the number of digits exceeds precision.
The default precision is 1.
For types: e, E
The precision specifies the number of digits to be printed after the decimal point. The
last printed digit is rounded.
The default precision is 6. If precision is 0 or the period (.) appears without a number
following it, no decimal point is printed.
For types: f
The precision value specifies the number of digits after the decimal point. If a
decimal point appears, at least one digit appears before it. The value is rounded to
the appropriate number of digits.
iNspect Express Scripting Guide 33 Version 1.6; 2019-4-29
Scripting Examples
The following examples demonstrate usages of the script tool. Each example has a
brief description of the application and associated code snippets from the relevant
functions. These examples cover basic scripting concepts only that apply to typical
applications.
Manipulating Outputs
Many applications require some sort of output manipulation. By default BOA outputs are
set to the “soft pulse” setting which automatically generates output pulses on GPO[0]
and GPO[1] for pass and fail results. Below we’ll show at how to generate pulses or
levels using the script tool.
Predefined function used:
• pulse(activeVal, offsetMillisec, durationMillisec) - generates a pulse output.
activeVal – 1=active-high pulse, 0=active low-pulse.
offsetMillisec – offset or delay from the moment this statement executes, in
milliseconds.
durationMillisec – duration of the pulse, in milliseconds.
In the Post Image Processing function:
// Set the pass/fail condition
if (Result=1) // If composite Pass condition
Global.GPO[0] = pulse(1,0,20) // generate a 20 ms pulse on output 0
else // Else fail
Global.GPO[1] = pulse(1,0,20) // generate a 20 ms pulse on output 1
endif() // Close condition statement
iNspect Express Scripting Guide 34 Version 1.6; 2019-4-29
Similar equation statements can be used to indicate that a specific measurement
caused a failure. There are many different ways to formulate a statement. You can use
the first field as part of the statement, enter a 1 (always true) or leave the field blank.
If (MS1.Result = 3) Global.GPO(1) = pulse(1,0,400)
The above equation outputs a 400 ms active high pulse on GPO(1) (no delay) if the
MS1 match tool fails (Result=3). The equation below generates the same pulse if the
MS1 match tool is not a pass (Result = 2 or 3)
If (MS1.Result != 1) Global.GPO(1) = (pulse(1,0,400)
MS1 is the measured value of the match. You can use the measured value in
statements, in place of the result of a measurement as shown below. Output a 50 ms
active high pulse on GPO(1) (5 ms delay) if the MS1 match score is less than 90
If (MS1 < 90) Global.GPO(1) = pulse(1,5,50)
Similarly, if the Distance measurement L1 is less than 400, output a 50 ms active high
pulse on GPO(1) (5 ms delay).
If (L1 < 400) Global.GPO(1) = pulse(1,5,50)
Below is an example of using the “always true” condition. Set the GPO(1) to logic 1 if
MS1 match tool does not pass; set GPO1 to logic 0 if MS1 match tool passes
If(1) Global.GPO(1) = (MS1.Result != 1)
Replacing “If(1)” with "If ( )" produces the same result.
Note: If you set an output to a level, it will stay that way until you change it. For example
you could set an output to “1” as above and then reset it to “0” before processing the
next image using the “Image Pre Process Function”.
iNspect Express Scripting Guide 35 Version 1.6; 2019-4-29
Solution Switching
There are different scripting methods available for solution switching. We’ll describe two
popular scenarios that use external inputs and Variables.
With a BOA and the PL-100 you can use a single input to switch between two solutions.
Add a Periodic Function (typically 100ms) to solution 1 with the following:
// GPI[1] - defines solution 0 (LOW) or solution 1 (HIGH)
if (GPI[1]=0) // Check for solution #
ChangeSolution(0) // switch to solution 0
endif // Close condition statement
Add a Periodic Function (typically 100ms) to solution 0 with the following:
// GPI[1] - defines solution 0 (LOW) or solution 1 (HIGH)
if (GPI[1]=1) // Check for solution #
ChangeSolution(1) // switch to solution 1
endif // Close condition statement
With the BOA and the PL-200 there is dedicated hardware and software to switch
solutions. You do not have to program a Periodic Function to switch solutions.
iNspect Express Scripting Guide 36 Version 1.6; 2019-4-29
If you use a variable to define the solution # instead of an input, then the script must be
modified to reflect the variable value. BOA supports variable access through integrated
network commands (inside a 3rd party program) or through PLC control. In the latter
case a PLC connection has to be established and a register or tag is assigned as the
solution ID variable.
As an example, let’s assume BOA is connected to a Rockwell ControLogix PLC with a
user defined tag called “BOA_SOLUTION”. We need to setup a periodic script to
monitor the tag for a solution change.
Note: Since this is a variable, it is always recommended to initialize it at solution load
time. This will prevent immediately switching to an unexpected solution upon entry if the
variable is in an unknown state.
Init variable in the Solution Initialize function:
CIx10.BOA_SOLUTION = solution // Add for each solution
Set up Periodic Function to monitor tag:
ChangeSolution(CIx10.BOA_SOLUTION) // switch to solution if ID is different
iNspect Express Scripting Guide 37 Version 1.6; 2019-4-29
Trigger Control
iNspect supports 3 modes of triggering, internal timer, external input and software
controlled. Most applications use external input or software controlled. Internal or
external triggering selected using the iNspect GUI in the sensor setup panel. Software
trigger is controlled via scripting or via network commands.
This simple example shows how to software trigger inspections using scripting.
Predefined functions used:
• trigger( ) - generate an image trigger signal. The Sensor Trigger must be set to
"Inspection Trigger" when using this function.
In the Solution Initialize function:
Trigger_Enable = 1 // Trigger qualifier for handshake (arm initially)
In a user defined Periodic Function:
Trigger_Start = MBSlaveHrs16[2] // Read Modbus defined trigger register
if(Trigger_Start=1 AND Trigger_Enable = 1) // Check trigger condition
Trigger() // Software trigger
Trigger_Enable = 0 // Turn off Trigger gate
endif
if(Trigger_Start=0) // Wait until PLC changes Trigger state
Trigger_Enable = 1 // Re-arm trigger
endif
Note: In general, software triggers are held off during an active acquisition cycle.
iNspect Express Scripting Guide 38 Version 1.6; 2019-4-29
ReTrigger Example
A special case of triggering uses the “retrigger” function. This function re-triggers the
last acquired image for processing, rather than triggering a new image. The function is
useful in an application where you first need to identify which part is passing the camera
before processing it. In this case, the external trigger captures the image for
identification and the retrigger function reloads the same image after the relevant
inspection solution is loaded.
Predefined functions:
• ReTrigger(camID) - causes re-processing the last image on the indicated camID.
camID – always 0 for the BOA.
In the Solution Initialize function:
ReTrigger(0) // Retrigger previous image for inspection
Note: If a client is connected, the GUI may not update correctly following a retrigger
after load. In such cases it is good to add a small delay inside a periodic function (using
the count variable defined below)
In the Solution Initialize function:
NewSolution = 2 // Set counter to 2
In a 40ms user defined Periodic Function:
if(NewSolution=0) // When count = 0
ReTrigger(0) // Force retrigger
endif
NewSolution = NewSolution -1 // Decrement count
iNspect Express Scripting Guide 39 Version 1.6; 2019-4-29
Customizing Text in the Monitor Panel
iNspect offers little in the way of runtime customization, but through scripting it is
possible to display results or messages in the “Display Status” window on the Monitor
panel.
Predefined functions used:
• SetDisplayStatus(statusMsg, color) - Sets the message to be displayed in the
Inspection Status box (in the Configuration and Status panel associated with the
Monitor panel). This overrides the display of "Pass" or "Fail".
NOTE: To reset the display back to the default, use SetDisplayStatus("","") or
SetDisplayStatus(0,0) in the Solution Initialize function.
statusMsg – the string that will be displayed. For multiple lines, add the character \n
to indicate a new line. Message text is automatically sized to be the largest possible
that can be contained in the Inspection Status box. String formatting information for
variables of the form [Var%FormatData] is also supported:
msg1="[L1%0.2f]" means display the value of L1 with 2 digits to the right of the
decimal point.
color – The string name of the color the message text is to appear in. Possible
values are: "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white",
"darkred", "darkgreen", "darkyellow", "darkblue", "darkmagenta", "darkcyan",
"lightgray1", "moneygreen", "skyblue", "cream", "lightgray2", "mediumgray".
The following script commands will display the messages ‘2D Code read” for pass
inspections and “Failed to Read” for fail inspections (screen shots shown on the
following page):
if(Result=1)
SetDisplayStatus(“2D Code Read”, “green”) // post pass message
else
SetDisplayStatus(“Failed to Read”, ”red”) // post fail message
endif
iNspect Express Scripting Guide 40 Version 1.6; 2019-4-29
iNspect Express Scripting Guide 41 Version 1.6; 2019-4-29
The font size in the text window is not user selectable, but rather scales according to
how much text is being displayed. The font type is also not selectable.
If you wish to display multiple lines of text, you need to construct strings accordingly
inside a single function call. If you define multiple SetDisplayStatus() functions in your
script, only the text from the last function will be displayed i.e. each will overwrite the
previous.
An example of how to define multiple lines of text in the “Post Image Process” function
is as follows:
Str1 = “Count Result = “ // define count string
Str2 = “\n Inspection Passed” // define pass message
Str3 = “\n Pass Count =“ // define pass count string
Str4 = “\n Inspection Failed” // define fail message
Str5 = “\n Fail Count =“ // define fail count string
if(Result=1)
SetDisplayStatus(Str1+N.Result+Str2+Str3+Global.PassCount, "darkgreen")
else
SetDisplayStatus(Str1+N.Result+Str4+Str5+Global.FailCount, "darkred")
endif
A pass result would produce the following text on the monitor screen:
iNspect Express Scripting Guide 42 Version 1.6; 2019-4-29
Manipulating Text in the Graphics Tool
The Graphics tool can be used to highlight items, or post messages in the image area.
The Graphic tool can optionally be displayed by the success or failure status of a
another tool. This can be useful for circling or pointing out a defect, to the operator or
for image logging.
Another popular use is communicating messages or instructions to the operator. The
Graphics tool message can appear on the success or failure of another tool. But
creating multiple Graphics tools for the Pass and Fail conditions can lead to a very
cluttered Setup Tool panel. To avoid this, you can create one Graphics tool and change
the displayed message using Scripts.
Predefined functions used:
• SetToolText(toolName, toolText) – changes the text shown in the Graphics tool.
Note: The font style, size and color are defined in the Graphics Tool Properties, and
cannot be changed by a Script.
In this example, we have two tools that check for the presence of two parts on an
assembly. A Graphics tool was created and the name changed to “Instr” in the Graphics
Tool Properties menu. The message in the Graphics tool is changed in this script based
on the success or failure of both tools.
In the Post Image Processing function:
part_a = (tool1.Result=1) // True if tool1 passes – Part A correct
part_b = (tool1.Result=1) // True if tool2 passes – Part B correct
if((part_a) AND (part_b))
SetToolText(Instr, “Both parts present and correct”)
else
if((part_a=1) AND (part_b=0))
SetToolText(Instr, “Fit part B”)
endif
if((part_a=0) AND (part_b=1))
SetToolText(Instr, “Fit part A”)
endif
if((part_a=0) AND (part_b=0))
SetToolText(Instr, “Fit parts A and B”)
endif
endif
iNspect Express Scripting Guide 43 Version 1.6; 2019-4-29
Hide and Show Variables
Any variables you define in a script will appear in the Monitor panel, which could be
quite confusing when you have many variables. You can hide variables that are not
critical to the operator using scripts. We recommend using the Solution Initialize
function because it is evaluated only once, when the solution gets loaded.
Use the variable’s name, with the “Disable” switch. Disable=1 will hide the variable.
Disable=0 will show the variable. For example, you have a variable named “MyVar1”.
In the Solution Initialize function:
MyVar1.Disable=1 //hides the variable
Disable and Enable Tools
You can disable a Tool in the Tools Setup panel (in the Tool Table). The Tool is hidden in
the image, and the results are disabled. All results are shown =0. The Tool Table
disables the tool for all inspections.
But you can also disable a tool in scripts. That means you could enable or disable a tool
based on a variable or on an input.
Use the tool name, with the “Disable” switch. Disable=1 will hide the tool and disable its
results. Disable=0 will show the tool and enable its results once again. The Tool remains
disabled if you do not re-enable it.
If you wish to disable a tool based on a variable, we recommend the Pre-Image
Processing function. If you wish to disable a tool based on an input, you may use the
Periodic function which you use to monitor the input.
if(GPI[3]=1)
MS1.Disable=1 // disable & hide Match tool if the input is 1
else
MS1.Disable=0 // enable & show Match tool if the input is 0
endif
iNspect Express Scripting Guide 44 Version 1.6; 2019-4-29
Sensor Control
Scripts can be used to dynamically monitor and adjust sensor parameters to
compensate for lighting variation. This is not a common concern since most applications
use controlled lighting, but it can be useful in situations where process changes affect
part intensity.
Predefined functions used:
• SetExposure(exposureTimeMilliseconds) - sets the image exposure time in
milliseconds.
Example: SetExposure(9.6) sets the exposure time to 9.6 milliseconds.
• GetExposure() - returns the current value of exposure, in milliseconds.
• SetDisplayStatus(statusMsg, color)
This inspection adjusts the camera exposure (shutter) to a lighting brightness range and
writes a message below the image. In this example we want to keep the area average
between 198 and 202.
Script in the Post Image Process function:
if(InspectAreaAve<198 OR InspectAreaAve>202) // Check condition
AdjustShutter() // Adjust Shutter to compensate
else
SetDisplayStatus(“Inspecting”,”green”) // Write to display
endif
iNspect Express Scripting Guide 45 Version 1.6; 2019-4-29
Script in the User Function “AdjustShutter”:
// This script gets called when the inspection intensity checks go above or below
// user defined limits
if(InspectAreaAve>210) // Check upper limit
ShutterAdjust = -0.5 // Lower shutter value
endif
if(InspectAreaAve<=210 AND InspectAreaAve>202) // Check mid upper limit
ShutterAdjust= -0.1 // Lower shutter value
endif
if(InspectAreaAve<190) // Check low limit
ShutterAdjust= 0.5 // increase shutter value
endif
if(InspectAreaAve>=190 AND InspectAreaAve<198) // Check mid lower limit
ShutterAdjust= 0.1 // increase shutter value
endif
CurrentShutter=GetExposure() // Get current exposure value
NewShutter=CurrentShutter+ShutterAdjust // Compensate
if(NewShutter>=0.1 AND NewShutter<=100) // Verify within exposure limits
SetExposure(NewShutter) // Set new exposure
SetDisplayStatus(“Adjusting Shutter”,”yellow”) // Inform operator
else
SetDisplayStatus(“Shutter Out of Range, Check Light”,”red”) // Inform operator
endif
Return()
iNspect Express Scripting Guide 46 Version 1.6; 2019-4-29
Image Logging
There are different ways to write images. This example shows how to log images to a
FTP Server. Note: Domain security may prevent fixed address devices (BOA) from
writing to the FTP Server.
iNspect Express supports ftp file logging where iNspect Express is the ftp Client logging
to an ftp Server. The user Name and password are optional in iNspect Express. They
may be required by your ftp server.
Example 1 WriteImageFile
Predefined function used:
• WriteImageFile(fileName, camID) - To be called only from the "Post Image Process"
function, will write the current image from the camera specified by camID to the
fileName specified (0 for BOA).
fileName – full path of file to save. Can use UNC
format: \\serverName\shareName\path\fileName to save to a server's shared drive.
In this example, no user name or password needed. The image file name becomes
“img#.bmp”.
In the Post Image Processing function:
x=x+1
fn = “ftp://ftp.acme.com/images/img” + x + “.bmp”
WriteImageFile(fn, 0)
Example 2 WriteImageTools
Predefined function used:
• WriteImageTools(fileName, camID) - writes an image file including the tool graphics.
fileName – full path of file to save. Can use UNC format to save to a servers shared
drive: \\serverName\shareName\path\fileName. Use function DriveConnect() to
connect to a remote server's share drive. camID – always 0 for the BOA.
User name “Joe”, password “bananas”. The image file name becomes “tool#.bmp”.
In the “Post Image Process” function:
x=x+1
fn = “ftp://[email protected]/images/img” + x + “.bmp”
WriteImageTools(fn, 0)
iNspect Express Scripting Guide 47 Version 1.6; 2019-4-29
Result Logging
This example shows how to log results to a CSV file on the client hard drive. The
“client” is a PC connected to a BOA camera. Note: Client and Server are one in the
same for the BOA emulator
To demonstrate both the “logstart” and “logstop” functions, we’ll design a small program
that stops logging after 20 failures. To do this we’ll need a count variable to keep track
of failures and we’ll need to initialize this variable when the solution first loads.
Predefined functions used:
• LogStart(fileName, onClient) - Start logging the processed frame data to the specified
CSV (comma separated values) file.
fileName – full path and file name to save CSV data to. For Example,
C:\Logs\iHistlog119200614.csv
onClient – if 0, save to file on server (not supported on BOA)
if 1, save to file on client (always 1 for BOA)
• LogStop( ) - Stop logging data that was started by a logstart call.
In the “Solution Initialize” function: In the “Post Image Process” function:
// Init fail_count variable // Check fail_count value
Fail_count = 0 If (fail_count = 20)
// Start the CSV file logging function LogStop() //stop logging
LogStart(“d:\DALSA\FailLog.csv”,1) Else
If (Result.0=3) //check for fail
fail_count=fail_count+1 //increment
Endif
Endif
iNspect Express Scripting Guide 48 Version 1.6; 2019-4-29
Screenshot of the CSV log file that this
example generates. Note that all results are
logged until the 21st failure is detected.
Below shows how to change the “Post Image
Process” script to log ONLY the failed results:
// Check for Fail_count limit
if (Fail_count < 20)
if (Result.0=3)
LogStart(“d:\DALSA\failog.csv,0”)
fail_count=fail_count+1
endif
else
LogStop() //stop logging
endif
iNspect Express Scripting Guide 49 Version 1.6; 2019-4-29
Using the Start and Stop Functions
These functions can be used to control the running state of BOA. Whilst in the STOP
state, BOA is effectively in bypass mode, meaning it will not respond to triggers and it
will not execute the preordered functions. However, it will continue to execute event
functions if defined.
This example shows how to stop iNspect (and restart) if a failed condition is detected n
number of times. In this case, the failed condition is an incorrect number of characters
read by the OCR tool. The “Post Image Process” function will be used to test the OCR
string and stop inspect when the count reaches 50. We’ll also check the code against a
preloaded value (stored in a variable) and set an output state to indicate “good” or “bad”
code. We’ll setup a periodic function to detect if iNspect has stopped and if so restart it.
This same function will be used to reset the failure count variable.
NOTE: You must save the solution before the Stopinspect() function will work
Predefined functions used:
• StartInspect( ) - start image inspection.
• StopInspect( ) - stop image inspection.
In the Solution Initialize function
fcount = 0
STOP=0
In the Post Image Processing function:
// Store the number of characters from the OCR string in variable “slength”
// Count number of times the expected length does not match and STOP if 50
slength=StrLen(OCR1)
if (slength<8) //check for wrong number of characters
fcount=fcount+1 //increment bad counter
if (fcount=50) //check for stop condition
STOP=1
endif
endif
In a user defined Periodic Function
if(STOP=1)
StopInspect()
endif
iNspect Express Scripting Guide 50 Version 1.6; 2019-4-29
Also in the “post Image Process” function, we’ll manipulate an output based on the read
result being correct or not:
// Check value of OCR1 against predefined code and action output
if (codecheck=OCR1) //codecheck is a preloaded user variable
Global.GPO[0]=1 //output code good
else
Global.GPO[1]=1 //output code bad
endif
The outputs can also be pulsed as shown earlier or terminated in length using the
“Image Process Delay function”. Another option would be to hold the current output
state until the next inspection starts (i.e. reset them in the “Image Receive Delay
Function”).
Now we’ll define a simple periodic function to restart iNspect based on notification from
a PLC:
// If iNspect has stopped, reset fail feature count and restart when directed
PLC_Runmode=EIPint[0] //Ethernet/IP register 0
if (PLC_Runmode = 1)
StartInspect()
fcount=0
STOP=0
endif
iNspect Express Scripting Guide 51 Version 1.6; 2019-4-29
Communication Using Strings
This script demonstrates how to read a string from an attached Ethernet port. In this
case, the string contains command characters for solution control and triggering. The
script parses the string to extract the control characters for action. We’ll define the string
to be 10 characters (+ delimiter character) as follows:
Char 0 = command character – “T” = Trigger, “S” = Stop, “R” = Restart
Char 1 = Solution # - 0 through 9
Char 2-9 = Job code
This script should be added to a periodic function for the following reasons:
1.Communication is asynchronous to processing
2.Periodic functions continue to run when the system is in a “stopped” state, enabling
the user to issue a “restart” command.
Predefined functions used :
• ReadString(comVar, endingChar) - Reads a string from the TCP/IP connection
specified by comVar if one is available, otherwise returns an empty string immediately.
• Substring(string, startIndex, length) - forms a sub-string from the input string,
beginning at startIndex (zero-based) of length characters. If length = 0 all characters
to the end of the string are included in the sub-string.
• trigger( ) - generate an image software trigger signal. The Sensor Trigger must be set
to "Inspection Trigger" when using this function.
• StartInspect( ) - start image inspection.
• StopInspect( ) - stop image inspection. Stops the camera or vision system from
processing and outputting. For example, something has gone wrong on the line and
controlling equipment needs to be stopped.
iNspect Express Scripting Guide 52 Version 1.6; 2019-4-29
In the Periodic Function:
ReadBuffer = ReadString( TcpP6001 , 13) // load string until “CR” line delimiter detected
if(ReadBuffer != "") // if buffer is not empty
CommandString = ReadBuffer // store string in string variable
CommandCharacter = Substring(CommandString, 0, 1) //extract command character
SolutionNumber = Substring(CommandString, 1, 1) // extract solution number
JobCode = Substring(CommandString, 2, 9) // extract job code
if(INT(SolutionNumber) >0 AND INT(SolutionNumber)<9) // validate solution #
SolutionNumber = INT(SolutionNumber) // convert from string to INT
ChangeSolution(SolutionNumber) // change to specified solution
endif
//Note: if SolutionNumber is different than current solution running, change will start
//immediately and the following code will be ignored. If they are the same, the following code
//will be executed
if(CommandCharacter = "T") // look for trigger command
trigger( ) // call trigger function
endif
if(CommandCharacter = “S") // look for trigger command
stopinspect( ) // call stop function
endif
if(CommandCharacter = “R") // look for trigger command
startinspect( ) // call restart function
endif
endif // close main IF statement
iNspect Express Scripting Guide 53 Version 1.6; 2019-4-29
Using Arrays
The script tool supports the use of arrays (consecutive data registers). Arrays can be
used to segment or organize data into a user defined structure. Some complex tools
output results into arrays for script manipulation, but most users define arrays for more
efficient communication.
Array Example 1:
This simple example shows how to parse an array of blob areas (Area.[x]) from the
count tool to find the biggest blob (Note: in practice this can easily be done using the
“max” feature of the count tool without writing any script):
In the Post Image Processing Function:
array_count=0 // reset array_count variable
max_value=0 // reset max_value variable
while(array_count<20) // Do while array_count <20
array_value = Area.[array_count] // Read entry in array
if(array_value>max_value) // Check for high value
max_value = array_value // Make new highest value
endif
array_count=array_count+1 // Increment counter
endwhile
iNspect Express Scripting Guide 54 Version 1.6; 2019-4-29
Array Example 2:
This similar example shows how to parse an array of numbers to find two consecutive
entries that differ by more than 20%:
Input Array (entries 3 and 4 differ by 25%): ds[0:5]=90, 90, 90, 100, 80, 90
In the Post Image Processing Function:
//
numHi = 0
i=0
while( i < 6 )
z = i+1
while( z < 6 )
if( ds[i] < ds[z] )
ratio = ds[z] / ds[i]
else
ratio = ds[i] / ds[z]
endif
if(ratio > 1.20)
highRatio[numHi] = ratio // store high ratio
highRatio[numHi][0] = I // store first number
highRatio[numHi][1] = z // store second number
numHi = numHi+1
endif
z = z+1
endwhile
i = i+1
endwhile
iNspect Express Scripting Guide 55 Version 1.6; 2019-4-29
Array Example 3:
This example shows how to match a barcode string to a predefined string stored in an
array. The 32 string array is indexed based on a user code supplied through the Global
Inputs (PL-200) i.e. if input = 0x4, compare the barcode value with string #4.
Place the 32 strings in array called “BarCodeList”
BarCodeList[0] = "M54321"
BarCodeList[1] = "JJ H4321"
…
BarCodeList[31] = "KLM6721"
In the Post Image Processing Function:
idx = 0
i=0
while( i < 5 ) // Find array entry to compare
idx = idx | (Global.GPI[i] << i) // Based on 5 GP inputs
i = i+1
endwhile
BarMatch = BarCodeList[idx] // Compare string
iNspect Express Scripting Guide 56 Version 1.6; 2019-4-29
Using Arrays for Communication
Arrays offer convenience and efficiency when communicating between BOA and 3rd
party equipment. You can define a common data structure that can be moved quickly
between devices using a single command.
WriteBytes(comVar, byteArray, numBytes) - Writes a byte array to the TCP/IP
connection specified by comVar
copy(source, dest, numElements) - Copy numElements from source (an array of
elements) to dest (an array of elements). The copy function can be used to cause
multiple PLC registers to be updated in a single transaction
Example:
This example shows how to send the X, Y and Z coordinates to a robot in one Modbus
multiple register transaction. With variable MB92HRs16 attached to a Modbus holding
register, the following will update the Modbus device coordinates in a single transaction.
cmd[0] = x // X coordinate
cmd[1] = y // Y coordinate
cmd[2] = z // Z coordinate
copy (cmd, MB92HRs16, 3) // Send coordinates
Similarly, you can store results from multiple tools in a single array and transfer them
efficiently using the WriteBytes function:
meas[0]= L1 // Array element 0
meas[1]= L2 // Array element 1
Meas[2]= N1 // Array element 2
…
Meas[9]= IntAverag1 // Array element 9
WriteBytes( TcpP5025 , meas, 10) // Send 10 elements
iNspect Express Scripting Guide 57 Version 1.6; 2019-4-29
Manipulating Bits of Data
This example shows how to use the Bit Function and TCP/IP communication. A byte
number is sent to BOA which has to be converted to a binary number. The binary
number defines which inspection results are to be sent over TCP/IP for display.
Predefined functions used:
• GetBit(value, bitPosition) - tests and returns the state of the bit at bitPosition in
value. Returns the bit state.
value – a valid number (or variable) to be manipulated on a bit level.
bitPosition – location of the bit to be tested.
Script in the Pre-Image Process Function:
// Initialize data bit variable
Bit0 = 0
Bit1 = 0
Bit2 = 0
Bit3 = 0
Script in the Post Image Processing Function:
MyData = ReadByte(TcpP5025) // Read byte from TCP port
if(MyData != “”)
Bit0= GetBit(MyData,0) // get bits from MyData byte
Bit1= GetBit(MyData,1)
Bit2= GetBit(MyData,2)
Bit3= GetBit(MyData,3)
SetDisplayStatus(“Data Received”, “green”) // send message to monitor
SendCountData() // call User function
else
SetDisplayStatus(“No Data”, “red”) // send message to monitor
endif
iNspect Express Scripting Guide 58 Version 1.6; 2019-4-29
Script in User Function SendCountData // User defined function
WriteFormatString(TcpP5025,”\n\r New Count Data”) // Send start of string
if(Bit0 = 1)
WriteFormatString(TcpP5025,”\n\r Left Side Found = [Left_Side]”) // send left count
endif
if(Bit1 = 1)
WriteFormatString(TcpP5025,”\n\r Right Side Found = [Right_Side]”) // send right count
endif
if(Bit2 = 1)
WriteFormatString(TcpP5025,”\n\r Top Side Found = [Top_Side]”) // send top count
endif
if(Bit3 = 1)
WriteFormatString(TcpP5025,”\n\r Bottom Side Found = [Bot_Side]”) // send bot count
endif
Return() // Return to main program
Example of String produced when Bit0=1:
New Count Data
Left Side Found = 38
iNspect Express Scripting Guide 59 Version 1.6; 2019-4-29
Subtracting Images
This example shows how to use the image comparison functions to subtract one image
from another. These functions us a temporary image storage buffer.
This example could be adapted and used for ImageMax or ImageMin.
Predefined functions used:
• SaveImage(fileName)
• ImageSub(inFile1, inFile2, outFile)
• TriggerOnFile(trigFile)
Script in the Solution Initialize Function:
k=2 // initalize variable
Script in the Post Image Processing Function:
k = (k+1)%3 // modulus 3
if(k=0)
SaveImage(“img1.raw”)
endif
if(k=1)
ImageSub(“img1.raw”, “current”, “out.raw”)
TriggerOnFile(“out.raw”)
endif
if(k=2)
//Processed result of out.raw image is available here for additional script
endif
iNspect Express Scripting Guide 60 Version 1.6; 2019-4-29