(Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

308

Transcript of (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Page 1: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing
Page 2: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Newnes Interfacing Companion

Page 3: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

To Robert Winston Cheary,friend and teacher.

Page 4: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

OXFORD AMSTERDAM BOSTON LONDON NEW YORK PARISSAN DIEGO SAN FRANCISCO SINGAPORE SYDNEY TOKYO

Page 5: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

NewnesAn imprint of Elsevier ScienceLinacre House, Jordan Hill, Oxford OX2 8DP225 Wildwood Avenue, Woburn MA 01801-2041

First published 2002

Copyright 2002, A. C. Fischer-Cripps. All rights reserved

The right of A. C. Fischer-Cripps to be identified as the author of this workhas been asserted in accordance with the Copyright, Designs andPatents Act 1988

No part of this publication may be reproduced in any material form (includingphotocopying or storing in any medium by electronic means and whetheror not transiently or incidentally to some other use of this publication) withoutthe written permission of the copyright holder except in accordance with theprovisions of the Copyright, Designs and Patents Act 1988 or under the terms ofa licence issued by the Copyright Licensing Agency Ltd, 90 Tottenham Court Road,London, England W1T 4LP. Applications for the copyright holder's writtenpermission to reproduce any part of this publication should be addressedto the publisher

British Library Cataloguing in Publication DataA catalogue record for this book is available from the British Library

Library of Congress Cataloguing in Publication DataA catalogue record for this book is available from the Library of Congress

ISBN 0 750 65720 0

For information on all Newnes publications visit our website at www.newnespress.com

Printed and bound in Great Britain

Page 6: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Preface ix......................................................

Part 1: Transducers 1.................................1.0 Transducers 2.................................................1.1 Measurement systems 3.................................

1.1.1 Transducers 4...............................................1.1.2 Methods of measurement 5...........................1.1.3 Sensitivity 6...................................................1.1.4 Zero, linearity and span 7..............................1.1.5 Resolution, hysteresis and error 8.................1.1.6 Fourier analysis 9..........................................1.1.7 Dynamic response 10......................................1.1.8 PID control 11..................................................1.1.9 Accuracy and repeatability 12.........................1.1.10 Mechanical models 13...................................1.1.11 Review questions 14.....................................

1.2 Temperature 15................................................1.2.1 Temperature 16...............................................1.2.2 Standard thermometers 17..............................1.2.3 Industrial thermometers 18..............................1.2.4 Platinum resistance thermometer 19...............1.2.5 Liquid-in-glass thermometer 20.......................1.2.6 Radiation pyrometer 21...................................1.2.7 Thermocouple 22............................................1.2.8 Thermistors 24................................................1.2.9 Relative humidity 25........................................1.2.10 Review questions 26.....................................1.2.11 Activities 28...................................................

1.3 Light 34.............................................................1.3.1 Light 35............................................................1.3.2 Measuring light 36...........................................1.3.3 Standards of measurement 37........................1.3.4 Thermal detectors 38......................................1.3.5 Light dependent resistor (LDR) 39..................1.3.6 Photodiode 40.................................................1.3.7 Other semiconductor photodetectors 41.........1.3.8 Optical detectors 42........................................1.3.9 Photomultiplier 43............................................1.3.10 Review questions 44.....................................

1.4 Position and motion 45.....................................1.4.1 Mechanical switch 46......................................1.4.2 Potentiometric sensor 47.................................1.4.3 Capacitive transducer 48.................................

Page 7: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.4.4 LVDT 49..........................................................1.4.5 Angular velocity transducer 50........................1.4.6 Position sensitive diode array 51.....................1.4.7 Motion control 52.............................................1.4.9 Review questions 53.......................................

1.5 Force, pressure and flow 54.............................1.5.1 Strain gauge 55...............................................1.5.2 Force 57..........................................................1.5.3 Piezoelectric sensor instrumentation 58..........1.5.4 Acceleration and vibration 59..........................1.5.5 Mass 60...........................................................1.5.6 Atmospheric pressure 61................................1.5.7 Pressure 63.....................................................1.5.8 Industrial pressure measurement 64...............1.5.9 Sound 65.........................................................1.5.10 Flow 66..........................................................1.5.11 Level 69.........................................................1.5.12 Review questions 70.....................................

Part 2: Interfacing 71.....................................2.0 Interfacing 72....................................................2.1 Number systems 73..........................................

2.1.1 Binary number system 74................................2.1.2 Decimal to binary conversion 75.....................2.1.3 Hexadecimal 76...............................................2.1.4 Decimal to hex conversion 77.........................2.1.5 2s complement 78..........................................2.1.6 Signed numbers 79.........................................2.1.7 Subtraction and multiplication 80....................2.1.8 Binary coded decimal (BCD) 81......................2.1.9 Gray code 82...................................................2.1.10 ASCII code 83...............................................2.1.11 Boolean algebra 84.......................................2.1.12 Digital logic circuits 85...................................2.1.13 Review questions 86.....................................2.1.14 Activities 87...................................................

2.2 Computer architecture 88.................................2.2.1 Computer architecture 89................................2.2.2 Memory 90......................................................2.2.3 Segmented memory 91...................................2.2.4 Memory data 92..............................................2.2.5 Buffers 93........................................................2.2.6 Latches 94.......................................................2.2.7 Flip-flop 95.......................................................2.2.8 Input/Output (I/O) 96.......................................

Page 8: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

2.2.9 Microprocessor unit (MPU/CPU) 97................2.2.10 Registers 98..................................................2.2.11 ROM 101.........................................................2.2.12 Interrupts 102..................................................2.2.13 Memory map 104............................................2.2.14 Real and protected mode CPUoperation 105.............................................................2.2.15 Review questions 107.....................................2.2.16 Activities 108...................................................

2.3 Assembly language 111......................................2.3.1 Instruction set 112.............................................2.3.2 Assembly language 113....................................2.3.3 Program execution 114.....................................2.3.4 Assembly language program structure 115.......2.3.5 Assembler directives 116..................................2.3.6 Code segment 117............................................2.3.7 Assembly language shell program 118.............2.3.8 Branching 119...................................................2.3.9 Register and immediate addressing 120...........2.3.10 Memory addressing 121..................................2.3.11 Indirect memory addressing 122.....................2.3.12 Indexed memory addressing 123....................2.3.14 Interrupts 124..................................................2.3.15 Review questions 125.....................................2.3.16 Activities 126...................................................

2.4 Interfacing 131....................................................2.4.1 Interfacing 132...................................................2.4.2 Input/Output ports 133.......................................2.4.3 Polling 134.........................................................2.4.4 Interrupts 135....................................................2.4.5 Direct memory access (DMA) 136....................2.4.6 Serial port 137...................................................2.4.7 Serial port addresses 138.................................2.4.8 Serial port registers 139....................................2.4.9 Serial port registers and interrupts 140.............2.4.10 Serial port baud rate 141.................................2.4.11 Serial port operation 142.................................2.4.12 Parallel printer port 143...................................2.4.13 Parallel port registers 144...............................2.4.14 Parallel printer port operation 145...................2.4.15 Review questions 146.....................................

2.5 A to D and D to A conversions 147.....................2.5.1 Interfacing 148...................................................2.5.2 The Nyquist criterion 149..................................2.5.3 Resolution and quantisation noise 150.............2.5.4 Oversampling 151.............................................

Page 9: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

2.5.5 Analog to digital converters 152........................2.5.6 ADC (integrating method) 153...........................2.5.7 ADC (successive approximation) 154...............2.5.8 Aperture error 155.............................................2.5.9 ADC08xx chip 156.............................................2.5.10 Sample-and-hold 157......................................2.5.11 Sample-and-hold control 158..........................2.5.12 Digital to analog conversion 159.....................2.5.13 DAC0800 160..................................................2.5.14 Data acquisition board 161..............................2.5.15 Review questions 162.....................................

2.6 Data communications 163..................................2.6.1 Communications 164.........................................2.6.2 Byte to serial conversion 165............................2.6.3 RS232 interface 166..........................................2.6.4 Synchronisation 167..........................................2.6.5 UART (6402) 168..............................................2.6.7 Line drivers 170.................................................2.6.8 UART clock 171................................................2.6.9 UART Master Reset 172...................................2.6.10 Null modem 173..............................................2.6.11 Serial port BIOS services 174.........................2.6.12 Serial port operation in BASIC 175.................2.6.13 Hardware handshaking 176............................2.6.14 RS485 177......................................................2.6.15 GPIB 178.........................................................2.6.16 USB 179..........................................................2.6.17 TCP/IP 181......................................................2.6.18 Review questions 182.....................................

2.7 Programmable logic controllers 183...................2.7.1 Programmable logic controllers 184..................2.7.2 Timing 185.........................................................2.7.3 Functional components 186..............................2.7.4 Programming 187..............................................2.7.5 Ladder logic diagrams 188................................2.7.6 PLC specifications 190......................................2.7.7 Review questions 191.......................................

2.8 Data acquisition project 192................................2.8.1 Serial data acquisition system 193....................2.8.2 Circuit construction 195.....................................2.8.3 Programming 201..............................................2.8.4 Sample-and-hold 206........................................2.8.5 Digital to analog system 208.............................

Part 3: Signal processing 211........................

Page 10: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

3.0 Signal processing 212.........................................3.1 Transfer function 213..........................................

3.1.1 Instrumentation 214...........................................3.1.2 Transfer function 215........................................3.1.3 Transforms 216.................................................3.1.4 Laplace transform 217.......................................3.1.5 Operator notation 218.......................................3.1.6 Differential operator 219....................................3.1.7 Integrator passive 220.....................................3.1.8 Differentiator passive 221................................3.1.9 Transfer impedance 222...................................3.1.10 Review questions 223.....................................3.1.11 Activities 224...................................................

3.2 Active filters 227..................................................3.2.1 Filters 228..........................................................3.2.2 T -network filters 229.........................................3.2.3 Twin-T filter 230.................................................3.2.4 Active integrator/differentiator 231....................3.2.5 Integrator transfer function 232.........................3.2.6 Low pass filter active 233................................3.2.7 2nd order active filter 234..................................3.2.8 Double integrator 235........................................3.2.9 Bandpass filter narrow 236..............................3.2.10 Differentiator transfer function 237..................3.2.11 High pass filter active 238.............................3.2.12 High pass filter w domain 239.......................3.2.13 Bandpass filter wide 240...............................3.2.14 Voltage gain and dB 241.................................3.2.15 Review questions 242.....................................3.2.16 Activities 244...................................................

3.3 Instrumentation amplifier 246..............................3.3.1 Difference amplifier 247....................................3.3.2 CMRR 248.........................................................3.3.3 Difference amplifier with voltagefollower inputs 249.....................................................3.3.4 Difference amplifier with cross-coupledinputs 250...................................................................3.3.5 CMRR cross-coupled inputs 251.......................3.3.6 Instrumentation amplifier 252............................3.3.7 Log amplifier 253...............................................3.3.8 Op-amp frequency response 254......................3.3.9 Review questions 255.......................................3.3.10 Activities 257...................................................

3.4 Noise 261............................................................3.4.1 Intrinsic noise 262.............................................

Page 11: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

3.4.2 Environmental noise 263...................................3.4.3 Signal-to-noise ratio 264...................................3.4.4 Optical detectors 265........................................3.4.5 Lock-in amplifier 266.........................................3.4.6 Correlation 267..................................................3.4.7 Review questions 268.......................................

3.5 Digital signal processing 269..............................3.5.1 Digital filters 270................................................3.5.2 Fourier series 271.............................................3.5.3 Fourier transform 272........................................3.5.4 Sampling 273....................................................3.5.5 Discrete Fourier transform 274..........................3.5.6 Filtering 275.......................................................3.5.7 Digital filtering (domain) 276..............................3.5.8 Convolution 277................................................3.5.9 Discrete convolution 278...................................3.5.10 Digital filtering (t-domain) 279.........................3.5.11 Example 280...................................................3.5.12 Smoothing transfer function 281.....................3.5.13 Review questions 282.....................................3.5.14 Activities 283...................................................

Index 286..........................................................

Further reading 294.........................................

Parts lists for activities 295............................

Page 12: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Preface

The overall aim of this book is to present transducer devices,computer interfacing and instrumentation electronics in a succinctand memorable fashion. The book combines physics, computerscience and electrical engineering in a science/engineering context.Starting from the transfer of physical phenomena to electrical signals,the book presents a comprehensive treatment of computer interfacingand finishes with signal conditioning, data analysis and digitalfiltering. The book covers a wide scope but contains sufficient detailto allow a practical application of the theory. Detailed explanationsare given, even of the most difficult of concepts. The reviewproblems offer a level of complexity which provides sufficientchallenge to impart a sense of achievement upon their completion.The accompanying project work reinforces the theoretical workwhile allowing the reader to gain the satisfaction and experience ofactually constructing a working interfacing circuit that can be usedon any personal computer with a serial port. The book will be usefulfor students who are new to the subject, and will serve as a handyreference for experienced engineers who wish to refresh theirknowledge of a particular topic.

In writing this book, I was assisted and encouraged by manycolleagues. In particular, I acknowledge the contributions of AlecBendeli, Stephen Buck, Bob Graves, Walter Kalceff, Les Kirkup,Geoff Smith, Paul Walker, my colleagues at the University ofTechnology, Sydney, the staff of the CSIRO Division ofTelecommunications and Industrial Physics, and all my formerstudents. My sincere thanks to my wife and family for their unendingencouragement and support. Finally, I thank Matthew Deans, JodiBurton and the editorial and production teams at Newnes for theirvery professional and helpful approach to the whole publicationprocess.

Tony Fischer-Cripps,Killarney Heights, Australia, 2002

xi

Page 13: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Newnes Interfacing Companionxii

Page 14: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1

Page 15: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.0 TransducersA measurement system is concerned with the representation of onephysical phenomenon by another. The purpose of the measurement systemis for the measurement and control of a physical system.

In Part 1 of this book,we are mainly interestedin transducers.• A sensor is a device

which responds to aphysical stimulus

• A transducer is adevice which converts aphysical stimulus toanother form of energy(usually electrical)

Physicalphenomena:SoundMeter readingLED indicatorDigital displayChart recorderVDU output

Physicalphenomena:TemperatureVoltagePositionVelocityForcePressureRadioactivityLight intensityResistanceHumidityGas concentrationMagnetic fieldFrequencySound level

Actuatorprovides aphysical

response toelectrical signal.

Actuator

Optionalfeedback

Transducer(sensor and

preamplifier)

Amplifier andsignal

conditioning

Computerinterface

Part 2 of thisbook isconcerned withcomputerinterfacing.

Part 3 of thisbook coversinstrumentationand signalprocessing.

Newnes Interfacing Companion2

Page 16: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

3

Page 17: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.1.1 Transducers

Of most interest are the physical properties and performancecharacteristics of a transducer. Some examples are given below:

Strain Strain gauge, a resistive transducer whose resistancechanges with length.

Temperature Resistance thermometer, thermocouple, thermister,thermopile.

Humidity Resistance change of hygroscopic material.Pressure Movement of the end of a coiled tube under

pressure.Voltage Moving coil in a magnetic field.Radioactivity Electrical pulses resulting from ionisation of gas at

low pressure.Magnetic field Deflection of a current carrying wire.

Property Method of measurement

Performance characteristics

SensitivityZero offsetLinearityRangeSpanResolutionThresholdHysteresisRepeatability

Response timeDampingNatural frequencyFrequency response

Operating temperaturerangeOrientationVibration/shock

Static Dynamic Environmental

A consideration of these characteristics influences thechoice of transducer for a particular application.Further characteristics which are often important arethe operating life, storage life, power requirementsand safety aspects of the device as well as cost andavailability of service.

In industrial situations, the property being measured or controlled is calledthe controlled variable. Process control is the procedure used to measurethe controlled variable and control it to within a tolerance level of a setpoint. The controlled variable is one of several process variables and ismeasured using a transducer and controlled using an actuator.

Newnes Interfacing Companion4

Page 18: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

An unknown component is inserted into thebridge and the values of the others arealtered to achieve balance condition.At balance, nocurrent flowsthrough thegalvanometer G.

Null method

Deflection method

• Direct comparison• No loading• Can be relatively slow

• Indirect comparison• Deflection from zero until

some balance conditionachieved

• Limited in precision andaccuracy

• Loading (transducer itselftakes some energy fromthe system beingmeasured)

• Relatively fast

Null method: Bridge circuit.

3

u

4

1

3

u41

CR

CR

CL

RR

=

=

Deflection method:Moving coil voltmeter.

1.1.2 Methods of measurement

All measurements involve acomparison between ameasured quantity and areference standard. Thereare two fundamentalmethods of measurement:

Although such a meter is designed to have avery high internal impedance, it has to drawsome current from the circuit being measuredin order to cause a deflection of the pointer.This may affect the operation of the circuititself and lead to inaccurate readings –especially if the output resistance of thevoltage source being measured is large.

pointer

coil

magnet

C3 R1

C4

Ru

Lu

R4

G

1.1 Measurement systems 5

Page 19: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.1.3 Sensitivity

An important parameter associated with every transducer is its sensitivity.This is a measure of the magnitude of the output divided by the magnitudeof the input.

dIdO

signalinput signaloutput ysensitivit

=

=

In most applications, the chances are that the signal produced by thetransducer contains noise, or unwanted information. The proportion ofwanted to unwanted signal is called the signal-to-noise ratio or SNR(usually expressed in decibels).

input detectableleast 1d =

e.g. If d = 106 V-1 for a voltmeter, it meansthat the device can measure a voltage as lowas 10-6 V.

e.g. The sensitivity of a thermocouple maybe specified as 10 µV/oC indicating that foreach degree change in temperature betweenthe sensor and the “reference” temperature,the output signal changes by 10 µV. Thesensitivity may not be a constant across theworking range.

The higher the SNR the better. Inelectronic apparatus, noise signals oftenarise due to thermal random motion ofelectrons and is called white noise.White noise appears at all frequencies.

The first stage of any amplification of signalis the most critical when dealing with noise.In most sensitive equipment, a preamplifieris connected very close to the transducer tominimise noise and the resulting amplifiedsignal passed to a main, or power amplifier.

The noise produced by a transducer limits its ability to detect very smallsignals. A measure of performance is the detectivity given by:

n

S10 V

Vlog20SNR =

Signalvoltage

Noisevoltage

The least detectable input is often referred to as the noise floor of theinstrument. The magnitude of the noise floor may be limited by thetransducer itself or the effect of the operating environment.

The output voltage of most transducers is in the millivolt range forinterfacing in a laboratory or light industrial applications. For heavyindustrial applications, the output is usually given as a current rather than avoltage. Such devices are usually referred to as “transmitters” rather thantransducers.

Newnes Interfacing Companion6

Page 20: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

e.g. A thermocouple has an input range of −100to +300 oC and an output range of −1 to +10 mV.

The span or full scale deflection (fsd) is the maximum variation in theinput or output:

e.g. The thermocouple above has an input spanof 400 oC and an output span S of 11 mV .

The % of non-linearity describes thedeviation of a linear relationshipbetween the input and the output.

Max non-linearity = 100

δ

Zero offset errors can occur becauseof calibration errors, changes orageing of the sensor, a change inenvironmental conditions, etc. Theerror is a constant over the range ofthe instrument.

Zero and span calibration controls:

A change in sensitivity, or a spanerror, results in the output beingdifferent to the correct value by aconstant %. That is, the error isproportional to the magnitude ofthe output signal (change in slope).

A linear output can be obtained byusing a look-up table or altering theoutput signal electronically.

1.1.4 Zero, linearity and span

The range of a transducer is specified by the maximum and minimuminput and output signals.

minmax OOS −=

O

I

Actual(non-linear)response

δ

S Desired linearresponse

O O

I I

Zero adjustmentchanges theintercept

Span adjustmentchanges the slope

Slope of the lineis thesensitivity

span

71.1 Measurement systems

Output maximum and minimum

Input signal

Page 21: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.1.5 Resolution, hysteresis and error

A continuous increase in the input signal sometimes results in a series ofdiscrete steps in the output signal due to the nature of the transducer.

e.g. A wire wound potentiometerbeing used as a distancetransducer. The wiper moves overthe windings bringing a stepchange in resistance (R of oneturn) with a change in distance.

The resolution of a transducer is defined as the size of the stepdivided by the fsd or span and is given in %.

SOδ

Resolution =e.g. The resolution of a 100 turnpotentiometer is 1/100 = 1%.

For a particular input signal, the magnitude of the output signal maydepend on whether the input is increasing or decreasing − this is calledhysteresis.

Maximumhysteresis = 100

δ

In mechanical systems,hysteresis usually occursdue to backlash in movingparts (e.g. gear teeth).

The general response ofa transducer is usuallygiven as a percent error.

100S×

δError =

O

I

δ

S

Hysteresis may lead tozero, span and non-linearity errors.

O

I

Actual responsecontaining zerooffset, non-linearity, spanerrors, etc.

δ

S

Theoreticalresponse

Newnes Interfacing Companion8

Page 22: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.1.6 Fourier analysis

Analog input signals that require sampling by a digital to analog convertersystem do not usually consist of just a single sinusoidal waveform. Realsignals usually have a variety of amplitudes and frequencies that vary withtime.

For example, a square wavecan be represented using thesum of individual componentsine waves:

π+ω

π+ω

π= ...t5sin

54t3sin

34tsin4y

Amplitude ofcomponent Frequency of

component

tsin4y ω

π

=

ω

π+ω

π= t3sin

34tsin4y

ω

π+ω

π+ω

π= t5sin

54t3sin

34tsin4y

ωt

y

π

1

−1

Such signals can be broken down into component frequencies and amplitudesusing a method called Fourier analysis. Fourier analysis relies on the factthat any periodic waveform, no matter how complicated, can be constructedby the superposition of sine waves of the appropriate frequency andamplitude.

Fourier analysis, or the breakingup of a signal into its componentfrequencies, is important when weconsider the process of filteringand the conversion of an analogsignal into a digital form.

91.1 Measurement systems

Page 23: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.1.7 Dynamic response

The dynamic response of atransducer is concerned withthe ability for the output torespond to changes at theinput. The most severe testof dynamic response is tointroduce a step signal at theinput and measure the timeresponse of the output.

Input(step)

1. Under-damped

3. Over-damped

2. Criticallydamped

Various formsof output

tOf particular interest arethe following quantities:

• Rise time• Response time• Time constant τ

A step signal at the inputcauses the transducer torespond to an infinitenumber of componentfrequencies. When theinput varies in asinusoidal manner, theamplitude of the outputsignal may varydepending upon thefrequency of the input ifthe frequency of theinput is close to theresonant frequency ofthe system. If the inputfrequency is higher thanthe resonant frequency,then the transducercannot keep up with therapidly changing inputsignal and the outputresponse decreases as aresult.

O

finput

Bandwidth

Resonantfrequency

3 dBpoint

21

'OO

=

Frequencyrange

O

t

63%

τ

90%

Responsetime

Rise time

5%

O’

O

Newnes Interfacing Companion10

Page 24: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.1.8 PID control

In many systems, a servo feedback loop is used to control a desired quantity.For example, a thermostat can be used in conjunction with an electric heaterelement to control the temperature in an oven. Such a servo loop consists of asensor whose output controls the input signal to an actuator.The difference between the target or set point and the current value of thecontrolled variable is the error signal ∆e. If the error is larger than somepreset tolerance or error band, then a correction signal, positive ornegative, is sent to the actuator to cause the error to be reduced. Insophisticated systems, the error signal is processed by a PID controllerbefore a correction signal is sent to the actuator. The PID controllerdetermines the magnitude and type of the correction signal to be sent to theactuator to reduce the error signal.

The PID correction acts upon the error signalwhich is itself a function of time. The PIDcorrection is thus also a function of time. Forexample, in servo motion control, a PIDcontroller is able to cause the moving body (e.g.a robot arm) to accelerate, maintain a constantvelocity, and decelerate to the target position.

The characteristics of a PID controller are expressed in terms of gains. Thecorrection signal O from the PID controller to the actuator is given by thesum of the error ∆e term multiplied by the proportional gain Kp, theintegral gain, Ki and the derivative gain Kd.

( )dt

edKdteKeKtO dIp∆

+∆+∆= ∫• The proportional term causes the controller to generate a signal to

the actuator whose amplitude is proportional to the magnitude of theerror. That is, a large correction is made to correct a large error.

• The integral term is used to ramp the actuator to the final state toovercome friction or hysteresis in the system. It is a long-termcorrection and allows the system to servo to the target value.

• The derivative signal offers a damping response that reducesoscillation. The magnitude of the derivative correction dependsupon the rate of change of the magnitude of the error signal. If thesignal changes rapidly, a large correction is made.

Constantvelocity

Acceleration

Decelerationv

t

111.1 Measurement systems

Page 25: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.1.9 Accuracy and repeatability

Accuracy is a quantitative statement about the closeness of a measuredvalue with the true value.

The true value of a quantity is thatwhich is specified by internationalagreement.

The kilogram is the unit ofmass and is equal to themass of an internationalstandard kilogram held inParis.

+

true value

++

++

+

true value+

++

+

+

+

++++

+

true value

+

High precisionLow accuracy

Low precisionHigh accuracy

High precisionHigh accuracy

This condition could be caused by asystematic error in the measuringsystem (e.g. zero offset).

This condition could be caused by arandom error in the measuring system.

There is a difference between theaccuracy and the precision of physicalmeasurements.

High precision need not beaccompanied by high accuracy.Precision is measured by the standarddeviation of several measurements.

High accuracy may also beaccompanied by a wide scatter inthe measurement readings leadingto low precision.

Newnes Interfacing Companion12

Page 26: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

If two (or more) springsare connected in series,then loaded with acommon force, then thetotal overall stiffness isgiven by:

If two or more springs areconnected in parallel, thenthey experience a commondisplacement. In this case,the overall stiffness is givenby:

∑=

= n

1i ik1

1k

k1

k2

k3

F

∑=

=

n

1iikk

k1 k2 k3

F

F1 F2 F3

Deflection of springs

1.1.10 Mechanical models

The response of materials and systems can often be modelled by springs anddashpots. This allows both static and dynamic processes to be modelledmathematically with some convenience. Most materials have a mechanicalcharacter that falls somewhere in between the two extremes of a solid and afluid. Springs represent the solid-like characteristics of a system. Dashpotsrepresent the fluid-like aspects of a system.

k

kxF =

n

dtdxF λ=

dtdxkxF λ+=

λ

Maxwell

λ

k

Voigt

dtdF

k1F1

dtdx

+

λ

=

x

t

Xt=∞

x

t

Xt=0

x

t

x

t

λXt=0

Displacement in responseto a step application ofconstant force.

NewtonHooke

131.1 Measurement systems

Page 27: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

5. A dashpot and spring in parallel (the Voigt model) can be represented bya resistor (k becomes R) and an inductor (λ becomes the inductance L) inseries. If the applied force is replaced by voltage, and the resultingdisplacement is replaced by the current, show that the magnitude of theapplied force and the magnitude of the displacement are related by:

1. A moving coil galvanometer has a series resistance of RM = 120 Ωand a full-scale deflection at 2.5 µA. The display scale is dividedinto 100 equal divisions. The meter is to be used as a voltmeter tomeasure the emf from a 3.0 V source which has an outputresistance RO of 1.5 kΩ.(a) Determine the resistance RS required to be connected in series

with the galvanometer to make a voltmeter 0−5 V range.(b) Determine the uncertainty in the measured value for the above

source emf due to meter resolution.(c) Determine the reading on the voltmeter when it is connected

across the 3.0 V voltage source.

1.1.11 Review questions

2. An infrared gas analyser is used to measure the concentration of carbonmonoxide (CO) in the exhaust gases of a motor vehicle. Before themeasurement is taken, purified air containing no CO is introduced andthe “zero” is adjusted for 0 mV on the output display. Then, acalibrated mixture of CO and air at 400 ppm is introduced and the spanadjusted to give 400 mV on the output. The exhaust gas is then sampledby the instrument and the reading is 350 mV. It is discovered later thatthe concentration of the calibrated mixture was in error and shouldhave been 410 ppm. Assuming the response of the instrument is linear,determine a corrected value for the measured concentration.

3. The diagram shows the output of a lineartransducer as a function of its input.

O

I

(a) What formal term is given to the slopeof this line?

(b) What control is used to adjust this slopeduring calibration, the “zero” or the “span”?

4. List three static, three dynamic and three environmental performancecharacteristics which would influence the choice of a transducer for aparticular application.

xkF 222λω+=

(Ans: 2 MΩ, 0.005 V, 2.9985 V)

(Ans: 358.8)

Newnes Interfacing Companion14

Page 28: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

15

Page 29: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.2.1 Temperature

Celsius temperature scale:defined such that0 oC = ice point of water100 oC = boiling point of water.

Fahrenheit temperature scale:defined such that32 oF = ice point of water212 oF = boiling point of water

18010032FC oo

−=

The measurement of temperature is naturally associated with the definitionof a temperature scale.

The International Temperature Scale is based on the definition of a numberof basic fixed points. The basic fixed points cover the range of temperaturesto be normally found in industrial processes. They are (expressed here in oC):

1. Temperature of equilibrium between liquid and gaseous oxygen at1 atm pressure is: −182.97 oC

2. Temperature of equilibrium between ice and air-saturatedwater at normal atmospheric pressure (ice point) is: 0.000 oC

3. Temperature of equilibrium between liquid water and its vapourat a pressure of 1 atm pressure (steam point) is: 100.000 oC

5. Temperature of equilibrium between solid silver and liquid silver atnormal atmospheric pressure is: 960.5 oC

4. Temperature of equilibrium between liquidsulphur and its vapour at 1 atm pressure is: 444.60 oC

6. Temperature of equilibrium between solid gold and liquid gold atnormal atmospheric pressure is: 1063 oC

Note: Standard atmospheric pressure(1 atm) is defined as 760 mm Hg (ρ =13.5951 g/cm3) at g = 9.80665 msec−2.

Other fixed points have been defined which facilitate calibration ofthermometers in particular applications. Some examples are:

• Equilibrium between solid and gaseous CO2: −78.5 oC• Freezing mercury: −38.87 oC• Freezing tin: 231.8 oC• Freezing lead: 327.3 oC• Freezing tungsten: 3400 oC

Newnes Interfacing Companion16

Page 30: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.2.2 Standard thermometers

Temperatures in between the standard fixed points are found using standardthermometers which have been calibrated using the fixed points as follows:

From the ice point to 660 oC, the temperature isfound from the resistance of a Platinum resistancethermometer:

2oT BTAT1RR ++=

The constants Ro, A and B, and degree of non-linearity, are determined from the ice, steam andsulphur points.

From −−−−190 oC to the ice point, the temperature isfound from the resistance of a platinum resistancethermometer:

( )32oT 100TCBTAT1RR −+++=

The constants Ro, A, B and C, and degree ofnon-linearity are determined from the ice, steam,sulphur points and oxygen points.

From 600 oC to the gold point (1063 oC)temperatures are found from the emf generatedusing a platinum/platinum-rhodiumthermocouple where the cold junction is held at0 oC. The temperature is found from:

2CTBTAemf ++=

The constants A, B and C are determined fromthe freezing point of antimony, the silver andgold points.

Above the gold point, temperature is determinedusing a radiation pyrometer which compares theintensity of the light of a particular wavelength tothat which would be emitted by a black body attemperature T.

Note: The official SI unitof temperature is theKelvin. It is thetemperature equal to thefraction 1/273.16 of thetemperature of the triplepoint of water.

The triple point of wateris the state of pure waterexisting as anequilibrium mixture ofice, liquid and vapour.Let the temperature ofwater at its triple pointbe equal to 273.16 K.This assignmentcorresponds to an icepoint of 273.15 K or 0 oC− slightly lower than thetriple point. The triplepoint is used as thestandard fixed pointbecause it isreproducible.

BS1041: 1943.

171.2 Temperature

Page 31: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.2.3 Industrial thermometers

Contact• Expansion of solids (bimetallic strip)• Expansion of liquids (mercury in glass)• Expansion of gases (bellows)• Thermoelectric junctions (thermocouple)• Electrical resistance (thermistor)• Change of state (melting point methods)

Non-contact• Optical pyrometers (change in colour of hot bodies,

disappearing filament device)• Total radiation pyrometer (intensity of all wavelengths of

radiation from hot body measured by focussing rays, using alens or mirror, onto a “receiver” which may be a thermocoupleor resistance element).

The choice of thermometer depends on: • The range of temperatures to be measured.• Permissible time lag.• Risk of chemical reaction with thermometer.• Size and space requirements – ease of readings.• Robustness.• Single readings or recordings.

Precautions:• Good contact between the hot body and sensor.• Sensor to have small heat capacity.• Chemical reactions which absorb or liberate heat to be avoided.• Condensation to be avoided (latent heat may cause errors in

temperature measurement).• Electrical shielding to reduce noise pickup.

In practice, thermometers used in industry have to be robust, reliable andoften fast-acting. There are two general classes of thermometer, those thatmake contact with the body whose temperature to be measured, and thosethat do not.

Thermocouple tip withwires bonded together

Bim

etal

lic s

trip

type

ther

mom

eter

Bellows typethermometer

Newnes Interfacing Companion18

Page 32: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.2.4 Platinum resistance thermometer

For a fundamental interval of38.5 Ω, and Ro= 100 Ω, thecalibration constants for Pt are:

The electrical resistance of a platinum wire-wound resistor changes withtemperature. The response is reasonably linear and can be approximated by:

Resistance at 0 oC

Resistance at T

A and B arecalibrationconstants

The resistance of the sensorchanges with temperature. Whenthe resistance changes, thecurrent in the circuit changes.The rheostat is adjusted to bringthe current back to its formervalue. This can be achieved bykeeping the voltage across thestandard resistor a constant usingthe rheostat. The change involtage on the measuringpotentiometer is thus due to achange in temperature only.

A = 3.91 × 10−3 °C−1

B = −5.85 × 10−7 °C−2

Power dissipated inelement not to exceed0.1 MΩ to avoid self-heating.

The change in resistance over a temperature range of 0 to100 oC is called the fundamental interval and fixes thesensitivity of the device. A fundamental interval of38.5 Ω is specified in BS1904 for temperature ranges upto 600 oC. Above 600 oC, the fundamental interval maybe reduced to 10.000 Ω or even 1.000 Ω.

The Pt resistance sensor normallycontains a supplementary ballastresistor (having a negligiblechange of resistance withtemperature) the value of which isselected to make the totalresistance of the element Ro to be100.0 Ω at 0 °C.

Pt re

sist

ance

ther

mom

eter

pro

be

V Rheostat

Rstand

R

Monitoringpotentiometer

Measuringpotentiometer

191.2 Temperature

( )2oPt BTAT1RR ++=

Page 33: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

A common thermometer in industry is the liquid-in-glass type which mightcontain either mercury or alcohol.

1.2.5 Liquid-in-glass thermometer

• Cheap, simple and portable.

• Restrictions on orientation• High heat capacity.• Significant time lag.

Advantages:

Disadvantages:

There are specific constructional guidelines(BS1704) which ensure uniformity of performanceof thermometers from different manufacturers.

Designed for temperature range−120 °C to +510 °C and may beeither total immersion or 100 mmimmersion.

Type “A” thermometers aremercury-in-glass inert gas, solidstem. Type “B” are alcohol-in-glass, solid stem.

• Stem: made of lead glass with an enamel back.• Bulb: made cylindrical and has an external

diameter not exceeding that of the stem.• Thermometer is required to be annealed before

graduation.• Graduation lines are of uniform thickness not

exceeding 0.15 mm and a line in a plane at rightangles to the stem aligned to the left when the stem isviewed from the front in a vertical position.

• Immersion line is etched on the back of the stem for100 mm immersion thermometers.

• A glass ring or rounded top is required at the top ofthe stem.

• A safety volume exists at the top of the capillary tubewhich is at least 20 mm above the top graduation line.

• Gas filling employed, e.g. N2.• Manufacturer’s mark.• Schedule mark.

Constructional features:

Markings:

e.g. GP 150C/Total meansgeneral purpose thermometer,maximum temperature 150 °C,total immersion type.

Safetygap

Liqu

id-in

-gla

ss th

erm

omet

er

Newnes Interfacing Companion20

Page 34: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.2.6 Radiation pyrometer

Radiation pyrometers are usually used to measure high temperatures wherephysical contact with the hot body is not possible. A very popular form ofpyrometer is the disappearing filament type.The brightness of an electricfilament lamp is adjusted by theoperator by altering the currentthat passes through it. The hotbody and an electric filament areboth visible through aneyepiece. When brightness ofthe filament matches that of thehot body, the filament becomesinvisible. The current throughthe filament at the matchingpoint is an indication oftemperature of the hot body.

Field of viewFilament

Usually, a red filter is used at theeyepiece so that matching is done at aparticular wavelength (makes it easierto obtain a match). A correction tableis used to obtain a true temperaturefrom the indicated value whichaccounts for non-black body radiationwhen using the red filter.

Note: An additional screen mayalso be employed before theobjective lens of the instrumentto reduce the amount ofincoming radiation. This permitsa lower current to be used whenmeasuring the temperature ofvery hot bodies and thusincreasing filament life. With thescreen in place (usually a pieceof optically neutral glass) asecond scale of temperatures isprovided.

Note: It is very common to usethe eye as an optical pyrometer.For example, in the heattreatment of metals, it issometimes required to heat until“cherry red” etc.

Optical pyrometer

211.2 Temperature

Page 35: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.2.7 Thermocouple

A thermocouple consists of two dissimilar metals joined at either end.One of the junctions is held at a reference temperature, and the otherjunction is at the temperature to be measured. If a voltmeter is introducedinto the circuit, the voltage depends on the difference in temperaturebetween the two junctions of the device.

Advantages:

Disadvantages:

• Able to measure hightemperatures.

• Easily calibrated.• Mechanically robust.• Reasonably resistant to

chemical attack.• Can measure temperature of

solids, liquids and gases.• Reasonably fast response

time (usually a few seconds).

• Loss of heat throughthermocouple wires maylead to error in measuredtemperature.

• Resistance of thermocouplewire may affect emfdisplayed on meter.

• Response may change withtime due to the diffusion ofimpurities.

• Limited range of linearity.• Accuracy limited to about

1%.

Sensor(“hot junction”)VReference

(“cold junction”)How it works:1. Consider a single length of metallic

conductor where the temperature of oneend is raised relative to the other. Thenumber density of mobile electronsincreases with increasing temperatureand leads to a concentration gradient ofelectrons between the hot and cold endsof the conductor. Due to this gradient,diffusion of electrons occurs from the hotend to the cold end. The hot endbecomes positively charged. This is theThomson effect.

2. Now consider two lengths of dissimilarmetals joined at one end. There is adifference in the density of electrons inthe two materials. Thus, there is aconcentration gradient of electrons atthe junction which results in diffusion ofelectrons across the junction. Thisdiffusion means that the material withthe higher density of electrons becomespositively charged. This is the Seebeckeffect.

These two effects lead to a contactpotential at the junction of two dissimilarmetals, the magnitude of which dependsupon the temperature and the nature of themetals. The difference in contact potentialsbetween the two junctions is a measure ofthe temperature difference between them.

Hot

junc

tion

Newnes Interfacing Companion22

Page 36: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

The selection of metals which are used to make thermocouples depends uponthe range of temperatures to be measured. The thermoelectric sensitivity(µV/°C) of a particular material is stated with respect to platinum at 0 oC.

Material Sensitivity (µV/°C)

Constantan* −35Copper +6.5Iron +18.5Platinum 0

A commonly used thermocouple iscopper/constantan. The sensitivityis thus: +6.5 − (−35) = 41.5 µV/°C.

* Constantan is an alloy of 60%Cu and 40%Ni.Chromel is an alloy of nickel and chromiumand alumel is an alloy of nickel and aluminium

Several standard pairs of materials are incommon use and are conventionally givencharacter labels, e.g. “Type K”.

Copper/constantan* T −200 +300 4.24 mVIron/constantan J −200 +1100 5.268Chromel/alumel* K −200 +1200 4.10

The emf produced for a hotjunction at 100 °C and coldjunction at 0 °C.

Temperature range °C

The introduction of a thirdmetal into the thermocouplecircuit does not alter thedifference in contactpotentials between its endsas long as the newlyintroduced junctions are bothat the same temperature.This means that the ends ofa thermocouple may bebrazed or soldered togetherwithout affecting theoperation of the device.

Thermocouples are usually non-linear. The output may be linearised insoftware using data from calibration reference tables that are availablewhich give temperature and voltage relationships referenced to 0 oC.However, the cold junction in an actual thermocouple is usually at roomtemperature. Cold junction compensation is required to correct for this.For example, an LM335 precision temperature sensor, a solid state devicewhich acts like a zener diode, can be used to offset the thermocouplevoltage. The reverse bias breakdown voltage of this device is linearlydependent upon the absolute temperature and is directly calibrated in K.The thermocouple voltage corresponding to the separately measured roomtemperature is added to the voltage from the thermocouple and then thecalibration look-up table is applied to determine the temperature at thesensor end of the thermocouple. Cold junction compensation can be doneelectrically in hardware, or by a software correction to the data.

231.2 Temperature

Page 37: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.2.8 Thermistors

Thermistors are resistive temperature elements made from semiconductormaterials. The resistance of these elements decreases with increasingtemperature (negative temperature coefficient). The correspondencebetween resistance and temperature is highly non-linear.

Advantages:• Inexpensive.• Small size.• Low mass (small time constant).• Large output signal (high sensitivity).

Disadvantages:• Accuracy generally not as good as Pt resistance thermometer.• Limited temperature range: −100 to 450 oC.• Non-linear response.• Tolerance only about ±5%.

The relationship between resistance and temperature is exponential andhas the form:

TT AeRβ

=

A and β are constants which depend upon thematerial with which the thermistor is made. Tis the temperature in K, and RT the resistanceat temperature T.

If a reference temperature To is chosen, then this equation can beexpressed as:

−β=

ooT T

1T1expRR

where Ro is the resistance at To, usually taken to be 25 oC.

A typical value of resistance at room temperature is 10 kΩ falling toabout 1 kΩ at 100 oC.

Thermistor

Newnes Interfacing Companion24

Some thermistors have apositive temperaturecoefficient.

Page 38: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.2.9 Relative humidity

The traditional method ofmeasuring humidity is by the useof a wet and dry bulbpsychrometer. In this device, awick, soaked in distilled water, isplaced over the bulb of a mercury-in-glass thermometer. Anotheridentical thermometer is placednearby with nothing over the bulb.The air whose relative humidity isto be measured is blown over thebulbs of both thermometers.The evaporation of water from the wetbulb causes the temperature measuredto fall compared with that of the drybulb. A psychrometric chart is used toread off the relative humidity from thewet and dry bulb thermometerreadings.

WickDry bulb(underneathshield)

Wet bulb(shieldremoved)

Air drawnin by fan

Relative humidity can be measuredelectronically. One device uses thechange in capacitance between twogold films separated by a mylar sheet.As water is absorbed into the mylar,the capacitance changes and this can bemeasured electronically. In anotherdevice, the change in capacitance oftwo silicon wafers on opposite sides ofa glass slide is measured. Thecapacitance depends upon the relativehumidity of the air surrounding thedevice. A temperature sensor mountedabove the device is used to compensatefor differences in response at differentambient temperatures.

Mylar sheet type sensor

Silicon wafer type sensor

Wet and dry bulbpsychrometer

251.2 Temperature

Page 39: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1. A Pt resistance thermometer is to be used to measuretemperature. The relationship between resistance andtemperature is to be given by the following equation:

If Ro = 100 Ω, R100 = 138.50 Ω, and R200 = 175.83 Ω, determine:(a) the value of the constants A and B;(b) the fundamental interval.

4. A mercury-in-glass thermometer is marked as follows:

Identify the meaning of each of these markings.

5. A mercury-in-glass thermometer made to an approved standard containsa widening of the capillary tube at the top of the instrument. What is thepurpose of this widening and why must it have a spherical top?

2. A Pt resistance element is marked as per the following diagram. Whatis the function of each pair of terminals?

E F A B

6. An optical pyrometer uses a disappearing filament to enable an estimateof temperature to be made. In what way does the filament disappearand what is the significance of the disappearance?

3. BS1904 specifies that the fundamental interval for a Pt resistancethermometer should be 38.5 Ω. What does the term “fundamentalinterval” refer to?

1.2.10 Review questions

Newnes Interfacing Companion26

( )2oPt BTAT1RR ++=

Page 40: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

7. Discuss the relative merits of thearrangement of thermocoupleconnections as shown:

8. Refer to an iron/constantan thermocouple (Type J) table.

(a) If the cold junction is at a room temperature of 25 oC, and thereading on the millivolt meter is 24.4 mV, determine thetemperature of the hot junction.

(b) The calibration table for an iron/constantan thermocouple canbe approximated by the following formula:

Using the mV reading given in (a), determine the percentagedifference between the results given by the table and the formulafor the temperature in (a).

Thermocouplewires

V

V

Copperleads

V

V

Copperleads

Furnaceat 600 oC

Control roomat 20 °C

Temperaturereadout inremotebuilding

Thermocouplewires

Thermocouplewires

Thermocouplewires

(a)

(b)

(c)

(d)

4937

24

T101334.0T108566.0

T103047.0T05038.0Emf−−

×+×−

×+=

(Ans: 469°C, 8%)

271.2 Temperature

Page 41: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

In a typical application, one end of a thermocouple is usually brazed orsoldered together to form the sensor and the other ends of the wires areconnected directly to the voltmeter. In this case, the reference junction is atroom temperature.

To overcome variations in voltage which would occur due to changes inroom temperature, a third temperature measuring device may be employedto provide cold junction compensation. The third temperature sensormeasures an absolute value of room temperature and provides a voltage,which when added to the thermocouple voltage, produces a total emf as ifthe cold junction of the thermocouple was at 0 oC.

A thermocouple consists of a length of two dissimilar metals which arejoined at either end. One of the junctions is commonly held at a referencetemperature, and the other junction is exposed to the temperature to bemeasured. The voltage measured across a break in one of the wiresdepends on the difference in temperature between the two junctions ofthe device.

Separatelycalibratedtemperaturemeasuring device

1.2.11 Activities

All at room temperature

oC

PtHotjunction

Newnes Interfacing Companion28

Page 42: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

The aim of this part of the experiment is to construct a chromel/alumelthermocouple and to calibrate it against a known standard.

1. Set up the apparatus as shown in the diagram and set the digitalvoltmeter to the 100 mV range.

2. Check the temperature of the ice bath at regular periods to ensure itremains at 0 oC.

3. Heat the water containing the hot junction gently and so obtain arange of temperatures between 0 oC and 100 oC with correspondingreadings on the voltmeter.

4. Take sufficient readings to enable you to construct a good calibrationgraph of temperature (oC) vs thermocouple voltage (mV).

5. Compare your data with that given by BS4937.

Reference (“cold”)junction 0 °C

Sensor(“hot”)

junctionT °C

mV

Glassthermometer

(a) Thermocouple calibration

291.2 Temperature

Page 43: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Cold junction compensation is a process whereby a voltage is added (orsubtracted) from the output voltage of the thermocouple so that thereference junction appears to be at 0 oC even if it is not. This may be doneelectronically using an LM335 precision temperature sensor. The LM335 isa solid-state device which acts like a zener diode. The reverse biasbreakdown voltage is linearly dependent upon the absolute temperature andis directly calibrated in K. For example, the output from the LM335extrapolates to 0 V for 0 K. At 273 K, the breakdown voltage is 2.73 V.

A third terminal on thedevice allows the outputto be calibrated against

a known referencetemperature.

To is a reference temperatureVoutTo is the output voltage atTo. The nominal value of thequantity: is 10 mV/K.

o

Tout

T

Vo

+−−−−

adj

LM335H

Errors due to self-heating of the device can be minimised by selecting acurrent limiting resistor R1 to reduce the operating current through thedevice to a minimum – enough to drive the device into breakdown atmaximum temperature for the application as well as any externally appliedloads. A current of about 1 mA is reasonable.

ooToutTout T

TVV =

(b) Cold junction compensation

LM335

+V

R1

10k

Newnes Interfacing Companion30

Page 44: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Now, the thermocouple output voltage is determined by the temperaturedifference between the hot and cold junctions and the relativethermoelectric sensitivity of the metals. The Seebeck coefficient α forsome common thermocouples is shown below:

Copper/constantan T α = 42.4 µV/KIron/constantan J 52.8Chromel/alumel K 41.0

The voltage output from the LM335 has to be matched with the voltagerange of the thermocouple material and this can be done using a simplevoltage divider resistor network.

The nominal sensitivity of the LM335 is 10 mV/K and we need to factorthis down to the µV/K range. We choose R3 and R4 so that:

34 RmV10

R α

=

For example, if R3 = 220 kΩ, and we are using a Type K thermocouple,then R4 is:

Ω=

×

×=

898

000,2201010108.40R 3

6

4

LM335

+V

R1

10k

R3

R4

311.2 Temperature

Page 45: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

+

The LM335 is calibrated in K. However, the voltage output from thethermocouple must be referenced to 0 oC = 273 K.

If the LM335 is above0 °C, then a voltage isadded to that producedby the thermocouple sothat it appears that thecold junction of thethermocouple is at 0 °C.

At 273 K, the output or reverse bias breakdown voltage of the LM335 willbe about +2.73 V. This voltage, factored down to match the thermocouple,must then be applied to the negative side of the thermocouple to raise itspotential. Thus, when the hot junction is at 0 oC, there will be no voltagedifference between the output terminals.

Thermocouplehot junction

Vout

R5

R6

A zener diode withbreakdown voltage Vzprovides a suitable fixedvoltage which is factoreddown using a resistordividing network.

R2

Vz

5z

6 RV273R α−

=

We need to chooseR6 so that:

Z2

Toinstrumentation(difference)amplifier

LM335

+V

R1

10k

R3

R4

+V

Newnes Interfacing Companion32

Page 46: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1. With +V = 5 V, calculate a suitable value of R1 to limit the currentthrough the LM335 to 1 mA.

2. Calculate a suitable value of R4 with R3 = 220 K to match thecharacteristics of the supplied thermocouple material.

3. Calculate a suitable value of R2 so that the maximum current throughthe zener diode Z2 is no more than 1 mA with a +5 V supply.

4. Calculate suitable values of R5 and R6 so that the appropriate “zero”offset is applied to the negative end of the thermocouple (select R5 =220 k).

1. Design, build and test a thermocouple circuit which employs coldjunction compensation. The output of the circuit is to be a differentialvoltage which is proportional to the temperature of the hot junction ofthe thermocouple over the range 0−100 oC.

2. Construct an instrumentation amplifier which will take in the voltagelevels from a cold-compensated thermocouple circuit and provide a0−5 V output voltage which is proportional to the temperature of thehot junction of the thermocouple (oC).

3. Using the serial data acquisition system, construct a computerisedtemperature recording and control system using the software of yourchoice.

In order to interface our thermocouple to the serial data acquisition systempresented in Part 2 of this book, we need to amplify the signal to obtain anappreciable voltage for subsequent conversion to digital format. The full-scale output from the thermocouple circuit depends of course on themaximum temperature being measured. Let us work with the range 0 to100 oC. At 100 oC, the output from a K type thermocouple (including anycold junction compensation) will be 4.1 mV. A convenient voltage gainrequired would thus be about 1000 to give an analog input of around 4 Vto the ADC. The overall aims of the project activity in this book are to:

Data acquisition system

Parts list:1x LM335H precision temperature reference1x IN4732 4.8 V zener diode2x 220 k; 1x 2.2 k; 1x 100 Ω; 1x 4.7 k; 1x 680 Ω; 1x 1 k

331.2 Temperature

Page 47: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

34

Page 48: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.3.1 Light

Light is an electromagnetic wave.

a travelling disturbance of varyingelectric and magnetic fields

The velocity of light waves in a vacuum is c = 2.99792458 × 108 ms−1

c = fλ

Wavelength350 nm to 700 nmfor “visible” light

For any type of wave, including light waves:

Frequency

Light can also beregarded as a stream ofphotons, individualparticles of zero masswith an energy:

For visible light, the frequency is of the order of 1015 Hz. Photodetectorscannot respond to such rapid changes and thus generally indicate rms ormean values of power of the radiation.

The energy of a photon depends on the frequency but is in the order of10−20 J. Most detectors respond to large numbers of photons but there area few that can provide a useful output for just one photon.

There is a difference between the measurement of radiant energy and thatof light. The term light implies a human connection, and the measurementof visible light is called photometry. The human eye is a very commonphotometric detector.

Radiometry is concerned with the measurement of radiant energyindependent of the type of detector used. A third field of radiationmeasurement is concerned with the quantum nature of light and is calledactinometry − which arose from a study of the photochemical effects oflight.

x

A

−A

λ

ν= hE

Planck’s constant6.63 × 10−34 Js

Frequency (Hz)

Velocity

WavelengthAm

plitu

de

351.3 Light

Page 49: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.3.2 Measuring light

The luminous flux per solid angle iscalled the luminous intensity and isgiven the unit candela (cd). It is thephotometric equivalent to radiantintensity.

Many units concerning light arein daily use but before weintroduce them, we need toconsider the definition of a solidangle, the steradian (sr).

The steradian Ω is the solid angle which,having its vertex in the centre of a sphere,cuts off an area of the surface of thesphere equal to that of a square withsides of length equal to the radius of thesphere.

The unit of luminous flux is thelumen (lm = cd.sr). Luminous fluxis the radiant flux weighted by aspectral efficiency factor whichcharacterises the response of thehuman eye. The lumen is the humanequivalent of radiometric power(W).

The brightness of a surface is calledthe illuminance and has the unit luxand is the luminous flux per unitarea (lx = l lm/m2). It is the humanor photometric equivalent of radiantflux density.

Radiant energy is energyreceived or transmitted in theform of electromagnetic wavesand has the units of joules (J).

Radiant power or flux isradiant energy received ortransmitted per unit time inwatts (W).

Radiant flux density(irradiance) is the radiant powerincident on a perpendicular unitarea and has the units (Wm−2).

Radiant intensity is the radiantpower per unit of solid angle(W/sr).

Radiometric definitions

Photometric definitions

Actinometric definitionPhoton flux is theactinometric equivalent ofradiant flux and is the numberof photons impinging on asurface per second. Eachphoton has an energy = hv.

The solid angle is the surface area ofthe cone divided by the square of theradius.

R

R

2rdAd =Ω

Newnes Interfacing Companion36

Page 50: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.3.3 Standards of measurement

The official SI base unit for measuring the luminous intensity of light is thecandela. The candela is the only SI base unit which has its origins in theresponse of a human organ (i.e. the eye) – it is a photometric quantity. Thecandela is a base SI unit upon which lumens and lux are derived.The candela has become an important base unit due to the historical natureof measurements of light which involved the human eye as the detector.Early standards by which the response of a human eye were quantifiedinvolved candles, flames, and incandescent lamps. Human observerscompared an unknown light source to a standard.

Modern methods utilise the response of a device (e.g. a photocell) whichhas spectral characteristics which are very close to that of a standardobserver. Standard sources provide a way of calibrating photocells to beused in industry.

The candela is defined as the luminous intensity in a given direction of asource that emits monochromatic radiation of frequency 540 x 1012 Hz andhas a radiant intensity of 1/683 W/sr in that direction.

The most commonly used measurement of light intensity is not actually thecandela, but the illuminance or brightness and is typically given in lux. Ina normal lecture room, the illuminance is about 300 lux. A brightsummer’s day: 20000 lux. In daylight, 680 lux corresponds to a radiantflux of about 1 Wm−2

Standard light source

Standard photometer

For precise photometric work, it is usually preferableto operate lamps on DC. It is preferable to set theoperating current. Measurement of luminous flux maybe made by comparison with luminous flux standardsusing an integrating sphere, or a goniophotometer.

371.3 Light

Page 51: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.3.4 Thermal detectors

In thermal detectors, incoming radiation results in a change of temperatureof the sensor. The temperature of sensor is an indication of the magnitudeof incident radiation.Temperature is usually measured with a thermopile, which consists of alarge number of thermocouples in series. The sensitivity of a thermaldetector using a thermopile with a surface area of 1−10 mm2 is typicallyabout 10−100 V/W, with a time constant of about 10 ms.

Roomtemp.

Hot

junc

tions

Emf

The sensitiveregion of thedetector is usuallyblackened so asto absorb themaximum amountof incomingradiation.

Another type of thermaldetector employsthermistors instead of athermopile to measuretemperature. Such a deviceis called a bolometer.

Still yet another type of thermal detector utilises the pyroelectric propertyof certain ferroelectric materials. Incident radiation causes a change in thesurface charge of a residually polarised ceramic. The effect can only bemeasured in a pulsed mode of operation and hence an AC amplifier is usedto produce a reasonable output.

Newnes Interfacing Companion38

Page 52: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

In a semiconductor, photoconductivity is a result of an increase inelectrical conductivity due to impingement of photons on thesemiconductor material. This increase can only occur if the incidentphotons have an energy hv > Eg where Eg is the energy gap between thevalence and conduction bands.

The increase in conductivity manifests itself as an increase in the currentthrough the device for a given applied voltage and as such may be called alight dependent resistor (LDR).

When an LDR is illuminated with a steady beam, an equilibrium isreached where the decay of electrons is matched by the excitation.

1.3.5 Light dependent resistor (LDR)

Incident photons causeelectrons in the valenceband to be given energyhv and, if hv > Eg,valence electrons enterthe conduction band,leading to an increase inthe number of mobileelectrons.

Conductionband

Valenceband

Energy gap

For a given frequency of incident beam, the number of mobile electronscreated is a function of intensity of the beam. However, the conductivity ofthe material depends not only on the intensity of the incident radiation, butalso upon its frequency. This is due to the filling of available quantumstates.

e.g. A popular material for LDRsis cadmium sulphide (CdS). CdShas a peak response at 600 nm,Eg = 2 eV and matches thefrequency response of the humaneye quite closely. In contrast, leadsulphide (PbS) (Eg = 0.4 eV) has apeak response at 300 nm.

The ratio of the number of excited electrons to the number of incomingphotons is called the quantum efficiency and is dependent on theprobability of the number of elastic collisions between photons andelectrons.

LDR

391.3 Light

Page 53: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.3.6 Photodiode

A photodiode employs the photovoltaic effect to produce an electriccurrent which is a measure of the intensity of incident radiation.

The area near the junction becomes free of majority carriers and is calledthe depletion region. When a photon creates an electron-hole pair in thedepletion region, the resulting free electron is swept across the junctiontowards the n side (opposite direction of Ed).

1. Near the junction,concentration gradientcauses free electronsfrom n side to diffuseacross junction to p sideand holes from p side todiffuse across to n side.

2. Resulting build-up ofnegative charge on p sideand positive charge on nside establishes anincreasing electric fieldEd across the junction.

Ed

p n+ve−ve

V

Current will flow in external circuit as long asphotons of sufficient energy strike the materialin the depletion region.

Even though the photodiodegenerates a signal in the absence ofany external power supply, it isusually operated with a smallreverse bias voltage. The incidentphotons thus cause an increase inthe reverse bias leakage current Io.

V

I

Io

Io

Dark

Illuminated

The reverse bias current is directlyproportional to the luminousintensity. Sensitivity is in the orderof 0.5 A/W.

Phot

odio

deNewnes Interfacing Companion40

Page 54: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.3.7 Other semiconductor photodetectors

Phototransistors provide currentamplification within the structure of thedevice. Incident light is caused to fallupon the reverse-biased collector-basejunction. The base is usually notconnected externally and thus thedevices usually only have two pins.Increasing the light level is the same asincreasing the base current in a normaltransistor.

Avalanche photodiodesoperate in reverse bias at avoltage near to the break-down voltage. Thus, a largenumber of electron-holepairs are produced for oneincident photon in thedepletion region (internalionisation).

Schottky photodiodesuse electrons freed byincident light at ametal–semiconductorjunction. A thin film isevaporated onto asemiconductor substrate.The action is similar to anormal photodiode butthe metal film used maybe constructed so as torespond to shortwavelength blue orultraviolet light onlysince only relatively highenergy photons canpenetrate the metal filmand affect the junction.

PIN photodiode is a pn junction witha narrow region of intrinsicsemiconductor sandwiched betweenthe p and n type material. Thisinsertion widens the depletion layerthus reducing the junction capacitanceand the time constant of the device –important for digital signaltransmission via optical cable.

A charge coupled device CCD is anarray of closely spaced photodiodes.Incident light is converted to an electriccharge in each diode. A sequence ofclock pulses transfers the accumulatedcharge to a digital output stream. Forvideo applications, an image must befocussed on the device using a lens.

811x

508

pixe

l CC

D a

rray

411.3 Light

Page 55: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.3.8 Optical detectors

Optical detectors are characterised by:

Responsivity/Sensitivity

Spectral response

Detectivity D

Detectivity D*

Detectivity D**

s

outP

POutput power

Input (signal) power

Sensitivity as a function ofincident wavelength

sPSNRD =

Signal to noise ratio

Input power

fAD*D ∆=

Detector area

Bandwidth

12121 WHzcm −

( )θ

π=θ

sin2*D*D

Half angle

Quantum efficiency η ehP

i ss

ν

η=

Photons/sec

Charge on electron

Signal current

1W−

Independent of areaand bandwidth.

Independent of fieldof view.

Newnes Interfacing Companion42

Page 56: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

These two electrons are thenaccelerated through another 200 Vpotential to another dynode and thuscause four electrons to be ejected. Thisamplification may involve severalstages of dynodes, each at a potentialof 100−200 V above the previousstage. Thus, the final electron current issufficiently high to measure withconventional electronic equipment.

1.3.9 Photomultiplier

One of the most common applications of photomultipliers is for thedetection of nuclear radiation. But, the device may be also used as thebasis for detection of a wide range of phenomena which involve very lowlight output levels (e.g. chemi-luminescent gas detector).The light sensitive surface of aphotomultiplier consists of a thin film ofan alkali metal which has a low workfunction W. When a photon with energyE impinges on the metal, if E > W, thenelectrons are emitted from the metal.These electrons are accelerated by anapplied potential (of about 200 V)towards a dynode. An acceleratingelectron, when it strikes the dynode, hassufficient kinetic energy to eject two ormore electrons from the dynode material.

Note: A high voltage power supply isneeded to produce the requiredaccelerating potentials at each dynode.

Amplifier

Photon

Dyn

ode

HV

R

R

R

R

Amplification is thus done within theevacuated structure and may be ashigh as 106. Further, thisamplification is done prior to theintrumentation amplifier inputresistance and noise in the signal isthus reduced considerably. Darkcurrent (due to thermionic emission atcathode) limits detectivity.

electron

Photomultiplier

431.3 Light

Page 57: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1. What is the photon flux incident on a 1 m2 surface being illuminated by60 W of light of wavelength 620 nm.

3. Discuss the differences between the radiometric and photometricdefinitions of light. That is, why are they different?

2. A 100 W motor cycle headlamp can just be seen by a pedestrian twokilometres away. The size of the pupil in the pedestrian’s eye is 1 mm2.Calculate the minimum incident power detectable by the retina of theeye. Assume that the headlamp is 25% efficient in converting electricalenergy into visible light.

4. A photodiode has a sensitivity of 9 nA/lux at 560 nm and an area of 40mm2. Express the detectivity in A/W. Note: 1 lux = l lumen/m2 . Aradiant flux of 1 W at 560 nm produces 685 lumens.

1.3.10 Review questions

(Ans: 1.87 × 1020/sec)

(Ans: 0.5 × 10-12 W)

(Ans: 0.154 A/W)

Newnes Interfacing Companion44

Page 58: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

45

Page 59: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.4.1 Mechanical switch

A simple contact type transducerconverts displacement into an electricalsignal and may take the form of amechanically operated switch.

Wear of the contact points in a switchoccurs mainly due to arcing. This isespecially important when a switch isused across an inductive load. Openingsuch a switch causes a very high voltageto be induced across it (due to Lenz’s law)which leads to arcing across the gap. Forthis reason, some switches have a gap andopening rate specifically designed for DCand AC applications.

Electrons are ejected from thenegative (or cathode) side of theswitch and accelerated towards thepositive side (anode). This causesions to be dislodged from theanode and be accelerated towardsthe cathode. Material accumulateson the cathode and cavities appearon the anode.

Switches are specified as single ordouble pole (one or two rows of parallelcontacts), single or double throw (centrecontact switches from one contact toanother). The size of the contact padsdepends upon the current and the type ofload in the circuit. For high voltageswitching, the contacts are immersed inoil to reduce the occurrence of arcing.

The main problem with switches ininterfacing applications is that of bounce.Most switches contain a spring to keep thecontacts either together or apart. When theswitch is closed, the spring often causesthe contacts to bounce, thus creating aseries of make and break contacts over aperiod of a few milliseconds. If anyinterfacing circuit should be monitoring theswitch, then it might register the openingand closing of the switch during bouncecontact. To avoid this, the interfacingsystem needs to incorporate switchdebounce circuitry or software logic.

Microswitch

Contact points

In software debouncing, theprogram may wait for 10 or 20msec after first registering an eventand test the switch again beforeproceeding.In hardware debouncing, theoutput of the switch can beprocessed by a latch circuit. Theoutput of the latch will only changestate if the inputs change by TTLlevel signals.

Newnes Interfacing Companion46

Page 60: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.4.2 Potentiometric sensor

A potentiometric sensor converts a linear or angular displacement into achange in resistance. The sensor itself may be made from a coil of wireover which a moving contact or wiper causes a change in resistancebetween the terminals of the device.

A very common application is the fuel level sensor in a motorvehicle. The sensor adjusts the resistance between its terminalsaccording to the level of fuel in the fuel tank and thus indicatesthe displacement of the surface of the liquid fuel as fuel isconsumed by the engine.

A coil of wire is wound on amandrel. If the winding isuniform and the wire is of aconstant cross-section A andresistivity ρ, then theresistance R is:

AlR ρ=

l is the total lengthof wire between Aand B.

A non-linear response caneasily be obtained byaltering the dimensions ofthe mandrel. For example,to show a larger deviationin R at low fuel level(increased sensitivity), thenthe mandrel can be shapedor the spacing of thewindings alteredaccording to position.

float

pivot

mandrel

windings

B

A

A

B

A

B

A

B

A B

Resistance mandrel

A B

471.4 Position and motion

Page 61: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.4.3 Capacitive transducer

A capacitive sensor converts a change in position or change in propertiesof the dielectric material into an electrical signal.

dAC ε=

Capacitance(farads)

Overlapping area ofplates (m2)

Distance betweenplates (m)

Permittivity = εo εr

Permittivity of free space εo = 8.85×10-12 Fm-1

εr is the relative permittivity of the dielectric

Alteration of any of thesethree parameters leads to achange in capacitancewhich may be measuredelectrically.

Examples:1. Overlapping area of semicircular plates alters with

angular displacement of shaft.The capacitance is proportional to the angulardisplacement. Let Ao = area of plate at θ = 0. Theoverlapping area A is computed from:

( )180

180AA oθ−

=The capacitance is thus:

( )180

180dA

C o θ−ε=

The sensitivity is dC/dθ:

Farads/degree

Note C is linearw.r.t. θ

θ

A

( )

( )dw

dxdC

xdw

dAC

o

oo

ε−ε=

ε−ε+ε=

farads/m

2. Change in dielectric property ofmaterial between plates can also beused.

( )d180

1NAddC o −ε−

N is total number ofmoving and stationaryplates

w

A

d x

The sensitivity is dC/dx:

Newnes Interfacing Companion48

Page 62: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.4.4 LVDT

The diagram shows the primarycoil being driven by anoscillator. If the core movesupwards the flux linkage to theupper coil is increased and V1increases. The magnetic fluxlinkage to the bottom coildecreases and V2 thus decreases.The displacement of the core isthus registered as (V2 − V1).

The output voltage also dependson the driving frequency andvoltage amplitude Vex.

The sensitivity of an LVDT is specified in mV/mm/Vex. Typical range ofdisplacements is ±0.25 mm to ±250 mm. Typical drive frequency of Vex isabout 1−10 kHz. With proper instrumentation, an LVDT can resolve lessthan a nanometre of movement.

Note: Arrangement of secondary coilsmeans that the voltage induced in each ofthem is opposite in polarity:∆Vout= ∆V1 − ∆V2

Prim

ary

Secondarycoils

~

Osc

illato

r

Vout

Vex

V1

V2

When the core is at the central ornull position, the output voltage iszero. As the core is moved aboveand below the null position, theoutput signal rises and falls thesame amount but undergoes achange of phase by 180°.

In order to extract the sign (andtherefore the direction of motion),it is necessary to use a synchronousdemodulation technique. DedicatedICs such as the AD698 or NE5521can be used for LVDT drive andsignal processing functions.

The most commonly used inductive transducer is the linear variabledifferential transformer (LVDT). In this device, a core is mounted on a rodwhich passes through the centre of a coil and which is connected to the partto be moved. Changes in the magnetic coupling between the coils converta mechanical movement into an electrical output.

LVDT core and coil

491.4 Position and motion

Page 63: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.4.5 Angular velocity transducer

Electromagnetic induction used to produce a voltage which depends onthe velocity of a coil which moves relative to a fixed magnet (or viceversa). Some examples are:

Amplitude andfrequency of the outputvoltage are directlyproportional to therotational speed ω.

Toothed-rotor magnetic tachometer

Magnetic teeth on rotor modifiesthe magnetic circuit when therotor is rotating. This induces avoltage in the windings whichsurround the magnet.

V

ω+

Windings onpermanentmagnet.

Drag-torque tachometer (motor vehicle speedometer)A permanent magnet revolves on a shaft and induces eddy currents in thedisk. These eddy currents themselves produce a magnetic field whichinteracts with the rotating magnetic field on the rotor. The net result is adrag force on the disk which is proportional to the speed of rotation of therotor.

The disk is connected to a pointer and a hairspring. The scale is calibratedto indicate velocity in the desired units (e.g. mph or km/h).

Rotating shaftor cable

Magnetattached todisk

Plaindisk

Plain disk

Magnet

Pointer andhairspring

Newnes Interfacing Companion50

Page 64: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.4.6 Position sensitive diode array

A diode array is an assembly of 1024 individual photodiodes in a lineararray. The device is particularly useful for spectrophotometerapplications where light, spread by a prism, is shone onto the array and theintensity of the wavelength spectrum measured simultaneously. In X-rayabsorption spectroscopy and xray diffraction a diode array is used as aposition sensitive detector (psd) to determine the angle of diffraction ofan xray beam.

25 mm

In the array assembly, a resistance material is placed on one side of a pnjunction. Light impinging on the junction (held in reverse bias with about12 V) generates a current whose maximum value is at the centroid of thegreatest power density of the incident light. This current flows along theresistance material to the connecting electrode. The output current signalthus depends on the total resistance from the electrode to the spot at whichthe current is generated.

The output from a diode arrayis an analog signal that givesthe distance from the edge ofthe array to the centroid of theincident light spot. Theresponse of a diode array isvery fast (rise time ≈ 5 µsec)and the device has very highpositional resolution (≈250nm) and a linearity of less than1% of full scale.

Ambient light will cause a signal to be generated in the devicecorresponding to the centre of the array. The spot size for the positionbeing measured should be made as bright as possible without damaging thephotodiodes by heating them excessively. It should be noted that the devicewill only respond to the distribution of light that actually falls on thesensitive elements of the array and so the output reflects the position of thecentroid of the spot received by the array – which might not be the same asthat incident on the device as a whole for a large incident spot.

511.4 Position and motion

Page 65: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.4.7 Motion control

Linearencoder

Track

Optical emitterand photocell

Rotary encoder

Opticalemitter andphotocell

RuledslotsA rotary encoder in its most simple form

comprises a disk in which there are slots atprecise regular intervals. The disk is typicallymounted on a shaft whose rotation is to bemeasured. The shaft can in turn be part of athread with a zero backlash ball nut thattransfers rotary motion into linear motion. Themovement of the disk is measured by aphotocell that detects light from an emitter onthe other side of the disk. The resolution orstep size is the angle between the slots.

Linear encoderA linear track encoder counts the number oflines over which is moved an optical emitter andphotocell. This has the advantage of a linearmovement being a measure of the actualdistance moved rather than the rotation of ageared screw thread. The accuracy dependsupon that of the ruled lines on the track whichare usually in the order of 20 µm spacing.

Positional encoders are usually fittedto motion control systems to provideposition and velocity feedback to aPID controller to control motion. ThePID controller in turn generates avoltage signal that produces a velocityprofile that will ensure that the motionis accomplished as desired.

Rotaryencoder

t

v

Acceleration tobegin motion

Decelerationto targetposition

Constantvelocity

The output signal from an optical encoder may be aquadrature signal. The encoder produces two squarewaves out of phase by 90o. A motion controller canthen extract four phase changes per cycle leading to afour-fold increase in step size. Some encoders canfurther interpolate the signals from the slots orgratings by up to a factor of 50. Step sizes of 0.1 µmare routinely available with these types of encoders.

Qua

drat

ure

enco

ding

Newnes Interfacing Companion52

Page 66: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1. In a capacitance transducer, the capacitance is usually connected tothe input of a charge amplifier. This type of amplifier has a gainwhich is not dependent on frequency. Why would this be anadvantage?

1.4.9 Review questions

3. A motorised specimen positioning table has a rotary encoder witha line count of 2000. It is attached to a lead screw of pitch 2 mmwhich translates rotary motion into a linear motion. Calculate thelinear step size (in µm) for the device.

4. A switch is in the process of opening and the open circuit voltageis 12 V. Compute the electric field strength when the gap betweenthe contacts is 1 µm.

2. A variable dielectric capacitive displacement transducer sensor consistsof two square metal plates of sides w = L = 5 cm separated by a gap of1 mm. A sheet of dielectric material 1 mm thick and the same area asthe plates can be slid between them.

dAC orεε=Hint:

(a) If the dielectric constant of air is εr = 1 and that of the dielectricmaterial is εr = 4, calculate the capacitance of the sensor whenthe input displacement L − x = 2.0 cm.

(b) Determine the sensitivity of the device.

w

A

dx

L

12 V

1 µm

(Ans: 61.85 pF, 5.75 pF/mm)

(Ans: 1 µm)

(Ans: 1.2 × 107 V/m)

531.4 Position and motion

Page 67: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

54

Page 68: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.5.1 Strain gauge

A strain gauge is a metal or semiconductor whose resistance changesmarkedly when it is deformed. The deformation is usually taken to be ameasurement of strain, and hence force, applied to a structure.

AlR ρ=

The resistance of a specimen of material of length l and cross-sectionalarea A is given by:

A change in length or area withstrain produces a change inresistance of a particular element.

If the resistance of a particularelement is Ro with no strain, then thestrain gauge factor G is given by:

LL

RRGo ∆

∆=

Strain gauge materials are selected sothat changes in resistivity with strain(piezoresistive effect) are small, andthe geometry is such that theapplication of strain results in a largechange in length of the element.Gauge factors of about 2 are common.

Strain gauges typically carry only asmall current (15 – 100 mA) to avoidself-heating changes in resistance andthermal expansion errors.

The strain gauge element typicallyforms one leg of a bridge circuitwhich is used to measure changes inresistance of the device.

Strain gauges are commonlypurchased as a metal foil bonded ontoa plastic adhesive film. The film isattached to the structure whose strainis to be measured with the “active”axis of the gauge aligned with thedirection of the expected strain.Several gauges can be accommodatedin the one film,each orientedin a differentdirection, toform a straingauge rosette.

Activeaxes

ρ is the resistivity

Relative changein length (strain)

Relative changein resistance

The sensitivity of the strain gaugemeasurement is dependent on thenumber of active arms in the bridge.Strain gauges are available withnominal resistances from 30 to3000 Ω. The most common valuesare 120, 350 and 1000 Ω.The output from a strain gauge element will typically respond to changes indimension arising from changes in temperature. The thermal expansionproperties of strain gauge material are usually matched to suit the specimenmaterial.

551.5 Force, pressure and flow

Page 69: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

R1 Rg

R3R2

Vo

In one configuration, a strain gaugeelement is put into one arm of abridge circuit. The output voltage isgiven by:

ex21

2

g3

3o V

RRR

RRR

V

+−

+=

At balance, R1R3 = R2Rg and Vo = 0.When the resistance Rg changes,there is a change in Vo. The changein Rg depends upon the gauge factorG and the strain ε such that:

GRR gε=∆

Letting R1 = R2 and R3 = Rg, theoutput voltage for a change ∆R in Rgis given by:

2G11

4G

V12G1

121V exo

ε+

ε−=

ε+=

Note that this expression gives anon-linear output with changingstrain. Before measuring strain, thebridge must be nulled (or zeroed) inthe absence of any strain. Strain isthen applied, and the output voltagemeasured.

Quarter bridge strain gauge circuit

Voltage drops caused by resistancein the wires connecting theexcitation voltage to the bridge canbe a source of error when the straingauge transducer is located somedistance from the signal processingcircuit. A technique called remotesensing can be used to compensatefor this. With feedback remotesensing, extra sense wires areconnected to the connection of Vexto the bridge circuit. These sensewires are used to regulate or controlthe voltage supply so that therequired Vex is obtained at thebridge. Another method uses adirect measurement of Vex appliedto the bridge. This measuredvoltage is then used as the value forVex in the calculations.

Vex

Typical strain gauge circuits use anexcitation voltage of 5 – 10V. Theoutput signal is in the mV range.Since very small output voltages areinvolved, the resistors that make upthe bridge circuit have to beprecision matched, and theexcitation voltage has to beextremely stable.

Sense leads

Strain gauges can be calibrated inthe field by using a shunt resistorof known value which temporarilyreplaces a gauge in the bridge andthus simulates a known strain forthe measurement electronics.

Newnes Interfacing Companion56

Page 70: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.5.2 Force

The most common type of force transducer is the piezoelectric type. In thisdevice, force is applied to a piezoelectric crystal such as quartz or leadzirconate titanate (PZT). The force acting on the crystal displaces theatoms within it. This displacement results in a net charge on the oppositefaces on the crystal which can then be measured electrically. The charge isdirectly proportional to the force.

In a piezoelectric forcetransducer, metal platesare bonded onto thesurface of the crystal. Thecrystal is pre-stressed toprovide the capability ofboth tension andcompressionmeasurements.

( )( )Fdq =

d is the sensitivity of the device (i.e. the amount of charge perunit of applied force). For quartz, d = 2 × 10-12 C/N.

- - -

- - -

+ + ++ + +

Force

Crystal

+

Piezoelectric forcetransducers are usefulfor rapidly changingforces but their response falls off at low frequencies and are thus oftentermed AC devices. Less than a few hertz, a DC force type transducer isrequired based upon either a semiconductor or piezoresistive strain gauge.Deflection of the diaphragm to which the strain gauge is mounted isregistered as an out of balance condition for a bridge circuit.

Piezoresistivetransducer

Piezoelectrictransducer

At low frequencies, the leakage ofcharge on piezoelectric devices causesa reduction in signal thus limiting thefrequency range to greater than a fewHertz. At higher frequencies, the chargeis continually refreshed by the changein dimensions of the device and there isa linear region of operation. At frequencieslarger than the resonant frequency, forboth types of transducers, the mechanicalresponse of the system cannot keep up with the rate of change of theapplied force and again the response falls off.

ω

Out

put

ωο

10 Hz

DC

AC

571.5 Force, pressure and flow

Page 71: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

For quartz crystals, the capacitance is relatively low leading to a largechange in voltage with a change in charge. The voltage can be measuredwith a voltage amplifier with a high input resistance (MOSFET circuitry).The sensitivity of the transducer is thus determined by the voltage gain ofthe amplifier. Such systems have a very good frequency response (1 MHz)but have a relatively high noise floor.

At high frequencies, the feedbackcapacitor limits the response of thedevice to about 100 kHz.

Cry

stal

Fout C

qdtiV −== ∫

Piezoelectric force transducers provide an output based upon the change ofcharge across the faces of the crystal. The capacitance of the crystalprovides a voltage signal according to: .CqV ∆=∆

For ceramic crystals (e.g. PZT) the internal capacitance is fairly high and theoutput can be fed into a high impedance input of a voltmeter or oscilloscope.However, the use of a charge amplifier allows the transducer to have a lowimpedance output thus making it far easier to route the signal over relativelylong distances to a high impedance measurement device. By mounting thecharge amplifier very close to the crystal, a very low noise output can beobtained.

1.5.3 Piezoelectric sensor instrumentation

Charge amplifier

The gain of this amplifieris expressed as mV/pC anddetermines the sensitivityof the transducer.

Cry

stal

R

CMOSFET amplifier Vo

Constantcurrentsource

When the voltageacross R varies, thebias voltage across theMOSFET changesand the signal ispassed through thecoupling capacitor Cproviding a measureof force.

CF

R

Rx

+

Newnes Interfacing Companion58

Page 72: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.5.4 Acceleration and vibration

Measurement of acceleration is most commonly done mechanically. Aseismic mass is supported by a spring and a dashpot. The mass is connectedto an arm which in turn operates a piezoresistive, capacitive or inductivedisplacement transducer element or a piezoelectric crystal. The resultingoutput signal gives the acceleration of the reference frame of the device.

2oo

2 s2sax

ω+ξω+=

s = jω

x is the displacement. Theacceleration is:

kxdtdx

dtxdmF 2

2+λ+=

mk;

km2o =ω

λ=ξ

Damping ratio

Higher frequency accelerations(vibrations) can be measured with aseismic mass attached to apiezoelectric crystal.

Seismicmass

Piezoelectriccrystal stack

The governing equation is:

Massm kg

Springstiffness k Nm-1

Dashpotλ Nsm-1

Referenceframe

F

then:

Undampednaturalfrequency.

If:

22 dtxda =

If ωo is known, then the acceleration a canbe found from measuring the displacementof the mass.

- - -+ + +

Mass

Crystal

+

- - -+ + +

x – metresa – ms−2

ω in rad/sec

ω

=

avrva;rv 2

=ω=

ω

2o

ωοa

x

at lowfrequencies.

2o

axω

=

Since

Then: and:ω

=

vxo

Amplitude of thevibration (m)

Maximumvelocity (ms −1)

591.5 Force, pressure and flow

Page 73: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.5.5 Mass

Mass may be measured by balancing the mass with a force. The force canarise from the deflection of a spring or some other linearly elastic element.In high quality balance instruments, the displacement is registeredelectronically and used in a feedback circuit to control a force actuatorwhich brings the displacement back to zero. The signal to the forceactuator is taken to be a measure of the mass of the specimen.

High quality mass balancewith displacementfeedback. Digital outputcan resolve massincrements to 0.00001 g.

Mass balances are usually self-contained units fitted with a digital readoutand a computer interface. The computer interface allows the balance to beconfigured by sending commands to it in ASCII text, often by serialcommunications. Mass values can be obtained by reading from the serialconnection by sending a read command.

The format of a weighing result is usually presented in a particularformat. A typical example is: | |I| | | |-|3|2|.|4|5|6| |g|CR|LF:

01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18

Identification block(e.g. I - invalid)

Data block(e.g. -32.546)

Unit block(g, %)

CR LF

Newnes Interfacing Companion60

Page 74: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.5.6 Atmospheric pressure

Units of atmospheric pressure:N/m2

millibar (=100 N/m2)mm Hg (mercury at 0 oC and atg = 9.80665 ms−

2)

Note: The “torr” as used in vacuumwork is 1/760 standard atmosphericpressure but is not recognised formeasuring barometric pressure.1 mmHg = 1 torr (named afterTorricelli).

Historically, mercury barometerswere used with a variety of standardgravities and temperature dependingon the field of application –meteorology, physics etc. This led,in 1954, to the introduction ofinternational standards, an exampleof which is BS2520.

Atmospheric pressureis conventionallymeasured with amercury barometersince it provides adirect reading ofpressure and uses adense liquid whichprovides for aconvenient height ofthe instrument.

Mercury barometers are of two generalcategories: Fortin and Kew. In a Fortin

barometer, the mercury surface in acistern adjusted to a fixed point prior to

taking a reading – this category alsoincludes U tube manometers.

h

Mercury levels aremeasured from topof meniscus.

Knurled cisternadjustment knob

Fixedpoint

Standard atmospheric pressure is:101.325 kPa = 760 mmHg = 29.921 inHg

Mercury level is raiseduntil surface justtouches the fixedpoint in the cistern.

611.5 Force, pressure and flow

Page 75: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

The construction of a Fortin barometer is such that it reads pressuredirectly when the whole device is at 0 oC and at a gravity of 9.80665 ms−2

(standard conditions).

Correction tables for temperatureallow for thermal expansion of themercury (β = 0.0001818), and thebrass scale (α = 0.0000184).

Correction tables for gravity are expressed in terms of the latitude of thelocation of the instrument and the height above sea level. The accelerationdue to gravity as a function of latitude φο is given by:

( )

β+

α−β−+=

T1Trrr TTo

Correctedbarometerreading

Actual barometerreading at T °C

The correction to be applied to the barometer reading for standard gravity is:

At a height Z m above sea level and at latitude φ, the acceleration due togravity is:

These values of g lead to corrections to the barometer reading taken at aheight Z metres above sea level and at a latitude φ.

If the atmospheric pressure is required at somepoint above or below the cistern of the barometer(i.e. the barometer cannot be easily moved into thedesired position) then a further correction is to bemade for the hydrostatic pressure of the air columnbetween the two heights.

φ+φ−=φ 2cos0000059.02cos0026373.0180616.9g 20,

−+=

φφφ 1

80665.9

grrr 0,

0,0,n

( )Z000003086.0gg 0,z, −= φφ

rn what the barometer would read iflocated where g = 9.80665 m/s2 andat sea level.

rφ,0 actual barometer reading at latitudeφ and at sea level.

−+=

φφφφ

0,Z,Z,0, g

Z000003086.0rrr

Correction factor

e.g. For a point 1 mabove the cistern,the correction is−0.1181 mb, 1 mbelow: +0.1181 mb

rφ,0 what the barometer would read atsea level at latitude φ.

rφ,Z actual barometer reading at latitudeφ and height Z m.

Newnes Interfacing Companion62

Page 76: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.5.7 PressureSimple switch typeThe oil pressure switch isscrewed into a drilling fromthe outlet side of the oilpump. The oil pressure switchconsists of a diaphragm whichopens switch contacts if theoil pressure is sufficient toovercome the force of anopposing spring.

Oil underpressure

Switchcontacts

Diaphragm

Electricalconnector

Bourdon gauge typeThe Bourdon gauge consists of a tube bent into a coil or an arc. As thepressure in the tube increases, the coil unwinds. A pointer connected tothe end of the tube can be attached to a lever and a pointer calibrated toindicate pressure.

End of tubemovesaccording topressure

A typical 50 mm diametertube has a displacement ofup to 4 mm. Pressures ofabout 35 kPa to 100 MPaare typically measured.The movement maytranslate directly into ameter movement, oractivate a displacementtransducer that providesan electrical signalsuitable for computer dataacquisition.

The tube itself is made frombrass and has a flattenedelliptical or rectangularcross-section.Pressure

applied toinside of tube

631.5 Force, pressure and flow

Page 77: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Pressure is one of the most importantprocess variables that need to bemeasured in industrial applications. Themost common arrangement makes useof a diaphragm to which is bonded apiezoresistive displacement transducer.Bending of the diaphragm leads to animbalance condition in a bridge circuit,the degree of which is a directmeasurement of pressure.

1.5.8 Industrial pressure measurement

When mounting a pressure transducer, it should be noted that anymechanical loading (other than the pressure being measured) will causea deflection of the diaphragm resulting in an error in the signal. It iscommon practice to monitor the output of the device (at zero pressure)during mounting and tightening to ensure that no mechanical stressingof the housing and subsequently the diaphragm occurs.

The diaphragms are typically made from stainless steel which allows themto be used with water and other corrosive fluids. In some applications,silicon diaphragm sensors are available that are useful for high frequencymeasurements. These devices have their strain gauges bonded to them byatomic diffusion during manufacture.The diaphragm can also be attached to a piezoelectric crystal. Pressuretransducers of this type incorporate acceleration compensation whichminimises the response of the device to vibration. They are useful for themeasurement of pressure variations occurring under conditions of high staticpressure.

Gauge: The pressure measured relative to ambient atmosphericpressure.

Absolute: Absolute pressure is equal to gauge pressure added toatmospheric pressure.

Differential: The pressure measured relative to a reference pressure.Proof: The maximum pressure that may be applied for the device to

remain within specifications.Burst: The maximum pressure that may be applied without physical

damage to the transducer.

Different types of pressure

Newnes Interfacing Companion64

Page 78: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.5.9 Sound

Microphones are pressure transducers designed for rapid changes in pressureat low amplitudes. For the professional sound industry, the frequencyresponse and directional characteristics of the microphone are the mostimportant parameters. Most microphones in use are of the condenser type.

Carbon buttonSound acts on a diaphragm which acts on an enclosed volume of carbongranules. Contact resistance between the granules depends upon thepressure. If a DC bias voltage is applied, the alternating resistanceproduces an AC signal which is proportional to the sound intensity.

Moving coilA diaphragm is attached to a coil which moves relative to a fixedpermanent magnet. The voltage induced in the coil is proportional tothe amplitude of the sound wave.

CondenserA metal diaphragm forms one plate of acapacitor, the other plate is fixed. Soundwaves cause the diaphragm to move. If thediaphragm moves towards the fixed plate,then, if the voltage across the plates is aconstant, this causes an increase in the fieldstrength between the plates since V = Ed.

PiezoelectricA diaphragm is attached to a quartz crystal. Displacements of the crystalarising from sound waves generate output voltage proportional to theamplitude of sound waves. Some crystal microphones have a preamplifierin them to reduce noise pickup by leads to the main power amplifier.

An increase in field strength draws more charge onto the plates thusresulting in a current flow in the connecting wires to the microphone.When the diaphragm moves away from the fixed plate, the current flow isreversed. The alternating current has frequency components equal to thatof the incoming sound waves. For high frequency work, an AC carriersignal is applied across the plates. The sound waves are then representedby a modulation of the carrier.

651.5 Force, pressure and flow

Page 79: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.5.10 Flow

The measurement of the flow of gases or liquids can be performed using arestriction which causes a pressure drop. The volume flow rate is usuallyproportional to the square root of the pressure difference. These types oftransducers are called differential pressure or dp flowmeters. They mayemploy orifices, nozzles, pitot tubes and centrifugal elbows.

For an incompressible fluid, andfrictionless flow, the theoreticalvolume flow rate Qth is:

( )ρ

= 212

1

2

2th

PP2

AA1

AQ

For the orifice plate, A2 is the areaof the vena contracta.

For real fluids, but still liquids, acorrection factor C, being thedischarge coefficient, is applied:

thactual CQQ =

p1 p2

p1p2

Orifice plate

Venturi

D

d

The discharge coefficient depends onthe type of meter (orifice or venturi) andis usually measured experimentally.

Characteristics:• No moving parts• Non-linear• Permanent

pressure loss

In one type of commerciallyavailable device, a tube is placedperpendicular to the flow stream.Holes in each side of the tubeface upstream (high pressure)and downstream (low pressure)leading to separate chambersinside the tube structure. Thepressure differential is measuredand calibrated to provide a flowrate. The cross-sectional shape ofthe tube is optimised to suit awide range of fluidviscosities.

p1

p2

A2

A1

Newnes Interfacing Companion66

Page 80: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Positive displacement flowmetersand rotating vane type flowmetersuse the physical movement of avane or piston as an indication offlow rate. In a typical device, twoimpellers are rotated by theflowing liquid. Magnets in theimpellers activate an external sensorwhich generates a pulsed output signal.Each pulse represents a known volumeof liquid that is captured between the lobes of the impellers and the pulsecount rate can thus be calibrated to provide flow rate in litres/minute.There should be enough back pressure on the outlet side of the flowmeterso that no gas pockets are formed during its operation. The positivedisplacement flowmeter is only suitable for liquid flow measurements.

Positive displacement

TurbineA turbine flowmeter contains a rotatingvane whose angular velocity is measuredand converted into flow rate. This typeof flowmeter is applicable for both liquidand gas flow measurements and issuitable for very low flow rates.ThermalMass flow rate can be determined by measuring the temperature drop ofa heated sensor. The technique is suitable for measuring gas and liquidflow. Some sensors of this type are used as a flow/no flow switch that canbe used to activate safety devices and level sensing. The technique uses nomoving parts.UltrasonicIn one ultrasonic method, a beam is directed into the flowing fluid at an angleand the doppler shift in frequency of the reflected beam is an indication offlow rate. In another method, the time taken for an ultrasonic pulse to travelfrom a transmitter to a receiver downstream is used as a measure of flow.

Turndown is the ratio between the minimum and maximum flow conditions in asystem. A 10:1 turndown ratio means that the maximum flow rate is 10 times theminimum flow rate in a system. A good flowmeter will be accurate for a turndownratio of approximately 150:1.

671.5 Force, pressure and flow

Page 81: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

The flowing fluid acts against the mass of the float that is inserted in thestream. A calibrated scale shows the flow rate directly.

This type of flowmeter is verysensitive to the arrangement ofinlet and discharge pipingconfigurations. The inletpiping should be as large adiameter as the inlet to themeter and be as straight aspossible – free from elbows,kinks and any otherrestrictions.

For gas flow measurements,the outlet or discharge pipeshould be as large as possibleto minimise back pressure.The gauge markings arecalibrated for an outlet intostandard atmospheric pressure.For liquid flow measurements,a moderate back pressure ispermissible.

The flowmeter ismounted vertically withthe inlet connection atthe bottom of the unit.

Float

This equation governs the physics of streamline or laminar flow.Bernoulli’s equation

p1h1

h2

A1

A2

v2

v1

p2P1

P2d

2222

2111 v

21ghpv

21ghp ρ+ρ+=ρ+ρ+

2211 vAvA =

Equation of continuity

Bernoulli’s equation

Newnes Interfacing Companion68

Page 82: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1.5.11 Level

The measurement of the level of liquids in tanks is a very important sensorand transducer application for process control. Various methods are available:

The differential pressure level transducermeasures the pressure difference betweenan upper and lower position in a tank (orthe atmosphere for a vented tank), andknowing the density of the fluid, the heightof the fluid can be determined.

In a float system, the float typically acts upon a displacement transducerdirectly or is mounted on a float arm that in turn operates a displacementtransducer. Float systems are mechanical devices that are prone to wearand corrosion. The displacement transducer can be of the resistive typethat offers a continuously varying signal, or simple switches that indicatean on/off condition for upper level and lower level limits.

Ultrasonic level transducers determine level by measuring the length oftime it takes for an ultrasonic pulse to be detected by a piezoelectrictransducer after reflecting from the fluid surface. While there are nomoving parts, vapours and turbulence affect the accuracy of the device.

hgp ∆ρ=∆

Pressuredifferential

Height offluid

• Float• Differential pressure• Ultrasonic• Capacitance• Radar• Ultrasonic

In a capacitance type level meter, the wall of the tank is used as one plateof a capacitor, and an electrode placed in the centre of the tank as the otherforming a capacitor. Changes in level of the liquid (which must be non-conducting) alter the capacitance (due to a change of permittivity of theinsulating medium or dielectric) of a connecting circuit driven at RFfrequencies. For conductive liquids, the probe is covered with an insulatingsheath (which becomes the dielectric) and a change in level is registered asa change in capacitance due to a change in effective area between theprobe and the grounded tank walls.Radar systems work on a similar principle to the ultrasonic type exceptthat electromagnetic waves are used to determine the time taken for areflection from the liquid surface to be received.

691.5 Force, pressure and flow

Page 83: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

3. The casing of a compressor is vibrating sinusoidally with adisplacement amplitude of 10−4 m and a frequency of 500 Hz.Calculate the amplitude of the acceleration.

5. A bellows is used to create a force in a system without contributingsignificantly to the stiffness in the system. If the bellows can beconsidered a series connection of 5 springs, each of stiffness 1 Nm−1,calculate the stiffness introduced into the system by the bellows.

9. If the discharge coefficient for a particular orifice plate of 1 cmdiameter inside a 5 cm pipe is 0.78, calculate the differential pressurefor a flow rate of water of 1 litre/sec.

2oo

2

2oout

s2sk1

FV

ω+ξω+

ω=

6. The expression describes the sensitivity of a piezoelectric forcetransducer. Letting s = jω, determine an expression for the sensitivityas a function of ω and indicate the general features of this response ona freehand graph. Assume ωo and ξ are constants.

1.5.12 Review questions

4. Would you expect the resonant frequency of a piezoresistive forcetransducer to be above or below that of a piezoelectric force transducerand why?

1. A strain gauge element has a gauge factor of 2.0 and an unstrainedresistance of 150 Ω. If the change in resistance of the element atmaximum strain is 5 Ω, determine the maximum strain that the elementis designed to measure.

2. Calculate the required spring stiffness k and damping constant λ for anaccelerometer that has a natural resonance at 10 Hz, a damping ratio of0.8, and a seismic mass of 5 grams.

7. A Fortin barometer is used to measure atmospheric pressure at latitude53 °N and at a height 10 m above sea level. The vernier scale on thebarometer reads 992.4 mbar and a nearby thermometer reads 19.8 °C.Calculate the corrected atmospheric pressure.

8. How does flow rate vary with the pressure drop in a restriction typeflow transducer (a semi-quantitative answer please, e.g. square, linear,exponential etc.).

(Ans: 1.67%)

(Ans: 0.197 N/m, 0.05 Ns/m)

(Ans: 100 g)

(Ans: 989.84 mbar)

(Ans: 8.34 kPa)

Newnes Interfacing Companion70

Page 84: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

71

Page 85: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

2.0 Interfacing

It is common practice to use a computer to record measurements from atransducer. Transducers generally provide an analog signal that must beconverted to digital format for data storage and analysis. The connectionbetween the transducer and the computer is called the computer interface.

In Part 1 of this book,we are mainly interestedin transducers.• A sensor is a device

which responds to aphysical stimulus

• A transducer is adevice which converts aphysical stimulus toanother form of energy(usually electrical)

Physicalphenomena:SoundMeter readingLED indicatorDigital displayChart recorderVDU output

Physicalphenomena:TemperatureVoltagePositionVelocityForcePressureRadioactivityLight intensityResistanceHumidityGas concentrationMagnetic fieldFrequencySound level

Actuatorprovides aphysical

response toelectrical signal

Actuator

Optionalfeedback

Transducer(sensor and

preamplifier)

Amplifier andsignal

conditioning

Computerinterface

Part 2 of thisbook isconcerned withcomputerinterfacing.

Part 3 of thisbook coversinstrumentationand signalprocessing.

Newnes Interfacing Companion72

Page 86: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

73

Page 87: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

2.1.1 Binary number system

There are ten digits in the decimalnumbering system. In the binary system,there are only two, 0 and 1. Each digit in abinary number is called a bit. Computersconsist of millions of transistor switchesthat can be either on or off, or true or false,and as a consequence they employ the twoavailable digits in binary number system torepresent the states of these switches.

Decimal Binary0 00001 00012 00103 00114 01005 01016 01107 01118 10009 100110 101011 101112 110013 110114 111015 1111

Bits can be arranged to provide anumerical code that can be used to conveyinformation. A particularly popular codeis the ASCII code used to representdecimal digits, alphabetic characters.

Since combinations of only two digits are used to represent binary numbers(i.e. 0 and 1), they tend to be rather cumbersome when large numbers areto be represented. For example, the number 26 in decimal is given by:

2610 = 11010A group of 8 bits occurs very frequently in computersystems and is called a byte. Groups larger than 8 bits,such as 12 or 16 bits, are called words. The left mostdigit in binary representation is called the mostsignificant bit, or msb, since it has the most weight indetermining the magnitude of the number. The rightmost digit is called the least significant bit or lsb.It is convenient to express large numbers arising frombinary arithmetic by a convenient factor which happensto be 210 = 1024. For example, 65 536 divided by 1024is 64 k where the ‘k’ means divided by 1024. For a 24bit word, we divide 16 777 216 by 1024 twice to obtain:16M where M means mega. 1024 bytes is one kilobyteand thus, 640 kb is really 640 × 1024 = 655 360 bytes. 1megabyte (Mb) is 1 × 1024 × 1024 = 1 048 576 bytes.64 kb = 65 536 bytes, which, if numbered sequentially,would be referenced from 0 to 65 535.

Powers of 222 423 824 1625 3226 6427 12828 25629 512210 1024211 2048212 4096213 8192214 16 384215 32 768216 65 536

Newnes Interfacing Companion74

Page 88: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

The binary numbering system has only two digits, 0 and 1. It is easy toconvert from decimal to binary by repeated divisions by 2. Start towardsthe right side of the page and work to the left.Example: Convert 2610 to binary:

26 Quotient÷213 Answer0 Remainder

13 26÷2 2 ÷

6 13 Answer1 0 Remainder

1 3 6 13 26 Quotient÷2 ÷2 ÷2 2 2 ÷

0 1 3 6 13 Answer1 1 0 1 0 Remainder

Repeat until zero obtained as Answer.

The result is given by the Remainder: 2610 = 11010.

2.1.2 Decimal to binary conversion

Transfer Answer to next Quotient column to the left and divide by 2.

For binary to decimal, each binary position, starting at the least significantbit, represents a power to which the base 2 should be raised – starting from0. Example: Convert 11010 to decimal:

= 1(24) + 1(23) + 0(22) + 1(21) + 0(20)= 26

The numbering of bits in a binary number from 0 to 7 starting from the rightand going to the left may seem a little backwards but ensures that each bit israised to the power given by the bit position when converting to decimal.

752.1 Number systems

Page 89: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Decimal Hex Binary0 0 00001 1 00012 2 00103 3 00114 4 01005 5 01016 6 01107 7 01118 8 10009 9 100110 A 101011 B 101112 C 110013 D 110114 E 111015 F 1111

Programming at assembly or machine language levels often entailsworking with groups of 4, 8 or 16 bits at a time. For this reason, it issimpler to use a numbering system which has as its base 4 bits, which is amaximum of 16 combinations from 0000 to 1111. The hexadecimalnumbering system is based on 16 combinations of 4 bits and uses letters tosignify numbers greater than decimal 9. Thus, single digit numbers go fromdecimal 0 to 9 but letters A through F are used to represent numbers greaterthan 9. The term “hexadecimal” is a combination of hex meaning six anddecimal meaning, of course, ten.

2.1.3 Hexadecimal

Hexadecimal (hex) numbers may be written with a leading $ sign todistinguish them from decimal numbers. For example, $FF is decimal 255or 1111 1111 in binary. Binary numbers may be specified with a leading% and decimal integers with . which in this case is not to be taken as adecimal point. Hex and binary numbers may also be represented by atrailing “h” or “b” respectively.

Note: We are onlyconcerned with integernumbers here.Methods of expressingfractions need notconcern us for themoment.

Newnes Interfacing Companion76

Page 90: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

2.1.4 Decimal to hex conversion

Repeated divisions by 16. Start at right of page and work towards left. Stopwhen 0 obtained as answer. The result is given by the Remainder.Example: Convert the number 26 to hex:

Convert from decimal to hex:

1 26÷16 ÷160 1 Answer1 10 Remainder

Answer: 1A (10 becomes A in hex).

Each binary position, starting at the least significant bit, represents a powerto which the base 16 should be raised – starting from 0.Example: Convert 1A to decimal:

Convert from hex to decimal:

1A = 1(161) + 10(160) = 26

Convert from hex to binary:

Arrange each hex digit in groups of four and usethe hex table.Example: Convert 1A to binary:

1 A0001 1010

Answer: Obtain binary equivalents from hextable and write the binary in groups of four. Thisgroup of 8 bits is called a byte. The answer is0001 1010 and the leading zeros can bediscarded if desired. However, it is sometimesconvenient to keep the binary digits grouped inlots of four and we write: 0001 1010. Thegroupings are for our convenience only.

Dec Hex Bin0 0 00001 1 00012 2 00103 3 00114 4 01005 5 01016 6 01107 7 01118 8 10009 9 100110 A 101011 B 101112 C 110013 D 110114 E 111015 F 1111

772.1 Number systems

Page 91: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

2.1.5 2’s complement

The 2’s complement is a special operation performed on a binary numberwhich yields a new binary number, the significance of which will beexplained shortly. The 2’s complement is found by reversing all the bits ina binary number (called the complement or the 1’s complement) and thenadding 1 to the result. Example: What is the 2’s complement of 13?

Original number 13invert all bitsadd 12’s complement

It so happens that the 2’s complement can be used torepresent the negative of a positive integer thus allowing acomputer to perform a subtraction with a digital addingcircuit. Taking the 2’s complement of a number twicereturns to the original number.

The binarynumber in thisrow is calledthe “1’scomplement”

The computer stores the mantissa and the exponent in different places. In asimplified system, the mantissa may occupy 4 bytes of storage followed bya 1 byte exponent. Decoding of this format is typically done in software,although a specialised maths co-processor chip is fitted to mostmicrocomputers to perform these conversion routines in hardware, andthus more quickly.

Note that in our discussion so far, we have always been working withintegers. Indeed, that is the only type of number that computers can workwith. However, we need to represent fractions and very large numbers aswell in everyday computing applications. How is this done? Briefly, thecomputer divides up numbers into two parts called the mantissa and theexponent. The format is very similar to scientific notation used byscientists and engineers. The number 7 × 105 (sometimes written 7E5) is700 000. In this example, 7 is the mantissa and 5 is the exponent.

7 ×105

Exponent

Mantissa

0 0 0 0 1 1 0 11 1 1 1 0 0 1 0

11 1 1 1 0 0 1 1

Newnes Interfacing Companion78

Page 92: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

An 8-bit memory location can cover the range of decimal integers from 0to 255. To enable an 8-bit memory location to hold both positive andnegative numbers, the most significant bit (msb) is reserved and is calledthe sign bit. A sign bit = 1 indicates a negative number. A sign bit = 0indicates a positive number. The other 7-bit positions are used to representthe magnitude of the number − but the way of doing this is different forpositive and negative numbers.

1. Positive numbers: Theremaining 7-bit positionsrepresent the magnitude ofthe number directly. 7 bitsgive a range 0 to +127.

0 0 1 0 1 0 0 00 msb indicates a positivenumber. The magnitude ofthe number is 23 + 24 = 40.

2. Negative numbers arerepresented in 2’s complementnotation. Example: −40 is:

40 in binary notationcomplement:add 1−40 in 2’s complement:

The sign bit (msb) indicates anegative number.

2.1.6 Signed numbers

For signed numberrepresentation, therange that can becovered by 8 bits is−128 to +127.Signed positivebinary numbers rollover to representnegative numbersafter +127.

7F 0 1 1 1 1 1 1 1 +127. . . . . . . . . .. . . . . . . . . .. . . . . . . . . 2. 0 0 0 0 0 0 0 1 10 0 0 0 0 0 0 0 0 0FF 1 1 1 1 1 1 1 1 -1. 1 1 1 1 1 1 1 0 -2. . . . . . . . . .. . . . . . . . . .80 1 0 0 0 0 0 0 0 −128

Whether or not a particular binary bit pattern represents a signed orunsigned number depends on the context in which it is being used. Forbinary numbers starting with 0, there is no confusion since they have thesame value whether they are signed or unsigned numbers. For numbersstarting with 1, they may be interpreted as an unsigned integer or the 2’scomplement representation of a negative number.

The +1 step in finding the 2’s complement takes into account ±0 possibilities(i.e. 1’s complement goes from −127 to −0, and +0 to +127).

0010100011010111 111011000

792.1 Number systems

Page 93: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

2.1.7 Subtraction and multiplication

For a subtraction, the 2’s complement isadded. Example: 43 − 40 = 43 + (−40)

00101011 +4311011000 −40 in 2’s complement100000011 answer = 11 (i.e. 3)

The extra bit on the left in theanswer is called the carry bit.The carry bit is ignored insigned arithmetic but not inunsigned arithmetic.

Example: 40 − 43 = ?

00101000 +4011010101 −43 in 2’s complement11111101 add to find answer

The msb is a sign bit which inthis case indicates a negativenumber. To find out what thisnumber is in decimal, weneed to find the inverse 2’scomplement.

11111101 answer from above00000010 complement 1 add 100000011 final answer is −3

Note that the final answer indecimal is −3 since the signbit indicated that the numberbeing stored was a negativenumber.

Convert answer from above into decimal:

Multiplication and division by 2 in the binary number system is very easilydone by a shift. Consider the product 2 × 4 = 8. Now, 410 = 0100 and shiftto the left, gives 1000 (810). A shift to the right is a division by 2.Multiplications with other numbers in binary isperformed in exactly the same way as for decimalnumbers e.g. 12 × 6 = 8.

1 1 0 0 multiplicand 12100 1 1 0 multiplier 6100 0 0 0 x by 0 with no shift

1 1 0 0 x by 1 and shift left1 1 0 0 x by 1 and shift twice

0 01 0 0 0 x by 0 and shift thrice1 0 0 1 0 0 0 + for final result = 72

Start by multiplying the multiplicand by the lsb of themultiplier. Repeat with other bit positions of multiplierand shift answers left one position each time.

This is analogous topositioning ofdecimal digits in the1’s, 10’s and 100’scolumns.

Multiplication involvesrepeated shifts left andadditions. The processof division is verysimilar except that itinvolves repeatedsubtractions of thedivisor.

Multiplication

Subtraction

Newnes Interfacing Companion80

Page 94: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

2.1.8 Binary coded decimal (BCD)

Coding schemes are used to represent data in binary format. Althoughnumbers may be expressed in the binary system directly, it is sometimesmore convenient to use a coding scheme. A very well-known scheme fornumerical data is the binary coded decimal system. The BCD code usesbinary numbers 0 and 1 to represent decimal numbers 0 to 9. Each digit ina decimal number is transcribed into a 4-bit binary number.

Decimal BCD0 00001 00012 00103 00114 01005 01016 01107 01118 10009 1001

Note: Binary numbers above1001 are not a part of the BCDsystem.

The main advantage of the BCD systemis that the binary numbers in BCD areeasily recognised and converted intodecimal numbers because of theirposition.

The main disadvantage is that arithmeticoperation on BCD encoded data is not soeasily performed. BCD adders arerequired to perform arithmeticoperations.

Consider the decimal number 2563. To represent this number in BCD isfairly straightforward. We simply write the binary numbers out insequence for each digit in the decimal number.

0010 0101 0110 0011 2 5 6 3

Each decimal number from 0 to 9 is represented by a four digit binarynumber. The weight, or contribution, of the msb in each binary numberis 23 = 8. The weight of the lsb is 20 = 1. The weights of the other twobit positions are 22 = 4 and 21 = 2. The BCD code is sometimes referredto as an 8421 code for this reason.

812.1 Number systems

Page 95: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

2.1.9 Gray code

The Gray code is well-known code originally used for encoding theangular position of a rotary encoder. Such an encoder may be constructedby a masked wheel whose concentric tracks are read by photo cells.The main problem with the binarynumber system in this type of encoderis that there are many positions inwhich several tracks change their stateat the same time. Thus, if a readoperation occurs part way through atransition from one angular position toanother, then the resulting error couldbe quite large.

Dec Hex Bin Gray0 0 0000 00001 1 0001 00012 2 0010 00113 3 0011 00104 4 0100 01105 5 0101 01116 6 0110 01017 7 0111 01008 8 1000 11009 9 1001 110110 A 1010 111111 B 1011 111012 C 1100 101013 D 1101 101114 E 1110 100115 F 1111 1000

To convert from binary to Gray, westart at the msb and compare it to 0.If the msb is 0, then we write 0 asthe msb for the Gray coded number,otherwise we write 1. We nextcompare the next msb and compareit to the msb. If they are equal wewrite a 0 in the position for the Graycoded number, otherwise, 1. Wethen compare each bit in the binarynumber to the bit just to the left of itand write 0 for a true comparisonand 1 for a false. This procedurecontinues until the lsb is comparedwith the second bit.

00000001

0011

0010

0110

01110101

010011001101

1111

1110

1010

1011

10011000

In the Gray code, only one track changes state at any one time during arotation. Should a read error occur, then the resulting number will be inerror by only one bit value. The Gray code is a non-weighted code. Anybinary number can be converted into the Gray code, there is no upper limitto the number of code combinations. Conversion from Gray to binary caneasily be done in a computer and so this code makes it ideal for this typeof instrumentation purpose.

Gray code

Newnes Interfacing Companion82

Page 96: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

2.1.10 ASCII code

The ASCII code is almost universally used to represent both numeric,character and special symbol data. The code is, in its standard form, a 7-bitcode. 7 bits gives 128 different combinations. The 8th bit is sometimesused as a parity bit for error detection. In the extended ASCII characterset, the 8th bit (or msb) is used to create another 128 characters that containmathematical and other special symbols.

0 1 2 3 4 5 6 7

0 NUL DLE Space 0 @ P ‘ p

1 SOH DC1 ! 1 A Q a q

2 STX DC2 “ 2 B R b r

3 ETX DC3 # 3 C S c s

4 EOT DC4 $ 4 D T d t

5 ENQ NAK % 5 E U e u

6 ACK SYN & 6 F V f v

7 BEL ETB ‘ 7 G W g w

8 BS CAN ( 8 H X h x

9 HT EM ) 9 I Y I y

A LF SUB * : J Z j z

B VT ESC + ; K [ k

C FF FS ‘ < L \ l |

D CR GS - = M ] m

E SO RS . > N ^ n ~

F SI US / ? O _ o DEL

msb

lsb

7-bit ASCII code

Example: The number 4F, or 1001111, is the letter ‘O’.

The first 32 characters in the code are control codes. These codes areinterpreted by the device to which the data is being sent. For example, aprinter receiving a CR code would execute a carriage return. Manymicrocomputer applications store their data in ASCII format. It is probablythe most universally used method of representing numeric and characterdata for both storage and transmission purposes.

832.1 Number systems

Page 97: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

True FalseHigh LowMark SpaceOn Off0 15 V 0 V

Binary system:

A

B

AND gate

Output = 1(TTL High)when A and Bare both 1

NOR gate

Output = 1(TTL High)when neither Anor B are 1

A

B

Digital electronic circuits contain components which act like high speedswitches that process voltage levels TTL high (5 V) and TTL low (0 V).These circuits are thus suitable for representing the binary numbers 0 and 1.TTL high and TTL low may also represent logic states true and false andthus allow binary data to be processed using Boolean algebra in a digitalcircuit. The components of a digital circuit are called logic gates. Booleanalgebra are laws which specify the interaction between logical states true (1)and false (0). Truth tables provide the rules for the Boolean operators.

2.1.11 Boolean algebra

A B A AND B A•B0 0 0 Output true0 1 0 only if both A and B1 0 0 are true 1 1 1

A B A OR B A+B0 0 0 Output true 0 1 1 if either A or B are1 0 1 true1 1 1 OR

AND

A B A NAND B0 0 1 Output true if 0 1 1 both A and B are not1 0 1 true1 1 0

A B A NOR B0 0 1 True if A and B 0 1 0 are both not true.1 0 01 1 0

A B A XOR B0 0 0 True if either A or B0 1 1 are true but not both1 0 1 together.1 1 0

NAND

NOR

XOR

Newnes Interfacing Companion84

Page 98: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Boolean algebra can be implemented using digital electronic circuits usingcombinations of logic gates.

A

B

A XOR B

In the circuit below, the XORfunction is used to add binary digitsA and B. The AND gate indicateswhether or not there is a carry bit.This circuit is a half adder.

A B O0 0 00 1 11 0 11 1 0

Truth table

A

B

Sum

Carry

A B S C0 0 0 00 1 1 01 0 1 01 1 0 1

Truth table

2.1.12 Digital logic circuits

e.g. A combination of NAND gatesgives a logical XOR function.

A + B = B + AB • A = A • B

(A + B) + C = A + (B + C)(A • B) • C = A •(B • C)

A + AB = A •(1 + B) = AA •(A + B) = A

A •(B + C) = A • B + A • CA + (B • C) = (A + B) •(A + C)

A + A = AA • A = A

A + A • B = A + BA •(A + B) = A • B

De Morgan’s theorem(A + B) = A • B(A • B) = A + B

Laws of Boolean algebra

A • A = 0A + A = 1A = A0 + A = A1 • A = A1 + A = 10 • A = 0

852.1 Number systems

Page 99: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1. How many numbers may be represented by a sequence of 8 binarydigits?

2. Shown below are some decimal numbers. Fill in the columns assuming2’s complement notation.

Decimal Binary Hex-1 . .127 . .28 . .

3. Fill in the table below (assume 2’s complement notation).Binary Decimal Hex1010 . .. . 80. . FF

4. Find the two’s complement of $0E and show that by finding the 2’scomplement twice the original number is returned.

5. Consider the bit pattern 1011 1101. Determine another bit pattern(called a mask) which, when logically combined (using a Booleanexpression) with the first, toggles the second most significant bit (from0 to 1 or 1 to 0) but leaves the others unchanged.

2.1.13 Review questions

7. Design a logic circuit which implements the XOR function but usingOR and NOR gates only.

6. Discuss the relative differences of the Gray code, the BCD code, andthe ASCII code.

8. Draw up the simplest logiccircuit satisfying the truth tablegiven:

A B C0 0 10 1 01 0 11 1 1

Newnes Interfacing Companion86

Page 100: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1. Start the Microsoft Windows Calculator and set to scientific mode.Then select BIN for binary mode and WORD.

3. Perform a decimal subtraction using the Calculator which gives anegative result (say 8-10). Convert the answer to Hex and then tobinary. What is the significance of these answers?

Dec:Hex:Bin:

2.1.14 Activities

4. Consider the product 2 × 4 = 8. Verify that this multiplication, whenperformed in Binary mode using the Calculator, is the same as the oneshift to the left of the binary representation of the decimal number 4(you may need to find out how to use the “shift left” function of theCalculator using the Help topics).

5. Consider the bit pattern 1011 1101. Determine another bit pattern (amask) which, when logically combined (using a Boolean expression)with the first, toggles the second most significant bit (from 0 to 1 or 1to 0) but leaves the others unchanged. Use the Calculator to test this(using the Boolean operator keys).

2. Set the Calculator to HEXmode and set to BYTE andthen type in FFFF. Convertthis number to Decimal andthen Binary by selecting theappropriate buttons:

Dec: ____________

Bin: _____________

Add the two 16-bit numbers below by first adding manually on paperand then using the calculator:

1 0 1 1 1 0 1 1 1 0 1 0 1 0 1 01 1 0 1 1 1 0 1 1 1 0 0 1 1 0 0

872.1 Number systems

Page 101: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

88

Page 102: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

The combination of functional components in a computer is referred to asthe architecture of the microcomputer. The main functional componentsin a microcomputer are the CPU or central processing unit, memory, andinput/output (I/O) devices:

2.2.1 Computer architecture

Each memory cell is capable ofholding 8 bits, or 1 byte, of data.Memory cells are labelled with aunique address.

Binary information is transferred asTTL logic across wires called thebus – the address bus, the data busand the control bus. When anaddress is placed on the address bus,the byte of information at or for thatmemory location is placed on thedata bus. Signals on the control bustell the CPU whether a read or writeoperation to that memory cell isrequired.

CPUI/O

Data bus

Address bus

Controlbus

The data bus in the 8086 CPU is16 bits wide and is bi-directional. It can transfer datain both byte and word length toand from the CPU and memory.

The address bus is unidirectional inthat data is placed on it only by theCPU. The 8086 chip has a 20-bitaddress bus but the internal registersof the CPU are only 16 bits. Aspecial segmented memoryaddressing scheme is used to obtainaccess to the full 1 MB memory.

The control bus carries varioussynchronisation and controlsignals, the only one of interest tous being the read/write signal.This is designated R/W (read/notwrite). During a read cycle, theprocessor receives data fromeither memory or a memory-mapped peripheral device. Duringa write cycle, the processor sendsdata to either a memory cell or amemory-mapped device.

The data bus is nominally 16 bits, butin 8088 machines, it is physically only8 bits wide. Internally, the CPUtransfers 2 bytes in sequence andoperates as a 16-bit device. Tofurther complicate matters, the databus and the first 8 lines of theaddress bus on the 8088 aremultiplexed (the same wires areused for both functions - but atdifferent times). Later processorsemploy data buses up to 64 bits wide.

892.2 Computer architecture

Page 103: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

00F101 3200F100 D300E111 32

Address data

2.2.2 Memory

Each memory cell is capable of holding 8 bits, or 1 byte, of data. Memorycells are labelled with a unique address. When the microprocessor wishesto read or write data to a particular memory cell, it places the address ofthe required cell on the address bus, and the data to or for that memorylocation appears on the data bus. Internal circuitry ensures that only thememory cell whose address appears on the address bus receives or sendsthe data from or to the data bus.The amount of memory that can be addressed by theCPU depends on the width of the address bus. TheIntel 8086 CPU has a 20 bit address bus and is able toaddress a total of 220 = 1 048 576 bytes (1MB ofRAM). Each memory cell is numbered $00000 to$FFFFF. However, the internal working registers inthe 8088 are only 16 bits wide and a specialsegmented memory addressing scheme is used to fitthe 20-bit address data into the 16-bit registers. Incontrast, the 80286 has a 24-bit address bus allowing16 MB adressable RAM. Later processors employ a32-bit address bus (486) giving 4 GB addressablememory while Pentium Pro and later processors have64 GB addressable memory.

Program statementsare always stored inthe code segment.Data for programs isstored in the datasegment etc.

Memory is divided into a number of segments, each of which is 64 kb in size:• Code segment• Data segment• Stack segment• Extra segment

Each segment is 64 k. Since the total addressspace is 1 048 576 bytes, there are a possible1 048 576 /65 536 = 16 segments.

0 1 0 0 . . . .0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

4-bit segmentidentifies one of16 possiblesegments ofmemory.

16 bit Offset identifies each ofthe 65536 individual memorylocations in each segment.

Thus, to specify a particularlocation in memory, all weneed is a 4-bit segment baseaddress and a 16-bit offset.

Lowmemory

Highmemory

Unfortunately, it is not that simple. Segments need not start on the 64k boundariesshown above. Indeed, segments can start anywhere on a 16-bit boundary since thefull 16-bit width of the CPU internal registers can then be utilised.

Newnes Interfacing Companion90

Page 104: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Here’s how segmented memory really works:

1. The 16-bit segment is multiplied by 16 to form a20-bit segment base address by shifting to theleft four times.

Segment baseaddress (20 bits)

2. The 16-bit offset is added to thesegment base address to obtainthe 20-bit absolute address.

1 0 1 0 0 1 1 1 1 0 1 0 0 1 0 0 0 0 0 0_ _ _ _ 1 0 0 0 1 0 0 1 1 1 0 0 1 1 1 01 0 1 1 0 0 0 0 0 1 0 0 0 0 0 0 1 1 1 0

+Final 20 bitaddress

16-bit offset

Note: Since segments can bespecified with any 16-bit number, it ispossible to have two differentsegmented addresses which refer tothe exact same physical memorylocation! For example, 0010:0000 isthe same as 0000:0100 which ismemory location 100H.

3. The segmented address iswritten with the segmentfollowed by a colon “:” andthen the offset. For example:

FFE2:01D0

Segment Offset

Why is it useful to have segments startat any 16-bit address boundary? Itpermits a more efficient use of memory.For example, a particular program maynot need a full 64k code segment.Some of this available memory may beused as the data segment by allowingthe segments to overlap. By allowing a16-bit number to specify the segment(instead of a 4-bit number), the start ofeach segment can be controlled towithin a 16-bit boundary (instead of a64 k boundary).

This example shows how the StackSegment can be accommodatedwithin a 64K block which is onlypartially used by the Code Segment.

64kCS

SS

actuallyusedavailableThe number obtained after the

segment has been added to theoffset is called the absoluteaddress.

2.2.3 Segmented memory

Segment: 1010 0111 1010 0100

Offset: 1000 1001 1100 1110

912.2 Computer architecture

Page 105: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Each memory cell can store 8 bits, or 1 byte, of data. The width of the databus indicates how much data can be transferred during each memoryread/write operation. The 8088 CPU has an 8-bit data bus but canactually process 16 bits at a time using its 16-bit internal registers. The80286 has a full 16-bit data bus. The 80486 has a 32-bit data bus andPentium processors have a 64-bit data bus.

Groups of bits larger than a byte arecalled words. In a 16-bit machine,the term word is used to describe16-bit (2-byte) data and the termlong word or double words for 32-bit (or 4-byte) data. In the 8086architecture, words are stored inmemory with the higher byte in thehigher numbered address.

In the example here, referencing aword at 06000H, one wouldobtain: 3E01H. When words anddouble words start at an addressthat is a multiple of 4, they arealigned.Double words take up fourmemory locations and are storedwith the higher word at the higheraddress pair. Within each word,the higher byte is stored at thehigher numbered address. It isusual to write memory addressesfrom the bottom upwards.

Data Logical (1s and 0s indicating T and F) orNumeric – signed or unsigned integers as binary numbers.

Instructions An assembly or machine language opcode.Address A “pointer” to which the CPU goes to get the data required.

06001 3E06000 01

Address data

The width of the address bus on theMC 68000 chip is effectively 24 bits (3bytes). (On the 68000 chip, theaddress bus is only 23 bits widenumbered A1 to A23 with an internalA0 bit which controls the way the 16-bit data bus is used. The effective buswidth is thus 24 bits.) The number ofaddressable memory locations is:

which are numbered from 0 to16 777 125 or in hex $000000 to$FFFFFF. Each address refers to adata space of one byte (or 8 bits)giving 16 MB of RAM.

No. addresses = 224

= 16 777 216

68000

2.2.4 Memory data

The contents of memory are interpreted by the CPU as either:

Newnes Interfacing Companion92

Page 106: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

2.2.5 Buffers

Binary signals are transmitted between the CPU and memory cells acrossthe address and data buses. Proper communication of data requires that oneand only one memory cell, the one whose address is present on the addressbus, has direct connection to the data bus at any one time. Decodingcircuitry determines the location of the desired memory cell to beactivated. Activation of a single memory cell entails connecting the cell tothe data bus and ensuring that all other cells are effectively disconnected.This connection procedure is carried out by tri-state buffers.The table below shows that the connection between the data bus and amemory location must be set at a high impedance when the chip-selectsignal CS is low and pass through the data when chip-select is high.

Data CS Connection0 0 High impedance1 0 High impedance0 1 01 1 1

Buffers isolate memory cells from the data bus and also allow data to passthrough during read/write operations. Since the data bus must pass data inboth directions, its connections to the bus and the memory cell must becapable of being at TTL high and TTL low (to represent logic levels 0 and1). When a memory location is not selected (by the decoders), the buffermust effectively disconnect the memory cell from the data bus by insertinga high impedance. The term tri-state means that the connection made bythe buffer can be either TTL high, low or high impedance.

Q1 Q2 OutputOff Off High impedanceOff On 0 V On Off +5 V

+5 V

Q1

Q2Output

Inputs

A simple example of tri-state logic can bemade using two transistors as shown:

932.2 Computer architecture

Page 107: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

2.2.6 Latches

A latch is a device which holds the data that appears on its input terminals.A memory cell in the microcomputer system is a latch. Typically, signalsdestined for storage in memory cells appear on the data bus momentarilyand then disappear. The timing of the signals is regulated by the internalclock which runs at speeds typically in the MHz range. The decodingcircuitry determines which buffer is to be activated. The activated buffer inturn connects the latch input terminals to the data bus. The signals on thedata bus are transferred through buffers to the latch circuit which stores thesignals on its output terminals.

An octal latch has 8 inputs and 8outputs. The data latch enable (DLE)pin, when set high, copies the voltagelevels on the input pins to thecorresponding output. The latchcircuitry retains the signals on theoutput pins even if the input signalsdisappear and DLE goes low. It isimportant that DLE is set when dataappears on the input. DLE istypically timed to go high when dataappears on the data bus. The clocksignals are used to synchronise thistiming.

A latch circuit can be implementedusing a series of RS flip-flops. Inthis figure, the 4 bit data at D3 to D0is transferred to Q on the clockpulse. When a bit D is logic 1,S = 1 and R = 0 and the output Qbecomes 1. When D is logic 0, S = 0and R = 1 and the output D = 0.

Q2

Q

D2 S

R

Q1

Q

D1 S

R

Q3

Q

D3

Qo

Q

Do S

R

Clock (DLE)

S

R

4 bit latch

Newnes Interfacing Companion94

Page 108: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Flip-flops can be used to represent binary numbers. An RS flip-flop is adigital circuit which is stable in one of two states − set or reset. Such acircuit can be made using NAND gates. A truth table summarises theaction of flip-flop. The voltage of one of the outputs can be used torepresent or store a binary digit since it can be either voltage high (logic 1)or low (logic 0) and will remain at that setting until signals on the input,which only last for a short time, set or reset the outputs.

A microcomputer uses a clocked flip-flop to synchronise the action of thecircuit.

Data at terminal S getstransferred to Q on theclock pulse and remains atQ even if the signal at Sdisappears and the clockgoes low.

S

R

The data stays at Q becausewhen the clock pulse goes low,the flip-flop circuits within thechip are at S = R = 1 (due to theNAND gates on the clock stage).Only when the clock goes highdo the flip-flops react to the logicsignals at D on the latch.

R S0 0 not used0 1 Q = 0; Q = 11 0 Q = 1; Q = 01 1 no change

Action table (RS):

R S0 0 no change0 1 Q = 1; Q = 01 0 Q = 0; Q = 11 1 not used

Action table (clocked RS):

Note: This action table is different tothe ordinary NAND flip-flop. Here,R = S = 1 is the “not used” state.

2.2.7 Flip-flop

S

R

Q

Q

clock

Q

Q

952.2 Computer architecture

Page 109: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

There are three methods of handling input/output devices. The first is bythe use of ports. In an 8088-based microcomputer, ports are identifiedusing a 16-bit port number. Thus, there are a total of 65 536 availableports numbered 0 to 65 535. The CPU uses a signal on the control bus tospecify that the information on the address bus and data bus refers to a portand not a regular memory location. The port with the specified numberthen receives or transmits the data from its own inbuilt memory which isnot part of the main computer’s memory. However, some devices usemain memory for their own use and thus data for these devices may bespecified using regular memory addresses. This is the second method usedfor I/O. Such devices (e.g. video adaptors) are called memory-mappedI/O devices.

This list shows the range of inputand output devices for a typicaldesktop microcomputer. Thesedevices may often by memory-mapped and data is writtenfrom/to them via interfaceadaptors. Some ports are notmemory mapped and a signal onthe control bus identifies to theCPU that the address is that of aport and not a memory location.

The third method of I/O involvesbypassing the CPU and writing orreading directly from memory. This iscalled direct memory access or DMA.A special DMA controller IC is used toregulate traffic on the bus for thisactivity. A computer’s disk driveusually transfers data to or frommemory using DMA.

2.2.8 Input/Output (I/O)

Part of the success of the originalIBM PC and the Intelmicroprocessor family was due tothe use of open architecture,made possible by the expansionbus. The original ISA (IndustryStandard Architecture) provided a16-bit bus. The introduction of thePentium CPU also saw theintroduction of the PCI (PeripheralComponent Interface) bus. Thisbus supports 32-bit and 64-bitdata transfers with an increase indata transfer rate over the ISAbus.

ISA and PCI bus

Newnes Interfacing Companion96

Page 110: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

The CPU is responsible for initiating transferring data to and frommemory and input/output devices, performing arithmetic and logicaloperations, and controlling the sequencing of all activities. Inside the CPUare various subcomponents such as the arithmetic logic unit (ALU), theinstruction decoder, internal registers and various control circuits whichsynchronise the timing of various signals on the buses.

The central processing unit organises and orchestrates all activities insidethe microcomputer. Each operation within the CPU is actually a verysimple task involving the interaction of binary numbers and Booleanalgebra. A large number of these simple tasks combine to form a particularfunction which may appear to be alarmingly complex.

The “MPU” is essentially the same thing as the morefamiliar and general term “CPU” (CPU applies to anycomputer, and not just a microcomputer).

Instruction decoderArithmetic logic unitRegisters

Address registersPointersFlagsInstruction pointer

2.2.9 Microprocessor unit (MPU/CPU)

80X86 CPU development1972 Intel introduces the 4004 with a 4-bit data bus, 10,000 transistors.1974 8080 CPU has 8-bit data bus and 64 kb addressable memory (RAM).1978 8086 with a 16-bit data bus and 1 MB addressable memory, 4 MHz clock.1979 8088 with 8 bit external data bus, 16-bit internal bus.1982 80286, 24 bit address bus, 16 MB addressable memory, 6 MHz clock.1985 80386DX with 32-bit data bus, 10 MIPS, 33 MHz clock, 275 × 103 transistors1989 80486DX 32-bit data bus, internal maths coprocessor, >1 × 106 transistors,

30 MIPS, 100 MHz clock, 4 GB addressable memory.1993 Pentium, 64-bit PCI data bus, 32-bit address bus, superscalar architecture

allows more than one instruction to execute in a single clock cycle, hard-wired floating point, >3 × 106 transistors, 100 MIPS, >200 MHz clock, 4 GBaddressable memory.

1995 Pentium Pro, 64-bit system bus, 5.5 × 106 transistors, dynamic executionuses a speculative data flow analysis method to determine which instructionsare ready for execution, 64 GB addressable memory.

1997 Pentium II, 7.5 × 106 transistors with MMX technology for video applications64 GB addressable memory.

1999 Pentium III, 9.5 × 106 transistors, 600 MHz to 1 GHz clock.2000 Pentium 4, 42 × 106 transistors, 1.5 GHz clock.2001 Xeon, Celeron processors, 1.2 GHz, 55 × 106 transistors.

CPU

972.2 Computer architecture

Page 111: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

The 8088/6 CPU has 14 internal registers. All the registers are 16 bits.Registers are used to hold data temporarily while the CPU performsarithmetic and logical operations.

__ __ __ _ AH _ __ __ __ __ __ __ _ AL _ __ __ ____ __ __ _ BH _ __ __ __ __ __ __ _ BL _ __ __ ____ __ __ _ CH _ __ __ __ __ __ __ _ CL _ __ __ ____ __ __ _ DH _ __ __ __ __ __ __ _ DL _ __ __ __

15 0

AXBXCXDX

Dataregisters

2.2.10 Registers

• AX is the accumulator and is used as a temporary storage space fordata involved in arithmetic and string (character) operations.

• BX is the base register and is often used to hold the offset part of asegmented address during memory transfer operations.

• CX is the count register and is used as a counter for loop operations.• DX is the data register and is a general purpose 16-bit storage

location used in arithmetic and string operations.

The data registers may be divided into two 8-bit registers depending onwhether the CPU is working with 8-bit, or 16-bit data. Within the 16-bit Xregisters, the 8-bit registers are AL, BL, CL and DL, and AH, BH, CH, and DH.Each half of the X registers may be separately addressed using L and H labels.

CSDSSSES

Segmentregisters

__ __ __ __ __ __ __ __ __ __ __ __ __ __ ____ __ __ __ __ __ __ __ __ __ __ __ __ __ ____ __ __ __ __ __ __ __ __ __ __ __ __ __ ____ __ __ __ __ __ __ __ __ __ __ __ __ __ __

15 0

• CS is the code segment and contains the base address of the segment ofmemory that holds the machine language program that is being executed.

• DS is the data segment and contains the base address of the segment ofmemory where current data (such as program variables) are stored.

• SS is the stack segment and contains the base address of the stacksegment which is used to hold return addresses and register contentsduring the execution of subroutines within the main program.

• ES is the extra segment and contains the base address of the extrasegment which is used to supplement the functions of the data segment.

Newnes Interfacing Companion98

Page 112: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

IPSPBPSIDI

Offsetregisters

__ __ __ __ __ __ __ __ __ __ __ __ __ __ ____ __ __ __ __ __ __ __ __ __ __ __ __ __ ____ __ __ __ __ __ __ __ __ __ __ __ __ __ ____ __ __ __ __ __ __ __ __ __ __ __ __ __ ____ __ __ __ __ __ __ __ __ __ __ __ __ __ __

15 0

• IP is the instruction pointer (or program counter) which provides theoffset address into the code segment (CS) for the address of the nextinstruction to be executed in a machine language program.

• SP is the stack pointer and together with the base pointer (BP) providethe offset into the stack segment (SS). This is the current location of thetop of the stack.

• BP, the base pointer, is used in conjunction with the stack pointer toprovide an offset into the stack segment.

• SI and DI are index registers and are used (usually in conjunction with adata register) to provide an offset into the data segment for theprocessing of long string characters.

__ __ __ OF DF IF TF SF ZF __ AF __ PF __ CF

Flags

Carry flag arithmetic carry outParity flag even number of 1sAuxiliary carry flag used for BCD arithmetic operationsZero flag zero result or equal comparisonSign flag negative result or not equal comparisonTrap flag generates single-step operationInterrupt enable fag interrupts enabledDirection flag decrement/increment index registers Overflow flag arithmetic overflow

Flags are individual bits which are used to report the results of variouscomparisons and processes done by the CPU. Program statements maythen branch depending on the status of these flags. Although the flagsthemselves are individual bits, they are arranged together in the form of a16-bit register so that their contents may be easily saved and restoredwhenever necessary (e.g. while a subroutine is being executed).

992.2 Computer architecture

Page 113: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

When the status of flags is reported in diagnostic programs, aspecial notation is used.

Flag Set ResetCF Carry CY NCPF Parity PE POAF Auxiliary AC NAZF Zero ZR NZSF Sign NG PLIF Interrupt EI DIDF Direction DN UPOF Overflow OV NV

After executing aninstruction, flags are eitherset (logic 1) or reset (logic0). Instructions with theCPU’s instruction set usethese flags to jump toanother section of thecurrent program.

The stack is a block of memory used for temporary storage. Saving data tothe stack is called pushing and retrieving the data is called popping. Datapushed onto the stack can be popped off the stack on a last-in, first-out(LIFO) basis. The offset which represents the top of the stack is held in aregister − called a stack pointer. The base address is the contents of thestack segment register. Thus, the segmented address of the top of the stackis given by SS:SP. The stack fills from high memory to low. The bottom ofthe stack is thus: SS:FFFF.

In the example here, the data at offsetaddress 5FFE is the top of the stack.The segment base address for thisoffset is the contents of the stacksegment register.

6000 A85FFF 345FFE FE

Top of stack

When a subroutine is called within a program, the contents of CS and IP arepushed onto the stack. After the subroutine has finished, CS:IP are poppedoff the stack and thus execution of the main program resumes at thestatement following the call to the subroutine. The subroutine itself can alsosave the contents of other registers by pushing them onto the stack and thenpopping them back before handing control back to the main program.When data is pushed or popped from the stack, the stack pointer (SP)decrements or increments either by 2 or 4 depending on whether a word or adouble word is being pushed or popped.

Other instructions exist which allow a program to set or reset some of theflags. The flag register as a whole is usually pushed onto the stack when asubroutine executes and is then popped off the stack when the mainprogram resumes.

Newnes Interfacing Companion100

Page 114: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Conventional memory is called “random access memory” or RAM and isable to be read from or written to. ROM is read only memory and canonly be read from. Data in ROM is burned in during manufacture of thememory chip. In an 8086 based microcomputer, there are a number ofprograms placed in ROM which allow the computer to do certain basicoperations. For example, ROM typically contains:

• Start-up routines.• BIOS (basic input/output services).• BIOS extensions for additional equipment

connected to the computer.

1. Start-up routinesWhen power is applied to themicrocomputer, the first program torun is a power-on-self-test which doesa memory check, initialises all supportchips and the vector interrupt table,and finally loads the operating system.

2. BIOSBIOS standards for BasicInput/Output Services and theseservices are a set of programs whichallow application programs tointerface with input/output devicesconnected to the computer in aconsistent manner. BIOS programsare usually stored in ROM firmware.The operating system calls upon ROMBIOS routines using interrupts. TheROM BIOS relieves the applicationprogram of interfacing directly withmemory locations to managekeyboard entry, video output, serialand parallel communications etc.

In this book, we areparticularly interested inserial port communications.BIOS routines available forthe serial port are:

Service0 initialise serial port

parameters1 transmit character2 receive character3 get serial port status

For example, the serial portparameters (baud rate,parity, stop-bit, data bits)are specified in a bit patternfor a single byte which isplaced in the AL register.When the service is called(using an interrupt), theinitialisation information isread from AL and the BIOSprograms the UART.

2.2.11 ROM

1012.2 Computer architecture

Page 115: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Servicing of I/O devices is usually done using interrupts. When aninterrupt signal is received, the CPU suspends its activities and runs aninterrupt service routine or interrupt handler. After the interruptservice routine has finished executing, normal execution is resumed.

There are three types of interrupts:

1. Microprocessor interruptsThese interrupts are initiated byvarious error conditions (such asa division by zero or arithmeticoverflow). These interrupts arealso known as processorexceptions.

2. Hardware interruptsThese interrupts are physicallywired into the microcomputer.A special NMI interrupt has thehighest priority and cannot bemasked out by other interrupts.It is processed during criticalhardware events such as apower loss.

3. Software interrupts These interrupts are initiated bysoftware to perform variousoperations such as writing to adisk file, reading from the serialport etc. These built-in interrupthandling routines are a part of thecomputer’s BIOS − BasicInput/Output Services.

2.2.12 Interrupts

Interrupts are handled on apriority basis. The interruptnumber determines its priority.High level interrupts cannotthemselves be executed if a lowerlevel or high priority interrupt isbeing processed.

The management of hardwareinterrupts is handled by aprogrammable interruptcontroller chip: the 8259. Thischip can be programmed toimplement a variety of priorityschemes and to accept level oredge-triggered interrupt signals. Itdetermines which interruptrequires servicing and signals theCPU via the INTR line that aninterrupt is pending. When anacknowledgement is received fromthe CPU, the 8259 places theinterrupt number on the data busand the CPU determines theaddress of the appropriate interrupthandler and the required interruptservice routine is then executed.

The 8259 controller can handle eight hardware devices. 8086-basedmicrocomputers have one 8259 controller. 80286+ computers have two, withthe second controller cascaded to interrupt channel 2 of the first givingaccess to 15 hardware devices.

Newnes Interfacing Companion102

Page 116: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

An interrupt vector table contains the address pointer for the interruptservice routines associated with each of the 256 available interrupts. Theinterrupt vector table is usually located in low memory. Interrupt vectors 0to 31 are usually reserved for microprocessor interrupts. The remainder canbe used for hardware or software interrupts.The interrupt type numberdetermines its place within theinterrupt vector table and itspriority (with the exception of theNMI interrupt (2), but has thehighest priority due to its directconnection with the CPU).

Microprocessor interrupts aredivided into fault, trap or abortconditions. For fault conditions,the instruction that caused thefault is retried after the interruptservice routine has beenexecuted. For trap conditions, thenext instruction in the programbeing run by the CPU is executedafter execution of the interruptservice routine. Abort conditionsstop the main program executionentirely necessitating a restart ofthe program.

The IF flag is used to control whether or not hardware interrupts canbe processed. When a hardware interrupt is recognised, the CPU clearsthe IF flag automatically, but this can be reset by the interrupt serviceroutine if additional higher priority hardware interrupts are to be servicedduring processing of the interrupt service routine.

The non-maskable interrupt (NMI) is a special hardware interrupt that isconnected to the NMI pin of the CPU. The NMI is assigned an interrupt numberof 2, although, since it cannot be masked by other interrupts, it effectively hasthe highest priority and is designed to be recognised in the shortest possibletime. Conditions such as a power failure or memory read or write errors typicallytrigger this interrupt.

Vector Interrupt32–255 Available for software and

hardware interrupts17–31 Reserved16 Coprocessor error14–15 Reserved13 General protection fault12 Stack fault10–11 Reserved9 Hardware keyboard8 Hardware timer7 Coprocessor not available6 Invalid opcode5 Print screen4 Overflow3 Breakpoint2 NMI1 Debug/single step0 Divide error

1032.2 Computer architecture

Page 117: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Memory is addressed by reference to segments and offsets. However, as wehave seen, the actual value of the segment may be on any 16-bit boundary.Memory itself is divided into blocks. There are 16 blocks each of size 64 k(65 536 bytes). Block 0 is the first block and starts at address 00000 andextends to 0FFFF. Block 1 starts at 10000 and goes to 1FFFF etc.

Fxxx:xxxxExxx:xxxxDxxx:xxxxCxxx:xxxxBxxx:xxxxAxxx:xxxx9xxx:xxxx8xxx:xxxx7xxx:xxxx6xxx:xxxx5xxx:xxxx4xxx:xxxx3xxx:xxxx2xxx:xxxx1xxx:xxxx0xxx:xxxx

16 × 64k blocks = 1 MB RAM

Blocks 0 to 9 are user blocksand are used to hold start-uproutines, user programs anddata. 10 blocks at 64k eachgives a total of 640k.

Blocks A to F arereserved forspecial purposes: -video memory,input/outputroutines etc.

Most of the 640k is available foruser programs except for a smallsection in low memory starting at00000. This low memory areacontains interrupt vectors which areused to service input/outputdevices connected to thecomputer.

00000

FFFFF

ROM BIOS

BIOSCRT display

interrupt vectors

A good example of amemory-mapped device isthe video display adaptorcard. It contains memorychips (usually 128K isinstalled on the actual card)and is considered a part ofmain memory-mapped intoblocks A and B.

2.2.13 Memory map

Newnes Interfacing Companion104

Page 118: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Multitasking under Windowsrequires programs running on thecomputer to be isolated from eachother and a protected mode ofoperation is thus required. Inprotected mode, a program cannotwrite directly to memory. Instead,any data to be written or read isdone to virtual memory space andtransferred to physical memoryusing a process called virtual-to-physical translation by the CPU.

80286 processors and above can operate in either real or protected mode.When operating in real mode, the CPU can execute the base instruction setof the 8086/8088 processors. In protected mode, the CPU makes use ofadvanced features for memory management and multi-tasking under theWindows operating system. In protected mode, 80386+ processors can act invirtual 8086 mode allowing 8086 instructions to run in a “DOS” window.

2.2.14 Real and protected mode CPU operation

Bit 0 in the control register is theprotection enable (PE) bit which, in realmode, toggles the CPU into protectedmode. At reset, PE is initially 0 and theCPU in real mode. When Windowsstarts, it toggles this bit to 1 to placethe processor into protected mode. Theactivities in this book are designed forreal mode operation of the CPU. Thiscan be simulated in a DOS commandwindow or by starting the computer in“command” mode.

When operating in protected mode, the CPU register structure is differentto that used in real mode. The most important additions are descriptortables which hold information about memory and interrupts for each taskbeing run. Details of each task or application being run on themicroprocessor are held in the task register.

Each task is assigned globaland local memory resources.All tasks can access theglobal address space, but atask cannot access anothertask’s local address space.

Each task is also assigned aprivilege level. The kernel isresponsible for low leveltasks such as memorymanagement, I/O and tasksequencing. The kernel hasthe highest privilege level: 0.

Globaladdressspace

Task A localaddress space

Task B localaddress space

Task C localaddress space

Task C virtualmemory spaceTask A virtual

memory space

Task B virtualmemory space

1052.2 Computer architecture

Page 119: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

The significance of protected mode operation for interfacing is that whenmultiple tasks or applications are being run by the CPU, it appears to the userthat they are operating simultaneously whereas task activity is actually time-shared within the CPU. For time-critical interfacing applications, the usermust be aware of the limitations imposed by this time sharing and hierarchyof privileges. Virtual device drivers (VxD) typically have a kernel level ofprivilege that permits direct I/O and this, together with direct memoryaccess, are required for time-critical interface applications.

Tasks with a lower privilege level can use routines that have a higherprivilege level but cannot modify them. User applications programs areassigned the lowest privilege level: 3.The combination of local addressspace and hierarchy of privilegelevels allows the instructions anddata for all the running tasks to beisolated from each other. Data inone task is thus protected fromerrors arising in another task.Unlike real mode operation, I/O operations from a user application do nothave the required privilege level and so must perform these functions inconjunction with an I/O device driver which does. This ensures that I/O isdone without violating not only the address space of another runningapplication, but also that the I/O does not adversely affect the low leveltask sequencing and memory management responsibilities of the CPU.

When a DOS program is run in a DOSor command window within aWindows environment, the CPU isplaced into virtual 8086 mode bysetting the VM flag in the extendedflag register. The DOS program is stillrun as a protected mode task, and whenthe CPU switches to this task, the VMflag is set as part of the task switchingprocess. The DOS mode program isassigned a privilege level of 3. Thememory addressing scheme of the tasksimulates that of a real mode CPUoperation and can be configured as partof the task properties.

Kernel

Drivers

Extensions

Applications

0 1 2 3

Newnes Interfacing Companion106

Page 120: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

2.2.15 Review questions

2. List the four types of special internal registers that exist in the8086 microprocessor.

3. Explain the difference between a port and an address.4. Draw a diagram which outlines the main components of a

microcomputer system (e.g. the CPU, memory etc). Describe thefunction of each main component and how each communicateswith the others. Indicate also what governs the amount ofmemory addressable by a program.

5. What is the ROM BIOS?6. Which bit in the flags register indicates whether or not a

subtraction operation produced a negative result.

1. Give brief answers to the following questions:

(a) How many memory locations (or memory cells) can beaddressed by a 8086 microprocessor and why?

(b) What is the largest (unsigned) hexadecimal number that can bestored in one memory location and why?

(c) How many memory locations can be read in one read/writecycle and why?

(d) What is a long word and how is it stored in memory?

1072.2 Computer architecture

Page 121: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

3. Start the debug program by typing the command debug at the DOSprompt. The debug prompt is a ‘-’ character and indicates debug isready for a command.

1. Start your computer into DOS mode, or open a DOS command windowfrom your Windows environment.

2. Enter the mem command from the DOS prompt and determine howmuch RAM memory your computer is fitted with and how it has beenallocated. Fill in the table below with the values shown on your screen.

Memory Type Total Used Free---------------- -------- -------- --------Conventional Upper Reserved Extended (XMS)---------------- -------- -------- --------Total memory

Total under 1 MB

Largest executable program sizeLargest free upper memory block

AX= BX= CX= DX= SP= BP= SI= DI=DS= ES= SS= CS= IP=

4. Enter the r command and display the contents of the registers. Fill inthe table with the values indicated on your screen (include the last lineof the debug output in this table).

2.2.16 Activities

5. What is the status of all the flags? Are they set or reset? Is there anyone flag that is set differently to the others? Why would this be?

6. The last line in the register listing displays machine code and assemblylanguage of the instruction pointed to by the CS:IP registers. Comparethe segmented address at the beginning of this line with the indicatedcontents of the CS and IP registers. CS: ________ IP: __________

Newnes Interfacing Companion108

Page 122: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

7. To list the contents of a single register, we enter r XX where XX is theregister name. Debug responds with the current contents of the registerand then allows us to change those contents. Display the contents ofthe AX register and change it to 00FE.

8. To display the flags, we enter r f at the debug prompt. We can thenset any of the flags by entering in the appropriate flag code. Displaythe flags and then change the parity flag to even.

Flag codesFlag Set ResetCF Carry CY NCPF Parity PE POAF Auxiliary AC NAZF Zero ZR NZSF Sign NG PLIF Interrupt EI DIDF Direction DN UPOF Overflow OV NV

AX accumulatorBX baseCX countDX data

CS code segmentDS data segmentSS stack segmentES extra segment

IP instruction pointerSP stack pointerBP base pointerSI source indexDI destination index

9. The “memory dump” command is d. The syntax is: d [address]If the segment base address is not specified, then the address is takento be the offset to the current contents of the DS register. Examine thecontents of the BIOS area of memory which is located at F000:0000.Note that the d command displays 128 bytes starting at the addressyou specify. The d command lists the memory contents in hex andattempts to interpret any ASCII characters and if any are found to bevalid ASCII, the characters are displayed on the right-hand side of thescreen. Continue to display the contents of the BIOS area of memoryuntil you find the copyright message from the manufacturer of yourcomputer. Record the memory location at which the copyrightmessage appears. _______: _______

You can continue to press d without any parameters to display more memorycontents. Some very interesting messages can be found in the BIOS contents.

1092.2 Computer architecture

Page 123: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

10. Debug permits the display, enter, fill, move, compare and search fordata in memory. The “enter” command e, allows us to change thecontents of memory. The syntax is: e [address] [data].Enter the value FF into memory location DS:0000 by typing: eDS:0000 FF. Verify that the contents of DS:0000 have changed byentering e ds:0000 and then pressing <enter> key to terminateenter mode.

11. The “fill” command fills a block of memory with all the same values.The syntax is: f [start address] [end address] [data].Initialise memory locations DS:0000 to 0100 with zeros. Note: the endaddress parameter is specified with an offset only and is assumed to bethe same as that as the starting address. Verify the contents of thesememory locations with the d command.

12. The “move” command allows us to copy a block of memory from oneplace to another in memory. The syntax is:m [start address] [end address] [destination address].Again, the segment base address is either implied (the DS registercontents) or specified within the start address. Move the contents ofDS:0000 to DS:0100 to DS:0200.

13. The “search” command allows us to scan a block of memory andsearch for a specific byte The syntax is:s [start address] [end address] [data].The address for any matches is displayed. Search memory locationsF000:0000 to F000:FFFF for the characters “read failure”.

Character data may be entered in a debug command if it is delimitedby quote marks. When debug processes the command, the ASCIIvalue of the characters is substituted.

Display the contents of nearby memory locations with the d command.

14. In addition to loading and running machine language programs (whichwe will investigate in the next laboratory session), debug also is ahandy hexadecimal calculator. The h command allows us to add andsubtract hex numbers. Both operations are performed by the samecommand.The syntax is: h [hex number 1] [hex number 2] and the sum anddifference of the two numbers is displayed (in hex).(a) Calculate the sum of the hex numbers 00FF and AB10.(b) Determine the negative of the number A3 (this will be displayed

in 2’s complement notation).

Newnes Interfacing Companion110

Page 124: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

111

Page 125: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

A microprocessor can only act upon instructions which are specified in itsinstruction set. The instruction set consists of a series of hexadecimalcodes, or opcodes, which are recognisable to the instruction decoder withinthe CPU. Each series of microprocessor has a unique instruction set,although many instructions are so common that they are found with onlyminor modifications in all microprocessors. In the 8086 CPU, instructionsare 1 to 6 bytes long.Some common classes of operations for which instructions are usuallyprovided are:

• Data movement• Integer and floating-point arithmetic• Logical operations• Shift and rotation of bits• Bit manipulation• Program control (branching)

2.3.1 Instruction set

A sequence of opcodes arranged to perform a particular task is called amachine language program or just machine code. To execute a machinelanguage program, the machine code needs to be stored into the codesegment of memory. The first byte of the program is stored at the lowestaddress and subsequent bytes stored at higher memory addresses insequence.Machine code instructions can be from 1 to 6 bytes in length. As anexample, the following 3 bytes of code move the literal number 2000H intothe AX register:

The most significant 6 bitsof the first byte specify the“opcode” of the instruction.The next bit specifieswhether the registeroperand (specified in thesecond byte of theinstruction) is the source orthe destination, and thethird bit specifies whetherthe operation will be on abyte or a word.

The second bytecontains informationabout the operandsfor the instruction.They are the mode,register andregister/memoryfields of theinstruction.

Other bytes containinformation aboutvarious addressingmodes which requiredata and/or addressdata to be used asdisplacements tocalculate a final“effective address” forthe instruction.

B8 00 20

0100 1000 0000 0000 0010 0000

Newnes Interfacing Companion112

Page 126: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

The instruction decoder within the CPU can only interpret machine codeinstructions which are defined in the instruction set. Machine codeprogramming is extremely laborious and for this reason programs areusually written using assembly language. An assembly language programis converted into machine code by an assembler program.

Assembly language instructions

Assembler

Object module

Linker

Run module

Machine code with all addressesspecified relative to a baseaddress. The object module isthus relocatable. For largeprograms, several such objectmodules may be created.

Separate object modules arecombined into a single run modulein which cross-references betweenmodules are resolved.

Source code in ASCII text. Symboliclabels are used in jumps so thatabsolute addresses need not becalculated by the programmer.

2.3.2 Assembly language

1F6D:0100 B81F6D:0101 001F6D:0102 201F6D:0103 8E1F6D:0104 D81F6D:0105 BF1F6D:0106 001F6D:0107 001F6D:0108 B91F6D:0109 FF1F6D:010A 001F6D:010B BA1F6D:010C 001F6D:010D 001F6D:010E 891F6D:010F 151F6D:0110 471F6D:0111 491F6D:0112 751F6D:0103 F71F6D:0114 90

Memorylocation

Machinelanguage

The run module created by the linker isrelocatable. The base address to which allother addresses are referenced is suppliedby the operating system when it is loadedand run. The linker creates an executablefile (with an .exe extension). In somecircumstances, a smaller .com file may bemade using a relocating loader. The loaderprovides the base address and thenresolves all relative addresses into absoluteaddresses. The resulting program file isalso executable but is given a .comextension. Com files are smaller andexecute faster than exe files since theoverhead in resolving addresses has beeneliminated.

1132.3 Assembly language

Page 127: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

The microprocessor can only interpret machine code instructions specifiedin its instruction set. While running a machine language program, theprogram counter or instruction pointer register holds the offset of theaddress of the next instruction to be executed. The segment base address isheld in the code segment (CS) register. The initial value of CS and IP isdetermined by the operating system when the program is run by the user.The following sequence then occurs.

1. CPU fetches the instruction atthe address given by theprogram counter (PC register)(and address +1 for instructionswhich are 2 bytes long) and theinstruction pointer register isincremented before theinstruction is executed.

2. The instruction is decoded bythe instruction decoder whichdecides what action to take next.

3. Operand data is fetched frommemory as required.

4. The instruction is executed.Typically, the arithmetic logicunit (ALU) performs thenecessary anding and oring etc.The result from the instructiongoes into a register or back toRAM memory (which wouldinvolve a write cycle). Theflags in the status register arealso set.

The fetch operation consistsof the address being put ontothe address bus; a read cycleis requested on the controlbus. The hex data at locationsaddress (and address+1 for 2byte instructions) is broughtover to the CPU on the databus to the instruction decoder.

Some instructions require furtherdata to be read from memory (theoperands) while others are stand-alone instructions may be actedupon immediately. The instructiondecoder determines the set ofcontrol signals required for thatinstruction.

The address of the nextinstruction to be executed is inthe IP register (from step 1) andthe program cycle starts again. Ifthe program contains somebranching instructions, then theaddress to which to branch to isplaced in the IP during theexecute step ready for the nextfetch cycle.

FETCH–EXECUTE cycle

2.3.3 Program execution

Newnes Interfacing Companion114

Page 128: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

An assembly language program contains statements which may be eitherassembly language instructions (from the instruction set) or assemblerdirectives (which are instructions for the assembler program to followwhen the program is assembled into machine language).

CODESEG SEGMENT ASSUME CS:CODESEG PUSH BP PUSH DS MOV BP,SP MOV DS,ES:[SI] . More instructions…. . POP DS POP BP RET 08HCODESEG ENDS

Assembly language programs use the code segment of memory to holdinstructions, the data and extra segment for data, and the stack segmentfor stack data. To facilitate programming, an assembly language programis also divided into segments.

The assembler directiveSEGMENT and ENDS define thebeginning and end of a programsegment. For example, the datasegment of a program wouldlook like:

DATASEG SEGMENT … Data definition directivesDATASEG ENDS

Following the data segment,the code segment whichcontains the actual CPUinstructions.

Note that eachsegment of aprogram beginswith a directiveSEGMENT andends with adirective ENDS.

In these examples, DATASEG andCODESEG are names that we give to eachsegment.

These program statements arewritten in a text editor and savedas a source file. An assemblylanguage program finishes withthe END directive which tells theassembler to stop assemblingwhen it reaches this line in the file.

2.3.4 Assembly language program structure

Label: <tab> mnemonic <tab> operands <tab>;Comment

Commentsmay be addedat the end ofeach line(preceded by atab and “;”).

Assembly languagemnemonic. Themanufacturer issuestables or books whichlist all availablemnemonics (theinstruction set) andtheir function.

Labels areoptional andare usefulwhen loopingback to repeata section of aprogram.

Operands or parametersor data which will beacted upon by theassembly languageinstruction. For 8088instructions requiring twooperands, the first is thedestination and thesecond is the source.

SYNTAX

1152.3 Assembly language

Page 129: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Name <tab> directive <tab> operands <tab>;Comment

There are various groups of assembler directives:1. Symbol definition directives allow names to be assigned to constants,

addresses, operands etc. There are two definition directives:

2. Data definition directives define memory space for variables.

3. External reference directives

4. Segment and procedure directives divide the program into segmentsand/or subroutines. The directives SEGMENT and ENDS mark thebeginning and end of a program segment.

name EQU expressionname = numeric expression

name DB expressionname DW expressionname DD expression

Allocates 1 byte

Allocates 2 bytes (word)

Allocates 4 bytes (long word)

PUBLIC expressionEXTRN name:typeINCLUDE file name

Allows variables and routines whichexist in other programs to be used inthe current program.

Segment_name SEGMENT PARA PUBLIC “class”

The namegiven to thesegment.

Specifies thatthe segment isaligned on a16-byteaddressboundary.

Specifies that allsegments with thesame name are to becombined into one.

Specifies the class ofsegment. Class can beeither one of the four typesof program segments: data,code, stack, or extra.

2.3.5 Assembler directives

Newnes Interfacing Companion116

Page 130: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

ASSUME DS:name, CS:name, ES:name, SS:name

PROC and ENDP define a portion of code which is used as a subroutine.The last instruction (before ENDP) must be RET. A procedure may beNEAR or FAR. NEAR procedures are defined and called within a singlecode segment (the CPU needs only to push the return address IP onto thestack while the subroutine executes). For a FAR procedure, both CS and IPare pushed onto the stack.

The program segments can be written in the source file in any order. Thecode segment is perhaps the most important since it contains the actualassembly language statements that are to be executed. An ASSUMEdirective is usually included in the code segment and is used to assign thesegment registers to the base addresses of the program segments.

CODESEG SEGMENT 'CODE' ASSUME CS:CODESEG,DS:DATASEG CODESEG ENDSEND

Example:

CODESEG SEGMENT “CODE”ASSUME CS:CODESEG,DS:DATASEGPUBLIC PROCNAME

For procedures that are called from other modules, its name must bedeclared “public” using the PUBLIC assembler directive.

PROCNAME PROC FAR....RET 08HPROCNAME ENDP

In this example, “CODESEG” is the name given to the code segment. TheASSUME statement specifies that the CS register holds the segment baseaddress for the “CODESEG” segment. The “CODE” class in the SEGMENTstatement also identifies the “CODESEG” segment as a code segment.

2.3.6 Code segment

1172.3 Assembly language

Page 131: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

CODE SEGMENT “CODE” ASSUME CS:CODEMYPROG PROC FAR

PUSH DS PUSH AX

... More statements.RET

MYPROG ENDPCODE ENDS END

Here is a useful summary of the statements required to produce a simpleassembly language program which when assembled and linked, can be runfrom the DOS prompt.

The name of the program is “MYPROG”. The statements required toproduce a workable assembly language program depend on the operatingsystem and the method by which the program is to be run. If the assemblylanguage program is to be called as a subroutine inside a higher levelprogram, then the handling of parameters and restoration of the stack isdifferent to the case where the program is to be compiled into a stand-aloneexecutable (EXE) file.The example shown here is suitable for a stand-alone program. Theprogram is assembled into an OBJ file which is then linked to form anEXE file which can then be executed from the DOS prompt.Particular care has to be taken with the RET instruction. RET without anyparameters appears sometimes to POP 4 bytes off the stack which is why inthis example, we have pushed DS and AX onto the stack at the start of theprogram. If you do not include these statements (PUSH DS, PUSH AX)your program will hang up and not return to the DOS prompt whenfinished.The END statement is also important if there is more than one procedure inthe program file. If there is more than one PROC and ENDP bracket, thenEND must be followed by a label which indicates which procedure is to runwhen then program is started.

This program shell is avery simple application ofassembly languagewhich is suitable for avery short programs notrequiring the passing ofcommand lineparameters. It is suitablefor the assemblylanguage interface to theserial data acquisitionsystem to be describedlater in this book.

2.3.7 Assembly language shell program

Newnes Interfacing Companion118

Page 132: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

2.3.8 Branching

Unless otherwise instructed, the CPU will advance from one instruction tothe next in sequence. This linear sequence of execution can be varied bybranching. There are two types of branching.

Unconditional jump straight to the instruction located at the specifiedaddress. The syntax is: JMP label

Branching involves an adjustment to the contents of the instruction pointer(IP). To branch to a label, the CPU obtains a number whose value dependson where label is located in the program relative to the current IP address.This number (which may be positive or negative) is added to the contentsof the IP to give the offset of label. This offset is then placed into IP andexecution proceeds from CS:IP. If the jump or branch is to a place withinthe same segment, then it is a NEAR jump. A branch to a different segmentis a FAR jump.

Bit positions in the flag registerindicate the results of theinstructions as they are executed.Many instructions cause the flagsto be set. Some instructions donot set any flags at all. Programcontrol statements test the flagsand allow branching to otherparts of a program outside themain sequence of instructions.

The symbol cc is a condition code. If cc istrue, then the program branches to theinstruction prefixed label. If false, thenprogram execution continues with the nextinstruction following Jcc.

Jcc flags tested jo overflow flag is set OF=1jno overflow flag clear OF=0jz equals zero ZF=1jnz not equals zero ZF=0jnc carry flag clear CF=0jc carry flag set CF=1js sign flag set SF=1jns no sign SF=0

The bit positions, or flags, in theflag register are tested andprogram execution is variedaccording to the branch instruction.The condition codes are set by the preceding instruction to the branch.Most assembly language statements set the condition codes as part of theexecution procedure within the CPU. Precisely which codes are affected bythe execution of a statement depends on the command. The Jcc instructiondoes not set the flags in the condition code register, it only tests those flags.Thus, one may use several Jcc instructions in sequence, each testing theresult of a single previously executed instruction.

Conditional jump to an instruction at an address, the value of whichdepends upon the result of a test. Jcc label

1192.3 Assembly language

Page 133: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

In register addressing, an operand isfetched from, or written to, a register.For example:

MOV AX,DX

In this example, the 16-bit contents ofDX are copied into AX. The contents ofDX are not changed.

In immediate addressing, the actualnumber specified in the programstatement is used as the sourceoperand. For example:

MOV CX,7FH

In this example, the hex number 7FH ismoved into register CX. However, CX is16 bits wide, and 7F is an 8-bit number:0111 1111. Since this number is positive(it has a zero as the msb), the mostsignificant 8 bits of CX are filled withzeros.

CX: 0000 0000 0111 1111For a negative number, e.g. A3, themsb of CX is filled with 1s.

CX: 1111 1111 1010 0011

Many assembly language instructions require data to be read or written tomemory locations and/or registers. The term addressing is used todescribe the method by which operands for the source and destinationinstructions are specified.Register and immediate addressing means that the operand is either aregister or specified as a constant within the assembly languageinstruction itself.

2.3.9 Register and immediate addressing

This is one of the most common instructions in an assembly language program.The general syntax of the instruction is:MOV destination, source

Data is actually copied, not moved, from the source to the destination. The data inthe source is not changed. There are some restrictions on MOV:

• Data cannot be moved from one memory location to another by a single MOVcommand.

• An immediate value cannot be moved into a segment register.• Data from one segment register cannot be moved into another segment register.• The CS register cannot be specified as the destination for a MOV instruction.

Some of these restrictions can be avoided by transferring data into a data register(e.g. AX) and then to the desired destination.

Newnes Interfacing Companion120

The MOV instruction

Page 134: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

If an operand is stored in memory, then the CPU must calculate the actualphysical address from which to read or write the data. The physical addressis formed from a segment base address and an offset. The offset is referredto as an effective address. The segment base address can be the contentsof any of the segment registers. The effective address can be formulated ina variety of ways. In general, the effective address is formed from:

EA = base + index + displacement

The actual physical address is thus:

CSSSDSES

:BXBP +

SIDI +

8 bit displacement16 bit displacement

Segmentbaseaddress

Offset (effective address)

Various combinations of the elements may be used to form aneffective address. Not all the elements are required.

2.3.10 Memory addressing

In direct memory addressing, information about the address is givenin the instruction directly. An example is:

MOV AX,[0A40H]This example says to move the contents of memory location with offset0A40 into the AX register. There are several points about this example thatrequire attention. First, there is no segment base address specified in theoperand. If this is the case, then the contents of DS are assumed to be thedesired segment base address. Second, AX is 16 bits wide, and so a wordis moved from the offset and offset+1 with the msb of the AX registerreceiving the data at offset+1.

DS:[direct address]The general format for direct memory addressing is:

Size codesThere are no explicit size codes used in 8086 assembly language instructions. Thesize code is taken from the size of the operands. For example, in the MOVinstruction, moving data into or out from a segment register is always a word (2-byte) operation. Moving data into or out from AL would be a byte operation since ALis 8 bits wide.

1212.3 Assembly language

Page 135: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Segment base addressIn these examples, the default segment base address for offsets (or effectiveaddresses) is the value in the DS register. However, this can be overridden byspecifying a segment register explicitly. For example:

MOV AX,ES:[0A40H]

2.3.11 Indirect memory addressing

In this example, the brackets indicate indirect addressing and BX containsa 16 bit number which is used as a relative offset with DS to obtain theabsolute address (and address+1) which contains the 16-bit data to bemoved into CX. Note that the term “relative offset” here means that theoffset is considered to be relative to the contents of the DS register.

MOV CX,[BX]

As with direct addressing, in indirect addressing, the effective address(i.e. offset) is combined with the contents of DS to form an actualphysical address. The effective address is determined from the contentsof either a base or index register.

DS : [ ]BXBPSIDI

The general format is:

Based addressing is particularly useful for accessing data in tables orlists. It involves a displacement which is added to the contents of the BXor BP register to form an effective address.

MOV [BX] + 0A10H,AL In this example, the offset for the destinationoperand is found by adding the number 0A10H tothe contents of BX. This is then used with thecontents of DS as the base segment address toform the physical address from which to obtain theoperand data.

DSSS

BXBP

The general format is:

+ 8-bit displacement16-bit displacement

If BP is used, then the default register for the segment base address is SSrather than DS.

:[ ]

Newnes Interfacing Companion122

Page 136: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

There are several forms of indexed addressing, all of which use adisplacement as a pointer to the start of an array of data in memory, andan index register as an index to select a specified element in that array.

MOV AL,[SI]+1010HThe example here shows a direct indexing mode. The displacement1010H is added to the contents of the stack index register to form aneffective address. The default segment base address is given by thecontents of the DS register. The advantage of this type of addressing is thatthe stack index can be incremented or decremented to find the next orprevious element in an array of data that begins at DS:1010H.

A combination of based addressing and direct indexed addressing resultsin a based index addressing mode. This is useful for accessing two-dimensional (m × n) arrays. The displacement locates the array in memory.The base register specified the m coordinate, and the index registerspecifies the “n” coordinate of the element.

MOV AL,[BX] [SI]+1010H

The effective address is found from the contents of BX added to thecontents of SI and then added to the value of the direct displacement1010H. The default segment base address is DS.

SIDI + 8-bit displacement

16-bit displacementDS :[ ]

BXBP + 8-bit displacement

16-bit displacementDS :[ ][ ]BX

BP

2.3.12 Indexed memory addressing

1232.3 Assembly language

Page 137: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

2.3.14 Interrupts

Software interrupts are used routinely in assembly language programsto call upon BIOS services to perform basic I/O tasks. Within the CPUprocessing operation, software interrupts are initiated using the INTstatement.

MOV AH,2CH ; SPECIFY DOS SERVICE NUMBER 2CINT 21H ; CALL INTERRUPT TO EXECUTE SERVICE

INT interrupt number

When an interrupt instruction is processed, the following sequence occurs:1. The flags register is pushed onto the stack2. Interrupts are disabled to prevent the interrupt routine being

interrupted by a lower priority interrupt.3. Contents of the CS and IP registers are pushed onto the stack4. The address pointer for the interrupt service routine is retrieved

from the interrupt vector table and loaded into CS and IP registers.5. The CPU begins executing instructions located at address CS:IP

The following example shows how to read the system clockto obtain the current date and time.

Software interrupts are numbered 32 and beyond and are generallyassigned a higher priority than external hardware interrupts. Mostsoftware interrupts are assigned by the operating system BIOS.

BIOS interruptsSoftware interrupts generally offer a service. The service is called by a servicecode placed in the AH register. Some common software interrupts are:

Interrupt Function05h Print screen 10h Video service11h Equipment list service12h Memory size service13h Disk drive service 14h Serial communications service15h System services support16h Keyboard support service17h Parallel printer support services 18h ROM BASIC 19h DOS bootstrap routine 1Ah Real time clock service routines

Newnes Interfacing Companion124

Page 138: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1. What is the relationship between machine language op-codes,mnemonics and the assembler. Also state why you cannot have anassembler that will produce an executable program which will run onmore than one type of computer.

2. What is the sequence of events inside the CPU during the execution ofa machine language program statement?

3. Determine the physical address given by the following segment:offset4000H:2H.

4. What is the general syntax of an 8086 assembly language statement?5. Write a short assembly language program that will arrange two 8-bit

numbers in ascending order.6. The AX register contains the value 1100H and BX contains 2B01H.

Write down the contents of the AX register after each of the followingassembly language statements executes:

7. The following program fragment places a character on the screen. Ifthe hex number A6 is placed in AL, explain what appears on thescreen. How would you have an assembly language program displaythe actual hex number in AL on the screen?

AND AX,BXOR AX,BXXOR AX,BX

MOV AH,9HINT 10H

2.3.15 Review questions

1252.3 Assembly language

Page 139: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

The debug program can be used to create a machine language programfrom our assembly language input. The command is the assemble or acommand.1. Start the debug program and enter the a command together with a

starting address as shown: a CS:0100Debug responds with the starting address for our program as CS:0100and an input prompt _. Enter the short assembly language programshown here and press the enter key at the last _ prompt to terminate theassemble command.

Assembly language program2. Verify the contents of the

assembly language programusing the unassemble ucommand: u CS:0100

3. The program is now ready to beexecuted. The go commandexecutes the entire program, whilethe trace command executes aspecified number of lines and thenstop, whereupon the contents ofregisters and memory locations canbe examined before proceeding.Enter the trace t command:

t =CS:0100 Examine the contents of theregisters after each statement. Presst to continue execution until thelast instruction is processed – donot press t after the NOP step.

This program fills memory locations2000:0000 to 2000:00FF with zeros.

1F6D:0100 MOV AX,20001F6D:0103 MOV DS,AX1F6D:0105 MOV DI,00001F6D:0108 MOV CX,00FF1F6D:010B MOV DX,00001F6D:010E MOV [DI],DX1F6D:0110 INC DI1F6D:0111 DEC CX1F6D:0112 JNZ 010B1F6D:0114 NOP

You enter thesecommands.

Debugresponds with

address

2.3.16 Activities

(a) Examine the contents of memory locations 2000:0000 to 2000:00FF andcheck their contents.

(b) Examine the contents of the AX, DX, DI, CX registers and explain theirvalues.

(c) Unassemble the program and determine the machine language code forthe first move statement.

(d) In the program, the JNZ statement was followed by a hex number 010B.What is the significance of this number?

Questions:

Newnes Interfacing Companion126

Page 140: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

4. The trace command is useful for executing the program one line at atime. The go command executes the program without pausing.However, we must be careful only to execute the instructions that wehave entered into the memory locations CS:0100 to CS:0114. The gocommand allows us to execute a block of statements by specifying thememory location at which to stop processing. Change the programslightly by editing memory location 010B to:

g =CS:0100 0114

MOV DX,00FFBy using the a command to reassemble this line:

a CS:010BRun the program using the go command:

Examine the contents of 2000:0000 to 2000:00FF and comment.

5. It is customary to use a text editor to write large assembly languageprograms. The program is saved to a disk file and then translated intomachine code using an assembler. Using a text editor, create a text filecontaining the assemblylanguage statements asshown.

CODESEG SEGMENT ‘CODE” ASSUME CS:CODESEGZERO PROC FAR PUSH DS MOV AX,0H PUSH AX MOV AX,2000H MOV DS,AX MOV DI,0H MOV CX,00FFHSTART: MOV DX,0H MOV [DI],DX INC DI DEC CX JNZ START RETZERO ENDPCODESEG ENDS END

Note: “Zero” is a namewe assign to theprocedure. We onlyneed this name if welink this program with aseries of others. Otherprocedures can thencall this program by itsprocedure name.

6. Save the file to disk with an .asm file name extension. For example:LAB2.ASM

1272.3 Assembly language

Page 141: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

7. Start the Microsoft Macro Assembler by typing in masm at the DOSprompt. The assembler responds with prompts for the source file,object file, source listing file, and cross-reference listing file. Thedefault names for the object file and the cross-reference file can beselected by just pressing the enter key at the prompt. For this exercise,do not accept the default NUL.LST (which produces no list file) butenter the name: LAB2.LST.

8. If there are any syntax errors in the source file, they will be reported bythe assembler. If there are no errors, then proceed. Edit the source listingfile created by the assembler and note its contents. The source listingshows both the source and corresponding machine code instructions.

9. The object file created by the assembler contains machine code but thiscode is not yet in executable form. A separate program called a“linker” is used to create the final executable program file. Start thelinker program by typing in link at the DOS prompt. The linker asks forthe object file names (of which there is just the one in our presentexercise) and the name of the final run file, a linker map file, and anylibrary files. Enter the name of the object file (e.g. LAB2.OBJ) and alsospecify a map file with the same file name but with a MAP extension.No library files are required so simply press enter at the LIB and DEFprompts. (Ignore the linker warning about there being no stacksegment.)

10. The linker creates two files, an executable program file with an EXEextension, and a map file which contains the start address, stop addressand program length for each program segment used by the program.Examine the contents of the MAP file using a text editor and note thestop address of the program.

11. The EXE file used by the linker is in executable form and can beexecuted directly from the DOS prompt. However, we shall run theprogram from within the DEBUG environment in this exercise.Assuming that the executable file is called LAB2.EXE, start the debugprogram with this file name as a command line parameter:

debug lab2.exe

Note the status of the registers (use the r command).

Newnes Interfacing Companion128

Page 142: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

12. Verification that the program has been loaded correctly can be done byusing the unassemble command. The starting address is given byCS:0000. Unassemble commands from this starting address to the stopaddress given by the MAP file (see Step 10).u CS:0000 stop address

Compare with the source listing (LAB2.ASM).

13. Now run the program using the go command. Use the memory dumpcommand d to verify that the program has performed its intendedpurpose.

g =CS:0000What message does debug display after executing the program?

Questions:(a) Examine the LST file created by the assembler and compare the

machine language output with that produced by the unassemblecommand of debug (see Step 2).

(b) When running this assembled and linked program from within debugusing the go command, we did not need to specify a stop addressas we did in Step 4. Why?

(c) In the source file (.ASM) we used a label as the target for the JNZcommand. Examine the unassembled program (from Step 12) andverify that the assembler calculated the correct offset for this jump.

14. Write an assembly language program that will swap the contents oflocations 2000:0000 and 2000:00FF.

15. Write an assembly language program to perform an 8-bit subtraction.The contents of 2000:0000 are to be taken away from the contents of2000:0001 and the answer stored in 2000:0002. Compare your answerto a pen and paper check using 2’s complement notation. Make sureyou include an example that gives a negative result.

1292.3 Assembly language

Page 143: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

17. Write an assembly language program which will inspect the contents ofthe AX register and either increment, decrement, or leave unchangedthe data located at address 2000:0000 depending on whether the data inAX is positive, negative or zero (in 2’s complement notation).

18. Write an assembly language program which will fill the locations2000:0000 to 2000:FFFF with zeros. (You can use a branch statementto loop back until some condition is met – for example, load the number0000 into a data register and increment that number each time you fill amemory location until the number equals FFFF. Try using the J[cc]commands to set this up).

19. Write an assembly language program that will swap the contents oflocation 2000:0400 to 2000:04FF with the contents of 2000:0500 to2000:05FF.

20. Write an assembly language program to scan the memory locations2000:0000 to 2000:FFFF to see if one of them contains a byte equal toa byte stored in the AL register. Put the address of that location in theBX address register.

21. Write an assembly language program that will return the contents of amemory location whose segment base address is specified in DS andoffset in SI. The contents are to be loaded into the lower half of AX.

22. Write an assembly language program that will return call DOSservice 21C via interrupt 21H. Examine the contents of CH, CL, DHand DL and determine what information is being returned by thisservice. (The DOS service number is to be placed into AH beforeinterrupt is called.)

16. Write an assembly language program which will add the two 16-bitnumbers below and store the result in locations 2000:0000, 2000:0001and 2000:0002 (you’ll need a third memory location since the additionof the two numbers shown below will overflow 16-bit positions).

1 0 1 1 1 0 1 1 1 0 1 0 1 0 1 01 1 0 1 1 1 0 1 1 1 0 0 1 1 0 0

Newnes Interfacing Companion130

Page 144: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

131

Page 145: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

The term interfacing is used to describe the connection between atransducer or some other external device and the microcomputer.Interfacing circuits may be required to deal with various levels ofincompatibility:

Mechanical or electronic devices requiringconnection to the microprocessor unit can beanything from the output screen or monitor,the keyboard, and external instruments. Twomain problems are usually encountered wheninterfacing such devices:

2.4.1 Interfacing

A port is a connection from the outsideworld to the microprocessor. The purposeof an input port is to transfer informationfrom the outside world to themicroprocessor. An output port providesinformation to the outside world from themicroprocessor. Each port has an addressand is thus connected to the address busand information to or from the port istransmitted over the data bus. From themicroprocessor’s point of view, a port isvery similar to a location in memory.

Ports may be memory mapped, interfacing direct to the computer’s RAM,or be assigned a separate port address. An interface adaptor connects thedata bus to the I/O device using compatible signals when the port isaccessed by the CPU for read/write operations.

• incompatible voltage levels• changing current levels• electrical isolation• timing of data transfers• digital to analog and analog to digital conversions

• Most devices do not operate at the samespeed as the microprocessor.

• There may be more than one devicewhich requires servicing at any one time.

Typical I/O ports on amicrocomputer

Newnes Interfacing Companion132

Page 146: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

In an 8086-based microcomputer, I/O ports are identified using a 16-bitport number or port address. Thus, there are a total of 65 536 possibleports numbered 0 to 65 535 (FFFF). The CPU uses a signal on the controlbus to specify that the information on the address bus and data bus refers toa port and not a regular memory location. The port with the specifiednumber then receives or transmits the data from its own internal memory.

2.4.2 Input/Output ports

Port number I/O device0000 – 001F Direct memory access controller0020 – 003F Programmable interrupt controller0040 – 005F System timer0060 – 0060 Standard 101/102-key keyboard0061 – 0061 System speaker0062 – 0063 System board extension for ACPI BIOS0064 – 0064 Standard 101/102-key keyboard0065 – 006F System board extension for ACPI BIOS0070 – 007F System CMOS/real time clock0080 – 009F Direct memory access controller00A0 – 00BF Programmable interrupt controller00C0 – 00DF Direct memory access controller00E0 – 00EF System board extension for ACPI BIOS00F0 – 00FF Numeric data processor0170 – 0177 Intel(R) 82801BA Ultra ATA storage controller – 244B0170 – 0177 Secondary IDE controller (dual fifo)01F0 – 01F7 Intel(R) 82801BA Ultra ATA storage controller – 244B01F0 – 01F7 Primary IDE controller (dual fifo)02F8 – 02FF Communications port (COM2)0376 – 0376 Intel(R) 82801BA Ultra ATA storage controller – 244B0376 – 0376 Secondary IDE controller (dual fifo)0378 – 037F ECP printer port (LPT1)03B0 – 03BB Intel(r) 82815 graphics controller03C0 – 03DF Intel(r) 82815 graphics controller03F0 – 03F5 Standard floppy disk controller03F6 – 03F6 Intel(R) 82801BA Ultra ATA storage controller – 244B03F6 – 03F6 Primary IDE controller (dual fifo)03F7 – 03F7 Standard floppy disk controller03F8 – 03FF Communications port (COM1)04D0 – 04D1 Programmable interrupt controller

Input ports generally require servicing (i.e. their data to be read) atirregular intervals and further, their signals may only appearmomentarily. Techniques such as polling, interrupts and directmemory access are used to service ports as required.

1332.4 Interfacing

Page 147: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

2.4.3 Polling

The easiest method of determining when a device requires servicing is toask it. This is called polling. In this method, the CPU continually andsequentially interrogates each device. If a device requires servicing, thenthe request (or bus access) is granted. If the device does not requireservicing, then CPU interrogates the next device.

Polling is very CPU intensivesince the processor must spend alarge amount of time interrogatingdevices which do not requireservicing. However, the proceduremay be easily implemented insoftware making it flexible andconvenient. In some circumstances,polling may be actually faster thanmore direct methods of interfacing(interrupts and DMA).

Interfacing in a multitasking environmentInterfacing in a multitasking operating system like Windows brings with itmany issues that may require special attention. The three main methods ofobtaining data from an interfaced device (polling, interrupts, and DMA)cannot be guaranteed to occur at a particular time. This causes problems fortime-critical applications in which the time at which the data is recorded isimportant, and also for applications requiring large amounts of data to berapidly collected.

Steps can be taken to minimise the problems. I/O devices such as generalpurpose data acquisition cards make use of virtual device drivers employingcommands with low level privileges, hardware buffering, and bus-masteringDMA can be used with some effect but cannot remove the limitations of theoverall system placed on it by the multitasking environment.In some applications, where the cost and effort is appropriate, interfacing canbe done at the transducer and the data buffered and transferred to themicrocomputer at a time convenient to the microprocessor. In these systems,the transducer contains a microprocessor of its own and is programmed usingan erasable programmable read only memory (EPROM). Commands can besent to the on-board microprocessor to run different internal programs using anordinary serial communications protocol.

Intelligent transducers contain all the power to obtain the necessary data fromthe sensor under a variety of conditions, report error conditions and self-calibrate under the control of a supervisory computer via an internet, radio ordirect cable connection.

Is there anyone there?

Is there anyone there?

Is there anyone there?

Newnes Interfacing Companion134

Page 148: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

2.4.4 Interrupts

0 System timer1 Standard 101/102-keyboard2 Programmable interrupt controller3 Communications port (COM2)4 Communications port (COM1)5 (free)6 Standard floppy disk controller7 ECP printer port (LPT1)

Typical IRQ allocations

Hardware interrupts are controlled bythe 8259 programmable interruptcontroller. I/O devices managed byhardware interrupts are printers, keyboard,and disk drives. The IRQ allocation is ahardware device interrupt numbersimply used to conveniently label thedevices making use of the 8259 controller.The lower the IRQ, the higher the priority.

PCI-based systems are able to share IRQ assignments. When a shared interrupt isactivated, the operating system calls each of the assigned interrupt service routinesuntil one of the routines (configured by the device driver of the hardware) claims theinterrupt by conducting its own tests. For example, often registers are availablewithin each device that can identify whether the device has signalled an interrupt

8 System CMOS/real time clock9 Intel(r) 82815 graphics controller9 ACPI IRQ holder for PCI IRQ steering9 SCI IRQ used by ACPI bus10 SoundMAX integrated digital audio10 Intel(R) 82801BA/BAM SM bus controller – 244310 ACPI IRQ holder for PCI IRQ steering11 Intel(R) 82801BA/BAM USB universal host controller – 244411 3Com 3C920 integrated fast ethernet controller11 ACPI IRQ holder for PCI IRQ steering12 PS/2 compatible mouse port13 Numeric data processor14 Primary IDE controller (dual fifo)14 Intel(R) 82801BA Ultra ATA storage controller – 244B15 Intel(R) 82801BA Ultra ATA storage controller – 244B

Additional interrupts from2nd 8259 controller

For interfacing applications, the time taken to register and process aninterrupt (interrupt latency) can lead to the need for the I/O device tobe heavily buffered. In addition, time critical interfacing applicationsmay not work as desired.

Come in! KnockKnock

1352.4 Interfacing

Page 149: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

2.4.5 Direct memory access (DMA)

In normal data transfer, data is transferred from one memory location toanother through registers in the CPU. The CPU has to hold the datatemporarily while it switches the control bus signal from a read to a writesince the data bus cannot be in a read state and a write state at the sametime. This temporary storage of data and resulting transfers into and out ofthe CPU is time consuming and wasteful for interfacing applications thatrequire rapid accumulation of data and precise timing.

In direct memory access or DMA, data canbe transferred directly between memory andthe I/O port since I/O memory locations areindependent of RAM memory. DMArequires full control of the address, data andcontrol buses. When a DMA transfer is tooccur, a DMA controller 8237 IC requestscontrol of the bus from the CPU. The CPUpromptly grants control and suspends anybus-related activity of its own. The DMAcontroller then transfers data from port to memory, or memory to portdirectly, without any stack or register overhead operations that wouldnormally be required by the CPU to accomplish the same task. The DMAacts as a third party to the data transfer. The latency time associatedwith DMA transfer is only a few CPU cycles.

With a PCI bus, DMA management can be performed not only with theDMA controller, but also by the device requiring DMA access. In suchsystems, the device that gains control of the bus is called the bus master.For interfacing applications, the combination of bus-mastering DMA anda high speed PCI bus ensures that data transfer occurs as fast as possiblefrom the I/O device to memory. Further, bus-mastering DMA does notrequire the allocation and usage of DMA channels since the DMAcontroller is not involved. Bus-mastering DMA is referred to as first partyDMA since the I/O device itself is handling all the data transfer.

The 8237 DMA controller has a number of independent channels, each ofwhich is assigned to a particular device. Channel 2 is usually assigned tothe floppy disk controller. DMA can take place as a single byte or word, ablock of bytes, or on demand up to a set number of bytes. DMA transferscan be initiated by a hardware request (via DREQ input on the 8237) or asoftware request using a request register.

Go right ahead

Excuse me

Newnes Interfacing Companion136

Page 150: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Most microcomputers are fitted with one and often two serial ports. Theseserial ports are labelled COM1 and COM2. The numbers 1 and 2 are forour “external” convenience only. The actual “internal” port numbers oraddresses are 3F8 for COM1 and 2F8 for COM2.The COM ports can usually be found on the back panel of a microcomputerand may take the form of either 25 or 9 pin connectors. These pins areconnected to buffers which convert the pin voltages used for datatransmission over external cables (usually using the RS232 standard) toTTL levels used for data transfer within the computer. The internal signalsare generated by a special communications IC called a UART.

25 pin

1

13

14

25

GNDTDRDRTSCTSDSRGNDDCDDTR

RI

1

5

6

9

DCDRDTDDTRGND

DSRRTSCTSRI

9 pin

Serial port pin connections forRS232 communications

The serial port is most often used fordata communications. Hence, one ofthe signal lines carries data eitherbeing transmitted from, or receivedby, the computer. The other signalsare used to control the flow of dataand to establish a communicationslink between the two serial ports ontwo different computers. Often, theserial ports are connected by amodem which converts digital datainto analog signals for transmissionover a telephone line.

The handling and control oftransmission is done by setting andreading the binary data whichappears in the internal registers of theUART. Each of these registers has anaddress (i.e. the port address) in theport address space of the computer.

2.4.6 Serial port

The 9 pin connector was introducedto save space when the parallel andserial ports were placed on a singleinterface card.

1372.4 Interfacing

Page 151: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Purpose COM1 COM2Tx,Rx data 3F8 2F8Interrupt enable 3F9 2F9Interrupt ident 3FA 2FALine control 3FB 2FBModem control 3FC 2FCLine status 3FD 2FDModem status 3FE 2FE

The port addresses for IBM compatible microcomputers have beenstandardised for many years.

It is customary to refer to thefirst address as the “baseaddress”.

Base address

Each port address is aregister that allows the serialport to be initialised andoperated on by softwarecommands. That is, the serialport controller ship, the 8250UART, is programmable inthe sense that its operationcan be controlled bysoftware rather than hard-wired circuitry.

When a serial port interfacecard is added to a computer,the base address must beset, either by a jumper on thecard, or by software. Thisallows the card to beconfigured as COM1 orCOM2 (or even COM3 orCOM4) as desired.

In Windows, it is easy to obtain the baseaddress for the COM ports. In Control Panel,select System, and then “Device Manager”.Select COM ports and then properties.

2.4.7 Serial port addresses

Newnes Interfacing Companion138

Page 152: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

LCR (Line Control Register)7 0

Data bits00 501 610 711 8

Stop bits0 11 2

Parity000 none001 odd011 even101 mark111 space

Break0 Off1 On

Baudgeneratordivisor latch0 normaloperation1 load divisor

MCR (Modem Control Register)7 0

DTRRTSOUT 1(unused)

OUT 20 deactivate interrupt1 activate interrupt

Loopback0 normal operation1 loopback mode

LSR (Line Status Register)7 0

Byte receivedOverrun error

Parity error

Framing errorBreak

Tx ready

Txregisterempty

The MCR is not set bythe 8250 UART itself.We must set bits in it tocontrol the UARToperation and/or themodem control lines.

MSR (Modem Status Register)7 0

CTS highDSR high

RI highCD high dCTS

dDSRdRIdCD

The d flags are set ifthe state of thecontrol lines haschanged since theywere last read.

2.4.8 Serial port registers

1392.4 Interfacing

Page 153: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

It is most common to operate the serial port (i.e. such as the 8250 UART)through the use of interrupts. However, this need not always be the case.The 8250 has four internal interrupt signals which can be connected throughto the CPU’s IRQ interrupt line via an INTR pin on the UART. The OUT2bit in the Modem Control Register specifies whether or not to connect theUART INTR output to the CPU’s IRQ line. In this way, the internalinterrupts generated by the UART can be optionally used by the CPU.

A 1 in the corresponding bit positionenables the internal interrupt. Thiswill not be registered at the CPUIRQ line unless OUT2 in the MCR isalso set to 1.

IIR (Interrupt Identification Register)7 0

1 no internal interrupts pending0 internal interrupt pending

Interrupt identification00 change in modem status01 transmitter buffer empty10 data received11 line status error or break

Note: COM1 usually uses IRQ4and COM2 IRQ3 on the CPU.

2.4.9 Serial port registers and interrupts

IER (Interrupt Enable Register)7 0

Received dataTransmitter buffer empty

Line status error or break

Change in modem status

Newnes Interfacing Companion140

Page 154: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

The baud rate is a measure of the number of bits per second that can betransmitted or received by the UART. This rate is regulated by a clockcircuit which, for most UARTS, is on the chip itself and can beprogrammed.

The UART clock must operate at 16 times the desired baud rate. The clockis based around the operation of a crystal oscillator which, in the case of a8250 UART, is set to a constant 1.8432 MHz. This clock signal is steppeddown through a series of counters to obtain the desired clock rate for thechip to give the desired baud rate.

Thus,

B115200D

D16108432.1B

6

=

×

=

where D is called the baudrate divisor and must beloaded into the UART.

How is this divisor loaded?

1. Bit 7 of the LCR must be set to 1.2. The LSB of D is written to the port base address (e.g. 3F8 for COM1).3. The MSB of D is written to the port base address +1 (e.g. 3F9).4. Bit 7 of LCR is cleared (and perhaps also set for other parameters such

as baud rate, stop bits etc).5. Check port base address +1 for the desired interrupt settings.

Example:A baud rate of 9600 is required.What is the divisor D?

129600

200115D

=

=

2.4.10 Serial port baud rate

1412.4 Interfacing

Page 155: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Although it is possible to write and read from the serial port registersdirectly, it is more convenient to use either applications’ programlanguages or BIOS service routines. Most applications’ languages havestatements or functions available which facilitate the programming of theserial port. For example, the

statement in BASIC allows the serial port to be configured without adetailed knowledge of the actual port addresses. However, for interfacingapplications, direct manipulation of the registers is required. For example,the BIOS service routines on an IBM compatible PC do not provide a wayto set RTS for hardware handshaking.

In Visual Basic, it is necessary to make use of the serial port object.

OPEN “COM1:9600,N,8,1” AS #1

These high level instructions ultimately result in a series of assemblylanguage instructions which call BIOS service routines through theinterrupt system.The serial port initialisationparameters are: baud rate, parity, stopbits, data bits. They are combined intoan 8-bit number which is loaded intoAL prior to calling the interrupt.

The service to be called (0 forinitialise serial port) is placed intoAH. Parameters for the service areplaced in AL. The interrupt iscalled, and the results placed in AL(or AX for service 3), e.g.:

mov AH,0int 14H

2.4.11 Serial port operation

.MSComm1.Settings = ”9600,E,7,1"

.MSComm1.InputLen = 0

.MSComm1.RTSEnable = True

.MSComm1.DTREnable = False

.MSComm1.PortOpen = True

MSComm1 has properties that can be set in code that allow theserial port to which is is assigned to be configured.

Newnes Interfacing Companion142

Page 156: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

The parallel port normally found on microcomputers is generally used forprinter output although there are some input lines which are used to reportprinter status (such as paper out etc.). The Centronics printer interfaceconsists of 8 data lines, a data strobe, and acknowledge, three control andfour status lines.

The printer port is driven by the parallel port adaptor. In the adaptor, thereare three registers which are assigned I/O port addresses. The byte to beprinted is held in the data register which is at the port base address. Theprinter status register contains the information sent to the computer by theprinter, and has an address of base+1. The printer control register hasaddress base+2 and contains the bit settings for computer control of printerfunctions.

2.4.12 Parallel printer port

25 pin (computer side)36 pin (printer side)

not shown

1

13

14

25

STBD0D1D2D3D4D5D6D7ACKBSYPESEL

Parallel port pinconnections

GND

AUTOLFERRINITSELIN

Data lines

Negative goingstrobe signalloads data ontothe data lines.

Negative goingacknowledgesignal sent tocomputer byprinter whendata has beenlatched.

Set high byprinter whenprinter is notready toreceive data.

Set high by printerwhen printer is out ofpaper.

Set high by printer whenprinter is “online”.

Set low bycomputer toenableautomatic linefeed when CRcharactertransmitted.

Set low byprinter if thereis a faultcondition inthe printer.

Set low bycomputer toinitialise theprinter.

Set low bycomputer toenable printing.

1432.4 Interfacing

Page 157: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

The base address for theparallel printer port can beeither of:3BC378278

This address maybe LPT1 if there isa monochromevideo adaptor fitted.

In Windows, the base address of theparallel port is obtained through theDevice Manager in the Control Panel.Select LPT1 and then Properties.

Printer port data register (base)7 0

378

Printer port control register (base +2)7 0

0 disable interrupt1 enable interrupt

0 initialise printer1 normal operation

0 normal1 auto LF

0 STB high1 STB low

0 deselect printer1 select printer

37A

This address isusually LPT1 onmost PCs. 278 wouldthen be LPT2 (iffitted).

2.4.13 Parallel port registers

Printer port status register (base+1)7 0

0 busy1 not busy

ACK

0 paper in1 paper out

0 offline1 online

0 error1 no error

379

Newnes Interfacing Companion144

Page 158: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Although it is possible to write directly to the parallel printer portregisters, it is customary to use the BIOS service routines availablethrough the computer’s operating system. Mostly this is done indirectlythrough high level program statements like PRINT. However, it is possible(and sometimes desirable) to call the BIOS routines directly from anassembly language program.

BIOS routines are called through interrupt 17H. Three services areavailable and are selected by the value placed in AH. For writing a byte tothe printer, the data to be printed is put into AL. The DX register is set toindicate the LPT port to use (0 for LPT1:).

AH BIOS service00 Write byte01 Initialise printer10 Report printer status

After the service has beenexecuted, the contents of theprinter status register arereported in AL.

When the printer port is being usedthrough the BIOS service routines orbeing accessed directly, the followingsequence is required to write the data:

• The data to be written is placed inthe Printer Port Data Register. Thatis, the byte is written to the printerport base address.

• The readiness of the printer toaccept data is confirmed by testingthe bits in the Printer Port StatusRegister.

• The STB line is then pulsed low bywriting a 1 to bit 0 of the PrinterPort Control Register. This transfersthe data from the Printer Port DataRegister to the Data Lines on theport connector.

Note: Although the parallel printer port is usually used for printing (i.e. output) thereis no rule against using the port for input and output for other peripherals. The morerecently introduced IEEE 1284 (1994) standard defines five modes of data transfer:Compatibility Mode (standard mode); Nibble Mode (4 bits in parallel using statuslines for data); Byte Mode (8 bits in parallel using data lines); EPP (EnhancedParallel Port – used primarily for CD-ROM, tape, hard drive, network adapters, etc.)and ECP Extended Capability Port – used primarily by new generations of printersand scanners.

2.4.14 Parallel printer port operation

Centronics typeparallel connector

1452.4 Interfacing

Page 159: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

2.4.15 Review questions

1. Arrange the following statements, which describe the sequence ofevents when a CPU services an interrupt-driven device, in thecorrect order.

2. Briefly describe the difference between programmed and interrupt-driven I/O.

3. What are the three different types of interrupts in an 8086 CPU-basedcomputer?

4. How many channels are offered by an 8259 DMA controller? How canfurther channels be accommodated?

5. What is the difference between bus-mastering DMA and DMA via8259?

6. What should the contents of the Line Control Register be for a UARTto be configured for 7 data bits, 1 stop bit, and even parity?

7. What is the main difference between serial and parallelcommunications? Give examples of advantages and disadvantages ofeach method.

8. How is data usually communicated out through the parallel port?9. For interfacing applications, what limits the maximum speed of data

acquisition in polling, interrupts, and DMA?

(a) The return address (i.e. contents of the program counter) isplaced on the stack.

(b) The CPU is directed to the interrupt service routine.(c) The CPU returns to the main program.(d) The interrupt service routine is executed.(e) The CPU checks the interrupt mask.(f) The return address is put back into the program counter PC.

Newnes Interfacing Companion146

Page 160: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

147

Page 161: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

2.5.1 Interfacing

Interfacing to a microcomputer is the process whereby the physicalphenomenon to be measured is converted into an analog electrical signalby a transducer. The signal is then digitised by an analog to digitalconverter (ADC) and then stored in memory.

Physicalphenomena:TemperatureVoltagePositionVelocityForce...

Transducer(sensor andsignalconditioning)

I/O p

ort

Interfacecard

CPU

RAM

Data bus

Address bus

Controlbus

ADC

Microcomputer

When a digital number is to be displayed on someexternal device, it is converted into an analogelectrical signal by an interface adaptor containinga digital to analog converter (DAC). The actuatorthen converts the analog signal into a physicalquantity.

The ADC can be located either near the transducer,or, as is more common, on a special purposeinterface card installed inside the microcomputer.The interface card interfaces directly to memoryeither by DMA or as a memory-mapped device.

Newnes Interfacing Companion148

Page 162: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

An analog signal variescontinuously with time. Agood example is a sinewave of frequency ω.

If we were to store this wave as a sequence of numerical data, we wouldchoose data pairs (y,t) at convenient intervals. The smaller the interval, themore accurate the representation of the original signal when we come toreconstruct it from the data.

ωt0

y

π 2π

ωt0

y

π 2π

0 0π/4 0.797π/2 13π/4 0.707π 05π/4 −0.7073π/2 −17π/4 −0.7072π 0

Discretenumerical data

Reconstruction

In this example, data was sampled at π/4 or 45o

intervals. If we decreased the sampling interval to π/8 (i.e. anincrease in the sampling rate), then we would obtain a moreaccurate representation of the original analog curve.What minimum sampling rate is required to reconstruct the signal? TheNyquist criterion states that the sampling rate (samples per second)should be greater than twice the highest frequency component (cycles persecond) of the signal.If the signal was sampled atintervals greater than π, thenthe resultant wave, whenreconstructed, may still be asine wave but at a different(lower) frequency. This iscalled aliasing. Thereconstructed signal is an aliasfor the original signal.

2.5.2 The Nyquist criterion

ωt0

y

π 2π

1492.5 A to D and D to A conversions

Page 163: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Now, a very interesting problem arises when analog data is to be stored ina digital system like a computer. The problem is that the data can only berepresented by the range of numbers allowed for by the analog to digitalconverter. For example, for an 8-bit ADC, then the magnitude of the fullrange of the original analog data would have to be distributed between thebinary numbers 00000000 to 11111111, or 0 to 255 in decimal. Numbersthat don’t fit exactly with an 8-bit integer have to be rounded up or downto the nearest one and then stored.

The quantisation error ∆e is ± half abit (LSB) and describes the inherentfundamental error associated with theprocess of dividing a continuousanalog signal into a finite number ofbits.

If the ADC were able to acceptinput voltages from 0 to 5 volts,then full scale, or 5 volts, on theinput would correspond to thenumber 255 on the output. Theresolution of the ADC would be:

V0196.02555 =

2.5.3 Resolution and quantisation noise

Thus, for an input range of 0 to 5volts, in this example, theresolution of the ADC would be19.6 mV per bit or 0.39%. A 12-bit ADC would have a resolutionof 1.22 mV per bit (0.02%) sinceit may divide the 5 volts into4095 steps rather than 255.

Quantisation noise

Nref

2V

=∆

where Vref is the range of inputfor the ADC in volts.

=∆N

ref

22

Ve

The quantisation error is random, inthat rounding up or down of the signalwill occur with equal probability. Thisrandomness leads to the digital signalcontaining quantisation noise, of afixed amplitude, and a uniform spreadof frequencies. The rms value in voltsof the quantisation noise signal isgiven by:

12erms

∆=

resolution

The quantization noise level placesa limit on the signal to noise ratioachievable with a particular ADC.

In general, the resolution of anN bit ADC is:

Newnes Interfacing Companion150

Page 164: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

2.5.4 Oversampling

In general, an input signal is comprised of a range of individual orcomponent frequencies. These signals can be separated by Fourier analysis.The range of component frequencies able to be handled by a particularanalog to digital converter circuit is called the bandwidth.

Ampl

itude

ω

Bandwidth

The Nyquist criterion requires us to samplethe input at a frequency of at least twice thatof the highest frequency component of theinput signal: fs >>2fo

fo 2fo fs

Input

Even if the Nyquist criterion is satisfied, then the existence of thequantisation noise limits the ability of the system to represent the originalinput signal exactly. This noise, the amplitude of which is independent ofthe frequency of the signal, becomes a component part of the sampled data.The power associated with this noise Pn is found by integrating erms overthe frequency range 0 to fo to give:

The ratio of the sampling frequency to theNyquist frequency is called theoversampling ratio: .f2fOSR os=

( )OSR1eP 2rmsn =

The significance of this is that the signal-to-noise ratio SNR can be improved byincreasing the OSR or increasing N.

n

sPP

SNR =

Signalpower

Noisepower

Increasing the number of bits increases the signal to noise ratio. However,oversampling with an N-bit ADC also reduces the noise power and thuscauses the N-bit ADC perform as if it were an N+w bit ADC. If fs is theoriginal sampling frequency, then to obtain w extra bits of resolution, thenew (or oversampling) frequency is given by 4wfs.

76.1N02.6

e1

22V

log20SNRrms

ref10db

+=

=

122V

e Nref

rms =where

2inV∝

Now, the noise voltage is expressed hereas an rms value, thus, we must alsoexpress the input voltage as an rms value.The maximum SNR is obtained when thefull range of the ADC is used. Allowingfor both positive and negative halves ofthe input cycle, the maximum value of Vinto the ADC is Vin = Vref/2, and thus, therms value of this is: .22Vref

The SNR is:

1512.5 A to D and D to A conversions

Page 165: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

An analog to digital converter accepts an input voltage and issues apositive integer on its output whose binary value is proportional to themagnitude of the input voltage.

Digital signalout representsbinary logiclevels

ADC

Analogsignal in

• Staircase (or integrating) method• Successive approximation method

Digital data can be readily storedand processed on a microcomputer.Analog signals cannot.

Volts05500555

V=Vmaxsinωt0 1 1 0 0 1 1 1

2.5.5 Analog to digital converters

ωt0

y

π 2π

Typical conversion times:8 bit 12 bit 16 bit

Integrating 20 msec 40 msec 250 msecSuccessiveapproximation 10 µsec 20 µsec 500 µsec

Analog signal

Dig

ital o

utpu

t

Quantisationerror

Gain error

Differentialnon-linearityerror

Linearityerror

Idealdigitaloutput

Actualdigitaloutput

Offset error

• Linearity error typically±1/2LSB

• Differential error typically±1/2 LSB

• Gain error % adjustable byexternal resistor

• Offset error: adjustable byexternal resistor

Newnes Interfacing Companion152

Page 166: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

The reference voltage is linearly increased in small steps until it equals orexceeds the signal voltage and a digital counter is used to record thenumber of voltage steps tested during the conversion time. The digitalcount is thus an indication of the magnitude of the voltage input.

A to D conversions are usually performed by comparing the unknowninput signal voltage to an internal reference voltage. A voltage generatorsupplies a reference voltage which is adjusted until it equals (to withinsome predefined tolerance level) the input signal voltage.

The conversion time depends uponthe magnitude of the input voltage.This type of ADC is suitable forrecording signals that do not changerapidly with time. The digitisedoutput value represents the averagevalue (or integral) of the input signalover the sampling period.

DC voltage comparator

Reference voltagegenerator

Binary counter(digital output)

Clock pulses

DC voltage input(analog signal)

Stop

cou

nt

2.5.6 ADC (integrating method)

In more sophisticated devices, a dual slope technique is used. After aninitial zeroing period, the analog input signal is integrated (addedtogether) for a fixed number of clock cycles. The integrator input is thenconnected to an internal reference voltage that has a polarity opposite tothe analog input signal.The number of clock cyclesfor the integrator to “discharge”to zero is proportional to themagnitude of the originalanalog signal voltage. Theaccuracy of the ADC is thusdependent on the accuracy ofthe reference voltage.

V

t

Vin (large)

Vin (small)

1532.5 A to D and D to A conversions

Page 167: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1. Set all bits set to zero.2. Set msb to 1.3. If Vin > D/A, then Vin is above half of full scale of output, thus,

keep a 1 in msb. If not, then clear msb to zero.4. Set next msb to 1 (i.e. could have 1100 0000 or 0100 0000).5. If Vin > D/A, then Vin is above 7/8 of fsd, thus, keep 1, else clear

bit.6. Set next msb to 1 (e.g. 0010 0000, 0110 0000, 1010 0000 or 1110

0000)7. If Vin > D/A then Vin is above 6/8 of fsd, thus, keep 1, else, clear

bit position.and so on until Vin is tested against lsb.The conversion time is fixed and is equal to:

fN

Number of bits

Clock frequency

2.5.7 ADC (successive approximation)

In this method, the input voltage is compared to half the full scale voltageand then lower values in succession. The steps are:

Vin

DAC

Dig

ital o

utpu

tmsb

lsb

Shift register

Clock pulses

D/A

Comparator

This method allows highspeed data acquisition (up to100 000 conversions/sec).However, the opportunityfor errors to be introduced isgreater. The fixedconversion time means thatthe input signal needs to besteady or at least capturedduring the sampling period.

Newnes Interfacing Companion154

Page 168: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

We have seen that the conversion of an analog signal to a digital outputtakes time: the conversion time, which in the case of a successiveapproximation ADC, is fixed. Now, if the analog input signal is changingduring the conversion time, then the converted output will be in error. Thisis known as aperture error.For example, for an 8-bit ADC, the smallest increment δ of input signalregistered by a single bit will be: δ = 1/28 = 0.0039 fraction of full scale ofsignal.

During conversion time, thesignal changes. For there to beno error in the digitised output,this change must be less thanthe smallest incrementregistered by a single bit: i.e. theproduct (δ)(Α).

( )

( )

f2t

tAAtt@AV

tAV

AdtV

tcosAdt

dVtsinAV

a

a

ain

in

max

in

in

in

π

δ=

ω

δ=

ω=δ

=∆δ=∆

∆ω=∆

ω=∆

ωω=

ω=

Vin

t

aperturetime ta

δΑ

Consider a sine wave:

Maximumrate ofchange whencos ωt = 1.

This would be themaximum change in Vinfor a particular timeincrement ∆t.

For there to be no error inthe output, ∆Vin < δA. Themaximum aperture time isthat at ∆ Vin= δ A.

Max aperture time for sine wave offrequency f Hz. Conversion time has to beless than this for no aperture error.

e.g. For 100 Hz input, 8-bitADC, ta = 6.2 µsec.

The aperture time is the maximum timeinterval within which the conversion mustoccur before the signal changes enough toaffect the digitised output.

2.5.8 Aperture error

1552.5 A to D and D to A conversions

Page 169: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

The ADC08xx series of ICs are 8-bit analog to digital converters whichuse the successive approximation technique.

There is an RC oscillator built into thechip whose frequency is approximately1/RC. For example:

Conversions are initiated by anexternal start pulse at pin WR.Conversions begin when WR goesfrom low to high. WR must remainhigh during conversion.

When conversion is completed, INTRgoes low indicating that the digitaldata on the outputs is complete andthe device is ready for the nextconversion.

The chip takes the differencebetween the two analog inputs asits input signal. If −Vin is tied toground, then the other may be usedas a single-ended input. If noexternal reference voltage isapplied at Vref/2, then the chip usesan internal reference whichdepends on the value of Vcc.

The conversion time is given bythe clock frequency. It takesapproximately 64 clock cycles toperform one 8-bit conversion.Thus, to obtain a sampling rate ofsay 10 000 samples per second, theclock frequency needs to be set to:

( )( )kHz640

101064f 3

=

×=

The conversion time is thus:

s10010640

64T 3

µ=

×

=

64 clock cyclesfor oneconversion,640 × 103 clockcycles persecond.

( )pF147k101kHz680

=

2.5.9 ADC08xx chip

R

C

ADC

0804

10k

+5 V

OSC

Digitaloutput

DB0

DB7

Analogsignal in

CLK

DGND

+Vin

− Vin

AGND

CS

RD

WR

Vref/2

INTR

Newnes Interfacing Companion156

Page 170: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

4

V+

Analoginput

To avoid aperture error, the conversion time and the desired performancecharacteristics of the ADC circuit must be taken into consideration. Forexample, given a conversion time of say 100 µsec, what is the maximumfrequency of sine wave that can be sampled by the 8-bit ADC0804 withoutaperture error?

Hz2.6ff2

0039.010100

f2t

6

a

=

π=×

π

δ=

For an 8-bit ADC, δ = 1/28 = 0.0039

Not very high! What to do?

We need a circuit that will take a sample of the input voltage at a particularinstant, and hold it until the ADC has processed the conversion - a sample-and-hold circuit. There are a number of pre-packaged ICs available, acommon one being the LF198, 298, 398 series.

The time taken for the sample-and-hold circuit to sample the signal and holdit must be shorter than the conversion time (otherwise we wouldn’t need touse the circuit!). The above circuit has a conversion time of about 10 µsec.

When logic input is high,output follows any changesin the analog input. Whenlogic input goes low, theanalog input signal iscaptured and passed throughto the output. Output remainsfixed at this value while logicinput is held low.

Ch is a hold capacitorand should be apolystyrene type≈ 0.01 µF.

V−

Output

Ch

5

6

78

3

1

Logic inputhold

sample

0 V

5V

Q. How many bits per secondneed to be transmitted for thisfrequency of sine wave? N =1/620 × 10-6 = 1611 bytes/sec= 12 888 bits/sec

2.5.10 Sample-and-hold

1572.5 A to D and D to A conversions

Page 171: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

+5V

Now, to control a sample-and-hold circuit, signals from the ADCcan be used.WR: Standby mode when WR islow. Conversions begin whenWR goes from low to high. WRmust remain high duringconversion.INTR: Usually high. Whenconversion is completed, INTRgoes low for eight clocks. WRmust then be held low for about500 nsec before going high toinitiate a new conversion.We can use a 7476 latch to control asample-and-hold circuit. The Q output fromthe latch can be made low while conversionis in progress thus sending the sample-and-hold circuit to “hold”.

• Start pulse initiates conversionsince it is connected directly toWR.

• Since SET is high, and initiallyRESET is high, the output Qwill respond to the clock goinglow and since J is high (with Klow), Q is sent low. Samplewill be latched on clock signalgoing low. Conversion actuallybegins when clock (WR) goesback high.

• At the end of conversion, INTRgoes low which sends a low toRESET sending Q highindependent of the signal at Jand sending sample and hold to“sample”.

J K0 0 no change, Qn+1 = Qn0 1 Qn+1 = 0 (RESET)1 0 Qn+1 = 1 (SET)1 1 Qn+1 = Qn toggle

Clock pulse 1 to 0

R S Q Q1 1 no change1 0 1 00 1 0 1

Normaloperation

Action tables:

7476

2.5.11 Sample-and-hold control

Startpulse

Q

S

R

J

K

To sample-and-hold logic input

CLK

CLK1

Vcc

S1

R1

J1

CLK2

S2

R2

GND

K1

Q1

Q1

J2

Q2

Q2

K208

04

INTR

WR

+Vin

Newnes Interfacing Companion158

Page 172: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Analogsignal out

Binary or digitalsignal in

DAC122, 134, 156, 169, 191,210, 225, 255, 225, 210,191, 169…

Digital to analog conversions can be performed using resistor networks andthe conversion to an analog signal is usually in the order of nanoseconds.Since the digital information is a step approximation of the input signal, theresulting output from a D to A converter reflects this step nature of the signal.

The sharp steps of thiswaveform lead to highfrequency componentsin the reconstructedsignal not present inthe original. A lowpass filter may beused to round offthese corners thusleading to a morefaithful reconstruction.

ωt

Originalsignal Reconstructed

signal

2.5.12 Digital to analog conversion

Digital to analog conversions may be made using a ladder network ofresistors or a weighted input to a summing amplifier. The voltage on theoutput depends upon the voltages applied to the inputs. These voltages maybe either 0 (for logic 0) or some supply voltage Vcc (for logic 1). The TTLinput connected to the lowest value resistor carries more weight than theothers, thus, a larger binary or digital input results in a larger analog outputvoltage.

23

22

21

20

Analog output

Dig

ital i

nput

R

2R

4R

8R R/2

0

y

π 2π

-

+

1592.5 A to D and D to A conversions

Page 173: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

A popular all-purpose 8-bit D to A converter IC is the DAC080x series.The settling time is in the order of 100 ns.

VLC

Iout

V-

Iout

B1

B2

B3

B4

CMP

Vref−

Vref+

V+

B8

B7

B6

B5

DAC

0800

The output for this IC is in the form of two complementary currents Ioand Io. In the diagram above, these current outputs are connected to a V+supply through two 10K resistors. A voltage output can be obtained bymeasuring the voltage between the two output terminals or measuring thevoltage of one of the outputs with respect to ground. As the binary value ofthe digital inputs increases, Io increases and Io decreases. A decrease in Iomeans an decrease in the voltage drop across the 10k resistor and anincrease in Vo measured w.r.t. ground.

Vref provides a currentreference. Setting Vref toV+ makes Vo swingpositive and negative.Setting Vo to V+/2 givesa 0 to V+ analog output.

2.5.13 DAC0800

Digitalinputsm

sb

lsb

5 6 7 8 9 10 11 12

12

414

153 16 13

∆Vout

V+

Vref

V+V−

5k

5k

10k10k

0.01 µF0.1 µF

0.1 µF

Io

Io

Vo

Newnes Interfacing Companion160

Page 174: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

2.5.14 Data acquisition board

In most circumstances, one would accomplish most interfacing tasks witha general-purpose data acquisition board. Such boards fit into an ISA orPCI slot in a microcomputer and would typically contain:

• Sixteen analog input channels (ADC)• Forty digital I/O• Four digital output channels (DAC)• Four 16-bit counter input• Two 16-bit timer outputs

Multiplexing is used on the input to a single ADC chip to allow multipleand continuous scans of the analog inputs. Interface boards generallyallow the 16 analog inputs to be open-ended, or paired to form eightdifferential inputs. The analog inputs may be fitted with simultaneoussample-and-hold circuits to reduce the error associated with sequentialsampling of the inputs by the multiplexer.Configuration and control of interface cards is done using applicationsprogram interface (API) calls. These are functions provided by the cardmanufacturer to perform tasks such as data acquisition, counter and timeroperation and selection of trigger method.For multiple channel data acquisition, the scan rate (1/scan interval) is animportant parameter. Scan rates and other time critical functions arereferenced to an on-board clock or an external trigger signal.

0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3

Scan 0 Scan 1 Scan 2 Scan 3

Scaninterval

Sampling interval(5 or 10 µsec)

Idlestate

Data transfer can be initiated by software polling, interrupts or DMA.Interrupt latency, especially under a multitasking operating system, canlimit the maximum data transfer rate. Maximum data transfer rate isusually obtained using bus-mastering DMA.

1612.5 A to D and D to A conversions

Page 175: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1. A 10-bit ADC accepts an input voltage from 0 to 5 V. Determine theresolution of the ADC.

2. For an input signal of 500 Hz frequency, determine the aperture time ofan 8-bit successive approximation ADC.

3. Given a conversion time of say 50 µsec, what is the maximumfrequency of sine wave that can be sampled by an 8 bit ADC withoutaperture error?

4. What is the purpose of a sample-and-hold circuit?5. Calculate the settling time of a DAC that is required to convert 16 bit

signals from a compact disc player to produce sound in the audiblefrequency range (say 20−20 000 Hz) whose signals were encodedwithout aperture error.

6. The input signal below is presented to a sample-and-hold circuit.Sketch the output signal which is in turn presented to the ADC whenthe logic input signal goes from sample to hold as shown.

2.5.15 Review questions

Sample

Hold

Input

7. Design (in principle) a D to A converter that uses a network ofresistors without any active components.

Ans: 4.88 × 10−3 V

Ans: 1.24 × 10−6 s

Ans: 12.4 Hz

Ans: 1.2 × 10−10 s

Newnes Interfacing Companion162

Page 176: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

163

Page 177: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Once an analog signal has been digitised by the ADC, the digitalinformation must then be passed to a port of a microcomputer forsubsequent placement on the data bus. An inexpensive, readily availablemethod is by serial communications using the serial port. Other commonmethods are to use an ADC interface card that interfaces directly to thecomputer bus system, and the GPIB parallel data bus.

Steps in serial transmission of abyte of digital data:(a) byte is converted into sequential

series of bits(b) bit transmitted over signal wire(c) bits reassembled into bytes

0 2πωt

y

π

2.6.1 Communications

The digital information coming from theADC is a series of bytes, generated oneafter the other, as the input signal isrepeatedly sampled. In the serial methodof transmission, the bits that compriseeach byte are sent one at a time, insequence, along a single wire and thenreassembled into a byte aftertransmission.

Serial interface card

Data bus

Serial port

Bit beingtransmittedon signal wire

Serial interface circuit

ADC

7 6 5

4

3 2 1 0

Newnes Interfacing Companion164

Page 178: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

At the transmission end of the process, the byte of data is sent bitwise overa signal wire. This is done using a shift register in a special integratedcircuit called a UART (Universal Asynchronous Receiver/Transmitter).

A shift register can be made usingcascaded JK flip-flops. A positivetransfer pulse loads theasynchronous inputs R and S withthe data to be shifted. For example,if D = 0, then on the transfer pulse,S = 1, R = 0 and Q = 0. If D = 1,then S = 0, R = 1 and Q = 1. Thus,after the transfer pulse, the paralleldata is transferred to the J input ofeach flip-flop. When the transferpulse goes low, R and S are both at1 which is the no change state, andon the clock or shift pulse, data istransferred along the chain from Qto J, the serial output bit streamappearing as the last output Q.

At the receiving end, the serial bitstream is converted to parallel 8-bit data by a reverse of the above.Data is clocked in, and then atransfer pulse transfers the data tothe parallel outputs.

Now, for long distances, the bitstream is not usually transmitteddirectly over wires since thebinary signals are easily distortedwith distance. This, together withthe requirement that thetransmitter and receiver need to besynchronised, means thatalternative arrangements arerequired to actually transmit thedata over distances of more thanabout 15 m.

D3

J QSx

K QR

J QS

D2

K QR

J QS

D1

K QR

J QS

D0

K QR

Shiftpulses

Transferpulse

4-bit shift register

11

0,1

1,0

0,1

0,1

Seria

l dat

a ou

t

1,0

0,1

1,0

1

1

0,1

1,0

2.6.2 Byte to serial conversion

1652.6 Data communications

Page 179: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

The RS232 interface standard defines the necessary control signals anddata lines to enable information to be transmitted between computerequipment (or data terminal equipment DTE) and the modem (or datacommunication equipment DCE). The modulated carrier signal istransmitted over a two-wire telephone network by the connecting modems.

A modem converts or “modulates”digital information into a form suitablefor transmission over the telephonenetwork. The receiving modemdemodulates the signal back intodigital data for use by the receivingcomputer. Modems transmitinformation using a sine wave carrierwhich is modulated (either throughamplitude, frequency or phase) tocarry binary information.

2.6.3 RS232 interface

1. RTS is raised high by thesending computer indicatingthat data is ready to be sent.

2. The transmitting modem sendsa carrier signal to the receivingmodem which raises DCD onits connection to the receivingcomputer which is thus notifiedof the existence of a carriersignal.

3. The transmitting modem waitsfor a preset period for thereceiving computer to getready to receive data.

4. The transmitting modem raisesCTS signalling to the sendingcomputer that it may nowbegin to send data.

5. The transmitting modemreceives digital data from thesending computer on the TDline and modulates the carrierwave accordingly. Thereceiving modem demodulatesthe carrier and puts digital dataon the RD line connection tothe receiving computer.

6. When the sending computerhas finished sending the data,it clears the RTS signal to thetransmitting modem whichthen drops the carrier andclears its CTS signal. Thereceiving modem detects lossof carrier signal and it drops itsDCD line to the receivingcomputer.

DTE (Computer)

DCE (Modem)

RDRTSCTSDTRDSRDCDRIGND

TD

Carrier signal + data

Receivingmodem Receiving

computer

Newnes Interfacing Companion166

Page 180: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Start and stop bits frame the data bits. When the signal line is not sendingdata, it is idle and held at mark or logic high. The start bit is low or spaceand thus when the receiver sees a transition from mark to space, it knowsthat the next bit to be received is the lsb of the data being transmitted. Afterall the data bits have been received, the receiver interprets the next bit to bea stop bit which is mark. If the bit actually received is not mark, then thereceiver knows that an error has occurred.

The rate of transmission is the databit rate which is called the baudrate. Generally, the baud rate is thesame as the bit rate; however,some transmission systems arecapable of sending more than onedata bit (e.g. amplitude and phasemodulation) into a transmission bitand the bit rate is thus higher thanthe baud rate.

The receiver clock is usually made 16 times the bit rate. When a mark tospace transition is detected, the receiver counts 8 clocks. If the signal is stillat space, then it is assumed that the signal is a valid start bit. The receivercounts off another 16 clocks and then samples the data until all the data bitsand stop bit(s) have been received. The bit sampling thus takes place in thecentre of the signal levels.After the data bit and before the stopbit, there may be a parity bit which isused as a check for data validity. Ineven parity, the total number of 1s(including the parity bit) is made to bean even number (and vice versa). Thereceiver computes its own parity bitwhen a byte is received and comparesit with that appended by the sender. Amismatch indicates a parity error.

2.6.4 Synchronisation

Startbit

8 data bits Stopbit

Idlestate

Idle state

8 clocks

Start bitdetected

16 clocks

1st data bitsampled

Start bitverified

16 clocks

0 1 0 0 1 0 1 1 0 1

1672.6 Data communications

Page 181: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

The 6402 UART takes in parallel byte data into the Transmitter BufferRegister at the inputs TBR1−8. This data is transferred into the TransmitterRegister for shifting. The output bit stream appears at Transmitter RegisterOutput (TRO). Similarly, serial data is read in at Receive Register Input,converted to a character in the Receive Register and appears at ReceiveBuffer Register outputs RBR1−8. The transmitter part of the circuitautomatically adds start, stop and parity bits according to logic levelsapplied at control inputs. The receiver checks for parity and stop bit errorsand issues logic levels at various indicator outputs.

When TBRL goes low, data is read from the input pins TBR1−8 andtransferred to the Transmitter Buffer Register. When TBRL goes from low tohigh, data is transferred from the Transmitter Buffer Register to theTransmitter Register whereupon data is shifted and transmitted out on TRO.

If RRD is held low, then the data on RBR1−8 is that last read from the inputstream at RRI. A high level on DR indicates that the data read is available atRBR1−8. Once read, DR needs to be reset by a negative pulse to DRR.

2.6.5 UART (6402)

Character length CLS1 CLS25 0 06 1 07 0 18 1 1

Parity PI EPENone 1 xEven 0 1Odd 0 0

SBS, stop bits, 0 forone, 1 for two

e.g. 8 data bits, 1stop bit, no parity.

CLS1, CLS2 to 1PI and EPE to 1SBS to 0.

1234567891011121314151617181920

VDD

not usedGNDRRD

RBR8RBR7RBR6RBR5RBR4RBR3RBR2RBR1

PEFEOE

SFDRRCDRR

DRRRI

6402

4039383736353433323130292827262524232221

TRCEPECLS1CLS2SBSPICRLTBR8TBR7TBR6TBR5TBR4TBR3TBR2TBR1TROTRETBRLTBREMR

Para

llel d

ata

in

Serialdata out

Serialdata in

Para

llel d

ata

out

Newnes Interfacing Companion168

Page 182: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

RRD: Receiver Register Disable. A high level forces RBR1 to RBR8 to a highimpedance state.

RBR8–RBR1: Receiver Buffer Register outputs. Parallel byte data is output here.PE: Parity Error: High level indicates that the received parity does not match

the parity set by the control bits. When the parity is inhibited (PI) this pinis held low.

FE: Framing Error: High level indicates that the first stop bit is invalid.OE: Overrun Error: High level indicates data received flag was not cleared

before the last character was transferred to the Receiver Buffer Register.SFD: Status Flag Disable: High level input forces the outputs PE, FE, OE,

DR, TBRE to high impedance.RRC: Receiver Register Clock. Set to 16 times the baud rate.DRR: Data Received Reset. A low level clears the output DR to low.DR: Data Received. A high level indicates character has been received and

transferred to the Receiver Buffer Registers.RRI: Receiver Register Input. Serial data is clocked into the Receiver Buffer

Registers from here.MR: Master Reset. High level clears PE, FE, OE and DR and sets TRE,

TBRE and TRO to high. MR should be pulsed high after power-up toreset the UART.

TBRE: Transmitter Buffer Register Empty indicates that the Transmitter BufferRegister has transferred its data to the Transmitter Register and is readyto accept new data.

TBRL: Transmitter Buffer Register Load. A low level transfers data from theinputs TBR1–8 to the Transmitter Buffer Register.

TRE: Transmitter Register Empty. A high level indicates that transmission of acharacter, including stop bits, has been completed and that theTransmitter Register is now empty.

TRO: Transmitter Register Output. Serial data output line.TBR1–8: Transmitter Buffer Register inputs. Parallel data is loaded into the

Transmitter Buffer Registers at these inputs.CRL: Control Register Load. High level loads the Control Register with parity,

character length and other settings.TRC: Transmitter Register Clock. Set to 16 times the baud rate.

The more versatile 8250 (16450) UART extends the functionality of the basic 6402by having programmable registers that set the baud rate, parity and stop bits, andan interrupt controller. High level commands in an application program set theappropriate bits in the internal registers (see Section 2.4.5). Later 16550 UARTSfeature first-in, first-out (FIFO) buffers which allow data transfer to happen atmaximum speed while the processor is momentarily occupied by other tasks.

A description of the pin functions on the 6402 UART is given below:

1692.6 Data communications

Page 183: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

RRI and TRO on the 6402 UART are the serial input and output lines. Thepolarity of the signals is +5 V for mark or high, and 0 V for space, orlow. However, the transmission of serial data along the wire in an RS232transmission interface requires −15 to −12 V for mark, and +12 to +15 Vfor space. Line drivers are used to convert the logic levels required by theUART to those required at the RS232 interface pins TD and RD.A very useful IC is the 232CPE dual RS232 transmitter/receiver. This ICrequires a single +5 V supply and generates +10 V and −10 V necessary todrive the RS232 signal lines. (Note: Handshaking signals CTS, RTS, DSRetc are also at +10 V, −10 V.)The 232 takes either TTL or CMOS logic levels as inputs, and provides±10 V at the RS232 outputs. It also receives RS232 inputs, and providesequivalent TTL or CMOS levels as an output. There are two separatechannels available for both receiving and transmitting.

TTL outRS232 in

TTL in

TTL in

TTL out

RS232 in

+5V

RS232 out

1µF

1µF

1µF

3.3k

RS232out

Transmitting: TTL input, RS232 outputReceiving: RS232 input, TTL outputThe external capacitors are used by theinternal voltage doublers to obtain ±10 VRS232 signals.

+

2.6.7 Line drivers

C1+

V+

C1-

C2+

C2-

V-

T2out

R2in

Vcc

GND

T1out

R1in

R1out

T1in

T2in

R2out

232

3.3k

+

+

+1µF

Newnes Interfacing Companion170

Page 184: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

The crystal’s piezoelectricproperties are electricallyequivalent to an inductance inseries with a capacitance at itsresonantfrequency.The circuitshown is aCMOS inverterimplementationof a Colpitts oscillator. Theinput-output states of theinverter oscillate at theresonant frequency of thecrystal.

The 6402 has two separate clock inputs but normally, these are driven bythe same clock so that the transmit and receive baud rates are the same. Theclock frequency is to be 16 times the baud rate. The 6402 chip does nothave a programmable baud rate divider (as in the 8520) so the desiredclock frequency must be supplied externally using a binary counter.A crystal oscillatorcan be used inconjunction with ahigh speed inverter toproduce a squarewave output whichcan be stepped downto the desiredfrequency with abinary counter.

The second inverterisolates the oscillatorcircuit from that to bedriven by the clock.

GND

Vcc

74HC

04

2.6.8 UART clock

153.6 kHz (9600 baud)

76.8 kHz (4800 baud)

38.4 kHz (2400 baud)

CP1

MR1

Q01

Q11

Q21

Q31

GND

Vcc

CP2

MR2

Q02

Q12

Q22

Q32

74HC

393

CLK signal toUART is to be 16times the baud rate

19.2 kHz (1200 baud)

307.2 kHz(19 200 baud)

4.9152 MHz

4.9152 MHz

10M

33 pF33 pF

74HC04

CLK

1712.6 Data communications

Page 185: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

MR: Master Reset. High level clears PE, FE, OE and DR and sets TRE,TBRE and TRO to high. MR should be pulsed high after power-up to resetthe UART. A simple delay circuit using a capacitor and a NAND gate canbe used to send a short positive pulse to MR on power-up. The timeconstant is simply the product RC, and values of R1 = 100 kΩ andC = 4.7 µF give a time constant of about 0.5 sec.

Initially, NAND output is at 0 V.When Vcc is applied, the NANDoutput goes to 1 since one input isat +5 V and the other at 0 V. Asthe capacitor charges up throughR1, voltage at upper input to theNAND rises and after a timecharacterised by R1C, the NANDgate flips from 1 V to 0 V. The 1kΩ resistor limits the current intothe NAND for protection.

to MR

+5 V

R1

1k

C

A suitable IC is the 7400series NAND.

2.6.9 UART Master Reset

GND

Vcc

7400

Newnes Interfacing Companion172

Page 186: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

The RS232 serial protocol was designed to transmit data over aconsiderable distance using the telephone network but may also be usedfor local communication to and from a device attached to the serial port ofa computer. The exact same control lines may be used to regulate the flowof data between the connected equipment without the use of a modem;however, there is a problem: if both devices are connected pin to pin andattempt to send data over the transmit line, then no signals will appear onthe receive lines. Thus, the transmit and receive lines must be crossed over.This type of connection is called a null modem.

RDRTSCTSDTRDSRDCDRIGND

TD

DTE DTE

RDRTSCTSDTRDSRDCDRIGND

TD

In the example above, the connectionsbetween RTS and CTS, and DTR, DSRand DCD, cause the computer to regardthe connection as occurring betweenmodems even if no modem is used at all.For instance, the computer which issending data first raises its RTS line,which is now directly connected to CTS.The sending computer thus immediatelyreceives a CTS signal from its own RTSand begins to transmit data on TD. Thereceiving computer receives this data onits RD line.

Tying DTR, DSR and DCDtogether in effect tells thecomputer that the modem isconnected to a telephone lineupon which there is a validcarrier signal and data can beeither sent or received. Ofcourse, there is no modempresent at all, hence the termnull modem. TD, RD and signalground are the minimumrequirements for a serialconnection between twocomputers, the otherconnections may be required ifthe communications softwareon the computers tests themodem status before sendingor transmitting data.

2.6.10 Null modem

1732.6 Data communications

Page 187: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

BIOS services may be used to initialise and use the serial port. Theseservices are available through interrupt 20 (14H). Parameters for theinterrupt are specified in the AL register. The serial port is specified inDX. The four services available are:

0 initialise serial port The serial port initialisation parameters are: baudrate, parity, stop bits, data bits. They are combinedinto an 8-bit number which is loaded into AL.

Bits baud7 6 5 rate0 0 0 1100 0 1 1500 1 0 3000 1 1 6001 0 0 12001 0 1 24001 1 0 48001 1 1 9600

Bits Parity4 30 0 none0 1 Odd1 0 None1 1 Odd

Bit No.2 stop bits0 one1 twoBit data1 0 bits0 0 unused0 1 unused1 0 71 1 8

The 8-bit data to betransmitted is placed inAL. After transmission,a status code is placedin AH.

The received characteris placed in AL. A codeis placed in AH to reportstatus.

The status returned by services 0−2 and that reported by service 3 are in theform of a bit pattern in the AH and AX registers respectively. A 1 in any bitposition indicates the condition or error returned.

AH7 Time out6 Transfer shift register empty5 Transfer holding register empty4 Break-detect error3 Framing error2 Parity error1 Overrun error0 Data ready

AL7 Receive signal detect6 Ring indicator5 Data set ready4 Clear to send3 Delta receive signal detect2 Trailing edge ring detector1 Delta data set ready0 Delta clear to send

The service to be called is placed into AH. Parameters for the service areplaced in AL. The interrupt is called, and the results placed in AL (or AX forservice 3).mov AH,0int 14H

“Delta” bits indicate a change in the indicated flags since the last read.

2.6.11 Serial port BIOS services

1 send one character

2 receive one character

3 read serial port status

Newnes Interfacing Companion174

Page 188: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Serial communications can be easily implemented in BASIC. Thislanguage provides statements which allow programming of the UARTwithout reference to the actual I/O port memory addresses. The serial portinitialisation parameters are set using the OPEN statement:

OPEN “COM1:9600,N,8,1” AS #1which initialises COM1 at 9600 baud, no parity, 8 data bits, 1 stop bit.Data is written to or read from a “file” numbered “1”.

To read 1 byte from COM1, we write: A$=INPUT$(1,#1) The byte is read from the receive buffer in the UART and converted to anASCII character and then assigned to a string variable A$. To display thedecimal number actually read, we can use the ASC function:

PRINT ASC(A$)

The INPUT$ function is the preferred method of reading data from the serialport. Other statements such as INPUT and LINE INPUT may work, but maygive unpredictable results if the data in the input stream contains ASCIIcontrol characters such as LF and CR. If we were to use INPUT, then theinput would stop when the incoming data contained a comma or a CRcharacter. This is OK for reading in data from the keyboard, but not from a filewhere we may wish to capture all the data.

2.6.12 Serial port operation in BASIC

frm_MainMenu.MSComm1.Output = WriteString + vbCrReadChar = frm_MainMenu.MSComm1.Input

frm_MainMenu.MSComm1.Settings = ”9600,E,7,1"frm_MainMenu.MSComm1.InputLen = 0frm_MainMenu.MSComm1.RTSEnable = Truefrm_MainMenu.MSComm1.DTREnable = Falsefrm_MainMenu.MSComm1.PortOpen = True

In Visual Basic (VB), the procedure is very similar. The COMM portobject is placed on a form, in the example below, the form is called dfrm_MainMenu and the COMM port object is called MSComm1.

MSComm1 has properties that can be set in code that allow the serial portto which is assigned to be configured.

Methods available to the serial port object allow characters to be read andassigned to a variable, or the value of a variable to be written andtransmitted from the computer:

1752.6 Data communications

Page 189: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

OUT &H2FC,&H8

Although at first sight reading the serial port using BASIC appears fairlystraightforward, difficulties arise when the data cannot be read fast enoughand the input buffer overflows. The buffer holds 255 characters (i.e.1 character = 1 byte). Handshaking (either software codes or hardwaresignals) is used to halt transmission of data from the sending computer untilthe receiving computer has emptied the buffer. Various functions areavailable in BASIC to allow either software or hardware handshaking.

• LOC(x) returns thenumber of characters inthe input buffer for filenumber “x”.

• LOF(x) returns thenumber of characterspaces available in theinput buffer.

• EOF(x) returns (−1) ifthe buffer is empty or 0if it is full.

For the serial data acquisition circuit, hardware handshaking must be usedsince there is no method of interpreting software codes such as XON andXOFF. The RTS line offers the most convenient form of hardwarehandshaking. RTS is arranged to go logic high (−10 V on RS232 signallines) when the buffer is full, and then low when the buffer is empty. Now,the RTS signal line is available via the 2nd bit in the Modem ControlRegister. Setting this bit to 0 will actually set RTS to logic high. TheBASIC OUT statement can be used to send a byte to an I/O port address.Thus:

Set RTS logic high

OUT &H2FC,&HA Set RTS logic low

MCR (Modem Control Register)7 0

DTRRTSOUT 1(unused)

OUT 20 deactivate interrupt1 activate interrupt

For COM2, the MCR port address is 2FC

These statements, incombination with the LOC,LOF and EOF functions,can be used to controlRTS. The RTS signal inturn can be wired to haltand resume transmission ofdata as required.

Note: The BASIC INPUT$ statement makes use ofinterrupts to read the data from the serial port. Makesure that OUT2 remains set at 1 when writing data tothe MCR.

2.6.13 Hardware handshaking

Newnes Interfacing Companion176

Page 190: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

2.6.14 RS485

The maximum distance allowed by RS232 is about 15 m which in anindustrial environment can be a severe limitation, especially when thecomputer is located say in a control room some distance away from thetransducer. Further, the maximum data transfer rate can be a limitationfor fast data acquisition. Standards such as RS422 and RS485 weredeveloped to overcome these limitations and permit greater flexibility andperformance for instrumentation applications.An increase in transmission speed and maximum cable length is done byusing voltage differentials on signal lines A and B. For a space, or logic 0,the voltage level on line A is greater than that on line B by 5 V. For a mark,or logic 1, the voltage level on line B is greater than that on line A. Thereceiver inputs on the line driver chip determine whether or not the signalis mark or space by examining the voltage difference between lines A andB. Two signal wires are thus required for data transmission.Unlike RS232, in which there is usually a connection between two piecesof equipment, the RS485 standard allows for up to 32 line drivers and 32receivers on the one set of signal lines. This is achieved by tri-state logicon the line driver pins.

In tri-state logic, pins canbe at logic 0, logic 1 orhigh impedance. The laststate effectivelydisconnects the driverfrom the line. The highimpedance state is set byan “enable” signal on thedriver chip.

Features of RS485:• Maximum distance 1200 m.• Data rate up to 10 Mbps.• 32 line drivers and receivers

on the same line.• TTL voltage levels.

1

5

6

9

ShieldTD (B+)RD (B+)RTS (B+)CTS (B+)

TD (A−)RD (A−)RTS (A−)CTS (A−)

Common RS485 9-pin connector

A(−)

B(+)

Input Output

Transmit Receive

1772.6 Data communications

Page 191: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

2.6.15 GPIB

• Listener: A device set to be a listener can accept data over the bus fromanother device. More than one listener at any one time is permitted. Alistener receives data when the controller signals it to read the bus.

• Talker: A device set to be a talker can send data to another device onthe bus. Only one talker can be specified at any one time. The talkerwaits for a signal from the controller and then places its data on the bus.

• Controller: A controller can set other devices as listeners or talkers orto take control. The presence of a controller is optional. For example, ifthere is only one talker and all other connected instruments are listeners,then no controller is required.

The General Purpose Interface Bus (GPIB) or IEEE 488 interface wasdeveloped in 1965 by Hewlett Packard for connecting multiple scientificmeasuring instruments together. Up to 15 devices may be attached to theinterface lines (or bus). One of the devices can be activated as the‘controller’. Control can be passed to another device if required.

• 8 data lines• 3 data control lines• 5 management lines• 8 ground lines

8-bit data can be transmitted in parallel, each bi-directional line carrying 1 Mbit/second. A maximumtotal cable length of 20 m with a maximumseparation of 4 m between devices is recommended.Bus extenders and expanders can also be used.

The interface consists of:

Devices may be configured as listeners, talkers and controllers.

Each device responds to commands sent over the data bus. Each device canrecognise its address when it appears on the data bus. The device address isusually set by dip switches or from software. The management of the bus isdone by the controller which typically contains a special purpose IC on aGPIB interface card.

IFCATNSRQRENEOI

DAVNRFDNDAC

Handshake

Control

Data

7

0

Data is put onto the data bus by a talker when no device has pulled NRFD(not ready for data) low (negative logic). DAV (data valid) indicates thatdata is ready, and all devices then pull NDAC (no data accepted) low untilthe data is read. The parallel connection of devices ensures that NDACgoes high again when all listeners have accepted the data.

GPIB connector

Newnes Interfacing Companion178

Page 192: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

2.6.16 USB

The range of peripheral devices now connected to personal computers areattached by serial, parallel and PS/2 ports, and the requirement for ease ofuse has resulted in the development of the Universal Serial Bus (USB).USB is designed to be a low cost, expandable, high speed, serial interfacethat offers “plug and play” functionality primarily for business andconsumer peripherals.Data transfer rates for the first implementation of USB were up to 12Mbps. USB 2.0 allows up to 480 Mbps making it suitable for real timevideo and audio, high resolution digital cameras and data storage devices.

• USB interconnect• USB devices• USB host

controller

A USB system consists of:The connection between USB devices andthe host, the data flow protocols, and themanner in which devices are addressed.

USB devices are either hubs, whichprovide attachments to other hubs or actualdevices. The host controller queries thehubs to detect the attachment or removal ofdevices. A unique bus address is assignedby the host when a device is connected.

There is only one host in anyUSB system. The hostcontroller sends a tokenpacket that describes the typeand direction of the data, thedevice address, and theendpoint number. The devicethat is addressed then receivesa data packet and respondswith a handshake packet.The USB transfers signal andpower over a four-wire cable.Differential signalling occursover two of the wires. Thereare three data rates:

• high speed at 480 Mbps• full speed at 12 Mbps• low speed at 1.5 Mbps

Host

Hub 1

Hub 2

Hub 3 Hub 4

Hub 5

Device

Device

Device

Device Device

DeviceHub 6

Device Device

Device

Device

1

2

3

4

5

6

7

Tier

A maximum of seven tiers is allowed. Tier1 is the root hub and Tier 7 can onlycontain devices.

1792.6 Data communications

Page 193: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

In the USB system, one device must be the host and this places somerestrictions on its use in an industrial setting. A simple modem, forexample, can be wired using a null modem connection and be used witha PLC or other RS232 supported transducer. With a USB system, acomputer must generally act as a host, even if communication is wantedonly from one device to another.

The ‘on the go’ (OTG) supplement to the USB 2.0 standard allows somedegree of peer to peer communication without the need for a fullyfeatured host.

In RS232 communications, the format of the data is not defined – it isusually ASCII text but need not be so. The USB uses layers of transmissionprotocols to transmit and receive data in a series of packets.Each USB transmission consists of: • token packet

• optional data packet• status packet

The USB host initiates alltransactions. The token packetdescribes the type of communication(read or write and the destination address). The data packet contains thedata to be communicated. The handshaking packet reports if the data wasreceived or transmitted successfully.

USB cable connections

1 Red 5 Volts

2 White D−

3 Green D+

4 Black Ground

Allows “bus-powered” devices tobe connected (no batteries ormains power needed).

USB is designed to be ‘plug and play’. When a device is plugged into thebus, the host detects its presence by signal levels on the data lines. It theninterrogates the new device for its device descriptor, assigns a bus addressto the device, and then automatically loads the required device driver.When the device is unplugged, the host detects this and unloads the driver.This process is called enumeration.

Firewire (IEEE 1394) is a serial interface standard originally developed by AppleComputer (ISB was originally developed by Intel). Firewire allows up to 400 Mbpsand is a competitor to ISB (when first introduced, Firewire was several times fasterthan the then USB standard). Like USB 2.0, the main consumer benefit is highspeed for video capture from digital cameras and camcorders without the need fordedicated video capture interface cards.

Newnes Interfacing Companion180

Page 194: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

2.6.17 TCP/IP

TCP stands for Transmission Control Protocol, and IP stands for InternetProtocol. TCP/IP is a set of protocols that allows computers tocommunicate over a wide range of different physical network connections.TCP/IP provides protocols at two different layers of the OSI ReferenceModel. In everyday terms, the world wide web (www) and email (SMTP)make use of TCP/IP to communicate over the internet which in turn runson a variety of packet switching network systems the most popular ofwhich is the Ethernet. The actual connections between host computers isdone by satellite, coaxial cable, phone lines etc. For interfacingapplications, the internet is useful for communicating commands andresults from a remote sensor, but would be unsuitable for a direct interfaceto the transducer due to the response time of the process.

7. Application

6. Presentation

5. Session

4. Transport

3. Network

2. Data link

1. Physical

TCP is concerned with sending and receivingpackets and assembling them into the correctorder. It is designed to be independent of theactual network characteristics.

IP is concerned with delivering packets of datathrough the internet. The IP isolates upper levelprotocols from the specific characteristics. It doesnot order packets in any way, but is simplyconcerned with sending a packet of data to therequested destination. IP addresses are assignedto specific devices on the network to identify themfor the receipt and transmission of data.

Packet switching protocols. Data Link Control(DLC), Ethernet. This layer is concerned with thetransmission of packets in a specific mode fordelivery over the mechanism of the physical layer.Characteristics of the Ethernet determine theresponse time of the network.

Wires, cables,microwave links.

Telnet, FTP (File Transfer Protocol), SMTP (Simple MailTransfer Protocol), HTTP (Hyper Text Transfer Protocol),etc. This layer defines the application that is used toperform the type of communication required by the user.IP addresses are decoded by a Domain Name Server(DNS) at this level.

1812.6 Data communications

Page 195: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1. What basic digital logic circuit forms the basis of a UART used forserial communications?

2. The RS232 serial interface is very popular because of its availabilityand simplicity. Without actually describing the sequence of events,describe the function of the six most commonly used signal lines.

3. What is a ‘null modem’ and under what circumstances should it beused?

4. In a UART, why would the receiver clock be made to oscillate 16times the rate of data transmission?

5. What is a parity bit?6. Why is a 232 line driver IC required for communications between two

UARTs which take place over an external signal cable?7. Why, in serial communications, is there a choice of 5, 6, 7 or 8 data

bits for the data being transmitted or received? (Hint: Investigate theASCII code for character transmission.)

8. What is the main advantage of the RS485 interface standard?9. What advantage would a GPIB interface have over an RS232

communication in an interfacing application?

2.6.18 Review questions

Newnes Interfacing Companion182

Page 196: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

183

Page 197: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Logicinstructions

2.7.1 Programmable logic controllers

Industrial processes have been traditionally controlled by electromechanicalsystems (i.e. switches and relays). An electromechanical control systemcontrols the output states according to the input states. The logic behind theswitching and the resultant actions depend upon way the switches and relaysare wired together. The overall function in these systems is not so easilychanged and the systems are not easily maintained.

In the late 1960s, digital controllers were introduced to allow some degreeof programming to control the sequence of operations required in anindustrial process. A programmable logic controller (PLC) examines itsinput states and turns off or on its outputs according to a pre-loadedprogram that can be easily altered to suit changed circumstances. Advancesin technology have resulted in programmable controllers that cancommunicate with each other, as well as receive and transmit control datato remote locations. Present day systems feature functional block diagramsand structured programming in a standardised way.

PLC devices have standardinput and output interfaces.Standard input interfaces allowdirect connection to processtransducers. Standard outputinterfaces allow directconnection to relays or circuitsthat energise process actuators.

PLC devices operate under programcontrol. A program consists of a series ofstatements or logic instructions called alist. The control unit scans the inputs andperforms logical operations according tothe loaded program and then switches theoutputs accordingly. The inputs are thenscanned again and the cycle repeats. Theresult is an industrial process.

5 V TTL24 V110 V240 V

24 V 100 mA110 V 1 A240 V 1 A240 V 2 A

Inputs Outputs

PLC

TransducersActuatorsProcess

A PLC itself consists of the control unit (or CPU) as well as connections forinput and outputs, RAM memory (≈10 Kb) and a power supply. Inputs areopto-coupled to the input circuits in the PLC to protect the PLC from noise.

Newnes Interfacing Companion184

Page 198: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

A PLC program consists of a series of instructions that represent logicaloperations performed on the inputs. The state of the outputs is set orcleared in accordance with the logical result of the program instructions.

2.7.2 Timing

Scan inputs

Update outputs

Since it takes a finite time for the PLC to read the inputs (input responsetime), process the instructions (execution time) and set the outputs(output response time), changes to the inputs can only be registered ifthey last longer than the scan time (input response time + execution time +output response time). If the input changes more rapidly than this, then thePLC may not detect the change and the required output may not be set.This is called a phasing error.When an input changes state, the resulting change in the output will takeplace, in the worst case, two scan times (less one input response time)later.

In some PLCs, the program is executed line by line. The control unit scans theinputs actually referenced by each program statement as it is executed. Theoutput named in each program statement is then updated according to the logicaloperation in the program statement and then held or latched in that state.

PLC scan times are usuallyquoted in terms of the length oftime to execute a 1024-byteprogram and depend upon theclock rate of the controller.Scan times are usually in theorder of 5 to 10 msec.

Executeprogram

statements

The states of all the inputs are copied into RAM before the programinstructions are executed. Instructions are then processed in sequence. Theresulting output states are stored in RAM. When the program execution iscompleted, the stored output states are transferred to the output terminals ofthe PLC.

Scan 1 Scan 2

Input

Output

Inp

Exe

Out

Inp

Exe

Out

1852.7 Programmable logic controllers

Page 199: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

The PLC inputs consist of input relays or contacts which may bephysically real devices or simulated as labelled contacts in the program.The outputs are called coils representing the coil of a relay. The outputscan take the form of transistor switches, triacs or relays. As well as inputsand output devices, the control unit also typically contains latches,counters, timers and registers for data storage. Some PLC devices alsohave analog I/O capability.

2.7.3 Functional components

Latch When set to true, the output of the latch will stay on untilthe latch is reset.

Counter Counts pulses at its input and sets the timer output to truewhen a preset number of counts have been registered.True at the reset input resets the accumulated count tozero.

Timer Output of the timer turns on or is true a preset number ofseconds after the input is true. When the input is set tofalse, the timer is reset and the output is set to false. Whilethe timer is counting down, the PLC continues to scan andexecute its instructions. Input and output errors can occurwith timers since the input to the timer may not beregistered until it is scanned. Further, the output devicemay not be energised until the PLC has completedexecuting the program.

Registers Used for storing data or the results of logical operations asbits (true 1 or false 0). Registers are similar to internalcontacts. The contents of registers may be shifted left orright. Data bits can be moved into and out of registers usinga MOV instruction.

A PLC can generally communicate with external devices using RS232serial communications. The PLC may be fitted with an RS232 serial portfor this purpose. Data may be sent to or received from the PLC. The datacan be stored in the PLC data memory.

The actual logic program run by the PLC is usually entered through akeypad or downloaded from a microcomputer. Before a program isexecuted, various levels of verification are performed to ensure that theprogram was transferred successfully into the CPU of the PLC. Varioussystems are employed to protect processes and plant in the event of a powerloss. PLC systems are designed to be robust and operate unattended in anindustrial environment.

Newnes Interfacing Companion186

Page 200: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

2.7.4 Programming

PLCs act upon list code instructions. To facilitate the creation of a listcode, ladder logic diagrams are used to simulate the existence and actionsof input and output devices. A ladder diagram consists of two vertical railsinside which are placed symbols for contacts, relays, functions, and logicaloperations on rungs. Logic flow (or current flow) is from left to right andtop to bottom on the diagram. An output on a rung is energised if there is acontinuous path of true logic leading back to the left (or positive) rail of theladder (logic continuity).

Contact

Coil End

X200 Y400

Addresses

Symbol ActionLD Evaluates to true if the physical contact it represents is

closed or on.

LDB Opposite to LD.

OUT Evaluates to true, and thus energises a normally opencoil, if there is a continuous “true” path from the left-hand side of the ladder to it.

OUTB Opposite to OUT

Listcode

Each rung must containone or more inputs andone or more outputs. Thefirst object on a rungmust be an input and thelast object on a rungshould be an output, acounter, timer or aninternal relay. The lastrung in a ladder diagramis an END instruction.

The PLC scans the ladder diagram from top to bottom and left to right. In aload instruction (LD) the physical state of a scanned input is determinedand the symbol in the ladder diagram evaluates to true if the physicaldevice is closed or on. The symbol may also be used for internal utilityrelays or switches that do not physically exist.

Basic instructions

Positiverail

Negative orground rail

Rungs

1872.7 Programmable logic controllers

Page 201: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

2.7.5 Ladder logic diagrams

Ladder diagrams can become quite complex. PLC systems generally havethe ability to perform math functions on data, apply Boolean operators, andstore data in registers or memory locations.Consider these simple examples:

X000 Y400X100

End

End

X000 Y400

X100

X000 Y400X100

End

End

X000 Y400

X100

Output Y400 is energised (true) aslong as inputs X000 AND X100are both closed (true).

Output Y400 is energised (true) aslong as input X000 is closed ORX100 is closed (true).

Output Y400 is energised (true) aslong as input X000 is closed ANDX100 is open (false).

Output Y400 is energised (true) aslong as input X000 is closed ORX100 is open (false).

LD X000 OR X100 OUT Y400 END

LD X000 AND X100 OUT Y400 END

LD X000 ORI X100 OUT Y400 END

LD X000ANI X100OUT Y400END

Ladder diagram List code

When X000 turns on (true) thentimer T300 begins counting down.After 10 seconds, switch contactsfor the timer T300 are closed (true)and output Y400 is energised(true).

LD X000 OUT T300K 10 LD T300 OUT Y400END

X000 T300

T300

End

Y400

10

An output is only energised whenthere is a continuous true path fromthe left-hand side to the right-handside of the ladder.

Newnes Interfacing Companion188

Page 202: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

The example below shows a timer circuit whose output device turns on andremains on for the time period when an input pulse appears at the input.This circuit uses an internal relay. Internal relays are coils and contactsthat are simulated by the PLC in memory. Like external relays, they consistof an output coil and a set of contacts that can be used as the input to otherobjects on a ladder rung.

In this example, when the input X000 istrue, there is logic continuity through thenormally closed timer contacts T300 to theoutput Y400. This true state is fed backinto the input to the normally closedcontacts of the timer. Thus, when the inputX000 goes false, the output Y400 remainson, it is latched by its own contacts.

X000

Y400

End

Y400

T300

10X000

T300

Now, when X000 goes false, a true signal is sent to the timer to begin thecountdown period. During the countdown period, the output device Y400remains energised by the latched path through the contacts Y400. When thecountdown period has expired, the normally closed contacts of T300become open, thus interrupting the logic continuity to the output Y400 andso Y400 is de-energised. The ladder logic above acts like a pulse extender.A short pulse on the input X000 can be extended into a longer pulseappearing at the contacts of the output Y400.Ladder logic diagrams can easily become unwieldy and difficult tomaintain unless a certain methodology is followed to give them structure.

X000

Y400

End

Y400

Y400

Y400

Y400Y400

All inputs goon the leftside.

All outputsgo on theright side.

Things to dowhen Y400 isenergised.

Internal relays,timers andcounters.

Logic that determineswhen the process iscompleted and resetsthe output.

1892.7 Programmable logic controllers

Page 203: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

2.7.6 PLC specifications

There are numerous PLC systems available. The table below gives typicalspecifications and features.

• 16 optically isolated AC inputs, 100 V−220 V, 50 Hz to 60 Hz.• 8 optically isolated DC inputs, 5 V−24 V.• 8 analog inputs, 0−5 V.• 2 high speed optically isolated inputs up to 100 KHz.• 8 AC optically isolated outputs, up to 220 V, 8 A.• 8 DC optically isolated outputs, 48 V, 8 A.• 32 timers, 16 on 0.01 second base, 16 on 1 second base. • 32 up or down counters.• 256 internal relays. • Real time clock with time and date.• RAM back-up.• Data logging for 16k bytes. • Programmable 4.5 digit LED display. • Internal 110 V/220 V AC power supply.• Ladder logic in EEPROM for 2 programs of 4k 32-bit words each. • Scan rate 7 msec/k 32-bit instructions. • Real time scan rate indicator.• Network and I/O expandable via RS485.• Heavy duty anodized aluminium alloy construction.• EMI immunity and efficient heat dissipation.• Standard DIN 43700 instrument case size.

PLC control panel for chilled water supply

Newnes Interfacing Companion190

Page 204: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

2.7.7 Review questions

1. The scanning operation that is the feature of a PLC can beconsidered to be similar to the multitasking mode of operation ofan event-based applications language like Visual Basic. Wouldyou agree?

2. Design a ladder logic diagram that switches on a refrigeratorcompressor motor when the temperature rises above a preset limitand switches it off when the temperature falls below anotherpreset limit.

3. Design a ladder logic diagram that will control a pedestriancrossing with a set of traffic lights. A press button on each side ofthe street act as inputs. “Red”, “Amber” and “Green” trafficlights, “Walk” and “Don’t Walk” indicator lights are the outputs.When a pedestrian presses a button momentarily, there is a 60second delay before the “Green” lights are extinguished and the“Amber” lights are illuminated. “Amber” is illuminated for 10seconds, then is extinguished, and “Red” is illuminated. There isnow a 2 second delay before the “Walk” signs are illuminated.“Walk” is illuminated for 60 seconds after which time it isextinguished and the “Don’t Walk” signs are flashed on and offfor 10 seconds. After 10 seconds, “Don’t Walk” is heldcontinuously on. At this time, there is a 2 second delay before theRed lights are extinguished and the Green lights are illuminated.The Green lights are kept illuminated if there is no momentarypress of the pedestrian button. If a pedestrian presses a buttonmore than once while the Green lights are illuminated,then the system only responds tothe first press. If a pedestrianpresses a button during the“Walk” and flashing “Don’t Walk”parts of the cycle, then thesepresses are ignored.

1912.7 Programmable logic controllers

Page 205: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

192

Page 206: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

This project is an analog to digital data acquisition system that readstemperature from a thermocouple and interfaces this to the computer’sserial port. No special computer interface card is required. This type ofinterface is suitable for relatively slowly changing physical quantities. Theinterface system requires a ±5 V power supply and a modest number ofintegrated circuits which are readily available from electronics partssuppliers. It can be used with virtually any PC equipped with a serial port.

2.8.1 Serial data acquisition system

ADC

UARTRESET

CLOCK

LINEDRIVER

Digital data toserial port

SAMPLEAND HOLD

THERMOCOUPLEINPUT AND COLDJUNCTIONCOMPENSATION

INSTRUMENTATIONAMPLIFIER

DACParts list:1 × ADC0804 A to D converter1 × 6402 UART1 × 7400 NAND1 × 232CPE RS232 line driver1 × 74HC04 hex inverter CMOS1 × 74HC393 CMOS counter1 × 4.9152 MHz crystal2 × 33 pF; 1 × 147 pF (or 3 × 47 pF);4 × 1 µF; 1 × 4.7 µF; 1 × 47 µF;2 × 3.3k; 1 × 10M; 1 × 100k;1 × 1k; 2 × 10k

1932.8 Data acquisition project

Page 207: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

ADC0800

0–5 V analoginput DB0-7

WR

INTR

+Vin

OscCLK

RDCS

−Vin

AGND

A negative pulse at INTRsignals the UART (TBRL)that data is ready and thusis latched. A 0−1transition at TRE indicatesdata has been sent andtriggers the ADC toinitiate a new conversion.TRE has to be pulsed lowto start the sequence.

6402 UART

74HC393Counter

74HC04Inverter

7400NAND

232Line

Driver

CLK

Reset pulse

RS232 outto serial port

TTL out

Osc

MR

TRC

TBR0-7

TRE

TROTBRL

T1in

T1out

CP1CP2

Q31Q02

PICLE2CLE1EPECRL

SBS

+5 V

(+10 space, −10V mark)

The ADC converts a 0−5 V analog signal to an 8-bit digital value (0−255).This digital value is passed through a UART which serialises the data into abit stream for transmission over a single wire to the computer’s serial port.

Data from the circuitappears as a serial bitstream at RD on thecomputer serial port.The data consists of astart bit, 8 data bits, and1 stop bit.Communicationssoftware can be used tocapture the data fordisplay or storage asdesired.

4.9152 MHz

Newnes Interfacing Companion194

Page 208: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

6. Now, we wish to indicate to the UARTthat data appearing at TBR1 to TBR8is valid and ready to transmit when theADC conversion is completed. Select asuitable signal line from the ADC andconnect to TBRL on the UART.

1. Connect an ADC0804 IC as shown in the figure below. Use +5 V for Vcc.2. Connect 2 V DC to +Vin (analog input) and measure the voltages that

appear on the digital outputs.3. Comment on the binary number indicated by these voltages (DB7 to

DB0).

2.8.2 Circuit construction

4. Position the UART on the laboratory breadboard and configure thedevice for 8 data bits, no parity, 1 stop bit.

5. Set CRL, PI and EPE to 1, and SBS,SFD, and RRD to 0. Use +5 V as Vdd.

7. We also wish to initiate a newconversion at the ADC after the data atthe UART has been sent. Select asuitable signal line on the UART andconnect to WR on the ADC.

Character lengthselect CLS1 CLS25 0 06 1 07 0 18 1 1

Parity PI EPENone 1 xEven 0 1Odd 0 0

SBS, stop bits, 0 for one,1 for two

10k

147 pF

ADC

080410k

+5 V

OSC

Digitaloutput

DB0

DB7

Analogsignal in

CLK

DGND

+Vin

−Vin

AGND

CS

RD

WR

Vref/2

INTR

1952.8 Data acquisition project

Page 209: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1234567891011121314151617181920

4039383736353433323130292827262524232221

VDDnot usedGNDRRDRBR8RBR7RBR6RBR5RBR4RBR3RBR2RBR1PEFEOESFDRRCDRRDRRRI

TRCEPE

CLS1CLS2

SBSPI

CRLTBR8TBR7TBR6TBR5TBR4TBR3TBR2TBR1TROTRE

TBRLTBRE

MR

6402

to linedrivercircuit

connect toDB0–DB7 atADC0804

8. Place the line driver 232CPE chip on the laboratory breadboard.9. Connect the TTL output from the UART to a TTL input on the

232CPE chip. Note: the 232 chip is a dual IC with two sets of separatedrivers. Select either T1 and R1 or T2 and R2.

10. Connect capacitors, resistors andsupply voltage to the 232CPE chipas required. Note polarity ofthe capacitors.

TTL outRS232 in

TTL in

TTL in

TTL out

RS232 in

+5 V

RS232 out

1 µF

1 µF

1 µF

3.3k

+C1+

V+

C1-

C2+

C2-

V-

T2out

R2in

Vcc

GND

T1out

R1in

R1out

T1in

T2in

R2out

232

3.3k

+

+

+1 µF

+5 V

+5 V

Newnes Interfacing Companion196

Page 210: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

11. Construct a crystal oscillator using high speed CMOS inverters74HC04.

12. Divide the clock signal down to obtain a baud rate of 9600 using a highspeed CMOS counter 74HC393.

13. Connect the stepped-down clock signal to the transmitter clock input(TRC) on the UART.

153.6 kHz (9600 baud)

76.8 kHz (4800 baud)

38.4 kHz (2400 baud)

CP1

MR1

Q01

Q11

Q21

Q31

GND

Vcc

CP2

MR2

Q02

Q12

Q22

Q32

74HC

393

CLK signal toUART is to be 16times the baud rate

19.2 kHz (1200 baud)307.2 kHz(19 200 baud)

74HC

0433 pF

10M

33 pF

+5 V

+5V

4.9152 MHz

1972.8 Data acquisition project

Page 211: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

14. Construct a master reset circuit for the UART using a 7400 NANDgate and associated components. Calculate suitable values of R1 and Cto give a time constant of about 2 sec.

15. Connect the output of the masterreset circuit to MR on the UART.

Time constant= 1/R1C

16. The interface circuit is now readyfor testing. The first step in testingthe circuit is to determine whetheror not there is a clock signal at theUART. Display the signal at TRCon a CRO and rectify any wiringerrors in the clock circuit.

17. Next, tie the analog input toground (0 V) and check thevoltages at the digital output of theADC. They should all be at 0 V.Rectify any wiring errors beforeproceeding.

18. Check the TTL signal at the outputof the UART (TRE). There shouldbe a +5 V pulse (the stop bit) aftera series of lows (0 V) which is thedata.

20. Now apply a small DC signal tothe analog input on the ADCand verify that the output fromthe 232 line driver is consistentwith that applied. (Themagnitude of the byte appearingas data in the bit stream on theoutput of the line driver shouldbe consistent with themagnitude of the DC inputsignal from 0−5 V range.)

19. Check the signal at the outputof the line driver to ensure thatthese same logic levels arerepresented in −10 to +10logic.

to MR

R1

C

7400

+5 V

1k

Newnes Interfacing Companion198

Page 212: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

21. Configure a 25 pin or 9 pin connector cable as a null modem, withhardware handshaking (connect RTS on the computer serial port plugto one of the spare RS232 inputs on the line driver IC).

22. Now, some handshaking is required. When the receive buffer is full,RTS is set high by the receiving computer or our applications program.When the receive buffer is empty, RTS is set low. When the transmitbuffer on UART is empty, UART sets TRE high. When transmission isin progress, TRE is low. We wish to arrange things so that when RTSis low and TRE goes from low to high, the WR signal on the ADC goesfrom low to high and remains high during conversion.

On our serial interface board,the RTS line will be controlledby us by connecting it to theappropriate pins on the otherICs. However, it must be firstpassed through the line driverto convert the RS232 logiclevels to TTL logic.

Serial interfacecircuit board 232line driver.

Plug to computerserial port

RDRTSCTSDTRDSRDCDRIGND

TD

Receivingcomputer

FromRS232out

ToRS232in

When the receive buffer is full, RTS is set high by the receiving computer(−10 V on RS232 signal lines from line driver). When the receive buffer isempty, RTS is set low (+10 V on signal lines). When the transmit buffer onthe UART is empty, the UART sets TRE high. When transmission is inprogress, TRE is low. We wish to arrange things so that when RTS is lowand TRE goes from low to high, the WR signal on the ADC goes from lowto high initiating a new conversion WR and remains high during conversion.

+5

RTS+5 full0 empty

High when buffer empty (RTS low),otherwise low when buffer full.

TRE

TRE is set low by UART while transmissionis in progress. TRE goes high when transmitbuffer is empty signalling completion oftransmission of character.

1992.8 Data acquisition project

Page 213: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Consider the logic circuit on the previous page. When transmission is inprogress, and the buffer is empty or full, output is high. When thetransmission is complete, the output is low if the buffer is empty, otherwisehigh. Thus, if this output goes low, transmission is complete and receivebuffer is empty, therefore a new conversion should be initiated. However, anew conversion requires a low to high transition on WR. Hence, if thissignal is inverted, then the required action is obtained. That is, whentransmission is complete and buffer is empty, final output goes from low tohigh and remains high. A new conversion is initiated, which whencomplete, INTR signals the UART to transmit. TheUART sends TRE lowwhile transmission is in progress which sends WR low.

4.7 µF1k100k

to TRE

to MRto WR

RS232 in

+5V

RS232 out toRD on serial port

1µF

1 µF

1 µF

3.3k

+C1+

V+

C1−

C2+

C2−

V−

T2out

R2in

Vcc

GND

T1out

R1in

R1out

T1in

T2in

R2out

232 3.3k

+

+

+1 µF

RTS fromserial port

From TRO

7400

+5 V

An inverter can be fashioned froma NAND gate as follows:

Newnes Interfacing Companion200

Page 214: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1. In this part of the project, an assembly language program will bewritten to perform the following steps:(a) Initialises the serial port (COM1 or COM2).(b) Causes RTS to be set at logic high (−10 V on RS232 signal line).(c) Reads in one byte from the serial port.(d) Displays the value on the screen.(e) Causes RTS to be set logic low (+10 V).(f) Allows the program to be terminated by pressing any key on the

keyboard.

To initialise the serial port, BIOS service routine 0 is used. The port to beinitialised (0 for COM1, 1 for COM2) is specified in the DX register. Theinitialisation parameters are assembled into a byte from the informationgiven in the table.

The service to be called (0) is placed into AH. The byte containing theinitialisation information is placed in AL. The serial port service is calledthrough interrupt 14H. Thus, to initialise the serial port COM2 to 9600baud, 8 data bits, 1 stop bit and no parity, the following assembly languageinstructions are required:

MOV DX,01H ;SELECT COM2MOV AH,0 ;INITIALISE SERIAL PORTMOV AL,0E3H ;9600,N,1,8INT 14H

There are four BIOS services available for the serial port. The number forthe service to be called is placed into AH. Parameters or data for theservice are placed in AL. Interrupt 14H is called, and any results placed inAL (or AX for service 3).

Assembly language

In this part of the project, a computer program is required to operate theserial data acquisition system. The program is to operate the control linesand data signal line of the serial port. Such a program can be implementedin low level assembly language or an applications language like BASIC.The procedure here assumes that the serial data acquisition system has beenbuilt and is working properly. This can be verified using an oscilloscope.With RTS from the computer’s serial port held low (+10 V on actual signalline), then there should be a bit stream of data at RD.

2.8.3 Programming

2012.8 Data acquisition project

Page 215: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

2. Now, the serial interface board is controlled by a signal on thecomputer’s RTS line. To start analog to digital conversions, the voltageon the RTS line needs to be set at −10 V (which is TTL logic high).This is called hardware handshaking. There is no BIOS serviceavailable which controls RTS and so writing directly to the modemcontrol register (MCR) will be necessary. To start conversions, a logic1 is placed in the RTS bit of the MCR (and OUT2 is also set to 1 toallow the BIOS routines to work).

Purpose COM1 COM2Tx,Rx data 3F8 2F8Interrupt enable 3F9 2F9Interrupt ident 3FA 2FALine control 3FB 2FBModem control 3FC 2FCLine status 3FD 2FDModem status 3FE 2FE

Determine a bit pattern and hence a hex number to write to the MCR toenable conversions. Then determine the hex number to write to theMCR to inhibit conversions. Note: A logic 1 in the RTS bit sets the

RTS logic level low (+10 V on signalline) which starts conversions on theinterface card.MCR (Modem Control Register)

7 0

DTRRTSOUT 1(unused)

OUT 20 deactivate interrupt1 activate interrupt

Loopback0 normal operation1 loopback mode

Bits Baud7 6 5 Rate0 0 0 1100 0 1 1500 1 0 3000 1 1 6001 0 0 12001 0 1 24001 1 0 48001 1 1 9600

Bits Parity4 30 0 none0 1 Odd1 0 None1 1 Odd

Bit No.2 stop bits0 one1 two

Bit Data1 0 bits0 0 unused0 1 unused1 0 71 1 8

BIOS services0 initialise serial port 1 send one character2 receive one character3 read serial port status

Despite these services beingavailable, they are actuallyparticularly unhelpful as weshall see.

Newnes Interfacing Companion202

Page 216: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

MOV DX,02FCH MOV AL,0AHOUT DX,AL

OUT DX, AL or AX

IN AL or AX, d8/DX

3. The hex codes which set and clear the RTS line need to be written tothe MCR which, for COM2, is located at I/O port address 2FCH. TheMOV instruction cannot be used for this since MOV writes data toeither registers or regular memory locations. The assembly languageinstructions IN and OUT are used to write to port addresses.

Now, the OUT instruction has two forms. The first form is:OUT d8, AL or AX

d8 is an 8-bit port address from 0 to 255 which is fine if a write to aport with an address in this range is required. If a write to a portwith a higher port address is needed, then this 16-bit number needsto be loaded into DX and then the OUT statement is used to obtainthe address from DX. Thus, the second form of the statement is:

A byte or a word is written depending on whether AL or AX isspecified as the source. To write a byte to location 2FCH, the byte isloaded into AL, and the number 2FCH is loaded into DX and thus:

4. To read in a byte from the serial port, the BIOS “receive one character”service and call interrupt 14H can be used. However, when this is used,interrupt 14H clears the MCR and control of RTS is lost. Thus, RX/TXregister needs to be read (located at the I/O port base address 3F8H or2F8H) directly with the IN instruction.

The IN instruction has a very similar syntax:

The source is specified by either the I/O port address in DX or an 8-bitnumber directly (for ports 0−255). The byte read is written to AL. IfAX is specified as the destination, then a word is read from the port. Inthis case, the port only gives us a byte to read (i.e. I/O port address3F8H or 2F8H contains 1 byte read from the serial port receivebuffer). Thus, AL must be specified as the destination.

2032.8 Data acquisition project

Page 217: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

5. The serial port can now be initialised (using a BIOS interrupt call),conversions can be started and stopped (using OUT to the MCR) anddata can be read (using IN). It would be convenient to display the byteon the screen and also to allow the user to exit the program by pressinga key. These last two features can be readily incorporated using BIOSservice routines.

MOV AH,01H ;KEYBOARD SERVICEINT 16HJNZ END JMP READ

Keyboard services are called through interrupt 16H. The service to becalled is specified in AH. We are interested in service 1 which reportswhether or not there is a character in the keyboard buffer. If there is acharacter in the buffer, then the service sets the zero flag (ZF) to 0. Ifthere is no character in the keyboard buffer, ZF is set to 1. A jumpstatement can then be used to terminate the program.

Video services are called through interrupt 10H. To write a character tothe screen, there are a number of services available. One that can beused is service 9H. This service writes an ASCII character to the screenat the current cursor position and does not advance the cursor position(other services automatically advance the cursor position so that thescreen would be filled with data in our present application as characterswere read from the serial port). The character to be written to thescreen is specified by the number in AL. The service to be executed isspecified by the number in AH.

MOV AH,9H ;OUTPUT SCREEN SERVICEINT 10H ;BYTE TO OUTPUT IS ALEADY IN AL

Note: The video BIOS services allow a character to be written to the screen. Acharacter means an ASCII character. That is, the hex number in AL is treated asan ASCII code and the matching character symbol appears on the screen. Tohave the actual number appear, rather than the ASCII interpretation of thatnumber, then one has to analyse the number and have the program output theASCII codes corresponding to each digit in the number to be displayed.

Newnes Interfacing Companion204

Page 218: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1. Write a program in BASIC that will perform the following steps:

(a) Accept user input which specifies baud rate and COM port.(b) Initialises the serial port (COM1 or COM2).(c) Causes RTS to be set at logic high (−10 V on RS232 signal line).(d) Causes RTS to be set logic low (+10 V).(e) Tests to see how many bytes are waiting to be read.(f) Tests to see how much space is left in the input buffer.(g) Reads in 1 byte from the serial port and displays the value in

decimal on the screen.(h) Brings all of the above functions together so that the program

continuously displays the byte read at the serial port on the screen.At the same time, the program is to halt and continue transmissionof data from the serial interface board if the buffer becomes too fullor empty as required.

Note: Make your program user-friendly. That is, allow the program tocontinuously read the serial port until the user presses Esc at which timethe program will close the file handle and exit gracefully to the operatingsystem or the BASIC interpreter prompt.

BASIC

Questions:(a) Calculate the aperture time and maximum frequency obtainable without

aperture error for the conversion time you are using in this circuit.(b) Calculate the required baud rate that would provide this maximum

frequency.(c) Compare with the maximum frequency obtained from your circuit.(d) Suggest a method (or two) by which the maximum frequency may be

increased.

2052.8 Data acquisition project

Page 219: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

−V

+V

1. Construct a sample-and-hold control circuit using a 7476 JK flip-flopas shown but do not connect R to INTR yet. Rather, supply +5 V to Rfrom the power supply.

2. Test the operation of the flip-flop by providing a negative start pulseand observing the Q output. Then put 0 V at the R input and observethe Q output.

3. Make sure the flip-flop is working correctly, then disconnect R fromthe ±5 V supply and connect to INTR on the ADC.

4. Connect the LF398 sample-and-hold IC as shown:

2.8.4 Sample-and-hold

Analog in

+5V

0.01 µF

to TBRL

to handshakecircuit (or TRE)

Logi

cin

put

Output

Parts list:1 × 7476 JK flip-flop1 × LF398 sample-and-hold1 × 0.01 µF capacitor

7476

CLK1

Vcc

S1

R1

J1

CLK2

S2

R2

GND

K1

Q1

Q1

J2

Q2

Q2

K2 0804INTR

WR

+Vin

LF398

1

2

3

4 5

8

7

6

Newnes Interfacing Companion206

Page 220: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

The LF398 requires a bi-polar voltage supply. Ideally, this needs to bea few volts greater than the maximum signal voltage. ±10 V would beacceptable, but ±5 V will suffice if a ±10 V supply is unavailable butthe output signal will be reduced in amplitude.

• Start pulse initiates conversion since it is connected directly to WR.• Since SET is high, and initially, RESET is high, the output Q will

respond to the clock going low and since J is high (with K low), Q issent low. Sample will be latched on clock signal going low. Conversionactually begins when clock (WR) goes back high.

• At the end of conversion, INTR goes low which sends a low to RESETsending Q high independent of the signal at J and sending sample andhold to “sample”.

Questions:(a) Make some comment about the width of the steps given by the LF398

IC in relation to the frequency of the input signal.(b) State whether or not the inclusion of a sample-and-hold circuit

improves the maximum frequency which can be digitised withoutaperture error.

(c) Is there are any other aspect of your system that might cause the upperlimit of frequency to be rather low?

5. Using a sine wave signal, compare the waveforms (using a CRO) onthe input and the output of the LF398 sample-and-hold IC. Draw thesewaveforms (you may like to increase the frequency of the signal toabout 100 Hz to obtain a clear display). Measure the width (inmicroseconds) of the steps in the LF398 output.

6. Investigate the signal appearing on the logic input of the LF398 andnote the time between each signal pulse.

7. Compare the upper limit to the frequency response of the A to Dsystem with and without the LF398 in use.

The sequence of operations is:

2072.8 Data acquisition project

Page 221: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

ToRS232 out

For the purposes of demonstration, the serial data acquisition system can beeasily modified to include a digital to analog facility. Digital data from thecomputer will be sent (via the line driver IC) to the receive register of theUART. This digital data can then be converted to an analog signal using theDAC0800 IC and monitored on a voltmeter or oscilloscope.

2.8.5 Digital to analog system

Serialinterfacecircuit board232 linedriver.

Plug tocomputerserial port

RDRTSCTSDTRDSRDCDRIGND

TDFromRS232 outTo RS232in

To RS232in

1. The first step in our DAC converter is to obtain a digital signal fromthe serial port of the computer. Connect the TD signal line from thecomputer serial port to an available RS232 IN pin on the 232 linedriver. Connect the corresponding TTL out to pin RRI (receive registerinput) on the 6402 UART.

2. Connect CTS from the computer serial port to an available RS232 out.Set CTS high so that the sending computer will send data continuously.Thus, connect the corresponding TTL IN to +5 V on the circuit board.

3. Connect the DAC0800 into the circuit as shown with the digital inputsbeing connected to the digital outputs from the UART. Also, connect aclock signal to the receiver circuit on the UART by connecting pin 40to pin 17.

4. Attach a voltmeter to Vo.5. Modify your interface program to include a write operation. As a

demonstration of the DAC operation, the overall procedure is first tofeed in an analog signal to the ADC and transmit the digitised output tothe computer. Then the computer is going to send the digitised signalback to the circuit board and the DAC is going to convert the signalback into an analog output.

Parts list:1 × DAC0800 D to A converter2 × 4.7k; 2 × 10k1 × 0.01 µF; 2 × 0.1 µF

Newnes Interfacing Companion208

Page 222: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

lsbmsb

Vo

+5 V10k

10k

to pins RBR8 to RBR1 onthe 6402 UART

to 0−10Vadjustablesupply or+5 V fixed

Vref

0.01 µF0.1 µF

0.1 µF

−5 V

+5V

5k

Questions:(a) Compare the analog output voltage level from the DAC

for 0 V and a steady 5 V on the input to the ADC. Canyou determine the significance of Vref on the DAC?

(b) Observe the output from the DAC on a CRO when a sinewave is fed into the input of the ADC. Comment on thedifferences in the shape of the two wave forms.

6. With a steady 0−5 V signal applied to the ADC input, and the interfaceprogram running, measure the output voltage of the DAC and adjustVref (if an adjustable power supply is available) so that 255 or FF on theinput to the DAC gives +5 V on the analog output. Vre = 2.3 V shouldbe about right. If no adjustable power supply is available, then set Vrefto +5 V and record the analog output voltage for 0 and FF on the digitalinputs.

7. Replace the steady DC input analog signal with a sine wave outputfrom a signal generator. Remember, the sine wave input to the ADChas to be positive going always and swing between 0 and 5 V.

8. Attach a CRO to Vo and monitor the analog output signal.

VLC

Iout

V−

Iout

B1

B2

B3

B4

CMP

Vref−

Vref+

V+

B8

B7

B6

B5

DAC

0800

5k

2092.8 Data acquisition project

Page 223: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Newnes Interfacing Companion210

Page 224: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

211

Page 225: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

3.0 Signal processing

The signals from a transducer are generally of very low magnitude. Toprepare them for the computer interface, they must be amplified to anacceptable level and filtered to eliminate unwanted noise. This is theprocess of signal processing.

In Part 1 of this book,we are mainly interestedin transducers.• A sensor is a device

which responds to aphysical stimulus

• A transducer is adevice which converts aphysical stimulus toanother form of energy(usually electrical)

Physicalphenomena:SoundMeter readingLED indicatorDigital displayChart recorderVDU output

Physicalphenomena:TemperatureVoltagePositionVelocityForcePressureRadioactivityLight intensityResistanceHumidityGas concentrationMagnetic fieldFrequencySound level

Actuatorprovides aphysical

response toelectrical signal

Actuator

Optionalfeedback

Transducer(sensor and

preamplifier)

Amplifier andsignal

conditioning

Computerinterface

Part 2 of thisbook isconcerned withcomputerinterfacing.

Part 3 of thisbook coversinstrumentationand signalprocessing.

Newnes Interfacing Companion212

Page 226: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

213

Page 227: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

3.1.1 Instrumentation

Qi Q1 Q2 Q3

Input Output

Q1 = f(Qi) Q2 = f(Q1) Q3 = f(Q2)

It is desirable to have linear relationships between the inputs and outputs ofthe various processes so that Q3 = K1K2K3Qi.

In practice, errors and noise are transmitted at each step along with thesignal of interest. The process of instrumentation is to maximise thetransmission of signal and to minimise the errors and noise. The process isconcerned with:

Instrumentation is concerned with producing a measurable output from thesignal provided by a transducer. This is usually done through a series ofsteps or processes, starting with the transducer signal or input, Qi.

• the electrical nature of signals and methods of measurement• signal processing by the application of a transfer function to

provide amplification and filtering• the origin and nature of noise in the signal• signal recovery – filtering, averaging, smoothing, etc.

An important issue in connecting a transducer to a preamplifier is toensure that maximum signal is transferred by a process called impedancematching.

∆Vs – signalactuallyproduced bysource

∆Vin – signalactuallyamplified

Ideally, Rin >> Rs because otherwise, negligible ∆Vin appears at theamplifier. That is, if RS >> Rin, then most of the voltage variations ∆VSappear across Rs and not at the amplifier input. Amplifiers should have ahigh input impedance Rin compared to Rs, the output resistance of thesource.

Vs

Rs

~

Vin

Rin

AmplifierTransducer

Newnes Interfacing Companion214

Page 228: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

3.1.2 Transfer function

Input signalfrom

transducer

Outputresponse to

meter orrecorder

C

R

Vin(t) Vout(t)

There is a definite relationship between the input signal S(t) and outputresponse R(t) of an electronic circuit. The relationship is called thetransfer function.The transfer function is the ratio of the output voltage over the inputvoltage. This is a general definition and includes any phase effects thatmight be present in the circuit. For example, for the simple RC low passfilter shown below, the transfer function is:

RCj11

VV

in

outω+

=

Vout and Vin are eitherpeak or rms values andare vector or phasorquantities. j is thesquare root of −1, thatis, this equationcontains complexnumbers.

Later, we shall see how the transfer function for a wide variety of circuits(mainly filter circuits) can be obtained easily using operator notation. Thetransfer function for a particular filter circuit can be used to modify thesignal being measured so as to eliminate noise (i.e. unwanted information).The mathematical representation of the transfer function allows the effectof various filter and amplifier circuits to be analysed and designed beforeany actual circuit is constructed.

Transferfunction

2153.1 Transfer function

Page 229: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

3.1.3 Transforms

Many physical phenomena can be described by differential equations,that is, equations which involve derivatives. A short-hand way of writing‘the derivative with respect to’ is to use the differential operator. Forexample:

Dydxdy

=

Here, D is a differential operator which, when applied to a function y(x),yields a new function in x. The differential operator may be quite complex,involving derivatives of higher orders. For example:

432

2

23

3

14

4

o adxda

dxda

dxda

dxdaD ++++=

thus

yadxdya

dxyda

dxyda

dxydaDy 432

2

23

3

14

4

o ++++=

After the operator has been applied to the original function, a new functionis formed. That is, the original function has been transformed into anotherfunction.

The differential operator is very useful for the treatment of many types ofdifferential equations. Another type of transform is the integral transformoperator T which has the form:

y*D = Y

Originalfunction

OperatorNew function

( )[ ] ( ) ( ) ( )sFdtt,sKtftfT == ∫∞

∞−

Here, f is a function of t which is transformed by the operator T. K is afunction of the variables s and t. The integration produces a new functionof s only and is the integral transform of the original function f(t). Thefunction K(s,t) can take many forms, and an especially interesting one isthat defined by:

( )ste

0t,sK−

=

=The resulting integral transform is called theLaplace transform L[f(t)] of the function f(t).

t<0

t≥0

an are constants

F(s) is the transform of f(t)

yDdx

yd 22

2=and

Newnes Interfacing Companion216

Page 230: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

3.1.4 Laplace transform

If the function f is a function of t, then the Laplace transform is defined as:

( )[ ] ( ) dtetftfL0

st∫∞

−=

The resulting integral, that is, L[f(t)], is a function of s only: L[f(t)] = F(s).F(s) is the Laplace transform of f(t). The symbol ‘L’ is the Laplaceoperator which acts on f(t) to give the transformed function F(s).A particularly interesting case is when f(t) is a periodic function, sayf(t) =sinωt:

[ ]

22

0

st

s

dte tsintsinL

ω+

ω=

ω=ω ∫∞

Similarly,

s > 0

[ ] 22sstcosLω+

Why are Laplace transforms important to us? Because they allowdifferential equations to be solved using algebraic expressions involvingoperators. We’ll see how this works in a moment. For now, consider yetanother interesting Laplace transform, that of L[1].

[ ]

s1

es1

dte1L

0st

0

st

=

−=

=

∫ Well, the question now is,“What is s”? Answer: It dependson the problem being analysed.For sinusoidal signals, it isappropriate to let s = jω.

The results are shownhere without showingthe working.

s > 0

Why bother with transforms? A particular input signal in the time domainmay be transformed into another signal, or function, in the frequencydomain. The transformed signal may then be operated upon by a filter andthen transformed back into the time domain for display. The transform of asignal gives information about the composition of the signal.

2173.1 Transfer function

Page 231: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

3.1.5 Operator notation

Let

s1dt

sdtd

=

=

∫and

‘s’ is an operator. In this case, a“differential” operator since theapplication of s to a functiontakes the time derivative of thatfunction.

Consider an integrator circuit:dtV

RC1V inout ∫=

Vin Vout

It can be shown that the outputvoltage is the time integral of theinput voltage:

t

t

Vin

Vout

If the input signal is a sine wave, then the output signal is a cosine wave(whose amplitude decreases with increasing frequency of the input signal).It can be shown (see page 218) that the amplitude and phase relationshipbetween Vin and Vout has the form (in complex number notation):

inout VRCj11V

ω+

=

dtVRC1V inout ∫=

when RC is large.

When RC is large, then:

inout VRCj

1Vω

But,

in

inout

VRCs

1

dtVRC1V

=

= ∫

Thus,

It appears therefore that in thisapplication, s = jω.

compare

Similarly for a differentiator,

dtdVRCV in

out =

whenRC issmall.

and it can be shown:

inout V

RCj11

1V

ω

+

=

When RC is small, then, with s = jω:

in

inoutRCsV

VRCjV=

ω≈

Is this s the same as that in theLaplace transform?

C

R

Newnes Interfacing Companion218

Page 232: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

3.1.6 Differential operator

Now, if s = jω, and s also is a differential operator, then exactly whatis ‘s’ ?Consider the function:

sy

sedtdy

ey

st

st

−=

−=

=

That is, ‘s’ is a differential operator for this function. Thus:

dtds =

That is, in the Laplace transform, where K(s,t) = e−st, s can be considereda differential operator and not just an ordinary everyday variable.

For sinusoidal periodic functions, we can let s = jω and still have s act likea differential operator. Thus, the s-domain analysis allows us to carryfrequency and phase information (for frequency domain analysis) ordifferential time information (for time domain analysis) in our calculations.

To analyse a circuit, the circuit is transformed into the s-domain, and thenecessary algebra performed (which is usually more manageable) and theresults transformed back into the frequency or time domain as required.

This procedure works because in the Laplace transform applied toperiodic sinusoidal functions, s is a differential operator and is alsoidentified with the product jω.

On the previous page, we saw how this dual nature of s was consistentwith the response of a passive integrator. Let us now apply the techniqueagain to the passive integrator and also the passive differentiator.

2193.1 Transfer function

Page 233: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

3.1.7 Integrator – passive

QC1R

dtdQV

IdtQIdtdQ

VVV

VCQV

in

CRin

Cout

+=

=∴=

+=

==

This is a 1st order ‘differentialequation’ involving differentialswith respect to ‘time’.

( )

RCs11

VV

RsV

C1

CQV

RsQ

QC1RsQV

sdtd

in

out

C1

in

out

C1

in

+=

+=

=

+=

+=

=

Now,

thus

This equation is a transferfunction in s. This is notdifferential equation, butsimple algebraic expressioninvolving the differentialoperator s. Operator notationallows us to avoid differentialequations in the time domainand complex algebra in thefrequency domain.

( )

( )

21

VV

1CRjRC1

11CR

CjR1

jC

1R

jC1

VV

jC

1I

jXIV

jC

1RI

jXRIIZV

in

out

222

in

out

Cout

C

in

=

ω+=

ω−=

ω−

ω

=

ω−=

−=

ω−=

−=

=

then

ω-domain analysis

3 dB point

Time domain analysis

let

complicatedalgebra

s-domain analysis

Vin Vout

C

R

Newnes Interfacing Companion220

Page 234: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

3.1.8 Differentiator – passive

QC1R

dtdQV

dtdQI

IdtQ

dtIC1IR

VVVVV

in

CRin

Rout

+=

=

=

+=

+=

=

C

R

Vin Vout

s-domain analysis

RCs1RCs

VV

1V

RsVRsV

RsQV

RsQ

QC1RsQV

sdtd

in

out

RsC1

in

C1

inout

out

C1

in

+=

+=

+=

=

+=

+=

=

Now,

Thus

Transfer function in s

ω-domain analysis

( )

jXRR

VV

IRVjXRIV

cin

out

out

Cin

=

=

−+=

21

VV

1CR1CR

CRC1R

R

jC

1R

R

in

out

222

222

=

ω=

ω

+

=

ω

let

3 dB pointIt appears that s = jω isconsistent with an ordinarycomplex number analysis of thetwo circuits. Next we will see the‘s’ notation used in the analysisof active filter circuits.

Time domain analysis

2213.1 Transfer function

Page 235: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

The transfer impedance of a network is defined as the ratio of the voltageapplied to the input terminals to the current which flows at the outputterminals when the output is grounded.

C

R

Vin Vout

C

RVin Vout

In these simplecases, the transferimpedances are:

jC

1ZTω

−=

RZT =

3.1.9 Transfer impedance

Newnes Interfacing Companion222

Page 236: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

4. The voltage at the input ofthe following filter issuddenly stepped from 0 to+5 V. Sketch the resultingoutput voltage as a functionof time and calculate the timerequired for the output tosettle to within 0.1 V of itssteady state output.

5. Using integration by parts (twice), show that

[ ]22s

stcosLω+

Hint:

tsin1v

tdtcosdvsedu

eu

duvuvdvu

st

st

ω

ω

=

ω=

−=

=

−=

∫∫

6. Using Euler’s formula, find L[cosωt]:

tsinjtcose tjω+ω=

ω

(Hint: L[cosωt] is the real part of the expression)

7. If ( )10s2s

1sF 2++

= find the inverse Laplace transform given that:

( )( ) ( )( )asFLesFL 1at1−=

−−−

and here letting a = 1.

0.1 µF

5k

Vin Vout

2. Design a simple RC filter which will attenuate 50 Hz ‘hum’ by 40 dB.Determine the effect of this filter on the following AC signals: (a) 500Hz, 0.8 V rms (b) 10 kHz, 1.2 V rms

3. Calculate the centrefrequency of thefollowing bandpass filtercircuit:

2 µF

100Ω

Vin Vout0.5H

3.1.10 Review questions

1. A transducer has an output resistance of 1.2 MΩ. What is the minimuminput resistance required for a preamplifier connected to this transducer ifat least 95% of the signal emf is to be applied to the preamplifier input?

(Ans: 23 MΩ)

(Ans: −20 dB, −1 dB)

(Ans: 160 Hz)

(Ans: 1.15 msec)

2233.1 Transfer function

Page 237: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1. Connect a 741 op-amp to an appropriate power supply and connect thenon-inverting input to ground and the inverting input to a variable DCvoltage source. Describe what happens at the output when the inputvoltage is swept from −1 V to +1 V.

2. Sweep the voltage again slowly and determine the input voltage (towithin a millivolt) when the output voltage is zero – you may have tomodify the circuit slightly to obtain the best estimation of this cross-over voltage.

3. With the non-inverting input still grounded, apply a small AC signal tothe inverting input and measure the open-loop gain as a function offrequency. Record your readings in a table, and then plot gain in dBagainst log of frequency.

4. Determine the open-loop bandwidth of the op-amp.

741

3.1.11 Activities

-

+

+Vcc

Vout

−Vcc

−Vin

+Vin

O/N

O/N-

+

+Vcc

−Vcc

Vin

Vout

Vout

Rin

Rout

Newnes Interfacing Companion224

Page 238: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

5. Construct a simple inverting amplifier with a gain of 100. Check theinput offset voltage and connect a nulling circuit to eliminate anyoffset.

6. Check the voltage at the inverting input and comment on its value.7. Measure the frequency response of the amplifier. Determine the

bandwidth.8. Measure the input resistance of the 741 IC by altering the circuit to a

non-inverting amplifier configuration with a gain of 50.9. Measure the output resistance by connecting a 100 Ω resistor to the

output and to ground and determining the change from open circuitoutput voltage.

10. Alter the circuit to have a gain of 10 and measure the frequencyresponse and input and output resistances. Compare with previouslymeasured quantities and comment.

Offset null adjustment:Ground the input Vin. Turn theadjustment pot while observingVout on an oscilloscope. A range ofseveral volts each side of zeroshould be obtainable. Adjust thepot for zero on the output. 1 µFcapacitors may be connectedbetween each power supply pinon the 741 to reduce RF pickup.

+

Vin

Vout

R2

R1

I−Rin

Rout

−Vcc

10k

Inverting amplifier

+

Vin

Vout

R2

R1

I−Rin

Rout

−Vcc

10k

Non-inverting amplifier

2253.1 Transfer function

Page 239: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

11. Construct a difference amplifier with a gain of 40.12. Measure the frequency response and bandwidth of the amplifier.13. Having measured the difference gain, devise a method to measure the

common mode gain of the amplifier and then determine the commonmode rejection ratio.

14. Measure the input resistance at each input and comment.

Difference amplifier

+

V1

R2

R1

Vout

R3=R1

V2

R4=R2

1

2

21

outd R

RVV

VA −=

=

Newnes Interfacing Companion226

Page 240: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

227

Page 241: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

• can incorporate gain• loading is not such a problem• cascading of filters for 2nd

order• don’t have to use inductors

(which are expensive, requirelarge currents, generate backemfs)

• tuning of filters can be done byadjusting resistors

Advantages:Active filters – op-amp circuits

Passive filters – RLC circuits

Two 1st order filters cascaded together produce a 2nd order filter:

Input Z of 2nd stage = output Z of 1ststage. To minimise loading, R2 >> R1and C2 << C1.

1st order filter (1st order differentialequation can describe the filter).

ω

Roll off20 dB/decade

ω

Roll off40 dB/decade(if no loading)

3.2.1 Filters

C

RVin Vout

C1

R1Vin Vout

C2

R2

+

Vin

Vout

Z2

Z1

0 V

Newnes Interfacing Companion228

Page 242: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

R R

R

V2

Vin

I1

I2

RCs1RZ

+

=

( )

( )

( )

( )RCs2RZ

ZRCs111RCs1R

IV

RCs111RCs1RI

RCs1RR

RRCs1RI

ZRIIZIRV

RRCs1RII

RIRCs1RI

IZV

T

T2

in

2

2

in

2

2

2

+=

=

+++=

+++=

++

+=

+=

+=

+=

=

+=

=

Transfer impedance

The transfer impedance of anetwork is defined as the ratio ofthe voltage applied to the inputterminals to the current whichflows at the output terminalswhen the output is grounded.

Now,

with RHSgrounded

A similar analysis for a highpass network yields

+==

RCsRCs21

Cs1

IVZ

2

inT

Texts on this subject often providetables of transfer impedances forstandard network arrangements whichcan then be easily combined (in the s-domain) for a particular application.

As s = jω increases,ZT increases(low pass filter)

R

C C

As s increases,ZT decreases.

3.2.2 T -network filters

C

Vin

R

C

2293.2 Active filters

Page 243: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Vin VoutZ1

Z2

R1 R1

C1R2

C2 C2

Vin Vout

Transferimpedance isobtained withVout grounded

( )

( )

( )

( ) ( )

( ) ( )( )

4RCs1sCR2RZ

RCs4sCR2R4

CRs2R4RCs

CRs2R1

42CRs12RCs

CRs2R1

sRC21sRC

sRC2R1Z

sCR21sRCsC

sCR2R1

Z1

sRCsCR21

sC1Z

sCR2RZZ1

Z1

Z1

222T

222

1222

122

1

22

22

22

111T

22

222

111T

22

22

22

1111

21T

+

+=

+

+=

++

+=

++

+=

++

+=

++

+=

+=

+=

+=

Let

RR2RCC2C

21

21==

==

Transferimpedance

The centrefrequency is:

RC1

o =ω

ωo

in

outVV

ω

Tuned rejection filter

3.2.3 Twin-T filter

Newnes Interfacing Companion230

Page 244: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Integrator

Differentiator

+

IVin

R

IC

+Q −Q

0 V

dtdVV in

out −=

dtdVRCV

dtdVC

RV

dtdVC

dtdQI

RV

I

inout

inout

in

out

−=

=

==

=

t

t

Vout

Vin

Differential equationin time domain

As the frequency of the input becomeslarger, the slope of the input increases andthus the magnitude of the outputincreases, i.e. gain increases withincreasing frequency.

−=

−=

=

=

=

=

dtVRC1V

CV

dtVR1Q

dtR

VdQ

RdtdQiRV

inout

out

in

in

in

Vin−

+

IR

I

C

+Q −Q

0 VVout

t

t

Vin

Vout

integral equation intime domain

As the frequency ofthe input becomeslarger, the outputdoes not have time toreach as high avalue, i.e. the gaindecreases withincreasing frequency.

3.2.4 Active integrator/differentiator

2313.2 Active filters

Page 245: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

( )

ω

−=

ω

−=

ω

+=

−−=

=

RCj1

VV

RCjV0

jCI0

IjX0VIRV

in

out

in

cout

in

−=

=

ω==

i

f

in

out

i

cf

ZZ

VV

RZCj

1XZNow

This is a general transfer functionthat holds for a general circuit withfeedback elements.

and

thus

Transfer function inω-domain

Invertingoutput

RV

I in=since

Now, s = jω

inout

in

out

Vs1

RC1V

RCs1

RCj1

VV

−=

−=

ω

−=

dtVRC1V

s1dt

inout ∫

−=

=but

thus

Transfer functionin s-domain

I is flowingtowards Vout sois negative

3.2.5 Integrator transfer function

Vin-

+

IR

I

C

+Q −Q

0 VVout

General transfer function

Newnes Interfacing Companion232

Page 246: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

CsR11

RR

VV

VZZV

CsR1R

sCR1Z;RZ

21

2

in

out

ini

fout

2

2

1

2fi

+−=

−=

+=

+==

Without R2, at low frequency,the gain (Vout/Vin) becomesvery large and at DC,approaches the open-loopgain. Need a low frequencycutoff to eliminate drift. Thisis the function of R2.

inout VRCj

1V

ω−=

R2

If s is small, then:

in1

out

in1

2out

VCsR

1V

VRRV

−=

−=

If s is large, then

Frequency domain analysis

[ ]

[ ]

[ ]

[ ] 21

21

22

1

2

in

out

in22

22

1

2out

in22

2

1

2

in21

2

in21

2out

CR1

1RR

VV

VCR1

CR1

RRV

VCR1CjR1

RR

VCjR1

1RR

VsCR1

1RRV

ω+

=

ω+

ω+

=

ω+

ω−−=

ω+−=

+−=

at R2ωC = 1

21

RR

VV

1

2

in

out=

Note, compared tothe passiveintegrator, this circuitcontains an elementof “gain” equal to theratio R2/R1.

Keep in mind that s = jωhence the use of | |.Need to square R2sCand then take thesquare root to find themagnitude.

An active integratorcan be modified to actlike a low pass filter.

Let s = jω

since

then

Transferfunction ins-domain

Transfer function in ω-domain

s

in

outVV

|R2Cs|=1

12

RR

Integrator

3.2.6 Low pass filter – active

Vin-

+

IR

I

C

0V

2333.2 Active filters

Page 247: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

RVV

I

sCVV

I

sCVV

I

RVV

I

IIII

outN4

2outsC

1out

3

1NsC

1N

2

Nin1

4321

2

1

=

−=

=

==

=

++=

( ) ( )

( )( ) ( ) ( )

1RsC3RsCC1

VV

1sRCV2sRCsRCVsCVR

RIV1sRCV2sRCVVR1sCV

R2sCV

RV

RV

RV

sCVsCVR

VR

VVsCVsCV

RVV

222

21in

out

2out12in

2out

3N

2out1Nin

2out1N

NoutN2out1N

in

outN2out1N

Nin

++

−=

++−+=

−=

=

+−++=

+−+

+=

+−+−+=

−+−+=

Transferfunction

Letting

C3bC

Cb3C

2

1

=

=

and

1RCsbsCR1

1RsC3RsCC1

VV

222

222

21in

out

++

−=

++

−=

b = 2 critically dampedb > 2 overdampedb < 2 underdamped

s

in

outVV

b < 2

b > 2

b: damping factor

Low pass

The analysis of this circuit in the frequency or time domain would be verycumbersome. Here we have arrived at a transfer function in the s-domain with verylittle effort.

Note: For a negative Vout,then I3 flows in thedirection indicated and isthus positive.

+

Vin R

C2

0 V

R

C1

N RI1

I4I3

I2Vout

3.2.7 2nd order active filter

Newnes Interfacing Companion234

Page 248: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

+

Vin R

C

0 V

R/2

2C

RVout

C

−=

i

f

in

outZZ

VV

Vin Vout

( )( )RCs1R2

Cs2R2RZi+=

+=

+=

RCsRCs1

Cs2Zf

( )

222 sCR1

RCs1R21

RCsRCs1

Cs2

−=

+

+−=

The transfer function for thiscircuit is easily obtained in thes-domain using transferimpedance results for theT–networks shown previously.The final transfer functioninvolves a s−2 term. Now, s is adifferential operator so that s−

1

is an integral operator. Here, wehave an s−

2 which means thatthe circuit takes the integraltwice − a double integrator.

ys1

dys1ydt

sdyydt

dtdysy

=

=

=

=

∫∫

3.2.8 Double integrator

+

0 V

2353.2 Active filters

Page 249: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Vout

+

Vin R1

C

0 V

R/2

R2

C

2C

R R

An active filter with a twin–Tnetwork as the feedback element

When twin-T is used as the feedback element, ZT is very high at the centrefrequency ωo and thus the gain of the active op-amp circuit is a maximum.At other frequencies, ZT is small and thus the gain of the overall circuit is aminimum. This leads to a bandpass filter with the followingcharacteristics:

ωo

in

outVV

ω

If the twin-T filter moved to the input, we would obtain a band reject ornotch filter.

R2 prevents open-loop instability atthe centrefrequency ωo

3.2.9 Bandpass filter – narrow

Newnes Interfacing Companion236

Page 250: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Generaltransferfunction

Transfer functionin ω-domainω−=

ω

=

=

−=

ω

=

ω

=

=

RCjVV

RCjV

V

RV

I

IRVCj

I

jCI

IZV

in

out

outin

out

out

iin

if

in

out

if

i

f

ZZ

VV

RCjZZ

Cj1Z

RZ

−=

ω=

ω

=

=Now

and

Now, s = jω

dtdVRCV

dtds

RCs

RCjVV

inout

in

out

−=

=

−=

ω−=

but

thus

Transfer functionin s-domain

thus

3.2.10 Differentiator transfer function

+

I

Vin

Zf

I

Zi

0 V Vout

2373.2 Active filters

Page 251: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

[ ] iout VRCjV ω−=

With an active differentiator, as the frequency increases, the output voltageincreases without limit in the ideal case (actually limited by the V+ and V−

supply). This is undesirable since high frequency noise will be greatlyamplified. The solution is to build in a cutoff frequency. The circuit thenacts like a high pass filter.

Cs1R

Cj1R

jXRZRZ

1

1

C1i

2f

+=

ω

+=

−+=

=

1CsRCsR

VV

V

Cs1R

R

VZZV

1

2

in

out

in1

2

ini

fout

+

−=

+

−=

−=

When s is small, then Vout ≈ R2CsVinWhen s is large, then Vout ≈ R2/R1Vin

-

+

Vin

Zf

Zi

R2

R1

If we multiply anddivide the numerator byR1, then we have:

1sCRsCR

RR

VV

1

1

1

2

in

out+

−=

Letting |R1sC| = 1 gives usthe 3 dB point. Note theelement of gain R2/R1compared to the passivedifferentiator.

Let s =jω

Transferfunction ins-domain

s

in

outVV

|R1Cs|=1

12

RR

Differentiator[ ] iout VRCjV ω−=

1CsRCsR

VV

1

2

in

out+

−=

Filter response

3.2.11 High pass filter – active

C

Newnes Interfacing Companion238

Page 252: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

( )( )( ) in2

1

12

in1

1

1

2

in1

2

in1

2out

VCR1

jCR1jCR0

VjCR1jCR1.

jCR1jCR0

VCjR1

CjR

VCsR1

CsRV

ω+

ω−ω+=

ω−

ω−

ω+

ω+=

ω+

ω=

+

=

( )( )( )

( )

( )

( )

( )

( )

ω+

ω=

ω+

+ωω

=

ω+

+ωω

=

ω+

ω+

ω−

=

ω+

ω−ω+=

21

1

1

2

in

out

in

21

221

2221

2222

in

21

221

22

2221

22

22

in

21

221

22

22212

in

2

21

12out

CR1

CRRR

VV

VCR1

1CRCR

VCR1

RCRRC

VCR1

CRCRR

VCR1

jCR1jCR0V

When R1ωC = 1, then

( )

21

RR

VV

V11

CRRRV

1

2

in

out

in1

1

2out

21

=

+

ω=

ω

in

outVV

R1ωC = 1

12

RR

[ ] in2out VCRV ω=

Transfer function in ω-domain

Note: The s-domain analysis is much easier tohandle. It allows the general characteristics of acircuit to be readily analysed. The precise shape ofthe frequency response of a circuit needs to beobtained, however, from the ω-domain analysis.

3.2.12 High pass filter – ω-domain

+

Vin

R2

R1C

Vout

2393.2 Active filters

Page 253: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

( ) ( )sCR1sC

sCR1R

ZZ

VV

sC1sCRsC

1RZ

sCR1RZ

RsRC1

sCR1

Z1

11

1

22

2

i

F

in

out

1

11

11i

22

2F

2

22

22F

++

=

−=

+

=

+=

+

=

+

=

+=

When s is small, then Vout ≈ R2C1sVinWhen s is large, then Vout ≈ 1/R1C2sVin

Integrator(high pass)

Differentiator(low pass)

s

in

outVV

R1C1s = 1

1

2RR

[ ] in12out VsCRV =

in21

out VsCR

1V =

R2C2 s= 1

3.2.13 Bandpass filter – wide

+

Vin

0 V

R2

R1C1

Vout

C2

Newnes Interfacing Companion240

Page 254: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

i

o

2

i

o

VV

log20

VV

log10db

=

=

The voltage gain of a circuit is obtained from the transfer function:

i

f

in

outv Z

ZVV

A −==

and may be expressed as a ratio (e.g. Av = 100). However, the gain of acircuit may cover several orders of magnitude depending on thefrequency of the input signal. To facilitate this range of possible values ofgain, it is often more convenient to express gain on a logarithmic scale.The scale chosen is the “decibel” scale (really a power gain).

The square factor is applied becausethe decibel scale represents the“power” output of a circuit and:

RVP

2=

3.2.14 Voltage gain and dB

2413.2 Active filters

Page 255: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1. Consider thefilter circuit:

(a) Determine the transfer function of the circuit. (Hint: Write thedifferential equation relating the input and output voltages withrespect to time.)

(b) Under what circumstances may the circuit be used as an analogintegrator?

2. Determine the s-domain transfer impedance for the T-type networkshown below.

3.2.15 Review questions

C

RVin Vout

R R

C

Vin Vout

3. (a) Show how the circuit below acts as an analog differentiator.

(b) The differentiator shown above is susceptible to high frequencynoise. Explain why this occurs.

(c) Modify the circuit to reduce high frequency noise and determine thetransfer function of this modified circuit.

(d) Sketch the transfer functions of the original and modified circuitsand discuss their features.

+

I

Vin

R

I

C

0 V Vout

Newnes Interfacing Companion242

Page 256: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

4. Consider the modified integrator circuit:

(a) What is the function of the feedback resistor R2?

(b) Derive an expression for the transfer function in the s-domain.

(c) Select values of resistors and capacitors to give integration ofsignals above 50 Hz.

R2

Vin−

+

IR

I

C

2433.2 Active filters

Page 257: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1. Construct the 1st order and 2nd order low pass filters as shown. Choosecomponent values to give cutoff frequencies of a few kilohertz.

2. Using a sinusoidal input signal, measure the frequency response of thefilter circuits and plot the transfer function of each filter. Compare the 3dB points and roll-off for each filter.

3. Using a square wave input, examine the step response of each filter.Compare the responses of the two filters.

4. With the 2nd order filter, alter the value of the parameter b andexamine its effect on the step response of the circuit.

C3bC

Cb3C

2

1

=

=

1RCsbsCR1

1RsC3RsCC1

VV

222

222

21in

out

++

−=

++

−=

1st order

2nd order

3.2.16 Activities

+

Vin R

C2

0 V

R

C1

N RI1

I4I3

I2 Vout

R2

Vin−

+

IR1

I

C

0 V

CsR11

RR

VV

21

2

in

out+

−=

Newnes Interfacing Companion244

Page 258: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

5. Design a twin-T bandpass filter to have a centre frequency of ωo =1000Hz.

6. Construct the twin-T network and measure its transfer characteristics.Plot on an appropriate graph.

7. Using this twin-T network, construct a bandpass filter. Adjust R2 forstability if necessary.

8. Plot the transfer function of this filter and comment on the significantfeatures.

9. Determine the theoretical transfer function of this circuit and comparewith that measured.

10. Examine the step response of this filter and comment.

Twin-T network

Bandpass filter

R1 R1

C1R2

C2 C2

Vin Vout

Vout

+

Vin R1

C

0 V

R/2

R2

C

2C

R R

2453.2 Active filters

Page 259: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

246

Page 260: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

2211

22s111

22122

out21111

s

RIRIRIVRIV

RIRIVVRIRIV

0V

+=

++=

+=

++=

=

21

out11

2111out1

out21111

RRVV

I

RIRIVVVRIRIV

+

=

+=−

++=

( )

21

22

212

22122

RRVI

RRIRIRIV

+

=

+=

+=

(1)(2)

(3)

from (1)

from (2)

substituting into (3)

( )

( ) ( )

( )

( )211

2out

1out221

1out2221

221out112211

221out1211

221

21

21

out1

22111

VVRRV

RVRVVRVRVRV

RVRVRVRVRVRVRVVRRV

RRR

VRRR

VVRIRIV

−=−

−=−

−=

+−=+

+−=+

+

+

+

=

+=

Now, the input resistance ofthe negative input isunbalanced with respect tothe positive input. If V1 isgrounded, then Rin of V2 isR1 + R2. If V2 is grounded,then Rin of V1 is R1 (sincewhen V2 is grounded, thenegative input is a virtualearth). This can causeproblems with unevenloading of the sources. Toovercome this, we can designan input stage using voltagefollowers.

Note: The negative input to the op-amp is not a virtual earth (0 V) in thiscircuit. The internal input resistanceof the op-amp is MΩ but becausethe input bias currents are nA, Vs= 0and so the voltage at negative inputis equal to I2R2.

1

2

21

outd R

RVV

VA −=

=

difference gain

3.3.1 Difference amplifier

V1

R2

R1

Vout

R3 = R1

V2

VS

R4 = R2

I1

I2

I1

I2

+

2473.3 Instrumentation amplifier

Page 261: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

The common mode rejection ratio (CMRR) is the ratio of the differentialgain to the common mode gain. The common mode gain is that obtainedwhen V1 = V2

cm

d10

cm

dAA

log20AA

CMRR ==

The more general expression for difference gain is:

11

22

43

21

1

4out V

RRV

RRRR

RRV −

+

+=−

With a common mode signal, V1 = V2, thus:

cm

1

2

43

21

1

4

in

out

A

RR

RRRR

RR

VV

=

+

+=

− Small variations in resistor valuesin a circuit can lead to somecommon mode gain.

Now consider the following circuitwhere the source voltages and outputresistances are included:

( )

1S

1S11

111

1S11S

RRVR

V

RIVRRIV

+

=

=

+=

( )( )

( )

( )

21S

2S21

43S

2S432

4322

43S22S

RRRVRRRRR

VRRV

RRIVRRRIV

++

+

=

++

+

=

+=

++=

for matched resistors

Now, even if VS1 = VS2 and resistors arematched, V1<>V2 and thus some commonmode gain is the result. The difference inV1 and V2 gets smaller as RS is reduced.At RS = 0, V1 = V2 = VS and no commonmode gain. For the highest common moderejection ratio, the amplifier should bedriven by low impedance sources – suchas a voltage follower.

3.3.2 CMRR

R2

VS1

VS2

RS

RS

V1 R1

Vout

R3=R1V2

VS

R4=R2

I1

I2

I1

I2

-

+

Newnes Interfacing Companion248

Page 262: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Unity gain (β = 1) voltage followers: high input impedance, low outputimpedance.

5oldin

ooldinnewin

10R

A1RR

β+= β = 1Ao = 105

Signal sources see only high impedances, therefore maximum transferof Vs and no uneven loading of the sources.

The amplifier itself is driven by low impedance sources (Rout of an op-amp is very small: 75 Ω). CMRR is improved. The effect on CMRR ofsource impedance is much greater than resistance mismatches.

3.3.3 Difference amplifier with voltage follower inputs

R2

R1

Vout

R3 = R1

VS

R4 = R2

I1

I2

I1

I2

+

V1

V2

+

+

2493.3 Instrumentation amplifier

Page 263: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Feedback resistors Ra and Rbtend to keep the negative andpositive inputs to the op-ampat equal potential hencevoltages at R are V1 and V2

( )

( ) ( )

( )R

RRRA

VVRRR

VVVV

RRR

VVVVVV

RR

VVVV

RR

VVVV

RVVI

IRVVIRVVIRVV

bai

21ba21

2o1o

ba21

2o211o

b21

2o2

a21

11o

21

b2o2

a11o

21

++

=

−++

=−

+

=−+−

=−

=−

=

=−

=−

=−Now,

thus

Note: This input stage isnot a difference amplifier.The difference in the outputvoltages = the gain timesthe difference in the inputvoltages. Common modesignals are passed throughwithout being amplified. Aproper difference amplifierrejects the common modesignal altogether.

Gain increases as R decreases.If R is made very large, the gainapproaches 1

This is the gain of the input stage.The gain of the input stage canthus be altered by adjusting justone resistor R.

3.3.4 Difference amplifier with cross-coupled inputs

To amplifierinputs

V1

Ra

+

V2

+

Rb

R

VO1

VO2

Newnes Interfacing Companion250

Page 264: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

( )( )

1AVV

RR

VVVVRR

VVVV

RR

RR

VVV

IRVV

VRR

VVVIRV

IRVVVVVV

2VV2VV

A

cm

21

a21

21a21

2o1o

ba

b21

2

b22o

1a21

1a1o

21

21

2o1o

21

2o1ocm

=

+=

−++

=+

=

+

−=

−=

+

=

+=

=−

+

+

=

+

+

=

but

and

if

then

Now,

i

cm

cm

i

ACMRR1AAACMRR

=

=

=

butthus

But, Ai is the gain of the inputstage which is adjustable via R.This means that the CMRR isadjustable. For highest CMRRwe thus require a high value ofAi (and hence a low value of R).

therefore

2VV

V 21cm

+

=

3.3.5 CMRR cross-coupled inputs

V1

Ra

+

V2

+

Rb

R

VO1

VO22VVV

VVVV

VV2

VV2

VVVV

2VVVV

21cm

cm21cm

cm221

21cm2

21cm1

+

=

−+=

−=

+=

−=

If the input signal consists of acommon mode component,(e.g. V1 = 5 V, V2 = 3 V means thatVcm = 3V and V1 − V2 = 2V) then:

Since common mode signalsare not amplified, then:

2VV

Vo 2o1ocm

+

=

thus

2513.3 Instrumentation amplifier

Page 265: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

An instrumentation amplifier is characterised by a high gain andhigh CMRR.

• Both inputs have a high input impedance.• The gain of the amplifier can be easily adjusted via R.• The resistors R1 at the input to the final differential amplifier are trimmed

to eliminate amplification of any common mode signal.

( )RRRR

VVVV ba21

2o1o ++

=−

The gain of the input stage is:

The gain of the amplifier stage is:

1

2d R

RA =

Thus the total gain is the product of the two:

( )

( )

( )211

2av

1

2aa

21

1

2ba

21v

VVRR1

RR2

A

RRRRR

RVV

RRRRR

RVVA

+−=

++−

−=

++−

−=

letting Ra = Rb

It is usual to have the requiredgain of the overall circuitobtained from the input stageand the R2/R1 term drops out.The difference amplifier D isdesigned for a gain of 1 and itspurpose is to reject anycommon mode signal.

3.3.6 Instrumentation amplifier

A

B

D

R2

R1

Vout

R1

VS

R2

I1

I2

I1

I2

+

V1

Ra

+

V2

+

Rb

R

VO1

VO2

Newnes Interfacing Companion252

Page 266: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

A non-linear resistor is connected into the feedback circuit. In practice, thiscan be a diode, but a transistor connected as a diode is used since theforward biased transfer function is more accurately exponential. Theexponential nature of the forward biased diode leads to a logarithmicdecrease in gain of the circuit as the input signal is increased.

The feedback transistor has its collector at 0 V (virtual earth) and the baseis also at ground potential (0 V). With the collector and base effectivelyshorted together, the device acts like a diode across the base–emitter pnjunction.

The forward biastransfer function of thediode is given by thediode equation:

kTeVoeII ≈

where Io is the reversebias leakage current.

( )o1inout

o1

inout

out

o1

in

kTeV

o1

in

kTeVo

1in

IRln026.0Vln026.0VIR

Vlne

kTV

kTeV

IRVln

eIR

VeII

IRV

out

out

−≈

=

=

=

=

=

Transferfunction

Note: This approximationholds for forward biaswhere I >> Io. Thus, thetransfer function shownhere requires Vin to bepositive so that the pnjunction is always well intoforward bias.

This amplifier has a high gain forsmall signals (low Vin) and a(logarithmic) progressively lowergain for increasing signals.

3.3.7 Log amplifier

+

Vin R1

0 V VoutR2

I

Note: e/kT≈ 40at T = 300K

e = 1.6 × 10-19Ck = 1.38 × 10-23 J/K

2533.3 Instrumentation amplifier

Page 267: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Thus far, it has been assumed that the op-amp has an infinite bandwidthand that the frequency response of a particular circuit depends only uponthe nature of the external resistors and capacitors. In practice, there is alimit to the open-loop voltage gain of an op-amp which limits the upperfrequency that may be used.

The upper frequency limit is due to the presence of internal capacitanceswithin the IC itself which are present intentionally to enhance stabilityunder feedback conditions.

The bandwidth increases with decreasing voltage gain (increasingnegative feedback).

1 10 100 1k 10k 100k 1 MHz

105

104

103

102

10

0

BandwidthVoltagegain

ω

Increasedbandwidth

Ao

Ac

3 dBpoint

For a 741 IC, the (gain × bandwidth) product is fairly constant at about1 MHz. The roll-off is about 25 dB/decade.

3.3.8 Op-amp frequency response

Newnes Interfacing Companion254

Page 268: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1. The difference amplifier shown has a gain of 10 and a CMRR of 60 dB.

(a) What are the disadvantages of using this circuit as an instrumentationamplifier?

(b) Design a cross-coupled input stage for this amplifier to provide anoverall gain of 100 and calculate the new CMRR.

(c) If this modified amplifier were presented with a 50 mV differencesignal with 20 mV of common mode noise, determine the nature ofthe output voltage.

2. A logarithmic amplifier is constructed using a diode whose reverse biasleakage current Io is 200 nA. At room temperature, the followingrelation applies to the diode:

kTeVoeII ≈

where e/kT = 40 at T = 300 K. The diode has a maximum forwardbias current rating of 50 mA. In the circuit below, determine a suitablevalue of R1 to provide an output of 0.5 V for an input of 20 V.

3.3.9 Review questions

10k

1k

1k

10k

V1 Vout

V2

+

+

Vin R1

0 V VoutR2

I

2553.3 Instrumentation amplifier

Page 269: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

3. A chromel–alumel thermocouple is being used to measure temperature.A voltage appears at the thermocouple outputs which is dependent ofthe temperature difference between the cold and hot junctions. Thevoltage is typically a few millivolts. A digital output display shows thetemperature in oC and is driven by an analog to digital converter. TheADC converts a signal from 0 to 10 V to an 8-bit digital value. Themaximum temperature to be measured is 1000 oC.

(a) Design an instrumentation amplifier which converts the outputfrom the thermocouple to that required to utilise the full inputrange of the ADC.

(b) Determine the resolution of the system.

∆ V

hot junction

0–1000 oC

cold junction

AMP ADC 8-bit output

4. Under what circumstances is it better to use a difference amplifier thana single-ended input amplifier?

Newnes Interfacing Companion256

Page 270: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

1. Construct a simple difference amplifier and measure the differencegain and CMRR when the amplifier is driven by high impedancesources (you may have to connect a large resistor in series with theinput signal). Comment on the results.

2. Add unity gain voltage followers to each input and measure thedifference gain and CMRR of the amplifier. Compare with previousmeasurements and comment. (Note: A better op-amp than a 741 maybe required – e.g. LM308N.)

Follower inputs

Difference amplifier

3.3.10 Activities

Instrumentation amplifier

Parts list:2 × LM308N operational amplifier1 × 741 operational amplifier2 × 100 pF2 × 2.2k; 1 × 56 Ω; 2 × 470 Ω; 2 × 4.7k

V1

R2

R1

Vout

R3 = R1

V2

VS

R4 = R2

I1

I2

I1

I2

+

V1

V2

+

+

2573.3 Instrumentation amplifier

Page 271: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

3. Design and construct a cross-coupled input stage for a differenceamplifier but do not connect to the amplifier yet. The cross-coupledinput stage is to have a gain of about 100.

4. Measure the gain of the input stage for various values of R.5. Measure the common mode gain of the input stage and comment.6. Connect to the difference amplifier and measure the gain of the overall

circuit, its common mode rejection ratio, and bandwidth. Comment onthe results.

7. Suggest how the gain of the amplifier should be distributed over thetwo stages for optimum performance.

8. Connect the output of the thermocouple circuit from Part 1 of this bookto the instrumentation amplifier input, and connect the instrumentationamplifier output to the analog input of the data acquisition system fromPart 2 of this book.

Cross-coupled input stage

Instrumentation amplifierLM308N

LM308N

741

0–5

mV

from

ther

moc

oupl

eou

tput

circ

uit

0–5 V(to analog inputof interfacecircuit)

-

+

+Vcc

Vout

−Vcc

−Vin

+Vin

O/N

O/N

For LM308N,connect a 100 pFfrom pin 8 to earth.

R2

R1

Vout

R1

VS

R2

I1

I2

I1

I2

+

V1

Ra

+

V2

+

Rb

R

VO1

VO2

V1

Ra

+

V2

+

Rb

R

VO1

VO2

8

Newnes Interfacing Companion258

Page 272: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

The principal problem with log amps is drift due to the input bias currentof the op-amp. An FET op-amp is usually used to minimise this error. Inthe circuit below, an LF356 FET input op-amp is used.The bias current is roughly balanced with R1 (on the positive input) ofabout 100 kΩ. A capacitor 0.01 µF across the transistor helps to stabilisethe circuit against high frequency (RF) oscillations. A large resistor (20MΩ) is needed in parallel to keep output drift low.For offset voltage balancing, a multi-turn pot is required since the inputvoltage has to span a wide range.

1. Connect the op-amp as an inverting amplifier with a gain of about 100(i.e. do not use the transistor as a feedback element yet). With Vin = 0,balance the offset voltage to zero.

2. Now connect the transistor and stabilising components as shownabove.

3. Vary Vin over a wide range to get a rough idea if the circuit isworking. Vout will not change very much (due to it being a logamplifier).

100k

1k

BC107

0.01 µF

20M

+Vcc

10k

Log amplifier

2593.3 Instrumentation amplifier

Page 273: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

+Vcc

4. When you are satisfied that the circuit is working, vary Vin fromabout 90 V down to about 10−3 V with about four points per decade.

5. Plot the gain of the circuit with Vout on the vertical axis and Vin on thehorizontal log axis. If you have only linear paper available, plot Voutvs logVin.

6. Estimate values for the transfer function from your experimentalreadings and compare with calculated values.

7. If time permits, try making a log amplifier using a 741 op-amp andrecord your findings.

+

−Vcc

72

34

6

5 1LF356N

+Vcc

10k

Newnes Interfacing Companion260

Page 274: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

261

Page 275: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

3.4.1 Intrinsic noiseThermal (Johnson or Nyquist*) noise

[ ]21

fkTR4V rmsn ∆=

fkT4R

VP

fkTR4V2

2n

∆=

=

∆=

Shot noise

feI2i s2

n ∆=

Rfei2RiP

n

2nn∆=

=

e charge on electron 1.6 × 10-19 CIs DC signal current (A)in noise current (A)∆f bandwidth (Hz)

Power

Power

k Boltzmann’s constant1.38 × 10-23 J/K

T Absolute temperatureR Resistance∆f Bandwidth

e.g. 10k resistor at 300K over a bandwidth of10 kHz gives an rmsnoise figure of 1.3 µV

Noise power is proportional to T and ∆f.

Associated with the randomness of charges moving across a potentialbarrier.

Thermal noise and shot noise are present at all frequencies and is calledwhite noise. Noise may be reduced by reducing any terms in theexpression, e.g. reducing the temperature, resistance and the bandwidth.

• thermoionic emission• contact points

Strictly speaking, white noise is noise which has a constant power density atall frequencies over the band of frequencies of interest.

Flicker noiseThis type of noise increases with decreasing frequency and is sometimescalled 1/f noise. For this reason, sensitive measurements should not bemade using DC. The precise origin of flicker noise is not well understood.It is usually not important compared to other noise above 1 kHz.

* Johnson did the experiments,Nyquist developed the equation.

Note: In general, noise increases withbandwidth. Noise is due to random fluctuationswhich can contribute to a significant highfrequency component of the total signal.Reducing the bandwidth reduces the amount ofhigh frequency noise.

Newnes Interfacing Companion262

Page 276: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

3.4.2 Environmental noise

This type of noise arises from sources outside the measuring system.Environmental noise is often called interference. Interference may bemechanical in nature (from mechanical vibrations) or electrical.Electromagnetic interference (EMI) is the most common. Such noise mayarise from:

The best method of reducing the effects of noise is to reduce the noise at itssource. This is not always practical, so the next best method is to attempt todivert the noise signal to ground through the use of filters before it isregistered by the transducer. Failing that, the most common approach forreducing EMI is to be careful with the physical location of sensitivecomponents. The major contribution to the effect of noise occurs at the firststage of amplification. For this reason, a preamplifier should be located asclose to the transducer as possible. The preamplifier should be adifferential amplifier with a good CMRR. Signal leads from the pre-amp tothe main power amplifier should be shielded cable and be routed awayfrom transformers and mechanical switches. All shields should begrounded at a common point so as to eliminate ground loops.

• Radiation from the abrupt cessation of electric current duringthe switching off or control of heavy machinery.

• Radiation from AC circuits such as power lines, rectifiers, etc.• Lightning.

Noise from the above generally occurs at low frequencies. Noise canalso occur at radio frequencies (RF). RF noise can arise from:

• Transmitters (two-way radios, cell phones, radarinstallations, etc.).

• Electronic devices working at high frequencies.A third source of noise, or even damage, is electrostatic discharge.This is very prominent in dry weather and depends on the material usedfor the equipment and furnishing the surroundings.

Types of environmental noise

Reduction of environmental noise

2633.4 Noise

Page 277: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

rms valuesusually used

n

S10db V

Vlog20SNR =

A measure of the relative magnitude of the noise is usually given by thesignal-to-noise ratio, or SNR (often expressed in dB).

3.4.3 Signal-to-noise ratio

in

Is

I

t

The signal-to-noise ratio isthe ratio of the signal powerover the noise power.

n

s10db

n

s

PP

log10SNR

PP

SNR

=

=

The larger the SNR the better.

Power is proportional to I2 (or V2), hence:

Noise is always present in the original signal and may be amplified andnew noise added by the instrumentation amplifier itself. The degradation ofSNR from the input to the output of an amplifier is called the “NoiseFigure” NF. An NF of less than about 3 dB is considered good.

o

sSNRSNR

NF =

Signal

Amplifier output

Noise in a transistor (such as a BC109 PNP BJT) arises from thermal noisefrom the resistance of the semiconductor itself and shot noise from thepassage of charge carriers across the pn junctions. Flicker noise is alsopresent and is due to the randomness of the diffusion process of carriers.Flicker noise, being 1/f dependent, is the main source of noise at lowfrequencies (<1 kHz) in a transistor. In an FET, shot noise is not soimportant since the pn junction is in reverse bias and the gate current is verysmall.

Newnes Interfacing Companion264

Page 278: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

ν

η∆=

∆=

hP

fe2

feI2i

s2

s2

n

3.4.4 Optical detectors

Consider the factors that affect the rate of electron productionwithin an optical detector:

ν

η=

hP

r sr rate of electron production (electrons/second)η quantum efficiencyh Planck’s constant (6.63 × 10-34)ν Frequency in HzPs Incident power (i.e. the signal)

Now, the resulting signal current Is is simply:

ν

η=

=

heP

reI

s

s e charge on electron

The noise current is found from:

The signal to noise ratio is thus:

η

∆ν=

∆ν

η=

=η∆

ν

νη=

fh2P

fh2P

PP

PP

Pfe2h

hPseSNR

mins

s

n

s

n

s

s222

222 2

n

2s

2

iI

SNR

RIP

=∴

=

Note:

NEPsignal limited(proportional to ∆f)

The minimum detectable signaloccurs when SNR = 1, that is, whenPsmin = Pn. This is called the NoiseEquivalent Power NEPsignal limited.

If the background radiation noise power Pb is >> than signal power Ps, thenthe signal is background limited and the SNR becomes:

( )

η

∆ν=

∆ν

η=

∆ν+

η==

fh2PP

fh2PP

fh2PPP

PP

SNR

bmins

b

2s

bs

2s

n

s

This is the NEP background limited(proportional to )f∆

This is noise from“internal” sourcesin the detector

This is noise frombackgroundradiation which isincident on thedetector alongwith the signal.

∆f is called the bandwidth.

2653.4 Noise

Page 279: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

3.4.5 Lock-in amplifier

The lock-in amplifier uses a phase detection circuit where the amplitudeof the output signal is proportional to the amplitude of the input signal andproportional to the cosine of the phase difference between the input signaland a reference signal – the input signal and reference signal must have thesame frequency.

The phase detector produces an output signal which follows variations inthe amplitude of the input signal (if the frequency of the input andreference signals are the same – which is ensured by having the referencesignal also operate the chopper) and where the phase of the referencesignal is the same as that of the signal.

For example, a particular input signal could consist of aslowly varying DC voltage (e.g. thermocouple output). By“chopping” the signal the DC output is converted into asquare wave of known frequency.

Phasedetector

Low passfilter

Phaseshifter

Chopper

Signal +noise

Signal +noisechopped

amp

Reference signal

The phase shifter is adjusted like atuner to give a maximum in theoutput signal. Noise in the signal isrejected since only thosecomponents of the signals whichhave a matching phase with thereference are passed by the phasedetector.

The lock-in amplifier thus requires a reference signal, and a periodic inputsignal. A slowly varying input signal, which contains noise, can be madeperiodic, or repetitive, by chopping.

Newnes Interfacing Companion266

Page 280: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

3.4.6 Correlation

This technique can be performed electronically or numerically on therecorded data. The signal of interest must be repetitive. There are twogeneral types of correlation:

• cross-correlation• auto-correlation

Both methods employ a reference signal (the auto-correlation uses thesample signal, shifted in time, as the reference). During a time period, thereference signal is delayed by a delay τ. The sample signal and the delayedreference signal are multiplied together and then added. The reference isshifted again and multiplied and added to the original signal, and so onuntil a complete period has been correlated.

( ) ( )dttVtVT1V ref

T

Tinout τ−= ∫

Mathematically, the correlated output Vout is given by:

where for auto-correlation, Vref = Vin.

Auto-correlation allows us to indirectly obtain information about thefrequencies present in a signal but not necessarily the waveform of thatcomponent. Cross-correlation gives information about the waveform of thesignal of interest.

Delay circuit

Amplifier

Multiplier Integrator

Inputsignal

Outputsignal

2673.4 Noise

Page 281: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

3.4.7 Review questions1. Calculate the open circuit rms noise voltage over the frequency range

0–1 MHz between the terminals of a 100 kΩ resistor at a temperature of27 oC. Also calculate the available noise power from this resistor.

2. A transducer of resistance 1 MΩ delivers a signal current of 10 µA to anamplifier which has an input resistance of 10 MΩ and an bandwidth of10 kHz. Calculate the temperature to which the transducer must becooled to achieve an SNR less than 130 dB.

3. A photodiode provides a signal current of 100 nA under a constant levelof illumination. What is the rms shot noise current in the diode over abandwidth of 100 kHz?

4. A signal of interest occurs at a frequency of 300 Hz and provides avoltage at the transducer output of 100 mV. A combination of thermaland flicker noise is present which is approximately described by:

( )fbafV += volts/Hz

5. An optical detector is required to have 15 dB signal to noise powerratio. The noise equivalent power (NEP) is background limited.

ν=

=∆=

kTh

TP

dtdP

PP mins power resolution

from Planck’s equation

(c) Express ∆P/PB in terms of PB, v and ∆f. Hence find anexpression for PB in terms of ∆f.

(d) Calculate the product of detector aperture area A and the bandpass∆ν required for ∆f = 5 MHz for a field ofview of solid angle Ω = 10-6 Sr given that: v

ceh2AfP 2

kT/h3∆

νΩ=∆

ν−

(e) Estimate the aperture A required ofthe detector for ∆ν = 1012 Hz.

(a) Calculate the power ratio Ps/Pn. Given that the response of thedetector is limited by the background noise, what is theminimum detectable power expressed in terms of the NEP.

(b) Find the ratio of the minimum detectable power Psmin to thebackground power PB at 300 K and λ = 8 µm if a temperatureresolution of ∆T = 0.05 oC is required.

36 100.4b;105.2a −−

×=×=

(Ans: 0.04 mV, 4.14 × 10−15 W)

(Ans: −73 °C)

(Ans: 5.66 × 10−11 A)

(Ans: 35 db)

(Ans: 31.6 NEP, 0.001, 5 × 10-14, 0.128 m2)

Calculate the SNR if the output is filtered to within 250–350 Hz.

Newnes Interfacing Companion268

Page 282: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

269

Page 283: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

The difference between the two is thatfor the FIR, the output of the filterdecays to zero for an impulse input.The output of an FIR filter depends onthe present,and previous inputs (thefilter is non-recursive). The outputfrom an IIR filter employs a feedbackmechanism so that the output dependsupon past outputs as well as past andpresent inputs (i.e. recursive).

3.5.1 Digital filters

There are two approaches to digital filtering. The data itself may beoperated upon using a filter algorithm with the desired transfer function,or, the frequency spectrum of the data may be obtained using Fourieranalysis, selected frequencies discarded, and then the filtered sequencerecomputed from the modified spectrum. The second method is describedin some detail in this chapter.

Digital filters fall into two basic categories: Infinite Impulse Response(IIR) or Finite Impulse Response (FIR). These terms describe the timedomain characteristics of the filter when presented with an impulse signalas an input.

0 0 0 1 0 0 0 0

Impulse input d(i)

If a continuous signal y(t) is sampled N times at equal time intervals ∆t,then the resulting digitised signal includes the information of interest plusany noise that might have been present in the original signal.The purpose of a digital filter is to take this set if data, performmathematical operations on it, and produce another set of data possessingcertain desirable properties (such as reduced noise).

Digital filter(transferfunctionH(ω))

IIR feedback path

The feedback associated with theIIR filter presents an input to thefilter even when the external inputdrops to zero. The output neverreaches zero. It may decrease,oscillate, or even become unstableand increase without limit. IIR filtersare usually more computationallyefficient than their FIRcounterparts.

Impulse response h(i)

FIR

i

IIRi

Newnes Interfacing Companion270

Page 284: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

( ) [ ]

( ) ( ) ( )∫∫∫

ω=ω==

ω+ω+=

=

ooo T

0o

on

T

0o

on

T

0oo

1nonono

dttnsintfT2B;dttncostf

T2A;dttf

T1A

tnsinBtncosAAtf

3.5.2 Fourier series

The Fourier series gives amplitudes and frequencies of the componentsine waves for any periodic function f(t). For periodic functions of periodTo with frequency ωo, the Fourier series can be written:

Using Euler’s formula, it can be shown that any cosine (or sine) functioncan be represented by a pair of exponential functions:

( ) dtetfT1C

eC)t(f

o

o

o

T

0

tnj

on

n

tnjn

ω−

−∞=

ω

=

=

“DC” termor averagevalue of f(t)

Amplitude terms for componentfrequency nωo

( )

( ) jBA21

jBA21C

nn

nnn

+=

−=

Note: Cn is a complexnumber, the real partcontains the amplitudeof the cos terms, andthe imaginary part theamplitude of the sinterms.

[ ] [ ]tjtjtjtj ee21jtsin;ee

21tcos ω−ωω−ω

−−=ω+=ω

Substituting into the Fourier series we obtain:

n > 0

n < 0

with

A plot of Cn vs frequency is a frequency spectrum of the signal. Forexample, if f(t) =A cos ω

οt, then the frequency spectrum is a pair of lines

of height A/2 located at ±ωο.

Negative frequencies arise fromthe representation of sinusoidalsignals by a pair of exponentialfunctions. There is no “DC” termsince the average value of thefunction is zero.ω

Cn

ωo−ωo

A/2

This plot is the magnitude of the exponential components of the signal. Afrequency spectrum using trigonometric coefficients would be a single lineof height A at ωo.

ωο

ω

AnA

2713.5 Digital signal processing

Page 285: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

3.5.3 Fourier transform

The function F(ω) is called the Fourier transform of f(t) and is writtenF[f(t)]. The Fourier transform is a continuous function of ω.

F(ω) = F[f(t)]

ωIndicates possiblehigh frequency noisein the original signal

The function f(t) is often termed the inverseFourier transform of F(ω): ( )[ ]ω=

− FF)t(f 1

Non-periodic functions are functions with an infinite period, i.e. To → ∞and ωo → 0. The component frequencies can no longer be represented asdiscrete spectral lines, but take on aninfinitely continuous range of values.Now, for the periodic case, we have:

( ) dtetfT1C

o

o

T

0

tnj

on ∫

ω−=

As To → ∞, Cn → 0. That is, the amplitude of the spectral lines becomesvanishingly small as the spectral lines merge into a continuum. But, theintegral is finite, hence, the product CnTo can be written:

( ) dtetfTC tnjon o∫

∞−

ω−= The product nωo becomes the

continuous variable ω, hence:

( )

( )ω=

= ∫∞

∞−

ω−

F

dtetfTC tjon

∑∞

−∞=

ω=

n

tnjn oeC)t(fNow, going back to the periodic case,

or: ( )( )ω

π

ω

=

ω

= F2T

FC o

on

and replacing nωo with the continuousvariable ω, we obtain:

( ) ( ) ωω

π

π

ω

∞−

−∞=

ω

∫∑ deF21eF

2)t(f tj

n

tjo ωo → 0

Fourierintegral

Because of the continuous nature of ω, theamplitude of the frequency component of thesignal at any one particular frequencyapproaches zero. F(ω) is really a frequencydensity function: ( )

onon

2CTCFω

π

==ω

Thus, it is more appropriate to say that thefrequency spectrum of a signal has an amplitudeof say 5 V per rad at a particular value of ω.

Newnes Interfacing Companion272

Page 286: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Thus, we can say that the continuous frequency spectrum of a non-periodicsignal can be completely specified by a set of regularly spaced frequenciesa minimum of ∆ω = 2π/To radians/sec apart. That is, for the purposes ofanalysis, we say that a non-periodic signal of finite length is periodic witha period equal to the length of the signal. The component frequenciesconsist of equally spaced intervals:

How many component frequencies are required to represent the data? Well,the spectrum of a digital signal is always periodic with the same set offrequencies repeating over and over with a frequency period of 2π/∆t. Ifwe sample at intervals of ∆ω = 2π/N∆t, then the total number offrequencies per period is just

NtN2

T2 s

o

ω=

π=

π=ω∆

3.5.4 Sampling

If a continuous signal y(t) is sampled N times at equal time intervals ∆t,then the sampling frequency is: .t2s ∆π=ω

Now, a non-periodic sample sequence of finite length N sampled over atime To can be considered to be periodic, for the purposes of analysis, witha period To. For a periodic signal, the frequency spectrum of the signalconsists of lines spaced ωo = 2π/To apart where ωo is the fundamentalfrequency of the signal.

sk Nk

tNk2

ω=∆

π=ω where k goes from 0 to N − 1

The frequency resolution ∆ω is ωs/N. The greater the value for N, thefiner the resolution of the frequency bins or channels used to represent theoriginal signal.

The digital signal has a duration To = N∆t.

The frequency components contained within the N data points are:

y

t

∆t

y(t)To

The data is equallyspaced so that theith measurement isat time iDt.

N2

tNt

2=

π

π

2733.5 Digital signal processing

Page 287: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Now, in general, F(ω) is given by the integral:

We can approximate this to a finitesum as:

( ) ( ) ( ) tetiyF1N

0i

tiji ∆∆=ω ∑

=

∆ω−

where N is the total number of equallyspaced data points and yi(i∆t) is the actualdata at i recorded at time i∆t. But, ω in thisformula is a continuous variable; however,for a discrete number of samples:

tNk2

k∆

π=ω

( ) ( ) dtetfF tj∫∞

∞−

ω−=ω

Further, recalling that F(ω) is actuallya frequency density function, we canthus write the actual amplitudespectrum of the signal as:

( )( )

( )kC

etiyt

F 1N

0i

Nki2ji

k

=

∆=∆

ω

∑−

=

π−

3.5.5 Discrete Fourier transform

where k goesfrom 0 to N − 1

Each value of C(k) is a complex number of the form A − Bj.The complete array of N complex numbers comprising thisseries is called a discrete Fourier transform or DFT. Notethat C(k) is periodic (with period 2π/∆t). If we perform thesum past k = N − 1, we get the same set of frequencycomponents again and again.

In terms of sines and cosines, we have:

( ) ( )∑−

=

π−

π∆=

1N

0ii N

ik2sinjNik2costiykC

This formula can beeasily implemented insoftware

Fast Fourier transform FFTComputation of the DFT is timeconsuming, requiring in theorder of N2 floating-pointmultiplications. However, manyof the multiplications arerepeated as i and k vary. TheFFT is a collection of routineswhich are designed to reducethe amount of redundantcalculations. Each differentimplementation of the FFTcontains different features andadvantages. Most pre-writtencomputer subroutines employsome sort of FFT routine to finda DFT of a series of samples.The algorithm used in somecomputer languages is knownas the “split-radix” algorithmand requires approximatelyN log2 N operations.

Newnes Interfacing Companion274

Page 288: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

3.5.6 Filtering

Consider a signal yin(t) whichcontains high frequency noise:yin(t)

t

The signal can be represented by aFourier integral:

Fourier transform inω-domain

The high frequency noise wouldlead to an increase in F[yin(t)] athigh frequencies. If it were possibleto separate out the signal of interestys from the noise yn, F[y(t)] foreach would be something like:F[y (t)]

ω

F[yn(t)]F[ys(t)]

Now, consider the transfer functionH(ω) = yout/yin of an ideal low passfilter in the ω-domain.

If this function H(ω) were multipliedwith the Fourier transform of yin, thenthe amplitude of all components of theFourier transform above ωo would bereduced to zero thus eliminating (or atleast reducing) the high frequencynoise component of the signal.

ω

)(H ω

H(ω) = 1 at ω < ωcand 0 at ω > ωc

ωo

100%

F[yin(t)]

ω

ωo

After filter

Goodrepresentationof ys due tofiltering.

yout(t)

t

The resulting Fourier series or integral(using the modified transform as theamplitude coefficients) then representsthe filtered signal in which noise isreduced.

( ) ωω= ∫∞

∞−

ω deV)t(y tjinin

F[yin(t)] = yin(ω)

ω

F[yin(t)]

F[ys(t)]Signal ofinterest

2753.5 Digital signal processing

Page 289: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

3.5.7 Digital filtering (ω-domain)For a given input signal yin(t), the filtered signal yout(t) is obtained from theinverse Fourier transform of the product H(ω)F(ω).

( ) ( )

( ) ( )

( )

c

c

ω>ω=

ω≤ω=ω

ωωωπ

=

∞−

ω−

∞−

ω

01H

dtetyF

deFH21)t(y

tjin

tjout

( )( )

( )kC

etiyt

F 1N

0i

Nki2ji

k

=

∆=∆

ω

∑−

=

π− where k goesfrom 0 to N − 1

The discrete Fourier transform of yi is:

The inverse transform is found from:

( ) ( ) ( ) Nki2j1N

0k

tijki ekC

N1deF

21tiy π

=

∆ω

∞−

∑∫ =ωωπ

=∆

Thus, the filtered sequence is given by:

( ) ( ) Nki2j1N

0kkout ekCH

N1)i(y π

=

∑ ω=

As written here, yout(i) is an array of complex numbers containing both phase andmagnitude information. The magnitudes may be obtained by taking the square root ofthe sum of the squares of the real and imaginary values.

For an array of discrete samples,we must replace the continuousvariable ω with:

tNk2

k∆

π=ω

sk Nk

tNk2

ω=∆

π=ω

Now, since

Then the filter transferfunction can beexpressed in terms ofthe parameter k/Nwhich goes from 0 to 1.

k/N

H(ωk)

0 1

Note: The product H(ω)C(k)involves complex numbers.

( ) ( )[ ]Nki2sinjNki2coskCN1tiy

1N

0ki π+π=∆ ∑

=

or

Note: The DFT and inverseDFT allow for processing ofcomplex signals (such as thatin an AC circuit). If the datasampled is real, the imaginaryterms in the reconstitutedsignal from the inversetransform reduce to zero.

complex numbers

Newnes Interfacing Companion276

Page 290: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

ω

)(H ω

ωc

1

3.5.8 Convolution

The filter transfer function H in theω− or s-domains is in fact a Fouriertransform! Although it does not showthe amplitude of the component sineand cosine functions of a particularsignal, it does show the amplitude ofthe ratio yout/yin against frequency forthe filter circuit.For a given input signal yin(t), the filtered signal yout(t) is obtained by theFourier integral given by:

( ) ( )

( ) ( )

( )

c

c

ω>ω=

ω≤ω=ω

π

ωωω=

∫∞

∞−

ω−

∞−

ω

01H

dtety21F

deFH)t(y

tjin

tjout

yout(t) is the inverse Fourier transformof the product H(ω)F(ω).

[ ]

[ ] ( ) ( )[ ] [ ])t(hF)t(yF

HF)t(h*)t(yF

de)t(h*)t(yF)t(y

in

in

tjinout

=

ωω=

ω= ∫∞

∞−

ω

convolution

A convolution is a special type ofsuperposition in the time domain. It isa weighted sum of products of twosignals. It is equivalent to amultiplication in the frequency domain.

Modulation is another type ofsuperposition. Consider theformula:

The frequency term is modulatedby the amplitude term which maychange as a function of time. Thisis called amplitude modulation.Modulation is a multiplication of twosignals in the time domain. Amultiplication in the time domain isequivalent to a convolution in thefrequency domain.

tjAe)t(y ω=

Digital filtering can be done ineither the time (using convolutions)or frequency (using Fouriertransforms) domains.

If the functions h(t) and yin(t) are the original functions in the time domain,we say that the output signal yout(t) is the convolution of these twofunctions.

2773.5 Digital signal processing

Page 291: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

3.5.9 Discrete convolution

In general, a discrete convolution between twoarrays of discrete samples yin(i) and h(i) is givenby:

( ) ( ) ( )xnhxynyn

0xinout −=∑

=

A digital signal canbe thought of as asummation of aseries of impulses,each offset by asampling interval.

Digital signal is sumof shifted impulses

Let the impulseresponse of a particulardigital filter berepresented by h(i):

To find the convolution of y(i) and h(i) we multiply the individual impulsewith the impulse response function suitably shifted so as to align with theimpulse. Then, all these are added together to obtain the final filtered digitalsignal.

y(i)*h(i)

2

1

−1

1

i

h(i)

y(i)

i = 1

1

2

1

i = 2

1

2

1

i = 3

1

2

1

i = 4

1

2

1

2

4

2

1

2

1

−1

−2

−1

1

2

1

i

x

x

x

x

+

+

+

0 0 0 2 5 3 0 1 1 0

0 0 0 2 1 −1 1 0

n goes from 0 to (Ny+Nh − 1). Arrays are numberedfrom 0 to N − 1 and contain N elements.

Newnes Interfacing Companion278

Page 292: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

A simple (non-recursive) difference equation which performs a five pointweighted averaging is:

3.5.10 Digital filtering (t-domain)

The time domain approach is often used in digital filtering in preference tothe ω-domain approach. There are several methods of approximating thedesired ideal filter transfer function. The transfer functions of two popularlow pass methods are shown:

Ideal Butterworth

ChebyshevH(ω)

ωc

A computer program can beused to calculate thefollowing sum to obtain thefiltered value of yi.

−= ∑∑

=

=

1M

1kkik

1N

0jjij

oi ybxa

b1y

N is the number of forward coefficients (aj) andM the number of reverse coefficients (bk).

( ) ( )2i2i21i1i1ioi yyayyayay−+−+

++++=

The actual filtering function is an equation (called a difference equation)which gives the smoothed value of yi in terms of the actual value of yi andvarious weighted combinations of previous and future values of y.

The procedure for finding the form of the difference equation and thevalues of the coefficients for a particular digital filter is for an advancedcourse in DSP although we will look at a simple example next.

The impulse response of a particular difference equation is found bysetting yi to 1 when i = 0 and yi to 0 otherwise. For example:

( ) ( )( ) ( )( ) ( ) 321o2

121o1

o21o0

a10a00a0aya00a10a0aya00a00a1ay

=++++=

=++++=

=++++=

2793.5 Digital signal processing

Page 293: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

3.5.11 Example

Let the measured value yi at i∆t be expressed as a sum of two sine waves(plus a DC term if needed @k = 0) making N = 3.

Measureddata

Sine wave#1

Sine wave#2

yi

t

∆t

Note: The data is equally spaced so thatthe ith measurement is at time i∆t.

Consider a set of measurements of a quantity y taken at equal timeintervals ∆t (a sampling frequency of 1/f).

We require an equation which gives the best estimated values of yi atany particular value of i. That is, a smoothing equation.

Let the smoothed value of yi at each data point be given by the formula:( ) ( )2i2i21i1i1ioi yyayyayay

−+−+++++=

This is a five point smoothing equation (the difference equation).

Non-recursive moving average filter

( ) ( ) Nki2j2

0ki eF

31tiy π

=

∑ ω=∆

Newnes Interfacing Companion280

Page 294: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

( )( ) ( )

( ) ( )

( )

( ) [ ]

( ) ( )∑

=

π

=

π

=

π−π

π−π

π

=

−π+π

−π+ππ

ωω=

π+π+ω=

+

+++ω=

+

+++ω=

2

0k

Nki2jkk

2

0k21o

Nki2jk

2

0kNk2j2tNk2j2

2

Nk2jNk2j1oNki2j

k

2

0kNk2i2jNk2i2j

2

Nk1i2jNk1i2j1

Nki2jo

ki

eHF

Nk4cosa2Nk2cosa2aeF

eea

eeaaeF

eea

eeaeaFy

yi are the actual data points and yi are the smoothed or fitted data points.The constants ao, a1 and a2 are to be chosen so as to smooth any noise fromthe actual data. Contributions to the smoothed value of a particular datapoint come from the actual data and four neighbouring data points yi+1, yi-

1, yi+2 and yi-2 making a five point smoothing formula. Now, each of themeasured data points yi can be calculated from the summation of the sinewaves #1 and #2 evaluated at n = i. Substituting gives:

3.5.12 Smoothing transfer function

tcos2ee tjtjω=+

ω−ωbut

H(ω) is a filter transfer function. Note that the form of F(ω) need not beknown precisely since once the coefficients ao, a1 and a2 have beendecided, we can obtain yi from the difference equation. If it is known thatthe original data contains say high frequency noise, then values for thesmoothing coefficients are selected such that H(ω) has the form of a lowpass filter. The coefficients ao, a1 and a2 are found by simultaneousequations of data points taken directly from the desired transfer function.Three coefficients require three such data points (H(ω),k) to be used in thetransfer function to obtain values of ao, a1 and a2. These values are thenused in the difference equation to give the fitted values of yi at the desiredvalue of i.

( ) ( )2i2i21i1i1ioi yyayyayay−+−+

++++=Differenceequation

^

Nk2tk

π=∆ωwhere

2813.5 Digital signal processing

Page 295: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

3.5.13 Review questions

1. Determine the real and imaginary parts of the DFT coefficients of thefollowing “real” digital signals:(a) 1, 2, 3, 1, 2, 3(b) 0, 1, 1, 0

2. The data shows the average daily temperature in oC for each month ofa year in Sydney, Australia.(a) Calculate the Fourier coefficients An,

Bn for the following data for all therequired values of k.

(b) Draw a histogram of the data.(b) Draw a frequency spectrum.(c) Perform an inverse DFT to check your

results of (a).

Jan 25Feb 23Mar 22Apr 20May 19Jun 18Jul 17Aug 17Sep 19Oct 22Nov 23Dec 25

3. Using the method of a digital convolution, findyout(i) = y(i)*h(i) for the following numbersequences:

y(i) = 1, 3, 2, −1, 4h(i) = 2, −1, 3

( ) ( ) ( )kihiyiy1N

0kinout −=∑

=

4. Design a seven point smoothing formula of the form:

which corresponds to a transfer function H(ωk) approximating tothe shape shown. Plot the actual transfer function calculated.

1

0.5

0.5 1

H(ωk)

k/N

( )( ) ( )3i3i32i2i2

1i1i1ioiyyayya

yyayay

−+−+

−+

++++

++=

Hint: Take H(0) = 0; H(1) = 1; H(0.5) = 0.5, H(0.8) = 1

(Ans: 2, 5, 4, 5, 15, −7, 12)

Newnes Interfacing Companion282

Page 296: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

A temperature measurement system consists of a thermocouple connectedto a difference amplifier, the output of which is fed into an ADC and thenstored as an array of equally spaced readings on a microcomputer.Samples are taken every 5 seconds. Design a digital filter (in the languageof your choice) which smoothes out any high frequency noise from thisdata. The smoothed data is to retain fluctuations which occur over a timegreater than about a minute.

Thermocouple

Amplifier

ADC

Serial port

Data yiDigital Filter Data yi

^

DAC

Output display

Computer

3.5.14 Activities

2833.5 Digital signal processing

Page 297: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Newnes Interfacing Companion284

Page 298: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

285

Page 299: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Index

Newnes Interfacing Companion286

2’s complement 782nd order 2442nd order active filter 2343 dB point 23880X86 CPU development 978250 UART 1408421 code 81

A to D and D to A conversions 147abort 103above the gold point 17absolute address 91absorbed 25AC 57acceleration 59acceleration and vibration 59accumulator 98accuracy 12actinometric definition 36actinometry 35action 187active filters 227active filters – op-amp circuit 228active integrator/differentiator 231activities 28, 87, 108, 126, 224, 244,

257, 283actuator 4actuators 184ADC 148, 153, 154ADC08xx chip 156address 89, 90, 92address data 90, 92addressing 120aliasing 149aligned 92ALU 97ambient light 51amplification 43amplitude spectrum 274analog to digital converter 148, 152analog to digital converters 152AND 84angular displacement 48angular velocity transducer 50aperture error 155API 161architecture 89arcing 46

arithmetic logic unit 97ASCII 74ASCII code 83assembler 113, 127assembler directives 115, 116assembly language 111, 113, 201assembly language instructions 115assembly language program structure

115assembly language shell program 118asynchronous 165atmospheric pressure 61avalanche photodiodes 41

band reject 236bandpass 236bandpass filter 245bandpass filter – narrow 236bandpass filter – wide 240bandwidth 151, 265base 98base address 90, 138base pointer 99based addressing 122based index 123BASIC 205basic input/output services 101baud 167baud rate 141baud rate divider 171BCD 81bernoulli’s equation 68bi-directional 89binary coded decimal 81binary coded decimal (BCD) 81binary number system 74, 84binary to decimal 75BIOS 101, 102BIOS interrupts 124BIOS service routines 145BIOS services 174, 202bit 74block 104, 136bolometer 38Boolean algebra 84bounce 46Bourdon gauge 63branching 114, 119

Page 300: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

287Index

brightness 37buffers 93, 137bus 89, 178bus-mastering DMA 136, 161bus address 179bus master 136byte 74, 77byte to serial conversion 165

candela 36, 37capacitance 25, 69capacitive transducer 48capacitor 65carbon button 65carrier 166carry 80, 85Celsius temperature scale 16central processing unit 97centroid 51centronics 143channels 136, 273charge 57charge amplifier 58charge coupled device 41chip-select 93chopping 266circuit construction 195classes of operations 112clock 94, 141clocked flip-flop 95CMRR 247CMRR cross-coupled inputs 251code segment 98, 114, 117coils 186cold junction compensation 23Colpitts oscillator 171comments 115common mode rejection ratio 248communications 164complement 78complementary currents 160complex numbers 215computer 283computer architecture 88, 89computer interface 60computer interfacing 2, 72, 212condenser 65condition code 119conditional 119contact 18

contact potential 22, 23contacts 186control bus 89control statements 119controlled variable 4controller 178conversion time 153, 154, 155, 156convert from decimal to hex 77convert from hex to binary 77convert from hex to decimal 77convolution 277core 49correction signal 11correlated 267correlation 266count 98counter 186CPU 89, 97critically damped 234cross-correlation 267crystal oscillator 171cutoff 238

DAC 148DAC0800 160dashpot 13, 59data 89, 92, 98data acquisition board 161data acquisition project 192data acquisition system 33data bus 89data communications 163data packet 179, 180data registers 98data segment 98data transfer rate 177DC 57DCE 166debounce 46debug 126decibel 241decimal 76decimal to binary conversion 75decimal to hex conversion 77decoding circuitry 93deflection method 5depletion region 40derivative 11descriptor tables 105detectivity 6

Page 301: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Newnes Interfacing Companion288

device driver 106dielectric 48difference amplifier 247, 257difference amplifier with cross-coupled

inputs 250difference amplifier with voltage

follower inputs 249difference equation 279, 280different types of pressure 64differential equations 216differential operator 216, 219differential pressure 66differential pressure level 69differentiator 218, 231differentiator – passive 221differentiator transfer function 237digital filtering (ω-domain) 276digital filtering ( t-domain) 277digital filters 270digital logic circuits 85digital signal processing 269digital to analog conversion 159digital to analog converter 148digital to analog system 208diode 253diode array 51direct indexing 123direct memory access 106, 133, 136direct memory addressing 121disappearing filament 21discharge coefficient 66discrete convolution 278discrete Fourier transform 274, 276discrete samples 276displacement 123dissimilar metals 22DMA 96domain name server 181doppler shift 67double integrator 235double words 92drag-torque tachometer 50driving frequency 49dry bulb 25DTE 166dual slope 153dynamic 4dynamic response 10dynode 43

eddy currents 50effective address 121electrostatic discharge 263email 181EMI 263enumeration 180environmental noise 263error 8, 11ethernet 181Euler’s formula 271EXE 118execution time 185extended ASCII 83extra segment 98

Fahrenheit temperature scale 16fast Fourier transform 274fault 103feedback transistor 253fetch 114filtering 275filters 228finite impulse response 270firewire 180first party 136fixed points 16flag register 119flags 99flicker noise 262, 264flip-flop 95float 68, 69flow 66follower inputs 257force 57, 65Fourier analysis 9, 270Fourier integral 275Fourier series 271Fourier transform 272frequency 39frequency domain 217frequency resolution 273fsd 8fuel level sensor 47full scale deflection (fsd) 7functional components 186fundamental interval 19furnace 27

Page 302: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

289Index

gain 233, 250general transfer function 232GPIB 164, 178gray code 82

half adder 85handshake packet 179handshaking 176hardware 23hardware device interrupt number 135hardware handshaking 176hardware interrupts 102, 103hex 76hexadecimal 76high pass 229high pass filter 239high voltage 46hub 179hysteresis 8

I/O 89ice point 17IEEE 1284 145IEEE 1394 180IEEE 488 178IER 140IF flag 103IIR 270IIR 140illuminance 36, 37immediate addressing 120impedance matching 214impulse response 279indexed memory addressing 123indirect addressing 122indirect memory addressing 122industrial pressure measurement 64industrial thermometers 18infinite impulse response 270input/output (I/O) 96input/output ports 133input port 132input response time 185inputs 184instruction decoder 97, 114instruction pointer 99, 114instruction set 112instructions 92instrumentation 2, 72, 212, 214instrumentation amplifier 246, 252

integral 11integral transform 216integrating 152integrator 218, 231integrator – passive 220integrator transfer function 232interface 72interface card 164, 178interfacing 131, 132, 148interfacing in a multitasking

environment 134interference 263internal relay 189international temperature scale 16interpolate 52interrupt function 124interrupt handler 102interrupt latency 135, 161interrupt service routine 102, 124interrupt vector table 103, 124interrupts 102, 124, 133, 135intrinsic noise 262inverse Fourier transform 272inverse transform 276IP addresses 181IRQ 135ISA 96

kd 11Kelvin 17ki 11kilobyte 74kp 11

ladder logic diagrams 187, 188ladder network 159Laplace operator 217Laplace transform 216, 217, 219latch 94, 158, 186latched 189latches 94laws of Boolean algebra 85LCR 139lead zirconate titanate 57leakage 57level 69LIFO 100light 34, 35light dependent resistor (LDR) 39line drivers 170

Page 303: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Newnes Interfacing Companion290

linear encoder 52linearity 7liquid-in-glass thermometer 20list code 187, 188listener 178lock-in amplifier 266log amplifier 253logic continuity 187logic gates 84, 85logic instructions 184logic states 84long word 92low pass 234low pass filter 229low pass filter – active 233lsb 74LSR 139lumen 36luminous flux 36luminous intensity 36lux 36, 37LVDT 49

machine code 112machine language 112magnetic circuit 50magnetic coupling 49mandrel 47mantissa 78mark 167, 170mass 60mass balances 60matching point 21maths co-processor 78MCR 139, 176, 202measurement systems 3measuring light 36mechanical models 13mechanical stressing 64mechanical switch 46megabyte 74memory 89, 90memory-mapped 89, 96, 132memory addressing 121memory data 92memory map 104metal foil 55methods of measurement 5microprocessor interrupts 102, 103microprocessor unit (MPU/CPU) 97

mnemonic 115modem 137, 166modulation 65, 277motion control 11, 52MOV instruction 120moving coil 65msb 74, 80MSR 139multiplexing 89, 161multiplication 80mylar sheet 25

NAND 84nanometre 49negative numbers 79noise 6, 215, 261noise current 265noise equivalent power 265noise figure 264noise floor 6non-contact 18non-linear 23, 24, 56non-maskable interrupt 103non-periodic 273non-weighted 82NOR 84notch 236null method 5null modem 173, 180number systems 73Nyquist criterion 149

OBJ 118octal latch 94offset 90offset registers 99op-amp frequency response 254opcodes 112operands 115operator 215, 218operator notation 218optical detectors 42, 265OR 84orifice plate 66OSI Reference Model 181OTG 180output port 132output response time 185overdamped 234oversampling ratio 151

Page 304: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

291Index

packets 180, 181parallel connection 178parallel port 143parallel port registers 144parallel printer port 143parallel printer port operation 145parity 167parity bit 83parity error 167passive filters – RLC circuits 228PCI 96permanent magnet 65phase 49phase changes 52phasing error 185photoconductivity 39photodiode 40photometric definitions 36photometry 35photomultiplier 43photon flux 36phototransistors 41photovoltaic 40physical phenomena 2, 72, 148, 212PID 11piezoelectric crystal 59, 64piezoelectric force transducer 57piezoelectric sensor instrumentation

58piezoresistive 55, 64piezoresistive strain gauge 57PIN photodiode 41platinum resistance thermometer 19PLC 184PLC specifications 190plug and play 179, 180polarity 170polling 133, 134popping 100port 132port address 132, 133, 137port number 96, 133port number I/O device 133ports 96position and motion 45position sensitive detector 51position sensitive diode array 51positional resolution 51positive displacement 67positive numbers 79

potentiometric sensor 47preamplifier 6, 214, 263precision 12pressure 63pressure drop 66pressure switch 63printer port 145printer port control register 144printer port data register 144printer port status register 144priority 102, 103privilege level 105process control 4process variables 4processor exceptions 102program counter 114program execution 114programmable 138programmable interrupt controller 102,

135programmable logic controllers 183,

184programming 187, 201psd 51psychrometer 25pulse extender 189pushing 100pyroelectric 38pyrometers 21PZT 58

quadrature signal 52quantisation error 150quantisation noise 150, 151quantum efficiency 39quartz 57quartz crystal 58, 65

radar 69radiant energy 36radiant flux density 36radiant intensity 36radiant power or flux 36radiation pyrometer 21radiometric definitions 36radiometry 35random access memory 101random error 12range 7read/write 89, 93

Page 305: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Newnes Interfacing Companion292

read/write operation 92read only memory 101real 105real and protected mode CPU

operation 105receiver 18red filter 21reference signal 267reference voltage 153register 120, 138register addressing 120register and immediate addressing 120registers 90, 97, 98, 136, 186rejection 230relative humidity 25relative offset 122relocatable 113request register 136reset 95resistances 55resolution 6, 8, 150resolution and quantisation noise 150resonant frequency 10, 57review questions 14, 26, 44, 53, 70,

86, 107, 125, 146, 162, 182, 191,223, 242, 255, 268, 282

RF noise 263rise time 10, 51ROM 101rosette 55rotary encoder 52, 82RS232 137, 166RS232 interface 166RS485 177rungs 187

sample-and-hold 157, 161, 206sample-and-hold control 158sampling 273sampling frequency 273sampling rate 149scan rate 161scan time 185scans 184scatter 12Schottky photodiodes 41scientific notation 78Seebeck effect 22segment base address 91, 122segment registers 98

segmented 90segmented address 91segmented memory 89, 91segments 90seismic mass 59self-heating 19semiconductor 24sense leads 56sensitivity 6, 7, 58sensor 2, 72, 212serial communications 60serial data acquisition system 193serial port 137, 164serial port addresses 138serial port baud rate 141serial port BIOS services 174serial port object 142serial port operation 142serial port operation in BASIC 175serial port registers 139serial port registers and interrupts 140serial transmission 164service routines 142servicing 132servo feedback loop 11set point 4, 11shared interrupt 135shift 80shift register 165shot noise 262shunt 56sign bit 79signal current 265signal processing 2, 72, 212signal-to-noise ratio 6, 151, 263signed numbers 79silicon diaphragm 64silicon wafers 25simple switch type 63size codes 121smoothing formula 281smoothing transfer function 281SNR 6software 23software interrupts 102, 124sound 65space 167, 170span error 7spectrophotometer 51speed 132

Page 306: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

293Index

springs 13stack 100stack pointer 99, 100stack segment 98staircase 152standard observer 37standard thermometers 17standards of measurement 37start-up routines 101status register 114step 10step size 52steradian 36stop bits 167strain gauge 55strain gauge factor 55subroutine 100subtraction 80subtraction and multiplication 80successive approximation 152switch 46symbol 187synchronisation 167systematic error 12

T-network filters 229talker 178task register 105TCP/IP 181telnet 181temperature 15, 16temperature drop 67thermal (Johnson) noise 262thermal detectors 38thermal expansion 55thermal noise 264thermistors 24thermocouple 22thermoelectric sensitivity 23thermopile 38Thomson effect 22time-shared 106time domain 217, 279timer 186timing 185token packet 179, 180toothed-rotor magnetic tachometer 50total resistance 51transducer 2, 4, 72, 212

transfer function 213, 214, 215transfer impedance 222, 229transforms 216transmitter/receiver 170transmitters 6trap 103tri-state 93, 177true value 12truth table 84, 95TTL 84turbine 67turndown 67twin-T filter 230, 245

UART 137, 165, 168UART clock 171UART master reset 172ultrasonic level transducers 69underdamped 234unidirectional 89unsigned integer 79USB 179

vector interrupt 103vena contracta 66venturi 66vibration 64, 59, 263virtual 8086 mode 106virtual device drivers 106virtual memory space 105VM flag 106voltage amplifier 58voltage amplitude 49voltage differentials 177voltage followers 247voltage gain 241

weighted input 159wet bulb 25white 262words 74, 92work function 43world wide web 181XOR 84, 85xray diffraction 51

zener diode 23zero 6zero offset 7

Page 307: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

Further readingR.M. Bertrand, “Programmable Controller Circuits ,” International ThomsonPublishing, 1995.H.B. Boyle, D. Page, “Transducer Handbook: User's Directory of ElectricalTransducers,” Butterworth-Heinemann, 1999.W. Buchanan, “Applied PC Interfacing: Graphics and Interrupts,” AddisonWesley Longman, Inc., 1996.F.M. Cady, "Microcontrollers and Microcomputers: Principles of software andhardware engineering," Oxford University Press, 1997.D. Crecraft, S. Gergely, “Analog Electronics Circuits, Systems and SignalProcessing,” Butterworth-Heinemann, 2002.A.J. Diefenderfer, B.E. Holton, "Principles of Electronic Instrumentation," 3rdEd., International Thomson Publishing, 1994.M. Elwenspoek, R. J. Wiegerink, “Mechanical Microsensors,” Springer-VerlagNY, 2000.D.R. Gillum, “Industrial Pressure, Level and Density Measurement,” ISA, 1995.A.R. Hambley, "Electrical Engineering: Principles and Applications," Prentice-Hall, Inc., 1997.E.C. Ifeachor, B.W. Jervis, “Digital Signal Processing: A Practical Approach,”2nd Ed., Pearson Education, 2002.J.H. Johnson, "Build your own low-cost data acquisition system and displaydevices," TAB Books, 1994.M. Predko, “PC PhD: Inside PC Interfacing,” McGraw-Hill Professional, 1999.W.H. Rigby, T. Dalby, “Computer Interfacing: A Practical Approach to DataAcquisition and Control Lab Manual,” Simon & Schuster, 1995.I.R. Sinclair, “Sensors and Transducers,” Butterworth-Heinemann, 2001.G.A. Smith, “Computer Interfacing,” Butterworth-Heinemann, 2000.M.H. Tooley, “PC-based Instrumentation and Control,” 3rd Ed., Butterworth-Heinemann, 2002.W.A. Triebel, "The 80386, 80486, and Pentium Processors: Hardware, Softwareand Interfacing," Prentice-Hall, 1998.M.J. Usher, D.A. Keating, "Sensors and Transducers," 2nd Ed., MacmillanPress Ltd, 1996.R.M. White, R. Doering, "Electrical Engineering Uncovered," Prentice-Hall,1997.I. Busch-Vishniac, “Electromechanical Sensors and Actuators,” Springer-Verlag,NY, 1998.

Newnes Interfacing Companion294

Page 308: (Newnes) interfacing companion -computers, transducers, instrumentation & signal processing

SemiconductorsIC-CMOS/LSI UART CDP6402CEIC-COMS 8-BIT A/D ADC0804LCNIC-DUAL TRANSCEIVER MAX232CPEIC-74 SERIES TTL DM7400NIC-74HC SERIES CMOS MC74HC04ANIC-74HC SERIES CMOS 74HC393NIC-74 SERIES TTL DM7476NIC-TEMPERATURE SENSOR LM335HIC-8-BIT DAC DAC0800LCNIC-SAMPLE AND HOLD LF398NIC-SUPER GAIN OP AMP LM308HIC-COMPENSATED OP AMP UA741CNDIODE,ZENER 4V7 BZX284-C4V7/T1CRYSTAL,4.915200 MHZ 4079WT-4M9152IC-FET OP AMP LF356H

Parts lists for activities

Part 11 × LM335H precision temperature reference1 × IN4732 4.8V zener diode2 × 220k; 1 × 2.2k; 1 × 100 Ω; 1 × 4.7k; 1 × 680 Ω; 1 × 1K

Part 21 × ADC0804 A to D converter1 × 6402 UART1 × 7400 NAND1 × 232CPE RS232 line driver1 × 74HC04 hex inverter CMOS1 × 74HC393 CMOS counter1 × 4.9152 MHz crystal2 × 33 pF; 1 × 147 pF (or 3 × 47 pF);4 × 1 µF; 1 × 4.7 µF; 1 × 47 µF;2 × 3.3k; 1 × 10M; 1 × 100k;1 × 1k; 2 × 10k

1 × 7476 JK flip-flop1 × LF398 sample and hold1 × 0.01 µF capacitor

1 × DAC0800 D to A converter2 × 4.7k; 2x 10k1 × 0.01 µF; 2x 0.1 µF

Part 32 × LM308N operational amplifier1 × 741 operational amplifier2 × 100 pF2 × 2.2k; 1 × 56 Ω; 2 × 470 Ω; 2 × 4.7k

295Parts lists