TelePACE C Tools User Manual

TelePACE C Tools User Manual

TelePACE C Tools

User and Reference Manual

CONTROL

MICROSYSTEMS

SCADA products... for the distance

48 Steacie Drive Telephone: 613-591-1943

Kanata, Ontario

K2K 2A9

Facsimile: 613-591-1022

Technical Support: 888-226-6876

Canada 888-2CONTROL

TelePACE C Tools User and Reference Manual

©2007 Control Microsystems Inc.

All rights reserved.

Printed in Canada.

Trademarks

TelePACE, SCADASense, SCADAServer, SCADALog, RealFLO, TeleSAFE, TeleSAFE

Micro16, SCADAPack, SCADAPack Light, SCADAPack Plus, SCADAPack 32, SCADAPack

32P, SCADAPack 350, SCADAPack LP, SCADAPack 100, SCADASense 4202 DS,

SCADASense 4202 DR, SCADASense 4203 DS, SCADASense 4203 DR, SCADASense

4102, SCADASense 4012, SCADASense 4032 and TeleBUS are registered trademarks of

Control Microsystems.

All other product names are copyright and registered trademarks or trade names of their respective owners.

Material used in the User and Reference manual section titled SCADAServer OLE

Automation Reference is distributed under license from the OPC Foundation.

TelePACE C Tools User and Reference Manual

May 9, 2007

1

Table of Contents

TABLE OF CONTENTS .......................................................................................................... 2

TELEPACE C TOOLS OVERVIEW......................................................................................... 3

GETTING STARTED ............................................................................................................... 6

C PROGRAM DEVELOPMENT ............................................................................................ 11

REAL TIME OPERATING SYSTEM...................................................................................... 24

OVERVIEW OF PROGRAMMING FUNCTIONS .................................................................. 37

TELEPACE C TOOLS FUNCTION SPECIFICATIONS........................................................ 73

TELEPACE C TOOLS MACRO DEFINITIONS .................................................................. 431

TELEPACE C TOOLS STRUCTURES AND TYPES ......................................................... 441

C COMPILER KNOWN PROBLEMS .................................................................................. 469

TELEPACE C TOOLS WARRANTY AND LICENSE ......................................................... 472

TelePACE C Tools User and Reference Manual

May 9, 2007

2

TelePACE C Tools Overview

The TelePACE C Tools are ideal for engineers and programmers who require advanced programming tools for SCADA applications and process control. The SCADAPack, 4000

Series and TeleSAFE families of controllers execute ladder logic and C application programs simultaneously, providing you with maximum flexibility in implementing your control strategy.

This manual provides full documentation on the TelePACE C program loader and the library of C language process control and SCADA functions. We strongly encourage you to read it, and to notify us if you find any errors or additional items you feel should be included in our documentation.

We sincerely hope that the reliability and flexibility afforded by this fully programmable controller enable you and your company to solve your automation problems in a cost effective and efficient manner.

The TelePACE C Tools include an ANSI C cross compiler; a customized library of functions for industrial automation and data acquisition; a real time operating system; and the

TelePACE C program loader. The C function library is similar to many other C implementations, but contains additional features for real time control, digital and analog I/O.

An overview of the application development environment and its features follows.

Program Development

C programs are written using any text editor. The MCCM77 compiler is used to compile, assemble and link the programs on a personal computer.

The memory image, which results from this process may then be, loaded either into the

RAM, committed to an EPROM, or both may be used together. Programs may be executed either manually or automatically at power up.

Modularity

Programs written in TelePACE C may be split into many separately compiled modules.

These modules may be tested individually before being linked together in the final program.

Command files specify how the various files are to be linked.

Assembly Language Code

Assembly language source code may be included directly within C programs. The #asm and

#endasm statements are used to enclose in-line assembly language code, which is then assembled without passing through the compiler.

C programs are converted to assembly language by the MCCM77 compiler, and this code may be viewed and modified. The resulting code may also be combined with programs written directly in assembler.

Program Options

A C application program may reside in RAM or ROM. The normal method of program development has the program in RAM. The program may call library routines in the operating system ROM. The RAM is nonvolatile (battery backed), so the program may remain in RAM once development is completed and the unit is installed.

Application programs may also be committed to EPROM. The RAM is used for data storage in this case.

TelePACE C Tools User and Reference Manual

May 9, 2007

3

Supported Language Features

The TelePACE C Tools use the Microtec® MCCM77 C compiler. The compiler is ANSI C compliant, and provides a code optimizer and assembler.

In addition to the standard C operators, data types and library functions, the C tools provide a set of routines specifically designed for control applications. Some applications and the descriptions of these functions may be found on the following pages.

Serial Communication

An extensive serial communication library supports simple ASCII communication, communication protocols and serial port configuration. The default communication mode uses the TeleBUS RTU communication protocol. It supports access to the I/O database, serial port reconfiguration and program loading.

The application program can disable the TeleBUS protocol, and use the serial ports for other purposes.

TeleBUS protocols are compatible with the widely supported, Modbus ASCII and RTU protocols.

Clock/Calendar

The processor's hardware clock calendar is supported by the C Tools. The time, date and day of week can be read and set by the application software.

Timers

The controller provides 32 software timers. They are individually programmable for tick rates from ten per second to once every 25.5 seconds. Timers may be linked to digital outputs to cause external devices to turn on/off after a specified period. All timers operate in the background from a hardware interrupt generated by the main system clock.

Duty Cycle and Pulse Outputs

The digital I/O driver provides duty cycle and pulse train outputs. Duty cycle outputs generate continuous square waves. Pulse train outputs generate finite sequences of pulses.

Outputs are generated independent of the application program.

Watchdog Timer

The controller supports a hardware watchdog timer to detect and respond to hardware or software failures. Watchdog timer trigger pulses may be generated by the user program or by the system clock.

Checksums

To simplify the implementation of self-checking communication algorithms, the C Tools provide four types of checksums: additive, CRC-16, CRC-CCITT, and byte-wise exclusive-

OR. The CRC algorithms are particularly reliable, employing various polynomial methods to detect nearly all communication errors. Additional types of checksums are easily implemented using library functions.

TelePACE C Tools User and Reference Manual

May 9, 2007

4

Standard I/O Functions

The TelePACE C Tools are an enhanced version of standard C libraries. Most of the usual

C programming techniques apply. However, with respect to I/O, there are some differences.

The C Tools function library supports all the standard I/O functions. There are no disk-drives or peripherals associated with the controller. Thus many file handling functions return fixed responses, indicating that the operation could not be performed.

All standard devices are opened automatically by the operating system and cannot be closed. The route function may be used to redirect stdin, stdout and stderr.

The TelePACE Program

TelePACE is an easy-to-use interface providing, among several other features, a C Program

Loader and a Ladder Logic program editor. On-line help provides a full reference to all the features of the TelePACE program. TelePACE runs on the Microsoft Windows operating system.

This manual references only those features of TelePACE pertaining to the C Program

Loader dialog. Please refer to the section TelePACE Program Reference for a complete description of TelePACE menus, which will be useful during C Program development.

Additional Documentation

Additional documentation on TelePACE Ladder Logic and the TeleSAFE and SCADAPack controllers is found in the following documents.

The on-line help for the TelePACE C program loader contains a complete reference to the operation of the loader. To display on-line help, select Contents from the Help menu.

The SCADAPack & Micro16 System Manual is a complete reference to controller and I/O modules used with SCADAPack and Micro16 controllers. It contains the SCADAPack

Controller Hardware Manual, the TeleSAFE Micro16 System Manual and hardware manuals for all 5000 Series I/O modules.

The TelePACE Ladder Logic Reference and User Manual describes the creation of application programs in the Ladder Logic language.

The TeleBUS Protocols User Manual describes communication using Modbus compatible protocols.

The TelePACE PID Controller Reference Manual describes PID control concepts and provides examples using the PID functions.

TelePACE C Tools User and Reference Manual

May 9, 2007

5

Getting Started

This section of the C Tools User Manual describes the installation of C Tools and includes a

Program Development Tutorial. The Program Development Tutorial leads the user through the steps involved in writing, compiling, linking and loading a C application program.

System Requirements

TelePACE requires the following minimum system configuration.

• Personal computer using 80386 or higher microprocessor.

• Microsoft ™ operating system versions including Windows 2000, NT and XP™ .

• Minimum 4 MB of memory.

• Mouse or compatible pointing device.

• Hard disk with approximately 2.5 Mbytes of free disk space.

Making Backup Disks

You should make a backup copy of the TelePACE disk and Microtec C compiler disks before using the software. A backup copy protects you against damage to the disk. Always work with the backup copy – if it fails, you can make a new copy from the original disk. Store the original disk in a safe location.

• In My Computer, click the icon for the disk you want to copy.

• On the File menu, click Copy Disk.

• Click the drive you want to copy from and the drive you want to copy to, and then click

Start.

Installation of C Compiler

Install the Microtec C compiler as described in the installation manuals supplied with the system.

To run the Microtec Compiler and Linker from any directory, without the need to specify the full path, you will have to setup the following System Environmental Variables:

Variable Value

mri_m77_bin c:\mccm77;c:\asmm77 mri_m77_inc c:\mccm77 mri_m77_lib c:\mccm77 mri_m77_tmp c:\mccm77\tmp

In addition you would need to add these values to the Path System Variable:

C:\MCCM77;C:\ASMM77;C:\XHSM77

Note that spaces are not tolerated in between entries in the Path value.

TelePACE C Tools User and Reference Manual

May 9, 2007

6

On a Windows XP Control Panel, select System | Advanced | Environmental Variables to access the dialog where the above variables need to be set.

Installation of TelePACE

Install TelePACE as described in the installation section of the TelePACE Ladder Logic

Reference and User Manual.

Some virus checking software may interfere with Setup. If you experience problems with the

Setup, disable your virus checker and run Setup again.

Installing C Tools as an Upgrade

If you are installing TelePACE as an upgrade to a previous C Tools installation for the

Micro16, note that the C Tools are installed in the new directory c:\telepace\ctools\520x

instead of the directory c:\telepace\ctools\micro16.

If the older version of C Tools is not needed, copy all user data files out of the micro16 directory and delete the directory and its contents.

When linking older programs you will need to modify all older linker command (.cmd) files to reference the new 520x directory instead of the micro16 directory, or see the sample linker file appram.cmd for the correct file contents.

The sample linker command file appram.cmd also loads the new ctools.lib library. This library contains the new C Tools functions defined in the header file ctools.h.

Program Development Tutorial

Program development consists of three stages: writing and editing; compiling and linking; and loading the program into the controller. Each uses separate tools. To demonstrate these steps a sample program will be prepared.

Refer to the C Program Development section for a full description of the program development process.

Traditionally, the first program that is run on a new C compiler is the hello, world program. It prints the message “hello, world”.

Writing and Editing

A controller C program is written using any text editor or word processor in text mode. The syntax should correspond to that described in the Microtec MCCM77 Documentation Set, and the C Program Development section of this manual. This chapter describes nonstandard functions, which are unique to the controller. It should be read carefully to make full use of the special purpose routines available.

Using your text editor, open the file hello.c file. It is located in the telepace\ctools\520x

directory. The program looks a little different from the traditional

hello, world program.

/* -----------------------------------------------

hello.c

SCADAPack and TeleSAFE Micro16 Test Program

The infamous hello, world program.

-------------------------------------------- */

#include <ctools.h>

TelePACE C Tools User and Reference Manual

May 9, 2007

7

void main(void)

{

/* Disable the protocol on serial port 1 */ settings.type = NO_PROTOCOL; settings.station = 1; settings.mode = AM_standard; settings.priority = 3; settings.SFMessaging = FALSE;

/* Print the message */ fprintf(com1, "hello, world\r\n");

/* Wait here forever */

{

NULL;

}

}

The “hello, world” message will be output to the com1 serial port of the controller. A terminal connected to the port will display the message.

The controller normally communicates on all ports using the TeleBUS communication protocol. The first section of the program disables the com1 protocol so the serial port can be used as a normal RS-232 port.

The fprintf function prints the message to the com1 serial port.

When you have completed examining the program, close the hello.c file. It is now ready to be compiled and linked.

Compiling and Linking

Compiling and linking convert the source code into executable code for the controller. The

TelePACE C Tools use a C cross compiler and linker from Microtec, a respected supplier of embedded system tools. The compiler produces tight, well-optimized code. The compiler and linker run under the Microsoft MS-DOS operating system.

The compiler has many command line options. The basic command line and options required to compile code for the controller are: mccm77 -v -nQ -Ml -c filename.c

This should be repeated for each file in the application. Note that the command line options are case sensitive. The character following the M is a lower case l (ell).

Files are linked together using linker command files. To link a program execute the command:

Sample command files for RAM and ROM based applications are located in the telepace\ctools\520x directory.

Example

The hello.c program is found in the telepace\ctools\520x directory. To compile and link the program:

• switch to the telepace\ctools\520x directory;

TelePACE C Tools User and Reference Manual

May 9, 2007

8

• enter the commands mccm77 -v -nQ -Ml -c hello.c lnkm77 -c hello.cmd

The file hello.abs contains the executable code in a format ready to load into the controller.

Loading and Executing

The TelePACE C Program Loader transfers executable files from a PC to the controller and controls execution of programs in the controller. The loader can also initialize program memory and serial port configuration.

Controller Initialization

The memory of the controller has to be initialized when beginning a new programming project or when it is desired to start from default conditions. It is not necessary to initialize the controller before every program load.

To initialize the controller, first perform a SERVICE boot. A SERVICE boot preserves programs and data in nonvolatile RAM, but does not start the programs running. Default communication parameters are used.

To perform a service boot:

• Remove power from the controller.

• Press and hold the LED POWER switch.

• Apply power to the controller.

• Wait until the STAT LED on the top of the board turns on.

• Release the LED POWER switch.

Second, initialize the program and data memory in the controller. A new controller will require all initializations to be performed. Selected initializations can be performed on a controller that is in use.

• Run the TelePACE program under Microsoft Windows.

• Connect the PC to the controller with the appropriate serial cable. The hello, world program will print data on the com1 serial port. Therefore connect to the com2 serial port on the controller. (All communication ports work the same. We use com2 here because the sample program is using com1.) check mark appears beside the desired type when it is selected.

• Select all options: Erase Ladder Logic Program, Erase C Program, Initialize

Controller and Erase Register Assignment Table.

• Click on the OK button.

The controller is now ready for a program.

Loading the Program

To load the hello, world program into the controller:

TelePACE C Tools User and Reference Manual

May 9, 2007

9

• Run the TelePACE program.

• Enter

in the edit box for the C Program file name.

• Select all write options: C Program, Register Assignment and Serial port settings.

• Click on the Write button. The file will be downloaded.

• A warning message about the empty register assignment will appear. Click on the OK button.

Executing the Program

• Connect a terminal to com1 on the controller. It will display the output of the program. Set the communication parameters to 9600 baud, 8 data bits, 1 stop bit, and no parity.

The “hello, world” message will be displayed on the terminal.

Serial Communication Parameters

When the controller is powered up in the SERVICE mode the serial ports are configured as:

• 8 data bits

• 1 stop bit

• Modbus RTU protocol emulation

• station address = 1

A program may change these settings with the set_port function. When the controller is powered up in RUN position, the custom parameters, as stored by the most recent save function, are used.

TelePACE C Tools User and Reference Manual

May 9, 2007

10

C Program Development

Program Architecture

A C application program may be contained in a single file or in a number of separate files, called modules. A single file is simple to compile and link. It can become cumbersome to edit and time-consuming to compile as the file grows in size.

An application stored in separate modules by function is easier to edit, promotes function reuse, and is quicker to compile when only a few modules are changed. Compiled modules can be combined into object libraries and shared among users.

The TelePACE C Tools support both single file and multiple module programs. A C application program consists of support functions provided by the C Tools and the main() and other functions written by the user.

Main Function Structure

The program sample below shows a typical structure for the main() function. void main(void)

{

/* Perform initialization actions */

/* Start support tasks */

/* Main Loop*/

{

/* Perform application functions */

}

}

Initialization actions typically consist of variable declarations, variable initialization and onetime actions that must be performed when the program starts running.

Supporting tasks (see Real Time Operating System section) are typically created before the main loop of the program. Tasks can be created and ended dynamically during the execution of a program as well.

The main loop of a program is always an infinite loop that continually performs the actions required by the program. The main() function normally never returns.

Example

The following is an example of a three-module program. Each function is stored in a separate file. This program will be used in subsequent examples.

File: func1.c

#include <ctools.h> void func1(void)

{

fputs(

"This is function 1\r\n", com1);

}

File: func2.c

TelePACE C Tools User and Reference Manual

May 9, 2007

11

#include <ctools.h> void func2(void)

{

fputs(

"This is function 2\r\n ", com1);

}

File: main.c

#include <ctools.h> extern void func1(void); extern void func2(void); void main(void)

{

func1();

{

func2();

}

}

Start-Up Function Structure

The user’s main() function is called from the appstart function of the C Tools. It is not necessary to understand the appstart function to write programs. However it performs a number of useful functions that can be modified by the user.

The start-up code has five major functions:

• create and initialize the application program heap (for dynamic memory allocation);

• specify the number of stack blocks allocated to the main task;

• initialize application program variables;

• control execution of the protocol, ladder logic and background I/O tasks; the function.

Source code for the function is supplied with the C Tools. The following discussion refers to statements found in the file appstart.c.

The heap is a section of memory used by dynamic memory allocation functions such as malloc

. The heap starts at the end of RAM used by the program and continues to the end of physical RAM. The limit is set by the statement: end_of_heap .EQU 41ffffh

The limit is set by default to the smallest memory option available for the controller. If your controller has more memory, change the value of the constant according to the following table.

RAM Installed C Application Program RAM

Addresses

128 Kbytes

256 Kbytes

640 Kbytes none (ladder logic only)

400000h – 41FFFFh

400000h – 47FFFFh

1024 Kbytes 388000h – 3E7FFFh

400000h – 47FFFFh

TelePACE C Tools User and Reference Manual

May 9, 2007

12

The application program signature section of the file contains a constant that determines the size of the stack allocated to the main task. The stack size is sufficient for most applications.

It can be changed by modifying the statement:

.WORD 4 ;stack size in blocks

Refer to the Real Time Operating System section for more information on the stack required by tasks.

The appstart function begins by initializing the heap pointers, setting all non-initialized variables to zero, and initializing system variables.

It then starts the communication protocols for each serial port, according to the stored values in the EEPROM (or the standard values on a SERVICE boot). If your application program never uses the communication protocols, some or all of the following commands

1

can be removed, to free the stack space used by the protocol tasks.

start_protocol(com1);

start_protocol(com2);

2

start_protocol(com3);

start_protocol(com4);

3

The background I/O task is required for the timer functions, dial-up modem communications, and PID controller functions to operate. If you do not intend to use these functions, you can reduce the CPU load by changing TRUE to FALSE in the following statement:

runBackgroundIO(TRUE);

The ladder logic interpreter is required for ladder logic programs. If you do not intend to use ladder logic, you can reduce the CPU load by changing TRUE to FALSE in the following statement:

runLadderLogic(TRUE);

The final operation is execution of the main function. The _initcopy function copies the initial values for initialized variables from the __INITDATA section in the program to the variables. If there are no errors in the data then the user’s application program runs. (An error is likely only if the program in RAM has been damaged or improperly linked.) if (_initcopy() == 0)

{ main();

}

If the main function returns, the task is ended. First, any modem control sessions started by the application are terminated.

abortAllDialupApps();

Then the task is ended. This will cause all other APPLICATION tasks created by main to be stopped as well. taskStatus = getTaskInfo(0);

end_task(taskStatus.taskID);

1

Stack space is required to create additional tasks. Refer to the create_task function for more

3 information.

2

com3 is used only in the SCADAPack and SCADAPack PLUS controllers.

com4 is used only in the SCADAPack LIGHT and SCADAPack PLUS controllers.

TelePACE C Tools User and Reference Manual

May 9, 2007

13

Data Storage

All non-initialized variables (local and global) are initialized to zero on program startup by the

Microtec C Compiler. The I/O database is the only section of memory that is not initialized to zero on startup. Data stored in the I/O database is maintained when power to the controller is lost, and remains until the controller is initialized from the TelePACE program.

In most cases the I/O database provides adequate space for data storage. However, if additional non-initialized memory is required, for example for an array of custom data structures, an non-initialized section of memory can be created as shown in the example below.

/* ---------------------------------------------------------------- datalog.c

This file contains the global variable definitions for a datalogger database.

These global variables are placed in a non-initialized section called "savedata". All data in these variables will be maintained over powerup.

------------------------------------------------------------------ */

#include <datalog.h>

/* define a non-initialized section called savedata */

#pragma option -NZsavedata

#pragma option -Xp

/* Global variable definitions */

/* log index */ unsigned logIndex;

/* log database */ struct dataLog logData[DATA_LOG_SIZE];

Any variable defined in this file datalog.c will be placed in the non-initialized section arbitrarily named savedata. Code operating on these variables should be placed in a separate file, which references these global variables through external definitions placed in a header file (e.g. datalog.h).

The #pragma option directive is documented in the Microtec MCCM77 Documentation

Set.

Compiling Source Code

The C Compiler converts source code into object files. The basic command line and options required to compile code for the controller are: mccm77 -v -nQ -Ml -c filename.c

A complete description of the command line options is given in the Microtec MCCM77 User’s

Guide. The options used here are:

Option Description

-v

Issue warnings for features in source file. This option allows you to detect potential errors in your source code before running the program.

-nQ

Do not suppress diagnostic messages. This option provides additional warnings that allow you to detect potential errors in your source code before running the program.

-Ml

Compile for large memory model (note that the character following the

TelePACE C Tools User and Reference Manual

May 9, 2007

14

-c

M is a lower case ell).

Compiler output is an object file.

The following options may be useful.

Option Description

-Jdir

Specify the directory containing the standard include files. Adding -

Jc:\telepace\ctools\520x

to the command line allows you to locate your application program files in a different directory. This helps in organizing your files if you have more than one application program.

-O

Enable standard optimizations. This produces smaller and faster executable code.

-Ot

Optimize in favor of execution time rather than code size where a choice can be made.

-nOc Pop the stack after each function call. This increases code size and execution time. This option should only be used if there is a large number of consecutive function calls in your program.

A large number of consecutive calls requires a large stack allocation for a task. Since the number of stack blocks is limited, using this option can reduce the stack requirements for a task. See the description for the create_task function for more information.

Each module in an application should be compiled to produce an object file. The object files are then linked together to form an executable program.

Example

The following commands are required to compile the program described in the previous sections. mccm77 -v -nQ -Ml -c main.c mccm77 -v -nQ -Ml -c func1.c mccm77 -v -nQ -Ml -c func2.c

This produces three output files: main.obj; func1.obj and func2.obj. In the next section these object files will be combined into an executable program.

Linking Object Files

The linker converts object files and object file libraries into an executable program. The basic command line and options to link a program are: lnkm77 -c filename.cmd

Controller programs can execute from RAM, Flash or ROM. The linker command file determines the location of the program.

RAM Based Applications

A sample linker command file for a RAM based program is appram.cmd located in the telepace\ctools\520x directory.

The file begins by specifying the location and order of memory sections. The far_appcode section is the first section in all controller C programs. It contains the start-up code that calls the main() function. In a RAM based program, the start-up code is located at the start of C application program RAM. This address is fixed at 00400000h.

TelePACE C Tools User and Reference Manual

May 9, 2007

15

The order commands specify the order of the sections. The sections are grouped so all the code and static data sections are first. The variable data sections follow. The heap is the last section. It is allowed to grow from the end of the program data to the end of memory (see

Start Up Function Structure section for more information).

The sections may be rearranged, and new sections added, according to the following rules:

• The section must be first in the order listing.

• All code sections must follow the far_appcode section.

• The

section must be the last code section.

• All data sections must follow the code sections.

• The

section must be last in the order listing.

; ----------------------------------------------

; Specify location and order of memory sections

; ---------------------------------------------- sect far_appcode = 00400000h order far_appcode, far_code, (CODE), const order strings, literals, __INITDATA, far_endcode order far_zerovars, far_initvars, (DATA), heap

The next section of the command file creates initialized data sections. All variables in the specified section are initialized at start-up of the program. The linker creates a copy of the data in these sections and stores it in the __INITDATA section.

; ----------------------------------------------

; Create initialized variables section

; ---------------------------------------------- initdata far_initvars

The next section of the command file lists the application program object modules (files) to be included in the program. You may also include libraries of functions you create here. The sample command file includes one object module: app.obj.

; ----------------------------------------------

; Load application program object modules

; ---------------------------------------------- load app

The next section of the command file lists the start-up routines and standard libraries to be included. There are three object modules and two libraries:

Module Description

Appstart.obj

This file contains the application program start up routine

(see Program Architecture section above). If you modify the start-up routine for a particular application, be sure to specify the path to the modified routine.

Romfunc.obj This file contains addresses of the jump table for calling

Ctools.lib functions in the operating system ROM. Only the symbols are loaded as only the addresses are needed.

This is the C Tools library, which contains C Tools functions not found in the operating system ROM. cm77islf.lib

This is the standard Microtec floating point library. cm77islc.lib This is the standard Microtec function library.

; ----------------------------------------------

; Load start up and library routines

; ---------------------------------------------- load c:\telepace\ctools\520x\appstart

TelePACE C Tools User and Reference Manual

May 9, 2007

16

load_symbols c:\telepace\ctools\520x\romfunc load c:\telepace\ctools\520x\ctools.lib load c:\mccm77\cm77islf.lib load c:\mccm77\cm77islc.lib

The final section of the command file specifies the output file format. The listmap command specifies what information is to be included in the map file. Refer to the Microtec manuals for more information on map files.

The format command specifies the executable output will be in Motorola S2 record format.

The TelePACE C Program Loader requires this format.

; ----------------------------------------------

; Specify output file formats and options

; ---------------------------------------------- listmap nopublics, nointernals, nocrossref format S2

Example

The standard command file must be modified to link the application described in the previous example. Copy the appram.cmd file to myapp.cmd. Modify the application object modules section to read:

; ----------------------------------------------

; Load application program object modules

; ---------------------------------------------- load main load func1 load func2

Link the file with the command lnkm77 -c myapp.cmd

This will produce one output file: myapp.abs. The next step is to load it into the controller using the TelePACE C Program Loader.

Flash Based Applications

A sample command file for a Flash based program is appflash.cmd located in the telepace\ctools\520x directory. This file is very similar to the command file for RAM based programs.

The file begins by specifying the location and order of memory sections. There are two types of sections in a Flash based program. The code and static data sections must be stored in the Flash. The variable data sections must be stored in RAM.

The far_appcode section is the first code section in all controller C programs. In a Flash based program, the far_appcode section is located at 110000h.

The far_zerovars section is the first data section. In a ROM based program it is normally located at the start of application program RAM (00400000h). It is possible to start this section at any RAM address, if your application requires it.

The order commands specify the order of the sections. The sections may be rearranged, and new sections added, according to the following rules:

• The

section must be first in the order listing.

• All code sections must follow the far_appcode section.

• The

section must be the last code section.

TelePACE C Tools User and Reference Manual

May 9, 2007

17

• The

section must be the first data section.

• All other data sections must follow the far_zerovars section.

• The

section must be the last data section.

; ----------------------------------------------

; Specify location and order of memory sections

; ---------------------------------------------- sect far_appcode = 00110000h sect far_zerovars = 00400000h order far_appcode, far_code, (CODE), const order strings, literals, __INITDATA, far_endcode order far_zerovars, far_initvars, (DATA), heap

The remaining sections of the file are identical to the RAM command file. Refer to the RAM

Based Applications section for a description.

The final section of the command file specifies the output file format. The default format command specifies the executable output will be in Motorola S2 record format. This is the format required by the TelePACE Flash Loader.

Example – C Program in Flash

The standard command file must be modified to link the application described in the previous example. Copy the appflash.cmd file to myapp.cmd. Modify the application object modules section to read:

; ----------------------------------------------

; Load application program object modules

; ---------------------------------------------- load main load func1 load func2

Link the file with the command lnkm77 -c myapp.cmd

This will produce one output file: myapp.abs. The next step is to write the file to the controller using TelePACE. Use the Flash Loader command on the Controller menu. Consult the TelePACE documentation for details.

ROM Based Applications

A ROM based program is very similar to a Flash based application. However, an EPROM programmer must be used to create the ROM. ROM based programs have access to more program (code) memory than Flash based applications.

It is recommended that Flash based programs be used, unless there is not enough program memory available.

If a ROM based program is created it should be stored in an EPROM. If a Flash based part is used the commands in TelePACE to erase Flash may not work as expected. Contact

Control Microsystems for more information about this.

A sample command file for a ROM based program is approm.cmd located in the telepace\ctools\520x directory. This file is very similar to the command file for Flash based programs.

The file begins by specifying the location and order of memory sections. There are two types of sections in a ROM based program. The code and static data sections must be stored in the ROM. The variable data sections must be stored in RAM.

TelePACE C Tools User and Reference Manual

May 9, 2007

18

The far_appcode section is the first code section in all controller C programs. In a ROM based program, the far_appcode section can be located at any address that is a multiple of 100h in the application ROM. The start of application ROM is fixed at 100000h.

A C application program may share the application ROM space with a ladder logic program.

If only a C program is stored in the ROM the far_appcode section is located at 100000h. If a ladder logic program is stored in ROM it must start at 100000h. The C application can start anywhere after the end of the ladder logic program. This location is determined by the size of the ladder logic program and is best determined by examining the memory image of the ladder logic program in your EPROM programmer.

The far_zerovars section is the first data section. In a ROM based program it is normally located at the start of application program RAM (00400000h). It is possible to start this section at any RAM address, if your application requires it.

The order commands specify the order of the sections. The sections may be rearranged, and new sections added, according to the following rules:

• The

section must be first in the order listing.

• All code sections must follow the far_appcode section.

• The

section must be the last code section.

• The

section must be the first data section.

• All other data sections must follow the far_zerovars section.

• The

section must be the last data section.

; ----------------------------------------------

; Specify location and order of memory sections

;

; Note: the far_appcode section address must

; be a multiple of 100h.

; ---------------------------------------------- sect far_appcode = 00100000h sect far_zerovars = 00400000h order far_appcode, far_code, (CODE), const order strings, literals, __INITDATA, far_endcode order far_zerovars, far_initvars, (DATA), heap

The remaining sections of the file are identical to the RAM command file. Refer to the RAM

Based Applications section for a description.

The final section of the command file specifies the output file format. The default format command specifies the executable output will be in Motorola S2 record format. Your

EPROM programmer may require a different output format. The following options are available. Refer to the Microtec Linker manual for a complete description.

Command Description

format ASCII

Intel ASCII hex format. This is also known as Intel-86 or

Extended Intel Hex format. format IEEE

Microtec extended IEEE-695 format. format S1 Motorola S1 record format. format S2

Motorola S2 record format.

Example – C Program in ROM

The standard command file must be modified to link the application described in the previous example. Copy the approm.cmd file to myapp.cmd. Modify the application object modules section to read:

TelePACE C Tools User and Reference Manual

May 9, 2007

19

; ----------------------------------------------

; Load application program object modules

; ---------------------------------------------- load main load func1 load func2

Link the file with the command lnkm77 -c myapp.cmd

This will produce one output file: myapp.abs. The next step is to program an EPROM using this file.

Example – C and Ladder Logic Program in ROM

The C application program may share the ROM with a ladder logic program. The ladder logic program is always located at 100000h. The C program may start at any address that is a multiple of 100h following the ladder logic program.

The standard command file must be modified to link the application described in the previous examples. Copy the approm.cmd file to myapp.cmd.

Assume for this example that the ladder logic program ends at address 100417h. The next multiple of 100h after this address is 100500h. Modify the section locations to read:

; ----------------------------------------------

; Specify location and order of memory sections

;

; Note: the far_appcode section address must

; be a multiple of 100h.

; ---------------------------------------------- sect far_appcode = 00100500h

Modify the application object modules section to read:

; ----------------------------------------------

; Load application program object modules

; ---------------------------------------------- load main load func1 load func2

Link the file with the command lnkm77 -c myapp.cmd

This will produce one output file: myapp.abs. The next step is to program an EPROM using this file.

Controller Initialization

You should initialize the memory of the controller when beginning a new programming project or when you wish to start from default conditions. It is not necessary to initialize the controller before every program load.

To initialize the controller, first perform a SERVICE boot. A SERVICE boot preserves programs and data in nonvolatile RAM, but does not start the programs running. Default communication parameters are used.

To perform a service boot:

• Remove power from the controller.

TelePACE C Tools User and Reference Manual

May 9, 2007

20

• Press and hold the LED POWER switch.

• Apply power to the controller.

• Wait until the STAT LED on the top of the board turns on.

• Release the LED POWER switch.

Second, initialize the program and data memory in the controller. A new controller will require all initializations be performed. Selected initializations can be performed on a controller that is in use.

• Run the TelePACE program under Microsoft Windows.

• Connect the PC to the controller with the appropriate serial cable. check mark appears beside the desired type when it is selected.

• Select all options: Erase Ladder Logic Program, Erase C Program, Initialize

Controller and Erase Register Assignment Table.

• Click on the OK button.

Loading Programs into RAM

The C Program Loader dialog transfers executable files from a PC to the controller.

To load a program into RAM:

• Initialize the controller (see Controller Initialization section above).

• Load the program into the controller:

• Run the TelePACE program.

• Enter the executable (.abs) file in the edit box for the C Program file name.

• Click on the Write button. The file will be downloaded.

A checksum is calculated for the complete C program. The checksum is verified each time the program is run. This prevents a damaged program from running.

Loading Programs into EPROM

The procedure for creating an EPROM depends on your EPROM programmer. In general you must follow these steps:

• Load the executable file into the programmer and program the EPROM.

• Install the EPROM in the controller.

The controller can accept the following EPROMs. Other EPROMs may be compatible.

Contact Control Microsystems if you are considering using an EPROM not in this list.

Size

(Kbytes)

Manufacturer Part Number

64 AMD AM27C512-70DC

TelePACE C Tools User and Reference Manual

May 9, 2007

21

128 AMD AM27C010-70DC

128 Atmel AT27C010-70PI (one time programmable)

256 AMD AM27C020-70DC

C Programs may be loaded into Flash memory or EPROM when using TelePACE firmware

1.64 or older.

TelePACE firmware 1.65 or newer no longer supports C Programs in Flash memory. C

Programs may be loaded in RAM memory only.

Creating the EPROM

Load the executable (.abs) file into the memory of the EPROM programmer, according to the instructions for the programmer.

The first byte of the EPROM (offset 0 in the EPROM) maps to address 100000h when the

EPROM is installed in the controller. The linker generates an executable file with address offsets starting at 100000h. These offsets must be removed with most programmers, so that the memory image can be placed at offset 0 in the EPROM itself. (Note that this does not affect the addresses in the program itself, just the address at which it loads.)

Consult your EPROM programmer documentation to determine how to remove the offset.

This is typically done in one of two ways:

• Specify the data is to be loaded from file address 100000h. You may have to specify that the file is loaded to offset 0h.

• Or, specify a load offset of –100000h when reading the executable file. The programmer will add –100000h to all load addresses in the file, resulting in a memory image at offset

0h.

Program the EPROM according to the instructions for your programmer.

Installing the EPROM

Install the EPROM in the application ROM socket on the 5203 or 5204 controller board:

• Locate the socket labeled U14. This is the application ROM socket.

• Orient the EPROM so the notch on the EPROM is at the same end as the notch in the socket.

• Align all pins of the EPROM with the socket.

• Press the EPROM gently into the socket.

• Check that all pins are inserted correctly and that none are bent.

Initialize the controller (see Controller Initialization section above). The Erase C Program option must be specified. Other initializations may be performed if desired.

Executing Programs

C application programs are executed when a run program command is received from the

TelePACE C Program Loader; or power is applied to the controller (except when a

SERVICE boot is performed).

TelePACE C Tools User and Reference Manual

May 9, 2007

22

To start a program from the program loader:

• Run the TelePACE program.

The controller will execute either the program in RAM or the program in ROM. It chooses the program to execute in the following order:

• C application program in RAM;

• C application program in ROM;

• no C application (standard start-up sequence for other components).

This mode of operation is useful in the following scenario. A controller is installed with a program in ROM. If new features or corrections are required, a program can be downloaded into RAM, either locally or remotely. This program will take precedence over the program in

ROM.

If the RAM program is lost or damaged, the ROM program will execute. The ROM program can be used as a fallback, performing minimal functions to maintain a process in a fail-safe condition.

TelePACE C Tools User and Reference Manual

May 9, 2007

23

Real Time Operating System

The real time operating system (RTOS) provides the programmer with tools for building sophisticated applications. The RTOS allows pre-emptive scheduling of event driven tasks to provide quick response to real-world events. Tasks multi-task cooperatively. Inter-task communication and event notification functions pass information between tasks. Resource functions facilitate management of non-sharable resources.

Task Management

The task management functions provide for the creation and termination of tasks. Tasks are independently executing routines. The RTOS uses a cooperative multi-tasking scheme, with pre-emptive scheduling of event driven tasks.

The initial task (the main function) may create additional tasks. The RTOS supports up to 16 tasks. There are 5 task priority levels to aid in scheduling of task execution.

Task Execution

SCADAPack controllers can execute one task at a time. The RTOS switches between the tasks to provide parallel execution of multiple tasks. The application program can be event driven, or tasks can execute round-robin (one after another).

Task execution is based upon the priority of tasks. There are 5 priority levels. Level 0 is reserved for the null task. This task runs when there are no other tasks available for execution. Application programs can use levels 1 to 4. The main task is created at priority level 1.

Tasks that are not running are held in queues. The Ready Queue holds all tasks that are ready to run. Event queues hold tasks that are waiting for events. Message queues hold tasks waiting for messages. Resource queues hold tasks that are waiting for resources. The envelope queue holds tasks that are waiting for envelopes.

Priority Inversion Prevention

When a higher priority task, Task H, requests a resource, which is already obtained by a lower priority task, Task L, the higher priority task, is blocked until Task L releases the resource. If Task L is unable to execute to the point where its releases the resource, Task H will remain blocked. This is called a Priority Inversion.

To prevent this from occurring, the prevention method known as Priority Inheritance has been implemented. In the example already described, the lower priority task, Task L, is promoted to the priority of Task H until it releases the needed resource. At this point Task L is returned to its original priority. Task H will obtain the resource now that it is available.

Note that this does not prevent deadlocks that occur when each task requests a resource that the other has already obtained. This “deadly embrace” is a design error in the application program.

Task Management Functions

There are five RTOS functions for task management. Refer to the Function Specification section for details on each function listed.

TelePACE C Tools User and Reference Manual

May 9, 2007

24

create_task

end_task

Create a task and make it ready to execute.

Terminate a task and free the resources and envelopes allocated to it.

end_application Terminate all application program type tasks. This function is used by communication protocols to stop the application program prior to loading new code.

installExitHandler Specify a function that is called when a task is ended with the end_task or end_application functions.

getTaskInfo Return information about a task.

Task Management Macros

The ctools.h file defines the following macros used for task management. Refer to the C

Tools Macros section for details on each macro listed.

RTOS_PRIORITIES

Number of RTOS task priorities.

RTOS_TASKS

STACK_SIZE

TS_EXECUTING

TS_READY

TS_WAIT_RESOURCE

TS_WAIT_ENVELOPE

TS_WAIT_EVENT

TS_WAIT_MESSAGE

Number of RTOS tasks.

Size of the machine stack.

Task status indicating task is executing

Task status indicating task is ready to execute

Task status indicating task is blocked waiting for a resource

Task status indicating task is blocked waiting for an envelope

Task status indicating task is blocked waiting for an event

Task status indicating task is blocked waiting for a message

Task Management Structures

The ctools.h file defines the structure Task Information Structure for task management information. Refer to the C Tools Structures and Types section for complete information on structures and enumeration types.

Resource Management

The resource management functions arbitrate access to non-sharable resources. These resources include physical devices such as serial ports, and software that is not re-entrant.

The RTOS defines nine system resources, which are used by components of the I/O drivers, memory allocation functions and communication protocols.

An application program may define other resources as required. Care must be taken not to duplicate any of the resource numbers declared in ctools.h as system resources.

Resource Management Functions

There are three RTOS functions for resource management. Refer to the Function

Specification section for details on each function listed.

request_resource

Request access to a resource and wait if the resource is not available.

TelePACE C Tools User and Reference Manual

May 9, 2007

25

poll_resource Request access to a resource. Continue execution if the resource is not available

release_resource Free a resource for use by other tasks.

IO_SYSTEM Resource

The IO_SYSTEM resource regulates access to all functions using the I/O system. C application programs, ladder logic programs, communication protocols and background I/O operations share the I/O system. It is imperative the resource is obtained to prevent a conflict, as protocols and background operations are interrupt driven. Do not retain control of the resource for more that 0.1 seconds, or background operations will not execute properly.

DYNAMIC_MEMORY Resource

The DYNAMIC_MEMORY resource regulates access to all memory allocation functions.

These functions allocate memory from the system heap. The heap is shared amongst all tasks. The allocation functions are non-reentrant.

The DYNAMIC_MEMORY resource must be obtained before using any of the following functions.

calloc allocates data space dynamically

free

malloc

realloc frees dynamically allocated memory allocates data space dynamically changes the size of dynamically allocated space

AB_PARSER Resource

This resource is used by the DF1 communication protocol tasks to allocate access to the common message parser for each serial port. This resource is of no interest to an application program. However, an application program may not use the resource number assigned to it.

MODBUS_PARSER Resource

This resource is used by Modbus communication protocol drivers to allocate access to the common message parser by tasks for each serial port. This resource is of no interest to an application program.

Resource Management Macros

The ctools.h file defines the following macros used for resource management. Refer to the

C Tools Macros section for details on each macro listed.

AB_PARSER

DF1 protocol message parser.

COM1_DIALUP

Resource for dialing functions on com1.

COM2_DIALUP

Resource for dialing functions on com2.

COM3_DIALUP

Resource for dialing functions on com3.

COM4_DIALUP

Resource for dialing functions on com4.

DYNAMIC_MEMORY M emory allocation functions.

HART

HART modem resource.

TelePACE C Tools User and Reference Manual

May 9, 2007

26

IO_SYSTEM

I/O system hardware functions.

MODBUS_PARSER

Modbus protocol message parser.

RTOS_RESOURCES

Number of RTOS resource flags.

Inter-task Communication

The inter-task communication functions pass information between tasks. These functions can be used for data exchange and task synchronization. Messages are queued by the

RTOS until the receiving task is ready to process the data.

Inter-task Communication Functions

There are five RTOS functions for inter-task communication. Refer to the Function

Specification section for details on each function listed.

send_message Send a message envelope to another task.

receive_message Read a received message from the task's message queue or wait if the queue is empty.

poll_message Read a received message from the task's message queue. Continue execution of the task if the queue is empty.

allocate_envelope Obtain a message envelope from free pool maintained by the RTOS, or wait if none is available.

deallocate_envelope Return a message envelope to the free pool maintained by the

RTOS.

Inter-task Communication Macros

The ctools.h file defines the following macros used for inter-task communication. Refer to the C Tools Macros section for details on each macro listed.

MSG_DATA

MSG_POINTER

RTOS_ENVELOPES

Specifies the data field in an envelope contains a data value.

Specifies the data field in an envelope contains a pointer.

Number of RTOS envelopes.

Inter-task Communication Structures

The ctools.h file defines the structure Message Envelope Structure for inter-task communication information. Refer to the C Tools Structures and Types section for complete information on structures and enumeration types.

Event Notification

The event notification functions provide a mechanism for communicating the occurrence events without specifying the task that will act upon the event. This is different from intertask communication, which communicates to a specific task.

Multiple occurrences of a single type of event are queued by the RTOS until a task waits for or polls the event.

TelePACE C Tools User and Reference Manual

May 9, 2007

27

Event Notification Functions

There are four RTOS functions for event notification. Refer to the Function Specification section for details on each function listed.

wait_event

poll_event

signal_event

Wait for an event to occur.

Check if an event has occurred. Continue execution if one has not occurred.

Signal that an event has occurred.

interrupt_signal_event Signal that an event has occurred from an interrupt handler. This function must only be called from within an interrupt handler.

There are two support functions, which are not part of the RTOS that may be used with events.

startTimedEvent Enables signaling of an event at regular intervals.

endTimedEvent Terminates signaling of a regular event.

Event Notification Macros

The ctools.h file defines the following macro used for event notification. Refer to the C

Tools Macros section for details.

RTOS_EVENTS

Defines the number of available RTOS events.

System Events

The RTOS defines events for communication port management and background I/O operations. An application program may define other events as required. Care must be taken not to duplicate any of the event numbers declared in ctools.h as system events.

BACKGROUND

This event triggers execution of the background I/O routines. An application program cannot use it.

COM1_RCVR

This event is used by communication protocols to signal a character or message received on com1. It can be used in a custom character handler

(see install_handler).

COM2_RCVR

This event is used by communication protocols to signal a character or message received on com2. It can be used in a custom character handler

(see install_handler).

COM3_RCVR

This event is used by communication protocols to signal a character or message received on com3. It can be used in a custom character handler

(see install_handler).

COM4_RCVR

This event is used by communication protocols to signal a character or message received on com4. It can be used in a custom character handler

(see install_handler).

FOXCOM_MSG_RECEIVED

This event is used when a Foxcom message is received. An application program cannot use it.

FOXCOM_STARTED

This event is used when Foxcom communication has been established with the sensor. An application program cannot use it.

NEVER

This event is guaranteed never to occur. It can be used to disable a task by waiting for it to occur. However, to end a task it is better to use end_task.

This frees all resources and stack space allocated to the task.

TelePACE C Tools User and Reference Manual

May 9, 2007

28

Error Reporting

Sharable I/O drivers to return error information to the calling task use the error reporting functions. These functions ensure that an error code generated by one task is not reported in another task. The errno global variable used by some functions may be modified by another task, before the current task can read it.

Error Reporting Functions

There are two RTOS functions for error reporting. Refer to the Function Specification section for details on each function listed.

check_error Check the error code for the current task.

report_error Set the error code for the current task.

Error Reporting Macros

The ctools.h file defines the following macro used for error reporting. Refer to the C Tools

Macros section for details.

NO_ERROR

Error code indicating no error has occurred.

TelePACE C Tools User and Reference Manual

May 9, 2007

29

SCA DAPack Task Architecture

The diagram shows the tasks present in the SC AD APack controller.

Background I/O Task

Executes every 0.1 s

Processes:

• software timers

• dialup modem

• PID controllers

Priority = 4

Timer Interrupt

240 Hz Interrupt

Processes:

• Ladders timers

• jiffy timer

• watchdog timer

• timed events

Priority = h/w interrupt

Optional User Tasks

Created by user from the Main Task.

Priority = 1 to 4

Com1 Protocol Task

Executes w hen message event occurs

Processes :

• messag e

Priority = 3

Com2 Protocol Task

Executes when message event occurs

Processes:

• message

Priority = 3

Com3 Protocol Task

Executes when message event occurs

Processes:

• message

Priority = 3

Com4 Protocol Task

Executes when message event occurs

Processes:

• message

Priority = 3

Ladders & I/O Scan Task

Task loop runs continuously:

{ while (TRU E)

request _resource(IO_SYSTEM);

read da ta from input modules to I/O database

(Registe r Assignment)

if progr am is in RUN mode e xecute ladder logic program

write da ta from I/O database to output modules

(Registe r Assignment)

}

release _resource(IO_SYSTEM);

release _processor();

Main Task (typical)

Task loop runs continuously:

{ while (TRUE)

request_resource(IO_SYSTEM);

functions requiring IO_SYSTEM resource

release_resource(IO_SYSTEM);

functions not requiring IO_SYSTEM resource

}

release_processor();

Priority = 1 Priority = 1

The hig he st prio rity routines that execute are hardware interrupt handlers. Most hardware interrupt handlers perform their functions tr ansparently. The Timer Interrupt handler is importa nt to application programs , because it updates several timers that can be used in application programs. It also triggers the background I/O task.

The bac kground I/O task is the highest priority task in the system. It processes software timers, PID controllers and dialup modem control routines.

There is one protocol task for each serial port where a protocol is enabled. The protoco l tasks wait for an event signaled by an interrupt handler. This event is signaled when a complete message is received. The protocol tasks process the received message and transmi t a response when needed. Protocol tasks may be disabled and replaced w it h protoco l tasks from the appl ication program.

The Ladder Logic and I/O Scan task executes the Ladder Logic program and performs an

I/O scan based on the register assignment. This task is the same priority as the main user applicat io n task .

TelePACE C Tools User and Reference Manual

May 9, 2007

30

The main task is the central task of the user application. It performs the functions required by the use r. Typically, it executes at the same priority as the Ladder L ogic and I/O Scan task. It may sta rt other u ser tasks if needed.

RTOS Ex pl

The foll ow ing pr ogram is used in the explanation o f the RTOS functions. It creates several simple t as ks tha t demonstrate how tasks execute. A task is a C language function that has as its body an infinite loop so it continues to execute forever.

The main task c reates two tasks. The echoData ta sk is higher priority than main. The auxiliary

tas e task then executes round robin with oth er tasks of the sa me priority.

The aux iliary

task is a simple task that executes round robin wit h the other tasks of its priority.

Only the code ne cessary for task switching is shown to sim plify the example.

The ech oData

task waits for a charac ter to be received on a serial port, then echoes it back out the port . It waits for t he event of the character being received to allo w lower priority tasks to execu te. It installs a character handler function – signalChara cter

– that signals an event e ac a cter is received. This function is h o oked into the receiver interrupt handler for the serial port.

The execution of this program is explained in the Explanation of Task Execution section.

/* --------------------------------------------------------------------

SCADAPack Real Time Operating System Sample

Copyright (c) 1998, Control Microsystems Inc.

Version History version 1.00 Wayne Johnston November 10, 1998

------------------------------------------------------------------ */

/* --- Version 1.00 --------------------------------------------------

This program create s several simple tasks for demonstration of the

functionality of the real time operation system.

------------------------------------------------------------------ */

#include <mriext.h>

#include <stdio.h>

#include "ctools,h"

/* -------------------------------------------------------------------

Constants

-------------------------------------------------------------------- * /

#def ine C HARACTER_RECEIVED 10

/* ------------------------------------------------------------------

signalCharacter

The signalChar acter function signals an event when a character is

received. This function must be called from an interrupt handler.

------------------------------------------------------------------ */ void signalChar acter(unsigned character, unsigned error)

{

/* If there was no error, signal that a cha racter wa s received */ if (erro r == 0)

{

interrupt _sig nal_event(CHARACTER_RECEIVED);

}

/* Prev ent compiler unused variables warning (generates no c ode) */

character;

}

/* --------------------------------------------------------------------

TelePACE C Tools User and Reference Manual

May 9, 2007

31

echoData

The echoData function is a task that waits for a character

to be received on com6 and echoes the character back. It installs

a character handler for com6 to generate events on the reception

of characters.

-------------------------------------------------------------------- */ void echoData(void)

{ struct prot_settings protocolSettings; struct pconfig portSettings;

3

/* Disable communication protocol */ protocolSettings.type = NO_PROTOCOL;

/* Set serial communication parameters */ portSettings.baud = BAUD9600; portSettings.duplex = FULL; portSettings.parity = NONE; portSettings.data_bits = DATA8; portSettings.stop_bits = STOP1; portSettings.flow_rx = DI SABLE; portSettings.flow_tx = DISABLE; portSettings.type = RS232; portSet tings.timeout = 600;

set_por

/* Install handler for received character */

{

/* Wait for a character to be received */

wait_event(CHARACTER_RECEIVED);

/* Echo the character back */

4 9

8

}

}

/* --------------------------------------------------------------------

auxiliary

The auxiliary function is a task that performs some action

required by the program. It does not have specific function so

that the real time operating system features are clearer.

-------------------------------------------------------------------- */ void auxiliary(void)

{

7

{

/* ... add application specific code here ... */

/* Allow other tasks of this p

release_processor();

} riority to run */

}

/* -------------------------------------------------------------------

main

This function creates two tasks: one at priority three and one at

priority 1 to demonstrate the functions of the RTOS.

------------------------------------------------------------------ */ void main(void)

{

/* Create serial communication task */

1

2

TelePACE C Tools User and Reference Manual

May 9, 2007

32

create_task(echoData, 3, APPLICATION, 3);

/* Create a task - same priority as main() task */ create_task(auxiliary, 1, APPLICATION, 2);

{

/* ... add application specific code here ... */

/* Allow other tasks of this priority to execute */

release_processor();

}

}

5

6

Explanation of Task Execution

SCADAPack controllers can execute one task at a time. The Real Time Operating System

(RTOS) switches between the tasks to provide parallel execution of multiple tasks. The application program can be event driven, or tasks can execute round-robin (one after another). This program illustrates both types of execution.

Task ex ecution is based upon the priority of tasks. There are 5 priority levels. Level 0 is reserve d for the null task. This task runs when there are no other ta sks available for execution. Application programs can use levels 1 to 4. The main task is created at priority level 1.

Tasks that are not running are held in queues. The Ready Queue holds all tasks that are ready to run. Event queues hold tasks that are waiting for events. Message queues hold tasks waiting for messages.

Resource queues hold tasks that are waiting for resources. The envelope queue holds tasks that are waiting for envelopes.

The execution of the tasks is illustrated by examining the state of the qu eues at various points in the program. These points are indicated on the program listing above. The example s show only the Ready queue, the Event 10 queue and the execu ting task. These are the only queues relevant to the example.

Execution Point 1

This point occurs just before the main task begins. The main task has not been created by the RTOS. The null task has been created, but is not running. No task is executing.

Ready Queue

4

3

2

1

0 null()

Event 10 Queue

4

3

2

1

0

Running Task

none

Figure 1: Queue Status before Execution of main Task

Execution Point 2

This point occurs just after the creation of the main task. It is the running task. On the next instruction it will create the echoData task.

TelePACE C Tools User and Reference Manual

May 9, 2007

33

1

0

Ready Queue

4

3

2 null()

1

0

Event 10 Queue

4

3

2

Figure 2: Queue Status at Start of main Task

Running Task main()

Execution Point 3

This point occurs just after the echoData task is created. The echoData task is higher priority than the main task so it is made the running task. The main task is placed into the ready queue. It will execute when it becomes the highest priority task.

The echoData task initializes the serial port and installs the serial port handler function signalCharacter

. It will then wait for an event. This will suspend the task until the event occurs.

The signalCharacter function will generate an event each time a character is received without an error.

Running Task echoData()

1

0

Ready Queue

4

3

2 main() null()

1

0

Event 10 Queue

4

3

2

Figure 3: Queue Status after Creation of echoData Task

Execu tion Point 4

This point occurs just after the echoData task waits for event 10. It has been placed on the event queue for event 10 .

The highest priority task on the ready queue was the main task. It is now running. On the next instruction it will create another task at the same priority as main.

TelePACE C Tools User and Reference Manual

May 9, 2007

34

2

1

0

Ready Queue

4

3 null()

Event 10 Queue

4

3

2

1

0 echoData()

Figure 4: Queue Status After echoData Task Waits for Event

Running Task main()

Execution Point 5

This point occurs just after the creation of the auxiliary task. This task is the same priority as the main task. Therefore the main task remains the running task. The auxiliary task is ready to run and it is placed on the Ready queue.

Ready Queue

4

Event 10 Queue

4

Running Task main()

3 3 echoData()

2

1

0 auxiliary() null()

2

1

0

Figure 5 Queue Status after Creation of auxiliary Task

Execution Point 6

This point occurs just after the main task releases the processor, but before the next task is selected to run. The main task is added to the end of the priority 1 list in the Ready queue.

On the next instruction the RTOS will select the highest priority task in the Ready queue.

Running Task

none

1

0

Ready Queue

4

3

2 auxiliary() null() main()

1

0

3

2

Event 10 Queue

4 echoData()

Figure 6: Queue Status After main Task Releases Processor

TelePACE C Tools User and Reference Manual

May 9, 2007

35

Execution Point 7

This point is just after the auxiliary task has started to run. The main and auxiliary tasks will continue to alternate execution, as each task releases the processor to the other.

2

1

0

Ready Queue

4

3 main() nullTask()

2

1

0

Event 10 Queue

4

3 echoData()

Figure 7: Queue Stat

us at Start of auxiliary Task

Running Task auxiliary()

Execution Point 8

This point occurs just after a character has been received. The signalCharacter function executes and signals an even t. The RTOS checks the event queue for the event, and makes the highest priority task ready to execute. In this case the echoData task is made ready.

The RTOS then determines if the new task is higher priority than the executing task. Since the echoData task is higher priority than the auxiliary

task, a task swit ch occurs. The auxiliary

task is placed on the Ready queue. The echoData task e xecutes.

Note the position of auxiliary in the Ready q ueue. The main task will execute before it at the next task switch.

Running Task echoData()

Ready Queue

4

1

0

3

2

main() null() auxiliary()

Event 10 Queue

4

1

0

3

2

Figure 8: Queue Status after Character Received

Execution Point 9

This point occurs just after the echoData task waits for the character-received event. It is placed on the event 10 queue. The highest priority task on the ready queue – main – is given the processor and executes.

TelePACE C Tools User and Reference Manual

May 9, 2007

36

2

1

0

Ready Queue

4

3 auxiliary() null()

1

0

3

2

Event 10 Queue

4 echoData()

9:

ueue Status after echoData Waits for Event

Overview of Programming

Fun ctions

Running Task main()

This section of the User Manual provides and overview of the Functions, Macros, Structure and Types available to the user. The Functions, Macros, Structure and Types overview is separated into sections of related functions. Refer to the Function Specification, C Tools

Macros and C Tools Structures and Types section of this manual for d etailed explanations of the Functions, Macros, Structure and Types describ ed here.

Cont roller Operati on

This section of the manual provides an overview of the TelePACE functions relating to controller ope ration. T hese functions are provide d in addition to the run-time library supplied with the Microtec C compiler.

Start Up Functions

There are tw o library f unctions related to the sy stem or application start up task. Refer to the

Function Specification section for details on each fun ction listed.

startup_task

R etu rns the address of the system start up routine.

system_start

The default start up routine.

Start Up Macros

The ctools.h file defines the following macros for use with the start up task. Refer to th e C

Tools Macros section for details on each macro listed.

STARTUP_APP LICA TION

Specifies the application start up task.

STARTUP_SYSTEM

Specifies the system start up task.

Start Up Task Info Structure

The ctools.h file defines the structure Start Up Information Structure for use with the startup_task f unc tion. Refer to the C Tools Structures and Types section fo r complete information on structures and enumeration types.

TelePACE C Tools User and Reference Manual

May 9, 2007

37

Program Status Information Functions

There are five library functions related to controller program status information. Refer to the

Function Specification section for details on each function listed.

applicationChecksum

Returns the application program checksum.

getBootType

Returns th e controller boot up status.

getProgramStatus

Returns the application program execution status.

setBootType

Sets the controller boot up status.

setProgramStatus

Sets the application program execution status.

Program Status Information Macros

The ctools.h file defines the following macr os for use with controller program information.

Refer to the C Tool s Macros section for details on each macro listed.

NEW_PROGRAM

A pplica tion program is newly loa ded.

PROGRAM_EXECUTED

COLD_BOOT

RUN

SERVICE

REENTRY_BOOT

Application program has been executed .

Controller started in COLD BOOT mode.

Co ntroller started in RUN mode.

Controller started in SERVICE mode.

Controller Information Functions

There is one library function related to controller information. Refer to the Function

Specification section for details on the function listed.

getControllerID

Returns the controller ID string.

Controller Information Macros

The ctools.h file defines the following macros for use with controller information. Refer to the Function Specification section for details on each macro listed.

AB_PROTOCOL DF1

protocol firmware option

BASE_TYPE_MASK

FT_NONE

Controller type bit mask

Unknown firmware type

FT_TELEPACE

FT_ISAGRAF

GASFLOW

TelePACE firmware type

ISaGRAF firmware type

Gas Flow calculation firmware option

RUNS_2

SCADAPACK

SCADAPACK_LIGHT

Set if Gas Flow supports two meter runs

SCADAPack controller

SCADAPack LIGHT controller

SCADAPack PLUS controller

SCADAPACK_

PLUS

UNKNOWN_CONTOLLER

Unknown controller type

TelePACE C Tools User and Reference Manual

May 9, 2007

38

F mware Version Information Function s

re version. Refer to the Function

Specification section for details.

getVersion

Returns controller firmware version information.

Firmware Version Information Macros

The ctools.h file defines the following macros for use with the f irmware version function.

Refer to the C Tools Macros section for details on each macro listed.

VI_DATE_SIZE

Number of characters in the version information date field.

VI_STRING_SIZE

Number of characte rs in the version information copyright field.

Firmware Version Information Structure

The ctools.h file defines the structure Version Information Structu re for controller firmware version information. Refer to the C Tools Structures and Types s ection for complete information on structures and enumeration types.

Sleep Mode Functions

SCADAPack controllers are capable of extremely low power operation when in sleep mode.

SCADAPack controllers enter the sleep mode under control of the ap plication program.

Refer to the SCADAPack System Hardware Manual for further infor mation on controller sleep mode. The SCADAPack 100 and the SCADASesne series of controllers do not support sleep mode.

There are three library functio ns related to sleep mode. Refer to the Function Specification section for details on each function listed.

getWakeSource

Gets wake up sources

setWakeSource sleep

Sets wake up sources

Put controller into sleep mode

Sleep Mode Macros

The ctools.h file defines the following macros for use sleep mode. Refer to the C Tools

Macros section for details on each macro listed.

SLEEP_MODE_SUPPORTED

WS_ALL

WS_COUNTER_1_OVERFLOW

WS_INTERRUPT_INPUT

WS_LED_POWER_SWITCH

WS_NONE

WS_REAL_TIME_CLOCK

WS_UNDEFINED

Defined if sleep function is supported

All wake up sources enabled

B it mask to enable counter 0 overflow as wake up source

Bit ma sk to enable counter 1 overflow as wake up source

Bit mask to enable counter 2 overflow as wake up source

Bit mask to enable interrupt input as wake up source

Bit mask to ena ble LED power switch as wake up source

No wake up source enabled

Bit mask to enable real time clock as wake up source

Undefined wake up source

TelePACE C Tools User and Reference Manual

May 9, 2007

39

Power Management Functions

Under normal operation, the SCADAPack 350 operates on a CPU clock frequency of 32

MHz. However, the SCADAPack 350 controller is capable of operating on a reduced CPU clock frequency of 8 MHz, known as Reduced Power Mode.

Further power savings can be realized on the SCADAPack 350 controller by disablin g the

LAN or USB peripheral and host ports. Activation of Reduced Power mode as well as the deactivation of the communication ports can be performed by the application program.

The library functions associated with the aforementioned power management allows for the following:

• The CPU speed can be changed from full speed (32 MHz) to reduced speed (8 MHz).

• The LAN port can be enabled or disabled

• The USB peripheral port can be enabled or disabled erating in Reduced

Power Mode.

The library functions associated with the power management fe atures are listed below.

Refer to the Function Specification section for details on ea ch function listed.

getPowerMode

Gets the current power mod e

setPowerMode

Sets the power mode

Power Management Macros

The ctools.h file defines the following macros for use in the power management functions.

Refer to the C Tools Macros section for d etails on each macro listed.

PM_CPU_REDUCED

The CPU is set to run at a red uced speed

The CPU is set to sleep mode

PM_LAN_DISABLED

PM_USB_PERIPHERAL_ENABLED

PM_UNAVAILABLE

The LAN is disabled

The USB peripheral port is enabled

PM_USB_PERIPHERAL_DISABLED

The USB peripheral port is disabled

PM_USB_HOST_ENABLED

PM_USB_HOST_DISABL ED

The USB host port is enabled

The USB host port is disabled

The status of the device could not be read

Configuration Data EEPROM Functions

The EEPROM is nonvolatile memory used to s tore configuration parameters. The application program cannot store application data into this memory. It can cause the system configuration parameters to be written, using the save function.

The contents of the EEPROM are copied to RAM under two condition s: during a RUN boot of the controller; and when the application pro gram executes the load function.

The following data is loaded on a RUN boot; otherwise default info rmation is used:

TelePACE C Tools User and Reference Manual

May 9, 2007

40

• serial port configuration tables

• protocol configuration tables

• enable store and forward settings

• LED power settings

• mask for wake-up sources

• execution period on power-up for each PID

There are two library functions related to the configuration data EEPROM. Refer to the

Function Specification section for d etails on each function listed.

load

Reads configuration data from EEPROM into RAM

Configuration Data EEPROM Macros

The ctools.h file defines the following macros for use with the configuration data EEPROM.

Refer to the C Tools Macros section for details on each macro li sted.

EEPROM_EVERY

EEPROM_RUN

EEPROM section loaded to RAM on every CPU reboot.

EEPROM section loaded to RAM on RUN type boots only.

EEPROM_SUPP

ORTED

If defined, indicates that there is an EEP ROM in the controller.

I/O Bus Communication Functions

The ctools.h file defines the following functions that access the I/O bus. The I/O bus is I

2

C compatible. Refer to the Function Specification section for details on each function liste d.

ioBusReadByte

Reads on e byte from an I

2

C slave device

ioBusReadLastByte

Reads one byte from an I

2

C slave device and terminates re ad

ioBusReadMessage

Reads a message from an I

2

C slave device

ioBusSelectForRea d

Selects an I

2

C slave device for reading

ioBusSelectForWrit e

Selects an I

2

C slave device for writing

ioBusStart

2

Issues a n I C bus START condition

ioBusStop ioBusWriteByte

Issues an I

2

C bus STOP condition

Writes one byte to an I

2

C slave device

ioBusWriteMessag e

Writes a message to an I

2

C slave device

I/O Bus Communication Macros

The ctools.h file defines the following macros for use with I/O Bus Communication. Refer to the C Tools Macros section for details on each macro listed.

The ctools.h file defines the following macros.

READSTATUS

WRITESTATUS

enumeration type ReadStatus enumeration type WriteStatus

TelePACE C Tools User and Reference Manual

May 9, 2007

41

I/O Bus Communication Types

The ctool s.h file defines the enumeration types ReadStatus and WriteStatus. Refer to the

C Tools St ructur

es and Types section for complete informatio n on structures and enumeration types.

System Functions

The ctools.h file defines the following functions for system initialization and for retrieving system information. Some of these functions are primarily use d in the appstart.c routine, having limited use in an application program.

Refer to the Function Specification section for details on each function listed.

applicationChecksum

Returns the application program checksum.

ioClear ioDatabaseRes et

Clears all I/O points

Resets the controller to default settings.

ioRefresh ioReset

Refresh outputs with internal data

Reset all I/O modules

Controller I/O Hardware

This section of the manual provides an overview of the TelePACE C Tools functions relating to controller signal input and output (I/O). These functions are provided in addition to the run time library supplied with the Microtec C compiler.

Analog Input Functions

The controller supports internal analog inputs and external analog input modules. Refer to the SCADAPack System Hardware Manual for further information on controller analog inputs and analog input mo dules.

There are several library functions related to internal analog inputs and analog input modules. Refer to the Function Specification section for details on each functio n listed.

readBattery

readThermistor

readInternalA

D

Read the controller RAM battery vo ltage.

Read the controller ambient temperature sensor.

Read the controller internal AD convert er.

ioRead4Ain

Read 4 analog inputs into I/O database.

ioRead8Ain Read 8 analog inputs into I/O database.

IoRead4202Inputs Read the digital, counter and analog inputs from a SCADASense

4202 DR.

IoRead4202DSInputs Read the digital, counter and analog inputs from a SCADASense

4202 DS.

ioRead5505Inputs Read the digital and analog inputs from a 5505 I/O Module.

ioRead5506Inputs Read the digital and analog inputs from a 5506 I/O Module.

ioRead5601Inputs Read the digital and analog inputs from a SCADAPack 5601 I/O

Module.

TelePACE C Tools User and Reference Manual

May 9, 2007

42

ioRead5602Inputs Read the digital and analog inputs from a SCADAPack 5602 I/O

Module.

ioRead5604Inputs Read the digital and analog inputs from a SCADAPack 5604 I/O

Module.

ioRead5606Inputs Read the digital and analog inputs from a 5606 I/O Module.

ioReadLPInputs Read the digital and analog inputs from the SCADAPack LP I/O.

ioReadSP100Inputs Read the digital and analog inputs from the SCADAPack 100 I/O.

Analog Input Macros

The ctools.h file defines the following macros for use with controller analog inputs. Refer to the C Tools Macros section for details on each macro listed.

AD_BATTERY

AD_THERMISTOR

T_CELSIUS

Internal AD channel connected to lithium battery.

Inter nal AD channel connected to thermistor.

Spec ifies temperatures in degrees Celsius.

T_FAHRENHEIT

T_KELVIN

T_RANKINE

Specifies temperatures in degrees Fahrenheit.

Spec ifies temperatures in degrees Kelvin.

Specifies temperatures in degrees Rankine.

Analog Output Functions

The controller supports external analog output modules. Refer to the SCADAPack Sys

tem

Hardware Manual for further information on these modules.

There are three library functions related to analog output modules. Refer to the Function

Specification section for details on each function listed.

ioWriteAout ioWrite2Aout ioWrite4Aout

Write to 4 analog outputs from I/O database.

Write to 2 analog outputs from I/O database.

Write to 4 analog outputs from I/O database.

IoWrite4202Outputs

Write to the analog outputs of a SCADASense 4202 DR.

IoWrite4202OutputsEx Write to analog outputs of a SCADASense 4202 DR with ext ended

IO (4202 DR with a digital output).

ioWrite5303Aout

Write to analog outputs of the 5303 module from I/O database.

ioWrite5606Outputs

Write to the digital and analog outputs of 5606 I/O Module.

ioWriteLPOutputs

Writes data to the digital and analog outputs of the SCADAPack LP

I/O.

Digital Input Functions

The controller supports internal digital input s and external digital input modules. Refer to the

SCADAPack System Hardware Manual for further information on controller digital inputs and digital input modules.

There are several library functions related to digital inputs and external digital input mod ules.

Refer to the Function Specification section for details on each function listed.

interruptInput Read the controller interrupt input.

TelePACE C Tools User and Reference Manual

May 9, 2007

43

readCounterInput

Read the status of the counter input points on the controller board.

ioRead8Din re ad 8 digital inputs into I/O database.

ioRead16Din

IoRead32Din read 16 digital inputs into I/O database. read 32 digital inputs into I/O database.

IoRead4202Inputs Read the digital, counter and analog inputs from a SCADASense

4202 D R.

IoRead4202DSInputs Read the digital, counter and analog inputs from a SCADASense

4202 DS.

ioRead5505Inputs

Read the digital and analog inputs fro m a 5505 I/O Module.

ioRead5506Inputs Read the digital and analog inputs from a 5506 I/O Module.

ioRead5601Inputs Read the digital and analog in puts from a 5601 I/O Module.

ioRead5602Inputs Read the digital or analog inputs from a 5602 I/O Module.

ioRead5604Inputs Read the digital and analog inputs from a SCADAPack 5604 I/O

Module.

ioRead5606Inputs Read the digital and analog inputs from a 5606 I/O Module.

ioReadLPInputs Read the digital and analog inputs from the SCADAPack LP I/O.

ioReadSP100Inputs Read the digital and analog inputs from the SCADAPack 100 I/O.

Digital Output Func tions

The controller supports external digital output modules. Refer to the SCADAPack Syste

m

Hardware Manual for further information on controller digital output modules.

There are several library functions related to digital output m odules. Refer to the Function

Specification

section for details on each function listed.

interruptInput ioWrite16Dout

IoWrite32Dout

Read the controller interrupt input.

Write data to any 1 6 point Digital output module.

Write data to any 32 point Digital output module.

IoWrite4202OutputsEx

ASense 4202 DR with extended IO (with digital output) from I/O database.

IoWrite4202DSOutputs Write to digital outputs of the SC database.

ADASense 4202 DS from I/O

ioWrite5601Outputs

Write to the digital an d analog outputs of SCADAPack 5601 I/O

Module.

ioWrite5602Outputs

Write to the digital and analog outputs of SCADAPack 5602 I/O

Module.

ioWrite5604Outputs

Write to the digital and analog outputs of SCADAPack 5604 I/O

Module.

ioWrite5606Outputs

Write to the digital and analog outputs of 5606 I/O Module.

ioWrite8Dout

Write data to any 8 point Digital output module.

ioWriteLPOutputs

Writes data to the digital and analog outputs of the SCADAPack LP

I/O.

TelePACE C Tools User and Reference Manual

May 9, 2007

44

ioWriteSP100utputs Writes data to the digital outputs of the SCADAPack 100 I/O.

Counter Input Functions

The controller supports internal counters and external counte r modules. The counter registers are 32 bits, for a maximum count of 4,294,967,295 . They roll over to 0 on the next count. The counter inputs measure the number of rising inputs. Refer to the

SCADAPack

System Hardware Manual for further information on cont roller counter inputs and counter input modules.

There are four library functions related to counters. Refer to the Function Specification section for details on each function listed.

readCounter Read a SCADA Pack, SCADAPack LP or SCADAPack 100 counter with or without automatic clearing of the counter register.

interruptCounter

ioRead4Counter

Read the SCADAPack or SCADAPack LP interrupt input as a counter with or without automatic clearing of the counter value.

Read any 4 point Counter input module.

IoRead4202Inputs

Read the digital, counter and analog inputs from a SCADASense

4202 DR.

IoRead4202DSInputs Read the digital, counter and analog inputs from a SCADAense

4202 DS.

Counter Input Macros

The ctools.h file defines the following macro for use with counter inputs. Refer to the C

Tools Macros section for deta ils.

LOCAL_COUNTERS

Number of controller counter inputs.

Status LED and Output Functions

The status LED and output indicate alarm conditions. The STAT LED blinks and the

STATUS output opens when an alarm occurs. The STAT LED turns off and the STATUS output closes when all alarms clear.

The STAT LED blinks a binary sequence indicating alarm codes. The sequences consist of long and short flashes, followed by an off delay of 1 second. The sequence then repeats.

The sequence may be read as the Controller Status Code.

Refer to the SCADAPack System Hardware Manual for further information on the status

LED and digital output. There is no status output on the SCADASense series of programmable controllers.

There are two library functions related to the status L ED and digital output. Refer to the

Function Specification section for details on each function listed.

clearStatusBit

Clears bits in controller st atus code.

setStatusBit

Sets

code.

Status LED and Output Macr os

The ctools.h file defines the following macros for use with the status LED and digital output.

Refer to the C Tools Macros section for details on each macro listed.

TelePACE C Tools User and Reference Manual

May 9, 2007

45

S_MODULE

_FAILURE

S_NORMA

L

Status LED code for I/O module co mmunication failure

Status LED code for normal status

Options Switches Functio ns

The controller has three option switches located under the cover of the controller module.

These switches are labeled OPTION 1,2 and 3. The option switches are user defined excep t when a SCADAPack I/O module or SC ADAPack AOUT module used. In this case option switches 1 and 2 select the analog ranges. Refer to the SCADAPack System Hardware

Manual for further information on option switches.

There are no option switches on the SCADAPack 100, SCADAPack LP or the SCADA Sense series of programmable controllers. ated to the controller option switches. Refer to the Function

Specification section for detail s.

optionSwitch

Read option switch states.

Option Switches Macros

The ctools.h file defines the following macros for use with option switches. Refer to the C

Tools Macros section for details on each macro listed.

CLOSED

Spec ifies switch is in closed position

OPEN

Specifies switch is in open position

LED Indicators Functions

An application program can control three LED indicators.

The RUN LED indicates the execution status of the program. The LED can be on o r off. It remains in the last state until changed.

The ST AT LED indicat es error conditions. It outputs an error code as a binary sequence.

The sequence repeats until a new error code is output. If the erro r code is zero, the status

LED turns off.

The FORCE LED indicates lock ed I/O variables. Use this function with caution in application programs.

There are three library functions related to the LED indicators. Refer to the Function

Specification

section for details on each function listed.

runLed

Controls the RUN LED status.

setStatus forceLed

Sets controller status code.

Sets state of the force LED.

LED Indicator s M acros

The ctools. h file defin es the following macros for use with L ED power control. Refer to the C

Tools Macros section for details on each macro listed.

LED_OFF

Specifies LED is to be turned off.

LED_ON

Specifies LED is to be turned on.

TelePACE C Tools User and Reference Manual

May 9, 2007

46

LED Power Control Functions

The controller board can disable the LEDs on the controller board, the 5601, 5602 or 560 4

I/O modules and the 50 00 Series I/O modules to conserve power. This is particularly useful in solar powered or unattended installations. Refer to the SCADAPack S

ystem Hardware

Manual

for further information on LED powe r control.

There a re four library functions related to LED power control. Re fer to the Function

Specifi

cation section for details on each function listed.

ledGetD ledPow efault er

Get default LED power state

Set LED power state

ledPow erSwitch ledSetD efault

Read LED power swi tch

Set default LED power state

LED Power Control Macros

The ctools.h file defines the following macros for use with LED power control. Refer to the C

Tools M

acros section for details on each macro listed.

LED_OFF

LED_ON

Specifies LED is to be turned off.

Specifies LED is to be turned on.

LED P o wer C ontrol Structure

The cto ols.h file defines the structure LED Power Con trol Structure for LED power control informa tion. Refer to the C Tools Structures and Type s section for complete information on struc tures and enumeration types.

Softw are Timer Functions

The controller provides 32 powerful software timers, which greatly simplify the task of programming time-related functions. Uses include:

• generation of time delays

• timing of process events such as tank fill times

• gen eration of time-based interrupts to schedule regular activ ities

• con trol of digital outputs by time periods

The 32 tim ers are individually programmable for tick rates from te n per second to once every

25.5 se co n d s. Time periods from 0.1 second to greater than nineteen days can be measur ed and controlled.

All time rs operate in the background from a hardwa re interrupt generated by the main system clock. Once loaded, they count without intervention from the main program.

There a re four library functions related to time rs. Refer to the Function Specification section for details on each function listed.

interval

Set timer tick interv al in tenths of seconds.

settime

r

timer

read_timer_info

Set a timer. Timers count down from

Read the time period the set value to zero. remaining in a timer.

Read information about a software timer.

TelePACE C Tools User and Reference Manual

May 9, 2007

47

Software Timer Macros

The ctools.h file defines the following macros for use with timers. Refer to the C Too

ls

Macros section for details on each macro listed.

NORMAL

TIMED_OUT

Specifies normal count down timer.

Specifies timer is has reached zero.

TIMER_BADINTERVAL

TIMER_BADTIMER

TIMER_BA

DVALUE

TIMER_MA

X

Error code indicating invalid timer in terval.

Error code indicating invalid timer.

Error code indicating invalid time value.

Number of last valid software timer.

Timer Information Structure

The ctools.h file defines the structure Timer Info rmation for timer information. Refer to the

C Tools Structures and Types section for complete information on structures and enumeration types.

Timer Example Programs

Example 1: Turn on a digital output assigned to coil register 1 and w ait 5 seconds before turning it off.

interval(0,10); /* timer 0 tick rate = 1 second */ request_resource(IO_ SYSTEM); setdbase(MODBUS, 1, 1); /* turn on output */ release_resource(IO_SYSTEM); settimer(0,5); /* load timer 0 with 5 seconds */ while(timer(0)) /* wait until time expires */

{

/* Allow other tasks to execute */ release_p rocessor();

} request_resource(IO_SYSTEM); release_resource(IO_SYSTEM);

Example 2: Time the duration a contact is on but wait in loop to me asure time.

Contact is assigned to status register 10001.

interval(0,1); /* tick rate = 0.1 second */ request_resource(IO_SYSTEM); if (dbase(MODBUS, 10001)) /* test if contact is on */

{ settimer(0,63000); /* start timer */ while(dbase(MODBU S, 10001)) /* wait for turn off */

{

/* Allow o ther tasks to execute */

release_resourc e(IO_SYSTEM);

release_process or();

request_resource(IO_SYSTEM);

} printf("time period = %u\r\n",63000-timer(0));

}

TE M) ;

Examp 3: nd print alarm message i f not full in 1 minute.

Contact is assigned to status register 10001. Valve is controlled by coil register 1.

TelePACE C Tools User and Reference Manual

May 9, 2007

48

interval(0,10); /* timer 0 tick rate = 1 second */ request_resource(IO_SYSTEM); setdbase(MODBUS, 1, 1) ; /* open valve */ se tt imer(0,60); /* set timer for 1 minute */

/* tank not full if contact is off */ wh il e((dbase(MODBUS, 10001)== 0) && timer(0))

{

/* Allow other tasks to execute */

release_resource(IO_SYS TEM); release_processor();

request_resource(IO_SYSTEM);

} if (dbase(MODBUS, 10001)== 0) puts("tank is not filling!!\r\n"); else puts("tank full\r\n"); setdbase(MODBUS, 1, 0); /* close valve */ release_resource(IO_SYSTEM);

Real T ime Cloc k Functions

The controller is provided with a hardware based real time clock that independently main tains the time and date for the operat ing system. The time and date remain accurate during power-off. This allows the controller to be synchronized to time of day for such functions as shift production reports, autom atic instrument calibration, energy logging, etc.

The calendar can be used to automatically take the controller off-line during weekends and holidays. The calendar automatically handles leap years.

There are eight libr ary functions, which access the real-time clock. Refer to the Function

Specification section for details on each function listed.

alarmIn

Returns absolute time of alarm given elapsed time

getclock getClockAlarm getClockTime

Read the real time clock.

Reads the real time clock alarm settings.

Read the real time clock.

installClockHandler

Installs a handler for real time clock alarms.

resetClockAlarm

Resets the real time clock alarm so it will recur at the same time next day.

setclock

Set the real time clock.

setClockAlarm

Sets real time clock alarm.

Real Time Clock Macros

The ctools. h file defines the following macros for real time clock alarms. Refer to the C

Tools Macros section for details on each macro listed.

AT_ABSOLUTE

AT_NONE

Specifies a fixed time of day alarm .

Disables alarms

Real Time Clock Structures

The ctools.h file defines the structures Real Time Clock Structure and Alarm Settings

Structure for real time clock information. Refer to the C Tools Structures and Types section for complete information on structures and enumeration types.

TelePACE C Tools User and Reference Manual

May 9, 2007

49

Real Time Clock Program Example

The following program illustrates how the date and time can be set and displayed. All field s of the c lock structure must be set with valid values for the clock to operate properly.

#include <ctools.h> void main(void)

{ struct clock now;

/* Set to 12:01:00 on January 1, 1994 */ now.hour = 12; /* set the time */ now.minute = 1; now.second = 0; now.day = 1; /* set the date */ now.month = 1; now.year = 94; now.dayofweek = 6; /* day is Sat. */

request_resource(IO_SYSTEM);

setclock(&now ); now = getclock();

release_resource(I O_SYSTEM);

/* Display current hour, minute and second */ printf("%2d:%2d:%2d", now.hour, now.minute,

now.second);

}

The Jiffy Clock

The jiffy clock is a counter that increments 60 times per second. The jiffy clock is useful for measuring execution times or generating d elays where a fine time base is required. The clock is reset to zero each time power is applied to the controller. It rolls over to zero after it reaches a value of 5183999. This is the number of 1/60-second intervals in 24 hours.

There are two library functions, which access the real-time clock. Refer to the Func

tion

Specification C Func tion Library chapter for a complete description.

setjiffy set the jiffy clock

jiffy rea d the jiffy clock

Watchdog Timer Functions

A watchdog timer is a hardware device, which enables rapid detection of computer hardware or software problems. In the event of a major problem, the CPU resets and the application program restarts.

The controller provides an integral watchdog timer to ensure reliable op eration. The watchdog timer resets the CPU if it detects a problem in either the hardware or system firmware. A user program can take control of the watchdog timer, so it will detect abnormal execution of the program.

A watchdog timer is a retriggerable, time delay timer. It begins a timing sequence e very time it receives a reset pulse. The time delay is adjusted so that regular reset pulses prevent the timer from expiring. If the reset pulses cease, the watchdog timer expires and turns on its output, signifying a malfunction. The time r output in the controller resets the CPU and turns off all outputs at the I/O system.

TelePACE C Tools User and Reference Manual

May 9, 2007

50

The watchdog timer is normally reset by the operating system. This is transparent to the application program. Operating in such a fashion, the watchdog timer detects any hardware or firmware problems.

The watchdog timer can detect failure of an application program. The program takes co ntrol of the timer, a nd resets it regularly. If unexpected operation of the program occurs, the reset pulses cease, and the watchdog timer resets the CPU. The program restarts from the beginning.

There are three library functions related to the watchdog timer. Refer to the Function

Specification section for details on each function listed.

wd_auto

w

d_manual

Gives control of the watch dog timer to the operating system (default).

Give s contr ol of the watchd og time r to an applicati on program.

w

d_pulse Ge nerates a watch dog res et pulse .

A watchdog reset pulse must be generated at least every 500 ms. The CPU resets, and program execution starts from the beginning of the program, if the watchdog timer is not re set.

Watchdog Timer Program Example

The following program segment shows how the watchdog timer could be used to detect the failure of a section of a program. wd_manua l (); / * take contr ol of wa tchdo g timer */ do {

/* pro gram cod e */ wd_pulse(); /* reset the watchdog timer */

} while (condition) wd_auto(); /* return control to OS */

Note: Always pass control of the watchdog timer back to the operating system before stopping a program, or switching to another task that expects the operating sy stem to reset the timer.

Checksum Functions

To simplify the implementation of self-checking comm unication algorithms, the C Tools provide four types of checksums: additive, CRC-16, CRC-CCITT, and byte-wise exclusive -

OR. The CRC algorithms are particularly reliable, employing various polynomial methods to detect nearly all communication erro rs. Additional types of checksums are easily implemented using library functions.

The re are two library functions related to checksums. Refer to the Fun ction Specification section for details on each function listed.

che

cksum Calculates add checksums itive, CRC-16, CRC-CCITT and exclusive-OR type

crc_reverse Calculates custom CRC type checksum using reverse CRC algorithm.

Checksum Macros

The ctools.h file defines macros for specifying checksum types. Refer to the C Too

ls

Macros section for details on each macro listed.

TelePACE C Tools User and Reference Manual

May 9, 2007

51

ADDITIVE

checksum

BYTE_EOR

Byte-wise exclusive OR checksum

CRC_16

CRC_CCITT

CRC-16 type CRC checksum (reverse algorithm)

CCITT type CRC checksum (reverse algorithm)

Seria l Communication

The SCADAPack family of controllers offers three or four RS-232 serial ports. The

TeleSAFE Micro16 has two RS-232 serial communication ports. (com1 on all contro llers is also available as an RS-485 port.) The ports are configurable for baud rate, data bits, stop bits, parity and communication protocol.

To optimize performance, minimize the length of messages on co m3 and com4. Examples of recommended uses for com3 and com4 are for local operator display termin als, and for programming and diagnostics using the ISaGRAF program.

For the SCADASense series of programmable controllers, com1 is not available for C applications.

Default Serial Parameters

All ports are configured at reset with default parameters when t he controller is powered up in

SERVICE mode. The ports use stored parameters when the controller is reset in the RUN mode. The default parameters are listed below.

Parameter om4

Parity none none None None

Stop 1 1 1 1

RTU

Modb us

RTU

Modbus

RTU

Modbus RTU

Rx flow control off

Tx flow control off

Serial time out 60 s

Type off off

60 s

Rx disable

Off

60 s

Rx disable

Off

60 s

RS-232 RS-232 RS-232 RS-232

Serial Communication Time Out

When the controller is transmitting data on the communication po rts, the transmit buffer may become full due to receipt of an XOFF character, a slow baud rate , or improper hardware handshaking.

If the transmit buffers become full, the task transmitting data is bloc ked until space is available or the serial time out period expires. If no space is availab le at the conclusion of this time period, the transmit buffer is emptied. The task then conti nues execution.

Debugging Serial Communication

Serial communication can be difficult to debug. This section describ es the most common causes of communication failures.

TelePACE C Tools User and Reference Manual

May 9, 2007

52

• To communicate, the controller and an external device must use the same communication parameters. Check the parameters in both units.

• If some but not all characters transmit properly, you probably have a pa rity or stop bit mismatch between the devices.

The connection between two RS-232 Data Terminal Equipment (DTE) devic es is made with a null-modem cable. This cable connects the transmit data ou tput of one device to the receive data input of the other device – and vice versa. The c ontroller is a DTE device. This cable is described in the System Hardware Manual for your controller.

The connection between a DTE device and a Data Communication Equipment (DCE) device is made with a straight cable. The transmit data output of the DTE device is connected to the transmit data input of the DCE device. The receive data input of the DTE device is connected to the receive data output of the DCE device . Modems are usually DCE devices.

This cable is described in the System Hardware Manu al for your controller.

Many RS-232 devices require specific signal levels on certain pins. Communication is not possible unless the required signals are present. In the controller the CTS line must be at the proper level. The controller will not transmit if CTS i s OFF. If the CTS line is not connected, the controller will force it to the proper val ue. If an external device controls this line, it must turn it ON for the controller to transmit.

Serial Communication Functions

The ctools.h file defines the following serial communication related functions. Refer to the

Function Specification section for details on each function listed . Additional serial communication functions are included in the Microtec run-time library.

clear_errors

Clear serial port error counters.

clear_tx get_port

GetPortCharacteristics get_status install_handler portConfiguration portIndex portStream queue_mode route setDTR set_port

Clear serial port transmit buffer.

Read serial port communication parameters.

Read information about features supported by a serial port.

Read serial port status a nd error counters.

Install serial port character received ha ndler.

Get pointer to port configuration table

Get array index for serial port

Get serial port corresponding to in dex

Set serial port transmitter mod e.

Redirect standard I/O stream s.

Control RS232 port DTR signal.

Set serial port comm unication parameters.

Serial Communication Macros

The ctools.h file defines macros for specifyin g serial communication parameters. Refer to the C Tools Macros section for details on each macro listed.

BAUD75

Specifies 75-baud port speed.

BAUD110

BAUD150

Specifies 110-baud port speed.

Specifies 150-baud port speed.

TelePACE C Tools User and Reference Manual

May 9, 2007

53

BAUD300

BAUD600

BAUD1200

BAUD24

00

BAUD48

00

BAUD96

00

BAUD19

200

BAUD38

400

BAUD57

600

BAUD1

15200

com1

com2

com3

com4

DATA7

DATA8

DISABL

E

ENABLE

EVEN

FULL

FOPEN_MAX

HALF

NONE

NOTYPE

ODD

PC_FLOW_RX I

PC_FLOW_RX_XON_X

OFF

PC_FLOW_TX_IGNORE_CTS

PC_FLOW_TX_X X

RS232

RS232_MODEM

RS485_4WIRE

SERIAL_PORTS

SIGNAL_CTS

SIGNAL_DCD

SIGNAL_OFF

SIGNAL_OH

OP

Specifies 300-baud port speed.

Specifies 600-baud port speed.

Specifie s 1200-baud port speed.

Specifies 2400-bau d port speed.

Specifies 4800 -baud port speed.

Specifies 9600-b aud port speed.

Specifies 19 200-baud port speed.

Specifi es 38400-baud port speed.

Spec ifies 57600-baud port speed.

Specifies 115200-b aud port speed.

Points to a file object for com1 s erial port.

Points to a file object for com2 serial port.

Points to a file object for com3 serial port.

Points to a file object for com4 serial port.

Specifies 7 bit w orld length.

Specifies 8 bit word length.

Specifies flow control is disabled.

Specifies flow co ntrol is enabled.

Specifies even parity.

Specifie s full duplex.

Redefinition of macro from stdio.h

Specifies half duplex.

Specifies no parity.

Specifies serial port type is not known.

Specifies odd parity.

Receiver disabled after receipt of a message.

Receiver Xon/Xoff flow control.

Transmitter flow control ignores C TS.

Transmitter Xon/Xoff flow control.

Specifies serial port is an RS-232 port.

Specifies serial port is an RS-232 dial-up modem.

Specifies serial port is a 4 wire RS-485 port.

Number of serial ports.

I/O line bit mask: clear to send signal

I/O line bit mask: carrier detect signal

Specifies a signal is de-asserted

I/O line bit mask : off hook signal

TelePACE C Tools User and Reference Manual

May 9, 2007

54

SIGNAL_ON

SIGNAL_RING

SIGNAL_VOICE

STOP1

STOP2

Specifies a signal is asserted

I/O line bit mask: ring signal

I/O line bit mask: voice/data swit ch signal

Specifies 1 stop bit.

Specifies 2 stop bits.

Serial Communication Structures

The ctools.h file defines the structures Serial Port Configuration, Serial Port Status and

Serial Port Characteristics for serial port configuration and information. Refer to the C

Tools Structures an

d Types section for complete information on structures and enumeration types.

fgets

fputc

fputs

fread

fwrite

getc

getchar

gets

initport

printf

putc

putchar

puts

scanf

Microtec Serial I/O Functions

These library functions are related to serial communication. They are documented in the

Microtec MCCM77 Docum

entation Set.

fgetc reads a character from a str eam reads a string from a stream writes a character to a stream writes a string to a stream reads from a stream writes to a stream reads a character from a stream reads a character from standard input device reads a string from a st ream re-initializes serial port formatted output to a strea m writes a character to a strea m reads a character to standard ou tput device writes a string to a stream formatted input from a stre am

Dial-Up Modem Functions

These l ibrary functions provide control of dial-up modems. They are used with external modems connected to a serial port. An external modem normally connects to the RS-232 port with a DTE to DCE cable. Consult the System Hardware Manual for your controller for details. fe to r details on each function listed.

Note:

The SCADAPack 100 does not support dial up connections on com port 1.

The SCADASense series of controllers do not support dial up connections.

modem In

it

modem

InitStatus send initialization st ring to dial-up modem. read status of modem initia lization operation.

TelePACE C Tools User and Reference Manual

May 9, 2007

55

modem

InitEnd

modemDial

modemDialStatus terminate modem initializatio n operation. connect with an external device using a dial-up modem. read status of connection with external device using a dial-up modem.

modemDialEnd

modemAbort terminate connection with external device using a dial-up modem . unc onditionally terminate connection with external device or modem initializ ation (used in task exit handler).

modem

AbortAll unconditionally terminate connection s with external device or modem initializations (used in tas k exit handler).

modem

Notification notify the dial-up modem handler that an interesting event has occurr ed. This function is usually called whenever a message is received by a protocol.

Dial-Up Modem Macros

The cto ols.h file defines the following macr os of interest to a C application program. Refer to the C Tools Macros section fo r details on each macro listed.

MODEM_

CMD_MAX_LEN

PHONE_

NUM_MAX_LEN

Maximum length of the modem initialization command string

Maximu m length of the phone number string

Dial-U p Modem Enumeration Typ es

The cto ols.h

file defines the enumerated types DialError and DialState. Refer to the

C Tools

Structures and Types section for co mplete information on structures and enumer ation types.

Dial-u p Modem Structures

The cto ols.h

file defines the structure s ModemInit and ModemSetup. Refer to the C

Tools S

tructures and Types section for com plete information on structures and enumer ation types.

Modem Initialization Example

The foll owing code shows how to initialize a modem. Typically, the mod em initialization is used to prepare a modem to answer calls. The example sets up a Hayes modem to answer incomin g calls.

#include <ctools.h> void main(void)

{ struct Mod emInit initSettings; reserve_i d portID; enum DialError status; enum DialState state; struct pconf ig portSettings;

/* Configure serial port 1 */ portSetti ngs.baud = BAUD1200; portSettings.duplex = FULL; portSett ings.parity = NONE; portSettings.data_bits = DATA8; po rt Settings.stop_bits = STOP1; portSetti ngs.flow_rx = DISABLE ; portSettings.flow_tx = DISABLE;

TelePACE C Tools User and Reference Manual

May 9, 2007

56

portSetti ngs.type = RS232_MODEM; po rt Settings.timeout = 600; request_resource(IO_SYSTEM); set_port(com1, &portSettings); rel ease_resource(IO_SYSTEM);

/* Initialize Hayes modem to answer incoming calls */ initSettings.port = com1; strcpy(initSettings.modemCommand, "

F1Q0V1X1 S0=1

"); if (modemInit(&initSettings, &portID) == DE_NoError)

{

do

{

/* Allow other tasks to execute */

release_processor();

/* Wait for the initialization to complete */ modemInitStatus(com1, portID, &status, &state);

} while (state == DS_Calling);

/* Terminate the initialization */ modemInitEnd(com1, portID, &status);

}

}

Connecting with a Remote Controller Example

The following code shows how to connect to a remote controller using a modem. The example uses a US Robotics modem. It also demonstrates the use of the modemAbort function in an exit handler.

#include <ctools.h>

/* --------------------------------------------

The shutdown function aborts any active

modem connections when the task is ended.

-------------------------------------------- */ void shutdown(void)

{

modemAbort(com1);

} void main(v oid)

{ struct ModemSe tup dialSettings; reserve_id por tID; enum DialError status; enum DialState state; struct pconfig portSettings;

TASKINFO taskStatus;

/* Configure serial port 1 */ portSettings.baud = BAUD19200; portSettings.duplex = FULL; portSettings.parity = NONE; portSettings.data_bits = DATA8; portSettings.stop_bits = STOP1; portSettings.flo

w_rx = DISABLE; portSettings.flo

w_tx = DISABLE; portSettings.type = RS232_MODEM; portSettings.timeout = 600; request_resource(IO_SYSTEM); set_port(com1, &portSettings); release_resource(IO_SYSTEM);

/* Configure US Robotics modem */ dialSettings.port = com1; dialSettings.dialAttempts = 3; dialSettings.detectTime = 60; dialSettings.pauseTime = 30; dialSettings.dialmethod = 0; strcpy(dialSettings.modemCommand, "&F1 &A0 &K0 &M0 &B1");

TelePACE C Tools User and Reference Manual

May 9, 2007

57

strcpy(dialSettings.phoneNumber, "555-1212");

/* set up exit handler for this task */ taskStatus = getTaskInfo(0); installExitHandler(taskStatus.taskID, shutdown);

/* Connect to the remote controller */ if (modemDial(&dialSettings, &portID ) == DE_NoError)

{

do

{

/* Allow other tasks to execute */

release_processor();

/* Wait for initialization to complete */ modemDialStatus(com1, portID, &status, &state);

} while (state == DS_Calling);

/* If the remote controller connected */ if (state == DS_Connected)

{

/* Talk to remote controller here */

}

/* Terminate the connection */ modemDialEnd(com1, portID, &status);

}

}

Note that a pause of a few secon ds is re quired between terminating a connection and initiating a new call. This pause allows the external modem time to hang up.

Com munication P rotoco ls

The TeleBUS protocols are compatible with the widely used Modbus RTU and ASCII protocols. The TeleBUS communication protocols provide a standard communication interface to SCADAPack controllers. Additional TeleBUS commands provide remote programming and diagnostics ca pability.

The TeleBUS protocols provide full access to the I/O database in the controller . The I/O database contains user-assigned registers and general purpose registers. Assigned registers map directly to the I/O hardware or system parameter in the controller. General purpose registers can be used by ladder logic and C application programs to store processed information, and to receive information from a remote device.

The TeleBUS protocols operate on a wide variety of serial data links. These include RS-23 2 serial ports, RS-485 serial ports, radios, leased line modems, and dial up modems. The protocols are generally independent of the communication parameters of the lin k, with a few exceptions.

Application programs can initiate communication with remote devices. A multiple port controller can be a data concentrator for remote devices, by polling remote dev ices on one port(s) and responding as a slave on another port(s).

The protocol type, communicatio n parameters and station addre ss are configured separately for each serial port on a controller. One controller can appear as different stations on different communication networks. The port configuration can be set from an application program, from the TelePACE pr ogramming softwar e, or from another Modbus or DF1 compatible device.

Protocol Type

The protocol type may be set to emulate the Modbus ASCII and Modbus RTU protocols, or it may be disabled. When the protocol is disabled, the port functions as a normal serial port.

TelePACE C Tools User and Reference Manual

May 9, 2007

58

The DF1 option enables the emulation of the DF1 protocols.

The DNP (Distributed Network P rotocol) option enables DNP.

See the DNP

Communication

Protocol secti

on for details on this protocol.

Station Number

The TeleBUS protocol allows up to 254 devices on a network using standard addressing and up to 65534 devices using extended addressing. Station numbers identify each device.

A device responds to commands addressed t o it, or to commands broadcast to all stations.

The station number is in the range 1 to 254 for standard addressing and 1 to 65534 for extended addressing. Address 0 indicates a command broadcast to all stations, and cannot be used as a station number. Each serial port may have a uniq ue station number.

The TeleBUS DF1 protocols allow up to 255 devices on a network. Station numbers identify each device. A device responds to commands addr essed to it, or to commands broadcast to all stations. The station number is in the range 0 to 254. Address 255 indicates a command broadcast to all stations, and cannot be used as a station number. Each serial port may have a unique station number.

Store and Forward Messaging

Store and forward messaging re-transm its messages received by a contr oller. Messages may be re-transmitted on any serial port, with or without station address translation. A userdefined translation table determines actions performed for each message. Store and forward messaging may be enabled or disabled on each port. It is disab led by default.

Store and forward messaging is not supported by DNP or Tele BUS DF1 protocol.

Communication Protocols Functions

There are several library functions related to TeleBUS communication protocol. Refer to the

Function Specification

section for de tails on each function listed.

checkSFTranslationTable clear_protocol_status clearSFTranslationTable enronInstallCommandHandler

Check translation table for invalid entries.

Clears protocol message and error counters.

Clear all store and forward translation table entries.

Installs ha ndler for Enron Modbus commands.

getABConfigu

ration

get_proto col getProto colSettings getProtocolSett ingsEx

Reads

Reads

DF1 protocol configuration parameters.

protocol parameters.

Reads extended addressing protocol parameters for a serial port.

Reads extended addressing and Enron Modbus protocol param eters for a serial port.

get_protocol_st atus getSFMapping getSFTranslation installModbusHandler

Reads protocol message and error counters.

This function is a stub and no longer performs a necessary operation.

Read store and forward translation table entry.

This fu nction allows user-defined extensions to standard

Modbu s protocol.

TelePACE C Tools User and Reference Manual

May 9, 2007

59

master_message modbusExceptionStatus modbusSlaveID

pollABSlave

resetAllABSl

aves

setABConfigu

ration

set_protocol setProtocolSetting s setProtcolSettingEx setSFMapping setSFTranslation start_protocol

Sends a protocol message to another device.

Sets response for the read exception status function.

Sets r esponse for the read slave ID function.

Requests a response from a slave controller using the halfduplex version of the protocol.

Clears responses from the response buffers of half-duplex slave controllers.

Define s DF1 protocol configuration parameters.

Sets protocol parameters and starts protocol.

Sets extended addressing protocol parameters for a serial port.

Sets extended addressing and Enron Modbus protocol parameters for a serial port.

This function is a stub and no longer performs a necessary opera tion.

Write store and forward translation table entry.

Starts protocol execution based on stored parameters.

Communication Protocols Macros

The ctools.h file defines macros for specifying communication protocol parameters. Re fer to the C Tools Macros section for details on each macro listed.

AB_FULL_BCC

Specifies the DF1 Full Duplex protocol e mulation for the serial port. (BCC checksum)

AB_FULL_CRC

AB_HALF_BCC

AB_HALF_CRC

FORCE_MULTIPLE_COILS

FORCE_SINGLE_COIL

LOAD_MULTIPLE_REGISTERS

LOAD_SINGLE_REGISTER

MM_BAD_ADDRESS

MM_BAD_FUNCTION

MM_BAD_LENGTH

MM_BAD_SLAVE

MM_NO_MESSAGE

MM_PROTOCOL_NOT_SUPPORTED

MM_RECEIVED

Specifies the DF1 Full Duplex protocol emulation for the serial port. (CRC checksum)

Specifies the DF1 Half Dupl ex protocol emulation for the serial port. (BCC c hecksum)

Specifies the DF1 Half Duplex protocol emulation f or the serial port. (CRC checksum)

Modbus function code

Modbus fu nction code

Modbus function code

Modbus function code

Master message status: invalid database address

Master message status: invalid function code

Maste r message status: invalid message length

Master message status: invalid slave station add ress

Master message status: no message was sent.

Master message status: selected protocol is no t supported.

Master message status: response was received.

TelePACE C Tools User and Reference Manual

May 9, 2007

60

MM_SENT

MM_EOT

MM_WRONG_RSP

MM_CMD_ACKED

MM_EXCEPTION_FUNCTION

MM_EXCEPTION_ADDRESS

MM_EXCEPTION_VALUE

MM_RECEIVED_BAD_LENGTH

MODBUS_ASCII

MODBUS_RTU

NO_PROTOCOL

READ_COIL_STATUS

READ_EXCEPTION_STATUS

READ_HOLDING_REGISTER

READ_INPUT_REGISTER

READ_INPUT_STATUS

REPORT_SLAVE_ID

SF_ALREADY_DEFINED

SF_INDEX_OUT_OF_RANGE

SF_NO_TRANSLATIO

N

SF_PORT_OUT_OF_RA

NGE

SF_STATION_OUT_OF_RA

NGE

SF_TABLE_SIZE

SF_VALID

Master message status: message was sent.

Master message status: DF1 slave response was an

EOT message

Master message status: DF1 slave response did not match command sent

Master message s tatus: DF1 half duplex command has been acknowledged by slave – Master may now send poll comm and

Master message status: Modbus slave returned a function ex ception

Master message status: Modbus slave returned an address exception

Master message status: Modbus slave returned a value exception

Master message status: response received with incorrect amount of data.

Specifies the Modbus ASCII protocol emulation for the serial port.

Specifies the Modbus RT U protocol emulation for the serial port.

Specifies no communication protocol for the serial port.

Modbus function code

Mo dbus function code

Modbus function code

Modbus function code

Modbus function code

Modbus function code

Result code: translation is already defined in th e table

Result code: invalid translation table index

Result code: entry does not define a translation

Result code: serial port is not valid

Result code: station number is not valid

Number of entries in the store and forward table

Result code: translation is valid

Communication Protocol s Enu meration Types

The ctools.h file defines the enumeration type ADDRESS_MODE. Refer to the C Too

ls

Structures and Type

s section f or complete information on structures and enumeration types.

TelePACE C Tools User and Reference Manual

May 9, 2007

61

Communication Protocols Structures

The ctools.h file defines the structures Protocol Status Information, Protocol Settings,

Extended Protocol Settings, Store and Forward Message and Store and Forward

Status. Refer to the C Tools Structures and Types section for complete information o n structures and enumeration types.

DNP Communication Protocol

DNP, the Distributed Network Protocol, is a standards-based communications protocol developed to achieve interoperability among systems in the electric utility, oil & gas, water/waste water and security industries. This robust, flexible non-proprietary protocol is based on existing open standards to work within a variety of networks. The IEEE has recommended DNP for remote terminal unit to intelligent electronic device messaging. DNP can also be implemented in any SCADA system for efficient and reliable communications between substation computers, RTUs, IEDs and master stations; over serial or LAN-based systems.

DNP offers flexibility and functio nality that go f ar beyond conventional communications protocols. Among its robust and flexible features DNP 3.0 includes:

• Output options

• Addressing for over 65,000 devices on a single link

• Time synchronization and time-stamped events

• Broadcast messa ges

• Data link and application layer confirmation

DNP 3.0 was originally designed based on three layers of the OSI seven-layer model: application layer, data link layer and physical layer. The application layer is object-based with objects provided for most generic data formats. The data link layer provides for several methods of retrieving data such as polling for classes and object variations. The physical layer defines most commonly a simple RS-232 or RS-485 interface.

Refer to the DNP User Manual for complete information on DNP protocol, including the

Device Profile Document.

DNP Communication Protocols Functions

There are several library functions related to DNP communication protocol. Refer to the

Function Specification section for details on each function listed.

dnpInstallConnectionHandler Configures the connection handler for DNP.

dnpClearEventLog dnpConnectionEvent dnpCreateRoutingTable dnpGenerateEventLog dnpGetConfiguratio

n

dnpGetConfigurationEx dnpSaveConfiguration dnpSaveConfigurationEx

Deletes all change events from the DNP change event buffers.

Report a DNP connection event

Allocates memory for a new routing table.

Generates a change event for the DNP point.

Reads the DNP protocol configuration.

Reads the extended DNP configuration parameters.

Writes the DNP protocol configuration parameters.

Writes the extended DNP configuration parameters

TelePACE C Tools User and Reference Manual

May 9, 2007

62

dnpGetBIConfig

dnpSaveBIConfig

dnpSaveBIConfigEx

dnpGetBOConfig

dnpGetBIConfigEx

dnpSaveBOConfig

dnpGetAI16Config

dnpSaveAI16Config

dnpGetAI32Config

dnpSaveAISFConfig dnpGetA ISFConfig

dnpSaveAI32Config

dnpGetAO16Config

dnpSaveAO16Config

dnpGetAO32Config

Reads the configuration of a DNP binary input point.

Writes the configuration of a DNP binary input point.

Writes the configuration of an extended DNP Binary Inpu t point

Reads the configuration of a DNP binary output point.

Reads the configuration of an extended DNP Binary Input point.

Sets the configuration of a DNP binary output point.

Reads the configuration of a DNP 16-bit analog input point .

Sets the configuration of a DNP 16-bit analog input poi nt.

Reads the configuration of a DNP 32-bit analog input poin t.

Sets the configuration of a DNP 32-bit short floating analo g input point

Reads the configuration of a DNP 32-bit short floating analog input point.

Sets the configuration of a DNP 32-bit analog input point.

Reads the configuration of a DNP 16-bit analog output point.

Sets the configuration of a DNP 32-bit analog output point.

Reads the configuration of a DNP 32-bit analog output point.

dnpSaveAO32Config

dnpSaveAOSFConfig dnpGetAOSFConf ig

dnpGetCI16Config

dnpSaveCI16Config

dnpGetCI32Config

dnpSaveCI32Config

dnpGetRuntimeStatu dnpSendUnsolicited s

Sets the configuration of a DNP 32-bit analog output point.

Sets the configuration of a DNP 32-bit short floating analog output point.

Sets the configuration of a DNP 32-bit short floating analog output point.

Reads the configuration of a DNP 16-bit counter input point .

Sets the configuration of a DNP 16-bit counter input point.

Reads the configuration of a DNP 32-bit counter input point.

Sets the configuration of a DNP 32-bit counter inp ut point.

Reads the current status of all DNP change event buffers.

Sends an ‘Unsolicited Response’ message in DNP protocol.

dnpSendUnsolicitedResponse Sends an Unsolicited Response message in DNP, with data from the specified classes.

dnpWriteRoutingTableEntry Wwrites an entry in the DNP routing table.

dnpReadRoutingTableEntry Reads an entry from the routing table.

dnpReadRoutingTableSize

Reads the total number of entries in the routing table.

dnpSearchRoutingTable

Searches the routing table for a specific DNP address.

dnpWriteRoutingTableDialStrings Writes a primary and secondary dial string into an entry in the DNP routing table.

TelePACE C Tools User and Reference Manual

May 9, 2007

63

dnpReadRoutingTableDialStrings Reads a primary and secondary dial string from an entry in the DNP routing table.

DNP Communication Protocol Structures and Types

The ctools.h file defines the structures DNP Configuration, Binary Input Point, Binary

Output Point, Analog Input Point, Analog Output Point and Counter Input Point. Refe r to the C Tools Structures and Types section for complete information on structures and enumeration types.

I/O D atabase

The I/O database allows data to be shared between C programs, Ladder Logic programs and communication proto cols. A simplified diagram of the I/O Database is shown below.

Ladder Logic

Progra ms

C Tools

Programs

TeleBUS

Protocols

Controller I/O

Database

Coil Registers

00001 to 04096

Status Registers

10001 to 14096

Input Registers

30001 to 31024

Holding Registers

40001 to 49999

Controller Register

Assignment Table

5000 Series

I/O Modules

System

Parameters

The I/O database contains general purpose and user-assigned registers. General purpose registers may be used by Ladder Logic and C application progr ams to store processed information and to receive information from a remote device. Initially all registers in the I/O

Database are general purpose registers.

User-assigned registers are mapped directly from the I/O database to physical I/O hardware, or to controller system configuration and diagnostic parameters. The Register Assignment performs the mapping of registers from the I/O database to physical I/O hardware and system parameters.

User-assigned registers are initialized to the default hardware sta te or system parameter when the controller is reset. Assigned output registers do not maintain their values during power failure s. As signed output registers do retain their values during a pplication program loading.

General purpose registers retain their values dur ing power failures and application program loading.

The valu es change only when written by an appl ication program or a communication protocol.

The TeleBUS communication protocols provi de a standard communication interface to the controller. The TeleBUS protocols are compatible with the widely used Modbus RTU and

ASCII protocols and provide full access to the I/O database in the c ontroller.

TelePACE C Tools User and Reference Manual

May 9, 2007

64

I/O Database Register Types

The I/O database is divided into four types of I/O registers. Each of these types are initially configured as general purpose registers by the controller.

Coil Registers

Coil registers are single bit registers located in the digital output section of the I/O database. eries digital output modules or SCADAPack I/O modules through the Register Assignment. Coil registers may also be assigned to controller on-board digital out puts and to system configuration modules.

There are 4096 coil registers numbered 00001 to 04096. Ladder logic programs, C language programs, and the TeleBUS protocols can read from and write to these registers.

Status Registers

Status registers are single bit registers located in the digital input section of the I/O database. Status, or digital input, database registers may be assigned to 5000 Series digita l input modules or SCADAPack I/O modules through the Register Assignment. Status registers may also be assigned to controller on-board digital inputs and to system diagnos tic modules.

There are 4096 status registers are numbered 10001 to 14096. Ladder logic programs and the TeleBUS protocols can only read from these registers. C language application programs can read data from and write data to these registers.

Input Registers

Input registers are 16 bit registers located in the analog input section of the I/O database.

Input, or analog input, database registers may be assigned to 5000 Series analog input modules or SCADAPack I/O modules through the Registe r Assignment. Input r egisters m ay also be assigned to controller internal analog inputs and to system diagnostic modules.

There are 1024 input registers numbered 30001 to 31024. Ladder logic programs and the

TeleBUS protocols can only read from these registers. C language application programs ca n read data from and write data to these registers.

The I/O database for the SCADAPack 100 controller has 512 input registers numbered

30001 to 30512. Ladder logic programs and the TeleBUS protocols can only read from these registers. C language programs can read data from and write data to these registers.

Holding Registers

Holding registers are 16 bit registers located in the analog output section of the I/O database. Holding, or analog output, database registers may be assigned to 5000 Series analog output modules or SCADAPack analog output m odules through the Register

Assignment. Holding registers may also be assigned to system diagnostic and configuration modules.

There are 9999 input registers numbered 40001 to 49999. Ladd er logic programs, C language programs, and the TeleBUS protocols can read from and write to these registers.

The I/O database for the SCADAPack 10 0 controller has 4000 holding registers numbered

40001 to 44000. Ladder logic programs, C language programs, and the TeleBUS protocols can read from and write to these registers.

TelePACE C Tools User and Reference Manual

May 9, 2007

65

I/O Database Functions

There are two library functions related to the I/O database. Refer to the Function

Specification section for details on each function listed.

dbase setdbase

Reads a value from the I/O database.

Writes a value to the I/O database.

I/O Database Macros

The ctools.h file defines library functions f or the I/O database. Refer to the C Tools Macros section for details on each macro listed.

AB

Specifies Allan-Bradley database addressing.

DB_BADSIZE

DB_BADTYPE

DB_OK

LINEAR

MODBUS

NUMAB

NUMCOIL

NUMHOLDING

NUMINPUT

NUMLINEAR

NUMSTATUS

START_COIL

START_HOLDING

START_INPUT

START_STATUS

Error code: out of range address specified

Error co de: bad database addressing type specified

Error co de: no error occurred

Specifie s linear database addressing.

Specifies Modbus database addressing.

Number of registers in the Allan-Bradley database.

Number of registers in the Modbus coil section.

Number of registers in the M odbus holding register section.

Number of registers in the M odbus input registers section.

Number of registers in the linear database.

Number of registers in the Modbus status se ction.

Start of the coil section in the linear database.

Start of the holding registers section i n the linear database.

Start of the input register section in th e linear database.

Start of the status section in the linear databas e.

Register Assignment Functions

All I/O hardware that is used by th e controller must be assigned to I/O database registers in order for these I/O points to be scanned continuously. I/O data may then be accessed through the I/O database within the C pro gram. C programs may read data from, or write data to the I/O ha rdware through user- assigned registers in the I/O database .

The Register Assignment assigns I/O database registers to user-assigned registers using

I/O modules. An I/O Module can refer to an actua l I/O hardware module (e.g. 5401 Digital

Input Module) or it may refer to a set of controller parameters, such as serial port settings.

The chapter Register Assignment Reference of the TelePACE Ladder Logic Reference

and User Manual contains a description of what each module is used for and the register assignment requirements for the I/O module.

Register assignments configured usin g the TelePACE Register Assignment dialog may be stored in the TelePACE program file o r downloaded directly to the controller. To obtain error checking that prevents invalid register assignments, use the TelePACE Register Assig nment dialog to initially build the Register Assignment. The Register Assignme nt can then be saved in a Ladder Logic file (e.g. filename.lad) and downloaded with the C program.

TelePACE C Tools User and Reference Manual

May 9, 2007

66

There are several library functions related to register assignment. Refer to the Function

Specification section for details on each function listed.

clearRegAssignment addRegA ssignment

Erases the current Register Assignment.

Adds one I/O module to the current Register Assignment.

getIOErrorIndication getOutputsInStopMode setIOErrorIndication setOutputsInS topMode

Gets the control flag for the I/O module error indication

Gets the control flags for state of Outputs in Ladders Stop

Mode

Sets the control flag for the I/O module error indication

Sets the control flags for state of Outputs in Ladders Stop

Mode

Register Assignment Enumeration Types

The ctools.h file defines one enumeration type . The ioModules enumeration type defines a list of results of sending a command. Refer to the C Tools Structures and Types section for complete information on structures and enumeration types.

Register Assignment Structure

The ctools.h file defines the structure RegAssign. Refer to the C Tools Structures and

Types section for complete information on structures and enumeration types.

HAR T Communication

The HART ® protocol is a field bus protocol for communic ation with smart transmitters.

The HART protocol driver provides communication between TeleSAFE Micro16 and

SCADAPack controllers and HART devices. The protocol drive r uses the model 5904 HART modem for communication. Four HART modem modules are s upported per controller.

The driver allows HART transmitters to be used with C application programs and with

RealFLO. The driver can read data from HART devices.

HART Command F unctions

The ctools.h file defines the following HART command related functions. Refer to the

Function Specification section for details on each function listed.

har

tIO

hartCommand har

tCommand0

har

tCommand1

har

tCommand2

har

tCommand3

har

tCommand11

ha

rtCommand33

Reads data from the 5904 interface m odule, processes HART responses, processes HART commands, and writes commands and configuration data to the 5904 interfa ce module. send a HART command string and specify a function to handle the response read unique identifier using shortaddress algorithm read primary variable read primary variable current and percent of span read primary variable current and dyna mic variables read unique identifier associated with tag read specified transmitter variables

TelePACE C Tools User and Reference Manual

May 9, 2007

67

ha

rtStatus

ha

rtGetConfiguration

ha

rtSetConfiguration

har

tPackString

ha

rtUnpackString return status of last HART command sent read HART module settings write HART module settings convert string to HART packed s tring convert HART packed string t o string

HART Command Macros

The ctools.h file defines the following macro of interest to a C application program. Refer to the C Tools Macros sect ion for details.

DATA

_SIZE

Maximum length of the HART command or response field.

HART Command Enumeration Types

The ctools.h file defines one enumeration type. The HART_RESULT enumeration type defines a list of results of sending a command. Refer to the C Tool s Structures and Types section for complete information on structures and enumeration types.

HART Command Structures

The ctools.h fil e defines five structures. Refer to the C Tools S tructures and Types section for complete information on structures and enumeration types.

The HART_DEVICE type is a structure containing information about t he HART device.

The HART_VARIABLE type is a structure containing a variable read from a HART device.

The HART_SETTINGS type is a structure containing the configuration for th e HART modem module.

The HART_COMMAND type is a structure containing a command to be sent to a HART slave device.

The HART_RESPONSE type is a structure containing a response from a HART slave device.

PID Control

TelePACE C Tools provides a total of 32 independent PID (Proportional, Integral, and

Derivative) controllers. PID control blocks operate independent of applicatio n programs. An elaborate control program need not be written to use the control bloc ks. A simple program to set up the co ntrol blocks i s all that is required.

The PID control blocks ar e not limited to the PID control algorithm.

They also provide ratio control, ratio/bias control, alarm scanning and square root function s. Control blocks may be interconnected to exchange setpoints, output limits, and other pa rameters.

Refer to the PID Controlle rs section of the TelePACE Ladder Logic User Manu al for complete inform ation on c onfiguring and using PID controllers.

PID Control Functions

The ctools.h file defines the following PID control related functions. Refe r to the Function

Specificati

on section for details on each function listed.

auto_pid

Set a PID block to execute automa tically at the specified rate.

TelePACE C Tools User and Reference Manual

May 9, 2007

68

clear_pid get_pid set_pid

Set all PID block variables to zero.

This function returns the value of a PID control bl ock variable.

This function assigns value to a PID control block variable .

PID Control Macros

The ctools.h file defines the following macros for PID block access. Refer to the C Tools

Macros sec tion for details on each function listed.

AO

CA

Variable name: alarm output address

Variable name: cascade setpoint source

CR

DB

DO

ER

EX

FS

GA

HI

IB

IH

IN

IO

IP

LO

OB

OP

PE

PID_AL AR

M

PID_ALAR

M_ABS

PID_ALAR

M_ACK

PID_ ALARM_DE

V

PID_

ALARM_ONLY

PID_AL

ARM_RATE

PID_

ANALOG_IP

PID_

ANALOG_OP

PID_BA

D_BLOCK

PID_BAD_IO_IP

PID_BAD_I

O_OP

Variable name: control register

Variable name: deadband

Variable name: decrease output

Variable name: error

Variable name: automatic execu tion period

Variable name: full scale o utput limit

Variable name: gain

Variable name: high alarm setpoint

Variable name: input bias

Variable name: inhibit execution addres s

Variable name: integrated error

Variable name: increase ou tput

Variable name: input source

Variable name: low alarm setpoint

Variable name: output bias

Variable name: output

Variable name: period

Control register mask: alarms enabled

Control register mask: absolute alarms

Status register mask: alarm acknowledged

Control register mask: deviation alarms

Control register mask: alarm only block

Control register mask: rate alarms

Control register mask: analo g input

Control register mask: anal og output

Return code: bad block number specified.

Status register mask: I/O failure on block input

Status register mask: I/O failure on block outpu t

TelePACE C Tools User and Reference Manual

May 9, 2007

69

PID_BLOC

K_IP

PID_BLOCKS

PID_CLAMP_FULL

PID_CLAMP_ZERO

PID_ER_SQR

PID_HI_ALARM

PID_INHIB

IT

PID_LO_ALA

RM

PID_MANUAL

PID_MODE_AUT

O

PID_MODE_MANUA L

PID_MOTOR_

OP

PID_NO_ALARM

PID_NO_ER_SQR

PID_NO_IP

PID_NO_OP

PID_NO_PV_SQR

PID_NO_S

P_TRACK

PID_OK

PID_OUT_DB

PID_PID

PID_PULSE_OP

PID_PV_SQR

PID_RATE_CLAMP

PID_RATIO_BIAS

PID_RUNNING

RA

RE

SP

SR

ZE

PID_SP_CASCADE

PID_SP_N

ORMAL

PID_SP_TRACK

PV

Control register mask: input from ou tput of another block

Number of PID blocks.

Status register mask: o utput is clamped at full scale

Status register mask: output is clamped at zero scale

Control register mask: take square root of error

Status register mask: high alarm detected

Status register mask: external inhibit in put is on

Status register mask: low alarm detect ed

Status register mask: block is in manual mode

Control register mask: automatic mode

Control register mask: manual mode

Control register mask: motor pulse dura tion output

Control register mask: alarms disabled

Control register mask: normal error

Control register mask: no input (other t han IP)

Control register mask: no output

Control register mask: normal PV

Control register mask: setpoint tracking disab led

Return code: operation completed successfu lly.

Status register mask: PID controller outside of dead band

Control register mask: PID control block

Control register mask: pulse duration output

Control register mask: take square root of PV

Status register mask: rate gain clamed at maxim um

Control register mask: ratio/bias control block

Status register mask: block is executing

Control register mask: cascade setpoint

Control register mask: setpoint store d in SP

Control register mask: setpoint tracking enabled

Variable name: process value

Variable name: rate time

Variable name: reset time

Variable name: setpoint

Variable name: status register

Variable name: zero scale output limit

TelePACE C Tools User and Reference Manual

May 9, 2007

70

Backward Compatibility Functions

The following functions are provided for backward compatibility. They c annot access all

5000 series I/O modules. It is reco mmended that these functions not be used in new programs. Instead use Register A ssignment or call the specific I/O module driver function directly.

These functions are defined in ctools.h for backward compatibility with these programs.

ain

Reads analog input

aioError

Reads analog I/O communication status

aout counter

Writes analog output

Reads counter module input channel

counterError

Reads counter module error flag

din dout off

Reads digital input channel (8 I/O points)

Writes digital output channel (8 I/O points)

Tests If one digital I/O poi nt is OFF

on pulse

Tests If one digital I/O point is ON

Generates a square wave on a digital output point

pulse_train timeout turnoff turnon

Generates a series of pulses on a digital output point

Performs time delayed action on a digital output point

Writes one digital output point to OFF status

Writes one digital output point to ON status

Backward Compatibility Macros

The following macros may have been used in C programs written for a controller with firmware version 1.22 or older to support the functions: ain, aioError, aout, counter, counterError, din, dout, off, on, pulse, pulse_train, timeout, turnoff or turnon.

These macros are defined in ctools.h for backward compatibility with these programs.

AIN_END

AIN_START

AIO_BADCHAN

AIO_TIMEOUT

AIO_SUPPORTED

AOUT_END

AOUT_START

COUNTER_CHANNELS

COUNTER_END

COUNTER_START

COUNTER_SUPPORTED

DIN_END

Number of last analog input channel.

Number of first analog input channel.

Error code: bad analog input channel specified.

Error code: input device did not respond.

If defined indicates analog I/O supported.

Number of last analog output channel.

Number of first analog output channel.

Specifies number of 5000 Series counter input channels

Number of last counter input channel

Number of first counter input channel

If defined indicates counter I/O hardware supported.

Number of last regular digital input channel.

TelePACE C Tools User and Reference Manual

May 9, 2007

71

DIN_START

DIO_SUPPORTED

DOUT_END

DOUT_START

DUTY_CYCL

E

EXTENDED_DIN_END

EXTENDED_DIN_START

EXTENDED_DOUT_END

EXTENDED_DOUT_START

NORMAL

PULSE_TRAIN

TIMEOUT

TIMER_BADADDR

Number of first regular digital input channel

If defined indicates digital I/O hardware supported.

Number of last regular digital output channel.

Number of first regular digital output channel

Specifies timer is generating square wave output.

Numbe r of last extended digital input channel.

Number of f irst extended digital input channel

Number of last e xtended digital output channel.

Number of first ex tended digital output channel

Specifies normal count down timer.

Specifies timer is generating pulse train output.

Specifies timer is generating timed output change.

Error code: invalid digital I/O address.

TelePACE C Tools User and Reference Manual

May 9, 2007

72

Tel ePACE C Tools Function

Sp ecifications

The controller C function specifications are formatted as follows. The functions are listed alphabe tically.

Name

Syntax

Each specification begins with the name of the function and a brief description.

The syntax shows a prototype for the function, indicating the return type and the types of its arguments. Any necessary header files are listed.

Descrip

tion This defines the calling parameters for the function and its return values.

Notes

See Als

Examp

o

le

This section contains additional informat ion on the function, and considerations for its use.

This section lists related functions.

The example gives a brief sample of the use of the function.

TelePACE C Tools User and Reference Manual

May 9, 2007

73

addR egAssignment

Add R eg iste r Assignment

Syntax

#in clude <ctools.h> unsigned addRegAssignment(

Description

The addRegAssignment function adds one I/O module to the current Register Assignment of type moduleType. The following symbolic constants are valid values for moduleType:

AIN_520xTemperature DIAG_forceLED

AIN_520xRAMBattery DIAG_IPConnections

AIN_5501 DIAG_ModbusStatus

AIN_5502 DIAG_protocolStatus

AIN_5503 DIN_520xDigitalInputs

AIN_5504 DIN_520xInterruptInput

AIN_5521 DIN_520xOptionSwitches

AIN_generic8 DIN_5401

AOUT_5301 DIN_5402

AOUT_5302 DIN_5403

AOUT_5304 DIN_5404

AOUT_generic2 DIN_5405

AOUT_generic4 DIN_5421

CNFG_5904Modem DIN_generic16

CNFG_clearPortCounters DIN_generic8

CNFG_clearProtocolCounters DIN_SP32OptionSwitches

CNFG_IPSettings DOUT_5401

CNFG_LEDPower DOUT_5402

CNFG_MTCPIfSettings DOUT_5406

CNFG_MTCPSettings DOUT_5407

CNFG_PIDBlock DOUT_5408

CNFG_portSettings DOUT_5409

CNFG_protocolExtended DOUT_5411

CNFG_protocolExtendedEx DOUT_generic16

CNFG_protocolSettings DOUT_generic8

CNFG_realTimeClock SCADAPack_AOUT

CNFG_saveToEEPROM SCADAPack_lowerIO

CNFG_setSerialPortDTR SCADAPack_upperIO

CNFG_storeAndForward SCADAPack_LPIO

CNTR_520xCounterInputs SCADAPack_100IO

CNTR_5410 SCADAPack_5604IO

CNTR_520xInterruptInput GFC_4202IO

DIAG_commStatus GFC_4202IOEx

DIAG_controllerStatus GFC_4202DSIO

DIAG_LogicStatus

moduleAddress specifies a unique address for the module. For the valid range for

moduleAddress refer to the list of modules in the chapter Register Assignment Reference of the TelePACE Ladder Logic Reference and User Manual. For module addresses com1,

TelePACE C Tools User and Reference Manual

May 9, 2007

74

com2, com3 or com4 specify 0, 1, 2 or 3 respectively for moduleAddress. For module types that have no module address (e .g. CNFG_LEDPower) specify -1 for moduleAddress. For

SCADAPack module types that have a module address fixed at 0, specify 0 for

moduleAddress.

startingRegister1 specifies the first register of any unused block of consecutive registers.

Refer to th e list of modules in the Register Assignment Reference for the type and number of registers required for th is block. Data read from or written to the module is stored in this block of registers.

If the module type specified has mo re than one type of I/O, use startingRegister2,

startingRegister3, and startingRegister4 as applicable. Each start r egister specifies the first register of an unused block of consecutiv e registers for each type of input or output on the module. Refer to the list of modules in th e Register Assignment Reference for the module

I/O types. Specify 0 for startingRegister2 , startingRegister3, or startingRegister4 if not applicable.

Notes

Up to 150 modules may be added to the Register Assignment. If the Register Assign ment is full or if an incorrect value is specified for any argument this function returns FALSE; otherwise TRUE is returned.

Output registers specified fo r certain C NFG type modules are initialized with the current parameter values when the module is added to the Register Assignment (e.g.

CNFG_realT imeClock).

Call clearRe gAssignment first before using the addRegAssignmen t function when creating a ne w Register Assignment.

Duplicate or overlapping register assig nments are not checked fo r by this function.

Overlapping register assignments may result in unpredictable I/O a ctivity.

To obtain error che cking that prevents invalid register assignments suc h as these, use the

TelePACE Re gister Assignment dialog to build the Register Assignment. Then save the

Register Assig nment in a Ladder Logic file (e.g. fil ename.lad

) and download it with the C program, or transfer the Register Assignment to the C program using the

clearRegAssignme

nt and addRegAs signment fun ctions.

The IO_SYSTEM resource mus t be requested before calling this function.

See Also

clearRegAssignment

Example

#include <primitiv.h> void main(void)

{

request_resourc e(IO _SYSTE M);

/* Create the Regi ster As signment */

clearRegAssignment( ); addRegAssignment( SCADAPac k_lowerIO, 0, 1,

10001, 30001, 0); addRegAssignment(SCADAPack_AOUT, 0, 40001, 0,

0); addRegAssignment(AOUT_5302, 1, 40003, 0, 0, 0);

TelePACE C Tools User and Reference Manual

May 9, 2007

75

addRegAssignment(DIAG_forceLED, -1, 10017, 0,

0);

0, 0, 0);

release_resource(IO_SYSTEM);

}

30009, 0, 0, 0); addRegAssignment(DIAG_protocolStatus, 2, 30010,

TelePACE C Tools User and Reference Manual

May 9, 2007

76

addRegAssignmentEx

Add Register Assignment

Syntax

ools.h> egAssignmentEx(

UINT16 moduleType,

UINT16 s,

startingRegister1

,

UINT16 ,

UINT16

startingRegister4,

);

UINT16 parameters[16]

Description

The addRegAssignmentE x function adds one I/O module to the current Register

Assignment of type moduleType. The following symbolic constants are valid values for

moduleT ype

:

AIN_5209Temperature CNTR_5209CounterInputs

AIN_5209RAMBattery CNTR_5410

AIN_5501 CNTR_5209InterruptInput

AIN_5502 DIAG_commStatus

AIN_5503 DIAG_controllerStatus

AIN_5504 DIAG_forceLED

AIN_5505 DIAG_IPConnections

AIN_5506 DIAG_ModbusStatus

AIN_5521 DIAG_protocolStatus

AIN_generic8 DIN_5209 DigitalInputs

AOUT_5301 DIN_5209InterruptInput

AOUT_5302 DIN_5401

AOUT_5304 DIN_5402

AOUT_generic2 DIN_5403

AOUT_generic4 DIN_5404

CNFG_5904Modem DIN_5405

CNFG_clearPortCounters DIN_5421

CNFG_clearProtocolCounters DIN_generic16

CNFG_IPSettings DIN_generic8

CNFG_LEDPower DOUT_5401

CNFG_modbusIpProtocol DOUT_5402

CNFG_MTCPIfSettings DOUT_5406

CNFG_MTCPS ettings DOUT_5407

CNFG_PIDBl ock DOUT_5408

CNFG_portSettings DOUT_5 409

CNFG_protocolExtended DOUT_5411

CNFG_protocolExtendedEx DOUT_generic16

CNFG_protocolSettings DOUT_generic8

CNFG_realTimeClock SCADAPack_AOUT

CNFG_saveToEEPROM SCADAPack_lowerIO

CNFG_setSerialPortDTR SCADAPack_upperIO

CNFG_storeAndForward SCADAPack_LPIO

SCADAPack_100IO

SCADAPack_5209IO

SCADAPack_5606IO

TelePACE C Tools User and Reference Manual

May 9, 2007

77

moduleAddress specifies a unique address for the module. For the valid range for

moduleAddress refer to the list of modules in the chapter Register Assignment Reference of the TelePACE Ladder Logic Reference and User Manual. For module addresses com1, com2, com3 or com4 specify 0, 1, 2 or 3 respectively for moduleAddress. For module address Ethernet1 specify 4 for moduleAddress. For module types that have no module address (e.g. CNFG_LEDPower) specify -1 for moduleAddress. For SCADAPack module types that have a module address fixed at 0, specify 0 for moduleAddress.

startingRegister1 specifies the firs t register of any unused block of consecutive registers.

Refer to the list of modules in the Register Assignment Reference for the type and number of registers requ ired for this block. Data read from or written to the module is stored in this block of register s.

If the module type specified has more than one type of I/O, use startingRegister2,

startingRegister3, and startingRegister4 as applicable. Each start register specifies the first register of an unused blo ck of consecutive registers for each type of input or output on the module. Refer to the list of modules in the Register Assignment Reference for the modu le

I/O types. Specify 0 for startingRegister2, startingRegister3, or startingRegister4 if not applicable. parameters is an array of configuration parameters for the register assig nment module.

Most modules do not use the parameters. Use the addRegAssignment function to configure these modules. Use parameters with the following modules.

5505 I/O Module: parameters[0] to [3] define the analog input type for the corresponding input. Valid values are:

• 0 = RTD in deg Celsius

• 1 = RTD in deg Fahrenheit

• 2 = RTD in deg Kelvin

• 3 = resistance measurement in ohms.

5505 I/O Module: parameter[4] defines the analog input filter . Valid values are:

• 0 = 0.5 s (minimum)

• 1 = 1 s

• 2 = 2 s

• 3 = 4 s (maximum)

5506 I/O Mo

dule: parameters[0] to [7] define the analog input type for the corresponding input. Vali d values are:

• 0 = 0 to 5 V input

1 = 1 to 5 V inpu t

• 2 = 0 to 20 mA input

3 = 4 to 20 mA input

5506 I/O Module: parameter[8] defines the ana log input filter. Valid values are:

• 0 = < 3 Hz (maximum filter)

• 1 = 6 Hz

• 2 = 11 Hz

• 3 = 30 Hz (minimum filter)

5506 I/O Module: parameter[9] defines the scan frequency. Valid values are:

• 0 = 60 Hz

• 1 = 50 Hz

5606 I/O Module: parameters[0] to [7] define the analog input type for the corresponding input. Valid values are:

TelePACE C Tools User and Reference Manual

May 9, 2007

78

• 0 = 0 to 5 V input

• 1 =

1 to 5 V input

• 2 = 0 to 20 mA input

• 3 = 4 to 20 mA input

5606 I/O Module: parameter[8] defines the analog input filter. Valid values are:

0 = < 3 Hz (maximum filter)

• 1 = 6 Hz

• 2 = 11 Hz

• 3 = 30 Hz (m inimum filter)

5606 I/O Module: parameter[9] defines the scan frequency. Valid v alues are:

• 0 = 60 Hz

• 1 = 50 Hz

5606 I/O Module: parameter[10] defines the analog output type. Valid values are:

• 0 = 0

to 20 mA output

• 1 = 4 to 20 mA output

Notes

Up to 150 mo dules may be added to the Register Assignment. If the Register Assignment is full or if an in correct value is specified for any argument this function returns FALSE; otherwise TRUE is returned.

O utput registers specified for certain CNFG type modules are initialized with the current parameter values when the module is added to the Register Assignment (e.g.

CNFG_realTimeClock

).

Call clearRegAssignment first before using the addRegAssignmentEx function when creating a new Register Assignment.

Duplicate or overlapping register assignments are not checked for by this function.

Overlapping register assignments may result in unpredictable I/O activity.

To obtain error checking that prevents invalid register assignments such as these, use the

TelePACE Register Assignment dialog to build the Register Assignment. Then save the

Register Assignment in a Ladder Logic file (e.g. filename.lad) and download it with the C program, or transfer the Register Assignment to the C program using the clearRegAssignment

and addRegAssignmentEx functions.

The IO_SYSTEM resource must be requested before calling this function.

See Also

addRegAssignment, clearRegAssignment

TelePACE C Tools User and Reference Manual

May 9, 2007

79

ain

Read an Analog Input

Syntax

#include <ctools.h> int ain(unsigned channel);

Description

The ain function reads from the analog input or output specified by channel. Input channe ls read from the analog input hardware. Output channels read t he value output to the channel with the aout function.

The valid range for channel is 0 to AIO_MAX. If an invalid channel is selected, the ain function returns INT_MIN and the current task's error code is set to AIO_BADCHAN. The error code is obtained with the check_error func tion.

The ain function normally returns a value in the range –32767 to +32767.

Notes

Use offsets from the symbolic constants AIN_START, AIN_END, AOU T_START and

AOUT_END to reference analog channels. The constants make programs more portable and p rotect against future changes to the analog I/O channel numbering.

The IO_SYSTEM resource must be requested before calling this function.

This function is provided for backward compatibility. It cannot access all 5000 series I/O modules. It is recommended that this function not be used in new programs. Instead use

Register Assignment or call the I/O driver ioRead8Ain directly.

See also

aout, check_error, ioRe ad8Ain

Example

#include <ctools.h> void main(void)

{ request_resource(IO _SYSTEM); printf("ain(%d)=%d\r\n", 2, ain(2)); release_resource(IO_SYSTEM) ;

}

TelePACE C Tools User and Reference Manual

May 9, 2007

80

aioError

Read Analog I/O Error Flags

Syntax

#include <ctools.h> int aioError(unsigned

channel

);

Description

The aioError function reads the I/O error flag for an analog channel.

It returns the error flag for the channel, if the channel number is valid ; otherwise it returns

INT_MIN. A value of 0 indicates no error occurred. A positive value indicates an error.

Notes

This function is provided for backward compatibility. It cannot access all 5000 series I/O modules. It is recommended that this function not be used in new programs. Instead use

Register Assignment or call the I/O driver ioRead8Ain directly.

See Also

aout, check_error, ioR ead8Ain

TelePACE C Tools User and Reference Manual

May 9, 2007

81

alarmIn

Determine Alarm Time fr om Elapsed Time

Syntax

#include <ctools.h>

ALARM_SETTING alarmIn(unsigned hours, un signed minutes, unsigned seconds);

Description

The alarmIn function calculates the alarm settings to configure a real time clock alarm to occur in hours, minutes and seconds from the current time.

The function returns an ALARM_SETTING structure suitable for passing to the

setClockAlarm function. The structure specifies an absolute time alarm at the time offset specified by the call to alarmIn. Refer to the Structures and Types section for a description of the fiel ds in the ALARM_SETTING structure.

Notes

If second is greater than 60 seconds, the additional time is rolled into the minutes. If minut e is greater than 60 minutes, the additional time is rolled into the hours.

If the offset time is greater that one day, then the alarm time will roll over wi thin the current day.

The IO_SYSTEM resource must be requested before calling this function.

See Also

getClockAlarm, setClockAlarm,

Example

#include <ctools.h>

/* -------------------------------------------

conservePower

The conservePower function places the

controller into sleep mode for 10 minutes.

------------------------------------------ */ void conservePower(void)

{ request_ resource(IO_SYSTEM);

/* Alarm in 10 minutes */ alarm = alarmIn(0, 10, 0);

setClockAlarm(alarm)

/* Put controller in low power mode */

sleep();

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

82

allocate_envelope

Obtain an Envelope from the RTOS

Syntax

#include <ctools.h>envelope *allocate_envelope(v oid);

Description

The allocate_en velope function obtains an envelope from the operating system. If no envelope is available, the task is blocked until one becomes available.

The allocate_envelope function returns a pointer to the envelope.

Notes

Envelope s are used to send messages between tasks. The RTOS allocates envelopes from a pool of free envelopes. It returns envelopes to the pool when they are de-allocated.

An application program must ensure that unneeded envelopes are de-allocated. Envelope s may be r eused.

See Also

deallocate_envelope

Example

#include <ctools.h> extern unsigned other _task_id; void task1(void)

{

en

/* send a message to another task */

/* assume it will deallocate the envelope */ letter = allocate_envelope(); letter>destination = other_task_id; letter->type = MSG_DATA; letter->data = 5;

send_message(letter);

/* receive a message from any other task */ letter = receive_message ();

/* ... pro cess the data here */ dealloca te _envelope(lett er);

}

/* ... th e rest of the t ask */

TelePACE C Tools User and Reference Manual

May 9, 2007

83

aout

Write to Analog Output

Syntax

#include <ctools.h> int aout(unsigned channel, int value);

D escription

The aout function writes value to the analog output specified by channel. The range for

channel is AOUT_START to AOUT_END inclusive. The range for value is -32767 to 32767.

aout returns the value written to the hardware, or -1 if the channel is not an analog output.

Notes

The value output may be limited by the analog output module.

Use offsets from the symbolic constants AIN_START, AIN_END, AOUT_START and

AOUT_END to reference analog channels. The constants make programs more portable and protect against future changes to the analog I/O channel numbering.

The IO_SYSTEM resource must be requested before calling this function.

This function is provided for backward compatibility. It cannot access all 5000 series I/O modules. It is recommended that this function not be used in new programs. Instead use

Register Assignment or call the I/O driver ioWrite4Aout directly.

See Also

addRegAssignment, ioWrite4Aout

Example

#include <ctools.h> void main(void)

{

/* ramp output from zero to full scale */ for (value = 0; value < 32767; value++)

{ request_resource(IO_SYSTEM); release_resource(IO_SYSTEM);

}

}

TelePACE C Tools User and Reference Manual

May 9, 2007

84

auto_pid

Execute a PID Block Automatically

Syntax

#include <ctools.h> void auto_pid(unsigned block , unsigned period);

Description

The auto_pid routine configures a PID control block to execute automatically at the specified period. period is measured in 0.1 second increments. block must be in the range 0 to PID _BLOCKS – 1.

Setting the period to 0 stops execution of the control block.

Notes

See the TelePACE PID Controllers Reference Manual for a detailed description of PID control.

The control b lock must be configured properly before it is engaged, or indeterminate operation may result.

T he IO_SYSTEM resource must be requested before calling this function.

See Also

set_pid, getPowerMode

Get Current Power Mode

Syntax

#include <ctools.h>

BOOLEAN getPowerMode(UCHAR* cpuPower, UCHAR* lan, UCHAR* usbPeripheral,

UCHAR* usbHost);

Description

The getPowerMode function places the current state of the CPU, LAN, USB peripheral port, and USB host port in the passed parameters. The following table lists the possible return values and their meaning.

Macro Meaning

PM_CPU_FULL

PM_CPU_REDUCED

The CPU is set to run at full speed

The CPU is set to run at a reduced speed

PM_CPU_SLEEP

PM_LAN_ENABLED

The CPU is set to sleep mode

The LAN is enabled

PM_LAN_DISABLED

PM_USB_PERIPHERAL_ENABLED

PM_USB_PERIPHERAL_DISABLED

The LAN is disabled

The USB peripheral port is enabled

The USB peripheral port is disabled

PM_USB_HOST_ENABLED

PM_USB_HOST_DISABLED

The USB host port is enabled

The USB host port is disabled

PM_UNAVAILABLE

The status of the device could not be read.

TelePACE C Tools User and Reference Manual

May 9, 2007

85

TRUE is returned if the values placed in the passed parameters are valid, otherwise FALSE is returned.

The application progra m may set the current power mode with the setPowerMode function.

See Also setPowerMode, setWak eSource, getWakeSource

get_pid, clear_pid

TelePACE C Tools User and Reference Manual

May 9, 2007

86

check_error

Get Error Code for Current Task

Syntax

#include <ctools.h> int check_error(void);

Description

The check_error function returns the error code for the current task. The error code is set by various I/O routines, when errors occur. A separate error code is maintained for each task.

Notes

Some routines in the standard C library, re turn errors in the global variable errno. This variable is not unique to a task, and may be modified by another task, before it can be read.

See Also

r eport_error

TelePACE C Tools User and Reference Manual

May 9, 2007

87

checksum

Calculate a Checksum

Syntax

#include <ctools.h> unsigned checksum(unsigned ch ar *start, unsigned char *end, unsigned

algorithm);

Description

The checksum function calculates a checksum on memory. The memory s tarts at the byte pointed to by start, and ends with the byte pointed to by end. The algorithm may be one of:

ADDITIVE

CRC_16

16 bit byte-wise sum

CRC-16 polynomial checksum

CRC_CCITT CRC-CCITT pol ynomial checksum

BYTE_EOR

8 bit byte-wise exclusive OR

The CRC checksums use the crc_reverse function.

See Also

crc_reverse

}

Example

This function displays two types of checksums.

#include <ctools.h> void checksumExample(void)

{ char str[] = "This is a test";

/* Display additive checksum */ sum = checksum(str, str+strlen(str), ADDITIVE); printf("Additive checksum: %u\r\n", sum);

/* Display CRC-16 checksum */ sum = checksum(str, str+strlen(str), CRC_16); printf("CRC-16 checksum: %u\r\n", sum);

TelePACE C Tools User and Reference Manual

May 9, 2007

88

checkSFTranslationTable

Test for Store and Forward Confi guration Errors

Syntax

#include <ctools.h> struct SFTranslationStatus checkSF TranslationTable(void);

Description

The checkSFTranslationTable function checks all entries in the address translation table for validity. It detects the following errors:

The function returns a SFTranslationStatus structure. Refer to the Structur es and Types section for a description of the fields in the SFTranslationStatus structure. The code field of the structure is set to one of the following. If there is an error, the index field is set to the location of th e translation that is not valid.

Result code

SF_VALID

SF_NO_TRANSLATION

SF_PORT_OUT_OF_RANGE

SF_STATION_OUT_OF_RANG

E

Meaning

All translations are valid

The entry defines re-transmission of the same message on the same port

One or both of the serial port indexes is not valid

One or both of the stations is not valid

Notes

The TeleBUS Protocols User Manual describes store and forward messaging mode.

See Also

getSFTranslation, setSFTranslation, checkSFTranslationTable

Example

See the example for the setSFTranslation function.

TelePACE C Tools User and Reference Manual

May 9, 2007

89

clearAllForcing

Clear All Forcing

Syntax

#include <ctools.h> void clearAllForcing(void);

Description

The clearAllForcing function removes all forcing conditions from all I/O database regist ers.

The IO_SYSTEM resource must be requested before calling this function.

See Als o

setForceFlag, overrideDbase

TelePACE C Tools User and Reference Manual

May 9, 2007

90

clear_errors

Clear Serial Port Error Counters

Syntax

#include <ctools.h> void clear_error s(FILE *stream);

Description

The clear_errors function clears the serial port error counters for the serial port specified by

stream. If stream does not point to a valid serial port the function has no effect.

The IO_SYSTEM resource must be requested before calling this function.

See Also

get_status

TelePACE C Tools User and Reference Manual

May 9, 2007

91

clear_pid

Clear PID Block Variables

Syntax

#include <ctools.h> void clear_pid(unsigned block);

Description

The clear_pid routine sets all variables in the specified control block to 0. clear_pid is normally used as the first step of control block configuration. block must be in the range 0 to

PID_BL

OCKS – 1.

Notes

See the Tele PACE PID Controllers Reference Manual for a detailed description of PID control.

V alues stored in PID blocks are not initialized when a program is run, and are guaranteed to re tain their values during power failures and program loading. PID block variables must a lways be initialized by the user program.

The IO_SYSTEM resource must be requested before calling this function.

See Also

set_pid, getPowerMode

Get Current Power Mode

Syntax

#include <ctools.h>

BOOLEAN getPowerMode(UCHAR* cpuPower, UCHAR* lan, UCHAR* usbPeripheral,

UCHAR* usbHost);

Description

The getPowerMode function places the current state of the CPU, LAN, USB peripheral port, and USB host port in the passed parameters. The following table lists the possible return values and their meaning.

Macro Meaning

PM_CPU_FULL

PM_CPU_REDUCED

The CPU is set to run at full speed

The CPU is set to run at a reduced speed

PM_CPU_SLEEP

PM_LAN_ENABLED

The CPU is set to sleep mode

The LAN is enabled

PM_LAN_DISABLED

PM_USB_PERIPHERAL_ENABLED

PM_USB_PERIPHERAL_DISABLED

The LAN is disabled

The USB peripheral port is enabled

The USB peripheral port is disabled

PM_USB_HOST_ENABLED

PM_USB_HOST_DISABLED

The USB host port is enabled

The USB host port is disabled

PM_UNAVAILABLE

The status of the device could not be read.

TelePACE C Tools User and Reference Manual

May 9, 2007

92

TRUE is returned if the values placed in the passed parameters are valid, otherwise FALSE is returned.

The application program ma y set the current power mode with the setPowerMode function.

See Also setPowerMode, setWak eSource, getWakeSource

get_pid, auto_pid

TelePACE C Tools User and Reference Manual

May 9, 2007

93

clear_protocol_status

Clear Protocol Counters

Syntax

#include <ctools.h> void clear_protocol_status(FILE *stream);

Description

The clear_protocol_status function clears the error and message counters for the serial port sp ecified by stream. If stream does not point to a valid serial port the function has no effect.

The IO_S YSTEM resource must be requested before calling this function.

See Also

get_protocol_status

TelePACE C Tools User and Reference Manual

May 9, 2007

94

clearRegAssignment

Clear Register Assignment

Syntax

#include <ctools.h> void clearRegAssignment(void);

Description

The clearRegAssignment function erases the current Register Assignment. Call this function first before using the addRegAssignment function to create a new Regist er

Assignment.

The IO_SYSTEM resource must be requested before calling this function.

See Als o

addRegAssignment

Example

See example for addRegAssignment.

TelePACE C Tools User and Reference Manual

May 9, 2007

95

clearSFTranslationTable

Clear Store and Forward Translati on Configuration

Syntax

#include <ctools.h> void clearSFTranslationTable(v oid);

Description

The clearSFTranslationTable function clears all entries in the store and forward translat ion table.

Notes

The TeleBU S Protocols User Manual describes store and forward messaging mode.

The IO_SYSTEM resource must be requested before calling this function.

See Also

getSFTranslation, setSFTranslation, checkSFTranslationTable

Example

See the example for the setSFTranslation function.

TelePACE C Tools User and Reference Manual

May 9, 2007

96

clearStatusBit

Clear Bits in Controller Statu s Code

Syntax

#include <ctools.h> unsigned clearStatusBit(unsigned bitMask);

Description

The clearStatusBit function clears the bits indicated by bitMask in the controller status code. When the status code is non-zero, the STAT LED blinks a binary sequence corresponding to the code. If code is ze ro, the STAT LED turns off.

The function returns the value of the status register.

Notes

The status output open s if code is non-zero. Refer to the System Hardware Manual for more information.

The binary sequence consists of short and long flashes of the error LED. A binary zero is indicated by a short flash of 1/10th of a second. A longer flash of approximately 1/2 of a second indicates a binary one. The least significant digit is output first. As f ew bits as possible are displayed – all leading zeros are ignored. There is a two-second delay betwe en repetitions.

The STAT LED is the LED located on the top left hand corner of the 5 203 or 5204 controller board.

Bits 0 and 1 of the status code are used by the Register Assignment.

S ee Also

setStatusBit, setStatus, getStatusBit

TelePACE C Tools User and Reference Manual

May 9, 2007

97

clear_tx

Clear Serial Port Transmit Buffer

Syntax

#include <ctools.h> void clear_tx(FILE *stream);

Description

The clear_tx function clears the transmit buffer for the serial port specified by stream. If

stream does not point to a valid serial port the function has no effect.

See Also

get_status

TelePACE C Tools User and Reference Manual

May 9, 2007

98

counter

Read Counter Input Module

Syntax

#include <ctools.h> long counter(unsigned counter);

Description

The counter function reads data from the counter input specified by channel. If the channel number is not valid a COUNTER_BADCOUNTER error is reported for the current task. The value returned by counter is not valid.

Notes

Refer to the TelePACE Ladder Logic User Manual for an explanation of counter input channel a ssignments.

Use offsets from the symbolic constants COUNTER_START and COUNTER_END to reference counter channels. The constants make programs more portable and protect against future changes to the counter input channel numbering.

The IO_SYSTEM resource must be requested before calling this function.

This function is provided for backward compatibility. It cannot access all 5000 series I/O modules. It i s recommended that this function not be used in new programs. Instead use

Register Assignment or call the I/O driver ioRead4Counter directly.

See Also

counterError, check_error, request_resource, release_resource, ioRead4Counter

TelePACE C Tools User and Reference Manual

May 9, 2007

99

counterError

Read Counter Input Error Flag

Syntax

#include <ctools.h> long counterError(unsigned counter);

Description

The counterErr or function returns the I/O error flag for a counter channel. It returns TRUE if an error occurred and FALSE if no occurred on the last read of the input module.

If the channel number is not valid a COUNTER_BADCOUNTER error is reported for th e current task. The value returned is not valid.

Notes

Refer to the TelePACE Ladder Logic User Manual for a explanation of counter input channel assignments.

Use offset s from the symbolic constants COUNTER_START and COUNTER_END to reference counter channels. The constants make programs more port able and protect against future changes to the counter input channel numbering.

This function is provided for backward compatibility. It cannot access all 5000 series I/O modules. It is recommended that this function not be used in new programs. Instead use

Register Assignmen t or call the I/O driver ioRead4Counter directly.

See Also

counter,

check_error, ioRead4Counter

TelePACE C Tools User and Reference Manual

May 9, 2007

100

crc_reverse

Calculate a CRC Checksum

Syntax

#i nclud e <ctools.

h> unsigned crc_reverse(unsig ned char *start, unsigned char *end, unsigned

poly, unsigned initial);

D ip on

The crc_reverse function calculates a CRC type check sum on memory using the reverse al gorith T nted to by start, and ends with the byte pointed to by en T poly. poly may be any value, but must be carefully chosen to ensure good error detection. The ch ecksum accumulator is set to initial be fore the calculation is started.

No tes

T he reverse algorithm is named for the direction bits are shifted. In the reverse algorithm, bits are shifted toward s the least significant bit. This produces different checksums than the classical, or forward algorithm , using the same polynomials.

See Also

ch ecks um

TelePACE C Tools User and Reference Manual

May 9, 2007

101

crea te_task

Create a New Task

Syntax

#include <ctools.h> int create_task(void *function, unsigned priority, unsigned type, unsigned

stack);

Description

The create_task function allocates stack space for a task and places the task on the ready queue. function specifies the start address of the routine to be executed. The task will execute immediately if its priority is higher than the current task.

priority is an execution priority between 1 and 4 for the created task. The 4 task priority levels aid in scheduling task execution.

type specifies if the task is ended when an application program is stopped. Valid values for

type are:

SYSTEM system tasks do not terminate when the program stops

APPLICATION application tasks terminate when the program stops

It is recommended that only APPLICATION type tasks be created.

The stack parameter specifies how many stack blocks are allocated for the task. Each stack block is 256 bytes.

The create_task function returns the task ID (TID) of the task created. If an error occurs, -1 is returned.

Notes

Refer to the Real Time Operating System section for more information on tasks.

Note that the main task and the Ladder Logic and I/O scanning task have a priority of 1. If the created task is continuously running processing code, create the task with a priority of 1 and call release_processor periodically; otherwise the remaining priority 1 tasks will be blocked from executing.

For tasks such as a protocol handler, that wait for an event using the wait_event or

receive_message function, a priority greater than 1 may be selected without blocking other lower priority tasks.

The number of stack blocks required depends on the functions called within the task, and the size of local variables created. Most tasks require 2 stack blocks. If any of the printf functions are used, then at least 4 stack blocks are required. Add local variable usage to these limits, if large local arrays or structures are created. Large structures and arrays are usually best handled as static global variables within the task source file. (The variables are global to all functions in the task, but cannot be seen by functions in other files.)

Additional stack space may be made available by disabling unused protocol tasks. See the section Program Development or the set_protocol() function for more information.

See Also

end_task

TelePACE C Tools User and Reference Manual

May 9, 2007

102

Example

#include <ctools.h> void task 1(void)

{ int a, b;

{

/* b ody of task 1 loop - processing I/O */ request_resource(IO_SYSTEM); a = dbase(MODBUS, 30001); b = dbase(MODBUS, 30002); setdbase(MODBUS, 40020, a * b); release_resource(IO_SYSTEM);

/* Allow other tasks to execute */ release_processor();

}

} void tas k2(void)

{

while(TRUE)

{

/* body of task 2 loop - event handler */ wait_event(TIME_TO_PRINT); prin

} tf("It’s time for a coffee break\r\n");

}

/* -------------------------------------------

The shut down function stops the signalling

of TIME_TO_PRINT e vents when application is

stopped.

------------------------------------------- */ void shutdown(void)

{ endTimedEvent(TIME_TO_ PRINT);

} vo id main(void)

{

/* continuos processing task at priority 1 */ create_task(task1, 1, APPLICATION, 2);

/* event handler needs larger stack create_task(task2, 3, APPLICATION,

for printf function */

4);

/* set up task exit handler to stop

signalling of events when this task ends */ taskStatus = getTaskInfo(0);

/* start timed event to occur every 10 sec */

while(TRUE)

{

/* body of main task loop */

/* other processing code */

/* Allow other tasks to execute */

TelePACE C Tools User and Reference Manual

May 9, 2007

103

release_processor();

}

}

TelePACE C Tools User and Reference Manual

May 9, 2007

104

data ba se Read

Read Value from I/O Database

Syntax

#include <ctools.h>

BOOLEAN databaseRead(UINT16 type, UINT16 address, INT16* value)

Description

The databaseRead function reads a value from the database. The value is written to the variable pointed to by value. The variable is not changed if type and address are not valid.

The function has three parameters. type specifies the method of addressing the database.

Valid values are MODBUS and LINEAR. address specifies the location in the database. value

is a pointer to a variable to hold the result.

The function returns TRUE if the specified address is valid and FALSE if the register does not exist.

Notes

The IO_SYSTEM resource must be requested before calling this function.

See Also

databaseWrite

Example

#include <ctools.h> void main(void)

{

request_resource(IO_SYSTEM);

/* Read Modbus status input point */ status = databaseRead(MODBUS, 10001, &value);

/* Read 16 bit register */ status = databaseRead(LINEAR, 3020, &value);

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

105

databaseWrite

Write Value to I/O Database

Syntax

#include <ctools.h>

BOOLEAN databaseWrite(UINT16 type, UINT16 address, INT16 value)

Description

The databa seWrite function writes value to the I/O database.

The function has three parameters. type specifies the method of addressing the database.

Valid values are MODBUS and LINEAR. address specifies the location in the database. value

is the data to write.

The function returns TRUE if the value was written. The function returns FALSE if

• the type is invalid

• the address is not valid for the controller

• the address is read only on the SCADASense 4202 controller (some registers in the range 40001 to 40499).

• the data is not valid for the address on the SCADASense 4202 controller (some registers in the range 40001 to 40499).

• the hardware write protect is installed on the SCADASense 4202 controller (regis ters in the range 40001 to 40499).

• the flow computer is running on the SCADASense 4202 controller (registers in the range

40001 to 40499).

Notes

When writing to LIN EAR digital addresses, value is a bit mask which writes data to 16 1-bit registers at once. If any of these 1-bit registers is invalid, only the valid registers are written and FALSE i s returned.

The IO_SYSTEM resource must b e requested before calling this function.

See Also

databaseRead

Example

#include <ctools.h> void main(void)

{

request_resour ce(IO_SYSTEM); status = databaseWrite(MODBUS , 40001, 102);

coil s */ status = databaseWrite(LINEAR , 0, 255);

TelePACE C Tools User and Reference Manual

May 9, 2007

106

/* Write to a 16 bit register */ status = databaseWrite(LINEAR, 3020, 240);

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

107

datalogCreate

Create Data Log Function

Syntax

#include <ctools.h>

DATALOG_STATUS datalogCreate(

UINT16 logID,

DATALOG_C ONFIGURATION * pLogConfiguration

);

Description

This function creates a data log with the specified configuration. The data log is created in the data log memory space.

The function has two parameters. logID specifies the data log to be created. The valid range is 0 to 15. pLogConfiguration points to a structure with the configuration for the data log.

The function returns the status of the operation.

Notes

The configuration of an existing data log cannot be changed. The log must be deleted and recreated to change the configuration.

All data logs are stored in memory from a pool for all data logs . If there is insufficient memory the creation operation fails. The function returns DLS_N

OMEMORY

.

If the data log already exists the creation operation fails. The function returns DLS_EXISTS.

If the log ID is not valid the creation operation fails. The function return s DLS_BADID.

If the configuration is not va lid the creation operation fails. The function returns

DLS_BADCONFI G

.

See Also

datalogDelete datalogSettings

Example

/*---------------------------------------------

The following code shows how to create a

data log and how to write one record into it.

--------------------------------------------*/

#include "ctools.h"

/*--------------------------------

Stru cture used only to copy on e

record into data log

------------------------------*/ struct dataRecord

{

UINT16 value1; int value2;

double value3;

TelePACE C Tools User and Reference Manual

May 9, 2007

108

}; int logID ;

/*---------------------------------

Declare a structure for the log

---------------------------------* /

DATALOG_ I I

/*----------------------------

Dec lare a struture to hold the

data that will be copied in log

--------------------------------*/ struct dataRecord data;

/* ---------------------

Function declaration

----------------------*/ void ConfigureLog(void); void InitRecord(void); void main(void)

{

ConfigureLog();

InitRecord();

/* function call to cofigure log */ if(datalogCreate(logID, &dLogConfig) == DLS_CREATED)

{

/* Start writing records in log */ if( datalogWrite(logID, (UINT16 *)&data) )

{

}

}

{

/* one record was written in data log */

}

/* Log configuration */ void ConfigureLog(void)

/* Assign a number to the data log */ logID = 10;

/* Fill in the log configuration structure */ dLogConfig.records = 200; dLogConfig.fields = 5; dLogConfig.typesOfFields[0] = DLV_UINT16; dLogConfig.typesOfFields[1] = DLV_INT32; dLogConfig.typesOfFields[2] = DLV_DOUBLE; dLogConfig.typesOfFields[3] = DLV_FLOAT;

}

} dLogConfig.typesOfFields[4] = DLV_FLOAT;

/* One record initialization */ void InitRecord(void)

{

/* Assign some data for the log */ data.value1 = 100; data.value2 = 200; data.value3 = 30000; data.value4 = 40.3; data.value5 = 50.75;

TelePACE C Tools User and Reference Manual

May 9, 2007

109

datalogDelete

Delete Data Log Function

Syntax

#include <ctools.h>

BOOLEAN datalogDelete(

);

Description

This function de stroys the specified data log. The memory used by the data log is returned to the freed.

The function has one parameter. logID specifies the data log to be deleted. The valid range is 0 to 15.

The function returns TRUE if the data log was deleted. The function returns FALSE if the log

ID is not valid or if the log had not been created.

See Also

datalogCreate

Example

/* The following code shows the only way to

chan ge the configuration of an existing log

is to delete the log and recreate the data

log */

#include <ctools.h> int logID;

/* Declare a structure for the log */

DATALOG_CONFIGURATION dLogConfig;

/* Select logID #10 */ logID = 10 ;

/* Read the configura tion of logID #10 */ i f( datalogSettings( logID, &dLogConfig ) )

{

if(dLogConfig.typesOfField

s[0] == DLV_INT16)

{

/* Wrong type. Delete whole log and start from scratch */

if(datalogDelete (logID) )

{

/* Reenter the log config uration */ dLogCon fig.records = 200; dLogConfig.fields = 5; dLogConfig.t

ypesOfFields[0] = DLV_UINT16; dLogConfig.ty

pesOfFields[1] = DLV_INT32; dLogConfig.typesOfFields[2] = DLV_DOUBLE; dLogConfig.types

OfFields[3] = DLV_FLOAT;

TelePACE C Tools User and Reference Manual

May 9, 2007

110

dLogConfig.typesOfFields[4] = DLV_FLOAT;

datalogCreate(logID, &dLogConfig);

}

else

{

/* could not delete log */

}

}

} el se

{

/* Could not read settings */

}

TelePACE C Tools User and Reference Manual

May 9, 2007

111

datalogPurge

Purge Data Log Function

Syntax

#include <ctools.h>

BOOLEAN datalogPurge( logID,

);

Description

This functio n removes records from a data log. The function can remove all the records, or a group of records starting with the oldest in the log.

The function has three parameters. logID

specifies the data log. The valid range is 0 to 15.

If purgeAll is TRUE, all records are removed, otherwise the oldest records are removed. sequenceNumber

specifies the sequence number of the most recent record to remove. All records up to and including this record are removed. This parameter is ignor ed if purgeAll is TRUE.

The function returns TRUE if the operation succeeds. The function returns FALSE if the log

ID is invalid, if the log has not been created, or if the sequence number cannot be found in the log.

Notes

Purging the oldest records in the log is usually done after reading the log. The sequence number used is that of the last record read from the log. This removes the records that have been read and leaves any records added since the records were read.

If the seq uence number specifies a record that is not in the log, no records are removed.

See Also

datalogReadStart datalogReadNext datalogWrite

Exam ple

#include <ctools.h> int logID, sequenceNumber;

/* Declare flag to purge entire of data log or part of it */

BOOLEAN purgeAll;

/* Which data log to purge? */ logID = 10;

/* Set fla g to purge only part of data log */ purgeAll = FALSE;

/* How many of the oldest records to purge */ sequenceNumber = 150;

TelePACE C Tools User and Reference Manual

May 9, 2007

112

if( datalogPurge(logID, purgeAll, sequenceNumber) )

{

/* Successful at purging the first 150 records of log */

/* Start writing records again */

}

/* To purge the entire data log, simply set flag to TRUE */ purgeAll = TRUE;

/* Call up function with s ame parameters */ if( datal ogPurge(logID, purgeAll, sequenceNumber) )

{

}

/* Suc cessful at purging the entire data log */

/* Start writing records again */

TelePACE C Tools User and Reference Manual

May 9, 2007

113

data lo gRe adNext

Read Da ta L og Next Function

This function returns the next record in the data log.

Syntax

#include <ctools.h>

BOOLEAN datalogRead Next(

U , s n ceNum ber,

UINT32 * pSequenceNumber,

UINT32 * pNextSequenceNumber,

UINT16 * pData

) ;

Desc p on

This function reads the next record from t he data log starting at the specified sequence num ber. The function returns the record with the specified sequence number if it is present in the log. If the record no longer exists it returns the next record in the log.

The function has five parameters. logID specifies the data log. The valid range is 0 to 15. sequenceNumber

is sequence number of the record to be read. pSequenceNumber is a pointer to a variable to hold the sequence number of the record read. pNextSequenceNumber

is a pointer to a variable to hold the sequence number of the next record in the log. This is normally used for the next call to this function. pData is a pointer to memory to hold the data read from the log.

The function returns TRUE if a record is read from the log. The function returns FALSE if the log ID is not valid, if the log has not been created or if there are no more records in the log.

Notes

Use the datalogReadStart function to obtain the sequence number of the oldest record in the data log.

The pData parameter must point to memory of sufficient size to hold all the data in a record.

It is normally necessary to call this function until it returns FALSE in order to read all the data from the log. This accommodates cases where data is added to the log while it is being read.

If data is read from the log at a slower rate than it is logged, it is possible that the sequence numbers of the records read will not be sequential. This indicates that records were overwritten between calls to read data.

The sequence number rolls over after reaching its maximum value.

See Also

datalogReadStart datalogPurge datalogWrite

Example

See the example for datalogReadStart.

TelePACE C Tools User and Reference Manual

May 9, 2007

114

datalogReadStart

Read Data Log Start Function

Syntax

#include <ctools.h>

BOOLEAN datalogReadStar t( logID,

UINT32 * pSequenceNu

); mber

Description

This function ret urns the sequence number of the record at the start of the data log. This is the oldest record in the log.

The function has two parameters. logID specifies the d ata log. The valid range is 0 to 15. pSequenceNumber

is a pointer to a variable to hold the sequence number.

The function returns TRUE if the operation succeeded. The function returns FAL SE if the log

ID is not valid or if the log has not been created.

Notes

Use the datalogReadNext function to read records from the log.

The function will return a sequence number even if the log is empty. In this case the nex t call to datalogReadNext will return no data.

See Also

datalogReadNext

datalogPurge datalogWrite

Example

/****************************** ******************

The following code shows how to read records

from data log.

************************************************/

#include "ctools.h"

#include <stdlib.h>

UINT16 recordSize,

logID,

*pData; /* Pointer to memory to hold data read from log. */

UINT32 sequenceNumber,/* Sequence number of record to be read. */

nextSequenceNumber; /* Sequence number of next record. */ void main(void)

{

/* Select data log #10 */

logID = 10;

/* Find first record in data log #10 and store

its sequence number into sequenceNumber */

TelePACE C Tools User and Reference Manual

May 9, 2007

115

if( datalogReadStart(logID, &sequenceNumber) )

{

/* Get the size of this record */ if( datalogReco rdSize(logID, &recordSize) )

{

/* Allocate memory of size recordSize */ pData = (UINT16 *) malloc(recordSize);

/* Read all record s from data log #10. */

while( da talogRe adNext(logID, sequenceNumber,

&sequenceNumber, &nextSequenceNumber, pData ) )

{

/* Use pData and its contents.

Set next sequence number of record to be read. */

}

sequenceNumber = nextSequenceNumber;

}

}

}

TelePACE C Tools User and Reference Manual

May 9, 2007

116

datalogRecordSize

Data Log Record Size Fun ction

Syntax

#include < ctools.h >

BOOLEAN datalogRecordSi ze(

UINT16 * pRecord

);

Size;

Description

This function returns the size of a record for the specified data log. The log must have been previously created with the datalogCreate function.

The function has two parameters. logID specifies the data log. The valid range is 0 to 15. pRecordSize points to a variable that will hold the size of a record in the log.

The function returns TRUE if the operation succeeded. The function returns FALSE if the log

ID is invalid or if the data log does not exist.

Notes

This func tion is useful in determining how much memory must be allocated for a call to datalogReadNext

or datalogWrite.

See Also

datalogSetti

ngs

Example

See the exam

ple for datalogReadStart.

TelePACE C Tools User and Reference Manual

May 9, 2007

117

datalogSettings

Data Log Settings Function

Syntax

#include < ctools.h >

BOOLEAN datalogSettings(

DATALOG_CONF IGURATION * pLogConfiguration

);

Description

This function reads the configuration of the specified data log. The log must have been p revious ly crea ted with the datal ogCreate

function .

T gID

specifies the data log. The valid range is 0 to 15. pLogConfigu ration

points to a structure that will hold the data log configuration.

The function re turns TRUE if the operation succee de d. The f unction returns FALSE if the log

ID is invali d or if the data log does not exist.

Notes

The configuration of an existing data log cannot be changed. The log must be dele ted and recreated to change the configuration.

See Also

datalogRecordSize

Example

See example

for datalogDelete.

TelePACE C Tools User and Reference Manual

May 9, 2007

118

datalogWrite

Write Data Log Function

Syntax

#include <ctools.h>

BOOLEAN datalogWrite(

UINT16 * pData

);

Description

This function writes a record to the specified data log. The log must have been previously created with the datalogCreate function.

The function has two parameters. logID specifies the data log. The valid range is 0 to 15. pData

is a pointer to the data to be written to the log. The amount of data copied using the pointer is determined by the configuration of the data log.

The function returns TRUE if the data is added to the log. The function returns FALSE if the log ID is not valid or if the log does not exist.

Notes

Refer to the datalogCreate function for details on the configuration of the data log.

If the data log is full, then the oldest record in the log is replaced with this record.

See Also

datalogReadStart datalogReadNext datalogPurge

Example

See the example for datalogDelete.

TelePACE C Tools User and Reference Manual

May 9, 2007

119

dbase

Read Value from I/O Database

Syntax

#include <ctools.h> int dbase(unsigned type, unsigned address);

Description

The dbase function reads a value from the I/O database. type specifies the method of addressing the database. address specifies the locat ion in the database. The table below shows the valid address types and ranges

Type Address Ranges Register

Size

MODBUS 00001 to NUMCOIL

10001 to 10000 + NUMSTATUS

1 bit

1 bit

30001 to 30000 + NUMINPUT 16 bit

40001 to 40000 + NUMHOLDING 1 6 bit

LINEAR 0 to NUMLINEAR-1 16 bit

Notes

Refer to the I/O Database and Register Assignment chapter for more information.

If the specified register is currently forced, dbase returns the forced value for the register.

The I/O database is not modified when the controller is reset. It is a permanent storage area, which is maintained during power outages.

The IO_SYSTEM resource must be requested before calling this function.

See Also

setdbase

Example

#include <ctools.h> void main(void)

{

request_resource(IO_SYSTEM);

/* Read Modbus status input point */ a = dbase(MODBUS, 10001);

/* Read 16 bit register */ a = dbase(LINEAR, 3020);

/* Read 16 bit register beginning at first status register */ a = dbase(LINEAR, START_STATUS);

/* Read 6th input register */ a = dbase(LINEAR, START_INPUT + 5);

TelePACE C Tools User and Reference Manual

May 9, 2007

120

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

121

deall cat e_envelope

Return E nve p

Sy ntax

#include <ctools.h> void deallocate_envelope(envelope *penv);

Description

The deallocate_envelope function returns the envelope pointed to by penv to the pool of free envelopes maintained by the operating system.

See Also

allocate_envelope

Example

See the example for the allocate_envelope function.

TelePACE C Tools User and Reference Manual

May 9, 2007

122

din

Read Digital I/O

Syntax

#include <ctools.h> int din(unsigned channel);

Description

The din function reads the value of a digital input or output channel. Reading an input channel returns data read from a digital input module. Reading an output channel returns the last value written to the output module.

The din function returns a value corresponding to the sum of the binary states o f all 8 bits of the channel.

Notes

The din function reads the status of digital i nput signals, and digital output modules.

The din function may be used to read the current values in the I/O disable, forced status an d

I/O form tables, and I/O type tables.

Use offsets from the symbolic con stants DIN_START, DIN_END, DOUT_START,

DOUT_END, EXTENDED_DIN_START, EXTENDED_DIN_END,

EXTENDED_DOUT_START and EXTENDED_DOUT_END to reference digital c hannels.

The constants make programs more portable and protect against future changes to the digital I/O channel numbering.

The IO_SYSTEM resource must be reque sted before calling this function.

This function is provided for backward compatibility. It cannot access all 5000 series I/O mod ules. It is recommended that this function not be used in new programs. Instead use

Reg ister Assignment or call the I/O driver ioRead8Din directly.

See Also

pulse, timeout, turnon, turnoff, on, off

Example

This program displays the first 8 digital inputs in binary.

#include <c tools.h> void main(void)

{ int loo p, value;

/* Read the first digital inp ut channel */

request_resource(IO_SYSTEM); value = din(DIN_START);

release_resource(IO_SYSTEM);

/* For each bit in the channel */ for(loop = 8; loop; loop--)

TelePACE C Tools User and Reference Manual

May 9, 2007

123

{ putchar((value & 0x80) ? '1' :'0')

/* Select the next bit */ value <<= 1;

} puts( "\r\n" );

}

TelePACE C Tools User and Reference Manual

May 9, 2007

124

dnpInstallConnectionHandler

Configures the connection handler for DNP.

Syntax

#include <ctools.h> void dnpInstallConnectionHandler(void (* function)

(DNP_CO NNECTION_EVENT event));

Description

This function installs a handler that will permit user-defined actions to occur when DNP requ ires a connection, message confirm ation is received, or a timeout occurs. function

is a pointer to the handler function. If function is NULL the handler is disab led.

The function has n o return value.

Notes

The handler function must process the event and return immediate ly. If the required action involves waiting this must be done outside of the ha ndler function. See the example below for one possible implementation.

Th e app lication must disable the handler when the application ends. This prevents the protocol driver from calling the handler while the application is stopped. Call the dnpInstallConnectionHandler

with a NULL point er. The usual method is to create a task exit handler function to do this. See the example below for details.

The handler function has one parameter.

• event

is DNP event that has occurred. It may be one of

DNP_CONNE CTION_REQUIRED

,

DNP_MESSAGE_COMP LETE

, or DNP_MESSAGE_TIMEOUT. See the st ructure definition for the eaning f thes e events.

The handler function has no return value.

By default no connection handler is installed and no special steps are taken wh en DNP requires a connection, receives a message confirmation, or a tim eout occurs.

See Also

dnpConnectionEvent

E l

This example shows how a C application can handle the events and inform a log ic application of the events. The logi c application is responsible for making and end ing the dialup connection.

The program uses the following registers.

100 01 turns on when a connection is requested by DNP for unsolicit ed reporting.

• 10002 turns on when the unsolicited report is comp lete.

• 10003 turns o n when the unsolicited report is fails.

TelePACE C Tools User and Reference Manual

May 9, 2007

125

• The ladder logic progr am turns on register 1 when the connection is complete and turns off the register when t he connection is broken.

/* ----------------------------------------------------------------------

dnp.c

Demonstr ation program for using the DNP connection handler.

Copyright 2001, Control Micros ystems Inc.

----------------------------------------------------------------------- */

/* -----------------------------------------------------------------------

Include Files

---------------------------------------------------------------------- */

#include <ctools.h>

/* ----------------------------------------------------------------------

Constants

----------------------------------------------------------------------- */

#define CONNE CTION_REQUIRED 10001 /* register for signaling connection required */

#define MESSA GE_COMPLETE 10002 /* register for signaling unsolicited message is complete */

#define MESSAGE_FAILED 10003 /* register fo r signaling unsolicited message

#define CONNECTION_STATUS 1 failed */

/* connection status register */

/* -----------------------------------------------------------------------

Private Functions

----------------------------------------------------------------------- */

/* -----------------------------------------------------------------------

sampleDNPHandler

This function is the user defined DNP connection handler. It will be

called by internal DNP routines when a connection is required, when

confirmation of a message is received, and when a communication timeout

occurs.

The function takes a variable of type DNP_CONNECTION_EVENT as an input.

This input instructs the handler as to what functionality is required.

The valid choices are connection required (DNP_CONNECTION_REQUIRED),

message confirmation received (DNP_MESSAGE_COMPLETE), and timeout occurred

(DNP_MESSAGE_TIMEOUT).

The function does not return any values.

----------------------------------------------------------------------- */ static void sampleDNPHandler(DNP_CONNECTION_EVENT event)

{

/* Determine what connection event is required or just occurred */

switch(event)

{

/* indicate connection is needed and clear other bits */

request_resource(IO_SYSTEM);

release_resource(IO_SYSTEM);

break;

/* indicate message sent and clear other bits */

request_resource(IO_SYSTEM);

release_resource(IO_SYSTEM);

break;

/* indicate message failed and clear other bits */

request_resource(IO_SYSTEM);

release_resource(IO_SYSTEM);

TelePACE C Tools User and Reference Manual

May 9, 2007

126

break;

default:

/* ignore invalid requests */

break;

}

}

/* ----------------------------------------------------------------------

Public Functions

---------------------------------------------------------------------- */

/* ----------------------------------------------------------------------

main

This function is the main task of a user application. It monitors a

register from the ladder logic application. When the register value

changes, the function signals DNP events.

The function has no parameters.

The function does not return.

----------------------------------------------------------------------- */ void main(void)

{ int lastConnectionState; int currentConnectionState;

/* i

/* last state of connection register */

/* current state of connection register */ nstall DNP connection handler */

dnpI nstallConnectionHandler(sampleDNPHandler);

/* get the current connection state */ lastConnectionState = dbase(MODBUS, CONNECTION_STATUS);

/* loop forever */

{

request_resource(IO_SYSTEM);

/* get the current connection state */ currentConnectionState = dbase(MODBUS, CONNECTION_STATUS);

/* if the state has changed */ if (currentConnectionState != lastConnectionState)

{

/* if the connection is active */

{

/* Inform DNP that a connection exists */

dnpConnectionEvent(DNP_CONNECTED);

/* clear the request flag */

}

else

{

/* Inform DNP that the connection is closed */

dnpConnectionEvent(DNP_DISCONNECTED);

/* clear the message flags */

}

/* save the new state */

}

/* release the processor so other tasks can run */

release_resource(IO_SYSTEM);

release_processor();

}

}

TelePACE C Tools User and Reference Manual

May 9, 2007

127

dnpClearEventLog

Clear DNP Event Log

Syntax:

#include <ctools.h>

BO OLEAN dnpClearEventLog(void);

Description:

The dnpClearEventLogs function deletes all change events from the DNP change event buffers, for all po int types.

Example:

See the example in the section dnpSendUnsolicited.

TelePACE C Tools User and Reference Manual

May 9, 2007

128

dnpConnectionEvent

Report a DNP connection event

Syntax

#inclu de <ctools.h> void dnpConnectionEvent(DNP_CONNECTION_EVENT event);

Descr iption

dnpConnectionEvent

is used to report a change in connection status to DNP. This function is only u sed if a custom DNP connection handler has been installed. event is current connection status. The valid connection status settings are

DNP_CONNECTED

, and DNP_DISCONNECTED.

See Also

dnpInstallConnectionHandler

Example

See the dnpInstallConnectionHandler exa mple.

TelePACE C Tools User and Reference Manual

May 9, 2007

129

dnpCreateRoutingTable

Create Routing Table

Syntax

#include <ctools.h>

BO OLEA N createRoutingTable (UINT16 si ze);

Description

This function de stroys any existing DNP routing table, and allocates memory for a new routing table according to the ‘size’ parameter.

Notes

DNP must be enabled before calling this function in order to create the DNP configurat ion.

The function returns TRUE if successful, FALSE otherwise.

Examp le

See the example in the section dnpSendUnsolicited.

TelePACE C Tools User and Reference Manual

May 9, 2007

130

dnpGenerateEventLog

Generate DNP Event Log

Syntax

#include <ctool s.h>

BOOLEAN dnpGenerateEv ent Lo g(

UINT16 pointType,

UINT16 pointAddress

);

Description

The dnpGenerateEventLog function generates a change event for the DNP point specified by pointType and pointAddress. pointType

specifies th e type of DNP point. Allowed values are:

BI_POINT binary

AI16_POINT

AI32_PO INT

16 bit analog input

32 bit analog input

AISF_POINT short float analog input

CI16_POINT

CI32_POINT

16 bit counter output

32 bit counter output pointAddress

specif ies the DNP address of the point.

A change event is generated for the specified point (with the current time and current value), and stored in the DNP event buffer.

The format of the event will depend on the Event Reporting M ethod and Class of Event

Object that have been configured for the point.

The function returns TRUE if the event was generated. It returns FALSE if the DNP point is invalid, or if the DNP configuration has not been created.

Notes

DNP must be enabled before calling this function in order to create the DNP configuration.

Example

See the example in the section dnpSendUnsolicited.

TelePACE C Tools User and Reference Manual

May 9, 2007

131

dnpGetAI16Config

Get DNP 16-bit Analog Input Configuration

Syntax

#include <ctools.h>

BOOLEAN dnpGetAI16Config(

UINT16 point, dnpAnalogInput * pAnalogInput

);

Description

This function reads the configuration of a DNP 16-bit analog input point.

The function has two parameters: the point number; and a pointer to an analog input point configuratio n structure.

The function returns TRUE if the configuration was read. It returns FALSE if the point number is not valid, if the pointer is NULL, or if DNP configuration has not been created.

Notes

DNP mus t be enabled before calling this function in order to create the DNP configuration.

See Also

dnpSaveAI16Config

Example

See example in the dnpGetConfiguration function section.

TelePACE C Tools User and Reference Manual

May 9, 2007

132

dnpGetAI32Config

Get DNP 32-bit Analog Input Configuration

Syntax

#include <ctools.h>

BOOLEAN dnpGetAI32Config(

UINT32 point, dnpAnalogInput * pAnalogInput

);

Description

This function reads the configuration of a DNP 32-bit analog input point.

The function has two parameters: the point number; and a pointer to an analog input point configuration structure.

The function returns TRUE if the configuration was read. It returns FALSE if the point number is not valid, if the pointer is NULL, or if DNP configuration has not been created.

Notes

DNP must be enabled before calling this function in order to create the DNP configuration.

See Also

dnpSaveAI32Config

Example

See example in the dnpGetConfiguration function section.

TelePACE C Tools User and Reference Manual

May 9, 2007

133

dnpGetAISFConfig

Get Short Floating Point Analog Input Configuration

Syntax

#include <ctools.h>

BOOLEAN dnpGetAISFConfig (

);

Description

This function reads the configuration of a DNP short floating point analog in put point.

The function has two parameters: the point number, and a pointer to a configuration structure.

The function returns TRUE if the configuration was successfully read, or FALSE otherw ise (if the point number is not valid, or pointer is NULL, or if the DNP configuration has not been created).

Notes

DNP must be enabled before calling this function in order to create the DNP configuration.

TelePACE C Tools User and Reference Manual

May 9, 2007

134

dnpGetAO16Config

Get DNP 16-bit Analog Output Configuration

Syntax

#include <ctools.h>

BOOLEAN dnpGetAO16Config(

UINT16 point, dnpAnalogOutput * pAnalogOutput

);

Description

This function reads the configuration of a DNP 16-bit analog output point.

The function has two parameters: the point number; and a pointer to an analog outpu t point configuratio n structure.

The function returns TRUE if the configuration was read. It returns FALSE if the point number is not valid, if the pointer is NULL, or if DNP configuration has not been created.

Notes

DNP mus t be enabled before calling this function in order to create the DNP configuration.

S ee Also

dnpSaveAO16Config

Example

See example in the dnpGetConfiguration function section.

TelePACE C Tools User and Reference Manual

May 9, 2007

135

dnpGetAO32Config

Get DNP 32-bit Analog Output Config uration

Syntax

#include <ctools.h>

BOOLEAN dnpGetAO32Config(

UINT32 point, dnpAnalogOutput * pAnalogOutput

);

Description

This function reads the configuration of a DNP 32-bit analog outpu t point.

The function has two parameters: the point number; and a pointer to an analog output poi nt configuration structure.

The function returns TRUE if the configuration was read. It returns FALSE if the point number is not valid, if the pointer is NULL, or if DNP configuration has not been created.

Notes

DNP must be enabled before calling this function in order to create the DNP configuration.

See Also

dnpSaveAO32Conf ig

Example

See example in the dnpGetConfiguration function section.

TelePACE C Tools User and Reference Manual

May 9, 2007

136

dnpGetAOSFConfig

Get Short Floating Point Analog Output Configuration

Syntax

#include <ctools.h>

BO OLEA N dnpGetAOSFConf ig (

);

Description

This function reads the configuration of a DNP short floating point analog outp ut point.

The function has two parameters: the point number, and a pointer to a configuration structure.

The function returns TRUE if the configuration was successfully read, or FALSE otherwise (if the point number is not valid, or pointer is NULL, or if the DNP configuration has not been created).

Notes

DNP must be enabled before calling this function in order to create the DNP configuration.

TelePACE C Tools User and Reference Manual

May 9, 2007

137

dnpGetBIConfig

Get DNP Binary Input Configuration

Syntax

#include <ctools.h>

BOOLEAN dnpGetBIConfig(

UINT16 point, dnpBinaryInput * pBinaryInput

);

Description

This function reads the configuration of a DNP binary input point.

The function has two parameters: the point number; and a pointer to a binary input point configuration structure.

The function returns TRUE if the configuration was read. It returns FALSE if the point number is not valid, if the pointer is NULL, or if DNP configuration has not been created.

Notes

DNP must be enabled before calling this function in order to create the DNP configuration.

See Also

dnpSaveBIConfig

Example

See example in the dnpGetConfiguration function section.

TelePACE C Tools User and Reference Manual

May 9, 2007

138

dnpGetBIConfigEx

Read DNP Binary Input Extended Point

Syntax

BOOLEAN dnpGetBIConfi gEx(

UINT16 point,

);

Description

This function reads the configuration of an extended DNP Binary Input po int.

The function has two parameters: the point number, and a pointer to an extended binary input point configuration structure.

The function returns TRUE if the configuration was successfully read. It returns FALSE if the point number is not valid, if the configuration is not valid, or if the DNP configuration has n ot been created.

This func tion supersedes dnpSaveBIConfig.

TelePACE C Tools User and Reference Manual

May 9, 2007

139

dnpGetBOConfig

Get DNP Binary Output Configuration

Syntax

#include <ctools.h>

BOOLEAN dnpGetBOConfig(

UINT16 point, dnpBinaryOutput * pBinaryOutput

);

Description

This function reads the configuration of a DNP binary output point.

The function has two parameters: the point number; and a pointer to a binary output point configuration structure.

The function returns TRUE if the configuration was read. It returns FALSE if the point number is not valid, if the pointer is NULL, or if DNP configuration has not been created.

Notes

DNP must be enabled before calling this function in order to create the DNP configuration.

Example

See example in the dnpGetConfiguration function section.

TelePACE C Tools User and Reference Manual

May 9, 2007

140

dnpGetCI16Config

Get DNP 16-bit Counter Input Configuration

Syntax

#include <ctools.h>

BOOLEAN dnpGetCI16Config(

UINT16 point, dnpCounte rInput * pCounterInput

);

Description

This function reads the configuration of a DNP 16-bit counter input point.

The function has two parameters: the point number; and a pointer to a counter input point configuration structure.

The function returns TRUE if the configurat ion was read. It returns FALSE if the point number is no t valid, if the pointer is NULL, or if DNP configuration has not been created.

Notes

DNP must be enabled before calling this function in order to create the DNP configuration.

See Also

dnpSaveCI16Con fig

Example

See example in the dnpGetConfigurat on

funct ion section.

TelePACE C Tools User and Reference Manual

May 9, 2007

141

dnpG tCI 32Config

Get DN 32bit Counter Input Configuration

S ynta x

#include <ctools.h>

BOOLEAN dnpGetCI32Config(

UINT32 point, dnpCounterInput * pCounterInput

);

Description

This function reads the configuration of a DNP 3 2-bit counter input point.

The function has two parameters: the point number; and a pointer to a counter in put point configuration structure.

The function returns TRUE if the configuration w as read. It returns FALSE if the point number is not valid, if the pointer is NULL, or if DN P configuration has not been created.

Notes

DNP must be enabled before calling this function in order to cr eate the DNP configuration.

See Also

dn pSav eCI32Config

E l

S m

the dnpGetConfiguration function se

ction.

TelePACE C Tools User and Reference Manual

May 9, 2007

142

dnpGetConfiguration

Get DN P Configuration

S ynta x

#include <ctools.h>

BOOLEAN dnpGetConfiguration( dn pCon figuration * pConfiguratio

); n

Description

This function reads the DNP configuration.

The function has one parameter: a pointer to a DNP configuration str ucture.

The function returns TRUE if the configuration was read a nd FALSE if an error occurred.

See Also

dn pSav eConfiguration

Example

The following program demonstrates how to configure DNP for operation on c om2. To illustrate creation of points it uses a sequential mapping of Modbus registe rs to points. This is not required. Any mapping may be used. void main(void)

{

UINT16 struct prot_settings settings; dnpConfiguration configuration; dnpBinaryInput binaryInput; dnpBinaryOutput binaryOutput; dnpAnalogInput analogInput; dnpAnalogOutput analogOutput; dnpCounterInput counterInput;

/* protocol settings */

/* configuration settings */

/* binary input settings */

/* binary output settings */

/* analog input settings */

/* analog output settings */

/* counter input settings */

/* Stop any protocol currently active on com port 2 */

get_protocol(com2,&settings); settings.type = NO_PROTOCOL;

set_protocol(com2,&settings);

/* Load the Configuration Parameters */ configuration.masterAddress = DEFAULT_DNP_MASTER; configuration.rtuAddress = DEFAULT_DNP_RTU; configuration.datalinkConfirm = TRUE; configuration.datalinkRetries = DEFAULT_DLINK_RETRIES; configuration.datalinkTimeout = DEFAULT_DLINK_TIMEOUT; configuration.operateTimeout = DEFAULT_OPERATE_TIMEOUT; configuration.applicationConfirm = TRUE; configuration.maximumResponse = DEFAULT_MAX_RESP_LENGTH; configuration.applicationRetries = DEFAULT_APPL_RETRIES; configuration.applicationTimeout = DEFAULT_APPL_TIMEOUT; configuration.timeSynchronization = TIME_SYNC; configuration.BI_number = 8; configuration.BI_cosBufferSize = DEFAULT_COS_BUFF; configuration.BI_soeBufferSize = DEFAULT_SOE_BUFF; configuration.BO_number = 8; configuration.CI16_number = 24; configuration.CI16_bufferSize = 48; configuration.CI32_number = 12;

TelePACE C Tools User and Reference Manual

May 9, 2007

143

configuration.CI32_bufferSize = 24; configuration.AI16_numbe

configuration.AI16_repor

r = 24; tingMethod = CURRENT_VALUE; configuration.AI16_bufferSi

ze = 24; configuration.AI32_number configuration.AI32_reporting

= 12;

Method = CURRENT_VALUE; configuration.AI32_bufferSize = 12; co nfiguration.AO16_number = 8; co nfiguration.AO32_number = 8; configuration.unsolicited = TRUE; configuration.holdTime = DEFAULT_HOLD_TIME; configuration.holdCount = DEFAULT_HOLD_COUNT;

dnpSaveConfiguration(&configuration);

/* Start DNP protocol on com port 2 */

get_protocol(com2,&settings); settings.type = DNP;

set_protocol(com2,&settings);

/* Save port settings so DNP protocol will automatically start */

request_resource(IO_SYSTEM);

save(EEPROM_RUN);

release_resource(IO_SYSTEM);

/* Configure Binary Output Points */ for (index = 0; index < configuration.BO_number; index++)

{ binaryOutput.modbusAddress1 = 1 + index; binaryOutput.modbusAddress2 = 1 + index; binaryOutput.controlType = NOT_PAIRED;

}

/* Configure Binary Input Points */ for (index = 0;index < configuration.BI_number; index++)

{ binaryInput.modbusAddress = 10001 + index; binaryInput.class = CLASS_1; binaryInput.eventType = COS;

}

/* Configure 16 Bit Analog Input Points */ for (index = 0; index < configuration.AI16_number; index++)

{ analogInput.modbusAddress = 30001 + index; analogInput.class = CLASS_2; analogInput.deadband = 1;

}

/* Configure32 Bit Analog Input Points */ for (index = 0; index < configuration.AI32_number; index++)

{ analogInput.modbusAddress = 30001 + index * 2; analogInput.class = CLASS_2; analogInput.deadband = 1;

dnpSaveAI32Config(index,&analogInput);

}

/* Configure 16 Bit Analog Output Points */ for (index = 0;index < configuration.AO16_number; index++)

{ analogOutput.modbusAddress = 40001 + index;

}

TelePACE C Tools User and Reference Manual

May 9, 2007

144

/* Configure 32 Bit Analog Output Points */ for (index = 0; index < configuration.AO32_number; index++)

{ analogOutput.m

odbusAddress = 40101 + index * 2;

dnpSaveA

}

/* Configure 16 Bit Counter Input Points */ for (index = 0; index < co nfiguration.CI16_number; index++)

{ counterInput.modbusAddress = 3000 1 + index; counterInput.class = CLAS S_3; counterInput.threshold = 1;

}

/* Configure 32 bit Counter Input Points */ for (index = 0; index < configuration.CI32_number; index++)

{ counterInput.modbusAddress = 30001 + index * 2; counterInput.class = CLASS_3; counterInput.threshold = 1;

}

/* add additional initialization code for your application here ... */

/* loop forever */

{

/* add additional code for your application here ... */

/* allow other tasks of this priority to execute */

release_processor();

}

return;

}

TelePACE C Tools User and Reference Manual

May 9, 2007

145

dnpGetConfigurationEx

Read DNP Extended Configuration

Syntax

BOOLEAN dnpGetConfigurationEx (

);

Des cription

This function reads the extended DNP configuration parameters.

The function has one parameter: a pointer to the DNP extended configuration structure.

The function returns TRUE if the configuration was successfully read, or FALSE otherwise (if the poi nter is NULL, or if the DNP configuration has not been created).

Notes

DNP must be enabled before calling this function in order to create the DNP configuration.

This function supersedes the dnpGetConfiguration

function.

TelePACE C Tools User and Reference Manual

May 9, 2007

146

dnpGetRuntimeStatus

Get DNP Runtime Status

Syntax:

#include <ctools.h>

BOOLEAN dnpGetRuntimeStatus(

DNP_RUNTIME_STATUS *status

);

Description:

The dnpGetRun timeStatus function reads the current status of all DNP change event buffers, and returns information in the status structu re.

DNP must be enabled before calling this function in order to crea te the DNP configuration.

Example:

See the e

xample in the section dnpSendUnsolicited.

TelePACE C Tools User and Reference Manual

May 9, 2007

147

dnpReadRoutingTableDialStrings

Read DNP Routing Table Entry Dial Strings

Syntax

BOOLEAN dnpReadRoutin gTableDialStrings(

UINT16 index,

UINT16 maxPrimaryDialStringLength,

* primaryDialString,

UINT16 maxSecondaryDialStringLength,

);

Description

This function reads a primary and secondary dial string from an entry in the DNP routing table. i ndex

specifies the index of an entry in the DNP routing table. maxPrimaryDialStringLength

specifies the maximum length of primaryDialString excluding the null-terminator character. The function uses this to limit the size of the returned string to prevent overflowing the storage passed to the function. primaryDialString

returns the primary dial string of the target station. It must point to an array of size maxPrimaryDialStringLength. maxSecondaryDialStringLength

specifies the maximum length of secondaryDialString

excluding the null-terminator character. The function uses this to limit the size of the returned string to prevent overflowing the storage passed to the function. secondaryDialString

returns the secondary dial string of the target station. It must point to an array of size maxSecondaryDialStringLength.

Notes

This function must be used in conjunction with the dnpReadRoutingTableEntry function to read a complete entry in the DNP routing table.

TelePACE C Tools User and Reference Manual

May 9, 2007

148

dnpReadRoutingTableEntry

Read Routing Table entry

Syntax

#include <ctools.h>

BOOLEAN dnpReadRoutingTableE ntry (

); routingTable *pRoute

Description

This function reads an entry from the routing table.

pRoute is a pointer to a table entry; it is written by this function.

The return value is TRUE if pRoute was successfully written or FALSE otherwise.

Notes

DNP must be enabled before calling this function in order to create the DNP configuration.

The func tion returns the total number of entries in the DNP routing table.

TelePACE C Tools User and Reference Manual

May 9, 2007

149

dnpReadRoutingTableSize

Read Routing Table size

Syntax

#include <ctools.h>

UINT16 dnpReadRoutingTableSi ze (void);

Description

This function reads the total number of entries in the routing table.

Notes

DNP must be enabled before calling this function in order to create the DNP configuration.

The function returns the total number of entries in the routing table.

TelePACE C Tools User and Reference Manual

May 9, 2007

150

dnpSaveAI16Config

Save DNP 16-Bit Analog Input Configuration

Syntax

#include <ctools.h>

BOOLEAN dnpSaveAI16Config(

UINT16 point, dnpAnalogInput * pAnalogInput

);

Description

This function sets the configuration of a DNP 16-bit analog input point.

The function has two parameters: the point number; and a pointer to an analog input point configuratio n structure.

The function returns TRUE if the configuration was written. It returns FALSE if the point number is not valid, if the configuration is not valid, or if DNP configuration has not been created.

Notes

DNP must be enabled before calling this function in order to create the DNP configuration.

See Also

dnpGetAI16Config

Example

See example in the dnpGetConfiguration function section.

TelePACE C Tools User and Reference Manual

May 9, 2007

151

dnpSaveAI32Config

Save DNP 32-Bit Analog Input Configuration

Syntax

#include <ctools.h>

BOOLEAN dnpSaveAI32Config(

UINT32 point, dnpAnalogInput * pAnalogInput

);

Description

This function sets the configuration of a DNP 32-bit analog input point.

The function has two parameters: the point number; and a pointer to an analog input point configuration structure.

The function returns TRUE if the configuration was written. It returns FALSE if the point number is not valid, if the configuration is not valid, or if DNP configuration has not been created.

Notes

DNP must be enabled before calling this function in order to create the DNP configuration.

See Also

dnpGetAI32Config

Example

See example in the dnpGetConfiguration function section.

TelePACE C Tools User and Reference Manual

May 9, 2007

152

dnpSaveAISFConfig

Save Short Floating Point Analog Input Configuration

Syntax

#include <ctools.h>

BOOLEAN dnpSaveAISFConfig (

);

Description

This function sets the configuration of a DNP short floating point analog in put point.

The function has two parameters: the point number, and a pointer to a configuration structure.

The function returns TRUE if the configuration was successfully written, or FALSE otherw ise

(if the point number is not valid, or the configuration is not valid, or if the DNP configuratio n has not b een created).

Notes

DNP must be enabled before calling this function in order to create the DNP configuration.

TelePACE C Tools User and Reference Manual

May 9, 2007

153

dnpSaveAO16Config

Save DNP 16-Bit Analog Output Configuration

Syntax

#include <ctools.h>

BOOLEAN dnpSaveAO16Config(

UINT16 point, dnpAnalogOutput * pAnalogOutput

);

Description

This function sets the configuration of a DNP 16-bit analog output point.

The function has two parameters: the point number; and a pointer to an analog outpu t point configuratio n structure.

The function returns TRUE if the configuration was written. It returns FALSE if the point number is not valid, if the configuration is not valid, or if DNP configuration has not been created.

Notes

DNP must be enabled before calling this function in order to create the DNP c onfiguration.

Example

See example in the dnpGetConfiguration function section.

TelePACE C Tools User and Reference Manual

May 9, 2007

154

dnpSaveAO32Config

Save DNP 32-Bit Analog Output Config uration

Syntax

#include <ctools.h>

BOOLEAN dnpSaveAO32Config(

UINT32 point, dnpAnalogOutput * pAnalogOutput

);

Description

This function sets the configuration of a DNP 32-bit analog outpu t point.

The function has two parameters: the point number; and a pointer to an analog output poi nt configuration structure.

The function returns TRUE if the configuration was written. It returns FALSE if the point number is not valid, if the configuration is not valid, or if DNP configuration has not been created.

Notes

DNP must be enabled before calling this function in order to create the DNP configuration.

See Also

dnpGetAO32Config

Example

See example in the dnpGetConfiguration function section.

TelePACE C Tools User and Reference Manual

May 9, 2007

155

dnpSaveAOSFConfig

Save Short Floating Point Analog Outpu t Configuration

Syntax

#include <ctools.h>

BO OLEA N dnpSaveAOSFCon fig (

);

Description

This function sets the configuration of a DNP short floating point analog output point.

The function has two parameters: th e point number, and a pointer to a configuration structure.

The function returns TRUE if the configuration was successfully written, or FALSE otherwise

(if the point numbe r is not valid, or the configuration is not valid, or if the DNP configuration has not been created).

Notes

DNP must be enabled before calling this function in order to create the DNP

TelePACE C Tools User and Reference Manual

May 9, 2007

156

dnpSaveBIConfig

Save DNP Binary Input Configuration

Syntax

#include <ctools.h>

BOOLEAN dnpSaveBIConfig(

UINT16 point, dnpBinaryInput * pBinaryInput

);

Description

This function sets the configuration of a DNP binary input point.

The function has two parameters: the point number; and a pointer to a binary input point configuration structure.

The function returns TRUE if the configuration was written. It returns FALSE if the point number is not valid, if the configuration is not valid, or if DNP configuration has not been created.

Notes

DNP must be enabled before calling this function in order to create the DNP configuration.

Example

See example in the dnpGetConfiguration function section.

TelePACE C Tools User and Reference Manual

May 9, 2007

157

dnpSaveBIConfigEx

Write DNP Binary Input Extended Point

Syntax

BOOLEAN dnpSaveBIConfigEx(

UINT16 point,

);

Description

This function wri tes the configuration of an extended DNP Binary Input point.

The function has two parameters: the point number, and a pointer to an e xtended binary input point configuration structure.

The function returns TRU E if the configuration was successfully written. It returns FALSE if the point number is not valid, if the configuration is not valid, or if the DNP configuration h as not been created.

This func tion supersedes dnpSaveBIConfig.

TelePACE C Tools User and Reference Manual

May 9, 2007

158

dnpSaveBOConfig

Save DNP Binary Output Configuration

Syntax

#include <ctools.h>

BOOLEAN dnpSaveBOConfig(

UINT16 point, dnpBinaryOutput * pBinaryOutput

);

Description

This function sets the configuration of a DNP binary output point.

The function has two parameters: the point number; and a pointer to a binary output point configuration structure.

The function returns TRUE if the configuration was written. It returns FALSE if the point number is not valid, if the configuration is not valid, or if DNP configuration has not been created.

Notes

DNP must be enabled before calling this function in order to create the DNP configuration.

Example

See example in the dnpGetConfiguration function section.

TelePACE C Tools User and Reference Manual

May 9, 2007

159

dnpSaveCI16Config

Save DNP 16-Bit Counter Input Configuration

Syntax

#include <ctools.h>

BOOLEAN dnpSaveCI16Config(

UINT16 point, dnpCounte rInput * pCounterInput

);

Description

This function sets the configuration of a DNP 16-bit counter input point.

The function has two parameters: the point number; and a pointer to a counter input point configuration structure.

The function returns TRUE if the configuration was written. It returns FALSE if the point number is not valid, if the configuration is not valid, or if DNP configuration has not been created.

Notes

DNP must be enabled before calling this function in order to create the DNP configuration .

See Also

dnpGetCI16Config

Example

See example in the dnpGe tConfiguration function section.

TelePACE C Tools User and Reference Manual

May 9, 2007

160

Configuration

Syntax

ls.h>

BOOLEAN dnpSaveCI32Config(

UINT 32 point, dnpCounterIn put * pCounterInput

);

Descriptio n

This function sets the configuration of a DNP 32-bit counter in put point.

T he function has two parameters: the point number; and a pointer to a counter input point configuration structure.

The function returns TRUE if the configuration was written. It returns FALSE if the point number is not valid, if the configuration is not valid, or if DNP configuration has not been created.

Notes

DNP must be enabled before calling this function in order to create the DNP configuration.

See Also

dnpGetCI32Config

Example

See example in the dnpGetConfiguration function section.

TelePACE C Tools User and Reference Manual

May 9, 2007

161

dnpSaveConfiguration

Save DNP Configuration

Syntax

#include <ctools.h>

BOOLEAN dnpSaveConfiguration( dnpConfiguration * pConfiguration

);

Description

This function sets the DNP configuration.

The function has one parameter: a pointer to a DNP configuration structure.

The function returns TRUE if the configuration was updated and FALSE if an error occurred.

No changes are made to any parameters if an error occurs.

Notes

This function must be called before enabling DNP.

The following parameters cannot be changed if DNP is enabled. Th e function will not make any changes and will return FALSE if this is a ttempted. The protocol must be disabled in order to make a change involving these parameters.

• BI_number

• BI_cosBufferSize

• BI_soeBufferSize

• BO_number

• CI16_number

• CI16_bufferSize

• CI32_number

• CI32_bufferSize

• AI16_number

• AI16_reportingMethod

• AI16_bufferSize

• AI32_number

• AI32_reportingMethod

• AI32_bufferSize

• AO16_number

• AO32_number

The following parameters can be changed when DNP is enabled.

• masterAddress;

• rtuAddress;

• datalinkConfirm;

• datalinkRetries;

• datalinkTimeout;

• operateTimeout

• applicationConfirm

TelePACE C Tools User and Reference Manual

May 9, 2007

162

• maximumResponse

• applicationRetries

• applicationTi meout

• timeSynchroni zation

• unsolicited

• holdT ime

• holdCount

See Also

dnpGetConfiguration

Example

See example in the dnpGetConfiguration function section.

TelePACE C Tools User and Reference Manual

May 9, 2007

163

dnpSaveConfigurationEx

Write DNP Extended Configuration

Syntax

BOOLEAN dnpSaveConfigurationEx ( dnpConfigurationEx nEx

);

Description

This function writes the extended DNP configuration parameters.

The function has one parameter: a pointer to the DNP extended configuration structure.

The function returns TRUE if the configuration was successfully written, or FALSE otherwise

if the DNP configuration has not been created).

Notes

DNP mu is

This function supersedes the dnpSaveConfiguration function.

TelePACE C Tools User and Reference Manual

May 9, 2007

164

dnpSearc hRoutingTable

Search Rout in g Table

Synta x

#inclu de <ctools.h>

BOOLEA N dnpSearchRoutingTable (

); routingTable *pRou te

Descr iption

This fun ction searches the routing table for a spe cific DNP address.

pRoute is a pointer to a table entry; it is written b y this function.

The return value is TRUE if pRoute was successfully written or FALSE otherwise.

Notes

DNP mu st be enabled before calling this function in order to create the DNP configuration.

TelePACE C Tools User and Reference Manual

May 9, 2007

165

Send DNP U o

Synta x

#include <ctools.h>

UINT16 dnpSendUnsolicitedResponse(

); ponse’ message in

DNP pr c

clas sp ecifies the class(es) of event data to include in the me ssage.

• Allo d

#define CLASS0_FLAG 0x01 /* flag for enabling Class 0 Unso licited Responses

*/

#define CLASS1_FLAG 0x02 /* flag for enabling Class 1 Unsolicited Responses

*/

#define CLASS2_FLAG 0x04 /* flag for enabling Class 2 Unsolicited Responses

*/

#define CLASS3_FLAG 0x08 /* flag for enabling Class 3 Unsolicited Responses

*/

DNP mu st be enabled before calling this function in order to cr eate the DNP configuration.

Examp le

/* ----------------------------------------------------------------

SCADAPack 32 C++ Application Main Program

Copyright 2001 - 2002, Control Microsystems Inc.

Test application for new DNP API Functions.

writt en by James Wiles May 2003

Th is app was written for a ScadaPack 32P, runni ng DNP on comm port

4.

------------------------------------------------------------- */

#i nclude <ctools.h>

#include <string.h>

/ * - --------------------------------------------------------------

Constants

----------------------------------------------------------- */

/*

* Event Trigger s :

* This application detects when these registers have been set,

* then p erforms the specified action and clears the register.

*/

00 r all DNP Event Log Buffers */

#define GENERATE_BI_EVENT 10 channel 0 */

TelePACE C Tools User and Reference Manual

May 9, 2007

166

#define GENERATE_AI16_EVENT 102 bit AI channel 0 */

#define CLASS0_REPORT 103

0 data */

/*

* Status Flags

*/

#define EVENTS_CL ASS1 110 e ASS2 111

#define EVENTS_CLAS S3 112

/*

* Status Registers

*/

#d ef ne EVENT_COUNT_AI16 40102

#define EVENT_COUNT_BI 40104

#define EVENT_COUNT_CLASS1 40106

#define EVENT_COUNT_CLASS2 40108

#define EVENT_COUNT_CLASS3 40110

/* ------------------------------------------------------------------

main

This routine is the main application loop.

-------------------------------------------------------------- */ void main(void)

{ struct prot_settings protocolSettings; /* protocol settings */

i class0_report_flag;

/* Set DNP Configuration */ configuration.masterAddress = 100; configuration.rtuAddress = 1; configur ation.datalinkConfirm = FALSE; configuration.datalinkRetries = DEFAULT_DLINK_RETRIES; configuration.datalinkTimeout = DEFAUL T_DLINK_TIMEOUT; configuration.operateTimeout = DEFAULT_OPER ATE_TIMEOUT; configuration.applicationConfirm = FALSE; configur ation.maximumResponse = DEFAULT_MAX_RESP_LENGTH; configuration.applicationRetries = DEFAULT_APPL_RETRIES; configuration.applicationTimeout = DEFAULT_A PPL_TIMEOUT; configuration.timeSynchronization = NO_TIME_SYNC; configuration.BI_number = 2; configur ation.BI_startAddress = 0; configuration.BI_reportingMethod = REPORT_ALL_EVENTS; configuration.BI_soeBufferSize = 10 00; configuration.BO_number = 0; configuration.BO_startAddress = 0; configuration.CI16_number = 0; configur ation.CI16_startAddress = 0; configuration.CI16_reportingMethod = REPORT_ALL_EVENTS; co figuration.CI16_bufferSize = 0; configuration.CI32_number = 0; configuration.CI32_startAddress = 100;

TelePACE C Tools User and Reference Manual

May 9, 2007

167

configuration.CI32_reportingMethod = REPORT_ALL_EVENTS; configuration.CI32_bufferSize = 0; configuration.CI32_wordOrder = MSW_FIRST; configuration.AI16_number = 2; configuration.AI16_startAddres

s = 0; configur ation.AI16_reportingM

ethod = REPORT_ALL_EVENTS; configuration.AI16_bufferSize = 1000; configuration.AI32_number = 0; configuration.AI32_startA

ddress = 100; configuration.AI32_reportingMethod = REPOR T_ALL_EVENTS; configuration.AI32_bufferSize = 0; configur ation.AI32_wordOrder = MSW_F IRST; configuration.AISF_number = 0; configuration.AISF_startAddress = 200; configurat ion.AISF_reportin

gMethod = REPORT_CHANGE_EVENTS; configuration.AISF_bufferSi

ze = 0; configuration.AISF_wordOrder = MSW_FIR ST; configuration.AO16_number = 0; configur ation.AO16_startAddress = 0; configuration.AO32_number = 0; configuration.AO32_startAddress = 100; configuration.AO32_wordOrder = MSW_FIRST; configuration.AOSF_number = 0; configuration.AOSF_startAddress = 200; configur ation.AOSF_wordOrder = MSW_FIRST; co figuration.autoUnsolicitedClass1 = TRUE; configuration.holdTimeClass

1 = 10; confi guration.holdCountClas

s1 = 3; configuration.autoUnsolicitedClass2 = TRUE; configuration.holdTimeClass2 = 10; configuration.holdCountClass2 = 3; configuration.autoUnsolicitedClass3 = TRUE; configuration.holdTimeClass3 = 10; configuration.holdCountClass3 = 3;

dnpSaveConfiguration(&configuration);

/* Start DNP protocol on com port 4 */ protocolSettings.type = DNP;

/* Configure Binary Input Points */ for (index = 0;index < configuration.BI_number; index++)

{ binaryInput.modbusAddress = 10001 + index; binaryInput.eventClass = CLASS_1;

dnpSaveBIConfig(configuration.BI_startAddress index,

&binaryInput);

}

/* Configure 16 Bit Analog Input Points */ for (index = 0; index < configuration.AI16_number; index++)

{ analogInput.modbusAddress = 40002 + index * 2; analogInput.eventClass = CLASS_2; analogInput.deadband = 1;

dnpSaveAI16Config(configuration.AI16_startAddress index,

&analogInput);

}

/*

* Configure DNP Routing Table :

* station 100 via com4

* station 101 via com4

TelePACE C Tools User and Reference Manual

May 9, 2007

168

*/

dnpCreateRoutingTable(2); dnpWriteRoutingTableEntry(0, 100, CIF_Com4, DEFAULT_DLINK_RETRIES,

DEFAULT_DLINK_TIMEOUT); dnpWriteRoutingTabl eEntry(1, 101, CIF_Com4, DEFAULT_DLINK_RETRIES,

DEFAULT_DLINK_TIMEOUT);

/*

* main loop

*/

{

/* request IO resource */ request_resource(IO_SYSTEM);

/* read DNP status */

dnpGetRuntimeStatus(&dnpS tatus); setdbase(MODBUS, EVENTS_CLASS1, dnpStatus.eventCountClass1 ? 1

: 0); setdbase(MODBUS, EVENTS_CLASS2, dnpStatus.eventCountClass2 ? 1

: 0); s etdbas e(MODBUS, EVENTS_CLASS3, dnpStatus .eventCountClass3 ? 1

: 0);

EVENT_COUNT_AI16, tus.eventCountAI16);

EVENT_COUNT_BI, s.eventCountBI); dnpStatus.eventCountClass1); dnpStatus.eventCountClass2); dnpStatus.eventCountClass3);

release_resource(IO_SYSTEM);

clear_events_flag FALSE;

bi_event_flag

ai16_event_flag

class0_report_flag FALSE;

/* Read Event Triggers */

{

clear_events_flag TRUE;

}

{

bi_event_flag FALSE;

}

{

ai16_event_flag FALSE;

}

{

class0_report_flag FALSE;

}

/* release IO resource */

release_resource(IO_SYSTEM);

TelePACE C Tools User and Reference Manual

May 9, 2007

169

/* Clear DNP Event Lo g buffer if requested */

if )

{

dnpCl earEventLog();

}

/* Generate a DNP Change Event for BI Point 0 if requested */

if nt_flag)

{

dnpGenerateEventLog(BI_P

}

/* Generate a DNP Cha nge Event for 16-bit AI Point 0 if requested */

{

}

/* Send DNP Class 0 Unsolicited Report if requested */

{

dnpSendUnsolicitedResponse(CLASS0_FLAG);

}

/* release processor to other tasks */

release_processor();

}

}

TelePACE C Tools User and Reference Manual

May 9, 2007

170

dnpSendUnsolicitedResponse

Send DNP Unsolicited Response

Syntax

BOOLEAN dnpSendUnsolicitedResponse(

);

Description

The dnpSendUnsolicitedResponse

function se nds an Unsolicited Response message in DN P, with data from the specified classes. class

specifies the class or classes of event data to include in the message. It can contain any combination of the following values; if multiple values are used they should be ORed together:

CLASS 0_FLAG

CLASS1_FLAG enables Class 0 Unsolicited Responses enables Class 1 Unsolicited Responses

CLASS2_FLAG

CLASS3_FLAG enables Class 2 Unsolicited Responses enables Class 3 Unsolicited Responses

The function returns TRUE if the D NP unsolicited response message was successfully triggered. It returns FALSE if an unsolicited message of the same class is already pending, or if the DNP configuration has not been created.

Notes

DNP must be enabled before calling this function in order to create the DNP configuration.

If no eve nts are pending an empty unsolicited message will be sent.

TelePACE C Tools User and Reference Manual

May 9, 2007

171

dnpWriteRoutingTableEntry

Write Routing Table E ntry

Syntax

#include <ctools.h>

BOOLEAN dnpWriteRoutingTableEntry (

UINT16 dnpAddress,

UINT16 nkTimeout

);

Description

This func tion writes an entry in the DNP routing table.

Notes

DNP must be enabled before calling this function in order to create the DNP configuration.

The function returns TRUE if successful, FALSE otherwise.

Example

See the example in the section dnpSendUnsolicited.

TelePACE C Tools User and Reference Manual

May 9, 2007

172

dnpWriteRoutingTableDialStrings

Write DNP Routing Table Entry Di al Strings

Syntax

BOOLEAN dnpWriteRoutingTab leDialStrings(

UINT16 index,

UINT16 primaryDialStringLength,

* primaryDialString,

UINT16 secondaryDialStringLength,

);

Description

This function writes a primary and secondary dial string into an entry in the DNP routing table. index

speci fies the index of an entry in the DNP routing table. primaryDialStringLe ngth specifies the length of primaryDialString excluding the null-terminator character. primaryDialString

specifies the dial string used when dialing the target station. This string is used on the first attempt. secondaryDialStringLength

specifies the length of secondaryDialString excluding the null-terminator character. secondaryDialString

specifies the dial string to be used when dialing the target station.

It is used for the next attempt if the first attempt fails.

Notes

This function must be used in conjunction with the dnpWriteRoutingTableEntry function to write a complete entry in the DNP routing table.

TelePACE C Tools User and Reference Manual

May 9, 2007

173

dout

Write Digital Outputs

Syntax

#include <ctools.h> int dout(unsigned channel, unsigne d value);

Description

The dout function outputs value to the digital input or output specified by channel. It sets the status of 8 digital points.

The dout function retu rns the value output to the channel, as modified by the channel configuration tables. If channel is not valid, –1 is returned.

Notes

T he dout function modifies all 8 bits (points) in a channel. Use the turnon and turnoff functions to write to single bits.

Use offsets from the symbolic constants DIN_START, DIN_END, EXTENDED_DIN_START,

EXTENDED_DIN_END, DOUT_START, DOUT_END, EXTENDED_DOUT_START and

EXTENDED_DOUT_END to reference digital channels. The constants make programs more portable and protect against future changes to the digital I/O channel numbering.

The IO_SYSTEM resource must be requested before calling this function.

This function is provided for backward compatibility. It cannot access all 5000 series I/O modules. It is recommended that this function not be used in new programs. Instead use

Register Assignment or call the I/O driver ioWrite8Dout directly.

See Also

ioWrite8Dout, din, pulse, timeout, turnon, turnoff, on, off

Example

This program sends all bit combinations to the second digital output channel.

#include <ctools.h> void main(void)

{ unsigned value; /* output values */ for (value = 0; value; value++)

{ request_resource(IO_SYSTEM); dout(DOUT_START + 1, value); release_resource(IO_SYSTEM);

}

}

TelePACE C Tools User and Reference Manual

May 9, 2007

174

end_application

Terminates all Application Tasks

Syntax

#include <ctools.h> void end_application(void);

Description

The end_application function terminates all APPLICATION type tasks created with the

create_task function. Stac k space and resources used by the tasks are freed.

Notes

This function is used normally by communication protocols to stop an executing applicatio n program , prior to loading a new program into memory.

See Als o

create_task, end_task

TelePACE C Tools User and Reference Manual

May 9, 2007

175

end_task

Termi nate a Task

Syntax

#include <ctools.h> void end_task(unsigned task_ID);

D ip

Th e end_task function terminates the task specified by task_ID. Stack space and resources used by the task are freed. The end_task function terminat es both APPLICATION and

SYSTEM t ype ta sks.

See Also

create_task, en

d_application, getTaskInfo

TelePACE C Tools User and Reference Manual

May 9, 2007

176

endTimedEvent

Termin la

Syntax

# include <ctools.h> u nsigned endTimedEvent( unsi gned event);

Description

T his endTimedEvent function cancels signaling of a timed event, initialized by the startTimedEvent function.

The function returns TRUE if the event signaling was canceled.

The function returns FALSE if the event number is not valid, or if the event was not previously initiated with the startTimedEvent function. The function has no effect in these cases.

Notes

Valid events are numbered 0 to RTOS_EVENTS - 1. Any events defined in ctools.h are not va lid events for use in an ap plication program.

Example

See the examples for startTimed Event.

See Also

startTimedEvent

TelePACE C Tools User and Reference Manual

May 9, 2007

177

enro nInstallCommandHandler

Installs handler for Enron Modbus com mands.

Syntax

#include <ctools.h> v oid enronInstallCommandHandler (

UINT16 (* function)(

UINT16 length,

UCHAR * pComma nd,

UINT16 responseSize,

UCHAR * pResponse

)

);

D p

This function installs a handler function for Enron Modbus co mmands. The protocol driver calls this handler function each time a command is received for the Enron Modbus station. fun ction

is a pointer to the handle r function. If function is NULL the handler is disabled.

The function has no return value.

Notes

The application must disable the hand ler when the application ends. This prevents the pro tocol driver from calling the handl er while the application is stopped. Call the enronInstallCommmandHandler

with a NULL pointer. Th e usual method is to create a task exit handler function to do this. See the example below fo r details.

The handler function has five parameters.

• length

is the num ber of characters in the command message.

• pCommand

is a pointer to the comman d message. The first byte in the message is the func tion code, followed by the Enron Modbus message. See the Enron Modb us protocol spe cification for details on the message f ormats.

• responseSize is the size of the response buffer in characters.

• pRe sponseLength

is a pointer to a variable that will hold the number of characters in the response. If the handler returns TRUE, it must set this variable.

• pRe sponse

is a pointer to a buffer that will hold th e response message. The buffer size is responseSize characters . The handler must not write beyond the end of the buffer.

If the handler r eturns TRUE, it must set this variable. The data must start with the func tio n cod e and end with the last data byte. The protoc ol driver will add the station address, chec ksum, and message framing to the response.

The handler function returns the following values.

Value

NORMAL

ILLEGAL_FUNCTION

Description

Indicates protocol handler should send a normal response message. Data are returned using pResponse

and pResponseLength.

Indicates protocol handler should send an Illegal

Function exception response message. This

TelePACE C Tools User and Reference Manual

May 9, 2007

178

Value Description

response should be used when the function code in the command is not recognised.

ILLEGAL_DATA_ADDRESS

Indicates protocol handler should send an Illegal

Data Address exception response message. This response should be used when the data address

ILLEGAL_DATA_VALUE in the command is not recognised.

Indic ates protocol handler should send an Illegal

Data Value exception response message. This response should be used when invalid data is found in the command.

If the function returns NORMAL then the protocol driver sends the response message in the buffer pointed to by pResponse. If the function returns an exception response protocol driver ret urns the exception response to the caller. The buffer pointed to by pResponse is not used.

Example

This program installs a simple handler function.

#include <ctools.h>

/* -----------------------------------------------------

This function processes Enron Modbus commands.

----------------------------------------------------- */

UINT16 commandHandler(

UINT16 length,

UCHAR * pCommand,

UINT16 responseSize,

UINT16 * pResponseLength,

UCHAR * pResponse

)

{

/* if a command byte was received */ if (length >= 1)

{

/* get the command byte */

{

/* read unit status command */

/* if the response buffer is large enough */

{

/* build the response header */

/* set the unit status */

TelePACE C Tools User and Reference Manual

May 9, 2007

179

/* indicate the command worked */ result

}

else

{

/* buffer is to small to respond */

}

break;

/* add cases f or other commands here */ default:

/* command is invalid */

}

}

else

{

/* command is too short so return error */

result

}

}

/* -----------------------------------------------------

This function unhooks the protocol handler when the

mai n task ends.

----------------------------------------------------- */ void m n

{

/* unhook the handler function */

enronInstallCommandHandler(NULL);

} v oid m ain (void)

{

/* install handler to execute when this task ends */ thisTask = getTaskInfo(0);

/* install handler for Enron Modbus */

enronInstallCommandHandler(commandHandler);

/* infinite loop of main task */

{

/* add application code here */

}

}

TelePACE C Tools User and Reference Manual

May 9, 2007

180

forceLed

Set State of Force LED

Syntax

#include <ctools.h> void forceLed(unsigned state);

Description

The forceLed function sets the state of the FORCE LED. state may be either LED_ON or

LED_OFF.

The FORCE LED is used to indicate forced I/O. Use this function with caution in application programs.

See Also

set Statu s

TelePACE C Tools User and Reference Manual

May 9, 2007

181

getABConfiguration

Get DF1 Protocol Configur ation

Syntax

#include <ctools.h> struct ABConfiguration *getABC onfiguration(FILE *stream, struct

ABConfiguration *ABConfig);

Description

The getABConfiguration function gets the DF1 protocol configuration parameters for the

stream. If stream does not point to a valid serial port the function has no effect. ABConfig must point to an DF1 protocol configuration structure.

The getA BConfiguration function copies the DF1 configuration parameters into the

ABConfig structure and returns a pointer to it.

Example

This program displays the DF1 configuration parameters for com1.

#inc lude <ctools.h> void main(void)

{ struct ABConfiguration ABConfig;

getABConfiguration(com1, fig); printf("Min protected address: %u\r\n",

ABConfi g.min_protected_address); pr intf("Max protected address: %u\r\n",

ABConfig.max

_protected_address);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

182

getBootType

Get Controller Boot Up State

Syntax

#include <ctools.h> unsigned getBootType(void);

Description

The getBootType function returns the boot up state of the controller. The possible return values are:

SERVICE

RUN controller started in SERVICE mode controller started in RUN mode

Example

#include <c tools.h> void main(void)

{ struct prot_settings settings;

/* Disable the protocol on serial port 1 */ settings.type = NO_PROTOCOL; settings.station = 1; settings.priority = 3; settings.SFMessaging = FALSE;

request_resource(IO_SYSTEM);

release_resource(IO_SYSTEM);

}

/* Display the boot status information */ printf("Boot type: %d\r\n", getBootType());

TelePACE C Tools User and Reference Manual

May 9, 2007

183

getclock

Read the Real Time Clock

Syntax

#include <rtc.h> struct clock getclock(void);

Description

The getclock function reads the time and date from the real time clock hardware.

The getclock function returns a struct clock containing the time and date information.

Notes

The time format returned by the ge tclock function is not compatible with the standard UNIX style functions supplied by Microte c.

The IO_S YSTEM resource must be requested before calling this function.

See Also

setclock, ge tClockTime

Example

This program displays the current date and time.

#include <ctools.h> main(void)

{ struct clock now;

request_resource(IO_SYSTEM); now = getclock(); /* read the clock */

release_resource(IO_SYSTEM); printf("%2d/%2d/%2d", now.day,

} printf("%2d:%2d\r\n",now.hour, now.minute);

TelePACE C Tools User and Reference Manual

May 9, 2007

184

getClockAlarm

Read the Real Time Clock Alarm Settings

Syntax

#include <ctools.h>

ALARM_SETTING getClockAlarm(void);

Description

The getClockAlarm function returns the alarm setting in the real time clock. The alarm is used to wake the controller from sleep mode.

Notes

The IO_SYS TEM resource must be requested before calling this function.

See Also

alarmIn, setClockA larm

TelePACE C Tools User and Reference Manual

May 9, 2007

185

getClockTime

Read the Real Time Clock

Syntax

#include <ctools.h> void getClockTime(long * pDays, long * pHundredths);

Description

The getClockTime function reads the read time clock and returns the value as the numbe r of whole days since 01/01/97 and the number of hundredths of a second since the start of the current day. The function wo rks for 100 years from 01/01/97 to 12/31/96 then rolls over.

The function has two parameters: a pointer to the variable to hold the days; and a po inter to a variable to hold the hundredths of a second.

The function has no return value.

Notes

The IO_SYSTEM resource must be requested before calling this function.

See Also

s etclock,

getc lock

TelePACE C Tools User and Reference Manual

May 9, 2007

186

getControllerID

Get Controller ID

Syntax

#include <ctools.h> void getControllerID(CHAR * pID)

Description

This function writes the Controller ID to the string pointed to by pID. The Controller ID is a unique ID for the controller set at the factory. The pointer pID must point to a characte r string of length CONTROLLER_ID_LEN.

Example

This prog ram displays the Controller ID.

#include <ctools.h> void main(void)

{ char ctlrID[CONTROLLER_ID_LEN];

UINT16 getControllerID(ctlrID); fprintf(com1, "\r\nController ID : "); for (index=0; index<CONTROLLER_ID_LEN; index++)

{

}

}

TelePACE C Tools User and Reference Manual

May 9, 2007

187

getForceFlag

Get Force Flag State for a Register

Syntax

#include <ctools.h> unsigned getForceFlag(unsigned type, unsigned address, unsigned *value);

Description

The getForceFl ag function copies the value of the force flag for the specified database register into the integer pointed to by value. The valid range for address is determined by the database addressing type.

The force flag value is either 1 or 0, or a 16-bit mask for LINEAR digital addresses.

If the address or addressing type is not valid, FALSE is returned and the integer pointed to by value is 0; otherwise TRUE is returned. The table below shows the valid address types and ranges.

Type Address Ranges

MODBUS 00001 to NUMCOIL

10001 to 10000 + NUM STATUS

30001 to 30000 + NUMINPUT

40001 to 40000 + NUMHOLDING

LINEAR 0 to NUMLINEAR-1

Register

Size

1 bit

1 bit

16 bit

16 bit

16 bit

Notes

Force Flags are not modified when the controller is reset. Force Flags are in a permanent storage area, which is maintained during power outages .

Refer to the I/O Database and Register Assignment chapter for more information.

See Also

setForceFlag, clearAllForcing, overrideDbase

Example

This program obtains the force flag state for register 40001, for the 16 status registers at linear address 302 (i.e. registers 10737 to 10752), and for the holding register at linear address 1540 (i.e. register 40005).

#include <ctools.h> void main(void)

{ unsigned flag, bitmask; getForceFlag(MODBUS, 40001, &flag); getForceFlag(LINEAR, 302, &bitmask); getForceFlag(LINEAR, 1540, &flag);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

188

getIOErrorIndication

Get I/O Module Error Indication

Syntax

#include <ctools.h> unsigned getIOErrorIndication(void);

Description

The getIOErrorIndication function returns the state of the I/O module error indication.

TRUE is returned if the I/O module communication status is currently reported in the controller status register and Status LED. FALSE is returned if the I/O module communication status is not reported.

Notes

Refer to the 5203/4 System Manual or the SCADAPack System Manual for further informatio n on the Status LED and Status Output.

See Also

setIOErrorIndication

TelePACE C Tools User and Reference Manual

May 9, 2007

189

getOutputsInStopMode

Get Outputs In Stop Mode

Syntax

#include <ctools.h> void getOutputsInStopMode( unsigned *doutsInStopMode, unsigned

*aoutsInStopMode);

Description

The getOutputsInStopMode function copies the values of the output control flags into the integers pointed to by doutsInStopMode and aoutsInStopMode.

If the value pointed to by do utsInStopMode is TRUE, then digital outputs are held at their last state when the Ladder Logic program is stopped.

If the value pointed to by doutsInStop Mode is FALSE, then digital outputs are tu rned OFF w hen the Ladder Lo gic program is st opped.

If the value pointed to by aoutsInStop Mode is TRUE, then analog ou tputs are held at their la st value when the Ladder Logic pro gram is stopped.

If the value pointed to by aoutsIn

Stop

Mode is FALSE, then analog outputs go to zero when th e Ladder Logic program is stop ped .

S ee Also

s etOutputsInStopMode

Example

See the example for setOutputsInStopMode function.

TelePACE C Tools User and Reference Manual

May 9, 2007

190

getPortCharacteristics

Get Serial Port Ch aracteristics

Syntax

#include <ctools.h> unsigned getPortCharacteristics(FILE *stream, PORT_CHARACTERISTICS

*pCharacteristics);

Description

The getPortCharacteristics function gets information about features supported by the serial port pointed to by stream. If stream does not point to a valid serial port the function has no effect and FALSE is returned; otherwise TRUE is returned.

The getP ortCharacteristics function copies the serial port characteristics into the structure pointed to by pCharacteristics.

Notes

Refer to the Overview of Functions section for detailed information on serial ports.

Refer to the Structures and Types section for a description of the fields in the

PORT_CHARACTERISTICS structure.

See Also

get_port

}

Example

#include <ctools.h> void main(void)

{ fprintf(com1, "Dataflow options: %d\r\n", options.dataflow); fprintf(com1, "Protocol options: %d\r\n", options.protocol);

TelePACE C Tools User and Reference Manual

May 9, 2007

191

getPowerMode

Get Cu rrent Power Mode

Syntax

#include <ctools.h>

BOOLEAN getPowerMode(UCHAR* cpuPower, UCHAR* lan, UCHAR* usbPeriphe ral,

UCHAR* usbHost);

Description

The getPowerMode function places the current state of the CPU, LAN, USB peripheral port, and USB host port in the passed parameters. The following table lists the possible return values and their meaning.

Macro Meaning

PM_CPU_FULL

The CPU is set to run at full speed

PM_CPU_REDUCED The CPU is set to run at a reduced speed

PM_CPU_SLEEP

PM_LAN_ENABLED

The CPU is set to sleep mode

The LAN is enabled

PM_LAN_DISABLED

PM_USB_PERIPHERAL_ENABLED

The LAN is disabled

The USB peripheral port is enabled

PM_USB_PERIPHERAL_DISABLED

PM_USB_HOST_ENABLED

The USB peripheral port is disabled

The USB host port is enabled

PM_USB_HOST_DISABLED

PM_UNAVAILABLE

The USB host port is disabled

The status of the device could not be read.

TRUE is returned if the v alues placed in the passed parameters are valid, otherwise FALSE is returned.

The application prog ram may set the current power mode with the setPowerMode function.

See Also

se tPow erMode, setWakeSource, getWakeSource

TelePACE C Tools User and Reference Manual

May 9, 2007

192

get_pid

Get PID Variable

Syntax

#include <ctools.h> int get_pid(unsigned name, unsigned block);

Description

The get_pid function returns the value of a PID control block variable. name must be specified by one of the variable name macros in pid.h. block must be in the range 0 to

PID_BLOCKS-1.

Notes

See the Tele PACE PID Controllers Manual for a detailed description of PID control.

Values stored in P ID blocks are not initialized when a program is run, and are guaranteed to retain their values during power failures and program loading. The user program must always initialize PID bloc k variables.

The IO_SYSTEM resource must be r equested before calling this function.

See Also

set_pid, aut

o_pid, clear_pid

TelePACE C Tools User and Reference Manual

May 9, 2007

193

get_port

Get Serial Port Configuration

Syntax

#include <ctools.h> struct pconfig *get_port(FILE *stream, struct pconfig *settings);

Description

The get_port function gets the serial port configuration for the stream. If stream does not point to a valid serial port the function has no effect.

The get_port function copies the serial port settings into the structure pointed to by settings and returns a pointer to the structure.

Notes

Refer to the Overview of Functions section for detailed information on serial ports.

Refer to the Structure and Types section for a description of the fields in the pconfig structure.

See Also

set_port

Example

#include <ctools.h> void main(void)

{ struct pconfig settings;

} printf("Baud rate: %d\r\n", settings.baud); printf("Duplex: %d\r\n", settings.duplex);

TelePACE C Tools User and Reference Manual

May 9, 2007

194

getProgramStatus

Get Program Status Flag

Syntax

#include <ctools.h> unsigned getProgramStatus( void );

Description

The getProgramStatus function returns the application program status flag. The status flag is set to NEW_PROGRAM when the C program is erased or downloaded to the controller from the program loader.

The application program may modify the status flag with the setProgramStatus function.

See Also

setPowerMode

Set Current Power Mode

Syntax

#include <ctools.h>

BOOLEAN setPowerMode(UCHAR cpuPower, UCHAR lan, UCHAR usbPeripheral, UCHAR usbHost);

Description

The setPowerMode function returns TRUE if the new settings were successfully applied.

The setPowerMode function allows for power savings to be realized by controlling the power to the LAN port, changing the clock speed, and individually controlling the host and peripheral USB power. The following table of macros summarizes the choices available.

Macro Meaning

PM_CPU_FULL

PM_CPU_REDUCED

The CPU is set to run at full speed

The CPU is set to run at a reduced speed

PM_CPU_SLEEP

PM_LAN_ENABLED

PM_LAN_DISABLED

The CPU is set to sleep mode

The LAN is enabled

The LAN is disabled

PM_USB_PERIPHERAL_ENABLED

PM_USB_PERIPHERAL_DISABLED

The USB peripheral port is enabled

The USB peripheral port is disabled

PM_USB_HOST_ENABLED

PM_USB_HOST_DISABLED

The USB host port is enabled

The USB host port is disabled

PM_NO_CHANGE

The current value will be used

TRUE is returned if the requested change was made, otherwise FALSE is returned.

The application program may view the current power mode with the getPowerMode function.

See Also

getPowerMode, setWakeSource, getWakeSource

TelePACE C Tools User and Reference Manual

May 9, 2007

195

setProgramStatus

Example

This program stores a default alarm limit into the I/O database the first time it is run. On subsequent executions, it uses the limit in the database. The limit in the database can be modified by a communication protocol during execution.

#include <ctools.h>

#define HI_ALARM 41000

#define ALARM_OUTPUT 1026 void main( void )

{ if (getProgramStatus() == NEW_PROGRAM)

{

/* Set default alarm limit */ request_resource(IO_SYSTEM); setdbase(MODBUS, HI_ALARM, 4000); release_resource(IO_SYSTEM);

/* Use values in database from now on */ setProgramStatus(PROGRAM_EXECUTED);

}

{ request_resource(IO_SYSTEM);

/* Test input against alarm limits */ if (ain(INPUT) > dbase(MODBUS, HI_ALARM)) else release_resource(IO_SYSTEM);

/* Allow other tasks to execute */ release_processor();

}

}

TelePACE C Tools User and Reference Manual

May 9, 2007

196

get_protocol

Get Protocol Configuration

Syntax

#include <ctools.h> struct prot_settings *get_protocol(FILE *stream, struct prot_settings

*settings);

Description

The get_protocol function gets the communication protocol configuration for the stream. If

stream does not point to a valid serial port the function has no effect. settings must point to a protocol configuration structure, prot_settings.

The get_protocol function copies the protocol settings into the structure pointed to by

settings and returns a pointer to that structure.

Refer to the ctools.h file for a description of the fields in the prot_settings structure.

Refer to the Overview of Functions section for detailed information on communication protocols.

See Also

set_protocol

}

Example

This program displays the protocol configuration for com1.

#include <ctools.h> void main(void)

{ struct prot_settings settings; printf("Type: %d\r\n", settings.type); printf("Station: %d\r\n", settings.station); printf("Priority: %d\r\n", settings.priority);

TelePACE C Tools User and Reference Manual

May 9, 2007

197

getProtocolSettings

Get Protocol Extended Addressing Configuration

Syntax

#include <ctools.h>

BOOLEAN getProtocolSettings(

FILE * stream,

PROTOCOL_SETTINGS * settings

);

Description

The getProtocolSettings function reads the protocol parameters for a serial port. This function supports extended addressing.

The function has two parameters: stream is one of com1, com2, com3 or com4; and

settings, a pointer to a PROTOCOL_SETTINGS structure. Refer to the description of the structure for an explanation of the parameters.

The function returns TRUE if the structure was changed. It returns FALSE if the stream is not valid.

Notes

Extended addressing is available on the Modbus RTU and Modbus ASCII protocols only.

See the TeleBUS Protocols User Manual for details.

Refer to the TeleBUS Protocols User Manual section for detailed information on communication protocols.

See Also

setProtocolSettings, get_protocol

Example

This program displays the protocol configuration for com1.

#include <ctools.h> void main(void)

{ if (getProtocolSettings(com1, &settings)

{ printf("Type: %d\r\n", settings.type); printf("Station: %d\r\n", settings.station); printf("Address Mode: %d\r\n", settings.mode); printf("SF Messaging: %d\r\n", settings.SFMessaging); printf("Priority: %d\r\n", settings.priority);

}

else

{ printf(“Serial port is not valid\r\n”);

}

}

TelePACE C Tools User and Reference Manual

May 9, 2007

198

getProtocolSettingsEx

Reads extended protocol settings for a serial port.

Syntax

#include <ctools.h>

BOOLEAN getProtocolSettingsEx(

FILE * stream,

PROTOCOL_SETTINGS_EX * pSettings

);

Description

The setProtocolSettingsEx function sets protocol parameters for a serial port. This function supports extended addressing and Enron Modbus parameters.

The function has two arguments:

• stream specifies the serial port. It is one of com1, com2, com3 or com4.

• pSettings is a pointer to a PROTOCOL_SETTINGS_EX structure. Refer to the description of the structure for an explanation of the parameters.

The function returns TRUE if the settings were retrieved. It returns FALSE if the stream is not valid.

Notes

Extended addressing and the Enron Modbus station are available on the Modbus RTU and

Modbus ASCII protocols only. See the TeleBUS Protocols User Manual for details.

See Also

setProtocolSettingsEx

Example

This program displays the protocol configuration for com1.

#include <ctools.h> void main(void)

{ if (getProtocolSettingsEx(com1, &settings)

{ printf("Address Mode: %d\r\n", settings.mode);

settings.enronStation);

}

else

{ printf(“Serial port is not valid\r\n”);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

199

}

TelePACE C Tools User and Reference Manual

May 9, 2007

200

get_protocol_status

Get Protocol Information

Syntax

#include <ctools.h> struct prot_status get_protocol_status(FILE *stream);

Description

The get_protocol_status function returns the protocol error and message counters for

stream. If stream does not point to a valid serial port the function has no effect.

Refer to the Overview of Functions section for detailed information on communication protocols.

See Also

clear_protocol_status

Example

This program displays the checksum error counter for com2.

#include <ctools.h> void main(void)

{ struct prot_status status; status = get_protocol_status(com2); status.checksum_errors);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

201

getSFMapping

Read Translation Table Mapping Control

Syntax

#include <ctools.h> unsigned getSFMapping(void);

Description

The getSFMapping and setSFMapping functions no longer perform any useful function but are maintained as stubs for backward compatibility. Include the CNFG_StoreAndForward module in the Register Assignment to assign a store and forward table to the I/O database.

Notes

The TeleBUS Protocols User Manual describes store and forward messaging mode.

See Also

addRegAssignment

TelePACE C Tools User and Reference Manual

May 9, 2007

202

getSFTranslation

Read Store and Forward Translation

Syntax

#include <ctools.h> struct SFTranslation getSFTranslation(unsigned index);

Description

The getSFTranslation function returns the entry at index in the store and forward address translation table. If index is invalid, a disabled table entry is returned.

The function returns a SFTranslation structure. It is described in the Structures and Types section.

Notes

The TeleBUS Protocols User Manual describes store and forward messaging mode.

See Also

setSFTranslation, clearSFTranslationTable, checkSFTranslationTable

Example

See the example for the setSFTranslation function.

TelePACE C Tools User and Reference Manual

May 9, 2007

203

get_status

Get Serial Port Status

Syntax

#include <ctools.h> struct pstatus *get_status(FILE *stream, struct pstatus *status);

Description

The get_status function returns serial port error counters, I/O lines status and I/O driver buffer information for stream. If stream does not point to a valid serial port the function has no effect. status must point to a valid serial port status structure, pstatus.

The get_status function copies the serial port status into the structure pointed to by status and returns a pointer to that structure settings.

Refer to the Overview of Functions section for detailed information on serial ports.

See Also

clear_errors

Example

This program displays the framing and parity errors for com1.

#include <ctools.h> void main(void)

{ struct pstatus status;

} printf("Framing: %d\r\n", status.framing); printf("Parity: %d\r\n", status.parity);

TelePACE C Tools User and Reference Manual

May 9, 2007

204

getStatusBit

Read Bits in Controller Status Code

Syntax

#include <ctools.h> unsigned getStatusBit(unsigned bitMask);

Description

The getStatusBit function returns the values of the bits indicated by bitMask in the controller status code.

See Also

setStatusBit, setStatus, clearStatusBit

TelePACE C Tools User and Reference Manual

May 9, 2007

205

getTaskInfo

Get Information on a Task

Syntax

#include <ctools.h>

TASKINFO getTaskInfo(unsigned taskID);

Description

The getTaskInfo function returns information about the task specified by taskID. If taskID is

0 the function returns information about the current task.

Notes

If the specified task ID does not identify a valid task, all fields in the return data are set to zero. The calling function should check the taskID field in the TASKINFO structure: if it is zero the remaining information is not valid.

Refer to the Structures and Types section for a description of the fields in the TASKINFO structure.

Example

The following program displays information about all valid tasks.

#include <string.h>

#include <ctools.h> void main(void)

{ struct prot_settings settings;

/* Set up state strings */ strcpy(state[TS_WAIT_ENVELOPE], "Waiting for Envelope"); strcpy(state[TS_WAIT_EVENT], "Waiting for Event"); strcpy(state[TS_WAIT_MESSAGE], "Waiting for Message"); strcpy(state[TS_WAIT_RESOURCE], "Waiting for Resource");

/* Set up type strings */

/* Disable the protocol on serial port 1 */ settings.type = NO_PROTOCOL; settings.station = 1; settings.priority = 3; settings.SFMessaging = FALSE;

request_resource(IO_SYSTEM);

release_resource(IO_SYSTEM);

/* display information about all tasks */ for (task = 0; task <= RTOS_TASKS; task++)

{ taskStatus = getTaskInfo(task); if (taskStatus.taskID != 0)

{

/* show information for valid task */

TelePACE C Tools User and Reference Manual

May 9, 2007

206

fprintf(com1, "\r\n\r\nInformation about task %d:\r\n", task); fprintf(com1, " Task ID: %d\r\n", taskStatus.taskID); fprintf(com1, " Priority: %d\r\n", taskStatus.priority); fprintf(com1, " Status: %s\r\n", state[taskStatus.status]); if (taskStatus.status == TS_WAIT_EVENT)

{ fprintf(com1, " Event: %d\r\n", taskStatus.requirement);

} if (taskStatus.status == TS_WAIT_RESOURCE)

{ fprintf(com1, " Resource: %d\r\n", taskStatus.requirement);

} fprintf(com1, " Error: %d\r\n", taskStatus.error); fprintf(com1, " Type: %s\r\n", type[taskStatus.type]);

}

}

{

/* Allow other tasks to execute */ release_processor();

}

}

TelePACE C Tools User and Reference Manual

May 9, 2007

207

getVersion

Get Firmware Version Information

Syntax

#include <ctools.h>

VERSION getVersion(void);

Description

The getVersion function obtains firmware version information. It returns a VERSION structure. Refer to the Structures and Types section for a description of the fields in the

VERSION structure.

Notes

The version information can be used to adapt a program to a specific type of controller or version of firmware. For example, a bug work-around could be executed only if older firmware is detected.

Example

This program displays the version information.

#include <ctools.h> void main(void)

{ struct prot_settings settings;

/* Disable the protocol on serial port 1 */ settings.type = NO_PROTOCOL; settings.station = 1; settings.priority = 3; settings.SFMessaging = FALSE;

request_resource(IO_SYSTEM);

}

release_resource(IO_SYSTEM);

/* Display the ROM version information */ versionInfo = getVersion(); fprintf(com1, "\r\nFirmware Information\r\n"); fprintf(com1, " Controller type: %d\r\n", versionInfo.controller &

BASE_TYPE_MASK); fprintf(com1, " Firmware version: %d\r\n", versionInfo.version); fprintf(com1, " Creation date: %s\r\n", versionInfo.date); fprintf(com1, " Copyright: %s\r\n", versionInfo.copyright);

TelePACE C Tools User and Reference Manual

May 9, 2007

208

getWakeSource

Gets Conditions for Waking from Sleep Mode

Syntax

#include <ctools.h> unsigned getWakeSource(void);

Description

The getWakeSource function returns a bit mask of the active wake up sources. Valid wake up sources are listed below.

• WS_REAL_TIME_CLOCK

• WS_INTERRUPT_INPUT

• WS_LED_POWER_SWITCH

• WS_COUNTER_0_OVERFLOW

• WS_COUNTER_1_OVERFLOW

• WS_COUNTER_2_OVERFLOW

See Also

setWakeSource, sleep

Example

The following code fragment displays the enabled wake up sources. unsigned enabled; enabled = getWakeSource(); fputs("Enabled wake up sources:\r\n", com1); if (enabled & WS_REAL_TIME_CLOCK) fputs(" Real Time Clock\r\n", com1); if (enabled & WS_INTERRUPT_INPUT) fputs(" Interrupt Input\r\n", com1); if (enabled & WS_LED_POWER_SWITCH) fputs(" LED Power Switch\r\n", com1); if (enabled & WS_COUNTER_0_OVERFLOW) fputs(" Counter 0 Overflow\r\n", com1); if (enabled & WS_COUNTER_1_OVERFLOW) fputs(" Counter 1 Overflow\r\n", com1); if (enabled & WS_COUNTER_2_OVERFLOW) fputs(" Counter 2 Overflow\r\n", com1);

TelePACE C Tools User and Reference Manual

May 9, 2007

209

hartIO

Read and Write 5904 HART Interface Module

Syntax

#include <ctools.h>

BOOLEAN hartIO(unsigned module);

Description

This function reads the specified 5904 interface module. It checks if a response has been received and if a corresponding command has been sent. If so, the response to the command is processed.

This function writes the specified 5904 interface module. It checks if there is a new command to send. If so, this command is written to the 5904 interface.

The function has one parameter: the module number of the 5904 interface (0 to 3).

The function returns TRUE if the 5904 interface responded and FALSE if it did not or if the module number is not valid.

Notes

This function is called automatically if the 5904 module is in the register assignment. Use this function to implement communication with the 5904 if register assignment is not used.

See Also

hartSetConfiguration, hartGetConfiguration, hartCommand

TelePACE C Tools User and Reference Manual

May 9, 2007

210

hartIOFromDbase

Read and Write 5904 HART Interface Module with Settings from Database

Syntax

#include <ctools.h>

BOOLEAN hartIOFromDbase(unsigned module, unsigned firstRegister);

Description

This function reads the specified 5904 interface module. It checks if a response has been received and if a corresponding command has been sent. If so, the response to the command is processed.

This function writes configuration and commands to the specified 5904 interface module.

Configuration data is read from the I/O database. It checks if there is a new command to send. If so, this command is written to the 5904 interface.

The function has two parameters: the module number of the 5904 interface (0 to 3); and the address of the first register of a group of four containing the HART interface configuration.

The function returns TRUE if the 5904 interface responded and FALSE if it did not or if the module number is not valid or there is an error in the settings.

See Also

hartIO, hartSetConfiguration

TelePACE C Tools User and Reference Manual

May 9, 2007

211

hartCommand

Send Command using HART Interface Module

Syntax

#include <ctools.h>

BOOLEAN hartCommand( unsigned module,

HART_DEVICE * const device,

HART_COMMAND * const command, void (* processResponse)( unsigned,

HART_RESPONSE)

);

Description

This function sends a command to a HART slave device using a HART interface module.

This function can be used to implement HART commands not provided by the Network

Layer API.

The function has four parameters. The first is the module number of the 5904 interface (0 to

3). The second is the device to which the command is to be sent.

The third parameter is a structure describing the command to send. This contains the command number, and the data field of the HART message. See the HART protocol documentation for your device for details.

The fourth parameter is a pointer to a function that will process the response. This function is called when a response to the command is received by the HART interface. The function is defined as follows:

The single parameter is a structure containing the response code and the data field from the message.

The function returns TRUE if the 5904 interface responded and FALSE if it did not or if the module number is not valid or there is an error in the command.

Notes

The function returns immediately after the command is sent. The calling program must wait for the response to be received. Use the hartStatus command to read the status of the command.

The number of attempts and the number of preambles sent are set with the hartSetConfiguration command.

A program must initialize the link before executing any other commands.

The function determines if long or short addressing is to be used by the command number.

Long addressing is used for all commands except commands 0 and 11.

The functions hartCommand0, hartCommand1, etc. are used to send commands provided by the Network Layer.

See Also

hartStatus, hartSetConfiguration, hartCommand0, hartCommand1

TelePACE C Tools User and Reference Manual

May 9, 2007

212

TelePACE C Tools User and Reference Manual

May 9, 2007

213

hartCommand0

Read Unique Identifier

Syntax

#include <ctools.h>

BOOLEAN hartCommand0(unsigned module, unsigned address, HART_DEVICE * const device);

Description

This function reads the unique identifier of a HART device using command 0 with a shortform address. This is a link initialization function.

The function has three parameters: the module-number of the 5904 module (0 to 3); the short-form address of the HART device (0 to 15); and a pointer to a HART_DEVICE structure. The information read by command 0 is written into the HART_DEVICE structure when the response is received by the 5904 interface.

The function returns TRUE if the command was sent. The function returns FALSE if the module number is invalid, or if the device address is invalid.

Notes

The function returns immediately after the command is sent. The calling program must wait for the response to be received. Use the hartStatus command to read the status of the command.

The number of attempts and the number of preambles sent are set with the hartSetConfiguration command.

A program must initialize the link before executing any other commands.

See Also

hartCommand11, hartStatus, hartSetConfiguration

TelePACE C Tools User and Reference Manual

May 9, 2007

214

hartCommand1

Read Primary Variable

Syntax

#include <ctools.h>

BOOLEAN hartCommand1(unsigned module, HART_DEVICE * const device,

HART_VARIABLE * primaryVariable);

Description

This function reads the primary variable of a HART device using command 1.

The function has three parameters: the module-number of the 5904 module (0 to 3); the device to be read; and a pointer to the primary variable. The variable pointed to by primaryVariable is updated when the response is received by the 5904 interface.

The primaryVariable must be a static modular or global variable. A primaryVariable should be declared for each HART I/O module in use. A local variable or dynamically allocated variable may not be used because a late command response received after the variable is freed will write data over the freed variable space.

The function returns TRUE if the command was sent. The function returns FALSE if the module number is invalid.

Notes

The HART_DEVICE structure must be initialized using hartCommand0 or hartCommand11.

The function returns immediately after the command is sent. The calling program must wait for the response to be received. Use the hartStatus command to read the status of the command.

The number of attempts and the number of preambles sent are set with the hartSetConfiguration command.

The code field of the HART_VARIABLE structure not changed. Command 1 does not return a variable code.

See Also

hartCommand2, hartStatus, hartSetConfiguration

TelePACE C Tools User and Reference Manual

May 9, 2007

215

hartCommand2

Read Primary Variable Current and Percent of Range

Syntax

#include <ctools.h>

BOOLEAN hartCommand2(unsigned module, HART_DEVICE * const device,

HART_VARIABLE * pvCurrent, HART_VARIABLE * pvPercent);

Description

This function reads the primary variable (PV), as current and percent of range, of a HART device using command 2.

The function has four parameters: the module-number of the 5904 module (0 to 3); the device to be read; a pointer to the PV current variable; and a pointer to the PV percent variable. The pvCurrent and pvPercent variables are updated when the response is received by the 5904 interface.

The pvCurrent and pvPercent variables must be static modular or global variables. A pvCurrent and pvPercent variable should be declared for each HART I/O module in use. A local variable or dynamically allocated variable may not be used because a late command response received after the variable is freed will write data over the freed variable space.

The function returns TRUE if the command was sent. The function returns FALSE if the module number is invalid.

Notes

The HART_DEVICE structure must be initialized using hartCommand0 or hartCommand11.

The function returns immediately after the command is sent. The calling program must wait for the response to be received. Use the hartStatus command to read the status of the command.

The number of attempts and the number of preambles sent are set with the hartSetConfiguration command.

The code field of both HART_VARIABLE structures is not changed. The response from the

HART device to command 2 does not include variable codes.

The units field of the pvCurrent variable is set to 39 (units = mA). The units field of the pvPercent variable is set to 57 (units = percent). The response from the HART device to command 2 does not include units.

See Also

hartCommand1, hartStatus, hartSetConfiguration

TelePACE C Tools User and Reference Manual

May 9, 2007

216

hartCommand3

Read Primary Variable Current and Dynamic Variables

Syntax

#include <ctools.h>

BOOLEAN hartCommand3(unsigned module, HART_DEVICE * const device,

HART_VARIABLE * variables);

Description

This function reads dynamic variables and primary variable current from a HART device using command 3.

The function has three parameters: the module number of the 5904 module (0 to 3); the device to be read; and a pointer to an array of five HART_VARIABLE structures.

The variables array must be static modular or global variables. An array of variables should be declared for each HART I/O module in use. A local variable or dynamically allocated variable may not be used because a late command response received after the variable is freed will write data over the freed variable space.

The variables array is updated when the response is received by the 5904 interface as follows.

Variable Contains

variables[0] primary variable current

The function returns TRUE if the command was sent. The function returns FALSE if the module number is invalid.

Notes

The HART_DEVICE structure must be initialized using hartCommand0 or hartCommand11.

The function returns immediately after the command is sent. The calling program must wait for the response to be received. Use the hartStatus command to read the status of the command.

The number of attempts and the number of preambles sent are set with the hartSetConfiguration command.

Not all devices return primary, secondary, tertiary and fourth variables. If the device does not support a variable, zero is written into the value and units code for that variable.

The code field of both HART_VARIABLE structures is not changed. The response from the

HART device to command 3 does not include variable codes.

The units field of variable[0] is set to 39 (units = mA). The response from the HART device to command 3 does not include units.

See Also

hartCommand33, hartStatus, hartSetConfiguration

TelePACE C Tools User and Reference Manual

May 9, 2007

217

hartCommand11

Read Unique Identifier Associated with Tag

Syntax

#include <ctools.h>

BOOLEAN hartCommand11(unsigned module, char * deviceTag, HART_DEVICE * device);

Description

This function reads the unique identifier of a HART device using command 11. This is a link initialization function.

The function has three parameters: the module number of the 5904 module (0 to 3); a pointer to a null terminated string containing the tag of the HART device; and a pointer to a

HART_DEVICE structure. The information read by command 11 is written into the

HART_DEVICE structure when the response is received by the 5904 interface.

The function returns TRUE if the command was sent. The function returns FALSE if the module number is invalid.

Notes

The function returns immediately after the command is sent. The calling program must wait for the response to be received. Use the hartStatus command to read the status of the command.

The number of attempts and the number of preambles sent are set with the hartSetConfiguration command.

A program must initialize the link before executing any other commands.

See Also

hartCommand0, hartStatus, hartSetConfiguration

TelePACE C Tools User and Reference Manual

May 9, 2007

218

hartCommand33

Read Transmitter Variables

Syntax

#include <ctools.h>

BOOLEAN hartCommand33(unsigned module, HART_DEVICE * const device, unsigned variableCode[4], HART_VARIABLE * variables);

Description

This function reads selected variables from a HART device using command 33.

The function has four parameters: the module number of the 5904 module (0 to 3); the device to be read; an array of codes; and a pointer to an array of four HART_VARIABLE structures.

The variables array must be static modular or global variables. An array of variables should be declared for each HART I/O module in use. A local variable or dynamically allocated variable may not be used because a late command response received after the variable is freed will write data over the freed variable space.

The variableCode array specifies which variables are to be read from the transmitter.

Consult the documentation for the transmitter for valid values.

The variables array is updated when the response is received by the 5904 interface as follows.

Variable Contains

variables[0] transmitter variable, code and units specified by variableCode[0] variables[1] transmitter variable, code and units specified by variableCode[1] variables[2] transmitter variable, code and units specified by variableCode[2] variables[3] transmitter variable, code and units specified by variableCode[3]

The function returns TRUE if the command was sent. The function returns FALSE if the module number is invalid.

Notes

The HART_DEVICE structure must be initialized using hartCommand0 or hartCommand11.

The pointer variables must point to an array with at least four elements.

The function returns immediately after the command is sent. The calling program must wait for the response to be received. Use the hartStatus command to read the status of the command.

The number of attempts and the number of preambles sent are set with the hartSetConfiguration command.

The function always requests four variables and expects four variables in the response.

See Also

hartCommand3, hartStatus, hartSetConfiguration

TelePACE C Tools User and Reference Manual

May 9, 2007

219

hartStatus

Return Status of Last HART Command Sent

Syntax

#include <ctools.h>

BOOLEAN hartStatus(unsigned module, HART_RESULT * status, unsigned * code);

Description

This function returns the status of the last HART command sent by a 5904 module (0 to 3).

Use this function to determine if a response has been received to a command sent.

The function has three parameters: the module number of the 5904 module; a pointer to the status variable; and a pointer to the additional status code variable. The status and code variables are updated with the following information.

Result Status

HART interface module is not communicating

Command ready to be sent HR_CommandPending

Command sent to device HR_CommandSent

Response received HR_Response

No valid response received after all attempts made

HR_NoResponse

code

not used current attempt number response code from HART device (see Notes)

0=no response from HART device.

Other = error response code from HART device (see

Notes)

HART interface module is not ready to transmit

The function returns TRUE if the status was read. The function returns FALSE if the module number is invalid.

Notes

The response code from the HART device contains communication error and status information. The information varies by device, but there are some common values.

• If bit 7 of the high byte is set, the high byte contains a communication error summary.

This field is bit-mapped. The table shows the meaning of each bit as defined by the

HART protocol specifications. Consult the documentation for the HART device for more information.

Bit

6

Description

vertical parity error

3

2 longitudinal parity error reserved – always 0

0 Undefined

TelePACE C Tools User and Reference Manual

May 9, 2007

220

• If bit 7 of the high byte is cleared, the high byte contains a command response summary. The table shows common values. Other values may be defined for specific commands. Consult the documentation for the HART device.

Code

32

64

Description

Busy – the device is performing a function that cannot be interrupted by this command

Command not Implemented – the command is not defined for this device.

• The low byte contains the field device status. This field is bit-mapped. The table shows the meaning of each bit as defined by the HART protocol specifications. Consult the documentation for the HART device for more information.

Bit

7

Description

field device malfunction

4

3

2

1

0 more status available (use command 48 to read) primary variable analog output fixed primary variable analog output saturated non-primary variable out of limits primary variable out of limits

See Also

hartSetConfiguration

TelePACE C Tools User and Reference Manual

May 9, 2007

221

hartGetConfiguration

Read HART Module Settings

Syntax

#include <ctools.h>

BOOLEAN hartGetConfiguration(unsigned module, HART_SETTINGS * settings);

Description

This function returns the configuration settings of a 5904 module.

The function has two parameters: the module number of the 5904 module (0 to 3); and a pointer to the settings structure.

The function returns TRUE if the settings were read. The function returns FALSE if the module number is invalid.

See Also

hartSetConfiguration

TelePACE C Tools User and Reference Manual

May 9, 2007

222

hartSetConfiguration

Write HART Module Settings

Syntax

#include <ctools.h>

BOOLEAN hartSetConfiguration(unsigned module, HART_SETTINGS settings);

Description

This function writes configuration settings to a 5904 module.

The function has two parameters: the module number of the 5904 module (0 to 3); and a settings structure.

The function returns TRUE if the settings were written. The function returns FALSE if the module number or the settings are invalid.

Notes

The configuration settings are stored in the EEPROM_RUN section of the EEPROM. The user-defined settings are used when the controller is reset in the RUN mode. Default settings are used when the controller is reset in the SERVICE or COLD BOOT modes.

If a CNFG 5904 HART Interface module is in the register assignment, forced registers from it take precedence over the settings supplied here.

See Also

hartGetConfiguration

TelePACE C Tools User and Reference Manual

May 9, 2007

223

hartPackString

Convert String to HART Packed String

Syntax

#include <ctools.h> void hartPackString(char * pPackedString, const char * pString, unsigned sizePackedString);

Description

This function stores an ASCII string into a HART packed ASCII string.

The function has three parameters: a pointer to a packed array; a pointer to an unpacked array; and the size of the packed array. The packed array must be a multiple of three in size.

The unpacked array must be a multiple of four in size. It should be padded with spaces at the end if the string is not long enough.

The function has no return value.

See Also

hartUnpackString

TelePACE C Tools User and Reference Manual

May 9, 2007

224

hartUnpackString

Convert HART Packed String to String

Syntax

#include <ctools.h> void hartUnpackString(char * pString, const char * pPackedString, unsigned sizePackedString);

Description

This function unpacks a HART packed ASCII string into a normal ASCII string.

The function has three parameters: a pointer to an unpacked array; a pointer to a packed array; and the size of the packed array. The packed array must be a multiple of three in size.

The unpacked array must be a multiple of four in size.

The function has no return value.

See Also

hartPackString

TelePACE C Tools User and Reference Manual

May 9, 2007

225

install_handler

Install Serial Port Handler

Syntax

#include <ctools.h> void install_handler(FILE *stream, void *function(unsigned, unsigned));

Description

The install_handler function installs a serial port character handler function. The serial port driver calls this function each time it receives a character. If stream does not point to a valid serial port the function has no effect.

function specifies the handler function, which takes two arguments. The first argument is the received character. The second argument is an error flag. A non-zero value indicates an error. If function is NULL, the default handler for the port is installed. The default handler does nothing.

Notes

The install_handler function can be used to write custom communication protocols.

The handler is called at the completion of the receiver interrupt handler. RTOS calls (see functions listed in the section Real Time Operating System Functions at the start of this chapter) may not be made within the interrupt handler, with one exception. The

interrupt_signal_event RTOS call can be used to signal events.

To optimize performance, minimize the length of messages on com3 and com4. Examples of recommended uses for com3 and com4 are for local operator display terminals, and for programming and diagnostics using the TelePACE program.

Example

#include <ctools.h>

#define CHAR_RECEIVED 11

/* --------------------------------------------

signal

This routine signals an event when a character

is received on com1. If there is an error, the

character is ignored.

-------------------------------------------- */ void signal(unsigned character, unsigned error)

{ if (error == 0) interrupt_signal_event( CHAR_RECEIVED );

character;

}

/* --------------------------------------------

main

This program displays all characters received

on com1 using an installed handler to signal

TelePACE C Tools User and Reference Manual

May 9, 2007

226

the reception of a character.

-------------------------------------------- */ void main(void)

{ struct prot_settings protocolSettings;

/* Disable protocol */ protocolSettings.type = NO_PROTOCOL;

request_resource(IO_SYSTEM);

release_resource(IO_SYSTEM);

/* Enable character handler */

/* Print each character as it is recevied */

{ wait_event(CHAR_RECEIVED); character = fgetc(com1); fputs("character: ", com1);

}

}

TelePACE C Tools User and Reference Manual

May 9, 2007

227

installClockHandler

Install Handler for Real Time Clock

Syntax

#include <ctools.h> void installClockHandler(void (*function)(void));

Description

The installClockHandler function installs a real time clock alarm handler function. The real time clock alarm function calls this function each time a real time clock alarm occurs.

function specifies the handler function. If function is NULL, the handler is disabled.

Notes

RTOS calls (see functions listed in the section Real Time Operating System Functions at the start of this chapter) may not be made within the interrupt handler, with one exception. The

interrupt_signal_event RTOS call can be used to signal events.

See Also

setClockAlarm

Example

/* --------------------------------------------

This program demonstrates how to call a

function at a specific time of day.

-------------------------------------------- */

#include <ctools.h>

#define ALARM_EVENT 20

/* --------------------------------------------

This function signals an event when the alarm

occurs.

-------------------------------------------- */ void alarmHandler(void)

{ interrupt_signal_event( ALARM_EVENT );

}

/* --------------------------------------------

This task processes alarms signaled by the

-------------------------------------------- */ void processAlarms(void)

{

while(TRUE)

{ wait_event(ALARM_EVENT);

/* Reset the alarm for the next day */ request_resource(IO_SYSTEM); resetClockAlarm(); release_resource(IO_SYSTEM);

TelePACE C Tools User and Reference Manual

May 9, 2007

228

fprintf(com1, "It’s quitting time!\r\n");

}

} void main(void)

{ struct prot_settings settings;

/* Disable the protocol on serial port 1 */ settings.type = NO_PROTOCOL; settings.station = 1; settings.priority = 3; settings.SFMessaging = FALSE;

request_resource(IO_SYSTEM);

release_resource(IO_SYSTEM);

/* Install clock handler function */

installClockHandler(alarmHandler);

/* Create task for processing alarm events */ create_task(processAlarms, 3, APPLICATION, 4);

/* Set real time clock alarm */ alarm.type = AT_ABSOLUTE; alarm.hour = 16; alarm.minute = 0; alarm.second = 0;

request_resource(IO_SYSTEM);

setClockAlarm(alarm);

release_resource(IO_SYSTEM);

while(TRUE)

{

/* body of main task loop */

/* other processing code */

/* Allow other tasks to execute */ release_processor();

}

}

TelePACE C Tools User and Reference Manual

May 9, 2007

229

installExitHandler

Install Handler Called when Task Ends

Syntax

#include <ctools.h> unsigned installExitHandler(unsigned taskID, void (*function)(void));

Description

The installExitHandler function defines a function that is called when the task, specified by

taskID, is ended. function specifies the handler function. If function is NULL, the handler is disabled.

Notes

The exit handler function will be called when:

• the task is ended by the end_task function

• the end_application function is executed and the function is an APPLICATION type function

• the program is stopped from the TelePACE program and the task is an APPLICATION type function

• the C program is erased by the TelePACE program.

The exit handler function is not called if power to the controller is removed. In this case all execution stops when power fails. The application program starts from the beginning when power is reapplied.

Do not call any RTOS functions from the exit handler.

Example

See the example for startTimedEvent.

TelePACE C Tools User and Reference Manual

May 9, 2007

230

installModbusHandler

Install User Defined Modbus Handler

Syntax

#include <ctools.h> void installModbusHandler( unsigned (* handler)(unsigned char *, unsigned,

unsigned char *, unsigned *)

);

Description

The installModbusHandler function allows user-defined extensions to standard Modbus protocol. This function specifies a function to be called when a Modbus message is received for the station, but is not understood by the standard Modbus protocol. The installed handler function is called only if the message is addressed to the station, and the message checksum is correct.

The function has one parameter: a pointer to a function to handle the messages. See the section Handler Function for a full description of the function and it’s parameters. If the pointer is NULL, no function is called for non-standard messages.

The function has no return value.

Notes

This function is used to create a user-defined extension to the standard Modbus protocol.

Call this function with the NULL pointer to disable processing of non-standard Modbus messages. This must be done when the application program is ended with an exit handler.

Use the installExitHandler function to install the exit handler.

If the Modbus handler is not disabled within an exit handler, it will remain installed and continue to operate until the controller power is cycled. Changing the protocol type or

Erasing the C Program from TelePACE Initialize dialog will not remove the Modbus handler.

If the handler is located in a RAM-based application and left enabled while a different C application is downloaded, the original handler will be corrupted and the system will likely crash.

See Also

installExitHandler, Handler Function

TelePACE C Tools User and Reference Manual

May 9, 2007

231

Handler Function

User Specified Handler Function

The handler function is a user-specified function that handles processing of Modbus messages not recognized by the protocol. The function can have any name; handler is used in the description below.

Syntax

#include <ctools.h> unsigned handler( unsigned char * message, unsigned messageLength, unsigned char * response, unsigned * responseLength

);

Description

This function handler is a user-defined handler for processing Modbus messages. The function is called for each Modbus message with a function code that is not recognized by the standard Modbus protocol.

The handler function should process the message string and create a response string. IF the message is not understood, one of the error codes should be returned.

The function has four parameters. first character of the message is the function code. The format of the data after the function code is defined by the function code. response. The function should write the response into this buffer. The buffer is 253 characters long. The first character of the buffer is the function code of the message.

The format of the data after the function code is defined by the function code. should set the length of the response using this pointer. The length is the number of characters placed into the response buffer.

The function must return one of four values. The first causes a normal response to be sent.

The others cause an exception response to be sent.

• NORMAL indicates the response and responseLength have been set to valid values.

The Modbus protocol will add the station address and checksum to this string and transmit the reply to the master station.

• ILLEGAL_FUNCTION indicates the function code in the message was not understood.

The handler function must return this value for all function codes it does not process.

The Modbus protocol will return an Illegal Function exception response.

• ILLEGAL_DATA_ADDRESS indicates the function code in the message was understood, but that the command referenced an address that is not valid. The Modbus protocol will return an Illegal Data Address exception response.

TelePACE C Tools User and Reference Manual

May 9, 2007

232

• ILLEGAL_DATA_VALUE indicates the function code in the message was understood, but that the command included data that is not valid. The Modbus protocol will return an

Illegal Data Address exception response.

Function Codes Used

The following function codes are currently used by the TeleBUS Modbus-compatible protocol. All other function codes are available for use. For maximum compatibility with other

Modbus and Modbus-compatible devices it is recommended that codes in the user-defined function code range be used first.

7

15

16

17

65

66

67

68

69

70

3

4

5

6

Code Type

1

2

Modbus standard

Modbus standard

Description

Read coil registers from I/O database

Read status registers from I/O database

Modbus standard

Modbus standard

Modbus standard

Modbus standard

Read holding registers from I/O database

Read input registers from I/O database

Write a single coil register

Write a single holding register

Modbus standard

Modbus standard

Read exception status

Write multiple coil registers

Modbus standard Write multiple holding registers

Modbus standard Report slave identification string

TeleBUS extension Used by TelePACE

TeleBUS extension Used by TelePACE

TeleBUS extension Used by TelePACE

TeleBUS extension Used by TelePACE

TeleBUS extension Used by TelePACE

TeleBUS extension Used by TelePACE

Notes

One handler function is used for all serial ports. Only one port will be active at any time.

Therefore, the function does not have to be re-entrant.

The handler function is called from the Modbus protocol task. This task may pre-empt the execution of another task. If there are shared resources, the handler function must request and release the appropriate resources to ensure proper operation.

The station address is not included in the message or response string. It will be added to the response string before sending the reply.

The checksum is not included in the message or the response string. It will be added to the response string before sending the reply.

The maximum size of the response string is 253 bytes. If a longer response length is returned, the Modbus protocol will report an ILLEGAL_DATA_VALUE exception. The response will not be returned.

See Also

installModbusHandler

Example

/* -----------------------------------------------

handler.c

TelePACE C Tools User and Reference Manual

May 9, 2007

233

This is a sample program for the InstallModbusHandler function. This sample program uses function code 71 to simple method for using the installModbusHandler function.

When the handler is installed Modbus ASCII messages using function code

71 that are received on com2 of the controller will

be processed as shown in the program text.

To turn on digital output 00001:

From a terminal send the ASCII command :014701B7

Where;

01 is the station address

47 is the function code in hex

01 is the command for the function code

B7 is the message checksum

To turn off digital output 00001:

From a terminal send the ASCII command :014700B8

Where;

01 is the station address

47 is the function code in hex

00 is the command for the function code

B8 is the message checksum

-------------------------------------------- */

#include <ctools.h> static unsigned myModbusHandler( unsigned char * message, unsigned messageLength, unsigned char * response, unsigned * responseLength

)

{ unsigned char * pMessage; unsigned char * pResponse; pMessage = message; if (*pMessage == 71)

{

/* Action for command data */ pMessage++;

if (*pMessage == 0)

{

request_resource(IO_SYSTEM);

release_resource(IO_SYSTEM);

pResponse response;

*pResponse

pResponse++;

71;

*pResponse 'O';

pResponse++;

*pResponse 'F';

pResponse++;

*pResponse

pResponse++;

'F';

*responseLength

} if (*pMessage == 1)

{

4;

TelePACE C Tools User and Reference Manual

May 9, 2007

234

request_resource(IO_SYSTEM);

release_resource(IO_SYSTEM);

pResponse response;

*pResponse

pResponse++;

*pResponse

71;

'O';

pResponse++;

*pResponse = 'N';

pResponse++;

*responseLength 3;

}

}

} static void shutdown(void)

{

installModbusHandler(NULL);

}

/* -----------------------------------------------

main

This routine is the modbus slave application.

Serial port com2 is configured for Modbus ASCII protocol.

Register Assignment is configured.

The modbus handler is installed.

The exit handler is installed.

-------------------------------------------- */ void main(void)

{

TASKINFO taskStatus; struct pconfig portSettings; struct prot_settings protSettings;

portSettings.baud BAUD9600; portSettings.duplex portSettings.parity

= FULL;

= NONE;

portSettings.type RS232; protSettings.station = 1; protSettings.type = MODBUS_ASCII; set_protocol(com2, &protSettings);

/* Configure Register Assignment */

clearRegAssignment(); addRegAssignment(DIN_generic8, 0, 10017, 0, 0, 0); addRegAssignment(SCADAPack_lowerIO,0, 1, 10001, 30001, 0); addRegAssignment(DIAG_protocolStatus,1,31000, 0, 0, 0);

/* Install Modbus Handler */

request_resource(IO_SYSTEM);

installModbusHandler(myModbusHandler);

release_resource(IO_SYSTEM);

TelePACE C Tools User and Reference Manual

May 9, 2007

235

/* Install Exit Handler */ taskStatus = getTaskInfo(0);

while(TRUE)

{ release_processor();

}

}

TelePACE C Tools User and Reference Manual

May 9, 2007

236

installRTCHandler

Install User Defined Real-Time-Clock Handler

Syntax

#include <ctools.h> void installRTCHandler( void (* rtchandler)(TIME *now,

TIME *new)

);

Description

The installRTCHandler function allows an application program to override Modbus protocol and DNP protocol commands to set the real time clock. This function specifies a function to be called when a Modbus or DNP message is received for the station. The installed handler function is called only if the message is intended to set the real time clock.

The function has one parameter: a pointer to a function to handle the messages. See the section RTCHandler Function for a full description of the function and its parameters. If the pointer is NULL, no function is called for set the real time clock commands, and the default method is used set the real time clock.

The function has no return value.

Notes

Call this function with the NULL pointer to disable processing of Set Real Time Clock messages. This must be done when the application program is ended with an exit handler.

Use the installExitHandler function to install the exit handler.

If the RTC handler is not disabled within an exit handler, it will remain installed and continue to operate until the controller power is cycled. Changing the protocol type or Erasing the C

Program from the TelePACE Initialize dialog will not remove the handler. If the handler is located in a RAM-based application and left enabled while a different C application is downloaded, the original handler will be corrupted and the system will likely crash.

See Also

RTCHandler Function, installExitHandler

TelePACE C Tools User and Reference Manual

May 9, 2007

237

RTCHandler Function

User Specified Real Time Clock Handler Function

The handler function is a user-specified function that handles processing of Modbus messages or DNP messages for setting the real time clock. The function can have any name; rtchandler is used in the description below.

Syntax

#include <ctools.h> void rtchandler(

TIME *now,

);

Description

This function rtchandler is a user-defined handler for processing Modbus messages or DNP messages. The function is called only for messages that set the real time clock.

The rtchandler function should set the real time clock to the requested time. If there is a delay before this can be done, the time when the message was received is provided so that a correction to the requested time can be made.

The function has two parameters. was received.

The function does not return a value.

Notes

The IO_SYSTEM resource has already been requested before calling this function. If this function calls other functions that require the IO_SYSTEM resource (e.g. setclock), there is no need to request or release the resource.

This function must not request or release the IO_SYSTEM resource.

See Also

installRTCHandler

TelePACE C Tools User and Reference Manual

May 9, 2007

238

interruptCounter

Read Interrupt Input Counter

Syntax

#include <ctools.h> unsigned long interruptCounter(unsigned clear);

Description

The interruptCounter routine reads the interrupt input as a counter. If clear is TRUE the counter is cleared after reading; otherwise if it is FALSE the counter continues to accumulate.

Notes

The interrupt input is located on the 5203 or 5204 controller board. Refer to the System

Hardware Manual for more information on the hardware.

The counter increments on the rising edge of the input signal.

The maximum input frequency that can be counted by the interrupt input is 200 Hz.

See Also

interruptInput, readCounter

TelePACE C Tools User and Reference Manual

May 9, 2007

239

interruptInput

Read State of Interrupt Digital Input

Syntax

#include <ctools.h> unsigned interruptInput(void);

Description

The interruptInput function reads the status of the interrupt input point on the controller. It returns TRUE if the input is energized and FALSE if it is not.

Notes

The interrupt input can be used as wake up source for the controller or as an additional a digital input. Refer to the System Hardware Manual for wiring details.

See Also

installRTCHandler

Install User Defined Real-Time-Clock Handler

Syntax

#include <ctools.h> void installRTCHandler( void (* rtchandler)(TIME *now,

TIME *new)

);

Description

The installRTCHandler function allows an application program to override Modbus protocol and DNP protocol commands to set the real time clock. This function specifies a function to be called when a Modbus or DNP message is received for the station. The installed handler function is called only if the message is intended to set the real time clock.

The function has one parameter: a pointer to a function to handle the messages. See the section RTCHandler Function for a full description of the function and its parameters. If the pointer is NULL, no function is called for set the real time clock commands, and the default method is used set the real time clock.

The function has no return value.

Notes

Call this function with the NULL pointer to disable processing of Set Real Time Clock messages. This must be done when the application program is ended with an exit handler.

Use the installExitHandler function to install the exit handler.

If the RTC handler is not disabled within an exit handler, it will remain installed and continue to operate until the controller power is cycled. Changing the protocol type or Erasing the C

Program from the TelePACE Initialize dialog will not remove the handler. If the handler is located in a RAM-based application and left enabled while a different C application is downloaded, the original handler will be corrupted and the system will likely crash.

TelePACE C Tools User and Reference Manual

May 9, 2007

240

See Also

RTCHandler Function, installExitHandler

TelePACE C Tools User and Reference Manual

May 9, 2007

241

RTCHandler Function

User Specified Real Time Clock Handler Function

The handler function is a user-specified function that handles processing of Modbus messages or DNP messages for setting the real time clock. The function can have any name; rtchandler is used in the description below.

Syntax

#include <ctools.h> void rtchandler(

TIME *now,

);

Description

This function rtchandler is a user-defined handler for processing Modbus messages or DNP messages. The function is called only for messages that set the real time clock.

The rtchandler function should set the real time clock to the requested time. If there is a delay before this can be done, the time when the message was received is provided so that a correction to the requested time can be made.

The function has two parameters. was received.

The function does not return a value.

Notes

The IO_SYSTEM resource has already been requested before calling this function. If this function calls other functions that require the IO_SYSTEM resource (e.g. setclock), there is no need to request or release the resource.

This function must not request or release the IO_SYSTEM resource.

See Also installRTCHandler

interruptCounter

TelePACE C Tools User and Reference Manual

May 9, 2007

242

interrupt_signal_event

Signal Event in Interrupt Handler

Syntax

#include <ctools.h> void interrupt_signal_event(unsigned event_number);

Description

The interrupt_signal_event function is used in an interrupt handler to signal events. The function signals that the event_number event has occurred.

If there are tasks waiting for the event, the highest priority task is made ready to execute.

Otherwise the event flag is incremented. Up to 255 occurrences of an event will be recorded. The current task is blocked of there is a higher priority task waiting for the event.

Notes

Refer to the Real Time Operating System section for more information on events.

This function must only be used within an interrupt handler.

Valid events are numbered 0 to RTOS_EVENTS - 1. Any events defined in ctools.h. are not valid events for use in an application program.

See Also

signal_event, startTimedEvent, installClockHandler

TelePACE C Tools User and Reference Manual

May 9, 2007

243

interval

Set Timer Tick Interval

Syntax

#include <ctools.h> void interval(unsigned timer, unsigned value);

Description

The interval function sets the tick interval for timer to value. Tick intervals are measured in multiples of 0.1 second.

If the timer number is invalid, the task's error code is set to TIMER_BADTIMER.

Notes

The default timer tick interval is 1/10 second.

See Also

settimer, read_timer_info, check_error

Example

Set timer 5 to count 12 seconds using 1.0 s ticks. interval(5, 10); /* 1.0 s ticks */ settimer(5, 12); /* time = 12 seconds */

Set timer 5 to count 12 seconds using 0.1 s ticks. interval(5, 1); /* 0.1 s ticks */ settimer(5, 120); /* time = 12 seconds */

TelePACE C Tools User and Reference Manual

May 9, 2007

244

ioBusReadByte

Read One Byte from I

2

C Slave Device

Syntax

#include <ctools.h> unsigned char ioBusReadByte(void);

Description

The ioBusReadByte function returns one byte read from an I

2

C slave device. The byte is acknowledged by the master receiver. This function can be used multiple times in sequence to read data from a slave device. The last byte read from the slave must be read with the

ioBusReadLastByte function.

If only one byte is to be read from a device, the ioBusReadLastByte function must be used instead of this function.

Notes

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioBusStart, ioBusStop, ioBusReadLastByte, ioBusReadMessage, ioBusSelectForRead

ioBusSelectForWrite, ioBusWriteByte, ioBusWriteMessage

Example

#include <ctools.h> void main(void)

{ unsigned char data[3]; unsigned char ioBusAddress = 114;

request_resource(IO_SYSTEM);

ioBusStart();

{ data[0] = ioBusReadByte(); data[1] = ioBusReadByte();

/* reading the last byte terminates read */ data[2] = ioBusReadLastByte();

}

ioBusStop();

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

245

ioBusReadLastByte

Read Last Byte from I

2

C Slave Device

Syntax

#include <ctools.h> unsigned char ioBusReadLastByte(void);

Description

The ioBusReadLastByte function returns one byte read from an I

2

C slave device and terminates reading from the slave. The byte is not acknowledged by the master receiver.

This signals to the slave device that the read is complete. This function must be used once at the end of a read.

Notes

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioBusStart, ioBusStop, ioBusReadByte, ioBusReadMessage, ioBusSelectForRead

ioBusSelectForWrite, ioBusWriteByte, ioBusWriteMessage

Example

See example for ioBusReadByte.

TelePACE C Tools User and Reference Manual

May 9, 2007

246

ioBusReadMessage

Read Message from I

2

C Slave Device

Syntax

#include <ctools.h>

READSTATUS ioBusReadMessage(unsigned address, unsigned numberBytes, unsigned char *message);

Description

The ioBusReadMessage function reads a specified number of bytes from an I

2

C slave device.

The function issues a START condition, selects the device for reading, reads the specified number of bytes, and issues a STOP condition. It detects if the device cannot be selected and, if so, aborts the read.

The function has three parameters: the address of the device; the number of bytes to read,

numberBytes; and a pointer to a buffer, message, capable of holding the data read.

The function returns the status of the read:

Value

RS_success

RS_selectFailed

Description

read was successful slave device could not be selected

Notes

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioBusWriteMessage, ioBusStart, ioBusStop, ioBusReadByte ioBusReadLastByte,

ioBusSelectForRead ioBusSelectForWrite, ioBusWriteByte, ioBusWriteMessage

Example

#include <ctools.h> void main(void)

{

request_resource(IO_SYSTEM);

/* Read a 10 byte message from I2C device */ status = ioBusReadMessage(ioBusAddress, 10, message);

release_resource(IO_SYSTEM); if (status != RS_success)

{ fprintf(com1, "I/O error = %d\n\r", status);

}

}

TelePACE C Tools User and Reference Manual

May 9, 2007

247

ioBusSelectForRead

Select I

2

C Slave Device for Reading

Syntax

#include <ctools.h> unsigned ioBusSelectForRead(unsigned char address);

Description

The ioBusSelectForRead function selects an I

2

C slave device for reading. It writes the slave device address with the read/write bit set to the read state. The function handles the formatting of the address byte.

The function has one parameter, the address of the device. It returns TRUE if the write succeeded, that is the byte was acknowledged by the slave. It returns FALSE if the write failed, that is the byte was not acknowledged by the slave.

Notes

This function can only be used immediately after a START condition, e.g. ioBusStart.

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioBusStart, ioBusStop, ioBusReadByte, ioBusReadLastByte, ioBusReadMessage,

ioBusSelectForWrite, ioBusWriteByte, ioBusWriteMessage

Example

See example for ioBusReadByte.

TelePACE C Tools User and Reference Manual

May 9, 2007

248

ioBusSelectForWrite

Select I

2

C Slave Device for Writing

Syntax

#include <ctools.h> unsigned ioBusSelectForWrite(unsigned char address);

Description

The ioBusSelectForWrite function selects an I

2

C slave device for writing. It writes the slave device address with the read/write bit set to the write state. The function handles the formatting of the address byte.

The function has one parameter, the address of the device. It returns TRUE if the write succeeded, that is the byte was acknowledged by the slave. It returns FALSE if the write failed, that is the byte was not acknowledged by the slave.

Notes

This function can only be used immediately after a START condition, e.g. ioBusStart.

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioBusStart, ioBusStop, ioBusReadByte, ioBusReadLastByte, ioBusReadMessage,

ioBusSelectForRead, ioBusWriteByte, ioBusWriteMessage

Example

See example for ioBusWriteByte.

TelePACE C Tools User and Reference Manual

May 9, 2007

249

ioBusStart

Issue an I

2

C Bus START Condition

Syntax

#include <ctools.h> void ioBusStart(void);

Description

The ioBusStart function issues an I

2

C bus START condition.

Notes

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioBusStop, ioBusReadByte, ioBusReadLastByte, ioBusReadMessage,

ioBusSelectForRead ioBusSelectForWrite, ioBusWriteByte, ioBusWriteMessage

Example

See example for ioBusReadByte.

TelePACE C Tools User and Reference Manual

May 9, 2007

250

ioBusStop

Issue an I

2

C Bus STOP Condition

Syntax

#include <ctools.h> void ioBusStop(void);

Description

The ioBusStop function issues an I

2

C bus STOP condition.

Notes

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioBusStart, ioBusReadByte, ioBusReadLastByte, ioBusReadMessage,

ioBusSelectForRead ioBusSelectForWrite, ioBusWriteByte, ioBusWriteMessage

Example

See example for ioBusReadByte.

TelePACE C Tools User and Reference Manual

May 9, 2007

251

ioBusWriteByte

Write One Byte to I

2

C Slave Device

Syntax

#include <ctools.h> unsigned ioBusWriteByte(unsigned char byte);

Description

The ioBusWriteByte function writes one byte to an I

2

C slave device and returns the acknowledge signal from the slave. It returns TRUE if the write succeeded, that is the byte was acknowledged by the slave. It returns FALSE if the write failed, that is the byte was not acknowledged by the slave.

This function can be used multiple times in sequence to write data to a device.

Notes

ioBusWriteByte can be used to write the address selection byte at the start of an I

2

C message; however, the ioBusSelectForRead and ioBusSelectForWrite functions provide a more convenient interface for doing this.

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioBusStart, ioBusStop, ioBusReadByte, ioBusReadLastByte, ioBusReadMessage,

ioBusSelectForRead ioBusSelectForWrite, ioBusWriteMessage

Example

#include <ctools.h> void main(void)

{ unsigned char data[2]; unsigned char ioBusAddress = 114;

request_resource(IO_SYSTEM);

ioBusStart();

{ ioBusWriteByte(data[0]); ioBusWriteByte(data[1]);

}

ioBusStop();

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

252

ioBusWriteMessage

Write Message to I

2

C Slave Device

Syntax

#include <ctools.h>

WRITESTATUS ioBusWriteMessage(unsigned address, unsigned numberBytes, unsigned char *message);

Description

The ioBusWriteMessage function writes a specified number of bytes to an I

2

C slave device.

The function issues the START condition, selects the device for writing, writes the specified number of bytes, and issues a STOP condition. If the slave fails to acknowledge the selection or any data written to it, the write is aborted immediately.

The function has three parameters: the address of the device; the number of bytes to write,

numberBytes; and a pointer to the buffer, message, containing the data.

The function returns the status of the write:

Value

WS_success

WS_selectFailed

WS_noAcknowledge

Description

write was successful slave could not be selected slave failed to acknowledge data

Notes

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioBusStart, ioBusStop, ioBusReadByte, ioBusReadLastByte, ioBusReadMessage,

ioBusSelectForRead ioBusSelectForWrite, ioBusWriteByte

Example

#include <ctools.h> void main(void)

{

unsigned ioBusAddress = 114;

request_resource(IO_SYSTEM);

/* Write a 10 byte message to I2C device */ status = ioBusWriteMessage(ioBusAddress, 10, message);

release_resource(IO_SYSTEM); if (status != WS_success)

{ fprintf(com1, "I/O error = %d\n\r", status);

}

}

TelePACE C Tools User and Reference Manual

May 9, 2007

253

ioClear

Turn Off all Outputs

Syntax

#include <ctools.h> void ioClear(void);

Description

The ioClear function turns off all outputs in the current Register Assignment as follows.

• analog outputs are set to 0;

• digital outputs are turned set to 0 (turned off).

If the Register Assignment is empty, all outputs are turned off for all possible I/O modules that exist under the fixed I/O hardware mapping of firmware versions 1.22 or older.

Also, all delayed digital I/O actions started by the pulse, pulse_train and timeout functions are always canceled.

Notes

Timers referenced by the pulse, pulse_train and timeout functions are set to 0. All other timers are not affected.

The IO_SYSTEM resource must be requested before calling this function.

TelePACE C Tools User and Reference Manual

May 9, 2007

254

ioDatabaseReset

Initialize I/O Database with Default Values

Syntax

#include <ctools.h> void ioDatabaseReset(void);

Description

The ioDatabaseReset function resets all I/O database values to their defaults:

• Configuration parameters are reset to default values. All registers assigned to configuration parameters through the Register Assignment are also reset to default values.

• All other registers are set to zero. I/O hardware assigned to these registers through the

Register Assignment are also set to zero.

• All forcing is removed.

• Locked variables are unlocked.

• Set all database locations to zero

• Clear real time clock alarm settings

• Clear serial port event counters

• Clear store and forward configuration

• Enable LED power by default and return to default state after 5 minutes

• Set Outputs on Stop settings to Hold

• Set 5904 HART modem configuration for all modems

• Set Modbus/TCP default configuration

• Write new default data to Flash

Notes

This function can be used to restore the controller to its default state. ioDatabaseReset has the same effect as selecting the Initialize Controller option from the Initialize command in the TelePACE program.

Use this function carefully as it erases any data stored in the I/O database.

The IO_SYSTEM resource must be requested before calling this function.

Example

#include <ctools.h> void main(void)

{

/* Power Up Initialization */

request_resource(IO_SYSTEM);

ioDatabaseReset();

release_resource(IO_SYSTEM);

}

/* ... the rest of the program */

TelePACE C Tools User and Reference Manual

May 9, 2007

255

ioRead16Din

Read 16 Digital Inputs into I/O Database

Syntax

#include <ctools.h> unsigned ioRead16Din(unsigned moduleAddress, unsigned startStatusRegister);

Description

The ioRead16Din function reads any 16 point Digital Input Module at the specified

moduleAddress. Data is read from all 16 digital inputs and copied to 16 consecutive status registers beginning at startStatusRegister.

The function returns FALSE if the moduleAddress or startStatusRegister is invalid or if an

I/O error has occurred; otherwise TRUE is returned.

The valid range for moduleAddress is 0 to 15. startStatusRegister is any valid Modbus status register between 10001 and (10000 + NUMSTATUS - 15).

Notes

Data is not copied to the I/O database for registers that are currently forced.

To read data from an I/O Module continuously, add the module to the Register Assignment.

Refer to the section I/O Database and Register Assignment for details.

This function is contained in the ctools.lib library. Load this library in you linker command

(.cmd) file as shown in the sample file appram.cmd in your ctools directory.

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioRead8Din

Example

This program displays the values of the 16 digital inputs read from a 16 point Digital Input

Module at module address 0.

#include <ctools.h> void main(void)

{

request_resource(IO_SYSTEM);

*/

/* Print data from I/O database */ for (reg = 10001; reg <= 10016; reg++)

{ fprintf(com1, "\n\r%d ", reg); putchar( dbase(MODBUS, reg) ? '1' :'0');

}

TelePACE C Tools User and Reference Manual

May 9, 2007

256

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

257

ioRead32Din

Read 32 Digital Inputs into I/O Database

Syntax

#include <ctools.h> unsigned ioRead32Din(

Description

The ioRead32Din function reads any 32 point Digital Input Module at the specified moduleAddress

. Data is read from all 32 digital inputs and copied to 32 consecutive status registers beginning at startStatusRegister.

The function returns FALSE if the moduleAddress or startStatusRegister is invalid or if an I/O error has occurred; otherwise TRUE is returned.

The valid range for moduleAddress is 0 to 15. startStatusRegister is any valid

Modbus status register between 10001 and (10001 + NUMSTATUS - 32).

Notes

Data is not copied to the I/O database for registers that are currently forced.

To read data from an I/O Module continuously, add the module to the Register Assignment.

Refer to the section I/O Database and Register Assignment for details.

This function is contained in the ctools.lib library. Load this library in you linker command (.cmd) file as shown in the sample file appram.cmd in your ctools directory.

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioRead8Din, ioRead16Din

Example

This program displays the values of the 32 digital inputs read from a 32 point Digital Input

Module at module address 0.

#include <ctools.h> void main(void)

{

request_resource(IO_SYSTEM);

/* Read data from module and write to I/O database */

/* Print data from I/O database */ fprintf(com1, "Register Value"); for (reg = 10001; reg <= 10032; reg++)

{

TelePACE C Tools User and Reference Manual

May 9, 2007

258

"\n\r%d reg); putchar( dbase(MODBUS, reg) ? '1' :'0');

}

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

259

ioRead4Ain

Read 4 Analog Inputs into I/O Database

Syntax

#include <ctools.h> unsigned ioRead4Ain(unsigned moduleAddress, unsigned startInputRegister);

Description

The ioRead4Ain function reads any 4 point Analog Input Module at the specified

moduleAddress. Data is read from all 4 analog inputs and copied to 4 consecutive input registers beginning at startInputRegister.

The function returns FALSE if the moduleAddress or startInputRegister is invalid or if an I/O error has occurred; otherwise TRUE is returned.

The valid range for moduleAddress is 0 to 15. startInputRegister is any valid Modbus input register between 30001 and (30000 + NUMINPUT - 3).

Notes

Data is not copied to the I/O database for registers that are currently forced.

To read data from an I/O Module continuously, add the module to the Register Assignment.

Refer to the section I/O Database and Register Assignment for details.

This function is contained in the ctools.lib library. Load this library in you linker command

(.cmd) file as shown in the sample file appram.cmd in your ctools directory.

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioRead8Ain

Example

This program displays the values of the 4 analog inputs read from a 4 point Analog Input

Module at module address 0.

#include <ctools.h> void main(void)

{

request_resource(IO_SYSTEM);

*/

/* Print data from I/O database */ for(reg = 30001; reg <= 30004; reg++)

{ fprintf(com1, "%d %d\n\r", reg, dbase(MODBUS, reg));

}

release_resource(IO_SYSTEM);

TelePACE C Tools User and Reference Manual

May 9, 2007

260

}

TelePACE C Tools User and Reference Manual

May 9, 2007

261

ioRead4Counter

Read 4 Counter Inputs into I/O Database

Syntax

#include <ctools.h> unsigned ioRead4Counter(unsigned moduleAddress, unsigned

startInputRegister);

Description

The ioRead4Counter function reads any 4 point Counter Input Module at the specified

moduleAddress. Data is read from all 4 counter inputs and copied to 8 consecutive input registers beginning at startInputRegister.

Each counter is a 32 bit number, stored in two input registers. The first register holds the least significant 16 bits of the counter. The second register holds the most significant 16 bits of the counter.

The maximum count is 4,294,967,295. Counters roll back to 0 when the maximum count is exceeded.

The function returns FALSE if the moduleAddress or startInputRegister is invalid or if an I/O error has occurred; otherwise TRUE is returned.

The valid range for moduleAddress is 0 to 15. startInputRegister is any valid Modbus input register between 30001 and (30000 + NUMINPUT - 7).

Notes

Data is not copied to the I/O database for registers that are currently forced.

To read data from an I/O Module continuously, add the module to the Register Assignment.

Refer to the section Overview of Functions for details.

This function is contained in the ctools.lib library. Load this library in you linker command

(.cmd) file as shown in the sample file appram.cmd in your ctools directory.

The IO_SYSTEM resource must be requested before calling this function.

Example

This program displays the values of the 4 counter inputs read from a 4 point Counter Input

Module at module address 0.

#include <ctools.h> void main(void)

{ unsigned counter, reg;

request_resource(IO_SYSTEM);

/* Read data from counter input module and write it to I/O database */

/* Print data from I/O database */ counter = 0;

TelePACE C Tools User and Reference Manual

May 9, 2007

262

for(reg = 30001; reg <= 30008; reg+=2)

{ value = dbase(MODBUS, reg) + fprintf(com1, "%d %ld\n\r", counter++, value);

}

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

263

ioRead4202Inputs

Read SCADASense 4202 DR Inputs into I/O Database

Syntax

#include <ctools.h> unsigned ioRead4202Inputs(

);

Description

The ioRead4202Inputs function reads the digital, counter, and analog inputs from the

SCADASense 4202 DR I/O. Data are read from 1 digital input and copied to 1 consecutive status registers beginning at startStatusRegister. Data is read from the analog input and copied to 1 input register beginning at startInputRegister. Data are read from the counter inputs and copied to 4 consecutive input registers beginning at startInputRegister + 1

. startStatusRegister

is any valid Modbus status register between 10001 and (10000

+ NUMSTATUS - 1)

. startInputRegister is any valid Modbus input register between

30001 and (30000 + NUMINPUT - 4).

The function returns FALSE if startStatusRegister or startInputRegister is invalid or if an I/O error has occurred; otherwise TRUE is returned.

Notes

When this function reads data from the transnmitter (controller), it also processes the receiver buffer for the com3 serial port. The com3 serial port is also continuously processed automatically. The additional service to the com3 receiver caused by this function does not affect the normal automatic operation of com3.

Data is not copied to the I/O database for registers that are currently forced.

To read data from an I/O Module continuously, add the module to the Register Assignment.

The IO_SYSTEM resource must be requested before calling this function.

Digital inputs can also be read with the readCounterInput function.

Counters can also be read with the readCounter function.

Analog inputs can also be read with the readInternalAD function.

See Also

ioWrite4202Outputs, readCounter, readCounterInput

Example

This program displays the values of the 1 digital input, 2 counter inputs and 1 analog input read from SCADASense 4202 DR I/O.

#include <ctools.h> void main(void)

{

TelePACE C Tools User and Reference Manual

May 9, 2007

264

request_resource(IO_SYSTEM);

/* Read 4202 DR inputs and write to I/O database */ ioRead4202Inputs (10001, 30001);

/* Print digital inputy */ fprintf(com2, "Register Value"); fprintf(com2, "\n\r%d ", 10001); putchar( dbase(MODBUS, 10001) ? '1' :'0');

/* print analog input */ fprintf(com2, "\n\r%d %d", reg, dbase(MODBUS, 30001));

/* print counter inputs */ counter = 0; for(reg = 30002; reg <= 30005; reg+=2)

{ value = dbase(MODBUS, reg) +

((long) dbase(MODBUS, reg+1)<<16); fprintf(com2, "%d %ld\n\r", counter++, value);

}

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

265

ioRead4202DSInputs

Read SCADASense 4202 DS Inputs into I/O Database

Syntax

#include <ctools.h> unsigned ioRead4202DSInputs(

);

Description

The ioRead4202DSInputs function reads the digital, counter, and analog inputs from the

SCADASense 4202 DS I/O. Data are read from 1 digital input and copied to 1 consecutive status registers beginning at startStatusRegister. Data is read from three analog inputs and copied to 3 input register beginning at startInputRegister. Data are read from the counter inputs and copied to 4 consecutive input registers beginning at startInputRegister + 4

. startStatusRegister

is any valid Modbus status register between 10001 and (10000

+ NUMSTATUS)

. startInputRegister

is any valid Modbus input register between 30001 and (30000 +

NUMINPUT - 6)

.

The function returns FALSE if startStatusRegister or startInputRegister is invalid or if an I/O error has occurred; otherwise TRUE is returned.

Notes

When this function reads data from the SCADASense 4202 DS I/O it also processes the receiver buffer for the com3 serial port. The com3 serial port is also continuously processed automatically. The additional service to the com3 receiver caused by this function does not affect the normal automatic operation of com3.

Data is not copied to the I/O database for registers that are currently forced.

To read data from an I/O Module continuously, add the module to the Register Assignment.

The IO_SYSTEM resource must be requested before calling this function.

The digital input can also be read with the readCounterInput function.

Counters can also be read with the readCounter function.

Analog inputs can also be read with the readInternalAD function.

See Also

ioWrite4202DSOutputs, readCounter, readCounterInput, readInternalAD

Example

This program displays the values of the digital input, 2 counter inputs and 3 analog inputs read from the SCADASense 4202 DS I/O.

#include <ctools.h>

TelePACE C Tools User and Reference Manual

May 9, 2007

266

void main(void)

{

request_resource(IO_SYSTEM);

/* Read 4202 DS inputs and write to I/O database */ ioRead4202DSInputs (10001, 30001);

/* Print digital input */ fprintf(com2, "Register Value"); fprintf(com2, "\n\r%d ", 10001); putchar( dbase(MODBUS, 10001) ? '1' :'0');

/* print analog inputs */ fprintf(com2, "\n\r%d fprintf(com2, "\n\r%d fprintf(com2, "\n\r%d

%d",30001,dbase(MODBUS, 30001));

%d",30002,dbase(MODBUS, 30002));

%d",30003,dbase(MODBUS, 30003));

/* print counter inputs */ counter = 0; for(reg = 30004; reg <= 30007; reg+=2)

{ value = dbase(MODBUS, reg) +

((long) dbase(MODBUS, reg+1)<<16); fprintf(com2, "%d %ld\n\r", counter++, value);

}

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

267

ioRead5505Inputs

Read 5505 Inputs into I/O Database

Syntax

#include <ctools.h>

UINT16 ioRead5505Inputs(

UINT16 startStatusRegister,

Description

The ioRead5505Inputs function reads the digital and analog inputs from the 5505 I/O. Data is read from all 16 digital inputs and copied to 16 consecutive status registers beginning at startStatusRegister

. Data is read from all 4 analog inputs and copied to 8 consecutive input registers in floating point format beginning at startInputRegister.

The function of the 16 digital inputs is described in the table below.

Point

Offset

0

Function

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

OFF = channel 0 RTD is good

ON = channel 0 RTD is open or PWR input is off

OFF = channel 0 data in range

ON = channel 0 data is out of range

OFF = channel 0 RTD is using 3-wire measurement

ON = channel 0 RTD is using 4-wire measurement reserved for future use

OFF = channel 1 RTD is good

ON = channel 1 RTD is open or PWR input is off

OFF = channel 1 data in range

ON = channel 1 data is out of range

OFF = channel 1 RTD is using 3-wire measurement

ON = channel 1 RTD is using 4-wire measurement reserved for future use

OFF = channel 2 RTD is good

ON = channel 2 RTD is open or PWR input is off

OFF = channel 2 data in range

ON = channel 2 data is out of range

OFF = channel 2 RTD is using 3-wire measurement

ON = channel 2 RTD is using 4-wire measurement reserved for future use

OFF = channel 3 RTD is good

ON = channel 3 RTD is open or PWR input is off

OFF = channel 3 data in range

ON = channel 3 data is out of range

OFF = channel 3 RTD is using 3-wire measurement

ON = channel 3 RTD is using 4-wire measurement reserved for future use

The function returns FALSE if the moduleAddress, startStatusRegister or startInputRegister

is invalid or if an I/O error has occurred; otherwise TRUE is returned.

TelePACE C Tools User and Reference Manual

May 9, 2007

268

moduleAddress

is the address of the 5505 module. Valid values are 0 to 15. startStatusRegister

is any valid Modbus status register between 10001 and (10001 +

NUMSTATUS

- 15). startInputRegister

is any valid Modbus input register between 30001 and (30001 +

NUMINPUT

- 7).

Notes

Data is not copied to the I/O database for registers that are currently forced.

To read data from an I/O Module continuously, add the module to the Register Assignment.

The IO_SYSTEM resource must be requested before calling this function.

Example

This program displays the values of the 16 digital inputs and 4 analog inputs read from 5505

I/O at module address 3.

#include <ctools.h> void main(void)

{ typedef union

{ float floatValue;

} UF_UNION;

UF_UNION value;

request_resource(IO_SYSTEM);

/* Read data from 5505 I/O into I/O database */ ioRead5505Inputs(3, 10001, 30001);

/* Print data from I/O database */ fprintf(com1, "Register Value"); for (reg = 10001; reg <= 10016; reg++)

{

"\n\r%d reg); putchar(dbase(MODBUS, reg) ? '1' :'0');

} for(reg = 30001; reg <= 30008; reg+2)

{ value.intValue[1] = dbase(MODBUS, reg); value.intValue[0] = dbase(MODBUS, reg + 1); fprintf(com1, "\n\r%d

}

%d", reg, value.floatValue);

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

269

ioRead5506Inputs

Read 5506 Inputs into I/O Database

Syntax

#include <ctools.h>

UINT16 ioRead5506Inputs(

UINT16 startStatusRegister,

Description

The ioRead5506Inputs function reads the digital and analog inputs from the 5506 I/O. Data is read from all 8 digital inputs and copied to 8 consecutive status registers beginning at startStatusRegister

. Data is read from all 8 analog inputs and copied to 8 consecutive input registers beginning at startInputRegister.

The function returns FALSE if the moduleAddress, startStatusRegister or startInputRegister

is invalid or if an I/O error has occurred; otherwise TRUE is returned. moduleAddress

is the address of the 5506 module. Valid values are 0 to 15. startStatusRegister

is any valid Modbus status register between 10001 and (10001 +

NUMSTATUS

- 7). startInputRegister

is any valid Modbus input register between 30001 and (30001 +

NUMINPUT

- 7).

Notes

Data is not copied to the I/O database for registers that are currently forced.

To read data from an I/O Module continuously, add the module to the Register Assignment.

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioWrite5606Outputs

Example

This program displays the values of the 8 digital inputs and 8 analog inputs read from 5506

I/O at module address 3.

#include <ctools.h> void main(void)

{

request_resource(IO_SYSTEM);

/* Read data from 5506 I/O into I/O database */ ioRead5506Inputs(3, 10001, 30001);

TelePACE C Tools User and Reference Manual

May 9, 2007

270

/* Print data from I/O database */ fprintf(com1, "Register Value"); for (reg = 10001; reg <= 10008; reg++)

{

"\n\r%d reg); putchar(dbase(MODBUS, reg) ? '1' :'0');

} for(reg = 30001; reg <= 30008; reg++)

{

}

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

271

ioRead5601Inputs

Read 5601 Inputs into I/O Database

Syntax

#include <ctools.h> unsigned ioRead5601Inputs(unsigned startStatusRegister, unsigned

startInputRegister);

Description

The ioRead5601Inputs function reads the digital and analog inputs from a 5601 I/O Module.

Data is read from all 16 digital inputs and copied to 16 consecutive status registers beginning at startStatusRegister. Data is read from all 8 analog inputs and copied to 8 consecutive input registers beginning at startInputRegister.

The function returns FALSE if startStatusRegister or startInputRegister is invalid or if an I/O error has occurred; otherwise TRUE is returned.

startStatusRegister is any valid Modbus status register between 10001 and (10000 +

NUMSTATUS - 15). startInputRegister is any valid Modbus input register between 30001 and (30000 + NUMINPUT - 7).

Notes

Note that when this function reads data from the 5601 it also processes the receiver buffer for the com3 serial port. If the controller type is a SCADAPack or SCADAPack PLUS, the com3 serial port is also continuously processed automatically.

The additional service to the com3 receiver caused by this function does not affect the normal automatic operation of com3.

Data is not copied to the I/O database for registers that are currently forced.

To read data from an I/O Module continuously, add the module to the Register Assignment.

Refer to the section I/O Database and Register Assignment for details.

This function is contained in the ctools.lib library. Load this library in you linker command

(.cmd) file as shown in the sample file appram.cmd in your ctools directory.

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioWrite5601Outputs

Example

This program displays the values of the 16 digital inputs and 8 analog inputs read from a

5601 I/O Module.

#include <ctools.h> void main(void)

{

request_resource(IO_SYSTEM);

/* Read data from 5601 I/O module and write it

TelePACE C Tools User and Reference Manual

May 9, 2007

272

to I/O database */

/* Print data from I/O database */ for (reg = 10001; reg <= 10016; reg++)

{ fprintf(com1, "\n\r%d ", reg); putchar( dbase(MODBUS, reg) ? '1' :'0');

} for(reg = 30001; reg <= 30008; reg++)

{ fprintf(com1, "\n\r%d %d", reg,

}

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

273

ioRead5602Inputs

Read 5602 Inputs into I/O Database

Syntax

#include <ctools.h> unsigned ioRead5602Inputs(unsigned startStatusRegister, unsigned

startInputRegister);

Description

The ioRead5602Inputs function reads the inputs from a 5602 I/O Module as digital or analog inputs. Data is read from all 5 analog inputs and copied to 5 consecutive input registers beginning at startInputRegister. The same 5 analog inputs are also read as 5 digital inputs and copied to 5 consecutive status registers beginning at startStatusRegister.

A digital input is ON if the corresponding filtered analog input value is greater than or equal to 20% of its full scale value, otherwise it is OFF. Analog input 0 to 4 correspond to digital inputs 0 to 4.

The function returns FALSE if startStatusRegister or startInputRegister is invalid or if an I/O error has occurred; otherwise TRUE is returned.

startStatusRegister is any valid Modbus status register between 10001 and (10000 +

NUMSTATUS - 4). startInputRegister is any valid Modbus input register between 30001 and

(30000 + NUMINPUT - 4).

Notes

Note that when this function reads data from the 5602 it also processes the receiver buffer for the com4 serial port. If the controller type is a SCADAPack LIGHT or SCADAPack PLUS, the com4 serial port is also continuously processed automatically.

The additional service to the com4 receiver caused by this function does not affect the normal automatic operation of com4.

Data is not copied to the I/O database for registers that are currently forced.

To read data from an I/O Module continuously, add the module to the Register Assignment.

Refer to the section I/O Database and Register Assignment for details.

This function is contained in the ctools.lib library. Load this library in you linker command

(.cmd) file as shown in the sample file appram.cmd in your ctools directory.

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioWrite5602Outputs

Example

This program displays the values of the 5 inputs read from a 5602 I/O Module as both digital and analog inputs.

#include <ctools.h> void main(void)

{

TelePACE C Tools User and Reference Manual

May 9, 2007

274

request_resource(IO_SYSTEM);

/* Read data from 5602 I/O module and write it to I/O database */

/* Print data from I/O database */ for (reg = 10001; reg <= 10005; reg++)

{ fprintf(com1, "\n\r%d ", reg); putchar( dbase(MODBUS, reg) ? '1' :'0');

} for(reg = 30001; reg <= 30005; reg++)

{ fprintf(com1, "\n\r%d %d", reg,

}

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

275

ioRead5604Inputs

Read 5604 Inputs into I/O Database

Syntax

#include <ctools.h> unsigned ioRead5604Inputs(

Description

The ioRead5604Inputs function reads the digital and analog inputs from the 5604 I/O.

Data is read from all 35 digital inputs and copied to 35 consecutive status registers beginning at startStatusRegister. Data is read from all 10 analog inputs and copied to

10 consecutive input registers beginning at startInputRegister.

The function returns FALSE if startStatusRegister or startInputRegister is invalid or if an I/O error has occurred; otherwise TRUE is returned. startStatusRegister

is any valid Modbus status register between 10001 and (10001 +

NUMSTATUS

- 35). startInputRegister

is any valid Modbus input register between 30001 and (30001 +

NUMINPUT

- 10).

Notes

When this function reads data from the 5604 I/O it also processes the receiver buffer for the com3 serial port. The com3 serial port is also continuously processed automatically. The additional service to the com3 receiver caused by this function does not affect the normal automatic operation of com3.

Data is not copied to the I/O database for registers that are currently forced.

To read data from an I/O Module continuously, add the module to the Register Assignment.

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioWrite5604Outputs

Example

This program displays the values of the 35 digital inputs and 10 analog inputs read from

5604 I/O.

#include <ctools.h> void main(void)

{

request_resource(IO_SYSTEM);

/* Read data from 5604 I/O into I/O database */

TelePACE C Tools User and Reference Manual

May 9, 2007

276

/* Print data from I/O database */ fprintf(com1, "Register Value"); for (reg = 10001; reg <= 10035; reg++)

{

"\n\r%d reg); putchar(dbase(MODBUS, reg) ? '1' :'0');

} for(reg = 30001; reg <= 30010; reg++)

{

}

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

277

ioRead5606Inputs

Read 5606 Inputs into I/O Database

Syntax

#include <ctools.h>

UINT16 ioRead5606Inputs(

UINT16 startStatusRegister,

Description

The ioRead5606Inputs function reads the digital and analog inputs from the 5606 I/O. Data is read from all 40 digital inputs and copied to 40 consecutive status registers beginning at startStatusRegister

. Data is read from all 8 analog inputs and copied to 8 consecutive input registers beginning at startInputRegister.

The function returns FALSE if the moduleAddress, startStatusRegister or startInputRegister

is invalid or if an I/O error has occurred; otherwise TRUE is returned. moduleAddress

is the address of the 5606 module. Valid values are 0 to 7. startStatusRegister

is any valid Modbus status register between 10001 and (10001 +

NUMSTATUS

- 39). startInputRegister

is any valid Modbus input register between 30001 and (30001 +

NUMINPUT

- 7).

Notes

Data is not copied to the I/O database for registers that are currently forced.

To read data from an I/O Module continuously, add the module to the Register Assignment.

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioWrite5606Outputs

Example

This program displays the values of the 40 digital inputs and 8 analog inputs read from 5606

I/O at module address 3.

#include <ctools.h> void main(void)

{

request_resource(IO_SYSTEM);

/* Read data from 5606 I/O into I/O database */ ioRead5606Inputs(3, 10001, 30001);

TelePACE C Tools User and Reference Manual

May 9, 2007

278

/* Print data from I/O database */ fprintf(com1, "Register Value"); for (reg = 10001; reg <= 10040; reg++)

{

"\n\r%d reg); putchar(dbase(MODBUS, reg) ? '1' :'0');

} for(reg = 30001; reg <= 30008; reg++)

{

}

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

279

ioRead8Ain

Read 8 Analog Inputs into I/O Database

Syntax

#include <ctools.h> unsigned ioRead8Ain(unsigned moduleAddress, unsigned startInputRegister);

Description

The ioRead8Ain function reads any 8 point Analog Input Module at the specified

moduleAddress. Data is read from all 8 analog inputs and copied to 8 consecutive input registers beginning at startInputRegister.

The function returns FALSE if the moduleAddress or startInputRegister is invalid or if an I/O error has occurred; otherwise TRUE is returned.

The valid range for moduleAddress is 0 to 15. startInputRegister is any valid Modbus input register between 30001 and (30000 + NUMINPUT - 7).

Notes

Data is not copied to the I/O database for registers that are currently forced.

To read data from an I/O Module continuously, add the module to the Register Assignment.

Refer to the section I/O Database and Register Assignment for details.

This function is contained in the ctools.lib library. Load this library in you linker command

(.cmd) file as shown in the sample file appram.cmd in your ctools directory.

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioRead4Ain

Example

This program displays the values of the 8 analog inputs read from an 8 point Analog Input

Module at module address 0.

#include <ctools.h> void main(void)

{

request_resource(IO_SYSTEM);

*/

/* Print data from I/O database */ for(reg = 30001; reg <= 30008; reg++)

{ fprintf(com1, "%d %d\n\r", reg, dbase(MODBUS, reg));

}

release_resource(IO_SYSTEM);

TelePACE C Tools User and Reference Manual

May 9, 2007

280

}

TelePACE C Tools User and Reference Manual

May 9, 2007

281

ioRead8Din

Read 8 Digital Inputs into I/O Database

Syntax

#include <ctools.h> unsigned ioRead8Din(unsigned moduleAddress, unsigned startStatusRegister);

Description

The ioRead8Din function reads any 8 point Digital Input Module at the specified

moduleAddress. Data is read from all 8 digital inputs and copied to 8 consecutive status registers beginning at startStatusRegister.

The function returns FALSE if the moduleAddress or startStatusRegister is invalid or if an

I/O error has occurred; otherwise TRUE is returned.

The valid range for moduleAddress is 0 to 15. startStatusRegister is any valid Modbus status register between 10001 and (10000 + NUMSTATUS - 7).

Notes

Data is not copied to the I/O database for registers that are currently forced.

To read data from an I/O Module continuously, add the module to the Register Assignment.

Refer to the section I/O Database and Register Assignment for details.

This function is contained in the ctools.lib library. Load this library in you linker command

(.cmd) file as shown in the sample file appram.cmd in your ctools directory.

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioRead16Din

Example

This program displays the values of the 8 digital inputs read from an 8 point Digital Input

Module at module address 0.

#include <ctools.h> void main(void)

{

request_resource(IO_SYSTEM);

*/

/* For each digital input on the module */ for (reg = 10001; reg <= 10008; reg++)

{ fprintf(com1, "\n\r%d ", reg); putchar( dbase(MODBUS, reg) ? '1' :'0');

}

TelePACE C Tools User and Reference Manual

May 9, 2007

282

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

283

ioReadLPInputs

Read SCADAPack LP Inputs into I/O Database

Syntax

#include <ctools.h> unsigned ioReadLPInputs (unsigned startStatusRegister, unsigned

startInputRegister);

Description

The ioReadLPInputs function reads the digital and analog inputs from the SCADAPack

LP I/O. Data is read from all 16 digital inputs and copied to 16 consecutive status registers beginning at startStatusRegister. Data is read from all 8 analog inputs and copied to 8 consecutive input registers beginning at startInputRegister.

The function returns FALSE if startStatusRegister or startInputRegister is invalid or if an I/O error has occurred; otherwise TRUE is returned. startStatusRegister

is any valid Modbus status register between 10001 and (10000 +

NUMSTATUS

- 15). startInputRegister is any valid Modbus input register between

30001 and (30000 + NUMINPUT - 7).

Notes

When this function reads data from the SCADAPack LP I/O it also processes the receiver buffer for the com3 serial port. The com3 serial port is also continuously processed automatically. The additional service to the com3 receiver caused by this function does not affect the normal automatic operation of com3.

Data is not copied to the I/O database for registers that are currently forced.

To read data from an I/O Module continuously, add the module to the Register Assignment.

The IO_SYSTEM resource must be requested before calling this function.

Example

This program displays the values of the 16 digital inputs and 8 analog inputs read from

SCADAPack LP I/O.

#include <ctools.h> void main(void)

{

request_resource(IO_SYSTEM);

/* Read data from LP I/O and write it to I/O database */ ioReadLPInputs (10001, 30001);

/* Print data from I/O database */ fprintf(com1, "Register Value"); for (reg = 10001; reg <= 10016; reg++)

{

"\n\r%d reg); putchar( dbase(MODBUS, reg) ? '1' :'0');

TelePACE C Tools User and Reference Manual

May 9, 2007

284

} for(reg = 30001; reg <= 30008; reg++)

{

}

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

285

ioReadSP100Inputs

Read SCADAPack 100 Inputs into I/O Database

Syntax

#include <ctools.h> unsigned ioReadSP100Inputs(unsigned startStatusRegister, unsigned

startInputRegister);

Description

The ioReadSP100Inputs function reads the digital and analog inputs from the

SCADAPack 100 I/O. Data is read from all 6 digital inputs and copied to 6 consecutive status registers beginning at startStatusRegister. Data is read from all 6 analog inputs and one counter input, and copied to 8 consecutive input registers beginning at startInputRegister

.

The function returns FALSE if startStatusRegister or startInputRegister is invalid or if an I/O error has occurred; otherwise TRUE is returned. startStatusRegister

is any valid Modbus status register between 10001 and (10000 +

NUMSTATUS

- 5). startInputRegister is any valid Modbus input register between 30001 and (30000 + NUMINPUT - 7).

Notes

Data is not copied to the I/O database for registers that are currently forced.

Data from the four external analog inputs is copied to the first four input registers.

Data from the temperature sensor is copied to the fifth input register.

Data from the battery voltage sensor is copied to the sixth input register.

Data from the counter input is copied to the seventh and eighth input registers.

To read data from an I/O Module continuously, add the module to the Register Assignment.

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioWriteSP100Outputs

Example

This program displays the values of the 6 digital inputs, 6 analog inputs, and the counter input read from SCADAPack 100 I/O.

#include <ctools.h> void main(void)

{ unsigned long count;

request_resource(IO_SYSTEM);

/* Read data from I/O and write it to I/O database */

TelePACE C Tools User and Reference Manual

May 9, 2007

286

/* Print digital data from I/O database */ for (reg = 10001; reg <= 10006; reg++)

{ fprintf(com1, "Register %d = %d\r\n", reg,

}

/* Print analog data from I/O database */ for(reg = 30001; reg <= 30006; reg++)

{ fprintf(com1, "Regsiter %d = %d\n\r", reg,

}

/* Print counter data from I/O database */ count = dbase(MODBUS, 30006); count += ((unsigned long) dbase(MODBUS, reg)) << 16; fprintf(com1, "Registers 30006 & 30007 = %ul\r\n", reg,

count);

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

287

ioRefresh

Update Outputs with Internal Data

Syntax

#include <ctools.h> void ioRefresh(void);

Description

The ioRefresh function resets devices on the 5000 series I/O bus. Input channels are scanned to update their values from the I/O hardware. Output channels are scanned to write their values from output tables in memory.

Notes

This function is normally only used by the sleep function to restore output states when the controller wakes.

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioClear, ioReset

TelePACE C Tools User and Reference Manual

May 9, 2007

288

ioReset

Reset 5000 Series I/O Modules

Syntax

#include <ctools.h> void ioReset(unsigned state);

Description

The ioReset function sets the state of the 5000 Series I/O bus reset signal. state may be

TRUE or FALSE.

The reset signal restarts all devices on the 5000 Series I/O bus. Output modules clear all their output points. Input modules restart their input scanning. All modules remain in the reset state until the reset signal is set to FALSE.

Notes

Do not leave the reset signal in the TRUE state. This will disable I/O.

The ioClear function provides a more effective method of resetting the I/O system.

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioClear

TelePACE C Tools User and Reference Manual

May 9, 2007

289

ioWrite16Dout

Write to 16 Digital Outputs from I/O Database

Syntax

#include <ctools.h> unsigned ioWrite16Dout(unsigned moduleAddress, unsigned startCoilRegister);

Description

The ioWrite16Dout function writes data to any 16 point Digital Output Module at the specified moduleAddress. Data is read from 16 consecutive coil registers beginning at

startCoilRegister, and written to the 16 digital outputs.

The function returns FALSE if the moduleAddress or startCoilRegister is invalid or if an I/O error has occurred; otherwise TRUE is returned.

The valid range for moduleAddress is 0 to 15. startCoilRegister is any valid Modbus coil register between 00001 and (NUMCOIL - 15).

Notes

To write data to an I/O Module continuously, add the module to the Register Assignment.

Refer to the section Overview of Functions for details.

This function is contained in the ctools.lib library. Load this library in you linker command

(.cmd) file as shown in the sample file appram.cmd in your ctools directory.

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioWrite8Dout

Example

This program turns ON all 16 digital outputs of a 16 point Digital Output Module at module address 0.

#include <ctools.h> void main(void)

{

request_resource(IO_SYSTEM);

/* Write data to I/O database */ for (reg = 1; reg <= 16; reg++)

{ setdbase(MODBUS, reg, 1);

}

/* Write data from I/O database to digital output module */

release_resource(IO_SYSTEM);

TelePACE C Tools User and Reference Manual

May 9, 2007

290

}

TelePACE C Tools User and Reference Manual

May 9, 2007

291

ioWrite32Dout

Write to 32 Digital Outputs from I/O Database

Syntax

#include <ctools.h> unsigned ioWrite32Dout(

Description

The ioWrite32Dout function writes data to any 32-point Digital Output Module at the specified moduleAddress. Data is read from 32 consecutive coil registers beginning at startCoilRegister

, and written to the 32 digital outputs.

The function returns FALSE if the moduleAddress or startCoilRegister is invalid or if an I/O error has occurred; otherwise TRUE is returned.

The valid range for moduleAddress is 0 to 15. startCoilRegister is any valid Modbus coil register between 00001 and (NUMCOIL - 31).

Notes

To write data to an I/O Module continuously, add the module to the Register Assignment.

This function is contained in the ctools.lib library. Load this library in you linker command (.cmd) file as shown in the sample file appram.cmd in your ctools directory.

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioWrite8Dout, ioWrite16Dout

Example

This program turns ON all 32 digital outputs of a 32 point Digital Output Module at module address 0.

#include <ctools.h> void main(void)

{

request_resource(IO_SYSTEM);

/* Write data to I/O database */ for (reg = 1; reg <= 32; reg++)

{

setdbase(MODBUS, 1);

}

/* Write data from I/O database to digital output module */

TelePACE C Tools User and Reference Manual

May 9, 2007

292

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

293

ioWrite8Dout

Write to 8 Digital Outputs from I/O Database

Syntax

#include <iomodule.h> unsigned ioWrite8Dout(unsigned moduleAddress, unsigned startCoilRegister);

Description

The ioWrite8Dout function writes data to any 8 point Digital Output Module at the specified

moduleAddress. Data is read from 8 consecutive coil registers beginning at

startCoilRegister, and written to the 8 digital outputs.

The function returns FALSE if the moduleAddress or startCoilRegister is invalid or if an I/O error has occurred; otherwise TRUE is returned.

The valid range for moduleAddress is 0 to 15. startCoilRegister is any valid Modbus coil register between 00001 and (NUMCOIL - 7).

Notes

To write data to an I/O Module continuously, add the module to the Register Assignment.

Refer to the section Overview of Functions for details.

This function is contained in the ctools.lib library. Load this library in you linker command

(.cmd) file as shown in the sample file appram.cmd in your ctools directory.

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioWrite16Dout

Example

This program turns ON all 8 digital outputs of an 8 point Digital Output Module at module address 0.

#include <ctools.h> void main(void)

{

request_resource(IO_SYSTEM);

/* Write data to I/O database */ for (reg = 1; reg <= 8; reg++)

{ setdbase(MODBUS, reg, 1);

}

/* Write data from I/O database to digital output module */

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

294

ioWrite2Aout

Write to 2 Analog Outputs from I/O Database

Syntax

#include <ctools.h> unsigned ioWrite2Aout(unsigned moduleAddress, unsigned

startHoldingRegister);

Description

The ioWrite2Aout function writes data to any 2 point Analog Output Module at the specified

moduleAddress. Data is read from 2 consecutive holding registers beginning at

startHoldingRegister, and written to the 2 analog outputs.

The function returns FALSE if the moduleAddress or startHoldingRegister is invalid or if an

I/O error has occurred; otherwise TRUE is returned.

The valid range for moduleAddress is 0 to 15. startHoldingRegister is any valid Modbus holding register between 40001 and (40000 + NUMHOLDING - 1).

Notes

To write data to an I/O Module continuously, add the module to the Register Assignment.

Ref er to the section Overview of F unctions for details.

This function is contained in the ctools.lib library. Load this library in you linker command

(.cmd) file as shown in the sample file appram.cmd in your ctools directory.

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioWrite4Aout, ioWrite5303Aout

Example

This program sets both analog outputs to half scale on a 2 point Analog Output Module at module address 0.

#include <ctools.h> void main(void)

{

request_resource(IO_SYSTEM);

/* Write data to I/O database */ setdbase(MODBUS, 40001, 16384); setdbase(MODBUS, 40002, 16384);

/* Write data from I/O database to analog output module */

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

295

ioWrite4Aout

Write to 4 Analog Outputs from I/O Database

Syntax

#include <ctools.h> unsigned ioWrite4Aout(unsigned moduleAddress, unsigned

startHoldingRegister);

Description

The ioWrite4Aout function writes data to any 4 point Analog Output Module at the specified

moduleAddress. Data is read from 4 consecutive holding registers beginning at

startHoldingRegister, and written to the 4 analog outputs.

The function returns FALSE if the moduleAddress or startHoldingRegister is invalid or if an

I/O error has occurred; otherwise TRUE is returned.

The valid range for moduleAddress is 0 to 15. startHoldingRegister is any valid Modbus holding register between 40001 and (40000 + NUMHOLDING - 3).

Notes

To write data to an I/O Module continuously, add the module to the Register Assignment.

Refer to the section Overview of Functions for details.

This function is contained in the ctools.lib library. Load this library in you linker command

(.cmd) file as shown in the sample file appram.cmd in your ctools directory.

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioWrite2Aout, ioWrite5303Aout

Example

This program sets all 4 analog outputs to half scale on a 4 point Analog Output Module at module address 0.

#include <ctools.h> void main(void)

{

request_resource(IO_SYSTEM);

/* Write data to I/O database */ for (reg = 40001; reg <= 40004; reg++)

{ setdbase(MODBUS, reg, 16384);

}

/* Write data from I/O database to analog output module */

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

296

ioWrite4AoutChecksum

Write to 4 Point Analog Output Module with Checksum

Syntax

#include <ctools.h>

UINT16 ioWrite4AoutChecksum(

UINT16 moduleAddress,

)

Description

The ioWrite4AoutChecksum function writes data to a 4-point analog output module with checksum support. Output data comes from the I/O database. The function can be used with

5304 analog output modules. Use the isaWrite4Aout function for all other analog output modules.

The function has two parameters.

• moduleAddress is the address of the module. The valid range is 0 to 15.

• Data are read from 4 consecutive holding registers and written to 4 analog outputs. startHoldingRegister

is any valid Modbus holding register between 40001 and

(40001 + NUMHOLDING - 4).

The function returns FALSE if the moduleAddress or startHoldingRegister is invalid, or if an I/O error occurs; otherwise TRUE is returned.

Notes

The IO_SYSTEM resource must be requested before calling this function.

This function is contained in the ctools.lib library. Load this library in you linker command (.cmd) file as shown in the sample file appram.cmd in your ctools directory.

To write data to an I/O Module continuously, add the module to the Register Assignment.

See Also

ioWrite2Aout, ioWrite4Aout, ioWrite5303Aout

Example

This program sets all 4 analog outputs to half scale on a 5304 Analog Output Module at module at address 0.

#include <ctools.h> void main(void)

{

request_resource(IO_SYSTEM);

/* Write data to I/O database */ for (reg = 40001; reg <= 40004; reg++)

{

setdbase(MODBUS, 16384);

TelePACE C Tools User and Reference Manual

May 9, 2007

297

}

/* Write I/O database to 5304 analog output module */

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

298

ioWrite4202Outputs

Write to SCADASense 4202 DR Outputs from I/O Database

Syntax

#include <ctools.h> unsigned ioWrite4202Outputs(

);

Description

The ioWrite4202Outputs function writes data to the analog output of the SCADASense

4202 DR I/O. Analog data is read from 1 holding register beginning at startHoldingRegister

and written to the analog output. startHoldingRegister

is any valid Modbus holding register between 40001 and (4000 +

NUMHOLDING

).

The function returns FALSE if startHoldingRegister is invalid, or if an I/O error has occurred; otherwise TRUE is returned.

Notes

When this function writes data to the SCADASense 4202 DR I/O it also processes the transmit buffer for the com3 serial port. The com3 serial port is also continuously processed automatically. The additional service to the com3 receiver caused by this function does not affect the normal automatic operation of com3.

To write data to an I/O Module continuously, add the module to the Register Assignment.

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioRead4202Inputs, ioWrite4202OutputsEx

Example

This program sets the analog output to full scale.

#include <ctools.h> void main(void)

{

request_resource(IO_SYSTEM);

/* Write analog data to I/O database */ setdbase(MODBUS, 40001, 32767);

/* Write data from I/O database to 4202 DR output */

ioWrite4202Outputs(40001);

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

299

ioWrite4202OutputsEx

Write to SCADASense 4202 DR with Extended Outputs, from I/O Database

Syntax

#include <ctools.h> unsigned ioWrite4202OutputsEx(

);

Description

The ioWrite4202OutputsEx function writes data to the outputs of the SCADASense

4202 DR with Extended I/O (digital output). Digital data is read from one coil register starting at startCoilRegister and written to the digital output. Analog data is read from 1 holding register beginning at startHoldingRegister and written to the analog output. startCoilRegister

is any valid Modbus coil register between 1 and (NUMCOIL). startHoldingRegister

is any valid Modbus holding register between 40001 and (4000 +

NUMHOLDING

).

The function returns FALSE if startCoilRegister or startHoldingRegister are invalid, or if an I/O error has occurred; otherwise TRUE is returned.

Notes

When this function writes data to the SCADASense 4202 DR I/O it also processes the transmit buffer for the com3 serial port. The com3 serial port is also continuously processed automatically. The additional service to the com3 receiver caused by this function does not affect the normal automatic operation of com3.

To write data to an I/O Module continuously, add the module to the Register Assignment.

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioRead4202Inputs

Example

This program sets the analog output to full scale and turns on the digital output.

#include <ctools.h> void main(void)

{

request_resource(IO_SYSTEM);

/* Write output data to I/O database */ setdbase(MODBUS, 1, 1); setdbase(MODBUS, 40001, 32767);

/* Write data from I/O database to 4202 DR outputs */

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

300

ioWrite4202DSOutputs

Write to SCADASense 4202 DS Outputs from I/O Database

Syntax

#include <ctools.h> unsigned ioWrite4202DSOutputs(

);

Description

The ioWrite4202DSOutputs function writes data to the outputs of the SCADASense 4202 DS

I/O module. Digital data is read from two coil registers starting at startCoilRegister and written to the digital outputs. startCoilRegister

is any valid Modbus coil register between 1 and (NUMCOIL - 1).

The function returns FALSE if startCoilRegister is invalid, or if an I/O error has occurred; otherwise TRUE is returned.

Notes

When this function writes data to the SCADASense 4202 DS I/O it also processes the transmit buffer for the com3 serial port. The com3 serial port is also continuously processed automatically. The additional service to the com3 receiver caused by this function does not affect the normal automatic operation of com3.

To write data to an I/O Module continuously, add the module to the Register Assignment.

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioRead4202DSInputs

Example

This program turns on the digital outputs.

#include <ctools.h> void main(void)

{

request_resource(IO_SYSTEM);

/* Write output data to I/O database */ setdbase(MODBUS, 1, 1); setdbase(MODBUS, 2, 1);

/* Write data from I/O database to 4202 DS outputs */

ioWrite4202DSOutputs(1);

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

301

ioWrite5303Aout

Write to 5303 Analog Outputs from I/O Database

Syntax

#include <ctools.h> unsigned ioWrite5303Aout(unsigned startHoldingRegister);

Description

The ioWrite5303Aout function writes data to the 2 points on a 5303 SCADAPack Analog

Output Module. Data is read from 2 consecutive holding registers beginning at

startHoldingRegister, and written to the 2 analog outputs.

The function returns FALSE if startHoldingRegister is invalid or if an I/O error has occurred; otherwise TRUE is returned.

startHoldingRegister is any valid Modbus holding register between 40001 and (40000 +

NUMHOLDING - 1).

Notes

To write data to an I/O Module continuously, add the module to the Register Assignment.

Refer to the section I/O Database and Register Assignment for details.

This function is contained in the ctools.lib library. Load this library in you linker command

(.cmd) file as shown in the sample file appram.cmd in your ctools directory.

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioWrite2Aout, ioWrite5303Aout

Example

This program sets both analog outputs to half scale on a 5303 Analog Output Module.

#include <ctools.h> void main(void)

{

request_resource(IO_SYSTEM);

/* Write data to I/O database */ setdbase(MODBUS, 40001, 16384); setdbase(MODBUS, 40002, 16384);

/* Write data from I/O database to analog output module */

ioWrite5303Aout(40001);

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

302

ioWrite5505Outputs

Write to 5505 Configuration from I/O Database

Syntax

#include <ctools.h>

UINT16 ioWrite5505Outputs(

);

Description

The ioWrite5505Outputs function writes configuration data to the 5505 I/O module.

The function returns FALSE if moduleAddress is invalid, or if an I/O error has occurred; otherwise TRUE is returned. moduleAddress

is the address of the 5505 module. Valid values are 0 to 15. inputType

is an array of 4 values indicating the input range for the corresponding analog input. Valid values are

• 0 = RTD in deg Celsius

• 1 = RTD in deg Fahrenheit

• 2 = RTD in deg Kelvin

• 3 = resistance measurement in ohms. inputFilter

is the analog input filter setting. Valid values are.

• 0 = 0.5 s

• 1 = 1 s

• 2 = 2 s

• 3 = 4 s

Notes

To write data to an I/O Module continuously, add the module to the Register Assignment.

The IO_SYSTEM resource must be requested before calling this function.

Example

This program writes configuration data to a 5505 I/O module at module address 5.

#include <ctools.h> void main(void)

{

request_resource(IO_SYSTEM);

/* set the input types */ for (index = 0; index < 4; index++)

TelePACE C Tools User and Reference Manual

May 9, 2007

303

{ inputType[index] = 1; // RTD in deg F

}

/* set filter */ inputFilter = 3; // maximum filter

/* Write configuration data to 5505 I/O module */ ioWrite5505Outputs(5, inputType, inputFilter);

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

304

ioWrite5506Outputs

Write to 5506 Configuration from I/O Database

Syntax

#include <ctools.h>

UINT16 ioWrite5506Outputs(

);

Description

The ioWrite5506Outputs function writes configuration data to the 5506 I/O module.

The function returns FALSE if moduleAddress is invalid, or if an I/O error has occurred; otherwise TRUE is returned. moduleAddress

is the address of the 5506 module. Valid values are 0 to 15. inputType

is an array of 8 values indicating the input range for the corresponding analog input. Valid values are

• 0 = 0 to 5 V

• 1 = 1 to 5 V

• 2 = 0 to 20 mA

• 3 = 4 to 20 mA. inputFilter

is the analog input filter setting. Valid values are.

• 0 = 3 Hz

• 1 = 6 Hz

• 2 = 11 Hz

• 3 = 30 Hz scanFrequency is the scan frequency setting. Valid values are.

• 0 = 60 Hz

• 1 = 50 Hz

Notes

To write data to an I/O Module continuously, add the module to the Register Assignment.

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioRead5606Inputs

TelePACE C Tools User and Reference Manual

May 9, 2007

305

Example

This program writes configuration data to a 5506 I/O module at module address 5.

#include <ctools.h> void main(void)

{

request_resource(IO_SYSTEM);

/* set the input types */ for (index = 0; index < 8; index++)

{ inputType[index] = 1; // 1 to 5 V

}

/* set filter and frequency */ inputFilter = 3; // minimum filter scanFrequency = 0; // 60 Hz

release_resource(IO_SYSTEM);

}

/* Write configuration data to 5506 I/O module */ ioWrite5506Outputs(5, inputType, inputFilter, scanFrequency);

TelePACE C Tools User and Reference Manual

May 9, 2007

306

ioWrite5601Outputs

Write to 5601 Outputs from I/O Database

Syntax

#include <ctools.h> unsigned ioWrite5601Outputs(unsigned startCoilRegister);

Description

The ioWrite5601Outputs function writes data to the digital outputs of a 5601 I/O Module.

Data is read from 12 consecutive coil registers beginning at startCoilRegister, and written to the 12 digital outputs.

The function returns FALSE if startCoilRegister is invalid or if an I/O error has occurred; otherwise TRUE is returned.

startCoilRegister is any valid Modbus coil register between 00001 and (NUMCOIL - 11).

Notes

Note that when this function writes data to the 5601 it also services to the transmit buffer of the com3 serial port. If the controller type is a SCADAPack or SCADAPack PLUS, the com3 serial port is also continuously processed automatically.

The additional service to the com3 transmitter caused by this function does not affect the normal automatic operation of com3.

To write data to an I/O Module continuously, add the module to the Register Assignment.

Refer to the section Overview of Functions for details.

This function is contained in the ctools.lib library. Load this library in you linker command

(.cmd) file as shown in the sample file appram.cmd in your ctools directory.

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioRead5601Inputs

Example

This program turns ON all 12 digital outputs of a 5601 I/O Module.

#include <ctools.h> void main(void)

{

request_resource(IO_SYSTEM);

/* Write data to I/O database */ for (reg = 1; reg <= 12; reg++)

{ setdbase(MODBUS, reg, 1);

}

/* Write data from I/O database to 5601 */

ioWrite5601Outputs(1);

TelePACE C Tools User and Reference Manual

May 9, 2007

307

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

308

ioWrite5602Outputs

Write to 5602 Outputs from I/O Database

Syntax

#include <ctools.h> unsigned ioWrite5602Outputs(unsigned startCoilRegister);

Description

The ioWrite5602Outputs function writes data to the digital outputs of a 5602 I/O Module.

Data is read from 2 consecutive coil registers beginning at startCoilRegister, and written to the 2 digital outputs.

The function returns FALSE if startCoilRegister is invalid or if an I/O error has occurred; otherwise TRUE is returned.

startCoilRegister is any valid Modbus coil register between 00001 and (NUMCOIL - 1).

Notes

Note that when this function writes data to the 5602 it also services to the transmit buffer of the com4 serial port. If the controller type is a SCADAPack LIGHT or SCADAPack PLUS, the com4 serial port is also continuously processed automatically.

The additional service to the com4 transmitter caused by this function does not affect the normal automatic operation of com4.

To write data to an I/O Module continuously, add the module to the Register Assignment.

Refer to the section Overview of Functions for details.

This function is contained in the ctools.lib library. Load this library in you linker command

(.cmd) file as shown in the sample file appram.cmd in your ctools directory.

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioRead5602Inputs

Example

This program turns ON both digital outputs of a 5602 I/O Module.

#include <ctools.h> void main(void)

{

request_resource(IO_SYSTEM);

/* Write data to I/O database */ setdbase(MODBUS, 1, 1); setdbase(MODBUS, 2, 1);

/* Write data from I/O database to 5602 */

ioWrite5602Outputs(1);

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

309

ioWrite5604Outputs

Write to 5604 Outputs from I/O Database

Syntax

#include <ctools.h> unsigned ioWrite5604Outputs(

Description

The ioWrite5604Outputs function writes data to the digital and analog outputs of the

5604 I/O. Digital data is read from 36 consecutive coil registers beginning at startCoilRegister

, and written to the 36 digital outputs. Analog data is read from 2 consecutive holding registers beginning at startHoldingRegister and written to the 2 analog outputs.

The function returns FALSE if startCoilRegister is invalid, if startHoldingRegister is invalid, or if an I/O error has occurred; otherwise TRUE is returned. startCoilRegister

is any valid Modbus coil register between 00001 and (1 +

NUMCOIL -

36). startHoldingRegister

is any valid Modbus holding register between 40001 and

(40001 + NUMHOLDING - 2)

.

Notes

When this function writes data to the 5604 I/O it also processes the transmit buffer for the com3 serial port. The com3 serial port is also continuously processed automatically. The additional service to the com3 transmitter caused by this function does not affect the normal automatic operation of com3.

To write data to an I/O Module continuously, add the module to the Register Assignment.

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioRead5604Inputs

Example

This program turns on all 32 external digital outputs and sets the analog outputs to full scale.

The internal digital outputs are turned off.

#include <ctools.h> void main(void)

{

request_resource(IO_SYSTEM);

/* Write digital data to I/O database */ for (reg = 1; reg <= 32; reg++)

TelePACE C Tools User and Reference Manual

May 9, 2007

310

{

setdbase(MODBUS, 1);

} for (reg = 33; reg <= 36; reg++)

{

setdbase(MODBUS, 0);

}

/* Write analog data to I/O database */ for (reg = 40001; reg <= 40002; reg++)

{

setdbase(MODBUS, 32767);

}

/* Write data from I/O database to 5604 I/O */

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

311

ioWrite5606Outputs

Write to 5606 Outputs from I/O Database

Syntax

#include <ctools.h>

UINT16 ioWrite5606Outputs(

UINT16 startCoilRegister,

);

Description

The ioWrite5606Outputs function writes data to the digital and analog outputs of the 5606

I/O. Digital data is read from 16 consecutive coil registers beginning at startCoilRegister

, and written to the 16 digital outputs. Analog data is read from 2 consecutive holding registers beginning at startHoldingRegister and written to the 2 analog outputs.

The function returns FALSE if moduleAddress, startCoilRegister or startHoldingRegister

is invalid, or if an I/O error has occurred; otherwise TRUE is returned. moduleAddress

is the address of the 5606 module. Valid values are 0 to 7. startCoilRegister

is any valid Modbus coil register between 00001 and (1 +

NUMCOIL -

15). startHoldingRegister

is any valid Modbus holding register between 40001 and

(40001 + NUMHOLDING - 1)

. inputType

is an array of 8 values indicating the input range for the corresponding analog input. Valid values are

• 0 = 0 to 5V

• 1 = 0 to 10 V

• 2 = 0 to 20 mA

• 3 = 4 to 20 mA. inputFilter

is the analog input filter setting. Valid values are.

• 0 = 3 Hz

• 1 = 6 Hz

• 2 = 11 Hz

• 3 = 30 Hz scanFrequency is the scan frequency setting. Valid values are.

• 0 = 60 Hz

• 1 = 50 Hz

TelePACE C Tools User and Reference Manual

May 9, 2007

312

outputType

selects the type of analog outputs on the module. Valid values are

• 0 = 0 to 20 mA

• 1 = 4 to 20 mA.

Notes

To write data to an I/O Module continuously, add the module to the Register Assignment.

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioRead5606Inputs

Example

This program turns on all 16 external digital outputs and sets the analog outputs to full scale.

The internal digital outputs are turned off. The module address is 5.

#include <ctools.h> void main(void)

{

request_resource(IO_SYSTEM);

/* Write digital data to I/O database */ for (index = 1; index <= 16; index ++)

{

}

/* Write analog data to I/O database */ for (index = 40001; index <= 40002; index ++)

{

}

/* set the input types */ for (index = 0; index < 8; index++)

{ inputType[index] = 1; // 0 to 10 V

}

/* set filter and frequency */ inputFilter = 3; scanFrequency = 0;

// minimum filter

// 60 Hz

/* set analog output type to 4-20 mA */ outputType = 1;

/* Write data from I/O database to 5606 I/O */

TelePACE C Tools User and Reference Manual

May 9, 2007

313

ioWrite5606Outputs(5, 1, 40001, inputType, inputFilter, scanFrequency, outputType);

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

314

ioWriteLPOutputs

Write to SCADAPack LP Outputs from I/O Database

Syntax

#include <ctools.h> unsigned ioWriteLPOutputs (unsigned startCoilRegister, unsigned

startHoldingRegister);

Description

The ioWriteLPOutputsfunction writes data to the digital and analog outputs of the

SCADAPack LP I/O. Digital data is read from 12 consecutive coil registers beginning at startCoilRegister

, and written to the 12 digital outputs. Analog data is read from 2 consecutive holding registers beginning at startHoldingRegister and written to the 2 analog outputs.

The function returns FALSE if startCoilRegister is invalid, if startHoldingRegister is invalid, or if an I/O error has occurred; otherwise TRUE is returned. startCoilRegister

is any valid Modbus coil register between 00001 and (NUMCOIL -

11). startHoldingRegister

is any valid Modbus holding register between 40001 and

(NUMHOLDING - 2).

Notes

When this function writes data to the SCADAPack LP I/O it also processes the transmit buffer for the com3 serial port. The com3 serial port is also continuously processed automatically. The additional service to the com3 receiver caused by this function does not affect the normal automatic operation of com3.

To write data to an I/O Module continuously, add the module to the Register Assignment.

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioReadLPInputs

Example

This program turns on all 12 digital outputs and sets the analog outputs to full scale.

#include <ctools.h> void main(void)

{

request_resource(IO_SYSTEM);

/* Write digital data to I/O database */ for (reg = 1; reg <= 12; reg++)

{

setdbase(MODBUS, 1);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

315

/* Write analog data to I/O database */ for (reg = 40001; reg <= 40002; reg++)

{

setdbase(MODBUS, 32767);

}

/* Write data from I/O database to SCADAPack LP I/O */ ioWriteLPOutputs (1, 40001);

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

316

ioWriteSP100Outputs

Write to SCADAPack 100 Outputs from I/O Database

Syntax

#include <ctools.h> unsigned ioWriteSP100Outputs(unsigned startCoilRegister);

Description

The ioWriteSP100Outputs function writes data to the digital outputs of the SCADAPack

100 I/O. Digital data is read from 6 consecutive coil registers beginning at startCoilRegister

, and written to the 6 digital outputs.

The function returns FALSE if startCoilRegister is invalid, or if an I/O error has occurred; otherwise TRUE is returned. startCoilRegister

is any valid Modbus coil register between 00001 and (NUMCOIL - 5).

Notes

To write data to an I/O Module continuously, add the module to the Register Assignment.

The IO_SYSTEM resource must be requested before calling this function.

See Also

ioReadSP100Inputs

Example

This program turns on all 6 digital outputs.

#include <ctools.h> void main(void)

{

request_resource(IO_SYSTEM);

/* Write digital data to I/O database */ for (reg = 1; reg <= 6; reg++)

{

setdbase(MODBUS, 1);

}

/* Write data from I/O database to SCADAPack 100 I/O */

ioWriteSP100Outputs(1);

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

317

jiffy

Read System Clock

Syntax

#include <ctools.h> unsigned long jiffy(void);

Description

The jiffy function returns the current value of the system jiffy clock. The jiffy clock increments every 1/60 second. The jiffy clock rolls over to 0 after 5183999. This is the number of 1/60 second intervals in a day.

Notes

The real time clock and the jiffy clock are not related. They may drift slightly with respect to each other over several days.

Use the jiffy clock to measure times with resolution better than the 1/10th resolution provided by timers.

See Also

interval, setjiffy

Example

This program uses the jiffy timer to determine the execution time of a section of code. The section is run 10 times to provide a longer time base for the measurement.

#include <ctools.h> void main(void)

{ int iterations = 10;

setjiffy(0UL); for(i=0; i<=iterations; i++)

{

/* statements to time */

} printf("average time=%ld jiffies", jiffy()/iterations);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

318

ledGetDefault

Read LED Power Control Parameters

Syntax

#include <ctools.h> struct ledControl_tag ledGetDefault(void);

Description

The ledGetDefault routine returns the default LED power control parameters. The controller controls LED power to 5000 series I/O modules. To conserve power, the LEDs can be disabled.

The user can change the LED power setting with the LED POWER switch on the controller.

The LED power returns to its default state after a user specified time period.

Example

See the example for the ledSetDefault function.

TelePACE C Tools User and Reference Manual

May 9, 2007

319

ledPower

Set LED Power State

Syntax

#include <ctools.h> unsigned ledPower(unsigned state);

Description

The ledPower function sets the LED power state. The LED power will remain in the state until the default time-out period expires. state must be LED_ON or LED_OFF.

The function returns TRUE if state is valid and FALSE if it is not.

Notes

The LED POWER switch also controls the LED power. A user may override the setting made by this function.

The ledSetDefault function sets the default state of the LED power. This state overrides the value set by this function.

See Also

ledPowerSwitch, ledGetDefault, ledSetDefault

TelePACE C Tools User and Reference Manual

May 9, 2007

320

ledPowerSwitch

Read State of the LED Power Switch

Syntax

#include <ctools.h> unsigned ledPowerSwitch(void);

Description

The ledPowerSwitch function returns the status of the led power switch. The function returns

FALSE if the switch is released and TRUE if the switch is pressed.

Notes

This switch may be used by the program for user input. However, pressing the switch will have the side effect of changing the LED power state.

See Also

ledPower, ledSetDefault, ledGetDefault

TelePACE C Tools User and Reference Manual

May 9, 2007

321

ledSetDefault

Set Default Parameters for LED Power Control

Syntax

#include <ctools.h> unsigned ledSetDefault(struct ledControl_tag ledControl);

Description

The ledSetDefault routine sets default parameters for LED power control. The controller controls LED power to 5000 series I/O modules. To conserve power, the LEDs can be disabled.

The LED power setting can be changed by the user with the LED POWER switch on the controller. The LED power returns to its default state after a user specified time period.

The ledControl structure contains the default values. Refer to the Structures and Types section for a description of the fields in the ledControl_tag structure. Valid values for the

state field are LED_ON and LED_OFF. Valid values for the time field are 1 to 65535 minutes.

The function returns TRUE if the parameters are valid and false if they are not. If either parameter is not valid, the default values are not changed.

The IO_SYSTEM resource must be requested before calling this function.

Example

#include <ctools.h> void main(void)

{ struct ledControl_tag ledControl;

request_resource(IO_SYSTEM);

/* Turn LEDS off after 20 minutes */ ledControl.time = 20; ledControl.state = LED_OFF;

ledSetDefault(ledControl);

release_resource(IO_SYSTEM);

/* ... the reset of the program */

}

TelePACE C Tools User and Reference Manual

May 9, 2007

322

load

Read Parameters from EEPROM

Syntax

#include <ctools.h> void load(unsigned section);

Description

The load function reads data from the specified section of the EEPROM into RAM.. Valid values for section are EEPROM_EVERY and EEPROM_RUN.

The save function writes data to the EEPROM.

Notes

The IO_SYSTEM resource must be requested before calling this function.

The EEPROM_EVERY section is not used.

The EEPROM_RUN section is loaded from EEPROM to RAM when the controller is reset and the Run/Service switch is in the RUN position. Otherwise default information is used for this section. This section contains:

• serial port configuration tables

• protocol configuration tables

See Also

save

TelePACE C Tools User and Reference Manual

May 9, 2007

323

master_message

Send Protocol Command

Syntax

#include <ctools.h> extern unsigned master_message(FILE *stream, unsigned function, unsigned

slave_station, unsigned slave_address, unsigned master_address, unsigned

length);

Description

The master_message function sends a command using a communication protocol. The communication protocol task waits for the response from the slave station. The current task continues execution.

stream specifies the serial port.

function specifies the protocol function code. Refer to the communication protocol manual for supported function codes.

slave specifies the network address of the slave station. This is also known as the slave station number.

address specifies the location of data in the slave station. Depending on the protocol function code, data may be read or written at this location.

master_address specifies the location of data in the master (this controller). Depending on the protocol function code, data may be read or written at this location.

length specifies the number or registers.

The master_message function returns the command status from the protocol driver.

Value

MM_SENT

MM_BAD_FUNCTION

MM_BAD_SLAVE

MM_BAD_ADDRESS

MM_BAD_LENGTH

MM_EOT

MM_WRONG_RSP

Description

message transmitted to slave function is not recognized slave station number is not valid slave or master database address not valid too many or too few registers specified

Master message status: DF1 slave response was an EOT message

Master message status: DF1slave response did not match command sent.

MM_CMD_ACKED

MM_EXCEPTION_FUNCTION

Master message status: DF1half duplex command has been acknowledged by slave

– Master may now send poll command.

Master message status: Modbus slave returned a function exception.

MM_EXCEPTION_ADDRESS

MM_EXCEPTION_VALUE

Master message status: Modbus slave returned an address exception.

Master message status: Modbus slave returned a value exception.

Master message status: response received.

MM_RECEIVED

MM_RECEIVED_BAD_LENGTH

Master message status: response received with incorrect amount of data.

TelePACE C Tools User and Reference Manual

May 9, 2007

324

The calling task monitors the status of the command sent using the get_protocol_status function. The command field of the prot_status structure is set to MM_SENT if a master message is sent. It will be set to MM_RECEIVED when the response to the message is received with the proper length. It will be set to MM_RECEIVED_BAD_LENGTH when a response to the message is received with the improper length.

Notes

Refer to the communication protocol manual for more information.

Users of TeleSAFE BASIC and the TeleSAFE 6000 C compiler should note that the address parameter now specifies the actual database address, when used with the Modbus protocol.

This parameter specified the address offset on these older TeleSAFE products.

To optimize performance, minimize the length of messages on com3 and com4. Examples of recommended uses for com3 and com4 are for local operator display terminals, and for programming and diagnostics using the TelePACE program.

The IO_SYSTEM resource must be requested before calling this function.

See Also

clear_protocol_status

Example Using Modbus Protocol

This program sends a master message, on com2, using the Modbus protocol, then waits for a response from the slave. The number of good and failed messages is printed to com1.

/* --------------------------------------------

poll.c

Polling program for Modbus slave.

-------------------------------------------- */

#include <ctools.h>

/* --------------------------------------------

wait_for_response

The wait_for_response function waits for a

response to be received to a master_message on

{

the serial port specified by stream. It returns

when a response is received, or when the period

specified by time (in tenths of a second)

expires.

-------------------------------------------- */ void wait_for_response(FILE *stream, unsigned time) struct prot_status status; static unsigned long good, bad; interval(0, 1);

/* Allow other tasks to execute */ release_processor(); status = get_protocol_status(stream);

} while (timer(0) && status.command == MM_SENT); if (status.command == MM_RECEIVED)

TelePACE C Tools User and Reference Manual

May 9, 2007

325

good++;

else bad++; fprintf(com1, "Good: %8lu Bad: %8lu\r", good,

bad);

}

/* --------------------------------------------

main

The main function sets up serial ports then

sends commands to a Modbus slave.

-------------------------------------------- */ void main(void)

{ struct prot_settings settings; struct pconfig portset;

request_resource(IO_SYSTEM);

/* disable protocol on serial port 1 */ settings.type = NO_PROTOCOL; settings.station = 1; settings.priority = 3; settings.SFMessaging = FALSE;

/* Set communication parameters for port 1 */ portset.baud = BAUD9600; portset.duplex = FULL; portset.parity = NONE; portset.data_bits = DATA8; portset.stop_bits = STOP1; portset.flow_rx = DISABLE; portset.flow_tx = DISABLE; portset.type = RS232; portset.timeout = 600;

/* enable Modbus protocol on serial port 2 */ settings.type = MODBUS_ASCII; settings.station = 2; settings.priority = 3; settings.SFMessaging = FALSE;

/* Set communication parameters for port 2 */ portset.baud = BAUD9600; portset.duplex = HALF; portset.parity = NONE; portset.data_bits = DATA8; portset.stop_bits = STOP1; portset.flow_rx = DISABLE; portset.flow_tx = DISABLE; portset.type = RS485_2WIRE; portset.timeout = 600;

release_resource(IO_SYSTEM);

TelePACE C Tools User and Reference Manual

May 9, 2007

326

/* Main communication loop */

{

/* Transfer slave inputs to outputs */ request_resource(IO_SYSTEM); master_message(com2, 2, 1, 10001, 17, 8); release_resource(IO_SYSTEM);

/* Transfer inputs to slave outputs */ request_resource(IO_SYSTEM); master_message(com2, 15, 1, 1, 10009, 8); release_resource(IO_SYSTEM);

/* Allow other tasks to execute */ release_processor();

}

}

Examples using DF1 Protocol

Full Duplex

Using the same example program above, apply the following calling format for the master_message function.

This code fragment uses the protected write command (function=0) to transmit 13

(length=13) 16-bit registers to slave station 10 (slave=10). The data will be read from registers 127 to 139 (master_address=127), and stored into registers 180 to 192

(address=180) in the slave station. The command will be transmitted on com2

(stream=com2). master_message(com2, 0, 10, 180, 127, 13);

This code fragment uses the unprotected read command (function=1) to read 74 (length=74)

16-bit registers from slave station 37 (slave=37). The data will be read from registers 300 to

373 in the slave (address=300), and stored in registers 400 to 473 in the master

(master_address=400). The command will be transmitted on com2 (stream=com2). master_message(com2, 1, 37, 300, 400, 74);

This code fragment will send specific bits from a single 16-bit register in the master to slave station 33. The unprotected bit write command (function=5) will be used. Bits 0,1,7,12 and

15 of register 100 (master_address=100) will be sent to register 1432 (address=1432) in the slave. The length parameter is used as a bit mask and is evaluated as follows: it mask = 1001 0000 1000 0011 in binary

Therefore the command, sent on com2, is: master_message(com2, 5, 33, 1432, 100, 36995);

Half Duplex

The example program is the same as for Full Duplex except that instead of waiting for a response after calling master_message, the slave must be polled for a response. Add the following function poll_for_response to the example program above and call it instead of wait_for_response:

/* --------------------------------------------

TelePACE C Tools User and Reference Manual

May 9, 2007

327

poll_for_response

The poll_for_response function polls the

specified slave for a response to a master

message sent on the serial port specified by

stream. It returns when the correct response

is received, or when the period specified by

time (in tenths of a second) expires.

-------------------------------------------- */ unsigned poll_for_response(FILE *stream, unsigned slave, unsigned time)

{ struct prot_status status; static unsigned long good, bad;

/* set timeout timer */ interval( 0, 10 ); settimer( 0, time );

do

{

/* wait until command status changes or

do

{ status = get_protocol_status( stream );

release_processor();

}

/* command has been ACKed, send poll */ if (status.command == MM_CMD_ACKED)

{

done FALSE;

}

/* response/command mismatch, poll again */ else if (status.command == MM_WRONG_RSP)

{

done FALSE;

}

/* correct response was received */ else if (status.command == MM_RECEIVED)

{

good++;

done TRUE;

}

/* timer has expired or status is MM_EOT */

else

{

bad++;

done TRUE;

}

} while (!done); fprintf(com1, "Good: %8lu Bad: %8lu\r", good,

bad);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

328

modbusExceptionStatus

Set Response to Protocol Command

Syntax

#include <ctools.h> void modbusExceptionStatus(unsigned char status);

Description

The modbusExceptionStatus function is used in conjunction with the Modbus compatible communication protocol. It sets the result returned in response to the Read Exception Status command. This command is provided for compatibility with some Modbus protocol drivers for host computers.

The value of status is determined by the requirements of the host computer.

Notes

The specified result will be sent each time that the protocol command is received, until a new result is specified.

The result is cleared when the controller is reset. The application program must initialize the status each time it is run.

See Also

modbusSlaveID

TelePACE C Tools User and Reference Manual

May 9, 2007

329

modbusSlaveID

Set Response to Protocol Command

Syntax

#include <ctools.h> void modbusSlaveID(unsigned char *string, unsigned length);

Description

The modbusSlaveID function is used in conjunction with the Modbus compatible communication protocol. It sets the result returned in response to the Report Slave ID command. This command is provided for compatibility with some Modbus protocol drivers for host computers.

string points to a string of at least length characters. The contents of the string is determined by the requirements of the host computer. The string is not NULL terminated and may contain multiple NULL characters.

The length specifies how many characters are returned by the protocol command. length must be in the range 1 to REPORT_SLAVE_ID_SIZE. If length is too large only the first

REPORT_SLAVE_ID_SIZE characters of the string will be sent in response to the command.

Notes

The specified result will be sent each time that the protocol command is received, until a new result is specified.

The function copies the data pointed to by string. string may be modified after the function is called.

The result is cleared when the controller is reset. The application program must initialize the salve ID string each time it is run.

See Also

modbusExceptionStatus

TelePACE C Tools User and Reference Manual

May 9, 2007

330

modbusProcessCommand Function

Process a Modbus command and return the response.

Syntax

#include <ctools.h>

BOOLEAN processModbusCommand(

FILE * stream,

UCHAR * pCommand,

UCHAR * pResponse,

UINT16 * pResponseLength

)

Description

The processModbusCommand function processes a Modbus protocol command and returns the response. The function can be used by an application to encapsulate Modbus

RTU commands in another protocol. stream

is a FILE pointer that identifies the serial port where the command was received.

This is used for to accumulate statistics for the serial port. pCommand

is a pointer to a buffer containing the Modbus command. The contents of the buffer must be a standard Modbus RTU message. The Modbus RTU checksum is not required. commandLength

is the number of bytes in the Modbus command. The length must include all the address and data bytes. It must not include the checksum bytes, if any, in the command buffer. responseSize

is the size of the response buffer in bytes. A 300-byte buffer is recommended. If this is not practical in the application, a smaller buffer may be supplied.

Some responses may be truncated if a smaller buffer is used. pResponse

is a pointer to a buffer to contain the Modbus response. The function will store the response in this buffer in standard Modbus RTU format including two checksum bytes at the end of the response. pResponseLength

is a pointer to a variable to hold response length. The function will store the number of bytes in the response in this variable. The length will include two checksum bytes.

The function returns TRUE if the response is valid and can be used. It returns FALSE if the response is too long to fit into the supplied response buffer.

Notes

To use the function on a serial port, a protocol handler must be created for the encapsulating protocol. Set the protocol type for the port to NO_PROTOCOL to allow the custom handler to be used.

The function supports standard and extended addressing. Configure the protocol settings for the serial port for the appropriate protocol.

The Modbus RTU checksum is not required in the command so the encapsulating protocol may omit them if they are not needed. This may be useful in host devices that don't create a

Modbus RTU message with checksum prior to encapsulation.

TelePACE C Tools User and Reference Manual

May 9, 2007

331

The Modbus RTU checksum is included in the response to support encapsulating a complete Modbus RTU format message. If the checksum is not needed by the encapsulating protocol the checksum bytes may be ignored.

See Also

set_protocol

Example

This example is taken from a protocol driver than encapsulates Modbus RTU messages in another protocol. It shows how to pass the Modbus RTU command to the Modbus driver, and obtain the response.

The example assumes the Modbus RTU messages are transmitted with the checksum. The length of the checksum is subtracted when calling the processModbusCommand function.

The checksum is included when responding.

/* receive the packet in the encapsulating protocol */

/* verify the packet is valid */

/* locate the Modbus RTU command in the command buffer */ pCommandData = commandBuffer + PROTOCOL_HEADER_SIZE;

/* get length of Modbus RTU command from the packet header */ commandLength = commandBuffer[DATA_SIZE] - 2;

/* locate the Modbus RTU response in the response buffer leaving room for the packet header */ pResponseData = responseBuffer + PROTOCOL_HEADER_SIZE;

/* process the Modbus message */ if (processModbusCommand(

stream,

pCommandData,

{

commandLength,

MODBUS_BUFFER_SIZE,

pResponseData,

&responseLength))

/* put the response length in the header */ responseBuffer[DATA_SIZE] = responseLength;

/* fill in rest of packet header */

}

/* transmit the encapsulated response */

TelePACE C Tools User and Reference Manual

May 9, 2007

332

modemAbort

Unconditionally Terminate Dial-up Connection

Syntax

#include <ctools.h> void modemAbort(FILE *port);

Description

The modemAbort function unconditionally terminates a dial-up connection, connection in progress or modem initialization started by the C application. port specifies the serial port the where the modem is installed.

The connection or initialization is terminated only if it was started from a C application.

Connections made from a Ladder Logic application and answered calls are not terminated.

This function can be used in a task exit handler.

Notes

The serial port type must be set to RS232_MODEM.

Note that a pause of a few seconds is required between terminating a connection and initiating a new call. This pause allows the external modem time to hang up.

Use this function in a task exit handler to clean-up any open dial-up connections or modem initializations. If a task is ended by executing end_task from another task, modem connections or initializations must be aborted in the exit handler. Otherwise, the reservation

ID for the port remains valid. No other task or Ladder Logic program may use modem functions on the port. Failing to call modemAbort or modemAbortAll in the task exit handler may result in the port being unavailable to any programs until the controller is reset.

The modem connection or initialization is automatically terminated when TelePACE stops the C application and when the controller is rebooted.

All reservation IDs returned by the modemDial and modemInit functions on this port are invalid after calling modemAbort.

See Also

modemAbortAll, modemDial, modemDialEnd, modemDialStatus, modemInit,

modemInitEnd, modemInitStatus, modemNotification

Example

Refer to the examples in the Functions Overview section.

TelePACE C Tools User and Reference Manual

May 9, 2007

333

modemAbortAll

Unconditionally Terminate All Dial-up Connections

Syntax

#include <ctools.h> void modemAbort(void);

Description

The modemAbortAll function unconditionally terminates all dial-up connections, connections in progress or modem initializations started by the C application.

The connections or initializations are terminated only if they were started from a C application. Connections made from a Ladder Logic application and answered calls are not terminated.

This function can be used in a task exit handler.

Notes

Note that a pause of a few seconds is required between terminating a connection and initiating a new call. This pause allows the external modem time to hang up.

Use this function in a task exit handler to clean-up any open dial-up connections or modem initializations. If executing end_task from another task ends a task, modem connections or initializations must be aborted in the exit handler. Otherwise, the reservation ID for the port remains valid. No other task or Ladder Logic program may use modem functions on the port.

Failing to call modemAbort or modemAbortAll in the task exit handler may result in the port being unavailable to any programs until the controller is reset.

The modem connection or initialization is automatically terminated when TelePACE stops the C application and when the controller is rebooted.

This function will terminate all open dial-up connections or modem initializations started by the C application - even those started by other tasks. The exit handler can safely call this function instead of multiple calls to modemAbort if all the connections or initializations were started from the same task.

All reservation IDs returned by the modemDial and modemInit functions are invalid after calling modemAbort.

See Also

modemDial, modemDialEnd, modemDialStatus, modemInit, modemInitEnd,

modemInitStatus, modemNotification

Example

This program installs an exit handler for the main task that terminates any dial-up connections made by the task. This handler is not strictly necessary if TelePACE ends the main task. However, it demonstrates how to use the modemAbortAll function and an exit handler for another task in a more complex program.

#include <ctools.h>

/* --------------------------------------------

The shutdown function aborts any active

TelePACE C Tools User and Reference Manual

May 9, 2007

334

modem connections when the task is ended.

-------------------------------------------- */ void shutdown(void)

{

modemAbortAll();

} void main(void)

{

/* set up exit handler for this task */ taskStatus = getTaskInfo(0);

while(TRUE)

{

/* rest of main task here */

/* Allow other tasks to execute */ release_processor();

}

}

TelePACE C Tools User and Reference Manual

May 9, 2007

335

modemDial

Connect to a Remote Dial-up Controller

Syntax

#include <ctools.h> enum DialError modemDial(struct ModemSetup *configuration, reserve_id *id);

Description

The modemDial function connects a controller to a remote controller using an external dialup modem. One modemDial function may be active on each serial port. The modemDial function handles all port sharing and multiple dialing attempts.

The ModemSetup structure specified by configuration defines the serial port, dialing parameters, modem initialization string and the phone number to dial. Refer to the

Structures and Types section for a description of the fields in the ModemSetup structure.

id points to a reservation identifier for the serial port. The identifier ensures that no other modem control function can access the serial port. This parameter must be supplied to the

modemDialEnd and modemDialStatus functions.

The function returns an error code. DE_NoError indicates that the connect operation has begun. Any other code indicates an error. Refer to the dialup.h section for a complete description of error codes.

Notes

The serial port type must be set to RS232_MODEM.

Note: The SCADAPack 100 does not support dial up connections on com port 1.

The SCADASense series controllers do not support dial up connections.

The modemDialStatus function returns the status of the connection attempt initiated by modemDial.

The modemDialEnd function terminates the connection to the remote controller. Note that a pause of a few seconds is required between terminating a connection and initiating a new call. This pause allows the external modem time to hang up.

If a communication protocol is active on the serial port when a connection is initiated, the protocol will be disabled until the connection is made, then re-enabled. This allows the controller to communicate with the external modem on the port. The protocol settings will also be restored when a connection is terminated with the modemDialEnd function.

If a modemInit function or an incoming call is active on the port, the modemDial function cannot access the port and will return an error code of DE_NotInControl. If communication stops for more than five minutes, then outgoing call requests are allowed to end the incoming call. This prevents problems with the modem or the calling application from permanently disabling outgoing calls.

The reservation identifier is valid until the call is terminated and another modem function or an incoming call takes control of the port.

To optimize performance, minimize the length of messages on com3 and com4. Examples of recommended uses for com3 and com4 are for local operator display terminals, and for programming and diagnostics using the TelePACE program.

Do not call this function in a task exit handler.

TelePACE C Tools User and Reference Manual

May 9, 2007

336

See Also

modemAbortAll, modemDialEnd, modemDialStatus, modemInit, modemInitEnd,

modemInitStatus, modemNotification

Example

Refer to the examples in the Functions Overview section.

TelePACE C Tools User and Reference Manual

May 9, 2007

337

modemDialEnd

Terminate Dial-up Connection

Syntax

#include <ctools.h> void modemDialEnd(FILE *port, reserve_id id, enum DialError *error);

Description

The modemDialEnd function terminates a dial-up connection or connection in progress.

port specifies the serial port the where the modem is installed. id is the port reservation identifier returned by the modemDial function.

The function sets the variable pointed to by error. If no error occurred DE_NoError is returned. Any other value indicates an error. Refer to the Structures and Types section for a complete description of error codes.

Notes

The serial port type must be set to RS232_MODEM.

A connection can be terminated by any of the following events. Once terminated another modem function or incoming call can take control of the serial port.

• Execution of the modemDialEnd function.

• Execution of the modemAbort or modemAbortAll functions.

• The remote device hangs up the phone line.

• An accidental loss of carrier occurs due to phone line problems.

Note that a pause of a few seconds is required between terminating a connection and initiating a new call. This pause allows the external modem time to hang up.

The reservation identifier is valid until the call is terminated and another modem function or an incoming call takes control of the port. The modemDialEnd function returns a

DE_NotInControl error code, if another modem function or incoming call is in control of the port.

Do not call this function in a task exit handler. Use modemAbort instead.

See Also

modemAbortAll, modemDial, modemDialStatus, modemInit, modemInitEnd,

modemInitStatus, modemNotification

TelePACE C Tools User and Reference Manual

May 9, 2007

338

modemDialStatus

Return Status of Dial-up Connection

Syntax

#include <ctools.h> void modemDialStatus(FILE *port, reserve_id id, enum DialError * error, enum

DialState *state);

Description

The modemDialStatus function returns the status of a remote connection initiated by the

modemDial function. port specifies the serial port where the modem is installed. id is the port reservation identifier returned by the modemDial function.

The function sets the variable pointed to by error. If no error occurred DE_NoError is returned. Any other value indicates an error. Refer to the Structures and Types section for a complete description of error codes.

The function sets the variable pointed to by state to the current execution state of dialing operation. The state value is not valid if the error code is DE_NotInControl. Refer to the

dialup.h section for a complete description of state codes.

Notes

The serial port type must be set to RS232_MODEM.

The reservation identifier is valid until the call is terminated and another modem function or an incoming call takes control of the port. The modemDialStatus function will return a

DE_NotInControl error code, if another dial function or incoming call is now in control of the port.

Do not call this function in a task exit handler.

TelePACE C Tools User and Reference Manual

May 9, 2007

339

modemInit

Initialize Dial-up Modem

Syntax

#include <ctools.h> enum DialError modemInit(struct ModemInit *configuration, reserve_id *id);

Description

The modemInit function sends an initialization string to an external dial-up modem. It is typically used to set up a modem to answer incoming calls. One modemInit function may be active on each serial port. The modemInit function handles all port sharing and multiple dialing attempts.

The ModemInit structure pointed to by configuration defines the serial port and modem initialization string. Refer to the Structures and Types section for a description of the fields in the ModemInit structure.

The id variable is set to a reservation identifier for the serial port. The identifier ensures that no other modem control function can access the serial port. This parameter must be supplied to the modemInitEnd and modemInitStatus functions.

The function returns an error code. DE_NoError indicates that the initialize operation has begun. Any other code indicates an error. Refer to the Structures and Types section for a complete description of error codes.

Notes

The serial port type must be set to RS232_MODEM.

The modemInitStatus function returns the status of the connection attempt initiated by modemInit.

The modemInitEnd function terminates initialization of the modem.

If a communication protocol is active on the serial port, the protocol will be disabled until the initialization is complete then re-enabled. This allows the controller to communicate with the external modem on the port. The protocol settings will also be restored when initialization is terminated with the modemInitEnd function.

If a modemDial function or an incoming call is active on the port, the modemInit function cannot access the port and will return an error code of DE_NotInControl.

The reservation identifier is valid until the call is terminated and another modem function or an incoming call takes control of the port.

To optimize performance, minimize the length of messages on com3 and com4. Examples of recommended uses for com3 and com4 are for local operator display terminals, and for programming and diagnostics using the TelePACE program.

Do not call this function in a task exit handler.

See Also

modemAbortAll, modemDial, modemDialEnd, modemDialStatus, modemInitEnd,

modemInitStatus, modemNotification

TelePACE C Tools User and Reference Manual

May 9, 2007

340

Example

Refer to the example in the Functions Overview section.

TelePACE C Tools User and Reference Manual

May 9, 2007

341

modemInitEnd

Abort Initialization of Dial-up Modem

Syntax

#include <ctools.h> void modemInitEnd(FILE *port, reserve_id id, enum DialError *error);

Description

The modemInitEnd function terminates a modem initialization in progress. port specifies the serial port where the modem is installed. id is the port reservation identifier returned by the

modemInit function.

The function sets the variable pointed to by error. If no error occurred DE_NoError is returned. Any other value indicates an error. Refer to the dialup.h section for a complete description of error codes.

Notes

The serial port type must be set to RS232_MODEM.

Normally this function should be called once the modemInitStatus function indicates the initialization is complete.

The reservation identifier is valid until the initialization is complete or terminated, and another modem function or an incoming call takes control of the port. The modemInitEnd function returns a DE_NotInControl error code, if another modem function or incoming call is in control of the port.

Do not call this function in a task exit handler. Use modemAbort instead.

See Also

modemAbortAll, modemDial, modemDialEnd, modemDialStatus, modemInit,

modemInitStatus, modemNotification

TelePACE C Tools User and Reference Manual

May 9, 2007

342

modemInitStatus

Return Status of Dial-up Modem Initialization

Syntax

#include <ctools.h> void modemInitStatus(FILE *port, reserve_id id, enum DialError *error, enum

DialState *state);

Description

The modemInitStatus function returns the status a modem initialization started by the

modemInit function. port specifies the serial port where the modem is installed. id is the port reservation identifier returned by the modemInit function.

The function sets the variable pointed to by error. If no error occurred DE_NoError is returned. Any other value indicates an error. Refer to the Structures and Types section for a complete description of error codes.

The function sets the variable pointed to by state to the current execution state of dialing operation. The state value is not valid if the error code is DE_NotInControl. Refer to the

dialup.h section for a complete description of state codes.

Notes

The serial port type must be set to RS232_MODEM.

The port will remain in the DS_Calling state until modem initialization is complete or fails.

The application should wait until the state is not DS_Calling before calling the

modemInitEnd function.

The reservation identifier is valid until the initialization is complete or terminated, and another modem function or an incoming call takes control of the port.

Do not call this function in a task exit handler.

See Also

modemAbortAll, modemDial, modemDialEnd, modemDialStatus, modemInit,

modemInitEnd, modemNotification

TelePACE C Tools User and Reference Manual

May 9, 2007

343

modemNotification

Notify the modem handler of an important event

Syntax

#include <ctools.h> void modemNotification(UINT16 port_index);

Description

The modemNotification function notifies the dial-up modem handler that an interesting event has occurred. This informs the modem handler not to disconnect an incoming call when an outgoing call is requested with modemDial.

This function is used with custom communication protocols. The function is usually called when a message is received by the protocol, although it can be called for other reasons.

The port_index indicates the serial port that received the message.

Notes

The serial port type must be set to RS232_MODEM.

Use the portIndex function to obtain the index of the serial port.

The dial-up connection handler prevents outgoing calls from using the serial port when an incoming call is in progress and communication is active. If communication stops for more than five minutes, then outgoing call requests are allowed to end the incoming call. This prevents problems with the modem or the calling application from permanently disabling outgoing calls.

The function is used with programs that dial out through an external modem using the modemDial

function. It is not required where the modem is used for dialing into the controller only.

See Also

modemAbortAll, modemDial, modemDialEnd, modemDialStatus, modemInit,

modemInitEnd, modemInitStatus

TelePACE C Tools User and Reference Manual

May 9, 2007

344

off

Test Digital I/O Bit

Syntax

#include <ctools.h> int off(unsigned channel, unsigned bit);

Description

The off function tests the status of the digital I/O point at channel and bit. channel must be in the range 0 to DIO_MAX. bit must be in the range 0 to 7.

The off function returns TRUE if the bit is off, FALSE if the bit is on, and –1 if channel or bit is invalid.

Notes

The off function may be used to check the status of digital inputs, outputs and configuration tables.

Use offsets from the symbolic constants DIN_START, DIN_END, DOUT_START and

DOUT_END to reference digital channels. The constants make programs more portable and protect against future changes to the digital I/O channel numbering.

The IO_SYSTEM resource must be requested before calling this function.

This function is provided for backward compatibility. It cannot access all 5000 series I/O modules. It is recommended that this function not be used in new programs. Instead use

Register Assignment or call the I/O driver ioRead8Din directly.

See Also

ioRead8Din, turnoff, turnon, on

Example

This code fragment inverts the digital output point at the first digital output channel, bit 3. request_resource(IO_SYSTEM); if (off(DOUT_START, 3)) else release_resource(IO_SYSTEM);

TelePACE C Tools User and Reference Manual

May 9, 2007

345

on

Test Digital I/O Bit

Syntax

#include <ctools.h> int on(unsigned channel, unsigned bit);

Description

The on function tests the status of the digital I/O point at channel and bit. channel must be in the range 0 to DIO_MAX. bit must be in the range 0 to 7.

The on function returns TRUE if the bit is on, FALSE if the bit is off, and –1 if channel or bit is invalid.

Notes

The on function may be used to check the status of digital inputs, outputs and configuration tables.

Use offsets from the symbolic constants DIN_START, DIN_END, DOUT_START and

DOUT_END to reference digital channels. The constants make programs more portable and protect against future changes to the digital I/O channel numbering.

The IO_SYSTEM resource must be requested before calling this function.

This function is provided for backward compatibility. It cannot access all 5000 series I/O modules. It is recommended that this function not be used in new programs. Instead use

Register Assignment or call the I/O driver ioRead8Din directly.

See Also

ioRead8Din, turnoff, turnon, off

TelePACE C Tools User and Reference Manual

May 9, 2007

346

optionSwitch

Read State of Controller Option Switches

Syntax

#include <ctools.h> unsigned optionSwitch(unsigned option);

Description

The optionSwitch function returns the state of the controller option switch specified by

option. option may be 1, 2 or 3.

The function returns OPEN if the switch is in the open position. It returns CLOSED if the switch is in the closed position.

Notes

The option switches are located under the cover of the controller module. The SCADAPack

LP, SCADAPack 100 and SCADASense series of controllers do not have option switches.

All options are user defined.

However, when a SCADAPack I/O module is placed in the Register Assignment, option switch 1 selects the input range for analog inputs on this module. When the SCADAPack

AOUT module is placed in the Register Assignment, option switch 2 selects the output range for analog outputs on this module. Refer to the SCADAPack System Hardware Manual for further information on option switches.

TelePACE C Tools User and Reference Manual

May 9, 2007

347

overrideDbase

Overwrite Value in Forced I/O Database

Syntax

#include <ctools.h> unsigned overrideDbase(unsigned type, unsigned address, int value);

Description

The overrideDbase function writes value to the I/O database even if the database register is currently forced. type specifies the method of addressing the database. address specifies the location in the database.

If the register is currently forced, the register remains forced but forced to the new value.

If the address or addressing type is not valid, the I/O database is left unchanged and FALSE is returned; otherwise TRUE is returned. The table below shows the valid address types and ranges.

Type Address Ranges

MODBUS 00001 to NUMCOIL

10001 to 10000 + NUMSTATUS

30001 to 30000 + NUMINPUT

40001 to 40000 + NUMHOLDING

LINEAR 0 to NUMLINEAR-1

Register

Size

1 bit

1 bit

16 bit

16 bit

16 bit

Notes

When writing to LINEAR digital addresses, value is a bit mask which writes data to 16 1-bit registers at once.

The I/O database is not modified when the controller is reset. It is a permanent storage area, which is maintained during power outages.

Refer to the Functions Overview chapter for more information.

The IO_SYSTEM resource must be requested before calling this function.

See Also

setdbase, setForceFlag

Example

#include <ctools.h> void main(void)

{

request_resource(IO_SYSTEM); overrideDbase(MODBUS, 40001, 102); overrideDbase(LINEAR, 302, 330);

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

348

pollABSlave

Poll DF1 Slave for Response

Syntax

#include <ctools.h> unsigned pollABSlave(FILE *stream, unsigned slave);

Description

The pollABSlave function is used to send a poll command to the slave station specified by

slave in the DF1 Half Duplex protocol configured for the specified port. stream specifies the serial port.

The function returns FALSE if the slave number is invalid, or if the protocol currently installed on the specified serial port is not an DF1 Half Duplex protocol. Otherwise it returns

TRUE and the protocol command status is set to MM_SENT.

Notes

See the example using the pollABSlave function in the sample polling function

"poll_for_response" shown in the example for the master_message function.

See Also

master_message

Example

This program segment polls slave station 9 for a response communicating on the com2 serial port.

#include <ctools.h> pollABSlave(com2, 9);

TelePACE C Tools User and Reference Manual

May 9, 2007

349

poll_event

Test for Event Occurrence

Syntax

#include <ctools.h> int poll_event(int event);

Description

The poll_event function tests if an event has occurred.

The poll_event function returns TRUE, and the event counter is decrements, if the event has occurred. Otherwise it returns FALSE.

The current task always continues to execute.

Notes

Refer to the Real Time Operating System section for more information on events.

Valid events are numbered 0 to RTOS_EVENTS - 1. Any events defined in primitiv.h are not valid events for use in an application program.

See Also

signal_event, wait_event, startTimedEvent

Example

This program implements a somewhat inefficient transfer of data between com1 and com2.

(It would be more efficient to test for EOF from getc).

#include <ctools.h> void main(void)

{

while(TRUE)

{ if (poll_event(COM1_RCVR))

(poll_event(COM2_RCVR))

/* Allow other tasks to execute */ release_processor();

}

}

TelePACE C Tools User and Reference Manual

May 9, 2007

350

poll_message

Test for Received Message

Syntax

#include <ctools.h> envelope *poll_message(void);

Description

The poll_message function tests if a message has been received by the current task.

The poll_message function returns a pointer to an envelope if a message has been received. It returns NULL if no message has been received.

The current task always continues to execute.

Notes

Refer to the Real Time Operating System section for more information on messages.

See Also

send_message, receive_message

Example

This task performs a function continuously, and processes received messages (from higher priority tasks) when they are received.

#include <ctools.h> void task(void)

{

while(TRUE)

{ letter=poll_message(); if (letter != NULL)

/* process the message now */

/* more code here */

}

}

TelePACE C Tools User and Reference Manual

May 9, 2007

351

poll_resource

Test Resource Availability

Syntax

#include <ctools.h> int poll_resource(int resource);

Description

The poll_resource function tests if the resource specified by resource is available. If the resource is available it is given to the task.

The poll_resource function returns TRUE if the resource is available. It returns FALSE if it is not available.

The current task always continues to execute.

Notes

Refer to the Real Time Operating System section for more information on resources.

See Also

request_resource, release_resource

TelePACE C Tools User and Reference Manual

May 9, 2007

352

portConfiguration

Get Pointer to Port Configuration Structure

Syntax

#include <ctools.h> struct pconfig *portConfiguration(FILE *stream);

Description

The portConfiguration function returns a pointer to the configuration structure for stream. A

NULL pointer is returned if stream is not valid.

Notes

It is recommended the get_port and set_port functions be used to access the configuration table.

TelePACE C Tools User and Reference Manual

May 9, 2007

353

portIndex

Get Index of Serial Port

Syntax

#include <ctools.h> unsigned portIndex(FILE *stream);

Description

The portIndex function returns an array index for the serial port specified by stream. It is guaranteed to return a value suitable for an array index, in increasing order of external serial port numbers, if no error occurs.

If the stream is not recognized, SERIAL_PORTS is returned, to indicate an error.

See Also

portStream

TelePACE C Tools User and Reference Manual

May 9, 2007

354

portStream

Get Serial Port Corresponding to Index

Syntax

#include <ctools.h>

FILE *portStream(unsigned index);

Description

The portStream function returns the file pointer corresponding to index. This function is the inverse of the portIndex function. If the index is not valid, the NULL pointer is returned.

See Also

portIndex

TelePACE C Tools User and Reference Manual

May 9, 2007

355

processModbusCommand

Process a Modbus Command and Return the Response

Syntax

#include <ctools.h>

BOOLEAN processModbusCommand(

FILE * stream,

UCHAR * pCommand,

UCHAR * pResponse,

UINT16 * pResponseLength

)

Description

The processModbusCommand function processes a Modbus protocol command and returns the response. The function can be used by an application to encapsulate Modbus

RTU commands in another protocol. stream

is a FILE pointer that identifies the serial port where the command was received.

This is used for to accumulate statistics for the serial port. pCommand

is a pointer to a buffer containing the Modbus command. The contents of the buffer must be a standard Modbus RTU message. The Modbus RTU checksum is not required. commandLength

is the number of bytes in the Modbus command. The length must include all the address and data bytes. It must not include the checksum bytes, if any, in the command buffer. responseSize

is the size of the response buffer in bytes. A 300-byte buffer is recommended. If this is not practical in the application, a smaller buffer may be supplied.

Some responses may be truncated if a smaller buffer is used. pResponse

is a pointer to a buffer to contain the Modbus response. The function will store the response in this buffer in standard Modbus RTU format including two checksum bytes at the end of the response. pResponseLength

is a pointer to a variable to hold response length. The function will store the number of bytes in the response in this variable. The length will include two checksum bytes.

The function returns TRUE if the response is valid and can be used. It returns FALSE if the response is too long to fit into the supplied response buffer.

Notes

To use the function on a serial port, a protocol handler must be created for the encapsulating protocol. Set the protocol type for the port to NO_PROTOCOL to allow the custom handler to be used.

The function supports standard and extended addressing. Configure the protocol settings for the serial port for the appropriate protocol.

The Modbus RTU checksum is not required in the command so the encapsulating protocol may omit them if they are not needed. This may be useful in host devices that don't create a

Modbus RTU message with checksum prior to encapsulation.

TelePACE C Tools User and Reference Manual

May 9, 2007

356

The Modbus RTU checksum is included in the response to support encapsulating a complete Modbus RTU format message. If the checksum is not needed by the encapsulating protocol the checksum bytes may be ignored.

See Also

setProtocolSettings

Example

This example is taken from a protocol driver than encapsulates Modbus RTU messages in another protocol. It shows how to pass the Modbus RTU command to the Modbus driver, and obtain the response.

The example assumes the Modbus RTU messages are transmitted with the checksum. The length of the checksum is subtracted when calling the processModbusCommand function.

The checksum is included when responding.

Contact Control Microsystems technical support department for a complete program that uses this function.

/* receive the packet in the encapsulating protocol */

/* verify the packet is valid */

/* locate the Modbus RTU command in the command buffer */ pCommandData = commandBuffer + PROTOCOL_HEADER_SIZE;

/* get length of Modbus RTU command from the packet header */ commandLength = commandBuffer[DATA_SIZE] - 2;

/* locate the Modbus RTU response in the response buffer leaving room for the packet header */ pResponseData = responseBuffer + PROTOCOL_HEADER_SIZE;

/* process the Modbus message */ if (processModbusCommand(

stream,

pCommandData,

commandLength,

MODBUS_BUFFER_SIZE,

pResponseData,

&responseLength))

{

/* put the response length in the header */ responseBuffer[DATA_SIZE] = responseLength;

/* fill in rest of packet header */

/* transmit the encapsulated response */

}

TelePACE C Tools User and Reference Manual

May 9, 2007

357

pulse

Generate a Square Wave

Syntax

#include <ctools.h> void pulse(unsigned channel, unsigned bit, unsigned timer, unsigned on, unsigned period);

Description

The pulse function generates a square wave with a specified duty cycle on a digital output point.

channel specifies the digital output channel;

bit specified the digital output bit;

timer specifies the timer used to generate the square wave;

on specifies the time the output will be on, measured in timer ticks;

period specifies the period of the wave (on time plus off time), measured in timer ticks.

If an error occurs, the current task's error code is set as follows.

TIMER_BADTIMER if the timer number is invalid

TIMER_BADVALUE if the period is less than the on time

TIMER_BADADDR if the digital channel or bit is invalid

Notes

The length of a timer tick is set with the interval function. The default value is 0.1 seconds.

To stop the square wave, set the timer to 0 with the settimer function. The square wave will stop if the controller is reset.

To ensure an orderly start of the duty cycle, use the following sequence: settimer(t, 0); /* stop the timer */ request_resource(IO_SYSTEM); turnoff(c, b); /* start with a rising edge */ release_resource(IO_SYSTEM); pulse(c, b, t, o, p); /* start pulses */

If the specified I/O point is on when the pulse function is executed, the square wave will start with the off portion of the cycle.

Use the timeout function to generate irregular or non-repeating sequences.

Use offsets from the symbolic constants DIN_START, DIN_END, DOUT_START and

DOUT_END to reference digital channels. The constants make programs more portable and protect against future changes to the digital I/O channel numbering.

This function is provided for backward compatibility. It cannot access all 5000 series I/O modules. It is recommended that this function not be used in new programs. Instead use

Register Assignment or call the I/O driver ioWrite8Dout directly.

TelePACE C Tools User and Reference Manual

May 9, 2007

358

See Also

pulse_train, settimer, timeout, ioWrite8Dout

Example

This code fragment generates a 60% duty cycle output with a period of 5 seconds. Bit 7 of channel 3 is controlled. Timer 10 generates the square wave. settimer(10, 0); /* stop timer */ request_resource(IO_SYSTEM); turnoff(3, 7); /* turn off the bit */ release_resource(IO_SYSTEM); interval(10, 10); /* set tick rate to 1.0 s */ pulse(3, 7, 10, 3, 5); /* on = 60% of 5 = 3 */

TelePACE C Tools User and Reference Manual

May 9, 2007

359

pulse_train

Generate Finite Number of Pulses

Syntax

#include <ctools.h> void pulse_train(unsigned channel, unsigned bit, unsigned timer, unsigned

pulses);

Description

The pulse_train function generates a specified number of pulses on a digital output point.

The output is a square wave with a 50% duty cycle and a period of 200 milliseconds (5 Hz).

channel specifies the digital output channel.

bit specified the digital output bit.

timer specifies the timer used to generate the square wave.

pulses specifies the number of pulses. The timer interval acts as a multiplier of the number of pulses. The total number of pulses is pulses * interval.

If an error occurs, the current task's error code is set as follows.

TIMER_BADTIMER if the timer number is invalid

TIMER_BADVALUE if the period is less than the on time

TIMER_BADADDR if the digital channel or bit is invalid

Notes

To stop the square wave, set the timer to 0 with the settimer function. The square wave will stop if the controller is reset.

To ensure an orderly start to the pulses, use the following sequence: settimer(t, 0); /* stop the timer */ request_resource(IO_SYSTEM); turnoff(c, b); /* start with a rising edge */ release_resource(IO_SYSTEM); pulse_train(c, b, timer, pulses);

Use offsets from the symbolic constants DIN_START, DIN_END, DOUT_START and

DOUT_END to reference digital channels. The constants make programs more portable and protect against future changes to the digital I/O channel numbering.

This function is provided for backward compatibility. It cannot access all 5000 series I/O modules. It is recommended that this function not be used in new programs. Instead use

Register Assignment or call the I/O driver ioWrite8Dout directly.

See Also

pulse, settimer, timeout, ioWrite8Dout

Example

This code fragment generates 300 pulses on channel 3, bit 4. interval(2, 1); /* multiplier = 1 */ pulse_train(3, 4, 2, 300); /* 300 pulses */

TelePACE C Tools User and Reference Manual

May 9, 2007

360

This code fragment also generates 300 pulses on channel 3, bit 4. It shows the use of a multiplier. interval(2, 100); /* multiplier = 100 */ pulse_train(3, 4, 2, 3); /* 300 pulses */

TelePACE C Tools User and Reference Manual

May 9, 2007

361

queue_mode

Control Serial Data Transmission

Syntax

#include <ctools.h> void queue_mode(FILE *stream, int mode);

Description

The queue_mode function controls transmission of the serial data. Normally data output to a serial port are placed in the transmit buffer and transmitted as soon as the hardware is ready. If queuing is enabled, the characters are held in the transmit buffer until queuing is disabled. If the buffer fills, queuing is disabled automatically.

stream specifies the serial port. If it is not valid the function has no effect.

mode specifies the queuing control. It may be DISABLE or ENABLE.

Notes

Queuing is most often used with communication protocols that use character timing for message framing. Its uses in an application program are limited.

TelePACE C Tools User and Reference Manual

May 9, 2007

362

readCounter

Read Accumulator Input

Syntax

#include <ctools.h> unsigned long readCounter(unsigned counter, unsigned clear);

Description

The readCounter routine reads the digital input counter specified by counter. The counter may be 0, 1 or 2. If clear is TRUE the counter is cleared after reading; otherwise if it is

FALSE the counter continues to accumulate.

If counter is not valid, a BAD_COUNTER error is reported for the current task.

Notes

The three DIN/counter inputs are located on the SCADAPack, SCADAPack LP or

SCADAPack 100. Refer to the System Hardware Manual for more information on the hardware.

The counter increments on the rising edge of the input signal.

See Also

readCounterInput, check_error

TelePACE C Tools User and Reference Manual

May 9, 2007

363

readCounterInput

Read Counter Input Status

Syntax

#include <ctools.h> unsigned readCounterInput(unsigned input)

Description

The readCounterInput function returns the status of the DIN/counter input point specified by

input. It returns TRUE if the input is ON and FALSE if the input is OFF.

If input is not valid, the function returns FALSE.

Notes

The three DIN/counter inputs are located on the 5203 or 5204 controller board. Refer to the

System Hardware Manual for more information on the hardware.

See Also

readCounter

TelePACE C Tools User and Reference Manual

May 9, 2007

364

readBattery

Read Lithium Battery Voltage

Syntax

#include <ctools.h> int readBattery(void);

Description

The readBattery function returns the RAM backup battery voltage in millivolts. The range is

0 to 5000 mV. A normal reading is about 3600 mV.

Example

#include <ctools.h> if (readBattery() < 2500)

{ fprintf(com1, “Battery Voltage is low\r\n”);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

365

readInternalAD

Read Controller Internal Analog Inputs

Syntax

#include <ctools.h> int readInternalAD(unsigned channel);

Description

The readInternalAD function reads analog inputs connected to the internal AD converter.

channel may be 0 to 7.

The function returns a value in the range 0 to 32767.

Notes

There are only two channels with signals connected to them.

• AD_THERMISTOR reads the thermistor input.

• AD_BATTERY reads the battery input

See Also

readBattery

TelePACE C Tools User and Reference Manual

May 9, 2007

366

readStopwatch

Read Stopwatch Timer

Syntax

#include <ctools.h> unsigned long readStopwatch(void)

Description

The readStopwatch function reads the stopwatch timer. The stopwatch time is in ms and has a resolution of 10 ms. The stopwatch time rolls over to 0 when it reaches the maximum value for an unsigned long integer: 4,294,967,295 ms (or about 49.7 days).

See Also

settimer, timer

Example

This program measures the execution time in ms of an operation.

#include <ctools.h> void main(void)

{ unsigned long startTime, endTime; startTime = readStopwatch();

/* operation to be timed */ endTime = readStopwatch(); printf("Execution time = %lu ms\r\n", endTime - startTime);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

367

readThermistor

Read Controller Ambient Temperature

Syntax

#include <ctools.h> int readThermistor(unsigned scale);

Description

The readThermistor function returns the temperature measured at the main board in the specified temperature scale. If the temperature scale is not recognized, the temperature is returned in Celsius. The scale may be T_CELSIUS, T_FAHRENHEIT, T_KELVIN or

T_RANKINE.

The temperature is rounded to the nearest degree.

}

Example

#include <ctools.h> void checkTemperature(void)

{ temperature = readThermistor(T_FAHREHEIT); if (temperature < 0) fprintf(com1, “It’s COLD!!!\r\n”); else if (temperature > 90) fprintf(com1, “It’s HOT!!!\r\n”);

TelePACE C Tools User and Reference Manual

May 9, 2007

368

read_timer_info

Get Timer Status

Syntax

#include <ctools.h> struct timer_info read_timer_info(unsigned timer);

Description

The read_timer_info function gets status information for the timer specified by timer.

The read_timer_info function returns a timer_info structure with information about the specified timer. Refer to the description of the timer_info structure for information about the fields.

See Also

settimer, pulse, pulse_train, timeout

Example

This program starts a pulse train and displays timer information.

#include <ctools.h> void main(void)

{ struct timer_info tinfo;

/* Start Pulse Train */ interval(10, 1); /* multiplier = 1 */ pulse_train(3, 5, 10, 500);

{

/* Allow other tasks to execute */ release_processor();

}

/* Display Status of Pulse Train */ tinfo = read_timer_info(10); printf("Pulses Remaining: %d\r\n",

tinfo.time/2); printf("Output Channel: %d\r\n",

tinfo.channel); printf("Output Bit: %d\r\n", tinfo.bit);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

369

receive_message

Receive a Message

Syntax

#include <ctools.h> envelope *receive_message(void);

Description

The receive_message function reads the next available envelope from the message queue for the current task. If the queue is empty, the task is blocked until a message is sent to it.

The receive_message function returns a pointer to an envelope structure.

Notes

Refer to the Real Time Operating System section for more information on messages.

See Also

send_message, poll_message

Example

This task waits for messages, then prints their contents. The envelopes received are returned to the operating system.

#include <ctools.h> void show_message(void)

{

{ msg = receive_message(); printf("Message data %ld\r\n", msg->data); deallocate_envelope(msg);

}

}

TelePACE C Tools User and Reference Manual

May 9, 2007

370

release_processor

Release Processor to other Tasks

Syntax

#include <ctools.h> void release_processor(void);

Description

The release_processor function releases control of the CPU to other tasks. Other tasks of the same priority will run. Tasks of the same priority run in a round-robin fashion, as each releases the processor to the next.

Notes

The release_processor function must be called in all idle loops of a program to allow other tasks to execute.

Release all resources in use by a task before releasing the processor.

Refer to the Real Time Operating System section for more information on tasks and task scheduling.

See Also

release_resource

TelePACE C Tools User and Reference Manual

May 9, 2007

371

release_resource

Release Control of a Resource

Syntax

#include <ctools.h> void release_resource(int resource);

Description

The release_resource function releases control of the resource specified by resource.

If other tasks are waiting for the resource, the highest priority of these tasks, is given the resource and is made ready to execute. If no tasks are waiting the resource is made available, and the current task continues to run.

Notes

Refer to the Real Time Operating System section for more information on resources.

See Also

request_resource, poll_resource

Example

See the example for the request_resource function.

TelePACE C Tools User and Reference Manual

May 9, 2007

372

report_error

Set Task Error Code

Syntax

#include <ctools.h> void report_error(int error);

Description

The report_error functions sets the error code for the current task to error. An error code is maintained for each executing task.

Notes

This function is used in sharable I/O routines to return error codes to the task using the routine.

Some functions supplied with the Microtec C compiler report errors using the global variable

errno. The error code in this variable may be written over by another task before it can be used.

See also

check_error

TelePACE C Tools User and Reference Manual

May 9, 2007

373

request_resource

Obtain Control of a Resource

Syntax

#include <ctools.h> void request_resource(int resource);

Description

The request_resource function obtains control of the resource specified by resource. If the resource is in use, the task is blocked until it is available.

Notes

Use the request_resource function to control access to non-sharable resources. Refer to the Real Time Operating System section for more information on resources.

See Also

release_resource, poll_resource

Example

This code fragment obtains the dynamic memory resource, allocates some memory, and releases the resource.

#include <ctools.h> void task(void)

{

/* ... code here */

request_resource(DYNAMIC_MEMORY); ptr = (unsigned *)malloc((size_t)100);

release_resource(DYNAMIC_MEMORY);

}

/* ... more code here */

TelePACE C Tools User and Reference Manual

May 9, 2007

374

resetAllABSlaves

Erase All DF1 Slave Responses

Syntax

#include <ctools.h> unsigned resetAllABSlaves(FILE *stream);

Description

The resetAllABSlaves function is used to send a protocol message to all slaves communicating on the specified port to erase all responses not yet polled. stream specifies the serial port.

This function applies to the DF1 Half Duplex protocols only. The function returns FALSE if the protocol currently installed on the specified serial port is not an DF1 Half Duplex protocol, otherwise it returns TRUE.

Notes

The purpose of this command is to re-synch slaves with the master if the master has lost track of the order of responses to poll. This situation may exist if the master has been power cycled, for example. This function should not normally be needed if polling is done using the sample polling function "poll_for_response" shown in the example for the master_message function.

Example

This program segment will cause all slaves communicating on the com2 serial port to erase all pending responses.

#include <protocol.h> resetAllABSlaves(com2);

TelePACE C Tools User and Reference Manual

May 9, 2007

375

resetClockAlarm

Acknowledge and Reset Real Time Clock Alarm

Syntax

#include <ctools.h> void resetClockAlarm(void);

Description

Real time clock alarms occur once after being set. The alarm setting remains in the real time clock. The alarm must be acknowledged before it can occur again.

The resetClockAlarm function acknowledges the last real time clock alarm and re-enables the alarm. Calling the function after waking up from an alarm will reset the alarm for 24 hours after the current alarm.

Notes

This function should be called after a real time clock alarm occurs. This includes after returning from the sleep function with a return code of WS_REAL_TIME_CLOCK.

The alarm time is not changed by this function.

The IO_SYSTEM resource must be requested before calling this function.

See Also

setClockAlarm, getClockAlarm, alarmIn

Example

See the example for the installClockHandler function.

TelePACE C Tools User and Reference Manual

May 9, 2007

376

route

Redirect Standard I/O Streams

Syntax

#include <ctools.h> void route(FILE *logical, FILE *hardware);

Description

The route function redirects the I/O streams associated with stdout, stdin, and stderr.

These streams are routed to the com1 serial port. logical specifies the stream to redirect.

hardware specifies the hardware device which will output the data. It may be one of com1, com2, com3 or com4.

Notes

This function has a global effect, so all tasks must agree on the routing.

Output streams must be redirected to a device that supports output. Input streams must be redirected to a device that supports input.

Example

This program segment will redirect all input, output and errors to the com2 serial port.

#include <ctools.h> route(stderr, com2); /* send errors to com2 */ route(stdout, com2); /* send output to com2 */ route(stdin, com2); /* get input from com2 */

TelePACE C Tools User and Reference Manual

May 9, 2007

377

runLed

Control Run LED State

Syntax

#include <ctools.h> void runLed(unsigned state);

Description

The runLed function sets the run light LED to the specified state. state may be one of the following values.

LED_ON

LED_OFF turn on run LED turn off run LED

The run LED remains in the specified state until changed, or until the controller is reset.

Notes

The ladder logic interpreter controls the state of the RUN LED. If ladder logic is installed in the controller, a C program should not use this function.

The SCADASense series of programmable controllers do not have a RUN led.

Example

#include <ctools.h> void main(void)

{ runLed(LED_ON); /* program is running */

/* ... the rest of the code */

}

TelePACE C Tools User and Reference Manual

May 9, 2007

378

save

Write Parameters to EEPROM

Syntax

#include <ctools.h> void save(unsigned section);

Description

The save function writes data from RAM to the specified section of the EEPROM. Valid values for section are EEPROM_EVERY and EEPROM_RUN.

Notes

The EEPROM_EVERY section is loaded whenever the controller is reset. It is not used.

The EEPROM_RUN section is loaded from EEPROM to RAM when the controller is reset and the Run/Service switch is in the RUN position. Otherwise default information is used for this section. This section contains:

• serial port configuration tables

• protocol configuration tables

• store and forward enable flags

• LED power settings

• make for wake-up sources

• execution period on power-up for PID controllers

• HART modem settings

The IO_SYSTEM resource must be requested before calling this function.

See Also

load

Example

This code fragment saves all parameters. request_resource(IO_SYSTEM); save(EEPROM_RUN); release_resource(IO_SYSTEM);

TelePACE C Tools User and Reference Manual

May 9, 2007

379

send_message

Send a Message to a Task

Syntax

#include <ctools.h> void send_message(envelope *penv);

Description

The send_message function sends a message to a task. The envelope specified by penv contains the message destination, type and data.

The envelope is placed in the destination task's message queue. If the destination task is waiting for a message it is made ready to execute.

The current task is not blocked by the send_message function.

Notes

Envelopes are obtained from the operating system with the allocate_envelope function.

See Also

receive_message, poll_message, allocate_envelope

Example

This program creates a task to display a message and sends a message to it.

#include <ctools.h> void showIt(void)

{

{ msg = receive_message(); printf("Message data %ld\r\n", msg->data); deallocate_envelope(msg);

}

} void main(void)

{ envelope *msg; /* message pointer */

unsigned /* task ID */ tid = create_task(showIt, 2, APPLICATION, 1); msg = allocate_envelope(); msg->destination = tid; msg->type = MSG_DATA; msg->data = 1002;

send_message(msg);

/* wait for ever so that main and other

APPLICATION tasks won’t end */

while(TRUE)

{

/* Allow other tasks to execute */

TelePACE C Tools User and Reference Manual

May 9, 2007

380

release_processor();

}

}

TelePACE C Tools User and Reference Manual

May 9, 2007

381

setABConfiguration

Set DF1 Protocol Configuration

Syntax

#include <ctools.h> int setABConfiguration(FILE *stream, struct ABConfiguration *ABConfig);

Description

The setABConfiguration function sets DF1 protocol configuration parameters. stream specifies the serial port. ABConfig references an DF1protocol configuration structure. Refer to the description of the ABConfiguration structure for an explanation of the fields.

The setABConfiguration function returns TRUE if the settings were changed. It returns

FALSE if stream does not point to a valid serial port.

Example

This code fragment changes the maximum protected address to 7000. This is the maximum address accessible by protected DF1 commands received on com2.

#include <ctools.h> struct ABConfiguration ABConfig; getABConfiguration(com2, &ABConfig);

ABConfig.max_protected_address = 7000; setABConfiguration(com2, &ABConfig);

TelePACE C Tools User and Reference Manual

May 9, 2007

382

setBootType

Set Controller Boot Up State

Syntax

#include <ctools.h> void setBootType(unsigned type);

Description

The setBootType function defines the controller boot up type code. This function is used by the operating system start up routines. It should not be used in an application program.

Notes

The value set with this function can be read with the getBootType function.

TelePACE C Tools User and Reference Manual

May 9, 2007

383

setclock

Set Real Time Clock

Syntax

#include <ctools.h> void setclock(struct clock *now);

Description

The setclock function sets the real time clock. now references a clock structure containing the time and date to be set.

Refer to the Structures and Types section for a description of the fields. All fields of the clock structure must be set with valid values for the clock to operate properly.

Notes

The IO_SYSTEM resource must be requested before calling this function.

See Also

getclock

Example

This function switches the clock to daylight savings time.

#include <ctools.h>

#include <primitiv.h> void daylight(void)

{ struct clock now;

request_resource(IO_SYSTEM); now = getclock(); now.hour = now.hour + 1 % 24;

setclock(&now);

request_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

384

setClockAlarm

Set the Real Time Clock Alarm

Syntax

#include <ctools.h> unsigned setClockAlarm(ALARM_SETTING alarm);

Description

The setClockAlarm function configures the real time clock to alarm at the specified alarm setting. The ALARM_SETTING structure alarm specifies the time of the alarm. Refer to the

rtc.h section for a description of the fields in the structure.

The function returns TRUE if the alarm can be configured, and FALSE if there is an error in the alarm setting. No change is made to the alarm settings if there is an error.

Notes

An alarm will occur only once, but remains set until disabled. Use the resetClockAlarm function to acknowledge an alarm that has occurred and re-enable the alarm for the same time.

Set the alarm type to AT_NONE to disable an alarm. It is not necessary to specify the hour, minute and second when disabling the alarm.

The IO_SYSTEM resource must be requested before calling this function.

See Also

alarmIn, getclock

Example

#include <ctools.h>

/* --------------------------------------------

wakeUpAtEight

The wakeUpAtEight function sets an alarm for 08:00 AM and puts the controller into

-------------------------------------------- */ void wakeUpAtEight(void)

{

/* Set alarm for 08:00 */ alarm.type = AT_ABSOLUTE; alarm.hour = 8; alarm.minute = 0; alarm.second = 0;

/* Set the alarm */

request_resource(IO_SYSTEM);

setClockAlarm(alarm)

release_resource(IO_SYSTEM);

TelePACE C Tools User and Reference Manual

May 9, 2007

385

/* Sleep until alarm ignoring other wake ups */

do

{ request_resource(IO_SYSTEM); wakeSource = sleep(); release_resource(IO_SYSTEM);

} until (wakeSource == WS_REAL_TIME_CLOCK);

/* Disable the alarm */ alarm.type = AT_NONE;

request_resource(IO_SYSTEM);

setClockAlarm(alarm);

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

386

setdbase

Write Value to I/O Database

Syntax

#include <ctools.h> void setdbase(unsigned type, unsigned address, int value);

Description

The setdbase function writes value to the I/O database. type specifies the method of addressing the database. address specifies the location in the database. The table below shows the valid address types and ranges

Type Address Ranges

MODBUS 00001 to NUMCOIL

10001 to 10000 + NUMSTATUS

30001 to 30000 + NUMINPUT

40001 to 40000 + NUMHOLDING

LINEAR 0 to NUMLINEAR-1

Register

Size

1 bit

1 bit

16 bit

16 bit

16 bit

Notes

If the specified register is currently forced, the I/O database remains unchanged.

When writing to LINEAR digital addresses, value is a bit mask which writes data to 16 1-bit registers at once. If any of these 1-bit registers is currently forced, only the forced registers remain unchanged.

The I/O database is not modified when the controller is reset. It is a permanent storage area, which is maintained during power outages.

Refer to the Functions Overview section for more information.

The IO_SYSTEM resource must be requested before calling this function.

See Also

overrideDbase, setForceFlag

Example

#include <ctools.h> void main(void)

{

request_resource(IO_SYSTEM); setdbase(MODBUS, 40001, 102);

/* Turn ON the first 16 coils */ setdbase(LINEAR, START_COIL, 255);

/* Write to a 16 bit register */ setdbase(LINEAR, 3020, 240);

/* Write to the 12th holding register */ setdbase(LINEAR, START_HOLDING, 330);

TelePACE C Tools User and Reference Manual

May 9, 2007

387

/* Write to the 12th holding register */ setdbase(LINEAR, START_HOLDING, 330);

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

388

setDTR

Control RS232 Port DTR Signal

Syntax

#include <ctools.h> void setDTR(FILE *stream, unsigned state);

Description

The setDTR function sets the status of the DTR signal line for the communication port specified by stream. When state is SIGNAL_ON the DTR line is asserted. When state is

SIGNAL_OFF the DTR line is de-asserted.

Notes

The DTR line follows the normal RS232 voltage levels for asserted and de-asserted states.

This function is only useful on RS232 ports. The function has no effect if the serial port is not an RS232 port.

TelePACE C Tools User and Reference Manual

May 9, 2007

389

setForceFlag

Set Force Flag State for a Register

Syntax

#include <ctools.h> unsigned setForceFlag(unsigned type, unsigned address, unsigned value);

Description

The setForceFlag function sets the force flag(s) for the specified database register(s) to

value. value is either 1 or 0, or a 16-bit mask for LINEAR digital addresses. The valid range for address is determined by the database addressing type.

If the address or addressing type is not valid, force flags are left unchanged and FALSE is returned; otherwise TRUE is returned. The table below shows the valid address types and ranges.

Type Address Ranges

MODBUS 00001 to NUMCOIL

10001 to 10000 + NUMSTATUS

30001 to 30000 + NUMINPUT

40001 to 40000 + NUMHOLDING

LINEAR 0 to NUMLINEAR-1

Register

Size

1 bit

1 bit

16 bit

16 bit

16 bit

Notes

When a register’s force flag is set, the value of the I/O database at that register is forced to its current value. This register’s value can only be modified by using the overrideDbase function or the Edit/Force Register dialog. While forced this value can not be modified by the

setdbase function, protocols, or Ladder Logic programs.

Force Flags are not modified when the controller is reset. Force Flags are in a permanent storage area, which is maintained during power outages.

The IO_SYSTEM resource must be requested before calling this function.

See Also

clearAllForcing, overrideDbase

Example

This program clears the force flag for register 40001 and sets the force flags for the 16 registers at linear address 302 (i.e. registers 10737 to 10752).

#include <ctools.h> void main(void)

{

request_resource(IO_SYSTEM); setForceFlag(MODBUS, 40001, 0); setForceFlag(LINEAR, 302, 255);

release_resource(IO_SYSTEM);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

390

setIOErrorIndication

Set I/O Module Error Indication

Syntax

#include <ctools.h> void setIOErrorIndication(unsigned state);

Description

The setIOErrorIndication function sets the I/O module error indication to the specified

state. If set to TRUE, the I/O module communication status is reported in the controller status register and Status LED. If set to FALSE, the I/O module communication status is not reported.

Notes

Refer to the 5203/4 System Manual or the SCADAPack System Manual for further information on the Status LED and Status Output.

See Also

getIOErrorIndication

TelePACE C Tools User and Reference Manual

May 9, 2007

391

setjiffy

Set the Jiffy Clock

Syntax

#include <ctools.h> void setjiffy(unsigned long value);

Description

The setjiffy function sets the system jiffy clock. The jiffy clock increments every 1/60 second. The jiffy clock rolls over to 0 after 5183999. This is the number of 1/60-second intervals in a day.

Notes

The real time clock and the jiffy clock are not related. They may drift slightly with respect to each other over several days.

Use the jiffy clock to measure times with resolution better than the 1/10th resolution provided by timers.

See Also

interval

Example

See the example for the jiffy function.

TelePACE C Tools User and Reference Manual

May 9, 2007

392

setOutputsInStopMode

Set Outputs In Stop Mode

Syntax

#include <ctools.h> void setOutputsInStopMode( unsigned doutsInStopMode, unsigned

aoutsInStopMode);

Description

The setOutputsInStopMode function sets the doutsInStopMode and aoutsInStopMode control flags to the specified state.

If doutsInStopMode is set to TRUE, then digital outputs are held at their last state when the

Ladder Logic program is stopped. If doutsInStopMode is FALSE, then digital outputs are turned OFF when the Ladder Logic program is stopped.

If aoutsInStopMode is TRUE, then analog outputs are held at their last value when the

Ladder Logic program is stopped. If aoutsInStopMode is FALSE, then analog outputs go to zero when the Ladder Logic program is stopped.

See Also

getOutputsInStopMode

Example

This program changes the output conditions to hold analog outputs at their last value when the Ladder Logic program is stopped.

#include <ctools.h> void main(void)

{

} getOutputsInStopMode( &holdDoutsOnStop, &holdAoutsOnStop); holdAoutsOnStop = TRUE;

TelePACE C Tools User and Reference Manual

May 9, 2007

393

set_pid

Write PID Block Variable

Syntax

#include <ctools.h> void set_pid(unsigned name, unsigned block, int value);

Description

The set_pid function assigns value to a PID control block variable. name must be specified by one of the variable name macros in pid.h. block must be in the range 0 to

PID_BLOCKS-1.

Notes

See the TelePACE PID Controllers Manual for a detailed description of PID control.

Values stored in PID blocks are not initialized when a program is run, and are guaranteed to retain their values during power failures and program loading. PID block variables must always be initialized by the user program.

The IO_SYSTEM resource must be requested before calling this function.

See Also

auto_pid, clear_pid, getPowerMode

Get Current Power Mode

Syntax

#include <ctools.h>

BOOLEAN getPowerMode(UCHAR* cpuPower, UCHAR* lan, UCHAR* usbPeripheral,

UCHAR* usbHost);

Description

The getPowerMode function places the current state of the CPU, LAN, USB peripheral port, and USB host port in the passed parameters. The following table lists the possible return values and their meaning.

Macro Meaning

PM_CPU_FULL

The CPU is set to run at full speed

PM_CPU_REDUCED The CPU is set to run at a reduced speed

PM_CPU_SLEEP

PM_LAN_ENABLED

The CPU is set to sleep mode

The LAN is enabled

PM_LAN_DISABLED

PM_USB_PERIPHERAL_ENABLED

The LAN is disabled

The USB peripheral port is enabled

PM_USB_PERIPHERAL_DISABLED

PM_USB_HOST_ENABLED

PM_USB_HOST_DISABLED

The USB peripheral port is disabled

The USB host port is enabled

The USB host port is disabled

PM_UNAVAILABLE

The status of the device could not be read.

TelePACE C Tools User and Reference Manual

May 9, 2007

394

TRUE is returned if the values placed in the passed parameters are valid, otherwise FALSE is returned.

The application program may set the current power mode with the setPowerMode function.

See Also setPowerMode, setWakeSource, getWakeSource

get_pid

TelePACE C Tools User and Reference Manual

May 9, 2007

395

set_port

Set Serial Port Configuration

Syntax

#include <ctools.h> void set_port(FILE *stream, struct pconfig *settings);

Description

The set_port function sets serial port communication parameters. stream must specify one of com1, com2, com3 or com4. settings references a serial port configuration structure.

Refer to the description of the pconfig structure for an explanation of the fields.

Notes

If the serial port settings are the same as the current settings, this function has no effect.

The serial port is reset when settings are changed. All data in the receive and transmit buffers are discarded.

To optimize performance, minimize the length of messages on com3 and com4. Examples of recommended uses for com3 and com4 are for local operator display terminals, and for programming and diagnostics using the TelePACE program.

The IO_SYSTEM resource must be requested before calling this function.

See Also

get_port

Example

This code fragment changes the baud rate on com2 to 19200 baud.

#include <ctools.h> struct pconfig settings; get_port(com2, &settings); settings.baud = BAUD19200; request_resource(IO_SYSTEM); set_port(com2, &settings); release_resource(IO_SYSTEM);

This code fragment sets com2 to the same settings as com1.

#include <serial.h>

#include <primitiv.h> struct pconfig settings; request_resource(IO_SYSTEM); set_port(com2, get_port(com1, &settings)); release_resource(IO_SYSTEM);

TelePACE C Tools User and Reference Manual

May 9, 2007

396

setPowerMode

Set Current Power Mode

Syntax

#include <ctools.h>

BOOLEAN setPowerMode(UCHAR cpuPower, UCHAR lan, UCHAR usbPeripheral, UCHAR usbHost);

Description

The setPowerMode function returns TRUE if the new settings were successfully applied.

The setPowerMode function allows for power savings to be realized by controlling the power to the LAN port, changing the clock speed, and individually controlling the host and peripheral USB power. The following table of macros summarizes the choices available.

Macro Meaning

PM_CPU_FULL The CPU is set to run at full speed

PM_CPU_REDUCED

PM_CPU_SLEEP

The CPU is set to run at a reduced speed

The CPU is set to sleep mode

PM_LAN_ENABLED

PM_LAN_DISABLED

PM_USB_PERIPHERAL_ENABLED

The LAN is enabled

The LAN is disabled

The USB peripheral port is enabled

PM_USB_PERIPHERAL_DISABLED

PM_USB_HOST_ENABLED

The USB peripheral port is disabled

The USB host port is enabled

PM_USB_HOST_DISABLED

PM_NO_CHANGE

The USB host port is disabled

The current value will be used

TRUE is returned if the requested change was made, otherwise FALSE is returned.

The application program may view the current power mode with the getPowerMode function.

See Also

getPowerMode, setWakeSource, getWakeSource

TelePACE C Tools User and Reference Manual

May 9, 2007

397

setProgramStatus

Set Program Status Flag

Syntax

#include <ctools.h> void setProgramStatus( unsigned status );

Description

The setProgramStatus function sets the application program status flag. The status flag is set to NEW_PROGRAM when a cold boot of the controller is performed, or a program is downloaded to the controller from the program loader.

Notes

There are two pre-defined values for the flag. However the application program may make whatever use of the flag it sees fit.

NEW_PROGRAM

PROGRAM_EXECUTED indicates the program is newly loaded. indicates the program has been executed.

See Also

getProgramStatus

Example

See the example for getProgramStatus.

TelePACE C Tools User and Reference Manual

May 9, 2007

398

set_protocol

Set Communication Protocol Configuration

Syntax

#include <ctools.h> int set_protocol(FILE *stream, struct prot_settings *settings);

Description

The set_protocol function sets protocol parameters. stream must specify one of com1,

com2, com3 or com4. settings references a protocol configuration structure. Refer to the description of the prot_settings structure for an explanation of the fields.

The set_protocol function returns TRUE if the settings were changed. It returns FALSE if there is an error in the settings or if the protocol fails to start.

The IO_SYSTEM resource must be requested before calling this function.

Notes

Setting the protocol type to NO_PROTOCOL ends the protocol task and frees the stack resources allocated to it.

Be sure to add a call to modemNotification when writing a custom protocol.

See Also

get_protocol, start_protocol, modemNotification

Example

This code fragment changes the station number of the com2 protocol to 4.

#include <ctools.h> struct prot_settings settings; get_protocol(com2, &settings); settings.station = 4; request_resource(IO_SYSTEM); set_protocol(com2, &settings); release_resource(IO_SYSTEM);

TelePACE C Tools User and Reference Manual

May 9, 2007

399

setProtocolSettings

Set Protocol Extended Addressing Configuration

Syntax

#include <ctools.h>

BOOLEAN setProtocolSettings(

FILE * stream,

PROTOCOL_SETTINGS * settings

);

Description

The setProtocolSettings function sets protocol parameters for a serial port. This function supports extended addressing.

The function has two arguments: stream is one of com1, com2, com3 or com4; and settings, a pointer to a PROTOCOL_SETTINGS structure. Refer to the description of the structure for an explanation of the parameters.

The function returns TRUE if the settings were changed. It returns FALSE if the stream is not valid, or if the protocol fails to start.

The IO_SYSTEM resource must be requested before calling this function.

Notes

Setting the protocol type to NO_PROTOCOL ends the protocol task and frees the stack resources allocated to it.

Be sure to add a call to modemNotification when writing a custom protocol.

Extended addressing is available on the Modbus RTU and Modbus ASCII protocols only.

See the TeleBUS Protocols User Manual for details.

See Also

getProtocolSettings, start_protocol, get_protocol, set_protocol, modemNotification

Example

This code fragment sets protocol parameters for the com2 serial port.

#include <ctools.h>

PROTOCOL_SETTINGS settings; settings.type = MODBUS_RTU; settings.station = 1234; settings.priority = 3; settings.SFMessaging = FALSE; settings.mode = AM_extended; request_resource(IO_SYSTEM); setProtocolSettings(com2, &settings); release_resource(IO_SYSTEM);

TelePACE C Tools User and Reference Manual

May 9, 2007

400

setProtocolSettingsEx

Sets extended protocol settings for a serial port.

Syntax

#include <ctools.h>

BOOLEAN setProtocolSettingsEx(

FILE * stream,

PROTOCOL_SETTINGS_EX * pSettings

);

Description

The setProtocolSettingsEx function sets protocol parameters for a serial port. This function supports extended addressing and Enron Modbus parameters.

The function has two arguments:

• stream specifies the serial port. It is one of com1, com2, com3 or com4.

• pSettings is a pointer to a PROTOCOL_SETTINGS_EX structure. Refer to the description of the structure for an explanation of the parameters.

The function returns TRUE if the settings were changed. It returns FALSE if the stream is not valid, or if the protocol fails to start.

Notes

The IO_SYSTEM resource must be requested before calling this function.

Setting the protocol type to NO_PROTOCOL ends the protocol task and frees the stack resources allocated to it.

Be sure to add a call to modemNotification when writing a custom protocol.

Extended addressing and the Enron Modbus station are available on the Modbus RTU and

Modbus ASCII protocols only. See the TeleBUS Protocols User Manual for details.

See Also

getProtocolSettingsEx

Example

This code fragment sets protocol parameters for the com2 serial port.

#include <ctools.h>

PROTOCOL_SETTINGS_EX settings; settings.type = MODBUS_RTU; settings.station = 1; settings.priority = 3; settings.SFMessaging = FALSE; settings.mode = AM_standard; settings.enronEnabled = TRUE; settings.enronStation = 4; request_resource(IO_SYSTEM);

TelePACE C Tools User and Reference Manual

May 9, 2007

401

setProtocolSettingsEx(com2, &settings); release_resource(IO_SYSTEM);

TelePACE C Tools User and Reference Manual

May 9, 2007

402

setSFMapping

Control Translation Table Mapping

Syntax

#include <ctools.h> void setSFMapping(unsigned flag);

Description

The setSFMapping and getSFMapping functions no longer perform any useful function but are maintained as stubs for backward compatibility. Include the CNFG_StoreAndForward module in the Register Assignment to assign a store and forward table to the I/O database.

Notes

The TeleBUS Protocols User Manual describes store and forward messaging mode.

See Also

getSFMapping

TelePACE C Tools User and Reference Manual

May 9, 2007

403

setSFTranslation

Write Store and Forward Translation

Syntax

#include <ctools.h> struct SFTranslationStatus setSFTranslation(unsigned index, struct

SFTranslation translation);

Description

The setSFTranslation function writes translation into the store and forward address translation table at the location specified by index. translation consists of two port and station address pairs. The function checks for invalid translations; if the translation is not valid it is not stored.

The function returns a SFTranslationStatus structure. It is described in the Structures and

Types section. The code field of the structure is set to one of the following. If there is an error, the index field is set to the location of the translation that is not valid.

Result code

SF_VALID

SF_NO_TRANSLATION

SF_PORT_OUT_OF_RANGE

SF_STATION_OUT_OF_RANG

E

SF_ALREADY_DEFINED

SF_INDEX_OUT_OF_RANGE

Meaning

All translations are valid

The entry defines re-transmission of the same message on the same port

One or both of the serial port indexes is not valid

One or both of the stations is not valid

The translation already exists in the table

The entry referenced by index does not exist in the table

Notes

The TeleBUS Protocols User Manual describes store and forward messaging mode.

Writing a translation with both stations set to station 256 can clear a translation in the table.

Station 256 is not a valid station.

The protocol type and communication parameters may differ between serial ports. The store and forward messaging will translate the protocol messages.

The IO_SYSTEM resource must be requested before calling this function.

See Also

getSFTranslation, clearSFTranslationTable, checkSFTranslationTable

Example

This program enables store and forward messaging on com1 and com2. Two entries are placed into the store and forward table.

Note that the communication parameters and protocol type on com2 are different from com1.

#include <ctools.h> void main(void)

{ struct prot_settings settings;

TelePACE C Tools User and Reference Manual

May 9, 2007

404

struct pconfig portset; struct SFTranslation translation; struct SFTranslationStatus status;

request_resource(IO_SYSTEM);

/* Set communication parameters for port 1 */ portset.baud = BAUD9600; portset.duplex = FULL; portset.parity = NONE; portset.data_bits = DATA8; portset.stop_bits = STOP1; portset.flow_rx = DISABLE; portset.flow_tx = DISABLE; portset.type = RS232; portset.timeout = 600;

/* Set communication parameters for port 2 */ portset.baud = BAUD1200; portset.duplex = HALF; portset.parity = NONE; portset.data_bits = DATA8; portset.stop_bits = STOP1; portset.flow_rx = DISABLE; portset.flow_tx = DISABLE; portset.type = RS232; portset.timeout = 600;

/* Set up the translation table */

clearSFTranslationTable(); translation.portA = portIndex(com1); translation.stationA = 2; translation.portB = portIndex(com2); translation.stationB = 3; translation.portA = portIndex(com1); translation.stationA = 4; translation.portB = portIndex(com2); translation.stationB = 5;

/* Enable store and forward messaging */ settings.type = MODBUS_RTU; settings.station = 1; settings.priority = 3; settings.SFMessaging = TRUE; settings.type = MODBUS_ASCII; settings.station = 1; settings.priority = 3; settings.SFMessaging = TRUE;

release_resource(IO_SYSTEM);

/* Check if everything is correct */ status = checkSFTranslationTable(); if (status.code != SF_VALID)

{

/* Blink the error code on the status LED */ setStatus(status.code);

}

TelePACE C Tools User and Reference Manual

May 9, 2007

405

else

{ setStatus(0);

}

{

/* main loop of application program */

}

}

TelePACE C Tools User and Reference Manual

May 9, 2007

406

setStatus

Set Controller Status Code

Syntax

#include <ctools.h> void setStatus(unsigned code);

Description

The setStatus function sets the controller status code. When the status code is non-zero, the STAT LED blinks a binary sequence corresponding to the code. If code is zero, the

STAT LED turns off.

Notes

The status output opens if code is non-zero. Refer to the System Hardware Manual for more information. Note that there is no status output on the SCADASense seires of programmable controllers.

The binary sequence consists of short and long flashes of the error LED. A short flash of

1/10th of a second indicates a binary zero. A binary one is indicated by a longer flash of approximately 1/2 of a second. The least significant digit is output first. As few bits as possible are displayed – all leading zeros are ignored. There is a two second delay between repetitions.

The Register Assignment uses bits 0 and 1 of the status code. It is recommended that the

setStatusBit function be used instead of setStatus to prevent modification of these bits.

See Also

setStatusBit, clearStatusBit, getStatusBit

TelePACE C Tools User and Reference Manual

May 9, 2007

407

setStatusBit

Set Bits in Controller Status Code

Syntax

#include <ctools.h> unsigned setStatusBit(unsigned bitMask);

Description

The setStatusBit function sets the bits indicated by bitMask in the controller status code.

When the status code is non-zero, the STAT LED blinks a binary sequence corresponding to the code. If code is zero, the STAT LED turns off.

The function returns the value of the status register.

Notes

The status output opens if code is non-zero. Refer to the System Hardware Manual for more information. Note that there is no status output on the SCADASense series of controllers.

The binary sequence consists of short and long flashes of the STAT LED. A short flash of

1/10th of a second indicates a binary zero. A binary one is indicated by a longer flash of approximately 1/2 of a second. The least significant digit is output first. As few bits as possible are displayed – all leading zeros are ignored. There is a two second delay between repetitions.

The Register Assignment uses bits 0 and 1 of the status code.

See Also

clearStatusBit, clearStatusBit, getStatusBit

TelePACE C Tools User and Reference Manual

May 9, 2007

408

settimer

Set a Timer

Syntax

#include <ctools.h> void settimer(unsigned timer, unsigned value);

Description

The settimer function loads value into timer specified by timer. The timer counts down at the timer interval frequency.

The settimer function can reset a timer before it has finished counting down.

Notes

The settimer function cancels delayed digital I/O actions started with the timeout, pulse and pulse_train functions..

See Also

interval

Example

This code fragment sets timer 8 for 10 seconds, using an interval of 0.5 seconds. interval(8, 5); /* interval = 1/2 second */ settimer(8, 20); /* 10 second timer */

This code fragment sets timer 9 for 60 seconds using an interval of 1.0 seconds. interval(9, 10); /* interval = 1 second */ settimer(9, 60); /* 60 second timer */

TelePACE C Tools User and Reference Manual

May 9, 2007

409

setWakeSource

Sets Conditions for Waking from Sleep Mode

Syntax

#include <ctools.h> void setWakeSource(unsigned enableMask);

Description

The setWakeSource routine enables and disables sources that will wake up the processor. It enables all sources specified by enableMask. All other sources are disabled.

Valid wake up sources are listed below. Multiple sources may be ORed together.

• WS_NONE

• WS_ALL

• WS_REAL_TIME_CLOCK

• WS_INTERRUPT_INPUT

• WS_LED_POWER_SWITCH

• WS_COUNTER_0_OVERFLOW

• WS_COUNTER_1_OVERFLOW

• WS_COUNTER_2_OVERFLOW

Notes

Specifying WS_NONE as the wake up source will prevent the controller from waking, except by a power on reset.

See Also

getWakeSource, sleep

Example

The code fragments below show how to enable and disable wake up sources.

/* Wake up on all sources */ setWakeSource(WS_ALL);

/* Enable wake up on real time clock only */ setWakeSource(WS_REAL_TINE_CLOCK);

TelePACE C Tools User and Reference Manual

May 9, 2007

410

signal_event

Signal Occurrence of Event

Syntax

#include <ctools.h> void signal_event(int event_number);

Description

The signal_event function signals that the event_number event has occurred.

If there are tasks waiting for the event, the highest priority task is made ready to execute.

Otherwise the event flag is incremented. Up to 255 occurrences of an event will be recorded. The current task is blocked of there is a higher priority task waiting for the event.

Notes

Refer to the Real Time Operating System section for more information on events.

Valid events are numbered 0 to RTOS_EVENTS - 1. Any events defined in ctools.h are not valid events for use in an application program.

See Also

wait_event

Example

This program creates a task to wait for an event, then signals the event.

#include <ctools.h> void task1(void)

{

while(TRUE)

{ wait_event(20); printf("Event 20 occurred\r\n");

}

} void main(void)

{ create_task(task1, 3, APPLICATION, 4);

while(TRUE)

{

/* body of main task loop */

/* The body of this main task is intended solely for signaling the event waited for by task1. Normally main would be busy with more important things to do otherwise the code in task1 could be executed within main’s wait loop */ settimer(0, 10); /* 1 second interval */ while (timer(0)) /* wait for 1 s */

{

/* Allow other tasks to execute */

release_processor();

} signal_event(20);

TelePACE C Tools User and Reference Manual

May 9, 2007

411

}

}

TelePACE C Tools User and Reference Manual

May 9, 2007

412

sleep

Suspend Controller Operation

Syntax

#include <ctools.h> unsigned sleep(void);

Description

The sleep function puts the controller into a sleep mode. Sleep mode reduces the power consumption to a minimum by halting the microprocessor clock and shutting down the power supply. All programs halt until the controller resumes execution. All output points turn off while the controller is in sleep mode.

The sleep function does not work with the SCADAPack 100 or SCADASense series of programmable controllers. These controllers do not support sleep mode.

The controller resumes execution under the conditions shown in the table below. The application program may disable some wake up conditions. If a wake up condition is disabled the controller will not resume execution when the condition occurs. The table below shows the effect of disabling the various wake up conditions. All wake up conditions will be enabled by default. Refer to the description of the setWakeSource function for details.

Condition Wake Up Effects Disable

Allowed

Disable Effect

Hardware

Reset

External

Interrupt

Real Time

Clock Alarm

LED Power

Button

Hardware

Counter

Rollover

Application programs execute from start of program.

Program execution continues from point sleep function was executed.

Program execution continues from point sleep function was executed.

Program execution continues from point sleep function was executed.

Software portion of counter is incremented.

Program execution continues from point sleep function was executed.

Yes

Yes

Yes

Interrupt input ignored

LED power button ignored

Software portion of counter is incremented.

Controller returns to sleep mode.

The sleep function returns a wake up code indicating which condition caused the controller to resume execution.

Return Code

WS_REAL_TIME_CLOCK

WS_INTERRUPT_INPUT

WS_LED_POWER_SWITCH

Condition

real time clock alarm rising edge of interrupt input

LED Power switch pushed

TelePACE C Tools User and Reference Manual

May 9, 2007

413

Return Code

WS_COUNTER_0_OVERFLO

W

WS_COUNTER_1_OVERFLO

W

WS_COUNTER_2_OVERFLO

W

Condition

roll over of low word of counter 0 (every 65536 transitions) roll over of low word of counter 1 (every 65536 transitions) roll over of low word of counter 2 (every 65536 transitions)

Notes

The sleep function does not work with the SCADAPack 100 or SCADASense controller firmware. These controllers do not support sleep mode.

The IO_SYSTEM resource must be requested before calling this function.

See Also

setclock, alarmIn, setWakeSource, getWakeSource

Example

See the examples for the setClockAlarm and alarmIn functions.

TelePACE C Tools User and Reference Manual

May 9, 2007

414

start_protocol

Enable Protocol Task

Syntax

#include <ctools.h> int start_protocol(FILE *stream);

Description

The start_protocol function enables a protocol task on the port specified by stream. The protocol configuration settings stored in memory are used.

The start_protocol function returns TRUE if the protocol started and FALSE if there was an error.

Notes

The start_protocol function is used by the system start up routine. Application programs should use the set_protocol function to control protocol operation.

See Also

get_protocol, set_protocol

TelePACE C Tools User and Reference Manual

May 9, 2007

415

startup_task

Identify Start Up Task

Syntax

#include <ctools.h> void *startup_task(void);

Description

The startup_task function returns the address of the system or application start up task.

Notes

This function is used by the reset routine. It is normally not used in an application program.

TelePACE C Tools User and Reference Manual

May 9, 2007

416

startTimedEvent

Enable Signaling of a Regular Event

Syntax

#include <ctools.h> unsigned startTimedEvent(unsigned event, unsigned interval);

Description

The startTimedEvent function causes the specified event to be signaled at the specified

interval. interval is measured in multiples of 0.1 seconds. The task that is to receive the events should use the wait_event or poll_event functions to detect the event.

The function returns TRUE if the event can be signaled. If interval is 0 or if the event number is not valid, the function returns FALSE and no change is made to the event signaling (a previously enabled event will not be changed).

Notes

Valid events are numbered 0 to RTOS_EVENTS - 1. Any events defined in primitiv.h are not valid events for use in an application program.

The application program should stop the signaling of timed events when the task which waits for the events is ended. If the event signaling is not stopped, events will continue to build up in the queue until a function waits for them. The example below shows a simple method using the installExitHandler function.

See Also

endTimedEvent, signal_event, wait_event

Example

The program prints the time every 10 seconds.

#include <string.h>

#include <ctools.h>

#define TIME_TO_PRINT 15

/* --------------------------------------------

The shutdown function stops the signalling

of TIME_TO_PRINT events.

-------------------------------------------- */ void shutdown(void)

{

endTimedEvent(TIME_TO_PRINT);

}

/* --------------------------------------------

The main function sets up signalling of

a timed event, then waits for that event.

The time is printed each time the event

occurs.

-------------------------------------------- */ void main(void)

{ struct prot_settings settings; struct clock now;

TelePACE C Tools User and Reference Manual

May 9, 2007

417

/* Disable the protocol on serial port 1 */ settings.type = NO_PROTOCOL; settings.station = 1; settings.priority = 3; settings.SFMessaging = FALSE;

request_resource(IO_SYSTEM);

release_resource(IO_SYSTEM);

/* set up task exit handler to stop

signalling of events when this task ends */ taskStatus = getTaskInfo(0);

/* start timed event */

{ wait_event(TIME_TO_PRINT); request_resource(IO_SYSTEM); now = getclock(); release_resource(IO_SYSTEM); fprintf(com1, "Time %02u:%02u:%02u\r\n", now.hour, now.minute, now.second);

}

}

TelePACE C Tools User and Reference Manual

May 9, 2007

418

timeout

Delayed Digital Output

Syntax

#include <ctools.h> void timeout(unsigned channel, unsigned bit, unsigned timer, unsigned

delay);

Description

The timeout function initiates a delayed control action on a digital output. The output changes state when the delay expires.

channel specifies the digital output channel.

bit specifies the output point within channel.

timer specifies the timer used to measure the delay. It must be in the range 0 to 31.

delay specifies the delay in timer ticks. The interval function sets the length of a timer tick.

If an error occurs, the current task's error code is set as follows:

TIMER_BADTIMER if the timer number is invalid

TIMER_BADADDR if the digital channel or bit is invalid

Notes

To cancel a timeout, set the timer to zero.

Use the pulse function to generate a repeating square wave.

The timeout function may start a new timeout sequence before the previous one completes.

In this case, the previous timeout sequence is canceled and the new one begins.

This function is provided for backward compatibility. It cannot access all 5000 series I/O modules. It is recommended that this function not be used in new programs. Instead use

Register Assignment or call the I/O driver ioWrite8Dout directly.

See Also

interval, ioWrite8Dout, turnoff, turnon, settimer, pulse

TelePACE C Tools User and Reference Manual

May 9, 2007

419

timeoutCancel

Cancel Timeout Notification Function

Syntax

#include <ctools.h> unsigned timeoutCancel(unsigned timeoutID);

Description

This function cancels a timeout notification that was requested with the timeoutRequest function. No notification will be sent. The envelope provided when the request was made is de-allocated.

The function has one parameter: the ID of the timeout request. This is the value returned by the timeoutRequest function.

The function returns TRUE if the request was cancelled and FALSE if the timeout ID is not currently active.

Notes

The function will return FALSE if the timeout notification has already been made. In this case the envelope will not be de-allocated as it has already been given to the destination task.

That task is responsible for de-allocating the envelope.

This function cannot be called from a task exit handler. See installExitHandler function for details of exit handlers.

See Also

timeoutRequest

Example

See the example for the timeoutRequest function.

TelePACE C Tools User and Reference Manual

May 9, 2007

420

timeoutRequest

Request Timeout Notification Function

Syntax

#include <ctools.h> unsigned timeoutRequest(unsigned delay, envelope * pEnvelope);

Description

This function requests a timeout notification. A message is sent to the task specified in the envelope after the specified delay.

A task receives the message using the receive_message or poll_message function. The envelope received by the receiving task has the following characteristics.

• The source field is set to the task ID of the task that called timeoutRequest.

• The message type field is set to MSG_TIMEOUT.

• The message data is set to the timeout ID.

The function has two parameters: the length of time in tenths of a second before the timeout occurs, and a pointer to an envelope. The resolution of the delay is –0.1/+0 seconds. The notification message is sent delay-1 to delay tenths of a second after the function call.

The function returns the ID of the timeout request. This can be used to identify and cancel the timeout. The timeout ID changes with each call to the function. Although the ID will eventually repeat, it is sufficiently unique to allow the timeout notification to be identified.

This can be useful in identifying notifications received by a task and matching them with requests.

Notes

Do not de-allocate the envelope passed to timeoutRequest in the calling function. After a call to timeoutRequest either use timeoutCancel to free the envelope if the timeout has not occurred yet, or call deallocate_envelope in the destination task after the envelope has been delivered.

The timeout may be cancelled using the timeoutCancel function.

The task that receives the notification message must de-allocate the envelope after receiving it.

No checking is done on the task ID. The caller must ensure it is valid.

If the delay is zero, the message is sent immediately, provided an envelope is available.

This function cannot be called from a task exit handler. See installExitHandler function for details of exit handlers.

See Also

timeoutCancel

TelePACE C Tools User and Reference Manual

May 9, 2007

421

Example

This example shows a task that acts on messages received from other tasks and when a timeout occurs. The task waits for a message for up to 10 seconds. If it does not receive one, it proceeds with other processing anyway.

The task shows how to deal with notifications from older timeout requests. These occur when the notification was send before the timeout was cancelled. The task ignores timeout notifications that don’t match the last timeout request.

#include <mriext.h>

#include <ctools.h> void aTask(void)

{ envelope * pEnvelope;

TASKINFO thisTask; unsigned timeoutID; unsigned done;

/* get the task ID for this task */ thisTask = getTaskInfo(0); while (TRUE)

{

/* allocate an envelope and address it to this task */ pEnvelope = allocate_envelope(); pEnvelope->destination = thisTask.taskID;

/* request a timeout in 10 seconds */ timeoutID = timeoutRequest(100, pEnvelope); done = FALSE;

{

/* wait for a message or a timeout */

/* determine the message type */ if (pEnvelope->type == MSG_TIMEOUT)

{

/* does it match the last request? */

{

}

else

{

}

/* cancel the timeout */

timeoutCancel(timeoutID);

/* return the envelope to the RTOS */

deallocate_envelope(pEnvelope);

}

/* process message from other task here */

}

TelePACE C Tools User and Reference Manual

May 9, 2007

422

/* proceed with rest of task’s actions here */

}

}

TelePACE C Tools User and Reference Manual

May 9, 2007

423

timer

Read a Timer

Syntax

#include <ctools.h> unsigned timer(unsigned timer);

Description

The timer function returns the time remaining in timer. timer must be in the range 0 to 31. A zero value means that the timer has finished counting down.

If the timer number is invalid, the function returns 0 and the task's error code is set to

TIMER_BADTIMER.

Notes

See Also

interval, settimer, timeout, read_timer_info, pulse

Example

This code fragment sets a timer, then displays the time remaining until it reaches 0.

#include <ctools.h> interval(0, 1); settimer(0, 10); while (timer(0)) printf("Time %d\r\n", timer(0));

TelePACE C Tools User and Reference Manual

May 9, 2007

424

turnoff

Turn Off a Digital Output

Syntax

#include <ctools.h> int turnoff(unsigned channel, unsigned bit);

Description

The turnoff function turns off the digital output specified by channel and bit.

The turnoff function returns the value written to the channel if successful. If channel or bit is invalid, it returns –1.

Notes

The turnoff function has no effect if the specified point is configured as a digital input.

The state of the physical output is modified by the values in the I/O form, disable, and force status tables.

Multiple bits in the same channel can be set with the dout function.

Use offsets from the symbolic constants DIN_START, DIN_END, DOUT_START and

DOUT_END to reference digital channels. The constants make programs more portable and protect against future changes to the digital I/O channel numbering.

The IO_SYSTEM resource must be requested before calling this function.

This function is provided for backward compatibility. It cannot access all 5000 series I/O modules. It is recommended that this function not be used in new programs. Instead use

Register Assignment or call the I/O driver ioWrite8Dout directly.

See Also

ioWrite8Dout, turnon

TelePACE C Tools User and Reference Manual

May 9, 2007

425

turnon

Turn On a Digital Output

Syntax

#include <ctools.h> int turnon(unsigned channel, unsigned bit);

Description

The turnon function turns on the digital output specified by channel and bit.

The turnon function returns the value written to the channel if successful. If channel or bit is invalid, it returns –1.

Notes

The turnon function has no effect if the specified point is configured as a digital input.

The state of the physical output is modified by the values in the I/O form, disable, and force status tables.

Multiple bits in the same channel can be set with the dout function.

Use offsets from the symbolic constants DIN_START, DIN_END, DOUT_START and

DOUT_END to reference digital channels. The constants make programs more portable and protect against future changes to the digital I/O channel numbering.

The IO_SYSTEM resource must be requested before calling this function.

This function is provided for backward compatibility. It cannot access all 5000 series I/O modules. It is recommended that this function not be used in new programs. Instead use

Register Assignment or call the I/O driver ioWrite8Dout directly.

See Also

ioWrite8Dout, turnoff

TelePACE C Tools User and Reference Manual

May 9, 2007

426

wait_event

Wait for an Event

Syntax

#include <ctools.h> void wait_event(int event);

Description

The wait_event function tests if an event has occurred. If the event has occurred, the event counter is decrements and the function returns. If the event has not occurred, the task is blocked until it does occur.

Notes

Refer to the Real Time Operating System section for more information on events.

Valid events are numbered 0 to RTOS_EVENTS - 1. Any events defined in primitiv.h are not valid events for use in an application program.

See Also

signal_event, startTimedEvent

Example

See the example for the signal_event function.

TelePACE C Tools User and Reference Manual

May 9, 2007

427

wd_auto

Automatic Watchdog Timer Mode

Syntax

#include <ctools.h> void wd_auto(void);

Description

The wd_auto function gives control of the watchdog timer to the operating system. The timer is automatically updated by the system.

Notes

Refer to the Functions Overview section for more information.

See Also

wd_manual, wd_pulse

Example

See the example for the wd_manual function

TelePACE C Tools User and Reference Manual

May 9, 2007

428

wd_manual

Manual Watchdog Timer Mode

Syntax

#include <ctools.h> void wd_manual(void);

Description

The wd_manual function takes control of the watchdog timer.

Notes

The application program must retrigger the watchdog timer at least every 0.5 seconds using the wd_pulse function, to prevent an controller reset.

Refer to the Functions Overview section for more information.

See Also

wd_auto, wd_pulse

Example

This program takes control of the watchdog timer for a critical section of code, then returns it to the control of the operating system.

#include <ctools.h> void main(void)

{

wd_manual();

wd_pulse();

/* ... code executing in less than 0.5 s */

wd_pulse();

/* ... code executing in less than 0.5 s */

wd_auto()

}

/* ... as much code as you wish */

TelePACE C Tools User and Reference Manual

May 9, 2007

429

wd_pulse

Retrigger Watchdog Timer

Syntax

#include <ctools.h> void wd_pulse(void);

Description

The wd_pulse function retriggers the watchdog timer.

Notes

The wd_pulse function must execute at least every 0.5 seconds, to prevent an controller reset, if the wd_manual function has been executed.

Refer to the Functions Overview section for more information.

See Also

wd_auto, wd_manual

Example

See the example for the wd_manual function

TelePACE C Tools User and Reference Manual

May 9, 2007

430

TelePACE C Tools Macro Definitions

A

Macro Definition

AB Specifies Allan-Bradley database addressing.

AB_PARSER

AB_FULL_BCC

AB_FULL_CRC

System resource: DF1 protocol message parser.

Specifies the DF1 Full Duplex protocol emulation for the serial port. (BCC checksum)

Specifies the DF1 Full Duplex protocol emulation for the serial port. (CRC checksum)

AB_HALF_BCC

Specifies the DF1 Half Duplex protocol emulation for the serial port. (BCC checksum)

AB_HALF_CRC

AB_PROTOCOL

Specifies the DF1 Half Duplex protocol emulation for the serial port. (CRC checksum)

DF1 protocol firmware option

AD_BATTERY

AD_THERMISTOR

Internal AD channel connected to lithium battery

Internal AD channel connected to thermistor

ADDITIVE

AIN_END

Additive checksum

Number of last analog input channel.

AIN_START

AIO_BADCHAN

AIO_SUPPORTED

Number of first analog input channel.

Error code: bad analog input channel specified.

If defined indicates analog I/O supported.

AIO_TIMEOUT

AO

Error code: input device did not respond.

Variable name: alarm output address

AOUT_END

AOUT_START

Number of last analog output channel.

Number of first analog output channel.

APPLICATION

AT_ABSOLUTE

Specifies an application type task. All application tasks are terminated by the end_application function.

Specifies a fixed time of day alarm.

AT_NONE

Disables alarms

B

Macro Definition

BACKGROUND

System event: background I/O requested. The background I/O task uses this event. It should not be used in an application program.

BASE_TYPE_MASK

BAUD110

Controller type bit mask

Specifies 110-baud port speed.

BAUD115200

BAUD1200

Specifies 115200-baud port speed.

Specifies 1200-baud port speed.

BAUD150

BAUD19200

Specifies 150-baud port speed.

Specifies 19200-baud port speed.

BAUD2400

BAUD300

Specifies 2400-baud port speed.

Specifies 300-baud port speed.

TelePACE C Tools User and Reference Manual

May 9, 2007

431

C

Macro Definition

CA

CLASS0_FLAG

Variable name: cascade setpoint source specifies a flag for enabling DNP Class 0 data

CLASS1_FLAG

CLASS2_FLAG

CLASS3_FLAG

CLOSED specifies a flag for enabling DNP Class 1 data specifies a flag for enabling DNP Class 2 data specifies a flag for enabling DNP Class 3 data

Specifies switch is in closed position

COLD_BOOT com1

COM1_RCVR com2

Cold-boot switch depressed when CPU was reset.

Points to a file object for the com1 serial port.

System event: indicates activity on com1 receiver. The meaning depends on the character handler installed.

Points to a file object for the com2 serial port.

COM2_RCVR com3

COM3_RCVR com4

COM4_RCVR

System event: indicates activity on com2 receiver. The meaning depends on the character handler installed.

Points to a file object for the com3 serial port.

System event: indicates activity on com3 receiver. The meaning depends on the character handler installed.

Points to a file object for the com4serial port.

System event: indicates activity on com4 receiver. The meaning depends on the character handler installed.

COUNTER_CHANNELS

COUNTER_END

Specifies number of 5000 Series counter input channels

Number of last counter input channel

COUNTER_START

COUNTER_SUPPORTED

CPU_CLOCK_RATE

CR

Number of first counter input channel

If defined indicates counter I/O hardware supported.

Frequency of the system clock in cycles per second

Variable name: control register

CRC_16

CRC_CCITT

CRC-16 type CRC checksum (reverse algorithm)

CCITT type CRC checksum (reverse algorithm)

D

Macro Definition

BAUD38400

Specifies 38400-baud port speed.

BAUD4800

BAUD57600

Specifies 4800-baud port speed.

Specifies 57600-baud port speed.

BAUD600 Specifies 600-baud port speed.

BAUD75

BAUD9600

Specifies 75-baud port speed.

Specifies 9600-baud port speed.

BYTE_EOR

Byte-wise exclusive OR checksum

Macro Definition

DATA_SIZE

Maximum length of the HART command or response field.

DATA7

DATA8

Specifies 7 bit world length.

Specifies 8 bit word length.

DB

DB_BADSIZE

Variable name: deadband

Error code: out of range address specified

TelePACE C Tools User and Reference Manual

May 9, 2007

432

Macro Definition

DB_BADTYPE

Error code: bad database addressing type specified

DB_OK

DE_BadConfig

Error code: no error occurred

The modem configuration structure contains an error

DE_BusyLine The phone number called was busy

DE_CallAborted

DE_CarrierLost

A call in progress was aborted by the user

The connection to the remote site was lost (modem reported NO CARRIER). Carrier is lost for a time exceeding the S10 setting in the modem. Phone lines with call waiting are very susceptible to this condition.

DE_FailedToConnect

DE_InitError

The modem could not connect to the remote site

Modem initialization failed (the modem may be turned off)

DE_NoDialTone

Modem did not detect a dial tone or the S6 setting in the modem is too short.

DE_NoError

DE_NoModem

DE_NotInControl

No error has occurred

The serial port is not configured as a modem (port type must be RS232_MODEM). Or no modem is connected to the controller serial port.

The serial port is in use by another modem function or has answered an incoming call.

DIN_END

DIN_START

Number of last regular digital input channel.

Number of first regular digital input channel

DIO_SUPPORTED

DISABLE

If defined indicates digital I/O hardware supported.

Specifies flow control is disabled.

DNP

DO

DOUT_END

Specifies the DNP protocol for the serial port

Variable name: decrease output

Number of last regular digital output channel.

DOUT_START

DS_Calling

DS_Connected

Number of first regular digital output channel

The controller is making a connection to a remote controller

The controller is connected to a remote controller

DS_Inactive

DS_Terminating

The serial port is not in use by a modem

The controller is ending a connection to a remote controller.

DUTY_CYCLE

DYNAMIC_MEMORY

Specifies timer is generating square wave output.

System resource: all memory allocation functions such as malloc, alloc, and zalloc.

E

Macro Definition

EEPROM_EVERY EEPROM section loaded to RAM on every CPU reboot

EEPROM_RUN

EEPROM_SUPPORTED

ENABLE

EEPROM section loaded to RAM on RUN type boots only.

If defined, indicates that there is an EEPROM in the controller.

Specifies flow control is enabled.

ER

EVEN

Variable name: error

Specifies even parity.

EX

Variable name: automatic execution period

TelePACE C Tools User and Reference Manual

May 9, 2007

433

Macro Definition

EXTENDED_DIN_END

Number of last extended digital input channel.

EXTENDED_DIN_START

EXTENDED_DOUT_END

Number of first extended digital input channel

Number of last extended digital output channel.

EXTENDED_DOUT_START Number of first extended digital output channel

F

G

Macro Definition

GA Variable name: gain

GASFLOW

GFC_4202

Gas Flow calculation firmware option

SCADASense 4202 DR controller

GFC_4202DS SCADASense 4202 DS controller

H

Macro Definition

HALF

HI

Specifies half duplex.

Variable name: high alarm setpoint

I

Macro Definition

FOPEN_MAX Redefinition of macro from stdio.h

FORCE_MULTIPLE_COILS

FORCE_SINGLE_COIL

FULL

Modbus function code

Modbus function code

FOXCOM_MESSAGE_RECEIVED This event is used when a Foxcom message is received. An application program cannot use this event.

FOXCOM_STARTED

This event is used when Foxcom communication has been established with a sensor. An application program cannot use this event.

FS

Variable name: full scale output limit

Specifies full duplex.

Macro Definition

IB

Variable name: input bias

IH Variable name: inhibit execution address

IN

IO

Variable name: integrated error

Variable name: increase output

IO_SYSTEM

IP

System resource for all I/O hardware functions.

Variable name: input source

TelePACE C Tools User and Reference Manual

May 9, 2007

434

L

Macro Definition

LED_OFF

LED_ON

Specifies LED is to be turned off.

Specifies LED is to be turned on.

LINEAR

LO

Specifies linear database addressing.

Variable name: low alarm setpoint

LOAD_MULTIPLE_REGISTERS Modbus function code

LOAD_SINGLE_REGISTER

Modbus function code

LOCAL_COUNTERS Number of 5203/4 counter inputs

M

Macro Definition

MAX_PRIORITY The maximum task priority.

MM_BAD_ADDRESS

MM_BAD_FUNCTION

Master message status: invalid database address

Master message status: invalid function code

MM_BAD_LENGTH

MM_BAD_SLAVE

MM_NO_MESSAGE

Master message status: invalid message length

Master message status: invalid slave station address

Master message status: no message was sent.

MM_PROTOCOL_NOT_SUPPORTED

MM_RECEIVED

Master message status: selected protocol is not supported.

Master message status: response received.

MM_RECEIVED_BAD_LENGTH

MM_SENT

Master message status: response received with the incorrect amount of data.

Master message status: message was sent.

MODBUS

MM_EOT

MM_WRONG_RSP

Specifies Modbus database addressing.

Master message status: DF1 slave response was an EOT message

Master message status: DF1slave response did not match command sent.

MM_CMD_ACKED

Master message status: DF1half duplex command has been acknowledged by slave –

Master may now send poll command.

MM_EXCEPTION_ADDRESS

MM_EXCEPTION_DEVICE_BUSY

Master message status: Modbus slave returned a Device Busy exception.

MM_EXCEPTION_DEVICE_FAILURE Master message status: Modbus slave returned a Device Failure exception

MM_EXCEPTION_FUNCTION

Master message status: Modbus slave returned a function exception.

MM_EXCEPTION_VALUE

Master message status: Modbus slave returned a value exception.

MODBUS_ASCII

Master message status: Modbus slave returned an address exception.

MODBUS_PARSER

Specifies the Modbus ASCII protocol emulation for the serial port.

System resource: Modbus protocol message parser.

TelePACE C Tools User and Reference Manual

May 9, 2007

435

Macro Definition

MODBUS_RTU

Specifies the Modbus RTU protocol emulation for the serial port.

MODEM_CMD_MAX_LEN

Maximum length of the modem initialization command string

MODEM_MSG

MSG_DATA

System event: new modem message generated.

Specifies the data field in an envelope contains a data value.

MSG_POINTER

Specifies the data field in an envelope contains a pointer.

N

O

Macro Definition

OB

ODD

Variable name: output bias

Specifies odd parity.

OB

OP

Variable name: output bias

Variable name: output

OPEN

Specifies switch is in open position

P

Macro Definition

NEVER

System event: this event will never occur.

NEW_PROGRAM Application program is newly loaded.

NO_ERROR

NO_PROTOCOL

NONE

Error code: indicates no error has occurred.

Specifies no communication protocol for the serial port.

Specifies no parity.

NORMAL

NORMAL

NOTYPE

Specifies normal count down timer.

Specifies normal count down timer.

Specifies serial port type is not known.

NUMAB

NUMCOIL

Number of registers in the Allan-Bradley database.

Number of registers in the Modbus coil section.

NUMHOLDING

Number of registers in the Modbus holding register section.

NUMINPUT

NUMLINEAR

Number of registers in the Modbus input register section.

Number of registers in the linear database.

NUMSTATUS

Number of registers in the Modbus status section.

Macro Definition

PC_FLOW_RX_RECEIVE_STOP Receiver disabled after receipt of a message.

PC_FLOW_RX_XON_XOFF

Receiver Xon/Xoff flow control.

PC_FLOW_TX_IGNORE_CTS Transmitter flow control ignores CTS.

PC_FLOW_TX_XON_XOFF

Transmitter Xon/Xoff flow control.

TelePACE C Tools User and Reference Manual

May 9, 2007

436

Macro Definition

PC_PROTOCOL_RTU_FRAMING Modbus RTU framing.

PID_ALARM

PID_ALARM_ABS

Control register mask: alarms enabled

Control register mask: absolute alarms

PID_ALARM_ACK Status register mask: alarm acknowledged

PID_ALARM_DEV

PID_ALARM_ONLY

Control register mask: deviation alarms

Control register mask: alarm only block

PID_ALARM_RATE

PID_ANALOG_IP

Control register mask: rate alarms

Control register mask: analog input

PID_ANALOG_OP

PID_BAD_BLOCK

Control register mask: analog output

Return code: bad block number specified.

PID_BAD_IO_IP

PID_BAD_IO_OP

Status register mask: I/O failure on block input

Status register mask: I/O failure on block output

PID_BLOCK_IP

PID_BLOCKS

Control register mask: input from output of another block

Number of PID blocks.

PID_CLAMP_FULL

PID_CLAMP_ZERO

Status register mask: output is clamped at full scale

Status register mask: output is clamped at zero scale

PID_ER_SQR

PID_HI_ALARM

PID_INHIBIT

Control register mask: take square root of error

Status register mask: high alarm detected

Status register mask: external inhibit input is on

PID_LO_ALARM

PID_MANUAL

Status register mask: low alarm detected

Status register mask: block is in manual mode

PID_MODE_AUTO

PID_MODE_MANUAL

Control register mask: automatic mode

Control register mask: manual mode

PID_MOTOR_OP

PID_NO_ALARM

Control register mask: motor pulse duration output

Control register mask: alarms disabled

PID_NO_ER_SQR

PID_NO_IP

Control register mask: normal error

Control register mask: no input (other than IP)

PID_NO_OP

PID_NO_PV_SQR

PID_NO_SP_TRACK

Control register mask: no output

Control register mask: normal PV

Control register mask: setpoint tracking disabled

PID_OK

PID_OUT_DB

PID_PID

Return code: operation completed successfully.

Status register mask: PID controller outside of deadband

Control register mask: PID control block

PID_PULSE_OP

PID_PV_SQR

PID_RATE_CLAMP

Control register mask: pulse duration output

Control register mask: take square root of PV

Status register mask: rate gain clamed at maximum

PID_RATIO_BIAS

PID_RUNNING

Control register mask: ratio/bias control block

Status register mask: block is executing

PID_SP_CASCADE

PID_SP_NORMAL

Control register mask: cascade setpoint

Control register mask: setpoint stored in SP

PID_SP_TRACK

PE

Control register mask: setpoint tracking enabled

Variable name: period

PHONE_NUM_MAX_LEN

PROGRAM_EXECUTED

PULSE_TRAIN

Maximum length of the phone number string

Application program has been executed.

Specifies timer is generating pulse train output.

PV

PM_CPU_FULL_CLOCK

Variable name: process value

The CPU is set to run at full speed

PM_CPU_REDUCED_CLOCK

PM_CPU_SLEEP

The CPU is set to run at a reduced speed

The CPU is set to sleep mode

TelePACE C Tools User and Reference Manual

May 9, 2007

437

R

Macro Definition

RA Variable name: rate time

RE

READ_COIL_STATUS

Variable name: reset time

Modbus function code

READ_EXCEPTION_STATUS

Modbus function code

READ_HOLDING_REGISTER

Modbus function code

READ_INPUT_REGISTER

READ_INPUT_STATUS

Modbus function code

Modbus function code

READSTATUS enum

ReadStatus

REPORT_SLAVE_ID

RS232

RS232_COLLISION_AVOIDAN

CE

RS232_MODEM

Modbus function code

Specifies serial port is an RS-232 port.

Specifies serial port is RS232 and uses CD for collision avoidance.

Specifies serial port is an RS-232 dial-up modem.

RS485_4WIRE

RTOS_ENVELOPES

RTOS_EVENTS

RTOS_PRIORITIES

Specifies serial port is a 4 wire RS-485 port.

Number of RTOS envelopes.

Number of RTOS events.

Number of RTOS task priorities.

RTOS_RESOURCES

RTOS_TASKS

RUN

Number of RTOS resource flags.

Number of RTOS tasks.

Run/Service switch is in RUN position.

S

Macro Definition

PM_LAN_ENABLED

The LAN is enabled

PM_LAN_DISABLED

PM_USB_PERIPHERAL_ENABLED

The LAN is disabled

The USB peripheral port is enabled

PM_USB_PERIPHERAL_DISABLED The USB peripheral port is disabled

PM_USB_HOST_ENABLED

PM_USB_HOST_DISABLED

The USB host port is enabled

The USB host port is disabled

PM_UNAVAILABLE

PM_NO_CHANGE

The status of the device could not be read.

The current value will be used

Macro Definition

SP Variable name: setpoint

SR

S_MODULE_FAILURE

Variable name: status register

Status LED code for I/O module communication failure

S_NORMAL

SCADAPACK

Status LED code for normal status

SCADAPack controller

SCADAPACK_LIGHT

SCADAPACK_PLUS

SCADAPack LIGHT controller

SCADAPack PLUS controller

SERIAL_PORTS

SERVICE

Number of serial ports.

Run/Service switch is in SERVICE position.

SF_ALREADY_DEFINED Result code: translation is already defined in the table

SF_INDEX_OUT_OF_RANGE

Result code: invalid translation table index

SF_NO_TRANSLATION Result code: entry does not define a translation

TelePACE C Tools User and Reference Manual

May 9, 2007

438

Macro Definition

SF_PORT_OUT_OF_RANGE

Result code: serial port is not valid

SF_STATION_OUT_OF_RANGE Result code: station number is not valid

SF_TABLE_SIZE

Number of entries in the store and forward table

SF_VALID Result code: translation is valid

SIGNAL_CTS

SIGNAL_CTS

I/O line bit mask: clear to send signal

Matches status of CTS input.

SIGNAL_DCD

SIGNAL_DCD

I/O line bit mask: carrier detect signal

Matches status of DCD input.

SIGNAL_OFF

SIGNAL_OH

Specifies a signal is de-asserted

I/O line bit mask: off hook signal

SIGNAL_OH

SIGNAL_ON

Not supported – forced low (1).

Specifies a signal is asserted

SIGNAL_RING

SIGNAL_RING

SIGNAL_VOICE

I/O line bit mask: ring signal

Not supported – forced low (0).

I/O line bit mask: voice/data switch signal

SIGNAL_VOICE

SLEEP_MODE_SUPPORTED

Not supported – forced low (0).

Defined if sleep function is supported

SMARTWIRE_5201_5202

SP

SmartWIRE 5201 and 5202 controllers

Variable name: setpoint

SR

STACK_SIZE

Variable name: status register

Size of the machine stack.

START_COIL

START_HOLDING

Start of the coils section in the linear database.

Start of the holding register section in the linear database.

START_INPUT

START_STATUS

Start of the input register section in the linear database.

Start of the status section in the linear database.

STARTUP_

APPLICATION

Specifies the application start up task.

STARTUP_SYSTEM

STOP1

STOP2

SYSTEM

Specifies the system start up task.

Specifies 1 stop bit.

Specifies 2 stop bits.

Specifies a system type task. System tasks are not terminated by the end_application function.

T

Macro Definition

T_CELSIUS

Specifies temperatures in degrees Celsius

T_FAHRENHEIT Specifies temperatures in degrees Fahrenheit

T_KELVIN

T_RANKINE

Specifies temperatures in degrees Kelvin

Specifies temperatures in degrees Rankine

TELESAFE_6000_16EX

TELESAFE_MICRO_16

TeleSAFE 6000-16EX controller

TeleSAFE Micro16 controller

TIMED_OUT

TIMEOUT

Specifies timer is has reached zero.

Specifies timer is generating timed output change.

TIMER_BADADDR

TIMER_BADINTERVAL

TIMER_BADTIMER

Error code: invalid digital I/O address

Error code: invalid timer interval

Error code: invalid timer

TIMER_BADVALUE

Error code: invalid time value

TelePACE C Tools User and Reference Manual

May 9, 2007

439

Macro Definition

TIMER_MAX

Number of last valid software timer.

TS_EXECUTING

TS_READY

Task status indicating task is executing.

Task status indicating task is ready to execute

TS_WAIT_

RESOURCE

TS_WAIT_ENVELOPE

Task status indicating task is blocked waiting for a resource

Task status indicating task is blocked waiting for an envelope

TS_WAIT_EVENT

Task status indicating task is blocked waiting for an event

TS_WAIT_MESSAGE

Task status indicating task is blocked waiting for a message

V

W

Macro Definition

WRITESTATUS enum

WriteStatus

WS_ALL All wake up sources enabled

WS_COUNTER_0_OVERFLOW

Bit mask to enable counter 0 overflow as wake up source

WS_COUNTER_1_OVERFLOW Bit mask to enable counter 1 overflow as wake up source

WS_COUNTER_2_OVERFLOW

Bit mask to enable counter 2 overflow as wake up source

WS_INTERRUPT_INPUT

WS_LED_POWER_SWITCH

Bit mask to enable interrupt input as wake up source

Bit mask to enable LED power switch as wake up

WS_NONE

WS_REAL_TIME_CLOCK source

No wake up source enabled

Bit mask to enable real time clock as wake up source

WS_UNDEFINED

Undefined wake up source

Z

Macro Definition

VI_DATE_SIZE

Number of characters in version information date field

Macro Definition

ZE

Variable name: zero scale output limit

TelePACE C Tools User and Reference Manual

May 9, 2007

440

TelePACE C Tools Structures and

Types

ABConfiguration

The ABConfiguration structure defines settings for DF1 communication protocol.

/* DF1 Protocol Configuration */ struct ABConfiguration {

};

• min_protected_address is the minimum allowable DF1 physical 16-bit address allowed in all protected commands. The default value is 0.

• max_protected_address is the maximum allowable DF1 physical 16-bit address allowed in all protected commands. The default value is NUMAB.

ADDRESS_MODE

The ADDRESS_MODE enumerated type describes addressing modes for communication protocols. typedef enum addressMode_t

{

AM_standard = 0,

AM_extended

}

ADDRESS_MODE;

• AM_standard returns standard Modbus addressing. Standard addressing allows 255 stations and is compatible with standard Modbus devices

• AM_extended returns extended addressing. Extended addressing allows 65534 stations.

ALARM_SETTING

The ALARM_SETTING structure defines a real time clock alarm setting. typedef struct alarmSetting_tag {

• type specifies the type of alarm. It may be the AT_NONE or AT_ABSOLUTE macro.

• hour specifies the hour at which the alarm will occur.

• minute specifies the minute at which the alarm will occur.

• second specifies the second at which the alarm will occur.

TelePACE C Tools User and Reference Manual

May 9, 2007

441

clock

The clock structure contains time and date for reading or writing the real time clock. struct clock {

UINT16 year;

UINT16 month;

UINT16 day;

UINT16 dayofweek;

UINT16 hour;

UINT16 minute;

UINT16 second;

};

• year is the current year. It is two digits in the range 00 to 99.

• month is the current month. It is in the range 1 to 12.

• day is the current day. It is in the range 1 to 31.

• dayofweek is the current day of the week. It is in the range 1 to 7. 1 = Sunday, 2 =

Monday…7 = Saturday.

• hour is the current hour. It is in the range 00 to 23.

• minute is the current minute. It is in the range 00 to 59.

• second is the current second. It is in the range 00 to 59.

DATALOG_CONFIGURATION

The data log configuration structure holds the configuration of the data log. Each record in a data log may hold up to eight fields. Not all the fields are used if fewer than eight variables are declared.

The amount of memory used for a record depends on the number of fields in the record and the size of each field. Use the datalogRecordSize function to determine the memory needed for each record. typedef struct datalogConfig_type {

UINT16 records; /* # of records */

UINT16 fields; /* # of fields per record */

} DATALOG_CONFIGURATION;

DATALOG_STATUS

The data log status enumerated type is used to report status information. typedef enum {

DLS_CREATED, /* data log created */

DLS_BADID, /* invalid log ID */

DLS_EXISTS, /* log already exists */

DLS_NOMEMORY, /* insufficient memory for log */

DLS_BADCONFIG /* invalid configuration */

DLS_BADSEQUENCE /* sequence number not in use */

} DATALOG_STATUS;

DATALOG_VARIABLE

The data log variable enumerated type is specify the type and size of variables to be recorded in the log.

TelePACE C Tools User and Reference Manual

May 9, 2007

442

typedef enum {

DLV_UINT16 = 0, /* 16 bit unsigned integer */

DLV_INT16,

DLV_UINT32,

/* 16 bit signed integer */

/* 32 bit unsigned integer */

DLV_INT32,

DLV_FLOAT,

DLV_CMITIME,

DLV_DOUBLE

} DATALOG_VARIABLE;

/* 32 bit signed integer */

/* 32 bit floating point */

/* 64 bit time */

/* 64 bit floating point */

DialError

The DialError enumerated type defines error responses from the dial-up modem functions and may have one of the following values. enum DialError

{

DE_NoError = 0,

DE_BadConfig,

DE_NoModem,

DE_InitError,

DE_NoDialTone,

DE_BusyLine,

DE_CallAborted,

DE_FailedToConnect,

DE_CarrierLost,

DE_NotInControl

DE_CallCut

};

• DE_NoError returns no error has occurred

• DE_BadConfig returns the modem configuration structure contains an error

• DE_NoModem returns the serial port is not configured as a modem (port type must be

RS232_MODEM). Or no modem is connected to the controller serial port.

• DE_InitError returns modem initialization failed (the modem may be turned off)

• DE_NoDialTone returns modem did not detect a dial tone or the S6 setting in the modem is too short.

• DE_BusyLine returns the phone number called was busy

• DE_CallAborted returns a call in progress was aborted by the user

• DE_FailedToConnect returns the modem could not connect to the remote site

• DE_CarrierLost returns the connection to the remote site was lost (modem reported

NO CARRIER). Carrier is lost for a time exceeding the S10 setting in the modem. Phone lines with call waiting are very susceptible to this condition.

• DE_NotInControl returns the serial port is in use by another modem function or has answered an incoming call.

• DE_CallCut returns an incoming call was disconnected while attempting to dial out.

DialState

The DialState enumerated type defines the state of the modemDial operation and may have one of the following values. enum DialState

{

TelePACE C Tools User and Reference Manual

May 9, 2007

443

DS_Inactive,

DS_Calling,

DS_Connected,

DS_Terminating

};

• DS_Inactive returns the serial port is not in use by a modem

• DS_Calling returns the controller is making a connection to a remote controller

• DS_Connected returns the controller is connected to a remote controller

• DS_Terminating returns the controller is ending a connection to a remote controller.

dnpAnalogInput

The dnpAnalogInput type describes a DNP analog input point. This type is used for both

16-bit and 32-bit points. typedef struct dnpAnalogInput_type

{

UINT16 modbusAddress;

UCHAR class;

UINT32 deadband;

} dnpAnalogInput;

• modbusAddress is the address of the Modbus register number associated with the point.

• class is the reporting class for the object. It may be set to CLASS_1, CLASS_2 or

CLASS_3

.

• deadband is the amount by which the analog input value must change before an event will be reported for the point.

dnpAnalogOutput

The dnpAnalogOutput type describes a DNP analog output point. This type is used for both 16-bit and 32-bit points. typedef struct dnpAnalogOutput_type

{

} dnpAnalogOutput;

• modbusAddress is the address of the Modbus register associated with the point.

dnpBinaryInput

The dnpBinaryInput type describes a DNP binary input point. typedef struct dnpBinaryInput_type

{

UCHAR class;

} dnpBinaryInput;

• modbusAddress is the address of the Modbus register associated with the point.

• class is the reporting class for the object. It may be set to CLASS_1, CLASS_2 or

CLASS_3

.

TelePACE C Tools User and Reference Manual

May 9, 2007

444

DNP Binary Input Extended Point

The dnpBinaryInputEx type describes an extended DNP Binary Input point. typedef struct dnpBinaryInputEx_type

{

UCHAR eventClass;

UCHAR debounce;

} dnpBinaryInputEx;

• modbusAddress is the address of the Modbus register associated with the point.

• class is the reporting class for the object. It may be set to CLASS_1, CLASS_2 or

CLASS_3

.

• debounceTime is the debounce time for thebinary input.

dnpBinaryOutput

The dnpBinaryOutput type describes a DNP binary output point. typedef struct dnpBinaryOutput_type

{

UINT16 modbusAddress1;

UINT16 modbusAddress2;

UCHAR controlType;

} dnpBinaryOutput;

• modbusAddress1 is the address of the first Modbus register associated with the point.

This field is always used.

• modbusAddress2 is the address of the second Modbus register associated with the point. This field is used only with paired outputs. See the controlType field.

• controlType determines if one or two outputs are associated with this output point. It may be set to PAIRED or NOT_PAIRED.

• A paired output uses two Modbus registers for output. The first output is the Trip output and the second is the Close output. This is used with Control Relay Output

Block objects.

• A non-paired output uses one Modbus register for output. This is used with Binary

Output objects.

DNP_CONNECTION_EVENT Type

This enumerated type lists DNP events. typedef enum dnpConnectionEventType

{

DNP_CONNECTED=0,

DNP_DISCONNECTED,

DNP_CONNECTION_REQUIRED,

DNP_MESSAGE_COMPLETE,

DNP_MESSAGE_TIMEOUT

} DNP_CONNECTION_EVENT;

• The DNP_CONNECTED event indicates that the handler has connected to the master station. The application sends this event to DNP. When DNP receives this event it will send unsolicited messages.

TelePACE C Tools User and Reference Manual

May 9, 2007

445

• The DNP_DISCONNECTED event indicates that the handler has disconnected from the master station. The application sends this event to DNP. When DNP receives this event it will request a new connection before sending unsolicited messages.

• The DNP_CONNECTION_REQUIRED event indicates that DNP wishes to connect to the master station. DNP sends this event to the application. The application should process this event by making a connection.

• The DNP_MESSAGE_COMPLETE event indicates that DNP has received confirmation of unsolicited messages from the master station. DNP sends this event to the application. The application should process this event by disconnecting. In many applications a short delay before disconnecting is useful as it allows the master station to send commands to the slave after the unsolicited reporting is complete.

• The DNP_MESSAGE_TIMEOUT event indicates that DNP has attempted to send an unsolicited message but did not receive confirmation after all attempts. This usually means there is a communication problem. DNP sends this event to the application. The application should process this event by disconnecting.

dnpConfiguration

The dnpConfiguration type describes the DNP parameters. typedef struct dnpConfiguration_type

{

UINT16 masterAddress;

UINT16 rtuAddress;

CHAR datalinkConfirm;

CHAR datalinkRetries;

UINT16 datalinkTimeout;

UINT16 operateTimeout;

UCHAR applicationConfirm;

UINT16 maximumResponse;

UCHAR applicationRetries;

UINT16 applicationTimeout;

INT16 timeSynchronization;

UINT16 BI_number;

UINT16 BI_startAddress;

CHAR BI_reportingMethod;

UINT16 BI_soebufferSize;

UINT16 BO_number;

UINT16 BO_startAddress;

UINT16 CI16_number;

UINT16 CI16_startAddress;

CHAR CI16_reportingMethod;

UINT16 CI16_bufferSize;

UINT16 CI32_number;

UINT16 CI32_startAddress;

CHAR CI32_reportingMethod;

UINT16 CI32_bufferSize;

CHAR CI32_wordOrder;

UINT16 AI16_number;

UINT16 AI16_startAddress;

CHAR AI16_reportingMethod;

UINT16 AI16_bufferSize;

UINT16 AI32_number;

UINT16 AI32_startAddress;

CHAR AI32_reportingMethod;

UINT16 AI32_bufferSize;

TelePACE C Tools User and Reference Manual

May 9, 2007

446

CHAR AI32_wordOrder;

UINT16 AISF_number;

UINT16 AISF_startAddress;

CHAR AISF_reportingMethod;

UINT16 AISF_bufferSize;

CHAR AISF_wordOrder;

UINT16 AO16_number;

UINT16 AO16_startAddress;

UINT16 AO32_number;

UINT16 AO32_startAddress;

CHAR AO32_wordOrder;

UINT16 AOSF_number;

UINT16 AOSF_startAddress;

CHAR AOSF_wordOrder;

UINT16 autoUnsolicitedClass1;

UINT16 holdTimeClass1;

UINT16 holdCountClass1;

UINT16 autoUnsolicitedClass2;

UINT16 holdTimeClass2;

UINT16 holdCountClass2;

UINT16 autoUnsolicitedClass3;

UINT16 holdTimeClass3;

UINT16 holdCountClass3;

} dnpConfiguration;

• masterAddress is the address of the master station. Unsolicited messages are sent to this station. Solicited messages must come from this station. Valid values are 0 to

65534.

• rtuAddress is the address of the RTU. The master station must send messages to this address. Valid values are 0 to 65534.

• datalinkConfirm enables requesting data link layer confirmations. Valid values are

TRUE and FALSE.

• datalinkRetries is the number of times the data link layer will retry a failed message. Valid values are 0 to 255.

• datalinkTimeout is the length of time the data link layer will wait for a response before trying again or aborting the transmission. The value is measured in milliseconds.

Valid values are 100 to 60000 in multiples of 100 milliseconds.

• operateTimeout is the length of time an operate command is valid after receiving a select command. The value is measured in seconds. Valid values are 1 to 6500.

• applicationConfirm enables requesting application layer confirmations. Valid values are TRUE and FALSE.

• maximumResponse is the maximum length of an application layer response. Valid values are 20 to 2048. The recommended value is 2048 unless the master cannot handle responses this large.

• applicationRetries is the number of times the application layer will retry a transmission. Valid values are 0 to 255.

• applicationTimeout is the length of time the application layer will wait for a response before trying again or aborting the transmission. The value is measured in milliseconds. Valid values are 100 to 60000 in multiples of 100 milliseconds. This value must be larger than the data link timeout.

TelePACE C Tools User and Reference Manual

May 9, 2007

447

• timeSynchronization defines how often the RTU will request a time synchronization from the master.

• Set this to NO_TIME_SYNC to disable time synchronization requests.

• Set this to STARTUP_TIME_SYNC to request time synchronization at start up only.

• Set this to 1 to 32767 to set the time synchronization period in seconds.

• BI_number is the number of binary input points. Valid values are 0 to 9999.

• BI_startAddress is the DNP address of the first Binary Input point.

• BI_reportingMethod determines how binary inputs are reported either Change Of

State or Log All Events.

• BI_bufferSize is the Binary Input Change Event Buffer Size.

• BO_number is the number of binary output points. Valid values are 0 to 9999.

• BO_startAddress is the DNP address of the first Binary Output point.

• CI16_number is the number of 16-bit counter input points. Valid values are 0 to 9999.

• CI16_startAddress is the DNP address of the first CI16 point.

• CI16_reportingMethod determines how CI16 inputs are reported either Change Of

State or Log All Events.

• CI16_bufferSize is the number of events in the 16-bit counter change buffer. Valid values are 0 to 9999.

• CI32_number is the number of 32-bit counter input points. Valid values are 0 to 9999.

• CI32_startAddress is the DNP address of the first CI32 point.

• CI32_reportingMethod determines how CI32 inputs are reported either Change Of

State or Log All Events.

• CI32_bufferSize is the number of events in the 32-bit counter change buffer. Valid values are 0 to 9999.

• CI32_wordOrder is the Word Order of CI32 points (0=LSW first, 1=MSW first).

• AI16_number is the number of 16-bit analog input points. Valid values are 0 to 9999.

• AI16_startAddress is the DNP address of the first AI16 point.

• AI16_reportingMethod determines how 16-bit analog changes are reported.

• Set this to FIRST_VALUE to report the value of the first change event measured.

• Set this to CURRENT_VALUE to report the value of the latest change event measured.

• AI16_bufferSize is the number of events in the 16-bit analog input change buffer.

Valid values are 0 to 9999.

• AI32_number is the number of 32-bit analog input points. Valid values are 0 to 9999.

• AI32_startAddress is the DNP address of the first AI32 point.

• AI32_reportingMethod determines how 32-bit analog changes are reported.

• Set this to FIRST_VALUE to report the value of the first change event measured.

TelePACE C Tools User and Reference Manual

May 9, 2007

448

• Set this to CURRENT_VALUE to report the value of the latest change event measured.

• AI32_bufferSize is the number of events in the 32-bit analog input change buffer.

Valid values are 0 to 9999.

• AI32_wordOrder is the Word Order of AI32 points (0=LSW first, 1=MSW first)

• AO16_number is the number of 16-bit analog output points. Valid values are 0 to 9999.

• AO16_startAddress is the DNP address of the first AO16 point.

• AO32_number is the number of 32-bit analog output points. Valid values are 0 to 9999.

• AO32_startAddress is the DNP address of the first AO32 point.

• AO32_wordOrder is the Word Order of AO32 points (0=LSW first, 1=MSW first)

• AOSF_number is the number of short float Analog Outputs.

• AOSF_startAddress is the DNP address of first AOSF point.

• AOSF_wordOrder is the Word Order of AOSF points (0=LSW first, 1=MSW first).

• autoUnsolicitedClass1 enables or disables automatic Unsolicited reporting of

Class 1 events.

• holdTimeClass1 is the maximum period to hold Class 1 events before reporting

• holdCountClass1 is the maximum number of Class 1 events to hold before reporting.

• autoUnsolicitedClass2 enables or disables automatic Unsolicited reporting of

Class 2 events.

• holdTimeClass2 is the maximum period to hold Class 2 events before reporting

• holdCountClass2 is the maximum number of Class 2 events to hold before reporting.

• autoUnsolicitedClass3 enables or disables automatic Unsolicited reporting of

Class 3 events.

• holdTimeClass3 is the maximum period to hold Class 3 events before reporting.

• holdCountClass2 is the maximum number of Class 3 events to hold before reporting.

dnpConfigurationEx

The dnpConfigurationEx type includes extra parameters in the DNP Configuration. typedef struct dnpConfigurationEx_type

{

UINT16 rtuAddress;

UCHAR datalinkConfirm;

UCHAR datalinkRetries;

UCHAR applicationConfirm;

UCHAR applicationRetries;

INT16 timeSynchronization;

TelePACE C Tools User and Reference Manual

May 9, 2007

449

UCHAR BI_reportingMethod;

UINT16 CI16_number;

UCHAR CI16_reportingMethod;

UCHAR CI32_reportingMethod;

UCHAR CI32_wordOrder;

UINT16 AI16_number;

UCHAR AI16_reportingMethod;

UCHAR AI32_reportingMethod;

UCHAR AI32_wordOrder;

UCHAR AISF_reportingMethod;

UCHAR AISF_wordOrder;

UINT16 AO16_number;

UCHAR AO32_wordOrder;

UCHAR AOSF_wordOrder;

UINT16 masterAddressCount;

UINT16 masterAddress[8];

Char modemInitString[64];

} dnpConfigurationEx;

• rtuAddress is the address of the RTU. The master station must send messages to this address. Valid values are 0 to 65534.

TelePACE C Tools User and Reference Manual

May 9, 2007

450

• datalinkConfirm enables requesting data link layer confirmations. Valid values are

TRUE and FALSE.

• datalinkRetries is the number of times the data link layer will retry a failed message. Valid values are 0 to 255.

• datalinkTimeout is the length of time the data link layer will wait for a response before trying again or aborting the transmission. The value is measured in milliseconds.

Valid values are 100 to 60000 in multiples of 100 milliseconds.

• operateTimeout is the length of time an operate command is valid after receiving a select command. The value is measured in seconds. Valid values are 1 to 6500.

• applicationConfirm enables requesting application layer confirmations. Valid values are TRUE and FALSE.

• maximumResponse is the maximum length of an application layer response. Valid values are 20 to 2048. The recommended value is 2048 unless the master cannot handle responses this large.

• applicationRetries is the number of times the application layer will retry a transmission. Valid values are 0 to 255.

• applicationTimeout is the length of time the application layer will wait for a response before trying again or aborting the transmission. The value is measured in milliseconds. Valid values are 100 to 60000 in multiples of 100 milliseconds. This value must be larger than the data link timeout.

• timeSynchronization defines how often the RTU will request a time synchronization from the master.

• Set this to NO_TIME_SYNC to disable time synchronization requests.

• Set this to STARTUP_TIME_SYNC to request time synchronization at start up only.

• Set this to 1 to 32767 to set the time synchronization period in seconds.

• BI_number is the number of binary input points. Valid values are 0 to 9999.

• BI_startAddress is the DNP address of the first Binary Input point.

• BI_reportingMethod determines how binary inputs are reported either Change Of

State or Log All Events.

• BI_soebufferSize is the Binary Input Change Event Buffer Size.

• BO_number is the number of binary output points. Valid values are 0 to 9999.

• BO_startAddress is the DNP address of the first Binary Output point.

• CI16_number is the number of 16-bit counter input points. Valid values are 0 to 9999.

• CI16_startAddress is the DNP address of the first CI16 point.

• CI16_reportingMethod determines how CI16 inputs are reported either Change Of

State or Log All Events.

• CI16_bufferSize is the number of events in the 16-bit counter change buffer. Valid values are 0 to 9999.

• CI32_number is the number of 32-bit counter input points. Valid values are 0 to 9999.

• CI32_startAddress is the DNP address of the first CI32 point.

TelePACE C Tools User and Reference Manual

May 9, 2007

451

• CI32_reportingMethod determines how CI32 inputs are reported either Change Of

State or Log All Events.

• CI32_bufferSize is the number of events in the 32-bit counter change buffer. Valid values are 0 to 9999.

• CI32_wordOrder is the Word Order of CI32 points (0=LSW first, 1=MSW first).

• AI16_number is the number of 16-bit analog input points. Valid values are 0 to 9999.

• AI16_startAddress is the DNP address of the first AI16 point.

• AI16_reportingMethod determines how 16-bit analog changes are reported.

• Set this to FIRST_VALUE to report the value of the first change event measured.

• Set this to CURRENT_VALUE to report the value of the latest change event measured.

• AI16_bufferSize is the number of events in the 16-bit analog input change buffer.

Valid values are 0 to 9999.

• AI32_number is the number of 32-bit analog input points. Valid values are 0 to 9999.

• AI32_startAddress is the DNP address of the first AI32 point.

• AI32_reportingMethod determines how 32-bit analog changes are reported.

• Set this to FIRST_VALUE to report the value of the first change event measured.

• Set this to CURRENT_VALUE to report the value of the latest change event measured.

• AI32_bufferSize is the number of events in the 32-bit analog input change buffer.

Valid values are 0 to 9999.

• AI32_wordOrder is the Word Order of AI32 points (0=LSW first, 1=MSW first)

• AISF_number is the number of short float Analog Inputs.

• AISF_startAddress is the DNP address of first AISF point.

• AISF_reportingMethod is the event reporting method, Change Of State or Log All

Events.

• AISF_bufferSize is the short float Analog Input Event Buffer Size.

• AISF_wordOrder is the word order of AISF points (0=LSW first, 1=MSW first) */

• AO16_number is the number of 16-bit analog output points. Valid values are 0 to 9999.

• AO16_startAddress is the DNP address of the first AO16 point.

• AO32_number is the number of 32-bit analog output points. Valid values are 0 to 9999.

• AO32_startAddress is the DNP address of the first AO32 point.

• AO32_wordOrder is the Word Order of AO32 points (0=LSW first, 1=MSW first)

• AOSF_number is the number of short float Analog Outputs.

• AOSF_startAddress is the DNP address of first AOSF point.

• AOSF_wordOrder is the Word Order of AOSF points (0=LSW first, 1=MSW first).

TelePACE C Tools User and Reference Manual

May 9, 2007

452

• autoUnsolicitedClass1 enables or disables automatic Unsolicited reporting of

Class 1 events.

• holdTimeClass1 is the maximum period to hold Class 1 events before reporting

• holdCountClass1 is the maximum number of Class 1 events to hold before reporting.

• autoUnsolicitedClass2 enables or disables automatic Unsolicited reporting of

Class 2 events.

• holdTimeClass2 is the maximum period to hold Class 2 events before reporting

• holdCountClass2 is the maximum number of Class 2 events to hold before reporting.

• autoUnsolicitedClass3 enables or disables automatic Unsolicited reporting of

Class 3 events.

• holdTimeClass3 is the maximum period to hold Class 3 events before reporting.

• HoldCountClass3 is the maximum number of Class 3 events to hold before reporting.

• EnableUnsolicitedOnStartup enables or disables unsolicited reporting at start-up.

• SendUnsolicitedOnStartup sends an unsolicited report at start-up.

• level2Compliance reports only level 2 compliant data types (excludes floats, AO-32).

• MasterAddressCount is the number of master stations.

• masterAddress[8] is the number of master station addresses.

• MaxEventsInResponse is the maximum number of change events to include in read response.

• PSTNDialAttempts is the maximum number of dial attempts to establish a PSTN connection.

• PSTNDialTimeout is the maximum time after initiating a PSTN dial sequence to wait for a carrier signal.

• PSTNPauseTime is the pause time between dial events.

• PSTNOnlineInactivity is the maximum time after message activity to leave a PSTN connection open before hanging up.

• PSTNDialType is the dial type: tone or pulse dialling.

• modemInitString[64] is the initialization string to send to the modem.

dnpCounterInput

The dnpCounterInput type describes a DNP counter input point. This type is used for both 16-bit and 32-bit points. typedef struct dnpCounterInput_type

{

UCHAR class;

UINT32 threshold;

} dnpCounterInput;

• modbusAddress is the address of the Modbus register number associated with the point.

TelePACE C Tools User and Reference Manual

May 9, 2007

453

• class is the reporting class for the object. It may be set to CLASS_1, CLASS_2 or

CLASS_3

.

• threshold is the amount by which the counter input value must change before an event will be reported for the point.

dnpPointType

The enumerated type DNP_POINT_TYPE includes all allowed DNP data point types. typedef enum dnpPointType

{

BI_POINT=0,

AI16_POINT,

/* binary input */

/* 16 bit analog input */

AI32_POINT,

AISF_POINT,

AILF_POINT,

CI16_POINT,

/* 32 bit analog input */

/* short float analog input */

/* long float analog input */

/* 16 bit counter output */

CI32_POINT,

BO_POINT,

AO16_POINT,

AO32_POINT,

AOSF_POINT,

AOLF_POINT

} DNP_POINT_TYPE;

/* 32 bit counter output */

/* binary output */

/* 16 bit analog output */

/* 32 bit analog output */

/* short float analog output */

/* long float analog output */

DNP_RUNTIME_STATUS

The DNP_RUNTIME_STATUS type describes a structure for holding status information about DNP event log buffers.

/* DNP Runtime Status */ typedef struct dnp_runtime_status

{

UINT16

UINT16 eventCountCI16;

UINT16 eventCountCI32;

UINT16 eventCountAI16;

UINT16 eventCountAISF;

UINT16 eventCountClass2;

UINT16 eventCountClass3;

} DNP_RUNTIME_STATUS;

• eventCountBI is number of binary input events.

• eventCountCI16 is number of 16-bit counter events.

• eventCountCI32 is number of 32-bit counter events.

• eventCountAI16 is number of 16-bit analog input events.

• eventCountAI32 is number of 32-bit analog input events.

• eventCountAISF is number of short floating-point analog input events.

• eventCountClass1 is the class 1 event counter.

• eventCountClass2 is the class 2 event counter.

TelePACE C Tools User and Reference Manual

May 9, 2007

454

• eventCountClass3 is the class 3 event counter.

envelope

The envelope type is a structure containing a message envelope. Envelopes are used for inter-task communication. typedef struct env {

struct env *link;

unsigned source;

unsigned destination;

unsigned type;

unsigned long data;

unsigned owner;

}

envelope;

• link is a pointer to the next envelope in a queue. This field is used by the RTOS. It is of no interest to an application program.

• source is the task ID of the task sending the message. This field is specified automatically by the send_message function. The receiving task may read this field to determine the source of the message.

• destination is the task ID of the task to receive the message. It must be specified before calling the send_message function.

• type specifies the type of data in the data field. It may be MSG_DATA,

MSG_POINTER, or any other value defined by the application program. This field is not required.

• data is the message data. The field may contain a datum or pointer. The application program determines the use of this field.

• owner is the task that owns the envelope. This field is set by the RTOS and must not be changed by an application program.

HART_COMMAND

The HART_COMMAND type is a structure containing a command to be sent to a HART slave device. The command field contains the HART command number. The length field contains the length of the data string to be transmitted (the byte count in HART documentation). The data field contains the data to be sent to the slave. typedef struct hartCommand_t

{ char data[DATA_SIZE];

}

HART_COMMAND;

• command is the HART command number.

• length is the number of characters in the data string.

• data[DATA_SIZE] is the data field for the command.

TelePACE C Tools User and Reference Manual

May 9, 2007

455

HART_DEVICE

The HART_DEVICE type is a structure containing information about the HART device. The information is read from the device using command 0 or command 11. The fields are identical to those read by the commands. Refer to the command documentation for more information. typedef struct hartDevice_t

{ unsigned char manufacturerID; unsigned char manufacturerDeviceType; unsigned char preamblesRequested; unsigned char commandRevision; unsigned char transmitterRevision; unsigned char softwareRevision; unsigned char hardwareRevision; unsigned char flags; unsigned long deviceID;

}

HART_DEVICE;

HART_RESPONSE

The HART_RESPONSE type is a structure containing a response from a HART slave device. The command field contains the HART command number. The length field contains the length of the data string to be transmitted (the byte count in HART documentation). The data field contains the data to be sent to the slave. typedef struct hartResponse_t

{ unsigned responseCode, unsigned length, char data[DATA_SIZE];

}

HART_RESPONSE;

• response is the response code from the device.

• length is the length of response data.

• data[DATA_SIZE] is the data field for the response.

HART_RESULT

The HART_RESULT enumeration type defines a list of results of sending a command. typedef enum hartResult_t

{

HR_NoModuleResponse=0,

HR_CommandPending,

HR_CommandSent,

HR_Response,

HR_NoResponse,

HR_WaitTransmit

}

HART_RESULT;

• HR_NoModuleResponse returns no response from HART modem module.

• HR_CommandPending returns command ready to be sent, but not sent.

• HR_CommandSent returns command sent.

TelePACE C Tools User and Reference Manual

May 9, 2007

456

• HR_Response returns response received.

• HR_NoResponse returns no response after all attempts.

• HR_WaitTransmit returns modem is not ready to transmit.

HART_SETTINGS

The HART_SETTINGS type is a structure containing the configuration for the HART modem module. The useAutoPreamble field indicates if the number of preambles is set by the value in the HART_SETTINGS structure (FALSE) or the value in the HART_DEVICE structure (TRUE). The deviceType field determines if the 5904 modem is a HART primary master or secondary master device (primary master is the recommended setting). typedef struct hartSettings_t

{ unsigned preambles;

BOOLEAN useAutoPreamble;

}

HART_SETTINGS;

• attempts is the number of command attempts (1 to 4).

• preambles is the number of preambles to send (2 to 15).

• useAutoPreamble is a flag to use the requested preambles.

• deviceType is the type of HART master (1 = primary; 0 = secondary).

HART_VARIABLE

The HART_VARIABLE type is a structure containing a variable read from a HART device.

The structure contains three fields that are used by various commands. Note that not all fields will be used by all commands. Refer to the command specific documentation. typedef struct hartVariable_t

{ float value;

}

HART_VARIABLE;

• value is the value of the variable.

• units are the units of measurement.

• variableCode is the transmitter specific variable ID.

ioModules

The ioModules enumerated type describes I/O modules used with register assignment. enum ioModules

{

DOUT_generic8 = 0,

DOUT_generic16,

DOUT_5401,

DOUT_5402,

DOUT_5406,

TelePACE C Tools User and Reference Manual

May 9, 2007

457

DOUT_5407,

DOUT_5408,

DOUT_5409,

DOUT_5411,

CNFG_clearPortCounters,

CNFG_clearProtocolCounters,

CNFG_saveToEEPROM,

CNFG_LEDPower,

SCADAPack_lowerIO,

SCADAPack_upperIO,

DIN_generic8,

DIN_generic16,

DIN_5401,

DIN_5402,

DIN_5403,

DIN_5404,

AIN_5503,

AIN_5504,

DIN_5405,

DIN_5421,

DIN_520xDigitalInputs,

DIN_520xOptionSwitches,

DIN_520xInterruptInput,

DIAG_forceLED,

AIN_generic8,

AIN_5501,

AIN_5521,

CNTR_5410,

CNTR_520xCounterInputs,

AIN_520xTemperature,

AIN_520xRAMBattery,

DIAG_controllerStatus,

DIAG_commStatus,

DIAG_protocolStatus,

AOUT_generic2,

AOUT_generic4,

AOUT_5301,

AOUT_5302,

SCADAPack_AOUT,

CNFG_portSettings,

CNFG_protocolSettings,

CNFG_realTimeClock,

CNFG_PIDBlock,

CNFG_storeAndForward,

CNFG_5904Modem,

CNFG_protocolExtended,

AIN_5502,

CNTR_520xInterruptInput,

CNFG_setSerialPortDTR,

SCADAPack_LPIO,

SCADAPack_10

CNFG_protocolExtendedEx,

SCADAPack_5604IO,

AOUT_5304,

GFC_4202IO

};

TelePACE C Tools User and Reference Manual

May 9, 2007

458

ledControl_tag

The ledControl_tag structure defines LED power control parameters. struct ledControl_tag {

};

• state is the default LED state. It is either the LED_ON or LED_OFF macro.

• time is the period, in minutes, after which the LED power returns to its default state.

ModemInit

The ModemInit structure specifies modem initialization parameters for the modemInit function. struct ModemInit

{

}; char modemCommand[MODEM_CMD_MAX_LEN + 2];

• port is the serial port where the modem is connected.

• modemCommand is the initialization string for the modem. The characters AT will be prefixed to the command, and a carriage returned suffixed to the command when it is sent to the modem. Refer to the section Modem Commands for suggested command strings for your modem.

ModemSetup

The ModemSetup structure specifies modem initialization and dialing control parameters for the modemDial function. struct ModemSetup

{

FILE * port;

}; char modemCommand[MODEM_CMD_MAX_LEN + 2]; char phoneNumber[PHONE_NUM_MAX_LEN + 2];

• port is the serial port where the modem is connected.

• dialAttempts is the number of times the controller will attempt to dial the remote controller before giving up and reporting an error.

• detectTime is the length of time in seconds that the controller will wait for carrier to be detected. It is measured from the start of the dialing attempt.

• pauseTime is the length of time in seconds that the controller will wait between dialing attempts.

• dialmethod selects pulse or tone dialing. Set dialmethod to 0 for tone dialing or 1 for pulse dialing.

• modemCommand is the initialization string for the modem. The characters AT will be prepended to the command, and a carriage returned appended to the command when it

TelePACE C Tools User and Reference Manual

May 9, 2007

459

is sent to the modem. Refer to the section Modem Commands for suggested command strings for your modem.

• phoneNumber is the phone number of the remote controller. The characters ATD and the dialing method will be prepended to the command, and a carriage returned appended to the command when it is sent to the modem.

PROTOCOL_SETTINGS

The Extended Protocol Settings structure defines settings for a communication protocol.

This structure differs from the standard settings in that it allows additional settings to be specified. typedef struct protocolSettings_t

{ unsigned char type; station; unsigned char priority;

}

PROTOCOL_SETTINGS;

• type is the protocol type. It may be one of NO_PROTOCOL, MODBUS_RTU, or

MODBUS_ASCII macros.

• station is the station address of the controller. Note that each serial port may have a different address. The valid values are determined by the communication protocol. This field is not used if the protocol type is NO_PROTOCOL.

• priority is the task priority of the protocol task. This field is not used if the protocol type is NO_PROTOCOL.

• SFMessaging is the enable Store and Forward messaging control flag.

• ADDRESS_MODE is the addressing mode, standard or extended.

PROTOCOL_SETTINGS_EX Type

This structure contains serial port protocol settings including Enron Modbus support. typedef struct protocolSettingsEx_t

{

}

PROTOCOL_SETTINGS_EX;

• type is the protocol type. It may be one of NO_PROTOCOL, MODBUS_RTU, or

MODBUS_ASCII

.

• station is the station address of the controller. Note that each serial port may have a different address. The valid values are determined by the communication protocol. This field is not used if the protocol type is NO_PROTOCOL.

TelePACE C Tools User and Reference Manual

May 9, 2007

460

• priority is the task priority of the protocol task. This field is not used if the protocol type is NO_PROTOCOL.

• SFMessaging is the enable Store and Forward messaging control flag.

• ADDRESS_MODE is the addressing mode, AM_standard or AM_extended.

• enronEnabled determines if the Enron Modbus station is enabled. It may be TRUE or

FALSE

.

• enronStation is the station address for the Enron Modbus protocol. It is used if enronEnabled

is set to TRUE. Valid values are 1 to 255 for standard addressing, and

1 to 65534 for extended addressing.

prot_settings

The Protocol Settings structure defines settings for a communication protocol. This structure differs from the extended settings in that it allows fewer settings to be specified. struct prot_settings {

unsigned char type;

unsigned char station;

unsigned char priority;

unsigned SFMessaging;

};

• type is the protocol type. It may be one of NO_PROTOCOL, MODBUS_RTU,

MODBUS_ASCII, AB_FULL_BCC, AB_HALF_BCC, AB_FULL_CRC, AB_HALF_CRC or

DNP macros.

• station is the station address of the controller. Note that each serial port may have a different address. The valid values are determined by the communication protocol. This field is not used if the protocol type is NO_PROTOCOL.

• priority is the task priority of the protocol task. This field is not used if the protocol type is NO_PROTOCOL.

• SFMessaging is the enable Store and Forward messaging control flag.

prot_status

The prot_status structure contains protocol status information. struct prot_status {

unsigned command_errors;

unsigned format_errors;

unsigned checksum_errors;

unsigned cmd_received;

unsigned cmd_sent;

unsigned rsp_received;

unsigned rsp_sent;

unsigned command;

int task_id;

unsigned stored_messages;

unsigned forwarded_messages;

};

• command_errors is the number of messages received with invalid command codes.

• format_errors is the number of messages received with bad message data.

• checksum_errors is the number of messages received with bad checksums.

TelePACE C Tools User and Reference Manual

May 9, 2007

461

• cmd_received is the number of commands received.

• cmd_sent is the number of commands sent by the master_message function.

• rsp_received is the number of responses received by the master_message function.

• rsp_sent is the number of responses sent.

• command is the status of the last protocol command sent.

• task_id is the ID of the protocol task. This field is used by the set_protocol function to control protocol execution.

• stored_messages is the number of messages stored for forwarding.

• forwarded_messages is the number of messages forwarded.

pconfig

The pconfig structure contains serial port settings. struct pconfig {

unsigned baud;

unsigned duplex;

unsigned parity;

unsigned data_bits;

unsigned stop_bits;

unsigned flow_rx;

unsigned flow_tx;

unsigned type;

unsigned timeout;

};

• baud is the communication speed. It is one of the BAUD_xxx macros.

• duplex is either the FULL or HALF macro.

• parity is one of NONE, EVEN or ODD macros.

• data_bits is the word length. It is either the DATA7 or DATA8 macro.

• stop_bits in the number of stop bits transmitted. It is either the STOP1 or STOP2 macro.

• flow_rx specifies flow control on the receiver. It is either the DISABLE or ENABLE macro.

• For com1 and com2 setting this parameter selects XON/XOFF flow control. It may be enabled or disabled.

If any protocol, other than Modbus ASCII, is used on the port you must set flow_rx to DISABLE. If Modbus ASCII or no protocol is used, you can set flow_rx to

ENABLE or DISABLE. In most cases DISABLE is recommended.

• For com3 and com4 setting this parameter selects Receiver Disable after message reception. This is used with the Modbus RTU protocol only. If the Modbus RTU protocol is used, set flow_rx to ENABLE. Otherwise set flow_rx to DISABLE.

• flow_tx specifies flow control on the transmitter. It is either the DISABLE or ENABLE macro.

• For com1 and com2 setting this parameter selects XON/XOFF flow control. It may be enabled or disabled.

TelePACE C Tools User and Reference Manual

May 9, 2007

462

If any protocol, other than Modbus ASCII, is used on the port you must set flow_tx to DISABLE. If Modbus ASCII or no protocol is used, you can set flow_tx to

ENABLE or DISABLE. In most cases DISABLE is recommended.

• For com3 and com4 setting this parameter indicates if the port should ignore the CTS signal. Setting the parameter to ENABLE causes the port to ignore the CTS signal.

• type specifies the serial port type. It is one of NOTYPE, RS232, RS232_MODEM,

RS485, or RS232_COLLISION_AVOID macros.

• timeout specifies the time the driver will wait when the transmit buffer fills, before it clears the buffer.

PORT_CHARACTERISTICS

The PORT_CHARACTERISTICS type is a structure that contains serial port characteristics. typedef struct portCharacteristics_tag { unsigned long options;

• dataflow is a bit mapped field describing the data flow options supported on the serial port. ANDing can isolate the options with the PC_FLOW_RX_RECEIVE_STOP,

PC_FLOW_RX_XON_XOFF, PC_FLOW_TX_IGNORE_CTS or

PC_FLOW_TX_XON_XOFF macros.

• buffering describes the buffering options supported. No buffering options are currently supported.

• protocol describes the protocol options supported. The macro,

PC_PROTOCOL_RTU_FRAMING is the only option supported.

• options describes additional options supported. No additional options are currently supported.

pstatus

The pstatus structure contains serial port status information. struct pstatus {

unsigned framing;

unsigned parity;

unsigned c_overrun;

unsigned b_overrun;

unsigned rx_buffer_size;

unsigned rx_buffer_used;

unsigned tx_buffer_size;

unsigned tx_buffer_used;

unsigned io_lines;

};

• framing is the number of received characters with framing errors.

• parity is the number of received characters with parity errors.

• c_overrun is the number of received character overrun errors.

• b_overrun is the number of receive buffer overrun errors.

TelePACE C Tools User and Reference Manual

May 9, 2007

463

• rx_buffer_size is the size of the receive buffer in characters.

• rx_buffer_used is the number of characters in the receive buffer.

• tx_buffer_size is the size of the transmit buffer in characters.

• tx_buffer_used is the number of characters in the transmit buffer.

• io_lines is a bit mapped field indicating the status of the I/O lines on the serial port.

The values for these lines differ between serial ports (see tables below). ANDing can isolate the signals with the SIGNAL_CTS, SIGNAL_DCD, SIGNAL_OH, SIGNAL_RING or SIGNAL_VOICE macros.

READSTATUS

The READSTATUS enumerated type indicates the status of an I

2

C bus message read and may have one of the following values. enum ReadStatus {

RS_success,

RS_selectFailed

}; typedef enum ReadStatus READSTATUS;

• RS_success returns read was successful.

• RS_selectFailed returns slave device could not be selected

regAssign

The regAssign structure is used to construct a register assignment. It is one entry in the register assignment. struct regAssign { unsigned moduleType;

};

• ioDriverType is the i/o module driver type

• moduleAddress is the address or group index for module

• startingRegister1 is the starting linear address of 1st group of consecutive registers mapped to module

• startingRegister2 is the starting linear address of 2nd group of registers

• startingRegister3 is the starting linear address of 3rd group of registers

• startingRegister4 is the starting linear address of 4th group of registers

• moduleType is the hardware or pseudo module type

TelePACE C Tools User and Reference Manual

May 9, 2007

464

• modbusStartReg1 is the starting Modbus register of 1st group

• modbusStartReg2 is the starting Modbus register of 2nd group

• modbusStartReg3 is the starting Modbus register of 3rd group

• modbusStartReg4 is the starting Modbus register of 4th group

routingTable

The routingTable type describes an entry in the DNP Routing Table.

Note that the DNP Routing Table is a list of routes, which are maintained in ascending order of DNP addresses.

typedef struct

RoutingTable_type

{

} routingTable;

• adress is the DNP address.

• comPort is the serial port interface.

• retries is the number of data link retires for this table entry.

• timeout is the timeout in milliseconds.

SFTranslation

The SFTranslation structure contains Store and Forward Messaging translation information. This is used to define an address and port translation. struct SFTranslation {

};

• portA is the index of the first serial port. The index is obtained with the portIndex function.

• stationA is the station address of the first station.

• portB is the index of the second serial port. The index is obtained with the portIndex function.

• stationB is the station address of the second station.

SFTranslationStatus

The SFTranslationStatus structure contains information about a Store and Forward

Translation table entry. It is used to report information about specific table entries. struct SFTranslationStatus {

TelePACE C Tools User and Reference Manual

May 9, 2007

465

};

• index is the location in the store and forward table to which the status code applies.

• code is the status code. It is one of SF_VALID, SF_INDEX_OUT_OF_RANGE,

SF_NO_TRANSLATION, SF_PORT_OUT_OF_RANGE,

SF_STATION_OUT_OF_RANGE, or SF_ALREADY_DEFINED macros.

TASKINFO

The TASKINFO type is a structure containing information about a task.

/* Task Information Structure */ typedef struct taskInformation_tag {

• taskID is the identifier of the task.

• priority is the execution priority of the task.

• status is the current execution status the task. This may be one of TS_READY,

TS_EXECUTING, TS_WAIT_ENVELOPE, TS_WAIT_EVENT, TS_WAIT_MESSAGE, or

TS_WAIT_RESOURCE macros.

• requirement is used if the task is waiting for an event or resource. If the status field is TS_WAIT_EVENT, then requirement indicates on which event it is waiting. If the status

field is TS_WAIT_RESOURCE then requirement indicates on which resource it is waiting.

• error is the task error code. This is the same value as returned by the check_error function.

• type is the task type. It will be either SYSTEM or APPLICATION.

taskInfo_tag

The taskInfo_tag structure contains start up task information. struct taskInfo_tag {

void *address;

unsigned stack;

unsigned identity;

};

• address is the pointer to the start up routine.

• stack is the required stack size for the routine

• identity is the type of routine found (STARTUP_APPLICATION or

STARTUP_SYSTEM)

timer_info

The timer_info structure contains information about a timer.

TelePACE C Tools User and Reference Manual

May 9, 2007

466

struct timer_info {

unsigned time;

unsigned interval;

unsigned interval_remaining;

unsigned flags;

unsigned duty_on;

unsigned duty_period;

unsigned channel;

unsigned bit;

};

• time is the time remaining in the timer in ticks.

• interval is the length of a timer tick in 10ths of a second.

• interval_remaining is the time remaining in the interval count down register in 10ths of a second.

• flags is the timer type and status bits (NORMAL, PULSE TRAIN, DUTY_CYCLE,

TIMEOUT, and TIMED_OUT). More than one condition may be true at any time.

• duty_on is the length of the on high portion of the square wave output. This is used only by the pulse function.

• duty_period is the period of the square wave output This is used only by the pulse function.

• channel and bit specify the digital output point. This is used by pulse, pulse_train and timeout functions.

VERSION

The Firmware Version Information Structure holds information about the firmware. typedef struct versionInfo_tag { char date[VI_DATE_SIZE + 1]; char copyright[VI_STRING_SIZE + 1];

• version is the firmware version number.

• controller is target controller for the firmware.

• date is a string containing the date the firmware was created.

• copyright is a string containing Control Microsystems copyright information.

WRITESTATUS

The WRITESTATUS enumerated type indicates the status of an I

2

C bus message read and may have one of the following values. enum WriteStatus {

WS_success,

WS_selectFailed,

WS_noAcknowledge

}; typedef enum WriteStatus WRITESTATUS;

• WS_success returns write was successful

• WS_selectFailed returns slave could not be selected

TelePACE C Tools User and Reference Manual

May 9, 2007

467

• WS_noAcknowledge returns slave failed to acknowledge data

TelePACE C Tools User and Reference Manual

May 9, 2007

468

C Compiler Known Problems

The C compiler supplied with the TelePACE C Tools is a product of Microtec. There are two known problems with the compiler.

Use of Initialized Static Local Variables

The compiler incorrectly allocates storage for initialized static local variables. The storage is allocated incorrectly in memory reserved for constant string data. The storage should be allocated in memory for initialized variables.

Problems Caused

A program loaded in ROM cannot modify a variable declared in this fashion.

A program loaded in RAM can modify the variable. However, the variable is in a section of program memory that the operating system expects to remain constant. Modifying the variable causes the operating system to think the program has been modified. The program continues to run correctly, but will not run again if it is stopped by the C Program Loader or if the controller is reset. The operating system detects that the program memory is corrupt and does not execute the program.

Example

The compiler generates incorrect code for the following example. Storage for the variable a is allocated in the strings section. It should be in the initvars section.

If the program is loaded in ROM, it cannot modify the variable a.

If the program is loaded in RAM, it can be run once after being written to a controller memory. All subsequent attempts to run the program will fail. void main(void)

{ static int a = 1;

a++;

/* other code here */

}

Working Around the Problem

There are two ways to work around the problem.

1. Use global variable instead of a local variable. For example: static int a = 1; void main(void)

{

a++;

/* other code here */

}

TelePACE C Tools User and Reference Manual

May 9, 2007

469

2. If the local variable is to be initialized to zero, then a non-initialized static local variable can be used. For example: void main(void)

{ static int a;

a++;

/* other code here */

}

In this example the declaration: static int a; is the same as the following: static int a = 0;

The operating systems sets non-initialized variables (stored in the zerovars section) to zero before running the program.

Correction to the Problem

This problem exists with the C Compiler supplied by Microtec. It will not be corrected. Users must work around the problem as described above.

Use of pow Function

The compiler sometimes incorrectly evaluates expressions involving the pow function with other arithmetic.

Also, a task calling the pow function requires at least 5 stack blocks. The need for more stack space by the pow function is not a compiler problem, it is simply a requirement of pow.

Problems Caused

Some arithmetic expressions involving the pow function may result in incorrect results.

When testing expressions that call pow, if the result is found to be incorrect, it will be consistently incorrect for all values used by variables in the expression.

The pow function requires at least 5 stack blocks. If 4 or less stack blocks are used by the task calling pow, the controller will overflow its stack space. When the stack space overflows the behavior is unpredictable, and will most likely cause the controller to reset.

}

Example

The compiler generates incorrect code for the following example. The result of this expression is incorrect for all values used for its variables. void main(void)

{ double a, b, c, d, e; a = pow(b, c) * (d + e);

/* other code here */

TelePACE C Tools User and Reference Manual

May 9, 2007

470

Working Around the Problem

There are two ways to work around the problem.

1. To work around the problem compute the pow result on a separate line and use the result in the arithmetic expression afterwards. For example: void main(void)

{ double a, b, c, d, e, result; result = pow(b, c); a = result * (d + e);

/* other code here */

}

Note that when a task calls the pow function it requires at least 5 stack blocks. The default stack space allocated to the main task is only 4 blocks. To modify the number of stack blocks allocated to the main task refer to the section Start-Up Function Structure for details on editing appstart.c. See the function create_task to specify the stack used by other tasks.

2. The powf function may be used instead of pow where double precision is not required.

Correction to the Problem

This problem exists with the C Compiler supplied by Microtec. It will not be corrected. Users must work around the problem as described above.

TelePACE C Tools User and Reference Manual

May 9, 2007

471

TelePACE C Tools Warranty and

License

Warranty Disclaimer

Control Microsystems makes no representation or warranty with respect to the TelePACE C

Tools. The sole obligation of Control Microsystems shall be to make available all published updates or modifications to the TelePACE C Tools at a price which will not exceed the current market price.

Limitation of Liability

The foregoing warranty is in lieu of all other warranties, expressed or implied, including but not limited to, the implied warranties of merchantability and fitness for a particular purpose.

The user shall at their own discretion determine the suitability of the TelePACE C Tools for their intended use. In no event will Control Microsystems, its agents, distributors, representatives, employees, officers, directors, or contractors be liable for any special, direct, indirect or consequential damages, losses, costs, claims, demands or claim for lost profits, fees or expenses of any nature or kind arising from the use of the TelePACE C

Tools. In accepting this product, you agree to these terms.

Modifications

Control Microsystems reserves the right to make modifications to the TelePACE C Tools and to change its specifications without notice.

Non-Disclosure

SCADAPack, TeleSAFE and TelePACE are registered trademarks of Control Microsystems.

The TelePACE C Tools is a copyrighted product of Control Microsystems. Users are specifically prohibited from copying the TelePACE C Tools, in whole or in part, by any means whatsoever, except for purposes of a backup copy, and from disclosing proprietary information belonging to Control Microsystems.

TelePACE C Tools User and Reference Manual

May 9, 2007

472

Was this manual useful for you? yes no
Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Download PDF

advertisement

Table of contents