S320 Controller Manual - Overview

Online-Documentation

S320 Controller Manual

Version 6

TetraTec GmbH
Gewerbestraße 8
71144 Steinenbronn
Deutschland / Germany
Telefon: +49 (0)7157/530056
Fax: +49 (0)7157/530057
Homepage von TetraTec www.tetratec.de
email an TetraTec info@tetratec.de

TetraTec® is a registered trademark of TetraTec Instruments GmbH.

1.1. Attention! Read the Manual!

Please read this manual carefully before putting the S320 Controller into operation.

In particular pay attention to the chapter "Appropriate Application and Safety Regulations". No liability is assumed for any direct or consequent damage caused through non-observance of the information given in this manual.

The manual at hand describes the S320 Controller and its functionality. These descriptions however do not constitute any guaranteed characteristics in a legal sense or in the sense of any product liability. The authors reserve the right to make changes to the software and to the manual without any obligation to communicate these changes to anybody. No warranty is given for the accuracy of the contents of the manual on hand. As some mistakes or omissions can not be avoided despite all efforts we appreciate any piece of your advice. In this manual we refer to registered trademarks which will not be explicitly indicated as such in the text. Therefore the absence of an indication does not exclude the rights of a third party. This english version of the manual is a translation of the german version of the manual. Obligatory in any cases is the german version of the S320 Controller manual.

1.2. Introduction

S320 Controller, Overview

The S320 Controller is a free programmable, high quality industrial process controller in a standard panel instrument case.

At the core of the S320 Controller is a 32-bit floating-point signal processor capable of processing huge amounts of information at an incredible speed. For the purposes of communication the basic model of the S320 Controller comes equipped with a standard twisted pair ethernet port, one RS232 and two RS485 interfaces. A real time clock, independent timer handling with finest resolution, a battery powered data memory is also included as well as the latest flash-memory technology which ensures safe, power supply independent storage of the programs, data and system routines.

The S320 Controller is programmed by a PC via a serial link interface. The programming is carried out in a high-level, Pascal based programming language. Any person who is familiar with any high-level language will start right off developing his own applications and will soon appreciate the range of choice of efficient functions, which allow straight forward programming without any knowledge about the hardware (e.g. serial communication, analog input, etc.) or complex algorithms (e.g. fluid properties, PID-control algorithms, spline, etc.).

All necessary software development tools and a range of programming libraries are included in delivery. A variety of different program samples illustrate the programming and can be easily modified for own applications.

Three 6-digit numerical LED displays and three 4-digit alphanumeric LED displays indicate parameters, results or any messages. Five front panel buttons establish an interface to the user. Even the basic S320 Controller unit is equipped with eight digital (PLC-compatible) inputs and outputs respectively. Their 24 volt signal allows easy communication with a PLC or is used to switch directly magnetic valves, relays, etc..

The modular design with its individual plug-in slot cards gives you the ability to adapt a powerful control system to your specific application. A multitude of specific slot cards is available to integrate all kind of analog input and output devices or to expand from the standard amount of digital ports up to your required number. A separate power supply for the sensors is generally not necessary as the sensors can be supplied directly by the slot cards which reduces wiring to a minimum.
If you require a flexible, high-performance control or measuring system at moderate price, the S320 Controller will perfectly match your expectations!

Measurement means: the world of the S320 Controller

Measurement means the world of analog signals. Values like the pressure or the temperature are picked up, processed and transmitted.

Measurement means: the world of the S320 Controller. The unrestricted programmability in a high-level, Pascal based programming language makes it very easy to process analog signals in any required form. A floating-point number which expresses directly the pressure in bar, psi or any required unit is more convenient for subsequent treatment than a raw sensor value. Thus the programming can be carried out without any knowledge of the sensors. An exchange of the measuring device does not influence the program in any way. Modifications of the program are not necessary.

All mathematical functions, basic arithmetical operations as well as scientific operations (trigonometric operations, roots, logarithm) are integral part of the programming language. PLCs (programmable logic controller) are traditionally suitable for the processing of digital signals for switches or relays. The S320 Controller is the ideal solution for measurement and controlling tasks.
Separate control panels often become unnecessary thanks to the front displays and the integrated front buttons. The buttons may be used for instance to input parameters or to switch the functionality, the displays provide significant information. The S320 Controller is furnished with PLC-compatible inputs and outputs. Relays or valves can be directly operated, input signals are directly picked up. The communication via three serial interfaces according to RS232 and RS485 respectively is completely accessible by the program. All sorts of data, results, control commands or the like can be easily exchanged.

The large memory makes it possible to record and analyse complex proceedings over a longer period. Essential data, set points, control algorithm parameters, etc. can be stored safely against power failure in the battery-powered memory or in a flash ROM section. Integrated timer support solutions wherein keeping to distinct time periods is important. An internal real time clock establishes time and date correlations.

A maximum flexibility and an individual adaptation of the S320 Controller to a certain task or a selected sensor type is guaranteed thanks to a wide range of interchangeable slot cards.
The S320 Controller offers maximum value for a moderate price.

1.3. Technical Overview

Supply

The S320 Controller needs 24 volt dc supply. The power-in connector is marked with 'SUPPLY'. The input voltage may vary in-between 18 volt and 28 volt. The voltage input is protected against overvoltage and reverse voltage with a transil diode.

The supply has galvanic isolation from the instrument's ground. The connection marked with 'PE' establishes the instrument's ground and must be connected to the protection earth. This provides the potential reference for the sensors and the serial interfaces.

The power consumption is approximately 8 watt plus the power consumption of the digital outputs. Instruments in 12 volt version are available upon request.

Displays and Keys

Three 6-digit LED displays with an effective height of 10 mm and three 4-digit alphanumeric LED displays indicate parameters, results, units and any messages. Texts and numbers are sent by simple program commands to the displays.

Five free functional panel buttons enhance the flexibility of your programs. They are marked with the functions F1, F2, F3, Up and Down. The function push buttons may be used to change the displayed value, e.g. for a representation in different units. The Up and Down push buttons usually serve for parameter setting.

Digital Inputs and Outputs

The basic version of the S320 Controller comes equipped with 8 digital inputs and outputs respectively. A higher required amount of digital I/Os can be satisfied by using a type 400 series slot card and the accompanying modules.

The digital I/Os are PLC compatible (24 volt, positive switching) and are supplied by the 24 volt main supply of the S320 Controller. These lines have galvanic isolation from the instrument's ground just like the power supply.

The digital outputs can be charged with 500 mA each which is generally sufficient for relays and valves. The outputs are short-circuit protected and secure against inductive charges up to 5 mJ. Of course it is always recommended to furnish inductive charges with clamping diodes or any comparable protection circuit. The digital inputs consume a current of approx. 5 mA.

Exchangeable Slot Cards

The S320 Controller can be adapted to various measuring tasks by plug-in slot cards. Slot cards are available for all usual tasks of measuring and controlling: they pick up sensor data, create analog outputs, read incremental encoders, measure frequency, output frequencies, etc.

The slot cards also can provide the transducer power supply. Unlike most PC plug-in boards, these slot cards make additional power supply and the need of wiring unnecessary.

The S320 Controller generates auxiliary 24 volt supply by an internal dc/dc-converter. The auxiliary supply is chargeable with approx. 500mA and also has galvanic isolation. Thus current loops can be directly supplied.

Simply remove the rear panel to exchange the slot cards. Please make sure that the inserted slot cards match with the parameters of the configuration file. Avoid the removal of the CPU board as the setting of the clock and the persistent data will get lost. NOTE: boards which are not installed in the device, are extremely sensitive to electrostatic decharges. Proper handling according to the relevant regulations is indispensable! Never install or remove slot cards in a S320 Controller while being connected to the power supply!

More details about the different slot cards are given in the corresponding chapters.
TYP100 2 x AnalogIn | TYP101 2 x AnalogIn True RMS Slotcard Type 101 | TYP110 2 x AnalogIn Slotcard Type 110
TYP120 4 x AnalogIn 0..10V Slotcard Type 120 | TYP200 2 x AnalogOut Slotcard Type 200 | TYP220 4 x AnalogOut 0..10V Slotcard Type 220
TYP310 1 x AnalogIn + 1 x AnalogOut Slotcard Type 310 | TYP400 Busmodule Slotcard Type 400 | TYP500 2 x Incremental encoder Slotcard Type 510
TYP510 2 x Counter/Freq. Slotcard Type 510 | TYP520 2 x Pulse / PWM Slotcard Type 520 |

Network interface

The builtin 10 Mbit ethernet port, accessible via a twisted pair (RJ45) jack allows the S320 Controller to exchange data with all devices "speaking" TCP/IP. The operating system contains a web server, which can be used to access web pages generated by Spell programs running on the controller with a standard web browser.

Serial Interfaces

The basic model of the S320 Controller comes equipped as standard with one RS232 interface (SER0) and two RS485 interfaces (SER1 and SER2) for half-duplex operation, all freely accessible from the program. The fourth serial interface (LINK) is reserved exclusively for the serial communication to the terminal program on the PC. The RS232 interface is equipped with a standard 9-line D-SUB connector and can be connected to a PC via a 1:1 cable. It may be used e.g. to transmit measured data to the PC. The S320 Controller programming possibilities allow to implement nearly any serial data transfer.

Real Time Clock

The S320 Controller has a real time clock supplied by a small storage cell. This cell is permanently charged while the S320 Controller is connected to a 24V supply. The system time is preserved approx. 3 months in switched-off state. The program has access to the internal system time and date. The system clock is set by the terminal program or directly by the Spell program.
A radio clock DCF-77 is available as an accessory which receives and evaluates the 'official' time signal sent through the 'Physikalisch Technische Bundesanstalt' in Mainflingen near Frankfurt/Main (Germany). It allows to update the internal real time clock automatically and permanently.

Continuous proceedings such as sampling frequencies for control circuits or similar are realised using the internal timers. They permit resolutions down to milliseconds.

Memory

The operating system of the S320 Controller, the user program, the complete source code and optionally further documentation files are stored in a non-volatile Flash-ROM. A Spell program may use the ROMPERSISTENT key word to declare variables that can be easily saved and restored from Flash-ROM. Since version 4 you also can use a filesystem to store your data. Refer to chapter S320 Filesystem and Files and Directories for detailed information.

The S320 Controller contains at least 1024 kbyte RAM for the program execution. The processor accesses this main memory without wait states.
A quick non-volatile memory stores about 32 kByte of data. This 'persistent' memory is allocated by declaring the concerning variables as 'RAMPERSISTENT' type. This memory area is suitable e.g. for storing the values of counters such as charging hours or similar. (See also chapter 'Persistent Data' for details).

Link-Connection to the PC

The data-transfer between the PC and the S320 Controller is done using the terminal program. Its functionality is described later in the chapter Development software.

There are to alternatives to create a link-connection to the S320 Controller:

RS232 connection :

The S320 Controller's connector marked 'LINK' is exclusively used for the controller's communication with the terminal program on the PC. This RS232 interface operates by default with a baud rate of 38400 and hardware handshake (RTS/CTS).

The necessary connection cable LINK2 is included in delivery.
You will find a detailed description in the chapter Technical data.

Network connection:

Simply connect the S320 Controller to your local network.
Please refer to chapter Technical data for detailed information.

Data Storing

All program sources and optionally documentation files are saved in the non-volatile flash-ROM of the S320 Controller.

Thus you can retrieve the program with its complete sources from the Controller even after years of service. If necessary you can always retrieve the original, active program, undertake modifications and retransfer the modified program.

This makes the instrument completely independent from external program sources. Of course it is always recommended to make backups and to preserve them in a safe place.

1.4. Development Tools

A performant grafic user environment for the PC supports the efficient program development for the S320 Controller. The PC program communicates with the S320 Controller via a serial interface of your PC. The necessary link cable is included in delivery. It is connected to the S320 Controller socket labeled "LINK".

The programs for the S320 Controller are created using the PC development environment. All necessary operations such as starting and stopping the controller, setting the system clock or retrieving the sources of the controller program are supported by this ergonomic grafical developer software.

Easy work control using drag&drop.
Launchpad for the direct access to the most frequent commands
Multiple embedded window technique - have all the important information in view!
Integrated ASCII terminal for the communication via a (second) serial interface
Automatic scan of the sources and listing of the includes libraries.
Text search function ('grep') over a complete project even in different directories.
Wizards supporting the calibration of analog slot cards.
Representation of measured values in diagrams (value over time or x/y diagram)

... and much more! See the chapter Programming Environment for further information.

1.5. Programming

Like a PLC the S320 Controller offers best flexibility by its free programmability. However in contrast to a PLC, programming is made easy, offering a specially designed, high-level programming language 'Spell'. Spell is a close derivative to the well-known and widely accepted language PASCAL.

The language Spell is easy to use, suitable for complex problems and generates a very efficient program code compared to known interpreters. Furthermore it permits a far-reaching error check even during compilation thanks to its strict syntax.

Modifications, extensions and cuts from standard Pascal's volume (ISO 7185) are made in respect to the Controller's maximum efficiency and highest transparency of the programs. A description of these differences is outlined in the corresponding chapters.

The program example below serves as an introduction into Spell. The program reads the voltage and the current from the AD-converters, computes the electric power and displays all three values with the corresponding units.

Program Sample, ready to run
PROGRAM CalculateElectricPower;       { S320-Programming Example  }
INCLUDE 'STDLIB';                     { External standard library }
VAR
  Voltage         : FLOAT;            { Declaration of variables  }
  Current         : FLOAT;
  Power           : FLOAT;
  chVoltage       : PortHandle;       { Declaration of channels   }
  chCurrent       : Porthandle;

BEGIN                                 { Begin program             }
  chVoltage  := OpenPort('Voltage');  { Initialise AD-converter   }
  chCurrent  := OpenPort('Current');

  ShowString(TopRight,  'Volt');      { Display units             }
  ShowString(MidRight,  'Amp ');
  ShowString(BotRight,  'VA  ');

  REPEAT
{ Calculation loop
}
Voltage  := AnalogIn(chVoltage);  { Read voltage
}
Current  := AnalogIn(chCurrent);  { Read current
}
Power    := Voltage * Current;    { Compute
electric power    }

ShowFloat(TopLeft,Voltage,2,4);   { Display voltage
}
ShowFloat(MidLeft,Current,2,4);   { Display current
}
ShowFloat(BotLeft,Power,  2,4);   { Display power
}
UNTIL False;
{ Endless loop
}
END.
{ Programmende
}

Analog and digital converters get a name in the configuration file and can be scaled so that the read value comes directly in any required physical unit. The function OpenPort assigns a channel number to the left side value. The function AnalogIn reads the converted value from the indicated A/D converter.

The functions ShowFloat and ShowString respectively are used to display the corresponding data on the LED display. For instance ShowFloat is used in the upper example to display a floating-point number on the indicated display (TopLeft) with two digits before and four digits after the decimal point.

1.6. Libraries

Libraries are included by the directive INCLUDE. The libraries offer various functions for specific actions. The standard library STDLIB contains inter alia all functions for addressing the hardware (e.g. access to analog or digital signals, display output, etc.).

The library REGEL provides functions for control application tasks. Linearise measured values using functions of the libraries LIN or POL. Gas properties can be evaluated by functions of the library GAS. A clear text display can be easily generated by functions of the library LAUFTEXT. And convert physical units by calling the UNITCON library.

1.7. Exemplary Applications

Flow Measurement

The calculation of the flow rate depends on the absolute pressure, temperature, differential pressure at the measuring device, humidity and the fluid properties. The result for the actual flow rate from the unprocessed sensor data is obtained by applying the laws from fluid mechanical, thermodynamical and mathematical theories. Ready to use libraries for the determination of fluid characteristics, the sensor linearisation, etc. facilitate the calculations. Any further processing like converting the volumetric flow rate to any other reference condition or determining the mass flow become an easy task with the S320 Controller.

Examples: Measuring of the differential pressure on devices (nozzles, orifices, laminar flow elements); Measuring with thermal mass flow meters, etc.

Control Engineering

The powerful processing performance of the S320 Controller makes even complex controlling tasks using standard algorithms (e.g. PI or PID) or state controlling easy. Calibration curves are easily taken into account, the realisation of multi loop control circuits, change-over, etc. become easy. Ready to use library routines exist for standard problems.

Examples: process controlling, hydraulic control, etc.

PLC Controlling

The S320 Controller evaluates sensor data which is put to a PLC's disposal in a pre-processed, e.g. digital form.

Device Controlling

Controlling in measurement devices for leak testing, pressure control, etc.

Plant Control

Combined measurement and control for industrial installations like compressor control, data acquisition, etc.

Assembly Places

Assembly places usually require intermediate steps of testing, adjusting or the like. The S320 Controller can undertake testing and adjusting respectively or handling (e.g. adaptation) in working steps for assembly places.

1.8 Commisioning

For detailed Technical Data see Technical Data Satandard Device and Technical Data Slot Cards.

Note: The notes below are valid only in the case, that you purchased the S320 Controller as a stand-alone device and not as part of a measuring system, an installation or similar and that the S320 Controller is not already configured or programmed for a certain task. In these latter cases please consult your supplier for connection or programming information.

The delivery of a S320 Controller includes (at least):

- this manual (omn storage device).
- the S320 Controller (basic device)
- slot cards, order depending, possibly already installed in the S320 Controller
- storage device with various programs
- a link cable between for connection to a PC
- two fixing clamps for front panel installation

Proceed in this order:

- | Read the manual. It contains important instructions about connection and operation.
- | Install the software as described in the chapter: "S320 Controller Programming" on your PC. Many of the demonstration programs are examples which do not require any slot cards or specific configuration data. Become familiar with the S320 Controller programming by reading this manual and by running the demonstration programs.
- | Establish the link connection between the S320 Controller and your PC. See chapter "The S320 Controller, Link-Connection to the PC" for details.
- | Connect the S320 Controller to a 24 volt power supply. See the chapters: "The S320 Controller - Power Supply" and "Technical Data Basic Device - Connections" for details.
- | Compile one of the demonstration programs. Many of these programs are executable with standard equipment without additional slot cards, e.g. the "clock program". Then send the resulting executable file (*.spx) to the S320 Controller. Likewise transmit the accompanying configuration file (*.cfg). Eventually start the program.
- | In order to connect sensors or digital input/output one possibly needs a corresponding slot card and some configuration data which is given through the configuration file. Each sample program on the included floppy disk is accompanied by its corresponding configuration file. The sample programs also show examples which require specific slot cards for execution.
- | Further program samples demonstrate signal handling, communication via the serial interfaces, practical use of library functions and more.

According to our experience the S320 Controller's programming and use do not raise any difficulties. Nevertheless if questions occur, please refer to the user's manual first. If the problem in cause still cannot be solved, consult your supplier or the manufacturer.

The industrial use of the S320 Controllers requires a similar preparation to the use of a PLC. In both cases it is useful to make channel lists and to organise the program before hand.

Surely you also will become enthusiastic about the S320 Controller's advantages handling analog signals, its easy use, its good price and the enormous processing speed!

Appropriate Application and Safety Regulations

Using the S320 Controller, similar considerations and preparations have to be made like when using a (small) PLC.

The disregard of the following points may cause potential risks of death or personal injury:

The S320 Controller is not designed, intended, authorised or warranted to be suitable for applications on men or animals. The S320 Controller should be kept away from children.
Do not use the S320 Controller for safety applications. You must face a malfunction or the occurrence of unwelcome or undefined operations at ANY TIME! Any safety-oriented control of a machine or a process, such as emergency stop switching, two handed control, door surveillance and the like must NOT be realised using the S320 Controller.
The S320 Controller is designed for processing analog signals. The wiring of analog signal conductors generally requires more care than the wiring for pure digital control signals.
Make sure that the installation meets the environment condition prescriptions. In particular the air circulation holes must not be covered and it has to be assured that the heat (e.g. in a switch cabinet) is sufficiently extracted.
Make sure that the electrical environment (power supply, power rating of outputs, etc.) during operation meets the specifications. The S320 Controller has to be connected to protection earth. Do NOT connect voltages to the S320 Controller which have a potential higher than 35 volt relative to the protection earth. Do not use the S320 Controller for the earthing of further earthing of further electrical devices.
National regulations have to be respected when having to do with electric and electronic products.
If a safe operation is not guaranteed, the S320 Controller must be stopped. Make sure to avoid any accidental starting. A safe operation is not guaranteed if:
the S320 Controller is visibly damaged
the S320 Controller does not work properly
the S320 Controller was stored in inconvenient conditions
the S320 Controller gets very hot during operation
overstraining during transport can not be excluded
The user/purchaser is responsible for the keeping to installation regulations and safety regulations of any form.

Conformity to Regulations

The S320 Controller fulfils all requirements of electromagnetic compatibility without additional metallic casing, given a suitable connection of communication lines and sensor lines. The more stringent parts of both of the corresponding norms are completely satisfied:

Generic Emission

The european norm EN 50 081-1, VDE 0839, Part 81-1. (Electromagnetic compatibility (EMC), Generic emission standard, Part 1: Residential, commercial and light industry) is completely satisfied.

Generic Immunity

The european norm EN 61000-6-2 (Electromagnetic compatibility (EMC), Generic Immunity, Part 2: Industrial environment) is completely satisfied.

The respective controls were executed by an accredited test laboratory. A conformity certificate is available on request. Please note that complete devices do not automatically meet the EMC requirements even if all of its components are conform to the EMC requirements.

Case Specifications

The S320 Controller's case is self-extinguishing and non-dripping. The fire safety properties meet the fire protection UL 94V1. The dielectric strength amounts to 250 kV/cm acc. to DIN 53481. The specific resistance is >1015 Ohm. The water absorption according to ASTM D 570 is less than 0,07 percent. The shape stability according to Vicat (B) is 150 degrees Celsius.

Protective System

A properly front panel integrated S320 Controller offers a front side protection conform to protective system IP54 (acc. to DIN 43700). At the rear the S320 Controller meets with protective system IP20. The same class is valid for a S320 Controller which is not installed into any enclosure.

1.9 Notes for Ordering

Please use the codes below to order individual parts from the S320 Controller product range:

Artikel | Code
S320 Controller Includes: S320 Controller basic unit, manual, cable LINK2 for link connection to PC, fixing clamp set KLK, CD with software. | S320
Type 100 slot card: 2 analog inputs Precision sigma-delta converters with variable filter frequency. Instrumentation amplifier input for voltages, current (20mA) and Pt100 RTD. Precise feed supply: 5V, 10V, 15V, 24V or 1mA for RTD. | TYP100
Type 101 slot card: 2 analog inputs for alternating voltages analog input for alternating voltage using true rms converters. Selectable ac or dc coupling. Precision sigma-delta converter with variable filter frequency. Instrumentation amplifier input for voltages. Feed supply 24 volt supported. | TYP101
Type 110 slot card: 2 analog inputs Precision integrating converters with 20ms or 16.66 ms integration periods (coinciding with the net period). Instrumentation amplifier input for voltages, current (20mA) and Pt100 RTD. Precise feed supply: 5V, 10V, 15V, 24V or 1mA for Pt100 RTD. | TYP110
Type 120 slot card: 4 analog inputs Four channel flash AD-converter with 12 bit resolution and an input voltage range between 0 and 10 volt. Ground related input. | TYP120
Type 200 slot card: 2 analog outputs Precision sigma-delta converters. Output in current (20 mA) or voltage. Feed supply 24V. | TYP200
Type 220 slot card: 4 analog outputs Four channel flash DA-converter with 12 bit resolution and an output voltage range between 0 and 10 volt. | TYP220
Type 310 slot card: 1 analog input and 1 analog output Precision flash-AD-converter. Instrumentation amplifier input for voltages, current (20mA) and Pt100 RTD. Precise feed supply: 5V, 10V, 15V, 24V or 1mA for Pt100 RTD. Precise flash-DA-converter. Output in current (20 mA) or voltage. Feed supply 24V. | TYP310
Type 400 slot card: Expansion of digital interfaces Slot card to expand the standard number of digital I/Os. Requires MOD-series expansion modules. Bus system allows connection of up to 8 modules. | TYP400
Expansion module MOD410: 16 x DI Module with 16 digital inputs for DIN rail mounting. Installation width 35 mm. Supply 24 Volt. State display by LEDs. | MOD410
Expansion module MOD412: 16 x DI Module with 16 digital inputs for 19" mounting. Dimensions: 3U x 7 HP x 70 mm. Supply 24 Volt. State display by LEDs. | MOD412
Expansion module MOD420: 16 x DO Module with 16 digital outputs (500mA each) for DIN rail mounting. Installation width 35 mm. Supply 24 Volt. State display by LEDs. | MOD420
Expansion module MOD422: 16 x DO Module with 16 digital outputs (500mA each) for 19" mounting. Dimensions: 3U x 7 HP x 70 mm. Supply 24 Volt. State display by LEDs. | MOD422
Expansion module MOD430: 8 x DI and 8 x DO Module with 8 digital inputs and 8 digital outputs (500mA each) respectively for DIN rail mounting. Installation width 35 mm. Supply 24 Volt. State display by LEDs. | MOD430
Expansion module MOD432: 8 x DI and 8 x DO Module with 8 digital inputs and 8 digital outputs (500mA each) respectively for 19" mounting. Dimensions: 3U x 7 HP x 70 mm. Supply 24 Volt. State display by LEDs. | MOD432
Type 500 slot card: 2 x input for incremental encoder Two inputs for incremental encoder with frequency measuring on phase B. Reciprocal frequency measuring method with 100 ns resolution. Input with opto couplers for galvanic isolation. Feed supply 5 volt and 24 volt. | TYP500
Type 510 slot card: 2 x input for counting and frequency measuring Two inputs for counting, frequency and duty cycle measuring. Reciprocal frequency measuring method with 20 ns resolution. Cascades for incremental encoder. Input with opto couplers for galvanic isolation. Feed supply 5 volt and 24 volt. | TYP510
Type 520 slot card: 2 x output frequency and PWM Two outputs for variable frequency and variable duty cycle. | TYP520
The Diagnostic adapter is plugged into the digital connectors of the S320 Controller in order to show the digital signal's state by LEDs. A DIP switch allows the activation of each digital input individually (disjunction between line inputs and switches). | LEDIG
Bus adapter T485 for easy installation of RS 485 field bus wiring. Connection to screwing plugs, DIN rail mounting, termination via DIP switches, including a 2 meter connection cable for direct use between RS 486 and S320 Controller. | T485
DCF77 Radio clock for serial interface port connection (Ser0) | DCF77
LINK2-Link connection cable to PC, 2 meter | LINK2
LINK7-Link connection cable to PC, 7 meter | LINK7
DSA25/9 DSUB-Adapter for 25-pin DSUB-plug | DSA25/9
DSK9/2 Serial connection cable, 9-pin, 2 meter | DSK9/2
DSK9/7 Serial connection cable, 9-pin, 7 meter | DSK9/7
ST8 - Connector 8 terminals | ST8
ST4 - Connector 4 terminals | ST4
ST3 - Connector 3 terminals | ST3
SS3 - Supply connector 3 terminals | SS3
KLK - Fixing clamps, short version, set with two pieces | KLK
KLL - Fixing clamps, long version, set with two pieces | KLL
DIF - Sealing for front panel cut out | DIF
NAD01 - Table power pack 24 volt 30 watt output. 90-260 VAC input. Supply connector. | NAD01
NAD02 - Power pack 24 volt for DIN rail mounting 30 watt output. 90-260 VAC input | NAD02

Final Remarks

The S320 Controller is the tool to help you implement a multitude of measuring and controlling tasks fast, elegantly and at moderate costs.

If technical considerations claim a computer system but commercial reflections only permit a small PLC, the S320 Controller will perfectly fill this gap.

The S320 Controller can be integrated in measuring devices or installations as an OEM-product. The costly and risky development of your own specific controller can be avoided thanks to the S320 Controller.

The S320 Controller was designed on the base of latest hardware and software. Its design and realisation profited from many years experience of industrial plant conception.

For further development we are highly interested in your ideas, your suggestions or your criticism. Please do not hesitate to contact us. Being developer and producer of the S320 Controller we will react fast and flexibly to our clients wishes. For example we could realise specific slot cards for a requested task and/or special program functions in order to perfectly match your aims.

Also contact us if any questions for specific applications occur.

We will be glad to give you advice.

Your TetraTec Team.

> Technical Data


S320 Controller Manual - Technical Data

 2. Technical Data

This chapter describes the hardware of the basic S320 Controller device, the modular slot cards and the correct configuration and calibration of the analog and digital signals.

The S320 Controller - a freely programmable measurement instrument

Type 100 Slotcard Type 120 Slotcard Type 220 Slotcard Type 510 Slotcard

The S320 Controller is designed as an open system. The completely flexible and modular concept allows to apply the system for any conceivable task. Follow the three steps below:

1. Select the slot cards and install them in the basic S320 Controller unit .

2. Define the S320 Controller configuration

3. Write the application software

2.1 Technical Data of the Basic Unit

This section describes the essential technical data of the basic S320 Controller device, such as the power supplay, the displays and keys, interfaces etc.

General Technical Data
Case: | DIN 43700 Front Panel Instrument Case
Front size: | 96 x 96 mm
Front panel cut out: | 92 x 92 mm
Installation: | Front side installation
Depth (no plugs): | approx.. 165 mm
Protrusion of front frame: | approx. 8 mm
Depth including plugs: | approx. 185 mm
Attachment: | by two fixing clamps on the rear
Power supply: | 18 - 28 volt dc
Power consumption: | approx. 8 Watt plus digital outputs
Mispolarizing protection: | Transil diode 33 volt
Excess voltage protection: | Transil diode 33 volt
Potential, supply: | none of device, must be provided by power supply
Potential digital I/O: | Power supply
Potential device ground: | Connection PE-terminal to earthing PE
Potential feed supply: | Device ground or PE
Potential analog I/O: | Device ground or PE
Power rating, digital output: | 24V, positive switching, max. 500 mA permanent current per channel, short-circuit protected, (current limitation typically 1500 mA), secure against inductive charges till up to 5 mJ.
Power rating, digital input: | 24 V, positive switching, approx. 5 mA
Operating environment : | 0 °C to 45 °C
Maximum number slot cards: | 5 (Slot 0 up to Slot 4)
Keys: | 5 (F1, F2, F3, Up, Down)
Seven-segment LED displays: | 3, 6-digit each
Alphanumeric displays: | 3, 4-digit each
Ethernet-Interface: | 1 (Eth 0), RJ45 jack, 8 lines
RS232-Interfaces: | 1 (Ser 0), DSUB-connector (female) 9 lines
RS485-Interfaces: | 2 (Ser 1 and Ser 2), FCC68-socket, 4 lines
Link connection to PC: | FCC68-socket, 6 lines, (RS232)

Connection

The rear of the S320 Controller and its respective connections.

Der Controller S320 von hinten.

Supply: The 24V dc power supply is connected to the 3-line connector marked by 'Supply' to the 0V and 24V terminal. 0V is the negative and 24V is the positive terminal. The positive terminal lies on the outer right hand, viewed from the rear. The 24volt power supply of the S320 Controller has galvanic separation from PE as the earthing of the control power generally must be realised at a central location inside the switch cabinet.

PE: The protection earth is connected to the PE terminal of the 3-line connector marked by 'Supply'. This establishes the defined potential of the internal device ground as well as the ground connection of the slot cards (marked by GND).

Digital-Out: The eight digital outputs of the S320 Controller switch the 24V supply voltage of the 'Supply'-connection via semiconductor switches (power rating: 500 mA) to the respective output. The outputs have galvanic separation from the controller's ground through opto couplers. The outputs switch positively like equivalent PLC standards. Hence a relay on channel 3 has to be connected to Digital-Out/Pin 3 and 0V. The current on the 24V supply connection is thus composed of the S320 Controller's supply current of about 0,35 ampere plus the current for all eight digital outputs.

Digital-In: The eight digital inputs relate to the 0V connection of the S320 Controller's supply and are thus controlled with 24V (positive switching). The current per channel is approx. 5 mA. The inputs have galvanic separation from the controller's ground.

Link: This socket is reserved for the communication between a PC and the S320 Controller for programming, configuration, etc. The S320 Controller needs the following five lines for the link connection:

PC-signal | TXD | RXD | RTS | CTS | GND | DSR | DTR
S320 Controller signal | RXD | TXD | CTS | RTS | GND |  |
9-line DSUB, PC | 3 | 2 | 7 | 8 | 5 | 6 | 4
25-line DSUB, PC | 2 | 3 | 4 | 5 | 7 | 6 | 20
6-line Link-socket, Controller | 1 | 4 | 5 | 3 | 6 |  |

Note: DSR and DTR must be bridged in the DSUB-plug. From the rear view on the S320 Controller the connection of the 6-line FCC68-link socket is: 1-2-3-4-5-6 counting from the left to the right side.

Note: Some 25/9-DSUB adapters available on the market do not support all the necessary lines. This is particularly the case for adapters delivered for PC mouse connection.

Note: Some older personal computers or low performance computers which are not equipped with a so called FiFo-Uart (16550) may not be capable to maintain communication at a transfer rate of 38400 baud. In such a case you can lower temporarily the link baud rate by defined key combinations during the start-up phase of the S320 Controller. Press F1+F2 for 4800 baud, F1 for 9600 baud or F2 for 19200 baud. For high-performance PCs you might raise the baud rate up to 57600 baud by pressing the F3-key during the auto test (see paragraph 'Displays and Keys'). The 'autobaud mechanism' of the terminal program selects automatically the required baud rate, see the chapter: Development Tools.

The terminal program supports the following interfaces of your PC: COM1, COM2, COM3 and COM4. Most PCs only have the first two interfaces. The interface COM1 is usually reserved for the mouse.

All serial COMx interfaces of the PC are male 9-pin or 25-pin connectors. The included standard connection cable is a 9-pin version. For the connection to the 25-pin socket you need the adapter 'DSA25/9'.

Ser0: This port is used for serial communication according to RS232.

The serial interface Ser0 has null modem sequence:

Ser0 Pins | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
S320 Connector | - | TXD | RXD | DSR | GND | DTR | CTS | RTS | -
9-line PC Connector | CD | RXD | TXD | DTR | GND | DSR | RTS | CTS | -

The serial interface Ser0 at the S320 Controller is implemented as a female 9-pin DSUB-connector. Using a 9-line 1:1 DSUB-connection results in the required null modem connection to a PC port. DTR and DSR are bridged at the S320 Controller. At the S320 Controller, CD is not occupied. If the PC comes equipped with 25-pin connectors, a 25/9-DSUB adapter becomes necessary. The translation follows the link interface description above.

Note: Some 25/9-DSUB adapters available on the market do not support all the necessary lines. This is particularly the case for adapters delivered for PC mouse connection.

Ser1 und Ser2: The serial interfaces Ser1 and Ser2 according to RS485 have the pin occupancy below:

Ser1 or Ser2 pins | 1 | 2 | 3 | 4
Signal | GND (100 Ohm) | A | B | 5V (100 Ohm)

At rear sight on the S320 Controller the connection of the 4-line FCC68-link socket is: 1-2-3-4 counting from the left to the right side.

Note: As the serial counterparts usually have earth protection potential, too, the additional ground connection via the serial interfaces have no importance. Nevertheless, if by any reason a potential drop occurs, the serial interfaces must be linked over external potential separation.

If several S320 Controller shall be interlinked for communication use a 1:1 connection (A-A, B-B). The two S320 Controllers to be located at an end of the bus connection each should have a termination as shown in the above figure. The bus adapter T485 can be used to make the installation easy.

Note: A correct field bus connection has a defined idle state: the voltage between A and PE must be approx. 2.8 volt and the voltage between B and PE approx. 2.1 volt (no active bus transfer).

Make sure that the communicating devices have faultless potential balance. The shield has to be connected at least at one point of the entire bus segment to the ground potential (PE).

A send data package is received by each controller connected to this bus, including the sending unit.

The sending controller can state the correctness of the send message by comparing the send data and the received data. The received data may differ from the send data, if another unit tried to simultaneously send a message. As the S320 Controller offers two serial RS485 interfaces, such a bus conflict can be avoided by an appropriate interlinkage of the units: sending via Ser1 and receiving via Ser2. In the case of such a circle topology only one sender employs one bus segment, thus no bus conflicts occur. However at failure of any of the links (e.g. by power failure), the complete bus transmission is interrupted.

NOTE: Please pay attention to possible potential differences when connecting the serial interfaces conform to the chapter "serial interfaces".

Eth0: 10 Mbit ethernet connector. The pin connections are as follows:

Eth0 pin number | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8
Name | TPO+ | TPO- | TPI+ | N.C. | N.C. | TPI- | N.C. | N.C.
Signal | Analog | Analog | Analog | - | - | Analog | - | -

Slot0 bis Slot4: Slots for various slot cards. Apart from the input and output connections, the slot cards mostly offer terminals for ground (GND) and supply (SUP) connection, where GND is the unit's internal ground (connected to PE) and SUP is an auxiliary feed supply depending on the slot card type and possibly its settings. SUP is generated internally via dc/dc-converters. It is related to the controller's ground and hence also has galvanic separation from the supply voltage..

Reference Potential Scheme

The scheme below illustrates the reference potential of the individual signals with galvanic separation by dc/dc converters and optocouplers respectively. An external potential reference of the feed supply is also shown which is generally provided for at a central spot inside a switch cabinet.

2.2. Technical Data Slot Cards

The interchangeable slot cards equip the S320 Controller for the desired task.
TYP100 2 x AnalogIn | TYP101 2 x AnalogIn True RMS Slotcard Type 101 | TYP110 2 x AnalogIn Slotcard Type 110
TYP120 4 x AnalogIn 0..10V Slotcard Type 120 | TYP200 2 x AnalogOut Slotcard Type 200 | TYP220 4 x AnalogOut 0..10V Slotcard Type 220
TYP310 1 x AnalogIn + 1 x AnalogOut Slotcard Type 310 | TYP400 Busmodule Slotcard Type 400 | TYP500 2 x Incremental encoder Slotcard Type 510
TYP510 2 x Counter/Freq. Slotcard Type 510 | TYP520 2 x Pulse / PWM Slotcard Type 520 |

NOTE: boards which are not installed in the device, are extremely sensitive to electrostatic decharges. Proper handling according to the relevant regulations is indispensable! Never install or remove slot cards in a S320 Controller while being connected to the power supply!

Connection Techniques for Analog Signals

Below follows a brief discussion of the connection techniques for the most important transducers and signals .

The analog inputs of the S320 Controller are usually furnished with four terminals. An instrumentation amplifier amplifies the voltage difference between +IN and -IN.

At the terminal SUP a mostly adjustable, precise voltage or constant current respectively is available for feed supply. The terminal GND is internally connected with the unit ground and with PE and hence is at protection earth level.

Analog connection circuit principle:

An instrumentation amplifier increases the voltage difference between the positive input +IN and the negative input -IN by a fix factor >1.0. This amplification is defined by the resistor RG. In contrast to a usual differential amplifier practically no current flows through the input, as the input impedance is in giga-ohm range. An instrumentation amplifier only allows correct function if both inputs +IN and -IN lie in between the input voltage range of the amplifier.

The S320 Controller's instrumentation amplifiers of the analog input slot cards are fed with a voltage supply of +24 volt and -5 volt respectively, both referred to the ground connection PE. (The slot card supply has galvanic isolation from the S320 Controller's feed supply.) Therefore the common mode input voltage range of this instrumentation amplifier lies in between approx. -3 volt and approx. 22 volt, referred to GND.

