Mike James is an established author and experienced FE lecturer. He currently works for Westland. His latest Newnes titles are Microcontroller Cookbook and Higher Electronics.
Interfacing with C is about interfacing personal computers using C. Anyone who is interested in ports, transducer interfacing, analog to digital conversion, convolution, filters or digital/analog conversion will benefit from reading Interfacing with C. Students will also find this a practical introduction to real-time programming with a generous collection of tried and tested programs.The pace of the book is such that the reader is encouraged to run the programs and experiment with C. The principles precede the applications in most cases in an attempt to provide genuine understanding and encourage further development. Readers will gain much from the hands-on experience the authors' approach provides, an approach designed to enable readers to climb steep learning curves with the minimum amount of assistance. The many programs included in the text provide the essential hands-on experience. Some of the programs inevitably become rather lengthy, so the source code used is available as a free download from the Newnes website. The aim of the book, however, is to give the reader enough confidence to rewrite and improve these programs.In the second edition Mike James has thoroughly updated all aspects relating to software, operating systems and graphical interfaces. He has also increased the scope of the book to include current forms of C++. Material on data acquisition has been thoroughly updated and the section on peripherals increased. - A practical and painless way of becoming an expert C programmer- New edition also covers C++ and the Windows environment- Get up to speed with the essential maths needed for C without having to buy a university maths text!
Front Cover 1
Interfacing with C 4
Copyright Page 5
Table of Contents 6
Preface 8
Preface to second edition 10
Chapter 1. An introduction to C 12
Properties and background 12
Fundamental interfacing 14
Programmable input–output devices 15
8255 programmable peripheral interface 15
Programming the 8255 18
IBM PC bus 19
Accessing specific memory locations with C 20
Reading the contents of I/O space using pointers 22
C program development 24
Variables 28
Data type 28
Qualifiers 29
Reading the status of an input port 29
Controlling printf() 31
The coercion operator: cast 32
Writing from keyboard to output port 32
Entering data using scanf() 32
Further reading 35
Chapter 2. Loops and data conversion 37
Repetition: unconditional jumps 37
Named constants # define
37
Infamous goto 39
For-loops in greater detail – in a binary counter
40
Port monitoring with a do-while construction 41
Light chaser effect 44
Communicating with peripherals 44
A-to-D systems and circuits 46
Successive approximation 47
Flash conversion 48
Dual and quad slope conversion 49
Synchronization and software control 50
12-bit A-to-D conversion 51
IBM-PC AD574A interface 52
Chapter 3. Data acquisition using C 57
Data capture using CGA graphics 57
Controlling the coordinate 57
Data capture with EGA graphics 59
Background and foreground colour 60
Building a Windows Application 60
Transducer interfacing with C/C++ 65
Conditioning the signal voltage 66
Simplifying program development 67
Displaying temperature using EGA graphics 69
Trying fancier software 70
Introducing random noise 71
A linear transducer 72
Measurement of Iight intensity 73
Statement of the problem 74
Further reading 77
Chapter 4. Essential mathematics 78
How many snapshots? 78
Mathematical modelling
80
Laplace transforms 81
Electronic calculus 82
Modelling A-to-D conversion 84
Zero-order sample-and-hold 86
z-notation – the algebra of sampled data systems 88
Further reading 91
Chapter 5. Convolution 92
Matching analogue signals and systems 93
Frequency-shifting rule 95
Convolution 95
Graphical interpretation of the convolution integral 96
Obtaining the digital output recursively 98
Digital feedback 98
Obtaining the digital output by convolution 100
Reconciling time-domain and frequency-domain processes
102
Computerized convolution 103
System response testing 104
Applying the program 105
Sophisticated applications 108
Further reading 110
Chapter 6. Digital filters 111
Peripheral hardware requirements 111
Conversion of sinusoidal signals 113
Analogue and digital filters 115
Poles and zeros 122
Band-pass digital filters 125
Real-time band-pass filter 128
The bilinear transform 132
Further reading 144
Chapter 7. Fourier transforms 145
Fourier transforms using a PC 145
Discrete Fourier transform DFT
145
Developing and explaining the program
148
Graphical spectral analysis 149
Understanding the logical system of coordinates 150
Applying the DFT program
150
Streamlining the arithmetic using the fast Fourier transform
153
How many multiplications? 153
FFT with real-time data capture and graphics 161
Control of the peripheral board and data capture 163
Signal truncation and spectral leakage 164
Reducing spectral spreading with a Hanning window 166
Further reading 167
Chapter 8. Correlation 168
Correlation methods using a PC 168
Linear systems and random inputs 168
Wiener-Khintchine theorem 171
Autocorrelation 172
Effect of finite observation time 173
Calculating discrete autocorrelation functions 173
Computing the autocorrelation function 174
Anatomy of the program 174
Graphical autocorrelation 176
Applying the program 176
ACF of sampled sine wave 176
ACF of decaying exponential 177
White noise 179
Generating random noise and computing the ACF 181
Anatomy of the program 181
Using autocorrelation to detect noise-corrupted signals 183
ACF with real-time data capture and graphics 184
Autocorrelation in the real world 185
The cross-correlation function 185
System testing and characterization using random noise 188
Order out of chaos 190
Further reading 193
Chapter 9. Kalman fiIters 194
Kalman filters – predicting uncertainty 194
Characterizing stochastic noise – Noddies' guide to statistics 196
Tracking a time-varying signal in the presence of noise – optimal estimation
199
Applied optimal control 200
Real-time Kalman filter 201
Simplifying the design – the steady-state Kalman filter 203
Appendices 203
Further reading 212
Chapter 10. Data conversion 213
Digital-to-analogue conversion
213
A primitive digitally controlled potentiometer 215
Buffering a binary-weighted resistor network 215
R-2R ladder network 216
Analog devices AD7226 D-to-A converter 218
Waveform generation using a D-to-A and C 219
Generating sine waves –
220
Waveform synthesis 220
Software-based random-noise generator 222
Digital transfer functions and waveform modification 223
Generating echo and reverberation 227
Historical records and circular buffers 232
Anti-aliasing filters and filtering the D-to-A output 233
Quantization noise 234
Simulating audio reverberation 234
Special audio effects 236
Further reading 238
Chapter 11. Investigati ng the spectral and time-domain performance of z-transforms using computer-managed instruction 239
Characterizing the frequency-selective properties of the rational function 240
A description of the frequency-selective properties of zeros 249
Programs listed in Appendix 2 256
Further reading 257
Chapter 12. Introduction to digital signal processing
258
Analog Devices 259
Software 263
Fixed point arithmetic 265
Application specific 265
Chapter 13. Standard programming structures 267
Introduction 267
Modular design 267
The internal structure of modules 268
Standard programming structures 269
Eight different ways to convert temperature in Celsius to Fahrenheit using C-based code 274
The sequence construct 274
Using the pre-processor directive 275
The repetition construct 276
Branching and looping 277
Writing functions in C 278
Commentary 278
Using purpose-built I/O functions – Peeking and Poking 279
Using the functions peek() and peekb() 280
Using the functions poke() and pokeb() 283
Port-mapped data transfer 283
Input circuit 284
Output circuit 284
Computer part of the problem 285
Microsoft C I/O calls 286
Further reading 289
Appendix 1 290
Appendix 2: Listings of programs described in Chapter 11 291
Listing 11.1 Graphical amplitude-ratio and phase response of rational z-function 291
Listing 11.2 Graphical convolution 295
Listing 11.3 Numerical amplitude-ratio and phase response of rational z-function 297
Listing 11.4 Numerical convolution 299
Glossary 302
Index 305
Loops and data conversion
Repetition: unconditional jumps
Repetition occurs prominently in many programming applications; C provides a number of particularly attractive and elegant constructions. In Figure 2.1, we require the main body of the program to be repeated indefinitely. One possible construction which avoids using the infamous ‘goto’ is:
This is a for( ) loop which has no initial condition, no terminating condition and no action which is applied on each iteration of the loop. Since there is no terminating condition, it does not ever terminate; it is a forever loop.
Figure 2.1 A simple flow diagram to light an LED
The program in Listing 2.1 is designed to read a number from the keyboard, to output the binary value to leds attached to port A and to read/display the contents of port A. Repetition is illustrated by the flowchart Figure 2.1. Alongside this is a construction called Structured English. It is an alternative way of describing a problem to be committed to software. More is explained about it on page 262. It is a descriptive structure which does not require graphic symbols and yet has a very good correlation to the code which it describes. The indentation is used to help visually align code under control of the LOOP construction.
Listing 2.1a: C
Connecting the data display circuit Figure 1.7 demonstrates the effect of the program. Alternatively this program construction successfully controls the speed of a small d.c. motor. A suitable circuit is shown in Figure 2.2.
Figure 2.2 Hardware for computerized speed control is simple: most of the work is done by the software
Integers 0 to 15, input from the keyboard, are processed through the 4-bit D-to-A and power amplifier to provide 16 unique speeds. This simple uni-directional open-loop control system provides the basis for more advanced closed-loop control.
Named constants #define
Listing 2.2 generates a square wave of approximately 5 V p–p at a frequency of 500 kHz, by causing PA0 to go repeatedly high, then low. As a programming exercise it demonstrates how to replace names for constants, improving the readability of the program. Most C/C++ programmers use upper-case letters when naming a #define constant: this helps to distinguish variables from defined constants. Notice that the constants are defined outside the main program and not terminated with a semicolon.
Listing 2.1b: C++
Infamous goto
The primitive, repetitive nature of this program provides an excuse to demonstrate an unconditional jump; using the goto statement. Many of the erudite books written about C/C++ insist that it should be avoided, or used with extreme caution. This is good advice, since its use encourages unstructured programming and makes programs difficult to read. Not wishing to be contentious, we show how the structured infinite for-loop can be replaced by the unstructured goto, without loss of readability (in this example). When the goto statement is executed, control is transferred to the C/C++ code following the label (in this case start). The label is always terminated by a colon.
The goto is generally considered to be a no-no for serious programmers, because it can lead to ‘spaghetti code’ which is very difficult to follow and debug. Many professional software houses forbid its use in any high level language programs. Having said that, it is the main method of transferring program control in assembly language programs. These are only included in small doses within a C/C++ program, usually to speed up a critical part of its operation. There is never an application in C/C++ which cannot be programmed without a goto. Sometimes, its use does make the resultant code more compact, but if its use is allowed, then use it cautiously and sparingly!
For-loops in greater detail – in a binary counter
Educationally, Listing 2.3 is particularly rewarding, because it demonstrates a number of different loop constructions in a single program. Connecting the data indication circuit (Figure 1.7) to port A configured as an output provides a binary representation of the current status of the count. The denary status is displayed on the monitor using the printf and cout functions. Counting from 0 to 255 is achieved using the post increment operator (i++), a versatile construction meaning i = i+1 (this could also be written using the C/C++ convention i + = 1).
Listing 2.2
Inspection of the structure shows the program consists of a number of nested loops; the outer loop
ensures that the procedure is continued indefinitely. The actual count is controlled by the construction
The terse nature of the expression: i++ < = 255 deserves further explanation. It means test if ‘i’ is less than or equal to 255 and regardless of the result, increase i by one. Two useful features of C/C++ are the increment and decrement operators, meaning i = i + 1 and i = i − 1. The versatility of C allows you to test the value of ‘i’ and then add 1 to it – post increment operator i + +. Or add 1 and then test, the pre-increment operator + +i. A similar construction is provided for decrementing. To produce an observable display it was necessary to introduce a significant time delay into the loop. This is exploited to demonstrate the ‘for’ construction in greater detail.
The for-loop construction is particularly elegant in C, succinctly combining the three loop parameters (initialize, test and increment) in a single bracketed term. Expression 1 initializes the count. Expression 2 indicates the condition for the count to continue and expression 3 denotes the action which must be taken before the loop repeats. Referring to my example program, notice that k is incremented after the main body of the for-loop has been executed. Incidentally, the use of i, j and k as loop counters was introduced as early as the 1960s when the FORTRAN programming language reserved variables as integers which started with these letters.
Port monitoring with a do-while construction
In this example (Listing 2.4) the program monitors the switches on port A and displays the decimal value on the screen, before latching the binary value to leds on port B. Including the conditional do-while statement ensures the body of instructions are always executed at least once, before the test is made. Thereupon, looping continues until the result of the test is false. Observe how the test monitors the input port and compares the current contents (called new_contents in the program) with the old_contents. When this expression is false (the double equal signs = = mean ‘of the same value’ in a comparison) control transfers to the instruction following the while-statement.
Listing 2.3
Figure 2.3 For-loop flowchart
Figure 2.4 Flowchart for Listing 2.4
The versatility of C provides an alternative while-do construction, which tests an expression and if true, permits looping to continue until the result of the test is false, at which point control passes to the next instruction in the program. These structured flowchart constructions are shown in Figure 2.5.
Figure 2.5 The anatomy of structured control
Be careful with the use of = and = =. The C/C++ expression
as shown in Listing 2.4 compares the values of variables new_contents and old_contents. If these are the same, then the statement(s) which follow it will be executed. Compare this with
This is a perfectly valid C/C++ expression. However, it allocates to the variable new_contents the value held in a variable called old_contents. Since new_contents and old_contents are now the same, the while statement then evaluates the contents of the bracketed term as zero. As was stated in Chapter 1, a zero is FALSE, so the statements which follow the while expression will never be executed.
Light chaser effect
This program Listing 2.5 is designed to produce the effect of a light running repeatedly across the leds connected to port A, which is conditioned as an output. It works by taking powers of 2 and writing the byte to the port. Don’t imagine this is frivolous; it does have a serious side, demonstrating how to write your own functions using C. Observe that the structure is composed of the main function that controls the flow of the program, together with an external function called power(x,n) that can be invoked and executed by a single statement in the main program. The new line int power(int x, int n); is called a function prototype. All functions in the program must be declared prior to the main( ) function. This is so that the compiler knows what functions to expect and what types of data will be passed in and out. A function declaration has the...
Erscheint lt. Verlag | 14.12.2000 |
---|---|
Sprache | englisch |
Themenwelt | Mathematik / Informatik ► Informatik ► Betriebssysteme / Server |
Mathematik / Informatik ► Informatik ► Programmiersprachen / -werkzeuge | |
Informatik ► Weitere Themen ► Hardware | |
ISBN-10 | 0-08-057435-1 / 0080574351 |
ISBN-13 | 978-0-08-057435-6 / 9780080574356 |
Haben Sie eine Frage zum Produkt? |
Größe: 55,6 MB
Kopierschutz: Adobe-DRM
Adobe-DRM ist ein Kopierschutz, der das eBook vor Mißbrauch schützen soll. Dabei wird das eBook bereits beim Download auf Ihre persönliche Adobe-ID autorisiert. Lesen können Sie das eBook dann nur auf den Geräten, welche ebenfalls auf Ihre Adobe-ID registriert sind.
Details zum Adobe-DRM
Dateiformat: PDF (Portable Document Format)
Mit einem festen Seitenlayout eignet sich die PDF besonders für Fachbücher mit Spalten, Tabellen und Abbildungen. Eine PDF kann auf fast allen Geräten angezeigt werden, ist aber für kleine Displays (Smartphone, eReader) nur eingeschränkt geeignet.
Systemvoraussetzungen:
PC/Mac: Mit einem PC oder Mac können Sie dieses eBook lesen. Sie benötigen eine
eReader: Dieses eBook kann mit (fast) allen eBook-Readern gelesen werden. Mit dem amazon-Kindle ist es aber nicht kompatibel.
Smartphone/Tablet: Egal ob Apple oder Android, dieses eBook können Sie lesen. Sie benötigen eine
Geräteliste und zusätzliche Hinweise
Buying eBooks from abroad
For tax law reasons we can sell eBooks just within Germany and Switzerland. Regrettably we cannot fulfill eBook-orders from other countries.
Größe: 19,3 MB
Kopierschutz: Adobe-DRM
Adobe-DRM ist ein Kopierschutz, der das eBook vor Mißbrauch schützen soll. Dabei wird das eBook bereits beim Download auf Ihre persönliche Adobe-ID autorisiert. Lesen können Sie das eBook dann nur auf den Geräten, welche ebenfalls auf Ihre Adobe-ID registriert sind.
Details zum Adobe-DRM
Dateiformat: EPUB (Electronic Publication)
EPUB ist ein offener Standard für eBooks und eignet sich besonders zur Darstellung von Belletristik und Sachbüchern. Der Fließtext wird dynamisch an die Display- und Schriftgröße angepasst. Auch für mobile Lesegeräte ist EPUB daher gut geeignet.
Systemvoraussetzungen:
PC/Mac: Mit einem PC oder Mac können Sie dieses eBook lesen. Sie benötigen eine
eReader: Dieses eBook kann mit (fast) allen eBook-Readern gelesen werden. Mit dem amazon-Kindle ist es aber nicht kompatibel.
Smartphone/Tablet: Egal ob Apple oder Android, dieses eBook können Sie lesen. Sie benötigen eine
Geräteliste und zusätzliche Hinweise
Buying eBooks from abroad
For tax law reasons we can sell eBooks just within Germany and Switzerland. Regrettably we cannot fulfill eBook-orders from other countries.
aus dem Bereich