Phil Lucht Math & Physics Archive
Home / Math and Physics Files / Math / Spectral Theory Book / PDF downloads

Thede book on filter design

PDF · 277 pages · 3.6 MB
Open PDF file

A published engineering textbook by Les Thede, not Phil's own work. It covers analog filter approximations (Butterworth, Chebyshev, inverse Chebyshev, elliptic), active op-amp filter implementation, discrete-time systems and z-transforms, IIR and FIR digital filter design including Parks-McClellan, C code, and FFT-based filtering. It also describes the accompanying WFilter design software.

AI-written summary; may contain errors.

Extracted text (machine-read; may contain errors)
Practical Analog and Digital Filter Design Artech House, Inc. Les Thede 2004 This text is dedicated to my wife who keeps me grounded, and to my grandchildren who know no bounds. vii Contents Preface xi Chapter 1 Introduction to Filters and Filter Design Software 1 1.1 Filter Selectivity 2 1.1.1 Lowpass Filters 3 1.1.2 Highpass Filters 4 1.1.3 Bandpass Filters 5 1.1.4 Bandstop Filters 5 1.2 Filter Approximation 6 1.3 Filter Implementation 8 1.4 WFilter - Filter Design Software 9 1.5 Conclusion 14 Chapter 2 Analog Filter Approximation Functions 15 2.1 Filter Transfer Functions 15 2.1.1 Transfer Function Characterization 16 2.1.2 Pole-Zero Plots and Transfer Functions 17 2.1.3 Normalized Transfer Functions 18 2.2 Butterworth Normalized Approximation Functions 19 2.2.1 Butterworth Magnitude Response 19 2.2.2 Butterworth Order 20 2.2.3 Butterworth Pole Locations 20 2.2.4 Butterworth Transfer Functions 21 2.3 Chebyshev Normalized Approximation Functions 27 2.3.1 Chebyshev Magnitude Response 27 2.3.2 Chebyshev Order 28 2.3.3 Chebyshev Pole Locations 28 2.3.4 Chebyshev Transfer Functions 29 2.4 Inverse Chebyshev Normalized Approximation Functions 34 viii Practical Analog and Digital Filter Design 2.4.1 Inverse Chebyshev Magnitude Response 34 2.4.2 Inverse Chebyshev Order 35 2.4.3 Inverse Chebyshev Pole-Zero Locations 35 2.4.4 Inverse Chebyshev Transfer Functions 37 2.5 Elliptic Normalized Approximation Functions 43 2.5.1 Elliptic Magnitude Response 43 2.5.2 Elliptic Order 45 2.5.3 Elliptic Pole-Zero Locations 45 2.5.4 Elliptic Transfer Functions 47 2.6 Comparison of Approximation Methods 52 2.7 Conclusion 54 Chapter 3 Analog Lowpass, Highpass, Bandpass, and Bandstop Filters 55 3.1 Unnormalized Lowpass Approximation Functions 55 3.1.1 Handling a First-Order Factor 57 3.1.2 Handling a Second-Order Factor 58 3.2 Unnormalized Highpass Approximation Functions 60 3.2.1 Handling a First-Order Factor 61 3.2.2 Handling a Second-Order Factor 62 3.3 Unnormalized Bandpass Approximation Functions 64 3.3.1 Handling a First-Order Factor 66 3.3.2 Handling a Second-Order Factor 66 3.4 Unnormalized Bandstop Approximation Functions 72 3.4.1 Handling a First-Order Factor 73 3.4.2 Handling a Second-Order Factor 73 3.5 Analog Frequency Response 76 3.5.1 Mathematics for Frequency Response Calculation 76 3.5.2 C Code for Frequency Response Calculation 80 3.6 Saving the Filter Parameters 82 3.7 Conclusion 84 Chapter 4 Analog Filter Implementation Using Active Filters 85 4.1 Implementation Procedures for Analog Filters 85 4.2 Lowpass Active Filters Using Op-amps 87 4.3 Highpass Active Filters Using Op-amps 92 4.4 Bandpass Active Filters Using Op-amps 96 4.5 Bandstop Active Filters Using Op-amps 98 4.6 Implementing Complex Zeros with Active Filters 103 4.7 Analog Filter Implementation Issues 106 4.7.1 Component Selection 106 4.7.2 Sensitivity Analysis 108 4.8 Using WFilter in Active Filter Implementation 111 4.9 Conclusion 113 Contents ix Chapter 5 Introduction to Discrete-Time Systems 115 5.1 Analog-to-Digital Conversion 115 5.1.1 Frequency Spectrum and Sampling Rate 116 5.1.2 Quantization of Samples 118 5.1.3 A Complete Analog-to-Digital-to-Analog System 119 5.2 Linear Difference Equations and Convolution 120 5.2.1 Linear Difference Equations 121 5.2.2 Impulse Response and Convolution 124 5.3 Discrete-Time Systems and z-Transforms 126 5.4 Frequency Response of Discrete-Time Systems 130 5.5 Playing Digitized Waveforms on a Computer System 137 5.6 Conclusion 139 Chapter 6 Infinite Impulse Re sponse Digital Filter Design 141 6.1 Impulse Response Invariant Design 142 6.2 Step Response Invariant Design 146 6.3 Bilinear Transform Design 151 6.4 C Code for IIR Frequency Response Calculation 158 6.5 Conclusion 160 Chapter 7 Finite Impulse Re sponse Digital Filter Design 161 7.1 Using Fourier Seri es in Filter Design 161 7.1.1 Frequency Response and Impulse Response Coefficients 162 7.1.2 Characteristics of FIR Filters 165 7.1.3 Ideal FIR Impulse Response Coefficients 166 7.2 Windowing Techniques to Improve Design 170 7.3 Parks-McClellan Optimization Procedure 177 7.3.1 Description of the Problem 177 7.3.2 The Remez Exchange Algorithm 179 7.3.3 Using the Parks-McClellan Algorithm 180 7.3.4 Limitations of the Parks-McClellan Algorithm 183 7.4 C Code for FIR Frequency Response Calculation 183 7.5 Conclusion 185 Chapter 8 Digital Filter Implementation Using C 187 8.1 Digital Filter Implementation Issues 187 8.1.1 Input and Output Signal Representation 188 8.1.2 Coefficient Representation 190 8.1.3 Retaining Accuracy and Stability 192 8.2 C Code for IIR Filter Implementation 194 8.3 C Code for FIR Filter Implementation 200 8.3.1 Real-Time Implementation of FIR Filters 201 x Practical Analog and Digital Filter Design 8.3.2 Nonreal-Time Implementation of FIR Filters 203 8.4 Filtering Sound Files 205 8.5 Conclusion 207 Chapter 9 Digital Filtering Using the FFT 209 9.1 The Discrete Fourier Transform (DFT) 209 9.2 The Fast Fourier Transform (FFT) 214 9.2.1 The Derivation of the FFT 215 9.2.2 The Inverse FFT 217 9.3 C Code for the FFT 218 9.4 Application of FFT to Filtering 221 9.5 Conclusion 225 Appendix A Technical References 227 Appendix B Filter Design So ftware and C Code 229 Appendix C Filter Design Using C 231 Appendix D C Code for Normalized Approximation Functions 233 Appendix E C Code for Unnormalized Approximation Functions 239 Appendix F C Code for Activ e Filter Implementation 247 Appendix G C Code fo r IIR Filter Design 253 Appendix H C Code for FIR Filter Design 257 Appendix I Filtering Sound Files 259 About the Author 263 Index 265 xi Preface This book was intentionally written to be different from othe r filter design books in two important ways. First, the most common analog and digital filter design and implementation methods are covered in a no-nonsense manner. All important derivations and descriptions are provide d to allow the reader to apply them directly to his or her own filter design problem. Over forty examples are provided to help illustrate the fundamentals of f ilter design. Not only are the details of analog active and digital IIR and FIR filter design presented in an organized and direct manner, but implementation issues are discussed to al ert the reader to potential pitfalls. An added feature to this text is the discussion of fast Fourier transforms and how they can be used in filtering applications. The simulation of analog filters is made easier by the generation of PSpice circuit description files that include R-C component values calculated directly from the filter coefficients. In addition, the testing of IIR and FIR filters designed for audio signals is enhanced by providing sample sound files th at can be filtered by using the digital filter design coefficients. Anyone with a sound card on their computer can then play the original and processed sound files for immediate evaluation. The second difference between this book and others is that the text is accompanied by WFilter, a fully functional, Windows®-based filter design software package, and the source code on which it is based. The CD provides the reader with the ability to install WFilter with a few simple clicks of the mouse, and also supplies the reader with th e well organized and clearly documented source code detailing the intricacies of f ilter design. No, the source code provided is not just a collection of fragmented functions, but rather a set of three organized programs that have been developed (with the addition of an easy-to-use graphical interface) into the organi zed structure of WFilter. A basic knowledge of C programming is expected of the reader, but the code presented in the text and the appe ndixes is thoroughly discussed and well documented. The text does assume the r eader is familiar with the fundamental concepts of linear systems such as sy stem transfer functions and frequency response although no prior knowledge of filter design is needed. xii Practical Analog and Digital Filter Design CHAPTER CONTENTS Chapter 1 introduces the reader to the filter design problem. An overview of WFilter is presented. Chapter 2 develops the normalized transfer functions for the Butterworth, Chebyshev, inverse Chebyshev, and elliptic approximation cases. Chapter 3 describes the conversion of the normalized lowpass filter to an unnormalized lowpass, highpass, bandpass, or bandstop filter. In addition, the calculation of the frequency response for anal og filters is discussed. By the end of the third chapter, a complete analog filter design can be performed. In Chapter 4, the implementation of analog filters is considered using popul ar techniques in active filter design with discussion of real-world considerations. A PSpice circuit description file is generated to enable the filter developer to analyze the circuit. Chapter 4 completes the discussion of analog filters in this book. Chapter 5 begins the discussion of discrete-time systems and digital filter design in this book. Several key features of discrete-time systems, including the notion of analog-to-digital conversion, Nyquist sampling theorem, the z-transform, and discrete-time system diagrams, are reviewed. Similarities and differences between discrete-time and continuous-time systems are discussed. In Chapter 6, digital IIR (recursive) filters are designe d. Three methods of designing IIR filters are considered. In addition, the frequency response calculations and related C code for the IIR filter are developed. Chapte r 7 considers digital FIR (nonrecursive) filters using a variety of window methods and the Parks-McClellan optimization routine. The special techniques necessary for FIR frequency response calculation are discussed. The implementation of real-time and nonreal-time digital FIR and IIR filters is discussed in Chapter 8. Implementation issues such as which type of digital filter to use, accuracy of quan tized samples, fixe d or floating point processing, and finite register length computation are discussed. The reader can then hear the effects of filtering by re playing the original and processed sound files on a sound card. Chapter 9 completes the text with an introduction of the discrete Fourier transform and the more efficient fast Fourier transform (FFT). The reader will learn how to use the FFT in filtering applications and see the code necessary for this operation. For those readers who desire filter design references or further details of the C code for the design of analog and digital filters, nine separate appendixes provide that added information. ACKNOWLEDGMENTS I would not have been able to complete this book without the help and support of a number of people. First, I thank the reviewers of this text who provided many helpful comments, both in the initial and final stages of development. In particular I want to thank Walter A. Serdijn of Delft University of Technology, The Netherlands. Preface xiii I also thank the friendly people at Artech House, Inc. who have provided me with so much help. This book could not have been written without their professional guidance throughout the publication process. I also thank Ohio Northern University and the Department of Electrical & Computer Engineering and Computer Science for their support. And finally, I thank my wife Diane for all of her encouragement and for the many hours of proofreading a second text that made no sense to her! TRADEMARKS Windows® is a registered trademark of Microsoft Corp. 1 Chapter 1 Introduction to Filters and Filter Design Software Everyone has probably come in contact with one type of filter or another in their lifetime. Maybe it was a coffee filter used to separate the grounds from the liquid, or perhaps an oil filter to remove contaminants from the oil of an engine. Anyone working in an office often filters the unimportant work from the important. In essence then the act of filtering is the act of separating desired items from undesired items. Of course when we discuss filters in this text, we are not talking about coffee, oil, or paperwork, but rath er electronic signals. The electronic filters we will be designing will separate the desirable signal frequencies from the undesirable, or in other applications simply change the frequency content which then changes the signal waveform. There are many types of electronic filters and many ways that they can be classified. A filter's frequency selectivity is probably the most common method of classification. A filter can have a lo wpass, highpass, bandpass, or bandstop response, where each name indicates how a band of frequencies is affected. For example, a lowpass filter would pass low frequencies with little attenuation (reduction in amplitude), while high freque ncies would be significantly reduced. A bandstop filter would severely attenuate a middle band of frequencies while passing frequencies above and below the a ttenuated frequencies. Filter selectivity will be the focus of the first section in this chapter. Filters can also be described by the method used to approximate the ideal filter. Some approximation methods empha size low distortion in the passband of the filter while others stress the ability of the filter to attenuate the signals in the stopband. Each approximation method has visible characteristics that distinguish it from the others. Most notably, the absence or presence of ripple (variations) in the passband and stopband clearly set one a pproximation method apart from another. Filter approximation methods will be disc ussed in further detail in the second section. 2 Practical Analog and Digital Filter Design Another means of classifying filters is by the implementation method used. Some filters will be built to filter an alog signals using i ndividual components mounted on circuit boards, while other filte rs might simply be part of a larger digital system which has other functions as well. Several implementation methods will be described in the third section of this chapter as well as the differences between analog and digital signals. However, it should be noted that digital filter design and implementation will be considered in detail starting in Chapter 5, while the first four chapters concentrate on filter approximation theory and analog filter implementation. In the final section of this chapter we discuss WFilter, an analog and digital filter design package for Windows®, which is included on the software disk. WFilter determines the transfer function coe fficients necessary for analog filters or for digital FIR or IIR filters. After the filter has been designed, the user can view the pole-zero plot, as well as the magnitude and phase responses. The filter design parameters or the frequency response para meters can also be edited for ease of use. In addition, for analog filters, the Spice circuit file can be generated to aid in the analysis of active filters. After digital filters have been designed, they may be used to filter wave files and the results can be played for comparison (a sound card must be present). Further discussion of WFilter and the C code supplied with this text can be found in Appendix B. 1.1 FILTER SELECTIVITY As indicated earlier, a filter’s primary purpose is to differentiate between different bands of frequencies, and therefore fre quency selectivity is the most common method of classifying filters. Names su ch as lowpass, highpass, bandpass, and bandstop are used to categorize filters, but it takes more than a name to completely describe a filter. In most cases a precise set of specifications is required in order to allow the proper design of a filter. There are two primary sets of specifications necessary to completely define a filte r's response, and each of these can be provided in different ways. The frequency specifications used to de scribe the passband(s) and stopband(s) could be provided in hertz (Hz) or in radians/second (rad/sec). We will use the frequency variable f measured in hertz as filter input and output specifications because it is a slightly more common wa y of discussing frequency. However, the frequency variable ω measured in radians/second will also be used as WFilter’s internal variable of choice as well as for unnormalized frequency responses since most of those calculations will use radians/second. The other major filter specifications are the gain characteristics of the passband(s) and stopband(s) of the filter re sponse. A filter's gain is simply the ratio of the output signal level to the input signal level. If the filter's gain is greater than 1, then the output signal is larger than the input signal, while if the gain is less than 1, the output is smaller than the input. In most filter applications, the gain Introduction to Filters and Filter Design Software 3 response in the stopband is very small. For t his reason, t he gai n is typically converted to decibels (dB) as indicated in (1.1). For exam ple, a filter' s passband gain response could be speci fied as 0.707 or as −3.0103 dB , whi le the stopband gain might be speci fied as 0.0001 or −80.0 dB . )gainlog(20 gaindB⋅= (1.1) As we can see, the values in decibels are m ore m anageable for very small gains. So me filter d esigners prefer to use atten uation (or loss) v alues instead of gain values. Atten uation is sim ply the inverse o f gain. For example, a filter with a gain of 1/ 2 at a part icular frequency would have an at tenuation of 2 at that frequency. If we ex press atten uation in decibels we will fin d that it is sim ply th e negat ive of t he gai n in deci bels as i ndicated in (1.2). Gai n values expressed in decibels will be the standard quantities used as filter specifications, although the term attenuation (or loss) will be us ed occasionally when appropriate. (1.2) dB1 dB gain )gainlog(20 ) gainlog(20 attn −= ⋅−= ⋅=− 1.1.1 L owpass Fi lters Figure 1.1 shows a typical lowpass filter’s response using frequency and gain specificatio ns necessary fo r precisio n filter d esign. The freq uency ran ge of the filter sp ecificatio n has been divided into three areas. Th e passband extends from zero frequency (dc) t o the passband edge frequency fpass, and t he stopband ext ends from the stopband edge frequency fstop to infinity. (W e will see later in this tex t that digital filters have a finite upper fre quency limit. W e will discuss that issue at the appropri ate time.) These t wo bands are separat ed by the transition band that extends from fpass to fstop. The filter response within the passband is allowed to vary between 0 dB and t he passband gai n apass, whi le the gai n in the stopband can vary between the stopband gai n astop and negat ive infinity. (The 0 dB gain in the passband relates to a g ain of 1.0, while th e gain of negative infinity in the stopband relates to a gain of 0.0.) A lowpass filter' s selectivity can now be speci fied wi th only four param eters: the passband gain apass, the stopband gai n astop, the passband edge frequency fpass, and t he stopband edge frequency fstop. Lowpass filters are used whenever it is im portant to lim it the high-frequency content of a signal. For exam ple, if an old audiotape has a lot of high-frequency “hiss,” a lo wpass filter with a passband edge freq uency of 8 kHz could be used to eliminate much of the hiss. Of course, it also elim inates h igh frequencies th at were intended to be reproduced. W e should rem ember that any filter can differentiate only between bands of frequenci es, not between i nform ation and noi se. 4 Practical Analog and Digital Filter Design Figure 1.1 Lowpass filter sp ecificatio n. 1.1.2 Hi ghpass Fi lters A highpass filter can be specified as shown in Figure 1.2. Note that in this case the passband ext ends from fpass to infinity (fo r analog filters) an d is lo cated at a higher frequency than the stopband whi ch ext ends from zero to fstop. The t ransition band still separates the passband and stopband. The passband gain is still specified as apass (dB) and the stopband gain is still specified as astop (dB). Figure 1.2 Highpass filter specification. Highpass filters are used when it is im portant to elim inate low frequencies from a signal. For exam ple, when turntabl es are used to play LP records (som e readers m ay rem ember those black vinyl di sks that would warp in a car' s back window), t urntable rum ble can som etimes occur, produci ng di stracting low- Introduction to Filters and Filter Design Software 5 frequency signals. A highpass filter set to a passband edge frequency of 100 Hz could help to elim inate th is distractin g signal. 1.1.3 Bandpass Filters The filter specification for a bandpass filte r shown in Figure 1.3 requires a bit more description. A bandpass filter will pass a band of frequencies while attenuating frequenci es above or bel ow that band. In t his case the passband exists between t he lower passband edge frequency fpass1 and t he upper passband edge frequency fpass2. A bandpass filter has two stopba nds. The lower stopband extends from zero to fstop1, whi le the upper stopband extends from fstop2 to infinity (fo r analog filters). W ithin the passband, there is a sin gle passband gain parameter apass in deci bels. However, i ndividual parameters for t he lower stopband gain astop1 (dB) and t he upper st opband gai n astop2 (dB) coul d be used i f necessary . Figure 1.3 Bandpass filter specification. A good exam ple for the application of a bandpass filter is the processing of voice signals. The norm al hum an voi ce has a frequency content located primarily in the range of 300–3,000 Hz. Therefore, t he frequency response for any system designed to pass primarily voice si gnals shoul d cont ain the input signal to that frequency range. In t his case, fpass1 woul d be 300 Hz and fpass2 woul d be 3,000 Hz. The st opband edge frequenci es woul d be sel ected by how fast we woul d want the signal response t o roll off a bove and bel ow the passband. 1.1.4 B andstop Fi lters The fin al typ e of filter to be discussed in this sectio n is the bandstop filter as shown i n Figure 1.4. In t his case t he band of frequenci es bei ng reject ed is located between t he two passbands. The st opband exi sts between the lower stopband edge frequency fstop1 and t he upper st opband edge frequency fstop2. The bandstop filter 6 Practical Analog and Digital Filter Design has two passbands. The l ower passband ext ends from zero t o fpass1, whi le the upper passband ext ends from fpass2 to infinity (for analog f ilters). W ithin the stopband, the single stopband gai n param eter astop is used. However, i ndividual gain param eters for t he lower and upper passbands, apass1 and apass2 (in dB) respectively , could be used i f necessary . Figure 1.4 Ban dstop filter sp ecificatio n. An excellen t example of a bandstop applicatio n would be a 60-Hz n otch filter used in sen sitive m easurement eq uipment. Mo st electro nic m easurement equipment today runs from an AC power source usi ng a 60-Hz i nput frequency . However, it is not uncom mon for som e of the 60-Hz si gnal to make its way into the sen sitive measurement areas o f the eq uipment. In order to eliminate this troublesom e frequency, a bandstop filter (som etimes called a notch filter in these applications) coul d be used wi th fstop1 set to 58 Hz and fstop2 set to 62 Hz. The passband edge frequenci es coul d be ad justed based on t he other t echni cal requirements of the filter. 1.2 FILTER APPROX IMATION The response of an ideal lowpass filte r is shown in Figure 1.5, where all frequenci es from 0 to fo are passed wi th a gai n of 1, and al l frequenci es above fo are com pletely attenuated (gain = 0). This type of filter response is physically unattainable. Practical filter responses that can be attained are also shown. As a filter' s response becom es closer and closer to the ideal, the cost of the filter (tim e delay, n umber of elem ents, dollars, p ower co nsumption, etc.) will increase. These pract ical responses are referred t o as approxi mations t o the ideal. There are a variety of way s to approxi mate an i deal response based on different criteria. For exam ple, some designs may emphasi ze the need for m inimum distortion of t he signals in the passband and would be w illing to trade off stopband attenuation for Introduction to Filters and Filter Design Software 7 that feat ure. Ot her desi gns m ay need t he fastest transition from passband to stopband and will allow m ore distortion in the passband to accom plish that aim . It is this engineerin g tradeoff that makes the design of filters so interestin g. Figure 1.5 Practical and ideal filter responses. We will b e discussing the primary ap proximation functions used in filter design today that can be cl assified bot h by nam e and t he presence of ri pple or variatio n in the signal bands. Ellip tic or Cau er filter ap proximations provide the fastest transition between passband and st opband of any studied in this text. An illustration of the m agnitude response of an elliptic filter is shown in Figure 1.1, where we can see that ripple exists in both the passband and st opband. W hat is not shown in that figure is th e phase distortion that the ellip tic filter g enerates. If th e filter is to be used with audio signals, this phase distortion must usually be correct ed. However, i n other applications, for exam ple the transm ission of data, the elliptic filter is a popular choice b ecause of its excellent selectivity characteristics. Th e ellip tic ap proximation is also one of the more complicated to develop. (W e will discuss all approxim ation m ethods in detail in Chapter 2.) The i nverse C hebyshev response i s another popul ar approxi mation m ethod that has a sm ooth response i n the passband, but variations in the stopband. On the other hand, t he norm al Chebyshev response has ri pple in the passband, but a smooth, ever-decreasi ng gai n in the stopband. The phase di stortion produced by these filters is n ot as sev ere as fo r the ellip tic filter, an d they are typ ically easier to design. The i nverse C hebyshev response i s shown i n Figure 1.2, and the norm al Chebyshev response is illustrated in Fi gure 1.3. The Chebyshev approxim ations provide a good com promise between the e lliptic and Butterworth approxim ation. The Bu tterwo rth filter is a classic filter approximation that has a smooth response i n both the passband and st opband as shown in Figure 1.4. It provi des the most linear phase response of any approxi mation techni que di scussed i n this text. (The B essel approxi mation provi des be tter phase charact eristics, but has very poor transition band characteristics.) Howeve r, as we will see in Chapter 2, a 8 Practical Analog and Digital Filter Design Butterwo rth filter will req uire a m uch higher order to match the tran sition band characteristics o f a Ch ebyshev or ellip tic filter. 1.3 FILTER IMPLEMENTATION After a filter h as been completely sp ecified , various numerical co efficien ts can be calculated (as descri bed i n Chapter 2). B ut after all the paperwork has been completed, the filter still has to be placed into operation. The first major decision is whether to use analog or digital t echnology to im plem ent the filter. The differen ces b etween analog and digital filter d esign are b ased primarily o n the differences bet ween anal og and di gital signals themselves. Any signal can be represent ed in the time dom ain by plotting its amplitude versus time. However, the amplitude and t ime vari ations can be e ither cont inuous or di scret e. If both the amplitude and t ime vari ations are cont inuous as shown i n Figure 1.6, the signal is referred to as an analog signal. Most r eal-life signals are analog in nature; for exam ple, sounds that we hear, el ectrocardi ogram signals recorded i n a m edical lab, and seismic variations recorded on m onitoring equi pment. However, t he probl em with anal og si gnals is that they contain so m uch inform ation. The exact amplitude of the sig nal (with infinite p recisio n) is av ailab le at ev ery in stant of time. Do we act ually need al l of t hat inform ation? And how do we st ore and transfer th at information? Figure 1.6 Comparison of anal og and di gital signals. As techni ques for the storage and t ransm ission of i nform ation in digital form are becom ing m ore efficient and cost effec tive, it is in creasin gly advantageous to use si gnals that are i n a digital form . The advant age of using the resul ting digital signals is that the amount of inform ation can be m anaged t o a level appropri ate for each application. An analog signal can be converted to a digital signal in two steps. First, the signal must be sam pled at fix ed time intervals, an d then the Introduction to Filters and Filter Design Software 9 amplitude of the signal must be quantized to one of a set of fixed levels. Once the analog signal has been converted to a di screte-time and discrete-amplitude signal it is commonly referred to as a digital signal as shown in Figure 1.6. The operation of sampling and quantizing is accomplishe d by an analog-to-digital converter (ADC). After filtering the signal in the digital domain, a digital-to-analog converter (DAC) can be used to return the signal to analog form. (A more complete discussion of these operations will be given in Chapter 5 where digital filter design is introduced and in Chapte r 8 where practical considerations of digital filter implementation are discusse d.) Today the digital images and sound files on computers as well as the music on compact discs are examples of signals in digital form. If we choose to implement a filter in analog form, we still have further choices to make. We could choose to im plement the filter with purely passive components such as resistors, capacitors, and inductors. This approach might be the best choice when high frequencies or high power is used. In other circumstances, analog active filters might be the best choice where either transistors or operational amplifiers are used to provide a gain element in the filter. The implementation of analog active filters is considered in Chapter 4. Digital filters will be implemented by using digital technology available today. Generally, the process will take pl ace within a microprocessor system that could have other functions besides the filtering of signals. We discuss two basic types of digital filters in Chapters 6 and 7 of this text. The first is the infinite impulse response (IIR) digital filter that is based in a large part on the design methodology of analog filters. The second type is the finite impulse response (FIR) digital filter that uses a complete ly different method for its design. The implementation of digital filters is consid ered in Chapter 8. Chapter 9 introduces the fast Fourier transform (FFT) and discusses how it can be used in filtering. As we can now see, there is more to describing a filter than referring to it as a lowpass filter. For example, we might be designing an “analog active lowpass Butterworth filter” or a “digital IIR bandpass Chebyshev filter.” These names along with a filter's specification paramete rs will completely describe a filter. 1.4 WFILTER - FILTER DESIGN SOFTWARE Although we haven’t discussed filter design in detail, it may be educational to see how to use a filter design software p ackage. This book includes a filter design software package called WFilter that automates the design process and provides filter coefficients and frequency response characteristics for the filters, and other features as well. As a first example, we will choose an analog lowpass Chebyshev filter with passband and stopband gains of −1 dB and −30 dB, respectively. The passband and stopband edge fre quencies will be 500 Hz and 1,000 Hz and the data files and frequency plots will be labeled with the title “Lowpass Chebyshev Filter.” (You will need to install WFilter on your computer before you can 10 Practical Analog and Digital Filter Design duplicate the act ions descri bed bel ow. Pl ease see Appendi x B for contents of the accom panying disc and installati on instructions for W Filter.) After startin g WFilter, yo u can begin the design of a new filter b y selectin g New from the File menu bar as shown i n Figure 1.7. You can al so Open a previously designed filter o r seek Help from this startu p screen . Figure 1.7 WFilter o pening screen . After selectin g New, you will be able to select th e typ e of filter yo u wan t to design and speci fy a descri ption as indicated earlier. The Filter Specification dialog box shown i n Figure 1.8 i ncludes sections for the different charact eristics of the filter, as well as sam pling freq uency (fo r digital filters o nly) an d a filter title. Figure 1.8 Filter Specification dialog box. After selectin g the characteristics of the filter, yo u can select Next and t he Lowpass Specification dialog box shown in Figure 1. 9 will appear, allowing you to specify th e gain and freq uency characteristics. Fo r a lowpass filter you must Introduction to Filters and Filter Design Software 11 enter the passband gai n and edge frequenc y as wel l as the stopband gai n and edge frequency as sp ecified in our sam ple filter. Yo u then have the option of designing the filter or returning to the previous di alog box to m ake changes. At each stage of this process y ou can cancel your act ions or seek hel p determining proper act ions. Figure 1.9 Lowpass Speci fication di alog box. After co mpleting the specifications, you can select Desig n Filter and t he following information will b e displayed in the Filter Pa rameter text window as shown in Figure 1.10. (Pole-zero information will also be displayed , but is not shown in this ex ample.) As in dicated , our filter will be fourth-order (length is a term used with digital FIR filters) an d will h ave an overall gain as indicated . The coeffi cients of t he transfer funct ion are gi ven i n the form of quadrat ics. Details concerning these v alues will b e discussed in the next chapter. Lowpass Chebyshev Filter Selectivity: Lowpass Approximation: Chebyshev Implementation: Analog Passband gain (dB): -1.0 Stopband gain (dB): -30.0 Passband freq (Hz): 500.0 Stopband freq (Hz): 1000.0 Filter Length/Order: 04 Overall Filter Gain: 8.91250938134E-01 Numerator Coefficients QD [S^2 + S + 1 ] == ========================================= 01 0.0 0.00000000000E+00 9.73641285912E+06 02 0.0 0.00000000000E+00 2.75754865948E+06 Denominator Coefficients QD [S^2 + S + 1 ] == ========================================= 01 1.0 8.76730519296E+02 9.73641285912E+06 02 1.0 2.11661471023E+03 2.75754865948E+06 Figure 1.10 Filter Ch aracteristic screen . 12 Practical Analog and Digital Filter Design We can now display the frequency re sponse of our filter by selecting Magnitude R esponse from the View menu. As indicated in the Response Specification dialog box shown i n Figure 1.11, t he user can speci fy frequency limits o f the display as well as th e magnitude range. Bo th the freq uency and magnitude axes can be scaled in a lin ear o r logarithmic fash ion. WFilter in itializes the values with educated guesses th at can be changed by the user. Figure 1.11 Response Speci fication di alog box. Selectin g Display Response will b ring up the graphics plots of the magnitude and phase responses. These graphs are shown i n Figures 1.12 and 1.13. Notice that on t he phase pl ot, the phase angl e is always displayed as a value between +180 and −180 degrees. Therefore t here is actually no di scont inuity in the phase plot. Figure 1.12 Magnitude response screen. Introduction to Filters and Filter Design Software 13 Figure 1.13 Phase response screen. In addition, for analog and digital IIR filters, th e pole-zero positions for a filter can be displayed by selectin g Pole-Zero Plot from the View menu. (The significan ce of poles an d zero s will b e discussed in the next chapter.) The pole- zero plot for our filter is sh own in Figure 1.14. Figure 1.14 Pole-zero pl ot. Any or all o f the information provided by WFilter can be printed by selectin g Print from the File menu. The Print dialog box as shown in Figure 1.15 will be displayed and t he user can choose from several options for pri nting. The details o f this filter d esign can now be saved by selectin g Save or Save As from the File menu. Aft er savi ng the inform ation, y ou can exi t the program by selectin g Exit from the File menu. Further details about the WFilter program will 14 Practical Analog and Digital Filter Design be presented in the chapters to come. We will h ave many more ch ances to use this program as we d evelop the theory behind analog and digital filter d esign. Figure 1.15 Print dialog box. 1.5 CONCLUSION At this point we have provided an in troduction to filter de sign by providing the standard definitions used to describe filters. We have also introduced W Filter, a powerful filter design software p ackage. Bu t we still n eed to learn the theory behind filter design and how we can design and implement the filters. W e’ll begin in the next chapter to study the design of analog filters. Fo r those interested in the C co de used in the design and implementation of filters, please refer to Appendix C–I. 15 Chapter 2 Analog Filter Approximation Functions As indicated in the first chapter, an ideal filter is unattainable; the best we can do is to approximate it. There are a number of approximations we can use based on how we want to define “best.” In this chapter we discuss four methods of approximation, each using a sli ghtly different definition. Four sections are devoted to the major approximation methods used in analog filter design: the Butterworth, Chebyshev, inverse Chebyshev, and e lliptic approximations. In each of these sections we determine the order of the filter required given the filter’s specifications and the required normalized transfer function to satisfy the specifications. In the following section we discuss the relative advantages and disadvantages of using these approxima tion methods. But first we begin this chapter by describing analog filters mathematically in the form of linear system transfer functions. 2.1 FILTER TRANSFER FUNCTIONS An analog filter is a linear system that has an input and output signal. This system’s primary purpose is to change the frequency response characteristics of the input signal as it moves through the f ilter. The characteris tics of this filter system could be studied in the time domain or the frequency domain. From a systems point of view, the impulse response h(t) could be used to describe the system in the time domain. The impulse response of a system is the output of a system that has had an impulse applied to the input. Of course, many systems would not be able to sustain an infinite spike (the impulse) being applied to the input of the system, but there are ways to determine h(t) without actually applying the impulse. A filter system can also be described in the frequency domain by using the transfer function H(s). The transfer function of the system can be determined by finding the Laplace transform of h(t). Figure 2.1 indicates that the filter system can be considered either in the time domain or in the frequency domain. However, 16 Practical Analog and Digital Filter Design the transfer function description is the predom inant m ethod used in filter design, and we will p erform most of our filter d esign using it. Figure 2.1 The filter as a system . 2.1.1 T ransfer Functi on Characteri zation The transfer function H(s) for a filter system can be characterized in a number of ways. As shown i n (2.1), H(s) is typ ically rep resented as th e ratio of two polynomials in s where in this case the num erator polynom ial is order m and t he denom inator is a pol ynomial of order n. G represent s an overal l gain const ant that can t ake on any value. ] [] [)( 0 12 21 10 12 21 1 bsb s b s b sasa s a s a sGsHn nn nnm mm mm +⋅++⋅+⋅++⋅++⋅+⋅+⋅=− −− −− −− − "" (2.1) Alternately, the pol ynomials can be fact ored t o give a form as shown i n (2.2). In this represent ation, the num erator and denom inator pol ynomials have been separat ed into first-order factors. The zs represent the root s of t he num erator and are referred to as the zeros of the transfer fu nction. Sim ilarly, th e ps represent the roots of t he denom inator and are referred t o as the pol es of t he transfer funct ion. )] () () () [()] () () () [()( 1 2 1 01 2 1 0 − −− − +⋅+ +⋅++⋅++⋅+⋅= n nm m ps ps ps pszs zs zs zs GsH"" (2.2) Most of the poles an d zero s in filter d esign will be complex valued and will occur as com plex conjugate pairs. In th is case, it will be m ore convenient to represent the transfer function as a ratio of quadratic term s that co mbine the individual com plex conjugat e factors as shown i n (2.3). The first-order factors that are in cluded will b e present only if the numerato r or denominator polynomial orders are odd. We will be using this fo rm for m ost of the analog filter design material. )] () () [()] () () [( )( 2 12 02 012 02 12 02 012 0 r rq q bsb s bs b s psas a s as a s zs G sH +⋅+ +⋅+⋅++⋅+ +⋅+⋅+⋅ = "" (2.3) Analog Filter Approximation Functions 17 As an exam ple of each expression, cons ider the three form s of a transfer funct ion that have a second-order num erator and t hird-order denom inator: 0001.4 0081.5 1650.3) 66667.0 (0.6)(2 32 +⋅+⋅++⋅= s s sssHa (2.4a) ) 3747.1 7837.0() 3747.1 7837.0() 5975.1() 81650.0 )( 81650.0 (0.6)(j s j s sjs jssHb−+⋅ ++⋅+− +⋅= (2.4b) ) 5040.2 5675.1 () 5975.1() 66667.0 (0.6)(22 +⋅+⋅++⋅= s s sssHc (2.4c) 2.1.2 Pol e-Zero Pl ots and T ransfer Functi ons When the quadratic fo rm of the tran sfer fu nction is used, it is easy to generate th e pole-zero pl ot for a part icular transfer funct ion. The pol e-zero plot simply plots the root s of t he num erator (zeros) and t he denom inator (pol es) on t he complex s- plane. As an exam ple, the pole-zero plot for the sam ple transfer funct ion gi ven i n (2.4) i s shown i n Figure 2.2. Figure 2.2 Pole-zero plot for (2.4). A pole is trad itionally rep resented by an X and a zero by an O. If the transfer function is odd, the first-order pole or zero will be located on the real axis. All poles and zeros from the quadrat ic factors are sym metrically lo cated pairs in the complex plane on opposi te sides of t he real axis. The gai n of the transfer funct ion 18 Practical Analog and Digital Filter Design must be i ndicated on t he plot or the inform ation woul d be i ncomplete. Note that there are onl y two zeros shown, but there is one located at infinity. W e can verify this by observing that if we were to allo w |s| to approach infinity, | H(s)| woul d approach zero. Transfer funct ions always have t he sam e num ber of pol es and zeros, but some exist at in finity. Conversely, we can also determ ine a filter’s transfer function from the pole- zero pl ot. In general , any critical frequency (pol e or zero) i s speci fied by indicating the real ( σ) and im aginary (ω) component . The t ransfer funct ion woul d then include a factor of [ s − (σ + jω)]. If the critical frequency is com plex, we can combine the two com plex conjugat e fact ors i nto a si ngle quadrat ic factor by multiplying them as sh own in (2.5): (2.5) ) ( 2 )] ([)] ([2 2 2ωσσ ωσωσ ++⋅⋅−=−−⋅+− s s j s j s Exampl e 2.1 Generati ng a T ransfer Functi on from a Pol e-Zero Pl ot Problem: Assum e that a pol e-zero pl ot shows pol es at (−3 ± j2) and (−4.5) and zeros at ( −5 ± j1) and (−1). Determ ine the tran sfer fu nction if its g ain is 1.0 at s = 0. Solution: Usi ng the techni que of (2.5), t he com plex conjugat e poles and zeros can be com bined into quadratic fact ors as indicated. The first-order factors are handl ed directly and t he gai n is included i n the num erator. The easi est method to use when gi ven a gai n requi rement of 1.0 at s = 0 is to prepare each factor independent ly to have a gai n of 1 at that frequency as shown i n the first transfer funct ion. Then t he set of const ants can be com bined as shown in the second equat ion. )13 6 ()5.4 ()26 10 ()1 (25.2= )13 6 (13 )5.4 (5.4 1)1 ( 26)26 10 ()( 2222 +⋅+⋅++⋅+⋅+⋅+⋅+⋅+⋅+⋅+⋅+= s s ss s ss s ss s ssH 2.1.3 Normal ized T ransfer Functi ons In this chapter we concentrate on devel oping what is referred t o as a norm alized transfer funct ion. A norm alized l owpass t ransfer funct ion is one i n whi ch the passband edge radi an frequency is set to 1 rad/sec. Of course, this seem s a rather unusual frequency, since seldom would a lowp ass filter be required to have such a low freq uency. Ho wever, th e tech nique actu ally allows the filter designer considerable latitude in designing filters because a norm alized transfer function Analog Filter Approximation Functions 19 can easily be unnorm alized to any other fre quency. In the next chapter, we will discuss in detail the procedures used to unnorm alize lowpass filters to other frequencies and even learn how to tran slate a lowpass filter to a highpass, bandpass, or bandstop filter. Before we begin the devel opment of the approxi mation funct ions for anal og filters, it m ay be helpful to go over the general ap proach taken in these sectio ns. In each case, the general characteristics of the approxim ation m ethod will be discussed, i ncluding its relative advant ages and di sadvant ages. Next , a descri ption of the transfer function for each approxi mation will be given. There will be no attem pt to give an exhaustive derivati on of each approxim ation m ethod in this text; there are m ore than enough sources of t heoret ical devel opments already availab le. (A list of referen ces fo r material p resented in this ch apter is g iven in Appendi x A. The texts by Dani els, Van Val kenburg, and Parks/ Burrus are particularly helpful when studying approximation theory.) W e will th en determine numerical methods t o find the order and t he coeffi cients of the transfer funct ion necessary to meet th e filter sp ecificatio ns. 2.2 BUTTERWORTH NORMALIZ ED APPROX IMATION FUNCTIONS The Butterwort h approxi mation funct ion i s often cal led the maximally flat response because no other approxim ation has a sm oother transition through the passband t o the stopband. The phase response al so is very smooth, which is important when consi dering di stortion. The l owpass B utterwort h polynomial has an al l-pole transfer funct ion wi th no fi nite zeros present . It is the approxi mation method of choi ce when l ow phase di stortion and m oderat e selectivity are requi red. 2.2.1 B utterw orth Magni tude Response Equat ion 2.6 gi ves t he Butterwort h approxi mation’s magnitude response where ωo is the passband edge freq uency for the filter, n is the order of t he approxi mation funct ion, and ε is the passband gain adjustment facto r. The tran sfer fu nctions will carry su bscripts to help identify th em in this chapter. In this case, th e subscript B indicates a Bu tterwo rth filter, an d n indicates an nth-order transfer function. [] n oo nBj H ⋅⋅+= 2 2, )/( 11 )/( ωωεωω (2.6) where 1 10pass1.0− =⋅− aε (2.7) 20 Practical Analog and Digital Filter Design If we set both ε = 1 and ωo = 1, the filter will h ave a gain of 1/2 or −3.01 dB at the norm alized passband edge frequency of 1 rad/ sec. The Butterwort h approxi mation has a num ber of i nteresting propert ies. First, the response will always have unity gain at ω = 0, no m atter what value is given t o ε. However, t he gai n at the norm alized passband edge frequency of ω = 1 will depend on t he val ue of ε. In addi tion, the response gai n decreases by a factor of −20n dB per decade of frequency change. That happens because for large ω, the transfer funct ion gai n becom es inversel y proport ional to ω, which increases by 10 for every decade. (A decade in frequency is a ratio of 10. For exam ple, the span of frequenci es from 1 to 10 rad/ sec and the span of frequenci es from 1,000 t o 10,000 Hz are both referred to as one decade.) Therefore, if we design a fifth-order Butterworth filter, the ga in will decrease 100 dB per decade for frequencies above the passband edge frequency . 2.2.2 B utterw orth Order The order of the Bu tterwo rth filter is d ependent on the specificatio ns provided by the user. These speci fications i nclude t he edge frequenci es and gai ns. The standard form ula for the Butterwort h order cal culation is given i n (2.8). In t his form ulation, not e that it is the rat io of t he stopband and passband frequenci es which is important, not either one of these in dependently. Th is means that a filter with a given set o f gains will req uire the sam e order whether the edge freq uencies are 100 and 200 rad/sec or 100,000 and 200,000 Hz. The val ue of n calculated using this equat ion m ust always be rounded to the next highest integer in order t o guarantee th at th e specificatio ns will b e met by the integer order of the filter designed: ) / log(2)]1 10/()1 10log[( pass stop1.0 1.0pass stop ωω⋅− −=⋅− ⋅− a a Bn (2.8) 2.2.3 B utterw orth Pol e Locations The poles for a Butterworth approxim ation function are equally spaced around a circle in the s-plane and are sy mmetrical about the jω axis. Plotting the pol es of the magnitude-squared funct ion |H(s)|2 shows t wice as m any poles as t he order of the filter. W e are ab le to determine the Bu tterwo rth tran sfer fu nction from the poles in the left h alf plane (LHP) th at produce a stable system . In order to determine the ex act p ole positions in the s-plane we use the polar form for specifying the com plex location. For each of the poles, we m ust know the distance from the origin (the radius of the circle) an d the angle from the positive real ax is. Analog Filter Approximation Functions 21 The radius of the circle for our norm alized case i s a funct ion of t he passband gain and i s given i n (2.9): (2.9) nR/1−=ε Once the radius of the circle is known, the pole positions are determ ined by calculating the necessary angles. Equat ion 2.10 can be used t o determine the angles for t hose com plex pol es in the second quadrant : even) ( 1 /2)( , 1, 0,= ,2)1 2(n n mnnm m −⋅++⋅⋅= …πθ (2.10a) odd) ( 1]2)/1 [( , ,1 ,0= ,2)1 2(n n mnnm m −−⋅++⋅⋅= …πθ (2.10b) It is im portant to remember that in this equation θm represents only the angles in the second quadrant that have compl ex conj ugates in the third quadrant . In other words, θm does not include t he pol e on t he real axis for odd-order funct ions. For this reason, (2.10b) is valid only for odd-order filters where n ≥ 3 since a first- order filter wo uld have no complex conjugate poles. (W e’ll see th at this definition allows a cleaner algorithm for the C code t hat is discussed i n Appendi x D.) The preci se pol e locations can t hen be det ermined from (2.11) and (2.12): ) cos(m mRθ σ⋅= (2.11) ) sin(m mRθ ω⋅= (2.12) In the case of odd-order transfer functi ons, the first-order pole will be located at a posi tion σR equal to the radi us of t he circle as indicated in (2.13): RR−=σ (2.13) 2.2.4 B utterw orth T ransfer Functi ons The Butterwo rth transfer fu nction can be determined from the pole locatio ns in the LHP as we saw in the first sectio n of this chapter. Since most of these poles are complex conjugat e pairs (except for t he possi ble pol e on t he real axis for odd orders), we can get all of the inform ation we need from the pol es in the second quadrant . The complete approxi mation transfer funct ion can be det ermined from a combination of a fi rst-order fact or (for odd orders) and quadrat ic factors. Each of 22 Practical Analog and Digital Filter Design these facto rs will h ave a co nstant in the numerato r to adjust the gain to unity at ω = 0 as illustrated in Example 2.1. We start b y defining the form of the first-o rder facto r in (2.14). No te that at this point the transfer funct ion vari ables are represent ed by an uppercase S where prior to this we have been using a lowercase s. This is an attempt to distinguish bet ween t he norm alized t ransfer funct ion (usi ng S) and t he unnorm alized funct ions (usi ng s), which will be developed in the next chapter. RSRSHo+=)( (2.14) For each com plex conjugate pole in the second quadrant, there will be the following quadrat ic factor in the transfer funct ion: m mm mBS B SBSH 2 122)( +⋅+= (2.15) where m mBσ⋅−=21 (2.16) (2.17) 2 2 2 m m mB ωσ+= The complete Butterwort h transfer funct ion can now be defi ned as shown i n (2.18): even) ( 1)2/( , ,1 ,0= , ) () ( )( 2 122 , n n mBS B SB S H mm mmm nB −+⋅+=∏∏ … (2.18a) odd) ( 1]2)/1 [( , ,1 ,0= , ) ( ) () ( )( 2 122 , n n mBS B S RSB R S H mm mmm nB −−+⋅+⋅+⋅ =∏∏ … (2.18b) Analog Filter Approximation Functions 23 We have now reached a point where som e exam ples are in order. First, we will co nsider so me numerical ex amples, an d then test the WFilter program on the same specifications. Example 2.2 Butterworth Third-Order Normaliz ed Transfer Function Problem: Det ermine the order, pol e locations, and transfer funct ion coefficien ts for a Bu tterwo rth filter to satisfy th e following specificatio ns: apass = −1 dB , astop = −12 dB , ωpass = 1 rad/ sec, and ωstop = 2 rad/ sec Solution: First, we det ermine the fundam ental const ants needed from (2.7)– (2.9): ε = 0.508847 n = 2.92 (3rd order) R = 1.252576 Next , we find the locations of the first-order pol e and t he com plex pol e in the second quadrant from (2.10)–(2.13). A graph of t he pol e locations (i ncluding those from the magnitude-squared funct ion in the right-half plane) i s shown i n Figure 2.3. (1st order) σR = −1.252576 ωR = 0.0 θ0 = 2π/3 σ0 = −0.626288 ω0 = 1.084763 Finally, we generat e the transfer funct ion from (2.14)–(2.18): ) 5689.1 2526.1 () 2526.1(5689.1 2526.1)(2 3,+⋅+⋅+⋅= S S SS HB Figure 2.3 Pole locatio ns for third-order Butterwo rth normalized filter. 24 Practical Analog and Digital Filter Design In order to use WFilter to determine the normalized transfer functions, we will assume a passband edge frequenc y of 1 rad/sec (0.159154943092 Hz) and a stopband edge frequency of 2 rad/sec (0.318309886184 Hz). (We must enter the frequencies into WFilter using the hertz values and they must have more significant digits than we require in our answer.) Twelve significant digits were used to enter the edge frequencies, but th ey are displayed on the coefficient screen with only ten significant digits. Rest assured that they are stored internally with the higher accuracy, but the display is se t for the more typical requirements of filter frequency. The coefficient values determined are shown in Figure 2.4. Butterworth 3rd-Order Normalized Lowpass Selectivity: Lowpass Approximation: Butterworth Implementation: Analog Passband gain (dB): -1.0 Stopband gain (dB): -12.0 Passband freq (Hz): 0.1591549431 Stopband freq (Hz): 0.3183098862 Filter Length/Order: 03 Overall Filter Gain: 1.00000000000E+00 Numerator Coefficients QD [S^2 + S + 1 ] == ========================================= 01 0.0 0.00000000000E+00 1.25257638818E+00 02 0.0 0.00000000000E+00 1.56894760823E+00 Denominator Coefficients QD [S^2 + S + 1 ] == ========================================= 01 0.0 1.00000000000E+00 1.25257638818E+00 02 1.0 1.25257638818E+00 1.56894760823E+00 Figure 2.4 Butterworth normalized third-order coefficients from WFilter. Example 2.3 Butterworth Fourth-Order Normalized Transfer Function Problem: Determine the order, pole locations, and transfer function coefficients for a Butterworth filter to satisfy the following specifications: apass = −1 dB, a stop = −18 dB, ω pass = 1 rad/sec, and ωstop = 2 rad/sec Solution: First, we determine the cons tants needed from (2.7)–(2.9): ε = 0.508847 n = 3.95 (4th order) R = 1.184004 Next, we find the locations of the two complex poles in the second quadrant from (2.10)–(2.13). A graph of the pole locations is shown in Figure 2.5. θ0 = 5π/8 σ0 = −0.453099 ω0 = +1.093877 θ1 = 7π/8 σ1 = −1.093877 ω1 = +0.453099 Analog Filter Approximation Functions 25 Finally, we generat e the transfer funct ion from (2.14)–(2.18). The coeffi cient values determined by WFilter are sh own in Figure 2.6. ) 4019.1 90620.0 () 4019.1 1878.2 () 4019.1()(2 22 4,+⋅ +⋅+⋅+= S S S SS HB Figure 2.5 Pole locatio ns for fourth-order Bu tterwo rth normalized filter. Butterworth 4th-Order Normalized Lowpass Selectivity: Lowpass Approximation: Butterworth Implementation: Analog Passband gain (dB): -1.0 Stopband gain (dB): -18.0 Passband freq (Hz): 0.1591549431 Stopband freq (Hz): 0.3183098862 Filter Length/Order: 04 Overall Filter Gain: 1.00000000000E+00 Numerator Coefficients QD [S^2 + S + 1 ] == ========================================= 01 0.0 0.00000000000E+00 1.40186544588E+00 02 0.0 0.00000000000E+00 1.40186544588E+00 Denominator Coefficients QD [S^2 + S + 1 ] == ========================================= 01 1.0 9.06197420862E-01 1.40186544588E+00 02 1.0 2.18775410363E+00 1.40186544588E+00 Figure 2.6 Butterwo rth normalized fourth-order co efficien ts fro m WFilter. 26 Practical Analog and Digital Filter Design The associ ated magnitude and phase responses for t he previ ous t wo exam ples are sh own in Figures 2.7 and 2.8 and illustrate th e differen ce between a th ird- order and fourth-order filter. Notice that the magnitude response uses a different scale for the passband and stopband respons e. (WFilter does not put two different responses on t he sam e graph or use different scal es for passband and st opband. They are di splayed here i n that manner for ease of com parison. However, the magnitude scale of WFilter can be changed on differen t graphs to provide more detail.) Figure 2.7 Butterwort h third-order and fourt h-order m agnitude responses. Figure 2.8 Butterwort h third-order and fourt h-order phase responses. Analog Filter Approximation Functions 27 2.3 CHEBYSHEV NORMALIZ ED APPROX IMATION FUNCTIONS The C hebyshev approxi mation funct ion al so has an al l-pole transfer funct ion like the Bu tterwo rth approximation. Ho wever, unlike th e Bu tterwo rth case, th e Chebyshev filter allo ws v ariatio n or ripple in the passband of the filter. Th is reduction in the restrictions placed on th e characteristics of the passband enables the transition characteristics of the Chebyshev t o be st eeper than the Butterworth transition. Because of this m ore rapid transition, the Chebyshe v filter is able to satisfy user specificatio ns with lower-o rder filters th an the Bu tterwo rth case. However, t he phase response i s not as linear as t he Butterwort h case, and t herefore if low phase di stortion is a pri ority, the Chebyshev approxi mation may not be the best choi ce. 2.3.1 Chebyshev Magni tude Response The m agnitude response funct ion for t he Chebyshev approxi mation is shown in (2.19): )/( 11)]/([ 2 2, o no nC Cj H ωωεωω ⋅+= (2.19) where t he defi nition of ε is again 1 10pass1.0− =⋅− aε (2.20) and Cn(ω) is the Chebyshev pol ynomial of t he first kind of degree n. The norm alized C hebyshev pol ynomial (ωo = 1) i s defined as (2.21a) 0 ,] )( cos cos[)(1≤ ⋅=−ωω ω n Cn (2.21b) 0 > ,] )( cosh cosh[)(1ωω ω−⋅= n Cn We can see that the m athem atical desc ription used for t his approxi mation is more involved than the Butterworth case. W e will be concerned with the expressi on where ω > 0, but the Chebyshev pol ynomial has m any interesting features which are discussed in the re ferences at the end of this text. 28 Practical Analog and Digital Filter Design 2.3.2 Chebyshev Order The order of the Chebyshev filter will b e dependent on the specificatio ns provided by the user. The general form of the calcula tion for the order is the sam e as for the Butterworth, except that the inverse hyperbo lic cosine function is used in place of the co mmon logarithm function. As in the Butterwo rth case, the value of n actually calculated must be rounded t o the next highest integer i n order to guarantee th at the specificatio ns will b e met. ) / ( cosh)1 10/()1 10( cosh pass stop11.0 1.0 1 pass stop ωω−⋅− ⋅− − ⎥⎦⎤ ⎢⎣⎡− − =a a Cn (2.22) 2.3.3 Chebyshev Pol e Locations The poles for a Chebyshev approxim ation function are located on an ellipse instead of a circle as in th e Butterworth case. The ellipse is centered at the origin of the s-plane with its m ajor axis along the j ω axis with intercepts of ± cosh( D), while the m inor axis is along the real axis with intercepts of ± sinh( D). The variable D is defined as nD)( sinh1 1−− =ε (2.23) The pole locations can be defined in term s of D and an angle φ as shown in (2.24). The angles determ ined locate the pol es of the transfer function in the first quadrant. However, we can use them to find the poles in the second quadrant by simply changing the sign of the real pa rt of each com plex pole. The real and imaginary components of the pole locations can now be defined as shown in (2.25) and (2.26): even) ( 1)2/( , ,1 ,0= ,2)1 2(n n mnm m −⋅+⋅⋅= …πφ (2.24a) odd) ( 1]2)/1 [( , ,1 ,0= ,2)1 2(n n mnm m −−⋅+⋅⋅= …πφ (2.24b) ) sin() sinh(m m Dφ σ ⋅−= (2.25) Analog Filter Approximation Functions 29 ) cos() cosh(m m Dφ ω ⋅ = (2.26) If the function has an odd-order, there w ill be a real pole located in the LHP as indicted by (2.27): ) sinh( DR−=σ (2.27) 2.3.4 Chebyshev T ransfer Functi ons Using the results of (2.27), we know that an odd-order C hebyshev transfer function will have a factor of the form illustrated in (2.28): ) sinh() sinh()(D SDSHo+= (2.28) The quadratic factors for the Chebyshev transfer function will take on exactly the sam e form as the Butterworth case, as shown below: m mm mBS B SBS H 2 122)( +⋅+= (2.29) m mBσ⋅−=21 (2.30) (2.31) 2 2 2 m m mB ωσ+= We are now just about ready to define the general form of the C hebyshev transfer function. However, one small detail still m ust be considered. Because there is ripple in the passband, C hebyshev even and odd-order approxim ations do not have the sam e gain at ω = 0. As seen in Figure 2.13 (a result of a future exam ple), each approxim ation has a num ber of half-cycles of ripple in the passband equal to the order of the filter. Th is forces even-order filters to have a gain of apass at ω = 0. However, the first-order and quadratic factors we have defined are all set to give 0 dB gain at ω = 0. Therefore, if no adjustm ent of gain is made to even-order C hebyshev approxim ations , they would have a gain of 0 dB at ω = 0 and a gain of −apass (that is, a gain greater than 1.0) at certain other frequencies where the ripple peaks. A gain constant m ust therefore be included for even-order transfer func tions with the value of 30 Practical Analog and Digital Filter Design (2.32) pass05.010aG⋅= We are now ready to define a generali zed transfer function for the Chebyshev approxim ation function as shown below: even) ( 1)2/( , ,1 ,0= , ) () ( ) 10( )( 2 12205.0 ,pass n n mBS B SB S H mm mmma nC −+⋅+⋅ =∏∏⋅ … (2.33a) odd) ( 1]2)/1 [( , ,1 ,0=, ) ( )) sinh( () ( ) sinh( )( 2 122 , n n mBSB S D SB D S H mm mmm nC −−++⋅ +⋅ =∏∏ … (2.33b) It is again tim e to consider som e num erical exam ples before using W Filter to determ ine the filter coefficients. Example 2.4 Chebyshev Third-Order Normaliz ed Transfer Function Problem: Determ ine the order, pole locations, and coefficients of the transfer function for a Chebyshev filter to satisfy the following specifications: apass = −1 dB , astop = −22 dB , ωpass = 1 rad/sec, and ωstop = 2 rad/sec Solution: First, we determ ine the fundam ental constants needed from (2.20), (2.22), and (2.23): ε = 0.508847 n = 2.96 (3rd order) D = 0.475992 cosh( D) = 1.115439 sinh( D) = 0.494171 Next, we find the locations of the firs t-order pole and the com plex pole in the second quadrant from (2.24)–(2.27). A plot of the poles is shown in Figure 2.9: (1st order) σR = −0.494171 ωR = 0.0 φ0 = 1π/6 σ0 = −0.247085 ω0 = +0.965999 Finally, we generate the transfer f unction from (2.28)–(2.33). The results from WFilter are shown in Figure 2.10. Analog Filter Approximation Functions 31 ) 99420.0 49417.0 () 49417.0(99420.0 49417.0)(2 3,+⋅+⋅ +⋅= S S Ss HC Figure 2.9 Pole locations for third-or der Chebyshev norm alized filter. Chebyshev 3rd-Order Normalized Lowpass Selectivity: Lowpass Approximation: Chebyshev Implementation: Analog Passband gain (dB): -1.0 Stopband gain (dB): -22.0 Passband freq (Hz): 0.1591549431 Stopband freq (Hz): 0.3183098862 Filter Length/Order: 03 Overall Filter Gain: 1.00000000000E+00 Numerator Coefficients QD [S^2 + S + 1 ] == ========================================= 01 0.0 0.00000000000E+00 4.94170604943E-01 02 0.0 0.00000000000E+00 9.94204586790E-01 Denominator Coefficients QD [S^2 + S + 1 ] == ========================================= 01 0.0 1.00000000000E+00 4.94170604943E-01 02 1.0 4.94170604943E-01 9.94204586790E-01 Figure 2.10 Chebyshev norm alized third-or der coefficients from WFilter. 32 Practical A nalog and D igital F ilter D esign Example 2.5 Chebyshev Fourth-Order Normaliz ed Transfer Function Problem: Determ ine the order, pole locations, and transfer function coefficients for a Chebyshev filter to satisfy the following specifications: apass = −1 dB , astop = −33 dB , ωpass = 1 rad/sec, and ωstop = 2 rad/sec Solution: First, we determ ine the fundam ental constants needed from (2.20), (2.22), and (2.23): ε = 0.508847 n = 3.92 (4th order) D = 0.356994 cosh( D) = 1.064402 sinh( D) = 0.364625 Next, we find the locations of the tw o complex poles in the second quadrant from (2.24)–(2.27). A plot of the poles is shown in Figure 2.11. θ0= 1π/8 σ0 = −0.139536 ω0 = +0.983379 θ1= 3π/8 σ1 = −0.336870 ω1 = +0.407329 Finally, we generate the transfer functi on from (2.28)–(2.33). Note that in this even-order case, the gain constant of 0.891251 is included. The results from WFilter for this Chebyshev specification are shown in Figure 2.12. ) 27940.0 67374.0 () 98650.0 27907.0 (27940.0 98650.0 89125.0)(2 2 4,+⋅+⋅ +⋅+⋅⋅= S S S SS HC Figure 2.11 Pole locations for fourth-ord er Chebyshev norm alized filter. Analog Filter Appr oxim ation Functions 33 The m agnitude and phase responses for the third and fourth-order C hebyshev filters are shown in Figures 2.13 and 2.14. Chebyshev 4th-Order Normalized Lowpass Selectivity: Lowpass Approximation: Chebyshev Implementation: Analog Passband gain (dB): -1.0 Stopband gain (dB): -33.0 Passband freq (Hz): 0.1591549431 Stopband freq (Hz): 0.3183098862 Filter Length/Order: 04 Overall Filter Gain: 8.91250938134E-01 Numerator Coefficients QD [S^2 + S + 1 ] == ========================================= 01 0.0 0.00000000000E+00 9.86504875318E-01 02 0.0 0.00000000000E+00 2.79398094130E-01 Denominator Coefficients QD [S^2 + S + 1 ] == ========================================= 01 1.0 2.79071991811E-01 9.86504875318E-01 02 1.0 6.73739387509E-01 2.79398094130E-01 Figure 2.12 Chebyshev norm alized fourth-o rder coefficients from WFilter. Figure 2.13 Chebyshev third-order and fourth-order m agnitude responses. 34 Practical A nalog and D igital F ilter D esign Figure 2.14 Chebyshev third-order and fourth-order phase responses. 2.4 INVERSE CHEBYSHEV NORMALIZ ED APPROX IMATION FUNCTIONS The inverse C hebyshev approxim ation functi on, also called the C hebyshev ty pe II function, is a rational approxim ation with both poles and zeros in its transfer function. This approxim ation has a sm ooth, m aximally flat response in the passband, just as the B utterworth appr oxim ation, but has ripple in the stopband caused by the zeros of the transfer function. The inverse C hebyshev approxim ation provides better transition characteristics than the Butterworth filter and better phase response than the sta ndard C hebyshev. Although the inverse Chebyshev has these features to recom mend it to the filter designer, it is m ore involved to design. 2.4.1 Inverse Chebyshev Magni tude Response The developm ent of the inverse C hebyshev response is derived from the standard Chebyshev response. We will discuss the m ethods needed to determ ine the inverse Chebyshev approxim ation function while l eaving the intricate details to the reference works. The nam e “inverse Cheb yshev” is well-deserved in this case since we will see that m any of the com putations are based on inverse or reciprocal values from the standard com putations. Let’s begin with the definition of the magnitude frequency response f unction as shown in (2.34). The first observation concerning (2.34) is that it indeed has a numerator portion that allows for the finite zeros in the transfer function. Upon closer inspection, we find the use of εi in place of ε. Equation (2.35) indicates εi, the Analog Filter Appr oxim ation Functions 35 inverse of ε, where apass is replaced with astop. Because of the differences, we will use the subscript to distinguish εi from the standard ε. Although Cn still represents the Chebyshev polynomial of the first kind of degree n as defined in (2.21), we notice that the argum ent of the function is the inverse of the standard definition (ωo/ω instead of ω/ωo). We will see a little later in this section how these differences affect our determ ination of the poles and zeros of the transfer function. [] )/( 1)/( )/( 2 22 2 , ωωεωωεωω o n io n i o nI CCj H ⋅+⋅= (2.34) where 1 101 stop1.0−= ⋅− aiε (2.35) 2.4.2 Inverse Chebyshev Order Because of the nature of the derivati on of the inverse Chebyshev approxim ation function from the standard C hebyshev approxim ation, it should com e as no surprise that the calculation of the order for an inverse Chebyshev is the same as for the standard C hebyshev. The expression is given in (2.36) and is the sam e as (2.22) except for the subscript I designating the calculation as the inverse Chebyshev order: ) / ( cosh)1 10/()1 10( cosh pass stop11.0 1.0 1 pass stop ωω−⋅− ⋅− − ⎥⎦⎤ ⎢⎣⎡− − =a a In (2.36) 2.4.3 Inverse Chebyshev Pol e-Zero L ocations The determ ination of the pole locations for the norm alized inverse C hebyshev approxim ation is based on t echniques sim ilar to those used for the standard norm alized C hebyshev approxim ation. The pole positions for the inverse Chebyshev case are found using the sam e values of φm, but the value of εi is calculated differently . Once the pole pos itions are found, however, the inverse Chebyshev poles are the reciprocals of th e standard poles. (There’s that inverse relationship again.) For exam ple, if ther e exists a standard Chebyshev pole at ωσ j p+= (2.37) 36 Practical A nalog and D igital F ilter D esign then the reciprocal of p gives the inverse C hebyshev pole position as 2 2 2 21 ) () ( ωσω ωσσ ωσωσωσ +− +=−⋅+−=−jj jjp (2.38) Notice that if a pole’s distance from the origin is greater than one, the reciprocal’s distance will be less than one , and vice versa. In addition, the position of the pole is reflected across the real axis, so although the original pole position may be in the second quadrant, the recipr ocal is located in the third quadrant. Consequently, if we are able to determine pole positions for the standard Chebyshev approxim ation function as discusse d in the previous section, we should have little problem finding the i nverse Chebyshev pole locations. Let’s derive the m athem atical equati ons necessary to determ ine the pole locations for the inverse C hebyshev a pproxim ation function along the sam e lines as we did for the standard Chebyshev case. First, Di will be defined in term s of εi in (2.39). nDi i) ( sinh1 1−− =ε (2.39) Next, we can define the pole locations in the second quadrant in the m anner of the previous section as shown in (2. 40)–(2.42), rem embering that these prim ed values m ust still be inverted. ) sin() sinh(m i m Dφ σ ⋅ −=′ (2.40) ) cos() cosh(m i m Dφ ω ⋅ =′ (2.41) even) ( 1)2/( , ,1 ,0= ,2)1 2(n n mnm m −⋅+⋅⋅= …πφ (2.42a) odd) ( 1]2)/1 [( , ,1 ,0= ,2)1 2(n n mnm m −−⋅+⋅⋅= …πφ (2.42b) We can determ ine the final pole locations by inverting these poles as indicated in (2.43) and (2.44): 2 2 m mm mωσσσ ′+′′= (2.43) Analog Filter Appr oxim ation Functions 37 2 2 m mm mωσωω ′+′′−= (2.44) If the approxim ation function is odd-order, then there will be a first-order pole on the negative real axis at σR as defined in (2.45): (2.45) 1)] [sinh(−−=i R D σ Next, we need to determ ine the placem ent of the finite zeros of the inverse Chebyshev approxim ation function, whic h are all purely im aginary com plex conjugate pairs located on the jω axis. Because they onl y occur in pairs, the numerator of an inverse Chebyshev transf er function will always be even. If the order of the denom inator is odd, then one zero of the transfer function will be located at infinity. The lo cation of the zeros on the jω axis is determ ined by (2.46) and (2.47), where φm is as defined in (2.42). A z is used in the subscript to differentiate the zero locations from the pole locations. (By the way , did y ou notice that the secant func tion in (2.47) is the reciprocal of the cosine function used in the standard C hebyshev function? ) 0.0=zmσ (2.46) ) sec(m zmφ ω= (2.47) 2.4.4 Inverse Chebyshev T ransfer Functi ons Now that we have located the necessary pol es and zeros that are pertinent to the definition of the inverse C hebyshev appr oxim ation, we can define the various factors that describe the transfer function. First, for odd- order approxim ations, (2.48) describes the first-order factor: 11 )] [sinh()] [sinh()(−− += ii oD SDSH (2.48) Next, the quadratic com ponents of the transfer function are described in (2.49)–(2.53). These are sim ilar to the qua dratic definition for the C hebyshev case, but we have added a num erator qua dratic for the zeros as well. ) () ()( 2 12 22 12 2 m m mm m m mBS B S AAS A S BS H +⋅+⋅+⋅+⋅= (2.49) 38 Practical A nalog and D igital F ilter D esign where m mBσ⋅−=21 (2.50) (2.51) 2 2 2 m m mB ωσ+= 0.0 21 =⋅−=zm mAσ (2.52) (2.53) 2 2 2 2 zm zm zm mA ωωσ =+= Although the value of A1m is zero, it is included to be consistent with the form at used throughout the rem ainder of the text. We are now ready to define the genera lized transfer function form for the inverse C hebyshev approxim ation function shown in (2.54). Since the inverse Chebyshev has a m aximally flat response in the passband as the Butterworth, there is no need for a gain adjustm ent consta nt as in the standard Chebyshev case. even) ( 1)2/( , ,1 ,0= , ) ( ) () ( ) ( )( 2 12 22 12 2 , n n mBS B S AAS A S B S H mm m mmmm m mm nI −+⋅+⋅+⋅+⋅ =∏∏∏∏ … (2.54a) odd) ( 1]2)/1 [( , ,1 ,0= , ) ( ) ( ))] [sinh(() ( ) ( )] [sinh( )( 2 12 212 12 21 , n n mBS B S A D SAS A S B D S H mm m mm imm m mm i nI −−+⋅+⋅ ⋅ ++⋅+⋅ ⋅ =∏∏∏∏ −− … (2.54b) The following num erical exam ples shoul d help to illustrate the process. Example 2.6 Inverse Chebyshev Third-Order Normaliz ed Transfer Function Problem: Determ ine the order, pole and zer o locations, and transfer function coefficients for an inverse Chebyshev f ilter to satisfy the following specifications: apass = −1 dB , astop = −22 dB , ωpass = 1 rad/sec, and ωstop = 2 rad/sec Analog Filter Appr oxim ation Functions 39 Solution: First, we determ ine the fundam ental constants needed from (2.35), (2.36), and (2.39): εi = 0.079685 n = 2.96 (3rd order) Di = 1.074803 cosh( Di) = 1.635391 sinh( Di) = 1.294026 Next, we find the locations of the first-order pole, the com plex pole in the second quadrant, and the second-order zeros on the jω axis from (2.40)–(2.47). A pole-zero plot is shown in Figure 2.15. (1st order) σR = −0.772782 ωR = 0.0 φ0 = 1π/6 σ‘0 = −0.647013 ω‘0 = +1.416290 σ0 = −0.266864 ω0 = −0.584157 (zeros) σz0 = +0.0 ωz0 = +1.154701 Finally , we generate the transfer function from (2.48)–(2.54): ) 41246.0 53373.0 () 77278.0 ( 3333.1) 3333.1 ( 41246.0 77278.0)(22 * 3,+⋅ +⋅ +⋅+⋅⋅= S S SSS HI ) 6498.1 0675.1 () 5456.1() 3333.5 ( 5456.1 30934.0)(22 3,+⋅+⋅++⋅⋅= S S SSS HI Figure 2.15 Pole and zero locations for thir d-order inverse Chebyshev filter. There is a problem with the first tr ansfer function above (shown with an asterisk *). It im plem ents an inverse Chebyshev approxim ation function that is norm alized to ωstop = 1 rad/sec instead of ωpass = 1 rad/sec. (This m eans that ωpass 40 Practical A nalog and D igital F ilter D esign would be at 0.5 rad/sec.) Therefore the entire frequency response is a factor of 2 too low. The attenuation at ω = 0.5 rad/sec is ~ 1 dB and the attenuation at ω = 1 rad/sec is ~22 dB. The process we use to correct the problem is actually an unnormalization procedure that is covered in Chapter 3. This unnormalization will usually occur as part of the total filte r design process, but we can make the adjustment manually in this particular cas e. The correct transfer function can be determined by substituting S/2 for S and then simplifying as indicated in the second transfer function above. This pro cess is mentioned here so we understand the WFilter coefficients, which are shown in Figure 2.16. Inv. Chebyshev 3rd-Order Normal. Lowpass Selectivity: Lowpass Approximation: Inv. Chebyshev Implementation: Analog Passband gain (dB): -1.0 Stopband gain (dB): -22.0 Passband freq (Hz): 0.1591549431 Stopband freq (Hz): 0.3183098862 Filter Length/Order: 03 Overall Filter Gain: 3.09341803036E-01 Numerator Coefficients QD [S^2 + S + 1 ] == ========================================= 01 0.0 0.00000000000E+00 1.54556432589E+00 02 1.0 0.00000000000E+00 5.33333333334E+00 Denominator Coefficients QD [S^2 + S + 1 ] == ========================================= 01 0.0 1.00000000000E+00 1.54556432589E+00 02 1.0 1.06745667061E+00 1.64982294953E+00 Figure 2.16 Inverse Chebyshev normalized thir d-order coefficients from WFilter. Example 2.7 Inverse Chebyshev Fourth-Order Normalized Transfer Function Problem: Determine the order, pole and zer o locations, and transfer function coefficients for an inverse Chebyshev f ilter to satisfy the following specifications: apass = −1 dB, a stop = −33 dB, ω pass = 1 rad/sec, and ωstop = 2 rad/sec Solution: First, we determine the fundament al constants needed from (2.35), (2.36), and (2.39): εi = 0.022393 n = 3.92 (4th order) Di = 1.123072 cosh( Di) = 1.699781 sinh( Di) = 1.374502 Analog Filter Appr oxim ation Functions 41 Next, we find the locations of the tw o complex poles in the second quadrant and the second-order zeros from (2.40)–( 2.47). A pole-zero plot is shown in Figure 2.17. φ0= 1π/8 σ‘0 = −0.525999 ω‘0 = +1.570393 σ0 = −0.191774 ω0 = −0.572549 φ0= 3π/8 σ‘0 = −1.269874 ω‘0 = +0.650478 σ0 = −0.623801 ω0 = −0.319535 (Zeros) σz0 = +0.0 ωz0 = +1.082392 (Zeros) σz1 = +0.0 ωz1 = +2.613126 Finally, we generate the transfer function from (2.48)–(2.54). (R efer to Exam ple 2.6 for an explanation of th e two transfer functions.) The WFilter coefficients are shown in Figure 2.18. ) 49123.0 2476.1 () 36459.0 38355.0 () 8284.6 () 1716.1 ( 022387.0)(2 22 2 * 4,+⋅+⋅ +⋅ ++⋅+⋅= S S S SS SS HI ) 9649.1 4952.2 () 4584.1 76710.0 ()314.27 () 6863.4 ( 022387.0)(2 22 2 4,+⋅+⋅+⋅ ++⋅ +⋅= S S S SS SS HI Figure 2.17 Pole and zero locations for four th-order inverse Chebyshev filter. 42 Practical A nalog and D igital F ilter D esign Inv. Chebyshev 4th-Order Normal. Lowpass Selectivity: Lowpass Approximation: Inv. Chebyshev Implementation: Analog Passband gain (dB): -1.0 Stopband gain (dB): -33.0 Passband freq (Hz): 0.1591549431 Stopband freq (Hz): 0.3183098862 Filter Length/Order: 04 Overall Filter Gain: 2.23872113857E-02 Numerator Coefficients QD [S^2 + S + 1 ] == ========================================= 01 1.0 0.00000000000E+00 4.68629150102E+00 02 1.0 0.00000000000E+00 2.73137084990E+01 Denominator Coefficients QD [S^2 + S + 1 ] == ========================================= 01 1.0 7.67095479088E-01 1.45835864853E+00 02 1.0 2.49520593780E+00 1.96492341597E+00 Figure 2.18 Inverse C hebyshev norm alized fourth-order coefficients. The m agnitude and phase responses for the two inverse C hebyshev exam ples are presented in Figures 2.19 and 2.20. Th e sam e procedure was used as in the Butterworth and C hebyshev cases. Figure 2.19 Inverse C hebyshev third-order and fourth-order m agnitude responses. Analog Filter Appr oxim ation Functions 43 Figure 2.20 Inverse C hebyshev third-order and fourth-order phase responses. 2.5 ELLIPTIC NORMALIZ ED APPROX IMATION FUNCTIONS The elliptic or Cauer approxim ation f unction provides the best selectivity characteristic of any of the approxim ation methods discussed t hus far. No other approxim ation m ethod will be able to provide a lower-order filter for the specifications provided. The elliptic filter com bines ripple in the passband and stopband in order to accom plish this feat. However, the elliptic approxim ation is also the m ost difficult to design. It invol ves the m ost sophisticated m athem atical functions of any of the methods discusse d in this text. Luckily , many good m inds have laid the foundation for this work and their results will be presented here so that we can put the design proce dure into a workable algorithm . 2.5.1 Elliptic Ma gnitude Respo nse The elliptic approxim ation’s m agnitude fre quency response function is shown in (2.55), where Rn is the C hebyshev rational function of order n. Rn is com posed of both num erator and denom inator portions, which allow an equiripple response in both the passband and stopband. The C hebyshev rational function Rn and m uch of elliptic approxim ation theory is based on the elliptic integral and the Jacobian elliptic functions. These functions can be evaluated via advanced m athem atical packages available for m ost computers and are discussed in Appendix D. The incom plete elliptic integral of the first kind is shown in (2.57), where k is referred to as the m odulus and φ is the amplitude of the integral. The m odulus k must be less than or equal to 1 for the elliptic integral to be real. The ellip tic sine, cosine, ta ngent, and difference functions based on the elliptic integral are given in (2.58)–(2.61), respectively. 44 Practical A nalog and D igital F ilter D esign These functions are used in the calculati on of the pole-zero locations in the next section. )/( 11)]/([ 2 2, ωωεωω o no nE Rj H ⋅+= (2.55) where ε is as defined previously . 1 10pass1.0− =⋅− aε (2.56) (2.57) ∫−−=φ φ 02/1 2 2) sin 1( ),( dx x k ku ) sin(),( φ=kusn (2.58) ) cos(),( φ=kucn (2.59) ) tan(),( φ=kusc (2.60) dudkudnφ=),( (2.61) The com plete elliptic integral of the first kind will be used m ore often than the incom plete integral and it is defined in (2.62). It should be noted at this point that there are various way s to define the elli ptic integrals and elliptic functions. Som e authors use the m odulus k as we have in this text, while others use other param eters related to k. (2.62) ∫−−= =2/ 02/1 2 2) sin 1( ),2/()(π π dx x k k uk CEI Analog Filter Appr oxim ation Functions 45 2.5.2 Elliptic Order The order of the elliptic approxim ation function required to m eet the specifications for a filter is given in (2.63): )( ) 1() 1( )( 22 kn CEI rt CEIkn CEIrt CEInE ⋅−−⋅= (2.63) where CEI refers to the com plete elliptic integral, and the ratio rt and the kernel kn are defined as stop pass/ωω=rt (2.64) )1 10/()1 10(stop pass 1.0 1.0− − =− − a akn (2.65) Example 2 .8 Elliptic Order Ca lcula tion Problem: Determ ine the order of an elliptic filter required to satisfy the following specifications: apass = −1 dB , astop = −34 dB , ωpass = 1 rad/sec, and ωstop = 2 rad/sec Solution: In order to determ ine the order of the elliptic approxim ation, we first determ ine that rt = 0.5 and kn = 0.0101548. Then, using any appropriate m ath package, we can determ ine that 97.2571.1 157.2976.5 686.1=⋅⋅=En which indicates that a third-order filter wi ll be required. Notice that the standard and inverse C hebyshev approxim ations require a fourth-order function to provide astop = −33 dB and a B utterworth approxim ation would require a seventh-order function to m eet this specification. 2.5.3 Elliptic Po le-Zero Locations The pole and zero locations for the elliptic approxim ation function are also dependent on the elliptic integral and the el liptic functions defi ned in the previous section. We’ll start by defining a variable vo, which is used in the calculation of the pole and zero locations. 46 Practical A nalog and D igital F ilter D esign )(),( )(1 1 kn CEInkn scrt CEIvo⋅⋅=−−ε (2.66) Next, the pole’s real and im aginary com ponents are determ ined as [] [] [] ⎟⎠⎞⎜⎝⎛− ⋅ −⎟⎠⎞⎜⎝⎛− ⋅⎟⎠⎞⎜⎝⎛− ⋅ ⋅ −= 2 2 22 2 1, ),( 11, 1, ),( ),( rt v snrtmf dnrt vcn rt vsnrtmfdnrtmfcn oo o mσ (2.67) [] [] ⎟⎠⎞⎜⎝⎛− ⋅ −⎟⎠⎞⎜⎝⎛− ⋅ = 2 2 22 1, ),( 11, ),( rt v snrtmf dnrt vdnrtmfsn oo mω (2.68) where even) ( 1)2/( , ,1 ,0= ,)1 2()()( n n mnm rt CEImf −+⋅⋅= … (2.69a) odd) ( 1]2)/1 [( , ,1 ,0= ,)2 2()()( n n mnm rt CEImf −−+⋅⋅= … (2.69b) Note the negative sign for σm, which effectively moves the pole location from the first quadrant to the second quadrant. In the case of odd-order approxim ations, the first-order denom inator pole will be located on the negative real axis at ⎟⎠⎞⎜⎝⎛− −⎟⎠⎞⎜⎝⎛− ⋅⎟⎠⎞⎜⎝⎛− −= 2 22 2 1, 11, 1, rt v snrt vcn rt vsn oo o Rσ (2.70) And finally , the location of the zeros that will be purely imaginary on the jω axis are given by 0.0=zmσ (2.71) Analog Filter Appr oxim ation Functions 47 []rtmfsnrtzm),(1 ⋅=ω (2.72) Although the elliptic approxim ation re quires a num ber of m athem atical functions which aren’t in every day usage, we have m ost of the hard work done in determ ining the transfer function we need. Our prim ary objective in this section is to develop an orderly manner to cal culate the pole and zero locations. 2.5.4 Elliptic Tra nsfer Functio ns Now we are able to define the first-orde r and quadratic factors that will make up the elliptic approxim ation function. Th e first-order factor for the elliptic approxim ation is indicated in (2.73), where σR is as indicated in (2.70). Again, there is no m atching finite zero for the fi rst-order pole factor; it is located at infinity . RR oSSHσσ +=)( (2.73) The form of the quadratic com ponents of the transfer function will also be identical to the inverse Chebys hev case, as indicated below: ) () ()( 2 12 22 12 2 m m mm m m mBS B S AAS A S BS H +⋅+⋅+⋅+⋅= (2.74) where m mBσ⋅−=21 (2.75) (2.76) 2 2 2 m m mB ωσ+= 0.0 21 =⋅−=zm mAσ (2.77) (2.78) 2 2 2 2 zm zm zm mA ωωσ =+= We are now ready to define a genera lized transfer function for the elliptic approxim ation function that is alm ost identi cal to the inverse C hebyshev case. The difference lies in the ripple in the passb and as in the standard C hebyshev case. 48 Practical A nalog and D igital F ilter D esign Consequently , the even-order ripple adjust ment factor is included in (2.79). The ratio of product factors is com bined with this value to determ ine the total gain adjustment: even) ( 1)2/( , ,1 ,0= , ) ( ) () ( ) ( ) 10( )( 2 12 22 12 205.0 ,pass n n mBS B S AAS A S B S H mm m mmmm m mma nE −+⋅+⋅+⋅+⋅ ⋅ =∏∏∏∏⋅ … (2.79a) odd) ( 1]2)/1 [( , ,1 ,0= , ) ( ) ( ) () ( ) ( )( 2 12 22 12 2 , n n mBS B S A SAS A S B S H mm m mm Rmm m mm R nE −−+⋅+⋅ ⋅++⋅+⋅ ⋅ =∏∏∏∏ …σσ (2.79b) Example 2 .9 Elliptic Third-Order No rmalized Tra nsfer Functio n Problem: Determ ine the order, pole and ze ro locations, and transfer function coefficients for an elliptic filter to satisfy the following specifications: apass = −1 dB , astop = −34 dB , ωpass = 1 rad/sec, and ωstop = 2 rad/sec Solution: First, we determ ine the fundam ental constants needed from (2.56) and (2.63)–(2.66): ε = 0.508847 n = 2.97 (3rd order) rt = 0.50 kn = 0.0101549 CEI(rt) = 1.685750 CEI(kn) = 1.570837 CEI[sqrt(1 − rt2)] = 2.156516 CEI[sqrt(1 − kn2)] = 5.976226 vo = 0.510786 Next, we find the locations of the first-order pole, the com plex pole in the second quadrant, and the second-order zeros on the jω axis from (2.67)–(2.72). A pole-zero plot is shown in Figure 2.21. (1st order) σR = −0.539953 ωR = 0.0 f(0) = 1.123834 σ0 = −0.217032 ω0 = +0.981574 (Zeros) σz0 = +0.0 ωz0 = +2.270068 Finally , we generate the transfer function from (2.73)–(2.79). The WFilter coefficients are given in Figure 2.22. Analog Filter Appr oxim ation Functions 49 ) 0106.1 43406.0 () 53995.0 ( 1532.5) 1532.5 ( 0106.1 53995.0)(22 3,+⋅ +⋅ +⋅+⋅⋅= S S SSs HE Figure 2.21 Pole and zero locations for thi rd-order elliptic norm alized filter. Elliptic 3rd-Order Normalized Lowpass Selectivity: Lowpass Approximation: Elliptic Implementation: Analog Passband gain (dB): -1.0 Stopband gain (dB): -34.0 Passband freq (Hz): 0.1591549431 Stopband freq (Hz): 0.3183098862 Filter Length/Order: 03 Overall Filter Gain: 1.96108842659E-01 Numerator Coefficients QD [S^2 + S + 1 ] == ========================================= 01 0.0 0.00000000000E+00 5.39953773543E-01 02 1.0 0.00000000000E+00 5.15320911642E+00 Denominator Coefficients QD [S^2 + S + 1 ] == ========================================= 01 0.0 1.00000000000E+00 5.39953773543E-01 02 1.0 4.34064063925E-01 1.01058987580E+00 Figure 2.22 Elliptic norm alized third-orde r coefficients from WFilter. 50 Practical A nalog and D igital F ilter D esign Example 2 .10 Elliptic Fo urth-Order No rmalized Tra nsfer Functio n Problem: Determ ine the order, pole and ze ro locations, and transfer function coefficients for an elliptic filter to satisfy the following specifications: apass = −1 dB , astop = −51 dB , ωpass = 1 rad/sec, and ωstop = 2 rad/sec Solution: First, we determ ine the fundam ental constants needed: ε = 0.508847 n = 3.95 (4th order) rt = 0.50 kn = 0.00143413 CEI(rt) = 1.685750 CEI(kn) = 1.570797 CEI[sqrt(1 − rt2)] = 2.156516 CEI[sqrt(1 − kn2)] = 7.933494 vo = 0.383119 Next, we find the locations of the two complex poles in the second quadrant and the second-order zeros on the j ω axis from (2.67)–(2.72). A pole-zero plot is shown in Figure 2.23. f(0) = 0.421438 σ0 = −0.351273 ω0 = +0.442498 f(1) = 1.264313 σ1 = −0.121478 ω1 = +0.989176 (Zeros) σz0 = +0.0 ωz0 = +4.922113 (Zeros) σz0 = +0.0 ωz0 = +2.143189 Finally , we generate the transfer function from (2.73)–(2.79). Note that in this even-order case, the gain constant of 0.891251 is included. The WFilter coefficients are given in Figure 2.24. ) 99323.0 24296.0 () 31920.0 70255.0 () 5933.4 ()227.24 ( 0025391.0)(2 22 2 4,+⋅ +⋅ +⋅ ++⋅+⋅= S S S SS SS HE Figure 2.23 Pole and zero locations for fourt h-order elliptic norm alized filter. Analog Filter Appr oxim ation Functions 51 Elliptic 4th-Order Normalized Lowpass Selectivity: Lowpass Approximation: Elliptic Implementation: Analog Passband gain (dB): -1.0 Stopband gain (dB): -51.0 Passband freq (Hz): 0.1591549431 Stopband freq (Hz): 0.3183098862 Filter Length/Order: 04 Overall Filter Gain: 2.53911536581E-03 Numerator Coefficients QD [S^2 + S + 1 ] == ========================================= 01 1.0 0.00000000000E+00 2.42272011683E+01 02 1.0 0.00000000000E+00 4.59326052578E+00 Denominator Coefficients QD [S^2 + S + 1 ] == ========================================= 01 1.0 7.02545661306E-01 3.19196825769E-01 02 1.0 2.42956737746E-01 9.93226261783E-01 Figure 2.24 Elliptic norm alized fourth-order coefficients from WFilter. The m agnitude and phase responses for th e elliptic filters are presented in Figures 2.25 and 2.26. Figure 2.25 Elliptic third-order and fourt h-order m agnitude responses. 52 Practical A nalog and D igital F ilter D esign Figure 2.26 Elliptic third-order and fourth-order phase responses. 2.6 COMPARISON OF APPROX IMATION METHODS Now that we have discussed the four a pproxim ation m ethods a nd display ed third- order and fourth-order magnitude and phase plots, we are in a position to com pare the results. First, we look at the magnitude plots of Figures 2. 7, 2.13, 2.19, and 2.25. Table 2.1 shows the gains achie ved at the stopband edge frequency of 2 rad/sec for each norm alized filter type and order. (Each filter was designed with a passband gain of −1 dB.) Obviously , if attenuation characteristics in the stopband are the prim ary concern, an elliptic filter would have to be the choice. It provides 12 dB more attenuation than the C hebyshev ty pes and 22 dB more attenuation than the B utterworth filt er for the third-order case. In the fourth-order case, the differences increase to over 18 and 33 dB com pared to the C hebyshev and B utterworth filters. The C hebyshev filter ty pes them selves afford better stopband characteristics when compared to the B utterworth filter. They provide 10 and 15 dB more attenuation for the third-order and fourth-orde r cases. Although the table only lists the gains for third-orde r and fourth-order filters, the sam e trend continues for higher-order filters. Although the Chebyshev and inverse C hebyshev filters provide the sam e gains at the passband and stopband edge frequencies, their responses are not identical. If we were to take a clos e look at the frequency response in the passband, we would find that the inverse C hebyshev provides a better approxim ation to the ideal response except at frequencies very near to 1 (the norm alized passband edge frequency ). In that case, the standard Chebyshev produces a tighter fit. In the transition band, the standard C hebyshev response provides a more rapid transition. And in the stopband, the standard C hebyshev’s response continues to increase the atte nuation as the frequency increases, while the inverse C hebyshev’s response alternates between sm all gains and astop. In Analog Filter Appr oxim ation Functions 53 some cases, the filter designer might trade the faster transition for the nondecreasing attenuation. Table 2.1 Comparison of Filter Gains at 2 rad/sec Filter Type 3rd Order 4th Order Butterworth −12.5 dB −18.3 dB Chebyshev −22.5 dB −33.8 dB Inverse Chebyshev −22.5 dB −33.8 dB Elliptic −34.5 dB −51.9 dB Although the magnitude characteristics of a filter are very important, the phase characteristics of a filter are also crucial in many projects. Whether in audio networks or data transmission systems, desi gners are looking for filters with linear phase response. Nonlinear phase response in an audio network will cause noticeable phase distortion for the listener th at cannot be tolerated, especially in high-quality systems. In data transmi ssion systems nonlinear phase response produces group delays that are functions of frequency. This produces distortion in the pulses sent over the system and can di stort edges and levels to the point of causing errors in the received signal. We can compare the phase responses of Figures 2.8, 2.14, 2.20, and 2.26 to see the level of phase distortion for each approximation type. Remember that the transitions from −180 to +180 degrees are not discontinuities, but rather a functi on of the display method. (The phase response is written to a data file in its t rue form.) Table 2.2 shows the phase angles for the third-order and fourth-orde r filters at the passband and stopband edge frequencies. Table 2.2 Comparison of Filter Phase at 1 and 2 rad/sec Filter Type 3rd @ 1 r/s 3rd @ 2 r/s 4th @ 1 r/s 4th @ 2 r/s Butterworth −104° −192° −146° −266° Chebyshev −154° −238° −230° −330° Inverse Chebyshev −94° −192° −133° −264° Elliptic −150° −238° −226° −330° As Table 2.2 and the phase plots indicate, the filters with the maximally flat response in the passband (Butterworth a nd inverse Chebyshev) provide the most linear response, although the inverse Cheb yshev does have phase discontinuities in the stopband caused by the complex ze ros. These are usually not critical because the filter’s magnitude response is very small at these frequencies and the distortion should be minimal. The phase responses of the standard Chebyshev and 54 Practical A nalog and D igital F ilter D esign elliptic are also matched very closely a nd can be judged equivalent except for the discontinuities in the stopband caused by the zeros for the elliptic case. A filter designer’s task is not always clear cut. It seems that every project requires as much stopband attenuation as possible while providing a phase response as linear as possible. The ta sk becomes one of weighing the importance of each characteristic. If phase response is more critical than magnitude response, then the Butterworth filter is a better c hoice. If the opposite is true, the elliptic filter is a better choice. If magnitude a nd phase responses are nearly equal in importance, then one of the Chebyshev fi lters may be the best choice. Other alternatives are also possible. Elliptic filte rs can be used for their selectivity, with phase compensation filters added to make the phase more linear. (These filter types are not covered in this text, but refe rences in the analog filter design section of Appendix A provide further information.) A designer mu st be careful when pursuing these alternatives, since in some cases the result may be no better than the equivalent Butterworth or Chebyshev filter. 2.7 CONCLUSION In this chapter, we studied the core of analog filter design, the normalized approximation functions. By de veloping these functions, we have laid the foundation for the remainder of the chapters on analog filter design as well as a good bit of digital IIR filter design. By approaching each approximation function in the same manner, and developing me thods for determining exact pole and zero placement, we have simplified the job of generating the C code necessary to implement these algorithms in a clean, effi cient manner. (Those who are interested in seeing more on the development of the C code can turn to Appendix D.) In the next chapter, we will finish up the analog filter design calculati ons by determining a technique to unnormalize the transfer functions we have just developed. Chapter 3 Analog Lowpass, Highpass, Bandpass, and Bandstop Filters In the last ch apter, we were ab le to determine the normalized approximation functions for the most co mmon types of analog filters. Ou r task in this ch apter is to unnorm alize those approxi mation funct ions i n a m anner t o produce l owpass, highpass, bandpass, and bandstop filters at the desired frequencies. This unnorm alization will be carried out in such a way that the design of the normalized approximation functions will b e central to the development. Fig ure 3.1 shows the three-st ep procedure used i n the unnorm alization. The si mplicity of this procedure is the fact that the second step is the sam e for all filter design m ethods. Figure 3.1 Procedure for unnorm alization. 3.1 UNNORMALIZ ED LOWPASS APPROX IMATION FUNCTIONS Even t hough t he norm alized approxi mation funct ions det ermined in the previ ous chapter are lowpass functions, they still need to be unnorm alized to the proper operat ional frequency . The first step i n the unnorm alization procedure, as indicated in Figure 3.1, i s to determine the order of t he approxi mation funct ion from the unnorm alized speci fications. The order of approxi mation funct ion depends onl y on t he passband and st opband gains and frequenci es. The gai ns for both the norm alized and unnorm alized appr oxim ation functions will be the sam e, the onl y speci fications t hat change are the passband and stopband edge frequenci es. However, as i ndicated i n Chapter 2, i t is not the individual 55 56 Practical Analog and Digital Filter Design frequenci es that determine the order of t he approxi mation funct ion, but rather the ratio of t he frequenci es. Therefore, we can defi ne a frequency ratio vari able in (3.1) that will b e used for the lowpass filter typ e as in dicated by the additional subscript L. passstop passstop ff rL ==Ωωω (3.1) Each of t he equat ions from Chapter 2 that were used to determine the order of a particular filter typ e can now be redefined in term s of Ωr, as indicated in (3.2)– (3.6). ) log(2)]1 10/()1 10log[(pass stop 1.0 1.0 ra a BnΩ⋅− −=⋅− ⋅− (3.2) )( cosh)1 10/()1 10( cosh 11.0 1.0 1 pass stop ra a I Cn n Ω⎥⎦⎤ ⎢⎣⎡− − ==−⋅− ⋅− − (3.3) )( 11 )( 22 kn CEI rt CEIkn CEIrt CEI nE ⋅⎟⎠⎞⎜⎝⎛−⎟⎠⎞⎜⎝⎛−⋅ = (3.4) where r rtΩ=/1 (3.5) )1 10/()1 10(stop pass 1.0 1.0− − =− − a akn (3.6) It may appear that we are doing a lot of work just to change a variable nam e, but Ωr will be defined differently for each of the other types of filter selectivities as we will see in the next sectio ns. For that reaso n (3.2)–(3.6) do not include the additional subscript L; however, in each section we will define Ωr with a subscript as in (3.1) for clarity . Analog Lowpass, Highpass, Bandpass, and Bandstop Filters 57 So in this lowpass case, t he first step in the unnorm alization procedure doesn’t require an y wo rk at all. W e simply determine the order of the filter as we have i n the past . The second st ep of the unnorm alization procedure, determination of the norm alized approxi mation funct ion, has al ready been devel oped i n the previous chapter. It appears that we are ready to determine the third and final step of the procedure, whi ch is to unnorm alize the norm alized approxi mation funct ion. In the lowpass case, th is sim ply req uires a scaling of the frequency characteristic from 1 rad /sec to a m ore u sable freq uency. A sim ple su bstitution for the norm alized vari able S is all that is necessary, as sh own in (3.7). (A su bscript of L is used to indicate th at this substitution is fo r lowpass filters o nly.) Th e freq uency const ant ωo will b e ωstop for t he inverse C hebyshev approxi mation, as di scussed i n Chapter 2, and ωpass for al l other approxi mations. oLsSω= (3.7) 3.1.1 Handl ing a Fi rst-Order Factor We will be developing code to im plem ent the unnorm alization process, so it is important to carefu lly d escrib e the substitution process. Fo r the first-o rder facto r, the process begins with (3.8), where the B1 coefficient is typically 1: 2 12 1 2 12 1 ) () ()(B s BA sA BSBASAsH oo sSo+⋅+⋅=+⋅+⋅= =ωω ω (3.8) In this equation, uppercase A and B represent the coefficients of the norm alized approxim ation function. After sim plification, (3.9) results in a new set of coefficients. In this equation, lowercase a and b represent the unnorm alized coefficients that will be used in our final approxim ation function: 2 12 1 2 12 1)(bsbasa BsBAsAsH oo +⋅+⋅=⋅+⋅⋅+⋅=ωω (3.9) We can generalize these results for the first-order factor below: • The gain constant is unchanged. • The s-term coefficients becom e a1 = A1, b1 = B1 • The constant term coefficients becom e a2 = A2 ωo, b2 = B2 ωo 58 Practical Analog and Digital Filter Design 3.1.2 Handl ing a Second-Order Factor In the case of the quadratic term s that are used to describe our coefficients, the unnorm alization process is s hown in (3.10) and (3.11): 2 12 02 12 0 2 12 02 12 0 ) ( ) () ( ) ()( B sB s BA sA sA BSB SBASA SAsH o oo o sSo+⋅+⋅+⋅+⋅= +⋅+⋅+⋅+⋅= =ω ωω ω ω (3.10) 2 12 02 12 0 2 2 12 02 2 12 0)( bsb sbasa sa Bs B sBAs A sAsH o oo o +⋅+⋅+⋅+⋅= ⋅+⋅⋅+⋅⋅+⋅⋅+⋅= ω ωω ω (3.11) The coefficient A0 will be 1 or 0. A value of 1 will be present only if an inverse Chebyshev or elliptic approxim ation is being unnorm alized, while a 0 will be used for C hebyshev and B utterworth. A1 will norm ally be 0 for all approxim ations, but is included for com pleteness of the derivation in the event we want to use any of our work at a later tim e when com plex conjugate zeros will occur off the jω axis. B0 will typically be 1 for all cases, but is retained for generality. By observation, we can determ ine the following relationships that can be used in our C code: • The gain constant is unchanged. • The s2-term coefficients becom e a0 = A0, b0 = B0 • The s-term coefficients becom e a1 = A1 ωo, b1 = B1 ωo • The constant term coefficients becom e aA b Boo 222 2 22==ωω, Complete numerical exam ples of the lowpass unnorm alization process are now in order. Example 3.1 Unnormaliz ed Inverse Chebyshev Lowpass Filter Problem: Determ ine the transfer function for an inverse C hebyshev lowpass filter to satisfy the specifications: apass = −0.25 dB , astop = −38.0 dB , ωpass = 600 rad/sec, ωstop = 1,000 rad/sec Analog Lowpass, Highpass, Bandpass, and Bandstop Filters 59 Solution: Using the m aterial of Section 2.4, the im portant values for this exam ple and the norm alized transfer func tion are listed below. The unnorm alized transfer function is then determ ined by m aking the substitution S = s / ωo and using the relationships just developed: Ωr = 1.667 n = 5.90 (6th order) ωo = 1000.0 rad/sec )034.1 895.1 () 7142.0 9583.0 () 5455.0 2679.0 ()93.14 ()000.2 ()072.1 ( 0.01259)(2 2 22 2 2 6,+⋅+⋅+⋅+⋅+⋅++⋅+⋅+⋅= S S S S S SS S SS HI )10 034.1 895,1 ()102.714 3.958 ()105.545 679,2 ()1093.14 ()10 000.2 ()10 072.1 ( 0.01259 )( 6 2 3 2 3 26 2 6 2 6 26, ⋅+⋅+⋅⋅+⋅+⋅⋅+⋅+⋅+⋅⋅+⋅⋅+⋅= s s s s s ss s ss HI Example 3.2 Unnormaliz ed Butterworth Lowpass Filter Problem: Determ ine the transfer function for a Butterworth lowpass filter to satisfy the following specifications: apass = −0.5 dB , astop = −21 dB , fpass = 1,000 Hz, fstop = 2,000 Hz Solution: Using the m aterial of Section 2.2, the im portant values for this exam ple and the norm alized transfer function are listed below: Ωr = 2.0 n = 5.00 (5th order) ωo = 6,283.19 rad/sec )523.1 7627.0 ()523.1 997.1 ()234.1(523.1523.1 234.1)(2 25,+⋅+⋅+⋅+⋅+⋅⋅= S S S S SS HB The unnorm alized transfer function is then determ ined by making the substitution S = s / ωo and using the relations hips just developed: )10 013.6 792,4 ()10 013.6 1055.12 ()754,7(10 013.6 10 013.6 7754)(7 2 7 3 27 7 5,⋅+⋅+⋅⋅+⋅⋅+⋅+⋅⋅⋅⋅= s s s s ss HB We can also use W Filter to design either of the lowpass filters just described, but in this case we’ll pick the Butterwort h filter. The coefficients and response of this filter are shown in Figures 3.2 and 3.3. 60 Practical Analog and Digital Filter Design Butterworth Lowpass Filter Selectivity: Lowpass Approximation: Butterworth Implementation: Analog Passband gain (dB): -0.5 Stopband gain (dB): -21.0 Passband freq (Hz): 1000.0 Stopband freq (Hz): 2000.0 Filter Length/Order: 05 Overall Filter Gain: 1.00000000000E+00 Numerator Coefficients QD [S^2 + S + 1 ] == ========================================= 01 0.0 0.00000000000E+00 7.75420567954E+03 02 0.0 0.00000000000E+00 6.01277057205E+07 03 0.0 0.00000000000E+00 6.01277057205E+07 Denominator Coefficients QD [S^2 + S + 1 ] == ========================================= 01 0.0 1.00000000000E+00 7.75420567954E+03 02 1.0 4.79236266571E+03 6.01277057205E+07 03 1.0 1.25465683452E+04 6.01277057205E+07 Figure 3.2 Filter coefficients for Exam ple 3.2 from WFilter. Figure 3.3 Filter m agnitude response for Exam ple 3.2. 3.2 UNNORMALIZ ED HIGHPASS APPROX IMATION FUNCTIONS The norm alized lowpass approxim ation can also be used to generate the approxim ation function for a highpass filte r. The calculation for the ratio frequency Ωr is based on the ratio of passband to stopband frequencies, as shown Analog Lowpass, Highpass, Bandpass, and Bandstop Filters 61 in (3.12). This is the reciprocal of the lowpass case, but since ωpass > ωstop , the result still produces a value greater than 1. The Ωr ratio alway s produces a value greater than 1 (as we will see in later sec tions as well) and as the value gets larger and larger, the order of the filter will reduce as long as other characteristics rem ain the sam e. stoppass stoppass ff rH ==Ωωω (3.12) Once the norm alized lowpass approxim ation is determ ined based on the order, we can unnorm alize the lowpass transfer function using an appropriate unnorm alization substitution. In the case of the highpass filter, the unnorm alization substitution is given in (3.13). As in the lowpass case, ωo will take on the value of ωpass except for the inverse C hebyshev approxim ation where it will have the value of ωstop. sSo Hω= (3.13) 3.2.1 Handl ing a Fi rst-Order Factor For the first-order case, we start with (3.14) and m ake the substitution of (3.13). The final result is then shown in (3.15). In this unnorm alization case, we see that there is a gain adjustm ent (A2 / B2) that m ust be considered. 2 12 1 2 12 1 ) () ()(Bs BAs A BSBASAsH oo s So+⋅+⋅=+⋅+⋅= =ωω ω (3.14) 2 12 1 22 2 12 1 22 )/()/()(bsbasa BA BBsAAs BAsH oo +⋅+⋅⋅=⋅ +⋅ +⋅=ωω (3.15) From careful observation we can dra w the following inform ation from these equations: • The gain constant is m ultiplied by A2 / B2. • The s-term coefficients becom e a1 = 1, b1 = 1 • The constant term coefficients becom e a2 = (A1 / A2) ωo, b2 = (B1 / B2) ωo 62 Practical Analog and Digital Filter Design 3.2.2 Handl ing a Second-Order Factor In the case of this highpass unnorm alizati on process, the second-order factors will be unnorm alized in the m anner shown in (3.16): 2 12 02 12 0 2 12 02 12 0 ) ( ) () ( ) ()( Bs B s BAs A s A BSB SBASA SAsH o oo o s So+⋅+⋅+⋅+⋅= +⋅+⋅+⋅+⋅= =ω ωω ω ω (3.16) that can be sim plified to produce 2 12 02 12 0 22 2 2 0 2 122 2 0 2 12 22 )/( )/()/( )/()( bsbsbasasa BA BBs BB sAAs AA s BAsH o oo o +⋅+⋅+⋅+⋅⋅= ⋅+⋅⋅+⋅+⋅⋅+⋅= ω ωω ω (3.17) Notice that if A0 and A1 are both zero (which will be the case for Butterworth and C hebyshev approxim ations), then a1 and a2 will be zero, leaving only an s2-term in the num erator. A2 will never be zero in a norm alized approxim ation function. We can sum marize the resu lts of the unnorm alization below: • The gain constant is m ultiplied by A2 / B2. • The s2-term coefficients becom e a0 = 1, b0 = 1 • The s-term coefficients becom e a1 = (A1 / A2) ωo, b1 = (B1 / B2) ωo • The constant term coefficients becom e aA A b B Boo 20 22 20 22= = (/ ), (/) ωω Num erical exam ples of the highpass unnorm alization process can now be used to better illustrate the process. Example 3 .3 Unno rmalized Elliptic Hig hpass Filter Problem: Determ ine the transfer function for an elliptic highpass filter to satisfy the following specifications: apass = −0.5 dB , astop = −45.0 dB , ωpass = 3,000 rad/sec, ωstop = 2,000 rad/sec Analog Lowpass, Highpass, Bandpass, and Bandstop Filters 63 Solution: Using the m aterial of Section 2.5, the im portant values for this exam ple and the norm alized transfer function are listed below: Ωr = 1.5 n = 4.61 (5th order) ωo = 3,000.0 rad/sec )032.1 1635.0 () 5760.0 5702.0 () 4260.0 ()426.2 ()438.5 ( 4260.0 04507.0)(2 22 2 5,+⋅+⋅+⋅+⋅++⋅+⋅⋅= S S S S SS SS HE The unnorm alized transfer function is then determ ined by making the substitution S = ωo / s and using the relations hips just developed: )10 722.8 2.475 ()10 562.1 970,2 ()043,7()10 711.3 ()10 655.1 ()(6 2 7 26 2 6 2 5,⋅+⋅+⋅⋅+⋅+⋅+⋅+⋅⋅+⋅= s s s s ss sss HE Exampl e 3.4 Unnormal ized Chebyshev Hi ghpass Fi lter Problem: Determ ine the transfer function for a Chebyshev highpass filter to satisfy the following specifications: apass = −1.5 dB , astop = −40 dB , fpass = 2,000 Hz, fstop = 800 Hz Solution: Using the m aterial of Section 2.3, the im portant values for this exam ple and the norm alized transfer function are listed below: Ωr = 2.5 n = 3.66 (4th order) ωo = 12,566.4 rad/sec ) 2434.0 5752.0 () 9505.0 2383.0 (2434.0 9505.0 8414.0)(2 24,+⋅+⋅+⋅+⋅⋅= S S S SS HC The unnorm alized transfer function is then determ ined by making the substitution S = ωo / s and using the relations hips just developed: )10 489.6 703,29 ()10 661.1 150,3 (8414.0)(8 2 8 22 2 4,⋅+⋅+⋅⋅+⋅+⋅⋅= s s s ssss HC The results of using WFilter to design the filter of Exam ple 3.4 are illustrated in Figures 3.4 and 3.5, which show the coefficients and m agnitude response. 64 Practical Analog and Digital Filter Design 3.3 UNNORMALIZ ED BANDPASS APPROX IMATION FUNCTIONS In the case of a bandpass unnorm alization, Ωr will be defined in (3.18). Note that for this case, Ωr will be greater than 1, as ha s been the case for the lowpass and highpass unnorm alization. Chebyshev Highpass Filter Selectivity: Highpass Approximation: Chebyshev Implementation: Analog Passband gain (dB): -1.5 Stopband gain (dB): -40.0 Passband freq (Hz): 2000.0 Stopband freq (Hz): 800.0 Filter Length/Order: 04 Overall Filter Gain: 8.41395141645E-01 Numerator Coefficients QD [S^2 + S + 1 ] == ========================================= 01 1.0 0.00000000000E+00 0.00000000000E+00 02 1.0 0.00000000000E+00 0.00000000000E+00 Denominator Coefficients QD [S^2 + S + 1 ] == ========================================= 01 1.0 3.15012807725E+03 1.66143895400E+08 02 1.0 2.97027255443E+04 6.48898535622E+08 Figure 3.4 Filter coefficients for Exam ple 3.4 from WFilter. Figure 3.5 Filter m agnitude response for Exam ple 3.4. Analog Lowpass, Highpass, Bandpass, and Bandstop Filters 65 pass1 pass2stop1 stop2 pass1 pass2stop1 stop2 f ff f rP−− =−− =Ωωωωω (3.18) After determ ining the norm alized lo wpass approxim ation using the order we determ ined from the bandpass specifica tions, we can unnorm alize the lowpass function into a bandpass function. To accom plish this we use the substitution given in (3.19): s BWsSo P⋅+=2 2ω (3.19) where for all approxim ations except the inverse C hebyshev, pass2 pass1ωωω ⋅=o (3.20) pass1 pass2ωω−=BW (3.21) For the inverse Chebyshev case these va lues are defined as (another exam ple of the opposite nature of this approxim ation) stop2 stop1ωωω ⋅=o (3.22) stop1 stop2ωω−=BW (3.23) In order to provide an accurate value of Ωr in (3.18), the stopband and passband edge frequencies m ust be symmetrically spaced on either side of ωo. The simplest way to test for this is to check to see that the relationship of (3.24) is satisfied. If this equation is not satisfied, the larger side m ust be reduced to form an equality by increasing ωstop1 or decreasing ωstop2. This will tighten the restrictions, so the origina l specifications will still be m et, and an accurate order can be calculated. (If there is an extrem e inequality, other m easures can be used to implem ent the filter. For exam ple, an additional lowpass or highpass filter can be added to provide the required selectivity .) pass2stop2 stop1pass1 ωω ωω = (3.24) 66 Practical Analog and Digital Filter Design As indicated by (3.19), the unnorm alization process will result in a bandpass approxim ation function that has twice the order of the lowpass function used to generate it. This seem s reasonable when we consider that a bandpass filter m ust provide a transition from a stopband to a passband (like a highpass filter) and another transition from a passband to a stopband (like a lowpass filter). The resulting function m ust therefore be twice the order of the original lowpass function on which it is based. 3.3.1 Handl ing a Fi rst-Order Factor For a first-order factor in the lowpa ss approxim ation function, (3.25) shows how the substitution of (3.19) is m ade: 22 2 122 2 1 ) () ( 2 12 1 ]) () ([]) () ([)( 2 2 B s BW s BA s BW s A BSBASAsH oo sBW sSo+⋅ +⋅+⋅ +⋅=+⋅+⋅= ⋅ +=ωω ω (3.25) And after som e simplification we have the result in (3.26). The relationships between the coefficients ar e shown. Note that if A1 = 0, as will norm ally be the case, the num erator will only have an s-term present. 2 12 02 12 0 2 1 22 12 1 22 1)( bsb sbasa sa Bs BWB sBAs BWA sAsH oo +⋅+⋅+⋅+⋅= ⋅+⋅⋅+⋅⋅+⋅⋅+⋅= ωω (3.26) • The gain constant is unchanged. • The s2-term bandpass coefficients becom e a0 = A1, b0 = B1 • The s-term bandpass coefficients becom e a1 = A2 BW, b1 = B2 BW • The constant term bandpass coefficients becom e aA b Boo 212 2 12==ωω, 3.3.2 Handl ing a Second-Order Factor Unnorm alizing a second-order factor is a bit m ore of a challenge. When the substitution variable SP of (3.19) is inserted into a second-order lowpass approxim ation, a fourth-order factor results . What do we do with a fourth-order factor? All of our developm ent to this point is based on quadratic factors and with good reason. They represent a com plex conj ugate pair and they will be used to efficiently im plem ent the filters in late r chapters. We could factor the fourth-order, but this would require a num erical algorithm that is tim e-consum ing and not alway s accurate. There is another di rected procedure that can be used. Analog Lowpass, Highpass, Bandpass, and Bandstop Filters 67 If we factor the lowpass approxim ation qua dratic into two com plex conjugate factors before m aking the substitution of (3.19), the result after the substitution and sim plification is two quadratic equa tions. However, each of these quadratics would have a com plex coefficient that w ould m ean they could not be im plem ented directly. However, if these two quadratics are again factored, we will find two sets of complex conjugate pairs within the set of four factors. These com plex conjugate pairs could then be com bined to produce two quadratics that have all real coefficients. Perhaps an easy exam ple is in order. C onsider the transfer function shown in (3.27) that has already been factored: )11 ()11 (2 2 22)(2j S j S S SSH−+⋅++= +⋅+= (3.27) Now if we assum e that ωo = 1 and BW = 1, we can substitute S = (s2 + 1) / s and sim plify to produce the following: ]1 )11( []1 )11( [2)(2 22 +⋅−+⋅+⋅++⋅= sj s sj sssH (3.28) The roots of the first quadratic can be determ ined to be )53.1 743.0( ),529.0 257.0(2)058.2 486.0()11( 2,1 j jj js −− +−=+±+−= (3.29a) and the two roots of the second quadratic pair up with the first. )53.1 743.0( ),529.0 257.0(4,3 j j s +− −−= (3.29b) The resulting transfer function can then be written as (3.30) by com bining the complex conj ugate roots from each quadratic: )890.2 486.1 ()346.0 514.0 (2)(2 22 +⋅+⋅+⋅+⋅= s s s sssH (3.30) This algorithm for finding the two quadratics in the bandpass approxim ation from the single quadratic in the lowpass function will be used as the standard method in this section. Unfortunately , it is very difficult to define the final bandpass coefficients in term s of only the initial lowpass coefficients because of 68 Practical Analog and Digital Filter Design the com plexity of expressions. However, if we use a few interm ediate variables, the process should be able to be dem onstrated without too m uch confusion. We start with the general expression for the norm alized lowpass second-order factor shown in (3.31) in norm al and factored form . The A0 and B0 coefficients have been om itted for clarity since they w ill be assum ed to be 1 in this case, and p and z represent the com plex poles and zeros, respectively. (An asterisk indicates the com plex conjugate value.) ) () (* 1 1* 1 1 2 122 12 2 2 ) )( () )( ()( sBW sSopSpSzSzS BSB SASA SsH ⋅ +=++++= +⋅++⋅+= ω (3.31) After m aking the indicated substitu tion and sim plifying, we have ) () () () ()(2 * 12 2 122 * 12 2 12 o oo o sp BW s sp BW ssz BW s sz BW ssH ω ωω ω +⋅⋅+⋅+⋅⋅++⋅⋅+⋅+⋅⋅+= (3.32) Each one of the quadratic factors in (3 .32) can now be factored into first- order factors, as indicated in (3.33). Note that the constants from the z1 quadratic are labeled with an a and b, while the com plex conjugates use c and d. The denom inator uses the sam e designations. ) () () () () () () () ()( 1 1 1 11 1 1 1 d c b ad c b a ps ps ps pszs zs zs zssH+⋅+⋅+⋅++⋅+⋅+⋅+= (3.33) Now, by matching the com plex conjugate pairs, we can reconstruct two quadratics with real coefficients in both the num erator and denom inator: ) )( () )( ()( 5 42 2 125 42 2 12 bsb sbsb sasa sasa ssH +⋅++⋅++⋅++⋅+= (3.34) The results shown in (3.34) are valid for the inverse Chebyshev and elliptic approxim ation functions that use zeros on the jω axis. However, for the Butterworth and Chebyshev approxim ation functions, the result will be som ewhat different. Equation (3.35) shows the starting point for this developm ent. After substitution and sim plification, (3.36) results. Then following the sam e basic steps as in the previous derivation, (3.37) eventually em erges. Analog Lowpass, Highpass, Bandpass, and Bandstop Filters 69 ) () (* 1 12 2 122 2 2 ) )( ()( s BW sSopSpSA BSB SAsH ⋅ +=++= +⋅+= ω (3.35) ) () ()(2 * 12 2 122 2 2 o o sp BW s sp BW ss BWAsH ω ω +⋅⋅+⋅+⋅⋅+⋅⋅= (3.36) ) )( ()( 5 42 2 122 2 2 bsb sbsb ss BWAsH +⋅++⋅+⋅⋅= (3.37) Now, som e exam ples illustrating the bandpass design process are in order. Example 3.5 Unnormaliz ed Butterworth Bandpass Filter Problem: Determ ine the transfer function for a Butterworth bandpass filter to satisfy the following specifications: apass = −1.0 dB , astop = −21 dB , fpass1 = 300 Hz, fpass2 = 3,000 Hz, fstop1 = 50 Hz, fstop2 = 9,000 Hz Solution: Using the m aterial of Section 2.2, the im portant values for this exam ple and the norm alized transfer function are listed below. In this case, fstop1 must be changed to 100 Hz to provide symmetry. The function is shown with quadratics in factored form , as indicated by the (2) superscript. Ωr = 3.3 n = 2.59 (3rd order) ωo = 5,960.8 rad/sec BW = 16,965 rad/sec )2( 3,) 0848.1 62629.0 () 2526.1(5690.1 2526.1)( j S SS HB± +⋅+⋅= After m aking the substitution of (3.19) and factoring again, the following equation em erges: )2( )2( 7 23 6,)836,19 9909( ) 14341.716()10 553.3 249,21 () 965,16( 569.1 253.1)( j s j s s sss HB±+⋅ ±+⋅⋅+⋅+⋅⋅⋅= After sim plification, the follo wing transfer function results: 70 Practical Analog and Digital Filter Design )10 917.4 817,19 ()10 568.2 432,1 ()10 553.3 249,21 ()10 125.2( )( 8 2 6 2 7 23 346, ⋅++⋅⋅++⋅⋅++⋅⋅= s s s s s sss HB Example 3.6 Unnormaliz ed Inverse Chebyshev Bandpass Filter Problem: Determ ine the transfer function for an inverse C hebyshev bandpass filter to satisfy the following specifications: apass = −0.5 dB , astop = −33 dB , fpass1 = 100 Hz, fpass2 = 200 Hz, fstop1 = 50 Hz, fstop2 = 400 Hz Solution: Using the m aterial of Section 2.4, the im portant values for this exam ple and the norm alized transfer f unction are listed below. The transfer function is shown with quadratics in f actored form , as indicated by the (2) superscript. Ωr = 3.5 n = 2.88 (3rd order) ωo = 888.58 rad/sec BW = 2,199.1 rad/sec )2()2( 3,) 38655.0 20190.0 () 47098.0 () 15470.1 ( 47098.0 0.14264)( j S SjSS HI± +⋅ +±⋅⋅= After m aking the substitution of (3.19) and factoring again, the following equation em erges: )2( )2( 5 2)2( )2( 6,)390,1 8.319( )6.539 2.124()10 896.7 036,1 ()819,2 ( )1.280 () 036,1( 14264.0)( j s j s s sjs jsss HI±+⋅ ±+⋅⋅+⋅+±⋅ ±⋅⋅⋅= After sim plification, the follo wing transfer function results: )10 033.2 6.639 ()10 066.3 4.248 ()10 896.7 036,1 ()10 949.7 ()10 843.7 () 036,1( 14264.0 )( 6 2 5 2 5 26 2 4 26, ⋅+⋅+⋅⋅+⋅+⋅⋅+⋅+⋅+⋅⋅+⋅⋅⋅= s s s s s ss sss HI We can use WFilter to design the inverse Chebyshev bandpass filter of Exam ple 3.6. The coefficients for this design are shown in Figure 3.6 with the magnitude response shown in Figure 3.7. Notice that two of the numerator coefficients are quite sm all (approxim ately 10−16 or sm aller) and should be interpreted as zero since these quadratic s represent com plex zeros located on the jω-axis. Analog Lowpass, Highpass, Bandpass, and Bandstop Filters 71 Inverse Chebyshev Bandpass Filter Selectivity: Bandpass Approximation: Inv. Chebyshev Implementation: Analog Passband gain (dB): -0.5 Stopband gain (dB): -33.0 PB freq-lower (Hz): 100.0 PB freq-upper (Hz): 200.0 SB freq-lower (Hz): 50.0 SB freq-upper (Hz): 400.0 Filter Length/Order: 06 Overall Filter Gain: 1.42635925362E-01 Numerator Coefficients QD [S^2 + S + 1 ] == ========================================= 01 0.0 1.03573607270E+03 0.00000000000E+00 02 1.0 1.52838376237E-16 7.84287312832E+04 03 1.0 -1.51816114564E-17 7.94884951494E+06 Denominator Coefficients QD [S^2 + S + 1 ] == ========================================= 01 1.0 1.03573607270E+03 7.89568352087E+05 02 1.0 2.48367370656E+02 3.06585558034E+05 03 1.0 6.39635528883E+02 2.03342318737E+06 Figure 3.6 Filter coefficients for Exam ple 3.6 from WFilter. Figure 3.7 Filter m agnitude response for Exam ple 3.6. 72 Practical A nalog and D igital F ilter D esign 3.4 UNNORMALIZ ED BANDSTOP APPROX IMATION FUNCTIONS We will find that the unnorm alization of the lowpass norm alized function into a bandstop approxim ation is very similar to the bandpass case. The first step in the procedure is to determ ine the order required from the lowpass approxim ation based on the bandstop specifications. The value of Ωr to use in the bandstop case is shown in (3.38), which is the recipr ocal of the bandpass case. We notice again that Ωr will be greater than 1: stop1 stop2pass1 pass2 stop1 stop2pass1 pass2 f ff f r−− =−− =Ωωωωω (3.38) As in the bandpass case, (3.24) m ust be satisfied in order to get an accurate value of Ωr, except in this case either ωpass1 must be increased or ωpass2 must be decreased to achieve equality. After finding the order, we can unnorm alize the lowpass function into a bandstop function using the substitution given in (3.39): 2 2 oSss BWS ω+⋅= (3.39) As before, all approxim ations except the inverse Chebyshev will define pass2 pass1ωωω ⋅=o (3.40) pass1 pass2ωω−=BW (3.41) while for the inverse Chebyshev case stop2 stop1ωωω ⋅=o (3.42) stop1 stop2ωω−=BW (3.43) The resultant bandstop approxim ation func tion will be twice the order of the norm alized lowpass function just as in th e bandpass case. The bandstop filter is in effect implem enting both a lowpass a nd highpass filter and therefore requires twice the order. Analog Lowpass, Highpass, Bandpass, and Bandstop Filters 73 3.4.1 Handl ing a Fi rst-Order Factor Equation (3.44) shows how a first-orde r factor is unnorm alized into a second- order factor using the substitution of (3.39): 22 2 122 2 1 ) () ( 2 12 1 ]) () ([]) () ([)( 2 2 B ss BW BA ss BW A BSBASASH oo ss BWSo++⋅⋅++⋅⋅=+⋅+⋅= +⋅=ωω ω (3.44) Equation (3.45) shows the result af ter sim plification followed by the observations that can be m ade for this case: 2 12 02 12 0 2 2 122 2 12 22 )/()/()( bsb sbasa sa s BW BB ss BW AA s BAsH oo +⋅+⋅+⋅+⋅= +⋅⋅ ++⋅⋅ +⋅= ωω (3.45) • The gain constant is m ultiplied by A2 / B2. • The s2-term bandstop coefficients becom e a0 = 1, b0 = 1 • The s-term bandstop coefficients becom e a1 = (A1 / A2) BW, b1 = (B1 / B2) BW • Constant term bandstop coefficients becom e aboo 22 22==ωω, 3.4.2 Handl ing a Second-Order Factor In order to unnorm alize a second-order fact or we experience the sam e problem s as in the bandpass case. A direct substitution would give us a fourth-order transfer function, which is not what we want. However, the m ethodology used in the bandpass case does work in this case as we ll. The procedure is outlined below for the bandstop case that has a few differences due to a different substitution factor. Starting at the sam e point as with th e bandpass case, (3.46) shows the result of the factoring of the initial quadratics: ) () (* 1 1* 1 1 2 122 12 2 2 ) )( () )( ()( o ss BWSpSpSzSzS BSB SASA SsH ω+⋅=++++= +⋅++⋅+= (3.46) Equation (3.47) results after th e substitution and sim plification: ] )/ ( [] )/ ( [] )/ ( [] )/ ( [)(2 * 12 2 122 * 12 2 12 * 1 1* 11 o oo o sp BW s sp BW ssz BW s sz BW s ppzzsH ω ωω ω +⋅ +⋅+⋅ ++⋅ +⋅+⋅ +⋅ ⋅⋅= (3.47) 74 Practical A nalog and D igital F ilter D esign The initial gain factor of (3.47) can be shown to be A2 / B2. The quadratic factors can be factored into first-or der factors, as indicated in (3.48): ) () () () () () () () ()( 1 1 1 11 1 1 1 22 d c b ad c b a ps ps ps pszs zs zs zs BAsH+⋅+⋅+⋅++⋅+⋅+⋅+⋅= (3.48) We then reconstruct two quadratics in the num erator and denom inator by matching the com plex conjugate pairs: ) )( () )( ()( 5 42 2 125 42 2 12 22 bsb sbsb sasa sasa s BAsH +⋅++⋅++⋅++⋅+⋅= (3.49) This result is valid for the rational approxim ation functions (inverse Chebyshev and elliptic), but for the a ll-pole approxim ations (Butterworth and Chebyshev), we must develop a slightly different version. E quations (3.50) and (3.51) show the factoring and substitution of (3.39). After the quadratics of (3.51) are factored and the m atching com plex c onjugate term s are com bined, the final form is (3.52) . ) () (* 1 12 2 122 2 2 ) )( ()( ω+⋅=++= +⋅+= ss BWSpSpSA BSB SAsH (3.50) ] )/ ( [] )/ ( [) ()(2 * 12 2 1222 2 * 112 o oo sp BW s sp BW ss ppAsH ω ωω +⋅ +⋅+⋅ ++⋅ ⋅= (3.51) ) )( () ()( 5 42 2 1222 2 22 bsb sbsb ss BAsHo +⋅++⋅++⋅=ω (3.52) Complete num erical exam ples of th e bandstop unnorm alization process are given next. Analog Lowpass, Highpass, Bandpass, and Bandstop Filters 75 Example 3.7 Unnormaliz ed Chebyshev Bandstop Filter Problem: Determ ine the transfer function for a Chebyshev bandstop filter to satisfy the following specifications: ωpass1 = 3,000 rad/sec, ωpass2 = 24,000 rad/sec, ωstop1 = 6,000 rad/sec, ωstop2 = 12,000 rad/sec, apass = −1.0 dB , astop = −35 dB Solution: Using the m aterial of Section 2.3, the im portant values for this exam ple and the norm alized transfer f unction are listed below. The transfer function is shown with quadratics in factored form as shown by the (2) superscript. Ωr = 3.5 n = 2.80 (3rd order) ωo = 8485.3 rad/sec BW = 21,000 rad/sec )2( 3,) 96600.0 24709.0 () 49417.0 (99421.0 49417.0)( j S SS HC± +⋅ +⋅= After m aking the substitution of (3.39) and factoring again, the following equation em erges, which can be sim plified into the final result: )2( )2( 7 237 2 6,)370,23 632,4( )965,2 6.587()10 200.7 500,42 ()10 200.7 ()( j s j s s sss HC±+⋅ ±+⋅⋅+⋅+⋅+= )10 676.5 263,9 )(10 134.9 175,1 )(10 200.7 495,42 ()10 200.7 ( )( 8 2 6 2 7 237 26, ⋅+⋅+⋅+⋅+⋅+⋅+⋅+= s s s s s sss HC Example 3 .8 Unno rmalized Elliptic Ba ndsto p Filter Problem: Determ ine the transfer function for an elliptic bandstop filter to satisfy the following specifications: apass = −0.3 dB , astop = −50 dB , fpass1 = 50 Hz, fpass2 = 72 Hz, fstop1 = 58 Hz, fstop2 = 62 Hz Solution: Using the m aterial of Section 2.5, the im portant values for this exam ple and the norm alized transfer func tion are listed below. In this case, fpass2 76 Practical A nalog and D igital F ilter D esign must be changed to 71.92 Hz to provide symmetry. The transfer function is shown with quadratics in factored form as shown by the (2) superscript. Ωr = 3.3 n = 2.75 (3rd order) ωo = 376.78 rad/sec BW = 137.73 rad/sec ) 93390.0 35753.0 () 73880.0 () 31445.6 ( 73880.0)(3,j S SjSS HE± +⋅ +±⋅= After m aking the substitution of (3.39) and factoring again, the following equation em erges: )2( )2( 2)2( )2( 2 6,)4.438 13.22( )0.323 30.16()960,141 4.186 ()0.366 ( )9.387 ()960,141 ()( j s j s s sjs js ss HI±+⋅ ±+⋅ +⋅+±⋅ ±⋅ += After sim plification, the follo wing transfer function results: )704,192 25.44 ()585,104 60.32 ()964,141 4.186 ()981,133 ()424,150 ()964,141 ()(2 2 22 2 2 6,+⋅+⋅ +⋅+⋅ +⋅++⋅ +⋅ += s s s s s ss s ss HE We can also use W Filter to design the ba ndstop elliptic filter of Exam ple 3.8. The results of this filter design are show n in Figures 3.8 and 3.9 that show the coefficients and m agnitude response, resp ectively . Again, as in the bandpass case, a couple of the num erator coefficients are very small and can be considered zero. 3.5 ANALOG FREQUENCY RESPONSE Up to this point we have developed the necessary foundation to design a variety of analog filters. W e have calculated the coe fficients and are ready to implem ent the filter in hardware. But before we addre ss the im plem entation issues in the next chapter, we need to check our design by determ ining the frequency response of the filter and com paring it to our design specifications. W e will discuss the calculation of the frequency response of our filters and also view the C code for the frequency response calculation. 3.5.1 Mathemati cs for Frequency Response Cal culation The filter approxim ation function, which we have j ust determ ined by the calculation of the unnorm alized coefficients , represents a transfer function of a linear system in the s-domain. In order to determ ine the frequency response of the transfer function, we m ust substitute jω for each of the s-variables in that transfer Analog Lowpass, Highpass, Bandpass, and Bandstop Filters 77 function. For exam ple, (3.53) shows a transfer function with one quadratic factor, while (3.54) shows the frequency response for that transfer function: Elliptic Bandstop Filter Selectivity: Bandstop Approximation: Elliptic Implementation: Analog Passband gain (dB): -0.3 Stopband gain (dB): -50.0 PB freq-lower (Hz): 50.0 PB freq-upper (Hz): 71.92 SB freq-lower (Hz): 58.0 SB freq-upper (Hz): 62.0 Filter Length/Order: 06 Overall Filter Gain: 1.00000000000E+00 Numerator Coefficients QD [S^2 + S + 1 ] == ========================================= 01 1.0 0.00000000000E+00 1.41964389705E+05 02 1.0 2.10251277992E-17 1.33980657885E+05 03 1.0 -1.98427257744E-17 1.50423861642E+05 Denominator Coefficients QD [S^2 + S + 1 ] == ========================================= 01 1.0 1.86421021332E+02 1.41964389705E+05 02 1.0 3.26004384421E+01 1.04584515861E+05 03 1.0 4.42522615272E+01 1.92704319359E+05 Figure 3.8 Filter coefficients for Exam ple 3.8 from WFilter. Figure 3.9 Filter m agnitude response for Exam ple 3.8. 78 Practical A nalog and D igital F ilter D esign 2 122 12 )( bsb sbasa sasH oo +⋅+⋅+⋅+⋅= (3.53) 2 122 12 )( )()( )()( )( b j b j ba j a j ajH sH oo js+⋅+⋅+⋅+⋅===ω ωω ωωω (3.54) After sim plification, the frequency response H(jω) is shown as a frequency dependent com plex num ber in (3.55). This com plex num ber can be represented in either rectangular form or polar form . However, when we deal with a frequency response, the polar form is the more natural form because the standard frequency response is com posed of both a m agnitude and phase respons e portion. Equation (3.56) shows the result of converting (3.55) into polar form : ) () () () ()( 12 212 2 ω ωω ωω ⋅+⋅−⋅+⋅−= bj bbaj a ajH oo (3.55) )( tan)( tan)(11 b ba a P MP MjH−− ∠∠=ω (3.56) where 2 122 2 )() ( ω ω a a a Mo a +−= 2 122 2 )() ( ωω b bb Mo b +−= ) /()(2 2 1 ω ωo a aa a P − = ) /()(2 2 1 ω ωo b bb b P − = Of course, if the original transfer function has m ultiple quadratic term s, as our approxim ation functions do, the total freque ncy response is dependent on all of the quadratics. The total m agnitude result will be the product of the individual magnitudes and the total phase result will be the sum of the individual phases as shown in (3.57), where q represents the num ber of quadratic factors: Analog Lowpass, Highpass, Bandpass, and Bandstop Filters 79 ∑∏∑∏ =− ==− = ∠∠ =q bbq bbq aaq aa t P MP M jH 11 111 1 )( tan)( tan )(ω (3.57) The total frequency response Ht(jω) can then be described as shown in (3.58), where the total m agnitude is the num erator magnitude divided by the denom inator magnitude, and the total phase angle is the denom inator phase subtracted from the numerator phase: t t t M jH Φ∠=)(ω (3.58) where ∏∏ = ==q bbq aa t M M M 1 1 ∑∑ =− =−− =Φq bbq aa t P P 11 11)( tan )( tan Exampl e 3.9 Frequency Response of a Hi ghpass Fi lter Problem: Determ ine the frequency response (both m agnitude and phase) at the passband edge frequency of 2,000 Hz and the stopband edge frequency of 800 Hz for the Chebyshev highpass filter designe d in Exam ple 3.4. Determ ine if the gain specifications of apass = −1.5 dB and astop = −40 dB are m et. The transfer function is shown below: )10 4890.6 703,29 ()10 6614.1 1.150,3 (84140.0)(8 2 8 22 2 4,⋅+⋅+⋅⋅+⋅+⋅⋅= s s s ssss HC Solution: We first m ake the substitution of s = jω into the transfer function to obtain the frequency response H(jω). Then after collecting the real and im aginary terms and arranging them , the followi ng equation for the frequency response results: ] 703,29) 10 4890.6[(]1.150,3) 10 6614.1[(8414.0)(2 8 2 84 4,ω ω ω ωωω ⋅ +−⋅⋅⋅ +−⋅⋅= j jj HC 80 Practical A nalog and D igital F ilter D esign This frequency response equation can firs t be used to determ ine the frequency response at the stopba nd frequency of 800 Hz. )10 4930.1 10 2363.6()10 5834.1 10 4087.1(10 3713.5) 600,1(8 8 7 814 4,⋅ +⋅⋅⋅ +⋅⋅= j jj HC π )5.13 10 4126.6()4.6 10 4176.1(10 3713.5) 600,1(8 814 4,°∠⋅⋅°∠⋅⋅=π j HC °−∠⋅=−9.19 10 9087.5) 600,1(3 4,π j HC This indicates a gain of −44.57 dB at the stopband frequency, which exceeds the specification, and a phase shift of −19.9° or 340.1°. In the case of the passband frequency of 2,000 Hz, sim ilar calculati ons can be m ade as shown below: )10 7326.3 10 9099.4()10 9585.3 10 2263.8(10 0982.2) 000,4(8 8 7 616 4,⋅ +⋅⋅⋅ +⋅⋅= j jj HC π )2.37 10 1676.6()3.78 10 0431.4(10 0982.2) 000,4(8 716 4,°∠⋅⋅°∠⋅⋅=π j HC °−∠= 5.115 8414.0) 000,4(4,π j HC This indicates a gain of −1.50 dB at the stopband frequency , which m eets the specification, and a phase shift of −115.5° or 244.50°. 3.5.2 C Code for Frequency Response Cal culation We are now ready to develop the C code for determ ining the frequency response of an analog filter. In order to properly determ ine the frequency response, we need to know the starting and stopping frequencie s for our calculations. We also need to know whether to space the frequencies in a linear or logarithm ic fashion, and whether to calculate the m agnitude in d ecibels or not. This, as well as other, inform ation is stored in a fre quency response structure called Resp_Params. All of the functions that actually perfo rm the frequency response calculations are contained in the F_R ESPON.C module that has a header file of F_RESPON.H in which Resp_Params is defined. Analog Lowpass, Highpass, Bandpass, and Bandstop Filters 81 The primary function for the calculati on of the analog frequency response is Calc_Analog_Resp, which is shown in Listing 3.1. (The set of frequencies used to evaluate the filter have already been calculated and stored in RP->freq .) /*==================================================== Calc_Analog_Resp() - calcs response for analog filts Prototype: int Calc_Analog_Resp(Filt_Params *FP, Resp_Params *RP); Return: error value Arguments: FP - ptr to struct holding filter params RP - ptr to struct holding respon params ====================================================*/ int Calc_Analog_Resp(Filt_Params *FP,Resp_Params *RP) { int c,f,q; /* loop counters */ double rad2deg, /* rad to deg conversion */ omega,omega2, /* radian freq and square */ rea,img; /* real and imag part */ rad2deg = 180.0 / PI; /* set rad2deg */ /* Loop through each of the frequencies */ for(f = 0 ;f < RP->tot_pts; f++) { /* Initialize magna and angle */ RP->magna[f] = FP->gain; RP->angle[f] = 0.0; /* Pre calc omega and omega squared */ omega = PI2 * RP->freq[f]; omega2 = omega * omega; /* Loop through coefs for each quadratic */ for(q = 0 ;q < (FP->order+1)/2; q++) { /* c is coef index = 3 * quad index */ c = q * 3; /* Numerator values */ rea = FP->acoefs[c+2] - FP->acoefs[c] * omega2; img = FP->acoefs[c+1] * omega; RP->magna[f] *= sqrt(rea*rea + img*img); RP->angle[f] += atan2(img,rea); /* Denominator values */ rea = FP->bcoefs[c+2] - FP->bcoefs[c] * omega2; img = FP->bcoefs[c+1] * omega; RP->magna[f] /= sqrt(rea*rea + img*img); RP->angle[f] -= atan2(img,rea); } /* Convert to degrees */ RP->angle[f] *= rad2deg; } /* Convert magnitude response to dB if indicated */ if(RP->mag_axis == LOG) { for(f = 0 ;f < RP->tot_pts; f++) { /* Handle very small numbers */ if(RP->magna[f] < ZERO) { RP->magna[f] = ZERO;} RP->magna[f] = 20 * log10(RP->magna[f]); } } return ERR_NONE; } Listing 3.1 Calc_Analog_Resp function . 82 Practical A nalog and D igital F ilter D esign After calculating the constant rad2deg for converting radians to degrees, the primary work of the function is performed within two nested for loops. The outer loop controls the frequency at which the response is being calculated, while the inner loop steps through the numbe r of quadratics in the approximation function. As we start the calculation fo r a new frequency, the magnitude value (RP->magna[f] ) is initialized to the overall gain value of the filter, while the phase value ( RP->angle[f] ) is set to 0. We then convert to radian frequencies and make the calculation of the radian frequency squared outsi de the quadratic loop. That saves time by not repeatedly making those calculations inside the loop where there is no change in their value. Once we reach the inner quadratic loop, which is controlled by the variable q, we define a value c that is based on q to help access the individual coefficients of each quadratic. We first handle the num erator portion of the quadratic by determining the real and imaginary parts of the complex number. Then the total magnitude is multiplied by the magnitude of the complex number, and the total angle is incremented by the angle of the complex number. A similar process is performed for the denominator portion of the quadratic except that the total magnitude is divide d by the denominator’s magnitude, and the denominator’s phase is subtracted from the total phase. This inner loop process is repeated for all of the quadratic terms, and then the phase value is converted to degrees outside the quadratic loop. If the magnitude of the response was speci fied to be in decibels, each of the magnitude values is converted to decibels before leaving the function. Since the logarithm of zero is undefined, an artificial value ZERO is defined in F_RESPON.H so that no math error will be produced by the compiler if values become too small. Since we are using type double to describe the magnitude values, a value of 1E-30 was chosen for ZERO that is still within the limits of expression for doubles. This value will produce a gain value of −600 dB, which is well beyond the normal levels of gain we e xpect in filter design, so our definition of ZERO should have no effect on the normal operation of the program. 3.6 SAVING THE FILTER PARAMETERS Once a filter has been designed, WFilter can save it. The saved file can then be used by other software programs to id entify the values of the filter gain, coefficients, and other characteristics of the filter, or the filter can be reloaded into WFilter for continued work. The structure of this WFilter binary data file is therefore included below. A binary file has a number of advantages over a text file in this situation. First, the binary file will be easier to read if the data is needed by another program. There is a very good chance that the filter designer will want to transfer the filter coefficients that have been determined by WFilter to another program for testing Analog Lowpass, Highpass, Bandpass, and Bandstop Filters 83 or implementation. Second, the coefficien ts and data can be stored with more accuracy than they can be displayed. In order to better understand the binary file structure, the format of the file is shown below. The first 4 bytes in the file will be an acronym for Analog and Digital Filter Design. The next byte is a w to indicate that the file was created by WFilter. The next 3 bytes are charact ers indicating the implementation, approximation, and selectivity types. The next 40 bytes are dedicated to the text description for the filter. The next 8 bytes are separated into 6 bytes of reserved space to allow for future indicators, and 2 bytes used to store the order of the filter. The filter order is placed into th e binary buffer in such a manner that it could be read as an integer if desired. (The PC format for disk storage dictates that the low-order byte is written before the high-order byte for an integer. Other machines may use other methods, but will be consistent between read and write operations.) Next, 10 variables of size double are stored, which includes the sampling frequency, the gains and frequencies in the order indicated in the listing, and the gain of the filter. Finally, the acoefs and bcoefs variables are written as type double in the order that they were stored by the program. Header (8 bytes) — Contains the identification “ADFDw” followed by three characters indicating the implementation, approximation, and selectivity types, respectively. The implementation options and values are: 0 - analog, 1 - digital FIR and 2 - digital IIR. The approximation options and values fo r analog and digital IIR filters are: 0 - Butterworth, 1 - Chebyshev, 2 - inverse Chebyshev, and 3 - elliptic. The approximation (or window) options and values for digital FIR filters are: 4 - rectangular, 5 - Barlett, 6 - Bl ackman, 7 - Hamming, 8 - von Hann, 9 - Kaiser, and 10 - Parks-McClellan. (Discussion of the digital approximations will be given later in the text.) The selectivity options and values are: 0 - lowpass, 1 - highpass, 2 - bandpass, and 3 - bandstop. Description (40 bytes) — Contains the text description of the filter and is filled by nulls at the end of the description to make exactly 40 characters. Reserved (6 bytes) — Reserved for future use. Order (2 bytes) — The order can be read as an integer. 84 Practical A nalog and D igital F ilter D esign Specifications (10 doubles) — Contains the sampling frequency in hertz, followed by the gains and frequencies fro m the specifications, and finally the overall filter gain. The gains are specified in decibels and are in the order of apass1, apass2, astop1, and astop2. The frequencies are specified in hertz and are in the order of fpass1, fpass2, fstop1, and fstop2. A coefficients (variable) — The acoefs written as doubles. B coefficients (variable) — The bcoefs written as doubles. 3.7 CONCLUSION We have now completed the design of a number of analog approximation types and are able to calculate the frequency re sponse and save the filter parameters for future use. In the next chapter we’ll see how to implement these functions as active filters. For those interested in the C code used to unnormalize the filter transfer functions, please turn to Appendix E. 85 Chapter 4 Analog Filter Implementation Using Active Filters In this chapter, we will discuss the implementation of the analog approximation functions that we developed and verified in previous chapters. There are several methods that could be used to allow th e successful implementation of an analog filter. Unfortunately, an entire book could be devoted to this topic (and several have), so we will concentrate on active filters. Using active filters to implement the transfer functions is a very popular method today because of the natural correspondence between the analog circuit a nd the mathematical function. We will not discuss the derivation of the transfer functions for active filters because the development of such circuit analysis techniques is beyond the scope of this text. However, a number of suitable references are given in the analog active filter texts of Appendix A for those who are interested in the derivations. Instead, the circuit topology and transfer functi on for several common active filters will be presented before determining the component valu es for each circuit. We will develop implementation procedures for each of the filter selectivities discussed in previous chapters as well as discuss other options for implementation and some of the important implementation issues. 4.1 IMPLEMENTATION PROCEDURES FOR ANALOG FILTERS There are many choices when it comes to implementing our continuous-time analog filters. For example, we could de scribe our single-i nput and single-output system by means of state variables and use a state-space approach to the problem. This method has the advantage of being very general and it puts the problem in a convenient mathematical form that allows manipulation in terms of matrix algebra. However, the development of this theory is beyond the scope of this text, but several references in Appendix A provide insight to this method. When considering the method of implementation, two key factors of frequency range and the power handling capability of the filter also come into 86 Practical Analog and Digital Filter Design quest ion. General ly speaki ng, high power and hi gh frequency dictates that passi ve filters b e used. Activ e filters (with op-amps) have a m aximum freq uency ran ge and power range where t hey can be used successful ly. (Sect ion 4.7 discusses the frequency issue in more detail.) Passiv e filters are also a bit more of a ch allen ge to design because they do not exhibit the near ideal qualities of input and output impedances t hat op-am ps have. Another choice for filter implem entati on is the transconductance-C (Gm -C) filter that extends the effective frequency range beyond that of the typical active filter. Finally, switch ed-capacito r (SC) f ilters, lik e the Gm -C filters, u se MOSFET technology and switchi ng signals to im plem ent analog filters. In that way the SC filter uses technology that bridges the gap between continuous-tim e and discrete- time system s. However, it is n ot possible to treat th e complete field of analog filter design in one chapter. Instead , we will co ncentrate o n a m ore trad itional approach to implementing our transfer fu nctions using a sin gle form of activ e filter. Th e Sallen -Key filter, wh ich will b e discussed in more detail in the following sectio ns, has t he advant age of i mplementing a second-order fact or with a single op-am p stage. There are m any other t opologies (ci rcuit confi gurat ions) t hat coul d be chosen, but the Sal len-Key is a tried and t rue confi gurat ion. It is important to see one method of implementing our cont inuous-t ime transfer funct ion before beginning the discussi on of di scret e-time systems. Each of the activ e filters d iscussed will be composed of several stages of electronic circuitry consi sting of a si ngle operat ional amplifier (op-am p) and a number of el ectronic com ponent s cal led resi stors (Rs) and capacitors ( Cs). The fact that active filters can implem ent com plex poles without the use of inductors (Ls) is a key point in their favor. Induct ors have t he disadvant ages of bei ng large, heavy , cost ly, and generat ors of spuri ous magnetic fields. Therefore, bei ng abl e to implem ent an active filter with com ponent s that can be m iniaturized is a big advant age. Each of these stag es of electro nic filte ring will h ave a tran sfer fu nction that charact erizes t he rel ationshi p of t he out put voltage to the input voltage, as indicated in (4.1). More sp ecifically, each quadratic factor of the transfer function will have the form as shown in (4.2), where each A and B in the tran sfer fu nction will b e a fu nction of the R and C used in the circu it. (Th e subscript c is used to indicate that these transfer funct ions are descri bing the circuit response.) )()( )( sVsVsHi o c= (4.1) 2 122 12 )( BsB sBAsA sAsH oo c+⋅+⋅+⋅+⋅= (4.2) Analog Filter Implementation Using Active Filters 87 We also have t he approxi mation funct ion that we deri ved t o meet a speci fic set of frequency and attenuation charact eristics. The general form of each quadrat ic fact or in the approxi mation funct ion is shown i n (4.3), where the subscript a is used t o desi gnate this quadrat ic factor as an approxi mation funct ion. The as and bs used as coefficients have al ready been determ ined and are numerical const ants. 2 122 12 )( bsb sbasa sasH oo a+⋅+⋅+⋅+⋅= (4.3) The i mplementation process t hen becom es a m atter of equat ing the two transfer funct ion fact ors as shown bel ow. Each A and B of the circuit transfer funct ion are equat ed to the respect ive a and b of the approxi mation funct ion and resul ts in several equat ions whi ch must be sol ved for appropri ate R and C values. )( )( sHsHa c= (4.4) We will see this com mon procedure used throughout the next four sections as we determ ine the com ponent values needed to im plem ent each of the active filters. 4.2 LOWPASS ACTIVE FILTERS USING OP-AMPS There are a num ber of active filter topologies (circuit configurations) that could be used to im plem ent a lowpass filter. W e will lim it ourselves to the popular Sallen- Key filter (sh own in Figure 4.1) with a tran sfer fu nction as d escrib ed in (4.5). As indicated by the tran sfer fu nction, this activ e filter stag e can implement one second-order factor of a lowpass filter f unction. This form is very convenient since i t naturally implements the quadrat ic factor that we have been using for the descri ption of t he approxi mation funct ion. Of course, several of t hese ci rcuit stages in cascade can be used to im plem ent higher-order funct ions, and wi th the addition of a single first-orde r stage, odd-order filters can be im plem ented as well. Figure 4.1 Sallen -Key lo wpass activ e filter stag e. 88 Practical Analog and Digital Filter Design []2121 22 12 1122121 ,/1 /) 1( /1 /1/)( CCRR s CRK CR CR sCCRRKs HLc+⋅ −+ + += (4.5) where )/(1A BR R K+= (4.6) In com parison to the transfer funct ion of (4.5), (4.7) shows the general form of an al l-pole lowpass approxi mation funct ion such as the Butterwort h and Chebyshev functions. (Inverse Ch ebyshev and ellip tic filter approximations will use a d ifferen t activ e filter to implement them since th ey req uire zeros in the complex plane.) The num erator value a2 in (4.7) will always b e equal to b2, and G will h ave a value of unity ex cept for the even-order Ch ebyshev case. 2 122 ,)( bsb saGs HLa+⋅+⋅= (4.7) If we equat e (4.5) and (4.7) as i ndicated in the previ ous sect ion, we woul d generat e one equat ion for b1 and one equat ion for b2 (or a2). However, we have five unknowns ( R1, R2, C1, C2, and K) in our circuit. Since there are m ore unknowns t han equat ions, we cannot uni quely determine the values of the components required for the active filter. This allows us to select values for three of the com ponent s. For exam ple, we coul d sel ect the val ues of R1, R2, and C2 if we want ed or t he val ues of C1, C2, and K. Another m ethod that we will use is to let R1 = R2 and C1 = C2, which effect ively eliminates two of t he unknowns. In addition, we will p ick a co mmon value for the cap acito rs sin ce th ey have far fewer available values than resistors. Thi s method of pi cking the R and C values has t he advant age of reduci ng the num ber of di fferent com ponent values needed t o implem ent the active filter. The disadvantag e of this m ethod is that the value of K, which represents the gain for the activ e filter, will n ot be unity. Ho wever, we will find that this problem can be easily solved. If we select com mon values for the prim ary resistors and capacitors, the transfer fu nction for the activ e filter th en becomes []22 222 ,/1 /) 3(/1)( CR s RCK sCRKs HLc+⋅ −+⋅= (4.8) By consi dering the denom inators of (4.7) and (4.8), we can det ermine the two relationshi ps as shown bel ow: 22 21 CR b= (4.9) Analog Filter Implementation Using Active Filters 89 RCK b ) 3(1−= (4.10) Since we have already picked the value of C, we can solve for the resistor values needed to implement the filter. Th e resu lts are 2 2/1 Cb R= (4.11) ()2 1/ 3 b b K−= (4.12) and t hen usi ng (4.6) ()2 1/ 2 / b b R RA B −= (4.13) Usually, RA will be picked as som e convenient value and RB will th en be calculated. The only adjust ment remaining is to equat e the num erator terms of t he two transfer fu nctions. Notice th at in this case, there exists a gain of K at ω = 0, while the approxi mation funct ion has a gai n of G. The value of G will always b e less than or equal to one, while th e value K will always be greater th an or equal to one. Thus, it is always n ecessary to reduce th e gain of the activ e filter to match the gain of the approxi mation funct ion. The am ount of this gain adjust ment factor is tot tot/G K GA= (4.14) where Ktot and Gtot represent the product s of al l the Ks and Gs in the total circu it and approxi mation funct ions, respect ively. This gain adjust ment factor can be implemented by a simple voltage divider at th e output of the activ e filter stag e. There are two conditions placed on this volta ge divider. The inverse of the voltage divider rat io must match the gai n adjust ment factor, and the equivalent resistance of the voltage divider as seen by the output load must eq ual the req uired filter output resistance. Therefore, assum ing an out put resistance Rout, and a vol tage divider net work m ade up of Rx and Ry, ) /(out y x y x R R RR R +⋅= (4.15) y y x R R R GA /) (+= (4.16) 90 Practical Analog and Digital Filter Design which m eans that outR GA Rx⋅= (4.17) )1 /(out− ⋅= GA R GA Ry (4.18) The ci rcuit of Fi gure 4.2 shows one st age of t he new confi gurat ion wi th the voltage divider output. If the input signal level is very high, we m ight choose t o use the voltage divider on the first stag e of the filter in order to reduce distortion in the filter. Figure 4.2 Activ e filter with voltage divider output. Before we consi der how t o implement an odd-order approxi mation funct ion, we need to consi der whet her t he gai n adjust ment techni que i s appropri ate for al l applicatio ns. In many cases, am plificatio n is a req uired part of the filterin g system , and therefore the differences in gain can be facto red into the overall g ain requi rement. For exam ple, if the overal l system gain requi red i s 60 dB , and the filter is producing a gain of 20 dB in the passband, a m ore efficient solution would be to design the remaining amplifiers to provi de 40 dB of gai n. Thi s desi gn woul d be m ore power effi cient, use fewer co mponent s, and have bet ter dynamic range. However, the preceding technique can be used if an exact gain is required from the filter. If an odd-order approxi mation fact or is to be implemented, an odd-order st age as sh own in Figure 4.3 can be used as th e first stag e of the activ e filter. This simple RC filter is fo llowed by a buffer am p so that the output impedance of the RC com bination will not affect the i nput to the next active filter stage. However, if an op-am p is going to be requi red to implement this first-order fact or, we m ight consi der addi ng a few m ore com ponent s and i mplementing a second- order st age i nstead. In m any cases, addi tional attenuation in the stopband woul d be wel come, and t he addi tional cost is slight. Analog Filter Implementation Using Active Filters 91 Figure 4.3 First-o rder lowpass filter with buffer am p. The t ransfer funct ion for t he first-order st age i s given i n (4.19). Thi s transfer funct ion m ust match a fi rst-order approxi mation funct ion as gi ven i n (4.20): RC sRCsHc/1/1)(+= (4.19) 22)(bsaGsHa+⋅= (4.20) Again, the values of a2 and b2 will b e identical an d G will have a value of 1. Then usi ng the val ue of C that has already been picked, Cb R2/1= (4.21) Example 4.1 illustrates how to use the information presented in this sectio n to design an activ e lowpass filter. Exampl e 4.1 B utterw orth L owpass Acti ve Fi lter Desi gn Problem: Determ ine the resistor and cap acito r values to implement a Butterwo rth lowpass activ e filter to meet th e following specificatio ns: apass = −1 dB , astop = −50 dB , fpass = 1000 Hz, and fstop = 4000 Hz Solution: First, we fin d that a fifth -order filter is required. The resulting unnorm alized approxi mation funct ion can t hen be det ermined to be )10 728.51 637,11 ()10 728.51 0.445,4 ()2.192,7()10 728.51(2.192,7)(6 2 6 226 ⋅+⋅+⋅⋅+⋅+⋅ +⋅⋅= s s s s ssHa The three facto rs in the denominator can now be matched to three activ e filter stages. By picking C = 0.01 µF and RA = 10 kΩ, the rem aining values for each stage can be cal culated from (4.11)–(4.13) and (4.21). The first-order stage does not requi re an RB value. 92 Practical Analog and Digital Filter Design m Rm Km RBm 0 13.90 kΩ — — 1 13.90 kΩ 2.3820 13.82 kΩ 2 13.90 kΩ 1.3820 3.820 kΩ In order t o achi eve a gai n of exact ly 1 at ω = 0, we can use a vol tage di vider at the out put. First, we det ermine Ktot 2919.3tot ==∏ mmK K This value along wi th the fact that Gtot has a val ue of 1 al lows us to determine that GA = 3.2919. The fol lowing resi stor di vider val ues can then be determined assum ing a requi red out put impedance of 10 k Ω. (The gai n adjust ment coul d be factored i nto the overal l gain of the system instead of usi ng the vol tage di vider.) Ω=Ω= k 36.14 ,k 92.32y x R R The resulting activ e filter is sh own in Figure 4.4. We will g enerate th e C co de for the det ermination of t hese com ponent values in a later sect ion of t his chapt er. Figure 4.4 Butterwo rth lowpass activ e filter fo r Example 4.1. 4.3 HIGHPASS ACTIVE FILTERS USING OP-AMPS We will also use a Sallen-Key circuit configuration for im plem enting a highpass filter. The circuit for im plem enting a second-order factor is shown in Figure 4.5, with the tran sfer fu nction for the stage shown in (4. 22). W e can see that this highpass confi gurat ion is the sam e as the lowpass case except that the primary Rs and Cs have changed posi tions, al though RA and RB remain in their o riginal positions. Analog Filter Implementation Using Active Filters 93 Figure 4.5 Sallen-Key highpass active filter stage. []2121 11 12 2222 ,/1 /) 1( /1 /1)( CCRR sCRK CR CR ssKs HHc+⋅ −+++⋅= (4.22) where again )/(1A BR R K+= (4.23) We can use the same procedure i n selecting the com ponent values as we used in the lowpass case b y lettin g R1 = R2 and C1 = C2. The resul t is shown i n (4.24), where we see that the denom inator is id entical to the lowpass case in (4.8): []22 22 ,/1 /) 3()( CR s RCK ssKs HHc+⋅ −+⋅= (4.24) This equat ion can t hen be m atched t o the quadrat ic fact ors from the approxi mation funct ions t hat have t he form shown i n (4.25) 2 122 ,)( bsb ssGs HHa+⋅+⋅= (4.25) When the equat ion for t he approxi mation funct ion i s compared to the equation for the activ e filter stag e, we see th at the relatio nships between term s are identical to those of the lowpass case. Therefore, if we pick the sam e value of capacito r, the resisto r values will be identical to those of the lowpass case, as shown bel ow: 2 2/1 Cb R= (4.26) 94 Practical Analog and Digital Filter Design ()2 1/ 2 / b b R RA B −= (4.27) The adjust ment of gai n for t he highpass case i s handl ed in a similar manner to the lowpass case. As (4.24) indicates, the K value of each stage can be determ ined by allowing the frequency to approach i nfinity, as opposed t o zero i n the lowpass case. Ktot can then be easi ly determined, and wi th the approxi mation funct ion gain, the gai n adjust ment fact or GA can be det ermined as shown previ ously in (4.14). A resi stive vol tage di vider i s used at the out put of t he last stage of t he active filter. If necessary, a buffer am plifier can be used after this voltage divider if the impedance of the network being driven by the filter is to o small. If an odd-order hi ghpass approxi mation fact or is to be implemented, an act ive filter stag e as sh own in Figure 4.6 can be used as th e first stag e of the activ e filter. The only difference between this stage and the lowpass first-o rder stag e is th e interchange of R and C values. Figure 4.6 First-order highpass filter with buffer am p. The t ransfer funct ion for t his stage i s given i n (4.28), while the approxi mation funct ion for a fi rst-order hi ghpass fact or is shown i n (4.29): RC sssHc/1)(+= (4.28) 2)(bssGsHa+⋅= (4.29) As in the second-order case, the resistor value will be the sam e as the lowpass value assum ing that the sam e value of capacitor is picked. Cb R2/1= (4.30) Exampl e 4.2 Chebyshev Hi ghpass Acti ve Fi lter Desi gn Problem: Determ ine the resistor and cap acito r values to implement a Chebyshev highpass active filter to meet the following specifications: Analog Filter Implementation Using Active Filters 95 apass = −0.5 dB , astop = −30 dB , fpass = 1000 Hz, and fstop = 400 Hz Solution: A fourt h-order transfer funct ion as shown bel ow is requi red. Si nce this is an even-order C hebyshev, t here is an adjust ment factor of 0.94406 included in the num erator. ) 1077.110 926,14 () 10 121.37 9.071,2 (94406.)(6 2 6 24 ⋅ +⋅ +⋅⋅ +⋅ +⋅= s s s sss Ha The two quadratic terms can be matched to two activ e filter stag es by again picking C = 0.01 µF and RA = 10 kΩ. The other circuit values can be calculated as shown bel ow: m Rm Km RBm 0 16.41 kΩ 2.6599 16.6 kΩ 1 9.502 kΩ 1.5818 5.82 kΩ In order to achi eve a gai n of exact ly 1 at ω = ∞, we can use a vol tage di vider at the output. First, we d etermine the gain adjustment facto r for the filter that in this case i ncludes not only the Km factors for each quadratic, but also the approxi mation funct ion’s gai n of 0.94406: 4567.4 94406.0/) ( = =∏ mmK GA Figure 4.7 Chebyshev highpass active filter for Exam ple 4.2. Assum ing an equi valent resistance of 10 k Ω, the resi stor divider val ues can be determined with the resu lting filter sh own in Figure 4.7. (Th e gain adjustment could be factored i nto the overal l gain of the system instead of usi ng the vol tage divider.) RRxy= = 4457 1289 .. k, k Ω Ω 96 Practical Analog and Digital Filter Design 4.4 BANDPASS ACTIVE FILTERS USING OP-AMPS Figure 4.8 shows a Sallen-Key active filter stage that im plem ents a second-order bandpass t ransfer funct ion. The t ransfer funct ion for t his bandpass stage is given in (4.31). Figure 4.8 Sallen-Key bandpass active filter stage. 213212 1 12 23 13 11211 ,) 1( 1 1 1/)( CCRRRRRsCRK CR CR CRsCRsKs HPc++⋅⎥ ⎦⎤ ⎢ ⎣⎡ −++++⋅= (4.31) where again )/(1A BR R K+= (4.32) We can simplify th is fu nction by lettin g R1 = R2 = R3 and C1 = C2. This simplified funct ion is given i n (4.33): []22 2,/2 /) 4(/)( CR s RCK sRCsKs HLc+⋅ −+⋅= (4.33) This bandpass t ransfer funct ion can now be m atched t o the general form of the approxi mation fact or, as shown i n (4.34): 2 121 ,)( bsb ssas HHa+⋅+⋅= (4.34) After matching equi valent denom inator terms, the following equat ions em erge, Analog Filter Implementation Using Active Filters 97 RCK b ) 4(1−= (4.35) 22 22 CR b= (4.36) which lead s to 2 22Cb R= (4.37) 22 12 4 bb K−= (4.38) 22 12 3 bb RRA B−= (4.39) After these calcu lations are made, the overall g ain of the activ e filter m ust be determined. Thi s is a more di fficult task than for t he lowpass and highpass cases since t he gai n adjust ment must be determined at the center frequency of the passband ωo. If we refer ag ain to (4.33) and (4.34), we see th at th ey will h ave identical denom inator coeffi cients since we have just deri ved t he equat ions t o guarant ee that. However, t he num erators di ffer by the constants that are present. The gain adjustm ent factor for each stage is then the ratio of the two numerator const ants, as shown i n (4.40). The t otal gain adjust ment is then the product of these stage gain adjustm ents: ∏= mmmm m CRa K GA ) /(1 (4.40) Once th e total gain adjustment has been determined, a vol tage di vider st age at the output of the activ e filter can be used for compensatio n. Example 4.3 Butterworth Bandpass Active Filter Design Problem: Determ ine the resistor and cap acito r values to implement a Butterworth bandpass active filter to meet the following specifications: apass = −1.5 dB , astop = −28 dB , fpass1 = 1,000 Hz, fpass2 = 2,000 Hz, fstop1 = 500 Hz, and fstop2 = 4,000 Hz 98 Practical Analog and Digital Filter Design Solution: A th ird-order equivalent lowpass filter is n eeded, which indicates that a sixth-order bandpass functi on will result as shown below: )103.160 880,4 ()1088.38 402,2 ()1096.78 282,7 () 7282( )( 6 2 6 2 6 23 ⋅+⋅+⋅⋅+⋅+⋅⋅+⋅+⋅= s s s s s sssHa By picking C = 0.01 µF and RA = 10 kΩ, the rem aining values can be determined by matching the three q uadratic term s: m Rm Km RBm GAm 0 15.92 kΩ 2.8410 18.41 kΩ 2.4512 1 22.68 kΩ 3.4550 24.55 kΩ 2.0919 2 11.17 kΩ 3.4550 24.55 kΩ 4.2481 The co mbined gain produced by the activ e filter stag es at ω = ωo is determined to be 21.783, whi ch can be com pensat ed by a voltage divider at the output of the filter. If th e output resistan ce is to be 10 kΩ, the vol tage di vider resistor values are gi ven bel ow. (Not e that in this case, i f a vol tage di vider were used, a gain of over 21 (over 40 dB ) woul d be sacri ficed. It woul d be bet ter to include this in the system gain.) Ω=Ω= k 10.5 ,k 218y x R R The resulting bandpass filter is shown in Figure 4.9. Figure 4.9 Butterworth bandpass active filter for Exam ple 4.3. 4.5 BANDSTOP ACTIVE FILTERS USING OP-AMPS Figure 4.10 shows a twin -tee b andstop activ e filter stag e that can implement a variety of second-order func tions. The adm ittance labeled Y can represent a conduct ance G, or a susceptance sC, or can have zero val ue (not be present at all). Analog Filter Implementation Using Active Filters 99 Figure 4.10 Twin -tee b andstop activ e filter stag e. The general fo rm of the tran sfer fu nction for this filter is g iven in (4.41): 222222 ,21 2 241 )( CRRYsRCRY KsCRsK s HSc++⋅⎥⎦⎤ ⎢⎣⎡+−+⎥⎦⎤ ⎢⎣⎡+⋅ = (4.41) where again )/(1A BR R K+= (4.42) Equation (4.43) rewrites this equati on in term s of the pole frequency ωp and the zero frequency ωz: 2 22 2 ,)/() ()( p pz ScsQ ssKs H ω ωω +⋅ ++⋅= (4.43) The transfer function of (4.43) m ust be m atched to the general form of a bandstop approxim ation function, as shown in (4.44): 2 1222 ,) ()( bsb sa sGs HSa+⋅++⋅= (4.44) Depending on the value of Y selected, ωz may be greater than, equal to, or less than ωp. This will affect the m atching of the respective term s in (4.43) and (4.44). The responses for the transfer function will also change, as indicated in Figure 4.11. Let’s look at how the transfer function changes for the three cases. 100 Practical Analog and Digital Filter Design Figure 4.11 Bandstop filter responses. First, we consider the case where no Y elem ent is present ( Y = 0), in which case the transfer function can be sim plified as shown in (4.45). Note that this function has the condition that ωz = ωp (a2 = b2), which will produce a bandstop response as shown in Figure 4.11(a). Notice that the response has the condition that the upper and lower pa ssbands have equal gain. 222222 0,1 241 )( CRsRCKsCRsK s HSc +⋅⎥⎦⎤ ⎢⎣⎡−+⎥⎦⎤ ⎢⎣⎡+⋅ = (4.45) The selection of com ponents to implem ent this ty pe of response is relatively easy as we m atch the term s of (4.44) a nd (4.45). B y first picking a value of C, the results are 2 2 1 Ca R= (4.46) 22 14 2 b b K−= (4.47) 22 14 1 b b RRA B−= (4.48) Analog Filter Implementation Using Active Filters 101 Next, in the case where Y = Go = 1/ Ro, the resulting transfer function is given in (4.49). Note that this function has ωz < ωp (a2 < b2), which will produce a bandstop response as shown in Figure 4.11(b). This is som etimes referred to as a “highpass notch” filter because the gain of the upper passband is larger than that of the lower passband. 222222 1,/)2 ( )/2 24(1 )( CRRR RsRCRR KsCRsK s H o o oSc++⋅⎥⎦⎤ ⎢⎣⎡+−+⎥⎦⎤ ⎢⎣⎡+⋅ = (4.49) The selection of com ponents to im plem ent this ty pe of response is again determ ined by matching term s and by first picking a value of C; the results are 2 2 1 Ca R= (4.50) ()[]1 / 22 2− = abR Ro (4.51) )2() (22 2 1 2 2 a ab a b K −−+= (4.52) )2() (12 2 1 2 2 a ab a b RRA B −−+= (4.53) Finally, in the case where Y = sCo, the resulting transfer function is given in (4.54). Note that this function has ωz > ωp (a2 > b2), which will produce a bandstop response as shown in Figure 4.11(c). This is som etimes referred to as a “lowpass notch” filter. )2 ( )2 (2 )24(1 )2 ()( 222222 2, o ooo Sc C C CRCsC C RCC CKsCRsC CCK s H +⋅+⋅⎥ ⎦⎤ ⎢ ⎣⎡ +⋅+⋅−+⎥⎦⎤ ⎢⎣⎡+⋅+⋅ = (4.54) The selection of com ponents to im plem ent this ty pe of response is again determ ined by matching term s and by first picking a value of C; the results are 102 Practical Analog and Digital Filter Design 2 2 1 Ca R= (4.55) [ ]2 1)/(2 2− ⋅= ba C Co (4.56) )2() (22 2 1 2 2 b ab b a K −−+= (4.57) )2() (12 2 1 2 2 b ab b a RRA B −−+= (4.58) After these calculations are m ade, the overall gain of the active filter can be determ ined by evaluating the transfer function at ω = 0 or ω = ∞. If the gain of the circuit is to be determ ined at ω = 0, then the value of K for that stage is used except for the highpass notch stage. In th at case, an additional m ultiplication factor of Ro / (Ro + 2R) should be included as seen from (4.49). If the gain is to be determ ined at an infinite frequency , then the lowpass notch stage will have a gain that must be increased by a value of C / (C + 2Co), as indicated by (4.54). These values will be the sam e and can be included in the circuit using a voltage divider. Exampl e 4.4 Chebyshev B andstop Acti ve Fi lter Desi gn Problem: Determ ine the resistor and capacitor values to im plem ent a Chebyshev bandstop active filter to meet the following specifications: apass = −1 dB , astop = −40 dB , fpass1 = 666.67 Hz, fpass2 = 1,500 Hz, fstop1 = 909.09 Hz, and fstop2 = 1,100 Hz Solution: A third-order lowpass equivalent function is required, which indicates that a sixth-order unnorm alized bandstop approxim ation function will be necessary , as shown below: )1021.87 792,1 )(1087.17 0.811 )(1048.39 600,10 ()1048.39 ()(6 2 6 2 6 236 2 ⋅+⋅+⋅+⋅+⋅+⋅+⋅+= s s s s s sssHa By picking C = 0.01 µF and RA = 10 kΩ, the rem aining values can be calculated by matching term s. Note th at there are three denom inator quadratics with three different values of constant terms. One of these values is larger than the numerator constant term , one is equal to the num erator constant term , and one is smaller than the num erator constant term . This indicates that one of the stages will Analog Filter Implementation Using Active Filters 103 have an Ro value, one will have no Y elem ent, and one will have a Co value, respectively. m Rm Km RBm Ym 0 15.92 kΩ 1.1569 1.569 kΩ — 1 15.92 kΩ 2.4619 14.62 kΩ Co = 6.045 nF 2 15.92 kΩ 2.4619 14.62 kΩ Ro = 26.33 kΩ The com bined gain produced by the active filter stages at ω = 0 or at infinity is 3.17422, which includes the product of the three K values and either the capacitor or resistor ratio of 0.45269. The vol tage divider resistor values can be calculated accordingly . The resulting bands top filter is shown in Figure 4.12. RRxy= = 3174. k, 14.60 kΩ Ω Figure 4.12 Chebyshev bandstop active filter for Exam ple 4.4. 4.6 IMPLEMENTING COMPLEX ZEROS WITH ACTIVE FILTERS Up to this point in the chapter, we have not discussed the im plem entation of rational functions such as the inverse Chebyshev and ellipt ic approxim ations. In previous chapters, we discovered that th e prim ary difference between all-pole and rational approxim ation functions was that the rational functions required complex zeros on the jω axis in the s-plane. The general form of a rational function quadratic factor is shown below. If the a1 coefficient is zero (as it is for zeros on the jω axis), the quadratic factor is iden tical to the form of a bandstop function derived for the all-pole respons e in the last section. 2 122 12 ,) ()( bsb sasa sGs HSa+⋅++⋅+⋅= (4.59) 104 Practical Analog and Digital Filter Design Therefore, we have already developed an active filter form to implem ent the inverse C hebyshev and elliptic approxim ations. It is the tw in-tee filter presented in the previous section. We can use that form for any of the selectivities (lowpass, highpass, bandpass, or bandstop) when designing inverse Chebyshev or elliptic filters. However, there are a few special conce rns that m ust be considered when implem enting filter approxim ation functions with com plex zeros. If a lowpass or highpass approxim ation function has an odd-order, the fi rst-order factor should still be im plem ented by the appropriate first-order stage disc ussed previously. In addition, for the case of a bandpass approxi mation, if the function was derived from an odd-order lowpass function, then the quadratic factor associated with the first-order factor should be implem ented by a Sallen-Key bandpass active filter section. The other quadratic factors of the bandpass function and the quadratic factors of the lowpass and highpass functions are then im plem ented by the twin- tee notch filter. Of course, all stages of a bandstop filter of any approxim ation use the twin-tee configuration. Two exam ples w ill now be used to dem onstrate the procedure of im plem enting inverse C hebyshev and ellipt ic approxim ations. Exampl e 4.5 Inverse Chebyshev L owpass Acti ve Fi lter Desi gn Problem: Determ ine the resistor and capacitor values to implem ent an inverse C hebyshev lowpass active filter to m eet the following specifications: apass = −1 dB , astop = −60 dB , fpass = 100 Hz, and fstop = 300 Hz Solution: In this case, a fifth-order filter will be used. We can determ ine the required approxim ation function to be )1064.698 7.305,1 ()1045.629 34.449 ()77.865()10 284.10 ()10 9282.3 ()77.865(10 886.10)(3 2 3 26 2 6 2 3 ⋅+⋅+⋅⋅+⋅+⋅+⋅+⋅⋅+⋅ ⋅=− s s s s ss ssHa The two quadratic term s must be m atched to two twin-tee active filter stages while the first-order factor can be im plem ented by a sim ple RC stage. B y again picking C = 0.01 µF and RA = 10 kΩ, the rem aining values can be calculated. Note that in this lowpass case, both twin-t ee sections em ploy a capacitor as the additional adm ittance elem ent. m Rm Km RBm Ym 0 115.5 kΩ — — — 1 50.46 kΩ 3.9129 29.13 kΩ Co = 26.20 nF 2 31.18 kΩ 5.8634 48.63 kΩ Co = 68.60 nF We determ ine the gain ad justm ent factor by finding Ktot, as shown below. Analog Filter Implementation Using Active Filters 105 KKm mtot==∏ 22943. If the desired output resistance is 10 kΩ, the following values result for the voltage divider with the final filter shown in Figure 4.13. RRxy= = 2294 1046 .. k, k Ω Ω Figure 4.13 Inverse C hebyshev active lowpass filter for Exam ple 4.5. Example 4.6 Elliptic Ba ndpass Active Filter Design Problem: Determ ine the resistor and capacitor values to implem ent an elliptic bandpass active filter to m eet the following specifications: apass = −1 dB , astop = −60 dB , fpass1 = 250 Hz, fpass2 = 400 Hz, fstop1 = 100 Hz, and fstop2 = 1,000 Hz Solution: The order of the equivalent lowpass f ilter is 3, which indicates that a sixth-order bandpass approxim ation function will be necessary. The transfer function is shown below: )10 227.6 6.281 )(10 503.2 5.178 )(10 948.3 8.469 ()103.311 ()1007.50 (8.469 1082.20)(6 2 6 2 6 23 2 6 2 3 ⋅++⋅++⋅+⋅+⋅+⋅⋅+⋅⋅⋅=− s s s s s ss ssHa These three quadratic term s must be m atched to three active filter stages. The stage related to the first-order factor in the normalized LP filter is im plem ented by the standard Sallen-Key bandpass filter. Th e other two stages are im plem ented using the twin-tee filters. B y picking C = 0.01 µF and RA = 10 kΩ, the rem aining values can be calculated as shown below. One of the twin-tee stages will have a Ro = 18.86 kΩ and the other will have Co = 95.04 nF. 106 Practical Analog and Digital Filter Design m Rm Km RBm Ym 0 71.18 kΩ 3.6656 26.66 kΩ — 1 14.13 kΩ 11.251 102.5 kΩ Co=95.04 nF 2 179.2 kΩ 11.251 102.5 kΩ Ro=18.86 kΩ The com bined gain produced by the active filter stages at ω = 0 is 4.4406 and that can be com pensated by a voltage di vider after the last stage. The voltage divider resistor values are shown below and are calculated to provide an output impedance of 10 k Ω. The resulting bandstop filter is shown in Figure 4.14. RRxy= = 444. k, 12.9 k Ω Ω Figure 4.14 Elliptic bandpass active filter for Exam ple 4.6. 4.7 ANALOG FILTER IMPLEMENTATION ISSUES In the previous sections, we determ ined co mponent values necessary to implem ent our analog filter designs in the form of active filters. These active filters m ake use of electronic com ponents that can be m anufactured only to a finite accuracy. The components are not perfect when they are first m anufactured and can change value because of aging or exposure to heat, chem icals, or hum idity. Therefore, it is important to select the best ty pe of component for our purpose (active filter implem entation). Although we can buy preci sion com ponents that resist changes, the cost of such com ponents can be expensive. It is m ost cost effective to specify precision com ponents only for t hose positions that actua lly require it. We can determ ine which com ponents are in critical positions by perform ing a sensitivity analysis. 4.7.1 Component Sel ection Each active filter stage is m ade up of a combination of resistors, capacitors, and op-am ps. There are im portant issues in the selection of each of these com ponents. Analog Filter Implementation Using Active Filters 107 We start with a discussion of the activ e device in our design and then discuss capacitors and resistors in turn. The op-amp is the amplifying device in our design and the response of the filter is based on the assumption that the op-amp is ideal. We assume that the input impedance is infinite (actually 1 M–100 M Ω depending on device), the output impedance is zero (actually 100–1,000 Ω ), and that the op-amp can amplify frequencies up to infinity (actually the bandlimit is usually 1 M–10 MHz). This later characteristic is specified by the op-amp’s gain-bandwidth product (GBP). This number provides a reference that can be used to determine the open loop gain of the op-amp at any frequency (or vice ve rsa). For example, the GBP of a 741 op- amp is 106, which indicates that this amplifie r has an open loop gain of 1,000 at a frequency of 1,000 Hz. Alternati vely, we could use this GBP to predict that an upper frequency limit of 20,000 Hz was ava ilable with an open loop gain of 50. The important point to remember, however, is that the transfer functions of the active filters were derived assuming that the gains of the op-amps used were very large for all frequencies of interest in the design. Therefore, whether or not the active filter is a lowpass, highpass, bandpass, or bandstop fi lter, the open loop gain of the op-amp must be large for all frequencies of interest. These frequencies of interest include not only the passbands , but also the stopbands. Luckily, there are many options (other than 741s) when it comes to specifying the active device to be used. Capacitors represent the reactive elemen ts in our active filter because they have a reactance that changes with freque ncy (unlike resistors). There are many types of capacitors manufactured today incl uding electrolytic, ceramic, poly, film, and others. Each capacitor type has a pl ace and is manufactured to serve a specific purpose in the electronics world. For exampl e, electrolytic capacitors are generally used in power applications where large values (up to 10,000 uF) are important and variations in value are not the most important criterion for selection. They are the farthest from ideal of any of the capacitor types and should not be used in active filter design. Ceramic capacitors generally have very small values (in the pF range) and are used most often in appli cations operating in the megahertz range. Generally, active filters will not be ope rating at that frequency because of the limitation of the op-amp. The most commonly used capacitors for active filters are referred to as “poly” capacitors. There are a number of types that fall into this category (polystyrene, poly propylene, polycarbonate, and polyester), where the different names indicate the dielectric used in their construction. There are trade-offs with regard to tolerance, cost, and ch aracteristics, but in general you will find these types effective in active filter design. In the case of resistors, there are a variety of types, including carbon composition, carbon film, metal film , wire-wound, and others. Wire-wound resistors are rarely used except in pow er applications, a nd carbon composition resistors generate excessive amounts of noise. Therefore, in our application, either metal film or carbon film resistors are usually used. You will find carbon film devices used for 5% tolerance values (meaning that the value of the resistor could be ±5% of its nominal value). The metal film device will have a lower temperature 108 Practical Analog and Digital Filter Design coefficient (m eaning that it will di splay less variation with changes in temperature) and is generally manufactured to 1% tolerance. Values are typically available from 10 Ω to 10 MΩ. Because of the nature of the active devices used (op-am ps) it is best to keep the resistor values used in a filter between 1 k Ω and 100 kΩ, if possible, and certainly between 100 Ω and 1 M Ω. Otherwise, the assum ptions about the im pedances of th e op-am p being ideal are no longer valid and the response of the filter m ay not be as expected. Hopefully , this brief discussion will ge t you started in the implem entation of your active filter. For furthe r inform ation, consult the references given in the analog filter design s ection of Appendix A. 4.7.2 Sensi tivity Anal ysis After selecting the best components for the active filter, it is im portant to identify which of these com ponents has the m ost effect on the overall perform ance of the filter. Since no com ponent is perfect, a nd they all will change with age, temperature, and other influences, thes e effects on the filter response can be minimized by selecting the m ost critical components to have the lowest tolerances to change. We can determ ine the m ost critical com ponents in a design by perform ing a sensitivity analysis. A sensiti vity analysis is the process of finding out how any or all of the characteristics of a filter are affected by each and every component that m akes up the filter. For exam ple, the sensitivity of a function F with respect to x is defined in (4.60). Note that sensitivity not only considers the change in F as a function of x, but also the nom inal values of F and x. Therefore, the sensitivity considers the per unit change of the function with respect to the per unit change of the param eter. Using the definition of (4.60), other com mon sensitivity relationships can be determ ined as shown in (4.61)–(4.66). (The value c is considered a constant and G is another function of x.) [] [] )ln()ln( xF xF FxSF x∂∂ ∂∂=⋅= (4.60) (4.61) 1=cx xS (4.62) F xF x S S−=/1 (4.63) G xF xFG x S S S += Analog Filter Implementation Using Active Filters 109 (4.64) G xF xGF x S S S −=/ (4.65) F xF x Sc Sc⋅= F xF xScS c⋅=1 (4.66) In each of the preceding sections, a transfer function for an active filter was given in term s of the resist or and capacitor values used to m ake up the circuit. In general, those functions can be specified in term s of the pole and zero frequencies and quality factors ( Qs) as shown in (4.67): () ()2 22 2 )( p p pz z z s Q ss Q sKsH ω ωω ω +⋅ ++⋅ +⋅= (4.67) If we consider the lowpass active filter of Section 4.2, which has a transfer function as indicated in (4.68), we can eas ily match term s to identify the pole frequency and Q in term s of the com ponent values as shown in (4.69) and (4.70): []2121 22 12 1122121 ,/1 /) 1( /1 /1/)( CCRR s CRK CR CR sCCRRKs HLc+⋅ −+++= (4.68) 2121/1 CCRRp=ω (4.69) 22 12 112121 1 1 1/1 CRK CR CRCCRRQp−++= (4.70) The sensitivity of either one of the param eters listed above to any one of the resistor or capacitor values can now be determ ined. For exam ple, (4.71) 5.0 1−=p RSω 110 Practical Analog and Digital Filter Design which indicates that for every 1.0% increase in R1 there is a 0.5% decrease in ωp. Likewise, we find that 11225.0 1 CRCRQ SpQ Rp+−= (4.72) which for equal resistor and capacitor values becom es (4.73) pQ RQ Sp+−= 5.0 1 Equation (4.73) indicates th at the sensitivity of Qp with respect to R1 can be quite high since Q values can reach 50 to 100. Therefore, the selection of R and C values for the active filters plays an im portan t part in the overall sensitivity of the circuit. W e do not have space for a full treat ment of sensitivity analysis in this text. However, references in Appendix A provide further details on sensitivity and on m ethods of selecting com ponent values that yield low sensitivities. The text by Dary anani provides a particularly good present ation. In fact, that text presents a different choice for the com pone nt values for a Sallen-Key active filter as listed below. B y making those selections, it can be shown by substitution into (4.70) that Qp is no longer a function of R at all and therefore woul d have a sensitivity of zero with respect to changes in resistance value: R R K ===2 1R ,1 p p pp QR RQ Cω ω ⋅⋅⋅=⋅⋅ =21C ,2 2 1 A sensitivity analysis provides us wi th valuable inform ation about the component values used in the circuit. With that inform ation, we can determ ine which com ponents are critical in control ling variation in ke y filter param eters. However, it is also very important to perform a worst-case analy sis on the circuit. This analy sis of the circuit would use th e sensitivities that have already been determ ined to set each com ponent to the extrem e lim it of its tolerance in order to see the effect on the overall circuit perform ance. For exam ple, all com ponents with negative sensitivities would be set to their lower tolerance lim it while all components with positive sensitivities would be set to their upper limits. The circuit would then be analyzed to see if it still m et the specifications. Next, all component values would be set to th e opposite lim it and the test would be repeated. If a circuit passed this test, it should perform up to specifications with Analog Filter Implementation Using Active Filters 111 the random ly chosen values used when it is assem bled. An exam ple of a worst- case analy sis using PSpice is given in Section 4.8. Another ty pe of statistical test that is less rigorous than a worst-case test, but probably more ty pical of what will happe n in real life, is the M onte C arlo simulation. In this test, com ponent valu es are selected random ly within their tolerance range and the circuit is tested to see if it m eets the required specifications. In m ost software packages , the values can be characterized as having a Gaussian or uniform distribution. A num ber of M onte C arlo tests are usually run to sim ulate the variation of com ponent values that will be seen in the norm al assem bly process. 4.8 USING WFILTER IN ANALOG FILTER IMPLEMENTATION In order to see how WFilter helps in analog filter im plem entation, we generate the component values and PSpice data file for the problem given in Exam ple 4.5. After we enter the filter specifications a nd design the filter, we can specify the common com ponent values and frequency specification in the Circuit Specification dialog box shown in Figure 4.15. This dialog box is display ed by selecting Options and then Genera te Sp ice File from the m enu bar. Figure 4.15 Circuit specification dialog box. We have entered a com mon capacitor value of 0.1 µF and com mon resistor value of 10 kΩ. In addition, we have specified the frequency analy sis range to be from 10 Hz to 1 kHz. After pressing the Show File button, the PSpice text file shown in Listing 4.1 is display ed. Notice th at the first stage is first-order with an RB value of one ohm (most circuit analys is tools do not accept zero ohm s), while the other two stages describe twin-tee not ch filters. The original calculated values are shown in the listing and should be used in a test analy sis of the circuit to determ ine if the specifications have been met. If the specifications are not m et with these “ideal” values, either the op-a mp model is not adequate or an error has been encountered in the design steps. 112 Practical Analog and Digital Filter Design Example 4.5 and PSpice Example * Specify input source: Vs 11 0 AC 1 0 * Stage Number 1 (Practical Values) R11 11 12 1.155E+04 (1.15E+04) C11 12 0 1.000E-07 (1.00E-07) Rb1 13 21 1.000E+00 (1.00E+00) X1 12 13 21 OPAMP * Stage Number 2 C21 21 22 1.000E-07 (1.00E-07) C22 22 24 1.000E-07 (1.00E-07) C23 23 0 2.000E-07 (2.00E-07) R21 21 23 5.046E+03 (4.99E+03) R22 23 24 5.046E+03 (4.99E+03) R23 22 31 2.523E+03 (2.49E+03) Ra2 25 0 1.000E+04 (1.00E+04) Rb2 25 31 2.913E+04 (2.94E+04) Co2 24 0 2.620E-07 (2.70E-07) X2 24 25 31 OPAMP * Stage Number 3 C31 31 32 1.000E-07 (1.00E-07) C32 32 34 1.000E-07 (1.00E-07) C33 33 0 2.000E-07 (2.00E-07) R31 31 33 3.118E+03 (3.09E+03) R32 33 34 3.118E+03 (3.09E+03) R33 32 41 1.559E+03 (1.54E+03) Ra3 35 0 1.000E+04 (1.00E+04) Rb3 35 41 4.863E+04 (4.87E+04) Co3 34 0 6.860E-07 (6.80E-07) X3 34 35 41 OPAMP * Voltage divider section Rx 41 42 2.294E+05 (2.32E+05) Ry 42 0 1.046E+04 (1.05E+04) * Sub-circuit model for op-amp .SUBCKT OPAMP 1 2 6 Ri 1 2 1.000E+08 E1 3 0 1 2 1.000E+03 Rx 3 4 1.000E+03 Cx 4 0 1.000E-09 E2 5 0 4 0 1.000E+03 Ro 5 6 1.000E+00 .ENDS * Analysis modes .AC DEC 100 1.000E+01 1.000E+03 .PROBE .END Listing 4.1 Circuit analysis data file for Example 4.5. The next step in the testing of the active filter is to replace the ideal components with practical values. For this exercise, we will use 1% resistor and 2% capacitor values. (The selected values are shown in italics and parentheses in the listing.) A worst-case analysis can then be run on the circuit that involves adding tolerance information for the com ponent values. (You need access to the PSpice program to make this run.) During the worst-case analysis, sensitivities for each component are determined, and as the final step, each component is set to its worst-case extreme. Figure 4.16 shows both the worst-case and nominal response. Analog Filter Implementation Using Active Filters 113 If the two frequency responses were carefu lly com pared, we would see that there is a +2.5 dB “bum p” in the passband, and we lose over 2 dB in the stopband attenuation. These changes should represent the “worst” that can happen due to the unfortunate selection of the worst po ssible com bination of com ponents. (A worst-case analy sis was also run with 5% resistor values and 10% capacitor values and the “bum p” increased to 15 dB .) A Monte C arlo analy sis can also be run on the circuit to indicate the m ore ty pical extrem es that m ight be encountered. Depending on the nature of th e application, we can live with the resulting variations, select even m ore precise (expensive) com pone nts, or redesign the filter to more stringent specifications than actua lly desired. This re designed filter would then be able to vary to som e degree wh ile still satisfying the real specifications. However, this filter m ay also require a higher order, which will add cost to the project. Figure 4.16 Frequency responses for Exam ple 4.5. 4.9 CONCLUSION We have reached the end of the first part of this text. W e were able to design a variety of analog filters, view their fre quency responses, and im plem ent them in an active filter form . Of course, we have left a good deal of material uncovered. There are other filter ty pes that could have been discussed. There are other features that could have been included in the frequency response calculation and display . Moreover, there are other im plementation techniques available for analog filters. However, it is now tim e to m ove in to the realm of digital filters. We will 114 Practical Analog and Digital Filter Design see that our work in the area of analog filters will prove valuable, since one form of a digital filter uses much of what we have learned so far. For those who are interested in seeing the code used to gene rate the PSpice circuit file, please turn to Appendix F. 115 Chapter 5 Introduction to Discrete-Time Systems Although most naturally occurring signals are of the analog variety (continuous- amplitude and continuous-time variation), we are finding that conversion of these signals to a digital form (discrete-time and discrete-amplitude variations) provides many advantages. For example, digital signals can be stored on computer floppy or hard disks. They can be compressed to save space, converted to other formats, or transmitted in combination with other signals. Digital forms of signals are truly becoming the standard in everyday use as compact discs (CDs) for audio and multimedia applications can attest. Therefore, the remainder of this text is devoted to the application of filtering techniques to digital signals. The material in this chapter should provide a review of the basic principles of discrete-time systems that are necessary to understand the material presented in the remainder of the text. In the first section of this chapter we will discuss the process of converting analog signals into a digital form. Next, we will develop methods of dealing with discrete-time signals in both the time domain and frequency domain. We will also learn how to find the frequency response of a discrete-time system as well as how to play digitized waveforms on a computer equipped with a sound card. 5.1 ANALOG-TO-DIGITAL CONVERSION As indicated in the introduction, most of the signals that we deal with every day are known as analog signals. This type of signal has a continuous variation in both time and amplitude, as shown in Figure 5.1(a). In order to convert this analog signal to a digital signal with discrete-time and discrete-amplitude, as shown in Figure 5.1(b), several steps must be performed. First, the frequency spectrum of the analog signal must be strictly band- limited. Second, the signal must be sampled at the proper sampling rate. Third, the sampled value must be quantized to an acceptable level of accuracy. When it is time to convert the digital signal back to analog form, there are a number of methods that can be used, but one simple method requires only two steps. The first 116 Practical Analog and Digital Filter Design step is to output the digital value of t he signal and hol d it for t he durat ion of t he sample period. The second step is to pass that signal through a lowpass filter. In order to understand the reasons why these steps are necessary for analog and digital conversi on, we need t o study the frequency spect rum of a sam pled signal and the requirem ents placed on the sam pling rate. Figure 5.1 Comparison of anal og and di gital signals. 5.1.1 Frequency Spectrum and Sampling Rate When an analog signal x(t) is sam pled, as shown i n Figure 5.1, t he sam ples are usual ly taken at equal intervals of time. This sampling period Ts is th e inverse o f the sam pling frequency fs. The resul ting di gitized waveform xs(nT) can be speci fied wi th an argum ent indicating the sam pling peri od Ts, as shown in (5.1): snTt s tx nTx== )()( (5.1) For exam ple, if we had an analog signal x(t) as specified in (5.2), the sam pled versi on of t he signal xs(nTs) as sh own in (5.3) would resu lt: (5.2) ) 200cos( 50)(100t e txt⋅⋅⋅=⋅− (5.3) ) 200cos( 50)(100 snTnT e nTxs ⋅⋅⋅=⋅− If we assum e that the anal og si gnal is sam pled at a frequency of 1,000 samples per second, t hen we can cal culate the val ues of xs(nTs) with Ts = 0.001 second. The val ues that resul t can be st ored as a sequence of num bers, as shown Introduction to Discrete-Time Systems 117 below. This is an important point: once an anal og si gnal has been di gitized, i t is nothing m ore than a sequence of num bers t hat can be stored, manipulated, transmitted, or processed in any way we see fit. … ,1 ,0 },... 16.4, 23.4, 30.6, 37.7, 44.3, 50.0,{)( = = n nTxs (5.4) Since t he sam pling peri od sel dom change s, discret e-time equat ions usual ly drop t he sam pling period Ts from the expressi ons t o produce an expressi on such as (5.5). Th e sam pling period will n ot be needed again until the digitized waveform is convert ed back t o anal og form . (5.5) ) 100cos( 25)(10n e nxn⋅⋅⋅=⋅− Although it doesn’t appear t hat much has changed i n the represent ation of t he signal in the time dom ain, a great deal has changed i n the frequency dom ain. The frequency spect rum of a si gnal is shown i n Figure 5.2(a) before sam pling. If t his signal were sam pled at a frequency of fs, the spect rum of the sam pled signal woul d be as shown i n Figure 5.2(b). The ori ginal anal og spect rum is replicated throughout the spect rum at intervals of fs (although onl y one i nstance of that is shown). Because of this replication, it is feasible that there will be corruption of the frequency com ponent s of t he ori ginal signal by com ponent s of the replicated signals. Thi s corrupt ion is referred t o as aliasing, and t he offendi ng frequenci es are alias frequenci es. (Furt her details of al iasing and t he upcom ing Ny quist criteria can be found in m ost of the digita l filter design references in Appendix A.) Figure 5.2 Spectrum of signal (a) befo re and (b) after sam pling. 118 Practical Analog and Digital Filter Design When digitizin g a sig nal, it is v ery im portant to capture most, if not all, of the inform ation present in the ori ginal anal og si gnal without generat ing alias frequencies. For this reason, a good deal of study has gone into the conditions necessary to faithfully convert an anal og si gnal into a digital form . We can see by closely observi ng Fi gure 5.2(b) that if we are to elim inate the effect of aliasing, the sampling frequency must be at least twice as hi gh as t he highest frequency in the ori ginal signal. This relationshi p, as shown i n (5.6), i s known as the Nyquist criteria, and i s a wel l-known requi rement in sampling theory: h s f f⋅>2 (5.6) In order to guarantee th at th is req uirement is m et at all tim es, it is normal procedure t o band-l imit the input signal to one-hal f of t he sampling frequency once t he sam pling frequency has been set . Thi s is a prudent measure, since frequencies beyond those which are norm ally expected can occasionally occur in all systems. The band-l imiting process can be i mplemented by sendi ng the anal og signal through an analog lowpass filter prio r to sampling. (W hat an excellent use of our analog filter th eory!) 5.1.2 Quanti zation of Sampl es Once the analog signal has been sam pled, it is a d iscrete-tim e sig nal since values of the signal exist only at part icular m oments of t ime, but the am plitude of t he signal is still continuous. Then, the next step in the analog-to-digital conversion (ADC) is to quantize the continuous-am plitude signal to one of many discrete values of amplitude. The number of possi ble val ues al lowed for t he am plitude i s determ ined by the size of the variable chos en to store the values. For exam ple, if a single byte of memory (8 bits) is ch osen to store the information, then the amplitude can t ake on one of 28 or 256 di fferent values. If t he original signal had a range of am plitudes from +1 vol t to −1 volt, then the diffe rence between adjacent amplitudes woul d be approxi mately 7.8 ⋅ 10−3 volts. On t he other hand, i f two bytes of m emory (16 bits) were used to store each sam ple, there would be 216 or 65,536 di fferent values to represent the signal. With this many values, the ±1 vol t signal would have adj acent amplitudes separated by only 3.05 ⋅ 10−5 volts. Obviously, th e larg er the variable used to store the sam pled data, th e more closely we can approximate the analog signal with the digital rep resentation. (In the previ ous di scussi on it is assum ed that uniform sam pling was used where all levels would be equally spaced. There are also techniques that use nonuniform spacing to place m ore levels at lower levels and wider spacing for larger signals.) However, t he drawback of usi ng larger and l arger vari ables is twofold. First, the storage requi rements to store t he digitized waveform are proport ional to the number of bi ts used t o quant ize the sam ples. For exam ple, suppose we deci de to Introduction to Discrete-Time Systems 119 sample a speech signal that contains si gnal frequencies from 300 to 3,000 Hz at a frequency of 8,000 Hz (which satisfies Ny quist’s criteria). The waveform would need a file size of 480,000 bytes (480 kilobytes) to store one minute’s worth of data using only 1 byte per sample. On the other hand, if we stored one minute of stereo music using 2 bytes of data for each channel (left and right), the file size would need to be over 10 million bytes (10 megabytes). This large file size is necessary to accommodate a sampling rate of 44 kHz, which is the normal rate used for high-fidelity audio signal with frequencies up to 20 kHz. The second drawback is the speed of conversion from analog-to-digital form. Although ADC chips are very fast these days, obtaining more accuracy requires more time for conversion. Eventually, a limit on accuracy will be reached because the conversion cannot be made in the allotted sample interval. This limitation is more common when processing video signals that have bandwidths in the millions of hertz (MHz). It is important to note at this point that theoretically the sampling of an analog waveform does not normally produce any error. (This assumes that the sample clock does not introduce error because of timing jitter.) It is the quantization of the sample that produces the error in a digital system. If the samples could be stored in their original continuous-amplitude form, they could be used to regenerate the original signal with no error (assuming the Nyquist criteria is met). The maximum amount of error introduced into the system by this quantization is equal to one- half of the difference between amplitude levels. As we can see, selecting a method for the digitization of an analog signal is a compromise between conversion speed, waveform accuracy, and stor age or transmission size. 5.1.3 A Complete Analog-to-Digital-to-Analog System Figure 5.3 shows a block diagram of a complete system that first converts an analog signal to digital form for processing, transmission, or storage. Then the conversion is undone by converting the digital signal back to analog form at another time and/or place using a digital-to -analog converter ( DAC). As shown in Figure 5.2(b), the process of sampling a signal produces replicas of the original analog spectrum at intervals of the sampling frequency. In order to recover the original analog signal we simply have to eliminate the frequencies higher than f s/2. This filtering is accomplished by a high-order lowpass filter. A good example of such a complete procedure is the processing of audio signals for a music CD. The original sounds of the music are supplied by instruments or voices and are then recorded on tape in analog form. At some later time, these analog signals are digitized and encoded on the compact disc. We can then buy this CD and take it home and play it on our stereo system where the musical data is first converted from digital to analog form and then reproduced for us. In this example, the data is proce ssed, stored, and reproduced at a later time and different place. 120 Practical Analog and Digital Filter Design Figure 5.3 Complete an alog-to-digital-to -analog system . 5.2 LINEAR DIFFERENCE EQ UATIONS AND CONVOLUTION In our st udy of di scret e-time systems, we need t o be abl e to descri be them in a number of differen t ways. In this sectio n we will learn how to describ e a discrete- time system by using a di fference equat ion and t he system’s impulse response. The impulse response of a sy stem is simply its response t o the discret e impulse funct ion δ(n), as defined in (5.7). Thi s funct ion is the discret e-time equi valent to the Dirac del ta funct ion δ(t) used i n cont inuous-t ime system theory. The i mpulse function is a very useful function because any input signal sequence can be descri bed by sum ming wei ghed and del ayed versi ons of t he impulse funct ion. Likewi se, a discret e-time system’s response can be descri bed by com bining the responses t o the input sequence. (5.7) ⎩⎨⎧ ≠==0 for ,00 for ,1)(nnnδ In addition, we will u se the unit step function u(n) in many of our expressi ons, so i ts defi nition is shown i n (5.8). Thi s funct ion is the equi valent of the cont inuous-t ime step funct ion u(t): (5.8) ⎩⎨⎧ <≥=0 for ,00 for ,1)(nnnu Just as u(t) can be defi ned as t he integral of δ(t), u(n) and δ(n) have a relatio nship built on the infinite su mmation as describ ed in (5.9): Introduction to Discrete-Time Systems 121 (5.9) ∑∞ == 0)( )( nn nuδ 5.2.1 Linear Difference Equations Continuous-t ime sy stems oft en requi re the sol ution of one or m ore linear different ial equat ions. In t his case, val ues of the input and out put signals and t heir derivatives are used. The discrete-tim e equivalent to this an alysis u ses lin ear difference equat ions t hat make use of past and present values of t he input and past values of t he out put. Not e that instead of usi ng deri vatives, we are using past values of t he signals. One classic exam ple of a discrete-tim e system that can be easily described by a difference equat ion is the bank account balance. Let y(n) reflect the balance in a savings account where x(n) dollars are deposited at th e beginning of each month. We can assum e that the account earns i nterest at a monthly percent age rate of I. If we let Ts, the sam ple peri od of t he system, be one m onth, then the difference equat ion shown i n (5.10) refl ects the bal ance i n the account at the beginning of each m onth: )()1()100/()1( )( nx ny I ny ny +−⋅+−= (5.10) If we assum e that we deposit $100 each month and the interest is 1% per month, we can repl ace x(n) with 100⋅u(n) in (5.10) to produce th e following resu lt: )( 100)1()01.1()( nu ny ny ⋅+−⋅= (5.11) Table 5.1 shows t he bal ance of t he account for six months, assum ing that we just opened t he account and t he bal ance was zero. Table 5. 1 Balance in Savings Account Month Balance 0 $100.00 1 $201.00 2 $303.01 3 $406.04 4 $510.10 5 $615.20 Although m anual techni ques for t he sol ution of t his difference equat ion are acceptable for six m onths’ tim e, other methods will need to be em ployed for 122 Practical Analog and Digital Filter Design longer periods of time. Let’s see i f we can det ermine a general form ula for t he balance of t his account . Starting wi th the first month we fi nd that 100)0(=y (5.12) )01.11( 100 100)0( 01.1)1( +⋅=+⋅= y y (5.13) (5.14) )01.101.11( 100 100)1( 01.1)2(2++⋅=+⋅= y y or in general (5.15) ∑ =⋅=n kkny 001.1 100)( Although this expression is com pact, it still would require the calculation of the sum of n + 1 term s in order to determine the value. What we really need is a closed form solution. (Of course I woul dn’t have m entioned such a t hing if one didn’t exist.) We can defi ne what is refe rred to as a finite geom etric sum, as shown bel ow: (5.16) ∑ ==n kka 0FGS Then, wi th som e ingeni ous m athematics, we can defi ne a di fference t hat cancels m ost of the term s: (5.17) 1 0 01 FGS FGS+ = =−=⋅−=⋅− ∑∑nn kkn kka a a a a Finally, we can det ermine the val ue of t he FGS, as shown below. (The value of FGS when a = 1 is determined directly fro m (5.16): ⎪⎩⎪⎨⎧ = +≠−− =+ 1 for ,11 for ,11 FGS1 a naaan (5.18) Introduction to Discrete-Time Systems 123 We can now wri te the equat ion for t he bal ance of our savi ngs account in a closed form , as shown below. Thi s expressi on does not need t he cal culation of n + 1 term s in order for us to evaluate it. 01.1101.11100)(1 −−⋅=+n ny (5.19) We can also define the value of the in finite geom etric sum , as shown below: (5.20) ∑∞ == 0IGS kka By sim ply allowing n in (5.18) to approach infi nity, we can see that IGS can be specified as ⎪⎩⎪⎨⎧<−= otherwise undefined1 for ,11 IGSaa (5.21) One way to com pletely define a discrete -time system is by using its difference equation. In general, the difference equa tion describing the out put for a discrete- time system can be written as (5.22) ) ( ) ( )( 1 0knyb knxa nyN kkM kk −⋅−−⋅= ∑ ∑ = = We would have com plete knowledge of the sy stem if we know the coefficients ak and bk. As indicated in (5.22), the output y(n) is a function of past and present values of the input x(n) and past values of the output. A system such as this is a recursive system . A system that has its output describe d only by past and present values of the input is a nonrecursive system . We will see in the chapters to com e that these definitions eff ectively divide the types of digital filters to be designed into two groups as well. Notice that we have defined the output of our sy stem in term s of only past and present values of the input. Such a sy stem is referred to as a causal system . Any real-tim e system, of course, m ust be causal since we cannot determ ine the output of a sy stem based on input or output values we have not y et seen. However, system s that are not real-tim e can be noncausal . For exam ple, any system that can draw its input from stored data can dete rmine the output of the sy stem at tim e n by 124 Practical Analog and Digital Filter Design using input values at n + m. These “future” values are known since they already have been stored. 5.2.2 Impul se Response and Convol ution Another way to com pletely describe a disc rete system is to specify the im pulse response h(n) of the system. The im pulse response of a sy stem can be determ ined from the difference equation by substituting the im pulse function δ(n) for the input x(n) and determ ining the output y(n). Example 5.1 Determinati on of Impulse Response Problem: Assum e that a discrete-tim e system is described by the difference equation shown below. Determ ine the first five values of the im pulse response, and then form ulate an analy tic expression for the im pulse response. )( )1 ( )(1 nx nyb ny +−⋅= Solution: First, the equation is m odified to reflect the fact that the output will be the im pulse response h(n) if the input is δ(n). )( )1 ( )(1 n nhb nh δ+−⋅= Next, the set of the first five values of the im pulse response are determ ined using Table 5.2. Table 5. 2 Results of I mpulse Response n δ(n) h(n − 1) h(n) 0 1 0 1 1 0 1 b1 2 0 b1 b1 2 3 0 b1 2b1 3 4 0 b1 3b1 4 From these results we can see that th ere is a general form to the im pulse response, as shown below: )( )(1 nu b nhn⋅= When the im pulse response of a sy stem is known, the com plete characteristics of the system are known. The reaction of the system to any other input can then be Introduction to Discrete-Time Systems 125 determ ined by using convolution (sim ilar to the operation in continuous sy stems). The output of the sy stem can be defined as in (5.23) where the ∗ indicates convolution, not m ultiplication. In that e xpression, we see that the output of the system y(n) is determ ined by com puting a sum of products of the im pulse response coefficients h(n) and past values of the input x(n − k). Convolution has the com mutative property so the order of the functions in the convolution definition is not im portant. From a pr actical standpoint however, the sim pler function is typically specified in the time-shifted form at. This is the predom inant method used to im plem ent an FIR filter, which is discussed in detail in Section 8.3. In addition, a num ber of the texts lis ted in the digital filter design section of Appendix A cover discre te-tim e convolution. (5.23) ∑∞ −∞=−⋅ =∗= kknxkh nxnhny ) ()( )()()( Exampl e 5.2 System Response by Convol ution Problem: Determ ine the output of the sy stem described in Exam ple 5.1 if the input is the signal shown below: )( )(1 nua nxn⋅= Solution: Since we already have the im pulse response of the sy stem, we can use convolution to determ ine the output of the system. The equation for the output of the system is ∑∞ −∞=−⋅ =∗= kknhkx nhnx ny ) ()( )()( )( or ∑∑∞ −∞==−⋅ ⋅=−⋅⋅⋅= kn kk n kn knu ba b knu bkua ny )( ) ( ) ( )( )( 01 1 1) ( 1 1 Note that the lim its on the convolu tion sum mation are adjusted by the functions u(k) and u(n − k). The step function u(k) has zero value for negative values of k and therefore the lower lim it of the summation is set to zero. The step function u(n − k) will have zero value for all k values greater than n, and therefore the upper lim it of the summation is set to n. We can use the form of a finite geom etric sum to sim plify the result into a closed form solution, as shown below: 126 Practical Analog and Digital Filter Design ⎪⎩⎪⎨⎧ = ⋅+≠−− =++ 1 1 11 1 1 11 11 1 for , )1(for ,)( a b b na baba b ny nn n 5.3 DISCRETE-TIME SYSTEMS AND Z-TRANSFORMS It is also important to be able to understand a discrete-tim e sy stem’s characteristics in the frequency dom ain as well as the tim e dom ain. For linear system s, the Laplace transform can be used to transform tim e dom ain characteristics to the frequency dom ain. For discrete-tim e system s, we will use the z-transform as defined in (5.24): (5.24) ∑∞ −∞=−⋅ == nnznx zX nxz )( )( )}({ The z-transform of a weighted im pulse f unction, for exam ple, results in a single term because the im pulse f unction has only one nonzero value. (5.25) A z A zn A n Az nn=⋅⋅=⋅ =⋅∑∞ −∞=− 01 )( )}( { δ δ The z-transform of a weighted step functi on can also be determ ined using the definition. In this case, the result can be simplified by using the definition of the infinite geometric sum. Some of the more commo n z-transform pairs are shown in Table 5.3. 1 1)( )( )}( {1 01 −⋅= −=⋅⋅=⋅ =⋅−∞ =−∞ −∞=−∑ ∑zzA zAz A znu A nuAz nn nn (5.26) The z-transform also has a set of useful properties, as shown in Table 5.4. First and forem ost is the property that the z-transform of the im pulse response is the system ’s transfer function in the z-dom ain. We’ll use that property in the next exam ple. The second property in Table 5.4 shows that convolution in the tim e domain can be represented as sim ple m ultiplication in the z-dom ain. The third Introduction to Discrete-Time Systems 127 property listed shows that tim e delay of k units of tim e can be represented by multiplication by z-k in the z-dom ain. And finally, m ultiplication by n in the tim e domain can be represented by differentiation in the z-dom ain. For further discussion of these and other properties of the z-transform or for a m ore comprehensive list of z-transform pairs, please refer to one of the reference texts listed in Appendix A. Table 5. 3 Commo n z-Tran sform Pairs Time Domain F unction Frequency Domain F unction )(n Aδ⋅ A )(nuA⋅ )1 (−⋅ zzA )(nunA⋅⋅ 2)1 (−⋅ zzA )(nuaAn⋅⋅ ) ( azzA −⋅ )() cos( nun A ⋅⋅Ω⋅ [] 1 ) cos(2) cos( 2+⋅Ω⋅−Ω−⋅⋅ z zzzA )() sin( nun A ⋅⋅Ω⋅ 1 ) cos(2) sin( 2+⋅Ω⋅−Ω⋅⋅ z zzA )() cos( nu n aAn⋅+⋅Ω⋅⋅ φ [] 2 2) cos( 2) cos( ) cos( az a za zzA +⋅Ω⋅⋅−Ω−⋅−⋅⋅⋅ φ φ Table 5. 4 Commo n z-Tran sform Properties Time Domain F unction Frequency Domain F unction )(nh )(zH ∑∞ −∞=−⋅ kknxkx ) ( )(2 1 )( )(2 1 zXzX⋅ ) (knx− )(zX zk⋅− )(nxn⋅ dzzdFz)(⋅− 128 Practical Analog and Digital Filter Design Example 5.3 Determining the Transfer Function Problem: Determ ine the transfer function of the sy stem described in Exam ple 5.1, which has an im pulse response of )( )(1 nubnhn⋅= Find the location of the poles and zeros of the transfer function as well as the difference equation of the sy stem from the transfer function. Solution: Using the fourth entry in the table of z-transform pairs, we can determ ine that the transfer func tion of the sy stem described is )()( ) 1(1 ) ()(1 1 1 zXzY zb bzzzH = ⋅−=−=− We see that there is a single pole (denom inator root) at z = b1 and a single zero (num erator root) at z = 0. By cross-m ultiplica tion, the following equation results: )( )( )(1 1 zX zY zbzY =⋅⋅−− By taking the inverse z-transform of this equation and apply ing the tim e shift property of the z-transform , we can determ ine the same difference equation, as in Exam ple 5.1: )()1( )(1 nx nyb ny +−⋅= Another way that a discrete-tim e system can be described is by drawing a system diagram to represent a general difference equation. Figure 5.4 shows the system diagram for (5.21). In the figure, delay s are represented by z-1 and multiplication by triangular sym bols. Of course, if a nonrecursive filter was being represented, the lower half of the system diagram would be elim inated since the output of such a sy stem does not de pend on past values of the output. In this system diagram , we see th at each tim e the signal m oves through a delay elem ent the output is delay ed by one sam ple interval. Although the sy stem diagram is correct and will produce the corr ect output relationship, there is a m ore efficient description of the system . First, if we transform the general difference equation of (5.22), we have (5.27) ∑ ∑ =− =−⋅⋅=⎟⎟ ⎠⎞ ⎜⎜ ⎝⎛⋅−⋅M kk kN kk k za zX zb zY 0 1)( 1)( Introduction to Discrete-Time Systems 129 Figure 5.4 System diagram of general discrete-tim e system. From this description, we can determ ine the transfer function H(z) to be ∑∑ =−=− ⋅−⋅ ==N kk kM kk k zbza zXzYzH 10 1)()()( (5.28) We can represent (5.28) in a slightly different way to allow for further developm ent: ∑∑ =−=− ⋅−⋅⋅ =⋅N kk kM kk k zbza zXzW zWzY 10 11 1 )()( )()( (5.29) This representation leads to two sepa rate relationships, as shown below: (5.30) ∑ =−⋅⋅=M kk kza zWzY 0)( )( (5.31) ∑ =−⋅⋅+=N kk kzb zWzXzW 1)( )( )( 130 Practical Analog and Digital Filter Design These two equations in the z-dom ain can be written in th eir equivalent form in the tim e dom ain by recognizing that z−k in the z-dom ain represents a delay of k sample periods in the tim e dom ain. (5.32) ∑ =−⋅=M kk knwa ny 0) ( )( (5.33) ∑ =−⋅+=M kk knwb nx nw 1) ( )()( The result of this derivation is that the general form of a discrete-tim e system diagram can be drawn with m ore effici ent use of the delay units by defining w(n) in the diagram . Since these delay units must be im plem ented in hardware or software, the fewer used the better. Fi gure 5.5 shows the preferred m ethod of drawing the sy stem diagram with fewer delay s. Figure 5.5 System diagram with fewer delay units. 5.4 FREQUENCY RESPONSE OF DISCRETE-TIME SYSTEMS The frequency response is one of the most important characteristics of a discrete- time system. Although it does not com pletely describe the sy stem as the difference equation, im pulse response, or transf er function does (it does not convey the transient behavior of the system), the frequency response does pr ovide im portant inform ation about the steady -state beha vior of the sy stem. We can begin by considering an analog sinusoidal signal and the sam pled signal using a sam pling period of Ts. Introduction to Discrete-Time Systems 131 ) cos( )( t Atx ⋅⋅=ω (5.34) ) cos( ) cos( )( n A nT A nTxs ⋅Ω⋅=⋅⋅=ω (5.35) where we have defined s s s ff Tf T / 2 2 π πω =⋅=⋅=Ω (5.36) Equation (5.36) provides us with a m ethod of com paring the analog frequency f to the digital frequency Ω. The range of analog frequencies acceptable for a discrete-tim e system does not extend from zero to infinity as would be the case in a norm al analog system . We m ust rem ember that the upper lim it of acceptable analog frequencies in discrete-tim e systems is governed by the Ny quist criteria, and therefore the range is defined as s hown below. Note that a subscript of d is appended to the frequency variable to indi cate we are talking about an equivalent analog frequency within a discrete-tim e system. 2/ 0s df f<≤ (5.37) Com bining this condition with (5.36) re sults in the following range of digital frequencies π<Ω≤0 (5.38) Although a sine or cosine function is us ually used to determ ine the frequency response of a hardware sy stem, both of these functions can be described by complex exponentials, as shown below: 2) cos(nj nje enΩ−Ω+=⋅Ω (5.39) je ennj nj 2) sin(Ω−Ω−=⋅Ω (5.40) In fact, all periodic functions can be represented by these exponentials and even constants can be represented as e xponentials with zero frequency . Therefore, when determ ining the frequency response of a discrete system, it is com mon to consider the driving function as the complex exponential, as shown below: 132 Practical Analog and Digital Filter Design (5.41) njenxΩ=)( The output of a discrete-tim e system can then be determ ined by convolving this input signal with the sy stem’s impulse response. The output is then (5.42) ∑ ∑∞ −∞=Ω− Ω∞ −∞=−Ω⋅ =⋅ = kkj nj kknjekh e ekh ny )( )( )() ( Or, we can rewrite the result as (5.43) ) ()( )( )()(Ω∞ −∞=Ω−⋅=⋅ =∑j kkjeHnx ekh nx ny where H(e jΩ) is defined as the frequency response of the sy stem. If we com pare the definition of the frequency response, as shown in (5.44), and the definition of the transfer function for a system , as shown in (5.45), we see a striking sim ilarity: (5.44) ∑∞ −∞=Ω− Ω⋅ = kkj jekh eH )( ) ( (5.45) ∑∞ −∞=−⋅ = kkzkh zH )( )( We can take advantage of this conveni ent sim ilarity by defining the frequency response of a system in term s of the transfer function by simply allowing z to be replaced by e jΩ. That is, Ω=Ω= jezjzH eH )( ) ( (5.46) Example 5.4 Determining the Frequency Response Problem: Determ ine the frequency response of the sy stem described in Exam ple 5.3, which has a transfer function of Introduction to Discrete-Time Systems 133 ) ()( 1bzzzH−= Assum e that b1 has a value of 0.8 for this sy stem. Solution: The frequency response can be found from the transfer function by simply making the substitution of z = e jΩ: ) sin( 8.0) cos() sin( ) cos( )8.0 ()( ) (Ω⋅+−ΩΩ⋅+Ω= −= =ΩΩ =Ω Ωjj eezH eHjj ezj j 2 2)) (sin( )8.0) (cos(0.1) ( Ω+−ΩΩ∠=ΩjeH The values for the frequency response can then be calculated by allowing the frequency Ω to range from 0 to π, as shown in Table 5.5. Note that the com plex exponential e jΩ can be converted to a com plex num ber in the rectangular form of cos(Ω) + j sin(Ω) using Euler’s relationship or converted to polar form as 1∠Ω. Table 5. 5 Frequency Response Frequency Magnitude Phase (deg) 0 5.00 0.00 π/4 1.42 −52.5 π/2 0.78 −38.7 3π/4 0.60 −19.9 π 0.56 0.00 Exam ple 5.4 shows that the frequency response of a sy stem is nothing m ore than a com plex valued function of freque ncy. At any particular frequency , the complex value of the function can be dete rmined and converted to polar form , as shown below: (5.47) )( )( ) ( ΩΦ∠Ω=ΩM eHj In this expression, M(Ω) represents the adj ustment in m agnitude that a signal will experience as it passes through the system , and Φ(Ω) represents the adjustm ent in phase that the input signal will experience. For in stance, if a digital signal 134 Practical Analog and Digital Filter Design ⎟ ⎠⎞⎜ ⎝⎛°+⋅= 302cos20)(nnxπ (5.48) was applied to the sy stem of Exam ple 5. 4, the output signal could be determ ined by m ultiplying the m agnitude of the input by the m agnitude of the frequency response at Ω = π/2, and by shifting the phase of the input by the phase of the frequency response at Ω = π/2. The result could be written as [ ]°−°+⋅⋅⋅= 38.7 30)2 (cos78.020)( n ny π (5.49) or [ ]°−⋅⋅= 7.8)2 (cos62.15)( n ny π (5.50) Using a digital frequency of Ω = π/2 may not be com fortable for analog filter designers who are used to working with much larger frequencies. Therefore it is important to note that this digital freque ncy does relate to som e analog frequency through the form ula expressed in (5.36). That equation is restated here in term s of the equivalent analog frequency fd. We see that this frequency is a function of both the digital frequency and the sam pling frequency for the sy stem, as discussed earlier: s d f f⋅Ω=π2 (5.51) Therefore, if we are dealing with a system with a sam pling frequency of 10,000 samples/second, it m ay be m ore natu ral to think of the input signal above as being an analog signal of 2,500 Hz that has been converted to a digital frequency : Hz 500,2 000,1022/=⋅=ππ df (5.52) Working with discrete-tim e system s will require us to be able to use all the material discussed thus far in this chap ter. Som e problem s will be better expressed in the tim e dom ain, while others will be easier to work with in the frequency domain. Some system analysis or design will be easier using the system ’s im pulse response, while others will require the use of the system ’s transfer function. As filter designers, we will definitely need to determ ine the frequency response of our system , and if we are to im plem ent these filters, a system diagram will be handy. So before we leave this section, let’s work an exam ple that uses all the facets of discrete system s discussed so far. Introduction to Discrete-Time Systems 135 Example 5.5 Complete Di screte-Time System Example Problem: Consider the difference equation fo r a discrete-tim e system shown below. Determ ine the im pulse response, transfer function, and frequency response of the system . )3(0.1)2(0.3)1(0.3)(0.1+ )3( 68.0)2( 81.1)1(0.2)( −⋅+−⋅+−⋅+⋅−⋅+−⋅−−⋅= nx nx nx nxny ny ny ny Also, find the location of the poles and zeros for the system as well as draw the system diagram . Finally , determ ine the out put of the sy stem if the input is the analog signal x(t) shown below. Assum e that the sampling frequency is 20,000 samples per second. )30 000,82sin(20)60 000,22cos(510)( °+⋅⋅ +°−⋅⋅ += t t tx π π Solution: We begin the solution of the problem by transform ing the difference equation to determ ine the transf er function for the system such that )( 0.1)( 0.3)( 0.3 )( 0.1)( 68.0)( 81.1)( 0.2)( 3 2 13 2 1 zX z zX z zX zzX zY z zY z zY z zY ⋅⋅+⋅⋅+⋅⋅+⋅+⋅⋅+⋅⋅−⋅⋅= − − −− − − or )( 68.0 81.1 0.20.10.1 0.3 0.30.1 )()( 3 2 13 2 1 zH z z zz z z zXzY= ⋅+⋅−⋅+⋅+⋅+⋅+=− − −− − − After we convert H(z) to positive powers of z, we factor the transfer function in order to determ ine the pole and zero locat ions. From the expression, we see that there are three zeros at z = −1.0 and three poles at z = 0.8 and 0.6 ± j0.7: )85.0 2.1 ()8.0()0.1()(23 +⋅−⋅−+= z z zzzH The frequency response can now be easily determ ined from the transfer function, as indicated below: )85.0 2.1 ()8.0 ()0.1 () (23 +⋅−⋅−+=Ω Ω ΩΩ Ω j j jj j e e eeeH 136 Practical Analog and Digital Filter Design If we are to determ ine the response of our sy stem to the sampled analog signal, we need to convert the critical analog frequencies to digital frequencies. The DC term is zero frequency in either case, while the analog frequency of 2,000 Hz converts to a digital frequency of π/5, and the analog frequency of 8,000 Hz converts to a digital frequency of 4π/5. The m agnitude and phase responses for this H(e jΩ) are shown in Table 5.6. Table 5. 6 Frequency Response Frequency Magnitude Phase (deg) 0.0 61.54 0 π/5 37.82 −88 2π/5 6.14 −249 3π/5 0.63 −261 4π/5 0.05 −266 π 0.00 −270 By apply ing the m agnitude and phase adjustm ents indicated in Table 5.6 for frequencies of 0, π/5, and 4π/5, we can determ ine the output of the sy stem as: ) 236 000,82sin(00.1) 148 000,22cos( 189 615)( °−⋅⋅⋅+°−⋅⋅⋅+= t t ty π π The im pulse response of the sy stem can be determ ined by finding the inverse z- transform of the transfer function. Th e most com monly used m ethod for finding the inverse transform is by using partial fract ion expansion of H(z)/z and then matching the resulting term s to ones in the transform table. )85.0 2.1 ()8.0()1( )( 23 +⋅−⋅−⋅+= z z zzz zzH After using the standard m ethods for evaluation of coefficients, we find )85.0 2.1 (5372.7 284.11 )8.0(755.13 4706.1 )( 2+⋅−−⋅−−+−= z zz z z zzH then we write H(z) as the sum of three term s )85.0 2.1 (5372.7 284.11 )8.0 (755.134706.1 )(22 +⋅−⋅−⋅−−⋅+−= z zz z zzzH Introduction to Discrete-Time Systems 137 The first two term s can be easily inverse transform ed by matching terms in the z-transform table. However, the third te rm relates to a dam ped sinusoid and requires som e manipula tion before it can be inverse transform ed. 2 22 22 ) cos( 2) cos( ) cos( )85.0 2.1 (5372.7 284.11 az a zz aA z A z zz z +⋅Ω⋅⋅−⋅Ω−⋅⋅−⋅⋅= +⋅−⋅−⋅ φ φ By com paring denom inator term s, we find that a = 0.92195 and Ω = 0.86217, while the num erator term s provide A = 11.337 and φ = 0.09677. With these values, the transfer function can be inverse transform ed to )() 09677.0 86217.0cos() 92195.0( 337.11 )( )8.0( 755.13)( 4706.1 )( nu nnu n nh nn ⋅ +⋅ ⋅ ⋅−⋅⋅+⋅−= δ There was a good deal of algebra and trigonom etry required to find the impulse response. If we need only a few of the first term s of the im pulse response, or if we want to verify the correctness of our work, there is a useful m ethod that can be applied. If we return to the original H(z) function and perform long division on the fraction, we will obtain a series of term s as shown: 68.0 81.1 0.20.1 0.3 0.3)(2 32 3 −⋅+⋅−+⋅+⋅+= z z zz z zzH ⋅⋅⋅+⋅+⋅+⋅+=− − − 3 2 101.15 19.11 00.50.1)( z z z zH By inverse transform ing this sequence, we have h(n) represented as a series of delay ed im pulse functions. This will tell us explicitly what the value of the impulse response is for the first few values of the sequence. These values indeed check with those given by the general expression above for h(n): ⋅⋅⋅+−⋅+−⋅+−⋅+= )3 ( 01.15)2 ( 19.11)1( 00.5)( )( n n n n nh δ δ δ δ 5.5 PLAYING DIGITIZ ED WAVEFORMS ON A COMPUTER SYSTEM In order to get the full benefit of the work we will be doing in the rem ainder of this text, a com puter sound card should be available. C ertainly , the C code in this text for the design and im plem entation of an alog and digital filters is the prim ary incentive for obtaining a copy of this text , but without a sound card to play the sound files that we will process in the ne xt few chapters, an im portant experience 138 Practical Analog and Digital Filter Design will be missed. We will be using seve ral sound files to illustrate the effects produced by the digital filters which we wi ll be designing. These sound files have been included on the software disc with this text in the \C_CODE\SOUND directory. In addition to sound file formats, there are other variations that must be considered when playing sound files. First, the sampling frequency must be considered. The standard sampling freque ncy for studio-quality a udio signals is 44,100 Hz. This frequency is high enough to allow audio frequencies in the 20,000 Hz range to be included in th e signal information. These frequencies represent the upper limit in the human hearing range. However, not all applications require this level of frequency response. Therefore, sampling rates of 22,050 and 11,025 Hz are also common. These lower frequencies provide attractive alternatives for signals wit hout high frequency co mponents or signals including only speech. The sound cards automati cally include an antialiasing filter set to the correct frequency based on th e sampling rate. Most sound cards also include the option of selecting the quanti zation to be used when the signal is sampled. Either 8-bit (1 byte) or 16-bit (2 byte s) resolution can be selected. (Other options are common for industrial applicat ions.) Table 5.7 provides a look at the size of sound files as a function of samp ling rate, number of channels, and quantization method. Table 5.7 Comparison of Sound File Size for 1 Minute of Recording Quantization Channels Sample Rate File Size 8 bits Mono (1) 11,025 Hz 0.662 MB 8 bits Mono (1) 22,050 Hz 1.323 MB 8 bits Mono (1) 44,100 Hz 2.646 MB 8 bits Stereo (2) 11,025 Hz 1.313 MB 8 bits Stereo (2) 22,050 Hz 2.646 MB 8 bits Stereo (2) 44,100 Hz 5.292 MB 16 bits Mono (1) 11,025 Hz 1.323 MB 16 bits Mono (1) 22,050 Hz 2.646 MB 16 bits Mono (1) 44,100 Hz 5.646 MB 16 bits Stereo (2) 11,025 Hz 2.646 MB 16 bits Stereo (2) 22,050 Hz 5.646 MB 16 bits Stereo (2) 44,100 Hz 10.58 MB Obviously, the size of audio files can grow very large! That is why it is important to select the sampling rate , number of channels , and quantization method carefully to provide the level of accuracy appropriate to the project. Of course today there are many options for th e compression of this data, but there is still a direct correlation between file size and sampling options. There are two different files included with the softwa re disc. The first file, SPEECH, is a monaural file that uses a sampling rate of 11,025 samples per second with 8 bits per sample. The second selection, MUSIC, is also a monaural signal recorded by Introduction to Discrete-Time Systems 139 sampling at 22,050 samples per second with 16 bits per sample. Since most sound cards will also record signals, other test signals can be captured and tested on the computer system as desired. At this point, it is time to check out the sound card on the computer by playing the sound files mentioned above. It is recommended that the sound files be copied to the hard disk for faster access. We ’ll be using them as input samples to be designed in the next two chapters. 5.6 CONCLUSION We have reached the end of our review of di screte-time systems. In this chapter, we found that the complete characteristics of a discrete-time system could be determined by knowing the system’s di fference equation, impulse response, transfer function, or system diagram. We learned ways to determine any one of these descriptions from any of the others. In addition, we learned how to find the frequency response of a system by direct substitution into the system’s transfer function. We will use the material prese nted in this chapter to design and implement digital filters in the next two chapters. The remainder of this text will be presented in a manner emphasizing appli cation rather than theory, but if the need arises, we can use the material in this chapter to better understand any problems that we might encounter. 140 Practical Analog and Digital Filter Design 141 Chapter 6 Infinite Impulse Response Digital Filter Design There are a variety of methods that can be used to design digital filters as we will see in this chapter and the next. One commonly used method is to use the analog filter approximation functions that have already been developed and simply translate them in a way that will make them usable for discrete-time systems. This method, which will be studied in this chap ter, makes use of the large backlog of filter design theory and tables of transfer functions that are readily available. Most of the filters designed using this method w ill be recursive in nature. That is, the output of the filter will depend on previous values of the output (as well as past and current values of the input). These types of filters can theoretically have impulse responses that continue forever and therefore are commonly referred to as infinite impulse response (IIR) filters. Another method of de signing discrete-time filters w ill be discussed in the next chapter. That method does not depend on an alog filter theory, but rather uses the frequency response of the desired filter to directly determine the digital filter coefficients. The method ge nerally yields nonrecursive filters that have outputs depending only on past and cu rrent values of the input. These types of filters generally have an impulse response contai ning only a finite number of values and thus are commonly called finite impulse re sponse (FIR) filters. As we are about to see, both the IIR and FIR design methods will differ from the analog filter design techniques studied in the first part of the text. (A more complete comparison of IIR and FIR filters will be given in Section 8.1.) In the first three sections of this chap ter, we will investigate different methods of translating an analog filter’s characteristic s into those of a digital filter. As we will see, there is no perfect digital equivalent to an analog filter at all frequencies; however, we can develop filters that closely match the important filter characteristics. In the final section of this chapter, we will develop the C code necessary to evaluate the frequency respons e characteristics of IIR digital filters. 142 Practical Analog and Digital Filter Design 6.1 IMPULSE RESPONSE INVARIANT DESIGN The impulse response i nvari ant desi gn m ethod (or i mpulse i nvari ant transform ation) is based on creating a digita l filter with an im pulse response that is a sam pled version of the im pulse response of the analog filter. W e first start with an analog filter’s tran sfer fu nction H(s), and by using the inverse Laplace transform , we determine the system’s cont inuous i mpulse response h(t). We next sample that response t o determine the system’s discret e-time impulse response h(nT). We then take the z-transform of this sam pled impulse response t o find the discrete-tim e tran sfer fu nction H(z). As an illustratio n, consider th e following exam ple. Exampl e 6.1 Impul se Response Invari ant Transformati on Problem: Assum e that we wi sh to convert the fol lowing cont inuous-t ime transfer funct ion to a discret e-time transfer funct ion usi ng the impulse invari ant transform ation m ethod: )5()2(12)(+⋅+=s ssH Solution: We first use basi c part ial fract ion expansi on techni ques t o write the transfer funct ion in a form suitable for i nverse t ransform ation: )5(4 )2(4)(+−+=s ssH Then recognizing the Laplace transform pair )( )() ()(1thtu eAasAsH Lat=⋅⋅= ⎭⎬⎫ ⎩⎨⎧ +=− − we can easi ly find the impulse response as )() 4 4()(5 2tu e e tht t⋅⋅−⋅=− − If we t hen sam ple this impulse response at intervals of T, we will h ave the discrete-tim e impulse response. Effectively, we sim ply replace every t with nT to denot e the nth sample at in tervals of T: )() 4 4()(5 2nTu e e nThnT nT⋅⋅−⋅=− − Infinite Impulse Response Digital Filter Design 143 This expressio n can be rewritten in a fo rm that m ore clearly in dicates th e exponent ial relationshi p of n: )(]) (4) (4[)(5 2nTu e e nThnT nT⋅⋅−⋅=− − Now we use the z-transform table as devel oped i n Chapter 6 t o find the transfer fu nction in the z-dom ain: 1 5 1 214 14)(−− −−−− −= ze zezHT T And, fi nally, we can com bine the terms over a com mon denom inator to produce the final resul t, whi ch can be si mplified once a val ue of t he sam pling period T is ch osen: ) 1() 1() (4)(1 5 1 21 5 2 −− −−−−− −⋅ −⋅−⋅= ze z ez e ezHT TT T Although Exam ple 6.1 clearly indicates the steps requi red t o translate an analog transfer funct ion to a di gital transfer funct ion, we can ski p som e of t he steps by recogni zing the com mon relationshi p between H(s) and H(z). As can be verified in the exam ple, for every term in the analog transfer function of the form shown in (6.1), there is a term created in the digital tran sfer fu nction of the form shown i n (6.2): assH+=1)( (6.1) 111)(−−⋅−= z ezHaT (6.2) This matching techni que can al so be appl ied to quadrat ic terms that have complex roots, where each factor is sim ply treated individually . For exam ple, if we have a quadrat ic of the form (6.3), the resul ting di scret e-time equi valent coul d then be written and simplified as sh own in (6.3) to (6.6): βαβαβαβαβ j sj j sj j s j ssH−+−++=−+⋅++=2/ 2/ ) () ()( (6.3) 144 Practical Analog and Digital Filter Design 1 ) ( 1 ) (12/ 12/)(− −− − +−⋅ −− ⋅ −= z ej z ejzHTj Tj βα βα (6.4) () ) 1() 1() (2/)(1 ) ( 1 ) (1 ) ( ) ( − −− − +−− −− +− ⋅ −⋅⋅ −⋅ − ⋅= z e z ez e e jzHTj TjTj Tj βα βαβα βα (6.5) 2 2 11 ) cos( 21) sin()(−−− −− − ⋅+⋅⋅⋅−⋅⋅= z e zT ezT ezHT TT α αα ββ (6.6) Exampl e 6.2 B utterw orth Impul se Invari ant Fi lter Desi gn Problem: Determ ine the im pulse invariant digital filter for a second-order Butterwort h approxi mation funct ion, as shown bel ow. Not ice that H(s) is norm alized and t herefore has a passband edge frequency of 1 rad/ sec or (1/ 2π Hz). Determine the differences t hat resul t from choosi ng sampling periods of T = 1.0 sec and T = 0.1 sec. 1 4142.11)(2+⋅+= s ssH Solution: We can first factor the analog transfer funct ion and use part ial fraction expansi on to determine 7071.0 7071.07071.0 7071.0 7071.07071.0)(j sj j sjsH−+−++= The digital transfer funct ion can t hen be det ermined by using the resul ts indicated in (6.3) to (6.6): 2 4142.1 1 7071.01 7071.0 ) 7071.0cos( 21) 7071.0sin( 4142.1)(−⋅−− ⋅−− ⋅− ⋅ +⋅⋅ ⋅⋅−⋅⋅ ⋅⋅= z e zT ezT ezHT TT We can now make the substitution of the differen t sampling periods in the general form to find the two distinct transfer funct ions: 2 11 0.124312.0 74971.0145300.)(− −− =⋅ +⋅−⋅= z zzzHT Infinite Impulse Response Digital Filter Design 145 2 11 1.086812.0 85881.11093096.0)(− −− =⋅ +⋅−⋅= z zzzHT It is interesting to com pare t he two transfer funct ions of Exam ple 6.2. We notice first that the gai ns and pol e posi tions are di fferent solely from the selection of the sampling period (or frequency ). We can al so get a qui ck indication of t he magnitudes of t hese t ransfer funct ions by determining the response at zero frequency. W e can do that easily lettin g z = ej0 = 1: 91808.049341.045300.0)( 0.10= = =TjeH 9917.9 10 3174.910 3096.9)(32 1.00= ⋅⋅=−− =TjeH With this quick check, we see t hat the response at zero frequency seem s to be proport ional to 1/T. Although usi ng onl y two val ues of sampling frequency hardl y makes a case, it is true in general that the magnitude i s proport ional to 1/T. For this reason, m ost impulse invari ant desi gns scal e the transfer funct ion by an amount equal to the sam pling peri od. As we can see, i f that scal ing were used i n the previ ous exam ple, the responses at zero frequency woul d be very close t o unity. The complete frequency responses for bot h transform ations are shown i n Figure 6.1 (wi th the T scaling fact or appl ied). The responses are not ably different as we would expect since the two transfer funct ions have di fferent gains and pole locations. It is important to notice how t his variation in transfer funct ion form and frequency response i s due solely to the val ue of sam pling peri od (or sam pling frequency) that has been selected. In order to see why this selection produces t he vari ations, we m ust rem ind oursel ves of t he rel ationshi p bet ween t he di gital and equi valent anal og frequenci es. As descri bed in Section 6.4, t he digital frequency Ω extends from 0 to π where π is analogous t o the anal og frequency of fs/2 as dictated by the Nyquist criteria. Each poi nt on the frequenc y axis can be referenced in term s of Ω, which ext ends from 0 to π, or in term s of fd, whi ch ext ends from 0 to fs/2. This relatio nship can be written in either of the two forms shown in (6.7) and (6.8): s dff/ 2⋅=Ωπ (6.7) π2Ω=s df f (6.8) 146 Practical Analog and Digital Filter Design 1.4 0.0 0.0 , 0.5, 5.0π Frequenc yMag. = 1.0 (frequency range 0 - 0.5 Hz) = 0.1 (frequency range 0 - 5.0 Hz)TT Figure 6.1 Frequency responses for Exam ple 6.2. Now we are abl e to see m ore cl early why the responses are so di fferent . Although the frequency axis extends from 0 to π, it represent s different anal og frequenci es for the two responses. In t he case of t he T = 1 sec response ( fs = 1 Hz), the digital frequency range ext ends from 0 to 0.5 Hz, and t he passband edge frequency of 0.159 Hz is clearly visible at a poi nt approxi mately one-t hird of t he way along t he frequency axis. However, i n the case of t he T = 0.1 second response (fs = 10 Hz), t he digital frequency range i s actually from 0 to 5 Hz. Therefore, the break frequency of 0.159 Hz occurs at a poi nt much cl oser t o the zero frequency point. Clearly th en from this ex ample it is im portant to pick the sampling frequency for an i mpulse invari ant desi gn careful ly. The frequency range of the input signal must be consi dered as wel l as the desi red overal l response. In general , the impulse invari ant design m ethod i s best for m atching low-frequency system responses. 6.2 STEP RESPONSE INVARIANT DESIGN Anot her com mon m ethod of convert ing an anal og transfer funct ion to the digital domain is to match the step response of bot h systems. The st ep response invari ant design procedure i s much the sam e as the impulse invari ant desi gn, except that we must determine the step response of t he anal og transfer funct ion before it is sampled and z-transform ed. W e can det ermine the anal og sy stem’s step response simply by multiplying H(s) by the transform of t he step input, which is 1/s. In (6.9) we defi ned t he system’s step response as G(s): Infinite Impulse Response Digital Filter Design 147 ssHsG1)( )( ⋅= (6.9) Once we have det ermined G(s), we can fi nd the time dom ain response to the step input g(t) by using the inverse Laplace transform : {})( )(1sGLtg−= (6.10) Then, t he discret e-time step response can be det ermined by sampling the continuous-t ime versi on: nTttg nTg== )( )( (6.11) Next , the discret e-time system response t o the step input can be determined by using the z-transform : {}111)( )( )(−−⋅= = zzH nTgZzG (6.12) As shown i n (6.12), G(z) is the product of the discret e-time transfer funct ion H(z) and t he z-transform of t he step input. Therefore, i n order t o find H(z), we simply multiply G(z) by (1 − z−1), as shown: ()11)( )(−−⋅= z zGzH (6.13) As we review this procedure, we can see that the prim ary steps are the sam e as for the impulse invari ant transform ation, except that we have added one st ep at the beginning and one step at the end. The new initial step requires th at we d ivide the anal og transfer funct ion by s, and the new fin al step requires th at we m ultiply the digital tran sfer fu nction by (1 − z−1). Exampl e 6.3 Step Response Invari ant Transformati on Problem: Assum e that we wi sh to convert the cont inuous-t ime transfer funct ion of Exam ple 6.1 to a discret e-time transfer funct ion, but this time we want to use t he step response i nvari ant transform ation m ethod. )5 )(2(12)(++=s ssH 148 Practical Analog and Digital Filter Design Solution: We need to determine the system’s response t o a st ep input by multiplying H(s) by the Laplace transform of the step input 1/ s. 58.0 20.2 2.1 )5()2(12)(+++−=+⋅+⋅=s s s s sssG We can then easily find the time dom ain response t o the step input by finding the inverse Laplace transform of G(s) as )() 8.0 0.22.1()(5 2tu e e tgt t⋅⋅+⋅−=− − If we sam ple this response at intervals of T, we will h ave the discrete-tim e response, as shown bel ow: )(]) (8.0) (0.22.1[)(5 2nTu e e nTgnT nT⋅⋅+⋅−=− − Then, usi ng the z-transform table in Chapter 5, we can find the z-transform of g(nT) as 1 5 1 2 118.0 10.2 12.1)(−− −− −−+ −− −= ze ze zzGT T And by com bining the terms over a com mon denom inator, we fi nd that ) 1() 1() 1() 2.1 0.2 8.0( ) 8.0 0.22.1()(1 5 1 2 12 7 5 2 1 5 2 −− −− −−− − − −− − −⋅ −⋅−⋅⋅+⋅−⋅+⋅⋅+⋅−= ze ze zz e e e z e ezGT TT T T T T where G(z) represent s the output of the system to a st ep input. In order t o determine the tran sfer fu nction of the system, we m ust rem ove the effects of the step input 1 / (1 − z−1). ) 1() 1() 2.1 0.2 8.0( ) 8.0 0.22.1()(1 5 1 22 7 5 2 1 5 2 −− −−−− − − −− − −⋅ −⋅⋅+⋅−⋅+⋅⋅+⋅−= ze zez e e e z e ezHT TT T T T T Although t he resul t of the previ ous exam ple looks quite involved, all of the exponential term s will becom e constants once the sam pling period for the system is selected. W e can al so use t he step invari ant desi gn m ethod on the Butterwort h filter o f Example 6.2. Infinite Impulse Response Digital Filter Design 149 Exampl e 6.4 B utterw orth Step Invari ant Fi lter Desi gn Problem: Determ ine the step invariant digital filter for a second-order norm alized B utterwort h approxi mation funct ion, as shown below. Determine the differences that result for sam pling peri ods of T = 1.0 sec and T = 0.1 sec. 1 4142.11)(2+⋅+= s ssH Solution: Again, we first d etermine the output of the analog system to an input step funct ion and then use part ial fract ion expansi on to determine the individual terms. 7071.0 7071.05.05.0 7071.0 7071.05.05.0 1)(j sj j sj ssG−+−−+++−= The step response can then be dete rmined by finding the inverse Laplace transform of G(s), as indicated below: t j t je j e j tg) 7071.0 7071.0( ) 7071.0 7071.0()5.0 5.0( )5.0 5.0(0.1)(−− +−⋅−− ⋅+−= Then, after sam pling at in tervals o f T, the di scret e-time step response is determined to be nT j nT je j e j nTg) 7071.0 7071.0( ) 7071.0 7071.0()5.0 5.0( )5.0 5.0(0.1)(−− +−⋅−− ⋅+−= The di scret e-time response t o the step input can t hen be det ermined by using the z-transform . 1 ) 7071.0 7071.0( 1 ) 7071.0 7071.0( 115.05.0 15.05.0 11)(− − − + −−−− −+− −= z ej z ej zzGT j T j Now, by combining these terms over a com mon denom inator (and perform ing a consi derabl e amount of com plex algebra), we have t he system response t o a step input: ] ) 707.0cos( 21[) 1()] 707.0cos() 707.0[sin( ] ) 707.0cos( 21[) 1()] 707.0cos() 707.0 [(sin()( 2 414.1 1 707.0 12 707.0 2 414.12 414.1 1 707.0 11 707.0 1 −⋅−− ⋅− −− −− −−⋅−− ⋅− −− −− +⋅⋅ ⋅−⋅−⋅⋅ +⋅ −++⋅ ⋅−⋅−⋅⋅ −⋅ += z e zT e zzT T e z ez e zT e zzT T e zzG T TT TT TT 150 Practical Analog and Digital Filter Design The discrete-tim e tran sfer fu nction H(z) can now be det ermined by removing the (1 − z−1) factor relating to the step input, and we can m ake the substitution of the different sampling peri ods i n the general form to find the two distinct transfer funct ions: ] ) 707.0cos( 21[)] 707.0cos() 707.0[sin( ] ) 707.0cos( 21[)] 707.0cos() 707.0 [(sin()( 2 414.1 1 707.02 707.0 2 414.12 414.1 1 707.01 707.0 1 −⋅−− ⋅−− ⋅−−⋅−−⋅−− ⋅−− ⋅−− +⋅⋅ ⋅−⋅⋅ +⋅ −++⋅⋅ ⋅−⋅⋅ −⋅ += z e zT ezT T e z ez e zT ezT T e zzH T TT TT TT 2 12 1 0.124312.0 74971.0145205.0 94546.0)(− −− − =⋅ +⋅−⋅−⋅= z zz zzHT 2 12 1 1.086812.0 8588.1112711.0 13643.0)(− −− − =⋅ +⋅−⋅−⋅= z zz zzHT Note that the pole locations are the sa me as for t he impulse invari ant design but that the zero l ocations have changed. We can com pare the frequency responses of these two discrete-tim e filters as sh own in Figure 6.2. Mag.1.4 0.00.0 Frequenc y , 0.5, 5.0π = 0.1 (frequency range 0 - 5.0 Hz) = 1.0 (frequency range 0 - 0.5 Hz)T T Figure 6.2 Frequency responses for Exam ple 6.4. As we can see, there is signi ficant difference between the two implementations, but the differences are again a result of the frequency axis having two different scales. In t he step invari ant desi gn m ethod, t here is no need Infinite Impulse Response Digital Filter Design 151 to scale the magnitude as was t he case for t he impulse invari ant design m ethod. B y comparing this frequency response t o that of Fi gure 6.1, we see a si gnificant difference. The reason for the difference is the different criteria placed on the design. In the previous section, the emphasis was placed on m atching an impulse like input signal, whi le in this sect ion the aim was t o match a st ep like input signal. As indicated in the fig ures, th e differen t criteria p roduce filters with quite different frequency responses. As in the prev ious section, this m ethod of IIR filter design is best suited to match low-frequency system responses. 6.3 BILINEAR TRANSFORM DESIGN Both the impulse invari ant and st ep invari ant desi gn m ethods provi de good approxim ations for lowpass and som e bandpass analog filter responses. However, they cannot provi de good m atching of hi gh-frequency responses, whi ch makes i t impossible to use them for highpass or bands top filter design. In fact, they do not provide the best m ethods for m atching analog filter responses when a good m atch is required throughout a wide range of frequencies. In addition, without careful selection of t he sam pling frequency and st rict band-l imiting of t he input signal, distortion from aliasin g can occur. Th erefo re, in this sectio n we will discuss the bilinear transformation that endeavors to make a reaso nable match over the entire filter freq uency ran ge. Of co urse, th at provides a ch allen ge since th e an alog frequency range ext ends from zero t o infinity and t he digital frequency range extends onl y from zero t o π. However, a transform ation from the analog s-dom ain to the digital z-dom ain has been devel oped (as descri bed i n more det ail in the techni cal references provi ded at the end of t he text). In t his method, t he relationshi p bet ween t he s and z complex vari ables can be descri bed by the following equat ion, where T is the sam pling peri od: 11 2 +−⋅=zz Ts (6.14) To better underst and this relationshi p, we can represent the com plex vari able z in the exponent ial form R⋅ e jΩ 1 sin cos1 sin cos 2 11 2 +Ω⋅⋅+Ω⋅−Ω⋅⋅+Ω⋅⋅= +⋅−⋅⋅=ΩΩ Rj RRj R T eReR Tsjj (6.15) This representation can be written in rectangular form as ] sin )1 cos [(] sin )1 cos [(] sin )1 cos [(] sin )1 cos [(2 Ω⋅⋅−+Ω⋅⋅Ω⋅⋅++Ω⋅Ω⋅⋅−+Ω⋅⋅Ω⋅⋅+−Ω⋅⋅=Rj R Rj RRj R Rj R Ts (6.16) 152 Practical Analog and Digital Filter Design and finally sim plified to () ⎥⎥ ⎦⎤ ⎢⎢ ⎣⎡ +Ω⋅⋅+Ω⋅⋅+ +Ω⋅⋅+−⋅=+⋅= 1 cos 2sin 2 1 cos 21 2 2 2 22 R RRj R RR TjTs ωσ (6.17) By referring to (6.17) and observing the s-plane and z-plane in Figure 6.3, we can see that there are thr ee distinct regions in the s-dom ain that relate to three distinct regions in the z-dom ain. In the first case, any point in the z-dom ain that lies outside of the unit circle ( R > 1) is associated with a point in the right-half plane (R HP) of the s-plane (σ > 0). In the second case, a point in the z-dom ain located inside the unit circle ( R < 1) is associated with a point in the left-half plane (LHP) of the s-dom ain (σ < 0). Finally , a point on the unit circle ( R = 1) is associated with a point in the s-plane that lies on the jω axis (σ = 0). In fact, in this last case, the positive jω axis relates to the top half of the unit circle as the angle travels from 0 to π, while the negative jω axis relates to the bottom half of the unit circle with angles from 0 to −π. LHP -plane -planeRHP = 1Outside Insideσωj R z s Figure 6.3 Comparison of s-plane and z-plane using bilinear transform . Although there does exist a one-to-one relationship between the positive jω axis and the upper part of the unit circle , it is a nonlinear one. If we look m ore closely at the im aginary portion of (6.17) when R = 1 (and therefore σ = 0), we see that () ()⎟ ⎠⎞⎜ ⎝⎛Ω⋅=Ω+Ω⋅=2tan2 cos1sin 2 T Tω (6.18) or, in term s of the z-dom ain frequency variable, Infinite Impulse Response Digital Filter Design 153 ⎟ ⎠⎞⎜ ⎝⎛⋅=Ω− 2tan21Tω (6.19) Equations (6.18) and (6.19) are important to the bilinear transform ation process because they are necessary to determ ine the proper m apping between the analog and digital dom ains. This m apping of analog frequencies to digital frequencies is fairly linear for low freque ncies, but becom es very nonlinear as higher frequencies are m apped. This m apping of frequencies is often referred to as “warping” to describe how the higher fre quencies are warped into their proper place on the unit circle. The reason that this warping is so im portant is that although we will specify the frequency character istics of the digital filter by digital frequencies, the filter will be derived fro m an analog filter transfer function. Therefore, it is necessary to properly determine the analog frequencies to use in the analog design by warping the specifi ed digital frequencies as shown in Exam ple 6.5. After determ ining the frequencies necessa ry for the analog filter design, the filter can be designed using the process described earlier in this text. Once the analog transfer function has been determ ined, we can use th e bilinear transform substitution given in (6.14). Since we will be developing code to im plem ent this transform ation process, it is im portant to carefully describe this substitution. In the case of a first-order factor, the transf ormation process begins with (6.20). Example 6.5 Determining Analog a nd Digital Critical Frequencies Problem: Assum e we wish to design a lowpass digital filter (with sampling frequency of 20 kHz) based upon a Butte rworth analog filter. The required characteristics of the digital filter are apass = −1 dB , astop = −20 dB , fpass = 1 kHz, and fstop = 5 kHz What param eters should we use to design the analog filter upon which our digital filter will be based? Solution: We first recognize that the digital frequency axis can be labeled in two different way s, as discussed earlier. Then using (6.7), we can determ ine ππ⋅=⋅⋅=Ω 1.0000,20000,1 2 p ππ⋅=⋅⋅=Ω 5.0000,20000,5 2 s 154 Practical Analog and Digital Filter Design Once these frequencies have been dete rmined they can be warped using (6.18) to produce the equivalent analog frequencies necessary for the analog filter design. sec/rad 4.335,63.008,1 22tan2=⋅⋅=⎟⎟ ⎠⎞ ⎜⎜ ⎝⎛Ω⋅= π ωp pT sec/rad 000,402.366,6 22tan2=⋅⋅=⎟ ⎠⎞⎜ ⎝⎛Ω⋅= π ωs sT Note the slight warping of the lowe r passband edge frequency (from 1,000 to 1,008 Hz) and the m ore significant warpi ng of the higher st opband edge frequency (from 5,000 to 6,366 Hz). The attenuations of the filter do not change; therefore, we have enough inform ation to proceed with the design of the analog filter, which will be the subj ect of the next exam ple. 2 12 1 11 22 12 1 11 211 2 )( Bzz TBAzz TA BsBAsAzH zz Ts +⎟ ⎠⎞⎜ ⎝⎛ +−⋅⋅+⎟ ⎠⎞⎜ ⎝⎛ +−⋅⋅ =+⋅+⋅= +−⋅= (6.20) In this equation, uppercase A and B represent the coefficients of the analog filter function. After sim plification, (6. 21) and (6.22) result with a new set of coefficients where 2/ T has been replaced with 2·fs. In these equations, lowercase a and b represent the digital filter coe fficients that will be used, and G represents the gain adjustm ent for this first-order term : 1 1 01 1 0 1 011 01 00 11 )(−− −− ⋅+⋅+⋅= ⋅⎟⎟ ⎠⎞ ⎜⎜ ⎝⎛+⋅⎟⎟ ⎠⎞ ⎜⎜ ⎝⎛+ ⋅= zbbza aG zDDzNN DNzH (6.21) where (6.22) 1 2 11 2 01 2 11 2 0 2222 Bf B DBf B DAf A NAf A N ssss −=+=−=+= Infinite Impulse Response Digital Filter Design 155 In the case of the quadratic terms that are used to describe our coefficients, the transform ation process is show n in (6.23) to (6.25). Again, G represents the gain adj ustment necessary for each of the quadratic factors for the filter. 2 12 02 12 0 11 2 11 211 2 11 2 )( Bzz TBzz TBAzz TAzz TA zH +⎟ ⎠⎞⎜ ⎝⎛ +−⋅⋅+⎟ ⎠⎞⎜ ⎝⎛ +−⋅⋅+⎟ ⎠⎞⎜ ⎝⎛ +−⋅⋅+⎟ ⎠⎞⎜ ⎝⎛ +−⋅⋅ = (6.23) 2 21 1 02 21 1 0 2 02 1 012 02 1 01 00 11 )(− −− − − −− − ⋅+⋅+⋅+⋅+⋅= ⋅⎟⎟ ⎠⎞ ⎜⎜ ⎝⎛+⋅⎟⎟ ⎠⎞ ⎜⎜ ⎝⎛+⋅⎟⎟ ⎠⎞ ⎜⎜ ⎝⎛+⋅⎟⎟ ⎠⎞ ⎜⎜ ⎝⎛+ ⋅= zb zbbza za aG zDDzDDzNNzNN DNzH (6.24) where (6.25) 02 1 2 202 2 102 1 2 002 1 2 202 2 102 1 2 0 4 2) 4 (24 24 2) 4 (24 2 Bf Bf B DBf B DBf Bf B DAf Af A NAf A NAf Af A N s ss ss ss s ss +−=−⋅=++=+−=−⋅=++= Example 6 .6 Butterwo rth Bilinea r Tra nsform Filter Desig n Problem: Determ ine the digital filter to meet the specifications given in Exam ple 6.5 using the bilinear transform ation. Solution: By entering the attenuations and the prewarped analog frequencies in W Filter for analog filter design, we determ ine the following analog transfer function: 7 4 27 10 8877.7 10 2560.110 8877.7)( ⋅+⋅+⋅= s ssH 156 Practical Analog and Digital Filter Design Then, by using the bilinear substitution for s, we can determ ine the transfer function in the digital dom ain. 7 427 10 8877.711 210 2560.111 210 8877.7)( ⋅+⎟ ⎠⎞⎜ ⎝⎛ +−⋅⋅⋅+⎟ ⎠⎞⎜ ⎝⎛ +−⋅⋅= zz T zz TzH The transfer function can be sim plified by using (6.23) to (6.25) to produce ) 53935.0 3947.11() 21( 036161.0)(2 12 1 − −−− ⋅ +⋅−+⋅+⋅= z zz zzH The frequency response of the digital f ilter designed in Exam ple 6.6 can be determ ined in the m anner discussed in the previous chapter (and is shown in Figure 6.4). Mag.1.0 0.00.0 Frequenc y , 10 kHzπ Figure 6.4 Frequency response for Exam ple 6.6. For a general quadratic factor of the form shown below: 2 21 1 02 21 1 0)(− −− − ⋅+⋅+⋅+⋅+= zb zb bza za azH (6.26) the frequency response can be determ ined by letting z = ejΩ as shown: Ω− Ω−Ω− Ω− Ω ⋅+⋅+⋅+⋅+=2 2 1 02 2 1 0)(j jj j j eb eb bea ea aeH (6.27) Infinite Impulse Response Digital Filter Design 157 The num erator and denom inator f actors can then be converted. () () )]2sin( ) sin([ )]2cos( cos [)]2sin( ) sin([ )]2cos( cos [)( 2 1 2 1 02 1 2 1 0 Ω+Ω⋅+Ω+Ω+Ω+Ω⋅+Ω+Ω+=Ω b bj b bba aj a a aeHj (6.28) We see in Figure 6.4 that the specificati ons have been m et (at 1,000 Hz the −1 dB gain = 0.89125, and at 5,000 Hz the −20 dB gain = 0.1). Example 6 .7 Cheby shev Bilinea r Tra nsform Filter Desig n Problem: Use W Filter to com pletely design a Chebyshev digital IIR filter and display the m agnitude response. Th e specifications for this filter are apass = −1 dB , astop = −60 dB , fpass = 10 kHz, fstop = 20 kHz, and fsamp = 50 kHz Solution: We can supply these values to W Filter and W Filter will calculate the m agnitude response of the filter, as shown in Figure 6.5. The digital IIR coefficients and the pole and zero lo cations are shown in Figure 6.6. In Figure 6.5 we see the effect of sampling on the frequency response. In particular, we see the lowpass response replicated in m irror im age form at the sampling frequency of 50 kHz. In addition, we see the lower half of the reflection at twice the sam pling frequency of 100 kH z. If we had chosen a larger-frequency scale, we would see these replications reproduced at all m ultiples of the sam pling frequency. Of course, in the typical di screte-tim e system , the antialiasing filter will be set to one-half of the sam pling frequency (25 kHz in this case), and the user would not see the effects of the higher-frequency com ponents. Figure 6.5 Magnitude response from WFilter. 158 Practical Analog and Digital Filter Design Example 6.7 - Chebyshev Lowpass Filter Selectivity: Lowpass Approximation: Chebyshev Implementation: IIR (digital) Passband gain (dB): -2.0 Stopband gain (dB): -60.0 Passband freq (Hz): 10000.0 Stopband freq (Hz): 20000.0 Sampling freq (Hz): 50000.0 Filter Length/Order: 04 Overall Filter Gain: 1.86714451145E-02 Numerator Coefficients QD [ 1 + z^-1 + z^-2 ] == ========================================= 01 1.0 2.00000000000E+00 1.00000000000E+00 02 1.0 2.00000000000E+00 1.00000000000E+00 Denominator Coefficients QD [ 1 + z^-1 + z^-2 ] == ========================================= 01 1.0 -6.20696688131E-01 8.14430976062E-01 02 1.0 -1.18935540161E+00 5.04413209263E-01 Zeros QD [ Real ] [ Imag ] == ========================================= 01 -1.00000000000E+00 0.00000000000E+00 02 -1.00000000000E+00 0.00000000000E+00 03 -1.00000000000E+00 0.00000000000E+00 04 -1.00000000000E+00 0.00000000000E+00 Poles QD [ Real ] [ Imag ] == ========================================= 01 3.10348344066E-01 8.47416592590E-01 02 3.10348344066E-01 -8.47416592590E-01 03 5.94677700806E-01 3.88293241542E-01 04 5.94677700806E-01 -3.88293241542E-01 Figure 6.6 Design values from WFilter. 6.4 C CODE FOR IIR FREQ UENCY RESPONSE CALCULATION To verify that all requirements have b een met, we must calculate the frequency response of our filter. In this case, the Calc_DigIIR_Resp function shown in Listing 6.1 would be called to perfo rm the frequency response calculations. Computations are made in the same manner as in Calc_Analog_Resp except the real and imaginary values are calculated using (6.28). Infinite Impulse Response Digital Filter Design 159 /*==================================================== Calc_DigIIR_Resp() - calcs response for IIR filters Prototype: int Calc_DigIIR_Resp(Filt_Params *FP, Resp_Params *RP); Return: error value Arguments: FP - ptr to struct holding filter params RP - ptr to struct holding respon params ====================================================*/ int Calc_DigIIR_Resp(Filt_Params *FP,Resp_Params *RP) { int c,f,q; /* loop counters */ double rad2deg, /* rad to deg conversion */ omega,omega2, /* radian freq and square */ rea,img; /* real and imag part */ rad2deg = 180.0 / PI; /* set rad2deg */ /* Loop through each of the frequencies */ for(f = 0 ;f < RP->tot_pts; f++) { /* Initialize magna and angle */ RP->magna[f] = FP->gain; RP->angle[f] = 0.0; /* Pre calc omega and omega squared */ omega = PI2 * RP->freq[f] / FP->fsamp; omega2 = 2 * omega; /* Loop through coefs for each quadratic */ for(q = 0 ;q < (FP->order+1)/2; q++) { /* c is coef index = 3 * quad index */ c = q * 3; /* Numerator values */ rea = FP->acoefs[c] + FP->acoefs[c+1]*cos(omega) + FP->acoefs[c+2]*cos(omega2); img = -FP->acoefs[c+1]*sin(omega) - FP->acoefs[c+2]*sin(omega2); RP->magna[f] *= sqrt(rea*rea + img*img); RP->angle[f] += atan2(img,rea); /* Denominator values */ rea = FP->bcoefs[c] + FP->bcoefs[c+1]*cos(omega) + FP->bcoefs[c+2]*cos(omega2); img = -FP->bcoefs[c+1]*sin(omega) - FP->bcoefs[c+2]*sin(omega2); RP->magna[f] /= sqrt(rea*rea + img*img); RP->angle[f] -= atan2(img,rea); } /* Convert to degrees */ RP->angle[f] *= rad2deg; } /* Convert magnitude response to dB if indicated */ if(RP->mag_axis == LOG) { for(f = 0 ;f < RP->tot_pts; f++) { /* Handle very small numbers */ if(RP->magna[f] < ZERO) { RP->magna[f] = ZERO;} RP->magna[f] = 20 * log10(RP->magna[f]); } } return ERR_NONE; } Listing 6.1 Calc_DigIIR_Resp function. 160 Practical Analog and Digital Filter Design 6.5 CONCLUSION In this chapter we investigated three di fferent methods of ge nerating digital IIR filters from analog transfer functions. In each case we found that there is no perfect match to the original analog functi on, primarily because there is a strict limit on the frequency range of a digital f ilter. However, the bilinear transform method does provide good overall response ch aracteristics, and for that reason it was chosen to be implemented in C code. (Details of this code are provided in Appendix G.) The frequency response charact eristics of the IIR filter were also considered, and the calculation of the response was implemented in C code. Finally, we used WFilter to design an IIR filter and display the complete magnitude response including the multiple replications of the original response. The implementation of IIR filters is discussed in Chapter 8. 161 Chapter 7 Finite Impulse Response Digital Filter Design In the last chapter, we considered the design of digital filters based on the approximation methods for analog filters. We investigated a number of ways that the transfer functions in the analog domain could be converted to transfer functions in the digital domain. In this chapter, we will develop methods that deal with the digital filter as a unique filter type, not based on analog filter approximation methods. The focus of this chapter will be on finite impulse response (FIR) filters that have only a fi nite number of terms in their impulse response. These filters have a number of advantages over the IIR filter types. An FIR filter is always stable, realizable , and provides a linear phase response under specific conditions. These characteristics make FIR filters attractive to many filter designers. However, the major disadvantage of FIR filters is that the number of coefficients needed to implement a specific filter is often much larger than for IIR designs. A more complete comparison of IIR and FIR filters is given in Section 8.1. We will begin this chapter with a st andard method of designing FIR digital filters using the Fourier series descripti on of the desired frequency response. This method will then be modified and impr oved by using a window ing technique to improve the shape of the responses. In a ddition, the Parks-McClellan optimization technique will be discussed as a technique of reducing the length of the resultant FIR filters. Finally, the C code for de termining the frequency response of FIR filters will be developed. 7.1 USING FOURIER SERIES IN FILTER DESIGN There are a number of methods that could be used to design FIR filters. We will investigate one of the most popular in this section. Other methods are described in the references listed in Appendix A for digital filter design. 162 Practical Analog and Digital Filter Design 7.1.1 Frequency Response and Impul se Response Coeffi cients In the process of filter design, the de signer begins with the frequency response characteristics. The critical band edge frequencies and the gains within each band are det ermined to meet certain speci fications. W e have found t hat the frequency response for digital filters is actually periodic in the frequency dom ain with a period of the sam pling freq uency. Fo r ex ample, a typ ical lo wpass filter speci fication is shown i n Figure 7.1, which clearly indicates the periodic nature of the frequency response. Si nce t his response is peri odic, it can be descri bed by a Fouri er series of t he form shown i n (7.1). In this fo rmulation, the co mplex frequency exponent ial is allowed t o take on al l possi ble frequency values. (7.1) ∑∞ −∞=Ω− Ω⋅ = kjk jekh eH )( )( Figure 7.1 Peri odic digital frequency response. The coeffi cients within the sum mation are t he impulse response coeffi cients that describ e the digital FIR filter. Th e procedure for determining the im pulse response coeffi cients from the frequency response i s straightforward and provi ded in the digital filter d esign referen ce tex ts listed in Appendix A. The final result of the derivation is shown in (7.2). As in dicated by the lim its of the integral, th e integration m ust include onl y one fu ll period of t he frequency response. … ,2 ,1 ,0 , )(21)( ±±=Ω⋅⋅ =∫+Ω −ΩΩΩn d e eH nho ojn jπ ππ (7.2) We will not be able to im plem ent an in finite num ber of coefficients as (7.2) indicates. The num ber of coefficients we retain is a com promise between how well we want our design to approxim ate the ideal, and how m any coefficients can be retained because of tim e delay, implem entation cost, or other constraints. W e can assum e that the indices are lim ited to the range −M ≤ n ≤ +M, which lim its the number of coefficients retained to N = 2 M + 1. B y making this selection, we are in effect setting all other coefficients to zero. Figure 7.2 shows the effect of Finite Impulse Response Digital Filter Design 163 limiting the num ber of coefficients by graphing the frequency response using a finite num ber of coefficients. The frequenc y response can be determ ined by using a modified form of (7.1), as shown in (7.3): (7.3) ∑ −=Ω− Ω⋅ =M Mnjn jenh eH )( )( As we increase the num ber of coefficien ts in the FIR filter approxim ation, we can see that a ripple concentrates near the passband edge frequency . This ripple cannot be elim inated, even by incr easing the num ber of impulse response coefficients; it sim ply concentrates at the transition. This effect is known as Gibbs’s phenom enon and results whenever a discontinuity is m odeled with a series. However, as we will see in the next section, there are m ethods we can use to reduce this effect. Figure 7.2 Approxim ated responses to lowpass filter. Figure 7.2 also shows a more common m ethod of specify ing passband and stopband gain for FIR filters. The erro rs within the passband and stopband are specified as δp and δs, respectively . As we can see, the frequency response is allowed to fluctuate both positively and ne gatively within these error lim its. We can translate these specifications into th e decibel gain specifications with which we are fam iliar by using (7.4) and (7.5). Alternatively, we can convert our decibel gains into these error values using (7.6) and (7.7). ) 1log(20pass p a δ−= (7.4) ) log(20stop s a δ= (7.5) 164 Practical Analog and Digital Filter Design (7.6) pass05.0101a p⋅−=δ (7.7) stop05.010a s⋅=δ As indicated earlier, the phase response of an FIR filter can be a linear function of frequency under certain conditions. For exam ple, if we assum e that frequency response within the passband of an FIR filter is as shown in (7.8), we are specify ing that the gain m ust be unity , while the phase angle changes linearly with frequency : (7.8) Ω−∠=⋅=Ω− Ωττ1 1) (passbandj je e H The necessary conditions that allow for this linear phase shift (or constant group delay ) are that the im pulse response coe fficients be either sy mmetric or antisym metric and that τ take on the value in (7.9) where N is the num ber of coefficients or the length of the filter. Th e filter coefficients are sym metric if they satisfy (7.10) and antisy mmetric if they satisfy (7.11). 21−=Nτ (7.9) )( )( nh nh−= (7.10) )( )( nh nh −−= (7.11) Perhaps it is tim e to say a few words about the difference between filter length and filter order. Analog and digital IIR filters use the order of the filter as a measure of the filter’s “size.” The order refers to the highest-order term in the polynomial equation used to describe the filter. On the other hand, digital FIR filters ty pically use the num ber of impulse response coefficients required to describe it as its “size.” This is probabl y because m ost FIR f ilters are im plem ented using convolution where the num ber of coeffi cients directly affects the length of the processing. Once the FIR coefficients are substituted into a difference equation (a little later in this section), we will see that the length of an FIR filter will sim ply be one larger than its order. Finite Impulse Response Digital Filter Design 165 7.1.2 Characteristics of FIR Filters When we consider symmetric and antisymme tric coefficients co mbined with even and odd filter lengths, four diffe rent types of FIR filters can be designed. Each of the four types has unique characteristics th at can be described briefly as follows. Type 1 FIR filters. The type 1 FIR filters, which have symmetric coefficients and odd length, also have a frequency response that has even symmetry about both Ω = 0 and Ω = π. This even symmetry allows the frequency response to take on any value at these two critical frequencie s, and thus lowpass, highpass, bandpass, and bandstop filters can be impl emented using this FIR type. Type 2 FIR filters. The type 2 FIR filters, which have symmetric coefficients and even length, have a frequenc y response that is even about Ω = 0 and odd about Ω = π. This condition dictates that the response at Ω = π be zero and thus type 2 FIR filters are not recomme nded for highpass or bandstop filters. Type 3 FIR filters. The type 3 FIR filters, which have antisymmetric coefficients and odd length, have a frequency response that has odd symmetry at both Ω = 0 and Ω = π. Because of the odd symmetry, the frequency response of this filter type must be zero at both of these two critical frequencies. Thus, this filter type is not recommended for lo wpass, highpass, or bandstop filters. However, this type of filter does provide a 90 ° phase shift of the output signal with respect to the input and therefore can be used to implement a differentiator or Hilbert transformer. This type of filter ha s other characteristics that make it the best choice for Hilbert transformation, while the differentiator is usually implemented using a type 4 filter. Type 4 FIR filters. The type 4 FIR filters, which have antisymmetric coefficients and even length, have a frequency response that has odd symmetry about Ω = 0 and even symmetry about Ω = π. The odd symmetry condition makes this type of filter a poor choice to impl ement either lowpass or bandstop filters. But, just as in the type 3 case, this filter provides a 90 ° phase shift that makes it able to implement differentiators and Hilber t transformers. This type of filter has better characteristics (in most cases) for im plementing a differentiator than type 3, but the type 3 filter has some advantages over this filter type for implementing the Hilbert transform. Since the type 1 FIR filter can be used to implement any of the filters we need to design, we will discuss only that type of filter from this point forward in this text. Further information concerning th e other filter types can be found in a number of the digital filter design references listed in Appendix A. The filter coefficients derived from (7.2 ) will not produce a causal filter. This means that the system could not be implemen ted in real time. We can verify this if we consider the output of a discrete-tim e system produced by the convolution of the input signal with the impulse response coefficients as shown in (7.12). Notice that the output y(n) becomes only a function of the input x(n) and does not include any past values of the output as in the IIR filter case. 166 Practical Analog and Digital Filter Design (7.12) ∑ −=−⋅ =M Mkknxkh ny ) ()( )( As we see, using the im pulse response coefficients directly will result in y(n) being determ ined by future values of the input. For exam ple, when k = −M, the summation includes a term x(n + M) that refers to an input value M sam pling periods ahead of y(n)’s reference time. The problem can be handled by shifting all coefficient values to the right on the tim e axis so that only positive values of n produce coefficients, as shown in Figure 7.3. The disadvantage of this action is to increase the tim e delay between sy stem input and output by M sampling periods. Figure 7.3 (a) Noncausal and (b) causal coefficients. The causal coefficients can be determ ined from the noncausal coefficients by making the following index adjustm ents. As the noncausal coefficients indices take on values from −M to + M, the causal coefficient indices will take on values from 0 to 2 M, as shown in (7.13): M nn h Mn h ±± =+ , ,1 ,0 = , )( ) (noncausal causal … (7.13) 7.1.3 Ideal FIR Impulse Response Coefficients We can now determ ine the ideal coefficien ts for various filter ty pes by using the integral form ula of (7.2). In each case, figures depicting ideal lowpass, highpass, Finite Impulse Response Digital Filter Design 167 bandpass, and bandstop filters along w ith equations for determ ining the coefficients based on the param eters of the particular filter are given. The frequency response in the passband of each f ilter is as defined in (7.8) and allows us to determ ine causal coefficients direc tly. We will be assum ing that the desired passband m agnitude response is 1, while the stopband response is 0. We will be using δp and δs (or apass and astop) later to help determ ine the required length of the filter. In the first case, Figure 7.4 illustrates the lowpass filter specification with the resulting derivation of the lowpass filter coefficients shown in (7.14) and (7.15). The highpass, bandpass, and ba ndstop filter cases are portray ed respectively in Figures 7.5 to 7.7 with the appropriate de rivations in (7.16) to (7.21). In each case, τ = M as determ ined from (7.9). Example 7.1 Determining Ideal Coefficients for an FIR Filter Problem: Determ ine the ideal impulse response coefficients for a lowpass filter of length 21 to satisf y the following specifications: ωpass = 2π⋅3,000 rad/sec, ωstop = 2π⋅4,000 rad/sec, and fs = 20 kHz Solution: We first need to determ ine Ωc, the cutoff frequency for the ideal filter. This frequency can be set in the middle of the transition band and converted to a digital frequency : sec/rad 0996.1) 2/() (pass stop =⋅ +=Ωs c f ωω Using this value along with τ = 10 in (7.15), we can determ ine the following ideal causal coefficients: 03183.0 )20( )0(01606.0 )19( )1(02339.0)18( )2(04491.0)17( )3(01639.0)16( )4(04502.0 )15( )5(07568.0 )14( )6(01660.0 )13( )7(12876.0)12( )8(28362.0)11( )9(35000.0)10( −==−========−==−==−======= h hh hh hh hh hh hh hh hh hh hh 168 Practical Analog and Digital Filter Design Figure 7.4 Lowpass filter specification. M nd e n hc cnj LP 2 , ,1 ,0 ,21)() ( …=Ω⋅ =∫Ω+ Ω−Ω−τ π (7.14) [] M nnnnn nh cc LP 2 , ,1 ,0 = for ,/for ,) () (sin )( …=⎪⎪ ⎩⎪⎪ ⎨⎧ Ω≠−Ω− = τ πτπττ (7.15) Figure 7.5 Highpass filter specification. M nd e d e n h cc nj nj HP 2 , ,1 ,0 + 21)() ( ) ( …=⎥⎥ ⎦⎤ ⎢⎢ ⎣⎡ Ω⋅ Ω⋅ = ∫ ∫+ ΩΩ−Ω− −Ω−π τ πτ π (7.16) [][] M nnnnn n nh cc HP 2 , ,1 ,0 = for ,/)-(for ,) () (sin ) (sin )( …=⎪⎪ ⎩⎪⎪ ⎨⎧ Ω≠−Ω−−− = τ ππτπττ πτ (7.17) Finite Impulse Response Digital Filter Design 169 Figure 7.6 Bandpass filter specification. M nd e d e n hc cc cnj nj BP 2 , ,1 ,0 + 21)(2 11 2) ( ) ( …=⎥⎥ ⎦⎤ ⎢⎢ ⎣⎡ Ω⋅ Ω⋅ = ∫ ∫Ω+ Ω+Ω−Ω− Ω−Ω− τ τ π (7.18) [][] M nnnnn n n h cc c BP 2 , ,1 ,0 for ,/) (for ,) () (sin ) (sin )( 1 c21 2 …=⎪⎪ ⎩⎪⎪ ⎨⎧ = Ω−Ω≠−Ω−−Ω− = τ πτπττ τ (7.19) Figure 7.7 Bandstop filter specification. M nd e d e d e n h cc cc nj nj nj BS 2 , ,1 ,0 + + 21)( 21 12 ) ( ) ( ) ( …=⎥⎥ ⎦⎤ ⎢⎢ ⎣⎡ Ω⋅ Ω⋅ Ω⋅ = ∫ ∫ ∫+ Ω+Ω−Ω+ Ω−Ω−Ω− −Ω−π τ τ πτ π (7.20) [][][] M nnnnn n n nh cc c BS 2 , ,1 ,0 = for ,/) + ( for ,) () (sin ) (sin ) (sin )( 1 c21 2 …=⎪⎪ ⎩⎪⎪ ⎨⎧ ΩΩ−≠−Ω−+Ω−−− = τ π πτπττ τ πτ (7.21) 170 Practical Analog and Digital Filter Design 7.2 WINDOWING TECHNIQUES TO IMPROVE DESIGN As indicated in the previous section, we are not able to include the infinite num ber of coefficients necessary to im plem ent an ideal filter. W e will have to reduce the number of coefficients used based on the c onstraints of our design. In the previous section, we sim ply truncated all non causal coefficients bey ond the indices ±M and kept the rest. (W e will use the noncausal de scription of the filter coefficients for mathem atical sim plicity at this point . After the windowing process has been completed, we can shift the resulting coeffi cients to produce a causal filter.) This procedure can be com pared to placing a window of width N = 2 M + 1 over all of the ideal coefficients, as shown in Figure 7.8. All of the coe fficients within the window are retained and all coefficients outside of the window are discarded. In effect we have produced a rectangular “window” function in which all window coefficients with indices within the range of the window have a value of 1 and all other coefficients have a value of 0. The re tained values of the filter coefficients would then be determ ined by perfo rming a coefficient-by-coefficient multiplication of the ideal coefficients and the window coefficients, as indicated in (7.22): M nnwn hnh ±± ⋅= , ,1 ,0= ,)()( )(ideal … (7.22) The rectangular window coefficients can be form ally defined in (7.23). However, the abrupt truncation of the filte r coefficients has an adverse effect on the resulting filter’s frequency response. Therefore, a num ber of other window functions have been proposed which sm oothl y reduce the coefficients to zero. For exam ple, a sim ple triangular window (also called the B artlett window) as shown in Figure 7.9 would sm ooth the truncati on process. An expression for these window coefficients is given in (7.24), where M = (N − 1 ) / 2. Figure 7.8 Window selection of coefficients. M n n w n w , ,1 ,0= ,1)( )(rect rect … =−= (7.23) Finite Impulse Response Digital Filter Design 171 M nMnMn wn w , ,1 ,0= ,) ()( )(bart bart …−=−= (7.24) Many window functions have been ba sed on the raised cosine function including the von Hann, Ham ming, and Blackm an windows. Graphs of those windows are also shown in Figure 7.9 with the m ethod of coefficient calculation for each window function provided in (7.25) to (7.27). Figure 7.9 Bartlett, B lackm an, Ham ming, and von Hann windows. M nMn Mn w n w , ,1 ,0=,) (cos15.0)( )(hann hann …⎭⎬⎫ ⎩⎨⎧ ⎥⎦⎤ ⎢⎣⎡−⋅−=−=π (7.25) M nMn Mn w n w , ,1 ,0=, ) (cos46.0 54.0)( )(hamm hamm …⎥⎦⎤ ⎢⎣⎡−⋅⋅−=−=π (7.26) M nn w n wMn M Mn Mn w , ,1 ,0= ),( )( and ) (2cos08.0) (cos5.0 42.0)( blck blckblck … −=⎥⎦⎤ ⎢⎣⎡−⋅⋅+⎥⎦⎤ ⎢⎣⎡−⋅⋅−=π π (7.27) As m ore tim e was spent try ing to im prove the window functions used in FIR filter design, it becam e apparent for a fixe d length of filter that there was a trade- 172 Practical Analog and Digital Filter Design off between transition band roll-off and attenuation in the stopband. One of the window functions that developed because of this fact was the Kaiser window function, as shown in Figure 7.10. The expression for the window coefficients as given in (7.28) is based on the m odified B essel function of the first kind Io. The value β generally ranges from 3 to 9 and can be used to control the trade-off between the transition band and stopband characteristics. Figure 7.10 Kaiser windows with various β values. () M nIMnI n w n w oo , ,1 ,0=, 21 )( )(2 kais kais …ββ⎥⎥ ⎦⎤ ⎢⎢ ⎣⎡ ⎟ ⎠⎞⎜ ⎝⎛⋅−⋅ =−= (7.28) A reasonable estim ate of β in the equation above has been determ ined empirically by Kaiser, as shown in (7.29): (7.29) ⎪⎩⎪⎨⎧ <≤≤ −⋅+−⋅> −⋅ = 21 for ,0.050 21for ),21 ( 078860 )21 ( 5842050 for )78( 11020 40 AA A . A . A , . A . .β In (7.29), the variable A represents the larger of the band errors ( δp or δs) expressed as attenuation, as shown in (7.30): Finite Impulse Response Digital Filter Design 173 )], log[min(20s p A δδ⋅−= (7.30) In addition, Kaiser developed em pirical estim ates of the filter length required to satisfy a given set of filter specificati ons, as indicated in (7.31). It should be emphasized here that FIR filter design is not as precise as IIR design. The truncation/m odification of co efficients results in responses that m ay or may not meet the requirem ents. Therefore, the N value of (7.31) is just an estim ate and the filter responses m ust be checked carefully to determ ine if all requirem ents are m et. If they are not, the value on N should be adjusted (usually up, but som etimes decreasing N can result in a better filter). ⎪ ⎩⎪ ⎨⎧ ∆Ω∆Ω⋅− = 21< for ,794.521> for ,285.295.7 AAA N (7.31) In (7.31), ∆Ω represents the norm alized radi an transition band for lowpass and highpass filters and the sm aller of th e two norm alized transition bands in the case of bandpass and bandstop filters. sf/pass stopωω−=∆Ω (7.32) Once the desired window function has b een selected and the adjustm ents made to the ideal coefficients, the causa l coefficients can be determ ined as indicated in the previous section. Example 7.2 Determining Hamming Coefficients for an FIR Filter Problem: Determ ine the coefficients for a lowpass filter using a Ham ming window of length 21 to satisfy the specifications shown below: ωpass = 2π⋅3,000 rad/sec, ωstop = 2π⋅4,000 rad/sec, and fs = 20 kHz Solution: The ideal coefficients have been determ ined in Exam ple 7.1. We can use (7.24) to determ ine the non causal Ham ming window coefficients as shown. After m ultiplication and shifting th e coefficients by 10 sam pling periods, the causal windowed coefficients result. Figure 7.11 shows the frequency response for both Exam ples 7.1 and 7.2. The rectangular window produces a filter that emphasizes transition band roll-off over ripple in the stopband. On the other hand, the filter produced by using Ham ming coefficients has no noticeable ripple, but does not have a rapid roll-off in the transition band. 174 Practical Analog and Digital Filter Design 0800.0)10( )10(10251.0)9( )9(16785.0)8( )8(26962.0)7( )7(39785.0)6( )6(54000.0)5( )5(68215.0)4( )4(81038.0)3( )3(91215.0)2( )2(97749.0)1( )1(0000.1)0( =−==−==−==−==−==−==−==−==−==−== w ww ww ww ww ww ww ww ww ww ww 00255.0 )20( )0(00165.0 )19( )1(00393.0)18( )2(01211.0)17( )3(00652.0)16( )4(02431.0 )15( )5(05163.0 )14( )6(01345.0 )13( )7(11745.0)12( )8(27723.0)11( )9(35000.0)10( −==−========−==−==−======= h hh hh hh hh hh hh hh hh hh hh Figure 7.11 Magnitude responses for Exam ples 7.1 and 7.2. Example 7.3 Determining Kaiser Coefficients for an FIR Filter Problem: Determ ine the im pulse response coefficients for a bandpass filter using a Kaiser window to satis fy the following specifications: fpass1 = 4 kHz, fpass2 = 5 kHz, fstop1 = 2 kHz, fstop2 = 8 kHz, apass1 = −0.5 dB , astop1 = astop2 = −50 dB , and fsamp = 20 kHz Solution: The solution to this problem begi ns with the determ ination of the passband and stopband errors δp and δs by using (7.6) and (7.7). Finite Impulse Response Digital Filter Design 175 055939.0 101025.0= −=− pδ 0031623.0 105.2==− sδ We can then use (7.29), (7.30), and (7.32) to find A = 50, β = 4.53351, and ∆Ω, where sec/rad 6263185.0000,20)000,2 000,4( 2 lower =−⋅⋅= ∆Ωπ sec/rad 9424778.0000,20)000,5 000,8( 2 upper =−⋅⋅= ∆Ωπ Equation (7.31) can then be used to estim ate the sm allest odd filter length as N = 31. Equation (7.17) can be used to de termine the ideal filter coefficients after finding the values of τ = 15 and calculating Ωc1 and Ωc2, as shown below. sec/rad 942478.0000,202)000,4 000,2( 2 1 =⋅+⋅⋅=Ωπ c sec/rad 042035.2000,202)000,8 000,5( 2 2 =⋅+⋅⋅=Ωπ c The Kaiser window coefficients can be determ ined by using (7.28). The final coefficients can be calculated by m ultiplying the ideal coefficients by the respective window coefficients and shifting all coefficient indices by a value of M = 15. Rather than perform all of the num erical calculations by hand, we can use WFilter to finish the design of this filte r. One addition to the design process for FIR filters is the indication of the filter length and an option to change the length if desired. Since the determ ination of filte r length is not an exact calculation, this option allows the user to in crease or decrease the length as necessary to satisfy the design. Figure 7.12 shows the FIR Estima ted Leng th dialog box, which includes an estim ate of the filter length and the value of β. 176 Practical Analog and Digital Filter Design Figure 7.12 FIR Estim ated Length dialog box. Figure 7.13 shows the coefficient screen with the final filter coefficients display ed. They are display ed in causal form , and are sy mmetric about the center value. The m agnitude response of the filte r is shown in Figure 7.14 and verifies that the specifications have been satisfied. FIR Bandpass with Kaiser Window Selectivity: Bandpass Approximation: Kaiser Implementation: FIR (digital) Passband gain (dB): -0.5 Stopband gain (dB): -50.0 PB freq-lower (Hz): 4000.0 PB freq-upper (Hz): 5000.0 SB freq-lower (Hz): 2000.0 SB freq-upper (Hz): 8000.0 Sampling freq (Hz): 20000.0 Filter Length/Order: 31 Overall Filter Gain: 1.00000000000E+00 Coefficients N [ N + 0 N + 1 ] === ===================================== 000 -2.01201050092E-03 -2.01616077587E-03 002 4.85062961990E-03 2.08877721763E-03 004 2.97741355116E-03 1.17872058678E-02 006 -2.03738740194E-02 -3.33459478620E-02 008 1.95330807169E-02 1.06179366366E-02 010 1.48522876861E-02 1.06004616317E-01 012 -4.55615841929E-02 -2.70313807850E-01 014 2.58671686944E-02 3.50000000000E-01 016 2.58671686944E-02 -2.70313807850E-01 018 -4.55615841929E-02 1.06004616317E-01 020 1.48522876861E-02 1.06179366366E-02 022 1.95330807169E-02 -3.33459478620E-02 024 -2.03738740194E-02 1.17872058678E-02 026 2.97741355116E-03 2.08877721763E-03 028 4.85062961990E-03 -2.01616077587E-03 030 -2.01201050092E-03 Figure 7.13 Coefficient values for Exam ple 7.3. Finite Impulse Response Digital Filter Design 177 7.3 PARKS-MCCLELLAN OPTIMIZ ATION PROCEDURE As we can see in Figure 7.14 for the f ilter using the Kaiser window, the stopband has ripple that generally decreases. In f act, if the passband characteristic were magnified, we would see ripple there as well. B oth the passband and stopband ripple (error) tend to be larger near the transition bands and then taper off as the response moves away from the band edge. This ty pe of response is not optim um. An optim um filter would have ripple in the passband and stopband with a constant maximum magnitude. The error would still be present but would be distributed equally throughout the bands. Figure 7.14 Magnitude response for Exam ple 7.3. In this section, we discuss a method for designing FIR filters with this characteristic. The Parks-M cClellan algorith m, as it is generally known, was first presented over 20 y ears ago. Although the basic procedure has rem ained the sam e, a number of im plem entation techniques have changed. A detailed description of the Parks-M cClellan (PM ) algorithm is bey ond the scope of this text, but a general overview of the procedure is appropriate. In addition, a review of the com mented filter design code (as introduced in the next section) provides further implem entation details. (Several of the texts listed in the digital filter design section of Appendix A provide m ore deta iled descriptions of the PM algorithm , with the text by Antoniou providing a particularly detailed description.) 7.3.1 Descri ption of the Probl em A primary component of the PM algorithm is a technique called the R emez exchange algorithm . But before we can use the power of the Rem ez algorithm to optim ize our FIR filter coefficients, we m ust redefine our problem in such a way 178 Practical Analog and Digital Filter Design that the solution requires the m inimization of an error function. To that end, we first define the frequency response of an odd-order FIR filter with symmetrical coefficients h(n), as shown in (7.33): (7.33) ∑ ∑ =−− =−⋅ =⋅=M mMjN nnj jm mc e enh eH 01 0) cos()( )( )( ωω ω ω where M = (N − 1) / 2 and (7.34) ⎩⎨⎧ ⋅=M m mMhm Mhmc , ,2 ,1= for ),-(2 ,0= for ,)()(… We can then define the sum mation com ponent of (7.33) as (7.35) ∑ =⋅ =M mm mc C 0) cos()( )( ω ω which is used to form ulate the error function that will be the obj ect of the minimization. As shown in (7.36), the e rror function can be described in terms of the desired frequency response e−jωM D(ω), the actual frequency response e−jωM C(ω), and a weighting function W(ω) that can be used to adjust the amount of error in each filter band: [ ])( )()( )( ωωωω C D W E −⋅= (7.36) The desired frequenc y response function D(ω) is usually defined as being 1 within the passband of the filter and 0 within the stopband, although other values can be assigned. The weighting function W(ω) can be defined equivalently throughout the filter band, or it can be a ssigned a value of 1 within the passband and 10 within the stopband if a sm aller error value δ is desired in the stopband. This result occurs because the m inimization algorithm will produce equal am ounts of error throughout the defi ned frequency range, and si nce the stopband error has been artificially increased by 10, the actual error will be 10 tim es sm aller. The optim um error function will produce variations within the passband and stopband sim ilar to those shown in Figure 7. 2 (except that all ripple will be of the same magnitude). The actual error func tion will alternate between positive and negative δ values because of the sum mation of co sine functions. If we pick a set of frequencies ( x = M + 1) at which the extrem es of the error occur, (7.36) can be written as Finite Impulse Response Digital Filter Design 179 [ ] , ,1 ,0= for ,)1()( )()( )( x iC D W Ei i i i i …δ ωωωω −=−⋅= (7.37) Equation (7.37) can be expanded into a matrix equation by considering these x+1 frequencies, which are typically called ex tremals and play a crucial role in the optim ization process. ()⎥⎥⎥⎥ ⎦⎤ ⎢⎢⎢⎢ ⎣⎡ = ⎥⎥⎥⎥⎥⎥ ⎦⎤ ⎢⎢⎢⎢⎢⎢ ⎣⎡ ⋅ ⎥⎥⎥⎥⎥⎥⎥⎥⎥⎥ ⎦⎤ ⎢⎢⎢⎢⎢⎢⎢⎢⎢⎢ ⎣⎡ −− )()()( )()1()0( )(1cos cos1)(1cos cos1)(1cos cos1 10 11 100 0 x xx x xDDD Mccc WMWMWM ωωω δ ωω ωωω ωωω ω ## "# #%##"" (7.38) In (7.38), ω0 – ωx represents the extrem al frequencies and δ is the error. W ith this expression the filter design problem has been set into a form that can be manipulated by the Rem ez exchange algorithm . 7.3.2 The Remez Exchange Algorithm The Rem ez exchange algorithm is a pow erful procedure that uses iteration techniques to solve a variety of m inimax problem s. (A m inimax problem is one in which the best solution is the one that minimizes the m aximum error that can occur.) Before initiating the process, a se t of discrete frequenc y points is defined for the passband and stopband of the filter. (Transition bands are excluded.) This dense grid of frequencies is used to re present the continuous frequency spectrum . Extrem al frequencies will then be located at particular grid frequencies as determ ined by the algorithm . The basic step s of the m ethod as it is applied to our filter design problem are shown below. Remez Exchange Algorithm I. Make an initial guess as to the location of x + 1 extrem al frequencies, including an extrem al at each band edge. II. Using the extrem al frequencies, estim ate the actual frequency response by using the Lagr ange interpolation form ula. III. Locate the points in the frequency response where m aximums occur and determ ine the error at those points. IV. Ignore all new extrem als beyond the num ber initially set in I. 180 Practical Analog and Digital Filter Design V. If the difference between the maximum and minimum error at the remaining extremal is small enough, continue to VI. Otherwise return to II using the retained extremals. VI. Estimate the final frequency response and determine the c(m) values from it. Then determine the impulse response coefficients. Each step in the procedure can be im plemented in a variety of ways. These variations can produce differences in th e speed of executing the algorithm, but usually little difference in accuracy is noticed. The simplest method of implementing step I is to assign the x + 1 extremal frequencies such that they are equally spaced throughout the bands of intere st. Extremals are usually placed at all band edges that are adjacent to trans ition bands. The initial band and final band may not have extremals located at their te rminal edges. The barycentric form of the Lagrange interpolation formula (as desc ribed in the mathematical references in Appendix A) is then used to determin e the frequency response on the dense grid of frequencies. This method is much more efficient and accurate than the alternative method of finding the c(m) values in (7.37) by matrix inversion. Once the frequency response has been determined , the true extrema can be located and the error at these locations calculated. (V arious methods can be used to locate the extrema, usually differing in speed and complexity.) These new frequency points will be used as the new extrema in the next iteration. It is not unusual to find more extrema in the frequency response than will be needed to characterize the final frequenc y response. Therefore, some means is necessary to reduce the number of retained frequencies to x + 1. Again, there are variations on this procedure, but the gene ral consensus is to retain the extremals that produce the largest error. In step V, we check the difference between the largest and smallest error produced at the retained extremals. By using this value as a progress indicator, we can set some threshold to indicate when the procedure has produced the required level of optimi zation. If the differences between the minimum and maximum errors have not been reduced enough, the algorithm continues from step II. When the optimization procedure has reached the desired threshold, the extremal frequencie s can be used to determine the c(m) values in (7.37) and therefore the impulse response coefficients h(n) from (7.34). 7.3.3 Using the Parks-McClellan Algorithm The general algorithm has great flexibility in designing any of the four types of FIR filters discussed earlier. The code that is included with this text will design lowpass, highpass, bandpass, and bandstop type 1 filters (with an odd number of symmetrical coefficients). The code is written so that other filter types can be implemented by adding to the program st ructure. In order to use the general algorithm, we must first convert our filter specifications into those needed by the algorithm. This amounts to converting gain requirements for decibels to absolute error and some redefi nition of frequencies. Finite Impulse Response Digital Filter Design 181 As in the Kaiser window case, an em pirical form ulation of the required length of an FIR filter designed using the PM algorithm has been developed, as shown in (7.39). Although som ewhat extensive in its presentation, it does provide an accurate estim ate of the required length. 12 2 1+∆∆⋅−=ff K KN (7.39) where (7.40) ] 42781.0 log 5941.0) (log 00266.0[ log] 4761.0 log 07114.0) (log 005309.0[ 22 1 +⋅+ ⋅ −⋅−⋅ + ⋅ = p ps p p K δ δδ δ δ 012.11) log (log 51244.02 +−⋅ =s p K δδ (7.41) sf f f f /) (pass stop−=∆ (7.42) Example 7.4 Determining Parks-McCl ellan Coefficients for FIR Filter Problem: Determ ine the im pulse response coefficients for a bandpass filter using the sam e specifications as in Exam ple 7.3 (as indicated below), except use the Parks-McClellan algorithm for coefficient determ ination. fpass1 = 4 kHz, fpass2 = 5 kHz, fstop1 = 2 kHz, fstop2 = 8 kHz, apass = −0.5 dB , astop1 = astop2 = −50 dB , and fsamp = 20 kHz Solution: We will use the W Filter program for this exam ple. The sam e input param eters as in the previous exam ple are specified, except the approxim ation type has been changed to Parks-M cClellan. Using the specified param eters, the first design attem pt resulted in an estim ated length of 19, which produced a filter with passband edge gains of −0.54 dB and stopband edge gains of −49.38 dB . These values are certainly very close to the design specifications and might be acceptable in m any designs. However, for com parison purposes, the filter was redesigned using a filter length of 21 and produced passband gains of −0.23 dB and stopband gains of −56.70 dB . The resulting coe fficients and frequency response curve are shown in Figures 7.15 and 7.16. We should notice the equal ripple in th e stopbands for the PM filter and the fact that it is im plem ented in one-third fewe r coefficients than the Kaiser filter. As a com parison to IIR filters, a sixth-order elliptic or an eighth-order Butterworth 182 Practical Analog and Digital Filter Design filter would be required to satisfy the same specifications, but without linear phase. FIR Bandpass using Parks-McClellan Procedure Selectivity: Bandpass Approximation: Parks-McClellan Implementation: FIR (digital) Passband gain (dB): -0.5 Stopband gain (dB): -50.0 PB freq-lower (Hz): 4000.0 PB freq-upper (Hz): 5000.0 SB freq-lower (Hz): 2000.0 SB freq-upper (Hz): 8000.0 Sampling freq (Hz): 20000.0 Filter Length/Order: 21 Overall Filter Gain: 1.00000000000E+00 Coefficients N [ N + 0 N + 1 ] === ===================================== 000 1.25270567042E-02 1.19473087473E-03 002 -3.33680410407E-02 -4.33317885804E-03 004 1.22816612467E-02 8.32245424391E-03 006 1.02738836518E-01 -8.97234696493E-03 008 -2.68080507538E-01 4.01012968419E-03 010 3.48822141957E-01 4.01012968419E-03 012 -2.68080507538E-01 -8.97234696493E-03 014 1.02738836518E-01 8.32245424391E-03 016 1.22816612467E-02 -4.33317885804E-03 018 -3.33680410407E-02 1.19473087473E-03 020 1.25270567042E-02 Figure 7.15 Coefficient values for Exam ple 7.4. Figure 7.16 Magnitude response for Exam ple 7.4. Finite Impulse Response Digital Filter Design 183 7.3.4 L imitations of the Parks-McCl ellan Algorithm The Parks-McClellan algorithm is certainly an attractive FIR filter design method, but it does have certain lim itations in comparison to window-based design methods. The Kaiser window design is basically a one-pass sy stem, although some variation of filter length m ay be nece ssary to attain the desired specification (as is also the case for the Parks-Mc Clellan procedure). The com putational intensity of the PM method is far greater than for any of the window m ethods, but computational power is also more readily available than it was 10 years ago. Probably the biggest problem with th e PM algorithm is that it does not always lead to a solution. In som e cases, the ite ration sequence will not converge, which makes it necessary to place an upper lim it on the num ber of iterations allowed. The algorithm can be m odified to allow th e frequency grid to be m ade more dense and to initiate the algorithm again if th is happens. Nonetheless, there will be occurrences when the problem statem ent w ill need to be redefined in order to attain convergence. For exam ple, if th e two stopbands of a bandpass filter are not of approxim ately equal size, one can be artificially reduced to help the convergence process. Occasionally, the e rror constraints on the filter m ust be adjusted to allow m ore freedom in the optimization process. Ev en if the process converges, the frequency response of th e resulting filter m ust be checked carefully. Since no requirem ents are placed on the frequency within the transition bands, strange results can som etimes occur. 7.4 C CODE FOR FIR FREQ UENCY RESPONSE CALCULATION Our last task is to determ ine the frequency response of the filter. As determ ined in Chapter 5, the frequency response of a digital filter can be determ ined from the transfer function, as shown in (7.43): Ω=Ω= jezjzH eH )( ) ( (7.43) For a causal FIR filter, the transfer function can be described in (7.44), which then leads to the description for th e frequency response shown in (7.45): (7.44) ∑− =−⋅=1 0)( )(N kkzkh zH (7.45) ∑− =Ω− Ω⋅=1 0)( )(N kjk jekh eH 184 Practical Analog and Digital Filter Design Equation (7.45) can also be expressed as a sum of the real and im aginary portions of the exponential as in (7.46). The Calc_DigFIR_Resp function implem ents (7.46) directly , as shown in Listing 7.1. (7.46) ∑ ∑− =− =ΩΩ⋅ +Ω⋅=1 01 0) sin()( ) cos()( )(N kN kjk khj k kh eH /*==================================================== Calc_DigFIR_Resp() - calcs response for FIR filters Prototype: int Calc_DigFIR_Resp(Filt_Params *FP, Resp_Params *RP); Return: error value Arguments: FP - ptr to struct holding filter params RP - ptr to struct holding respon params ====================================================*/ int Calc_DigFIR_Resp(Filt_Params *FP,Resp_Params *RP) { int f,i; /* loop counters */ double rad2deg, /* rad to deg conversion */ omega,i_omega,/* radian freq and incrmnt */ mag, /* magnitude of freq resp */ rea,img; /* real and imag part */ rad2deg = 180.0 / PI; /* set rad2deg */ /* Loop through each of the frequencies */ for(f = 0 ;f < RP->tot_pts; f++) { /* Initialize magna and angle */ RP->magna[f] = FP->gain; RP->angle[f] = 0.0; /* Pre calc adjusted omega, rea and img */ omega = PI2 * RP->freq[f] / FP->fsamp; rea = 0.0; img = 0.0; /* Loop through all the coefs */ for(i = 0 ;i < FP->order; i++) { i_omega = i * omega; rea += FP->acoefs[i] * cos(i_omega); img += FP->acoefs[i] * sin(i_omega); } /* Calc final result and conv to degrees */ mag = sqrt(rea*rea + img*img); RP->magna[f] *= mag; /* Guard against atan(0,0) */ if(mag > 0) { RP->angle[f] += atan2(img,rea);} RP->angle[f] *= rad2deg; } /* Convert magnitude response to dB if indicated */ if(RP->mag_axis == LOG) { for(f = 0 ;f < RP->tot_pts; f++) { /* Handle very small numbers */ if(RP->magna[f] < ZERO) { RP->magna[f] = ZERO;} RP->magna[f] = 20 * log10(RP->magna[f]); } } return ERR_NONE; } Listing 7.1 Calc_DigFIR_Resp function. Finite Impulse Response Digital Filter Design 185 The magnitude variable is initialized to the value of the gain constant, and the angle variable is set to zero. Then, the response at each frequency is determined by evaluating the effect of each filter coeffici ent. The angle is converted to degrees, and after all calculations have been made, the magnitude is converted to decibels if the user requested that format. 7.5 CONCLUSION By completing this chapter, we have completed the material on digital filter design. We investigated two of the most popular methods of FIR filter design: the Fourier series method us ing window functions and the Parks-McClellan optimization method. We can also determ ine and display the magnitude and phase response of the FIR filters we design. In the next chapter we will investigate the implementation of both the FIR and IIR dig ital filters we have designed. For those interested in the C code for FIR filte r design, please refer to Appendix H. 186 Practical Analog and Digital Filter Design 187 Chapter 8 Digital Filter Implementation Using C In the previous three chapters we discussed the nature of digital filter design. We are now ready to discuss the implementation of these digital filters. We begin this chapter with a discussion of several important issues in digital filter selection and implementation. These issues include the differences between real-time and nonreal-time implementation, as well as the effects of finite precision representation of input signals and filter co efficients. Then, we discuss the C code for implementing IIR and FIR filters. Efficient algorithms will be developed to increase the speed of execution. Each filter type will use a different technique appropriate to the specific filter’s representation. Finally, we conclude with a discussion of the format for a popular s ound file on the PC. We will consider how we can use sound files to investigate the characteristics of the filters we have designed. 8.1 DIGITAL FILTER IMPLEMENTATION ISSUES The first decision to make when designing a system with a digital filter is whether an IIR or FIR filter should be used. Some of the advantages and disadvantages of each type have been discussed in the pr evious two chapters, so we will summarize those points here. First, and foremost, the correct filter type must be determined by the requirements of the application. IIR (recursive) filters have the advantages of providing higher selectivity for a particular order and a closed form design technique that doesn’t require iteration. The design technique also provides for the rather precise solution to the specifications of gain and edge frequencies. However, IIR filters also have the disadvantages of nonlinear phase characteristics and possible instability due to poor implem entation. FIR (nonrecursive) filters, on the other hand, can provide a linear phase response (constant group delay) that is important for data transmission and high-quality audio systems. Also, they are always stable because they are implemen ted using an all-zero transfer function. Since no poles can fall outside the unit circle, the filter will always be stable. But 188 Practical Analog and Digital Filter Design because of this, the order of the filter is much higher than the IIR filter, which has a comparable magnitude response. This higher order leads to longer processing times and larger memory requirements. In addition, FIR filters must be designed using an iterative method since the require d filter length to satisfy a given filter specification can only be estimated. Therefore, the filter designer must weigh the requirements placed on the digital filter. If great importance is pl aced on magnitude response with much less importance on phase response, then an IIR filter would seem the better choice. If phase response is far more important than magnitude response, then an FIR filter is in order. If both magnitude and phase response seem to be of equal concern, then the processing time constraints and memory requirements must be considered. The FIR filter, even when designed using the Parks-McClellan method, will require more processing time and more memory to implement, but always will be stable. If all else fails, both an FIR and IIR filter (with some phase correction) can be designed to meet the specifications and they both can be tested to evaluate the results. Once the choice of filter type has been made, there are still a number of decisions to make. For example, is the syst em to operate in real-time or can it be a nonreal-time system? A real-time system is one in which input samples are provided to the digital filter and must be processed to provide an output sample before the next input sample arrives. Obviously, this puts a very precise time constraint on the amount of processing available to the system. The higher the sampling frequency, the less time is available for processing. On the other hand, some systems are afforded the luxury of being able to operate in nonreal time. For example, signals can be recorded on tape or other media and processed at a later time. In this type of system, extensive processing can take place because there is no fixed time interval that marks the end of the processing time. In nonreal-time applications, high-precision floating-point representation for the coefficients and signal can usually be used since speed is not the critical factor. However, the majority of digital filter applications will be real-time applications. In these applications there will inevitably be a battle to obtain the highest accuracy, the fastest speed, and the lowest-cost system. One of the first decisions to make is whether the system will be a fixed-point or a floating-point system. This deals not only with the input and output signal streams, but also the representation of the coefficients and intermediate results within the processing unit. 8.1.1 Input and Output Signal Representation Fixed point systems represent a large market in today’s digital signal processing arena. Many analog-to-digital (A/D) converters are available to provide output in a fixed-point representation. Although many input and output digital signals use fixed-point representation, there are severa l ways in which the same signals can be interpreted. Most people are familiar with the base 10 system that humans use, but the digital computers of the world use a binary or base 2 system. In that system, Digital Filter Implementation Using C 189 each digit represents a m ultiplier of a power of 2 j ust as each digit in the decim al or base 10 system represents a m ultiplier o f a power of 10. Let’s start with an 8-bit binary num ber shown bel ow: (8.1) 103 4 7 2 152 21 21 21 10011000 =⋅+⋅+⋅= This binary num ber i s equi valent to 152 10 only when we assum e that the number is unsigned (rep resents only positive numbers). If we h ad considered the binary num ber as si gned, t he leftmost 1 woul d have indicated a negat ive sign, and the val ue woul d have been i nterpret ed different ly. Using two’s complement arithmetic, we can determine the value of the number in (8.1) by first n egating every digit in the number and t hen addi ng one t o the resul t. That value is then consi dered a negat ive val ue, as shown i n (8.2): 10 2 2 2 104 01101000 )1 01100111( 10011000 −= −=+ −= (8.2) We can even interpret th e original binary number in a differen t way if we assum e that the placem ent of the binary poi nt (equivalent to the decim al point) is located at a posi tion ot her than to the right of the right-most digit. For exam ple, if we place the binary point in the middle of the eight binary dig its, the num ber takes on another value ent irely. (In t he represent ation shown bel ow, it is consi dered an unsigned num ber, but it coul d just as well be consi dered a si gned num ber as descri bed before.) (8.3) 101 0 3 2 5.9 21 21 21 1000. 1001 =⋅+⋅+⋅=− There are advantages and disadvantages to each of the binary representations. The use of signed numbers is required in most digital filters, an d the two ’s complement representation provides easier methods for addition and subtraction, but multiplicatio n requires sp ecial co nsideratio n. The sig ned fractio nal arithmetic illustrated in (8.3) provides great effici ency in m ultiplication even though addition and subt raction do requi re som e speci al steps. B y using fractional notation, as most commercial digital signal processi ng (DSP) chi ps do, we can guarant ee that the resu lt of a m ultiplicatio n will still b e less th an one and therefo re cause no overfl ow. However, t he addi tion of t wo fractional num bers can provi de a resul t larger than one and t herefore m ust be handl ed careful ly. Techni ques for deal ing with potential erro rs in calcu lations are co nsidered further in Sectio n 8.1.3. Before we leave the area of input and out put data represent ation com pletely, we m ust consi der the effect of the num ber of bi ts per sam ple on the signal-to-noise ratio (SNR) o f a digital system . It is sh own in a number of the digital filter design references l isted in Appendi x A t hat the SNR for a digital signal processi ng 190 Practical Analog and Digital Filter Design system will be directly proportional to the number of quantization bits used. To be specific, the equation is 8.10) / log(20 02.6 SNRmax dB + ⋅+⋅= A Bxσ (8.4) In (8.4), B represent s the num ber of bi ts used t o represent the magnitude of the digitized signal, wh ile σx and Amax represent the input signal’s standard deviation and t he quant izer’s m aximum input signal. Usual ly, the input signal’s amplitude is adjusted such that σx/Amax is approxi mately 1/4. If t his condi tion is met, and we assum e that the input signal has a Gaussi an di stribution (whi ch is a valid assum ption for m any signals), then the quantizer’s lim its will be exceeded only 0.064% of the time. (If a sm aller num ber is chosen for t he ratio, the dynamic range of t he sy stem woul d be sacri ficed. If a larger number is chosen, the frequency of overfl ow woul d increase.) Usi ng the val ue of 1/ 4 gives 2.1 02.6 SNRdB −⋅= B (8.5) An important realization drawn from this expressi on is that the SNR can be improved by 6 dB for every bit added t o the quant ized represent ation. For example, if a particular filterin g applicatio n requires a sig nal-to-noise ratio of 80 dB, then a D/ A convert er wi th at least 14 bi ts of m agnitude quant ization m ust be available. 8.1.2 Coefficient Representation When it comes to the internal processin g of data for a digital filter system , there is more of an even mix bet ween fi xed-poi nt and fl oating-poi nt systems. The m arket has a variety of DSP microprocessor chi ps from a num ber of m anufact urers. These DSP systems include a wi de sel ection of fi xed-poi nt and fl oating-poi nt systems. The fi xed-poi nt systems general ly provi de hi gher processi ng speed at lower cost than do the floating-poi nt systems. However, t he floating-poi nt systems provi de accuracy that m any fixed-poi nt system s cannot achieve. The representation for the coeffi cients does not have t o be t he sam e as the representation selected for the input signal. Even if both are fi xed-poi nt num bers, t he coeffi cient represent ation can use a h igher precisio n representation (more bits). It is u p to the digital filter designer to determ ine the system character istics such that su fficient accuracy is achieved wi th adequat e processi ng sp eed at the lowest possible cost. The rep resentation of the filter co efficien ts with in the DSP system is of prime concern. Enough accuracy is required in the representation of the filter coefficients (which determ ine the pole and zero l ocations) t o guarant ee that the specifications of the filter are m et by th e implem entation. If the accuracy of the coefficients is com promised, the response of the filter m ay be severely distorted, and in some cases, th e stab ility o f IIR filters can be jeopardized. FIR filters will always be stable because they are represen ted by transfer functions with all zeros. Digital Filter Implementation Using C 191 However, their frequency response can still be affected by the lack of accuracy of their coefficients. As an exam ple, we consider the case of the Parks-McClellan filter designed in Example 7.4. The co efficien ts fo r that ex ample have been truncat ed to signed 16-bi t, 12-bi t, and 8-bi t num bers as shown i n Tabl e 8.1. Table 8. 1 Com parison of Original and Truncated Coef ficients Coefs Original 16-bit 12-bit 8-bit h(10) 0.348822 0.348822 0.348822 0.348822 h(9), h(11) 0.004010 0.004013 0.004090 0.002747 h(8), h(12) -0.268081 -0.268076 -0.268049 -0.269170 h(7), h(13) -0.008972 -0.008974 -0.009032 -0.008240 h(6), h(14) 0.102739 0.102740 0.102755 0.101625 h(5), h(15) 0.008322 0.008325 0.008350 0.008240 h(4), h(16) 0.012282 0.012285 0.012269 0.010987 h(3), h(17) -0.004333 -0.004333 -0.004260 -0.005493 h(2), h(18) -0.033368 -0.033363 -0.033400 -0.032960 h(1), h(19) 0.001195 0.001192 0.001193 0.000000 h(0), h(20) 0.012527 0.012530 0.012610 0.013733 Equat ion (8.6) shows t he procedure for det ermining the truncat ed values. The calcu lation with in the Round funct ion act ually indicates the procedure of convert ing the floating-poi nt coeffi cient to a signed fract ion represent ation for use in fixed-point processo rs. The multiplicatio n outside of the Round funct ion convert s the signed fract ion back t o a truncat ed deci mal: )1 2()10( )10()1 2()()(11 trunc−⋅ ⎥⎥ ⎦⎤ ⎢⎢ ⎣⎡ −⋅=−− BBh hnhRound n h (8.6) As we woul d expect , as t he num ber of bi ts is reduced, the error in the coeffi cients increases. The frequency response generat ed from the 16-bi t coeffi cients was vi rtually identical to the ori ginal response. However, the responses due to the 12-bit and 8-bit coefficients were noticeably degraded, as shown in Figure 8.1. In that figure, t he passband response was vi rtually unchanged i n all cases, but the stopband charact eristics did not match those of the original coefficients (shown as −56.7 dB). The 12-bi t coeffi cients did produce a response that satisfied the ori ginal desi gn speci fications of −50 dB . The 8-bi t coeffi cients, however, caused the frequenc y response t o degenerat e com pletely, providing as little as 32 dB of atten uation. The reaso n for this degradation, of course, is that the truncat ion has m oved t he pol e and zero l ocations from their original posi tions. 192 Practical Analog and Digital Filter Design Figure 8.1 FIR filter frequency response using truncated coefficients. 8.1.3 Reta ining Accura cy and Sta bility There is no effective way to directly relate the accuracy of the coefficients to the degree of degradat ion of t he frequency response. At this time, trial and error techniques are all that can be offered wh en determ ining the necessary accuracy of coefficients. However, there are som e help ful practices that can be observed when dealin g with the im plementation of these coefficients to reduce the effects of truncation. The following suggestions relate to IIR filters unless stated otherwise since t hey have som e unique probl ems due t o their recursi ve nature. The fact that IIR filters are im plemented using feed back lead s to special p roblems that the FIR filter d oes not experience. Probabl y the most important implementation rul e when deal ing wi th IIR filters is that it is m uch better to implement the filter as a cascad e of quadratic factors (as we have done) t han to com bine the transfer funct ion into a quot ient of high-order polynomials. (Even some experi mentation has been done wi th this idea for FIR filters.) Th is tech nique provides better co ntrol of the stability of the filter. By quantizing the coefficien ts that rep resent the filter, we are actu ally sp ecifyin g a fixed num ber of posi tions wi thin the uni t circle where t he pol es can be located. The fewer bi ts used for quant ization, t he fewer t he posi tions for t he pol es. In addition, these pol e locations are not uniform ly distributed wi thin the uni t circle. However, by choosi ng different topologies for t he implementation (such as a coupl ed form of quadrat ic), more uni form ly distributed pol e locations can be achieved. Also, it has been shown t hat those pol es whi ch either lie close to the uni t circle or to each other are the most critical to represent properly, and therefore may need some speci al implementation m ethod. Anot her t echni que t hat can be used to reduce errors caused by com putati ons using finite accum ulators is to pair poles and zeros located near each other in the sam e quadratic factor to reduce large fluctuations. In addition, sectio ns with poles clo sest to the unit circle can be Digital Filter Implementation Using C 193 moved to the end of the evaluation process to help eliminate overflows. The digital filter design references in Appendix A provide further information on other structures than the quadratic form, including those for representing poles located extremely close to the unit circle. Antoniou’s, Oppenheim/Shafer’s (1975), and Proakis/Manolakis’s texts provide valuable and detailed material. Several other points can be made when discussing the coefficients and internal processing of the filter calculations. In both FIR and IIR filter implementation, the final output values are stored in a register that gradually accumulates the value of the final output . This accumulator should normally be allocated as many bits of representation as possible because it controls the ultimate accuracy of the processor. Overflow and underflow are potential problems for the accumulator since it is hard to predict the exact nature of incoming signals. Most present dedicated DSP chips provide some form of scaling that can be applied to the input so that temporary large va riations can be accommodated without incurring a great deal of error. This s caling bit can effectively be used as a temporary additional bit of accuracy for accumulated values to prevent overflow. However, if overflow is inevitable, it is better to have a processor that will simply saturate at its maximum level than to allow an overflow that can be interpreted as a swing from positive to negative value. In recursive systems that use finite precision representations, a troublesome problem called limit cycle oscillation can occur. There are actually two types of limit cycles: overflow and quantization. Overflow limit cycles (also called large- signal limit cycles) are due to the unman aged overflow of the accumulator during processing. Most overflow limit cycles can be effectively eliminated by the proper use of signal scaling at the input of the system and saturation arithmetic in the accumulator. Many DSP processors incl ude some scaling feature within the processor unit that allows the input signal to be reduced in size. However, a reduction in the size of the input signal also reduces the SNR of the system, although this is usually better than the distortion produced by an overflow. Another useful feature on many DSP systems today is the use of saturation arithmetic within the processing unit. This feature will saturate the value to its positive or negative limit rather than overfl ow the accumulator. Again, this will result in distortion, but usually less than the overflow would produce. Of course, another way to help control overflow limit cycles is to increase the size of the accumulator, if the processing system allows the accumulator to be larger than the standard coefficient storage size. The quantization limit cycles (also called small-signal limit cycles) generally result from the handling of quantization with in the system and are noticeable when the output should be constant or zero. This problem is the result of the input signal changes being less than the quantization le vel. Two methods have been developed to combat this type of limit cycle. The first, which may not be a practical alternative, is to increase the number of bits assigned to the representation of the signal values in order to reduce the quantization error. By reducing the quantization error, the limit cycles can eith er be eliminated altogether, or reduced to a tolerable level. The second method suggests that the products produced by 194 Practical Analog and Digital Filter Design finite precision m ultiplication be truncated , rather than rounded, as they are accum ulated. Other, m ore detailed, analys is of limit cycles is included in the references. 8.2 C CODE FOR IIR FILTER IMPLEMENTATION When discussing the im plementation of IIR filters, we assu me that th e filter is descri bed by a set of quadrat ic coeffi cients of the form determined in Chapter 7. As we have seen i n the previ ous sect ion, a cascaded sequence of quadrat ic structures i s the recom mended m ethod of i mplementation. The basi c quadrat ic building bl ock i s shown i n the system diagram of Fi gure 8.2. Figure 8.2 System diagram for a single quadrat ic factor. We can generate the transfer function for this sectio n by determining the expressio ns for the intermediate sig nal w(n) and t he out put signal y(n). )2( )1( )( )(2 1 −⋅+−⋅+= nwb nwbnx nw (8.7) )2( )1( )( )(2 1 −⋅+−⋅+= nwa nwanw ny (8.8) These equations can be z-transform ed to give (8.9) )( )( )( )(2 21 1 zWzbzWzbzXzW ⋅⋅+⋅⋅+=− − (8.10) )( )( )( )(2 21 1 zWzazWzazWzY ⋅⋅+⋅⋅+=− − Equations (8.9) and (8.10) can be rewritten and combined to determine the transfer function for this sectio n of the filter, as sh own in (8.11). This formulation matches the quadratic terms we d eveloped for IIR filters. W e will b e able to match Digital Filter Implementation Using C 195 equivalent terms if we recogni ze two charact eristics. Fi rst, the ao coefficient is always one, and second, t he b coefficien ts in the system diagram will b e the negat ive of t heir value in the transfer funct ion equat ion. ) 1() 1( )()()(2 21 12 21 1 − −− − ⋅−⋅−⋅+⋅+== zb zbza za zXzYzH (8.11) As an exam ple, consider the fourth-o rder transfer function for a Chebyshev highpass filter shown in (8.12). This f ilter can be im plem ented by using the system diagram shown i n Figure 8.3. As we see i n the diagram , the input signal is first m ultiplied by the gain constant and is then processed through two quadratic facto rs. Th e multiplicatio n by the gain constant could occur at the end of the process or be di stributed throughout the diagram as wel l. Not ice the sign difference on t he b coefficients between the transf er funct ion of (8.12) and t he system diagram of Figure 8.3. (Of co urse, th e coefficien ts will b e represented with higher preci sion than indicated here.) ) 222.0 0448.01() 795.0 047.11() 1 21() 1 21( 201.0)(2 1 2 12 1 2 1 4− − − −− − − − ⋅+⋅−⋅⋅+⋅−⋅+⋅−⋅⋅+⋅−⋅= z z z zz z z zz HC (8.12) Figure 8.3 System diagram for fourth-order IIR filter. 196 Practical Analog and Digital Filter Design After d etermining the system diagram for a filter, we can use the diagram as a guide to implementing the filter. Fo r every q uadratic facto r, we can calcu late an intermediate sig nal w(n) and an out put signal y(n). Besides x(n), w(n), and y(n), every quadrat ic section al so requi res the val ues w(n − 1) and w(n − 2) (as shown in Figure 8.2) to be retained. W e can rewrite (8.7) and (8.8) as 2 2 1 1 mb mbxw ⋅+⋅+= (8.13) 2 2 1 1 ma mawy ⋅+⋅+= (8.14) where we have defi ned )1(1−=nw m (8.15) )2(2−=nw m (8.16) The nam es m1 and m2 are picked to reflect the f act that these values are the memory states of the quadratic factor. Each quadratic structure m ust keep track of the previ ous val ues that have been present in the structure. The IIR filtering process can be im plem ented by first m ultiplying the input signal by the gain and then im plem enting (8.13) to (8.16) for each of the quadrat ics. Then, before progressi ng to the eval uation of the next quadrat ic factor, the values of m1 and m2 are updated. A section of code that will implem ent this process is sh own in Listin g 8.1. In the listin g, it is assu med that there are m1 and m2 array s with sizes equal to the number of quadrat ics, and that the a and b coefficien ts for the filter are sto red in the usual manner. (Th at is, th e three coefficients a0, a1, and a2 for the first q uadratic are fo llowed by the three coeffi cients for t he second quadrat ic, and so on. The sam e organi zation is assum ed for the b coefficients.) Note that the a0 and b0 coefficients are not used since they are assu med to be one. We have also substituted the output variable o for t he input variable x to let the output value accum ulate through several quadratic sections. o = x * gain; for(j = 0; j < numb_quads ;j++) { jj = j*3; w = o - m1[j] * b[jj+1] - m2[j] * b[jj+2]; o = w + m1[j] * a[jj+1] + m2[j] * a[jj+2]; m2[j] = m1[j]; m1[j] = w; } Listing 8.1 Seg ment of code for IIR filter im plementation. Digital Filter Implementation Using C 197 Although the algorithm in Listing 8.1 w ill make the correct computations, it could be slow because of all of the index calculations that must be made. (Actually, compilers will differ in terms of how much optimization can be made with speed-critical code such as we ar e discussing.) The speed of this loop can usually be increased by using pointers to the coefficients and memory values. In order to take advantage of this pointer efficiency we must store the filter coefficients in an orderly manner, which will allow them to be accessed sequentially in the exact order that they are needed. We can define a new array C that will store all of the needed coefficients as well as the filter gain constant. The first element in the array will be the gain constant followed by the coefficients b 1, b2, a1, and a2 for each quadratic factor. The structure of the C array then has the following form: C[0] = gain C[5] = b 1 (quad 2) C[1] = b 1 (quad 1) C[6] = b 2 (quad 2) C[2] = b 2 (quad 1) C[7] = a 1 (quad 2) C[3] = a 1 (quad 1) C[8] = a 2 (quad 2) C[4] = a 2 (quad 1) ... In addition, an M array must be created to store the memory states of the IIR filter. The size of the array is equal to twice the number of quadratic factors with the m 1 states stored in the firs t half of the array and the m2 states in the last half. Initially, all of the memory states are set to zero (unless we know some predefined state exists for the filter). Thus, the M array has the following structure where N is the number of quadratics: M[0] = m 1 (quad 1) M[N] = m (quad 1) 2 M[1] = m 1 (quad 2) M[N + 1] = m 2 (quad 2) M[2] = m (quad 3) M[N + 2] = m (quad 3) 1 2 ... ... Listing 8.2 shows the Dig_IIR_Filter function used in the DIGITAL program discussed later in this chapter. (All of the functions discussed in this chapter can be found in the \DIGITAL\DIGITAL.C module on the software disc that accompanies this text.) The function ta kes as arguments pointers to arrays of input values ( X), output values ( Y), memory states ( M), and coefficient values ( C), as well as the number of quadratic factor s and number of values in the input and output arrays. Notice that since we will be progressing through the X , Y, C, and M arrays, we have defined indexing pointers x, y, c, and m, which can take on changing values. ( Never use the array name itself as an index or the address of the array will be lost.) The notation may look a little foreign so let’s take a look at the code on a line-by-line basis. (The line numbers shown are to help with this discussion and are not part of the normal code.) The process of using pointers is very efficient for comput ational purposes because it fits the nature of the computer. However, it can be a bit confusing to follow. Therefore, in order to provide a more descriptive analysis of the IIR filter code, the code has been annotated with the status of primary arrays and variables. For this illustration, it is 198 Practical Analog and Digital Filter Design assumed that there are two quadratic factor s and sample values have been entered for the C and M arrays. At each step of the proce ss, the particular values to which c, m1, or m2 are pointing within the arrays are shown in bold. Only the first time through the inner loop is illustrated, but we can see from this how the pointers progress through the arrays, and how the memory state array is changed. In lines 1 and 2 of Listing 8.2, the addr esses of the input and output arrays are transferred to temporary variables x and y that can change without affecting the addresses stored in X and Y. Then, line 4 begins a for loop to process every value in the input array. Lines 6 to 8 set up pointers to the memory states and coefficient arrays. The m1 pointer is set to start at the beginning of the M array where the m1 states are stored, while the m2 pointer is set midway through the M array since the m2 states are stored in the second half of the array. The initial value of the output, indicated by o, is calculated by multiplying the input value by the first value in the coefficient array, which is the gain constant. /*==================================================== Dig_IIR_Filter() - filters input array using IIR coefs and mem values to generate output Prototype: void Dig_IIR_Filter(int *X,int *Y, double *M,double *C,int numb_quads,int N); Return: error value. Arguments: X - ptr to input array Y - ptr to output array M - ptr to memory array C - ptr to coefs array numb_quads - number of quadratics N - number of values in array ====================================================*/ void Dig_IIR_Filter(int *X,int *Y,double *M,double *C, int numb_quads,int N) { int *x,*y, /* ptrs to in/out arrays */ i,j; /* loop counters */ double *c,*m1,*m2, /* ptrs to coef/memory arrays*/ w,o; /* intermed & output values */ /* Make copies of input and output pointers */ 01 x = X; 02 y = Y; x : 3,4,5,6,7,... y : 0,0,0,0,0,... 03 /* Start loop for number of data values */ 04 for(i = 0; i < N ;i++) 05 { /* Make copies of pointers and start calcs */ 06 m1 = M; 07 m2 = M + numb_quads; 08 c = C; C: 0.20 ,1.0,-0.80,-2.0,-1.0,0.05,-0.20,-2.0,-1.0 M : 1.0,3.0,2.0,4.0 09 o = *x++ * *c++; C : 0.20, 1.0,-0.80,-2.0,-1.0,0. 05,-0.20,-2.0,-1.0 x : 3,4,5,6,7,... o : 0.60 Listing 8.2 Dig_IIR_Filter function. Digital Filter Implementation Using C 199 10 /* Start loop for number of quad factors */ 11 for(j = 0; j < numb_quads ;j++) 12 { w = o - *m1 * *c++; C : 0.20,1.0, -0.80 ,-2.0,-1.0,0.05,-0.20,-2.0,-1.0 M : 1.0,3.0,2.0,4.0 w : -0.40 13 w -= *m2 * *c++; C : 0.20,1.0,-0.80, -2.0,-1.0,0.05,-0. 20,-2.0,-1.0 M : 1.0,3.0,2.0,4.0 w : 1.20 14 o = w + *m1 * *c++; C : 0.20,1.0,-0.80,-2.0,-1.0 ,0.05,-0.20,-2.0,-1.0 M : 1.0,3.0,2.0,4.0 o : -0.80 15 o += *m2 * *c++; C : 0.20,1.0,-0.80,-2.0,-1.0, 0.05,-0.20,-2.0,-1.0 M : 1.0,3.0,2.0,4.0 o : -2.8 16 *m2++ = *m1; M : 1.0,3.0,1.0, 4.0 17 *m1++ = w; M : 1.2, 3.0,1.0,4.0 18 } 19 /* Convert output to int and store */ 20 *y++ = (int)ceil(o-0.5); y : -3,0,0,0,0,... 21 } } Listing 8.2 Continued. Notice that the method used to access th e gain constant is by using the *c notation, which can be read as “the value at which c is pointing.” Since c has just been initialized to the start of the C array, and since the first element in C is the gain constant, then c is pointing at the gain constant. The “++” notation after c instructs the computer to increment the value of c by one after the equation has been evaluated. (This is referred to as post-incrementing as opposed to ++c, which is called preincrementing.) At this point, we are performing pointer arithmetic, which is a special type of arithmetic. Remember that the variable c (and C) contains a number that is an address of where coefficients are stored in memory. When we increment a pointer we are incrementing an address and therefore must do so in a meaningful way. In this case, the coefficients are stored as double s, which take up 8 bytes of memory on a PC. It would be meaningless to increment the address of an array containing double s by 1 byte, or 2, or anything but 8 bytes. Therefore, when we tell the machine to increment c, it increments the number stored in c by 8. (This is what is meant by special arithmetic.) The compiler keep s track of how to increment pointer variables based 200 Practical Analog and Digital Filter Design on how the variables are in itially d eclared . For example, if th e variables are double , the increm ent is 8; if they are int, the increm ent is 2. Now, ret urning to our di scussi on of Li sting 8.2, we next enter a for loop (line 11) used to calculate the effects of each quadra tic factor on the ultim ate output value. Lines 12–13 com pute the value of w and increm ent the pointer in the C array as each value is used. Lines 14–15 then m ake the calculations representing the right half of Fi gure 8.2 t o determine the out put value. The pointer c is now pointing to the b coeffi cients for t he next quadrat ic sect ion. Li nes 16–17 updat e the values of the m emory states and increm ent m1 and m2 to point to the memory states of the next quadrat ic sect ion. The fi nal step in the det ermination of t he output value is the conversi on of t he floating-poi nt value of o to the fixed poi nt value of *y. The method used i n convert ing the floating poi nt value to an integer value insures that both positive and negativ e values will be rounded correctly. The pointer y is then increm ented and the proce ss repeats for the next value in the input array . We shoul d not e that by the end of t he out er for loop, t he c, m1, and m2 pointers will be pointing to values that do not belong to them . That’s all right as long as we don’t try to access them . The next tim e an input value is filtered, lines 6–8 will reset the pointers to the correct positions. One advant age of the algorithm we have just devel oped i s that it can be used effect ively for ei ther real -time or nonreal -time appl ications. The val ue x can be taken from either an i nput port of a DSP sy stem, or from an array of values to be processed (as illu strated ). Lik ewise, th e value y can be fed t o an out put port of a DSP system or placed in an output a rray (as we have done). W e will see a program for a co mplete filterin g system in Sectio n 8.4. 8.3 C CODE FOR FIR FILTER IMPLEMENTATION An FIR filter h as no feed back and thus its system diagram can be displayed as shown in Figure 8.4. Thi s confi gurat ion represent s a convol ution involving N coeffi cients, as descri bed by (8.17). Figure 8.4 System diagram for general FIR filter im plementation. (8.17) ∑− =⋅−⋅=1 0)() ( )(N kkaknx g ny Digital Filter Implementation Using C 201 8.3.1 Real-Time Implementation of FIR Filters Although t he al gorithm woul d appear t o be very simple for such an implem entation, the fact that we require N − 1 values to store the m emory states (past values of the input) of the filter complicates the procedure som ewhat. W e will b egin by discussing the real-tim e implementation problem, and then later we will see that significant tim e savings can be m ade with nonreal-tim e implementations. First, we can generate C co de to implement (8.17). We will n eed to update each m emory state after each convolutional sum , which we can do within the sam e loop i f we perform the convol ution in reverse order. The si mplest way to handl e this reverse order i s to reverse the coefficients and m emory states in their respective arrays, as shown in (8.18) (the coefficient array) and (8.19) (t he memory state array). No te that the gain constant is sto red as th e last en try in the C array : (8.18) } , , , . . . , , { : array 0 1 2- 1 gainaa a a CN N− (8.19) } , , . . . , , { : array 0 1- )2-(- )1(- xx x x MN N− The segm ent of code gi ven i n Listing 8.3 shows t he basic implementation. We start the process by placing the current value of i nput x[0] into the last position of the memory array M. The initial v alue of the output o is calcu lated using the initial values of the memory state an d the coefficien t arrays. Th en we enter th e for loop t o com pute the rest of the convol ution sum . Each t ime through the loop, the memory states are updat ed so t hat by the end of t he loop al l of the memory states occupy the correct posi tion for t he next input value. The final step in the process is to multiply the output value by the gain constant of the filter. m[N-1] = x; o = a[0] * m[0]; for(k = 1; k <= N ;k++) { m[k-1] = m[k]; o += a[k] * m[k]; } o *= gain; Listing 8.3 Seg ment of code for FIR filter im plementation. The co de of Listin g 8.3 will co rrectly co mpute the output value but the execution will be slow because of the need for so m any index calculations. Listing 8.4 shows t he Dig_FIR_Filt_RT funct ion for i mplementing a real -time (RT) digital FIR filter th at makes use of pointers to speed the process. In this case, we will n eed an M array o f a size eq ual to the len gth of the filter ( N) and a C array that is one larg er (N + 1) to accom modate the gain constant. Initially, the M array is 202 Practical Analog and Digital Filter Design filled with zeros (unless we know the state of the filter), and the C array is filled with the FIR coefficients in reve rse order. The final value of the C array is the filter’s gain constant. We will use movable pointers within the M and C arrays. The m1 and m2 pointers are initially set to the start of the array and then incremented toward the end. By using two movable pointers, we can transfer memory states without any need for address computation. The final step in the process (before converting the output variable back to an integer) is to multiply the accumulated value in o by the gain constant of the filter. Although for this code, we obtain the value of input from an array, it could just as well be coming from an input port on a DSP system. Likewise, the output value could be written to an output port instead of an array. /*==================================================== Dig_FIR_Filt_RT() - filters input array using FIR coefs (uses real-time code) Prototype: void Dig_FIR_Filt_RT(int *X,int *Y, double *M,double *C,int numb_coefs,int N); Return: error value. Arguments: X - ptr to input array Y - ptr to output array M - ptr to memory array C - ptr to coefs array numb_coefs - number of coefficients N - number of values in array ====================================================*/ void Dig_FIR_Filt_RT(int *X,int *Y,double *M,double *C ,int numb_coefs,int N) { int *x,*y, /* ptrs to in/out arrays */ i,j; /* loop counters */ double *c,*m1,*m2, /* ptrs to coef/memory array */ o; /* output value */ /* Make copies of input and output pointers */ x = X; y = Y; /* Start loop for number of data values */ for(i = 0; i < N ;i++) { /* Make copy of pointers and start loop */ M[numb_coefs-1] = *x++; c = C; m1 = m2 = M; o = *m1++ * *c++; /* Use convolution method for computation */ for(j = 1; j < numb_coefs ;j++) { *m2++ = *m1; o += *m1++ * *c++; } /* Multiply by gain, convert to int and store */ o *= *c; *y++ = (int)ceil(o-0.5); } } Listing 8.4 Dig_FIR_Filt_RT function. Digital Filter Implementation Using C 203 This implementation of the FIR filter is slow because of the constant memory state shuffle. Note that most sophisticated DSP processors have handled this shuffle by implementing what is referred to as a circular buffe r. A circular buffer is one in which the last entry is magically connected to the first entry. In other words, if a pointer that is pointing to the last entry in the buffer is incremented, the processor automatically adjusts the pointer to point to the first entry of the buffer. This helps tremendously, because with a circ ular buffer, no memory states need to be moved. The newest input value is simply written into the circular buffer over the oldest memory state. The starting point of the convolution is then adjusted to the proper value and the process continues in the normal manner. Although a circular buffer can be simulated on a PC, it requires special coding beyond the scope of this text. In the next section we will discuss a much faster nonreal-time method that we can use instead. We w ill leave the real-time circular buffer implementation to the DSP chip programmers since DSP systems are usually used for this type of work. 8.3.2 Nonreal-Time Implementation of FIR Filters The implementation of the FIR filter unde r nonreal-time conditions can be made much more efficient because we will have av ailable as many of the input values as we would like (and that memory will hold) . The input values not only represent the input for the system, but also the memory states of the system. The need for the constant shuffle of past memory states will be removed (to a great degree) as we will see. To understand the efficiency of the nonreal-time process, it may be helpful to view the convolution process graphically. Figure 8.5 shows an array of input values and an array of coefficient values. We can visualize the convolution process as the generation of the sum of products as the coefficients slide past the input values. In part (a) of Figure 8.5, we see th e initial position of the convolution process where x0 is the first input value to be processed. If previous values of the input are not available then x−1 through x −(N−1) would be set to zero. After the convolution sum of products is calculated, the value of y0 can be determined. The array of coefficients can then be effectively moved one position to the right and the convolution performed again for y 1. This procedure will continue until we reach the end of the input array, processing the last value of the array xL−1, as shown in part (b). Note that since we have a very large array of input values, we can perform many convolution sums without shuffling the past values of input. However, there is usually a limit to how large an input array can be brought into memory. Therefore, we will eventually need to bring in a new array of L input values and start the convolution again from the start of the new array. But in order for the initial convolution sums on this new array to be correct, the values immediately preceding the x L value must be available at the beginning of the input array, as shown in part (c) of the figure. Consequently, we will need to move the last N − 1 values of the initial input array to the beginning on the array. This 204 Practical Analog and Digital Filter Design movem ent process will have to be accomplished at the end of processing each segm ent of the input array . If we m ake the input array buffer m uch larger t han the length of the FIR filter, this am ount of processing should be insignificant. Figure 8.5 Graphi cal interpret ation of convol ution. Listing 8.5 shows t he Dig_FIR_Filt_NRT funct ion for i mplementing the nonreal-tim e (NRT) form of the FIR filter. In this function, the pointers to the input, output, and coeffi cient array s are pa ssed as argum ents as wel l as the num ber of coeffi cients and num ber of val ues to be processed i n the input array . Notice that a separat e array of m emory states is not necessary since t he input array also represent s the memory states. The funct ion st arts by assigning the address of t he first input value to the pointer variable x, which will m arch through the array keepi ng track of t he starting poi nt of the convol ution. A t emporary pointer to the proper output array v alue is also initialized . The pointer to the coefficien t array c is initialized with in the first for loop, whi ch cont rols the processi ng of al l input values. The convol ution sum is then cal culated moving the x and c pointers progressively through the respective a rrays accum ulating products. After the summation is com plete, the next step is to multiply the accum ulation by the filter’s gain const ant, whi ch has been st ored at the last entry in the C array. Th e process is completed by convert ing the output floating-poi nt value to a fixed-poi nt value and reset ting the starting poi nt in the x array to the correct position for the calculation of the next output value. Aft er all values in the input array have been processed, Digital Filter Implementation Using C 205 the last N − 1 values in the array are copied to the beginning of the X array for the processing of the next input segment. As we will see in the next section, when input values are stored in the X array, they are not placed at the beginning of the array (which would overwrite the memory st ates of the filter), but rather placed at an advanced position in the array based on the length of the filter. /*==================================================== Dig_FIR_Filt_NRT() - filters input array using FIR coefs (uses nonreal-time code) Prototype: void Dig_FIR_Filt_NRT(int *X,int *Y, double *C,int numb_coefs,int N); Return: error value. Arguments: X - ptr to input array Y - ptr to output array C - ptr to coefs array numb_coefs - number of coefficients N - number of values in array ====================================================*/ void Dig_FIR_Filt_NRT(int *X,int *Y,double *C, int numb_coefs,int N) { int *x,*y, /* ptrs to in/out arrays */ i,j; /* loop counters */ double *c, /* ptrs to coefficient array */ o; /* output value */ /* Make copies of input and output pointers */ x = X; y = Y; /* Start loop for number of data values */ for(i = 0; i < N ;i++) { /* Make copy of coefs pointer and start loop */ c = C; o = *x++ * *c++; /* Use convolution method for computation */ for(j = 1; j < numb_coefs ;j++) { o += *x++ * *c++;} /* Multiply by gain, convert to int and store */ o *= *c; *y++ = (int)ceil(o-0.5); /* Reset the pointer in input data */ x -= (numb_coefs - 1); } /* Copy last values to front of buffer */ memcpy(X,&X[CHUNK_SIZE],2*(numb_coefs-1)); } Listing 8.5 Dig_FIR_Filt_NRT function. 8.4 FILTERING SOUND FILES We have now developed several ways to implement the digital filters that we designed in the previous chapters. It is now time to actually implement them and listen to the results. Dedicated DSP processors may not be available to us, but many of us do have sound cards in our computers, so we can at least implement 206 Practical Analog and Digital Filter Design the nonreal-tim e versions of the filters . The m anner in which this will be accom plished is the following. Two s ound files have been included on the software di sc included wi th this text, and we can record other sound files using our sound cards. These sound files can be filtered using W Filter, which has been included with this text. After filtering th e sound files, we can com pare the results using the sound card to play the original and filtered versions of the sound files. (Please read t he docum entation for y our sound card t o determine how to record and pl ay sound fi les.) To get further i nform ation on sound file form ats and the C code used in filterin g the files, p lease refer to Appendix I. To demonstrate the ease o f filterin g wav eforms, we’ll d esign a digital filter and use it to filter o ne of the wav eforms on the software d isc in our next example. Exampl e 8.1 IIR Di gital Filtering of Waveform Problem: Determ ine the effects on m usic.wav (available on the CD) when it is filtered by a digital Bu tterwo rth IIR filter with the following characteristics: apass = −0.5 dB , astop = −60 dB , fpass = 800 Hz, and fstop = 1,600 Hz Solution: First, we design the filter u sing WFilter. Sin ce we will b e filterin g a file sampled at 22,050 Hz, we use t hat value as t he sam pling frequency . After designing the filter, we can select Filter Wa ve File from the Options menu. The following dialog box will be shown. Figure 8.6 Filter W ave File dialog box. We can identify the f ile to be filtered by typing di rectly into the dialog box or by using the browse button to locate the file. After speci fying the input and out put file nam es, sim ply press the Filter button and the filtering action will take place. You will be able to tell wh en the filterin g has finished by the play buttons being enabled. Now we can com pare the tw o sound files by playing each file individually. Notice that the lowpass filter was successful in elim inating the chimes fro m the original version. Digital Filter Implementation Using C 207 Other filters can be created and other sound files can be filtered. If you use the speech.wav file on the accompanying di sc be aware that it has a sampling frequency of 11,025 Hz. It is also captured as an 8-bit file. 8.5 CONCLUSION We have reached the end of this chapte r where the implementation of FIR and IIR filters has been developed. We have developed a fully functional program to filter sound files, which can be mono or stereo, and 8-bit or 16-bit files. Other file formats can be added to the program with minimum effort by writing functions to read and write the file headers and passing the required information to our functions. Compressed files can be handled by implementing a decompression function between the reading of the data and its filtering. Further information on sound file formats and C code for f iltering can be found in Appendix I. 208 Practical Analog and Digital Filter Design Chapter 9 Digital Filtering Using the FFT At this point we h ave discussed the design and implementation of digital filters. In the process we have i nvest igated the charact eristics of t he input and out put signals in both the time and frequency dom ains. It is time now to invest igate a more direct relationshi p bet ween t he time dom ain and frequency dom ain for di scret e time system s. W e will b egin by discussing the discrete tim e version of the Fo urier transform. After th e discrete Fo urier tran sform (DFT) d iscussion, we will learn about the more com putational efficient versi on cal led the fast Fouri er transform (FFT). The C code for the FFT will be de veloped, and finally, we will take a look at one m ethod of using the FFT in linear filtering. 9.1 THE DISCRETE FOURIER TRANSFORM (DFT) The Discret e Fouri er Transform (DFT) can be used t o com pute the frequency content of any discret e time signal. Consider first (9.1), where ω is periodic with a period of 2π. (Remember that a radi an frequency of 2π in the z-plane is equi valent to the sam pling frequency (Fs) in the s-plane.) In (9.1), x(n) represents the tim e domain signal, which has an infinite number of sam ples. Th e spectru m that will result from sam pling an analog signal will actu ally be many replicas o f the analog spectrum spaced at m ultiples of the sam pling frequency, as shown in Figure 5.2 in Chapter 5. We will b e able to select j ust one of these sp ectru ms by using a filter at the out put of our di scret e time system. (9.1) ∑∞ −∞=−⋅ = nnjenx Xωω )( )( We see t hat although (9.1) correct ly defi nes t he Fouri er transform for a discrete time signal, it is im possible to implement for two reaso ns. First, we will never be abl e to obtain all of the tim e dom ain sam ples, and second, we will never be able to evaluate the equation at all values of t he frequency vari able ω. 209 210 Practical Analog and Digital Filter Design Therefore, t he first adjust ment we m ake to our st rict defi nition is to modify (9.1) to reflect the fact that we will h ave only a fin ite number of sam ples o f x(n) with which to work. Equat ion (9.2) shows t he definition when we assum e that we have only N samples of the signal data: (9.2) ∑− =−⋅=1 0)( )(N nnjenx Xωω Truncat ing the signal sequence as in (9.2) i s effect ively appl ying a rect angul ar window to the tim e dom ain sequence. Th is causes problem s in the resulting frequency dom ain descri ption whi ch can be lessened by appl ying a di fferent window such as one used in Chapter 7 dealing with FIR filter coefficients. The impact of such a window w ill be discussed very soon. If we further assum e that we’l l only need t o eval uate the frequency response data at a finite num ber of e qually spaced frequencies from 0 – 2π, we have t he definition of t he K-point DFT of an N-point signal. Kk, K-, , k enx X kN nnj kk πωωω 2 where 1 10 , )( )(1 0 ==⋅=∑− =−… (9.3) Exampl e 9.1 Cal culation of DFT with Rectangul ar Wi ndow Problem: Determ ine the DFT of an audio signal containing three distinct frequencies of F1 = 2 kHz, F2 = 3 kHz, and F3 = 4 kHz. Assum e that the sam pling frequency is Fs = 20 kHz and that we m ake use of either 20 or 40 samples of the waveform . Use a rectangular window (i n other words, sim ply truncate the sequence). Solution: First, we generate a waveform containing the three frequencies. )/ 2sin()/ 2sin()/ 2sin()(3 2 1 s s s FnF FnF FnF nx π π π + + = Then, we calculate the DFT using (9.3) letting K = 1,000 points. (This gives us a near continuous frequency response.) Th e results are shown in Figure 9.1. Although not shown, if we had used a large num ber of data points (N = 1,000), the DFT graphs would have show n six very distinct spikes in the frequency dom ain with far less “clutter” at other frequencie s. (There are six m ajor responses in the spectrum because the content from 10 kHz to 20 kHz is a m irror reflection of the Digital Filtering Using the FFT 211 content from 0 Hz to 10 kHz. We need only to concern ourselves with the first half of the spectrum .) As it is, we can see that the three m ajor spikes in the first half of the spectrum generally reflect th e three frequencies of our waveform . As N increases, the position will becom e more and m ore precise. However, we should be concerned about the clutter at othe r frequencies and why it is reduced as N increases. Figure 9.1 DFT of three frequencies with rectangular window. The explanation of the num erous extr aneous lobes contained in the DFT responses goes back to the tim e dom ain and our truncation of x(n). By truncating the sequence, we effectively m ultiplied two tim e dom ain functions together, as shown in (9.4). (The r ectangular window function w(n) in our exam ple will have 20 or 40 values of one and zeros for all other values.) )()( )( nwnx n xtrun ⋅= (9.4) 212 Practical Analog and Digital Filter Design When two waveform s are m ultiplied in the time domain, their frequency spectrum s are convolved in the fre quency dom ain. Although the frequency spectrum of the signal will be three sp ikes, the frequency spectrum of the rectangular window will be a sinc function shown in Figure 9.2. Notice all of the side lobes produced. When convolved with the three spikes re presenting the three signal frequencies, these side lobes will cr eate the extraneous side lobes shown in Figure 9.1. B y contrast, when viewing the response of the transform of the Ham ming window, we see no annoy ing side l obes, but a sm aller and wider main lobe. The results of using a Ham ming window is shown in Exam ple 9.2. Figure 9.2 DFT of rectangular and Ham ming windows. Exampl e 9.2 Cal culation of DFT with Hammi ng Wi ndow Problem: Repeat Exam ple 9.1, but use a Ham ming window on the truncated input sequence. Solution: The input sequence x(n) is form ed the sam e way as in Exam ple 9.1, but the window function w(n) takes on the following values: ))1 /(2cos(46.0 54.0)( − ⋅−= Nn nw π After calculating the DFT of the product x(n)·w(n), the results are displayed in Figure 9.3 with a num ber of interesting com parisons to Figure 9.1. First, we notice that the clutter of the side lobes of Figur e 9.1 has been reduced to a great degree. However, we also notice that for the 20-point signal case, there are no longer three, nearly equal spikes in the first half of the sp ectrum . Even in the 40-point case, the three spikes are no longer as cl early distinct. These results derive from the fact that the transf orm of the Ham ming window is approxim ately twice as wide as the m ain lobe of the recta ngular window transform . The resulting resolution of the transform is therefore not as crisp as in the rectangular case. Digital Filtering Using the FFT 213 Figure 9.3 DFT of three frequency lengths with Ham ming window. It can be shown that the frequency resolution ∆f of the DFT is improved by increasing the num ber of tim e dom ain sam ples, as shown in (9.5). As N increases, the ability to see sm aller frequency details im proves regardless of window type used. The coefficient mw is a windowing factor that takes on a value of 1 for a rectangular window, approxim ately 2 for a Ham ming window, and other values for Kaiser based on the β value chosen. (See Orfanidis’ text for further details.) NTmNfmf sws w⋅⋅=⋅=∆1 (9.5) Example 9.3 Determine Resolution for DFT System Problem: Determ ine the num ber of tim e dom ain sam ples needed to resolve the three frequencies of Exam ples 9.1 and 9.2. 214 Practical Analog and Digital Filter Design Solution: In each case, the resolution ∆f required is 1 kHz in order to clearly see the three frequencies. In Example 9.1, mw will be 1, and for Example 9.2, we will use a value of 2. Equation (9.3) can th en be used to determine that the number of time samples N needed would be 20 for Example 9.1 and 40 for Example 9.2. Figures 9.1 and 9.3 seem to support these values. From the previous examples we see that we must choose N carefully to get the resolution required for our system. It s eems obvious that the more time domain samples available, the clearer the pict ure of the frequency spectrum will be, and that is true. But once the minimum number of data samples is determined, is there any advantage to increasing the number of frequency points co mputed? It may not be clear at this point, but pr oviding more freque ncy points does not improve the resolution, it simply provides a more con tinuous graph of the spectrum. This is seen in Figure 9.4, which shows the Hamming window case with N = 20 and K = 20. Comparing this to the 20-point graph in Figure 9.3, we note that the 3-kHz component is obscured in either case. Increasing the number of frequency data points 50-fold did nothing to improve the resolution of the DFT. In a similar argument, if you have ava ilable many time samples, but compute far fewer frequency points, you are losing valuable frequency information. Therefore, a general rule of thumb is to let N = K as a starting point in the design of a DFT system. On occasion, it may be necessary to allow K to increase to find a more exact value of the frequency of a maximum. 9.2 THE FAST FOURIER TRANSFORM (FFT) While the computation of the DFT may be straightforward, it is not without computational cost. For an N-point DFT, each frequenc y point will require N multiplications of the real valued x(n) times the complex valued exp(–jωkn). (This operation effectively requires two real multipliers.) Then, assuming there are N different frequency points, there will be N2 complex multiplications necessary for the computation of the DFT. This can produce large numbers very quickly. The fast Fourier transform (FFT) had its beginnings in 1965, long before the DSP chip was even a dream of engineer s. However, it took the computational power of computers to bring its importan ce to the attention of designers. It is sometimes thought that the FFT produces a different result than the DFT, but it does not. The FFT is simply a faster met hod of computing the DFT. Derivations of the FFT algorithm can be found in the re ferences in Appendix A, but it is worthwhile to see a simple illustration of how computational savings can be made using the FFT. Digital Filtering Using the FFT 215 Figure 9.4 DFT with Ham ming window and K = 20. 9.2.1 T he Deri vation of the FFT To begin, consider (9.6), which is a str eamlined version of (9.2). In it we replace ωk with the index k, and let WN replace the cum bersom e exp(–j2π/N). (These WNkn terms are often referred to as “twiddle factors.”) (9.6) 1 10 , )( )(1 0, N-, , k Wnx kXN nkn N …=⋅=∑− = We can now look at a simple 4-point DFT exam ple. If we expand (9.6) into four separate equations representing the four frequency points, we have (9.7) 9 46 43 40 46 44 42 40 43 42 41 40 40 40 40 40 4 )3( )2( )1( )0( )3()3( )2( )1( )0( )2()3( )2( )1( )0( )1()3( )2( )1( )0( )0( W x W x W x W x XW x W x W x W x XW x W x W x W x XW x W x W x W x X ⋅+⋅+⋅+⋅=⋅+⋅+⋅+⋅=⋅+⋅+⋅+⋅=⋅+⋅+⋅+⋅= Using the values of the twiddle factors in this special case we can represent this process as a m atrix multiplication as follows: (9.8) x X ⋅ ⎥⎥⎥⎥ ⎦⎤ ⎢⎢⎢⎢ ⎣⎡ −−− −−= j jj j 1 11 11 11 11 1 11 216 Practical Analog and Digital Filter Design Another popular m ethod desc ribing the m athem atical process, and one that better describes the com putational efficien cy we are looking for, is to use signal flow graphs, as shown in Figure 9.5. In th is description, all branches of the graph have a weight (or m ultiplier) of 1 except as noted. Figure 9.5 Four point decim ation-in-tim e FFT. It is clear from this illustration that fe w multiplications are necessary and also that sam ples are com bined at interm ediate points along the path. For exam ple, in the m iddle of the diagram we see that combinations of x0 and x2 as well as x1 and x3 are m ade. These com binations are then processed as a unit that saves individual computations. So instead of x0 being involved in four m ultiplications as shown in (9.7), it is involved only in two. This efficiency is continued for larger FFTs. For exam ple, if an 8-point DFT were required, two 4-point DFTs would be used with an additional butterfly stage. (The distin ctive cross-linked structure in Figure 9.5 is called a butterfly because if you rotate it 90 ° that is what it looks like.) As the length of the DFT increases, the num ber of butterfly stages increases as well, which produces the efficiency. The net ef fect is that the FFT algorithm would require N·log2(N) com plex m ultiplications instead of N2 as in the DFT case. The resulting efficiency can be seen in Table 9.1. One interesting feature of the proce ss shown in Figure 9.5 is that the frequency points along th e right side of the graph are in sequence, while the tim e points are in shuffled order. This pa rticular ordering is described as the decim ation-in-tim e (DIT) transform . There is also a decim ation-in-frequency (DIF) algorithm in which the time-dom ain samples rem ain in sequence, but the frequency com ponents are shuffled. A lthough the shuffled sequence m ay look arbitrary, we will see that the ordering can be exploited with a novel addressing mode available in m ost DSP processors. As an exam ple, consider an 8-point FFT looking only at the input se quence as shown in Table 9.2. C olumn 1 shows the shuffled order of x(n) as being x(0), x(4), x(2), and so forth. C olumn 2 shows the Digital Filtering Using the FFT 217 binary equivalent of the i ndex. C olumn 3 shows the result of reversing the bits of colum n 2. Finally, the last colum n shows that the indices are in order if viewed as bit-reversed values. This feature is exploited in DSP chips and is a common addressing m ode used for FFTs, one of the many efficiencies bu ilt into DSP chips. Table 9. 1 Com parison of DFT and FFT Com putations N DFT FFT Ratio (DFT/FFT) 16 256 64 4 64 4,096 384 10.7 256 65,536 2,048 32 1,024 1.05E06 10,240 102 4,096 16.8E06 49,152 341 16,384 268.E06 229,380 1,170 65,536 4.29E09 1.05E06 4,096 Table 9. 2 Bit-Rever sed Addr essing DIT order Index as binary Bit-reversed index Bit-reversed order 0 000 000 0 4 100 001 1 2 010 010 2 6 110 011 3 1 001 100 4 5 101 101 5 3 011 110 6 7 111 111 7 9.2.2 T he Inverse FFT Once the FFT has been com puted, we have inform ation about the frequency content of the signal. There are m any cas es when we will need to process this frequency inform ation in som e way and then want to transform the frequency content back to the tim e dom ain. For that we will need the inverse FFT. Because of the sym metry of the tran sform , it can be shown that the inverse FFT can be based on the FFT with sim ple operations both before and after the FFT, as shown in (9.9). As indicated, the inverse FFT of a sequence can be found by finding the FFT of the conjugate of the sequence, and then conjugating the result and dividing by N (the length of the FFT). We will m ake use of this fact in Section 9.4. At this point we are ready to discuss the C code necessary to im plem ent the FFT algorithm . NX FFTX FFT** 1 )]( [)(=− (9.9) 218 Practical Analog and Digital Filter Design 9.3 C CODE FOR THE FFT As we begin the discussion of the C code for computation of the FFT, it is important to note the differences be tween program ming for a general purpose processor and a DSP chip. The DSP ch ip is a m icroprocessor designed to implem ent the types of com putations that are com monplace in digital signal processing applications. These include co mplex arithm etic, convolution, and fast Fourier transform s. DSP processors have multiple data and control buses and highly efficient instructional com mands. Fo r exam ple, m ost DSP processors will be able to accom plish a m ultiply-add inst ruction in only one instruction cycle while general purpose processors would require m any more. Another m ajor difference is the fact that DSP chips have an addressing m ode that includes bit-reversed addressing. This elim inates the shuffling of data points (either tim e-dom ain or frequency -domain) that we need in our general purpose code. As well, DSP processors have dual m emories to hold the real and im aginary parts of complex numbers, while we have to im plem ent a com plex data ty pe to handle the FFT com putations. Therefore, it is recom mended that if your project will be im plem ented on a DSP chip, you use the features of the software for that chip to m ost efficiently im plem ent your project. B ut if y ou have a need to implem ent the FFT on a general purpose processor, we will develop that code now. There are a num ber of FFT algorithm s discussed in the available references, but we will discuss the com mon decim ation-in-tim e radix-2 algorithm . A radix-2 implem entation requires that the num ber of input data points be equal to a power of two, as shown in (9.10), where B is an integer. Although this m ay first appear to be a lim itation, it is not. Any input sequence can sim ply be increased to the required size by adding zeros to the end of the sequence. This operation is referred to as “padding” the sequence and in no wa y affects the com putation of the FFT. (9.10) BN2= Listing 9.1 shows FastFT, a function to com pute the DIT implem entation of the FFT. This function has been ad apted from Orfanidis’ text listed in Appendix A and is sim ilar to others described in the literature. The input signal has been placed into a com plex array X since this particular algorithm will perform an “in-place” computation of the FFT. That means that after the FFT has been completed, the resulting com plex valu ed FFT will reside in the array X. This will make the use of m emory more efficient. In addition to the input array , the function also receives the length of the FFT and th e number of bits required to describe each index. The first step in the procedure is to swap the values in the input array as required in a DIT im plem entation. This is accom plished in the first loop and makes use of the RevBits function shown in Listing 9.2 (also adapted from the Orfanidis text). After the i nput values have been swapped, the FFT is com puted by Digital Filtering Using the FFT 219 means of sequential calculation of the bu tterfly stages with the required twiddle factors computed first. /*============================================================ FastFT() - radix-2 decimation-in-time Fast Fourier Transform Prototype: void FastFT(short Length, short Bits, complex *X); Arguments: Length - length of FFT Bits - Length = 2^Bits X - ptr to array of complex numbers Return: none (conversion done in place) ============================================================*/ void FastFT(short Length, short Bits, complex *X) { long k, i, p, q, /* counters and indices */ M; /* stage of FFT */ complex A, B, V, W, Tmp; /* complex constants */ short n, /* counter */ RIndex; /* reversed ndex */ /* Swap the values in x */ for(n = 0; n < Length; n++) { RIndex = RevBits(n,Bits); /* get reversed index */ if (RIndex < n) continue; /* only need to swap half */ Tmp = *(X+n); *(X+n) = *(X+RIndex); *(X+RIndex) = Tmp; } /* Implement the butterfly in stages */ M = 2; while (M <= Length) /* while loop controls stages of FFT */ { W.re = cos(2*PI / M); /* twiddle factors */ W.im = sin(2*PI / M); V.re = 1; V.im = 0; for(k = 0; k < M/2; k++) /* index through stages */ { for(i = 0; i < Length; i += M) { p = k + i; q = p + M / 2; A = X[p]; B = cmul(X[q],V); X[p] = cadd(A,B); /* butterfly operations */ X[q] = csub(A,B); } V = cmul(V,W); } M = 2 * M; } } Listing 9.1 FastFT function. These two functions can now be used to compute the FFT of any input sequence. All that is required is that the sequence be adjusted to a length that is a power of two by padding the end of the sequence with zeros. The function can then be provided with the pointer to the sequence, the length of the sequence, and the number of bits in the indices. After the function has completed its work, the array X will hold the complex valued FFT. These values will be stored as the real and imaginary values of th e transform, but can be better interpreted as the 220 Practical Analog and Digital Filter Design magnitude and phase angle of the transf orm. The conversion from one form to another is shown in (9.11)–(9.12). When com puting the phase angle y ou should use the atan2 function that takes both the real and imaginary values as argum ents. This guarantees that the angle will be placed in the correct quadrant. /*============================================================ RevBits() - reverses the bits in an integer Prototype: short RevBits(short Input, short NumBits); Arguments: Input - integer to reverse NumBits - number of bits used Return: integer with bits reversed ============================================================*/ /* Adapted from Orfanidis - Intro. to Signal Processing */ short RevBits(short Input, short NumBits) { short i, /* loop counter */ RevInput; /* interger with reversed bit values */ RevInput = 0; /* Loop through Input, bit by bit. If bit is set, set appropriate bit in RevInput, and clear bit in Input.*/ for(i = NumBits-1; i >= 0 ;i--) { if ((Input >> i) == 1) { RevInput += (1 << (NumBits-1-i)); Input -= (1 << i); } } return RevInput; } Listing 9.2 RevBits function. 2 2) Im() Re( X X Magnitude + = (9.11) )) Re(/) arctan(Im( X X Angle= (9.12) The interpretation of the resulting freque ncy response is easy as long as we remember that the values of the FFT w ill be spread from zero frequency up to the sampling frequency . Therefore, if we had a 1,024-point FFT com puted on a sequence that had been sampled at a frequency of 20 kHz, the values in the transform ed sequence would be spaced every 19.53 Hz (20 kHz ÷ 1024). This would mean that the first sam ple was the response at 0 Hz (or the DC value), and the last value would represent the response at 19,980.47 Hz. R emember that the last half of the response will be a m irror im age of the first half. Therefore, for this particular case, only the first half of th e FFT values would need to be analyzed. The others will sim ply be duplicates. Digital Filtering Using the FFT 221 9.4 APPLICATION OF FFT TO FILTERING There are m any applications for the FFT. Frequency analysis, spectral densities, and filtering are am ong the m ore popular. Sin ce this is a text about filtering, we discuss how the FFT can be used in filtering applications. To begin this discussion, we review the process of FIR filtering first. Once FIR filter coefficients have been determ ined, the output signal of the filter can be determ ined from the input si gnal by convolving the filter co efficients and the input signal, as shown in (9.13). We learned in Chapter 5 that convolution in the tim e domain was equivalent to sim ple m ultiplication in the frequency dom ain, as shown in (9.14). (9.13) 1 , ,1 ,0 ,) ()( )()( )(1 0− =−⋅ =∗=∑− =N nknxkh nxnh nyM k… )()( )( zXzH zY ⋅= (9.14) Since we now have a fast algorithm for determ ining the transform of a tim e- domain signal, it m ay be useful to consid er the alternative presented by (9.14). Let’s consider the steps involved in using transform s to im plem ent the filtering process: 1. Transform the filter coeffients: H(z) = FFT [ h(n) ]. 2. Transform the input signal: X(z) = FFT [ x(n) ]. 3. Multiply the two com plex sequences: Y(z) = H (z)·X(z). 4. Inverse transform to find the output: y(n) = FFT -1 [ Y(z) ]. The process outlined above m ay or m ay not prove to be faster than the convolution of (9.13). It all depends on th e num ber of filter coefficients and the number of points in the FFT. The text by Proakis and M anolakis m entioned in Appendix A offers a detailed com parison that will be discussed further at the end of this section. Listing 9.3 shows Dig_FFT_Filt that perform s steps 2 through 4 above. Note that it is assum ed that th e filter coefficients have already been transform ed and stored in H. The function first transform s the input signal X, then multiplies the coefficients times the transform of X, and finally com putes the inverse FFT. Note that the results of each of these steps are stored in X. There are m any cases when the length of the input signal exceeds the size of the FFT that can be applied. In that case, the signal m ust be broken into sm aller, more manageable, sections and the FFT f iltering algorithm applied to each section. Unfortunately, it is not as sim ple as taking each N-point group of input samples and generating an output group. The resu lting patched-together sequence would undoubtedly have discontinuities at the combination points. This problem can be 222 Practical Analog and Digital Filter Design alleviated by keeping some processed samples from each grouping and using them as the initial points in the next sequence. This is exactly what was done in the FIR filtering code described in Section 8.3.2 and represents providing initial conditions to the filtering process. When applied in FFT filtering this process is often called the overlap-and-save method. /*============================================================ Dig_FFT_Filt() - performs FFT filtering Prototype: void Dig_FFT_Filt(complex *X, complex *H, short numb_coefs, short FFT_size, short Bits); Return: error value. Arguments: X - input data H - transform of filter coefs numb_coefs - number of filter coefs FFT_size - number of pts in FFT Bits - FFT_size = 2^Bits ============================================================*/ void Dig_FFT_Filt(complex *X, complex *H, short FFT_size, short Bits) { short i; /* Perform FFT on X */ FastFT(FFT_size,Bits,X); /* Multiply X and H */ for (i = 0; i < FFT_size; i++) { X[i] = cmul(X[i],H[i]);} /* Get inverse FFT of X */ /* Conjugate input */ for (i = 0; i < FFT_size; i++) { X[i] = cconj(X[i]);} /* Perform FFT */ FastFT(FFT_size,Bits,X); /* Conjugate again */ for (i = 0; i < FFT_size; i++) { X[i] = cconj(X[i]);} /* X now holds the filtered data */ return; } Listing 9.3 Dig_FFT_Filt function. Figure 9.6 shows the process. The input signal is padded with M–1 initial zeros (assuming there are M filter coefficients). Then, the remaining signal is broken into sections containing L values where L is defined in (9.15). As pictured in the diagram, there will be N samples transformed in each operation, but the first M–1 will be the values saved from the last M–1 values of the previous operation (except for the initial grouping, which will have M–1 zeros.) Once the FFT filtering has been completed on the grouping, the last L values of the sequence are saved, discarding the first M–1 values. This operation will result in an error-free result when the y groupings are reassembled. Digital Filtering Using the FFT 223 )1 (−−= M NL (9.15) Figure 9.6 Using the overlap-and-save method for linear FFT filtering. WFilter does have an option for FFT filtering available if an FIR filter has been designed. Once the filter has been de signed, the user can elect to filter a WAV file by selecting Options->Filter Wave File. The Filter Wave File dialog box will appear, as shown in Figure 9.7, and will provide the user the option of filtering the waveform via the m ore trad itional m ethod of convol ution as discussed in Chapter 7, or using the FFT tec hniques discussed in this chapter. Figure 9.7 Filter Wave File dialog box. 224 Practical Analog and Digital Filter Design Unfortunately , the true speed of the FFT technique cannot be realized on a general-purpose processor that m any users will be using to filter waveform s. As mentioned previously, the general-purpose processor will not have the option of bit-reversed addressing or manipulati on of com plex num bers in two m emory locations. Therefore, the true effici ency of the FFT algorithm cannot be demonstrated on a general-purpose processor. However, Proakis and M anolakis have di scussed the theoretical efficiencies of this process that we can review at th is point. They have determ ined that the number of com plex m ultiplications required per output point can be determ ined by (9.16). Recognizing that there are four real multiplications needed for each complex m ultiplication, and also recognizing that for convolution there are M real multiplications needed for each output point , a com parison can be m ade in Table 9.3. In the table, the left-hand colum n represents the num ber of data points N in the FFT. The top row gives the various numbers of filter coefficients used M. Within the table are given the num ber of real multiplications per output point necessary for the calculation of the FFT. These num bers should be com pared to the M value, which represents the num ber of calculations per output point for the convolution m ethod. Not all filter applica tions should consider the FFT approach as depicted in colum n 2 (M = 32). In the best case, the FFT approach would require 41 real m ultiplications to the convol ution approach of 32. However, it is apparent that as the num ber of filter coe fficients increase, th e FFT approach can provide real efficiencies. A second point to recognize is that the num ber of points in the FFT should also be considered when setting up the filtering system . In general, it appears that the size of the FF T should be set to approxim ately 8 tim es the num ber of coefficients used in the filter. LN Nc)2( log2⋅⋅= (9.16) Table 9. 3 Num ber of Real Multiplica tions per Output Point N=F FT size M=32 M=64 M=128 M=256 M=512 64 54 - - - - 128 43 64 - - - 256 41 48 72 - - 512 43 46 54 80 - 1,024 46 47 51 59 88 2,048 49 50 52 55 64 4,096 53 53 54 56 60 8,192 57 56 57 58 60 Digital Filtering Using the FFT 225 9.5 CONCLUSION This completes our chapter on the FFT and its application to linear filtering. The FFT is a valuable function that provides a link from the time domain to the frequency domain. We have found that FFT will find application to linear filtering when the number of coefficients is la rge enough to warrant the more complex computations. This is also the conclusion for the te xt. Along the way, we have developed some of the most time-honored methods used in analog and digital filter design. By no means have we explored every nua nce of filter design, and we see new techniques being developed every day. However, we have developed the key approximation techniques used today. The methods used can serve as a template in the development of other approximati ons. We have been able to adjust normalized functions for use in a variet y of selectivities. We have shown one method of implementing analog filters and di scussed some of the potential pitfalls that must be considered. After the introduction of some principles of discrete-time theory, we learned how to design both FIR and IIR digital filters using two entirely different techniques. C code for the implementation of these filter types was developed and analyzed. And finally, we finished with the discussion of the FFT in filtering applications. I hope this text and the acco mpanying software disc will serve as a starting point for your journey into the exciting field of filter design. 226 Practical Analog and Digital Filter Design 227 Appendix A Technical References This appendix includes a list of references appropriate for the study of analog and digital filter design methods using C. ADVANCED MATHEMATICS REFERENCES Abramowitz, Milton, and Stegun, Irene, eds., Handbook of Mathematical Functions , Dover Publications, Inc., New York, 1965. Morris, John L., Computational Methods in Elementary Numerical Analysis , John Wiley & Sons, New York, 1983. Rice, John R., Numerical Methods, Software, and Analysis , 2nd ed., Academic Press, Inc., San Diego, CA, 1993. Spiegel, Murray R., Mathematical Handbook of Formulas and Tables , Schaum’s Outline in Mathematics, McGraw-Hill Book Co., New York, 1968. ANALOG FILTER DESIGN REFERENCES Daniels, Richard W., Approximation Methods for Electronic Filter Design , McGraw-Hill Book Company, New York, 1974. Daryanani, Gobind, Principles of Active Network Synthesis and Design , John Wiley & Sons, New York, 1976. Johnson, D. E., Johnson, J. R., and Moore, H. P., A Handbook of Active Filters , Prentice Hall, Inc., Englewood Cliffs, NJ, 1980. Moschytz, G. S., and Horn, P., Active Filter Design Handbook , John Wiley & Sons, New York, 1981. Sedra, Adel S., and Brackett, Peter O., Filter Theory and Design: Active and Passive, Matrix Publishers, Inc., Champaign, IL, 1978. 228 Practical Analog and Digital Filter Design Schaumann, R., Ghausi, Mohammed S., and Laker, Kenneth R., Design of Analog Filters: Passive, Acti ve RC and Switched Capacitor , Prentice Hall, Inc., Englewood Cliffs, NJ, 1990. Schaumann, R., and Van Valkenburg, M. E., Design of Analog Filters , Oxford University Press, New York, 2001. C PROGRAMMING REFERENCES Bronson, Gary, C for Engineers and Scientists , West Publishing Co., New York, 1993. Deitel, H. M., and Deitel, P. J., C How to Program, 2nd ed., Prentice Hall, Inc., Englewood Cliffs, NJ, 1994. Hanly, J. R., Koffman, E., and Friedman, F., Problem Solving and Program Design in C , Addison-Wesley Publishing Co., Reading, MA, 1993. Kernighan, Brian W., and Ritchie, Dennis M., The C Programming Language , Prentice Hall, Inc., Englewood Cliffs, NJ, 1978. Maguire, Steve, Writing Solid Code , Microsoft Press, Redmond, WA, 1993. McConnell, Steve, Code Complete , Microsoft Press, Redmond, WA, 1993. Waite, Mitchell, and Prata, Stephen, The Waite Group’s New C Primer Plus, Howard W. Sams & Co., Carmel, IN, 1990. DIGITAL FILTER DESIGN REFERENCES Antoniou, Andreas, Digital Filters: Analysis, Design and Applications , 2nd ed., McGraw-Hill, Inc., New York, 1993. Embree, Paul M., and Kimble, Bruce, C Language Algorithms for Digital Signal Processing , Prentice Hall, Inc., Englewood Cliffs, NJ, 1991. Oppenheim, Alan V., and Schafer, Ronald W., Digital Signal Processing , Prentice Hall, Inc., Englewood Cliffs, NJ, 1975. Orfanidis, Sophocles J., Introduction to Signal Processing , Prentice Hall, Inc., Englewood Cliffs, NJ, 1996. Parks, T. W., and Burrus, C. S., Digital Filter Design , John Wiley & Sons, New York, 1987. Proakis, John G., and Manolakis, Dimitris G., Digital Signal Processing: Principles, Algorithms, and Applications , 2nd ed., Macmillan Publishing Co., New York, 1992. Programs for Digital Signal Processing, edited by Digital Signal Processing Committee of IEEE ASSP Society, IEEE Press, New York, 1979. Roberts, Richard A., and Mullis, Clifford T., Digital Signal Processing , Addison-Wesley Publishing Co., Reading, MA, 1987. 229 Appendix B Filter Design Software and C Code WFILTER FILTER DESIGN SOFTWARE WFilter is an analog and digital filter design package for Windows. To install WFilter on your computer, simply run the SETUP.EXE file in the \WFILTER directory on the accompanying CD. WFilter determines the transfer functi on coefficients necessary for analog filters, and for digital FIR and IIR filters. The user is allowed to make choices of lowpass, highpass, bandpass, or bandstop f ilters for frequency selectivity as well as choices of approximation. For digital IIR and analog filters, the approximation choices are Butterworth, Chebyshev, inverse Chebyshev, and elliptic. For digital FIR filters, the rectangular, Barlett, Blackman, Hamming, von Hann, and Kaiser windows are available, as well as the Parks-McClellan optimization technique. The order of FIR filters based on design specifications cannot be predicted as accurately as for IIR and analog filters, th erefore the user is given the option of changing the filter length during the design process. After the filter has been designed, the user can view the pole-zero plot, as well as the magnitude and phase frequency responses. The filter design parameters or the frequency response parameters can also be edited for ease of use. Filter parameters can be saved and printed, and all plots can be printed or included in other documents by copying to the clipboard. In addition, for analog filters, the Spice circuit file can be generated to aid in the analysis of active filters. After WFilter generated the file, it can be saved or printed. Digital filters may be used to f ilter wave files. Afte r specifying an input wave file, a filtered output file can be generated, and both i nput and output files can be played (sound card must be present). In the case of an FIR filter, the user is given the option of filtering the sound file using convolution or the FFT. 230 Practical Analog and Digital Filter Design C COMPUTER CODE All of the C code discussed in the first eight chapters of this text (and much more) is included in the \C_Code directory on the CD that accompan ies this text. The three short FFT functions discussed in Chapter 9 are listed in the text. The C code files originally acco mpanied the text Analog and Digital Filter Design Using C by Les Thede. There are thr ee DOS executables that have been compiled by Microsoft Corp's Visual C++ compiler. The majority of WFilter is based on these files but with a GUI interface added for convenience. FILTER.EXE - designs analog and digital filters. ANALOG.EXE - implements analog active filters. DIGITAL.EXE - implements digital IIR/FIR filters. Three subdirectories have also been created on this disc to hold the source (.C), header (.H), and information (.TXT) files. In addition, sample sound files have been included to be used with the DIGITAL program. Appendixes C through I discuss various C functions that are important parts of the filter design software. FEEDBACK I would appreciate any feedback you care to share about the text and software. Errors, problems, suggestions for improvement, and general comments can be forwarded to me via e-mail or the more traditional means. Thank you. Les Thede - ECCS Department Ohio Northern University 525 S. Main Street Ada, Ohio 45810 Email: [email protected] 231 Appendix C Filter Design Using C Although learning analog and digital filter design techniques is the first objective of this text, many readers may be interested in the use of C in the design and implementation of analog and digital filte rs. Therefore, supplementary material dealing with these programming issues is included in this and succeeding appendixes. All of the C code discussed in the first eight chapters of this text (and much more) is also included on the CD in the directory called \C_Code. The three short FFT functions in Chapter 9 are provided in the text. The C programming language (and its succe ssor C++) is a predominant force in engineering and computer science. In particular, C is the primary language used in digital filter design (with the possible exception of hardware-specific assembly language). C provides the combination of higher-level constructs while producing fast, compact executables. Other languages are available, and could be used in filter design, but C provides the best combination of efficiency and effectiveness. Several C language references are listed in Appendix A. The primary data elements describing our filter will be used by a number of the design functions and therefore should be made available in a neat package. An array would be nice, but arrays require that all elements are of the same data type. Therefore the only reasonable choice is a structure. We will store our filter data elements in a structure called Filt_Params . We can assume that we will need all of the filter specifications discussed in the first chapter. These will include the pa ssband and stopband e dge frequencies ( wpass1 , wpass2 , wstop1 , and wstop2 ) and gains ( apass1 , apass2 , astop1 , and astop2 ). We will also need indicators of the filter selectivity, the approximation method, and the implementation type ( select , approx , and implem ). The sampling frequency ( fsamp ) is an additional element that will be necessary for digital filters, but will not be used by analog filters. All of these variables represent the input specification for th e filter design and are shown in the Filt_Params structure below. 232 Practical Analog and Digital Filter Design typedef struct { double apass1,apass2, /* passband gain's */ astop1,astop2, /* stopband gain's */ wpass1,wpass2, /* passband edge freq's */ wstop1,wstop2, /* stopband edge freq's */ fsamp, /* samp freq for dig filt */ gain, /* gain multiplier */ *acoefs,*bcoefs; /* ptr's to coefs */ int order; /* order or length of filter */ /* selectivity, approximation and implementation */ char select,approx,implem; } Filt_Params; In addition to the input specifications, th ere will also be a need for another set of filter data once the filter has been designed. The filter's order ( order ) indicates the size of the filter's transfer function. The filter's gain constant ( gain ) and pointers to two sets of filter coefficients ( acoefs and bcoefs ) will completely describe the filter's transfer function and will be stored in the structure as type double . It is impossible to determine the number of coefficients necessary to describe a filter before the filter is designed. We will design some filters with fewer than 10 coefficients, but other designs may require more than 200 coefficients. For that reason we will use pointers to the arrays instead of simply defining acoefs and bcoefs as large arrays. Using large a rrays would make the structure unnecessarily large, and there would still be no guarantee that these fixed arrays would be large enough to store every filter that might be designed. It will be far more efficient to determine the size of the array necessary for the individual design, then allocate memory dynamically for the coefficient array, and finally store the pointer (address) to the array in the structure. That way only a pointer variable needs to be stored in th e structure, not an entire array. As it is, our Filt_Params structure is fairly large, and since we will be using this structure with most of the functions that we develop, it would be much more efficient to transfer a pointer (address) to the structure inst ead of the structure itself. Actually, there is another reason for doing this. In C all arguments of functions are “called by value,” which m eans that a copy of the argument is transferred to the function. This practice does not allow the transferred variable to be changed by the function. (Technically, we can change the variable all we want within the function, but when we leave the function the original value of the variable within the calling function remains unchanged.) Since our filter design functions will need to make changes to the data values stored in the structure, sending a copy of the structure to the function without allowing data values to change would be unacceptable. However, if we send a pointer to the structure (or actually a copy of the address), we w ill be able to access the actual memory locations of the data stored in the structure. In this way, our filter design functions will be able to enter values in to the structure as necessary. 233 Appendix D C Code for Normalized Approximation Functions In the main file of the FILTER program on the CD, we called Calc_Filter_Coefs (as shown in Listing D.1) in order to calculate the necessary filter coefficients for the user-specified design. That function in turn called one of three other functions named Calc_Analog_Coefs, Calc_DigFIR_Coefs, or Calc_DigIIR_Coefs . /*==================================================== Calc_Filter_Coefs() - determines implementation and calls appropriate calculation function Prototype: int Calc_Filter_Coefs(Filt_Params *FP); Return: error value Arguments: FP - ptr to struct holding filter params ====================================================*/ int Calc_Filter_Coefs(Filt_Params *FP) { int Error; /* error value */ /* Call correct calc function for analog, digital FIR or IIR filters. */ switch(FP->implem) { case 'A': Error = Calc_Analog_Coefs(FP); if(Error) { return 10*Error+1;} break; case 'F': Error = Calc_DigFIR_Coefs(FP); if(Error) { return 10*Error+2;} break; case 'I': Error = Calc_DigIIR_Coefs(FP); if(Error) { return 10*Error+3;} break; default: return ERR_FILTER; } return ERR_NONE; } Listing D.1 Calc_Filter_Coefs function. 234 Practical Analog and Digital Filter Design The implementation type for the filter is stored in the FP->implem variable and is used to select an analog, digital FIR, or digital IIR filter implementation. In each case the user’s specifications are tran sferred to the next appropriate function via FP, the pointer to the Filt_Params structure discussed in Appendix C. In this function, as well as others we will discuss, a simple error reporting system is used. Most of the functions used will return an integer value that will be zero if no error occurred and nonzero if an error did occur. At each new level of the program, the error value is multiplied by 10 and a single digit value is added. The result of this practice will be a multidigit error value wh ere each digit represents a different level in the program. This can be used to trace the error to a particular function. The Calc_Analog_Coefs function is given in Listing D.2. It is designed primarily to organize the calculation process, not to perform the calculations explicitly. The first function called is Calc_Filter_Order, which determines the filter order from the user specifications in FP. Next the normalized filter coefficients are determined using Calc_Normal_Coefs, which stores the coefficients in the Filt_Params structure. Finally, the coefficients are unnormalized to lowpass, highpass, bandpass, or bandstop coefficients at the user-specified frequencies via the Unnormalize_Coefs function. /*==================================================== Calc_Analog_Coefs() - calcs normal analog coefs Prototype: int Calc_Analog_Coefs(Filt_Params *FP); Return: error value Arguments: FP - ptr to struct holding filter params ====================================================*/ int Calc_Analog_Coefs(Filt_Params *FP) { int Error; /* error value */ /* Determine filter order, then normal coefs, then unnormalize them. */ Error = Calc_Filter_Order(FP); if(Error) { return 10*Error+1;} Error = Calc_Normal_Coefs(FP); if(Error) { return 10*Error+2;} Error = Unnormalize_Coefs(FP); if(Error) { return 10*Error+3;} return ERR_NONE; } Listing D.2 Calc_Analog_Coefs function. In the case of the Calc_Normal_Coefs function, as shown in Listing D.3, we must allow for individual functions to carry out the actual coefficient calculation. However, before we actually make the coefficient calculations, we allocate memory for the storage of the coefficients. By taking care of this necessary task in Calc_Normal_Coefs , we eliminate the need to handle it in C Code for Normalized Approximation Functions 235 each of the four individual functions. It is important to remember that by simply reserving a place in the Filt_Params structure for the pointers acoefs and bcoefs , we have not reserved any memory for the coefficients themselves. The pointers were originally set to zero or NULL by the calloc command we used to allocate memory for the Filt_Params structure. This effec tively says that there is no memory available for coefficient stor age, and if we try to access a coefficient while in this state, we would get an error. In fact, we hope we get an error to let us know that there is a problem in our algorithm. It would be far worse to have the pointers hold a nonzero value that is pointing to some random address in memory. In that case, we would get no error, but the values we would be accessing would be random nonsense. /*==================================================== Calc_Normal_Coefs() - allocates memory for coefs and calls proper function to calc coefs Prototype: int Calc_Normal_Coefs(Filt_Params *FP); Return: error value Arguments: FP - ptr to struct holding filter params ====================================================*/ int Calc_Normal_Coefs(Filt_Params *FP) { int Number_Coefs, /* Number of coefs in array */ Error; /* error value */ /* Allocate memory for coefs. There are 3 coefs for each quadratic. First-order factors are considered as quadratics. */ Number_Coefs = 3 * ((FP->order + 1) / 2); FP->acoefs = (double *) malloc(Number_Coefs * sizeof(double)); if(!FP->acoefs) { return ERR_ALLOC;} FP->bcoefs = (double *) malloc(Number_Coefs * sizeof(double)); if(!FP->bcoefs) { return ERR_ALLOC;} /* Calculate coefs based on approximation. */ switch (FP->approx) { case 'B': Error = Calc_Butter_Coefs(FP); if(Error) { return 10*Error+1;} break; case 'C': Error = Calc_Cheby_Coefs(FP); if(Error) { return 10*Error+2;} break; case 'E': Error = Calc_Ellipt_Coefs(FP); if(Error) { return 10*Error+3;} break; case 'I': Error = Calc_ICheby_Coefs(FP); if(Error) { return 10*Error+4;} break; default: return ERR_FILTER; } return ERR_NONE; } Listing D.3 Calc_Normal_Coefs function. 236 Practical Analog and Digital Filter Design Up to this point in the program, we did not have the necessary information to determine the number of coe fficients in each of the acoefs and bcoefs arrays. But since we now have the order of the filter, we can determine the number of coefficients exactly in the following ma nner. Each quadratic factor of the approximation function will require three coefficients (the s2-term coefficient, the s-term coefficient, and the constant term coefficient). In addition, we will treat any odd-order approximation first-order factor as a quadratic. We can make use of the integer math in C to simplify the calculation for the number of coefficients based on the order of the filter. Once the correct number of coeffi cients has been determined, malloc is used to allocate memory for that number of double s, and if an error occurs, we leave the function. The coefficient arrays are organized in the following manner. The acoefs array stores the coefficients fo r the numerator factors while the bcoefs array will store the coefficients for the denominator factors. ( acoefs and bcoefs will take on different meanings in the digital filter design so for now we can remember A for above the line and B for below the line.) If the approximation function has an odd-order, the first-order coefficients are stored as a quadratic in the first three coefficients of each array with the s2-term set to zero. The next three coefficients are for the first true quadratic, and then all other quadratics follow. If the approximation function has an even-order, then the first three coefficients are for the first quadra tic, the next three coefficients for the second quadratic, and so on. Within the three coefficients, the first coefficient always refers to the s 2-term, the second refers to the s-term coefficients, and the last coefficient is the constant term in the quadratic factor. The Calc_Butter_Coefs function shown in Listing D.4 is an example of the approximation calculation function. The function first checks for valid pointers and order values, and then proceeds to ma ke the calculations outlined in Section D.2. If the order is odd, the first order coefficients are calculated followed by all coefficients for quadratic factors. The other individual functions for calculating the normalized coefficients for the four approximation methods can be found on the software disc in the \C_CODE\F ILTER\F_DESIGN.C module. They all determine the coefficients in a manner consistent with our development earlier in this chapter. There are a number of advanced math functions required by our approximation functions. These functions are not contained in F_DESIGN.C as are the rest of the functions discussed in th is appendix, but are instead a part of the \C_CODE\FILTER\ADV_MATH.C m odule. These include the asinh and acosh functions used in the Chebyshev functions as well as the elliptic integral and Jacobian elliptic functions necessary to define the elliptic approximation. The values of these functions are typically calculated by the arithmetic-geometric mean method of iteration. A detaile d discussion of this method and the elliptic functions in general is beyond the scope of this te xt, but references have been provided in the analog and digital filter design sections of Appendix A. C Code for Normalized Approximation Functions 237 /*==================================================== Calc_Butter_Coefs() - calcs normal Butterworth coefs Prototype: int Calc_Butter_Coefs(Filt_Params *FP); Return: error value Arguments: FP - ptr to struct holding filter params ====================================================*/ int Calc_Butter_Coefs(Filt_Params *FP) { int m,a,b; /* Loop counter and indices*/ double R,epsilon, /* Intermediate values */ theta, /* Angle location of poles */ sigma,omega; /* Real/imag pos of poles */ /* Check for NULL ptrs and zero order. */ if( !FP->acoefs) { return ERR_NULL;} if( !FP->bcoefs) { return ERR_NULL;} if(FP->order <= 0) { return ERR_VALUE;} /* Make calculations of necessary constants. */ epsilon = sqrt( pow(10.0,-0.1*FP->apass1) - 1.0 ); R = pow(epsilon,-1.0/FP->order); /* Initialize gain to 1.0. Start indices at 0 */ FP->gain = 1.0; a = 0; b = 0; /* Handle odd order if necessary. */ if(FP->order % 2) { FP->acoefs[a++] = 0.0; FP->acoefs[a++] = 0.0; FP->acoefs[a++] = R; FP->bcoefs[b++] = 0.0; FP->bcoefs[b++] = 1.0; FP->bcoefs[b++] = R; } /* Handle all quadratic terms. */ for(m = 0;m < FP->order/2;m++) { /* Calc angle first, then real and imag pos. */ theta = PI*(2*m + FP->order +1) / (2 * FP->order); sigma = R * cos(theta); omega = R * sin(theta); /* Set the quadratic coefs. */ FP->acoefs[a++] = 0.0; FP->acoefs[a++] = 0.0; FP->acoefs[a++] = sigma*sigma+omega*omega; FP->bcoefs[b++] = 1.0; FP->bcoefs[b++] = -2 * sigma; FP->bcoefs[b++] = sigma*sigma+omega*omega; } return ERR_NONE; } Listing D.4 Calc_Butter_Coefs function. The Ellip_Integral function is shown in Listing D.5 and uses the arithmetic-geometric mean method of dete rmining the complete elliptic integral, as defined in (2.62). It takes as an argument the modulus k and returns the value of the complete elliptic integral. MAX_TERMS and ERR_SMALL have been defined 238 Practical Analog and Digital Filter Design as 100 and 1E-15, respectively, in the ADV_MATH.H include file. Of course these values could be changed as necessary. /*==================================================== Ellip_Integral() - calcs complete elliptic integral using arithmetic-geometric mean method Prototype: void Ellip_Integral(double k); Return: complete elliptic integral value Arguments: k - the modulus of the integral ====================================================*/ double Ellip_Integral(double k) { int i; /* Loop counter. */ double A[MAX_TERMS],B[MAX_TERMS], C[MAX_TERMS]; /* Array storage values. */ /* Square the modulus as required by this method.*/ k = k * k; /* Initialize the starting values. */ A[0] = 1; B[0] = sqrt(1-k); C[0] = sqrt(k); /* Iterate until error is small enough. */ for(i = 1; i < MAX_TERMS ;i++) { A[i] = (A[i-1] + B[i-1])/2; B[i] = sqrt(A[i-1]*B[i-1]); C[i] = (A[i-1] - B[i-1])/2; if(C[i] < ERR_SMALL) { break;} } return PI / (2 * A[i]); } Listing D.5 Ellip_Integral function. 239 Appendix E C Code for Unnormalized Approximation Functions The Unnormalize_Coefs , which is given in Listing E.1, first determines the variables used for unnormalization. The unnormalization frequency freq for lowpass and highpass, as well as the center frequency Wo and the bandwidth BW for bandpass and bandstop cases are dete rmined differently for the inverse Chebyshev case as compared to the other approximation methods. After these calculations, the appropriate unnormalization function is chosen based on the selectivity of the filter. Each of the specific functions called uses the Filt_Params structure pointer FP as well as the appropriate unnormalization variables. Any errors that occur in the functions are handled in the manner described in Appendix D to allow easy identification of the location of the problem. Listing E.2 contains the Unnorm_LP_Coefs , which handles the lowpass unnormalization. The function first determines whether there is a first-order factor by determining if the order of the approximation is odd. Remembering our technique of always placing first-order fact ors in the coefficient arrays first, we can safely refer to the constant term coefficients using the index of 2. (The coefficients are arranged with the s 2-term coefficient first, then the s-term coefficient, and finally the constant term coefficient.) Each additional quadratic factor then follows in the same order. The coefficients within the loop are adjusted as we determined in Section 3.1. Proper indexing is accomplished by using cf to index individual coefficients based on qd, the quadratic indicator. Using this technique, any coefficient using cf as an index is referring to an s 2-term coefficient, while if the co efficient has an index of cf+1, it is an s-term coefficient, and cf+2 will be the index for the constant term of a quadratic expression. Note that we are us ing the efficient C style where a *= b ; is equivalent to a = a * b;. 240 Practical Analog and Digital Filter Design The Unnorm_HP_Coefs function is very similar to the previous function and therefore will not be discussed he re. That function can be found in the \C_CODE\FILTER\F_DESIGN.C module. /*==================================================== Unnormalize_Coefs() - converts normal lowpass coefs to unnormalized LP/HP/BP/BS. Prototype: int Unnormalize_Coefs(Filt_Params *FP); Return: error value Arguments: FP - ptr to struct holding filter params ====================================================*/ int Unnormalize_Coefs(Filt_Params *FP) { int Error; /* error value */ double freq, /* unnormalizing freq for LP & HP */ BW, /* unnormal. bandwidth for BP & BS */ Wo; /* unnormal. ctr freq for BP & BS */ /* Calc freq, Wo and BW based on approx method */ switch(FP->approx) { case 'B': case 'C': case 'E': freq = FP->wpass1; Wo = sqrt(FP->wpass1 * FP->wpass2); BW = FP->wpass2 - FP->wpass1; break; case 'I': freq = FP->wstop1; Wo = sqrt(FP->wstop1 * FP->wstop2); BW = FP->wstop2 - FP->wstop1; break; default: return ERR_FILTER; } /* Call unnormal. function based on selectivity */ switch(FP->select) { case 'L': Error = Unnorm_LP_Coefs(FP,freq); if(Error) { return 10*Error+1;} break; case 'H': Error = Unnorm_HP_Coefs(FP,freq); if(Error) { return 10*Error+2;} break; case 'P': Error = Unnorm_BP_Coefs(FP,BW,Wo); if(Error) { return 10*Error+3;} break; case 'S': Error = Unnorm_BS_Coefs(FP,BW,Wo); if(Error) { return 10*Error+4;} break; default: return ERR_FILTER; } return ERR_NONE; } Listing E.1 Unnormalize_Coefs function. C Code for Unnormalized Approximation Functions 241 /*==================================================== Unnorm_LP_Coefs() - converts normal lowpass coefs to unnormal LP coefs at a specific freq. Prototype: int Unnorm_LP_Coefs(Filt_Params *FP, double freq); Return: error value Arguments: FP - ptr to struct holding filter params freq - unnormalization frequency ====================================================*/ int Unnorm_LP_Coefs(Filt_Params *FP,double freq) { int qd,cf, /* quad and coef number */ qd_start; /* starting quad for loop */ /* Handle first-order, if odd; set qd_start */ if(FP->order % 2) { FP->acoefs[2] *= freq; FP->bcoefs[2] *= freq; qd_start = 1; } else { qd_start = 0;} /* Handle quadratic factors, qd indexes through quadratic factors, cf converts to coef number */ for(qd = qd_start; qd < (FP->order + 1)/2; qd++) { cf = qd * 3; FP->acoefs[cf+1] *= freq; FP->acoefs[cf+2] *= (freq * freq); FP->bcoefs[cf+1] *= freq; FP->bcoefs[cf+2] *= (freq * freq); } return ERR_NONE; } Listing E.2 Unnorm_LP_Coefs function. Listing E.3 shown below gives the Unnorm_BP_Coefs function. This function and the Unnorm_BS_Coefs function are more complicated than the lowpass and highpass functions. One of the ways that these functions are more complicated is that the coe fficient arrays must be resi zed to hold the larger number of coefficients for a bandpass function. (Remember that for bandpass and bandstop filters, the final order will be twice the original lowpass normalized order.) Thus, early in this function, variables from the original lowpass function are stored as well as the new order of the bandpass function. Then new pointers to the larger arrays of bandpass coefficients are assigned while leaving the original pointers unchanged. Throughout this function new_num , new_den , org_num and org_den are used to identify the ne w and original numerator and denominator coefficients, respectively. As in previous functions, we handle the first-order factors before the second-order factors. The values assigned to the new coefficients are the same as we determined in Section 3.3. 242 Practical Analog and Digital Filter Design /*==================================================== Unnorm_BP_Coefs() - converts normal lowpass coefs to unnormal BP coefs at a specific freq. Prototype: int Unnorm_BP_Coefs(Filt_Params *FP, double BW,double Wo); Return: error value Arguments: FP - ptr to struct holding filter params BW - bandwidth for unnormalization Wo - center freq for unnormalization ====================================================*/ int Unnorm_BP_Coefs(Filt_Params *FP, double BW,double Wo) { int qd,ocf,ncf,qd_start,/* loop cntrs, indexes*/ numb_coefs, /* num coefs in array */ org_quads, /* orig num of quads */ org_order; /* original order */ double *org_num,*org_den, /* orig num, den ptrs */ *new_num,*new_den; /* new num, den ptrs */ complex A,B,C,D,E; /* temp cmplx vars */ /* Store orig number of quads and order, new order will be twice original. */ org_order = FP->order; org_quads = (org_order + 1)/2; FP->order = org_order * 2; /* For clarity, assign ptrs to temp variables */ org_num = FP->acoefs; org_den = FP->bcoefs; /* Three coefs for each new quad=3*(new_order+1)/2, but new_order will be even, so its simplified */ numb_coefs = 3 * org_order; /* Allocate memory for new arrays with more coefs*/ new_num=(double *)malloc(numb_coefs*sizeof(double)); if(!new_num) { return ERR_ALLOC;} new_den=(double *)malloc(numb_coefs*sizeof(double)); if(!new_den) { return ERR_ALLOC;} /* If org_order odd, convert first-order factor to quadratic, qd_start indic start pt for loop */ if(org_order % 2) { new_num[0] = org_num[1]; new_num[1] = BW * org_num[2]; new_num[2] = org_num[1] * Wo * Wo; new_den[0] = org_den[1]; new_den[1] = BW * org_den[2]; new_den[2] = org_den[1] * Wo * Wo; qd_start = 1; } else { qd_start = 0;} /* Each orig quad term will be converted to two new quads via complex quadratic factoring. */ for(qd = qd_start;qd < org_quads;qd++) { /* ocf indexes org coefs, 3 coefs per org quad ncf indexes new coefs, 6 coefs per org quad ncf also adjusts for first-order factor */ ocf = qd * 3; ncf = qd * 6 - qd_start * 3; /* For numers which DON'T have s^2 or s terms. */ if(org_num[ocf] == 0.0) { new_num[ncf] = 0.0; new_num[ncf+1] = sqrt(org_num[ocf+2]) * BW; C Code for Unnormalized Approximation Functions 243 new_num[ncf+2] = 0.0; new_num[ncf+3] = 0.0; new_num[ncf+4] = sqrt(org_num[ocf+2]) * BW; new_num[ncf+5] = 0.0; } /* For numers which DO have s^2 and s terms. */ else { /* Convert coefs to complex, then factor */ A = cmplx(org_num[ocf],0); B = cmplx(org_num[ocf+1],0); C = cmplx(org_num[ocf+2],0); cQuadratic(A,B,C,&D,&E); /* Make required substitutions, factor again */ A = cmplx(1,0); B = cmul(cneg(D),cmplx(BW,0)); C = cmplx(Wo*Wo,0); cQuadratic(A,B,C,&D,&E); /* Determine final values for new coefs. */ new_num[ncf] = 1.0; new_num[ncf+1] = -2.0 * creal(D); new_num[ncf+2] = creal(cmul(D,cconj(D))); new_num[ncf+3] = 1.0; new_num[ncf+4] = -2.0 * creal(E); new_num[ncf+5] = creal(cmul(E,cconj(E))); } /* Denoms will always have nonzero s^2 term. */ /* Convert coefs to complex, then factor */ A = cmplx(org_den[ocf],0); B = cmplx(org_den[ocf+1],0); C = cmplx(org_den[ocf+2],0); cQuadratic(A,B,C,&D,&E); /* Make required substitutions, factor again */ A = cmplx(1,0); B = cmul(cneg(D),cmplx(BW,0)); C = cmplx(Wo*Wo,0); cQuadratic(A,B,C,&D,&E); /* Make required substitutions, factor again */ new_den[ncf] = 1.0; new_den[ncf+1] = -2.0 * creal(D); new_den[ncf+2] = creal(cmul(D,cconj(D))); new_den[ncf+3] = 1.0; new_den[ncf+4] = -2.0 * creal(E); new_den[ncf+5] = creal(cmul(E,cconj(E))); } /* Free the memory allocated to original coefs. */ free(FP->acoefs); free(FP->bcoefs); /* Assign the new ptrs to old array ptrs. */ FP->acoefs = new_num; FP->bcoefs = new_den; return ERR_NONE; } Listing E.3 Unnorm_BP_Coefs function. Before we begin the discussion of the unnormalization of second-order factors within the for loop, we need to make a slight excursion into the use of complex numbers in C. The C language does not support complex numbers as a standard data type as it does ints, floats, and double s. Therefore, if we are 244 Practical Analog and Digital Filter Design to use them in the solution of the unnormalization of bandpass and bandstop coefficients, we will have to define our own complex number definition. A complex number can easily be defined with a structure using a real and imaginary member as shown below. typedef struct { double re, /* Real part of complex number */ im; /* Imag part of complex number */ } complex; Using this complex struct will allow us to define any variables we like as type complex . For example, in the variable d eclaration section of the function we are studying now, the variables A, B, C, D, and E are defined as complex as shown below. complex A,B,C,D,E; /* temp cmplx vars */ Within the \C_CODE\FILTER\COMPLEX .C module there are a number of complex functions defined to implement standard mathematical functions for complex numbers. A list of the functions is shown below. We do not have space to study them here, but the full module is contained on the software disc included with this text. cadd() — adds complex numbers and returns result. cang() — returns angle (radians) of a complex number. cconj() — returns complex conjugate of a complex number. cdiv() — divides complex numbers and returns result. cimag() — returns imaginary part of a complex number. cmag() — returns the magnitude of a complex number. cmplx() — returns complex number made from two doubles. cmul() — multiplies complex numbers and returns result. cneg() — returns the negative of a complex number. cprt() — prints the value of a complex number. cQuadratic() — factors quadratic eqn. with complex coefficients. creal() — returns real part of a complex number. csqr() — returns the square root of a complex number. csub() — subtracts complex numbers and returns result. As an example of one of these complex functions, cadd is shown in Listing E.4. As indicated in the listing, cadd takes two complex numbers as arguments and adds their respective real and im aginary parts. The new complex number x is then returned to the calling function. Another complex function is shown in Listing E.5 below. cQuadratic takes five arguments, all of which are complex or point to complex numbers. The first three arguments, a , b, and c, are the coefficients of a quadratic equation, while d and e are the addresses where the factor s of the quadratic equation are to be stored. Each line of the function makes a partial calculation of the quadratic formula, but using complex functions. The final results are then stored where the C Code for Unnormalized Approximation Functions 245 variables d and e point. Remember this advanced version of the quadratic equation solver is necessary because some of the coefficients of the quadratic equation are complex, unlike the typical s ituation where they all would be real. /*==================================================== cadd() - adds complex numbers (a+b), returns result ====================================================*/ complex cadd(complex a,complex b) { complex x; x.re = a.re + b.re; x.im = a.im + b.im; return x; } Listing E.4 cadd function. /*==================================================== cQuadratic() - solves quadratic equation with cmplx coefficients. Equation form is a*x^2 + b*x + c, solutions will be placed in cmplx numbers d and e, whose addresses are sent to cQuadratic. ====================================================*/ void cQuadratic(complex a,complex b,complex c, complex *d,complex *e) { complex a2,ac4,sq; /* intermediate values */ a2 = cmul(a,cmplx(2,0)); /* 2*a */ ac4 = cmul(cmul(a,c),cmplx(4,0)); /* 4*a*c */ sq = csqr(csub(cmul(b,b),ac4)); /* sqrt(b*b-4*a*c)*/ *d = cdiv(cadd(cneg(b),sq),a2); /* first root */ *e = cdiv(csub(cneg(b),sq),a2); /* second root */ } Listing E.5 cQuadratic function. Now we can return to the discussion of the Unnorm_BP_Coefs . qd_start is again used to control the starting point of the for loop, and org_quads controls the ending point. Once we enter the loop to unnormalize the original second-order factors we first de fine indexing variables to control the location within the original coefficient array and the new coefficient array. The variable ocf controls the position within the original coefficient array by indexing three positions for each original quadratic factor. The variable ncf controls the position within the new coefficient array by indexing six positi ons for each of the original quadratics. The six positions are necessary because for each original quadratic there will be two new quadratics produced. In addition ncf must adjust for the unnormalized first-order factor if there is one. Therefore, ncf starts at 0 if the original order was even, but starts at 3 if the order was odd. Thereafter, it increments by a value of 6. The numerator unnormalization can be of two different types. In the Butterworth and Chebyshev cases, there will be no s2-term or s-term, while the inverse Chebyshev and elliptic approximations will have an s2-term present for the complex zeros. Therefore, an if statement is used to determine the appropriate 246 Practical Analog and Digital Filter Design method to use for a particular case. In the first case, only s-term coefficients take on the nonzero values we determined in Section 3.3. In the second case, all coefficients take on nonzero values, which are dependent on a number of complex calculations. In this second, more complicated case, we must first convert the original coefficients into complex numbers using the cmplx function. Then the roots of the quadratic are determined by the cQuadratic function and stored in the variables D and E. (We will not be dealing with the E root of this first quadratic because we know that it is th e complex conjugate of the D root.) We are then ready to define another quadratic as we found in Section 3.3. The appropriate values from this quadratic are loaded into A , B, and C, and then cQuadratic is called again. The roots of this second quadratic are then stored in D and E again. Each of these roots will define one quadratic, just as one pole location in Chapter 2 was enough to determine a quadratic. For example, if D = α + jβ and E = δ + jλ, then the D root will produce a quadratic of the forms s2 − 2 α s + (α2 + β2) and the E root will produce s2 − 2 δ s + (δ2 + λ2). These representations are mirrored in the C code. Note that the sum of squares is calculated by multiplying the root by its complex conjugate. The denominator quadratics are calculated in just the same manner as this numerator case. Once we leave the loop, all of the new coefficients have been calculated and put in place. All we have left to do is to reassign the array pointers in the Filt_Params structure. We are now finished with the original coefficients from the lowpass normalized approximation, so we can free the memory allocated to them by using the free command. Next, we take the pointers for the new, larger arrays and put them into FP. Now the pointers in FP point to areas in memory that store the larger arrays of bandpass coefficients, and the areas in memory that stored the original coefficients have been freed for future use. At this point, we have covered a ll of the necessary description for Unnorm_BS_Coefs as well. There are really no significant differences in the bandstop unnormalization func tion. It can be found in the \C_CODE\FILTER\ F_DESIGN.C module. 247 Appendix F C Code for Active Filter Implementation In order to aid in the implementation and evaluation of analog active filters, we will now develop the code necessary for the calculation of component values and the generation of PSpice text files. These text files will serve as input to PSpice that will analyze the active filters. We will use two structures to pass information to the various functions in this project. The first structure is the familiar Filt_Params structure, discussed previously. The second is a new structure used to hold the component values for the active filters to be designed. This RC_Comps structure is shown below and includes the voltage divider resistors R x and Ry as well as the number of stages in the filter. The other variables contained in the structure are pointers to arrays because these variables will be present in each stage of the filter and we will not know at the time of the program execution how many stages will be present. The components included are the primary R and C values, the gain control resistors R A and RB, and the bandstop parameters Ro and Co. typedef struct { double Rx,Ry, /* Voltage divider values */ *R,*C, /* Primary R-C values */ *Ra,*Rb, /* Feedback resistors */ *Ro,*Co; /* Twin-tee addl components */ int stages; /* Number of stages */ } RC_Comps; Once we have the common values of capacitor CO and resistor RA to use in each of the filter’s stages, as well as th e frequency information, we can calculate the other circuit values using the Calc_Components function. (This function, as well as others associated with anal og filter implementation, can be found in \C_CODE\ANALOG\ANALOG.C.) Calc_Components will in turn call an appropriate function based on the selectivity of the desired filter. For example, if a lowpass filter is being implemented, then the Calc_LP_Comps function will be called, while if a bandpass filter is being implemented, the Calc_BP_Comps function will be called. However, no matter which function is to be called, memory must be allocated for the arrays of component values in the structure. 248 Practical Analog and Digital Filter Design This memory allocation can be done prio r to calling the indi vidual functions and thereby eliminate the requirement of memo ry allocation in each of the individual functions. The component calculation functions are very similar to one another although the equations for component values are somewhat different. For that reason, only the Calc_LP_Comps function shown in Listing F.1 will be discussed here. The work within the function begins by initializing the variable K_Total , which will store the product of all stage Ks. Then, if a first-order stage is required, the R and C values for it are calculated and start is set to 1. Then, the component values for the stages implementing the quadratic factors are calculated within the for loop, which has a starting index of start. The coefficients from the Filt_Params structure are retrieved, and the common values of C and RA are placed in the RC_Comps structure. Then a determination has to be made within a switch statement as to whether a filter with complex conjugate zeros will be required. If the zeros are not required, the calculations are made and the process continues. However, if complex conjugate zeros are required, it must be decided whether a resistor, capacitor, or no additional value is necessary. The loop will continue its iterations until all stage components have been determined. Once the loop finishes, the gain adjustment factor can be determined and the voltage divider components can be calculated. If the gain adjustment is exactly 1, no values are calculated since a division by zero would result. /*==================================================== Calc_LP_Comps() - calculates the component values for lowpass analog active filter. Prototype: int Calc_LP_Comps(Filt_Params *FP, RC_Comps *RC,double C,double Ra); Return: error value Arguments: FP - ptr to struct holding filter params RC - ptr to struct holding RC components C - capacitor value for all stages Ra - feedback resistor for all stages ====================================================*/ int Calc_LP_Comps(Filt_Params *FP,RC_Comps *RC, double C,double Ra) { int i,start; /* Loop counter and start pt*/ double K,K_Total, /* K value and total */ Gain_Adj, /* Gain adjustment factor */ a2,a2r, /* Numerator constants */ b1,b2,b2r; /* Denominator constants */ /* Initialize K total */ K_Total = 1; /* If order is odd, determine R & C values for first-order stage and set start to 1 */ start = 0; if(FP->order % 2) { RC->C[0] = C; RC->R[0] = 1 / (C * FP->bcoefs[2]); RC->Ra[0] = Ra; start = 1; } /* Determine values for second-order stages */ C Code for Active Filter Implementation 249 for(i = start; i < RC->stages ;i++) { /* Determine coefficients and roots */ a2 = FP->acoefs[i*3 + 2]; a2r = sqrt(a2); b1 = FP->bcoefs[i*3 + 1]; b2 = FP->bcoefs[i*3 + 2]; b2r = sqrt(b2); /* Set standard values in structure */ RC->C[i] = C; RC->Ra[i] = Ra; /* Calculate values based on approx type B,C use Sallen-Key, E,I use Twin-Tee */ switch(FP->approx) { case 'B': case 'C': RC->R[i] = 1 / (C * b2r); K = 3 - (b1/b2r); break; case 'E': case 'I': RC->R[i] = 1 / (C * a2r); /* Find K, Ro, Co dependent on a2,b2 */ if(a2 > b2) { K = 2 + ((a2-b2-b1*a2r)/(2*b2)); RC->Co[i] = (((a2/b2) - 1) * C) / 2; } else if(a2 < b2) { K = 2 + ((b2-a2-b1*a2r)/(2*a2)); RC->Ro[i] = 2 * RC->R[i] / ((b2/a2) - 1); } else { K = 2 - (b1/(2*a2r));} break; default: return ERR_FILTER; } /* If Co = 0, K_Tot only increases by K */ K_Total *= ( (K * C) / (C + 2*RC->Co[i]) ); RC->Rb[i] = Ra * (K - 1); } /* Make final adjustment of gain and calculate voltage divider values */ Gain_Adj = K_Total / FP->gain; if(Gain_Adj == 1.000) { return ERR_NONE;} RC->Rx = Gain_Adj * R_OUT; RC->Ry = Gain_Adj * R_OUT / (Gain_Adj - 1); return ERR_NONE; } Listing F.1 Calc_LP_Comps function. After an analog active filter has been designed and the component values have been calculated, the next logical step is to test the circuit. Testing usually includes both computer analysis, where a circuit simulation is performed, and laboratory analysis, where the circuit is built from co mponents and tested with electronic equipment. We can help in the computer evaluation of the filter circuit by preparing the analysis data file necessary for PSpice tool. 250 Practical Analog and Digital Filter Design The Write_Circ_File function contained in ANALOG.C is used to coordinate the generation of the circuit analysis text file. After all of the filter sections have been written, the final voltage divider section is appended, and an appropriate model for the op-amp circuit is specified. Finally, the analysis modes are specified using the starting and ending frequencies provided by the user. As an example of one of the functions that generates circuit analysis data files, Listing F.2 shows Write_LP_Section . /*==================================================== Write_LP_Section() - writes a lowpass filter section to the circuit data file. Prototype: void Write_LP_Section(int stage, RC_Comps *RC,FILE *CF); Return: none Arguments: stage - section number of filter RC - ptr to struct holding RC components CF - ptr to output file ====================================================*/ void Write_LP_Section(int stage,RC_Comps *RC, FILE *CF) { int s,t; /* Stage related variables */ double R,C,Ra,Rb; /* Component values */ /* Simplify some variables */ t = stage + 1; s = 10 * t; R = RC->R[stage]; C = RC->C[stage]; Ra = RC->Ra[stage]; Rb = RC->Rb[stage]; /* Rb == 0 if first-order stage, otherwise generate circuit text for second-order */ if(Rb == 0) { fprintf(CF,"\n* Stage Number %d",stage+1); fprintf(CF,"\nR%d\t%d\t%d\t%8.3E",s+1,s+1,s+2,R); fprintf(CF,"\nC%d\t%d\t%d\t%8.3E",s+1,s+2,0,C); fprintf(CF,"\nRb%d\t%d\t%d\t1",t,s+3,s+11); fprintf(CF, "\nX%d\t%d\t%d\t%d\tOPAMP",t,s+2,s+3,s+11); } /* Generate circuit text for second-order stage If Ro and Co != 0, then use BS stage to generate elliptic or inv Chebyshev approx, otherwise use standard BP configuration */ else {if( (RC->Co[stage] != 0) || (RC->Ro[stage] != 0) ) { Write_BS_Section(stage,RC,CF);} else {fprintf(CF,"\n* Stage Number %d",stage+1); fprintf(CF,"\nR%d\t%d\t%d\t%8.3E",s+1,s+1,s+2,R); fprintf(CF,"\nR%d\t%d\t%d\t%8.3E",s+2,s+2,s+3,R); fprintf(CF,"\nC%d\t%d\t%d\t%8.3E",s+1,s+3,0,C); fprintf(CF,"\nC%d\t%d\t%d\t%8.3E",s+2,s+2,s+11,C); fprintf(CF,"\nRa%d\t%d\t%d\t%8.3E",t,s+4,0,Ra); fprintf(CF,"\nRb%d\t%d\t%d\t%8.3E",t,s+4,s+11,Rb); fprintf(CF,"\nX%d\t%d\t%d\t%d\tOPAMP",t,s+3,s+4,s+11); } } } Listing F.2 Write_LP_Section function. C Code for Active Filter Implementation 251 This function begins by simplifying the form of the components for each stage and then writes a section based on the order of the filter stage and the implementation of the filter stage. If the stage is implementing a first-order factor as indicated by RB having a value of zero, the necessary component values are written to the file. If the stage is impl ementing a second-order factor, the stage configuration could be either a Sallen-Key or a twin-tee notch form. If either the capacitor C o or the resistor R o is nonzero, the twin-tee notch form is indicated, and the Write_BS_Section function is called since it implements the twin-tee notch filter form. Otherwise, the compone nts for a standard Sallen-Key stage are written to the text file. 252 Practical Analog and Digital Filter Design Appendix G C Code for IIR Filter Design The bilinear transform appro ach to IIR filter design is popular because it has wide applicatio n. Our procedure will b e the sam e as o utlined in Chapter 6: prewarp the critical digital frequenci es to their anal og count erpart s, desi gn a st andard analog filter using the new sp ecificatio ns, perform the bilinear tran sform on the analog transfer funct ion to produce t he digital transfer funct ion, and fi nally, set the frequenci es back t o their original values for fut ure use. The desi gn of the analog filter h as alread y been covered in earlier ch apters, so we wo n’t need to develop that code. C onsequent ly, our work involves generat ing onl y a few new funct ions in order to add the IIR filter d esign capability to our project. In the Calc_DigIIR_Coefs funct ion shown i n Listing G.1, we fi rst use Warp_Freqs to prewarp the freq uencies; th en, we call Calc_Filter_Order , Calc_Normal_Coefs , and Unnormalize_Coefs in order t o desi gn the analog filter. After the analog filter h as been designed, the analog coefficien ts can be convert ed to digital coeffi cients by the Bilinear_Transform funct ion. And, fi nally, the UnWarp_Freqs function converts the critical frequencies back to their original values. Throughout this process, all critical param eters are transferred to and from the function in the Filt_Params structure usi ng the pointer FP. During the filter sp ecificatio n phase of our program, the user entered the desired freq uency sp ecificatio ns that th e digital filter must satisfy. In the Warp_Freqs funct ion, t hese frequenci es m ust be convert ed t o anal og frequenci es usi ng the techni ques di scussed i n Chapter 6. W e can com bine (6.7) and (6.18) in order to determine the relatio nship that m ust ex ist b etween the analog and di gital radi an frequenci es. The UnWarp_Freqs funct ion si mply reset s the critical frequenci es using the relationshi p of (G.2). 253 ⎟⎟ ⎠⎞ ⎜⎜ ⎝⎛ ⋅⋅⋅=⎟⎟ ⎠⎞ ⎜⎜ ⎝⎛ ⋅⋅⋅⋅= sd s sd affff T 2tan 222tan2 ω πω (G.1) 254 Practical Analog and Digital Filter Design ⎟⎟ ⎠⎞ ⎜⎜ ⎝⎛ ⋅⋅⋅=− sa s dff2tan 21ωω (G.2) /*==================================================== Calc_DigIIR_Coefs() - calcs digital IIR coefs Prototype: int Calc_DigIIR_Coefs(Filt_Params *FP); Return: error value Arguments: FP - ptr to struct holding filter params ====================================================*/ int Calc_DigIIR_Coefs(Filt_Params *FP) { int Error; /* error value */ /* Pre-warp frequencies before making calcs */ Error = Warp_Freqs(FP); if(Error) { return 10*Error+1;} /* Calc order and coefs, then unnormalized coefs */ Error = Calc_Filter_Order(FP); if(Error) { return 10*Error+2;} Error = Calc_Normal_Coefs(FP); if(Error) { return 10*Error+3;} Error = Unnormalize_Coefs(FP); if(Error) { return 10*Error+4;} /* Transform from s-domain to z-domain */ Error = Bilinear_Transform(FP); if(Error) { return 10*Error+5;} /* Put the critical freqs back to orig value */ Error = UnWarp_Freqs(FP); if(Error) { return 10*Error+6;} return ERR_NONE; } Listing G.1 Calc_DigIIR_Coefs funct ion. The objective of the Bilinear_Transform funct ion shown i n Listing G.2 is to implement the tran sformation from an anal og transfer funct ion to a digital transfer function. A check that the acoefs and bcoefs arrays actu ally ex ist is made first in the function. Then, constants that will be used often are calcu lated and st ored i n f2 and f4. And, fi nally, the num ber of quadrat ics is calculated as well as a starting point for the quadratic loop. If the order of the filter is odd, then a first-order t erm is handl ed, and start is set to 1. Notice th at start cont rols which quadratic facto r will start th e process. If a first-o rder facto r (which is sto red as a quadratic) has already been processed, the for loop will start with the second quadrat ic (if one i s present ). The act ual transform ation cal culations are handl ed in exactly the same manner as derived in (6.20) to (6.25). Also notice th at the total gain of the filter is adjusted in the first-order case as well as in the quadratic loop. By the end of the funct ion, all gain adjust ments have been i ncluded and t he anal og coefficients have been replaced by digital IIR coefficients. C Code for IIR Filter Design 255 /*==================================================== Bilinear_Transform() - use bilinear transform to convert transfer function from s-domain to z-domain Prototype: int Bilinear_Transform(Filt_Params *FP, double fsamp); Return: error value Arguments: FP - ptr to struct holding filter params ====================================================*/ int Bilinear_Transform(Filt_Params *FP) { int i,j,start, /* loop counters and index */ num_quads; /* number of quad factors */ double f2,f4, /* 2 * fsamp, and 4 * fsamp^2 */ N0,N1,N2, /* numerator temp variables */ D0,D1,D2; /* denominator temp variables */ if( (!FP->acoefs) || (!FP->bcoefs) ) { return ERR_NULL;} /* determine some constants */ f2 = 2 * FP->fsamp; f4 = f2 * f2; num_quads = (FP->order + 1)/2; /* handle first-order factor if present */ start = 0; if(FP->order % 2) { N0 = FP->acoefs[2] + FP->acoefs[1] * f2; N1 = FP->acoefs[2] - FP->acoefs[1] * f2; D0 = FP->bcoefs[2] + FP->bcoefs[1] * f2; D1 = FP->bcoefs[2] - FP->bcoefs[1] * f2; FP->acoefs[0] = 1.0; FP->acoefs[1] = N1 / N0; FP->acoefs[2] = 0.0; FP->bcoefs[0] = 1.0; FP->bcoefs[1] = D1 / D0; FP->bcoefs[2] = 0.0; FP->gain *= (N0 / D0); start = 1; } /* Handle quadratic factors. */ for(i = start; i < num_quads ;i++) { j = 3 * i; N0 = FP->acoefs[j]*f4 + FP->acoefs[j+1]*f2 + FP->acoefs[j+2]; N1 = 2 * (FP->acoefs[j+2] - FP->acoefs[j]*f4); N2 = FP->acoefs[j]*f4 - FP->acoefs[j+1]*f2 + FP->acoefs[j+2]; D0 = FP->bcoefs[j]*f4 + FP->bcoefs[j+1]*f2 + FP->bcoefs[j+2]; D1 = 2 * (FP->bcoefs[j+2] - FP->bcoefs[j]*f4); D2 = FP->bcoefs[j]*f4 - FP->bcoefs[j+1]*f2 + FP->bcoefs[j+2]; FP->acoefs[j] = 1.0; FP->acoefs[j+1] = N1 / N0; FP->acoefs[j+2] = N2 / N0; FP->bcoefs[j] = 1.0; FP->bcoefs[j+1] = D1 / D0; FP->bcoefs[j+2] = D2 / D0; FP->gain *= (N0 / D0); } return ERR_NONE; } Listing G.2 Bilinear_Transform function. 256 Practical Analog and Digital Filter Design 257 Appendix H C Code for FIR Filter Design The design of digital FIR filters is accomplished by Calc_DigFIR_Coefs shown in Listing H.1. (All of the functions necessary to implement that section of the project can be found in the \C _CODE\FILTER\F_DESIGN.C module on the software disc.) In this function, we see that all of the necessary steps in the design process are accomplished by the functions called from Calc_DigFIR_Coefs . In addition, the user is given an opportunity to adjust the length of the filter after it has been estimated. This option is necessa ry since the FIR filter length cannot be calculated exactly. Once the length has been accepted or changed, memory can be allocated for the filter coefficients. The length of the FIR filter is estimated by the Estm_Filter_Len function. In this function the various para meters required to estimate the length of either a window FIR design or a Parks-McClellan design are calculated. All window designs use the Kaiser estimate, which provides a starting point for the filter designer. In most cases, the Kaiser will be the preferred window design with the other methods used for comparison pur poses. After the filter length has been estimated, the calculated value is converted to the next higher odd integer and stored in FP->order. We recognize that the variable is actually the filter’s length, but this saves us from defining another variable in the Filt_Params structure. If the design method uses the window tec hnique, the ideal filter coefficients are calculated using Calc_Ideal_FIR_Coefs. This function implements the appropriate equation for ideal coefficien t calculation and stores them in the FP−>bcoefs array. Next, the proper window coefficients are calculated using one of several Calc_xxxx_Win_Coefs functions and stored in the FP−>acoefs array. Finally, the ideal and window coefficients are multiplied by the Multi_Win_Ideal_Coefs function with the final coefficients stored in the FP−>acoefs . 258 Practical Analog and Digital Filter Design /*==================================================== Calc_DigFIR_Coefs() - calcs the digital FIR coefs Prototype: int Calc_DigFIR_Coefs(Filt_Params *FP); Return: error value Arguments: FP - ptr to struct holding filter params ====================================================*/ int Calc_DigFIR_Coefs(Filt_Params *FP) { char ans; int Error; /* error value */ double beta; /* parameter for Kaiser window */ /* Estimate the length (order) of filter. Get beta for Kaiser window, if needed. */ beta = Estm_Filter_Len(FP); /* See if user wants to adjust estimated length */ printf("\n Filter length is estimated as %d.", FP->order); ans = Get_YN("\n Do you wish to change it? (Y/N):"); if(ans == 'Y') { FP->order = Get_Int("\n Please enter new length: ",0,500);} /* Allocate memory for coefficients. */ FP->acoefs = (double *) malloc(FP->order * sizeof(double)); if(!FP->acoefs) { return ERR_ALLOC;} FP->bcoefs = (double *) malloc(FP->order * sizeof(double)); if(!FP->bcoefs) { return ERR_ALLOC;} /* Set overall gain to 1.0 */ FP->gain = 1.0; /* Calculate the ideal FIR coefficients but not for Parks-McClellan. */ if(FP->approx != '6') { Error = Calc_Ideal_FIR_Coefs(FP); if(Error) { return 10*Error+1;} } /* Determine the approximation method to use. */ switch(FP->approx) { case '0': Error = Calc_Rect_Win_Coefs(FP); if(Error) { return 10*Error+2;} break; case '1': Error = Calc_Bart_Win_Coefs(FP); if(Error) { return 10*Error+3;} break; case '2': Error = Calc_Blck_Win_Coefs(FP); if(Error) { return 10*Error+4;} break; case '3': Error = Calc_Hamm_Win_Coefs(FP); if(Error) { return 10*Error+5;} break; case '4': Error = Calc_Hann_Win_Coefs(FP); if(Error) { return 10*Error+6;} break; case '5': Error = Calc_Kais_Win_Coefs(FP,beta); if(Error) { return 10*Error+7;} break; case '6': Error = Calc_ParkMccl_Coefs(FP); if(Error) { return 10*Error+8;} break; default: return ERR_FILTER; } /* Multiply window and ideal coefs only for but not for Parks-McClellan coefficients */ if(FP->approx != '6') { Error = Mult_Win_Ideal_Coefs(FP); if(Error) { return 10*Error+9;} } return ERR_NONE; } Listing H.1 Calc_DigFIR_Coefs function. 259 Appendix I Filtering Sound Files There are a number of sound file formats in use today, but one of the most popular is the WAVE file format (.WAV). This f ile format has a number of different ways that the file information can be stored, but we will concentrate on just the basic techniques. We discuss only the formats for monaural and stereo signals with either 8 bits or 16 bits per sample. Co mpression schemes are popular today to save space in transferring or saving music f iles, but we will concentrate only on uncompressed files. We will see that handling four different options will provide us with enough challenge for now. Each sound file begins with a header of information that describes the important characteristics of the file such as sampling frequency, number of samples, number of channels (mono or ster eo) and number of bits per sample. For our work, the header information for each file is shown in Table I.1. After the header information, the raw data for the sound file is provided in one of the four formats. If the data file is monaural, the data is just a sequence of bytes or integers depending on the number of bits per sample. The number of data values can be determined from the informati on in the header, which specifies the number of data bytes in the file. If the file is using 16 bits (2 bytes) per sample, then the number of data values is one-half of the number of data bytes. In the case of a stereo sound file, the byte or intege r samples of each channel are alternated starting with the left channel and then the right channel. Therefore, if we need to know how many samples to process for the left channel of a 16 bits per sample stereo sound file, we would need to divide the number of data bytes by four to arrive at the proper value. If the data is in the form of 16 bits per sample, then we can treat the data as a simple signed integer that has a range of values from +32,767 to −32,768. If the data is in the form of 8 bits per sample, then it is stored as an unsigned character with values from 0 to 255 with 128 considered as the midpoint. This is not the same as a signed character data type, and therefore special consideration must be given to the conversion of 8-bit to 16-b it representation. Equation (I.1) indicates the proper procedure to convert from 8-b it unsigned data to 16-bit signed data, while (I.2) shows the opposite conversion. (The functions Convert2Char and 260 Practical Analog and Digital Filter Design Convert2Int are i ncluded i n the \C_CODE\ DIGITAL di rectory of t he accom panying software disc as are all other functions associated with digital filter implementation.) Table I.1 File Form at for .WAV Files Bytes Description 0 – 3 “RIFF” — identification str ing 4 – 7 Reser ved 8 – 15 “WAVEf mt∅“ — ID strin g (∅ = space) 16 – 19 Reser ved 20 – 21 Type of for mat — shor t integer 22 – 23 Num ber of channels — shor t integer 24 – 27 Samples per second — long integer 28 – 31 Aver age by tes per second — long integer 32 – 33 Block alignm ent — shor t integer 34 – 35 Bits per sample — shor t integer 36 – 39 “data” — identification str ing 40 – 43 Num ber of data by tes — long integer 256)128 data( data8 16 ⋅−= (I.1) 128)256/ data( data16 8 + = (I.2) We are now ready to discuss the functi ons necessary to filter a sound file. W e will n eed to determine the parameters o f the filter as well as the waveform to be filtered . Then we will need to read in the wav eform data, filter it, an d write o ut the processed data. Since there are four di fferent form ats that coul d be used, and si nce we don’t want to generate four differe nt filtering algorithm s to handle each one, we standardize each file type into a monaural 16-bit data waveform . Then, the filterin g algorithms can be optimized to operate o n that type of file. Since we will be operat ing in a nonreal -time mode, t his conversi on shoul d not be a probl em. In the case of reading the input data and writing the output data, we must handl e the conversi on of 8 bits per sample and st ereo fi les. If t he file uses 8 bi ts per sample, the input data waveform is first convert ed to 16 bi ts per sam ple. If the input file is stereo, we t hen separat e it into two monaural files and process t hem as two independent files. Th e filterin g process will b e relativ ely easy sin ce we h ave already developed the functions to accomplish this in Chapter 8. A special structure is used t o store i nform ation about the waveform to be processed. The Filtering Sound Files 261 Wvfrm_Params structure contains all of the important information about the waveform. typedef struct { char *header; /* ptr to header info */ int file_type, /* type of data file */ numb_chan, /* number of channels */ bytes_per_samp; /* bytes per sample */ long samp_per_sec, /* samples per second */ numb_samples; /* number of samples */ } Wvfrm_Params; Listing I.1 Wvfrm_Params structure. The Digital_Filter function performs most of the work in the program and is quite long. Therefore, only an abbreviated version is shown in Listing I.2. Array creation, error checking, and conversions from 8 to 16 bit as well as stereo to mono versions have been removed. (T he complete function can be viewed on the software disc.) The actual digital filtering is handled by using one of the functions discussed in earlier sections. Based on the filter implementation type and the status of the REAL_TIME constant (defined in DIGITAL.H), we will use Dig_IIR_Filter , Dig_FIR_Filt_RT , or Dig_FIR_Filt_NRT to produce the filtering. /*==================================================== Digital_Filter() - determines the type of waveform (mono/stereo - 8bit/16bit), type of filter (FIR/IIR) and sets up all memory for filtering process Prototype: int Digital_Filter(FILE *InFile, FILE *OutFile,Filt_Params *FP,Wvfrm_Params *WP); Return: error value. Arguments: InFile - input data file OutFile - output data file FP - ptr to Filt_Params struct WP - ptr to Wvfrm_Params struct ====================================================*/ int Digital_Filter(FILE *InFile,FILE *OutFile, Filt_Params *FP,Wvfrm_Params *WP) { /* Declaration of variables (not shown - NS) */ /* Set all pointers to null */ a = c = C = M1 = M2 = 0; X1 = X2 = Y1 = Y2 = 0; Z = 0; /* Set common values */ bytes = WP->bytes_per_samp; chan = WP->numb_chan; error = ERR_NONE; /* Allocate memory for data (NS) */ /* ===== ===== Handle the IIR case ===== ===== */ if(FP->implem == 'I') { /* Set numb_quads and start for later use */ numb_quads = (FP->order + 1) / 2; start = 0; 262 Practical Analog and Digital Filter Design /* Alloc memory for input, coefs and mem (NS) */ /* Set up second set of arrays if stereo (NS) */ /* Load the coef array with gain, b's and a's */ c = C; *c++ = FP->gain; for(i = 0; i < numb_quads ;i++) { j = i * 3; *c++ = FP->bcoefs[j+1]; *c++ = FP->bcoefs[j+2]; *c++ = FP->acoefs[j+1]; *c++ = FP->acoefs[j+2]; } } /* ===== ===== Handle the FIR case ===== ===== */ else if(FP->implem == 'F') { /* Set numb_coefs and start for later use */ numb_coefs = FP->order; if(REAL_TIME) { start = 0;} else { start = numb_coefs - 1;} /* Alloc memory for input, coefs and mem (NS) */ /* Set up second set of array if stereo (NS) */ } /* Load the coef array (in reverse order) with a's and gain */ c = C; a = FP->acoefs + numb_coefs - 1; for(i = 0; i < numb_coefs ;i++) { *c++ = *a--;} *c++ = FP->gain; } else { error = ERR_VALUE; goto TIDY_UP;} k = 0; /* Start outer loop of filtering process */ Total = WP->numb_samples * WP->numb_chan; Done = 0; while(!Done) { /* Read in data */ numb_read = fread(&X1[start],sizeof(int), CHUNK_SIZE * chan,InFile); /* Select IIR or FIR filter for ch 1 or mono */ if(FP->implem == 'I') { Dig_IIR_Filter(X1,Y1,M1,C,numb_quads,numb_read/chan);} if(FP->implem == 'F') { if(REAL_TIME) { Dig_FIR_Filt_RT(X1,Y1,M1,C,numb_coefs,numb_read/chan);} else { Dig_FIR_Filt_NRT(X1,Y1,C,numb_coefs,numb_read/chan);} } /* Write out data */ numb_writ = fwrite(Y1,sizeof(int),numb_read,OutFile); } /* End of while loop */ TIDY_UP: /* Free memory, close files and return (NS) */ return error; } Listing I.2 Abbreviated Digital_Filter file. 263 About the Author Les Thede is a professor of electrical and com puter engineering at Ohio Northern University, Ada, Ohio. A former design engineer for Motorola, Inc., he holds a B.S and M.S. in electrical engineering from the University of Iowa and a Ph.D. in engineering science from the University of Toledo. He established the DSP lab at Ohio Northern University in 1989 and ha s written several articles on filter design and C programming. He has written a previous book on analog and digital filter design and currently is teaching courses in filter design, digital signal processing, and image processing. He is a member of IEEE and ASEE. His e-mail address is [email protected]. 264 Practical Analog and Digital Filter Design 265 Index Analog filters Butterworth bandpass example, 97 Butterworth lowpass example, 91 Chebyshev bandstop example, 102 Chebyshev highpass example, 94 component selection, 106 elliptic bandpass example, 105 frequency response calculation, 76–82 implementation issues, 106–11 implementation procedures, 85– 87 implementing complex zeros, 103–6 inverse Chebyshev lowpass example, 104 Sallen-Key bandpass, 96 Sallen-Key highpass, 92 Sallen-Key lowpass, 87 sensitivity analysis, 108 twin-tee notch, 98, 103 Analog-to-digital conversion general description, 115–20 Approximation. See also Butterworth, Chebyshev, inverse Chebyshev, and elliptic approximations. comparison of methods, 52–54 general description, 6–8 Bandpass filter analog active implementation, 96–98 general description, 5 unnormalization, 64–71 Bandstop filter analog active implementation, 98–103 general description, 5–6 unnormalization, 71–76 Bartlett window, 170 Bilinear transform design, 151–58 Blackman window, 171 Butterworth approximation, 19–26 analog bandpass example, 69 analog lowpass example, 59 bandpass active example, 97 bilinear transform example, 155 impulse invariant example, 144 lowpass active example, 91 normalized examples, 23–26 step invariant example, 149 Chebyshev approximation, 27–34 analog bandstop example, 75 analog highpass example, 63 bandstop active example, 102 bilinear transform example, 155 highpass active example, 94 normalized examples, 30–34 266 Practical Analog and Digital Filter Design Digital FIR filtering use of FFT, 221–24 Digital FIR filters C code for implementation, 200–5 four types, 165 frequency response calculation, 183–85 Hamming window example, 173 ideal coefficient example, 167 ideal coefficient values, 168–69 implementation issues, 187–94 Kaiser window example, 174 Parks-McClellan example, 181 Parks-McClellan procedure, 177– 83 real-time vs. nonreal-time, 200–5 windowing techniques, 170–76 Digital IIR filters bilinear transform design, 151 C code for implementation, 194– 200 frequency response calculation, 158–59 implementation issues, 187–94 impulse invariant design, 142–46 step invariant design, 146–51 Discrete Fourier transform (DFT) determination of resolution, 212 general description, 209 with Hamming window, 212 with rectangular window, 210 Discrete-time system analog-to-digital conversion, 118 convolution, 124 digital-to-analog conversion, 119 frequency response, 130 frequency spectrum, 116–18 impulse response, 124–26 linear difference equations, 120– 24 playing waveforms, 137–39 sampling and quantization, 118– 19 z-transforms, 126 Elliptic approximation, 43–52 analog bandstop example, 75 analog highpass example, 62 bandpass active example, 105 normalized examples, 48–52 Fast Fourier transform (FFT) C code, 218–20 general description, 214–17 inverse FFT, 217 used in filtering, 221–24 Frequency response analog calculation, 76–82 C code for analog calculation, 80 C code for FIR filter, 183–85 C code for IIR filter, 158–59 discrete-time, 130 Hamming window, 171 Highpass filter analog active implementation, 92–95 general description, 4–5 unnormalization, 60–63 Implementation. See also analog, digital FIR and digital IIR filters. C code for FIR filters, 200 C code for IIR filters, 194 coefficient representation, 190 component selection, 106 general description, 8–9 retaining accuracy and stability, 192 sensitivity analysis, 108 signal representation, 188 Impulse response invariant design, 142–46 Inverse Chebyshev approximation, 34–43 analog bandpass example, 70 analog lowpass example, 58 lowpass active example, 104 normalized examples, 38–43 Kaiser window, 172 Linear difference equations, 120 Lowpass filter analog active implementation, 87–92 Index 267 general description, 3–4 unnormalization, 55–60 Nyquist criteria, 118 Parks-McClellan optimization FIR design, 177–83 Quantization, 118 Remez Exchange Algorithm, 179– 80 Selectivity. See also lowpass, highpass, bandpass, and bandstop filters. general description, 2–6 Step response invariant design, 146– 51 Transfer function and pole-zero plots, 17–18 general description, 15–19 normalized, 18–19 von Hann window, 171 WFilter analog filter implementation, 111 bilinear transform example, 157 filtering sound files, 205–7 general description, 9–14 IIR filtering example, 206 Kaiser window example, 174 Parks-McClellan example, 181 saving parameters, 82–84 Windows for FIR filters, 170–76 z-transforms, 125