Usually one has to provide for a potential balance between the analog signal transducer and the analog input of the S320 Controller, in order to maintain the input signals within the common mode input voltage range.

This potential balance is not established, if for instance a battery fed signal source or an analog signal source having galvanic isolation from the net supply is only connected to the S320 Controller by the two input lines +IN and -IN. In this case the output of the signal source might float far beyond the common mode input voltage range of the instrumentation amplifier, e.g. by static charges. Then the very high input impedance of the instrumentation amplifier does not balance the difference of potentials - a correct measuring becomes impossible. In this specific case, the potential balance can be established by simply connecting the analog input's negative input (-IN) and its ground potential (GND) whether directly or via a resistor.

However if an analog input source with defined potential (as e.g. the analog outputs of the S320 Controller) is connected to the analog input, only the inputs +IN and -IN should be joined. As such an analog signal source remains within the defined common mode input voltage range by its potential reference a supplementary bridging between -IN and GND would create as a result a so-called 'ground loop' which allowed uncontrolled compensation currents and such could provoke unwelcome effects. When supplying the sensors by the internal feed supply, the necessary potential balance is of course 'automatically' established.

Potential compensation lines should always be wired in a 'star-shaped' way, i.e. any internal loop should be avoided. This guarantees that only compensation currents run through this lines but no conjoined 'hum currents' or even part of the device's supply.

For measuring currents (e.g. 4..20mA) a 47 ohm resistor parallel to the input of the slot card input is used which provokes a voltage drop, e.g. of approx. 0.2 .. 1.0 volt for a 4..20mA current. This voltage drop is increased by the instrumentation amplifier and transmitted to the analog digital converter (ADC) like an ordinary voltage input signal. Of course a current input also requires a defined potential reference.

According to common usage, it is recommended to connect the shield of the analog signal wire on one side to the ground. As far as possible, connection wires with twisted pair cores should be used. The appropriate pairing is: +IN with -IN and SUP with GND respectively.

Four-wire Bridge Transducer

Common sensor type for measuring pressure, force, moment, etc. without integrated electronics. A physical force influences the resistors of the measurement bridge and such creates a difference in voltage between the positive and the negative input.

The bridge is supplied with a precise constant voltage (usually 10.00 volt). The bridge output, a voltage difference is evaluated. This difference amounts to typically 100 mV or lower, depending on the bridge type. This sensor form represents a classic application for an instrumentation amplifier, as the inputs have for example 5 volt static potential, the proper signal however results from the difference of the two voltages +IN and -IN.

100 Ohm Platinum RTD, Four-Wire Configuration

A low cost, however very precise temperature detector. A resistance temperature detector always measures the absolute temperature referred to the absolute zero: 0 degrees Kelvin. The 100 ohm Pt RTD has a resistance of 100 ohm at a temperature of 0°C. It is usually supplied by a constant current of 1.00 mA, hence a voltage difference of 100 mV is measured at a temperature of 0°C. The Pt-resistance over temperature curve is standardised (IEC751). The input is calibrated by successively applying two reference resistors, e.g. 100 and 150 ohm. The transformation from the measured resistance into the corresponding temperature is computed by a Spell-function, which is included in the libraries. The four-wire configuration avoids the introduction of lead effect error terms (caused by voltage drop inside the lead wire).

100 Ohm Platinum RTD, Two-Wire Configuration

In contrast to the four-wire configuration, the effects of (temperature dependent) lead-wire resistance of the two-wire configuration can be very significant and thus provoke an important error.

Thermocouples

Thermocouples are temperature transducers which generate a thermocouple voltage (Seebeck voltage) in the range of some millivolt due to dissimilar metal junctions. Thermocouples always require a reference junction compensation. Electronically this reference temperature is mostly determined by a platinum RTD incorporated into the evaluation electronics.

Thermocouples can not be connected directly to the S320 Controller, as the reference temperature compensation is not integrated into the slot cards as standard. A simple possibility for thermocouple connection offer 'head transmitters'. These are inexpensive electronic converters from thermocouple signals to ordinary signals, such as 4..20mA, for installation inside the temperature transducer's connection head.

Sensor with 0..20mA Output, Three-Wire Configuration

Sensors with a current output between 0 and 20 mA are usually connected using three-wire technique. The important advantage of a current signal compared to a voltage signal is that the changing resistance of the lead wires or its connections have no effect on the current whilst the voltage is changed. The sensor is usually supplied with 24 volt dc. The S320 Controller input transforms the current via an internal resistor (mostly 50 ohm which provides 1.0 volt at a current of 20 mA) back to a voltage. The resulting voltage is suitably amplified. In the case of the four-wire version the -IN input is not connected to GND of the S320 Controller but to GND of the sensor.

Sensor with 4..20mA Output, Two-Wire Configuration

Sensors with a current output between 4 and 20 mA are usually connected applying two-wire technique. In this version, the minimum current of 4mA feeds the sensor electronics. An interrupt of the connections can be detected if the actual current remains under the minimum current of 4mA.

The connection is advisably carried out as shown below. Referred to GND the measured voltage is generated by the resistor RI in a range between 0.2 and 1.0 volt.

Sensor with 4..20mA Output, Two-Wire Configuration, Alternative Connection

The connection version below integrates an external resistor RE which generates an easy measurable voltage signal of 1 to 5 volt between GND and -IN for test purposes. In addition this resistor offers a certain protection against short circuits in the two-wire line. Also the power loss is reduced and thus the self-heating in the sensor. This connection version however requires the sensor to allow a load of 290 ohm at 24 volt supply .

Sensor with 4..20mA Output, Two-Wire Configuration, Other Alternative

Not recommended, but possible in principle is the connection version below. Here the sensor is located in the 'ground loop'. As the resistor RI is directly connected to the 24 volt supply the measurement voltage at the negative input -IN referred to GND would lie in between 23.8 volt (4mA) and 23.0 volt (20mA). The voltage +IN stays stable at 24 volt referred to GND. In this version both inputs would be outside the common mode input voltage range of the instrumentation amplifier. A correct measuring is not possible. Silicium diodes can be used to provoke a voltage drop of approx. 2.0 volt from 24 volt level. Then the inputs enter the admissible common mode input voltage range of the instrumentation amplifier.

Instead of the diodes a resistor RE (see above) with at least 500 ohm can be put between SUP and +IN. In this case the sensor's load limitation at 24 volt must be > 550 ohm.

Analog Voltage Output with Ground Reference

A distinction is made between analog voltage outputs with ground reference (i.e. protection earth potential) and analog outputs with free potential. If the output is referred to the ground and if it is assured, that the ground difference plus the effective signal between the S320 Controller and the external device lies in-between the common mode input voltage range of the instrumentation amplifier, the device can be connected as shown below:

Analog Voltage Output with Free Potential

External devices with free potential must be put to protection earth potential. This can be done via the S320 Controller's connection or via a separate protection earth connection. The device can be supplied by the S320 Controller or by another power supply with free potential (e.g. plug-in power pack). Of course an external device cannot be 'earthed' over the S320 Controller's GND-terminal according to relevant directions.

Analog Current Output with Ground Reference as a Current Source

If the output with a current source has ground reference and if it is guaranteed, that the ground potential difference plus the effective signal between the S320 Controller and the external device lies inside the common mode input voltage range of the instrumentation amplifier, then the device can be connected as shown below:

Analog Current Output with Ground Reference as a Current Subsidence

If the output works as a current subsidence with ground reference, a feed supply is needed for the current loop which is usually provided for by the device itself. An external resistor RE at a feed supply of more than 22 volt assures that the common mode input voltage range of the instrumentation amplifier is not left.

Analog Current Output with Free Potential

For devices with potential free current output the current loop is simplest fed by the internal feed supply of the S320 Controller (compare 4..20mA sensor connection).

Overview Slot Cards for Analog Signals

The table below shows the specifications of the slot cards described in the following chapters.

Analog Inputs:

Parameter | TYP10x1 | TYP110 | TYP120 | TYP310
Number of analogue inputs | 2 | 2 | 4 | 1
Hardware resolution 24 bit | 24 bit | 18 bit | 12 bit | 14 bit
typ. stable at 0..10 V input 2 | 18 bit 3 | 15 bit | 12 bit | 12 bit
Conversion method | SigDelta | MultiSlope | Flash | Flash
Scaling 4 | B | B | U | B
typ. temperature influence | 50 ppm/K | 50 ppm/K | 50 ppm/K | 50 ppm/K
typ. conversion time | 1-100ms 5 | 65 ms 6 | 15 µs | 10 µs
Input impedance | > 1GOhm | > 1GOhm | > 1GOhm | > 1GOhm
Instrumentation amplifier | yes | yes | no | yes
Feed supply | jes | yes | no | yes

1: type 100 for direct voltages, type 101 for alternating voltages
2: typ. number of bits not to be influenced by noise
3: approx. 18 bit at 100ms conversion time, approx. 10 bit at 1 ms conversion time
4: B: always bipolar operation input , U: always positive (unipolar) operation input
5: Depending on filter setting of the configuration file
6: Measuring time depending on the "reject"-parameter setting: 16,67ms (60Hz) or 20ms (50Hz)

Analog Outputs:

Parameter | TYP200 | TYP220 | TYP310
Number of analogue output | 2 | 4 | 1
Hardware resolution | 16 bit | 12 bit | 14 bit
Conversion method | SigDelta | Flash | Flash
Scaling 1 | B, U | U | B, U
Output possibilities 2 | V, mA | V | V, mA
typ. conversion time | 3 ms | 15 µs | 10 µs
typ. temperature influence | 50 ppm/K 3 | 50 ppm/K | 50 ppm/K

1: B: bipolar, U: unipolar
2: V: voltage output, mA: current output, depending on the output's scaling
3: approx. 50 ppm/K for current output, approx. 100 ppm/K at voltage output

Standard Settings of Analog Signals

By standard the analog slot cards are calibrated at delivery as given below:

Analog inputs: | 0 .. +10 volt input range 0.0 .. 10.0 conversion range no feed supply
Analoge Ausgänge: | 0 .. +10 volt output range 0.0 .. 1.0 internal range no feed supply.

The slot cards can be easily calibrated when changing the input/output range. Therefore follow the instructions given in the chapter 'Configuration'.

Individual Calibration of Analog Signals

On request the slot cards can also be purchased with individually adjusted input range, conversion range and feed supply.

Any listed combination for the respective slot card can be chosen. In that case the precise configuration data must be given together with the order.

Also specific 'exotic' ranges can be realised with the slot cards as for instance +/- 120 mV, 0 .. 7.5 volt, -2.5 .. 10 volt, 0 .. 20 volt, or 0.1 mA feed supply for 1000 ohm RTD, 12 volt feed supply, etc.. Often these ranges can be implemented by special fitting or exchange of components. This service is optionally offered ex works.

Exclusivity of Plug Connectors

It is possible to encode the slot card connectors or the digital I/O connectors with coding pins.

Encoding the slot card connectors

> Type 100 slotcard


Controller S320 Manual - Slot Card Typ100

 2.3. TYPE 100 Slot Card: 2 x Analog Input

The type 100 slot card contains two mutually independent analog inputs with precise A/D converters applying the sigma-delta method.

The type 100 slot card is the standard choice for measuring analog signals. The exploitable resolution under a 10 Hz input filter is 1 : 200.000 or better. The converter has 24 bit resolution.
The conversion time can be adapted to one's needs by modifying the filter frequency, whereby the exploitable resolution improves when prolonging the conversion time (signal integration). The conversion time is the reciprocal of the set filter frequency.

The input instrumentation amplifier's gain can be adjusted by a resistor RGx. The limiting frequency and a possible preamplification are adjustable.

Analog input: difference input with a common mode input voltage range between -3 and +22 volt referred to GND. The preamplification G by the instrumentation amplifier INA can be defined by the resistor RGx according to the equation: RGx = 49K4/(G-1) The converter is bipolar in the range between -2.5 and 2.5 volt. Switching on SWx8 forces a voltage separation down to 23.25 percent before the conversion. For current measuring, a 47 ohm resistor can be connected in parallel to the input by switching on SWx7.

The table below shows the appropriate resistors RGx (always the next higher resistor according to E24 table is used) and the switch positions SWx7 and SWx8. You will also find the magnitude of the parameters Gain and Offset for analog standard signals. The exact calibration of the input is done by these parameters, specified in the configuration file. The values in the table can not replace a precise calibration. Inevitable tolerances of the slot card's resistors are only compensated for by the precise calibration.

 |  |  |  |  | normalized unipolar 0..+1 |  | normalized bipolar -1..+1 |  | value equal to input signal
input signal |  | RGx | SWx7 | SWx8 | Gain | Offset | Gain | Offset | Gain | Offset
0 .. +10 | Volt | - | OFF | ON | 1,00 | 0,00 |  |  | 10,00 | 0,00
0 .. +5 | Volt | 47k0 | OFF | ON | 1,00 | 0,00 |  |  | 5,00 | 0,00
-2 .. +2 | Volt | 240k | OFF | OFF |  |  | 1,00 | 0,00 | 2,00 | 0,00
-1 .. +1 | Volt | 36k0 | OFF | OFF |  |  | 1,00 | 0,00 | 1,00 | 0,00
-500 .. +500 | mV | 13k0 | OFF | OFF |  |  | 1,00 | 0,00 | 0,50 | 0,00
-200 .. +200 | mV | 4k70 | OFF | OFF |  |  | 1,00 | 0,00 | 0,20 | 0,00
-100 .. +100 | mV | 2k20 | OFF | OFF |  |  | 1,00 | 0,00 | 0,10 | 0,00
0 .. +20 | mA | 33k0 | ON | OFF | 1,00 | 0,00 |  |  | 20,00 | 0,00
4 .. +20 | mA | 33k0 | ON | OFF | 1,25 | -0,20 |  |  | 20,00 | 0,00

100 Ohm Pt RTDs have constant current supply of 1mA. Thus the measured value in mV equals exactly the detector's resistance in ohm. The library function linPT100(X) where X is the measured resistance then yields the corresponding temperature in degrees Kelvin. The possible measuring range depends on the pre-amplification defined by the resistor RGx:

Pt100 RTD Range Definition
Temperature Range | RGx | SWx7 | SWx8 | Input voltage |  | Gain | Offset
.. ~ 15°C | 2k2 | OFF | OFF | 0 .. +107 | mV | 107,00 | 0,00
.. ~ 40°C | 2k4 | OFF | OFF | 0 .. +116 | mV | 116,00 | 0,00
.. ~ 75°C | 2k7 | OFF | OFF | 0 .. +130 | mV | 130,00 | 0,00
.. ~ 110°C | 3k0 | OFF | OFF | 0 .. +143 | mV | 143,00 | 0,00
.. ~ 145°C | 3k3 | OFF | OFF | 0 .. +157 | mV | 157,00 | 0,00
.. ~ 180°C | 3k6 | OFF | OFF | 0 .. +170 | mV | 170,00 | 0,00
.. ~ 215°C | 3k9 | OFF | OFF | 0 .. +183 | mV | 183,00 | 0,00

Feed supply: The feed supply offered by the terminal SUP can be set up following the table below. The fine tuning of each feed supply except 24V is done using the trimmer: PSUPx.

Supply | SWx1 | SWx2 | SWx3 | SWx4 | SWx5 | SWx6 | power rating | PSUPx
none | OFF | OFF | OFF | OFF | OFF | OFF |  |
5 volt | OFF | ON | ON | ON | OFF | OFF | approx. 15 mA | yes
10 volt | OFF | ON | ON | OFF | OFF | ON | approx.15 mA | yes
15 volt | OFF | ON | ON | OFF | ON | ON | approx. 15 mA | yes
24 volt | ON | OFF | OFF | OFF | OFF | OFF | approx. 25 mA 1 | no
1 mA | OFF | ON | OFF | ON | OFF | ON | 1 mA | yes

1: The S320 Controller's 24V supply is chargeable up to a total of approximately 200 mA. If it is assured that the sum of consumption does not exceed this total current, one may tap a somewhat higher current from a single slot card.

Note: Don't set SWx1 and SWx2 at ON together!

Configuration possibilities type 100 slot card:

Syntax: | Port <val> {Name "<val>"; Gain <val>; Offset <val>; Filter <val>; PreGain <val>;};
Port | <val> is the channel number (integer value: 0 or 1) specifying the port.
Name | <val> is an arbitrary, user-defined port name, e.g. "voltage", "pressure", etc.
Gain | <val> is a floating-point number, specifying the gain (e.g. 10.12345).
Offset | <val> is a floating-point number, specifying the offset (e.g. 0.12345).
Filter | <val> is a floating-point number between 10.0 (Hz) and 1000.0 (Hz), specifying the limiting frequency of the converter. The exact value is adjusted to match the hardware possibilities.
PreGain | PreGain <val> is an integer value from the following parameter set: 1, 2, 4, 8, 16, 32, 64 or 128. It defines the preamplification of the converter.

Configuration sample type 100 slot card:

MODULE 100 { Port 0 { Name "voltage";
                      Gain 10.76194576;
                      Offset 0.00147000;
                      Filter 10.0;
                      PreGain 1; };
             Port 1 { Name "current";
                      Gain 10.74436995;
                      Offset 0.00190000;
                      Filter 10.0;
                      PreGain 1; };
            } Slot 0;

> Type 101 Slotcard


Controller S320 Manual - Slot Card Typ101

 2.4 TYPE 101 Slot Card: 2 x Analog Input for Alternating Voltage

The type 101 slot card contains two mutually independent true rms (root-mean-square) analog inputs with precise A/D converters applying the sigma-delta method.

In contrast to the type 100 slot card a true rms converter is placed ahead of each input which allows the determination of the true effective value of a signal whether sinusoidal or distorted.

The input can be changed over from dc to ac coupling. The dc coupling evaluates the sum of the alternating and direct voltages of the signal, whilst the ac coupling neglects the dc portion.
The input instrumentation amplifier's gain can be adjusted by a resistor RGx. The limiting frequency and a possible preamplification are adjustable. A separate switch turns on a 24 volt feed supply.

The type 101 slot card allows to connect various kind of signals directly to the S320 Controller which normally would call for a separate signal processing.

Such signals are for instance: motor speed tachos, bridge sensors with ac feed supply, current clamps e.g. for measuring motor currents, PWM signals e.g. of temperature sensors, inductive displacement transducers, etc.

Analog input: difference input with a common mode input voltage range between -3 and +22 volt referred to GND. The preamplification G by the instrumentation amplifier INA can be defined by the resistor RGx according to the equation: RGx = 49K4/(G-1) The converter is bipolar in the range between -2.5 and 2.5 volt.

The table below shows the appropriate resistors RGx (always the next higher resistor according to E24 table is used) and the switch positions SWx2 (port0) and SWx5 (port1). You will also find the magnitude of the parameters Gain and Offset for analog standard signals. The exact calibration of the input is done by these parameters, specified in the configuration file. The values in the table can not replace a precise calibration. Inevitable tolerances of the slot card's resistors are only compensated for by the precise calibration.

 |  |  |  | normalized unipolar 0..+1 |  | normalized bipolar -1..+1 |  | Value equal to input signal
Input signal |  | RGx | SW2 / SW5 | Gain | Offset | Gain | Offset | Gain | Offset
0 .. +10 | Volt | - | ON | 1,00 | 0,00 |  |  | 10,00 | 0,00
0 .. +5 | Volt | 47k0 | ON | 1,00 | 0,00 |  |  | 5,00 | 0,00
-2 .. +2 | Volt | 240k | OFF |  |  | 1,00 | 0,00 | 2,00 | 0,00
-1 .. +1 | Volt | 36k0 | OFF |  |  | 1,00 | 0,00 | 1,00 | 0,00
-500 .. +500 | mV | 13k0 | OFF |  |  | 1,00 | 0,00 | 0,50 | 0,00
-200 .. +200 | mV | 4k70 | OFF |  |  | 1,00 | 0,00 | 0,20 | 0,00
-100 .. +100 | mV | 2k20 | OFF |  |  | 1,00 | 0,00 | 0,10 | 0,00

Note: The table corresponds to direct voltage signals! The instrumentation amplifier works in the range between -2.5 volt and 2.5 volt, i.e. a correct measuring is only possible if the maximum values of the alternating input voltage can be processed.

The effective value of an alternating voltage depends on its shape. The maximum value of a sinusoidal input signal of 1 volt eff. is 1.0 volt x 1.4142 = 1.4142 volt. This fact has to be taken into account when selecting the adequate input range.

Switch on SW3 (port0) or SW6 (port1) respectively to select dc coupling. Imaginge a sinusoidal signal of 1 volt eff. with an overlain direct voltage of 0.5 volt. If the dc-coupling is selected, the complete signal will be evaluated, i.e. the result is the sum of the ac and the dc portion. If in contrast the ac-coupling is selected (SW3=OFF for port0 or SW6=OFF for port1) then only the ac portion will be taken into account, i.e. the result will be 1 volt eff.

One always has to choose the input range thus, that the maximum values resulting from the sum of the dc portion and the ac portion lie in-between the instrumentation amplifiers range, even when selecting the ac coupling.

Feed supply: Switching on SW1 and SW4 provides a 24 volt supply for port0 and port1 respectively with a power rate of approximately 25mA each.

True rms: in brief terms the effective value of an alternating voltage equals the direct voltage which would provoke the same power loss over the same resistance. In general, i.e. including not sinusoidal signals, the effective value equals the root of the signal's mean square.

The power and the voltage over a resistor of a dc signal have a quadratic relationship. Thus when measuring the effective voltage, more value is put on higher input voltages than on lower input voltages. Another consequence is that negative voltages yield a positive result, as the negative current also provokes a positive power. Remember Ohm's law (U = R x I) and the electric power equation (P = U x I).

The accuracy and the behaviour over the time of a true rms conversion depends (among other things) of the following factors: signal shape, dc portion and dc error, crest factor, frequency, slewing rate, ripple and the averaging time constant. It would be beyond this manual's scope to describe all details of rms-to-dc conversion. We refer the interested reader to the technical description of the integrated true rms converter AD637.

By default the type 101 slot card is equipped with CAx = 0,47µF (Cav in the data sheet) and CBx = 1,5µF (C2 in the data sheet). The single pole Sallen-Key filter gives the best overall compromise between ripple and settling time. These capacitors are marked in the slot card layout and may be adapted by the well-informed customer to meet his own specific needs. One should however retain more or less to the ratio of the capacities (CBx = 3,3 x CAx). Using the default capacities the ripple after filtering amounts to approx. 1% at 50Hz and to approx. 0.05% at 1000Hz. The settling time is approximately 200ms.

The maximum frequency of the input signal is determined by the signal processing. Depending on the signal's shape (sine wave, pulse train waveform, etc.) the highest sensible input frequency is about 50kHz.

Configuration possibilities type 101 slot card:

Syntax: | Port <val> {Name "<val>"; Gain <val>; Offset <val>; Filter <val>; PreGain <val>;};
Port | <val> is the channel number (integer value: 0 or 1) specifying the port.
Name | <val> is an arbitrary, user-defined port name, e.g. "voltage", "pressure", etc.
Gain | <val> is a floating-point number, specifying the gain (e.g. 10.12345).
Offset | <val> is a floating-point number, specifying the offset (e.g. 0.12345).
Filter | <val> is a floating-point number between 10.0 (Hz) and 1000.0 (Hz), specifying the limiting frequency of the converter. The exact value is adjusted to match the hardware possibilities.
PreGain | <val> is an integer value from the following parameter set: 1, 2, 4, 8, 16, 32, 64 or 128. It defines the preamplification of the converter..

Configuration sample type 101 slot card:

MODULE 101 { Port 0 { Name "voltage";
                      Gain 10.76194576;
                      Offset 0.00147000;
                      Filter 10.0;
                      PreGain 1; };
             Port 1 { Name "current";
                      Gain 10.74436995;
                      Offset 0.00190000;
                      Filter 10.0;
                      PreGain 1; };
           } Slot 0;

> Type 110 Slotcard


Controller S320 Manual - Slot Card Typ110

 2.5 TYPE 110 Slot Card: 2 x Analog Input

The type 110 slot card contains two mutually independent analog inputs with precise A/D converters.

The type 110 slot card attains an exploitable resolution of approximately 1 : 50.000. The converter has 18 bit resolution. The type 110 slot card's preferred application is the measuring of signals interfered by net hum. The slot card contains integrating converters which allow good line ac rejection (50Hz or 60Hz) by setting the (input) integration time equal to a net period of 20 or 16.67 ms respectively. The type 110 slot card performs 16 conversions per second (thus permits 16 readings per second).

The input instrumentation amplifier's gain can be adjusted by a resistor RGx.

Analog input: difference input with a common mode input voltage range between -3 and +22 volt referred to GND. The preamplification G by the instrumentation amplifier INA can be defined by the resistor RGx according to the equation: RGx = 49K4/(G-1) The converter's analog input range is bipolar between -2.5 volt and 2.5 volt. Switching on SWx8 forces a voltage separation down to 24.36 percent before the conversion. For current measuring, a 47 ohm resistor can be connected in parallel to the input by switching on SWx7.

The table below shows the appropriate resistors RGx (always the next higher resistor according to E24 table is used) and the switch positions SWx7 and SWx8. You will also find the magnitude of the parameters Gain and Offset for analog standard signals. The exact calibration of the input is done by these parameters, specified in the configuration file. The values in the table can not replace a precise calibration. Inevitable tolerances of the slot card's resistors are only compensated for by the precise calibration.

 |  |  |  |  | normalized unipolar 0..+1 |  | normalized bipolar -1..+1 |  | value equal to input signal
Input Signal |  | RGx | SWx7 | SWx8 | Gain | Offset | Gain | Offset | Gain | Offset
0 .. + 0 | Volt | - | OFF | ON | 1,00 | 0,00 |  |  | 10,00 | 0,00
0 .. +5 | Volt | 47k0 | OFF | ON | 1,00 | 0,00 |  |  | 5,00 | 0,00
-2 .. +2 | Volt | 240k | OFF | OFF |  |  | 1,00 | 0,00 | 2,00 | 0,00
-1 .. +1 | Volt | 36k0 | OFF | OFF |  |  | 1,00 | 0,00 | 1,00 | 0,00
-500 .. 500 | mV | 13k0 | OFF | OFF |  |  | 1,00 | 0,00 | 0,50 | 0,00
-200 .. 200 | mV | 4k70 | OFF | OFF |  |  | 1,00 | 0,00 | 0,20 | 0,00
-100 .. 100 | mV | 2k20 | OFF | OFF |  |  | 1,00 | 0,00 | 0,10 | 0,00
0 .. +20 | mA | 33k0 | ON | OFF | 1,00 | 0,00 |  |  | 20,00 | 0,00
4 .. +20 | mA | 33k0 | ON | OFF | 1,25 | -0,20 |  |  | 20,00 | 0,00

100 Ohm Pt RTDs have constant current supply of 1mA. Thus the measured value in mV equals exactly the detector's resistance in ohm. The library function linPT100(X) where X is the measured resistance then yields the corresponding temperature in degrees Kelvin. The possible measuring range depends on the pre-amplification defined by the resistor RGx:

Pt100 RTD Range Definition
Temperature Range | RGx | SWx7 | SWx8 | Input voltage |  | Gain | Offset
.. ~ 15°C | 2k2 | OFF | OFF | 0 .. +107 | mV | 107,00 | 0,00
.. ~ 40°C | 2k4 | OFF | OFF | 0 .. +116 | mV | 116,00 | 0,00
.. ~ 75°C | 2k7 | OFF | OFF | 0 .. +130 | mV | 130,00 | 0,00
.. ~ 110°C | 3k0 | OFF | OFF | 0 .. +143 | mV | 143,00 | 0,00
.. ~ 145°C | 3k3 | OFF | OFF | 0 .. +157 | mV | 157,00 | 0,00
.. ~ 180°C | 3k6 | OFF | OFF | 0 .. +170 | mV | 170,00 | 0,00
.. ~ 215°C | 3k9 | OFF | OFF | 0 .. +183 | mV | 183,00 | 0,00

Feed supply: The feed supply offered by the terminal SUP can be set up following the table below. The fine tuning of each feed supply except 24V is done using the trimmer: PSUPx.

Supply | SWx1 | SWx2 | SWx3 | SWx4 | SWx5 | SWx6 | power rating | PSUPx
none | OFF | OFF | OFF | OFF | OFF | OFF |  |
5 volt | OFF | ON | ON | ON | OFF | OFF | approx. 15 mA | yes
10 volt | OFF | ON | ON | OFF | OFF | ON | approx.15 mA | yes
15 volt | OFF | ON | ON | OFF | ON | ON | approx. 15 mA | yes
24 volt | ON | OFF | OFF | OFF | OFF | OFF | approx. 25 mA 1 | no
1 mA | OFF | ON | OFF | ON | OFF | ON | 1 mA | yes

1: The S320 Controller's 24V supply is chargeable up to a total of approximately 200 mA. If it is assured that the sum of consumption does not exceed this total current, one may tap a somewhat higher current from a single slot card.

Note: Don't set SWx1 and SWx2 at ON together!

Configuration possibilities type 110 slot card:

Syntax: | Port <val> {Name "<val>"; Gain <val>; Offset <val>; Reject <val>;};
Port | <val> is the channel number (integer value: 0 or 1) specifying the port.
Name | <val> is an arbitrary, user-defined port name, e.g. "voltage", "pressure", etc.
Gain | <val> is a floating-point number, specifying the gain (e.g. 10.12345).
Offset | <val> is a floating-point number, specifying the offset (e.g. 0.12345).
Reject | <val> is an integer number whether 50 or 60, specifying the integration period for ac rejection: 50Hz (20ms) or 60Hz (16.67ms) respectively.

Configuration sample type 110 slot card:

MODULE 110 { Port 0 { Name "voltage";
                      Gain 10.76194576;
                      Offset 0.00147000;
                      Reject 50; };
             Port 1 { Name "current";
                      Gain 10.74436995;
                      Offset 0.00190000;
                      Reject 60; };
           } Slot 0;

> Type 120 Slotcard


Controller S320 Manual - Slot Card Typ120

 2.6 TYPE 120 Slot Card: 4 x Analog Input

The type 120 slot card contains four mutually independent analog inputs with rapid A/D converters.

The converter has 12 bit resolution, the conversion time is approx. 15 µs. The four analog inputs have ground reference, have very high input resistance and work exclusively in the input range between 0 and 10 volt.

This slot card is mainly designed for the particular VA-Mode of the S320 Controller, nevertheless it also can be used for general purposes. Remember however that the inputs are designed for maximum speed with an accuracy of less than 1 per cent .

Analog input: Input range in between 0 and 10 volt. High input resistance. Ground reference. The pins 1, 3, 5 and 7 of the connector are the input channels. The pins 2,4,6 and 8 offer the respective ground connections. Due to the high input impedance and the internal protection diodes, the unconnected inputs drift against 10 volt. This effect can be avoided by connecting external input resistors of approx. 100K. The type120 slot card does not support any feed supply.

Configuration possibilities type 120 slot card:

Syntax: | Port <val> {Name "<val>"; Gain <val>; Offset <val>;};
Port | <val> is the channel number (integer value: 0 or 1) specifying the port.
Name | <val> is an arbitrary, user-defined port name, e.g. "voltage", "pressure", etc.
Gain | <val> is a floating-point number, specifying the gain (e.g. 10.12345)..
Offset | <val> is a floating-point number, specifying the offset (e.g. 0.12345).

Configuration sample type 120 slot card:

MODULE 120 { Port 0 { Name "AI0";
                      Gain 10.0;
                      Offset 0.0; };
             Port 1 { Name "AI1";
                      Gain 10.0;
                      Offset 0.0; };
             Port 2 { Name "AI2";
                      Gain 10.0;
                      Offset 0.0; };
             Port 3 { Name "AI3";
                      Gain 10.0;
                      Offset 0.0; };
           } Slot 0;

> Type 200 Slotcard


Controller S320 Manual - Slot Card Typ200

 2.7 TYPE 200 Slot Card: 2 x Analog Output

The type 200 slot card contains two mutually independent analog outputs with precise A/D converters applying the sigma-delta method.

The type 200 slot card is the standard choice for the output of analog signals. The converters have 16 bit resolution. The conversion time is about 3 ms.

The output can be adjusted to match the usual voltages or currents.

Output: Analog output depending on the switch position SWx. Voltage output: analog output at terminal 2 referred to GND at terminal 3. Current output: current source at terminal 2 with 24V supply.

Output | SWx1 | SWx2 | SWx3 | SWx4 | SWx5 | SWx6 | SWx7 | SWx8
0 .. +1 V | ON | ON | OFF | ON | ON | ON | OFF | ON
-1 .. +1 V | ON | ON | OFF | ON | OFF | ON | OFF | OFF
0 .. +2 V | ON | ON | OFF | ON | OFF | ON | OFF | ON
-2 .. +2 V | ON | ON | OFF | ON | OFF | OFF | OFF | OFF
0 .. +2,5 V | ON | ON | OFF | ON | ON | ON | ON | ON
-2.5 .. +2.5 V | ON | ON | OFF | ON | OFF | ON | ON | OFF
0 .. +4 V | ON | ON | OFF | ON | OFF | OFF | OFF | ON
-0 .. +5 V | ON | ON | OFF | ON | OFF | ON | ON | ON
0 .. +10 V | ON | ON | OFF | ON | OFF | OFF | ON | ON
0 .. 20 mA | OFF | ON | ON | OFF | OFF | ON | OFF | ON
4 .. 20 mA | ON | OFF | ON | OFF | ON | ON | ON | ON
0 .. 24 mA | OFF | OFF | ON | OFF | ON | ON | ON | ON

Note: Don't set SWx3 and SWx4 at ON together!

The accurate calibration of the output is done by adjusting the parameters GAIN and OFFSET of the configuration file. The slot cards are designed thus, that the output range surpasses the specified range. For instance the analog output for a 0..+10V setup actually covers a range of approx. -0.25V .. 10.25V (for the configuration: Offset = 0.0 and Gain = 1.0). Find the magnitude of the parameters Gain and Offset (without considering the 'surpassing') in the table below:

Output signal |  | normalized unipolar 0..+1 |  | normalized bipolar: -1..+1 |  | value equal to output signal
 |  | Gain | Offset | Gain | Offset | Gain | Offset
0 .. +1 | Volt | 0,50 | 1,00 |  |  | 0,50 | 1,00
-1 .. +1 | Volt |  |  | 1,00 | 0,00 | 1,00 | 0,00
0 .. +2 | Volt | 0,50 | 1,00 | 0,00 | 0,00 | 1,00 | 1,00
-2 .. +2 | Volt |  |  | 1,00 | 0,00 | 2,00 | 0,00
0 .. +2,5 | Volt | 0,50 | 1,00 | 0,00 | 0,00 | 1,25 | 1,00
-2,5 .. +2,5 | Volt |  |  | 1,00 | 0,00 | 2,50 | 0,00
0 .. +4 | Volt | 0,50 | 1,00 |  |  | 2,00 | 1,00
0 .. +5 | Volt | 0,50 | 1,00 |  |  | 2,50 | 1,00
0 .. +10 | Volt | 0,50 | 1,00 |  |  | 5,00 | 1,00
0 .. +20 | mA | 0,50 | 1,00 |  |  | 10,00 | 1,00
4 .. +20 | mA | 0,50 | 1,00 |  |  | 8,00 | 1,50
0 .. +24 | mA | 0,50 | 1,00 |  |  | 12,00 | 1,00

