Eindhoven University of Technology

MASTER

An intelligent sensor controller using Profibus

Zinken, P.J.H.

Award date: 1998

Link to publication

Disclaimer This document contains a student thesis (bachelor's or master's), as authored by a student at Eindhoven University of Technology. Student theses are made available in the TU/e repository upon obtaining the required degree. The grade received is not published on the document as presented in the repository. The required complexity or quality of research of student theses may vary by program, and the required minimum study period may vary in duration.

General rights Copyright and moral rights for the publications made accessible in the public portal are retained by the authors and/or other copyright owners and it is a condition of accessing publications that users recognise and abide by the legal requirements associated with these rights.

• Users may download and print one copy of any publication from the public portal for the purpose of private study or research. • You may not further distribute the material or use it for any profit-making activity or commercial gain ~ ICSlEB691

Technische UniversiteittUJ Eindhoven Faculty ofElectrical Engineering ICS (EB) Section of Information and Communication Systems

Master's Thesis:

An intelligent sensor controller using Profibus

P.l.H. Zinken

Id.nr.403715

Location : Ellips BV, Eindhoven, The Netherlands Coach : Ir. H.P.E. Stox Supervisor : Prof. Ir. M.PJ. Stevens ~ Period : August 1997 - July 1998 ELLIPS

The Faculty of Electrical Engineering of Eindhoven University of Technology does not accept any responsibility regarding the contents of Master's Theses. An intelligent sensor controller using Profibus E~

SUMMARY

The new fruit grading system that is currently developed by Ellips B.V. is based on a Profibus DP (PROcess FIeldBUS Decentralised Peripheral) environment. The system consists of one master computer and several intelligent slaves; an I/O controller, a weight controller, a sensor controller and a diameter- and color measurement system.

In this document the design of the sensor controller card will be discussed. The sensor controller board is a multifunctional board for the decentralised handling of position measurement, static/dynamic weight measurement, input/output control and fruit roll measurement. It features two high-resolution rotary encoders, a 24-bit sigma delta analog/digital converter, 8 isolated analog inputs and 4 isolated digital outputs.

The sensor controller board is an embedded system based on an 80C310 micro controller, it interfaces to the Profibus by a SPC4 Profibus controller. A Quicklogic FPGA is used to implement most of the Memory Management, the position decoding and to glue all other parts together.

In this design the position measurement must be as accurate as 1I20th cup. The static weight measurement is performed with a peak-peak resolution of 16 bits, so accuracy is better than 0.2 gram. Dynamic operation can be performed at 14 bits and an accuracy of better than 1 gram. (Based on a 10 kg bridge.) The input circuitry can handle most industrial encoders, proximity sensors and photo switches. The output circuitry is designed for the switching of relays up to 1.8 Ampere.

2 ~ An intelligent sensor controller using Profibus ELLIPS

TABLE OF CONTENTS

1. INTRODUCTION 6

2. CONTROLLER CONCEPT 7

2.1 OVERVIEW 7 2.2 THE FRUIT GRADING SYSTEM 9 2.2.1 Mechanical structure 9 2.2.2 Communication model 12 2.2.3 Profibus 14 2.2.4 Profibus-DP 15 2.2.5 Timing Specifications 19 3. EMBEDDED SYSTEM DESIGN 23

3.1 SPECIFICATIONS 23 3.2 DESIGN 24 3.2.1 Profibus 1nterface 24 3.2.2 25 3.2.3 Memory Management 30 3.2.4 Glue 34 3.2.5 Power-supply & watchdog 37 3.3 TEST RESULTS 38 4. POSITION MEASUREMENT 39

4.1 SPECIFICATIONS 39 4.2 ROTARY ENCODERS 40 4.3 DESIGN 43 4.4 METASTABILITY 48 4.5 TEST RESULTS 49 5. WEIGHT MEASUREMENT 50

5.1 SPECIFICATIONS 50 5.1.1 STATIC 51 5.1.2 SEMI-DYNAMIC 51 5.2 STRAIN GAUGE TRANSDUCER 52 5.3 DATA ACQUISITION 53 5.3.1 Sigma delta ADC's 54 5.3.2 Analog Devices compared to Burr Brown 55 5.4 ANALOG DEVICES AD7730 59 5.4.1 1nterfacing the weight-bridge 60 5.4.2 Configuration ofthe AD7730 62 5.5 DESIGN 67 5.5.1 Static 67 5.5.2 Semi-dynamic 68 5.5.3 Converter settings 69 5.6 TEST RESULTS 71 6. I/O CONTROL 75

6.1 SPECIFICATIONS 75 6.2 DESIGN 77 6.3 TEST RESULTS 79

3 An intelligent sensor controller using Profibus E~

7. SOFTWARE 80

7.1 PROFIBUS PROTOCOL SOFIWARE 80 7.2 SENSOR CONTROLLER SOFIWARE 82 7.2.1 Sensor Input Handling 82 7.2.2 Decoder software 83 7.2.3 Data Acquisition Software 84 8. CONCLUSIONS & RECOMMENDATIONS 87 8.1 CONCLUSIONS 87 8.2 RECOMMENDATIONS 87 9. BIBLIOGRAPHY 88

10. ACKNOWLEDGEMENT 90

APPENDIX A: NOMENCLATURE 91

APPENDIX B: PROFIBUS PERFORMANCE 92

APPENDIX C: ENCODER CALCULATIONS 94

APPENDIX D: ADC CALCULATIONS 95

APPENDIX E: SIGMA DELTA AID CONVERTERS 96

APPENDIX F: ADC COMMUNICATION 100

APPENDIX G: MMU TIMING REQUIREMENTS I04

APPENDIX H: VHDL DECODER PACKAGE 107

APPENDIX I: VHDL SOURCE GLUE 112

LIST OF TABLES

TABLE 3.1: GLUE MEMORY CONFIGURATION 35 TABLE 3.2: MMU SIGNALS OF THE GLUE 35 TABLE 3.3: I/O SIGNALS OF THE GLUE 36 TABLE 3.4: ADDITIONAL SIGNALS OF THE GLUE 36 TABLE 4.1: ELECTRICAL ENCODER SPECIFICATIONS 40 TABLE 4.2: MECHANICAL ENCODER SPECIFICATIONS 40 TABLE 4.3 : ENVIRONMENTAL ENCODER SPECIFICATIONS 41 TABLE 4.4: VENDOR SPECIFIC ENCODER SPECIFICATIONS 43 TABLE 4.5: ENCODER STATE TRANSITIONS 44 TABLE 5.1: ADC TYPE COMPARISON 54 TABLE 5.2: ANALOG DEVICES VERSUS BURR BROWN 58 TABLE 5.3: FILTER REGISTER SETTINGS 69 TABLE 5.4: MODE REGISTER SETTINGS 69 TABLE 5.5: CALIBRATION DURATIONS 70 TABLE 6.1: SENSOR INPUT CONFIGURATIONS 75 TABLE 7.1: CONTROL SIGNALS FOR THE WEIGHT STATE MACHINE 85

4 E~ An intelligent sensor controller using Profibus

LIST OF FIGURES

FiGURE 2.1: SENSOR CONTROlLER CORE 8 FIGURE 2.2: LINE SYSTEM 9 FIGURE 2.3: STATIC WEIGHT SYSTEM 10 FIGURE 2.4: ROLL SYSTEM 11 FIGURE 2.5: PROFIBUS COMMUNICATION MODEL 12 FIGURE 2.6: PROFIBUS PRODUCT GRAPH 14 FIGURE 2.7: TELEGRAM-SEQUENCE IN THE PROFIBUS-DP-SYSTEM 16 FIGURE 2.8: PROFIBUS-DP-sLAVE STATE MACHINE 17 FiGURE 2.9: PROFIBUS MESSAGE CYCLE TIME 19 FIGURE 2.10: SYSTEM REACTION TIME VERSUS N 21 FIGURE 2.11: ENCODER RESOLUTION VERSUS N 21 FIGURE 2.12: ENCODER RESOLUTION VERSUS UPDATE RATE 22 FIGURE 3.1: DESCRIPTION PROFIBUS-INTERFACE 24 FIGURE 3.2: DS80C320-MICROCONTROlLER FROM DALLAS 26 FIGURE 3.3: MEMORY-ORGANISATION OF THE MICROCONTROLLER 27 FIGURE 3.4: 80C32 -MODEL 28 FIGURE 3.5: INTERRUPT-SCHEME 80C320 29 FiGURE 3.6: MEMORY CONFIGURATION OF THE 80C31O/320 32 FiGURE 4.1: ENCODER OUTPUT SIGNALS 42 FIGURE 4.2: STATE DIAGRAM OF THE DECODER 44 FIGURE 4.3: HYSTERESIS WINDOW 46 FiGURE 4.4: SNAPSHOT OF POSITION ENCODING SIMULATION 49 FiGURE 5.2: GAUSS DISTRIBUTED P-P NOISE 56 FIGURE 5.3: GAUSSIAN DISTRIBUTION 57 FIGURE 5.4: FUNCTIONAL BLOCK DIAGRAM OF THE AD7730 59 FIGURE 5.5: AC-EXCITED BRIDGE APPLICATION 61 sT FIGURE 5.6, FREQUENCY RESPONSE 1 STAGE FILTER 62 FIGURE 5.7, FIR-FILTER RESPONSE 63 FIGURE 5.8: STEP RESPONSE FOR FASTSTEP AND NORMAL OPERATION 64 FIGURE 5.9: PEAK TO PEAK RESOLUTIONS (CHOPPING MODE) 67 FIGURE 5.10: PEAK TO PEAK RESOLUTIONS (NON-CHOPPING MODE) 68 FIGURE5.11: JAPIE 1,2,3 73 FIGURE 5.12: JAPIE4 ON THE 110 BOARD 73 FIGURE5.13:JAPIE5 74 FIGURE 6.1: IDS-UDS CHARACTERISTIC BF556c 77 FIGURE 6.2: SINGLE INPUT CIRCUIT 78 FIGURE 6.3: DC (UPPER) AND AC (LOWER) OUTPUT CONFIGURATIONS 79 FIGURE 7.1: SENSOR CONTROlLER SOFTWARE 82 FIGURE 7.3: WEIGHT MACHINE 84 FIGURE 7.2: SENSOR STATE MACHINE FOR WEIGHT 86

5 E~ An intelligent sensor controller using Profibus

1. INTRODUCTION

With this work the last step is taken for graduation at the faculty Electrical Engineering of the Eindhoven University of Technology. For the five-year curriculum it consists of a nine-month period of work in one out of five sections at either the university itself or, external, in a company.

This graduation work is supervised by the section Information and Communication Systems (ICS), it consists of two research chairs: Computer and Communication Systems and Design Technology. This work is done in labour of the section "Computer and Communication Systems", which focuses on analysis and specification methods, design, realisation, and application of digital information and communication systems. These are extremely complex systems with high communication speeds, a large number of operations per time unit, special memory structures, etc. The realisation is based on a (formal) design process, in which an optimal architecture is developed with a proper balance between hardware and software.

The choice was made to do this graduation work external, namely at Ellips B.V. Eindhoven. Ellips B.V. is specialised in designing electronic control systems, including all relevant software, for vision applications. In real time images are processed from industrial and natural products such as raw materials, fruit, vegetables, etc. Dimensions, contour characteristics, position, colour and quality are calculated in order to classify these products in terms of control parameters for the production process.

One of the systems Ellips B.V. is working on is a machine control unit for the grading of fruit and vegetables on several criteria, e.g., size, shape, weight and colour. Fruit is passing by at speeds of up to 20 pieces a second per line. In the next chapters we will discuss the design of an intelligent sensor controller board that will be part of the next generation of fruit grading systems. The sensor controller will take care of position measurement, fruit roll measurement, weight measurement and input/output control.

6 ~ An intelligent sensor controller using Profibus ELLfpS

2. CONTROLLER CONCEPT

In this chapter the concept of an intelligent sensor controller board is described and an overview is given of its functionality in the next generation of fruit grading systems using Profibus. After describing the mechanical and communication models, timing specifications will be explained. In the last paragraph a short description of Profibus is given.

2.1 Overview

The new sensor controller board is the third board to be designed for the next generation of fruit grading systems. An I/O controller and a weight controller board have already preceded it.

The main task of the sensor controller board is the measurement of cup positions in order to synchronise other processes (e.g. fruit exit-control) in the system. Further the board features fruit weight measurement, fruit roll measurement and general-purpose input/output control. In the next paragraph these functionality will be explained while an overview is given of the next generation of fruit grading systems.

Like previous controller designs, the sensor controller is based on an 80C51 embedded system featuring a Profibus controller that takes care of the lower layers of the Profibus protocol, a galvanically separated interface to the Profibus and several memory units for program code and data. Further the board contains a Field Programmable Gate Array (FPGA) for the Memory Management Unit (MMU) and to 'glue' all parts together. The board is powered by a switched supply in order to reduce power dissipation. A watchdog is used for the detection of power and software failures.

7 An intelligent sensor controller using Profibus E~

The core (as depicted in figure 2.1) of the sensor controller can be divided in the following functional blocks:

• Profibus-interface • Profibus-controller • Micro-controller • Memory units (Flash, SRAM, EEPROM) • Glue • I/O-interface • Data acquisition (static/semi-dynamic weight measurement) • Power-supply

GLUE

Figure 2.1: Sensor Controller core

8 E~ An intelligent sensor controller using Profibus LLIPS

2.2 The fruit grading system

In this paragraph we will explain the fruit grading system's mechanical structure and its communication model which is based on a PROcess FIeldBUS (Profibus) infrastructure.

2.2.1 Mechanical structure

In the grading system fruit is moving in cups from left to right over one of M (in our case: M ~ 8) lines until, after the grading has taken place and its quality is known, the fruit is led to an exit by one of the N lines. See figure 2.2.

In order to measure cup-positions, a sensor SO indicates the position of the first cup on the line and the displacement of the cups is measured either by two proximity-sensors S1 and S2 or is measured by a rotary encoder RE1 which is coupled to the line's motor. A sensor S3 is used to indicate if any stretch has occurred in the chain of the line.

-- ~ ~

,...... , r-- It--- '-" "-" r-- I'-' '-"

M I ()()c.,)() () I cCp 3 I• ()()()() () I 2 I ()()()() () I 1 I( ) ()()() () I . # # t l l # I II 0- ­- [S3] .[SO] ••[S1] [52] ~ '-- ~ ~ ~ 123 N

Figure 2.2: Line System

The goal is to report cup-locations to the master computer and to synchronise all other processing, for example the switching of exit relays.

9 An intelligent sensor controller using Profibus

All fruit that is not qualified for sale is sorted out by hand before it reaches the grading system. It is led to a delivery-line from which it is led to a weight-line where its weight is measured in order to gain information about the amounts of degraded fruit. This amount can then be subtracted from the total delivered amount of fruit in order to pay the supplier. At the end of the weight line a valve is placed to prevent fruit falling of the line.

Because of the static character of the weight measurement, the lines have to be controlled to assure an accurate measurement. A sensor initiates the weighing after detecting a full weight-line. The transducer used for the weight measurement is a standard load-cell [LC] that is placed in a Wheatstone bridge, see paragraph 5.2.

The system acts as follows: While both the delivery- and weight-line are running and the exit-valve is closed, the fruit is led from the delivery-line onto the weight-line where the fruit is collected. When the weight-line is full (indicated by the lack of pulses from a sensor [s4]) the delivery-line is stopped first, then the weight-line is stopped and after a certain debounce time the weight measurement takes place. When finished the exit-valve is opened and the weight-line is started in order to empty its cups. When, after a specified time, the weight-line is empty the exit-valve is closed and the delivery line is started. Now the whole process is repeated again. See figure 2.3.

Full-Sensor [54] Valve 41> ~~ •~ .. ~ .. lrcJ "Delivery" ¥~--'-W-e-ig-h-t"~~~'"~

Load cell [Lc] Start/stop

Figure 2.3: Static Weight System

10 An intelligent sensor controller using Profibus

When measuring colour, the fruit is rotated with a certain speed in order to get an accurate measurement. In the old grading system the fruit rotation was closely coupled to the system's line motor. In the current system this speed can be independent of the machine's line speed because a separate motor drives it. This way a more flexible system is achieved. An incremental encoder [RE2] that is attached to the motor takes care of the rotation speed measurement. See figure 2.4:

oCoI"C••m

Rotation Encoder [RE2]

Figure 2.4: Roll system

11 E~ An intelligent sensor controller using Profibus LLIPS

2.2.2 Communication model

The communication model of the new fruit grading system is outlined in figure 2.5. The general idea is that maximum flexibility must be offered to any customer using this system. Therefore, the system's architecture includes communication to the outside world. This way remote diagnoses and service of the system is possible, which is convenient when the actual factory is somewhere abroad. For example: the software of any device attached to the system can be updated from anywhere in the world by using the modem connection. The grading system consists of several intelligent controllers and measurement systems that are all attached to one of two Profibuses. See paragraph 2.2.3 for a brief description of Profibus. One bus is used for peripherals that require fast data­ exchanges (token rotation lOms) in short messages (32 bytes data length), and the other one is intended for devices that will produce

Windows Windows

Sensor

Vl Vl ColorO :l :l ..0 ..0 I/O ~ ~e a...e a...

Colorl Weight ~ co V) => V) co =>co

Figure 2.5: Profibus communication model

12 E~ An intelligent sensor controller using Profibus LLIPS data at a slower rate (token rotation lOOms) but with more information (256 byte data length). Bus A (slow) is located in the systems 19" rack, while bus B (the fast one) is distributed over the line system. Only one master computer controls all devices. This master computer is based on a real time operating system with the Profibus hardware in it. The master detects each new attached device and configures it according to the user's specifications. During operation the master receives information of all devices attached to the busses in order to completely control the grading process. The grading system features the following devices [1]:

~ sensor controller • detects cup-positions, performs roll- and 'static' weight measurement ~ weight controller • dynamically measures the weight of the cup and its contents ~ I/O-controller • switches relays on and off to let the cups drop their contents ~ diameter measurement unit • measures the diameter of the fruit by means of a camera ~ colour detector • detects the colour of the fruit inside the cup

Because the diameter measurement and the colour detector require only one data transfer for every cup but must be able to send complete images to the master computer, these devices are attached to the slower Profibus. The sensor controller generates more than one message for each cup and thus must be connected to the fast bus. The I/O-controller is used for dropping the contents of the cup, but is suited for any switching purpose. Therefore, switching at higher rates is also provided and the I/O-controllers are also connected to the fast bus. The weight controller might be attached to both busses since it requires only one message per cup but does not need to send large messages. For the moment we will leave it attached to the fast Profibus connection.

A unique number, the envelope number, will indicate every row of cups. Once a row of cups, maximal eight, passes a device, the master computer will indicate that device to start its measurement and will tell the device the envelope number of that row of cups. All devices will send their measurement results (e.g. weight or diameter) to the master computer, accompanied by the envelope number. The master computer stores all the information of the cups of that envelope, until it has all the information needed to send the contents of a cup to a certain exit. At the exits a semi-dynamic measurement of the fruit weights can be carried out. This involves a simple and straightforward manner to sort fruit to a desired amount.

13 ~ An intelligent sensor controller using Profibus ELLIPS

2.2.3 Profibus

Nowadays automation systems are successfully established with fieldbusses. The main advantage of using fieldbusses is that information can be easily exchanged between the main system and its (distributed) devices in the field. Since fieldbusses operate from only two wires the costs of cabling can be drastically reduced. Today there are several types of fieldbusses, some of them are INTERBUS-S, P-NET, CAN, PROFIBUS and WorldFIP [1]. Only few busses in the range of fieldbusses are standardised in Europe (EN 50170), these are PROFIBUS, P-NET and WorldFIP.

For our application the choice was made to use PROFIBUS since it is the fastest standardised fieldbus, it supports speeds up to 12 MbiUs and according to several studies (CONSULTIC, PNO) it is the fastest growing standard in this area. At the moment there are more than 1200 Profibus-DP, PA and FMS products and services available from a broad range of manufacturers. As can been seen from the graph below, the number of Profibus-DP products is the fastest growing. (Source: PNO, 1998)

PROFIBUS·DP iR::.ttfrc;tioft of "'\ j PROFIBUS·OP ) ~~~~~~;;~~~\ OIN 1~245 p.rt 3, DIN 1'245 or' 4/ I ..... lROFIBUS.FMI f. •• Shart of FMS/ DP Clnbl Devlal

91 92 93 94 95 96 97

Figure 2.6: Profibus product graph

The Profibus standard specifies three kinds of communication protocols, namely Profibus FMS, PA and DP. From these standards only Profibus DP (Decentralised Peripheral) can achieve 12 MbiUs, Profibus FMS (Fieldbus Message Specification) and Profibus PA (Process Automation) have maximum speeds of 1.5 MbiUs respectively 31.25 kbiUs.