Feed supply output: Switching on SPx permits to put a 24V feed supply at terminal 1 (SUP) with a power rate of approximately 25 mA for each port respectively. (The S320 Controller's 24V supply is chargeable up to a total of approximately 200 mA. If it is assured that the sum of consumption does not exceed this total current, one may tap a somewhat higher current from a single slot card.)

Configuration possibilities type 200 slot card:

Syntax: | Port <val> {Name "<val>"; Gain <val>; Offset <val>;};
Port | <val> is the channel number (integer value: 0 or 1) specifying the port.
Name | <val> is a user-defined port name, e.g. "voltage", "pressure", etc.
Gain | <val> is a floating-point number (e.g. 0.54321).
Offset | <val> is a floating-point number (e.g. 0.87654).

Configuration sample type 200 slot card:

MODULE 200 { Port 0 { Name "ControlVoltage";
                      Gain 0.548061;
                      Offset 0.888446; };
             Port 1 { Name "RevolutionsPM";
                      Gain 0.548602;
                      Offset 0.889649; };
           } Slot 0;

> Type 220 Slotcard


Controller S320 Manual - Slot Card Typ220

 2.8 TYPE 220 Slot Card: 4 x Analog Output

The type 220 slot card contains four mutually independent analog outputs with rapid d/a converters.

The converters have 12 bit resolution, the conversion time is approx. 15 µs. The four analog outputs have ground reference, are save against short circuit and work exclusively in the input range between 0 and 10 volt.

This slot card is mainly designed for the particular VA-mode of the S320 Controller, nevertheless it also can be used for general purposes. Remember however that the inputs are designed for maximum speed with an accuracy of less than 1 per cent.

Analog output: Output range in between 0 and 10 volt. Ground reference. The pins 1, 3, 5 and 7 of the connector are the output channels. The pins 2,4,6 and 8 offer the respective ground connections. The outputs are save against short circuits.

Configuration possibilities type 220 slot card:

Syntax: | Port <val> {Name "<val>"; Gain <val>; Offset <val>;};
Port | <val> is the channel number (integer value: 0 or 1) specifying the port.
Name | <val> is a user-defined port name, e.g. "voltage", "pressure", etc.
Gain | <val> is a floating-point number, specifying the gain (e.g. 10.12345).
Offset | <val> is a floating-point number, specifying the offset (e.g. 0.12345).

Configuration sample type 220 slot card:

MODULE 220 { Port 0 { Name "AO0";
                      Gain 10.0;
                      Offset 0.0; };
             Port 1 { Name "AO1";
                      Gain 10.0;
                      Offset 0.0; };
             Port 2 { Name "AO2";
                      Gain 10.0;
                      Offset 0.0; };
             Port 3 { Name "AO3";
                      Gain 10.0;
                      Offset 0.0; };
            } Slot 0;

> Type 300 Slotcard


Controller S320 Manual - Slot Card Typ300

 2.9 TYPE 300 Slot Card: 1 x Analog Input, 1 x Analog Output

The type 300 slot card contains one analog input and one analog output. Precise A/D converters applying the sigma-delta method, combination of the type 100 and type 200 slot cards.

Product in preparation.

> Type 310 Slotcard


Controller S320 Manual - Slot Card Typ310

 2.10 TYPE 310 Slot Card: 1 x Analog Input, 1 x Analog Output

The type 310 slot card contains one analog input and one analog output. It contains flash-converter with 14bit resolution and a conversion time of approx. 10µs.

The high conversion speed makes the type 310 slot card the ideal choice to realise control tasks with cycle times in the range of a few milliseconds.

The input instrumentation amplifier's gain can be adjusted by a resistor RG. The analog output provides usual voltage and current signals.

Analog input: difference input with a common mode input voltage range between -3 and +22 volt referred to GND. The preamplification G by the instrumentation amplifier INA can be defined by the resistor RGx according to the equation: RGx = 49K4/(G-1). The converter is bipolar in the range between -3.0 and 3.0 volt. Switching on SWx8 forces a voltage separation down to 23.25 percent before the conversion. For current measuring, a 47 ohm resistor can be connected in parallel to the input by switching on SWx7.

The table below shows the appropriate resistors RGx (always the next higher resistor according to E24 table is used) and the switch positions SWx7 and SWx8. You will also find magnitude of the parameters Gain and Offset for analog standard signals. The exact calibration of the input is done by these parameters, specified in the configuration file. The values in the table can not replace a precise calibration. Inevitable tolerances of the slot card's resistors are only compensated for by the precise calibration.

 |  |  |  |  | normalized unipolar 0..+1 |  | normalized bipolar -1..+1 |  | value according to input signal
input signal |  | RGx | SWx7 | SWx8 | Gain | Offset | Gain | Offset | Gain | Offset
0 .. +10 | Volt | - | OFF | ON | 1,00 | 0,00 |  |  | 10,00 | 0,00
0 .. +5 | Volt | 47k0 | OFF | ON | 1,00 | 0,00 |  |  | 5,00 | 0,00
-2 .. +2 | Volt | 240k | OFF | OFF |  |  | 1,00 | 0,00 | 2,00 | 0,00
-1 .. +1 | Volt | 36k0 | OFF | OFF |  |  | 1,00 | 0,00 | 1,00 | 0,00
-500 .. +500 | mV | 13k0 | OFF | OFF |  |  | 1,00 | 0,00 | 0,50 | 0,00
-200 .. +200 | mV | 4k70 | OFF | OFF |  |  | 1,00 | 0,00 | 0,20 | 0,00
-100 .. +100 | mV | 2k20 | OFF | OFF |  |  | 1,00 | 0,00 | 0,10 | 0,00
0 .. +20 | mA | 33k0 | ON | OFF | 1,00 | 0,00 |  |  | 20,00 | 0,00
4 .. +20 | mA | 33k0 | ON | OFF | 1,25 | -0,20 |  |  | 20,00 | 0,00

Feed supply: The feed supply offered by the terminal SUP can be set up following the table below. The fine tuning of each feed supply except 24V is done using the trimmer: PSUP:

Supply | SWx1 | SWx2 | SWx3 | SWx4 | SWx5 | SWx6 | power rating | PSUP
none | OFF | OFF | OFF | OFF | OFF | OFF |  |
5 Volt | OFF | ON | ON | ON | OFF | OFF | ca. 15 mA | yes
10 Volt | OFF | ON | ON | OFF | OFF | ON | ca. 15 mA | yes
15 Volt | OFF | ON | ON | OFF | ON | ON | ca. 15 mA | yes
24 Volt | ON | OFF | OFF | OFF | OFF | OFF | ca. 25 mA 1 | no
1 mA | OFF | ON | OFF | ON | OFF | ON | 1 mA | yes

1: The S320 Controller's 24V supply is chargeable up to a total of approximately 200 mA. If it is assured that the sum of consumption does not exceed this total current, one may tap a somewhat higher current from a single slotcard.

Note: Don't set SWx1 and SWx2 at ON together!

Analog output: The analog output provides optionally voltages or currents which can be adjusted as shown below:

Output | SWx1 | SWx2 | SWx3 | SWx4 | SWx5 | SWx6 | SWx7 | SWx8
0 .. +1 V | sup | OFF | OFF | ON | ON | ON | OFF | ON
-1 .. +1 V | sup | OFF | OFF | ON | OFF | ON | OFF | OFF
0 .. +2 V | sup | OFF | OFF | ON | OFF | ON | OFF | ON
-2 .. +2 V | sup | OFF | OFF | ON | OFF | OFF | OFF | OFF
0 .. +2,5 V | sup | OFF | OFF | ON | ON | ON | ON | ON
-2.5 .. +2.5 V | sup | OFF | OFF | ON | OFF | ON | ON | OFF
0 .. +4 V | sup | OFF | OFF | ON | OFF | OFF | OFF | ON
0 .. +5 V | sup | OFF | OFF | ON | OFF | ON | ON | ON
0 .. +10 V | sup | OFF | OFF | ON | OFF | OFF | ON | ON
4 .. 20 mA | sup | ON | ON | OFF | OFF | ON | OFF | ON
0 .. 20 mA | sup | ON | OFF | OFF | ON | ON | ON | ON

The accurate calibration of the output is done by adjusting the parameters GAIN and OFFSET of the configuration file. The slot cards are designed thus, that the output range surpasses the specified range. For instance the analog output for a 0..+10V setup actually covers a range of approx. -0.25V .. 10.25V (for the configuration: Offset = 0.0 and Gain = 1.0). Find the magnitude of the parameters Gain and Offset (without considering the 'surpassing') in the table below:

Output signal |  | normalized unipolar 0..+1 |  | normalized bipolar: -1..+1 |  | value equal to output signal
 |  | Gain | Offset | Gain | Offset | Gain | Offset
0 .. +1 | Volt | 0,50 | 1,00 |  |  | 0,50 | 1,00
-1 .. +1 | Volt |  |  | 1,00 | 0,00 | 1,00 | 0,00
0 .. +2 | Volt | 0,50 | 1,00 | 1,00 | 0,00 | 1,00 | 1,00
-2 .. +2 | Volt |  |  | 1,00 | 0,00 | 2,00 | 0,00
0 .. +2,5 | Volt | 0,50 | 1,00 | 1,00 | 0,00 | 1,25 | 1,00
-2,5 .. +2,5 | Volt |  |  | 1,00 | 0,00 | 2,50 | 0,00
0 .. +4 | Volt | 0,50 | 1,00 |  |  | 2,00 | 1,00
0 .. +5 | Volt | 0,50 | 1,00 |  |  | 2,50 | 1,00
0 .. +10 | Volt | 0,50 | 1,00 |  |  | 5,00 | 1,00
0 .. +20 | mA | 0,50 | 1,00 |  |  | 10,00 | 1,00
4 .. +20 | mA | 0,50 | 1,00 |  |  | 8,00 | 1,50

Feed supply output: Switching on SPx permits to put a 24V feed supply at terminal 1 (SUP) with a power rate of approximately 25 mA for each port respectively. (The S320 Controller's 24V supply is chargeable up to a total amount of approximately 200 mA. If it is assured that the sum of consumption does not exceed this total current, one may tap a somewhat higher current from a single slot card.)

Configuration possibilities type 310 slot card:

Syntax: | Port <val> {Name "<val>"; Gain <val>; Offset <val>;};
Port | <val> is the channel number (integer value: 0 or 1) specifying the port.
Name | <val> is an arbitrary, user-defined port name, e.g. "voltage", "pressure", etc.
Gain | <val> is a floating-point number, specifying the gain (e.g. 10.12345).
Offset | <val> is a floating-point number, specifying the offset (e.g. 0.12345).

Configuration sample type 310 slot card:

MODULE 310 { Port 0 { Name "voltage";
                      Gain 10.76194576;
                      Offset 0.00147000; };
             Port 1 { Name "current";
                      Gain 10.74436995;
                      Offset 0.00190000; };
           } Slot 0;

> Type 400 Slotcard


Controller S320 Manual - Slot Card Typ400

 2.11 TYPE400 Slot Card: Expansion of Digital Interfaces

The type 400 slot card expands the standard number of digital I/Os. The output communicates via a two-wire bus cable (galvanic separation exists) with separate switching modules. The bus allows to connect several I/O modules to one type 400 slot card. The switching modules are designed for DIN-rail mounting.

Expansion modules:

Channels | 16xDI | 8xDI | 16xDO | 8xDO | 8xDI / 8xDO
Module | MOD410 MOD412 | MOD414 | MOD420 MOD422 | MOD424 | MOD430 MOD432

Medium:

The type 400 slot card is connected to the modules via a shielded two-wire cable, preferably with twisted cores. The shield also serves for balancing the potentials. The overall length of the bus segment may have up to 1000 meters depending on the used cable type. The data transfer is regulated over RS485 interfaces (hardware). Inherent micro-controllers in the modules and in the bus slot card each effect the software protocol 'transparently' for the user, i.e. the user is not concerned with any internal procedures.

Connection:

The bus lines are connected to the four-terminal screwing-plugging-clamp. Connect line A to terminal 2 and line B to terminal 3. The ground (protection earth) lies on terminal 4. Terminal 1 offers a 5 volt supply (VCC) via a 100 ohm resistor for termination.

The 3,5 mm stereo-plug that you can find on older type 400 slot cards is no longer supported.

Shielding, Potential balance

The shield has to be put on GND, i.e. protection earth potential (at least ) at one point of the complete bus segment. Beyond that, the potential balance between the S320 Controller and the bus modules has to be guaranteed.

Termination:

The complete bus has to be terminated at both ends following the scheme below:

The termination is usefully implemented at the four-terminal clamp as it offers the VCC signal. Resistors for termination always come in delivery together with each module and slot card respectively and are identified by colour rings in the usual form:

270 Ohm: | red - violett - black - black - brown
120 Ohm: | brown - red - black - black - brown
390 Ohm: | orange - white - black - black - brown

Organization:

Each type 400 slot card allows a theoretic expansion for up to 256 digital inputs and 256 digital outputs respectively, all addressed by a common bus. The ports stay completely 'transparent' for the Spell-programmer, i.e. the input and output handling is identical with the S320 Controller's standard digital input and output. Each digital port is addressed by the standard functions DigitalIn (input) and DigitalOut (output) independent of his hardware location. Only in particular applications one has to be aware, that the transmission of signals via the bus segment causes short delays of some milliseconds until a state of a port is available for the program.

The type 400 slot card supports up to eight modules to maximum 32 bit DI and 32 bit DO each. The actual number of the ports realised by the hardware depends on the switching module type. The module addresses are set by code selectors on each expansion module.

The individual ports of the expansion modules are organised by (byte-wise) sub-addresses. Thus there are eight sub-addresses for each expansion module, which represent 8 bit each. The even sub-addresses stand for digital inputs and the odd sub-addresses stand for the digital outputs. These module sub-addresses are fixed and cannot be modified by the user.

Organization Survey: Type 400 Slot Card bus modules

Addr | Sub 0 | Sub 1 | Sub 2 | Sub 3 | Sub 4 | Sub 5 | Sub 6 | Sub 7
Modul 0 | 8xDE | 8xDA | 8xDE | 8xDA | 8xDE | 8xDA | 8xDE | 8xDA
Modul 1 | 8xDE | 8xDA | 8xDE | 8xDA | 8xDE | 8xDA | 8xDE | 8xDA
Modul 2 | 8xDE | 8xDA | 8xDE | 8xDA | 8xDE | 8xDA | 8xDE | 8xDA
Modul 3 | 8xDE | 8xDA | 8xDE | 8xDA | 8xDE | 8xDA | 8xDE | 8xDA
Modul 4 | 8xDE | 8xDA | 8xDE | 8xDA | 8xDE | 8xDA | 8xDE | 8xDA
Modul 5 | 8xDE | 8xDA | 8xDE | 8xDA | 8xDE | 8xDA | 8xDE | 8xDA
Modul 6 | 8xDE | 8xDA | 8xDE | 8xDA | 8xDE | 8xDA | 8xDE | 8xDA
Modul 7 | 8xDE | 8xDA | 8xDE | 8xDA | 8xDE | 8xDA | 8xDE | 8xDA

Example:MOD410 MOD 420 MOD430

Example Type MOD430 Module at Type 400 Slot Card:

The expansion module MOD430 offers eight digital inputs (DI) and eight digital outputs (DO). Assume its connection to a type 400 slot card at slot 0. The module address 4 is defined by the module's selector. The sub-addresses Sub 0 and Sub 1 are fixed in the case of the type MOD430 module.

The configuration file for the above sample is shown below:

MODULE 400 {          Ü connection to Type 400 Slotcard
     Addr 04 {         Ü module address defined by DIP-Switch
       SubAddr 00 {         Ü 8 digital Inputs on sub-address 0
         Port 0 {Name "DI00";};   Ü name of digital input port 0
         Port 1 {Name "DI01";};
         Port 2 {Name "DI02";};
         Port 3 {Name "DI03";};
         Port 4 {Name "DI04";};
         Port 5 {Name "DI05";};
         Port 6 {Name "DI06";};
         Port 7 {Name "DI07";};
       };
       SubAddr 01 {         Ü 8 digital Outputs on sub-address 1
         Port 0 {Name "DO00";};   Ü name of digital output port 0
         Port 1 {Name "DO01";};
         Port 2 {Name "DO02";};
         Port 3 {Name "DO03";};
         Port 4 {Name "DO04";};
         Port 5 {Name "DO05";};
         Port 6 {Name "DO06";};
         Port 7 {Name "DO07";};
       };
     };
} SLOT 0;             Ü type 400 slotcard on slot 0

Programming of the type 400 slot card:

As far as the modules connected to the type 400 slot card are supplied during the start and the following automatic test of the S320 Controller, any interruption or failure of the bus connection can be excluded and the external ports are updated at regular intervals one can generally avoid particular error handling.

However special situations may cause failures due to the two-wire transfer to the bus modules of the type 400 series, for which specific measures can be provided when designing the program.
The type 400 slot card communicates permanently with the connected bus modules, exchanging data packages. Thereby the information of the digital inputs of the bus modules are continuously transferred to the type 400 slot card, and will be stored there for possible reading access. This access is effected by the program running, when coming to a command DigitalIn. Digital outputs are communicated when the status of an output is changed by a DigitalOut directive.
At program start the type 400 slot card carries out a module scan and detects which modules are connected at the moment. The result may differ from the configuration data due to the several reasons, which can be detected and handled by the executed program using the following three tools:

1. Signal SigHWFailure: This signal is actuated whenever a failure occurs during a data transfer. It will occur when a temporarily unavailable module is tried to be accessed or sporadically due to data transfer failure because of a fault on the line. Consider that this signal is actuated immediately after a call of one of the functions DigitalIn or DigitalOut respectively inside the main program such as a possible error can be processed directly after this hardware call. However if one of this functions is called inside a signal routine, the signal SigHWFailure will only be effected after having executed the entire active signal routine. A possible result from an error signal handling is therefore not yet available inside the calling signal routine.

2. Function GetHardwareError: Use this function after an occurrence of the SigHWFailure signal to detect which module and which port has provoked an error.

3. Function ModuleInit: This function allows the reinitialisation of a distinct slot card. In the particular case of the type 400 slot card a new module scan will be implicitly effected such that a module available meanwhile can be reintegrated into the bus transfer.

The possible occurring error situations will now be discussed briefly:

1. Modules are not correctly configured:

Often error messages can be put down to an incorrect configuration of the bus modules. Make sure that the module addresses set at the module switches match the information of the configuration file. In particular module addresses must not be assigned more than once.

2. Supply failure of Module or Interruption of Bus Connection
To use an example from real life consider an external module installed inside a switch cabinet of an air compressor being supplied with local electric power. The communication can not be established if the compressor is completely switched off. A similar situation occurs if the connection to the module is interrupted. The S320 Controller can not identify the module, each access onto this module will provoke an error. Using the earlier described mechanism the program can recognise the error situation and therefore avoid further access onto this module. A reintegration of the module (after establishing the physical connection or switching on the compressor in the above example) can be effected by a call of the function: ModuleInit.

3. Sporadic Failure of the Bus Connection

External interference to the bus connection may trouble the data transfer between the type 400 slot card and the modules. Those errors can be detected by the SigHWFailure failure. The bus transfer keeps on running unalteratedly after the interference, it is generally not necessary to take particular measures. In such a case it may just be useful to repeat the command for the setting of digital outputs. This kind of error occurs extremely seldom if the installation and the termination of the bus connection is correct.

4. Missing or wrong termination

Missing or wrong termination does inevitably lead to data transfer errors up to a complete interruption of the bus communication. Sporadic, incoherent or just 'inexplicable' errors often are an indication of a faulty termination.

13.14 * Expansion Modules for Type 400 Bus Slot Card
The type 400 slot card allows the flexible adaptation of the S320 Controller to match the required number of digital inputs and outputs. There are different types of expansion modules to be connected to the type 400 slot card. Only the most frequently used types for DIN rail mounting are described below.

> Module MOD410

> Type 500 Slotcard


Controller S320 Manual - Slot Card Typ400

 2.11.1 Expansion Module MOD410 16xDI
No longer available

Module supporting up to 16 digital inputs, 24 volt positive switching, DIN rail mounting design.

Addr | Sub 0 | Sub 1 | Sub 2 | Sub 3 | Sub 4 | Sub 5 | Sub 6 | Sub 7
DIP switch | 8xDI |  | 8xDI |  |  |  |  |

The expansion module MOD410 requires approx. 35 mm DIN rail width. It is supplied by a 24V control voltage and dissipates 150 mA without charge. The inputs are connected by screw terminals. There are two 3,5mm jacks and a four-terminal screwing-plugging-clamp at the module's front for bus connection. The state of each input is shown by LEDs. A rear side rotary selector is used to specify the module's address between 0 and 7. The bus logic has galvanic separation from the 24V supply and receives its potential reference via the bus cable.

Expansion Module MOD410 16xDI
Sub 2:

31: DI Port 0
32: DI Port 1
33: DI Port 2
34: DI Port 3
11: DI Port 4
12: DI Port 5
13: DI Port 6
14: DI Port 7

Sub 0:

21: DI Port 0
22: DI Port 1
23: DI Port 2
24: DI Port 3
41: DI Port 4
42: DI Port 5
43: DI Port 6
44: DI Port 7

15 und 35: Supply 24 V

25 und 45: Supply 0 V

NOTE: The 0V connection of the power supply must be connected externally to protection earth.

The digital inputs dissipate a current of approx. 5 mA.

Configuration possibilities: expansion module MOD410

Syntax: | Addr <val> {SubAddr <val> {Port <val> {Name "<val>";};};};
Addr | <val> is an integer number between 0 and 7 which corresponds to the selected module address (rear side rotary selector).
SubAddr | <val>: set '0' or '2' for the respective eight digital inputs.
Port | <val> is the channel number, specifying the input port 0 to 7.
Name | <val> is the name of the port.

Configuration Sample Module MOD410:

MODULE 400 {
     Addr 04 {
       SubAddr 00 {
         Port 0 {Name "DI40000";};
         Port 1 {Name "DI40001";};
         Port 2 {Name "DI40002";};
         Port 3 {Name "DI40003";};
         Port 4 {Name "DI40004";};
         Port 5 {Name "DI40005";};
         Port 6 {Name "DI40006";};
         Port 7 {Name "DI40007";};
       };
       SubAddr 02 {
         Port 0 {Name "DI40200";};
         Port 1 {Name "DI40201";};
         Port 2 {Name "DI40202";};
         Port 3 {Name "DI40203";};
         Port 4 {Name "DI40204";};
         Port 5 {Name "DI40205";};
         Port 6 {Name "DI40206";};
         Port 7 {Name "DI40207";};
       };
     };
} SLOT 0;

> Module MOD412


Controller S320 Manual - Slot Card Typ400

 2.11.2 Expansion Module MOD412 16xDI

Module supporting up to 16 digital inputs, 24 volt positive switching, 19" mounting. Dimensions: 3U x 7 HP x 70 mm.

Addr | Sub 0 | Sub 1 | Sub 2 | Sub 3 | Sub 4 | Sub 5 | Sub 6 | Sub 7
DIP switch | 8xDI |  | 8xDI |  |  |  |  |

The module requires an internal power supply of 24V and dissipates 150 mA without charge.

A rotary selector is used to specify the module's address between 0 and 7.

The bus is connected with a four-terminal screwing-plugging-clamp. With switch "Term" the bus can be terminated. The termination is enabled with both switches set to "On" and disabled with both switches set to "Off". Be shure to enable the termination only for modules that are connected at the end of the bus.
The bus logic has galvanic separation from the 24V supply and receives its potential reference via the bus cable.

The inputs are connected by a 10 pin screwing-plugging-clamp. Depending on the INT/EXT switch this connector also has the internal power supply connected to 24V and 0V. The state of each input is shown by LEDs.

The digital inputs dissipate a current of approx. 5 mA.

INT/EXT switch:

In position INT the internal supply is connected to the terminals 24V and 0V. The maximum load ist 500 mA.

In position EXT the inputs are driven with an external voltage of 24V with respect to 0V. There is no galvanic coupling between the internal supply and the external control voltage.

Configuration possibilities: expansion module MOD412

Syntax: | Addr <val> {SubAddr <val> {Port <val> {Name "<val>";};};};
Addr | <val> is an integer number between 0 and 7 which corresponds to the selected module address (rear side rotary selector).
SubAddr | <val>: set '0' or '2' for the respective eight digital inputs.
Port | <val> is the channel number, specifying the input port 0 to 7.
Name | <val> is the name of the port.

Configuration Sample Module MOD412:

MODULE 400 {
     Addr 04 {
       SubAddr 00 {
         Port 0 {Name "DI40000";};
         Port 1 {Name "DI40001";};
         Port 2 {Name "DI40002";};
         Port 3 {Name "DI40003";};
         Port 4 {Name "DI40004";};
         Port 5 {Name "DI40005";};
         Port 6 {Name "DI40006";};
         Port 7 {Name "DI40007";};
       };
       SubAddr 02 {
         Port 0 {Name "DI40200";};
         Port 1 {Name "DI40201";};
         Port 2 {Name "DI40202";};
         Port 3 {Name "DI40203";};
         Port 4 {Name "DI40204";};
         Port 5 {Name "DI40205";};
         Port 6 {Name "DI40206";};
         Port 7 {Name "DI40207";};
       };
     };
} SLOT 0;

> Module MOD414


Controller S320 Manual - Slot Card Typ400

 2.11.3 Expansion Module MOD414 8xDI

Module supporting up to 8 digital inputs, 24 volt positive switching, DIN rail mounting design.

Addr | Sub 0 | Sub 1 | Sub 2 | Sub 3 | Sub 4 | Sub 5 | Sub 6 | Sub 7
DIP switch | 8xDI |  |  |  |  |  |  |

A rotary selector is used to specify the module's address between 0 and 7.

The module requires an internal power supply of 24V (24V_LOG) and dissipates 150 mA without charge.The internal power supply and the bus is connected with a five-terminal screwing-plugging-clamp. The bus logic has galvanic separation from the 24V supply and receives its potential reference via the bus cable.
Alternatively these signals can be connected via connectors that are placed directly in the DIN-rail. If connecting multiple modules this significantly reduces the cabling effort.

With switch "Term" the bus can be terminated. The termination is enabled with both switches set to "On" and disabled with both switches set to "Off". Be shure to enable the termination only for modules that are connected at the end of the bus.

The inputs are connected by two 4-pin screwing-plugging-clamps at the bottom of the module. Each input dissipates a current of approx. 5 mA.

The external 24V power supply (24V_PWR) is connected by a 4-pin screwing-plugging-clamp on top of the module. For easy connection of multiple modules, there are two contacts for each 0V and +24V.

There is no galvanic coupling between the internal supply and the external control voltage.

The state of each input and the power supply is shown by LEDs.

Configuration possibilities: expansion module MOD414

Syntax: | Addr <val> {SubAddr <val> {Port <val> {Name "<val>";};};};
Addr | <val> is an integer number between 0 and 7 which corresponds to the selected module address (rear side rotary selector).
SubAddr | <val>: set '0'.
Port | <val> is the channel number, specifying the input port 0 to 7.
Name | <val> is the name of the port.

Configuration Sample Module MOD414:

MODULE 400 {
     Addr 04 {
       SubAddr 00 {
         Port 0 {Name "DI40000";};
         Port 1 {Name "DI40001";};
         Port 2 {Name "DI40002";};
         Port 3 {Name "DI40003";};
         Port 4 {Name "DI40004";};
         Port 5 {Name "DI40005";};
         Port 6 {Name "DI40006";};
         Port 7 {Name "DI40007";};
       };
     };
} SLOT 0;

> Module MOD420


Controller S320 Manual - Slot Card Typ400

 2.11.4 Expansion Module MOD420 16xDO
No longer available

Module supporting up to 16 digital outputs, 24 volt positive switching, DIN rail mounting design.

Addr | Sub 0 | Sub 1 | Sub 2 | Sub 3 | Sub 4 | Sub 5 | Sub 6 | Sub 7
DIP switch |  | 8xDO |  | 8xDO |  |  |  |

The expansion module MOD420 requires approx. 35 mm DIN rail width. It is supplied by a 24V control voltage and dissipates 150 mA without charge. The inputs are connected by screw terminals. There are two 3,5mm jacks and a four-terminal screwing-plugging-clamp at the module's front for bus connection. The state of each output is shown by LEDs. A rear side rotary selector is used to specify the module's address between 0 and 7. The bus logic has galvanic separation from the 24V supply and receives its potential reference via the bus cable.

Expansion Module MOD420 16xDO
Sub 3:

31: DO Port 0
32: DO Port 1
33: DO Port 2
34: DO Port 3
11: DO Port 4
12: DO Port 5
13: DO Port 6
14: DO Port 7

Sub 1:

21: DO Port 0
22: DO Port 1
23: DO Port 2
24: DO Port 3
41: DO Port 4
42: DO Port 5
43: DO Port 6
44: DO Port 7

15 und 35: Supply 24 V

25 und 45: Supply 0 V

Note: The 0V connection of the power supply must be connected externally to protection earth.

Semiconductor switches put the 24V supply to the terminals related to the digital outputs. The sum of all output currents must not exceed 4 Ampere. Each output can be charged with 500 mA. The outputs are short-circuit protected and secure against inductive charges up to 5 mJ. Of course it is always recommended to furnish inductive charges with clamping diodes or any comparable protection circuit.

Configuration possibilities: expansion module MOD420

Syntax: | Addr <val> {SubAddr <val> {Port <val> {Name "<val>";};};};
Addr | <val> is an integer number between 0 and 7 which corresponds to the selected module address (rear side rotary selector).
SubAddr | <val>: set '1' or '3' for the respective eight digital outputs.
Port | <val> is the channel number, specifying the output port 0 to 7.
Name | <val> ist der Name des Ports.

Configuration Sample Module MOD420:

MODULE 400 {
     Addr 04 {
       SubAddr 01 {
         Port 0 {Name "DO40100";};
         Port 1 {Name "DO40101";};
         Port 2 {Name "DO40102";};
         Port 3 {Name "DO40103";};
         Port 4 {Name "DO40104";};
         Port 5 {Name "DO40105";};
         Port 6 {Name "DO40106";};
         Port 7 {Name "DO40107";};
       };
       SubAddr 03 {
         Port 0 {Name "DO40300";};
         Port 1 {Name "DO40301";};
         Port 2 {Name "DO40302";};
         Port 3 {Name "DO40303";};
         Port 4 {Name "DO40304";};
         Port 5 {Name "DO40305";};
         Port 6 {Name "DO40306";};
         Port 7 {Name "DO40307";};
       };
     };
} SLOT 0;

> Module MOD422


Controller S320 Manual - Slot Card Typ400

 2.11.5 Expansion Module MOD422 16xDO

Module supporting up to 16 digital outputs, 24 volt positive switching, 19" mounting. Dimensions: 3U x 7 HP x 70 mm.

Addr | Sub 0 | Sub 1 | Sub 2 | Sub 3 | Sub 4 | Sub 5 | Sub 6 | Sub 7
DIP switch |  | 8xDO |  | 8xDO |  |  |  |

The module requires an internal power supply of 24V and dissipates 150 mA without charge.

A rotary selector is used to specify the module's address between 0 and 7.

The bus is connected with a four-terminal screwing-plugging-clamp. With switch "Term" the bus can be terminated. The termiantion is enabled with both switches set to "On" and disabled with both switches set to "Off". Be shure to enable the termination only for modules that are connected at the end of the bus.
The bus logic has galvanic separation from the 24V supply and receives its potential reference via the bus cable.

The outputs are connected by a 10 pin screwing-plugging-clamp. The state of each output is shown by LEDs.

Semiconductor switches put the 24V supply (see INT/EXT switch) to the terminals related to the digital outputs. Each output can be charged with 500 mA. The outputs are short-circuit protected and secure against inductive charges up to 5 mJ. Of course it is always recommended to furnish inductive charges with clamping diodes or any comparable protection circuit.

INT/EXT switch:

In position INT the outputs are driven by the internal 24V supply voltage. In this case the terminal 24V is not connected.

In position EXT an external supply is needed at the terminals 24V and 0V. There is no galvanic coupling between the internal and the external supply voltage.

Configuration possibilities: expansion module MOD422

Syntax: | Addr <val> {SubAddr <val> {Port <val> {Name "<val>";};};};
Addr | <val> is an integer number between 0 and 7 which corresponds to the selected module address (rear side rotary selector).
SubAddr | <val>: set '1' or '3' for the respective eight digital outputs.
Port | <val> is the channel number, specifying the output port 0 to 7.
Name | <val> ist der Name des Ports.

Configuration Sample Module MOD422:

MODULE 400 {
     Addr 04 {
       SubAddr 01 {
         Port 0 {Name "DO40100";};
         Port 1 {Name "DO40101";};
         Port 2 {Name "DO40102";};
         Port 3 {Name "DO40103";};
         Port 4 {Name "DO40104";};
         Port 5 {Name "DO40105";};
         Port 6 {Name "DO40106";};
         Port 7 {Name "DO40107";};
       };
       SubAddr 03 {
         Port 0 {Name "DO40300";};
         Port 1 {Name "DO40301";};
         Port 2 {Name "DO40302";};
         Port 3 {Name "DO40303";};
         Port 4 {Name "DO40304";};
         Port 5 {Name "DO40305";};
         Port 6 {Name "DO40306";};
         Port 7 {Name "DO40307";};
       };
     };
} SLOT 0;

> Module MOD424


Controller S320 Manual - Slot Card Typ400

 2.11.6 Expansion Module MOD424 8xDO

Module supporting up to 8 digital outputs, 24 volt positive switching, DIN rail mounting design.

Addr | Sub 0 | Sub 1 | Sub 2 | Sub 3 | Sub 4 | Sub 5 | Sub 6 | Sub 7
DIP switch |  | 8xDO |  |  |  |  |  |

A rotary selector is used to specify the module's address between 0 and 7.

The module requires an internal power supply of 24V (24V_LOG) and dissipates 150 mA without charge.The internal power supply and the bus is connected with a five-terminal screwing-plugging-clamp. The bus logic has galvanic separation from the 24V supply and receives its potential reference via the bus cable.
Alternatively these signals can be connected via connectors that are placed directly in the DIN-rail. If connecting multiple modules this significantly reduces the cabling effort.

With switch "Term" the bus can be terminated. The termination is enabled with both switches set to "On" and disabled with both switches set to "Off". Be shure to enable the termination only for modules that are connected at the end of the bus.

The outputs are connected by two 4-pin screwing-plugging-clamps at the bottom of the module. Semiconductor switches put the 24V supply to the terminals related to the digital outputs. Each output can be charged with 500 mA. The outputs are short-circuit protected and secure against inductive charges up to 5 mJ. Of course it is always recommended to furnish inductive charges with clamping diodes or any comparable protection circuit.

The external 24V power supply (24V_PWR) is connected by a 4-pin screwing-plugging-clamp on top of the module. For easy connection of multiple modules, there are two contacts for each 0V and +24V.

There is no galvanic coupling between the internal supply and the external control voltage.

The state of each output and the power supply is shown by LEDs.

Configuration possibilities: expansion module MOD424

Syntax: | Addr <val> {SubAddr <val> {Port <val> {Name "<val>";};};};
Addr | <val> is an integer number between 0 and 7 which corresponds to the selected module address (rear side rotary selector).
SubAddr | <val>: set '1'.
Port | <val> is the channel number, specifying the output port 0 to 7.
Name | <val> ist der Name des Ports.

Configuration Sample Module MOD424:

MODULE 400 {
     Addr 04 {
       SubAddr 01 {
         Port 0 {Name "DO40100";};
         Port 1 {Name "DO40101";};
         Port 2 {Name "DO40102";};
         Port 3 {Name "DO40103";};
         Port 4 {Name "DO40104";};
         Port 5 {Name "DO40105";};
         Port 6 {Name "DO40106";};
         Port 7 {Name "DO40107";};
       };
     };
} SLOT 0;

> Module MOD430


Controller S320 Manual - Slot Card Typ400

 2.11.7 Expansion Module MOD430 8xDI, 8xDO
No longer available

Module supporting up to 8 digital inputs and 8 digital outputs respectively, 24 volt positive switching, DIN rail mounting design.

Addr | Sub 0 | Sub 1 | Sub 2 | Sub 3 | Sub 4 | Sub 5 | Sub 6 | Sub 7
DIP switch | 8xDI | 8xDO |  |  |  |  |  |

The expansion module MOD430 requires approx. 35 mm DIN rail width. It is supplied by a 24V control voltage and dissipates 150 mA without charge. The input and outputs are connected by screw terminals. There are two 3,5mm jacks and a four-terminal screwing-plugging-clamp at the module's front for bus connection. The state of each input/output is shown by LEDs. A rear side rotary selector is used to specify the module's address between 0 and 7. The bus logic has galvanic separation from the 24V supply and receives its potential reference via the bus cable.

Expansion Module MOD430 8xDI, 8xDO
Sub 1:

31: DO Port 0
32: DO Port 1
33: DO Port 2
34: DO Port 3
11: DO Port 4
12: DO Port 5
13: DO Port 6
14: DO Port 7

Sub 0:

21: DI Port 0
22: DI Port 1
23: DI Port 2
24: DI Port 3
41: DI Port 4
42: DI Port 5
43: DI Port 6
44: DI Port 7

15 und 35: Supply 24 V

25 und 45: Supply 0 V

Note: The 0V connection of the power supply must be connected externally to protection earth.

Semiconductor switches put the 24V supply to the terminals related to the digital outputs. Each output can be charged with 500 mA. The outputs are short-circuit protected and secure against inductive charges up to 5 mJ. Of course it is always recommended to furnish inductive charges with clamping diodes or any comparable protection circuit.

The digital inputs dissipate a current of approx. 5 mA.

Configuration possibilities: expansion module MOD430

Syntax: | Addr <val> {SubAddr <val> {Port <val> {Name "<val>";};};};
Addr | <val> is an integer number between 0 and 7 which corresponds to the selected module address (rear side rotary selector).
SubAddr | <val>: set '0' for the eight digital inputs and '1' for the digital outputs respectively.
Port | <val> is the channel number, specifying the port (0 to 7) for the inputs/outputs.
Name | <val> is the name of the port.

Configuration Sample Module MOD430:

MODULE 400 {
     Addr 04 {
       SubAddr 00 {
         Port 0 {Name "DI00";};
         Port 1 {Name "DI01";};
         Port 2 {Name "DI02";};
         Port 3 {Name "DI03";};
         Port 4 {Name "DI04";};
         Port 5 {Name "DI05";};
         Port 6 {Name "DI06";};
         Port 7 {Name "DI07";};
       };
       SubAddr 01 {
         Port 0 {Name "DO00";};
         Port 1 {Name "DO01";};
         Port 2 {Name "DO02";};
         Port 3 {Name "DO03";};
         Port 4 {Name "DO04";};
         Port 5 {Name "DO05";};
         Port 6 {Name "DO06";};
         Port 7 {Name "DO07";};
       };
     };
} SLOT 0;

> Module MOD432


Controller S320 Manual - Slot Card Typ400

 2.11.8 Expansion Module MOD432 8xDI, 8xDO

Module supporting up to 8 digital inputs and 8 digital outputs respectively, 24 volt positive switching, 19" mounting. Dimensions: 3U x 7 HP x 70 mm.

Addr | Sub 0 | Sub 1 | Sub 2 | Sub 3 | Sub 4 | Sub 5 | Sub 6 | Sub 7
DIP switch | 8xDI | 8xDO |  |  |  |  |  |

The module requires an internal power supply of 24V and dissipates 150 mA without charge.

A rotary selector is used to specify the module's address between 0 and 7.

The bus is connected with a four-terminal screwing-plugging-clamp. With switch "Term" the bus can be terminated. The termiantion is enabled with both switches set to "On" and disabled with both switches set to "Off". Be shure to enable the termination only for modules that are connected at the end of the bus.
The bus logic has galvanic separation from the 24V supply and receives its potential reference via the bus cable.

The inputs and outputs are connected by a 10 pin screwing-plugging-clamp. Depending on the INT/EXT switch the input connector also has the internal power supply connected to 24V and 0V. The state of each input and output is shown by LEDs.

Semiconductor switches put the 24V supply (see INT/EXT switch) to the terminals related to the digital outputs. Each output can be charged with 500 mA. The outputs are short-circuit protected and secure against inductive charges up to 5 mJ. Of course it is always recommended to furnish inductive charges with clamping diodes or any comparable protection circuit.

The digital inputs dissipate a current of approx. 5 mA.

INT/EXT switch:

In position INT the outputs are driven by the internal 24V supply voltage. In addition the supply voltage is connected to the 24V an 0V terminals of the input connector and can be charged with 500 mA.

In position EXT an external supply is needed at the terminals 24V and 0V of the output connector to drive the outputs. The inputs are driven with an external voltage of 24V with respect to 0V. The external supply voltage is also connected to the 24V an 0V terminals of the input connector and can be charged with 500 mA.
There is no galvanic coupling between the internal and the external supply voltage.

Configuration possibilities: expansion module MOD432

Syntax: | Addr <val> {SubAddr <val> {Port <val> {Name "<val>";};};};
Addr | <val> is an integer number between 0 and 7 which corresponds to the selected module address (rear side rotary selector).
SubAddr | <val>: set '0' for the eight digital inputs and '1' for the digital outputs respectively.
Port | <val> is the channel number, specifying the port (0 to 7) for the inputs/outputs.
Name | <val> is the name of the port.

Configuration Sample Module MOD432:

MODULE 400 {
     Addr 04 {
       SubAddr 00 {
         Port 0 {Name "DI00";};
         Port 1 {Name "DI01";};
         Port 2 {Name "DI02";};
         Port 3 {Name "DI03";};
         Port 4 {Name "DI04";};
         Port 5 {Name "DI05";};
         Port 6 {Name "DI06";};
         Port 7 {Name "DI07";};
       };
       SubAddr 01 {
         Port 0 {Name "DO00";};
         Port 1 {Name "DO01";};
         Port 2 {Name "DO02";};
         Port 3 {Name "DO03";};
         Port 4 {Name "DO04";};
         Port 5 {Name "DO05";};
         Port 6 {Name "DO06";};
         Port 7 {Name "DO07";};
       };
     };
} SLOT 0;

> Type 500 Slotcard


Controller S320 Handbuch - Slotkarte Typ510

 2.12 TYPE500 Slot Card: 2 x Input for incremental encoders

The type 500 slot card contains two independent inputs for incremental encoders (Channel A and B) with 24 bit counters. The maximum signal frequency is 500 kHz. In addition it is possible to measure the frequency on channel B.

The inputs are implemented via opto couplers, so that nearly any signal form existing in practice can be connected directly. A feed supply of 5 volt and 24 volt is provided for.

Each input logically consists of two ports. For input 1 this is Port 0 for counting and Port 1 for frequency measurement and accordingly for input 2 there is Port 2 for counting and Port 3 for frequency measurement.

The operation modes below are supported:

Port 0/2 |
1. | Incremental encoder: Forward and backward counting of impulses provided by incremental encoders. The maximum counting frequency is 500 kHz, the counting width is 24 bit. On port 1/3 a frequency measurement can be performed simultaneously.
2. | Incremental encoder with quadruple evaluation: As above, however each signal edge of the encoder is counted. This results in a four times better resolution of the encoder signal.
Port 1/3 |
 | Frequency measuring: Reciprocal frequency measuring method. An adjustable prescaler (2 to 256) generates a logical counting period, whilst a 10 MHz pulse is counted by a 24 bit counter. The frequency results from: 5E6 * (prescaler setting / counter value). This method allows to easily fit the measuring period and the resolution best to the specific requirements..

Input: The inputs of the type 500 slot card are equipped with opto couplers. With the dip-switches S1 to S4 the inputs can be configured to meet the requirements of the different encoders A 5 volt or 24 volt feed supply is provided for.

The input is designed as shown below:

Note: replace S1 with S3 and S2 with S4 for input 2.

Configuration examples:

In practice the three most important configurations are:

1. Active encoder outputs for cannel A and B. The encoder has to be connected to an external power supply. In this case the encoder is fully galvanic isolated.

Switch settings::

Voltage | S1 / S3 |  |  |  |  |  |  |  | S2 / S4
 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 1 | 2 | 3 | 4 | 5
5V | OFF | OFF | OFF | ON | ON | ON | OFF | OFF | ON | OFF | ON | ON | OFF
24V | OFF | OFF | OFF | ON | ON | OFF | OFF | OFF | ON | OFF | OFF | ON | OFF

2. Switching the inputs to Vcc. The encoder is powered by the type 500 slot card. Note that there is no galvanic isolation between the encoder and the S320 controller.

Switch settings:

Supply | S1 / S3 |  |  |  |  |  |  |  | S2 / S4
 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 1 | 2 | 3 | 4 | 5
5V | OFF | ON | ON | OFF | OFF | ON | OFF | ON | ON | OFF | ON | ON | ON
24V | ON | OFF | ON | OFF | OFF | OFF | OFF | ON | ON | OFF | OFF | ON | ON

3. Switching the inputs to GND. The encoder is powered by the type 500 slot card. Note that there is no galvanic isolation between the encoder and the S320 controller.

Switch settings:

Supply | S1 / S3 |  |  |  |  |  |  |  | S2 / S4
 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 1 | 2 | 3 | 4 | 5
5V | OFF | ON | OFF | ON | ON | ON | ON | OFF | OFF | ON | ON | OFF | ON
24V | ON | OFF | OFF | ON | ON | OFF | ON | OFF | OFF | ON | OFF | OFF | ON

The maximum load of the supply voltage ist approx. 50 mA for 24V und approx. 20 mA for 5V.

Note: If you determine the switch settings using the schematic above for your special requirements, be shure not to have some illegal settings (e.g. short cuts).
Incorrect settings can cause permanent damage to the type 500 slot card.
For example S1.1 and S1.2 and resp. S3.1 and S3.2 must not be simultaneously ON since this would produce a short cut between the two supply voltages.

Note: If the encoder is powered by the S320 Controller, there is no galvanic isolation.

Note: The built-in pre-resistors for the opto-coupler LEDs are dimensioned for 5V and 24V. An adaption to other requirements can easily be done by an external resistor. The LED of the opto coupler needs a current > 5mA up to 10mA max. for switching. In switched off state the current must be less than 0.25 mA. The diode voltage at 10 mA is typ. 1.5 volt.

Note: Some signal encoders (e.g. mechanical switches) can give several impulses during switching e.g. due to bouncing of the contacts and thus provoke unexpected results. This effect can be avoided by external measures such as RC-elements, monoflops or similar.

Note: The opto couplers establish galvanic isolation in the meaning of a functional separation. It is however not permissible to operate the inputs with voltages > 50 volt relative to the PE-level of the S320 Controller.

Explanation to the reciprocal frequency measuring method: This method is advantageous over the 'current' method (counting a number of impulses during a fixed period) especially for small frequencies, where it leads much faster to a result with higher resolution.

From the frequency to be measured one generates the measuring period by a counter adjustable via a (software) prescaler. Possible prescaling values are 2, 4, 8, 16, 32, 64, 128 and 256. During the positive level of this prescaled signal a 10 MHz pulse is counted by a 24 bit counter. The frequency results from:
5E6 * (prescaler setting / counter value).

Thus the measuring period is not fixed, but results from the prescaler setting and the actual input frequency.

The equations below yield the respective values:

measuring period [s] | = prescaler setting / measuring frequency [Hz]
resolution [Hz] | = measuring frequency [Hz] / (5E6 * measuring period[s])
frequency [Hz] | = 5E6 * (prescaler setting / counter value)

Example 1 kHz-signal: this signal's period length is 1ms. Using the prescaling of 256 the measuring period sums up to 256 ms. During this period the internal counter counts 10.000.000 * 0.5 * 0.256 = 1.280.000 impulses. The resolution is thus 1.000 Hz / 1.280.000 = 0.000781 Hz. Using the 'current' method with a period length of 1 second the resolution would only be 1 Hz (!).

Further examples:

Signal [Hz] | PreScaler | Measuring Period [s] | Resolution [Hz]
1 | 2 | 2,00000000 | 0,00000001
10 | 2 | 0,20000000 | 0,00000100
100 | 2 | 0,02000000 | 0,00010000
100 | 256 | 2,56000000 | 0,00000781
1.000 | 4 | 0,00400000 | 0,05000000
1.000 | 128 | 0,12800000 | 0,00156250
10.000 | 64 | 0,00640000 | 0,31250000
100.000 | 256 | 0,00256000 | 7,81250000
1.000.000 | 256 | 0,00025600 | 781,25000000

Note: It lasts >0.8 seconds until the 24 bit counter running with 10 MHz swaps over (overflow) and then yields a negative result. Thus, using a prescaling of 2, the lowest still measurable frequency is approx. 1.19 Hz.

The standard library stdlib.spi contains the functions for the communication with the type 500 slot card. Below follows a short enumeration of the related functions. The specific descriptions of these function are given in the chapter about the standard library.

Counters are set to zero by the function CounterInit and are read by the function CounterRead .

With CounterSet the counters can be preset.

The function CounterEnable can be used to start and stop the counters.

A frequency measuring is started with FrequencyInit and the result is obtained by calling FrequencyRead. The function FrequencyMeas carries out the complete measuring
in one step.

Configuration sample type 500 slot card:

Syntax: | Port <val> {Name "<val>"; Mode <val>;};
Port | <val> is the channel number (integer value: 0, 1, 2 or 3) specifying the port.
Name | <val> is an arbitrary, user-defined port name, e.g. "gas_ counter", "x-axis", etc.
Mode | <val> the channel's operation mode. Valid parameters are:
 | Port 0/2: |
 | "incrementalcounter" | - incrementalcounter
 | "incrementalcounter4x" | - incrementalcounter4x
 | Port 1/3: |
 | "frequency" | - frequency this is the only possible setting here, but has to be given.

Configuration sample type 500 slot card:

MODULE 500 { Port 0 { Name "CounterA";
                      Mode "incrementalcounter"; };
             Port 1 { Name "FrequencyA";
                      Mode "frequency"; };
             Port 2 { Name "CounterB";
                      Mode "incrementalcounter4x"; };
             Port 3 { Name "FrequencyB";
                      Mode "frequency"; };
           } Slot 0;

> Type 510 slotcard


Controller S320 Manual - Slot Card Typ510

 2.13 TYPE 510 Slot Card: 2 x Input for Frequency Measuring

The type 510 slot card is a universal tool for the counting and the measuring of digital signals. This slot card contains two mutually independent channels with 32 bit counting width and internal 50 MHz oscillator for frequency measuring.

The inputs are implemented via opto couplers, so that nearly any signal form existing in practice can be connected directly. A feed supply of 5 volt and 24 volt is provided for.

Note: The actual version TYP510 Rev.B is a 1:1 replacement of the previous version. This means that there is no need to change the software or the configuration file, but there are different and extended hardware settings.

The operation modes below are supported:

1. | Impulse counting: Counting of impulses with 32 bit counting width and a maximum frequency of approx. 1 MHz.
2. | Incremental encoder: Forward and backward counting of impulses provided by incremental encoders. This operation mode is only possible at port 0. Then at port 1 the by 90° phase displaced signal is connected for the forward-backward detection. The maximum counting frequency is 50 kHz, the counting width is 32 bit. On the second channel can be carried out simultaneously the frequency measuring or the pulse-pause ratio determination of the encoder signal.
3. | Incremental encoder with quadruple evaluation: As above, however each flank changing of the encoder is counted. This results in a four times better resolution of the encoder signal.
4. | Frequency measuring: Reciprocal frequency measuring method. An adjustable prescaler (2 to 256) generates a logical counting period, whilst a 50 MHz pulse is counted by a 32 bit counter. The frequency results from: 25E6 * (prescaler setting / counter value). This method allows to easily fit the measuring period and the resolution best to the specific requirements.
5. | Pulse-pause ratio determination: A 50 MHz pulse is counted in succession by a 32 bit counter during the positive or negative flank of an input signal. The result is the ratio from the "high-flank" over the entire impulse duration. The determination of an impulse length is equally possible in this operation mode.

Input: The inputs of the type 510 slot card are equipped with opto couplers. A 5 volt or 24 volt feed supply is provided for. The input is designed as shown below:

Note: replace S1 with S2 for input port 1.

Settings:

 | Supply voltage |  | Input voltage
S1 / S2: | 1 | 2 | 3
5V | OFF | ON | ON
24V | ON | OFF | OFF

Note: The maximum load of the supply voltage ist approx. 50 mA for 24V und approx. 20 mA for 5V.

Note: S1.1 and S1.2 resp. S2.1 and S2.2 must not be simultaneously ON since this would produce a short cut between the two supply voltages

Note: The pre-resistor to the opto coupler is adjusted to the given input voltage by S1.3 (port0) and S2.3 (port1) respectively. Chosing the position ON for S1.3 and S2.3 respectively, the input with 470 ohm will be suited for 5 volt TTL signals. Otherwise, choosing position OFF, the inputs with 3170 ohm support 24 volt input signals. The LED of the opto coupler needs a current >5mA till up to 10mA max. for switching. In switched off state the current must be less than 0.25mA. The diode voltage at 10 mA is typ. 1.5 volt.

Further input conditions can be matched easily by the use of appropriate external preresistors. The opto coupler allows to connect positive switching as well as 'ground switching' signals. If the feed supply of the S320 Controller is used, the galvanic isolation is of course not given. In this case a connection between -IN and GND is established for positive switching sensors and between SUP and +IN for 'ground switching' sensors.

Note: The opto couplers establish galvanic isolation in the meaning of a functional separation. It is however not permissible to operate the inputs with voltages > 50 volt relative to the PE-level of the S320 Controller.

Filter:

 | Analog signalfilter
S1 / S2: | 4 | 5 | 6
fg = 1.5 MHz | OFF | OFF | OFF
fg = 70 kHz | ON | OFF | OFF
fg = 700 Hz | OFF | ON | OFF
fg = 80 Hz | OFF | OFF | ON

 | Digital signalfilter (only impulse counting)
S1 / S2: | 7 | 8
fg = 8 MHz | OFF | OFF
fg = 70 kHz | ON | OFF
fg = 8 kHz | OFF | ON
fg = 125Hz | ON | ON

The switches S1/2.4 to S1/2.6 respectively add an analog low pass, which restricts the maximum input frequency. This might be necessary when handling low frequency signals with a gentle rise of the flanks (e.g. flow meters) in order to avoid the reading of multiple impulses at flank changing.

Note: Some signal encoders (e.g. mechanical switches) can give several impulses during switching e.g. due to bouncing of the contacts and thus provoke unexpected results. This effect can be avoided by appropriate filter settings.

Explanation to the reciprocal frequency measuring method: This method is advantageous over the 'current' method (counting a number of impulses during a fixed period) especially for small frequencies, where it leads much faster to a result with higher resolution.

From the frequency to be measured one generates the measuring period by a counter adjustable via a (software) prescaler. Possible prescaling values are 2, 4, 8, 16, 32, 64, 128 and 256. During the positive level of this prescaled signal a 50 MHz pulse is counted by a 32 bit counter. The frequency results from:
25E6 * (prescaler setting / counter value).

Thus the measuring period is not fixed, but results from the prescaler setting and the actual input frequency.

The equations below yield the respective values:

measuring period [s] | = prescaler setting / measuring frequency [Hz]
resolution [Hz] | = measuring frequency [Hz] / (25E6 * measuring period[s])
frequency [Hz] | = 25E6 * (prescaler setting / counter value)

Example 1 kHz-signal: this signal's period length is 1ms. Using the prescaling of 256 the measuring period sums up to 256 ms. During this period the internal counter counts 50.000.000 * 0.5 * 0.256 = 6.400.000 impulses. The resolution is thus 1.000 Hz / 6.400.000 = 0.000156 Hz. Using the 'current' method with a period length of 1 second the resolution would only be 1 Hz (!).

Further examples:

Signal [Hz] | PreScaler | Measuring Period [s] | Resolution [Hz]
1 | 2 | 2,00000000 | 0,00000002
10 | 2 | 0,20000000 | 0,00000200
100 | 2 | 0,02000000 | 0,00020000
100 | 256 | 2,56000000 | 0,00000156
1.000 | 4 | 0,00400000 | 0,01000000
1.000 | 128 | 0,12800000 | 0,00031250
10.000 | 64 | 0,00640000 | 0,06250000
100.000 | 256 | 0,00256000 | 1,56250000
1.000.000 | 256 | 0,00025600 | 156,25000000

Note: It lasts >40 seconds until the 32 bit counter running with 50 MHz swaps over (overflow) and then yields a negative result. Thus, using a prescaling of 2, the lowest still measurable frequency is approx. 0.05Hz.

Explanation of the pulse-pause ratio determination: the pulse-pause ration is determined by double time measuring of the high and low flank respectively. The resolution for this operation mode is fixed to 20 nanoseconds. Of course, the simple determination of the impulse length is equally possible in this operation mode.

The standard library stdlib.spi contains the functions for the communication with the type 510 slot card. Below follows a short enumeration of the related functions. The specific descriptions of these function are given in the chapter about the standard library.

Counters are set to zero by the function CounterInit and are read by the function CounterRead .

A frequency measuring is started with FrequencyInit and the result is obtained by calling FrequencyRead. The function FrequencyMeas carries out the complete measuring in one step.

The pulse-pause ratio measuring is started by one of the functions: DutyCycleHighInit or DutyCycleHighLowInit and DutyCycleRead is used to read its result. The function DutyCycleMeas reduces the implementation to one single step.

Configuration possibilities type 510 slot card:

Syntax: | Port <val> {Name "<val>"; Mode <val>;};
Port | <val> is the channel number (integer value: 0 or 1) specifying the port.
Name | <val> is an arbitrary, user-defined port name, e.g. "gas_ counter", "x-axis", etc.
Mode | <val> the channel's operation mode. Valid parameters are:
 | "impulsecounter" | - impulsecounter
 | "incrementalcounter" | - incrementalcounter (port 0 only)
 | "incrementalcounter4x" | - incrementalcounter4x (port 0 only)
 | "frequency" | - frequency
 | "dutycycle" | - dutycyle

Configuration sample type 510 slot card:

MODULE 510 { Port 0 { Name "CounterA";
                      Mode "incrementalcounter4x"; };
             Port 1 { Name "CounterB";
                      Mode "frequency"; };
           } Slot 0;

> Type 520 slotcard


Controller S320 Manual - Slot Card Typ520

 2.14. TYPE 520 Slot Card: 2 x Output Frequency and PWM

The type 520 slot card contains 2 outputs which generate TTL signals with adjustable frequencies and pulse widths.

The outputs offer either the signal ( OUT ) or the inverted signal ( OUT/ ). Both channels work independently from one another and can be synchronized with the function 'StartSync'. Additionally it's possible to read back the current state. At frequencies < 200 Hz the slot card generates a signal SigPWM. With that signal it is possible to synchronize measurements received from analog inputs with the generated pulse.

The frequency is adjustable in the range from ca. 0.1 Hz up to - where it makes sense - ca. 100 kHz. The pulse width can be adjusted between 0 .. 1 or 0 .. 100 %.

NOTE: The signal is generated via several counters and thus cannot be adjusted steplessly. The actual frequency or the actual pulse width thus can differ slightly from the target value. The function PWMGetSettings returns the exact frequency applied by the slot card and the exact resolution of the pulse width. Note that, the higher the frequency, the rougher the stepping of the frequency adjustment and the smaller the resolution of the pulse width.

NOTE: The TTL signals at the outputs are 'pure' TTL signals (74HCT14) and as such are only supposed to be handled inside a shielded case with short wire length (< 1 meter). In case of doubt you should use a linking block with galvanic separation.

All functions needed to communicate with the slot card Typ520 are implemented in the standard library stdlib.spi. The exact definitions of those functions can be looked up in the appropriate chapter.

With PWMSetFrequency the frequency is set and PWMSetPulsewidth sets the pulse width. With the function PWMStart the pulse is started and with PWMStop the pulse is stopped. PWMStartSync starts both channels in the synchronized mode.

PWMGetSettings generates a record, which returns the necessary data to calculate all the applied values. For details look up the library stdlib.spi, section 'Generating Pulse and Frequencies'. PWMGetState returns the current state.

Configuration possibilities type 520 slot card:

Syntax: | Port <val> {Name "<val>"; StopState <val>;};
Port | <val><val> is the channel number (integer value: 0 or 1) specifying the port.
Name | <val> is an arbitrary, user-defined port name, e.g. "valve" etc.
StopState | <val> 0 oder 1, state of the output while stop

Configuration sample type 510 slot card:

MODULE 510 { Port 0 { Name "PWM0";
                      StopState 0; }
             Port 1 { Name "PWM1";
                      StopState 1; }
            } Slot 0

> Accessories


Accessories S320 Controller

 2.15 Accessories
Full Scale Picture 800x600 ( 105 kByte)
 Sensible accessories make working easier!

The accessories embrace power packs for a quick putting into operation, a diagnostic adapter, expansion modules and of course cables, plugs and clamps.

A RS485 field bus adapter facilitates the bus connection.

If you need 'atomic' precision of the real time clock, the DCF77-radio clock will solve your problem.

LEDIG - Diagnostic Adapter for Digital Standard I/Os

The diagnose adapter LEDIG is plugged into the digital I/O and the supply connectors at the rear of the S320 Controller. The status of the digital I/Os is shown by LEDs. The digital inputs can be set by DIP switches. These switches and the adapter's digital inputs are linked (over diodes) in a logical 'OR'-relation.

T485 - Adaptor for RS485-Field Bus Connection

The T485 adapter facilitates the wiring of RS485 field bus connections. The adapter is The adapter is mounted to a DIN rail. A 2 meter cable for the connection between the adapter and the S320 Controller with 4-terminal FCC68 connectors fitting the S320 Controller is included in delivery. The field bus cable is connected via screwing plugs.

The two plugs marked with the earthing symbol (PE-connector) have to be connected to the protection earth and if necessary to the bus cable shielding. The PE of the T485 adapter must be connected to PE of the S320 Controller. For end-termination switch both DIL-switches to ON. Both switches in OFF position means no termination. The signal lines A and B are interconnected to the S320 Controller. The T485 adapter additionally contains protection diodes. See also chapter for the S320 Controller 'Connections'.

Note: Correct field bus connection provided, a voltage of approx. 2.8 volt between A and PE and a voltage of approx. 2.1 volt between B and PE can be measured in quiescent state, i.e. without any active bus transfer.

DCF77 Radio Clock

The radio clock DCF77 receives and evaluates the 'official' time signal sent through the 'Physikalisch-Technische-Bundesanstalt' (PTB) in Mainflingen near Frankfurt/Main (Germany).
It allows to permanently and automatically update the internal real time clock.

The DCF77 radio clock is connected to the serial interface Ser0. The serial interface also provides the necessary power supply. Each time when a time signal is correctly received, the operating system activates a signal. By including a relevant signal function the internal real time clock of the S320 Controller can be updated continuously.

During operation the integrated LED shines in green and flashes in red once a second. The usual measures for DCF77 signal receiving have to be taken: the radio clock must not be installed inside a switch cabinet or too close to other electrical devices such as monitors, frequency transformators or even the S320 Controller itself. The cable length is approximately 2 meters. Use for example the cable DSK9/2 or DSK9/7 for extension.

Assembly Material

KLK - Fixing clamp, short version, set with two pieces.

KLL - Fixing clamp, long version, set with two pieces.

DIF - Sealing for front panel cut-out

Link Cable

LINK2 - Cable for link interface, 2 meter length, included in delivery. FCC68-6-pins at one end, DSUB socket 9-pins at the other end.

LINK7 - Cable for link interface, 7 meter length. FCC68-6-pins at one end, DSUB socket 9-pins at the other end.

DSA25/9 - Link-adaptor for 25-pin serial PC ports. DSUB socket 9-pins at one end, DSUB socket 9-pins at the other.

DSK9/2 - Serial connection cable 9-pins, 2 meter length. DSUB socket 9-pins at one end, DSUB plug 9-pins at the other. Connection 1:1. The connection of a COM PC port and the Ser0 port of the S320 Controller provides the required null modem connection.

DSK9/7 - Serial connection cable 9-pins, 7 meter length. DSUB socket 9-pins at one end, DSUB plug 9-pins at the other. Connection 1:1. The connection of a COM PC port and the Ser0 port of the S320 Controller provides the required null modem connection.

Plugs

ST8 - 8-terminal connection plug, e.g. for the digital standard I/Os

ST4 - 4-terminal connection plug, e.g. for analog inputs

ST3 - 3-terminal connection plug, e.g. for analog outputs

SS3 - 3-terminal connection plug for the supply connection

Power Packs

NAD01 - Table power pack 24 volt 30 watt output, input 90-260VAC. For the S320 Controller supply, e.g. during commissioning. Supply connector.
NAD02 - Power pack for DIN rail mounting. Output: 24 volt 30 watt , input: 90-260VAC. For the S320 Controller supply in a permanent installation, e.g. in a switch cabinet..

> Configuration


Configuration of the S320 Controller

 2.16 S320 Controller Configuration

The S320 Controller's hardware is configured in a configuration file: '*.cfg'.

The hardware defined in this file becomes accessible to the Spell program. Digital and analog ports are addressed via names which are defined for each port in the configuration file. The name is arbitrary and has a maximum length of 15 characters.

This name allows the operating system to create a handle for a port calling the function OpenPort. The access itself onto the ports is effected for instance by the function AnalogIn with the previously obtained handle.

PROGRAM Access;
VAR
  hdp : PortHandle; {Handle, channel 'differential pressure'}
  dp  : FLOAT;      {Variable 'differential pressure'       }

BEGIN
  hdp := OpenPort('DiffPress');
  dp  := AnalogIn(hdp);
END.

and the coresponding part in the configuration file:

# TYPE100 Analog Input at Slot 0 Port 1
MODULE 100      { Port 0    { Name "DiffPress";
                              Gain 10.76194576;
                              Offset 0.00147000;
                              Filter 10.0;
                              PreGain 1; };
                  Port 1    { Name "NotUsed";
                              Gain 10.74436995;
                              Offset 0.00190000;
                              Filter 10.0;
                              PreGain 1; };
                } Slot 0;

Note: the port names called in a Spell program are case-sensitive and must match exactly those of the configuration file.

Thanks to this port name assignment the Spell program is independent from the eventual hardware realisation. As a consequence hardware changes (e.g.: substitution of the slot card type 110 for a slot card type 100) only concern the configuration file.

Furthermore the physical scaling of the hardware is done in the configuration file where the converter's offset and gain errors can be directly compensated for. Therefore exist the parameters: 'Gain' and 'Offset'. For instance analog inputs always yield internal values between -1.0 and +1.0 for bipolar input. The offset value is added to this internal value. The result is multiplied by Gain and then returned by the function 'AnalogIn'.

The determination of the parameters Gain and Offset will be explored later in this chapter.

Depending on the slot card type there exist further parameter for filter coefficients, pre-gains, etc. which are equally defined in the configuration file. These parameters will be described in the chapters about each specific slot card.

The serial interfaces must also be declared in the configuration file with a defined baud rate.

The Configuration File

The configuration file is described below discussing the following example:

# Configuration File S320 Controller
# Slot0 : TYPE100
# Author : Herbert Mustermann

# Serial interfaces
SERIAL          { Baud 9600;
                  Buffer 256;
                  Term 13;
                  Frame "8N1";
                  Protocol "STRING";
                  Handshake "None";
                 } Ser 0;

# Standard Digital I/O
MODULE 50       { Port 0     { Name "I00"; };
                  Port 1     { Name "I01"; };
                  Port 2     { Name "I02"; };
                  Port 3     { Name "I03"; };
                  ...
                  Port 8     { Name "O00"; };
                  Port 9     { Name "O01"; };
                  ...
                  Port 15    { Name "O07"; };

# TYPE100 Analog Input at Slot 0
MODULE 100      { Port 0    { Name "voltage";
                              Gain 10.76194576;
                              Offset 0.00147000;
                              Filter 10.0;
                              PreGain 1; };
                  Port 1    { Name "current";
                              Gain 10.74436995;
                              Offset 0.00190000;
                              Filter 10.0;
                              PreGain 1; };
                } Slot 0;

General syntax of the configuration file:

Comments are identified by a leading '#'. The following characters will be disregarded until the start of a new line. The S320 Controller can only access hardware which is declared in the configuration file. A call of faulty or not declared hardware results usually in a run time error.

Syntax: | KEY <nr> { <list> } <loc>;
KEY: | Key word: 'SERIAL' or 'MODULE'. Use SERIAL for the settings of the serial interface of the Controllers S320 and MODULE to define the slot cards or the basic digital ports.
<nr>: | Only for module definition. Here the type number of the slot cards is needed (e.g. 400 when a type 400 series card is plugged in) or when referring to the standard digital I/Os put module number 50 on slot -1.
<list>: | The parameter list of the respective module, separated by semicolons.
<loc>: | The slot or the interface respectively whereto the parameters are assigned. Whether put one of the expressions Ser 0, Ser 1 or Ser 2 for the definition of the respective serial port, Slot -1 for the standard digital I/Os or define the slot by the expression Slot x, where x is the slot number between 0 and 4.

Parameter List Serial Interfaces

Syntax: | Baud <val>; Buffer <val>; Term <val>;
Baud | The transfer velocity in Baud. <val> is an integer number. Possible values are: 300, 600, 1200, 4800, 9600, 19200, 38400. This parameter has to be defined explicitly, otherwise the interface can not be addressed.
Buffer | Serial interface buffer size, defined by <val>, an integer type number between 256 and 4096. Optional parameter, the default value is 256.
Term | Specifying the sign marking the string termination. This sign is usually a line feed (LF = 10 = $0A) or a carriage return (CR = 13 = $0D). Alternatively any other sign (e.g. '>' ) may be used for particular communication applications. Optional parameter, the default value is LF.
Frame | Interface parameters (data bits, parity and stop bits) in the common representation, e.g.: "8N1". Possible values for data bits: 5, 6, 7 or 8. Possible values for parity: N (None), O (Odd), E (Even), S (Space) and M (Mark). Possible values for stop bits: 1 or 2. Alternatively the parameters Databits <val>, Parity <val> and Stopbits <val> can be explicitly given. The settings are optional, default values are: 8 data bits, no parity and one stop bit (8N1).
Protocol | The serial interface communication can be run using two different protocols: the default string-protocol (PROTOCOL "String";) or alternatively the byte-protocol (PROTOCOL "Byte";). Some of the communication functions differ depending on which protocol is used. These functions are contained in the standard library stdlib.spi. See the respective chapter for further information. A radio clock DCF-77 is available as an accessory which can be connected directly to the Ser0 serial interface. The radio clock is declared by: PROTOCOL "DCF77"; All further parameters (baud, buffer, etc.) will then be implicitly set to the appropriate values.
Handshake | Employed handshake method for the RS232 interface Ser0. Possible values are "none" (no handshake) or "rts/cts" (hardware handshake). When using the hardware handshake it must be assured that the communication opposite (e.g. PC) does operate the respective lines. Optional parameter, the default value is "none".

For safe data transfer serial interfaces according to RS232 should preferably operate using hardware handshake. It has however to be assured that both members operate correctly the respective signals RTS and CTS respectively. Consider that the S320 Controller naturally only signals its readiness to receive data (RTS) if the serial interface SER0 is correctly declared in the configuration file and if the user program is active. A S320 Controller in terminal mode and during the data transfer from and to the S320 Controller does therefore take away this signal. Also the signal is cut after the execution end of a program (including also e.g. a run time error).

The received characters are stored in an internal buffer. After receiving the terminating sign (generally a line feed) when running in 'string-mode' or after receiving one or more characters running in byte-mode, the signal SigSer0 is actuated. Alternatively or additionally the function ComAvail allows to check if the respective data is available from the buffer. The user program has to adopt the buffer data, which is done by the function ComReceive or ComBufReceive respectively. If data is not taken over the RTS signal will be cut as soon as the buffer is filled.

Accordingly the S320 Controller interrupts the sending of data via the interface, if the receiving device (e.g. a PC) does not signal a request (RTS). If the data can not be sent and the S320 Controller sending buffer becomes full, the functions ComSend and ComBufSend respectively wait until sufficient buffer memory is available again. This might lead to unwelcome 'hanging' of the executable program. Thus before putting a string into the sending buffer it is recommended to always check if enough memory is available (Functions: ComBufFree, ComBufferAvail).

Digital Inputs and Outputs of the Basic Device

Digital Inputs and Outputs of the Basic Device

The 8 digital inputs and outputs respectively of the basic S320 Controller are declared in the configuration by MODULE 50 on Slot -1. The parameter list distributes the names to the used ports.

MODULE 50, Parameter List:

Syntax: | Port <val> {Name "<val>";};
Port | The key word 'Port' is used to characterise one input or output. The following value <val> is an integer channel number for the corresponding port. The channels 0 to 7 are digital inputs and the channels 8 to 15 are digital outputs.
Name | The key word 'Name' serves for assigning a reference name to the port. The string constant <val> contains the name of the port, a (case-sensitive) character string, e.g. 'cylinder', 'alarm' or the like. The name's maximum character number is 15.

Modules and Slot Cards

Different parameter list formats exist for the different slot card types used. This results from optimal use of special hardware possibilities. The parameter lists for all slot cards are described together with the card details in the corresponding chapter.

MODULE 100, Parameter List::

The module 100 (Type 100 Series slot card - analog inputs) is here described representatively for all card types. See the individual chapters for a specific card.

Syntax: | Port <val> {Name "<val>"; Gain <val>; Offset <val>;
Port | The key word 'Port' opens the parameter list. The integer <val> contains the channel number. In type 100 series cards both channels (0 and 1) are analog inputs.
Name | The key word Name assigns the subsequent name: <val> to the port, e.g. 'voltage', 'pressure' or the like.
Gain | The floating-point number following this keyword serves for scaling and calibration of the analog input.
Offset | This floating-point number following this keyword serves for scaling and calibration of the analog input.

These four parameters always occur in all analog card definitions. Further parameters are specific and differ for all card types. See the corresponding chapter for particularities.

Gain and Offset

The scaling and the calibration of the analog hardware is done by defining the parameters GAIN and OFFSET. The S320 Controller uses these two parameters to replace the otherwise indispensable trimmer for the adjustment of the analog measuring device. As far as possible one has abstained from using potentiometer or trimmer for the adjustment of the hardware. Merely the transducer supply outputs are partly fitted with trimmers.

The parameters GAIN and OFFSET however achieve much more than their analog equivalents. They are more flexible, for instance a straight scaling to a physical unit, e.g. to 'Psi' is no problem.
Mathematically the procedure described below is nothing more than the evaluation of simple linear equations. Admittedly this procedure may seem confusing at first sight. However, those who were already searching for a sensor on the roof of a production plant, 'armed' with a screwdriver, or who had the chance to look after an electronic board deeply inside a 19"-switch cabinet will soon appreciate this alternative.

As a rule you should switch on the S320 Controller and its connected sensors approx. one hour before starting precise calibration in order to establish stable operating conditions (temperature).

The basic equation for the analog inputs is of the form:

E = ( X + OFFSET ) * GAIN

where E is the physical input value i.e. the value which will be returned by the function 'AnalogIn' and X is the internal converter value. This latter value ranges between -1.0 and +1.0. The other parameters OFFSET and GAIN are defined in the configuration file.

For analog outputs the scaling is effected the other way round.

The basic equation for the analog outputs is then:

X = ( A / GAIN ) - OFFSET

where A is the physical output value given to the function 'AnalogOut', i.e. the value in the S320 Controller's representation. X is the internal value between -1.0 and +1.0, the converter input. The OFFSET and the GAIN again are defined in the configuration file.

Below we discuss a data acquisition chain in detail. Giving an example one begins at a pneumatic pressure and ends at its representation as a numeric value of the S320 Controller.

1. | The pressure to be measured is in-between -0.5 bar and 7.0 bar.
2. | A transducer transforms this range to an electrical signal in-between 4 and 20mA.
3. | The current is conducted through a 50 Ohm resistor what results in a voltage between 0.2 and 1.0 volt.
4. | An instrumentation amplifier enhances the voltage signal by the factor 2.3. The signal now lies in-between 0.46 volt and 2.3 volt. The amplification is sensibly chosen such that the resulting upper value lies somewhat underneath the theoretical limit (in the present case 2.5) in order to assure the conversion of the complete range.
5. | An AD-converter generates a dimensionless value between -1.0 and 1.0 corresponding to the analog value between -2.5 volt and + 2.5 volt.
6. | An offset value is added to this dimensionless value and the sum is multiplied by a gain value. The result now represents a pressure in form of a floating-point value.

The procession sequence is shown in the figure below:

In practice each of the mentioned transformations is tainted with an error. Even the most precise pressure sensor will not yield exactly 4.00000mA at a pressure of -0.5 bar and exactly 20.00000mA at a pressure of 7.0 bar. Also the resistor for current-to-voltage transformation will provoke an error and the enhancement of the instrumentation amplifier will not be exactly 2.30000.

Nevertheless the sum of these errors can be compensated for in step 6 using appropriate values for gain and offset.

If you want to compensate for non-linearities of the sensors, the S320 Controller is the ideal device to perform any mathematical interrelation between the measured signal and its internal representation.

The standard library LIN.SPI offers ready-to-use functions for the linearization tasks below:

- 100 ohm platinum RTD linearization
- polynomial of any order
- linear interpolation with any number of setpoints
- spline interpolation with any number of setpoints

If for instance you find a logarithmic or quadratic character of your sensor, the correction can also be easily performed by the respective mathematical equation.

Contemplating the range limit: analog inputs and outputs always have an upper and a lower limit. An input which is configured in a range between 0.0 and 10.0 volt will inevitably yield a maximum value for an input signal higher than 10.0 volt.

If the calibration is done for 'exactly' 10.0 volt, it might happen, that the converter already is at its limits (e.g. due to internal tolerances), then the result of the calibration will not be correct.

For this reason particular care has been taken to design the S320 Controller slot cards in a way that most inputs and outputs cover more than the set range. For instance a type 200 slot card which is set to 0..10 volt is able to actually provide an output voltage of approx. -0.5 to 10.5 volt. This guarantees that the required end values can be reached. The necessary adjustment is done by choosing the appropriate gain and offset parameter.

This however was not possible for all output ranges. The end values of the type 200 slot card in current mode 4..20mA are defined by chip-internal references. They are of course tainted with slight, however measurable errors. If an exact representation of the end values is required, one possibility would be to choose the next higher range, e.g. 0..24mA. The end values 4mA and 20mA are then sure to lie in-between the operation range of the output.

If the output limit is a problem at calibration only, because e.g. the output does not provide 20.0000mA but 19.9998mA only, it is recommended to shift the calibration points inside the range. For instance the calibration could be performed for the setpoints 4.5mA and 19.5mA. The operation range is still calibrated correctly. Of course one will still have an error at the physical limits where the linear rise of the characteristic curve will bend into the constant maximum value.

Calibration using the Development Software

The Development Software offers the menue commands: Config > Calibrate Analog Port to support you calibrating the analog inputs and outputs. It also computes new settings for Gain and Offset.

Analog inputs: After selecting the menue command a list appears on the left side on the screen which contains all analog inputs defined in the configuration file stored inside the S320 Controller. First choose the input to be calibrated. The next dialogue window shows the current values for Gain and Offset. Type the value of the measuring signals you want to connect the input to into the fields for "Upper setpoint" and for "Lower setpoint".

The following dialogue displays continuously the current measured input value. Connect the input value corresponding to the upper setpoint to the input and accept the result by choosing "Set upper". Repeat this procedure for the lower signal. Use "Done" to let the Development software compute the new values for Gain and Offset. Copy these new values to the configuration file and transfer the file to the S320 Controller. The new calibration can be checked choosing the menue command: "Config/Test I/O".

Analog outputs: After selecting the menue command a list appears on the right side on the screen which contains all analog outputs defined in the configuration file stored inside the S320 Controller. First choose the output to be calibrated. The next dialogue window shows the current values for Gain and Offset. Type the internal value you will use as an argument for the function AnalogOut into the fields for "Upper Logical Signal Range" and for "Lower Logical Signal Range" setpoint. Check the output equation X=(A/GAIN)-OFFSET to assure that the given value A for both, the upper and lower setpoint, lies in-between -1.0 and +1.0 for bipolar converters or between 0.0 and +1.0 for unipolar converters. If an error message occurs after giving the setpoint values, check the current Gain and Offset settings, following the instructions in the chapter "First Calibration of analog outputs" and choose appropriate values in the configuration file.

Eventually type the values you expect to later measure at the output for the earlier given internal values into the fields "Upper Physical Signal Range" and "Lower Physical Signal Range". The following dialogue allows to set the output using the menue commands: "Set Upper" and "Set Lower". Input the measured values to the respective fields for "Upper Value" and "Lower Value". The S320 PC program will now compute the new values for Gain and Offset. Copy these new values to the configuration file and transfer the file to the S320 Controller. The new calibration can be tested calling the menue command "Config/Test I/O".

Initial Calibration of Analog Inputs

The data acquisition chain for analog inputs is calibrated following the steps below:

1. | Adjust OFFSET = 0.0 and GAIN = 1.0 in the configuration file.
2. | Adjust the input range, the pre-amplification and if necessary the transducer supply on the slot card as required by the intended task. Further information about this adjustment is given in the chapter for the individual the slot card and in the documents accompanying the sensor. Above all, make sure that the chosen input range is actually covered by the converter, so that over-range conditions are precluded. This would be the case, for instance if the configured input range included 0 to 5 volt while you tried to measure or scale a signal between 0 and 10 volt.
3. | Put a lower range input signal Il for example 4 mA when input range lies in-between 4 and 20 mA. If using the calibration support of theDevelopment Software enter this value into the field "Lower Physical Signal Range" and the upper value Iu into the field "Upper Physical Signal Range". Get the result of the conversion Xl, assume 0.12345. Implement a simple S320 Controller program to show the resulting value or accept this lower value by the menue command: "Set Lower".
4. | Put an upper range input signal Iu, for example 20 mA. Get the result Xl, assume1.0543. Using the Development Software accept the displayed value by the command: "Set Upper".
5. | Let the Development Software calculate the new values of Gain and Offset or calculate the parameters applying the following relationship: GAIN = (Iu - Il) / (Xu - Xl) OFFSET = (Il Xu - Iu Xl) / (Iu - Il) our example would yield: GAIN = 17.18822 and OFFSET = 0.10927 Note: Of course, these equations will only yield correct results if the actual values used are directly provided by the converter and not subject to further transformations.
6. | Substitute the new values of the OFFSET and the GAIN for the initial values in the configuration file. Transfer the file to the S320 Controller. After restarting the program you will find the numerical value 4.0 for an input signal of 4mA and a numerical value 20.0 for an input signal of 20 mA.
7. | Likewise you can set any physical unit that will suit. For instance using a pressure transducer which provides a 4-20mA output for a pressure range of 0-10 bar you can calibrate the input as follows: Put a 4 mA current to the input and use Il = 0.0 (bar) in the above equation. Then put a 20 mA current and use Iu= 10.0 (bar). Alternatively you also may directly connect the pressure transducer and create the calibration pressures of 0 bar and 10 bar respectively. With this calibration method one implicitly eliminates the sensor's inaccuracies .

Re-Calibration of Analog Inputs

If the values GAIN and OFFSET have already been calculated however a re-calibration of an analog input becomes necessary for example due to a sensor's drift, follow the instructions below:

1. | Put a low range analog signal Irl (required low input) to the input, e.g. 4 mA for an input range between 4 and 20 mA. If using the calibration support of the Development Software enter this value into the field "Lower Physical Signal Range" and the upper value Iru into the field "Upper Physical Signal Range". Get the result of the conversion: IAl (actual low input), for example 4.0880 mA. Using the Development Software support accept this lower value by the menue command: "Set Lower".
2. | Put an upper range analog signal Iru (required upper input), e.g. 20 mA. Read the result Iau (actual upper Input), e.g. 19.8030 mA. Using the Development Software support accept this lower value by the menue command: "Set Upper".
3. Let the Development Software calculate the new values of Gain and Offset or compute the corrected values OFFSETcorr and GAINcorr by applying the following relationship, where the values OFFSETact and GAINact are the actual values in the configuration file, for example:

 GAINact    =  17.18822180
 OFFSETact  =   0.10926750

 GAINcorr   =  ((Iru - Irl) / (Iau - Ial)) * GAINact
 OFFSETcorr =  (Iru / GAINcorr) - (Iau / GAINact) + OFFSETact

 the example respecting the above assumptions yields:
 GAINcorr   =  17.5000
 OFFSETcorr =   0.1000

Note: Of course, these equations will only yield correct results if the actual values used are directly provided by the converter and not subject to further transformations.

4. | Replace the actual configuration parameters by the corrected values OFFSETcorr and GAINcorr in the configuration file and transfer the modified file to the S320 Controller. After restarting the program you will again receive the numerical value 4.0 for an input signal of 4mA and 20.0 for an input signal of 20mA respectively.
5. | Likewise assign any wished physical unit to your input signal. See the previous section.
6. | Check your range conditions even when re-calibrating. In particular when effecting important changes of the GAIN and the OFFSET there is a risk of involuntary establishment of over-range conditions.

Initial Calibration of Analog Outputs

The calibration of analog outputs requires two steps:

The first step is to define the translation which the function AnalogOut has to give to the converter, respecting the equation: X=(A/GAIN)-OFFSET.

1. | A signal in the range between e.g. Ol = 4.5 bar and Ou = 23.0 bar shall correspond to the converter's range between Xl = 0.0 and Xu = 1.0 First calculate the parameters GAIN and OFFSET using the relationships below:GAIN = (Ao - Au) / (Xo - Xu) GAIN = (Ou- Ol) / (Xu - Xl) OFFSET = Ou (( Xu-Xl )/( Ou-Ol )) - Xu Inserting the upper values one receives: GAIN = 18.500000 OFFSET = 0.243243 Please note, that some DA-converters (e.g. TYPE200 and TYPE310) have bipolar operation. In that case a value between -1.0 and +1.0 is transformed into a unipolar signal (e.g. between 0 and 10V). The translation has then to be defined for Ol = 4.5 bar and Ou = 23.0 bar to Xl = 0.0 and Xu = 1.0. The resulting parameters would then be: GAIN = 9.250000 OFFSET = 1.486486
2. | Write the values for GAIN and OFFSET to the configuration file.
3. | Select the required output signal, e.g. 4 to 20 mA. The slot card jumpers permit to output a variety of common used signals. Read the description of the individual slot cards for details.

The second step is eventually to physically calibrate the output as described in the following chapter 'Re-Calibration'.

Re-Calibration of Analog Outputs

Follow the steps below to re-calibrate analog outputs.

1. | Charge the converter with an upper range output value Ou, e.g. Ou = 23bar, for which one assumes a required output current of Oru = 20 mA. Measure the actual output current, which may be for example Oau = 20.331 mA. If using the output calibration support of the Development Software first enter the required values as follows:
 | "Upper logical" = Ou = 23 "Lower logical" = Ol = 4.5 | "Upper physical" = Oru = 20 "Lower physical" = ORl = 4
 | The program checks if the values to be given to the converter, which follow from the logical borders Ou and Ol, lie in the range between -1 and +1.
 | The following dialogue permits to output the upper value with "Set Upper". Measure the current value, e.g. 20.331 mA and enter the result into the upper field: "Upper Value".
2. | Repeat this procedure for a lower range output value, for example Ol = 4.5 bar, with a required output current Orl = 4 mA. To illustrate the proceeding one now assumes an actual lower output value of Oal = 4.131 mA. Using the Development Software support you now set the output to the value Ol using "Set Lower". Measure the current, e.g. 4.131 mA and enter the result into the lower field: "Lower Value".
3. | Let the Development Software calculate the new values of Gain and Offset or compute the new values for GAINcorr and OFFSETcorr applying the following relationships: The current values of the configuration file are for example: GAINact = 18.500000 OFFSETact = 0.243243 The relationships: GAINcorr = ((Oau - Oal) / (Oru - Orl)) * GAINact OFFSETcorr= OFFSETact + (((Orl-Oal)*Ou-(Oru-Oau)*Ol) *(1/GAINcorr-1/GAINact))/ (Orl-Oal-Oru+Oau) yield for our numerical example: GAINcorr = 18.73125 OFFSETcorr = 0.2483267
4. | Write the new values for GAINcorr and OFFSETcorr to the configuration file and transfer the modified file to the S320 Controller. When restarting the Controller's program, the Controller will output a signal of 20 mA for an input signal of 23 bar or the output signal of 4 mA for an input of 4.5 bar respectively.
5. | Beware of over-range conditions. Particularly when effecting important modifications of the GAIN and the OFFSET you should check if the converter is still working in its specified range.

> Development Tools


S320 Controller Manual - Development Tools

 3. Development Tools for the S320 Controller

There're several tools included that allow you to program the Controller S320 .

After you insert the CD into your CD-Rom drive the installation program will start automatically. There're three options to choose from:

1. Installation of the IDE onto your PC.
2. Browse offline through the TetraTec web pages.
3. Read whats new.

If the installation program isn't starting automatically, please open your CD-Rom folder and doubleclick installs320.exe.

3.1 Development Software

For quick and rational program development we offer you a powerful integrated development environment (IDE) for your PC. The IDE manages all communication with the controller via the serial interface or a network connection.
The cable for the serial LINK connection is included in the shipment and is connected to the controller via the link socket. For a network connection a normal network cable is needed.

Within the IDE the programs are written, compiled and transfered to the controller S320. You can also start or stop the controller with the IDE. Additional features of the IDE are: read back the program source code or set the system clock.

Within the main window all settings are accessible through the usual menus. The functions needed most during routine work can be started directly from the launchpad, which can be placed anywhere.

Each child window can be placed at any position on the screen via Options > Float Selected or Float Current. So even if you're engaged in a complex project you will always have everything in your view.

During program development you can activate the following single windows:

3.1.1Build

In this window the actual program development takes place.

This window shows the sources which will be linked and compiled to the executable program file (*.spx). This screen is separated into two main parts. In the upper part you find an explorer-like window, the file list which usually shows all the source files which will be linked together to the executable. In the lower part you see a file viewer window.

File-List:

Unlike the files showed in the explorer these files can be distributed over many different directories. This is the advantage of this view, that you will always have an overview and direct access to all files included into your project independent from your preferred file organization.

The file symbols come in three different colors. Symbols of files in the local directory are painted in blue, those in any other directories are painted in yellow. If a file is read-only, its symbol will always be painted in red.

NOTE: After installation of the include files or the demos from CD, those files are usually write-protected and as such displayed red. If you want to modify those files you need to change their attributes manually.

Files which can not be found at all in the currently given folders are labeled with a question mark icon. If you select such a file (e.g. by clicking on the respective line or symbol) a Dialog appears which asks how to proceed with this file:

Here you find two search options which are basically the same, only that the resulting path will be found either specifically for your current project, or generally available for all projects as standard path (see Global Settings). If you are convinced the file does not exist at all, e.g. because you just typed another include statement to your code (see exemplary program development) click on create a new file. This will create an empty file with only one comment at its top telling you the name of this file. If you are not certain what to do with this file, cancel the operation.

File-Viewer:

In the lower part of the window you usually see the contents of the selected source file. You can inspect the file, scrolling up and down, moving in the text. However this is only a viewer of the files. You can not change the files in this window. For editing just use the editor you feel most comfortable with (see Global Settings to change your editor to be used as the default). To open the editor double-click in this viewer window, or double-click directly on the file in the upper window. Clicking once on the files does select them and open them in the viewer.

If a file is showed in the viewer, the status line on top of the viewer tells you its name and path.

The viewer however can display more information. After you have finished developing your program (do not worry if you have not even started, you can follow an exemplary program development later in this manual ) you will "make" your executable program. You can do this whether by chosing the hammer and screwdriver symbol of the symbol menu or by the menu command Build->Make. If you did an impeccable job, the message "Compiled ok." will appear in the status line, and a memory statistic will appear in the viewer. (This statistic shows the memory distribution in the code, data, constant and RAM/ROM persistent segment. ) Congratulations.

If you compile a new program development for the first time, you might have overseen a slight error. Then the error line is displayed in the viewer. The above file list will change to an error list, which gives you more information about the reason and the location of the error. There is always only one error at a time which will be mentioned. The compiler stops after the first noticed error. The list might get longer however if warnings were previously detected. Then you can click on different warnings to open the respective locations in the file viewer. Double-clicking in the error list will open the file in the editor (even at the respective line if your editor is able to position a file at opening, see Global Settings).

Finally the viewer can be used to look at the code listing or assembler listing which you just created by the menu commands: Build->Make Assembler Listing or Build->Make Code Listing respectively. Nevertheless these files do easily become too big to be displayed in these windows (the maximum file size of the viewer is limited to ~65000 characters). But again just double click in the viewer to open the file in your editor. (Make sure it is not the default editor notepad, as notepad will sure not open it either). The current "health state" of your spx file can always be controlled in the main windows statusbar.

Refresh command:

The structure of your program is determined directly from the sources. If you want to include another source file, you have to edit the file where the new file has to be included and add an include statement to that file: INCLUDE "newfile";. Of course it would cost to much resources to always check the program structure and immediately update the list after each change. This is why it is up to you to refresh the screen after you finished a programming or structuring step. Another reason for a structure changement could be the use of another include file of another directory, e.g. by adding a new project specific path. Therefore use the menu command Build->Refresh or the respective button of the symbol menu.

Project specific paths can be given to your project to facilitate the work with different hierarchical file structures: if you develop several programs you will soon find code of one program to be useful for the next. So you might decide to create a directory where you share the code between both projects. Then again you do not consider this code being so general as to always include it in all your projects, where it would have been preferable to make this path a standard include path (see Global Settings). There you see the blue bar on top of the file list window. You see the text "Project Specific Paths" written on it. After that a number in braces tells you how many include paths are specific to thisproject. It is at least one specific path, namely the current working directory, the path where you settle your spc file. At its left hand side you see a button with a downwards arrow. Click on it to drop down a path list. Here you can add, edit or remove the specific paths at will.

Explorer command:

The explorer command of the menu or the respective symbol opens the explorer of your operating system in your current working directory. So you have your familiar environment for file operations, e.g. for copying or deleting files. Creating files for your project is best be done as described in our exemplary program development.

Grep command:

This is the search engine for your spell sources. It allows you to retrieve text in your project sources. And this text will be searched in all the included files over all the different directories. If you are looking for a specific section of code but you get too many matches for all the comments you have written in your code (as you are a good programmer which uses comments abundantly) just switch on the option "Skip Comments" which allows to have a search in the "naked" code without comments.

The other options are "Local Files Only" which does only search in the files of the current working directory, i.e. the home directory of your project's spc file. "Ignore Case" lets you decide if you want to have case sensitive or case insensitive search. Normally one would leave this option set, as spell itself is not that sensitive to upper or lower characters either.

After the search you get a list with all the matches. A double click on the line of this list opens this code at the given position in your editor. (You have to use an editor which is capable of doing this, see Global Settings).

Copy files command:

If you want to copy a complex program however which is distributed over several include paths it might be too fussy to use the standard mechanism to copy all the files. Therefore the S320 program offers the command Build->Copy Files (or again use the symbol menu button). This will open a directory browser. Choose the directory where you want to copy your project to. Then all files from your current hierarchical file structure will be copied to this directory (flat file structure). Note: spp-libraries are considered being part of the system. So these files are neither shown in the file viewer nor copied by this mechanism.

3.1.2 Exec

In that window the structure of the compiled spx-file is shown. There's also the possibility to unpack the program sources included in the spx-file. Another feature of that window is, that in case of a run time error you can type in the error code supplied by the error-handler and the line will be marked in the source code wich caused the error.

3.1.3 Config

This screen shows the hardware configuration file for the S320 Controller. The configuration file is stored as *.cfg. A double-click on the file viewer opens the current configuration file for editing.
The commands related to the configuration file are: send configuration, retrieve the configuration and check the correctness of the current configuration (Debug Configuration).

The config menu provides further operations concerning the hardware-configuration of the S320 Controller:

Test I/O:

The menu command Config->Test I/O opens a form which allows a simultaneous supervision of all analog and digital signals.

Calibrate analogt Port:

The menu command Config-> Calibrate Analog Port starts a wizard which will guide you step by step through the calibration process of analog inputs or outputs:

  1. Choose the calibration port:
The first step is to choose the port you wish to calibrate. You get a list of the ports defined in the currently loaded configuration file. You must decide if you want to calibrate an analog input or an analog output port by chosing the appropriate radio button. Then you can select one of the ports in the respective list and click continue to proceed.
  2. Choose the signal range:
In the next window the current settings of the active configuration file are displayed. This is for control only, they are of no further interest for your calibration.

You have to specify the physical signal range for your calibration, e.g. 0.0 for the lower and 10.0 for the upper value for a signal range between 0 and 10 volts.

If you are calibrating an input port, let's say for a pressure input signal, you could even specify directly the resulting pressure range here, e.g. between 20 and 0 bar absolute pressure. There are even more meaningful settings for this pair of values as there are different sensors out there on the market.

If you are calibrating an output there will be fewer meaningful choices. Then the physical signal range corresponds to the expected output signal, whether in volts (e.g. 0..10 volt) or in mA (e.g. 4..20mA). A second value pair gives the range which you use for its internal representation in the program, which could be identical (0..10 in the source code means 0..10 volt at the output) but often one prefers a normed output value 0..1, so that one is independent from the actual physical output, i.e. one does not have to decide inside the program code whether the signal will later be 4..20mA or 0..5 volts or any other possible range.

  3. Determine the current range:
Now you have to provide for the current discrepancies, i.e. tell the program what you really measure with the current settings. Therefore you need an external reference of course. This step differs fundamentally between the input and the output:

For the determination of the input value you connect an external signal to your input port (e.g. by using the signal generator MIGEN -ask your supplier for more information). Tune in the upper value which corresponds to your physical range of step 2. Then push the button "Set Upper" to copy the current input value (shown at the top of the window) to the upper value box. Repeat this for the lower value and finally continue to the last step.

For the determination of the output value you need an external volt-meter or ampere-meter respectively. Connect this to your analog output. Then push the button "Set Upper" and read the value from your external device. Copy this value to the input field "Upper Range". Next push the button "Set Lower" and again copy the measured value to the lower value field. Proceed to the final step.

  4. Calibration result:
In the port combo box you can display all the ports which you have re-calibrated so far since starting the calibration wizard. In the gain and offset window you see the new values for your configuration file for this port.

The push button "Calibrate Another Port" sets the wizard back to step one, but intermediately stores the values from the previous calibration. Check the box "Modify Configuration File" if you want the current configuration in your S320 program to be modified automatically when finishing the calibration wizard.
Attention: this modifies the configuration file loaded in the S320 Controller! So make sure these configuration files are compatible, otherwise do the modifications manually!

3.1.4 SystemMsg

System messages from the S320 controller, for example after the boot sequence, are shown here. If there has been a run time error, this window is definetly worth a look.

3.1.5 UserMsg

Within that window you can communicate with the S320 controller via the serial interface. Especially for debugging purposes this is a very helpful tool. Within a program the functions 'TermSendMsg' and 'TermReceiveMsg' are used for serial communication. The example program 'DemoTermSer0' explains how to use those functions.

3.1.6 CommMsg

In contrast to UserMsg this window works with a second connection to the S320 Controller. This connection is either a serial or a network connection. For setup of this connection see GlobalSettings->Comm. In fact this window offers you a seperate small ASCII-terminal which can be used for other purposes.

For example you can communicate with the Ser0 interface on your S320 controller. Connect your second serial device to the Ser0 interface of your controller with a 1:1-Cabel DSK9/2. The example program 'DemoTermSer0' works also with the Ser0 interface.

3.1.7 Graph

The S320 controller cannot - mostly out of mechanical reasons - display graphics. But it's often very usefull to display measurements graphically. Since version 3 there's the possibility to display any result in the IDE.

This window allows you to plot your results either as 'Graph' or as a 'YX-Plot'. The example programs 'DemoGraph' and 'DemoPlot' show you how it's done. The necessary data is recieved via the Link interface.

Graphical Interface:

The data, that is supposed to be displayed - that data could be any sort of measurement or some calculated data - is transfered to the IDE via some specific commands and interfaces.

One of the most popular functions is drawing the characteristic curve. The IDE can draw up to 6 different curves simultaneously, each with a different color. The additional code in your program is very easy and simple to implement. How to do that is described in the example program 'DemoGraph'.

Thats how you can test plot the characteristic curve:

1. load the files 'DemoGraph.spc' and 'DemoGraph.cfg' to the IDE
2. compile the spc-file, e.g. with Ctrl+M.
3. upload the spx-file, e.g. with Exec > Send Executable
4. upload the cfg-file, e.g. with Config > Send Config
5. start the program, e.g. with F9
6. open the child window Graph
7. start plotting with Enable Graph
8. after each Enable Graph or Disable Graph the representation changes from horizontal to vertical.
9. with List View you can follow the data, that is used to draw the graph, or with Graph View you can go back to 'pure' graphics.

Plotter Interface:

The plot function simulates the known XY-plotter of the S320 controller in the IDE. The implementation is very similar to the above described graph function. The example program 'DemoPlot' shows you how to work with this feature. The program will plot concentric squares in different colors.

That's how you can test the plot-function:

1. load the file 'DemoPlot.spc' and 'DemoPlot.cfg' to the IDE
2. compile the spc-file, e.g. with Ctrl+M
3. upload the spx-file, e.g. with Exec > Send Executable
4. upload the cfg-file, e.g. with Config > Send Config
5. start the program, e.g. with F9
6. open the child window Graph
7. start plotting with Enable Graph

3.1.8 Statusbar

In the statusbar the status of the link-connection, the Comm connection of the internal terminal program and the status of the compiled code is displayed.

3.1.9 Launchpad

Through the launchpad all the important functions are accessible without running through menus. You can dock and undock the launchpad from the main window by clicking the blue pin or with Options > Launchpad. With 'Float Current' the activated child window can be disconnected from the main winwow and placed everywhere on the screen.
At the top of the launchpad you can see the actual version of your controller. This version is of course only valid if you have a link-connection to the controller. If you are working offline you see the default version wich could be set in the Global Settings->Misc.
With the buttons Connect Link and Connect Comm you can establish or cut the connections. If you click on the Icon , the connection type toggles between serial and network connection.
The launchpad also gives you direct access to the configuration *.cfg, the source code *.spc and the compiled code *.spx. If you click on either button the appropriate child window will be activated. You can also load files here via Drag&Drop. If you hover with the mouse pointer over one of the buttons a short help message will appear, that tells you what the function of that button is.

3.1.10 Network configuration

The S320 controller since Version 4 has also a network interface.
You find the configuration under System->Network_Configuration. To configure the controller you must have a link connection.

The settings in detail:

  • General
Here you can enter the IP-address and the netmask of the controller interface and if available a nameserver can be specified here. This screen also allows you to enable or disable the network interface.
  • Routing
You can enter up to to 5 static routes here.
  • Syslog
To send messages to another host you can configure syslog. To use this feature you need another computer that has the syslog service enabled.
  • HTTP
The controller also offers you a small HTTP-Server . So you can access data that is stored on the controller with your web browser. The setting here specifies the number of simultaneous connections to the server.,

3.1.11 S320 Filesystem

The S320 controller since Version 4 offers you a filesystem where you can store files.
You can start the explorer with S320File->Explore. On the left side you see the files that are stored on your computer and on the right side you see the files that are stored on the controller. With the buttons above the file lists you can change the directories. On the controller there are the two builtin directories "/www/" and "/dat/". In the "/www/" directory you can store files that you want to access over the HTTP-Server . The "/dat/" directory is meant as a common data directory.
To copy data you first have to select the file(s). With the ">>" button the files are copied to the controller and with the "<<" button the files are copied to your computer. In both windows you have a context menu by pressing the right mouse button. With this menu you can rename or delete files.
If you transfer files to the controller the files are stored in the RAM of the controller because writing of the internal ROM is not really fast. With the button "Flush" all files that are actually stored in RAM are written to the internal ROM. (Where a file is actually stored is displayed in the column "Loc." of the controller window).
The flush function is automatically called when you leave the explorer and there are any changes or if you transferred multiple files and the internal RAM buffer cannot hold all the files.

3.2 Software Configuration (Global Settings)

The software is usually set up correctly for different systems by the installation program. Nevertheless it maybe necessary to configure the interfaces manually. You can access the configuration menu with Options->Global_Settings

In any case check the settings for the Link-Interface in the main menu: Options->Global_Settings->Link.

Since version 4 of the S320 Terminal Program (s320.exe) all settings are stored in an ini-file and not any more in the registry.
When installing the software you are asked whether you want to have common settings for all users or own settings for each user. If you decide to have common settings for all users the ini-file is created in the S320 program folder. To be able to save changes each user must have write permissions in this folder.
If you decide to have own settings for each user the ini-file is created in %APPDATA%\Tetratec\S320 when the program is started for the first time. In this case the user is informed that the ini-file is created.
In any case whenever the program is started, it first looks if there is a user ini-file. So if you have selected to use a common ini-file when you have installed the program, you can create the folder %APPDATA%\Tetratec\S320, copy the common ini-file into this folder and you have a special ini-file for the logged in user.

NOTE: Since Windows 2000 APPDATA is an environment variable that contains the path for user specific application data. If you are running Windows NT 4.0 use USERPROFILE instead.

The different settings in detail:

  • Editor
Here you can choose an editor. The default setting is 'Notepad' which comes along with the windows operating system. For programming however we recommend you to use another editor. The best choice is always the editor you are most familiar with. If you have not made up your mind yet we might recommend you 'UltraEdit'. For this editor we can deliver also an extension for syntax highlighting of "spell". You get this extension from TetraTec for free. The editor itself however is not free (and unfortunately not from TetraTec either).
The arguments are used to tell the editor which file to display and (if possible) at which line to position the cursor. Since the editor calls to perform this tasks differ from editor you can specify the command-line here. There are two keywords for the filename and the linenumber:

%FILE is replaced by the filename
%LINE is replaced by the linenumber the cursor should be placed.

any other other character in this field is taken as is. So the correct Argument setting if you use UltraEdit is:

"%FILE/%LINE"

and for the Notepad - since this editor is not able to take a line number argument - simply:

%FILE

Note: This settings have been basicallly changed in S320 version 4

  • Include
The standard include paths are specified here.

Since there are many differences in the standard include files for the controller version 3 and 4 you have to specify the path for both versions separately.

For compiling the paths are searched in the order: 1. local directory, 2. project paths, 3. standard paths. The standard paths are searched in the listed order from the top to the bottom. Use the arrow buttons to change the order. Browse to the directory you want to add using a file browser which you can open with the "Browse" button. Or use the editor line to type a new path which you have to accept by the "Set" button. Note: the edited path will not be stored if you push the ok button directly to leave the settings dialog! You have to add it to the list first.

  • Compiler
The S320 program calls an external compiler. Here you specify the compiler's path and the filename. There are also different versions of the compiler for your Controller version 3 or 4 . So you have to specify them separatly. The "Check Version" button allows you to control the version of the compiler.
The compiler options allow you to pack the source code together with the executable code, so that it will be stored in the S320 Controller's memory. So you always know where to recover your original sources even after years of operation. Three warning levels let you decide how penible the code should be checked. It is recommended to keep the high warning level unless you have got a good reason for reducing the warning level.
  • Listing
The listing options concern the command: Build->Make Assembler Listing and determine the amount of information given in this listing.
  • Comm
Here you set the connection parameters for the communication screen "CommMsg". This is a conventional ASCII-terminal for communication to the S320 Controller.

For the controller version 4 you can decide if you want to connect via network or the serial interface Ser0. By clicking the radio button "RS 232" or "Network" you specifiy the default connection. This can easily be changed by using the launchpad.

RS 232 connection:

The COM port is the serial port of your PC that you use for serial connection to the S320 Controller.

The baud rate, the interface parameter frame, the hardware handshake and the string termination character must match the configuration of the S320 Controller.

The baud rate is the transfer speed in bits per second, the S320 Controller default is 9600 baud.

Interface parameters (data bits, parity and stop bits) are given in the common frame representation, e.g.: "8N1". Possible values for data bits are 5, 6, 7 or 8. Possible values for the parity are N (None), O (Odd), E (Even), S (Space) and M (Mark). Possible values for the stop bits is 1 or 2. The default values used by the S320 Controller are: 8 data bits, no parity and one stop bit (8N1). "RTS/CTS" is the hardware handshake method for the RS232 interface Ser0 which is off per default.

The termination value is the ASCII code of the character used for end detection of a send data package. It is usually a line feed (LF = 10 = $0A) or a carriage return (CR = 13 = $0D). Alternatively any other sign (e.g. '>' ) may be used for particular communication applications. The default value is a carriage return: 13. This setting is only interesting in ASCII transfer mode ("string mode") and not used for byte transfer mode (see chapter Serial Interfaces in the manual's library description).

Network connection:

In the Name or IP field you can specify the hostname or the ip-address of the controller you want to connect to. The Port field specifies the ip-port the controller is listening for connections. Use the the ping button to check if the the controller is reachable.

Common settings:

The option local echo determines whether the sent data is also logged on the terminal screen.

The delay per line in milliseconds is interesting for file transfer. There you might want to reduce the speed after sending a data package to give time to the S320 Controller application to react and process the received data. Whether this is necessary depends on how the S320 Controller side is programmed. Usually it does not do any harm to have a halt of some milliseconds granted.

  • Link
Here you find the parameters for the connection beween your PC and the link interface of the S320 Controller, i.e. the programming and controlling connection to the S320 Controller. If you can't get a connection to the S320 controller e.g. with Connect->Link Connect or Ctrl+L this is the place to check.

As in the Comm section you can decide whether you want a network o a serial connection. Usethe radio button "RS 232" or "Network" to specify the default connection type.

RS 232 connection:

The COM port is the serial port of your PC that you use for link connection to the S320 Controller.

The baud rate is the transfer speed in bits per second, the S320 Controller default setting for link communication is 38400 baud.

Network connection:

In the Name or IP field you can specify the hostname or the ip-address of the controller you want to connect to. The Port field shows you the port the S320 Controller is listening for Link connects. Use the the ping button to check if the the controller is reachable.

Common settings:

The check parameter determines whether the S320 Controller shall be automatically be re-booted after the transfer of a new operating system. As you always need to re-boot the system after an update, leave this option checked.

  • Misc
Here you can specjfy which version to use if you are working offline (no connection to the controller). Also the font settings e.g. for the terminal screens, and a flag which decides whether the command "Build->Copy Files" affects the files in the standard library paths or not can be set here.
  • Graph
Presentation and scaling of the axis for the graph- and plot-function can be modified.
  • Manual
Path to the local html-files of the manual for the S320 controller.

3.3 Set Link Connection

There are several ways to get a LINK Connection with your S320 controller. Controller version 3 only supports the serial connection. Controller version 4 supports the serial and a network connection.

Serial connection:
In order to connect the serial link-interface of the S320 controller to your PC you need the LINK cable, which is included in the shipment. More data concerning the link-interface can be found in chapter Technical Data.

Network connection:
Simply connect the controller to your local network.

To establish the connection you can press the button Connect Link on the lauchpad, press Ctrl+L or choose Connect->Link Connect. If necessary you can check the settings via Options->Global Settings->Link. Many functions are only available if the link-connection is working properly. To test the connection you can always go to Connect->Link Check or press Ctrl+Shift+L. With Command > Get System Info the connection is also tested.

With the autobaud detection Connect->Link Autobaud or Ctrl+A the current baud rate of the S320 controller will be detected. The default baud rate is 38400 baud.

NOTE: If the autobaud detection of the terminal program fails, the reason might be the continuous sending of data by a TermSendMsg function of the active program. This can foil the successful initialisation of the serial interface. Remedy: restart the S320 Controller and keep the 'up' (>) and 'down' (<) keys pressed simultaneously until the end of the auto-test of the S320 Controller in order to suppress automatic starting of the user program.

3.4 Set Comm Connection

There several ways to get a COMM Connection with your S320 controller. Controller version 3 only supports the serial connection. Controller version 4 supports either the serial or a network connection.

Serial connection:
In order to establish a connection from the Ser0 interface of the S320 controller to another serial interface on your PC you need a 9-pole 1:1 cabel like the DSK9/2. More data concerning the serial connection can be found in chapter Technical Data. To establish the connection you can press the button Connect Comm on the launchpad, press Ctrl+S or choose Connect->Comm Connect. If necessary you can check the settings via Options->Global Settings->Comm. You can check the connection if you upload the program 'DemoTermSer0' to the S320 controller, start it and then type in an arbitrary string in CommMsg.

Network connection:
Simply connect the controller to your local network. To establish the connection you can press the button Connect Comm on the launchpad, press Ctrl+S or choose Connect->Comm Connect. If necessary you can check the settings via Options->Global Settings->Comm. You can check the connection if you upload the program 'DemSock' to the S320 controller, start it and then type in the command 'HELP' in CommMsg.

3.5 Programming step by step

The controller needs two files to run - the spx-file and the *.cfg configuartion file. The basic principles of programming the S320 controller are explained in the example program 'Demo05'.

Please read the chapters about electrical wiring, installation of hardware and software and establishing the link-connection first.

1. Open with File > Open > spc or via Drag&Drop the example program file Demo05.spc. In the child window Build the source code of the program appears as well as a list of the included libraries.

2. Open with File > Open > cfg or via Drag&Drop the configuration file Demo05.cfg of the program file Demo05.spc. This file probably already has been loaded due to the name equality.

3. Activate the child window Build or doubleclick the editor-symbol on the launchpad. The source file will be opened with your chosen editor and can be modified.

NOTE: After installation of the include files or the demos from CD those files are usually write-protected and as such displayed red. If you want to modify those files you need to change their attributes manually.

4. Close the editor and compile the program with Build > Make, Ctrl+M or through the button on the launchpad. The spx-file will be generated and you can see the result of the compilation in the child window Build. If there were any mistakes no spx-file will be generated, instead the appropriate error messages will appear in the child window Build.

5. Upload the spx-file with Exec > Send Executable or via the launchpad to the S320 controller.

6. Upload the cfg-file with Config > Send Config or via the launchpad to the S320 controller.

7. Start the programm in the controller with Command > Start Program , by pressing F9 or directly via the button on the launchpad. A digital clock appears on the front panel of the S320 controller..

Until a programm fits your needs several development cycles will probably be necessary, which will look like the above described cycle.

3.6 Communication to the S320 Controller

There're two different ways how to communicate with the S320 controller:

Link-Interface: The link-connection is the main link between the S320 controller and the PC during program development. Via this connection the transfer of configuration and program-files from and to the S320 controller is made possible. In the child window SystemMsg you can follow the system messages. In the child window UserMsg you can communicate with your program on the S320 controller through the link-connection. This connection is also needed for the following features: updating of the operating system with Command > Send Operating System, receiving plot data, retrieving system information with Command > Get System Info, setting of the clock with Command > Set Time, erasing and transfering persistent data with Command > Delete Persistent Data, testing of analog and digital connections with Config > Test I/O, calibration of slot cards with Config > Calibrate Analog Port and many more.

Serial RS232 Interface Ser0: The serial interface Ser0 on the S320 controller is designed for communication with the PC during operation. Through this interface the program can transfer data, adjustments can be made and parameters can be exchanged. During development or installation you can directly communicate with the S320 controlller through the child window CommMsg..

Another possibility for communication are the two serial RS485 interfaces Ser1 and Ser2 of the S320 controllers, which also can be used for data exchange during operation. Since a PC usually doesn't provide RS485 interfaces those cannot be directly accessed through the IDE.

3.7 Compiler Errors

In the child window Build the program is compiled with Build > Make, Ctrl+M or directly through the launchpad. If there were no errors you'll receive some data concerning memory usage.

If there's been a syntax error the compiler will stop and show you the line in the source code which contains the error. Correct the mistake, save the file and recompile. If there's been a compiler error no spx-file will be generated and the statusbar shows the following message: SPX Not Up To Date.

Warnings can prevent programming errors. In this case a spx-file will be generated. A warning is released for example if a variable is used before its initialisation. In this case the program's syntax is correct, the program can be executed. However a programming error is probable. Warnings may be suppressed in Options > Global Settings > Compiler. This can be helpful during the program's developing. A program in its final version however should not provoke any warnings even at warning level 3.

-w3 Function <Name> is never called

-w2 Parameter <Name> is never used

-w3 Variable <Name> is declared but never used

-w1 Use of <Name> before initialisation

-w1 Value assigned to variable <Name> is never used

-w3 Constant <Name> is declared but never used

-w2 Reference parameter <Name> was not changed
A variable is given to a function as a 'reference' parameter, though it is not changed by the function. You should consider a 'normal' declaration.

-w2 Low and high border of range are equal
The two limits of the range label ('CASE'-directive) are equal.

-w1 Low border of range is greater than high border
The lower limit of the range label of a CASE-directive is higher than the upper limit. The corresponding code is unreachable.

-w2 Unreachable code
Look for faulty set RETURN directives, impossible conditions or the like.

-w1 Function may return without a value
Does function contain a RETURN directive?

-w1 Floating point underflow
A floating-point operation resulted in a number which is too small for representation with the available accuracy

-w1 Partial loss of floating point precision
A floating-point operation can not be carried out accurately, because the argument reaches the value's limits of the operation.

-w3 { found inside a comment
Did you put a section in comment brackets which already included comments?

-w3 Condition is always true

3.8 Run Time Errors

Run time errors are errors which occur during operation and cause the termination of the program. A popular example is the division by zero or if the subscript is out of line.

If the S320 controller is connected to the IDE via the link-connection when a run time error occurs, the error message will appear in the child window SystemMsg. The IDE will then detect the code which caused the error. You can ignore the password dialog with the OK button since there's no password. In order to test the error detection you can use the example program 'Demo03' where a run time error is caused with a division by zero.

If the controller works 'offline' (which means that it's not connected to the IDE) the run time error will be handled by an error handler, which should always be implemented by including the library stderr.spi or with a selfdesigned error handler. In case of stderr.spi the error code appears in the upper display and the address in the middle display. Load the program which is running on the S320 controller in the IDE and type in the error code in the child window Exec at Error Address and press the button Find Address. Again the line which caused the run time error will be displayed.

The possible run time errors are described in the libraries.

3.9 Retrieve Data

The programs, configuration file and a copy of the persistent memory which are currently loaded in the S320 controller can always be retrieved by the IDE and modified.

With Exec > Retrieve Code you retrieve the program source from the S320 controller. Of course the feature Options > Global Settings > Compiler > Include Source Code has to be activated in order to retrieve any data at a later time. A possible password request can be ignored by pressing the OK button since there's no password. With Unpack Sources you can save the program sources at a directory of your choice.

With Config > Retreive Config the configuration file can be retrieved and stored with File > Save As.

With Command > Retreive Persistent Data you can retrieve a copy of the persistent data. ( = power outage / saved data in the flashrom) WithCommand > Delete Persistent Data you can erase the persistent data. After the next program start, that part of the memory will be initialized with the data provided in the program sources. The ROM-persistent data in the S320 controller can be replaced with an image from your hard drive with Command > Send Persistent Data. With Command > Retrieve Persistent Data that data can be stored to your hard drive. This is a direct image of the ROM-persistent memory. There's no mapping to the variables defined in spell. This function therefore is mainly suited to duplicate parameters for controllers with identical programs or variable definitions.

3.10 Configuration of the Hardware

Within the menu Config you can upload the cfg-file to the S320 controller with Config > Send Config or directly from the launchpad. You can check whether the syntax of the files is correct with Debug Configuration.

The Configuration File is the link between the Spell program and the hardware of the S320 controller like interfaces and slot cards.

The Configuration File can - just like a spell program - be modified in an editor. In chapter Configuration File and in the description of the different slot cards you'll find examples how to include hardware into you program. Even if your program doesn't use any external hardware you need an empty Configuration File in order to make the program work.

To test the current digital and analog ports you can use Config > Test I/O.

3.11 Calibration of Slotcards

The IDE supports you during Calibration or Re-Calibration of slot cards via Config > Calibrate Analog Ports. Results are new parameters for Gain and Offset, which will be stored into the Configuration file and the uploaded to the S320 controller

In order to calibrate an analog input you need a device, which can generate the needed signals, and a measuring device with the desired accuracy, which serves as the reference.

In order to calibrate analog outputs you only need a reference with the desired accuracy.

3.12. Configuration Errors

The S320 Controller is able to detect some of the slot card types. At each program start, the resulting information is compared with the slot card configuration. If any configuration error occurs, the program will not be started, instead the error message 'S/P' will be displayed together the number of the slot and the port, where the failure was detected and with the expected slot card type.

3.13. System Errors

System errors are errors of the run time environment, in external functions or errors while addressing the hardware. Apart from few exceptions, system errors should not occur. When a system error does occur, the upper display shows the error number 'Sys'. The address is shown on the middle display 'Adr'. The lower display possibly gives supplementary information 'Info'.

The system errors are classified as listed below:

1: Internal program error
2: Flash ROM Error
3: Memory not sufficient for Spell program and stack
4: Hardware error
5: Unknown slot card
6: Unknown interrupt from slot card
7: Heap is corrupt
8: Configuration data is invalid
9: Unexpected out of memory condition
10: Invalid data
11: File system is corrupt
12: Unexpected trap

If a system error cannot be traced back to a wrong configuration, please inform us. In order to eliminate the error, we need the following data:

- Error number, error address and the supplementary information if displayed
- Version of the operating system
- Compiler version
- Your program sources *.SPC, *.SPI and *.CFG
- Occupancy of the S320 Controller's slots.

NOTE: After the occurrence of a system error the S320 Controller can not be controlled any more from the terminal program. The Controller has to be reset by cutting the power supply. If the error was caused by the SPELL program or by a wrong configuration file, you can avoid a new program start by simultaneously pressing the keys "up" (>) and "down" (<) until the end of the auto-test phase.

NOTE: System error 2 (flash-ROM error) does inevitably occur if the functions LoadRomPersistent or SaveRomPersistent are called simultaneously e.g. from the main program and from a signal function.

NOTE: The system error Sys4 indicates a false slot card configuration. Most slot cards do not affect booting behaviour. However the Sys4 error might occur particulary in combination with an incorrectly configured TYPE310 slot card. Remedy: start the S320 Controller while pushing the '<' and '>' front keys simultaneously during the initialisation. Then transfer a correct configuration file or install the slot cards properly.

3.14. NTSPC - The Compiler

Since version 3 the compiler is fully integrated into the IDE and is activated via the launchpad..

The following section is only of interest if you plan to use the compiler separately:

Technically the compiler is like in earlier versions a pure console application, that also works without the IDE. The compiler is activated by the command: NTSPC <flags> <filename>.

The compiler generates the executable program *.SPX for the S320 Controller from the sources *.SPC and the libraries *.SPI . Optionally you can generate a listing *.SPL or an assembler listing *.SPA .

Usage: SPC [flags] file[.spc]

The compiler options are chosen by the flags below:

  -a[x] produce an assembler listing. Modifiers:
        d:  Dump data segment in addition to code
        i:  Interlist assembly listing with source
  -c[x] compress data if possible. Modifiers:
        c:  Compress the executable code segment
        d:  Compress the executable data segment
        m:  Compress misc data
        s:  Compress the sources
  -h,-?    get this message
  -I<Path> Add <Path> to the include file search path
  -l       produce listing
  -q       produce binary output
  -s       pack sources into SPX file (necessary for retrieving)
  -S       suppress banner
  -v       verbose flag, give additional information
  -V       print version information and exit
  -wN      Set warning level N, x = max., - = no warnings

Flags are negated by adding a '-' sign, e.g. -s- means: no sources in SPX-file

The default flags are: -a- -c -I. -l- -q -s -S- -v -wx

Example: SPC -Ic:\S320\Demo00

Compiler Path Specification

When compiling a Spell program without path specifications, all included files must be present in the directory where the compiler was started. The flag -I expands the search to further directories, which are defined by the path names following this flag. When specifying more than one path name, they must be separated by semicolons. The multiple use of this flag followed by different path names effects the same result. The search for an include-file always begins in the current directory. Then the search is continued in the listed order until a file with the relevant name is found. The path name specified by an include directive (see chapter 'program structure') may be relative, e.g. the compiler call below

ntspc -IDirA\DirB;DirA main

where the program "main.spc" includes the file:

INCLUDE "DirC\STDLIB.spi"

searches for the file "STDLIB.spi" in the following directories in the listed order:

DirC
DirA\DirB\DirC
DirA\DirC

3.15. Operating System

The operating system SPELLOS.BIN is the central piece of software for the S320 controller and works like the operating system on your PC. It's also possible to upgrade the operating system.

For versions <= 3.xx the operating system file is named SPELLOS.BIN.

Since version 4 there is the following convention:
S320V400.BIN: First final release
S320V401.BIN: First updated version
S320V402.BIN: Second updated version
and so on..

Command > Send Operating System replaces the operating system by a new version. This can become necessary for an addition of external functions or for updates. Note that a newly transferred operating system only becomes active after cutting and reconnecting the power supply to S320 Controller or by the terminal command Command > Boot the Controller. You can do this automatically via Options > Global Settings > Link.

If an update is possible depends on the existing hardware end the actual running operating system. For further details please contact the manufacturer.

NOTE - only valid for versions <= 3.xx:
When transferring a new Spell operating system, the stored Spell program, sources included, the persistent memory area and the configuration will be deleted. If you need any of this data, the respective files must be retrieved BEFORE transferring the new operating system. Command > Boot the Controller resets the S320 Controller S320 and activates a possible new operating system.

NOTE: Please take care that neither the S320 Controller nor the PC is shut down (e.g. for power failure) during the transmission of a new operating system. The data stored in the flash-ROM must temporarily be deleted. If the transfer process is interrupted at that moment the S320 Controller can not start anymore. Please send the CPU board or the Controller back to the producer, as a rule it will be sent back the same day with a new operating system.

Proceed as listed below when updating the operating system:

If necessary, save the program, the configuration and the data of the S320 Controller with the current Development Software version on your hard disk using the Exec > Retrieve Code or Config > Retrieve Config commands.

Transfer the new operating system using the current version of the terminal program.

Reset the S320 Controller either by cutting the power supply or by choosing the command "Boot the controller".

Exit the current terminal program and install the new versions of the terminal program, the compiler and the libraries.

Generate the new executable using the new compiler and the new libraries.

Start the new Development Software.

transfer the new generated executable file and the configuration file to the S320 Controller.

Do no longer use older versions.

> Programming Language


S320 Controller Manual - Programming

 4. Programming Language of the S320 Controller

The programming language for the S320 Controller 'Spell' is a derivate of standard Pascal which was specially adapted in order to best match the particularities of the S320 Controller. The global language characteristics are identical to Pascal. Thus this language shares the important advantages with Pascal:

Widely used and well-known
Easy learning and program realisation
Programs are easy to understand and easy to maintain
Highly efficient object code
The following chapters describe the language and the programming in Spell. However those descriptions are not well suited for a person who does not have any programming experience in languages like Pascal, C or similar. In that case one should have recourse to the multitude of good education manuals available on the market.

4.1. Language Elements

The language Spell embraces characters, numbers, operators and keywords. Furthermore many identifiers are pre-defined. Some are taken over from standard Pascal (ISO7185), others have been added to satisfy the specific demands of the S320 Controller. This chapter gives an overview about the available language elements.

Symbols

A list of the specific symbols is shown below:

+ | - | * | / | % | ** | :=
< | <= | = | >= | > | <> |
( | ) | [ | ] | { | } |
? | " | . | , | : | ; |

Keywords

The following list shows the defined keywords:

AND | ATTRIBUTE | BEGIN | BIND
BITAND | BITNOT | BITOR | BITXOR
BREAK | CASE | CONFIG | CONST
CONTINUE | DO | DOWNTO | ELSE
END | EXTERNAL | FOR | FORWARD
FROM | FUNCTION | HALT | IF
IGNORE | INCLUDE | NOT | OF
OR | PACK | PROGRAM | RAMPERSISTENT
RECORD | REPEAT | RETURN | ROMPERSISTENT
SHL | SHR | SIGNAL | STATIC
STEP | THEN | TO | TYPE
UNTIL | VAR | WHILE | XOR

They must not be used in any other context than the defined one.

Identifiers

Identifiers (names for constants, variables, data types and functions) are formed by a sequence of (case-insensitive) letters and the digits 0 through 9. The first character must not be a digit.

The pre-defined Spell identifiers are:

Typen: | INTEGER, FLOAT, BOOLEAN, STRING, CHAR
Konstanten: | True, False, MaxInt, MinInt, Pi, e
Funktionen: | Integer, Float, Char, Min, Max, Inc, Dec, Fract, Trunc,Sin, Cos, Tan, Asin, Acos, Atan, Abs, Ln, Log, Sqrt, Sqr,Sign, Hvs, Odd, ord, SizeOf, Low, High
These identifiers can be re-defined by the programmer. However one advises against any redefinition as the given sense will be cancelled.

(The functions will be described later below the paragraphs 'Basic Data Types').

Further functions are defined by the standard library "StdLib.SPI". They will be introduced in the respective chapter.

Numbers

Numbers exist in the common representation, i.e.:

Integer type with an optional leading sign, with or without leading '0'-digits

Floating-point type distinguished by the presence of either a period, an e (or E), or both. The mantissa must include a sequence of digits (with or without a leading sign) followed by a period and the sequence of digits representing the fractional part. The exponent is optional and is distinguished by a leading e or E.

Characters

Character constants (CHAR) are put in single quotes: 'C'..

String Literals

A sequence of zero or more characters enclosed within double-quotes is a string literal, e.g. "this is a string literal". Its end is marked by a terminating null character.

Comments

Any brace-enclosed set of characters is identified as a comment. Comments can be placed anywhere in the program. All characters after the opening brace '{' will be ignored until the closing brace '}' is found. (Thus a nesting of comments is not allowed.) A comment is treated as a "white-space" character.

White-Space Characters

"White-space" characters separate Spell-symbols. They include space characters, line endings and comments.

4.2. Program Structure

The program is executed sequentially instruction for instruction. Each instruction is finished by a semicolon. Its maximum length is 256 characters.

A program starts with the head line of the form:

PROGRAM Name;

Underneath starts the declaration part of the program. It contains the definition of constants and types, the announcement of the include-files used and the declaration of variables.

The program can call functions which are defined in separate files after its announcement by the 'INCLUDE'-directive:

INCLUDE "FileName";

A file name is composed of a name followed by a dot and a suffix. The standard suffix for Spell libraries is: 'SPI'. If the suffix is omitted the Spell compiler implicitly assumes this standard suffix. Thus the above directive is equivalent to:

INCLUDE "FileName.SPI";

Some of the libraries for the S320 Controller are shipped in a machine readable format. These files have the suffix ".spp" and are included from the corresponding header file (*.spi) into the program by the command below:

BIND "modul" FROM "package";

Sometimes several modules are embedded into one package. This command is only mentioned for completeness and is of no further importance for the user. The user only includes the header file to his sources as usual. He only has to be aware that for compiling not only the header files but also the package files must be present in one of the compiler search paths.

A particular compiler directive permits the inclusion of any file, e.g. for documentation, which will then also be stored inside the S320 Controller flash memory:

PACK "Dateiname.Doc";

The so included file is transferred to the S320 Controller together with the other sources and can always be retrieved for later service purpose.

If the included files (by an INCLUDE or PACK directive) are not located in the directory where the compiler was started, a path name must be given whether directly in the compiler command line (see chapter 'Compiler Path Specification') or together with the file name. In the latter case one has to recall that a character with a preceding backslash is interpreted as an 'escape sequence'. The backslash itself is given by a double backslash: '\\', for example:

INCLUDE "C:\\S320\\STDLIB.SPI"

Alternatively one can also use the slash-character: '/' for include path names. The directive below is therefore equivalent to the above one:

INCLUDE "C:/S320/STDLIB"

(Remember that the standard suffix for Spell libraries must not be given explicitly in an INCLUDE-directive.)

The keyword CONFIG allows to open a particular configuration block wherein the program environment of the S320 Controller can be suited to one's needs.

CONFIG
    Stacksize = $1000;
    RestartOnError = False;
Use the parameter Stacksize to adapt the maximum stack size of the Spell program. The default setting is $1000 words for the program stack and another $800 for the signal handler stack. If the stack size is too low, the program will exit with the system error 3 (stack overflow).

The parameter RestartOnError concerns the reaction on Spell run time errors (e.g. division by zero). Possible values are TRUE and FALSE (default). If RestartOnError is set to TRUE the Spell program will be automatically restarted, which may be useful when running the S320 Controller without surveying. A continuous restart due to a repeating run time error can be suspended by simultaneous pressing of the up-key and the down-key on the S320 Controller's front.

The compiler version 3 introduces conditional compilation possibilities. Use compiler directives to control the compilation of distinctive code sections:

#if Const_Expr
The sources below will only be compiled if the expression Const_Expr equals TRUE.

#ifdef Identifier
The sources below will only be compiled if Identifier was declared before reaching this directive.
An alternative writing with the same effect is: #if Defined (Identifier)

#ifndef Identifier
The sources below will only be compiled if Identifier was NOT YET declared when reaching this directive.
An alternative writing with the same effect is: #if NOT Defined (Identifier)

#elseif Const_Expr
The sources below will only be compiled if no preceding conditional directive of the same level was selected and if the expression Const_Expr equals TRUE.

#else
The sources below will only be compiled if no preceding conditional directive of the same level was selected.

#endif
This directive is necessary after every code section to be conditionally compiled. It finishes a chain of conditional directives.

A compilation can be interrupted with a user defined error message by the command below:
#error ("user defined error message");

If you only want to put out a warning but let the compilation continue, then use the command:
#warning ("user defined warning");

The pragma directives represent an alternative notation for setting the CONFIG values. At the current state all the options that can be set using the CONFIG statement can also be set using the pragma directive, e.g.:
#pragma (StackSize, 16384);

A constant is defined using the following syntax::

CONST ConstIdentifier: Datatype = Value;

A so defined constant can not be modified. The constants can be used as array size for initialisation. The explicit declaration of the data type makes sure that no problems through combination with other variables occur.

Any type of constants can be defined. The assignment to structured data types is described in the relevant chapters.

Type declarations have the form:

TYPE TypeIdentifier = TypeDeclaration;

They are mainly used if several variables of the same structure data type (records or arrays) exist. So one can form individual data types which fit best the specific problem. For example:

TYPE Polynom = FLOAT[ConstDim];
TYPE Date = RECORD
              Day  : INTEGER;
              Month: INTEGER;
              Year : INTEGER;
            END;
In particular type declarations are used to exchange data of structured type between a function and the calling code. See chapter 'Functions' for details.

All variables used in a program must be declared in the declaration list at the beginning of a program. For this use assign the new identifier with the intended data type and, if necessary, declare the array size:

VAR
  VarIdentifier1:DataType1;
  VarIdentifier2:DataType2[Dim];
The variables can also be initialised implicitly. The syntax is identical to the syntax of a constant's declaration:

VAR VarIdentifier1:DataType = Value;

This is valid also for variables with structured data type which will be described in the relevant chapters.

A particular memory area can be allocated for variables by its declaration under the keywords: RAMPersistent or ROMPersistent. In contrast to 'normal' variables these variables will not get lost even after cutting the power supply.

About 32kbyte of variables can be put into the battery-powered RAM area, and another 192kbyte of data can be stored in the flash ROM block. When a program including 'persistent' data is started, it is checked if data is available from this persistent memory area. If data is available and this data fits to the declarations, these data is automatically assigned to the persistent variables. Otherwise the implicit initialisation is effected.

The declaration syntax is identical to that of an ordinary variable. However the above reflection suggests to always use the implicit initialisation for persistent variables. If the initialisation is omitted, only variables of boolean type are defined, they are all set to 'FALSE'. Variables of other types are undefined.

RAMPERSISTENT PersDataId1:INTEGER   = 0;
              PersDataId2:Datatype2 = Value2 ;

ROMPERSISTENT PersDataId3:Datatype3 = Value3;
              PersDataId4:Datatype4 = Value4;

The persistent data area is not updated until the functions:

SaveRAMPersistent();

SaveROMPersistent();

are called. These functions are included in the standard library: 'STDLIB.SPI'. See there for further description.

The order of the different declaration blocks is not fixed.

Each declaration block is clearly identified by its leading keyword (INCLUDE, PACK, CONFIG, TYPE, CONST, VAR, RAMPERSISTENT, ROMPERSISTENT). The keywords may appear as many times as wanted. For example a constant which is needed in an included file can be declared before the respective include statement whilst the further constants can be declared later at an appropriate location of the declaration list. The circumspect use of this possibility further enhances the program's transparency.

The statement list follows the declaration list, with the used functions first (if not included in other files) and finally the main program. It is embraced by the word symbols:

BEGIN

END.

Note the terminal dot after the main program's END. It distinguishes the end of the program in contrast to the END-statement of a logical block which is followed by a semicolon.

4.3. Data Types

The data types have been mostly taken over from standard Pascal. Some modifications are made with regard to the application purpose as well as to the efficiency of the S320 Controller.

One distinguishes basic data types (or scalar data types) and structured data types.

Basic Data Types

Spell supports the basic data types: Integer, Float, Char and Boolean. An implicit type conversion is not provided. All conversions must be carried out explicitly. This strict respect of types has been established as implicit conversions often are the cause of surprising and obstinate errors. The strict data type handling has been expanded also for constants, such that constant definitions also must include a type declaration.

Integer

The data type integer embraces the integral numbers between MinInt = -2147483648 and MaxInt= 2147483647 (32bit integer). If an out-of-range value occurs (in any step of an equation's evaluation) this will provoke an overflow error.

The basic arithmetical operations: addition (+), subtraction (-), multiplication (*), division (/) and modulo (%) can be performed inside the allowed range. Note that the division is strictly handled for integral numbers which corresponds to the 'div' - expression in standard Pascal. In order to obtain the floating-point result one first has to convert explicitly the numerator and the denominator.

Apart from these operations, the following standard functions yield integer results. (The parameter i has integral type (integer), b has boolean type, c is a character (char) and f has arithmetic type (float):

Abs (i)   - Absolute value of i
Hvs (i)   - Heavyside function
Integer (f) - Type conversion including rounding (an error may occur for arguments outside the permissible integer range)
Min (i1,i2) - Returns the smaller value of the two values passed
Max (i1,i2) - Returns the larger of the two values passed
Ord (b)   - Returns the ordinal value of the argument b (0 when FALSE, 1 when TRUE)
Ord (c)   - Returns the ordinal value of the argument c (according to the used character code table)
Sign (i)  - Signum function (Result: -1 , 0 or 1)
Trunc (f) - Type conversion whereby the fractional part is discarded.
Dec(i1[,i2]) - Decrement the value i1 by 1 or by i2, if given
Inc(i1[,i2]) - Increment the value i1 by 1 or by i2, if given
The comparative operations between two integers yield results of boolean type.

The functions: Abs, Min, Max, Hvs, Sign, Dec and Inc are 'overloaded' functions and can be used equally for arithmetic (floating-point) type values.

A particularity represent the following three functions, which not only accept variable values as an argument but also type declarations:

SizeOf(a) | yields the size of an argument a specified in 'words'. The argument can be a type or a variable of arbitrary type. Complex types or structured variables are also accepted, however they must be of existing type.
Low(a) | yields the lower index limit of an array a. The argument must be a variable of array type, the array type itself or a user defined type with an array as basic type.
High(a) | yields the upper index limit of an array a. The argument must be a variable of array type, the array type itself or a user defined type with an array as basic type.
The functions Low and High are necessary for the handling of open arrays as function arguments. Their use is described later when discussing open arrays.

Bit Operations

The version 3 of the operating system introduces bit operations, using integer type values. Thus an integer value becomes a bit vector of field length 32. Bit operations consider integer type values being unsigned values.

Five statements support the manipulation of individual bits:

x BITAND y:
The result of the binary operator BITAND is the bitwise AND of the operands. That is, each bit in the result is set if and only if each of the corresponding bits in the converted operands is set.

x BITOR  y:
The result of the binary operator BITOR is the bitwise inclusive OR of the operands. That is, each bit in the result is set if and only if at least one of the corresponding bits in the converted operands is set.

x BITXOR y:
The result of the binary operator BITXOR is the bitwise exclusive OR of the operands That is, each bit in the result is set if and only if exactly one of the corresponding bits in the converted operands is set.

BITNOT x:
The result of the BITNOT operation is the bitwise complement of its (promoted) operand. That is, each bit in the result is set if and only if the corresponding bit in the converted operand is not set.

x SHL    y: The result of x SHL n is x left-shifted n bit positions; vacated bits are filled with zeros.

x SHR    y: The result of x SHR n is x right-shifted n bit positions.

The include library bit.spi (that needs the package bit.spp) provides further functionality for directly set or query bit positions.

FUNCTION SetBitAll (VAR i: INTEGER, Set: BOOLEAN);
Initialises all elements of a bit vector i to the value "Set". For implicit initialisations use the constant "BitFalseInit".

FUNCTION SetBit (VAR i: INTEGER, pos: INTEGER, Set: BOOLEAN); FORWARD;
Set the element at the position "pos" of a bit vector "i" to the value "Set".

FUNCTION GetBit (i: INTEGER, pos: INTEGER): BOOLEAN; FORWARD;
Yields the value of the element at the position "pos" of a bit vector "i".

The function below yields the bit pattern as a character string what can be useful e.g. for test purposes:
FUNCTION BitPattern (i: INTEGER): STRING; FORWARD;
Yields the bit pattern of the variable i as character string of 0 (FALSE) and 1 (TRUE). The position 0 to 31 is read from the left hand side to the right one.

Float

The data type float includes the real numbers with arithmetic type:

3.4038238E38 bis 5.8774717E-39,
0.0,
-5.8774724E-39 bis -3.4028236E38.
The basic arithmetic operations +, -, * and / yield real numbers. The operation x**y returns the value of x raised to the power of y. Furthermore the following functions return a floating-point result:
Abs(f)    - Absolute value
Float(i)  - Type conversion
Hvs(f)    - Heavyside-function
Sin(f)    - Sine
Cos(f)    - Cosine
Tan(f)    - Tangent
Asin(f)   - Arcsine
Acos(f)   - Arccosine
Atan(f)   - Arctangent
Ln(f)     - Natural logarithm (base e)
Log(f)    - Logarithm (base 10)
Sign(f)   - Signum function (return values: -1.0 , 0.0 ,1.0 dep. on sign)
Sqr(f)    - Square
Sqrt(f)   - Square root
Fract(f)  - Returns the smaller value of the two values passed
Min(f1,f2) - Returns the larger of the two values passed
Max(f1,f2) - Returns the larger of the two values passed
Dec(f1[,f2]) - Decrement the value f1 by 1.0 or by f2, if given
Inc(f1[,f2]) - Increment the value f1 by 1.0 or by f2, if given
The functions: Abs, Min, Max, Hvs, Sign, Dec and Inc are 'overloaded' functions and can be used equally for arithmetic type values.

The comparative operations ( < , <= , = , >= , > , <> ) can also be used with floating-point expressions. Be aware of inherent inaccuracies (for numerical reasons) using the operators "equal to" (=) and "not equal to" (<>).

Char

A character type value is identified by its embracing single quotes, e.g.::

CONST ALower : CHAR = 'a';

This data type has particular meaning in the context with serial interfaces and there particularly when operating in 'BYTE'-mode. Functions are available to convert a CHAR-value either to an integral type value: ord(c) or also to convert a character into a string literal (cf. chapter "The Standard Library Stdlib.SPI"). The only standard function which yields a CHAR-type result is the conversion function:

Char(i) yields the CHAR-value related to the Integer-type value i following the ASCII-code table. The value i has to be in the valid range between 1 and 255.
The standard library offers further functions, which make this type an appropriate tool for the analysis and procession of string literals. The relation between characters and numerical values can be used for instance for the easy evaluation of a check sum to survey the correct transfer via the serial interfaces.

Boolean

Operands of boolean type either have the value: TRUE or the value FALSE. They can be logically combined by the operators:

AND logical 'and' operator
OR  logical 'or' operator
XOR exclusive logical 'or'
NOT negation
The logical standard function:

Result := Odd(i);

yields the return value True if i (integral type) is odd, otherwise the result is False.

Structured Data Types

Structured data types or advanced data types are structures of scalar data types which are composed to a complex data type. An array is a field which embraces a fixed number of components of one single data type, whilst the data type 'record' permits to compose a sequential group of members of various types.

Array

Arrays are declared by means of a variable declaration:

VAR Array: Datatyp[ConstDim];

or by means of a type identifier:

TYPE Arraytyp = Datatyp[ConstDim];

VAR Array: Arraytype;

where ConstDim is an integer constant. It defines the number of components. References to array elements are usually made through indexing into the array. To facilitate this, the elements of the array are numbered starting at zero. Hence the above array declared with ConstDim elements is indexed using indices between 0 and (ConstDim-1). The data type of the components is arbitrary. Apart from scalar types, structured data types are also valid as long as each element has the same type.

Integral expressions inside brackets [] are evaluated before the access to the element.

A violation of the index range is found during compilation if the elements index is constant, whilst a violation by a variable expression provokes a program failure (Range Error).

A constant array can be defined as shown below:

CONST Array: Datatype[Dim]= ( Val_0, Val_1, ..., Val_Dim-1);

The order of the values in the initialisation braces corresponds to the increasing indices from 0 to (Dim-1). The same syntax is used for the implicit initialisation of variable arrays.

This assignment syntax is only valid in the declaration part of a program. In the statement part, assignment must be effected either by addressing individual components:

Array[Index] := Value;

or by copying a complete array to an array of the same type:

Array1 := Array2;

It is possible to declare arrays with two (or more) dimensions is done by simply adding a second dimension size. For example:

VAR Array2: Datatype[ConstDim1][ConstDim2];

If an array of more than one dimension is initialised, then each subarray may be initialised using a brace-enclosed list of values. This form will work for an arbitrary number of dimensions. Consider the following two-dimensional case:

VAR Array: Datatype[Dim1][Dim2]=
    ((Val_0_0, Val_0_1, ..., Val_0_Dim2-1),
(Val_1_0, Wert_1_1, ..., Val_1_Dim2-1),
........
(Val_Dim1-1_0,     ..., Val_Dim1-1_Dim2-1) );
The object Array is an array of Dim1 arrays of Dim2 values with the specified data type. There are Dim1 values in the initialisation list, corresponding to the first dimension (Dim1 rows). Each initialisation value is itself a list of values corresponding to the second dimension (Dim2 columns). In other words, the first list of values (Val_0_0, Val_0_1, ..., Val_0_Dim2-1) is assigned to the first row of Array, the second list of values to the second row of Array and so on.

Record

A RECORD is a user-defined type composed of a sequential group of members of various types.

The type definition has the form:

TYPE TypeIdentifier = RECORD
                         Memberlist
                      END;
The syntax is illustrated using an example of the include file StdLib:
TYPE
  HardwareErrorDesc = RECORD
    Error : INTEGER;
    Handle : PortHandle;
    Slot : INTEGER;
    Port : INTEGER;
    Module : INTEGER;
  END;
It shows how members of different data types are collected in a record. Previously defined structured data types are also permitted as a record member. Thus a previously declared record structure may itself be member of another record structure.

A record variable can then be declared in the usual way:

VAR HWE : HardwareErrorDesc;

The assignment of an entire record to another record is only possible if both have the same data type. However usually one directly refers to individual record members. References to a record member are made using the dot operator (.). The first operand of the . operator is the object containing the record. The second operand is the name of the member. Thus the identifier HWE.Error refers to the member Error of the record HWE of type HardwareErrorDesc.

An example which uses the above defined record, clarifies the handling of records:

VAR A,B:HardwareErrorDesc;        {Decl.: A,B of type HardwareErrorDesc}

BEGIN
  A.Error := ErrNone;             {Initialisation member-wise          }
  GetHardwareError(A);            {Assignment by standard function     }
  B := A;                         {Make copy of entire record          }
  ShowInteger(TopLeft,A.Error,6); {Individual access                   }
  .....
END.

The implicit initialisation of records is similar to those of arrays. Take care to list the initialisation values in the same order of the type declaration list.

Equally one can define constant records. An assignment of such a record constant allows a simple initialisation of record variables.

String

String literals are defined through the keyword STRING. The string variable's length is fixed internally to a length of 127 characters plus the terminating null character, unlike in the case of string constants, where the allocated memory fits the string's effective length. However the maximum number of characters of a string constant is also 127.

A string is embraced in double-quotes. A string constant is assigned as shown below in the example:

CONST StringIdentifier: STRING = "A String";

Two strings may be concatenated simply by using the '+' operator:

VAR strA,strB: STRING;  {Declaration: two strings  }
BEGIN
  strA :="S320 ";       {first string              }
  strB :="Controller";  {second string             }
  strA := strA + strB;  {Result: "S320 Controller" }
END.
Two strings can be compared using the operators: '=' (is equal) and '<>' (is different).

Specific functions for the manipulation of strings as well as conversion functions are included in the standard library file STDLIB.SPI. Refer to this chapter for further information.

The characters which are not directly representable since they are assigned other meanings can be entered by an 'escape sequence'. Whilst the second double-quote is interpreted as the end of the string, one can nevertheless use the double-quote inside the string by placing a backslash in front. Also a number of escape sequences may be used to represent non-graphic characters:

"\a" Causes an audible alert (Bell)
"\b" Backspace
"\f" Move to the start of the next page (form feed)
"\n" Move to the start of the next line (new line)eilenendezeichen (Newline)
"\r" Move to the start of the current line (Carriage Return)
"\t" Move to the next horizontal tab
"\v" Move to the next vertical tab
"\"" Double-quote
"\\" The backslash sign itself
Any character sign can be embedded into a string except the terminating character '\0', e.g.:

VAR S: STRING = "Hello\$0D"; { = "Hello\n" }

4.4. Expressions and Statements

A statement describes what actions are to be performed. There are statements which effect an action (e.g. an assignment) and statements which control the program execution (e.g. loops). An expression is a sequence of operators and operands. Expressions and statements together form the program.

Assignment

The ':=' symbol denotes an assignment. The value of the expression on the right side which may be a constant, a variable a function or an arithmetic expression replaces the value designated by the left operand. The syntax is::

Variable := Expression;

As no implicit type conversions are supported, the result of the expression and the variable must be of the same type. This rule has to be respected equally when assigning numerical literals. A number with either a period, an e or E (e.g. 1E2), or both is interpreted being a floating-point number. If no exponent is specified the whole number part and the fractional part must be present. A number which only consists of the whole number part is assumed to be an integer type value.

Arithmetic expressions combine constant and/or variable operands and function calls by means of operators. The evaluation of the expression is effected from the left to the right. The order of execution can be influenced by placing parentheses in the usual way. The implicit hierarchy of operations is shown in the table below. Operations at a higher level in the table will occur before those below.

- +            (unary arithmetic operator: leading sign)
NOT / BITNOT    (Bool / Bit-Negation)
**             (exponential operator)
* / %           (multiplicative operators)
BITOR / BITXOR  (Bitwise Or / Exclusive Or)
SHL / SHR       (Shiftoperations)
= <> <= >= < > (boolean operators)
AND            (Bool And)
OR / XOR        (Bool Or / Exclusive Or)
It is however recommended to define the evaluation priority explicitly using braces.

In the case of boolean expressions all parts must be well-defined, since the evaluation is not stopped after the being fixed of the truth value. (Thus it is not possible to carry out a validity check of a field index together with a logical expression which uses this index in one combined logical expression. This example will unconditionally provoke a range error.)

When combining two comparisons in a logic function, these must always be put in braces, since the logical expressions AND/OR have higher priority than the comparative operators. For example it is to be assured that x lies in between 0 and 10. The correct expression would be:

(x>0) AND (x<10)

whilst the expression

x>0 AND x<10

provokes a compiler error: incompatible types as it is first tried to evaluate the expression: 0 AND x

Compound Statement

The compound statement is a set of statements grouped together in between the two key words: BEGIN and END; . It is an essential programming tool. The syntax of many structure statements (conditions, loops) only accept one statement for each selection of a branch. The compound statement however is handled the same way as a simple statement.

The syntax is:

BEGIN  Statement 1;
  Statement 2;
  .....
  Statement N;
END;
The terminating semicolon of the last statement inside the block is compelling contrary to standard Pascal where it is interpreted as a "null statement".

Iteration Statements

Iteration statements control looping. Three types of iteration statements are available. The "FOR" -statement realises a certain number of repetitions of the loop body. The two alternatives (while-, repeat-statement) iterate over an indefinite number of repetitions, whereby the occurrence of a specified event serves as abort condition.
The evaluation of the controlling expression takes place before each execution of the loop body in the case of the while-statement and after each execution of the loop body in the case of the repeat-statement.

In order to simplify the reaction on further events inside a loop body the statements "BREAK" and "CONTINUE" have been integrated into Spell as an additional feature beyond standard Pascal.

FOR-Statement

The FOR-statement appears in the two forms:

FOR Counter:=StartValue TO EndValue DO Statement
FOR Counter:=StartValue DOWNTO EndValue DO Statement
Counter, start value and end value must be of integer type. The start value and the end value are priorily computed before executing the loop. Their modification inside the loop does not affect the number of iterations. The counter variable must not be modified inside the loop body.

As an extension to standard Pascal one also may define the step-width by the following formulation:

FOR Counter:=StartValue TO EndValue STEP Expression DO Statement

The expression must yield a value of type integer.

The implicit step width is:

+1  using "TO" (case a) and
-1 using "DOWNTO" (case b).
If the start value and the end value are equal, the loop will be executed exactly once. The loop body will be skipped if the evaluation of the limits yields:

EndValue < StartValue for case a and
EndValue > StartValue for case b.

The counter is defined only inside the loop body. Before reusing it during the further program execution it has to be reinitialised.

WHILE-Statement

The controlling expression of a while statement:

WHILE Expression DO Statement;

is of boolean type. Its evaluation takes place before each execution of the loop body. If the expression evaluates to FALSE the execution will be continued at the first statement behind the loop body.

If it evaluates to FALSE the first time, the loop body is not executed at all.

REPEAT-Statement

In contrast to the WHILE-loop, the REPEAT-loop is always executed at least once, as the evaluation of the controlling expression (type boolean) only takes place after the execution of the loop body. The loop is continued if the expression evaluates in a boolean "FALSE". If the result is "TRUE" the program execution is continued with the statement following the loop.

The syntax is now:

REPEAT
  Statement 1;
  Statement 2;
  ......
UNTIL Expression;
The keywords REPEAT and UNTIL may embrace any number of statements such that one does not need explicit grouping using a compound statement.

BREAK-Statement

A break statement may only appear in an iteration (loop) body. It makes possible to interrupt the (most inner) FOR, WHILE or REPEAT-loop at any time independently from the loop controlling expression and it will cause execution to continue at the statement following the loop body.

FOR i := 1 TO 10 DO BEGIN
IF i = 5 THEN BREAK;
END;
This (purely didactic) example illustrates the statement's function: the loop is not iterated for all ten values of i but will be quit after the iteration variable takes the value 5.

CONTINUE-Statement

A continue statement may only appear within a loop body, and causes a jump to the innermost loop's loop-continuation statement (the end of the loop body). Thus, the complete iteration is not aborted, but only the actual iteration. In a while statement, the jump is effectively back to the while. In a repeat statement, the jump is effectively down to the UNTIL.

In a for statement, the jump is effectively to the end of the iteration block that is the subject of the for loop. The iteration variable will be incremented or decremented before control is returned to the top of the loop.

i := 0;
REPEAT
inc(i);
IF odd(i) THEN CONTINUE;
ShowInteger(TopRight,i,4);
UNTIL i = 10;
In the previous example only even values of i will be shown on the upper right display.

Selection Statements

A selection statement evaluates an expression, called the controlling expression, then based on the result selects from a set of statements.If a statement has to be executed whether or not, depending on a condition, one uses the if-statement (conditional statement). If one of several statements has to be selected depending on a certain event ("real alternative"), one either uses the if-statement appending an else-alternative or the case-statement.

IF-Statement

As mentioned above one can use the if-statement either to realise a conditional statement:

IF Condition THEN Statement;

or to control the selection from different statements (real alternative):

IF Condition THEN
    Statement1
  ELSE
    Statement2;
In both cases, the type of the controlling expression is a boolean type. If the controlling expression evaluates to "TRUE" then the first statement is executed and a possible else statement is ignored. In the second form, the statement following else is executed if the controlling expression evaluates to "FALSE".

Note: In the classic case of the "dangling" ELSE, the ELSE is bound to the nearest IF that does not yet have an ELSE. For example:

IF a=1 THEN
  IF b=1 THEN a:=2
  ELSE a:=3;
will assign a value to the variable a only if a is equal to 1. In this example code all cases in which a is not equal to 1 stay unconsidered as the statement is then completely ignored. Otherwise the subject of the control structure must be explicitly defined using a compound statement. To bound the lower ELSE statement to the first IF expression it would have to be changed to:
IF a=1 THEN BEGIN
  IF b=1 THEN a:=2;
END ELSE a:=3;
This example illustrates why it is a good idea to always use the BEGIN-END "braces" to explicitly state the subject of the control structures, leaving no doubt about the meaning.

CASE-Statement

Complicated IF-ELSE constructions with more than one alternative statement can be efficiently replaced by the CASE statement. The syntax is:

CASE Variable  OF
    Label1: Statement1;
    Label2: Statement2;
    .....
    LabelN: StatementN;
    ELSE ...;
END;
The variable must be scalar type (Integer, Boolean or Char), which is compared with the labels (constants of the corresponding type). The statement will be executed, whose label equals the value of the variable. If no matching label is found, control is given to the statement following the ELSE label (if present). If no ELSE default label is present, the program will be interrupted with the error message: "Illegal Case".

An example illustrates the use of the CASE statement and shows how the clearness of a program can be improved by the use of named constants:

PROGRAM CaseExample;

CONST
  Wait           : INTEGER = 0;        { State: Wait for signal }
  Extend         : INTEGER = 1;        { State: Extend cylinder }
  Ram            : INTEGER = 2;        { State: Ram             }
  Retract        : INTEGER = 3;        { State: Retract cylinder}

VAR
  State          : INTEGER;            { System state of system }

BEGIN
  State := Wait;           { Initialise state  }

  CASE State OF
    Wait : ....
    Extend : ....
    Ram : ....
    Retract: ....
    ELSE ErrTrigger(1000);     { Error handling  }
  END; {Case}
  ....
END.

If an identical statement shall be executed for more than one label, one can either list several labels, separated by commas, or define a scope giving two labels separated by a double dot, which selects the affiliated statement for any label between these two given (included) labels, e.g.:

CASE i OF
  0..3:      Statement1;  { For all values i between 0 and 3  }
  4,6,8:     Statement2;  { For I=4, I=6 or I=8                 }
  5,7,9..12: Statement3;  { combination is possible    }
END;
The double occurrence of a label or overlapping label scopes are errors which are detected during compilation.

If possible, several labels separated by commas will be put together to a scope (i.e. "1,2" is translated to "1..2") which allows the generation of a shorter code which will be more effective during execution.

4.5. Functions

By means of functions, program blocks can be delimited for logical organisation of a program. Alike the main program body, the function consists of a declaration block and an execution block. The declarations of a function have local scope and may not be referenced elsewhere. Its scope terminates at the END; which terminates the function block. Allocated memory for local variables is set free when exiting the function. This is why local variables also are called "automatic variables". Automatic variables can not be implicitly initialised.

Standard-Pascal offers a second possibility for the separation of program function blocks by the 'Procedure'-statement. However there is no possibility in this statement which could not equally be realised using the 'Function'-statement. Therefore one renounced this option.

In contrast to local identifiers, the identifiers declared at the beginning of the program are also called global identifiers. They may be referenced anywhere below its declaration. This also means that identifiers can be used (and modified) inside a function body without explicitly passing a parameter to this function. If global variables are changed inside a function, the modification will persist even after leaving the function. This may lead to unintentional effects which are often hard to track down. Anyhow the transparency of a program will be badly reduced. Therefore it is generally preferable to explicitly pass all parameters to a function which are used by both, the function and the calling routine.

An argument of a function can be modified at will without affecting the parameters of the calling routine. An intentional modification of the source parameters can be realised by declaring the arguments as being variable.

Furthermore, a function can be used for different arguments (of equal type) if passing the variables explicitly. The information exchange is fixed by the parameter list of the function header.

IF a function contains a declaration for the same identifier which already exists with global scope, the global identifier is hidden within the function. After leaving the function, the identifier with global scope becomes visible again.

A combination of local and global characteristics offers the "static" variable.

It is declared by the leading keyword STATIC. This variable has local scope which means that it only is visible inside the function body, however it is not an automatic variable which looses its value after leaving the function, i.e. its value when entering the function is equal to its value when last leaving this function. Therefore a static variable only is sensible together with an implicit initialisation: at the first call of this function the initial value is assigned to the variable. It is thereby suitable e.g. as a counter for the number of calls of a respective function:

FUNCTION Whatsoever();
STATIC NCalls : INTEGER = 0;
BEGIN
  inc(NCalls);
  ShowString(TopRight,"Call");
  ShowInteger(TopLeft,NCalls,6);
  ..........
END;
As mentioned before the structure of a function is similar to that of the main program whereby the program header is replaced by the function header and a function result is possibly returned to the calling statement.

Some of the functions included in delivery (e.g. the functions of the standard library STDLIB.SPI) are implemented externally. They are put at disposal by the run time environment. The header of an external function is implemented in SPELL followed by the keyword "EXTERNAL" and a code of integer type. This code as well as the function arguments must not be changed! Otherwise the keyword EXTERNAL has no further interest for the SPELL user.

Function Implementation

The syntax of the function header is:

FUNCTION FIdentifier1(Par1Id: Par1Type, .....) : ResultType;

If a function is exclusively used as a subroutine where no result is yielded the declaration of the result value is omitted:

FUNCTION FIdentifier2(Par1Id: Par1Type, .....);

The argument list is a (possibly empty) comma-separated list of identifiers (Object names, here Par1Id) followed by its type definitions (Par1Type).

If a result type is declared in the function, any possible exit of the function must return a result value . This is done using the formulation:

Return ResultVariable;

If no result type is specified, the RETURN statement can be used (directly followed by the semicolon) to exit the function at any appropriate location other than the end of the function. The occurrence of a certain event could provoke a premature exit of the function using the statement:

IF Event THEN RETURN;

The above example function yielding a result is called by the following statement:

Result := FIdentifier1(ActualPar1,......);

and the second function without a return value declaration is called by

FIdentifier2 (ActualPar1,...);

If a function call is referenced to a function which indeed yields a result, a compiler error message will occur. Nevertheless it may be intended to execute a function where the result however has no significance for the calling routine. Instead of assigning the result to a meaningless variable, the function result can be ignored using the leading keyword: "IGNORE":

IGNORE FIdentifier1 (Actualpar1,.....);

Remember that only the value of the parameter is passed to the function, i.e. local variables will be generated which adopt the value of the function call parameter. ("Call by Value"). So an unintentional modification will be avoided. The variable Par1Id of the above example is hence a copy of the actual parameter Actualpar1.

However it is sometimes intended to change a variable in a function. For this aim one also can pass the actual parameters to the function ("Call by Reference"). This is done by the leading symbol VAR:

FUNCTION FIdentifier(VAR Par1Id: Par1Type, .....):ResultType;

The function call stays identical.

The same way one can place a leading symbol CONST to the argument. CONST- parameter cannot be changed inside the function body and they have automatically the attribute INPUT (see . Chap. Attribute), i.e. no compiler warning will be given that the argument was not used.

Structured data types are always passed in form of a reference, however the compiler does not accept modifications of a variable of structured data type declared being constant. A local copy of a constant argument will not be generated, what pays off particularly for functions which do not use an argument themselves but only pass it through to another function.

A function is visible to the program only after its implementation, i.e. a function call must always be placed sequentially underneath the function implementation. The so caused restrictions (e.g. two functions cannot mutually call themselves) can be overcome by means of function prototypes. This is a function header which has to be formulated absolutely identical (!) to the later "real" implementation, followed by the keyword "FORWARD".

The statement

FUNCTION FIdentifier (Par1Id: Par1Type,....): ResultType; FORWARD;

allows to call a function even though the actual code is implemented further down in the source code. Note that the prototype must be exactly (!) identical to the function header.

Recursive Function

A function may also call itself from its own function body. Such a function, calling itself is called a recursive function. By its means a recursive algorithm can be directly implemented. A simple example is the mathematical definition of the faculty which has been earlier computed using an iteration. Following its proper recursive definition a possible realisation would be:

Program Faculty;                      { Recursive realisation    }

INCLUDE "STDLIB";

FUNCTION Fac (N:INTEGER):INTEGER;     { recursive function       }
VAR Res:INTEGER;                      { local variable           }
BEGIN
   IF N=0 THEN Res:=1                 { Definition: 0! = 1       }
   ELSE Res := N*Fac(n-1);            { Def.:n!=n(n-1)! for n>0  }
   RETURN Res;                        { return result            }
END;

VAR
  Result,Input: INTEGER;

BEGIN
  Input:=5;                           { Initialisation           }
  Result:=Fac(Input);                 { Function call            }
  ShowInteger(BotLeft,Result,6);      { show result              }
END.

The shown possibility to compute the faculty is an extract from the demonstration programs.

Arrays as Function Parameters

There are two kind to pass arrays to a function, with:

1. defined size, where the type and the dimension(s) must be previously defined in a TYPE statement. The argument is then defined being of the introduced type.

2. open size, where only the element type is declared, the brackets which usually define the array size remains empty.

The specification of array dimensions inside a function's parameter list is not permitted.

Arrays with Defined Size as a Function's Argument

The example below illustrates how to initialise an array with defined size by a function:

CONST Dim : INTEGER = 10;
TYPE Array : FLOAT[Dim];

FUNCTION InitArray(VAR A: Array);
VAR i: INTEGER;
BEGIN
  FOR i:= 0 TO Dim-1 DO A[i] := 0.0;
END;

Arrays with Open Size as a Function's Argument

The same result can be obtained by a function which accepts arrays of any size. Its formulation is then:

FUNCTION InitArray(VAR A: FLOAT[]);
VAR i: INTEGER;
BEGIN
  FOR i:= Low(A) TO High(A) DO A[i] := 0.0;
END;
The usual rules for type compatibility are also valid for open arrays:
The element type of the parameter of the function call must be identical with the argument's element type. The range of an open array is determined at the executing time by the functions: Low (constant 0 in the present version) and High.

4.6. Attributes

Sometimes even intentional program structures may cause disturbing compiler warnings. Included libraries for instance mostly offer more functions as eventually used by the program. Normally each unused function would provoke a compiler warning. By means of attributes one gives further information to the compiler to suppress superfluous warnings or even to receive further warnings respecting the specified intention.

Attributes are set by the following syntax:

ATTRIBUTE Identifier: Attr1[, Attr2];

The available attributes are:

NOREF: | This symbol tells the compiler there must not necessarily exist a reference to the preceding identifier. Thus the compiler warning that the identifier is not used, will be suppressed.
NORETURN: | This attribute is useful for a function after whose leaving the program execution is not continued, but the program is ended (generally for an exception or error handling).
In order that the compiler is able to distinguish a "VAR" parameter of a function being an input parameter which must be initialised in the calling routine from an output parameter which allows an initialisation inside the function, one can specify its use with one of the attributes: INPUT, OUTPUT or INOUT.

The attribute of a function parameter can be defined in the usual format underneath the function header or outside the function whereby apart from the parameter identifier also the function identifier has to be specified. The syntax is then:

ATTRIBUTE FunctionID.ParamID: Attribut;

The meaning of these parameter attributes are:

INPUT | A function's VAR-parameter is an input value and therefore must be initialised by the calling routine.
OUTPUT | A function's VAR-Parameter is used as return value and therefore must be initialised, but need not be used inside this function.
INOUT | A function's VAR-Parameter has common characteristic of both, input and output parameters (default).
If no parameter attributes are explicitly defined, a VAR-Parameter need not be initialised, however it is marked being initialised and being used after the functions call.

> Libraries


S320 Controller Manual - Libraries

 5. Libraries

5.1. The Standard Library STDLIB.SPI

The file STDLIB.SPI contains all the essential functions to run the S320 Controller. Therefore it always should be included in any Spell program. Apart from standard data type declarations also known from Pascal, further data types have been introduced which support important and frequently used features of the S320 Controller in a suitable way.

The standard library's inclusion enlarges the list of the predefined identifiers by the following language elements:

Types: | DateTime, Time, Timer, DCF77Info, PortHandle, HardwareErrorDesc, PWMSettings, FileHandle, DirHandle, FileSysInfo, DirEntry, Socket, IpAddress, IpPort, ConnSpec, DnsTimeout
Constants:
Keys: | KeyF1, KeyF2, KeyF3, KeyUp, KeyDown,KeyAll
Days: | Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
Display positions: | TopLeft, MidLeft, BotLeft, TopRight, MidRight, BotRight, DisplayCount
Serial interfaces: | Ser0, RS232_A, Ser1, RS485_A, Ser2, RS485_B
Signal IDs: | SigTimer, SigKbd, SigSer0, SigSer1, SigSer2, SigDCF77, SigTermMsg, SigTermStr, SigPWM, SigNet, SigCounter, SigAbort, SigHWFailure
Signal-'Masks': | SigMaskTimer, SigMaskKbd, SigMaskSer0, SigMaskSer1, SigMaskSer2 , SigMaskDCF77, SigMaskTermMsg, SigMaskTermStr, SigMaskPWM, SigMaskNet, SigMaskCounter, SigMaskAbort, SigMaskHWFailure, SigMaskSerial, SigMaskAsync, SigMaskSync
7-segment displays: | D7_DP, D7_A, D7_B, D7_C, D7_D, D7_E, D7_F, D7_G
File modes: | FM_READ, FM_WRITE, FM_READWRITE, FM_CREATE, FM_TRUNC
Directory flags: | DF_RAM
Error codes: | see chapter 'Error Codes'
Timer: | TimRundownInit
Port handling: | InvPortHandle
Network: | InvPortHandle, IPADDR_ANY, INFINITE, InvalidSocket
specific function arguments:
StrPad(...): | PadLeft, PadRight, PadLeftRight
Functions: | The description and the headers of the numerous functions are given below in the following, classified chapters.

Most of the following standard functions are marked with the earlier mentioned keyword EXTERNAL. These functions are components of the run time environment itself and such will not be executed in a "virtual machine" but run with full speed of the signal processor. External functions are used for hardware calls and for large-scale computations.

The numbers assigned to external functions as well as the function header must not be changed!

5.2 Keyboard

The library "STDLIB.SPI" defines the following constants for the keys, which can be used as 'masks' (i.e. the sum of any combination of this constants is unequivocal): KeyF1, KeyF2, KeyF3, KeyUp, KeyDown and KeyAll.

FUNCTION KeyPressed (Mask: INTEGER): BOOLEAN;

Yields TRUE , if each (!) of the keys given as mask is pressed. The mask is the sum of the key constants to be checked. The following example verifies if the Up and the "Down" key are simultaneously pressed:

IF KeyPressed (KeyUp+KeyDown) THEN .....

FUNCTION KeyReleased (Mask: INTEGER): BOOLEAN;

yields TRUE, if none of the keys (given in mask form) is pressed. The formulation to verify that no key is pressed at the moment is:

IF KeyReleased (KeyF1+KeyF2+KeyF3+KeyUp+KeyDown) THEN .....

or:

IF KeyReleased (KeyAll) THEN .....

5.3 Display Output

The display output is done in two steps: First a function Write puts a string in one of the 32 "virtual" displays. Each has a maximum length of 31 characters. The virtual displays are addressed by numbers between 0 and 31.

The second step is two copy the content of the virtual display to the physical display by the function: Display.

If the virtual displays are not particularly used one may also use the functions:
ShowInteger, ShowFloat and ShowString to simplify matters.

FUNCTION Write (Virtual: INTEGER, S: STRING);

Puts the string 'S' to the virtual (!) display with the number 'Virtual'. If s is too long, it is cut off without provoking an error message.

FUNCTION Display (Virtual: INTEGER, Display: INTEGER);

Copies the first 'n' characters of a virtual Displays to the real display. The seven segment displays only support numbers and few more characters. A character which cannot be represented by the display will be shown as: "_.".

A "wrap string" results from a number which has more leading digits as announced to a conversion function "xxxToString". The return string from this function will then be filled with exclamation marks and is shown on the numerical displays as: "9.9.9.9.9.9." .

The physical displays of the S320 Controller front are have a number each between 0 and 5, starting from top left going to bottom right. The displays with even numbers are the numerical displays on the left side, the alphanumerical displays of the right side have odd numbers. For more transparency use the constants: TopLeft, TopRight, MidLeft, MidRight, BotLeft and BotRight

The three mentioned functions for outputs of integer, float or string type variables help to save time and thoughts for display programming. They carry out a type conversion (if necessary) and write the string first to a virtual then to the real display:

FUNCTION ShowInteger(Loc: INTEGER, i: INTEGER, nfig: INTEGER);

FUNCTION ShowFloat (Loc:INTEGER,f:FLOAT,nfig:INTEGER,ndig:INTEGER);

FUNCTION ShowString (Loc: INTEGER, s: STRING);

Loc is the number of the physical display (one of the above constants, e.g. TopLeft) where the variable appears.

The information to be shown is i (integer), f (float) or s (string). The parameter 'nfig' fixes the number of (leading) digits. The parameter 'ndig' fixes the number of digits after the decimal point.

FUNCTION DisplayInit(Reserved: INTEGER);

This function allows reinitialisation of displays, which otherwise is only done at the program start. The actual shown data is not influenced. The parameter is reserved for later program versions and is not significant in the previous version. For later compatibility set this parameter to zero.

FUNCTION DisplayClear(Loc: INTEGER);

Clears the specified LED-display

FUNCTION DisplayClearAll();

Clears all LED-displays

5.4 User communication via the PC

The user messages can be used for sending user character data from the PC terminal to the S320 program via the link interface and for sending character data from a running S320 program on the terminal screen of a PC. The S320 PC program has an ON/OFF button which serves this mechanism. To activate the function of this button just include the standard libraries DlgUser.spi an DlgEnabl.spi into your source code. Otherwise you can determine that user messages will always been sent, wether the PC program is present or not. This latter case is active after the following function call:

FUNCTION TermEnableMsg (OnOff: BOOLEAN);

This function sets a global switch which whether allows the data transfer via the link interface or gives rise to ignore all following TermSendMsg functions. The default setting is: FALSE.

The following function sends character data from the Spell code to the S320 PC program (if the user message interface is active):

FUNCTION TermSendMsg (S: STRING);

If the data transfer is established by the function TermEnableMsg, the function TermSendMsg sends string messages to the PC which will then be displayed in a window of the terminal program (and possibly be recorded, depending on the terminal program settings). Otherwise this function will be ignored.

The user message screen of the S320 PC program offers an text input field which can be used to send character data to the S320 Controller. The sent data can always be received by the controller wether the sending of data is activated or not.

The signal SigTermMsg occurs at the receipt of such a message. The function below can then be placed in the corresponding signal function to read out the transfered character string:

FUNCTION TermReceiveMsg ();

If no message was sent previously before calling this function it will yield an empty string.

5.5 Persistent Data

Persistent data is stored in a particular memory, which is independent of the net power supply.

The persistent data is declared using the keywords: RAMPERSISTENT or ROMPERSISTENT instead of VAR. They are read automatically from the persistent memory when starting a program's execution. If no persistent data is found or if the form of the stored data does not fit the form of the present program's persistent data, the persistent data will be initialised following the given initialisation instructions.

The RAM-persistent memory is fed by a battery. Its size is 32 kbyte, which is enough to store about 8000 variables of scalar type or the equivalent amount of data with structured data type. The RAM-persistent memory is suitable e.g. for storing the values of counters such as charging hours or similar.

ROM-persistent data will be stored in the file system in a file named /dat/default.rom. This means that file size limitations take effect. ROM-persistent data is perfectly suited e.g. for a data recorder, which does its recording in an installation and can be removed later in order to retrieve and analyse the data in an appropriate place, in the office for instance.

The writing into the Flash-ROM might last some seconds. The hardware restricts the number of storing cycles to approximately 100.000. The S320 Controller does not check the frequency of writing operations.

FUNCTION SaveRAMPersistent ();

Writes the data declared being RAMpersistent to the battery backed RAM-memory.

FUNCTION SaveROMPersistent ();

Writes the data declared being ROMpersistent to the Flash-ROM.

Note: The function SaveROMPersistent will call FileFlushCache internally. Any file data that is in the cache at the moment of the call is written to Flash-ROM.

FUNCTION LoadRAMPersistent ();

FUNCTION LoadROMPersistent ();

These functions may be used to regain old correct data e.g. after input of incorrect program parameters by the user.

The ROM-persistent data can be reset using the function:

FUNCTION DeleteRomPersistent ();

The current persistent data memory is then deleted. However the present data in the working memory is not concerned. If you also want to reset the present data you might do this by a subsequent call of the function LoadRomPersistent.

This deletes the currently stored persistent data. The operation memory content is not influenced by this function call, this however is possible by adding a subsequent call of the function LoadRomPersistent.

The correct handling of persistent data is shown in the demonstration examples.

RAM-persistent data memory is controlled on its consistency using check sums. If the data stored in the battery-fed RAM memory becomes invalid because of an empty accumulator, the stored data is deleted.

5.6 Timer

FUNCTION TimSet (VAR T: Timer, Time: FLOAT);

Starts a timer, which terminates after the time at the timer start plus a given number of seconds specified by the parameter Time. The S320 Controller's timer resolution is 1 millisecond. A timer once run down will not be reactivated. However since a timer's termination is only detected by calling one of the functions TimRundown, TimUsed or TimLeft an overflow may occur, if a timer is not interrogated over a very long period.

A timer can be initialised by the assignment of the constant TimRundownInit (also implicitly). The assignment of this initialisation corresponds to a call of the function TimSet with the argument 0.0:

T := TimRunDownInit;

has the same effect as:

TimSet(T, 0.0);

FUNCTION TimRundown (VAR T: Timer): BOOLEAN;

Yields TRUE if the timer has run down.

FUNCTION TimUsed (VAR T: Timer): FLOAT;

Yields the seconds passed since the timer's start. If the timer has run down, this function yields the time span the timer was last set to (rounded to the actual resolution).

FUNCTION TimLeft (VAR T: Timer): FLOAT;

Yields the remaining seconds until the timer's termination.

FUNCTION TimWait (VAR T: Timer);

Waits until the timer's termination. PARTICULARITY: The function 'TimWait' waits passively, i.e. the signal processor is set into an 'Idle mode' and is only reactivated after the timer has run down. The parallel processing of the signal functions defined in Spell as well as the serial communication remain however ensured. Since the processor in idle state does not execute any system activities, the S320 Controller's power consumption is reduced substantially, which decreases the device's warming on the one hand and saves energy on the other hand, which is particularly advantageous when running the Controller with accumulators for mobile operation. Generally the use of the function 'TimWait' is always meaningful as long as the specific application does permit waiting periods.

FUNCTION Sleep (Time: FLOAT);

The function suspends the program execution for the given time period (seconds). This function is a short form of the combination of 'TimSet' followed by 'TimWait'. Therefore the above described particularity of passive waiting also takes effect.

Note: The time period passed to the function TimSet is rounded to the actually available hardware timer resolution. In particular the value provided by the function TimUsed after the time has run down can differ slightly from the originally specified value given to the TimSet function. Therefore use the function TimRundown or the wait functions TimWait or Sleep respectively to assure correct detection of a run down timer.

5.7 Time and Date

FUNCTION GetTime (): Time;

Yields a number (seconds after January 1st 1970, 00:00) which in combination with one of the functions below serves to specify the current time and date respectively.

Note: the above return value is result of large-scale operations based on internal system time and date. Therefore variables of the type 'Time' are not suited to control time dependent processes. For that aim it is preferable to use the timers described above.

FUNCTION SetTime (T: Time);

Sets the internal system time to the value defined by T, where T is the number of seconds after January 1st of 1970, 00:00.

FUNCTION SplitTime (T: Time, VAR S: DateTime);

where DateTime is a record with the following components:

TYPE
DateTime = RECORD
Second     : INTEGER;     { 0..59
}
Minute     : INTEGER;     { 0..59
}
Hour       : INTEGER;
{ 0..23 }
Day        : INTEGER;
{ 1..31 }
Month      : INTEGER;
{ 1..12 }
Year       : INTEGER;
{ 1970..2038 }
WeekDay    : INTEGER;     { 0..6 }
YearDay    : INTEGER;     { 1..366 }
END;

These components are accessible in the usual manner (see. chapter 'Record').

FUNCTION MakeTime (S: DateTime): Time;
Transforms the specified record of type DateTime into a variable of type Time. Only the components: second, minute, hour, day, month and year are significant.
FUNCTION GetDayOfWeek (T: Time): INTEGER;
Returns the week day (corresponding to the constants Sunday till Saturday).
FUNCTION GetDayOfMonth (T: Time): INTEGER;
Returns the day of the month (1..31).
FUNCTION GetMonth (T: Time): INTEGER;
Returns the month of the year (1..12).
FUNCTION GetYear (T: Time): INTEGER;
Returns the year.
FUNCTION GetHour (T: Time): INTEGER;
Returns the current hour of the day.
FUNCTION GetMinute (T: Time): INTEGER;
Returns the minute of the current hour.
FUNCTION GetSecond (T: Time): INTEGER;
Returns the second of the current minute.

The optional radio clock is evaluated by the following command:

FUNCTION GetDCF77Info (VAR Info: DCF77Info);

where DCF77Info is the record shown below:

TYPE
DCF77Info = RECORD
Minute           : INTEGER;
{ 0..59 }
Hour
: INTEGER;  { 0..23 }
Day
: INTEGER;  { 0..31 }
Month
: INTEGER;  { 1..12 }
Year
: INTEGER;  { 1970..2038 }
DayLightSaving   : BOOLEAN;
OutOfSync        : INTEGER;
UnexactReceives  : INTEGER;
FrameErrors      : INTEGER;
LastReceive      : INTEGER;
END;

This function is best called after the occurrence of the affiliated signal SigDCF77 (cf. section "Signals") to update the time information. The essential information is the precise time and date which serves to correct the system time settings.

FUNCTION TimeToStr (T: Time): STRING;

Transforms a variable of type Time (e.g. as result from the function GetTime) into a string of the form "DD.MM.YYYY HH:MM:SS".

FUNCTION StrToTime (S: STRING, VAR T: Time): BOOLEAN;

Converts a string of the form "DD.MM.YYYY HH:MM:SS" to a variable of type Time and returns the boolean value TRUE if the conversion has been carried out. If the conversion was not possible (because of a wrong input format or an unsupported date) the function will return the value FALSE.

5.8 String Manipulations

FUNCTION StrCut (S:STRING, Index:INTEGER, Count:INTEGER): STRING;

This function returns a string which is cut from the string S starting at position Index with a length of Count characters (plus terminating null character). The index of the first character of a string is 0.

FUNCTION StrLen (S: STRING):INTEGER;

This function returns the length of a string i.e. the number of characters that precede the terminating null character.

FUNCTION StrTrans (S: STRING, From: STRING, To: STRING): STRING;

This function returns a string where any occurring character from the set From is replaced by the corresponding set To.

Hereby the relative position of each character of the two character sets is significant: the first character from the first set is replaced by the first character from the second set, etc.. If the character set From is longer than the set To then each character without a correspondence will be deleted.

The below example statement transforms the characters between a and f to upper case and deletes the dot '.':

S := StrTrans (S, "abcdef.", "ABCDEF");

The time part of the string created by the function TimeToStr can be displayed on a numeric display after having replaced the colons by dots. Therefore also use the function StrTrans:

S := StrTrans (S, ":", ".");

FUNCTION StrPos (S: STRING, C: CHAR): INTEGER;

The function locates the first occurrence of C in the string S and returns the index of the located character or -1 if the character does not occur in the string.
Example: Find the first occurrence of the character A in the string whatsoever.

Pos := StrPos(whatsover,'A');

FUNCTION StrPad(S:STRING, Len:INTEGER, C:CHAR, Pad:INTEGER):STRING;

This function returns a copy of the string S with the required length Len. If s is longer than the required length, then the right side overlapping characters will be cut off. If S is shorter than the required length, it will be filled up to this length with the character C. The parameter Pad defines where these characters are placed:

·PadLeft  - places the filling characters on the left side
·PadRight - places the filling characters on the right side
·PadLeftRight - places the filling characters on both sides of the string S
angeordnet und der entstehende Raum mit dem Zeichen C aufgefüllt.

FUNCTION StrAt (S: String, Index: INTEGER): CHAR;

The function returns the character of the string S located at the position Index. The index must be valid, i.e. it must not point over the terminating character of the string. Otherwise a range error is released.

FUNCTION StrUpper (VAR S: STRING);

This function transforms all lowercase characters of the string S to uppercase characters according to Codepage 437.

FUNCTION StrLower (VAR S: STRING);

This function transforms all uppercase characters of the string S to lowercase characters according to Codepage 437.

5.9 Type Conversion Functions

FUNCTION IntToStr (i: INTEGER, Digits: INTEGER): STRING;

This function converts the integer value i into the equivalent string with the length specified by Digits. If i has less digits than required for the string, it will be filled up with blanks on the left side. If i has more digits than representable by the string, a string filled with exclamation marks of correct length will be returned.

FUNCTION FloatToStr (F:FLOAT, LDig:INTEGER, TDig:INTEGER): STRING;

This function converts the floating point value f into the equivalent string with a maximum of LDig digits before and exactly NDig digits after the decimal point. If the converted string has got more leading digits than specified, a string filled with exclamation marks of correct length will be returned.

FUNCTION StrToInt (S: STRING, VAR I: INTEGER): BOOLEAN;

Converts the string S into a number of integer type and returns TRUE if the conversion was possible. If I becomes too large or if non-numerical characters are found inside the string the return value is FALSE.

FUNCTION StrToFloat (S: STRING, VAR F: FLOAT): BOOLEAN;

Converts the string S into the floating-point number F and returns TRUE if the conversion was possible. If F becomes too large or if non-numerical characters are found inside the string the return value is FALSE.

FUNCTION BufToStr (CONST A: INTEGER [], Count: INTEGER): STRING;

Converts an array of integral type values (yielded e.g. by the function ComBufReceive) into a string. The value Count defines the length of this string, i.e. the number of elements of A to be converted. The error StrOverflow is launched if the dimension of the array is larger than the maximum string size. A null-character inside the array will provoke a range error.

FUNCTION CharToStr (C: CHAR): STRING;

Converts a character value C into a string of the length: 1.

5.10 Serial Interfaces

The serial interface ports can be run using two different modes: string or byte mode, which is defined in the hardware configuration file. In addition the RS232 serial interface port Ser0 supports the "DCF77" mode for the communication with the optional radio clock.

Some functions adapt to the used mode, e.g. the use of the function ComSend is supported in both modes. However where the behaviour becomes ambiguous using one mode or the other, must not be used in the wrong mode, namely:

ComReceive    use for string-mode only, yielding an ASCII string
ComBufReceive use for byte-mode only, filling an integer array with the received character codes
When running the string-mode, the run time environment handles in- and outgoing characters at the serial interfaces as complete ASCII strings. The character determining a received string is defined in the hardware configuration file. If no character is explicitly declared the default character: \n (line feed) is used as determining character. The end of a sent string is thus determined by the programmer by appending the respective character to the string to be sent. The signal related to the serial port is launched when a determined string is received.

In contrast when running the byte-mode the signal related to the serial port is launched after one or several characters have been received. A determining character is not necessary. The data is stored by the receiving function in an integer array.

Also see the chapters 'Configuration File', 'Serial Interfaces' and 'Connection' (Ser0, Ser1 and Ser2) for further information about the serial interfaces
The serial port is addressed by the constants:

·Ser0 or RS232_A for the RS232-interface,
·Ser1 or RS485_A for the first RS485-interface and
·Ser2 or RS485_B for the second RS485-interface.
FUNCTION ComAvail (Port: INTEGER): BOOLEAN;

Returns TRUE if data is available on the specified port, i.e. if a complete determined string was transmit in string-mode or at least one byte is available from the receiving buffer in byte-mode.

FUNCTION ComReceive (Port: INTEGER): STRING;

Used in string-mode to read the data from the specified port. If no data is available an empty string is returned.

FUNCTION ComBufReceive (Port: INTEGER, VAR A: INTEGER []): INTEGER;

This function is used in byte-mode for reading data from the specified port. At most that number of bytes is stored in the array A which is possible regarding its array dimension. The result value of the function is the number of valid bytes copied to the array A.

FUNCTION ComBufFree (Port: INTEGER): INTEGER;

Yields the number of free bytes available in the sending buffer of the specified interface.

FUNCTION ComBufferAvail (Port: INTEGER, S: STRING): BOOLEAN;

String-mode function which returns TRUE if the sending buffer for the serial interface Port offers enough space to accept the string S. Otherwise FALSE is returned.

FUNCTION ComBufSend(Port:INTEGER,CONST A:INTEGER[],Count:INTEGER);

Byte-mode function passes the number of Count bytes from the array A to the sending buffer to be transferred via the serial interface Port. The value of Count must (evidently) not be larger than the number of elements of the array A.

FUNCTION ComSend (Port: INTEGER, S: STRING);

String-mode function passes the string S to the sending buffer and arranges for the string to be sent over the serial interface Port.

If the buffer has not enough capacity to store the data to be sent, the routine waits until enough characters have been passed to the interface so that the buffer is then able to accept the data. If no data can be passed because of locked handshake lines, the program may get stuck on this routine. Therefore it is recommended only to pass data to the serial interface after previously checking if the buffer offers enough memory to accept it. This check is effected by the function: ComBufFree (or also ComBufferAvail in string-mode).

After sending data via the RS485 interface, the port might need a time delay of longest 1 ms before it will be ready again to receive data. In order to avoid bus conflicts, other bus members should respect a delay of 1 ms between receiving data and sending messages.

FUNCTION ComSetBaud (Port: INTEGER, Baudrate: INTEGER);

Using this function it is possible to change the baud rate of a serial port at runtime. The function will not change the setting in the configuration file, so the new baud rate is lost when the program terminates. The parameter Baudrate must contain a valid baud rate. The function cannot be used to change the baud rate of the link port.

FUNCTION ComSetTerm (Port: INTEGER, Term: CHAR);

The function allows to change the line termination character at program runtime. The function will not change the the configuration file, so the new setting is lost when the program terminates.

5.11 I/O-Hardware

At programming level one distinguishes the I/O-types below:

Analog signals
Digital signals
Counter signals
No distinction is made for the programming of the actually used hardware, i.e. the slot card type. If for instance a type 110 slot card is substituted for a type 100 slot card, merely the hardware configuration file (*.cfg) has to be changed, the program remains unaffected by the substitution.

All I/O-types are addressed by handles. Handles are declared being of the type: Porthandle. They are initialised using the same function for all I/O-types. Thus one can distinguish between common functions for any I/O-hardware and specific functions which can only be used for certain I/O-types.

5.12 Common I/O-Handling

A name is assigned to each input or output in the configuration file. The program establishes an unambiguous link to the input/output by reference to this name. This link is the variable of the type 'Porthandle' which is initialised by the function OpenPort, which has to be called for each used channel at the program start. The function result is assigned to a previously declared variable of the type 'PortHandle'.

FUNCTION OpenPort (Name: STRING): PortHandle;

Returns the handle to a digital, analog or counter channel. The specified name must be equal (case-sensitive!) to the one specified in the configuration file (see corresponding chapter).

FUNCTION ValidPort (Name: STRING): BOOLEAN;

The function determines if the port with the given name is configured in the config file. Use of invalid ports will generate runtime errors when calling OpenPort.

FUNCTION GetHardwareError (VAR HWE: HardwareErrorDesc);

This function yields information in order to analyse the last occurring hardware error. It only yields valid results, if a SigHWFailure signal was launched, in any other case the yielded value is not defined. The result is a record of the form:

TYPE
  HardwareErrorDesc = RECORD
    Error      : INTEGER;
    Handle     : PortHandle;
    Slot       : INTEGER;
    Port       : INTEGER;
    Module     : INTEGER;
  END;

The number assigned to the record member Error specifies the (possibly) occurred error:

0: no error
1: unknown module
2: slot not occupied as defined in configuration
3: wrong port number
4: wrong slot number
5: slot card not installed
6: generic error
7: time-out during slot card access
8: module present but not initialized
9: invalid prescaler value
10: invalid filter value

FUNCTION ModuleInit (Handle: PortHandle);

This function allows the reinitialisation of the slot card which contains the port specified by Handle. The slot must contain a slot card, otherwise a run time error is provoked. The initialisation may last some seconds. It has to be assured that during this time any access to this slot card (e.g. from a signal function) is avoided as this would provoke a run time or system error or any undefined behaviour!

Note: The initialisation covers ALL inputs and/or outputs of the slot card which contains the given porthandle!

The function ModuleInit is particularly interesting for bus supporting slot cards such as the type 400 slot card. Herewith the bus can be re-established after a failure without restarting the S320 Controller. Such a failure would be e.g. an interruption of the bus interconnection or the power failure of a bus module.

FUNCTION SetFilter (Handle: PortHandle, Filter: FLOAT);

The function SetFilter allows to set the filter value for a module type 100 (it will also work for future modules supporting filter values). The value set with this function is valid until the program ends, or until SetFilter is called again.

FUNCTION SetGainAndOffs (Handle: PortHandle, Gain: FLOAT, Offs: FLOAT);

SetGainAndOffs sets gain and offsets for ports that support these two configuration variables. The new values are used until the program ends, or until SetGainAndOffs is called a second time.

FUNCTION GetGainAndOffs (Handle: PortHandle, VAR Gain: FLOAT, VAR Offs: FLOAT);

GetGainAndOffs retrieves gain and offset settings from an analog port.

5.13 Digital Input/Output

FUNCTION DigitalIn (Handle: PortHandle): BOOLEAN;

Returns TRUE or FALSE depending on the digital input's state.

FUNCTION DigitalOut (Handle: PortHandle, Value: BOOLEAN);

Sets the state of the digital output to the specified boolean state.

5.14 Analog Input/Output

FUNCTION AnalogIn (Handle: PortHandle): FLOAT;

Reads the value of an analog input.

FUNCTION AnalogOut (Handle: PortHandle, Value: FLOAT);

Passes a signal specified by 'Value' to the analog output.

5.15 Frequency or Impulse Input

For programming counter slot cards one has to distinguish the operation modes below (see type 510 slot card description):

Impulse counting
frequency measuring
Pulse-Pause Ratio Determination
In addition to the following functions, which are available for all counter cards, different functions exist for each of the above operation modes.

FUNCTION GetCounterWidth (Handle: PortHandle): INTEGER;

The function returns the the width of a counter in bits.

FUNCTION GetCounterBaseFrequency (Handle: PortHandle): FLOAT;

The function returns the base frequency of the given port.

5.16 Impulse Counting

FUNCTION CounterInit (Port: PortHandle);

The function resets the counter to zero.

FUNCTION CounterRead (Port: PortHandle): INTEGER;

The function yields the actual counter reading, an integer type value.

FUNCTION CounterEnable (Port: PortHandle, Enable: BOOLEAN): INTEGER;

Enables or disables a counter

FUNCTION CounterSet (Port: PortHandle, Value: INTEGER): INTEGER;

Set a counter to a specific value.

FUNCTION GetCountDir (Port: PortHandle): FLOAT;

The function GetCountDir returns 1.0 if the counter is currently forward counting, and -1.0 if the counter is counting backwards. The values 1.0/-1.0 are the only possible function results.

5.17 Frequency Measuring

In contrast to the impulse counting mode where the occurring impulses are counted during a given period, now a 50 MHz pulse is counted by a 32 bit counter until a given number of impulses has occurred. This however limits the maximum measuring period to approx. 40 seconds. The number of input impulses is defined by an adjustable pre-scaler, which accepts the values: 2, 4, 8, 16, 32, 64, 128 or 256.

The measuring ends after having counted the specified number of impulses or latest after the longest necessary (or possible) measuring time has run down.

The frequency measuring is started by the initialisation:

FUNCTION FrequencyInit (Port: PortHandle, PreScaler: INTEGER, MinFrequency: FLOAT): FLOAT;

which yields the longest necessary time to detect the lowest frequency MinFrequency by counting the number of PreScaler impulses. After the specified number of impulses has been detected, the function FrequencyRead will yield a result higher than 0.0. If the maximum measuring time has run down without having counted the specified number of impulses, the measuring is equally finished and the function FrequencyRead will still yield the value 0.0 which means that the frequency is lower than the lowest measurable frequency: MinFrequency or too low to be measured within the longest possible measuring time. Sensibly a timer is started for the maximum measuring time. If the function FrequencyRead does still not yield a value higher than 0.0 even after this timer has run down, the frequency is too low and a new measuring can be started.

FUNCTION FrequencyRead(Port:PortHandle, PreScaler:INTEGER): FLOAT;

This function evaluates a measuring initiated by FrequencyRead. It yields the frequency (Hz) if the specified number of impulses has been counted, otherwise 0.0 is returned.

FUNCTION FrequencyMeas (Port: PortHandle, PreScaler: INTEGER, MaxTim: FLOAT): FLOAT;

This function executes a complete frequency measuring. The function is finished only after the number of impulses defined by Prescaler has been counted or after the maximum time period MaxTim has run down. If the necessary number of impulses was counted, the function yields the respective frequency (Hz), otherwise 0.0 is returned.

5.18 Pulse-Pause Ratio Determination

This operation mode allows to determine the ratio between the duration of a 'High'-signal and a 'Low'-signal or simply to measure the duration of an impulse with 20 nanoseconds resolution.

Use the functions below in this operation mode:

FUNCTION DutyCycleInit (Port: PortHandle, RisingEdge: BOOLEAN): FLOAT;

The function initiates a measurement cycle. RisingEdge specifies if the cycle starts with the rising or falling edge of the input signal.

FUNCTION DutyCycleHighInit (Port: PortHandle);

The function starts the time measuring at the positive flank of the input signal.

FUNCTION DutyCycleLowInit (Port: PortHandle);

The function starts the time measuring at the negative flank of the input signal.

FUNCTION DutyCycleRead (Port: PortHandle): FLOAT;

The function yields the impulse duration depending on the preceding initialisation. If the period is not complete, 0.0 is returned.

FUNCTION DutyCycleMeas (Port: PortHandle, MaxTim: FLOAT): FLOAT;

This function effects a complete pulse-pause ratio determination. The function is finished only after a complete positive and negative impulse has occurred or until the time-out MaxTim has passed. If the complete impulses have been measured, the function yields the pulse-pause ration in a range between 0.0 and 1.0, otherwise 0.0 is returned.

5.19 Generate PWM Signals

The slot card type 520 generates impulses and frequencies with adjustable duty cycles.
See the corresponding description in the manual.

The record structure below is defined in the library stdlib.spi:

TYPE
  PWMSettings     = RECORD
    BaseFrequency : INTEGER;            { Frequency              }
    Prescale      : INTEGER;            { Prescale value }
    Period        : INTEGER;            { Period                 }
    PulseWidth    : INTEGER;            { Pulswidth              }
  END;

FUNCTION PWMSetFrequency (H: PortHandle, Frequency: FLOAT);
Set the frequency (Hz) for the given output. Appropriate values lie in a range between approx. 0.1 Hz and approx. 100 KHz. Note that an increasing frequency results in a more rough scaling of the frequency adjustment as well as in a lower resolution of the duty cycle.

FUNCTION PWMSetPulseWidth (H: PortHandle, PulseWidth: FLOAT); EXTERNAL 83;
Set the pulse-pause ratio for the given output. PulseWidth is a floating-point number in a range between 0 and 1 (corresponding to 0 .. 100%). If the value lies outside this valid range it will be adopted to the nearest border value without an error message. A newly set duty cycle will only be valid after finishing the current cycle. If the duty cycle had to be modified instantly, the frequency generation must be stopped (using PWMStop) and restarted (PWMStart).

FUNCTION PWMStart (H: PortHandle);
Launches the pulse generation for the given output.

FUNCTION PWMStartSync (H: PortHandle);
Synchronized start of both output channels of one slot card. The called port handle identifies one of the ports (no matter which one).

FUNCTION PWMStop (H: PortHandle);
Stops the pulse generation of the given output channel. The output is reset to the state given in the configuration file.

FUNCTION PWMGetState (H: PortHandle): BOOLEAN;
Yields the current state of the output.

FUNCTION PWMGetSettings (H: PortHandle, VAR Settings: PWMSettings);
Yields the actual physical settings for the given channel. This value might slightly differ from the original setpoint due to the adaptation to the physical resolution of the output hardware. Thus this result can be used to compute the achieved accuracy.

Note: the actually generated frequency in Hz results from the data of the record PWMSetting by the equation (in Spell notation):
Frequency := Float(PWM.BaseFrequency) / Float(PWM.Prescale * PWM.Period);

Note: the resolution of the pulse width (0..1) results from the data of the record PWMSetting by the equation (in Spell notation):
ResolutionPulsewith  := 1.0 / Float(PWM.PulseWidth);
(For the pulse width in percent multiply this value by 100.)

FUNCTION PWMGetIntState (H: PortHandle): BOOLEAN;
Yields TRUE if the specified channel launched a signal and FALSE otherwise.

5.20 Random Integer Generator

FUNCTION Randomize ();

Re-initialises the pseudo-random integer generator.

FUNCTION Random (Range: INTEGER): INTEGER;

This function computes a sequence of pseudo-random integers in the range between 0 and Range. The value of Range is inclusive, i.e. Random (2) yields an integer value between 0 and 2. The value Range must be positive. If the function Randomize is not called, the generated pseudo-random integer sequence is always identical.

5.21 Signals

The SPELL program gets signals at the occurrence of distinct external events. These external events, e.g. the receiving of data at the serial interfaces or pressed front keys, are communicated to the program by the run time environment in form of signals:

Signal listing:

SigTimer | This signal is actuated approximately every 10 milliseconds. Be aware that the period length between two time signals may not necessarily be constant. Furthermore one cannot assume that the real period length will not exceed or remain under a certain minimum time span. This is why the timer signals are not suitable for time measuring.
SigKbd | This signal is actuated if a key is pressed or released, i.e. each time that the current state of the keyboard changes.
SigSer0 | This signal is actuated after one or several characters (byte-mode) or a terminated string (string-mode) have been received at the serial interface Ser0.
SigSer1 | This signal is actuated after one or several characters (byte-mode) or a terminated string (string-mode) have been received at the serial interface Ser1.
SigSer2 | This signal is actuated after one or several characters (byte-mode) or a terminated string (string-mode) have been received at the serial interface Ser2.
SigDCF77 | is actuated when data has been received from the radio clock DCF77 connected to the serial interface 0. This data can be used to update permanently the internal real time clock inside a signal function. This updating procedure is then completely independent from the actual program. The signal occurs once a minute, correct receiving provided.
SigTermMsg | This signal is actuated after a character message sent by the user of the S320 PC program was received.
SigTermStr | For internal use only.
SigPWM | This signal is actuated at every pulse generation of the PWM slot card type 520 if the current frequency is below 200 Hz.
SigNet This signal is triggered under the following conditions:
  • Data has been received on a socket.
  • A connection has been established to a socket that is in LISTEN state.
  • A connection has been closed by the remote side.
SigCounter | The signal SigCounter is triggered after a measurement cycle of the optional type 500 card has been completed.
SigAbort | This signal is actuated at the occurrence of a run time error. The program execution will be aborted. If an error handling function does exist, it will be executed first.
SigHWFailure | is actuated at the occurrence of a slot card error. This signal is particularly interesting for bus supporting modules such as the type 400 slot card, as it allows to react immediately on an interrupt of the bus interconnection or power failure of a bus module.

After each action of the spell program, an internal demand for signals is made. It is now possible to implement "signal functions" which are executed at any step of the program at the occurrence of a certain signal. The signal is locked during the execution of the signal function and reset after its ending.

The handling of signals requires much care. On one hand, signals are not buffered, i.e. if several identical signals occur while this signal is locked, the corresponding signal function will only be executed one more time, as only one of these signals will eventually be communicated to the running program. On the other hand problems may occur by interference of the signal routine with the main program, as it is not predictable where the proper program will be interrupted by a signal. This problem is known under the expression "re-entrance". A short discussion of this problem is given in the following chapter.

There are two types of signals: synchronous signals and asynchronous signals. Asynchronous signals are triggered by external events, which do not depend on the momentary executed program statement. Thus they may interrupt the program at any possible point.

Synchronous signals are only triggered at certain function calls, possibly in combination with certain conditions. Thus the program will be interrupted at a defined point.

Among the synchronous signals we merely find the error signals: SigAbort and SigHWFailure, whereas all other signals are asynchronous.

During the execution of an asynchronous signal function all other asynchronous signals are blocked. Any signal occurring more than once during the execution of this signal function is lost. After exiting the signal function for a signal all other signals occurred meanwhile will be processed.

5.22 Signal Functions

Signal functions are called after the occurrence of a certain signal. As no explicit call is made, no explicit parameters can be specified either. Thus any signal function can only communicate via global variables with the main program.

A signal function is therefore a function with an empty parameter list and without a return value. The function header is followed by the keyword SIGNAL and the identifier of the signal to react on. Several functions (with different names) can be implemented for one specific signal. These functions will be executed at the occurrence of a signal in the order of its declaration in the source code.

The example below shows the function header to react on the receiving of information at the serial interface 0:

FUNCTION SigSer0Handler();SIGNAL SigSer0;

When a signal occurs and the corresponding signal function exists, the current program is interrupted until the execution of the signal function has ended. A signal function will not be interrupted even through the occurrence of further signals. The main program will be continued after the complete execution of the signal routine at the location where it was interrupted.

The signal handling supported by the S320 Controller is in principle comparable to common interrupt handling. Additionally a series of measures have been taken against possible conflict potentials. Nevertheless signal procedure execution time should be reduced to a minimum. One also has to assure that no data of the main program is unintentionally changed by the signal function. As the main program can be interrupted at any location, side effects may be provoked which lead to surprising errors or to errors which are hard to locate. Among the demonstration programs you will find a simple example for such a side effect.

5.23 Manipulating Signals

With regard to the mentioned re-entrance problems a mechanism is given at hand in order to suppress signals temporarily. This is particularly useful for asynchronous signals, because they can occur at any time and can provoke re-entrance problems. The signals you want to suppress are given in form of an integer type value, which may be a single value or the sum of several values from the list below:

SigMaskTimer | identifies the signal SigTimer
SigMaskKbd | identifies the signal SigKbd
SigMaskSer0 | identifies the signal SigSer0
SigMaskSer1 | identifies the signal SigSer1
SigMaskSer2 | identifies the signal SigSer2
SigMaskDCF77 | identifies the signal SigDCF77
SigMaskTermMsg | identifies the signal SigTermMsg
SigMaskTermStr | identifies the signal SigTermStr
SigMaskPWM | identifies the signal SigPWM
SigMaskNet | identifies the signal SigNet
SigMaskCounter | identifies the signal SigCounter
SigMaskAbort | identifies the signal SigAbort
SigMaskHWFailure | identifies the signal SigHWFailure

The most important combinations are already predefined:

SigMaskSerial | identifies the signals of all serial interfaces: Ser0 to Ser2, and SigTermMsg/SigTermStr.
SigMaskAsync | identifies the all asynchronous signals, i.e. timer, keyboard, the serial interfaces, the radio clock signal, plus network, counter and PWM signals.
SigMaskSync | includes the synchronous signals: SigAbort and SigHWFailure

FUNCTION SigBlock (Mask: INTEGER): INTEGER;

This function locks all signals specified by Mask and yields the previously active mask. This return value has to be used to re-establish the old settings using the function SigUnblock. This makes a nesting of SigBlock/SigUnblock calls possible. Only one single occurrence of each different signal is buffered. This buffered signal is then activated when calling SigUnblock.

FUNCTION SigUnblock (OldMask: INTEGER);

Resets the signal block pattern to the previous state specified by OldMask. If a signal has occurred when it was blocked, its occurrence (but not the number of occurrences) is buffered. If this signal is unlocked by the SigUnblock function, then it is directly executed, even before returning from the SigUnblock function.

FUNCTION SigBlockAsync (): INTEGER;

Identical to the call of SigBlock with a mask which includes all asynchronous signals.

The example below, locks temporarily all signals occurring from the serial interfaces 1 and 2:

VAR OldMask: INTEGER;
BEGIN
    OldMask := SigBlock (SigMaskSer1 + SigMaskSer2);
    ....
    SigUnblock (OldMask);
END;
5.24 Watchdog

The Controller S320 is equiped with a hardware watchdog device. If the watchdog is enabled, it will trigger a hardware reset after a timeout of 1.6 seconds has expired. The watchdog timer must be reset within this time. The watchdog can be used as a provision against software malfunction. A hanging program will cause the watchdog timer to run down, and the following reset will restart the controller.

The watchdog device can be controlled using the following functions:

FUNCTION WatchdogEnable ();

The function enables the watchdog and resets the watchdog timer. After calling this function, the controller will get reset if the WatchdogTrigger is not called in regular intervals to reset the timer.

FUNCTION WatchdogDisable ();

The function disables the watchdog. If the watchdog is disabled, it will no longer cause a controller restart if the timer expires. This function can be used to protect code that has an unknown runtime against expiration of the watchdog timer.

FUNCTION WatchdogTrigger ();

The function resets the watchdog timer. If the watchdog is enabled, it must be called in regular intervals, otherwise the watchdog timer will expire causing a restart of the Controller S320.

5.25 Files and Directories

The Controller S320 uses part of the internal flash ROM as a file system. Data stored in this file system survives a restart or loss of power.The functions to access files and directories within the file system are very similar to those on "bigger" operating systems.

The size of the file system in the flash ROM is 384 KB. The directory can contain not more than 128 file entries. The size of a single file is limited to 192 KB. This limit is not within the file system itself, but results from the size of the file system cache (see below).

The file system has two predefined directories named "www" and "dat". All files must be created in one of these two directories. The "www" directory is special in that it is used by the builtin web server. Files in this directory can be accessed from the outside if the web server is enabled. Using the terminal program, it is possible to create, read or delete files in either of the two directories. Filenames in the file system are using the '/' character as a path separator.

Since writing to the flash ROM is rather slow, and since the number of write cycles is limited by the hardware, the operating system will buffer all data in the file system cache. The file system cache is a RAM buffer with a size of 192 KB. The buffer can be written to the flash ROM by calling FileFlushCache.

A file exists either in the RAM cache or in the flash ROM. Opening a file for write operations will therefore copy the complete contents of the file into the file system cache. This is the reason for the maximum file size of 192 KB (the size of the file system cache). Because the size of the cache is limited, there may be errors when writing to a file: The new data may grow a file beyond the size of the cache. The file system cache is not written to the flash ROM automatically by the operating system. Flushing the cache is the responsibility of the programmer.

NOTE: In case of power loss, or a restart of the Controller S320, data in the file system cache is lost if it was not written to the flash ROM before!

NOTE: There is one exception to the rule that the operating system will not flush the file system cache itself: The cache is written to the flash ROM whenever a SPELL program terminates.

All SPELL functions that handle files and directories return an error code. A return value of EOK means that the function has been successful. Any other value means that the function had an error. Possible error codes are described in a separate section.

The following function are available to work with files and directories:

FUNCTION FileOpen (CONST Name: STRING, Mode: INTEGER, VAR H: FileHandle): INTEGER;

The function FileOpen opens a file. The file name must contain a valid directory. Examples for valid file names are:

/www/index.html
/dat/messergebnisse.dat
/dat/protokoll.txt

The parameter Mode is the open mode for the file. The following modes are available:

FM_READ | Opens a file for reading. Files opened for reading only are not transfered into the file system cache, they are read from the flash ROM directly instead.
FM_WRITE | Opens a file for writing. When using FM_WRITE as an open mode, the file is transfered to the file system cache.
FM_READWRITE | Opens a file for reading and writing. This mode is a combination of FM_READ and FM_WRITE.
FM_CREATE | The file will be created if it does not exist. Without FM_CREATE, an attempt to open a non existing file will generate an error. FM_CREATE can only be used in combination with FM_WRITE.
FM_TRUNC | If the file exists, it will be truncated, that is, the size is set to zero. FM_TRUNC can only be used in combination with FM_WRITE.
FM_APPEND | Appends data to a file. This mode can only be used in combination with FM_WRITE. When using FM_APPEND, the file pointer will be set to the end of the file once after the open was successful.

File modes can be combined by using the '+' or BITOR operators. For example, FM_READWRITE is equivalent to FM_READ BITOR FM_WRITE.

If the function was successful (return code EOK), it returns a handle for the open file in H. This file handle can be used together with other file manipulation functions.

FUNCTION FileClose (VAR H: FileHandle): INTEGER;

This function closes an open file. The file handle passed in H is invalidated by the function.

NOTE: Even after closing a file, any data written to the file is still in the file system cache and therefore lost on a power outage. You will have to call FileFlushCache to write the data from the file system cache into the flash ROM.

FUNCTION FileDelete (CONST Name: STRING): INTEGER;

The function FileDelete deletes the file with the given name.

FUNCTION FileMove (CONST Source: STRING, CONST Target: STRING): INTEGER;

FileMove renames a file. Source is the name of an existing file, Target is the new name of the file. The file with the name Source must not be open when FileMode is called. If the target file exists, it will be deleted. If the target file is open and cannot be deleted, an error code is returned. If the rename was successul, FileMove returns EOK.

FUNCTION FileWriteStr (H: FileHandle, CONST S: STRING): INTEGER;

This function writes the string S into an open file at the current file position.

FUNCTION FileReadLine (H: FileHandle, VAR S: STRING): INTEGER;

The function reads one line from the file referenced by H. If the function is successful, EOK is returned and the line read is placed in S, including the line terminator. In case of errors, S is cleared (set to the empty string). If the line in the file is longer than the maximum string length in SPELL (255 characters), the first part of the line is placed in S, and the remainder of the line is skipped in the file. If this happens, the line terminator is missing from S.

FUNCTION FileGetPos (H: FileHandle, VAR Pos: INTEGER): INTEGER;

The function FileGetPos determines the current read/write position and returns it in Pos. The first element in the file has the index zero. The function returns an error code.

FUNCTION FileSetPos (H: FileHandle, Pos: INTEGER): INTEGER;

FileSetPos sets the read/write position of a file to the value passed in Pos. Pos must not be negative, and not greatter than the size of the file (the size of the file can be determined by calling FileSize). The first element of a file has the index zero. The function returns an error code.

FUNCTION FileSize (H: FileHandle, VAR Size: INTEGER): INTEGER;

FileSize determines the size of an open file. The function returns an error code. On success (EOK is returned), the variable Size contains the size of the file.

FUNCTION FileFlushCache (): INTEGER;

The function writes all data in the file system cache the the flash ROM. The function may not return for several seconds, depending on the amount of data that is currently stored in the flash ROM file system. This must be considered when the watchdog feature is used. Without calling this function, all data in the file system cache are lost in case if a power outage or controller restart.

The function returns an error code.

FUNCTION FileGetSysInfo (VAR Info: FileSysInfo): INTEGER;

The function returns information about the file system. The record FileSysInfo is defined in stdlib.spi as follows:

TYPE
  FileSysInfo   = RECORD
    TotalSpace  : INTEGER;              { Total space available for data }
    UsedSpace   : INTEGER;              { Used space }
    TotalEntries: INTEGER;              { Maximum number of directory entries }
    UsedEntries : INTEGER;              { Used direcory entries }
  END;

FUNCTION DirOpen (VAR H: DirHandle): INTEGER;

DirOpen opens a directory for reading and returns an error code. If EOK is returned, H will contain a directory handle that can be used when calling other directory handling functions.

FUNCTION DirClose (VAR H: DirHandle): INTEGER;

The function closes an open directory handle. H must be a handle created with the help of the DirOpen function.

FUNCTION DirRead (H: DirHandle, VAR Entry: DirEntry): INTEGER;

DirRead reads the next file entry from a directory. If the function was successful, the file entry is returned in Entry. The record type DirEntry is defined in stdlib.spi as follows:

TYPE
  DirEntry      = RECORD
    Name        : STRING;               { Name of the file }
    Size        : INTEGER;              { Size of the file }
    CTime       : Time;                 { Time of creation }
    MTime       : Time;                 { Time of last modification }
    Flags       : INTEGER;              { File flags }
  END;

The variable Flags contains a combination of one or more of the following flags:

DF_RAM The file is currently in the file system cache.

NOTE: If a file system directory is modified between two calls to DirRead (for example by creating or deleting files) , there is a chance that DirRead does not work as expected. It may return one entry twice or skip an existing file entry.

5.26 Network functions

The Controller S320 is equipped with an ethernet port, and an implementation of TCP/IP, the "internet protocol". This section covers the functions necessary to establish network connections and transfer data.

One basic element of the SPELL network API is a Socket. This is a data type that represents the end point of a network connection.

Since TCP/IP is rather complex, we would suggest to use one of the example programs for first tests. Books discussing the TCP/IP protocol might also be useful.

The order of function calls for actively establishing a connection is as follows:

  1. A socket is created using SockCreate.
  2. If necessary, a timeout can be set with SockSetWriteTimeout.
  3. The connection is established with SockConnect.
  4. The connection is closed with SockClose. This will also destroy the socket.
To wait passively for incoming connections:
  1. A socket is created using SockCreate.
  2. The socket is put into LISTEN state by calling SockListen.
  3. If necessary, a timeout for can be set for the following calls to SockAccept using SockSetReadTimeout.
  4. Incoming connections are accepted with calls to SockAccept.
  5. The last step can be repeated (a socket in LISTEN state can accept more than one connection).
  6. The sockets for the connections are close using SockClose.
  7. The listening is also close with SockClose.

FUNCTION SockCreate (SocketType: INTEGER, VAR Sock: Socket): INTEGER;

The function creates a new socket and returns an error code. If the return value is EOK, the variable Sock contains the new socket.
NOTE: SPELL limits the number of sockets to 4. If this number is exceeded, SockCreate will return an error code of EMFILE.

FUNCTION SockConnect (Sock: Socket, Addr: IpAddress, Port: IpPort): INTEGER;

SockConnect will try to establish a connection with a remote computer, using the given IP address and port number. The function will return if a connection was established or if there is an error. When establishing the connection, the current write timeout (set with SockSetWriteTimeout) is used, provided it is greater than 5 seconds and less than 90. If the current write timeout is INFINITE, a default value of 75 seconds is used.

FUNCTION SockListen (Sock: Socket, Addr: IpAddress, Port: IpPort): INTEGER;

The function will put the given socket into LISTEN state. If the function returns EOK, the socket is in listen state, which means that it will accept incoming connections. Sockets for accepted connections can be retrieved by calling SockAccept. For each incoming connection, the operating system will also raise the signal SigNet.

FUNCTION SockAccept (Sock: Socket, VAR NewSock: Socket): INTEGER;

The function will fetch a socket for an already accepted connection from the queue. Sock must be a socket in LISTEN state. If no connection has already been accepted, the function waits until there is one, or a timeout occurs. The timeout can be set using SockSetReadTimeout. The function returns a error code, which is EOK if a connection socket is returned, and ETIMEDOUT in case of a timeout.

FUNCTION SockClose (VAR Sock: Socket): INTEGER;

SockClose will close a connection and delete the socket passed to the function. In case of an established connection, buffered data is transfered to the remote side, even after the connection has been closed. The function returns an error code and will invalidate the passed socket variable (it is set to InvalidSocket).

FUNCTION SockWriteString (Sock: Socket, CONST S: String): INTEGER;

SockWriteStr sends the given string over a network connection. The function does not return, until there is enough space in the write buffer to store the string, or until there is a time. The timeout value may be set by a call to SockSetWriteTimeout. The function returns an error code, which is EOK if anything worked ok, and ETIMEDOUT in case of a timeout.

FUNCTION SockReadString (Sock: Socket, VAR S: STRING): INTEGER;

The function reads one line of input from the socket, and pass it back to the caller in S. If the received line exceeds the maximum SPELL string length (255 chars), the function will still read the whole line, but store only the first part of it in S. If a timeout was set before with SockSetReadTimeout it will be used for the read. The function returns an error code.

FUNCTION SockSetReadTimeout (Sock: Socket, Timeout: FLOAT): INTEGER;

SockSetReadTimeout sets the timeout that is used when reading data or accepting a connection with SockAccept. The timeout is specific for the given socket Sock. An error code is returned by the function.

FUNCTION SockSetWriteTimeout (Sock: Socket, Timeout: FLOAT): INTEGER;

SockSetWriteTimeoput sets the timeout used when writing data or establishing a connection with SockConnect. The timeout is valid only for the given socket Sock. An error code is returned by the function.

FUNCTION SockAvail (Sock: Socket): BOOLEAN;

SockAvail returns TRUE if receive data is available for this socket, otherwise it returns FALSE. If the socket is put in LISTEN state by a call to SockListen, SockAvail returns TRUE if there are established connections for this socket.
NOTE: The function does also return true if a following call to SockRead... would return an error. Because of this, errors returned by the SockRead... functions must be handled by the programmer, otherwise a closed connection would not be detected and the socket left in this state indeterminate.

FUNCTION SockGetConnSpec (Sock: Socket, VAR Info: ConnSpec): INTEGER;

The function SockGetConnSpec returns information about the connection data for a socket in a record of type ConnSpec. ConnSpec is defined in stdlib.spi as follows:

TYPE
  ConnSpec      = RECORD
    LocalPort   : IpPort;
    RemotePort  : IpPort;
    LocalAddr   : IpAddress;
    RemoteAddr  : IpAddress;
  END;

Unused fields (for example data for the remote host, if the socket is not connected) do have the value zero for the port, and IPADDR_ANY for the address. SockGetConnSpec returns an error code.

FUNCTION IpAddressToStr (Addr: IpAddress): STRING;

The function converts an IP address into a string in "dotted quad" notation (aaa.bbb.ccc.ddd) and returns it.

5.27 DNS Functions

DNS allows to translate internet host names into IP numbers used to establish TCP connections, or to translate IP numbers back into host names. This is done by querying the distributed DNS (Domain Name Service) database. Because of size constraints, the SPELL implementation has the following limitations:

  1. The DNS functions need a nameserver to be configured and available.
  2. The nameserver must support recursive queries (this is the default).
  3. The SPELL functions limit the queries to A, CNAME und PTR records.
  4. The resolver (the DNS client library) will always use UDP for queries. This limits the maximum size of the returned data. In rare cases, this can cause query errors.
Since all DNS queries are sent over the network, there may be delays. For this reason, it is possible to control the behaviour of the resolver using the timeout parameter. The type DnsTimeout is defined in stdlib.h as follows:

TYPE
  DnsTimeout    = RECORD
    MaxTime     : FLOAT;    { Timeout for one NS Query }
    MaxTries    : INTEGER;  { Maximum number of messages for one query }
    MaxFollow   : INTEGER;  { Maximum number of CNAMEs that are resolved }
  END;

The record fields have the following meanings:

MaxTime | MaxTime is the timeout in seconds for one message sent to a nameserver. Resolving a name or IP address may need more than one message exchange. The value should be a few seconds in a local area network, and about 10-90 seconds when querying data from ther internet.
MaxTries | This is the maximum number of messages sent for one query. One message is sent repeatedly if there is no answer from the name server. Since DNS uses UDP, and UDP packets may get lost on the network, it is suggested to use a value greater than one (for example 3).
MaxFollow | If the resolver gets data for an alias (a CNAME) instead of an A record, it will try to resolve the alias to find the "real" name. Unfortunately, an alias can point to another alias, and so on (this is not recommended practice, but some admins are careless). MaxFollow defines, how many aliases are resolved before giving up. A reasonable value for this parameter would be 2 or 3.

FUNCTION GetHostByName (CONST Name: STRING, VAR Addr: IpAddress, CONST T: DnsTimeout): INTEGER;

The function resolves a host name into an IP address. It returns an error code. If the return code is EOK, Addr contains the IP address of the host with the given name. If the host has more than one IP address, only the first one is returned.

FUNCTION GetHostByAddr (Addr: IpAddress, VAR Name: STRING, CONST T: DnsTimeout): INTEGER;

The function tries to find the name for the given IP address. It returns an error code. If the return code is EOK, Name contains the name of the host with the given IP address. In any other case, Name will contain the IP address converted to a string in "dotted quad" notation (aaa.bbb.ccc.ddd).

5.28 Syslog

The Controller S320 supports the Unix syslog protocol. Using this protocol, log messages can be sent over the network to remote hosts. If a syslog daemon runs on the remote host, it is able to receive and process such a log message. This allows central monitoring and processing of log messages.

Before the SPELL function SysLog can be used, it is necessary to specify the IP of a syslog server in the network configuration. This server must accept message from the network.

Each message is assigned a priority. The priorities can be used by the syslog server to enable special handling. Log messages may be sent by mail to an administrator, just logged into a file, or ignored, depending on the priority. Possible priorities are defined in stdlib.spi as contstants:

CONST
LOG_DEBUG   : INTEGER = 7;
{ Debug-level messages }
LOG_INFO    : INTEGER = 6;
{ Informational message }
LOG_NOTICE  : INTEGER = 5;       { Normal
but significant condition }
LOG_WARNING : INTEGER = 4;       { Warning
conditions }
LOG_ERROR   : INTEGER = 3;
{ Error conditions }
LOG_CRIT    : INTEGER = 2;
{ Critical conditions }
LOG_ALERT   : INTEGER = 1;
{ Action must be taken immidiately }
LOG_EMERG   : INTEGER = 0;
{ System is unusable }

Syslog messages do also contain a facility code in each message. The facility specifies the part of a system that sent the log message. The Controller S320 supports one such facility. It is specified in the network configuration, and may not be altered from within SPELL.

FUNCTION SysLog (Priority: INTEGER, CONST Msg: STRING);

The function sends the given message to the syslog server configured in the network settings using the specified priority. If no syslog server is configured, or if the server is not reachable, the message is lost.

NOTE: Syslog messages are sent over the network using the UDP protocol. Since UDP is not a reliable protocol, messages may get lost in transit. The advantage of using UDP messages is the low overhead.

5.29 Retrieving Configuration Data

The following set of functions allows a program to retrieve generic configuration data.

FUNCTION CfgGetSerial (): STRING;

The function returns the serial number of the controller as a string.

FUNCTION CfgLanIsEnabled (): BOOLEAN;

The function returns TRUE if the LAN hardware is available and enabled.

FUNCTION CfgGetLanIP (): IpAddress;

The function returns the IP address of the controller. If the LAN hardware is not available, not enabled, or not configured, the function will return IPADDR_ANY as its result. IPADDR_ANY is a constant defined in stdlib.spi.

FUNCTION CfgGetLanMac (): STRING;

The function returns the MAC address of the controller as a string.

FUNCTION CfgGetLibSupport (): INTEGER;

The function returns the supported library functions as bitset contained in an integer. The result is zero if all library functions are supported.

FUNCTION CfgGetOsVersion (): STRING;

The function returns the version of the Controller S320 operating system as a string.

5.30 Error Handling

The S320 Controller does not implicitly report error messages. It is thus always recommended to include an error signal function (SigAbort) in the program. The standard error function (file: STDERR.SPI) causes the expenditure of diagnostic numbers onto the display.

There are two types of error handling functions:

1. One function to release an error. It is often used for user defined exception handling, and

2. Functions to analyse an occurred error. These functions help to find the cause of an error and its location in the source code. If the S320 Controller is linked to the PC's terminal program, this information is directly available by the command "Find error location". The error is retraced by the terminal program using debug information of the sources saved by the S320 Controller. Only if the program sources have not been transferred to the Controller the version on the PC's hard disk will be checked. (Then of course, sources must not have been modified since the last transfer).

5.31 Error codes

Starting with version 4 of the Controller S320 operating system, error codes have been unified. For this reason, the following list of possible error codes contains runtime errors as well as errors returned by the file and network functions. All error codes are defined as constants in stdlib.spi.

Code | Name | Bedeutung
0 | EOK | No error.
1 | EBREAK | Unexpected breakpoint.
2 | ENOTIMP | Function not implemented.
3 | EILLEGAL | Invalid operation.
4 | ECASE | No matching CASE label found.
5 | ESTRSIZE | String overflow.
6 | EDIVBYZERO | Division by zero.
7 | EMODBYZERO | Modulo operation with zero.
8 | ERANGE | Value outside a valid range.
9 | EFPOVERFLOW | Floating point overflow.
10 | EFPUNDERFLOW | Floating point underflow.
11 | EDOMAIN | Domain error.
17 | EINVAL | Invalid parameter.
19 | ESTACK | Stack overflow.
21 | EINVPORT | Invalid port name.
22 | ENOMEM | Not enough memory available.
23 | EHOSTUNREACH | Host is unreachable.
24 | ENETUNREACH | Network is unrechable.
25 | ETIMEDOUT | Connection timed out.
26 | ECONNREFUSED | Connection refused.
27 | ECONNRESET | Connection has been reset.
28 | ECONNABORTED | Connection has been aborted.
29 | ENOTCONN | There is no connection.
30 | EISCONN | A connection has already been established.
31 | EADDRINUSE | Address is in use.
32 | EPORTINUSE | Port is in use.
33 | EINPROGRESS | Operation is in progress.
34 | EPIPE | Connection has been closed.
35 | EACCESS | Access was denied.
36 | ENOENT | File does not exist.
37 | EEXIST | File exists.
38 | EBUSY | File or device is in use.
39 | ENOSPC | No space left on device.
40 | ENOEXEC | Not an executable file.
41 | EBADDATA | Bad data.
42 | EMFILE | Too many open files.
43 | EMSGSIZE | Message is too big.
44 | EHOSTNOTFOUND | Host not found.
45 | ENODATA | Host doesn't have an IP address.
46 | EXDEV | Cross device operation is not allowed.

Old error codes starting with Err... are still supported. However, they shouldn't be used for new programs.

5.32 Error Handling Functions

FUNCTION ErrTrigger (Code: INTEGER);

This function launches a run time error with the given error code. The pre-defined errors (division by zero, etc.) are listed in the chapter 'Run time errors'.

FUNCTION ErrCode (): INTEGER;

This function yields the code of an occurred error or the result 0, if no error is present. This function is used to display the error code in an error signal function.

FUNCTION ErrAdr (): INTEGER;

This function yields the address of an occurred error. If no error is present the result is undefined. It can be used to locate the position in the source code where an error has occurred.

FUNCTION ErrGetMsg (Code: INTEGER): STRING;

The function returns an error message (in english) for the error code passed as a parameter.

5.33 Predefined Run Time Errors

Some error codes defined in the SPELL environment are also used for runtime errors. In order to avoid confusion, the programmer should never use these constants when calling the ErrTrigger function. Specific error codes of further libraries available from TetraTec are composed of three digits. Thus it is recommended to choose four digit error codes when defining own error codes.

5.34 The Library STDERR.SPI

The standard error function included yields the error code and the error address if the running program is interrupted by an error (e.g. division by zero). The standard error handling or a custom error handling should always be included in any Spell-program. The error code can be compared with the corresponding table in this manual. The terminal program can be used to locate the line of the source code where the error occurred (choose: "Find error location").

5.35 Support Libraries

More libraries for common tasks in measurement and control are included in delivery.

So you will find the ready to use implementation of control algorithms in the library REGEL. Functions for the linearisation of measurement values are included to the library LIN or the library POL. For the determination of the properties of gas use the library GAS. A text ticker display can be realised by using a function from the library LAUFTEXT. And eventually a wide variety of units is covered in the library UNITCON for easy unit conversion.

* * *


Controller S320 Manual - Slot Card Typ510

 2.13.1 TYPE 510 Slot Card: 2 x Input for Frequency Measuring (till 12/2005)

The type 510 slot card is a universal tool for the counting and the measuring of digital signals. This slot card contains two mutually independent channels with 32 bit counting width and internal 50 MHz oscillator for frequency measuring.

The inputs are implemented via opto couplers, so that nearly any signal form existing in practice can be connected directly. A feed supply of 5 volt and 24 volt is provided for.

The operation modes below are supported:

1. | Impulse counting: Counting of impulses with 32 bit counting width and a maximum frequency of approx. 1 MHz.
2. | Incremental encoder: Forward and backward counting of impulses provided by incremental encoders. This operation mode is only possible at port 0. Then at port 1 the by 90° phase displaced signal is connected for the forward-backward detection. The maximum counting frequency is 50 kHz, the counting width is 32 bit. On the second channel can be carried out simultaneously the frequency measuring or the pulse-pause ratio determination of the encoder signal.
3. | Incremental encoder with quadruple evaluation: As above, however each flank changing of the encoder is counted. This results in a four times better resolution of the encoder signal.
4. | Frequency measuring: Reciprocal frequency measuring method. An adjustable prescaler (2 to 256) generates a logical counting period, whilst a 50 MHz pulse is counted by a 32 bit counter. The frequency results from: 25E6 * (prescaler setting / counter value). This method allows to easily fit the measuring period and the resolution best to the specific requirements.
5. | Pulse-pause ratio determination: A 50 MHz pulse is counted in succession by a 32 bit counter during the positive or negative flank of an input signal. The result is the ratio from the "high-flank" over the entire impulse duration. The determination of an impulse length is equally possible in this operation mode.

Input: The inputs of the type 510 slot card are equipped with opto couplers. A 5 volt or 24 volt feed supply is provided for. The input is designed as shown below:

Switching on SW1 and SW5 for port 0 and port 1 respectively, a supply voltage of 24 volt which can be charged till up to approx. 25 mA is is put to the SUP connector. Equally a 5 volt feed supply, chargeable till up to approx. 20 mA can be chosen by switching on SW2 (Port0) and SW6 (Port1) respectively.

Note: Don't set the switches SW1 and SW2 or SW5 and SW6 at ON simultaneously.

The pre-resistor to the opto coupler is adjusted to the given input voltage by SW3 (port0) and SW7 (port1) respectively. Chosing the position ON for SW3 and SW7 respectively, the input with 470 ohm will be suited for 5 volt TTL signals. Otherwise, choosing position OFF, the inputs with 3170 ohm support 24 volt input signals. The LED of the opto coupler needs a current >5mA till up to 10mA max. for switching. In switched off state the current must be less than 0.25mA. The diode voltage at 10 mA is typ. 1.5 volt.

The switches SW4 (port0) and SW8 (port1) respectively add a low pass, which restricts the maximum input frequency to approximately 50 kHz. This might be necessary when handling low frequency signals with a gentle rise of the flanks (e.g. flow meters) in order to avoid the reading of multiple impulses at flank changing.

Further input conditions can be matched easily by the use of appropriate external preresistors. The opto coupler allows to connect positive switching as well as 'ground switching' signals. If the feed supply of the S320 Controller is used, the galvanic isolation is of course not given. In this case a connection between -IN and GND is established for positive switching sensors and between SUP and +IN for 'ground switching' sensors.

Note: Some signal encoders (e.g. mechanical switches) can give several impulses during switching e.g. due to bouncing of the contacts and thus provoke unexpected results. This effect can be avoided by external measures such as RC-elements, monoflops or similar. See also for the functionality of the switches SW4 and SW8.

Note: The opto couplers establish galvanic isolation in the meaning of a functional separation. It is however not permissible to operate the inputs with voltages > 50 volt relative to the PE-level of the S320 Controller.

Note: Due to the high operating frequency of the type 510 slot card the power rating is relatively high. This is why not more than two type 510 slot cards can be used together in the S320 Controller. Nevertheless other slot card types can be additionally be installed, e.g. three more type 100 slot cards.

Explanation to the reciprocal frequency measuring method: This method is advantageous over the 'current' method (counting a number of impulses during a fixed period) especially for small frequencies, where it leads much faster to a result with higher resolution.

From the frequency to be measured one generates the measuring period by a counter adjustable via a (software) prescaler. Possible prescaling values are 2, 4, 8, 16, 32, 64, 128 and 256. During the positive level of this prescaled signal a 50 MHz pulse is counted by a 32 bit counter. The frequency results from:
25E6 * (prescaler setting / counter value).

Thus the measuring period is not fixed, but results from the prescaler setting and the actual input frequency.

The equations below yield the respective values:

measuring period [s] | = prescaler setting / measuring frequency [Hz]
resolution [Hz] | = measuring frequency [Hz] / (25E6 * measuring period[s])
frequency [Hz] | = 25E6 * (prescaler setting / counter value)

Example 1 kHz-signal: this signal's period length is 1ms. Using the prescaling of 256 the measuring period sums up to 256 ms. During this period the internal counter counts 50.000.000 * 0.5 * 0.256 = 6.400.000 impulses. The resolution is thus 1.000 Hz / 6.400.000 = 0.000156 Hz. Using the 'current' method with a period length of 1 second the resolution would only be 1 Hz (!).

Further examples:

Signal [Hz] | PreScaler | Measuring Period [s] | Resolution [Hz]
1 | 2 | 2,00000000 | 0,00000002
10 | 2 | 0,20000000 | 0,00000200
100 | 2 | 0,02000000 | 0,00020000
100 | 256 | 2,56000000 | 0,00000156
1.000 | 4 | 0,00400000 | 0,01000000
1.000 | 128 | 0,12800000 | 0,00031250
10.000 | 64 | 0,00640000 | 0,06250000
100.000 | 256 | 0,00256000 | 1,56250000
1.000.000 | 256 | 0,00025600 | 156,25000000

Note: It lasts >40 seconds until the 32 bit counter running with 50 MHz swaps over (overflow) and then yields a negative result. Thus, using a prescaling of 2, the lowest still measurable frequency is approx. 0.05Hz.

Explanation of the pulse-pause ratio determination: the pulse-pause ration is determined by double time measuring of the high and low flank respectively. The resolution for this operation mode is fixed to 20 nanoseconds. Of course, the simple determination of the impulse length is equally possible in this operation mode.

The standard library stdlib.spi contains the functions for the communication with the type 510 slot card. Below follows a short enumeration of the related functions. The specific descriptions of these function are given in the chapter about the standard library.

Counters are set to zero by the function CounterInit and are read by the function CounterRead .

A frequency measuring is started with FrequencyInit and the result is obtained by calling FrequencyRead. The function FrequencyMeas carries out the complete measuring in one step.

The pulse-pause ratio measuring is started by one of the functions: DutyCycleHighInit or DutyCycleHighLowInit and DutyCycleRead is used to read its result. The function DutyCycleMeas reduces the implementation to one single step.

Configuration possibilities type 510 slot card:

Syntax: | Port <val> {Name "<val>"; Mode <val>;};
Port | <val> is the channel number (integer value: 0 or 1) specifying the port.
Name | <val> is an arbitrary, user-defined port name, e.g. "gas_ counter", "x-axis", etc.
Mode | <val> the channel's operation mode. Valid parameters are:
 | "impulsecounter" | - impulsecounter
 | "incrementalcounter" | - incrementalcounter (port 0 only)
 | "incrementalcounter4x" | - incrementalcounter4x (port 0 only)
 | "frequency" | - frequency
 | "dutycycle" | - dutycyle

Configuration sample type 510 slot card:

MODULE 510 { Port 0 { Name "CounterA";
                      Mode "incrementalcounter4x"; };
             Port 1 { Name "CounterB";
                      Mode "frequency"; };
           } Slot 0;

> Type 520 slotcard