Profibus DP is the fastest because its protocol is based on the lowest two layers (physical, data link) and the application layer of the OSI model, leaving out the other layers [2]. In the Profibus specification the data link layer is called Fieldbus Data Link (FDL) layer.

14 An intelligent sensor controller using Profibus E~

2.2.4 Profibus-DP

In this paragraph we will discuss the functions of masters and slaves in the Profibus DP system. At the end of this paragraph the advantages of the use of Profibus DP will be summarised.

Profibus-DP Master

Two kinds of masters are possible in Profibus-DP [2]. The first one is a master of class 1 and the other one a master of class 2. A master of class 1 polls the associated slaves cyclically to submit data to its local users. A master of class 2 requests or sends a-cyclically messages with masters and slaves. A master of class 2 is used as a programming- and/or management-system. In a realistic system it's possible that one master acts as a master class 1 as well as a master class 2.

Functions of a master class 1 are:

• Initialization of the DP-system • Parameter-assignment and configuration of the dedicated DP-slaves, if parameterization and configuration were okay then data-exchange-mode can be entered, otherwise the slave will be made inactive • Cyclic data-exchange with the DP-slaves, this is done by polling all slaves sequentially • Monitoring of the DP-slaves • Fetching of diagnostic information from the DP-slaves (if errors occur)

Functions of a master class 2:

• Commissioning of new active stations • Down- and upload of parameters from and to other masters • Checking of the configuration of slaves • Downloading of in- and output-images of DP-slaves

A master communicates in four modes with the slaves:

~ Off-line • No communication at all between a master and his slaves. This is the starting phase when the system is booted up. ~ Stop • There's no communication between the master and his slaves, however a master of class 2 can read out diagnostic information of a class 1 master.

15 An intelligent sensor controller using Profibus E~

~ Clear • This mode is the first real communication with the slaves. The slaves are parameterised and configured. If all went well the data-exchange-mode can be entered. In this state "OOH" is sent as output indicating that the slaves are still to be inactive in processing outputs. ~ Operate • Now the master can cyclically exchange data with the dedicated DP-slaves. Every slave is polled in a sequence. Each slave can receive output-data and send input-data to the master in one poll-cycle. Ifan error occurs at the slave then this will indicated to the master with a high-priority telegram.

An example of a poll-cycle is depicted below:

> I Trailer I Output-DATA I Header I

DP-SLAVE DP-MASTER Immediate Respons 1

Trailer Input-DATA I J r Header I ~

Figure 2.7: Telegram-sequence in the Profibus-DP-system

The master will always start in off-line-mode (power-up). After this the following sequence has to be made to enter the productive (i.e.: operate) mode:

Off-line -+ Stop -+ Clear -+ Operate

Furthermore to assure the correct timing in the DP-system, the master (de-) activates the watchdog-timer of the slave. Ifthe master doesn't communicate with the slave within the specified watchdog-time (defined in the parameter-telegram) the slave will assume that a serious (fatal) error has occurred (for example a power-failure or line­ break). Ifthis happens the master has to parameterize and configure the slave in order to let the slave enter the data-exchange mode again.

16 An intelligent sensor controller using Profibus E~

Profibus-DP Slave

A slave in the Profibus-DP system can be interrogated by a master of class 1 as well as by a master of class 2. A description of DP-slave communication is shown in below figure that presents the state-machine of the slave. Every ellipse in the picture is a state and every arrow is an event that directs the slave into a possible state.

SLAVE_Diag GET_CFG

CHK_CFG,NO OK SET_PRM, NO __---I SLAVE_Diag OK SET_PRM GET_CFG

Figure 2.8: Profibus-DP-slave state machine

We'll start from the upper edge with the first phase: 'Power-On' mode. Only in this state an address-change-request is permitted only from a class 2 master. If the slave supports this changing of the station-address, it shall have non-volatile memory on board. After this state the slave will go in wait-parameter-mode.

In the state 'Wait-Parameter' the slave will await the arrival of parameter-telegrams or get-configuration-telegrams. All other kinds of telegrams are denied in this phase and data-exchange is not possible. Diagnostic information is requested before the 'Data­ Exchange' mode is entered.

17 An intelligent sensor controller using Profibus E~

After the 'Wait-Parameter' state, the 'WaicCfg' state is entered. The slave expects configuration-data from the master to check whether the master knows the length, sort and consistency of the exchange-data the slave expects. A master of class 2 can ask for the configuration of a slave by a GeCCfg-request. After the master has received the configuration of the slave, it will be send back to the slave in order to check for correctness.

After these two last states are approved, the data-exchange-mode will be entered. In the 'Data-Exchange' mode the real data is exchanged (Le.: slave's in/output). During this state diagnostic information can be requested by the master if the slave indicates an error to the master with a high-priority telegram (this is indicated in the FC-octet together with eventually input-data from the slave).

The images of the inputs and outputs of a slave can be requested by every master. However the exchange of data from master to slave such that the slave has to process it, is only possible by the master that has parameterized and configured the slave before.

Advantages using Profibus:

Evaluating the system using Profibus DP as its communication protocol reveals that it has several advantages over the old fruit grading system.

Advantages of this new Profibus architecture are:

• only two twisted-pair cables necessary instead of two wires for every device, often resulting in several kilometres of wire • higher speeds possible since the Profibus standard supports bit rates of 12 Mbit/s • easy adding and removing of devices to the system • easy update of software of each device via the modem-connection and Profibus • connectivity of any third-party device designed for Profibus

18 An intelligent sensor controller using Profibus E~

2.2.5 Timing Specifications

Timing is vital in fieldbus applications, particular in the case of our fruit grading system. The system must be able to respond within a certain amount of time to commands issued by the master computer. This is called the System Reaction Time. We shall examine the reaction time for Profibus systems in this paragraph. We first define the Message Cycle Time, TMe, which is the time that elapses between two consecutive transmissions of a Profibus master station. Figure 2.9 illustrates the Message Cycle Time[l],[2].

Master Station Slave Station Master Station

I Send / Request 1 ----~I__R_e....:.sp_o_ns_e_1 ~ Send / Request 2 I

~f---T-S-IR----"~TTD+TSDR~--T-AIR-~~ TTD+Till ~

.~------~ TMC

Figure 2.9: Profibus Message Cycle Time

The Message Cycle Time is therefore defined as:

(2.1)

Where all times are in bit times (TBIT = 1 / bit rate) and

TSIR = Transmission time of the action frame = a . 11 bits, a is the number ofUART-characters to send TAIR = Transmission time of the response frame =b . 11 bits, b is the number of UART-characters to send TS DR = Station Delay Time of Responders, time that elapses between request and response TID Idle Time, time that elapses between response and new request TTD = Transmission Delay Time, time that elapses on the transmission medium between transmitter and receiver when a frame is line length (m)' bit rate (bit/s) b' transmitted, T - It TD- 2· 108 (rn!s)

The System Reaction Time is determined from the Message Cycle Time. Suppose we have one master and np slaves in our system. Furthermore, the maximum amount of retries for a message is mp. The System Reaction Time is:

(2.2)

19 E~ An intelligent sensor controller using Profibus

TMc,RE~ is the message cycle time for a retry. We shall assume that this is the same time as the normal Message Cycle Time.

In our fruit grading system two timing values are important. We must be able to switch the relays within a certain amount of time to ensure that fruit will leave the system at the correct exit. The time between two consecutive polls of a relay is the same as the System Reaction Time if we assume that all relays are listed once in the master's Poll List. The second important timing is the time between two consecutive polls of the encoder card (read sensor controller) in order to detect cup positions. To guarantee the required accuracy, the encoder must be polled more than once between two consecutive relay polls to give the exact conveyor position. This means that this card must be listed more than once in the Poll List. Unfortunately this is not possible in Profibus DP, therefore in the current design we will also need to access the FDL­ layer directly. In future Profibus DPe (DP extensions) will be implemented, which allows the a-cyclic polling of slaves.

The desired specifications are that at a speed of 20 cups per second the system must be able to control the relays with an accuracy of l/5th cup. This means that the System Reaction Time must be less than 10 milliseconds. The encoder precision must be 1I20th cup at the same speed, so the time between two consecutive encoder polls must be less than 2.5 milliseconds.

Suppose the Poll List is set up in such a way that the master polls n other slaves, then the encoder, then again n other slaves, the encoder again and so on, until all slave stations are serviced. Assume furthermore that the relays are polled with an SD2­ frame containing 4 user bytes, thus 13 bytes total. The response of each relay is simply an acknowledgement with a SC-message of 1 byte. The weight controller has also 13 bytes in its action frame and uses a total amount of 29 bytes in the response SD2­ frame. The encoder needs a 6-byte SD1-frame and a 13-byte SD2-frame for its response. The Message Cycle Times for each device can be calculated from equation (2.1). For a description of the frame formats see [1], [2]. The total Message Cycle Time is:

TMC, TOTAL =nr .TMC,RELAY +TMC,WEIGlIT +In:1, TMC,ENCODER (2.3)

Where:

Nr = The number of I/O-controllers in the system Np = the total number of slaves in the system N = the number of slaves polled between two encoder polls

The System Reaction Time TSR can then be determined from (2.2). The time between two consecutive encoder polls is given the next formula:

20 An intelligent sensor controller using Profibus E~

(2.4) TSENSOR =Inpn-1l

Figures 2.10 and 2.11 show what the impact is of changing n with respect to the System Reaction Time and the encoder resolution for various bit rates, for a system containing one master, one encoder, one weight controller and 28 I/O-controllers.

~ 50 -,------, l/) E 45 -; 40 E -+-0,5 MbiVs ii' i= 35 _1,5 MbiVs c 30 ~ 25 ---J!r-3 MbiVs g 20 -X-6MbiVs I Gl

ex: 15 1 12 MbiVs ~ 10 ~5f==::::;~===a~~~~~~ l/) 0 +-__-+-__--+ -I---__~ 1 3 5 10 15 n

Figure 2.10: System Reaction Time versus n

12 -,------. 11O c I-+-0,5 MbiVs .S! 8 'S _1,5MbiVS ~ 6 ---J!r-3 MbiVs I Gl ex: """,*"",6 MbiVs I ~ 4 "C ~___ 12MbiVs I o ~ :~~~~§§~~~~!=~::T 1 3 5 10 15 n

Figure 2.11: Encoder Resolution versus n

~ ~ To meet the requirements of TSR 10 ms and TENC 2.5 ms, the bit rate should be at least 1.5 Mbitfs for this system, and the encoder should be polled after 8 other slaves, thus n=8. Tables with the calculated timing parameters, produced with Excel, can be found in Appendix B.

21 An intelligent sensor controller using Profibus E~

Since we use a bitrate of 12 Mbit/s we can see from appendix B that the System

Reaction Time TSR is 3.2 ms and the total Sensor Controller's Resolution TENc is 0.8 ms. So for two measurements (position and roll) the Sensor Controller's resolution has to be 0.4 ms.

Because we use reply update communication for the transfer of position information, theoretically the effective resolution (in cups) of the position measurement (paragraph 4.1) is dependent on the rate at which the position information data is updated.

Eff.resolution = cps' Tupd (2.5)

Where: cps cups per second Tupd Position update rate

0.09 -,.------, 0.08 0.07 .§ 0.06 'S 0.05 \ 10 cups/s '0 0.04 ..:ll t • 20 cups/s == 0.03 Cll 0.02 0.01

O~..:....,...... ,...... ,__r_.,...... ,.__r_.,.....,.....,.... _ __r_...... ,..__r_...... ,..__r_,.....,...... ,...... I

(Tupd / 100) ns

Figure 2.12: Encoder resolution versus update rate

As can be seen from above table, the resolution is within the required accuracy of 1I20lh cup at update rates below 2.6ms. This is with 1 cup per rotation, with 10 cups per rotation the resolution is 10 times lower at the same update rate.

22 E~ An intelligent sensor controller using Profibus LLIPS

3. EMBEDDED SYSTEM DESIGN

In this chapter the design of the embedded system will be discussed. First the desired specifications for the system will be formulated. Then the design is discussed and finally test results will be evaluated.

The sensor controller should, as stated earlier in chapter 2, act as a slave in the Profibus DP environment so all communications are restricted to this protocol. Because Profibus DP makes use of Decentralised Peripherals, the sensor controller should be intelligent in order to handle dedicated processes and communicating only with the master to initiate processes and deliver results.

3.1 Specifications

The main task of the system is position measurement, while the other functions are implemented so the board can be used in a broader range of applications. The idea is that this board has to be much cheaper than the previous boards (I/O, Weight) and that it can be used instead whenever the required specifications are less demanding.

The embedded system as already described in paragraph 2 .2 should meet the following requirements:

• Galvanic connection to Profibus • ESD-proof (Electro Static Discharge-proof)

• Support Profibus DP communication protocol (12 Mbit/s) • Support Direct FDL access • Support remote updates

Also (as seen in paragraph 2.2) the sensor controller needs to implement the following functions:

• Position measurement • Fruit roll measurement • Static weight measurement • Semi-dynamic weight measurement • I/O control

In the next paragraph we will start describing the design of the blocks that are part of the embedded system design.

23 E~ An intelligent sensor controller using Profibus

3.2 Design

In this paragraph we will give a brief description and only discuss changes and extensions to parts of the embedded system that were used by the I/O controller and Weight controller board [1], [2].

3.2.1 Profibus Interface

The standard interface connection that is described in all Profibus specifications is shown in figure 3.1.

...lIllIl lll.... PROFIBUS-DP Shielded/Isolated Profibus- RTS RTS Controller ~ I... ,... , OPTO-CPLR 1 INV I'" i I'" TxD-enable ...... RxD .J UART OPTO-CPLR ,.. "I I ~ .. RS-485 , ,- DRIVER I... I... TxD I ~ I OPTO-CPLR I I'" 1_-I _ "'IIIlII III"""

Figure 3.1: Description Profibus-interface

In above figure we see that opto-couplers are used to establish a galvanic isolation towards the Profibus controller's UART. The opto-couplers prevent disturbances from the hardware to occur at the Profibus controller and therefore disturbing the whole system.

On the other hand the circuitry should be protected against Electro Static Discharge (ESD) and any transients occurring on the Profibus. In order to stay below the specified maximum capacitance of the Profibus (30 pF/m), the capacitance of the protection device should be low. The Harris SP723 is a low capacitance (5 pF) electronic protection array, used for ESD and Over-Voltage protection. Up to six lines can be protected. Also care should be taken not to corrupt the RS-485-driver's common mode range (for the ADM1485: ­ 7 to +12 Volt). Shifting the SP723's input voltage levels with zener diodes assures this.

24 An intelligent sensor controller using Profibus E~

3.2.2 Microcontroller

The Sensor Controller board will be the third board for the new fruit grading system since it is preceded by the I/O Controller and the Weight Controller. In order to achieve backward compatibility it is convenient to use the same microcontroller on all boards. The choice of an appropriate microcontroller depended on several aspects.

Main selection criteria were:

• 8 bit databus microcontroller because of the simple functions • no critical speed (enough to control inputs / outputs / weights) • watchdog (in case of power/software failures) • easy interfacing with a Profibus controller • low price (8 bit is cheaper than 16 bit) • number of ports (depends on how many control-lines are needed) • serial communications-protocol (UART and SPI) • software-compatibility with a standard 8051 • number of pins (design of PCB easier) • Flash-memory preferable instead of other (EEP)ROM (code uploads via Profibus)

Because some experience is available at Ellips BV with the 8051-family, the 80C32 was chosen. Also this processor is recommended for the interface to the desired Profibus controller.

Unfortunately, after evaluation of the processor performance on the I/O-board, it was clear that the required timing requirements were not met. The problem is that the interrupt handling is too slow, this occurs whenever the Profibus controller receives an indication and the microcontroller has to deliver the required (position) data. In order to assure the required response times (see paragraph 2.2.5) the system should be (at least) twice as fast as the old configuration.

Although it should be possible to speed up the lame part of the software (SPC4­ communcication), this is not easy since this part is written by a third party (TMG­ itec). Besides the fact that it is very time consuming, rewriting the code would probably not yield the required improvement in speed. In order to speed up the system it is necessary to replace the 80C32 by a faster microcontroller that has to be compatible with it in order to support the previous hardware and software.

Dallas Semiconductor manufactures such , namely the DS80C31O and DS80C320, which are fast 80C32 (pin) compatible microcontrollers.

25 E~ An intelligent sensor controller using Profibus

By redesigning the processor core, wasted clock- and memory cycles have been removed, yielding a speed improvement of about 2,5 (at the expense of an increase in microcontroller-costs by factor 5). This should be sufficient for our application.

While the DS80C310 only features more , the DS80C320 additionally has a second serial port, a programmable watchdog and a powerfail interrupt. The most speed improvement is gained from the dual data pointers, speeding up block data memory moves.

Because of the increased speed, attention should be paid to the timing requirements of the memory interface. For this purpose the DS80C31O/320 provides speed-adjustment in order to slow down off-chip data memory accesses when using slower memory.

The 80C31 0/320 is fully compatible with the well-known micro-controllers 80C51 and 80C32, featuring additional hardware (bracketed numbers for 80C32 specs). It contains a 256-byte scratchpad RAM, four 8-bit I/O-ports, three 16-bit timer/counters, 13 (7) sources of 3 (2) priority level interrupts and 2 (1) serial ports. All extra hardware is accessed via new special function registers.

Figure 3.2: DS80C320-microcontroller from Dallas

Because both the 80C310 and 80C320 are compatible with the 80C32, in the next paragraph a global description will be given of both controllers, indicating the differences between them. The memory-organisation is described and the interrupt model will be explained. For further detailed information, please refer to the datasheets [16], [17].

26 An intelligent sensor controller using Profibus E~

Functional description

Port 0 is used as a multiplexed address/data-bus. Asserting ALE results in sending an address to an external latch. As ALE goes low, the address is latched and data can be send. Port 2 is used as the upper 8 bit address-bus. The 80C310/320 from Dallas has no program-memory on board. The read- and write-control-lines are used to transfer data from and to external memory. PSEN is used to fetch program-code from EEPROM or Flash-memory. An USART can perform serial communication with other devices. Also two timers are available to the user for counter/timer-purposes.

The memoryworganisation of the microcontroller

This micro-controller doesn't have any program-space internal, but instead all program-space is accessed outside. The memory-model of the controller is showed below:

External Ext.rncl

OOOOH OOOOH '------y----./ '------v------' '~---v".------' "Code Space" "Data Space" "Internal Data Space"

Figure 3.3: Memory-organisation of the microcontroller

Because the 80C31O/320 doesn't have any internal code-space. Up to 64KB ROM and 64KB RAM can be externally addressed by using the EA-signal. Also internally some space is reserved for SFR's (Special Function Registers). The registers, except the program counter and the four general purpose register banks, reside in the special function register area.

The 27 Special Function Registers (SFRs) include pointers and registers that provide an interface between the CPU and the other on-chip peripherals. All SFR-addresses with address bits 0-2 at zero are bit-addressable. (E.g. 80H)

27 An intelligent sensor controller using Profibus E~

The interrupt-system of the microcontroller

Timor 0 Ovorflow .-"0 .....0

ETO IE. 1

Timor 1 Ovorflow .-"0 .....0 TCON.O H1 1E.3

~ 1 .-"0 .....0

ET2 IE.o EXEN2 T2CON.3 ~ 1 .-"0 .....0 USART ES IE.4

P3.2/ INTO .....0 EXO ILO

P3.3/ INT1 .....0 ITl EX1 EA PX1 TCON.2 IL2 1E.7 IP.2

Figure 3.4: 80C32 interrupt-model

From figure 3.4 we see that the 80C32 supports six maskable interrupt-sources with a two-level priority. The 80C320 adds 7 interrupt-sources to this scheme, extending the priority to three levels, where high priorities are commonly used for time-critical applications. The 80C31O has the same scheme as the 80C320 except for the Power Fail Interrupt (PFD, the 2nd Serial Port Interrupt (SCONl) and the Watchdog Toggle Interrupt (WDTl).

The interrupts can be level sensitive or event sensitive. All settings can be made by using the special function registers.

28 An intelligent sensor controller using Profibus E~

Below table summarises all interrupt sources of the 80C310/320:

NAME DESCRIPTION VECTOR NATURAL PRIORITY OLD/NEW PFI Power Faillnterrupl 33h 1 NEW INTO Extemallnlerrupl 0 03h 2 OLD TFO limerO OBh 3 OLD INTl Extemallnterrupll 13h 4 OLD TFl limer 1 lBh 5 OLD SCONO TIO or RIO from serial port 0 23h 6 OLD TF2 limer 2 2Bh 7 OLD SCONl Til or Rll from serial port 1 3Bh 8 NEW INT2 Externallnterrupl 2 43h 9 NEW INT3 External Interrupt 3 4Bh 10 NEW INT4 External Interrupt 4 53h 11 NEW INT5 Externallnlerrupt 5 5Bh 12 NEW WDTt Watchdog lime-out Interrupt 63h 13 NEW

Figure 3.5: Interrupt-scheme 80C320

The Power-fail interrupt (PFI), if enabled, always has the highest priority. The two remaining priority-levels are user selectable high or low. All other new interrupt­ sources have a lower natural priority than the original (80C32) ones.

29 E~ An intelligent sensor controller using Profibus

3.2.3 Memory Management

The memory management consists of the configuration of the memories for the 80C310/320 and the configuration of the memory located in the glue.

Memory Configuration of the 80C310

The microcontroller will need non-volatile memory for storing its program-code. Also Static RAM (SRAM) is needed for storing variables. We could use an EEPROM as program memory, but this would be inconvenient with respect to remote software updates. For a fruit grading system abroad this would mean that a new EEPROM has to be shipped every time the software is changed. Flash memory has the advantage that the processor itself can program it. After power on, the controller will transfer its program from Flash memory to SRAM and run from SRAM afterwards. Ifthe master computer sends new software, the host controller will store it in Flash memory, from which it can boot. This provides a very flexible service for upgrading the system's software, since the actual program code can be send to the master station over a phone line using modems.

The memory-module can be divided into three parts:

1. SRAM 2. EEPROM 3. Flash-memory

The SRAM is addressed via the glue-logic and micro-controller to store variable data and new program code for the Flash-memory. Also the stack from the micro-controller can be located here if wished.

Aspects to consider when selecting a type of memory are: price, speed, second sources, compatibility, availability and memory size (32Kbytes or more needed for SRAM)

Several manufacturers produce SRAM memory, some of them are Samsung, Hitachi, UMC, Toshiba, Cypress and others.

30 ~ An intelligent sensor controller using Profibus ELLIPS

The Flash-memory is used to hold the complete sensor-controller software. Also specific parameter-data can be stored here, for example the Serial Number which is used for identification of the sensor-controller. To assure that it is possible to download new firmware, a boot-sector-program is always present in the lowest 16K-part of the Flash-memory. This program includes only the most elementary communications-code, capable to download new code over the Profibus with the ASIC and Profibus-DP protocol.

Several Flash-memories are available, but not all of them are programmable in a trivial way. The most convenient way is to program the memory by software, without the use of additional hardware. A lot of Flash-memories need a 'high' voltage for programming the device, but a few Flash-memories can be programmed by the same 5-Volt voltage that is used for its power supply. This eliminates the need for additional hardware. Manufacturer AMD has introduced some Flash-memories that can be programmed with a voltage of 5 Volt. The minimum size of these Flash­ memories is 128Kbytes. These Flash-memories have the possibility to erase whole blocks (sectors) of memory at once. Also very straightforward programming-software is presented with it. Second sources for this device are from ATMEL and Toshiba.

An EEPROM is used to store the actual station-address of the device. The EEPROM is connected to the microcontroller via a Serial Protocol Interface (SPI), which is a protocol standardised by Motorola. SPI consists of three lines; one line provides a clock-signal, while the other lines are used to transmit the data and address. In this way the EEPROM is quickly addressable and is less complex to program than the Flash-memory.

The microcontroller can perform all actions if it is able to choose from one of three memory configurations, shown in figure 3.6. The left side in each memory block is program memory, while the right side is data memory.

After power-on the host will start in the boot-configuration, in which it will run its program from Flash-memory. The Flash memory is 128kB and only the lower 64kB will be used in this state. The processor will start running from address 0 and this is where its "survival code" is located. This piece of code allows the host to download new software over the Profibus. In this way, the system will always run, even if by accident the rest of the host software is erased.

31 An intelligent sensor controller using Profibus E~

The upper 64kB of the Flash memory is used in the nonnal-configuration. This allows the host to run a different program by simply switching the memory configuration. The lower 64kB of the Flash-memory can for example be filled with the "survival­ code", while the actual encoder functions are located in the upper 64kB of the Flash­ memory.

The memory mode can be controlled (read/write) by a special register in the Glue, while the Flash bank is selected with a write-only register in the Glue.

Bus arbitration is necessary, since only one multiplexed data/address bus is used to address the Flash memory, the SRAM, the SPC4 and the micro-controller. Furthermore, the different memory modes imply that program instructions are fetched from both SRAM and Flash-memory. Access control of the appropriate chips is also managed by the Glue logic.

The figure below shows the three memory configurations of the 80C3l0/320.

FFFF FFFF FFFF GLUE GLUE GLUE F cooo F cooo cooo L L Flash- A A bank S IX8000 S IX8000 8000 H H

0 RAM 1 RAM RAM RAM

ooסס ooסס ooסס

Boot Normal Update

Figure 3.6: Memory Configuration of the 80C310/320

The MMU on the I/O board and the weight board was established conventionally, namely chipselect was operated by an adresdecoder in the glue, read and write control signals were shared for the data memory and PSEN was used for the program memory. Also the demultiplexing of data/address was done in the glue.

When using the Dallas DS80C3l0/320, this MMU does not meet all timing requirements because the memory interface is too slow (see Appendix G).

In order to win some time, all devices' chip selects should be tied to the appropriate levels in order to be continuously asserted. Then we make use of separate read/write signals for each device. This saves up to l5ns resp. 20ns for the SRAM and the Flash.

32 E~ An intelligent sensor controller using Profibus

Although the SPC4 is too slow, this is simply solved by using the Dallas' feature for stretching read/write operations. A stretch value of I should be sufficient. See appendix G.

When fetching program code the MMU should decide whether to access the Flash or the SRAM. The signal PSEN controls this flow. Dependant on the provided address either the Flash or the SRAM has to be selected. Since the chipselects are all asserted an active PSEN signal will always access the Flash first. However when the address falls in the SRAM area a fast switch has to be made.

The read and write signals should be delayed and should not become active before the correct address is valid. In case of reads this isn't very important because the correct value will be read at the end. But in case of a write, (code) data can be corrupted.

From appendix G we see that the address latch has critical specifications, the propagation delay should be low (around IOns), because the more propagation delay the less time remains for the memory access. Also the hold time should be less than 3ns because PSEN can become active already 3ns after ALE has become inactive. This means we have to place the latch outside the glue. With a fast latch (74VHCT573) this timing is assured.

When the read/write signals are delayed by IYz-clock cycles, it is assured that the address will be valid before the actual action is carried out. Also the read/write signals should become inactive whenever the original read/write has become inactive, this way its pulse width stays within the specified ranges.

When implementing the MMU in the glue it is highly recommended to fix the read and write logic near to each other to keep the propagation delays as low as possible. See appendix I.

33 E~ An intelligent sensor controller using Profibus

3.2.4 Glue

The glue is used for the implementation of the Memory Management Unit (MMU), the position decoding logic and all supplementary hardware. Its functionality is described with VHDL and implemented in a Quicklogic pASIC, type QL 2003 QPFIOOC. See appendices H and I.

The following table summarises all registers and their addresses, located in the glue:

Address ReadlWrite Function COOO-DFFF - Not Used EOOO-E5FF RIW SPC4 dual ported ram E600-EFFF - Not Used FOOO W Memory Mode: OOh - Boot Olh- Normal 02h- Update FOOl W Flash Bank: 0-7 The number of the Flash bank that will be mapped in data memory at 8000h-BFFFh in memory mode Update. F002 R Slave address of Sensor controller as set with the switches F003 RIW Output register: (1=active, O=inactive) Bit 0: Solid Output 0 Bit I: Solid Output I Bit 2: Solid Output 2 Bit 3: Solid Output 3 Bits 4-7: 0 F004 RIW Interrupt register: Writing a zero to the bit resets it (* no interrupt generated). Bit 0: 1 = General Purpose Interrupt Bit 1: 1 = Position AddWin Interrupt Bit 2: 1 = Position SubWin Interrupt Bit 3: 1 = Position Zero Indication * Bit 4: 1 = Latch Command Bit 5: 1 = Roll Addwin Interrupt Bit 6: 1= Roll SubWin Interrupt Bit 7: 1 = Roll Zero Indication * F005 R General Purpose Input register: Bit 0: Digital input 0 (Ap I Sdisp I I Sfull) Bit I: Digital input I (Bpi Sdisp2) Bit 2: Digital input 2 (Cp) Bit 3: Digital input 3 (Ar) Bit 4: Digital input 4 (Br) Bit 5: Digital input 5 (Cr) Bit 6: Digital input 6 (SO) Bit 7: Digital input 7 (Sr)

A description of the interrupt register is given in paragraph 4.3

34 E~ An intelligent sensor controller using Profibus

F006 RIW GPI-interrupt-mask Bit 0: Digital input 0, (l=enable, O=disable interrupt) Bit 1: Digital input 1 Bit 2: Digital input 2 Bit 3: Digital input 3 Bit 4: Digital input 4 Bit 5: Digital input 5 Bit 6: Digital input 6 Bit 7: Digital input 7 F007 R Bits 0-3 : RollCounter-MSB-value (bits 8-11) Bits 4-7 : PositionCounter-MSB-value (bits 8-11) F008 R PositionCounter-LSB-value F009 R RollCounter-LSB-value FOOA RIW Counters Mode Register: (1= enable, 0 = disable) Bit 0: Position count reset at zero-pulse Bit 1: Roll count reset at zero-pulse FOOB-FFFF - Not Used

Table 3.1: Glue memory configuration

The design of the MMU can be derived from above table and the design of the position decoding from paragraph 4.3.

The glue consists of the following in- and outputs, grouped by its functionality:

Signal: Port type: Description: AD7...ADO in/out Multiplexed address and data A7 in...AO in in 8 lower address lines A8 in...All in in Address lines for ITAG purposes A15 in...AI2 in in Address lines for register addressing A16 out. ..A14 out out Address lines for MMU bankswitch WRN in Memory-write from uC RDN in Memory-read from uC PSEN in Strobe for code reads from uC RDN_FLASH out Read signal Flash RDN RAM out Read signal SRAM RDN SPC4 out Read signal SPC4 WRN FLASH out Write signal Flash WRN RAM out Write signal SRAM WRN SPC4 out Write signal SPC4

Table 3.2: MMU signals of the glue

35 ~ An intelligent sensor controller using Profibus ELLIPS

Signal: Port type: Description: OUTO...OUT3 out Outputs to solid state switches GPIO...GPI7 in Inputs from the sensors GLUE INTN out Interrupt from glue to J..lC

Table 3.3: I/O signals of the glue

Si~nal: Port type: Description: CLK 2 in 24 MHz from SPC4 RST m reset logic in glue RST ADC in reset AID Converter RSTN OUT out active low reset 10 0...10 6 out slave address sensor card

Table 3.4: Additional signals of the glue

The Memory Management takes care of redirecting all accesses to SRAM, Flash, EEPROM, SPC4 or the registers in the glue. Because the SOC31 0/320 has a multiplexed data/address bus, demultiplexing is necessary. As stated earlier this is done with an extemallatch.

For the processing of the inputs and outputs the glue provides registers to store actual values, for the inputs an interrupt is generated every time an input-value changes. An interrupt mask register is provided in order to mask interrupts when using rotary encoders.

The glue further consists of the rotary decoding logic and conversions from active high to active low of some signals. See appendices H and I.

36 ~ An intelligent sensor controller using Profibus ELLIPS

3.2.5 Power-supply & watchdog

Together with the Profibus-twisted-pair-cable, a power-line with a DC-voltage of 24­ 60 Volt is distributed over the system. This power-line can be used for powering slaves and other devices. Because the Profibus power-line is only defined within this range, care should be taken when using this line to power any devices. Also several industrial devices (e.g. proximity sensors and optical encoders) need to be powered with less than 24 Volt.

The control-logic and the Profibus-interface use a supply of 5 Volt. These voltages should be disjoint because of the different circuits. This introduces the need for a DC­ DC-converter. With a standard DC-DC-converter the power-dissipation in the converter-component is too high, introducing to much heat. A search for a switched voltage regulator was done to eliminate the heat as much as possible. A switched voltage regulator switches the output-voltage 'on' and 'off' at a speed of approximately 100 kHz. This high speed switching is used to establish an output voltage that is the mean value of the switched voltage. A low-pass filter is used to eliminate high frequency spikes.

A WatchDog device (WD) continuously measures the Profibus power line, when power-failures are detected the device resets the whole system.

The power-supplies of the ADC consist of a separate digital and analog 5 Volt supply, they must be galvanic isolated from each other so the digital circuitry has no influence on the analog part and vice versa. Since the ADC is to be supplied with separate analog and digital voltages, care should be taken to avoid latchup.

Since the incoming Profibus supply voltage may vary between 18 and 60 Volt, it is not recommended to use this supply for powering sensors and encoders. Therefore a supply of 12 Volt is provided to the encoders and the proximity sensors.

In order to achieve better performance, the Weight Bridge can be excited with 10 Volt instead of 5 Volt.

37 E~ An intelligent sensor controller using Profibus

3.3 Test results

It is convenient to make use of the in earlier state developed 1/0- and Weight controller boards for testing purposes. This way the designed hardware can be tested and optimised.

The design of the weight section is the most critical in the design of the sensor controller board. Therefore several points should be considered regarding its power supplies:

~ Voltage limits • Latch up • Frequency pickup

In the absolute maximum ratings of the AD7730 [11] the analogue and digital supply voltages are specified between -O.3V and +7V while the differential voltage between them (AVdd to DVdd) is specified between -2V and +5V. On the test board this requirements were easily met.

However because the weight section is powered by a separate analogue and digital supply care should be taken to avoid latch up problems. This occurs when power is switched on and either the analogue or the digital supply comes up to late. Although the AD7730 specification states that its latch up performance is very good several devices died because of this phenomenon. The solution to this problem is as simple as effective: by placing diodes anti-parallel between the analogue and digital supplies any supply may come up first and will always take the other supply along.

Since we use a switched power supply that is switched at 100kHz we might expect frequency pickup problems by the transformer. Therefore a filter should be placed between the transformer and the voltage regulators. Measurements also showed that the frequency pickup was less when using the Coilcraft instead of the Renco transformer.

38 ~ An intelligent sensor controller using Profibus ELLIPS

4. POSITION MEASUREMENT

In the current implementation of the fruit grading system, the displacement of the cups is determined by three sensors, namely a sensor indicating the position of the first cup (zero-position) and two sensors placed along the line indicating cup-displacements. In the new system an incremental optical shaft encoder can replace these sensors. The encoder is attached mechanically to the rotating part of the machine (either directly to the motor or at the end of its transmission), where it determines the position of the device. The measurement of the fruit roll is new in this version of the fruit grading system, because the hardware to be used is the same as for the position encoding we will only discuss the position encoding hardware.

4.1 Specifications

The cup-position measurement (as depicted in paragraph 2.2.1) should be as accurate as 1/20 cup. The fruit cups are located on the line which has a speed of up to 20 cups per second (in the next paragraphs we will use the term: cps) and an approximate line-length of 100 meters. The rotation speed of the cups is either 1 or 10 cup(s) per rotation (cpr)

The sensor used for the translation of position into electrical signals is an incremental optical shaft encoder (rotary encoder). See next paragraph. The sensor controller board periodically has to send the position information to the master over the Profibus. See appendix B.

Summarised this gives the following:

• accuracy (a::; 1/20th cup) • cups per rotation (cpr::; 10) • cups per second (cps::; 20) • line length (1 ::; 100m)

39 E~ An intelligent sensor controller using Profibus

4.2 Rotary encoders

Incremental encoders that emit pulses that determine how far a device has rotated are called rotary encoders. The key specification of a rotary encoder is the number of Pulses Per Revolution (PPR) or pulses per inch (or centimetre). PPR's of 250,512, 1000, 1024, up to 100,000 are available.

Incremental encoders emit either uni- or bidirectional pulses consisting of square wave (or sinusoidal) voltage pulses, formed as a slit moves between a fixed phototransistor and a LED. Bidirectional pulses are most commonly available as quadrature pulses. A quadrature encoder has two separate sets of slits and electronics, offset 90 degrees from each other in phase. The used coding is Gray-coding. Thus one phototransistor I LED pair will always come ON before the other depending on the parts direction. A third pulse­ output is activated at every whole rotation of the encoder.

Specifications of encoders can be divided in three groups, namely: electrical, mechanical and environmental characteristics. Below tables give some examples:

Electrical Example Output-circuit Push-pull, etc Supply voltage Vb 14 Volt Power consumption 30 rnA OutputH ~ 2 Volt Output L ~ Vb-3 Volt Max. output load ±30mA Table 4.1: Electrical encoder specifications

Mechanical Example Shaft diameter 6mm Abs.max. shaft load Radial ION, axial 5N Abs.max. speed 10000 RPM Protection IP50 Weight 60 g Table 4.2: Mechanical encoder specifications

40 E~ An intelligent sensor controller using Profibus

Environmental Example Operating temp.range -10 °C to +60 °C Vibration proof 500 impulses (10-2000 Hz) Shock resistance 500 impulses 30G Table 4.3: Environmental encoder specifications

There are several output configurations used with industrial encoders, these include: (open collector) NPN, (open collector) PNP, line driver (TTL) output, push-pull and fixed voltages. The output signals are dependant of the used output circuit; for TTL the output switches between 0 and 5 Volt, for Push-Pull it switches between £1 Volt and the supply voltage subtracted by £2 Volt, where £1,2 are certain offsets. Most industrial encoders use supply voltages between 4.5 and 14 Volt with a power consumption of up to 30 rnA.

Most industrial shaft diameters are 5 or 6 mm, under normal conditions the maximum shaft load is about ION / 5N (radial / axial), more robust encoders can have a maximum shaft load of up to lOON / 50N. The protection grade is standardised in DIN 40050, it contains grades IPOO to IP68, where IPOO stands for no protection and IP68 for a device that is totally protected against dust and against immersion under pressure.

For the selection of an appropriate encoder that will be used in our system the following specifications should be met:

• incremental rotary type • bidirectional outputs • zero pulse output • minimum required resolution 1000 PPR (see appendix C). • operating voltage between 4.5 and 14 Volt • output voltage range between 5 and 30 Volt • maximum speed 1200 RPM (see appendix C), • low protection grade; IP 50 (limited dust ingress) suffices.

41 An intelligent sensor controller using Profibus E~

Before choosing an implementation for the decoding logic we should examine its input signals (produced by the encoder). Most encoders deliver three signals: A, Band C (also called Z). The number of pulses in the A- (or B-) signal is proportional to the position of the attached device. Because A and B are shifted 90 degrees from each other also the direction is known: pulse A before pulse B means clockwise while pulse B before pulse A means counter clockwise. Signal C is used for signalling the zero position. Whenever the encoder has made a full rotation a pulse is generated at the C-output. See figure 4.1.

... A ~ I I ... B ~ l I I ... 36

Figure 4.1: Encoder output signals

As can be seen from above figure, the A- and B-signal can be used to decode the encoder's position by dividing its period into maximum 4 different states, namely: (A,B) =(0,0), (1,0), (1,1) and (0,1). This is also called 'fu1l4x decode', and it means that the maximum achievable resolution is four times the specified resolution of the encoder. In 2x decode- or Ix decode mode respectively 2 or all states are combined, this gives resolutions of 2x PPR or Ix PPR.

Nowadays several manufacturers produce encoders, unfortunately this also means that different manufacturers use different specifications for the electrical behaviour of their encoders. These differences are mainly: the shift between signals A and B, the pulse width of all signals and the position of the zero-pulse with respect to the other pulse position. Table 4.4 on the next page gives a brief overview of most common encoder manufacturers and their specifications. The types printed in bold are currently used at Ellips.

42 E~ An intelligent sensor controller using Profibus LLIPS

Vendor Shift of A,B Width of A,B WidthofC C at state AB (degrees) (degrees) (degrees) (± accuracy) Bourns 90±45 180 ±45 360± 90 AB = (11)±45 BEl 90±27 180 180 AB = (00) Hengstler 90 180±25 180±25 AB = (11) HP 90±45 180 ±45 90 ±50 AB = (00) ±45 Nemicon 90 180 360 AB = (11) Pepperl&Fuchs 90 90 to 360 360 AB = (11) ±45 Siemens 90±45 180±45 180± 45 AB = (11) ± 45 BEl 90±27 180 180 AB = (00)

Table 4.4: Vendor specific encoder specifications

4.3 Design

There are several options for the implementation of the decoding logic. One could think of using the microcontroller's hardware counter to do the job or another option is to make use of already available decoding devices from Hewlett Packard.

Keeping in mind that we want to share position information between the hardware and software (see later in this paragraph) and in order to keep the hardware simple without having much overload because of multiplexed counter values, using the microcontroller's hardware counter isn't an option anymore.

For the interfacing of incremental encoders to microprocessors several devices from Hewlett Packard (HCTL 2000,2016,2020) are available. These devices feature an microprocessor-interface, 14 MHz Clock Operation, Fu1l4x decode, 12 or 16 bit binary up/down counting and quadrature decoder output signals up/down and count. Unfortunately we need some control signals in order to synchronise the sharing of position values between hardware and software. This would require additional hardware.

Because the design of the decoding logic is very custom and also the pASIC used for the glue is not utilised completely the decision is made to design the decoding-logic in house and to implement it in the glue. This way a very cost-effective solution is found, while the needed board space remains the same.

Next we will discuss the design of the decoding logic by deducting and translating it's state machine. An intelligent sensor controller using Profibus E~

It is easy to translate these signals into information about displacement and direction by assigning states to combinations of A and B.

Table 4.5 reviews all possible states:

A,B (n+l) 81=00 82=01 83=11 84=10 81=00 !(enable) DWN Error UP A,B (n) 82=01 UP !(enable) DWN Error 83=11 Error UP !(enable) DOWN 84=10 DWN Error UP !(enable)

Table 4.5: Encoder state transitions

As depicted in the previous table the output signals are:

• UP I DWN: encoder turns clockwise I counter clockwise • !(enable) encoder position not changed • Error encoder missed a position

These signals are depicted in figure 4.2. The direction signal UPIDWN is translated to upnotdwn.

Figure 4.2: State diagram of the decoder

44 An intelligent sensor controller using Profibus E~

It has now become clear that the decoder consists of the described state-machine that translates the encoder-outputs to control-signals for the counter.

We should decide what to do when an error occurs. An error means that the state-machine missed one of four states, so it is not possible to determine if the counter was counting up or down. Ifwe hold the counter when an error occurs the counter misses 2 positions. If we count up or down, depending on the last direction, the counter only misses 1 position assuming the direction has not changed.

The clock-frequency of the decoding-logic depends on the encoder's resolution, the line speed and the diameter of the transmission wheel. The encoder resolution is specified in Pulses Per Rotation (PPR). Because the number of cups per rotation is exactly known and it is more transparent than using the wheel diameter, the number of cups per rotation (cpr) is used to specify the wheel diameter. In the current system a cpr of 1 or lOis used. The line speed is specified by the number of cups per second (cps). The current system has a maximum cps of 20.

Because of flexibility the decoding-logic should be able to handle a broad range of encoder-resolutions, rotation speeds and wheel diameters. The next relation gives the minimum clock-frequency of the decoding-logic:

8· PPR .cps f CLKMIN (4.1) cpr

Encoder resolutions are available up to PPR =100,000 and the maximum line speed is 20 cups per second (max. cps =20). With a cps of 20 and a cpr of 1 the clock frequency should be at least 16 MHz, with the same cps and a cpr of 10, the clock frequency should be higher than 1.6 MHz

Because the sensor controller uses a maximum frequency of 48 MHz to clock the Profibus controller that divides this clock internally to 24 MHz this clock can also be used for the decoding logic. This should be sufficient for future extensions of encoder resolution or line speed. See appendix C.

In comparison; Hewlett Packard's quadrature decoder/counter interface HCTL20xx chip uses a clock frequency of 14 MHz.

45 E~ An intelligent sensor controller using Profibus

The width of the hardware (hw) counter depends on the amount of overhead the software can manage. The general idea here is to share position information between a hardware- and a software counter. By moving a predefined number of counts (window) between both of them the hw-counter will never reach an overflow or borrow condition which would mean that position information is corrupted. We can make use of a small range counter with an appropriate counting window.

Every time the hw-counter, while decrementing, leaves the window and passes the lower bound an interrupt is generated to the micro-controller, indicating that the software counter should subtract one window and after doing so compensate the hw­ counter by adding one window. Whenever the counter, while incrementing, passes the upper bound an interrupt is generated, indicating to the software it should add one window value to its counter. The hardware counter is then subtracted by one window. This way the HW-counter will always move 'within' the defined window. See figure 4.3, where a window of 2048 counts is used.

+1024

--·1024 Figure 4.3: Counter hysteresis window

Regardless of the number of bits the optimum window would range from lA till % of the counter's range, so the bounds are situated equidistant. After the exceeding of the window is signalled by an interrupt, this must be serviced within lA range of the counter in order to avoid overflows or borrows. This must be assured by the interrupt handling routine.

We see that the interrupt handler needs approximately 40 J.ls to perform its tasks. This means that worst case, using a 100.000 PPR encoder, a cps of 20 and a cpr of 1, the counter may have moved about 320 counts (in 40 J.ls). For safety reasons we will assume a count of 1000 in stead.

46 E~ An intelligent sensor controller using Profibus LLIPS

To assure that the counter will not overflow or borrow within these counts, a counter should be used with a minimum width of 12 bits, assuring a counting range of 4 times 1000. (212 = 4096 > 4000).

This way the hardware is reduced and only one bus transfer is needed to read both counter's four Most Significant Bits (MSBs). The 8 Least Significant Bits (LSBs) only have to be read when an exact position needs to be known. Because the transfer of complete counter values can not be done in one transfer, the counter values should be latched in order to achieve consistency between the MSB and LSB counter values.

Instead of defining the window from 1024 to 3072 (lA till % range), it is convenient to shift the window to -1024 to 1024 in order to simplify the software. This means that only the two most higher order bits have to be used to detect that the counter exceeds the window and it is also easy to add/subtract a window (synchronously reset these two bits).

Although the hw-counter is only 12 bits, the position value can be extended to much higher ranges in software.

Summarised, the specifications of the counter are: • width 12 bits • count up/down • enable/disable counting • provide latched counter values before reading • indicate higher and lower boundary passing • synchronous reset

The value and the interrupt status of the counter are placed in dedicated registers in the glue. The interrupt register of the counter is filled with flags which indicate the counter's passing zero, exceeding the higher bound or the lower bound of the defined window. Every time the counter leaves its window this is signalled to the micro­ controller by an interrupt.

In appendix H the VHDL code of the decoding logic is given which consists of the explained state-machine and counter.

Care should be taken to avoid metastability problems with the state machine. Metastability occurs when setup- and/or hold times are not satisfied so flip flops don't switch appropriately (within a required time) into a stable state.

47 E~ An intelligent sensor controller using Profibus LLIPS

4.4 Metastability

Metastability occurs whenever a clocked flipflop synchronises an asynchronous input and if there is a small probability that the flipflop output will exhibit an unpredictable delay. This happens when the input transition not only violates the specified setup and hold times but actually occurs within the small timing window in which the flipflop accepts the new input. What happens is that the flipflop will enter a symmetrically balanced transitory state and after a certain delay it will revert to one of its stable states. The Mean Time Between Failures (MTBF) can be defined statistically as follows:

K2·t MTBF = e [sees] (4.2) Fl·F2·Kl

Where: K2 is the resolving speed of the metastable condition (indication of gain-bandwidth product in feedback path of master latch) Kl is the metastability-catching setup time window Fl is the frequency of the asynchronous input F2 is the clock frequency of the flipflop t is the settling time

In order to calculate the MTBF in our case we need to know above parameters, these can be found from Quicklogic's specifications for the QL2003, see below: lIK2 29 ns Fl 8 KHz (worst case: 20cps, lOcpr, 1000PPR) F2 24 MHz (cpu clock) Kl 0.3 ps t 2-5 ns

(4.3)

To reduce metastability, thus increasing the MTBF it is common to place additional flipflops in series, so the settling time is increased.

In our case the inputs from the encoders to the state machine will be asynchronous, by placing an extra flipflop in its path to the glue the MTBF is improved from approximately 20 seconds to 16 years.

48 ~ An intelligent sensor controller using Profibus ELLIPS

4.5 Test results

Since the actual hardware is not assembled yet, we will have to do with timing simulation results at the moment. This simulation is done on a fully placed and routed design in the Quicklogic device with worst case environment parameters.

Figure 4.4 shows a snapshot of one of the glue simulations regarding the position decoding:

(~l Counter P cl1c24 1J1.IU'lMJ1M1l.MrulM11lMJ1MIlJ1MJ'lMJ1f\MJ1J1.IU'lMJ1f\MJ1J1.IU'lM11M1l.MrutllllMln.nn.n.rwuuutnn reset

gp I17:0] gp112) up1ll] UPI(O] penl _11_ __a _

dsp_lo p_rst sp_zcro

Figure 4.4: Snapshot of position encoding simulation

As can be seen encoder P (a, b, c) is attached to gpi[O,1,2] and encoder R is attached to gpi[3,4,5]. PCNT and RCNT are their respective counters. Further we see that the c-pulse resets the counter and indicates this in the counter's register (sp_zero).

49 E~ An intelligent sensor controller using Profibus

5. WEIGHT MEASUREMENT

In this chapter we will discuss the design of the data acquisition unit of the sensor controller board which is used to perform weight measurements. In the next paragraphs we will first define the required specifications, look at strain gauge transducers and discuss Analog Digital Converters (ADCs). After giving design considerations the final design is discussed. At the end of this chapter we will evaluate the results after putting the design to test.

5.1 Specifications

For the acquisition of the weights a conversion has to be made from the analog outputs of the weight-bridge to a digital representation which can be processed by the sensor controller, clearly this requires an Analog Digital Converter (ADC). We define the accuracy of the weight-measurement as a percentage of the maximum weight that can be measured; this gives for the number of required bits:

# Bits =r210g 1 l (5.1) Accurracy

Substitution of a 0.01 % accuracy gives for the number of bits: 14. (13.3)

To obtain a safe margin in processing the signals, 16 bits are appropriate, this means a high-resolution ADC is required. Because the outputs of the weight-bridge are in the order of mY, amplification of the bridge-outputs might be necessary. This is expensive because of the strict drift and noise requirements of the needed amplifiers.

As already seen in paragraph 2.2 two kinds of measurements must be carried out, namely weighing of degraded fruit on a controlled line and weighing of qualified fruit at the exits in order to fill boxes. In the next paragraphs we will make a distinction between both, by referring to them as static- and semi-dynamic measurements.

Therefore the required ADC should have the following specifications:

• 16 bits effective resolution • conversion speeds up to several kHz • easy microcontroller interface (SPD • low costs

50 E~ An intelligent sensor controller using Profibus

5.1.1 Static

The fruit which quality is not high enough to be sold has to be weighted before it is transformed into juices. The weighing of the fruit takes place after sorting it out by hand and leading it via a delivery-line to a weighing-line that has a load-cell attached to it. (figure 2.3)

The fruit that is sorted out by hand is weighted by amounts of 10 kg. It should also be possible to fill boxes of up to 50 kg. The measurement has a static character because a line is filled with a certain amount of fruit before the actual measurement is carried out. A sensor that indicates a full line (by the lack of pulses it emits) controls the line and initiates measurements. The measurements can be carried out as a dedicated process because no communication with the Profibus is required. Although it should be possible to set (change) the required filling amount. The accuracy should be better than 0.01 %, this means that 1 gram deviation is allowed on a weight of 10 kg. For a 50 kg box this means that it can vary 5 grams above or below its weight.

Summarised specifications:

• Effective resolution 16 bits • Conversion rate several Hertz

5.1.2 Semi.dynamic

The qualified fruit leaving the exits has to be weighted in order to fill boxes with the right amount of fruit. Because the fruit is leaving the exits at a maximum speed of 20 pieces per second this measurement should be performed at a minimum rate of 200 Hz in order to achieve an accurate measurement. Again the accuracy should be better than 0.01 % which is 1 gram with a load cell of 10 kilograms. The measurement is called semi-dynamic because, compared to the measurements of the weight controller [2], it is slow (8000 Hz).

The semi-dynamic weight measurement might also be used instead of the static measurement. It should be possible to leave out the sensor that indicates a full line and perform measurements while the line is moving. This wayan estimation of the amount of fruit on the line can be made in order to determine if the line is already full.

Summarised specifications:

• Effective resolution 16 bits • Conversion rate several hundred Hertz

51 An intelligent sensor controller using Profibus E~

5.2 Strain gauge transducer

For the translation of weights into electrical signals a weight bridge is used. A weight-bridge consists of a strain-gauge transducer, whose resistance changes when subjected to mechanical stress, and a few fixed resistors according to the Wheatstone principle. This is also called a standard load cell [Lc]. Because of the passive character it requires an excitation voltage to derive a voltage output. Therefore the output voltage is proportional to the amount of weight and the excitation voltage. See figure 5.1.

...------{) Vref +

l------u Vref-

Figure 5.1: Wheatstone bridge principle

With the differential reference voltages applied and no weight on the load cell the differential output voltage should equal zero. Due to several influences (e.g. lead resistance, tolerances) in practice the output will not be zero but will have a certain offset. Therefore calibration should be carried out before any measurement is done. The main advantage of using differential outputs is that disturbances will always occur on both wires so the average result of the disturbance will be zero.

The key specifications of the used load cell are:

• Max load 50 kg /10 kg • Output voltage 2 mVN

The above output voltage is related to the excitation voltage as follows: the output voltage is equal to 2 mV per Volt excitation. This means that when using a 10 kg load cell and an excitation of 10 Volt, the maximum output voltage (when applying 10 kg to the cell) will be 20 mY. It is easily calculated that a load of 1 gram will produce an output voltage of 2 JlV.

52 E~ An intelligent sensor controller using Profibus

5.3 Data acquisition

As already seen in paragraph 5.1 we require a one channel high resolution ADC with an effective resolution of 16 bits, a conversion rate of up to 200 Hz and a simple interface to the microcontroller.

At this point the question arises why a new design for the data acquisition is necessary while the design of the weight controller board can be used instead. The weight controller board [2] is designed for the dynamic acquisition of weights, it is equipped with a Digital Signal Processor (DSP) that is interfaced to the microcontroller by a Host Interface Port (HIP). The weight board features:

• 16 bit effective accuracy • conversion rates up to 8000 Hz • 8 multiplexed channels • low noise/drift signal amplification

Although the weight controller board can be used for the required data acquisition, it does not fulfil our requirement that it must be low cost. Also, since we use only one channel at much slower conversion rates, it would be exorbitant to use the weight controller board.

In order to keep the costs of the design of the data acquisition for the sensor controller board as low as possible we would prefer an integrated solution, that is an appropriate ADC without the need for a DSP, HIP and expensive amplifiers.

Nowadays many ADC products are available from several manufacturers, ranging from more conventional types (sampling, successive approximation) to more exotic ones (flash, sigma-delta). However when moving in the field of high precision acquisition, most (high-resolution) ADC's are sigma-delta ADC's. Sigma delta modulators are becoming increasingly important in data conversion applications. Their advantage over more conventional AID or D/A converters lies in their robustness to circuit imperfections, simple circuitry, and ease for on-chip VLSI implementation. The basic operation of sigma delta modulators is to trade off sampling rate with amplitude resolution. Specifically, they sample signals many times faster that the Nyquist rate, but only with one bit of amplitude resolution. Low pass filtering is typically used to recover the signal at the output.

53 E~ An intelligent sensor controller using Profibus LLIPS

5.3.1 Sigma delta ADC's

In below table a comparison is made between a sigma-delta ADC and several other types of ADCs, regarding speed, resolution and costs.

Type: Resolution: Speed: Costs: Sub-ranging (multistep) 8-16 10 Mbit/s High Flash 6-16 1 Mbit/s Sampling (Succ. Approx.) 8-16 1 Mbit/s Delta-Sigma 12-22 100 kbit/s Dual slope (integrating) 12-24 30 bit/s PWM 6-10 10 bit/s Low

Table 5.1: ADC type comparison

As can be seen from above table delta sigma ADCs feature resolutions higher than 12 bit at speeds up to 100 kbit/s. Before an appropriate sigma-delta ADC is selected the following parameters [15, 16, 17] should be evaluated:

Resolution (no missing codes resolution) This is the eye catching specification in many ADC datasheets, it is very misleading since it only states the number of bits which are used when the converter passes a range of codes, without skipping a code.

Effective resolution This is the resolution with respect to a certain level of rms-noise.

Peak-peak resolution This gives the resolution at the maximum allowed p-p noise level, this resolution is also called the noise free resolution and it is always lower than the effective resolution.

Accuracy Accuracy includes errors of quantization, noise and drift. So this constrain gives the actual needed resolution.

Input Span The input span is the allowed voltage range, which can be applied to the inputs so the converter's full-scale range is covered.

Conversion rate This term refers to the frequency at which conversions take place; this frequency should be higher than twice the highest signal frequency (Nyquist).

54 E~ An intelligent sensor controller using Profibus

5.3.2 Analog Devices compared to Burr Brown

In the area of sigma delta ADC's manufacturers Analog Devices and Burr-Brown have developed converters that are optimised for the connection of low-level transducers like weight bridges. They feature resolutions up to 24 bits, differential inputs, serial SPI and on chip programming facilities. These ADC's are the Burr­ Brown ADS 1210 and the Analog Devices AD7730.

When selecting an appropriate AID converter, several specifications need to be compared. While some specifications are straightforward, others might be slightly misleading.

In order to determine the maximum achievable resolution of the ADC's some noise calculations have to be done.

For an ideal ADC, with a sinusoidal input, the signal to noise ratio in decibels (dB) is given by:

S -=6.02NB+1.76 (5.2) N

See also appendix E. This gives for the number of bits NB:

_ 2010g[~ )-1.76 NB- (5.3) 6.02

With N = Vrms (the effective noise voltage) and S at the Full Scale Voltage (FSV), this gives for the effective resolution:

2010g FSV -1.76 Nrms = Vrms (5.4) 6.02

The peak-peak resolution is calculated based on the maximum peak-peak noise voltage, which is proportional to the crest factor and the rms noise voltage:

55 E~ An intelligent sensor controller using Profibus

2010g FSV -1.76 IV, - Vrms'K (5.5) pp- 6.02

To calculate peak-peak resolution, one should decide the amount of acceptable rms­ noise related to the peak-peak noise voltage. This is quantified in the crest factor K.

2K = Vpp (5.6) Vrms

The noise on the outputs of the ADC is distributed according to a Gauss-function, see formula 5.7:

1 (5.7) qJ(X) = ·e a.J27t

p-p NOISE CALCULATIONS FROM RMS 1.0 __Il. I I 0.1 lJl ~ ~ - ...... (1j 0.01 ...... a.Cl> ... 0.001 Cl> .c ~ 0) 0.0001 "'" I ~ -0 0.00001 I £ :0 (1j 0.000001 .0 "" e 0.0000001 " a...... 0.00000001 '" '" 0.000000001 2 3 4 5 6 7 8 9 10 11 '"12 2x Crest Factor (Vp-pNrms)

Figure 5.2: Gauss distributed p-p noise

Figure 5.2 shows this Gauss-function with respect to the crest factor. The probability function is derived as follows:

56 ~ An intelligent sensor controller using Profibus ELLIPS

(x)=P(x~X)=-oc frp(t)dt (5.8)

.....:::;~ ..r...---'-...... I. • X ll-lC<1 Il 1l+1(<1 .. 21(<1 •

Figure 5.3: Gaussian distribution

With K=l f 2 f 3 fete. the probability that all values are in the range [~-kcr, ~+kcr] is a% = 68.3 f 95.5 f 99.7 f .. .(according to the Gaussian distribution).

Both Analog Devices and Burr Brown specify a crest factor of around K=3 (resp. values are Ka=2,55 and Kb=3,3) This means the noise level is specified in terms of the 3a noise level, which is 6 times the rms noise level. The 3a noise level is the level at which the possibility of the noise (that high) is below 0.3 %( ±0.5 LSB), see above.

Although Burr Brown seems to be far better than Analog Devices, the comparison of both converters against exactly the same parameters reveals that their resolution is almost the same. While Analog Devices specifies peak-peak resolutions in their datasheet, Burr Brown specifies effective resolutions. As can be seen from above the difference between effective and peak-peak resolution is given by:

201og(K) Npp=Nrms (5.9) 6.02

With K=3.3 (Burr Brown), 2,72 bits should be subtracted from the specified resolutions in order to get a correct comparison against the Analog Devices converter.

57 E~ An intelligent sensor controller using Profibus

When doing so, it becomes clear that although Burr Brown's converter has a higher resolution than the Analog Devices, the difference is only 1 bit (without amplification). With amplification of the inputs an additiona11.5 bits are achieved.

Although the Analog Devices' and Burr Brown converters are both conditioned for weigh-scale and pressure measurement, they differ in several features, the next table summarises these (best specs in italics):

Specification Analog Devices Burr-Brown (AD7730) (ADS1210) Smallest full scale input range 10mV 0.625V Max. eff. res. @ outputrate 18 bits @ 50 Hz @ 20 bits @ 50 Hz @ @ -3dB freq. (gain=l) 1.97 Hz 13.1 Hz Max. outputrate @ eff. res. 1200 Hz / 16 bits @ 1 kHz 1 10 bits @ @ -3dB freq. (gain=l) 46.8 Hz 262Hz Max. outputrate @ eff. res. 1200 Hz 118 bits @ 1 kHz/20 bits @ @ -3dB freq. (max. gain) 46.8 Hz (gain=8) 262 Hz (Rain=16) Sample frequency 307.2 kHz 1 - 312 kHz Integral non-linearity 0.0015 %/ FSR 0.003 %/FSR Drift (gain/fullscale, offset) 2 ppm/ °C, 5nV/ °C 1uV / °C PSR (50/60 Hz) no dB 65 dB CMR/NMR 120 dB /88 dB 110 dB 1100 dB Channels 2 1 Filtering Sine!'3 + 22 tap FIR SincA 3 AC Excitation Yes No Calibration zero/full/backgrnd Yes, yes, no Yes, yes, yes Burnout check Yes No TareDAC Yes No Chipselect tristates device Yes No

Table 5.2: Analog Devices versus Burr Brown

As can be seen from table 5.2, The ADS 1210 can achieve a higher effective resolution at higher conversion speeds, however to achieve significantly better resolutions, amplification of its inputs is needed. Also it doesn't support chopping of its inputs in order to eliminate drift-effects. Also the ADS 1210's ChipSelect (CS) doesn't tri-state the device, it is only used at SPI-communication. This is not desirable because multiple devices (eeprom) must be interfaced via SPI, without any bus contention. It has now become convenient to use the Analog Devices ADC in our design. In the next paragraph an overview of this device will be given.

58 E~ An intelligent sensor controller using Profibus LLIPS

5.4 Analog Devices AD7730

After comparison of all specifications ( [11], [12] ) the choice was made to use the Analog Devices AD7730 because the measurements will be almost static, an effective resolution of 14 bits suffices and no expensive amplifiers are needed. Further it has some useful features. See Figure 5.4.

The device accepts direct low-level signals directly from a transducer, and outputs serial words via SPI. The input signal is applied to a proprietary programmable gain front end based around an analog modulator.

The modulator output is processed by a low pass programmable digital filter; allowing adjustment of filter cut-off, output rate and settling time.

The part features two buffered differential programmable gain analog inputs as well as a differential reference input. It accepts four unipolar analog input ranges (0-10mv, 20mV,40mV and 80mV) and four bipolar input ranges (±lOmV, ±20mV, ±40mV and ±80mV). The peak to peak resolution achievable directly from the part is 220,000 counts. An on-chip 6 bit DAC allows the removal of TARE voltages. Clock signals for synchronising ac excitation of the bridge are also provided. The serial interface on the part can be configured for three-wire operation and is compatible with micro-controllers and digital signal processors. The AD7730 operates at a clock-frequency between 1 and 5 MHz.

AVoo DVoo REF IN(-) REF IN(+)

VB lAS

AINI(+)

AINI(-) IDOnA

MUX 1-----.----1 AIN2(+)/D1 MCLKIN AIN2(-)IDO MCLKOUT

SCLK ~ DIN ACX DOUT ACX

AGND DGND POL

Figure 5.4: Functional block diagram of the AD7730

59 An intelligent sensor controller using Profibus

As can be seen in the previous figure, the device features:

.:. AC-Excitation ~ For AC-excited bridge applications (see next paragraph) .:. Output Drivers ~ The second analog input channel can become two digital output lines .:. OffsetfTare DAC ~ Allows programmed voltage to be added/subtracted from input .:. Register Bank ~ 13 registers control all functions and provide status-information .:. Serial Interface ~ SPI-compatible .:. Clock-Oscillator Circuit ~ External clock or crystal resonator can be applied .:. Standby Mode ~ This mode reduces power consumption .:. Programmable Digital Filter ~ 2-stage filter that sets the output-update-rate and settling-time .:. Sigma-Delta ADC ~ 24 bits no missing codes, supports chopmode for removing drift errors .:. Differential Reference ~ This facilitates ratiometric operation, the reference is either 2,5 or 5 Volts .:. Programmable Gain Amplifier ~ The amplifier allows 4 uni- and bipolar input ranges from 0 to 80mV .:. Buffer Amplifier ~ Presents a high impedance input stage .:. Burnout Currents ~ 2 burnout currents of lOOnA to detect transducer bum or open-circuit .:. Analog Multiplexer ~ Switches one of 2 input-channels to the buffer-amplifier

5.4.1 Interfacing the weight-bridge

The weight-bridge can be excited in DC or in AC mode. A common source of unwanted drift effects are parasitic thermocouples, these effects are generated every time there is a junction of two dissimilar metals.

AC excitation addresses many of the concerns about drift and thermocouple effects. In AC-excitation the polarity of the excitation voltage to the bridge is reversed on alternate cycles. The result is the elimination of DC errors in expense of a more complex system design. Figure 5.5 outlines the connections for an AC excited bridge application.

60 An intelligent sensor controller using Profibus E~

The excitation voltage to the bridge must be switched on alternate cycles. Transistors Tl to T4 in Figure 5.5 perform this switching. A special bridge driver chip (Micrell 4427 or Maxim TSC 427) can be used to perform this task.

One of the problems encountered with AC excitation is the settling time associated with the analog input signals after the excitation voltage is switched. The AD7730 addresses this problem by allowing the user to program a delay of up to 48,75 ~s between the switching of the ACX signals and the processing of the data at the analog inputs.

Figure 5.5: AC-excited bridge application

When connecting the bridge directly to the ADC the bridge signal will be degraded because of several influences. Examples of these influences are drift due temperature, noise, cross-talk of the line-frequency and clock frequencies on the controller-card. To avoid this a filter is inserted between the bridge and the ADe.

For the static measurement theoretically the cut-off frequency can be very low. A restriction is that the frequency must be higher than the chopping frequency (which is half the output rate). In our case the output rate is 80 Hz. In practice the cut-off frequency has to be much higher in order to obtain an acceptable signal at the input of the ADC with very low attenuation below cut off, therefore a High Pass Filter (HPF) is not applicable here. The AD7730 has a standard line-frequency rejection of 88 dB, so this is not an issue and the drift is eliminated due to chopping the device, so the only remaining degradation is due noise and cross-talk of higher frequencies. A Low Pass Filter (LPF) is used to attenuate these signals.

For the dynamic measurement the cut-off frequency must be higher than twice the maximum cup-speed, so the -3 dB frequency has to be higher than 40 Hz. Again it is related to the output-rate (we can't use chopping here because the required output rate is to high, see figures 5.9 and 5.10).

61 An intelligent sensor controller using Profibus E~

5.4.2 Configuration ofthe AD7730

Before the actual measurement is performed, the ADC has to be configured to adjust the right settings for the filter, gain, mode and offset. After configuration a calibration should be performed to assure accurate measurements. The standard procedure is:

1. configuration 2. (self-) calibration (after power-on I reset) 3. measurement

An additional feature of the AD7730 is the check for burnout of the bridge-transducer, this is performed by switching internal current sources, see figure 5.4.1

Configuration ofthe adc

The first stage filter is a low pass sine 3 filter whose primary function is to remove quantization noise introduced at the modulator. By setting SFII-SFO, the amount of averaging, outputrate and cut-off frequency can be programmed. The outputrates in chop and non-chop mode are determined by the following relationships and a figure of the frequency-response is given below:

o -10 '\ -20 fCLKIN 1 -30 Output Rate NONCHOP -=----x- 40 \ \ I 16 SF !g -60 \ ...... I -60 I \ ;!; f ~ -70 \ I \ (5.10) -eo \ I \ -90 \ -100 fCLKIN 1 -110 Output Rate CHOP = -=----x--- -120 o 200 400 600 800 1000 1200 uoo 1600 1800 16 3xSF FREQUENCY - H. (5.11) Figure 5.6, Frequency response 1sl stage filter

Because of noise-reduction it is recommended to use the lowest output data rate as possible. Also multiples of the line-frequency should be avoided because harmonics will not fully be attenuated. Because the scaling factor SF has range: 2048 - 75 (20 if in skipped mode) and the clock frequency is 4 MHz, the maximum output rate is 1111 Hz (4167 Hz if skipped) The minimum output rate is 41 Hz.

62 E~ An intelligent sensor controller using Profibus

Notice that the -3 dB frequency is 0.0395 times the output rate, for an output rate of 41 Hz this gives a -3 dB frequency of 1,6 Hz, this is not acceptable for faster (dynamic) measurements.

The second stage filter is a 22 tap Finite Impulse Response (FIR) filter, this filter processes the output of the first stage filter. The filter has three modes of operation: Normal, FastStep and Skip mode, which will be explained now.

FIR-mode

In this mode the filter acts like a normal 22-tap FIR filter. The -3dB and stop frequencies are determined by the following relationships and a figure of the frequency-response is given below. Notice that the FIR filter's settling time depends on the output rate.

For non-chopping mode these frequencies have to be multiplied by 3.

...... -10

-20

-JO " \ f 3dbchop = 0.0395 X fCLK IN X 1 -40 \ 16 3xSF ...., ~ I -60 l!i ~ -70 (5.12) -<10 11"\ n. -90 1'\ -100 V"\ U \ 1\ -110 \1" I X fCLK IN X V \ slop chop 0.14 1 -120 I\f f o 10 20 30 40 50 60 70 80 IlO 100 16 3x SF FR~QU~NCY - HI

(5.13)

Figure 5.7, FIR-filter response

It is recommended to choose a cut off frequency with certain distance to the line frequency because of aliasing effects.

In chop mode the part is chopped at its input and output to remove all offset and drift errors on the part. In AC excitation mode chopping must always be enabled.

63 An intelligent sensor controller using Profibus

FastStep mode

In this mode the filter will process steady inputs the same as in the normal FIR mode, but step changes to the inputs will be processed with a much faster response time. See Figure 5.8:

I ./ 1500000O /1 81- u / / / o o 10 15 20 25 NUMBER OF OUTPUTS

Figure 5.8: Step response for Faststep and normal operation

The main disadvantage of using FastStep mode is that the exact time through the filter can't be predicted anymore. It is therefore better to use the normal FIR mode so results can be processed whenever an averaged conversion result leaves the filter.

Skip mode

In this mode the FIR filter is skipped and each output of the sinc3 filter is a valid result itself. The advantage of skipping the FIR-filter is the faster settling time but on the other hand the noise will be significantly higher. For our purpose the FIR-filer is needed.

64 An intelligent sensor controller using Profibus

Calibration:

The AD7730 provides a number of calibration options. Four calibrations can be performed (restricted to the following sequence):

• internal full-scale (80 mV*) • internal zero-scale • system zero-scale • system full-scale

* Note that it is recommended to perform this calibrations at the lowest output rate because of the accompanying noise-levels. The coefficients generated at any output rate will be valid for all selected output update rates [11].

The calibration time is related to the output rate. The time needed for an internal zero­ scale calibration is [22/ output rate] (in chop mode), otherwise [24/ output rate]) and for an internal full- scale calibration [44/ output rate] ([48/ output rate] non­ chopping). The calibration times for system zero-scale and system full-scale calibration are both [22/ output rate] in chop-mode and [24/ output rate] in non-chop mode.

While calibrating the device the signal RDY maintains high and after completion of this task the RDY-signal turns low. After the calibration the AD7730 goes into idle-mode. Now the AD7730's mode needs to be set; in order to set bi- or uni-polar inputs, word­ length, input range, channel selection, ACIDC excitation, conversion mode, etc. before the actual measurement is carried out.

Measurement:

The continuous measurement is characterised by the following steps:

~ Set continuous reading mode • Do RDY signal goes low; indicates an updated data register Read the data-register • Until stop continuous mode ~ Device goes into IDLE mode

Single measurement steps:

• Set single read • RDY signal goes low; indicates an updated data register • Read the data-register • Device goes into IDLE mode

65 E~ An intelligent sensor controller using Profibus

Reading from the AD7730's on-chip registers can be operated in continuous or single mode. Writing can only be done in single mode. Before reading or writing the device an initial write to the communications register has to be performed, to indicate the next action and the desired register. See appendix F.

Reading from the On-Chip registers is performed in two stages. First the desired reading-mode for the specified register is indicated to the AD7730. (by writing byte W for single or byte Y for continuous reading, see appendix F). In case of a single read the AD7730 goes into idle-mode after updating the desired register. When in continuous mode, byte Z has to be written in order to stop the continuous reading of the desired register and let the device go into idle mode.

Timing: Reading from and writing to the On-Chip registers is done by SPI-communication. SPI is a Serial Peripheral Interface specification from Motorola that only uses three wires: Data-input (DIN), Data-output (DOUT) and Serial clock (SCLK). The communication between the micro-controller and the ADC is shown in appendix F. Whenever the ADC has updated his data-register RDY is activated (low) and the controller can assert CS in order to read the data registers contents. The active edge of SCLK can be selected with the POL-input on the AD7730 device. Writing to the ADC's on-chip registers is analogous. See appendix F.

Notice that when sending data from the micro-controller the ADC expects MSB first (Motorola format), also when reading data from the ADC, the MSB is read first.

66 E~ An intelligent sensor controller using Profibus

5.5 Design

By making use of the AD7730, the further design of the data acquisition is simplified to the appropriate programming of the device's On-chip registers. In the next paragraphs we will discuss the needed settings for the static and semi­ dynamic weight measurement.

5.5.1 Static

Because this measurement is carried out only once in several seconds, the output rate of the ADC doesn't have to be high. Also the ADC's peak to peak resolution is increased at decreasing output rates. Chopping should be enabled in order to eliminate offset and drift errors. Below figure shows the ADC's behaviour:

Output -3 dB SF Settling Time Settling Time Input Range Input Range Input Range Input Range Data Rate Frequency Word NonnalMode Fast Mode = ±80mV = ±40mV =±20mV = ±IOmV 50 Hz 1.97 Hz 2048 460 ms 60 ms 230k (18) 175k (17.5) 120k (17) 80k (16.5) 100 Hz 3.95 Hz 1024 230 ms 30 ms 170k (17.5) 125k (17) 90k (16.5) 55k (16) 150 Hz 5.92 Hz 683 153 ms 20 ms 130k (17) lOOk (16.5) 70k (16) 45k (15.5) 200 Hz· 7.9 Hz 512 115 ros 15 ms 120k (17) 90k (16.5) 65k (16) 40k (15.5) 400 Hz 15.8 Hz 256 57.5 ms 7.5 ms 80k (16.5) 55k (16) 40k (15.5) 30k (15)

Figure 5.9: Peak to peak resolutions (chopping mode)

As seen in paragraph 5.1 the minimum resolution required for our application is 16 bits and with our bridge which outputs 20mV max. we need an output rate lower than 100 Hz. In order to avoid aliasing we should choose an output rate that is not related to the line frequency. With an output rate of 80Hz these conditions are satisfied. Notice that the settling time at this output rate is about 730 ms, in order to reduce this time (to about 40 ms) we can use Faststep mode. (normal mode: settling time is 23/outputrate, faststep mode: 3/outputrate). However this has the disadvantage of unpredicted filter output timing.

From figure 5.9 and 5.10 we see that the peak-peak resolution of the AD7730 from Analog Devices is 14.5 to 18 bits guaranteed.

Excitation of a 50kg load-cell with 10 Volts and a resolution of 2 mVN gives: (max. output voltage of 20mV at 50 kg, is OAIlV at 1 gram)

This gives: 14 bit, resolution: 1 bit is 1220 nV ~ resolution is 3 gram. 18 bit, resolution: 1 bit is 76 nV ~ resolution is 0.2 gram.

These values are acceptable because they are below 5 gram and best case even below 1 gram. See appendix D.

67 E~ An intelligent sensor controller using Profibus

5.5.2 Semi-dynamic

This measurement has a dynamic character but because the outputrate is in the order of 1 kHz we shall use the term semi-static. Measurements should be performed on fruit that passes the line with a speed of maximum 20 pieces a second. This means chopping mode can not be used because this will attenuate all frequencies below the chopping frequency, which is the same as half the output rate. Below figure shows the peak to peak resolutions in non-chopping mode.

Output -3 dB SF Settling Tbne Settling Tbne lnputRange Input Range Input Range Input Range Data Rate Frequency Word Normal Mode Fast Mode = :!:80mV = :!:40mV = :!:20mV =:!:IOmV

150 Hz 5.85 Hz 2048 166 InS 26.6 ms 165k (17.5) 120k (17) 80k (16.5) 55k (16) 200Hz 7.8 Hz 1536 125ms 20 ms 140k (17) lOOk (16.5) 70k (16) 45k (15.5) 300 Hz 11.7 Hz 1024 83.3 ms 13.3 ms 115k(l7) 90k (16.5) 65k (16) 40. (15.5) 600 Hz 23.4 Hz 512 41.6 ms 6.6 ms 90. (16.5) 60k (16) 50. (15.5) 30. (15) 1200 Hz 46.8 Hz 256 20.8 ms 3.3 ms 60. (16) 43. (15.5) 32. (15) 20k (14.5)

Figure 5.10: Peak to peak resolutions (non-chopping mode)

For accurate weight measurement we should establish a cutoff frequency (first stage filter) that is not below 40 Hz. Again we should satisfy the required resolution of 16 bits. As can be seen the required resolution is slightly higher than we can achieve, but notice that we have chosen 16 bits resolution for safety reasons, we only need 14 bits, see paragraph 5.1.

From the above table it can be seen that an output rate of 1200 Hz satisfies these conditions. The settling time is 20.8 ms. (normal mode: settling time is 25/outputrate, faststep mode: 4/outputrate) When amplifying the input signals with a gain of 8 the resolution is slightly better, namely: 16 bits. Although this yields a profit of 1.5 bit, an amplifier is needed which features low noise and low drift. Unfortunately the 1.5 bits yield does not justify the price for it.

Excitation of a 10kg load-cell with 10 Volts and a resolution of 2mVN gives: (max. output voltage of 20mV at 10 kg, is 2 JlV at 1 gram)

This gives: 14 bit, resolution: -70.6 gram. 18 bit, resolution: -70.04 gram.

These values are acceptable because they are below 1 gram and best case even below 0.1 gram. See appendix D.

68 E~ An intelligent sensor controller using Profibus

5.5.3 Converter settings

In this paragraph we will discuss the required settings for the converter in our application. This settings are also used at testing, see next paragraph. (In below tables bits that are not mentioned are always zero!)

Filter-register:

Bits Parameter Check InCCal InCCal Burnout (chop=1) (chop=O) 3-0 DL3-0 0,0,0 0,0,0 0,0,0 4 CHP 0 1 0 5 AC 0 1 0 8 FAST 0 0 0 9 SKIP 1 0 0 23-12 SF11-0 Ox 1000 Ox14 Ox96

Table 5.3: Filter register settings

Notes: - use lowest outputrate at calibration - use highest outputrate at burnout check - delay is in modulatorcycles (MCLKIN/16 = 4 J.!s) - (Ox 1000 = 2048 Hz) / (Ox14 = 50 Hz) / (Ox96 = 150 Hz)

Mode-register:

Bits Parameter Check Int. Int. Syst. Syst. Burnout Zero Cal Full Cal Zero Cal Full Cal 1-0 CH1-0 0,0 0,0 0,0 0,0 0,0 2 BO 1 0 0 0 0 3 CLKDIS 0 0 0 0 0 5-4 RN1,0 0,0 0, 1 1, 1 0,1 0, 1 7 HIREF 1 1 1 1 1 8 WL 0 1 1 1 1 10-9 D1-0 0 0 0 0 0 11 DEN 0 0 0 0 0 12 BID 0 0 0 0 0 15-13 MD2-0 0,1,0 0,0,1 1,0, 1 1, 1,0 1, 1, 1

Table 5.4: Mode register settings

Notes: - use max. inputrange at internal Fullscale calibration - use correct input range at other calibrations (RN1,0 = 0,1 = 20 mY)

69 ~ An intelligent sensor controller using Profibus ELLIPS

Duration of calibrations:

Calibration-type Chop = 1 Chop =0 Internal_Zero 0.28 sec 0.16 sec OR=80Hz OR= 150Hz Internal_Full 0.55 sec 0.32 sec OR= 80Hz OR= 150Hz System_Zero 0.28 sec 0.30 sec OR=80Hz OR=80Hz System_full 0.28 sec 0.30 sec OR=80Hz OR= 80Hz

Table 5.5: Calibration durations

So when performing an internal calibration (both zero and full scale) this may take up to 1 second, this time the Weight-SAP (chapter 7) will be dead.

Calculated FIR-filter times:

The FIR filter times in normal mode can be easy calculated:

#taps + 1 T.sc(h)op =---- (5.14) OutputRate

# taps +3 Ts(nonchop) = ----"--- (5.15) OutputRate

For the filter times in FastStep mode the following formulas apply:

3 Ts(chop) = (5.16) OutputRate

4 Ts(nonchop) = (5.17) OutputRate

70 ~ An intelligent sensor controller using Profibus ELLIJ5s

5.6 Test results

The testing of the data acquisition was done by adding the design to the I/O controller board, this way the maximum achievable resolution was measured. Before the actual measurement was carried out, it took several designs and modifications to improve the overall noise performance. These modifications included:

• careful ground layout • special decoupling • use crystal resonator instead of squared clock

Above modifications led to a resolution improvement of about 2 bits.

All measurements were performed with a 10 kg transducer from AEP which outputs 2 mVN. The transducer was excited with 5 Volt.

Below table shows the (static) measured results when operating the device in chopped mode at an output rate of 80 Hz (-3 dB frequency of 3.2 Hz):

Reference Wei~ht (~ram): # 1.00 2.00 5.00 10.00 100.00 200.00 500.00 1 0.95 2.00 4.87 10.12 100.19 199.81 500.18 2 1.04 2.10 5.00 9.99 100.17 200.16 500.11 3 1.11 2.07 5.06 9.97 100.14 199.90 500.07 4 1.13 2.12 5.09 10.18 100.08 200.09 500.14 5 0.86 1.94 5.06 10.17 99.98 200.12 500.12 6 0.88 1.96 5.00 10.12 99.91 200.16 500.20 7 1.10 1.97 4.91 10.07 100.07 199.98 500.14 8 1.10 2.13 5.14 10.00 100.06 200.20 499.92 9 0.99 2.17 5.14 10.00 100.08 200.17 500.02 10 1.06 2.17 5.10 9.88 100.08 200.15 500.03

Table 5.6: Chopped mode measured results

From the above table we see that the absolute accuracy is about 0.2 gram. This gives an effective resolution of 16 (15.6) bits. As seen in figure 5.8, this resolution is close to the maximum achievable resolution (Figure 5.9).

71 E~ An intelligent sensor controller using Profibus

When operating the device in non-chopping mode we get the following results. The output rate is again 80 Hz (-3 dB frequency of 3.2 Hz):

Reference Wei~ht (~ram): # 1.00 2.00 5.00 10.00 100.00 200.00 500.00 1 n.a* 1.33 5.90 10.86 99.00 200.00 500.77 2 n.a* 1.46 5.72 9.35 99.00 200.78 500.14 3 n.a* 1.20 4.98 9.78 100.96 201.68 499.49 4 n.a* 1.26 4.56 10.65 100.85 200.18 500.06 5 n.a* 2.87 5.94 10.87 101.00 199.28 501.00 6 n.a* 2.92 5.56 9.54 100.08 199.28 499.87 7 n.a* 3.55 5.05 10.98 99.76 200.26 500.45 8 n.a* 1.22 5.47 10.85 99.00 200.97 500.71 9 n.a* 1.99 5.98 9.04 99.65 200.83 500.33 10 n.a* 2.07 4.84 9.05 100.78 200.84 501.00

Table 5.7: Non-chopping mode measured results

Now the absolute accuracy is about 1 gram. This gives an effective resolution of 13 (13.3) bits. From figure 5.10 we see that the measured resolution is lower than the specified (14 bit) resolution. (n.a* indicates not applicable weight measurements)

To further improve the accuracy of the weight measurement it is recommended to excitate the transducer with 10 Volt instead of 5 Volt. This should yield one additional bit of resolution.

The above measured resolution should be evaluated as worst case resolution. Integrated on the Sensor Controller board, with the exact ground planes and all components flattened on the board, the noise performance should be better and this should result in a better resolution.

72 E~ An intelligent sensor controller using Profibus

Unfortunately the following devices (named Japie) all died because of bad latch-up behaviour during the tests:

Figure 5.11: Japie 1,2,3

After fixing the problems with with Japie 1,2 and 3 concerning latch-up (see page 38), the design of the weight circuit was connected to the I/O board for further testing.

Figure 5.12: Japie 4 on the I/O board

73 ~ An intelligent sensor controller using Profibus ELLIPS

Japie 5 integrated on the Sensor Controller board:

Figure 5.13: Japie 5

74 E~ An intelligent sensor controller using Profibus LLIPS

6. I/O CONTROL

In this chapter the designs of the input- and output circuitry will be described. We will start with the desired specifications, then the design is discussed and finally some test results are evaluated.

6.1 Specifications

Inputs:

The sensor controller gets its process-input from proximity sensors and incremental encoders which are placed along the line, and depending on the gathered input data some devices (valves and motors) need to be controlled.

In order to achieve flexibility, the sensor controller should support most industrial proximity-sensors with a broad range of power-supplies and output types. Most common specifications are:

~ Sensor types • Capacitive, inductive, optical proximity sensors ~ Supply voltages • TTL, 12 to 24 Volt ~ Output types • TTL, (open collector-) PNP, (open collector-) NPN, push-pull

Below table summarises the possible configuration of attached sensors to the sensor controller board. See also paragraph 2.2.1.

Configuration SO SI S2 S3 S4 REI RE2 Lc (Ap,Bp,Cp) (Ar,Br,Cr) Displacement Sensors (D.S.) x x x x Encoder (displacement) x x x D.S. + Encoder (roll) x x x x x Encoders (displacement + roll) x x x x Weight x x

Table 6.1: Sensor input configurations

75 ~ An intelligent sensor controller using Profibus ELLIPS

From table 6.1 we see that at least 8 inputs are needed. Each encoder requires three inputs. Because the sensor output voltages can be in the range of 0 to 24 Volt a conversion needs to be made to TTL-levels. Also the input-circuitry should be galvanic isolated from the controller-logic in order to prevent disturbances reaching the controller logic.

Outputs:

The isolated output-circuitry should be able to drive valve-relays and motors, which means that a load current of 1 Ampere and a power of 40 Watt must be acceptable for the valve-relays. The motors should be driven by separate relays because of their load. It should be possible to drive either AC- or DC loads.

Further the input- and output circuitry should be protected against overvoltage, transients and other disturbances.

76 E~ An intelligent sensor controller using Profibus

6.2 Design

The la-interface is divided in two parts:

1. Sensor- en encoder-inputs 2. Outputs

Because not all sensors/encoders have TTL-outputs a conversion needs to be made before their output signals are fed to the sensor controller logic (which uses TTL logic). It is also recommended to achieve some kind of galvanic isolation between the sensor-outputs and the controller-logic. The obvious solution is to use opto-couplers, in this way both requirements are met. One of the main specifications of opto-couplers is the current transfer ratio, it is defined as the ratio of output collector current 10 and forward LED input current If times 100%. It is recommended to use a constant transistor current in order to achieve TTL output levels. We use an N-channel Field Effect Transistor (N-FET) to assure a constant current through the LED. For our purpose the Philips BF245c and BF556c are suited with maximum ratings of Ids = 25 rnA and Dds = 30 Volt. While the input voltages may vary between 5 and 30 Volt a shorted gate-source field effect transistor is used in order to get a constant current independent of the input voltage. This can be achieved because the Ids-Dds characteristics of these PETs are quite straight in its saturation area. See figure 6.1.

MBH554 30

'0 (rnA)

20 VGS= ov-e-- I /' I 1V 10 I /' 1/ 2V II ,,- r/ 3V f£. - -4V o o 10 Vos (V) 20

Figure 6.1: Ids-Dds Characteristic BF556c

77 E~ An intelligent sensor controller using Profibus

The opto-couplers should be high-speed devices since they have to support encoders with pulse rates of up to 1 MHz. Most high speed opto-couplers are manufactured by Hewlett Packard, with speeds up to 50 Mbit/s they satisfy almost every high speed requirement. In our case the HCPL0531, a 1 Mbit/s device is fast enough to interface all input signals to the controller logic. It is also possible to directly attach TTL sensors; placing a zero Ohm resistor can short the IN-inputs and SENSOR-outputs together. Figure 6.2 shows the circuit for a single input.

There should also be some kind of filtering on the inputs to avoid noise and spikes from reaching the controller-logic. Notice that the sensor inputs change 'slowly' at several Hertz while the encoder inputs can change at 1 MHz.

., D2 "'".. sa.EJI5CA 14,4.~

1~+"-,-----e:>SENSO~1

IH1 ... .--,----' ,-H(P1Di531

IHI- ~>------'------'

Figure 6.2: Single input circuit

To protect the input-circuitry we make use of a transient suppressor. Transient suppressors are diodes that begin to break down at the specified breakdown voltage and assure that the maximum voltage, which is specified as the clamping voltage, will not be exceeded.

The inputs should be latched to avoid the missing of pulses. Every time sensor inputs change, this is indicated to the micro-controller by an interrupt. In his interrupt handler the micro-controller should check which inputs have changed and initiate the correct actions. The latch and interrupt control is placed in the glue. (See paragraph 3.2.4)

78 E~ An intelligent sensor controller using Profibus

Outputs:

In order to control the outputs a register is located in the glue that can be read and written by the micro-controller. Because the logic of the sensor controller is not able to drive heavy powered devices, an output-circuitry should be designed which is capable of switching these devices. As mentioned before, these devices include valves and motors. The choice was made to use solid state switches, these switches provide equivalent electromechanical relay functionality with the additional features of solid state long term reliability, smaller size and lower drive requirements. It is possible to operate the output-circuitry in DC or in AC mode. The desired mode is established by changing the output's resistor configuration.

0+5

R91 1501 lk ·;·'·01 OUTo 6 Rl30 0 016 TRIGGERl 5 COMMONl 5MBJ4BA 4BV

1/-02 OUTl LCA71 0 R132 0+5 0

R91 1501 lk +/4 01 OUTo 014 TRIGGERl 5 COMMON' 5MBJ4BCA 48V R130 -02 OUTl LCA71 0

Figure 6.3: DC (upper) and AC (lower) output configurations

Because the load-current of the valve-relay is about 1 Ampere and the switching itself induces a higher peak-current, the heaviest solid state switch available is chosen, namely: LCA710 from CPCLARE. This switch is a 60 Volt, 1 Ampere solid state relay with a maximum load current of 1 resp. 1,8 Ampere (in AC resp. DC mode). The allowed peak current is 5 Ampere for the duration of 5 ms. The output protection is provided by tranzorb diodes with a breakdown of 48 Volt and a clamp of 60 Volt.

6.3 Test results

The input circuitry supports voltages from 5 up to 30 Volt, keeping the LED current (of the opto-coupler) between 10 and 12mA. When applying an encoder to the inputs the square waved input is transferred to the output of the opto-coupler without any degradation of the signal edges. Since the rotation of the encoder was established by driving it with an electric drill, the circuitry could only be tested up to 25kHz. Also the outputs worked well in both modes.

79 E~ An intelligent sensor controller using Profibus

7. SOFTWARE

In this chapter a description is given of the embedded software that is used by the sensor controller board.

The software for the sensor controller can be divided in the following parts:

.:. Profibus Protocol Software .:. Sensor Controller Software ~ Sensor Input Handling ~ Decoder Software ~ Data Acquisition Software

These parts will be explained in the following paragraphs.

7.1 Profibus Protocol Software

The protocol software takes care of all communication with the Profibus master. We make use of software by TMG-itec to implement this part of the design. The software consists of all functions needed for the implementation of a DP(E) slave. These functions include initialisation, reading diagnostics, checking configurations, set parameters and data exchange. These tasks (placed in the function do_dp) have to be performed cyclically in the main loop of the software.

For the handling of the communication between master and slave Service Access Points (SAPs) are used. This way a number of services can be multiplexed. The Sensor Controller uses the following SAPs:

Number: Functions: #Commands: #30 Diag SAP 1 #31 Control SAP 10 #34 Roll SAP 1 #35 Weight SAP 13 #36 Position SAP 1 #37 Gpio SAP 1

All communication on above SAPS is handled in the function do_ellips_saps that is added to the main loop. Except for the Control-SAP every other SAP makes use of reply update communication. This means that whenever the SPC4 receives an indication it's buffers are filled with the requested data (updated) so they can be sent directly at the next received indication. The control-SAP uses a Send Data Acknowledge (SDA) for the indication of executed commands and Send Request Data's (SRD's) for sending back the requested data.

80 ~ An intelligent sensor controller using Profibus ELLfpS

The actual measurement flow is carried out by dedicated state machines, see next paragraph. Each SAP can be operated with several commands that will be described briefly on the next page.

On the Diag-, Position-, Roll- and Gpio-SAP only one command is needed since we don't need to control anything on this SAP. These SAPs provide respectively: diagnostic-data, position information, roll and input/output data. The position- and roll data is updated at a predefined rate (see paragraph 2.2.5), specified at the Control SAP's setup. The 1/0- and diagnostic data are updated every time a change orrurs in its data.

The commands on the Control- and Weight-SAP include:

~ Control-SAP • GeCID : Get the Identification number of the slave • Kernel Mode : Switch to kernel mode (load new program) • Start Upload : Start upload new program code • Upload Packet : Packet with program code • Stop Upload : Stop upload new program code • Reboot : Reboot the system • Initialise : Initialise the hardware • Setup : Setup hardware configuration • Get Configuration : Get the setup configuration • Get Stretch : Get the chain stretch value

~ Weight-SAP • Get Status : Get status information • Internal Calibration : Start internal calibration • System Zero cal : Start system zero calibration • System Full cal : Start system full calibration • Set Calibration : Set Offset- and Gain settings • Get Calibration : Get Offset- and Gain settings • Set Filter : Set Filter values • Get Filter : Get Filter values • Get Single : Get a single weight measurement • Get Multiple : Get multiple weight measurements II Get Next : Get next measurement • Set Tare : Set the Tare offset of the DAC • Get Tare : Get the Tare offset

81 An intelligent sensor controller using Profibus E~

7.2 Sensor Controller Software

The software for the sensor controller consists of four functional blocks: the sensor input handling, the position decoding, the weight (data acquisition) and the in previous paragraph described Profibus protocol software. These blocks are all imbedded in the Main routine of the Sensor Controller. See figure 7.1.

Figure 7.1: Sensor Controller Software

7.2.1 Sensor Input Handling

This part of the software consists of an interrupt-handling routine for the processing of all sensor inputs and encoder indications. The sensor board can be equipped with up to 8 sensor inputs. These include inputs from the position encoders, proximity sensors for zero-position, stretch, displacement and weight indication. Whenever an input changes (and the source is not masked) this is signalled by an interrupt from the glue. Also every change will be saved in a so-called 'glitch bitmap', this way every input glitch will be seen. After the microcontroller receives the interrupt, it has to read the interrupt register in order to determine the interrupt's source. The interrupt is caused either by a change at one of the inputs, or by one of the encoder-counters. After reading the interrupt register the source is known and either the input register or the counter register must be read. Also the appropriate interrupt flags must be cleared. The input's information is updated in the SPC4 every time an interrupt from the inputs is received.

82 ~ An intelligent sensor controller using Profibus ELLIPS

7.2.2 Decoder software

The measurement of the cup-positions with the rotary encoder is done in hardware and in software, the hardware uses a 12 bit counter that indicates an interrupt whenever the defined hysteresis window is left. The real position counter is done in software so its range can be bigger than that of the hardware counter and is always extendible.

The software-part for the decoding of the cup-positions makes use of the interrupt­ handling routine of the core software. After the determination of exiting the hysteresis of the counter, both the software-counter and hardware counters have to be adjusted.

Using a 32 bit counter in software should be sufficient for our application (1000 PPR, 100m, 20 cps, 10 cpr) since the total count can be represented by 20 bits. Whenever the microcontroller receives a window based (upper or lower bound exceeded) interrupt, the software should add or subtract one window to/from the 32 bit counter and initiate the subtraction/addition of the window from/to the hardware counter.

83 E~ An intelligent sensor controller using Profibus

7.2.3 Data Acquisition Software

The software needed for the static weight measurement consists of procedures to write and read On-chip registers of the ADC. With these the ADC has to be calibrated, the mode of operation can be set and finally the measurement has to be initiated.

A state machine performs the weight acquisition, see figure below:

Figure 7.3: Weight machine

Outline:

The state machine always starts in idle mode and stays here until a 'START'-request for calibration or conversion (Get Samples) is received. As can be seen the internal calibration is performed in two stages, first full-scale calibration then zero scale calibration is carried out. (This is done because the full­ scale calibration alters the offset register.) System calibration is performed either by starting the full scale or the zero scale calibration, and again: after a full-scale calibration a zero scale calibration is needed.

84 E~ An intelligent sensor controller using Profibus

The ADC can be read out once, in single mode, or a defined number of times, in multiple mode. After the specified number of samples are read the SM goes back into Idle mode where it is ready for the next request. In burnout mode the ADC's internal current sources are applied to the inputs and a single measurement is carried out, this way the transducer can be checked against short-circuit or open circuit failures.

Every time the ADC has finished calibration or a valid conversion result is available the ADC generates an interrupt (RDY) to the microcontroller.

An interrupt handling routine takes care of the appropriate actions at every state of the weight machine and delivers the control signals in order to step through the weight machine. These control signals are the START- and EO-signals as depicted in figure 7.3. START indicates the beginning of an action and EO (controlled by interrupt handler) indicates the end of an action. Table 7.1 summarises all control signals:

StartIntZeroCal EoIntZeroCal StartIntFullCal EoIntFullCal StartSysZeroCal EoSysZeroCal StartSysFullCal EoSysFullCal

StartBurnOut EoBurnOut StartGetResults EoGetResults

Table 7.1: Control signals for the weight state machine

Next we will describe an implementation of the static weight measurement which can be used as a stand-alone application. We don't need to communicate with the Master computer, so this will relieve the Profibus.

85 E~ An intelligent sensor controller using Profibus

For the handling of a dedicated static weight measurement a state machine is used that makes use of the Sensor Full input, indicating a full weight-line and the start of measurements. Next we will give a description of this state machine.

As already mentioned Sensor Full is used to indicate a full weighing-line. This is simply done by checking its pulsing, if the pulsing has stopped for longer than a specified time, the weight line should be full.

The state machine always starts in Idle mode, where it stays until the weighing line is loaded, Sensor Full located at the beginning of the line is interrupted every time a cup comes along. Since the end of the weighing line is closed with a valve, the fruit is lining up before it and in the end the sensor will stop pulsing, indicating a full weight line. Now the lines have to be stopped (delivery-line before weight line, think of fruit just falling of the edge). See figure 7.2.

After a certain debouncing time the weight measurement can be started. The handling of the weights is done by another state machine, see figure 7.3. At the end of each acquisition control is given back to the main state machine, that takes care of emptying the line and start allover again.

Sensor Full StopDeliveryLine StopWeightLine EriiPiYiii9 Debouncing = 1 CloseValve ..... SlartDeliveryLine '.".

Debouncing •••••••• StartGetResults

Figure 7.2: Sensor state machine for weight

86 ~ An intelligent sensor controller using Profibus ELLIPS

8. CONCLUSIONS & RECOMMENDATIONS

8.1 Conclusions

The sensor controller board is designed with the following hardware:

./ Dallas DS80C310 microcontroller ./ Analog Devices AD7730 sigma delta ADC ./ Siemens SPC4 Profibus controller ./ Isolated Profibus interface ./ Quicklogic QL 2003 pASIC ./ A switched power supply

In its current design the sensor controller board supports position- and roll measurement up to a precision of 10-2 cup, weight measurement with an accuracy of 0.2 gram in static mode and 1 gram in dynamic mode. A total of eight sensors can be attached with a broad range of specifications, including most common industrial ones. Up to four solid outputs are available for the switching of lA loads in AC and 1.8A in DC mode. Care is taken to establish an EMC-free design and to provide protection against transients and stress due overvoltage. In this document a description of the design and all used hardware is given.

The written VHDL code for the position measurement and the Memory Management Unit is simulated. Software for the communication with the ADC is also tested.

We have managed to keep the costs of this design below the costs of the I/O- and the Weight Controller. This means the Sensor Controller is about twice as cheap as the Weight Controller is.

8.2 Recommendations

Although several parts were already tested individually, the complete Sensor Controller board still has to be tested. For the weight-section using an excitation of 10 Volt instead of 5 Volt should increase its accuracy by 1 bit. Also this section should be shielded in order to prevent disturbances from reaching its logic. Instead of doing a static weight measurement a semi-dynamic one can be performed, this way the Full Sensor can be left out. By continuously monitoring the total amount of weight on the weight-line an indication is given before the accurate measurement is carried out. In future Profibus DPE is to be implemented in order to provide a-cyclic polling of slaves, this way a very flexible polling of the Sensor Controller is established.

87 E~ An intelligent sensor controller using Profibus

9. BIBLIOGRAPHY

[1] David, C.F.L. DESIGN OF AN ACTUATOR-CONTROLLER USING PROFIBUS-DP. Information and Communication Systems Section, Faculty of Electrical Engineering, Eindhoven University of Technology, 1997.

[2] Kester, H.A.J. AN INTELLIGENT WEIGHT CONTROLLER USING PROFIBUS. Information and Communication Systems Section, Faculty of Electrical Engineering, Eindhoven University of Technology, 1997.

[3] DP PROFILE FOR ROTARY, ANGLE AND LINEAR ENCODERS. Order number 3.062 Profibus Nutzerorganisation e.v., Karslruhe 1997

[4] PROFIBUS STANDARD, DIN 19245 part 1 & 2 Order number 0.002 Profibus Nutzerorganisation e.v., Karslruhe 1991

[5] PROFIBUS DP DRAFT STANDARD, DIN 19245 part 3 Order number 0.012 Profibus Nutzerorganisation e.v., Karslruhe 1994

[6] PROFIDUS GUIDELINES; IMPLEMENTATION GUIDE DIN 19245 PART 3. Order number 2.041 Profibus Nutzerorganisation e.v., Karslruhe 1996

[7] Popp, M. THE RAPID WAY TO PROFIBUS-DP. Order number 4.072 Profibus Nutzerorganisation, 1997.

[8] Bokhorst, A.M. ONTWERP, BOUW EN BEPROEVING VAN EEN NAUWKEURIGE POSITIE­ OPNEMER, GEBASEERD OP EEN INCREMENTELE AS-ENCODER. Technische Universiteit Eindhoven vakgroep EMV, Eindhoven 1980

88 E~ An intelligent sensor controller using Profibus

[9] Seippe1, R.G. TRANSDUCER INTERFACING FOR PROCESS CONTROL New Jersey: Prentice Hall, 1988

[10] Hordeski M.F. DESIGN OF MICROPROCESSOR SENSOR & CONTROL SYSTEMS. Virginia: Prentice Hall Company, 1985

[11] BRIDGE TRANSDUCER ADC AD7730 REV.O. Analog Devices

[12] 24-BIT ANALOG-TO-DIGITAL CONVERTER ADS 1210/1 1. Burr Brown U.S.A. June,1996.

[13] Hnatek, E. A USER'S HANDBOOK OF D/A AND AID CONVERTERS. DCA Reliability Laboratory Inc., 1997

[14] Daugherty, K. ANALOG TO DIGITAL CONVERSION, A PRACTICAL APPROACH. MC GrawHill Inc., 1994.

[15] Candy, J. and G. Ternes OVERSAMPLING DELTA-SIGMA DATA CONVERTERS, THEORY, DESIGN AND SIMULATION. IEEE press, 1992.

[16] DALLAS DS80C310 HIGH-SPEED MICRO Dallas Semiconductor Corporation U.S.A. June, 1995

[17] DALLAS DS80C320 HIGH-SPEED MICRO Dallas Semiconductor Corporation U.S.A. February, 1998

89 E~ An intelligent sensor controller using Profibus LLIPS

10. ACKNOWLEDGEMENT

First I would like to thank Erwin Bakker who provided the opportunity to do my graduation project at Ellips B.V. and making me be part of his great team.

My gratitude goes out to:

Harry Stox, for being my supervisor and first aid after system crashes. Jean-Paul Smeets, for all hardware clues and redesign suggestions. Roland Scheffer, SMD-magician and PCB wizard. Ivo Kleuters, for his technical support. Gerard Brouwers, for all hints and tips concerning the Windows environment Tiago Gons, who made karting look as easy as racing. Sandra de Groot, for taking good care of us and sharing horrible stories at lunch. Hans Kester, for his work on the controller cards and sharing lots of currant buns with me. Erik Walstra, for all VISIO hints and tips. Erwin Limpkens and Maurice de Lijer.

I would like to thank prof. M.P.J. Stevens for his supervison and comments on this graduation work.

Finally I thank Brian Small (Quicklogic), Frank Bazelmans (Bourns), Henk Heymans (Alcorn) and Ronnie te Linteloo (Eurodisffexim) for the swift providing of information and samples.

90 ~ An intelligent sensor controller using Profibus ELLIPS

APPENDIX A: NOMENCLATURE

AC Alternating Current ADC Analog to Digital Converter pASIC Programmable Application Specific Integrated Circuit. DC Direct Current DP Decentralised Periphery DPE Decentralised Periphery Extensions DS Displacement Sensor DSP Digital Signal Processor ESD Electro Static Discharge FDL Fieldbus Data Link FIR Finite Impulse Response FPGA Field Programmable Gate Array HIP Host Interface Port HW HardWare JTAG Joint Test Action Group LED Light Emitting Diode LSB Least Significant Bit /.LC Microcontroller MMU Memory Management Unit MSB Most Significant Bit MTBF Mean Time Between Failures OSI Open Systems Interconnection p-p Peak-Peak PPR Pulses Per Revolution PROFIBUS PROcess FIeld BUS RE Rotary Encoder Rms Root Mean Square (effective value) SAP Service Access Point SDA Send Data Acknowledge SM State Machine SPC4 Siemens Profibus Controller 4 SPI Serial Protocol Interface SRAM Static Random Access Memory SRD Send Reply Data SW SoftWare TTL Transistor Transistor Logic UART Universal Asynchronous Receiverffransmitter character VHDL Very high speed integrated circuit Hardware Description Language

91 E~ An intelligent sensor controller using Profibus

APPENDIXB: PROFIBUS PERFORMANCE

The following formulas and parameters were used in paragraph 2.2.5 for the calculation of system reaction times and encoder resolution times.

Equations: TSR = TMC,TOTAL + mp· TMC,RET

TMC = TS/R + TSDR + TAIR + TID + 2·TTO TMC, TOTAL =nr .TMC,RELAY+TMC,WEIGIIT +In:;1· TMC,SENSOR TSR

Assume: TMC,RET = TMC,RELAY

1 for 187.5 kbit/ s, 500 kbit/ s and 1.5 Mbit/ s 2 for 3 Mbit/ s mp = 3 for 6 Mbit/ s 4 for 12 Mbit/ s

nr = 28 np = 30

143 bits for the relay controller and the weight controller T- SIR - {66 bits for the sensor controller

II bits for the relay controller

TAIR = l43bits for the sensor controller { 319 bits for the weight controller

92 ~-- An intelligent sensor controller using Profibus EVUifs

Description: This simulated Profibus system consists of one master and 30 slaves; 1 weight controller, 1 sensor controller and 28 I/O controllers. The Poll List of the master station is constructed in such a way that it will poll n slaves, then the sensor controller, n other slaves, the sensor controller again, and so on. Decreasing n will enhance the sensor controller's resolution, but reduce the System Reaction Time TSR. Tables B1 and B2 show calculations for several values of n and different bit rates. Greyed values are not acceptable for the fruit grading system.

Table HI: S stem Reaction Time TSR (ms) 187.5 kbit/s 500 kbit/s 1.5 Mbit/s 3 Mbit/s 6 Mbit/s 12 Mbit/s ~---I-----1------+--_---:""'--1 n=1 10.0 7.2 5.5 n=3 6.6 4.8 3.7 n=5 5.9 4.3 3.4 n=8 5.6 4.1 3.2 n=10 5.4 4.0 3.1 n=15 5.2 3.8 3.0

Table H2: Sensor Controller Resolution TsENsoR (ms) 187.5 kbit/s 500 kbit/s 1.5 Mbit/s 3 Mbit/s 6 Mbit/s 12 Mbit/s n=1 ./ /35 1.6 0.6 0.3 0.2 0.2 n 3 •. f\ ...., :;{A~I 1.2 0.7 0.5 0.4 n 5 9.6 i~ 1.7 1.0 0.7 0.6 n=8 .A iAl~ .. nAB 1.4 1.0 0.8 n 10 /::ITi/!;./i 1.8 1.3 1.0 .:: ;;.,'" n 15 ...... ,'!' .. t'n ~ .; .. 1.9 1.5

93 rvY:: An intelligent sensor controller using Profibus EVf!iis

APPENDIXC: ENCODER CALCULATIONS

To achieve certain accuracy (1I20th cup) of the position measurement we need an appropriate resolution for the rotary-encoder. The needed resolution (PPR) for the encoder depends on the number of cups per rotation (the diameter of the transmission wheel).

The maximum number of cups per second (cps) is 20, while the number of cups per rotation (cpr) is at least 1 and at most 10. This gives for the encoder's rotation speed a value of approximately 1200-120 RPM. The minimal clock frequency of the decoder depends on the speed V of line.

Relations:

Fmin.clk - 8·PPR . cps PPR _ cpr cpr 4·Accuracy

As can be seen in the table below an accuracy of 1I20th cup (5 %) is achieved with a minimum PPR of 64, however it is better to use a higher resolution to decrease the influence of errors. A practical resolution is 1000 PPR.

The state sampling frequency should be high enough to distinguish every single state; therefore every state should be sampled at least twice.

PPR Cps Cpr Clockfreq. (kHz) Accuracy (%)

·::i.. 161<20 L. 1·'n'::':: ~~;~ : 32 i.; :20 :<.I:.;i.:jO. <.... ····;Zi~J?R 64 20 10 1.02 3.9063 128 20 10 2.05 1.9531 256 20 10 4.10 0.9766 512 20 10 8.19 0.4883 1000 20 1 160.00 0.0250 1000 20 10 16.00 0.2500 1024 20 10 16.38 0.2441 2048 20 10 32.77 0.1221 4096 20 10 65.54 0.0610 8092 20 10 129.47 0.0309 10000 20 10 160.00 0.0250 16384 20 10 262.14 0.0153 32768 20 10 524.29 0.0076 65536 20 10 1,048.58 0.0038 100000 20 1 16,000.00 0.0003 100000 20 10 1,600.00 0.0025

94 E~ An intelligent sensor controller using Profibus

APPENDIXD: ADC CALCULATIONS

Accuracy calculations:

The accuracy of the weight measurement depends on the maximum load (in kg) of the weight-cell, the excitation voltage and the number ofbits guaranteed by the ADC. From the specifications of the AD7730 we find that the number of guaranteed bits is dependent of the output rate. We find that the number of guaranteed bits is always in the range of 14 to 18 bits. The accuracy should be 0.01 % of the full-scale, so with a 10 kg load cell 1 gram accuracy and with a 50 kg load cell 5 grams.

Max.Load .103 Accuracy (gram) = b' 2 us

Bits (#) Excitation (V) Resolution (mVN) Accuracy (nV) Max. load (kg) Accuracy (gram)

14 10 2 1220.70 10 0.6104 14 10 2 1220.70 50 3.0518 15 10 2 610.35 10 0.3052 15 10 2 610.35 50 1.5259 16 10 2 305.18 10 0.1526 16 10 2 305.18 50 0.7629 17 10 2 152.59 50 0.3815 18 10 2 76.29 50 0.1907 I .. ~A 19 10 ..' ··2 . - ••.. H:; 50 ' .. 0.0954 n:n'7 20 10 . 2. .50::::- - U. ~£ . 21 10 '<2 ,.J;}i:" 'OI:A 50 ..',' =;= (\ l~s:l 22 10 2 . , .' .' ·4.77 l:;() O. 119 {\ vI,::n 23 ..... 10. . . 2 . . 10 '1.19 0.0030 24 .2.' '. '. I . '

The greyed values above can not be achieved anymore.

95 An intelligent sensor controller using Profibus E~

APPENDIX E: SIGMA DELTA AID CONVERTERS

This appendix gives a brief description of aid converters of the sigma-delta type, which make use of the principles of delta-modulation. [15, 16, 17]

As can be seen in figure 1-1, the correct name for these converters should be: "Delta­ Sigma Converters", but due to historical reasons (the term "delta-modulation" should not be corrupted) it is widespread to use the name Sigma-Delta Converter.

ANALOG DIFFERENCE INPUT AMP COMPARATOR 0---1+ + INTEGRATOR

DIGITAL DATA

Figure E-l: Sigma-Delta modulator diagram

A sigma-delta ADC generally consists of two main blocks, namely an analog modulator and a digital filter.

The analog modulator consists of a difference amplifier, an integrator block, a comparator and a feedback DAC as illustrated in figure E-l. In operation, the analog signal sample is fed to the difference amplifier along with the output of the feedback DAC. The difference between these two signals is integrated and fed to the comparator. The output of the comparator provides the input to the feedback DAC so that the system functions as a negative feedback loop that tries to minimize the difference signal. The digital data that represents the analog input voltage is contained in the duty cycle of the pulse train appearing at the output of the comparator. This duty cycle data can be recovered as a data word using the digital filter. The sampling frequency of the modulator loop is many times higher (approx. 300 kHz for AD7730 and ADS 1210) than the bandwidth of the input signal. The integrator in the modulator shapes the quantization noise (which results from the analog-to-digital conversion) so that the noise is pushed toward one half of the modulator frequency. The digital filter then bandlimits the response to a frequency significantly lower than one half of the modulator frequency. In this manner, the I-bit output of the comparator is translated into a bandlimited, low noise output. The key difference between sigma-delta ADC's and other ADC's is that the sample frequency is much higher than twice the maximum input frequency (Nyquist) and that a closed loop modulator is used.

96 E~ An intelligent sensor controller using Profibus

The mathematical representation of figure E-I is shown below:

Quantization

1th Accu

Xi H,,---.---.Yi I l ...... _:I

Figure E-2: Mathematical representation of a 2nd order sigma-delta modulator

y(z) = X(Z) -[z-l +e oCl-z)2] (d-I)

N(t) 1th order

Noise in baseband

...... ~I------. t fO

Figure E-3: Noise shaping

97 E~ An intelligent sensor controller using Profibus

Now assume e is the quantization error and the device's noise is white noise, equally distributed (probability ± Y2~), then:

e2nns = 1 / ~ * -Vul f +Vul e2de = (~2/12) (d-2)

Using a sample frequency fs = 1 / 't and a signal in the range 0:::; f :::; fs/2 we get for the power density function:

E(f) = enns * SQRT (2/fs) = enns * SQRT (2't) (d-3)

Defining the OverSampling Ratio as OSR = fs / 2fo = 1 / 2fo't we find that for the nOIse:

(d-4)

From the above we see that oversampling reduces the in band noise no. A simple doubling of the sample frequency results in a noise reduction of 3 dB. (Winning Y2 bit)

Next the Signal to Noise Ratio (SNR) is calculated. Consider an amplitude-quantised system using n bits quantisation. When applying an sinusoidal waveform to the quantiser the maximum of 2n will not always be reached, therefore the maximum signal amplitude lies in the range:

(d-5)

To avoid the uncertainty about the maximum signal definition we will introduce a correction factor Stcor. Now the peak-peak amplitude will be:

n App = (2 - Stcor)· qs (d-6)

Stcor is determined by an accurate amplitude of the first harmonic in the signal frequency in the quantised system. For n=l a square wave will be generated at the converter output, by a series expansion this wave the peak-peak amplitude of the first harmonic becomes:

App (lst harmonic) = 4qsht. (d-7)

98 E~ An intelligent sensor controller using Profibus LLIPS

With this amplitude substituted in d-6 we see that:

4 Stcor=2-- (d-8) 7r The RMS value is simply calculated as:

In this equation a sine wave is adapted and the SNR can be calculated as the quotient of d-9 and the square root of d-2. This gives (when neglecting the term -2 + 4/n):

(d-lO)

And in decibels:

S/ N =6.02·n+1.76 (d-ll)

QED.

99 ~ An intelligent sensor controller using Profibus ELLIPS

APPENDIX F: ADC COMMUNICATION

Below figures show the state diagrams of the consecutive actions when writing/reading the ADC's on-chip registers.

WRITE:

( START

WRITE BYTE Y TO COMMUNICATIONS REGISTER (SEE ACCOMPANYING TABLE) + WRITE TO REGISTER

( END

Byte \\oT ByteY ByteZ Register (Hex) (Hex) (Hex)

StatUE, Register 10 20 30 Data Register 11 21 30 lviode Register J2 22 .30 Filter R.egister 13 NiA* .r\/A* DAC R~gister I ;~ NiA* K.iA* onset Register 15 N/A* KiA~ Gain Rcgi~tel' 16 N/A* KiA* Test Register L7 N/A* K.iA*

.IN/A= Xot Applicable. Cominuous re3.d~ of (hese registe~ does no[ make sense ax the rq,:ri.xtl:'r cnntt.:n1:S \vould iCtrulln the sarnl:' since tht.:~, :..ITt: only t.:hangt'd hy a \\Tite 0 pe1'l1.ti011.

Figure F-l: Single write to the on-chip registers

Byte Y indicates that the mode is single-write and which register has to be accessed next.

100 An intelligent sensor controller using Profibus E~

READ:

Re~ister B)1:e Y (Hex)

Communication::> Regi~tet 00 Data Register Read Only Register ~v1ode Register 02 Pilrer Register 03 DAC Register 0·1 OlTscl Register 05 Gain Register 06 Test Register User is L-tdvised not to l:h~mge contents ofTest Register.

Figure F-2: Read from the on-chip registers

101 E~ An intelligent sensor controller using Profibus

'------.:u-~------:1 tlO --l

SCLK (POL = 1)

SCLK (POL =0) ---1----1 r- ts rr= ter- POUT -----it MSB 1__X"----n..1_~X"-----'X'- --1:'1-"~

Figure F-3: Read cycle timing diagram

Figure F-4: Write cycle timing diagram

The timing characteristics belonging to the figures F-3 and F-4 are shown on the next page.

102 An intelligent sensor controller using Profibus E~

limit at T:'oliN to T.'MX Parameter (B Version) Units b-1astcr Clock Rangl;: 1 MHz min 5 MHz max tl 50 nsmin 11 50 nsmin Read Operation I} 0 nsmin 14 0 os min t·,4 0 ns min 60 nsmax 80 nsmax 1 4. '; iA 0 nsmin 60 ns max 80 nsmax 16 100 nsmin tl 100 nsmin lr! 0 nsmin 19,j )0 nsmin 80 ns max tJI'> 100 ns max Write Operation til 0 os min t 1Z 30 os min Ir.\ ?--") nsmin lu 100 nsmin 115 100 nsmin lib 0 nsmin

Figure F-5: Timing characteristics

103 ~ An intelligent sensor controller using Profibus ELLIPS

APPENDIX G: MMU TIMING REQUIREMENTS

This appendix gives a brief overview of the timing requirements when interfacing the microcontroller 80C310/320 with memory:

• SRAM CY7C199-25VC • Flash AM29FO10-45JC • SPC4

As can be seen from the next table the SPC4 will be the limiting factor in the design of the memory management. For comparison the 80C32 specifications are also displayed.

Spec. : SRAM Flash SPC4 Access-time 25 45 73 Address to output 25 45 73 CE to valid data 25 45 73 OE to valid data 10 25 -

Spec. : symbol 80C320 80C32 RDIWR pulse width trlrh/twlwh 153+ 210+ ALE pulse width tlhll 52+ 70+ ALE to valid instr. In tlliv 77- 130- ALE to PSEN 1 tHol 3+ 30+ PSEN pulse width toloh 86- 100+ PSEN to valid instr. In toliv 72- 85- RD to valid data in trldv 141- 175- PO addr. To valid instr. in tavivl 97- taviv = P2 addr. To valid instr. In taviv2 112- 153-

1 The address-latch should have a smaller hold-time than this!

This gives for the read- and write signals:

Spec. : Max. Glue delay RDN to RDN SPC4 27- RDN to RDN FLASH 75- RDN to RDN SRAM 130- WRN to WRN SPC4 27- WRN to WRN FLASH 75- WRN to WRN SRAM 130-

104 An intelligent sensor controller using Profibus E~

\04--- ILHLl. ---+I

ALE

.--- -j-___+___. \04------_+_ IpLPH ---'1r------

IpXIX

~ ADDRESS INSTRUCTION ADDRESS ADQ-AD7 AQ-A7 IN AO-A7

1-4---- IAVIV1 -----.l

\04----- IAVIV2 ------I~

PORT 2 ADDRESS A8-A15 OUT ADDRESS A8-A15 OUT

Figure G1: Timing Dallas 80C310, program read

ALE

IWHLH

RD

INSTRUCTION DATA IN ADQ-AD7 IN

IAVDV2 --+-----+1

PORT 2 ADDRESS AB-A15 OUT

IAVWL2 -

Figure G2: Timing Dallas 80C31O, data read

105 E~ An intelligent sensor controller using Profibus

ALE

lWHLH

PSEN 1+--- tWlWH -----I~

INSTRUCTION DATA OUT ADo-AD7 IN

tavwx

PORT 2 ADDRESS A8-A15 OUT X '------+------'---

Figure 03: Timing Dallas 80C31O, data wite

106 E~ An intelligent sensor controller using Profibus

APPENDIX H: VHDL DECODER PACKAGE

--############################################################################ -- # Filename decoder_pkg.vhd -- # •• # Package rotation-decoder; •• # -- # a, b : inputs, B is shifted 90 degrees from A -- # clk : 24 Mhz -- # reset : synchronous -- # adjust : adjust counter [bits 11·10: 0) -- # dcount : 12 bits -- # hibound 3072 reached while counting up -- # lobound : 1024 reached while counting down -- # _. # -#A~hm : P~IZ~~n -- # last.rev. : 12/06/98 --############################################################################ library ieee; use ieee.std_logic_1164.all; use ieee.stdJogic_unsigned.all; package decoder_pkg is

component grey port (clk, reset, a, b : in std_logic; upnotdwn, enable : out std_logic); end component;

component counter port ( clk, reset : in std_logic; upnotdwn, enable : in stdJogic; adjust : in std_logic; cnt : out std_logic_vector(11 downto 0); hibound, lobound : out std_logic); end component;

component decoder port ( a, b, clk, reset : in std_logic; adjust : in std_logic: dcount : out std_logic_vector(11 downto 0); hibound, lobound : out std_logic); end component; end decoder_pkg: library ieee; use ieee.std_logic_1164.all;

107 An intelligent sensor controller using Profibus E~

------•••• GREY entity grey is port ( elk, reset, a, b : in std_logic; upnotdwn, enable : out std_logic); end grey; architecture state_machine of grey is type state_type is (s4, s1, s2, s3); signal state, nextstate : state_type; signal en, up : std_logic; begin process(clk, reset) begin if rising_edge(clk) then if reset = '1' then state <= s4; enable <= '0'; upnotdwn <= '1'; else state <= nextstate; enable <= en; upnotdwn <= up; end if; end if; end process;

process(state, a, b) begin case state is

-- statecode ab=10 when s1 => if (a = '1' and b = '1') then nextstate <= s2 ; up <= '1 '; en <= '1 '; •• 10->11 elsif (a = '0' and b = '0') then nextstate <= s4; up <= '0'; en <= '1'; -. 10->00 elsif (a = '1' and b = '0') then nextstate <= s1 ; en <= '0'; up <= '0'; -- steady else nextstate <= s3; en <= '0'; up <= '0'; -- error end if;

•• statecode ab=11 when s2 => if (a = '0' and b = '1') then nextstate <= s3 ; up <= '1 '; en <= '1 '; -- 11->01 elsif (a = '1' and b = '0') then nextstate <= s1 ; up <= '0'; en <= '1 '; .- 11->10 elsif (a = '1' and b = '1 ') then nextstate <= s2 ; en <= '0'; up <= '0'; -- steady else nextstate <= s4; en <= '0'; up <= '0'; -- error end if;

-- statecode ab=01 when s3 => if (a = '0' and b = '0') then nextstate <= s4; up <= '1'; en <= '1';·- 01->00 elsif (a = '1' and b = '1 ') then nextstate <= s2 ; up <= '0'; en <= '1 '; •• 01-> 11 elsif (a = '0' and b = '1') then nextstate <= s3 ; en <= '0'; up <= '0'; •• steady else nextstate <= s1; en <= '0'; up <= '0';·· error end if;

108 E~ An intelligent sensor controller using Profibus

•• statecode ab=OO when s4 => if (a = '1' and b = '0') then nextstate <= s1 ; up <= '1'; en <= '1';··00->10 elsif (a = '0' and b = '1 ') then nextstate <= s3 ; up <= '0'; en <= '1'; -- 00->01 elsif (a = '0' and b = '0') then nextstate <= s4 ; en <= '0'; up <= '0'; •• steady else nextstate <= s2; en <= '0'; up <= '0'; •• error end if;

when others => nextstate <= s1; en <= '1';

end case; end process; end state_machine; library ieee; use ieee.std_logic_1164.all; use ieee.std_logic_unsigned.all;

.------COUNTER entity counter is port (clk, reset : in std_logic; upnotdwn, enable : in std_logic; adjust : in std_logic; cnt : out std_logic_vector(11 downto 0); hibound, lobound : out std_logic); end counter; architecture behave of counter is signal icnt : std_logic_vector(11 downto 0); signal carry : std_logic; signal borrow : std_logic; signal d1, d2 : std_logic_vector(1 downto 0); signal delta_hi: std_logic_vector(1 downto 0); alias icnUo : std_logic_vector(9 downto 0) is icnt(9 downto 0); alias icnLhi : std_logic_vector(1 downto 0) is icnt(11 downto 10); begin cnt <= icnt; 1 process (clk) variable delta: std_logic_vector(9 downto 0); begin if rising_edge(clk) then if (reset = '1 ') then icnUo <= '0000000000"; delta:= '0000000000'; else if (enable = '1 ') then if (upnotdwn = '1 ') then delta:= (0 => '1', others => '0'); else delta := (others => '1 '); end if; icnUo <= icnUo + delta; end if; end if; end if; end process;

109 E~ An intelligent sensor controller using Profibus

carry <= '1' when (upnotdwn = '1 ') and (icnUo = '1111111111') else '0';

borrow <= '1' when (upnotdwn = '0') and (icnUo = '0000000000') else '0';

d1 <= '01' when (enable = '1') and (carry = '1') else -- +1 '11' when (enable ='1 ') and (borrow ='1 ') else ---1 '00';

d2 <= '01' when (adjust = '1') and (icnChi(1) = '1') else -- +1 '11' when (adjust ='1 ') and (icnt_hi(1) ='0') else -- -1 '00';

delta_hi <= d1 + d2;

process (clk) begin if rising_edge(clk) then if reset ='1' then icnChi <= "00"; else icnChi <= icnt_hi + delta_hi; end if; end if; end process;

process (clk) begin if rising_edge(clk) then if reset ='1' then hibound <= '0'; elsif ((icnt ='010000000000") and (upnotdwn ='1 ')) then hibound <= '1 '; else hibound <= '0'; end if; end if; end process;

process (clk) begin if rising_edge(clk) then if reset ='1' then lobound <= '0'; elsif ((icnt ='110000000000") and (upnotdwn ='0')) then lobound <= '1'; else lobound <= '0'; end if; end if; end process; end behave;

110 E~ An intelligent sensor controller using Profibus

library ieee; use ieee.std_logic_1164.all; use ieee.std_logic_unsigned.all;

------ROTATION-DECODER entity decoder is port ( a, b, clk, reset : in std_logic; adjust : in std_logic; dcount : out std_logic_vector(11 downto 0); hibound, lobound : out std_logic); end decoder; architecture gedrag of decoder is

component grey port (clk, reset, a, b : in std_logic; upnotdwn, enable : out std_logic); end component;

component counter port (clk, reset : in std_logic; upnotdwn : in std_logic; enable : in std_logic; adjust : in std_logic; cnt : out stdJogic_vector(11 downto 0); hibound, lobound : out std_logic); end component;

signal ud, en : std_logic; signal cnt : std_logic_vector(11 downto 0);

begin g1 :grey port map(c1k, reset, a, b, ud, en); c1 :counter port map(clk, reset, ud, en, adjust, cnt, hibound, lobound); dcount <= cnt(11 downto 0); end gedrag;

111 An intelligent sensor controller using Profibus E~

APPENDIX I: VHDL SOURCE GLUE

-- Profibus sensor card glue logic

-- Author : P. Zinken _. Last rev.: 12-06-98

-- The later of the two signals RD or CS for the SPC4 has a setup time of -- 8 ns before rising edge of SPC4 clk

library ieee; use ieee.std_logic_1164.all; use ieee.std_logic_unsigned.all; use work.decodecpkg.all; -- package contains rotation-decoder use work.ql_macros.all; .- package contains qUicklogic macros entity memdec is port ( reset : in std_logic; rsLad : in std_logic; clk24 : in std_logic; psen, rdn, wrn : in std_logic; fasLrdn : in std_logic;

addUn_7_0 : in std_logic_vector(7 downto 0); addUn_15_12 : in std_logic_vector(15 downto 12); gpi : in std_logic_vector(7 downto 0); id : in stdJogic_vector(6 downto 0);

: inout std_logic_vector(7 downto 0); : inout std_logic_vector(11 downto 8); -- for JTAG purposes test pins:

-- dataout : out std_logic_vector(7 downto 0); -- pct : out std_logic_vector(11 downto 0);

addr_ouL16_14 : out std_logic_vector(16 downto 14); f1ash_rdn : out std_logic; flash_wrn : out std_logic; ram_rdn : out std_logic; ram_wrn : out std_logic; spc4_wrn : out std_logic; spc4_rdn : out std_logic; glue_irqn : out std_logic; outn : out std_logic_vector(3 downto 0); resetn : out std_logic); end memdec; architecture memdec_arch of memdec is subtype byte is std_logic_vector(7 downto 0); subtype offseLaddUype is stdJogic_vector(3 downto 0); constant spc4_base: std_logic_vector (15 downto 0) := X'EOOO'; constant glue_base: std_logic_vector (15 downto 0) := X'FOOO';

112 ~ An intelligent sensor controller using Profibus ELLIJ5S

•• offsets within glue constant mem_mode_offset : offseCaddUype := X"O'; constant flash_bank_offset : offseCaddctype := X'1'; constant id_offset : offseCaddctype := X'2'; constant ouUeg_offset : offseCaddr_type := X'S'; constant irq_reg_offset : offseCaddctype := X'4'; o. r_zero I clo I r_hi I latch I p_zero I p_lo I p_hi I gpUrq constant gpLoffset : offseCaddctype := X"S'; 00 General Purpose Input register constant gpUr~mask_offset : offseCaddctype := X'S'; o. GPI 0 interrupt mask register constant cntrs_hUeg_offset : offseCaddctype := X"7'; 00 highest nibble count r I highest nibble count p constant p_cnUo_reg_offset : offseCaddctype := X"S"; 00 lowest byte p_countervalue constant ccnUo_reg_offset : offseCaddctype := X"g'; •• lowest byte ccountervalue constant cnCmode_reg_offset : offseCaddUype := X"A'; 00 000000 I r_rsLenable I p_rsLenable

•• local signals alias offseCaddr : offseCaddctype is addcinJ_O(S downto 0); signal d_in. d_out : byte; signal glue_cs : std_logic; signal mem_mode : std_logic_vector(1 downto 0); signal flash_bank : stdJogic_vector(2 downto 0); signal wrn_delayed1 : std_logic; signal wrn_delayed11 : std_logic; signal wrn_delayed2 : std_logic; signal rdn_delayed1 : std_logic; signal rdn_delayed2 : std_logic; signal flash_rdsel, ram_rdsel : std_logic; signal spc4_rdsel, rdsel : std_logic;

•• clock's signal clk, clkn. clk_c

•. outputs signal ouCreg : std_logic_vector(S downto 0);

•• general purpose inputs signal sgpi. dsgpi : std_logic_vector(7 downto 0); signal gpUrq : std_logic; signal gpUrq_mask_reg : std_logic_vector(7 downto 0); signal gpUrq_mask3s : std_logic;

•• position encoder signal p_count : std_logic_vector(11 downtoO); signal sp_cnLreg : std_logic_vector(11 downto 0); signal p_rst, p_adj : std_logic; signal p_adjust : std_logic; signal p_rscenable : std_logic; signal p_lo, p_hi : std_logic; signal sp_zero. sp_hi. sp_lo : std_logic; signal dsp_hi. dsp_lo : std_logic;

•. roll encoder signal r_count : std_logic_vector(11 downto 0); signal sr3nt_reg : std_logic_vector(11 downto 0); signal ust. r_adj : std_logic; signal r_adjust : std_logic; signal r_rsCenable : std_logic; signal Uo, Chi : std_logic; signal sUo, sChi, sczero : std_logic; signal dsr_hi, dsUo : std_logic; signal latch : std_logic; signal dlatch, latchcnt : std_logic;

113 An intelligent sensor controller using Profibus E~

begin

•• test pins

-- dataout <= d_out when ((glue3s ='1') and (rdn ='0')) else 'ZllZllll';

•• pct(11 downto 0) <= r_count;

.- split bidirectional ad bus in internal d_in and d_out busses d_in <= ad; ad <= d_out when ((glue3s = '1 ') and (rdn = '0')) else ?ZZZZZZZ';

d_out <= '000000' & mem_mode when offseCaddr =mem_mode_offset else '00000' & flash_bank when offseCaddr =flash_bank_offset else "0' & id when offseCaddr =id_offset else '0000" & ouUeg when offseCaddr =oucreg_offset else sgpi when offseCaddr =gpLoffset else gpUrq_mask_reg when offseCaddr = gpUrq_mask_offset else sr_zero & sUo & sr_hi & latch & sp_zero & sp_lo & sp_hi & gpUrq when offseCaddr = irq_reg_offset else sp3nUeg(11 downto 8) & sccnUeg(11 downto8) when offsecaddr = cntrs_hLreg_offset else sp3nUeg(7 downto 0) when offset_addr =p_cnUo_reg_offset else sr3nUeg(7 downto 0) when offseCaddr =r_cnUo_reg_offset else '000000" & usCenable & p_rsCenable when offseCaddr = cncmode_reg_offset else .------_.;

------••-•••----- MMU

-- memmode reg process (reset, wrn) begin if (reset = '1 ') then mem_mode <= '00'; else if rising_edge(wrn) then if (offset_addr =mem_mode_offset) then jf (glue3s ='1') then mem_mode <= d_in(1 downto 0); end if; end if; end if; end if; end process;

114 An intelligent sensor controller using Profibus E~

-- flash_bank reg process (reset, wrn) begin if (reset ='1 ') then flash_bank <= '000'; else if rising_edge(wrn) then if (offseCaddr =flash_bank_offset) then if (glue_cs ='1 ') then flash_bank <= d_in(2 downto 0); end if; end if; end if; end if; end process;

-- read/write signal generation process (rdn, wrn, wrn_delayed2, addUn_15_12, mem_mode, flash_bank) begin if ((rdn ='1') and (wrn ='1')) then -- program memory spc4_rdsel <= '0'; glue_cs <= '0'; spc4_wrn <= '1'; ram_wrn <= '1'; f1ash_wrn <= '1 ';

case mem_mode is when "00' => -- lower 64K of flash addr_ouU6_14 <= '0' & addUn_15_12(15 downto 14); flash_rdsel <= '1'; ram_rdsel <= '0';

when '01' => -- upper 64K of flash addr_ouU6_14 <= '1' & addUn_15_12(15 downto 14); flash_rdsel <= '1'; ram_rdsel <= '0';

when "10' => -- 32K RAM only addr_ouU 6_14 <= '0' & addUn_15_12(15 downto 14); flash_rdsel <= '0'; ram_rdsel <= '1';

when others => -- illegal mode addr_ouC16_14 <= '---'; flash_rdsel <= '0'; ram_rdsel <= '0'; end case; else -- data memory if (addUn_15_12(15) ='0') then -- lower 32K is RAM addr_ouU6_14 <= '0' & addUn_15_12(15 downto 14); flash_rdsel <= '0'; flash_wrn <= '1'; ram_rdsel <= '1 '; ram_wrn <= wrn_delayed2; spc4_rdsel <= '0'; spc4_wrn <= '1'; glue_cs <= '0'; else

115 An intelligent sensor controller using Profibus E~

if (addUn_15_12(14) = '1') then -- COOO-FFFF addcouL16_14 <= •••••; flash_rdsel<= '0'; f1ash_wrn <= '1 '; ram_rdsel <= '0'; ram_wrn <= '1';

if (addUn_15_12(13 downto 12) = spc4_base(13 downto 12)) then spc4_rdsel<= '1'; spc4_wrn <= wrn_delayed2; else spc4_wrn <= '1 '; spc4_rdsel<= '0'; end if;

if (addUn_15_12(13 downto 12) = glue_base(13 downto 12)) then glue_cs <= '1 '; else glue_cs <= '0'; end if;

else -- 8000-BFFF addcouL16_14 <= flash_bank; flash_rdsel <= '1 '; flash_wrn <= wrn_delayed2; ram_rdsel <= '0'; ram_wrn <= '1'; spc4_rdsel <= '0'; spc4_wrn <= '1 '; glue_cs <= '0'; end if; end if; end if; end process;

------delay rdn and wrn

-- use cktpad for clk24 C1: CKTPAD port map( P => clk24, -- clk24 input 00 => clkn, -- inverted clock output 01 => clk, -- hidrive clock output 02 => clk_c -- normal clock output );

-- Use d'Morgan:

-- rdsel = (not(psen)) or (not(rdn_delayed2)) not(psen and rdn_delayed2)

-- ram_rdn = not(rdsel and ram_rdsel) -- ram_rdn = not[not(psen and rdn_delayed2) and rdn_delayed2) -- ram_rdn = (psen and rdn_delayed2) or (not(ram_rdsel))

116 E~ An intelligent sensor controller using Profibus

-- make delayed 'short' rdn/wrn process (elk, reset) begin if (reset = '1 ') then wrn_delayed1 <= '1'; else if rising_edge(clk) then wrn_delayed1 <= wrn; end if; end if; end process; process (elk, reset, wrn, wrn_delayed1) begin if (reset ='1 ') or ((wrn = '1 ') and (wrn_delayed1 ='O'))then wrn_delayed11 <= '1 '; else if rising_edge(c1k) then wrn_delayed11 <= wrn_delayed1; end if; end if; end process; process (clkn, reset, wrn, wrn_delayed1) begin if (reset = '1 ') or ((wrn = '1 ') and (wrn_delayed1 = '0'» then wrn_delayed2 <= '1'; else if rising_edge(clkn) then wrn_delayed2 <= wrn_delayed1; end if; end if; end process; process (elk, reset) begin if (reset = '1 ') then rdn_delayed1 <= '1 '; else if rising_edge(clk) then rdn_delayed1 <= rdn; end if; end if; end process; process (clkn, reset, fasLrdn) begin if (reset = '1 ') or (fasUdn ='1 ') then rdn_delayed2 <= '1 '; else if rising_edge(clkn) then rdn_delayed2 <= rdn_delayed1; end if; end if; end process;

117 An intelligent sensor controller using Profibus Eiiis

rdsel <= (psen and rdn_delayed2); -- active high rdsel!

-- pads for rdn signals

81: OUTORPAD port map( A1 => ram_rdsel, -- inverted input A2 => rdsel, -- normal input P => ram_rdn -- output );

82: OUTORPAD port map( A1 => spc4_rdsel, A2 => rdsel, P => spc4_rdn );

83: OUTORPAD port map( A1 => flash_rdsel, A2 => rdsel, P => f1ash_rdn );

••••••••••••••••••••••-._-- OUTN

.- out-register process(wrn, reset, glue_cs) begin if reset ='1' then ouCreg <= ·0000"; else if rising_edge(wrn) then if (offseCaddr = ouUeg_offset) then if (glue_cs ='1 ') then ouUeg <= djn(3 downto 0); end if; end if; end if; end if; outn <= not(ouCreg); -- active low outputs! end process;

------GPI gpUrq_mask_cs <= '1' when ((glue_cs = '1 ') and (offseCaddr = gpUrq_mask_offset)) else '0';

118 An intelligent sensor controller using Profibus E~

-- gpUrq_mask process (wrn, reset) begin if (reset = '1 ') then -- all interrupts disabled gpUrq_mask_reg <= '00000000'; -- Sr, SO, Cr, Br, Ar, Cp, [Bp, (Sd2)], [Ap/(SdllSfull}], 1=enable else if rising_edge(wrn} then if (gpUrq_mask_cs = '1 ') then gpUrq_mask_reg <= d_in; end if; end if; end if; end process;

-- synchronise gpi with clk process (clk) begin if rising_edge(clk} then sgpi <= gpi; end if; end process;

-- delay sgpi (metastability!) process (elk) begin if rising_edge(clk} then dsgpi <= sgpi; end if; end process;

----.-.------counter registers

-- gpi interrupt process (clk, reset) begin if (reset = '1 ') then gpUrq <= '0'; else if rising_edge(clk} then if ((glue_cs = '1 ') and (offsecaddr = irq_reg_offset» then if (wrn_delayed11 = 'O') then if (d_in(O) = 'O'} then gpUrq <= '0'; end if; else if ( (sgpi(7 downto O) and gpUrq_mask_reg} 1= (dsgpi(7 downto O) and gpUrq_mask_reg} } then gpUrq <= '1'; end if; end if; end if; end if; end if; end process;

119 ~ An intelligent sensor controller using Profibus ELLIPS

-- hi/1o bound indication process (clk, reset) begin if (reset = '1 ') then sp_hi <= '0'; sp_lo <= '0'; sehi <= '0'; sUo <= '0'; else if rising_edge(clk) then if ((glue_cs = '1 ') and (offseLaddr = irCL-reg_offset)) then if (wm_delayed11 = '0') then

if (d_in(1) = '0') then sp_hi <= '0'; end if; if (d_in(2) ='0') then sp_lo <= '0'; end if; if (d_in(5) ='0') then sehi <= '0'; end if; if (d_in(6) = '0') then sUo <= '0'; end if;

end if; else if (p_lo ='1 ') then sp_lo <= '1'; end if; if (p_hi = '1') then sp_hi <= '1'; end if; if (Uo ='1') then sUo <= '1'; end if; if (Chi ='1 ') then sr_hi <= '1'; end if; end if; end if; end if; end process;

.- zero indication process (clk, reset) begin if (reset ='1 ') then sp_zero <= '0'; sr_zero <= '0'; erst <= '0'; p_rst <= '0'; else if rising_edge(clk) then if ((glue_cs ='1 ') and (offseLaddr =irq_reg_offset)) then if (wrn_delayed11 ='0') then if (d_in(3) = '0') then sp_zero <= '0'; end if; if (d_in(7) = '0') then sezero <= '0'; end if; end if; else if ((sgpi(2) = '1') and (p_rsLenable = '1 ')) then sp_zero <= '1 '; p_rst <= '1 '; else p_rst <= '0'; end if;

if ((sgpi(5) ='1 ') and (erst_enable ='1 ')) then sezero <= '1 '; erst <= '1 '; else r_rst <= '0'; end if; end if; end if; end if; end process;

120