Designs an FIR notch filter from a lowpass filter by computing the difference between the prototype lowpass filter and its amplitude complementary

An all-pass equalisation filter cascade (Heq) is available for equalising the phase response of the H1 filter cascade and H2 filter respectively.

Many Audio/acoustics engineers and researchers and audio hobbyists work with DSP (Digital Signal Processing). Some now and then, some on daily basis. Working on DSP for audio and speech, common challenges to create digital filters are: Noise cancellation, due to interference and Audio and Speech enhancement. And for whom DSP is not his daily job: filter design in general. In this blog, you’ll find out how the ASN Filter Designer may help for both experienced audio engineers and engineers where DSP is not their daily job to create digital filters for audio and speech.

## For whom? **For those **with some and experienced DSP knowledge alike

If you are a audio/acoustics engineer or researcher or hobbyist: ASN Filter Designer is tailored for whom DSP is not his daily job and with some knowledge DSP. For those who need filter design and have to create some signal analysis. But also for those whom DSP is his daily job and want to save time and money. Most engineers who are working with DSP on a daily basis, are usually working with extensive but also expensive tools. Or want to do the maths themselves. Also for them ASN Filter Designer is useful:

- Intuitive and easy to use
- Save days of time spending calculating on your own for the price of 2-3 hours of work
- Few lesser costs then extensive tooling with features you don’t use anyway
- Automatic code generation: export for further analysis to MATLAB, etc, or to Cortex-M Arm based processors via the Arm CMSIS-DSP software framework

## How DSP for Speech and audio benefit from ASN Filter Designer:

- Experiment with a variety of equalisation, noise cancellation and sound effect audio filtering algorithms
- Perform data analysis in the frequency domain and via specialised methods, including Cepstral analysis on the streaming data
- Import your own
*wav*audio files (mono or stereo up to 48kHz) for streaming, and modify the filter characteristics in real-time while listening to the filtered audio stream

## Some features for creating digital filters for Audio and Speech:

**The sampling frequency may be specified up to 4 decimal places **

which is useful for designing filters based on fractional sampling frequencies, such as multiples of the 44.1kHz audio standard. Common examples include audio interpolation filters: 44.1kHz × 128 = 5.6448MHz and 44.1kHz × 256 = 11.2896MHz.

**Filter orders of up to 499 **

may be constructed, where this is limited to 200 for streaming audio applications. As with the IIR filters, a FIR’s zeros may be modified by the P-Z editor (Method dropdown list changes to User defined), including the ability of adding poles and converting it into an IIR filter

**Audio and user data playback streaming**

The signal analyzer allows designers to test their design on audio, real (user) data or synthetic data via the built-in signal generator. Default data playback is implemented as streaming data, providing a simple way of assessing the filter’s dynamic performance, which is especially useful for fixed point implementations. Both frequency domain and time domain charts are fully supported, allowing for design verification via transfer function estimation using the cross and power spectral density functions. As with all other charts, the signal analyzer chart fully supports advanced zooming and panning, as well as comprehensive chart data file export options.

**Load .wav for playback**

The signal generator allows you to load .wav audio files for playback via the Audio File method. Both mono and stereo formats are fully supported for 8.000, 11.025, 16.000, 22.05 and 44.1kHz. sampling rates. There is no restriction as to the length of the .wav file

**You may add extra signals to input audio stream **

20 extra signals for an IIR filter this is set at 20, 200 for an FIR

**Intuitive data analysis with the mouse**

Move the mouse over the chart will automatically produce data markers and data analytics (shown at the bottom right side of the GUI). The signal analyzer is directly coupled to the filter designer GUI. This means that you may modify the filter characteristics. And see the effects in real-time in the signal analyzer. This functionality is very useful when designing audio filters, as the new filter settings can be heard immediately on the streaming audio feed

## Digital filters commonly used in audio and speech

The ASN Filter designer includes digital filters commonly used in audio such as:

- All-pass filter for improving phase response
- Bell filter/Peaking filter to perform magnitude equalization
- Linear Phase Filters for prevention of phase
- The APF equalizer for linearising the passband phase
- A-curve equalization, for modelling perceived sound
- Comb filter for powerline (50/60Hz) harmonic noise cancellation
- 3-band equalizer
- And many more…

## Read review here:

Top marks from Jacob Beningo

Chebyshev I and Chebyshev II filters: what are the advantages and disadvantages? And what is the syntax of Chebyshev, explained with ASN Filterscript

Butterworth filters have a magnitude response that is maximally flat in the passband and monotonic overall. Good choice for eg DC and loadcells

As discussed in a previous article, the moving average (MA) filter is perhaps one of the most widely used digital filters due to its conceptual simplicity and ease of implementation. The realisation diagram shown below, illustrates that an MA filter can be implemented as a simple FIR filter, just requiring additions and a delay line.

Modelling the above, we see that a moving average filter of length \(\small\textstyle L\) for an input signal \(\small\textstyle x(n)\) may be defined as follows:

\( y(n)=\large{\frac{1}{L}}\normalsize{\sum\limits_{k=0}^{L-1}x(n-k)}\quad \text{for} \quad\normalsize{n=0,1,2,3….}\label{FIRdef}\tag{1}\)

This computation requires \(\small\textstyle L-1\) additions, which may become computationally demanding for very low power processors when \(\small\textstyle L\) is large. Therefore, applying some lateral thinking to the computational challenge, we see that a much more computationally efficient filter can be used in order to achieve the same result, namely:

\(H(z)=\displaystyle\frac{1}{L}\frac{1-z^{-L}}{1-z^{-1}}\tag{2}\label{TF}\)

with the difference equation,

\(y(n) =y(n-1)+\displaystyle\frac{x(n)-x(n-L)}{L}\tag{3}\)

Notice that this implementation only requires **one addition and one subtraction** for any value of \(\small\textstyle L\). A further simplification (valid for both implementations) can be achieved in a pre-processing step prior to implementing the difference equation, i.e. scaling all input values by \(\small\textstyle L\). If \(\small\textstyle L\) is a power of two (e.g. 4,8,16,32..), this can be achieved by a simple binary shift right operation.

**Is it an IIR or actually an FIR?**

Upon initial inspection of the transfer function of Eqn. \(\small\textstyle\eqref{TF}\), it appears that the efficient Moving average filter is an IIR filter. However, analysing the pole-zero plot of the filter (shown on the right for \(\small\textstyle L=8\)), we see that the **pole at DC has been cancelled by a zero**, and that the resulting filter is actually an FIR filter, with the same result as Eqn. \(\small\textstyle\eqref{FIRdef}\).

Notice also that the frequency spacing of the zeros (corresponding to the nulls in the frequency response) are at spaced at \(\small\textstyle\pm\frac{Fs}{L}\). This can be readily seen for this example, where an MA of length 8, sampled at \(\small\textstyle 500Hz\), results in a \(\small\textstyle\pm62.5Hz\) resolution.

As a final point, notice that the our efficient filter requires a delay line of length \(\small\textstyle L+1\), compared with the FIR delay line of length, \(\small\textstyle L\). However, this is a small price to pay for the computation advantage of a filter just requiring one addition and one subtraction. As such, the MA filter of Eqn. \(\small\textstyle\eqref{TF}\) presented herein is very attractive for very low power processors, such as the Arm Cortex-M0 that have been traditionally overlooked for DSP operations.

## Implementation

The MA filter of Eqn. \(\small\textstyle\eqref{TF}\) may be implemented in ASN FilterScript as follows:

ClearH1; // clear primary filter from cascade interface L = {2,32,2,4}; // interface variable definition Main() Num = {1,zeros(L-1),-1}; // define numerator coefficients Den = {1,-1}; // define denominator coefficients Gain = 1/L; // define gain

A digital filter is a mathematical algorithm that operates on a digital dataset (e.g. sensor data) in order extract information of interest and remove any unwanted information. Applications of this type of technology, include removing glitches from sensor data or even cleaning up noise on a measured signal for easier data analysis. But how do we choose the best type of digital filter for our application? And what are the differences between a IIR filter and a FIR filter?

Digital filters are divided into the following two categories:

- Infinite impulse response (IIR)
- Finite impulse response (FIR)

As the names suggest, **each type of filter is categorised by the length of its impulse response**. However, before beginning with a detailed mathematical analysis, it is prudent to appreciate the differences in performance and characteristics of each type of filter.

**Example**

In order to illustrate the differences between an IIR and FIR, the frequency response of a 14th order FIR (solid line), and a 4th order Chebyshev Type I IIR (dashed line) is shown below in Figure 1. Notice that although the magnitude spectra have a similar degree of attenuation, the phase spectrum of the IIR filter is non-linear in the passband (\(\small 0\rightarrow7.5Hz\)), and becomes very non-linear at the cut-off frequency, \(\small f_c=7.5Hz\). Also notice that the FIR requires a higher number of coefficients (15 vs the IIR’s 10) to match the attenuation characteristics of the IIR.

These are just some of the differences between the two types of filters. A detailed summary of the main advantages and disadvantages of each type of filter will now follow.

**IIR filters**

IIR (infinite impulse response) filters are generally chosen for applications where linear phase is not too important and memory is limited. They have been widely deployed in audio equalisation, biomedical sensor signal processing, IoT/IIoT smart sensors and high-speed telecommunication/RF applications.

**Advantages**

**Low implementation cost**: requires less coefficients and memory than FIR filters in order to satisfy a similar set of specifications, i.e., cut-off frequency and stopband attenuation.**Low latency**: suitable for real-time control and very high-speed RF applications by virtue of the low number of coefficients.**Analog equivalent**: May be used for mimicking the characteristics of analog filters using s-z plane mapping transforms.

**Disadvantages**

**Non-linear phase characteristics**: The phase charactersitics of an IIR filter are generally nonlinear, especially near the cut-off frequencies. All-pass equalisation filters can be used in order to improve the passband phase characteristics.**More detailed analysis:**Requires more scaling and numeric overflow analysis when implemented in fixed point. The**Direct form II**filter structure is especially sensitive to the effects of quantisation, and requires special care during the design phase.**Numerical stability**: Less numerically stable than their FIR (finite impulse response) counterparts, due to the feedback paths.

**FIR filters**

FIR (finite impulse response) filters are generally chosen for applications where linear phase is important and a decent amount of memory and computational performance are available. They have a widely deployed in audio and biomedical signal enhancement applications. Their all-zero structure (discussed below) ensures that they never become unstable for any type of input signal, which gives them a distinct advantage over the IIR.

**Advantages**

**Linear phase**: FIRs can be easily designed to have linear phase. This means that no phase distortion is introduced into the signal to be filtered, as all frequencies are shifted in time by the same amount – thus maintaining their relative harmonic relationships (i.e. constant group and phase delay). This is certainly not case with IIR filters, that have a non-linear phase characteristic.**Stability**: As FIRs do not use previous output values to compute their present output, i.e. they have no feedback, they can never become unstable for any type of input signal, which is gives them a distinct advantage over IIR filters.**Arbitrary frequency response**: The Parks-McClellan and ASN FilterScript’s firarb() function allow for the design of an FIR with an arbitrary magnitude response. This means that an FIR can be customised more easily than an IIR.**Fixed point performance**: the effects of quantisation are less severe than that of an IIR.

**Disadvantages**

**High computational and memory requirement:**FIRs usually require many more coefficients for achieving a sharp cut-off than their IIR counterparts. The consequence of this is that they require much more memory and significantly a higher amount of MAC (multiple and accumulate) operations. However, modern microcontroller architectures based on the Arm’s Cortex-M cores now include DSP hardware support via SIMD (signal instruction, multiple data) that expedite the filtering operation significantly.**Higher latency**: the higher number of coefficients, means that in general an FIR is less suitable than an IIR for fast high throughput applications. This becomes problematic for real-time closed-loop control applications, where an FIR filter may have too much group delay to achieve loop stability.**No analog equivalent**: using the Bilinear, matched z-transform (s-z mapping), an analog filter can be easily be transformed into an equivalent IIR filter. However, this is not possible for an FIR as it has no analog equivalent.

**Mathematical definitions**

As discussed in the introduction, the name IIR and FIR originate from the mathematical definitions of each type of filter, i.e. an IIR filter is categorised by its theoretically infinite impulse response,

y(n)=\sum_{k=0}^{\infty}h(k)x(n-k)

\)

and an FIR categorised by its finite impulse response,

y(n)=\sum_{k=0}^{N-1}h(k)x(n-k)

\)

We will now analyse the mathematical properties of each type of filter in turn.

**IIR definition**

As seen above, an IIR filter is categorised by its theoretically infinite impulse response,

\(\displaystyle y(n)=\sum_{k=0}^{\infty}h(k)x(n-k) \)

Practically speaking, it is not possible to compute the output of an IIR using this equation. Therefore, the equation may be re-written in terms of a finite number of poles \(\small p\) and zeros \(\small q\), as defined by the linear constant coefficient difference equation given by:

y(n)=\sum_{k=0}^{q}b_k x(n-k)-\sum_{k=1}^{p}a_ky(n-k)

\)

where, \(\small a_k\) and \(\small b_k\) are the filter’s denominator and numerator polynomial coefficients, who’s roots are equal to the filter’s **poles** and **zeros** respectively. Thus, a relationship between the difference equation and the z-transform (transfer function) may therefore be defined by using the z-transform delay property such that,

\sum_{k=0}^{q}b_kx(n-k)-\sum_{k=1}^{p}a_ky(n-k)\quad\stackrel{\displaystyle\mathcal{Z}}{\longleftrightarrow}\quad\frac{\sum\limits_{k=0}^q b_kz^{-k}}{1+\sum\limits_{k=1}^p a_kz^{-k}}

\)

As seen, the **transfer function** is a frequency domain representation of the filter. Notice also that the **poles** act on the **output** **data**, and the **zeros** on the **input** **data**. Since the poles act on the output data, and affect stability, it is essential that their radii **remain inside the unit circle **(i.e. <1) for BIBO (bounded input, bounded output) stability. The radii of the zeros are less critical, as they do not affect filter stability. This is the primary reason why all-zero FIR (finite impulse response) filters are always stable.

**BIBO stability**

A linear time invariant (LTI) system (such as a digital filter) is said to be **bounded input, bounded output stable**, or BIBO stable, if every bounded input gives rise to a bounded output, as

\(\displaystyle \sum_{k=0}^{\infty}\left|h(k)\right|<\infty \)

Where, \(\small h(k)\) is the LTI system’s impulse response. Analyzing this equation, it should be clear that the BIBO stability criterion will only be satisfied if the **system’s poles lie inside the unit circle**, since the system’s ROC (region of convergence) must include the unit circle. Consequently, it is sufficient to say that a bounded input signal will always produce a bounded output signal if all the poles lie inside the unit circle.

The zeros on the other hand, are not constrained by this requirement, and as a consequence may lie anywhere on z-plane, since they do not directly affect system stability. Therefore, a system stability analysis may be undertaken by firstly calculating the roots of the transfer function (i.e., roots of the numerator and denominator polynomials) and then plotting the corresponding poles and zeros upon the z-plane.

An interesting situation arises if any poles lie on the unit circle, since the system is said to be **marginally stable**, as it is neither stable or unstable. Although marginally stable systems are not BIBO stable, they have been exploited by digital oscillator designers, since their impulse response provides a simple method of generating sine waves, which have proved to be invaluable in the field of telecommunications.

**Biquad IIR filters**

The IIR filter implementation discussed herein is said to be **biquad**, since it has two poles and two zeros as illustrated below in Figure 2. The biquad implementation is particularly useful for fixed point implementations, as the effects of quantization and numerical stability are minimised. However, the overall success of any biquad implementation is dependent upon the available number precision, which must be sufficient enough in order to ensure that the quantised poles are always inside the unit circle.

*Figure 2: Direct Form I (biquad) IIR filter realization and transfer function.*

Analysing Figure 2, it can be seen that the biquad structure is actually comprised of two feedback paths (scaled by \(\small a_1\) and \(\small a_2\)), three feed forward paths (scaled by \(\small b_0, b_1\) and \(\small b_2\)) and a section gain, \(\small K\). Thus, the filtering operation of Figure 1 can be summarised by the following simple recursive equation:

\(\displaystyle y(n)=K\times\Big[b_0 x(n) + b_1 x(n-1) + b_2 x(n-2)\Big] – a_1 y(n-1)-a_2 y(n-2)\)

Analysing the equation, notice that the biquad implementation only requires four additions (requiring only one accumulator) and five multiplications, which can be **easily accommodated on any Cortex-M microcontroller**. The section gain, \(\small K\) may also be pre-multiplied with the forward path coefficients before implementation.

A collection of Biquad filters is referred to as a **Biquad Cascade**, as illustrated below.

The ASN Filter Designer can design and implement a cascade of up to 50 biquads (Professional edition only).

**Floating point implementation**

When implementing a filter in floating point (i.e. using double or single precision arithmetic) Direct Form II structures are considered to be a better choice than the **Direct Form I** structure. The **Direct Form II Transposed** structure is considered the most numerically accurate for floating point implementation, as the undesirable effects of numerical swamping are minimised as seen by analysing the difference equations.

*Figure 3 – Direct Form II Transposed strucutre, transfer function and difference equations*

The filter summary (shown in Figure 4) provides the designer with a detailed overview of the designed filter, including a detailed summary of the technical specifications and the filter coefficients, which presents a quick and simple route to documenting your design.

The ASN Filter Designer supports the design and implementation of both single section and Biquad (default setting) IIR filters.

**FIR definition**

Returning the IIR’s linear constant coefficient difference equation, i.e.

y(n)=\sum_{k=0}^{q}b_kx(n-k)-\sum_{k=1}^{p}a_ky(n-k)

\)

Notice that when we set the \(\small a_k\) coefficients (i.e. the feedback) to zero, the definition reduces to our original the FIR filter definition, meaning that the FIR computation is just based on past and present inputs values, namely:

y(n)=\sum_{k=0}^{q}b_kx(n-k)

\)

**Implementation**

Although several practical implementations for FIRs exist, the direct form** **structure and its transposed cousin are perhaps the most commonly used, and as such, all designed filter coefficients are intended for implementation in a Direct form structure.

The Direct form structure and associated difference equation are shown below. The **Direct Form** is advocated for fixed point implementation by virtue of the single accumulator concept.

\(\displaystyle y(n) = b_0x(n) + b_1x(n-1) + b_2x(n-2) + …. +b_qx(n-q) \)

The recommended (default) structure within the ASN Filter Designer is the **Direct Form Transposed** structure, as this offers superior numerical accuracy when using floating point arithmetic. This can be readily seen by analysing the difference equations below (used for implementation), as the undesirable effects of numerical swamping are minimised, since floating point addition is performed on numbers of similar magnitude.

\(\displaystyle \begin{eqnarray}y(n) & = &b_0x(n) &+& w_1(n-1) \\ w_1(n)&=&b_1x(n) &+& w_2(n-1) \\ w_2(n)&=&b_2x(n) &+& w_3(n-1) \\ \vdots\quad &=& \quad\vdots &+&\quad\vdots \\ w_q(n)&=&b_qx(n) \end{eqnarray}\)

## What have we learned?

Digital filters are divided into the following two categories:

- Infinite impulse response (IIR)
- Finite impulse response (FIR)

IIR (infinite impulse response) filters are generally chosen for applications where linear phase is not too important and memory is limited. They have been widely deployed in audio equalisation, biomedical sensor signal processing, IoT/IIoT smart sensors and high-speed telecommunication/RF applications.

FIR (finite impulse response) filters are generally chosen for applications where linear phase is important and a decent amount of memory and computational performance are available. They have a widely deployed in audio and biomedical signal enhancement applications.

ASN Filter Designer provides engineers with everything they need to design, experiment and deploy complex IIR and FIR digital filters for a variety of sensor measurement applications. These advantages coupled with automatic documentation and code generation functionality allow engineers to design and validate an IIR/FIR digital filter within minutes rather than hours.

Modern embedded processors, software frameworks and design tooling now allow engineers to apply advanced measurement concepts to smart factories as part of the I4.0 revolution.

In recent years, PM (predictive maintenance) of machines has received great attention, as factories look to maximise their production efficiency while at the same time retaining the invaluable skills of experienced foremen and production workers.

Traditionally, a foreman would walk around the shop floor and listen to the sounds a machine would make to get an idea of impending failure. With the advent of I4.0 technology, microphones, edge DSP algorithms and ML may now be employed in order to ‘listen’ to the sounds a machine makes and then make a classification and prediction.

*One of the major challenges is how to make a computer hear like a human.*

## Physics of the human ear

An illustration of the human ear shown on the right. As seen, the basic task of the ear is to translate sound (air vibration) into electrical nerve impulses for the brain to interpret.

An illustration of the human ear shown on the right. As seen, the basic task of the ear is to translate sound (air vibration) into electrical nerve impulses for the brain to interpret.

**How does it work?**

The ear achieves this via three bones (Stapes, Incus and Malleus) that act as a mechanical amplifier for vibrations received at the eardrum. These amplified sounds are then passed onto the Cochlea via the Oval window (not shown). The Cochlea (shown in purple) is filled with a fluid that moves in response to the vibrations from the oval window. As the fluid moves, thousands of nerve endings are set into motion. These nerve endings transform sound vibrations into electrical impulses that travel along the auditory nerve fibres to the brain for analysis.

**Modelling perceived sound**

Due to complexity of the fluidic mechanical construction of the human auditory system, low and high frequencies are typically not discernible. Researchers over the years have found that humans are most perceptive to sounds in the 1-6kHz range, although this range varies according to the subject’s physical health.

This research led to the definition of a set of weighting curves: the so-called **A, B, C and D weighting curves**, which equalises a microphone’s frequency response. These weighting curves aim to bring the digital and physical worlds closer together by allowing a computerised microphone-based system to hear like a human.

The A-weighing curve is the most widely used as it is mandated by IEC-61672 to be fitted to all sound level meters. The B and D curves are hardly ever used, but C-weighting may be used for testing the impact of noise in telecoms systems.

The frequency response of the A-weighting curve is shown above, where it can be seen that sounds entering our ears are **de-emphasised below 500Hz and are most perceptible between 0.5-6kHz**. Notice that the curve is unspecified above 20kHz, as this exceeds the human hearing range.

## ASN FilterScript

ASN’s FilterScript symbolic math scripting language offers designers the ability to take an analog filter transfer function and transform it to its digital equivalent with just a few lines of code.

The analog transfer functions of the A and C-weighting curves are given below:

\(H_A(s) \approx \displaystyle{7.39705×10^9 \cdot s^4 \over (s + 129.4)^2\quad(s + 676.7)\quad (s + 4636)\quad (s + 76655)^2}\)

\(H_C(s) \approx \displaystyle{5.91797×10^9 \cdot s^2\over(s + 129.4)^2\quad (s + 76655)^2}\)

These analog transfer functions may be transformed into their digital equivalents via the `bilinear()`

function. However, notice that \(H_A(s) \) requires a significant amount of algebracic manipulation in order to extract the denominator cofficients in powers of \(s\).

**Convolution**

A simple trick to perform polynomial multiplication is to use linear convolution, which is the same algebraic operation as multiplying two polynomials together. This may be easily performed via Filterscript’s `conv()`

function, as follows:

y=conv(a,b);

As a simple example, the multiplication of \((s^2+2s+10)\) with \((s+5)\), would be defined as the following three lines of FilterScript code:

a={1,2,10}; b={1,5}; y=conv(a,b);

which yields,` 1 7 20 50 `

or \((s^3+7s^2+20s+50)\)

For the A-weighting curve Laplace transfer function, the complete FilterScript code is given below:

ClearH1; // clear primary filter from cascade Main() // main loop a={1, 129.4}; b={1, 676.7}; c={1, 4636}; d={1, 76655}; aa=conv(a,a); // polynomial multiplication dd=conv(d,d); aab=conv(aa,b); aabc=conv(aab,c); Na=conv(aabc,dd); Nb = {0 ,0 , 1 ,0 ,0 , 0, 0}; // define numerator coefficients G = 7.397e+09; // define gain Ha = analogtf(Nb, Na, G, "symbolic"); Hd = bilinear(Ha,0, "symbolic"); Num = getnum(Hd); Den = getden(Hd); Gain = getgain(Hd)/computegain(Hd,1e3); // set gain to 0dB@1kHz

Frequency response of analog vs digital A-weighting filter for \(f_s=48kHz\). As seen, the digital equivalent magnitude response matches the ideal analog magnitude response very closely until \(6kHz\).

**The ITU-R 486–4 weighting curve**

Another weighting curve of interest is the ITU-R 486–4 weighting curve, developed by the BBC. Unlike the A-weighting filter, the ITU-R 468–4 curve describes subjective loudness for broadband stimuli. The main disadvantage of the A-weighting curve is that it underestimates the loudness judgement of real-world stimuli particularly in the frequency band from about 1–9 kHz.

Due to the precise definition of the 486–4 weighting curve, there is no analog transfer function available. Instead the standard provides a table of amplitudes and frequencies – see here. This specification may be directly entered into Filterscript’s `firarb()`

function for designing a suitable FIR filter, as shown below:

ClearH1; // clear primary filter from cascade ShowH2DM; interface L = {10,400,10,250}; // filter order Main() // ITU-R 468 Weighting A={-29.9,-23.9,-19.8,-13.8,-7.8,-1.9,0,5.6,9,10.5,11.7,12.2,12,11.4,10.1,8.1,0,-5.3,-11.7,-22.2}; F={63,100,200,400,800,1e3,2e3,3.15e3,4e3,5e3,6.3e3,7.1e3,8e3,9e3,1e4,1.25e4,1.4e4,1.6e4,2e4}; A={-30,A}; // specify arb response F={0,F,fs/2}; // Hd=firarb(L,A,F,"blackman","numeric"); Num=getnum(Hd); Den={1}; Gain=getgain(Hd);

Frequency response of an ITU-R 468-4 FIR filter designed with Filterscript’s `firarb()`

function for \(f_s=48kHz\)

As seen, FilterScript provides the designer with a very powerful symbolic scripting language for designing weighting curve filters. The following discussion now focuses on deployment of the A-weighting filter to an Arm based processor via the tool’s automatic code generator. The concepts and steps demonstrated below are equally valid for FIR filters.

**Automatic code generation to Arm processor cores via CMSIS-DSP**

The ASN Filter Designer’s automatic code generation engine facilitates the export of a designed filter to Cortex-M Arm based processors via the CMSIS-DSP software framework. The tool’s built-in analytics and help functions assist the designer in successfully configuring the design for deployment.

Before generating the code, the **H2 filter** (i.e. the filter designed in FilterScript) needs to be firstly re-optimised (transformed) to an H1 filter (main filter) structure for deployment. The **options** menu can be found under the **P-Z** tab in the main UI.

All floating point IIR filters designs must be based on **Single Precision** arithmetic and either a **Direct Form I** or **Direct Form II Transposed** filter structure. The **Direct Form II Transposed** structure is advocated for floating point implementation by virtue of its higher numerically accuracy.

Quantisation and filter structure settings can be found under the **Q** tab (as shown on the left). Setting **Arithmetic** to **Single Precision** and **Structure** to **Direct Form II Transposed** and clicking on the **Apply** button configures the IIR considered herein for the CMSIS-DSP software framework.

Select the **Arm CMSIS-DSP** framework from the selection box in the filter summary window:

The automatically generated C code based on the CMSIS-DSP framework for direct implementation on an Arm based Cortex-M processor is shown below:

As seen, the ASN Filter Designer’s automatic code generator generates all initialisation code, scaling and data structures needed to implement the A-weighting filter IIR filter via Arm’s CMSIS-DSP library.

In ECG signal processing, the Removal of 50/60Hz powerline interference from delicate information rich ECG biomedical waveforms is a challenging task! The challenge is further complicated by adjusting for the effects of EMG, such as a patient limb/torso movement or even breathing. A traditional approach adopted by many is to use a 2nd order IIR notch filter:

\(\displaystyle H(z)=\frac{1-2cosw_oz^{-1}+z^{-2}}{1-2rcosw_oz^{-1}+r^2z^{-2}}\)

where, \(w_o=\frac{2\pi f_o}{fs}\) controls the centre frequency, \(f_o\) of the notch, and \(r=1-\frac{\pi BW}{fs}\) controls the bandwidth (-3dB point) of the notch.

**What’s the challenge?**

As seen above, \(H(z) \) is simple to implement, but the difficulty lies in finding an optimal value of \(r\), as a desirable sharp notch means that the poles are close to unit circle (see right).

In the presence of stationary interference, e.g. the patient is absolutely still and effects of breathing on the sensor data are minimal this may not be a problem.

However, when considering the effects of EMG on the captured waveform (a much more realistic situation), the IIR filter’s feedback (poles) causes ringing on the filtered waveform, as illustrated below:

*Contaminated ECG with non-stationary 50Hz powerline interference (IIR filtering)*

As seen above, although a majority of the 50Hz powerline interference has been removed, there is still significant ringing around the main peaks (filtered output shown in red). This ringing is **undesirable for many biomedical applications**, as vital cardiac information such as the ST segment cannot be clearly analysed.

The frequency reponse of the IIR used to filter the above ECG data is shown below.

*IIR notch filter frequency response*

Analysing the plot it can be seen that the filter’s group delay (or average delay) is non-linear but almost zero in the passbands, which means no distortion. The group delay at 50Hz rises to 15 samples, which is the source of the ringing – where the closer to poles are to unit circle the greater the group delay.

ASN FilterScript offers designers the notch() function, which is a direct implemention of H(z), as shown below:

ClearH1; // clear primary filter from cascade ShowH2DM; // show DM on chart interface BW={0.1,10,.1,1}; Main() F=50; Hd=notch(F,BW,"symbolic"); Num = getnum(Hd); // define numerator coefficients Den = getden(Hd); // define denominator coefficients Gain = getgain(Hd); // define gain

**Savitzky-Golay FIR filters**

A solution to the aforementioned mentioned ringing as well as noise reduction can be achieved by virtue of a Savitzky-Golay lowpass smoothing filter. These filters are FIR filters, and thus have no feedback coefficients and no ringing!

Savitzky-Golay (polynomial) smoothing filters or least-squares smoothing filters are generalizations of the FIR average filter that can better preserve the high-frequency content of the desired signal, at the expense of not removing as much noise as an FIR average. The particular formulation of Savitzky-Golay filters preserves various moment orders better than other smoothing methods, which tend to preserve peak widths and heights better than Savitzky-Golay. As such, Savitzky-Golay filters are very suitable for biomedical data, such as ECG datasets.

**Eliminating the 50Hz powerline component**

Designing an 18th order Savitzky-Golay filter with a 4th order polynomial fit (see the example code below), we obtain an FIR filter with a zero distribution as shown on the right. However, as we wish to eliminate the 50Hz component completely, the tool’s P-Z editor can be used to nudge a zero pair (shown in green) to exactly 50Hz.

The resulting frequency response is shown below, where it can be seen that there is notch at exactly 50Hz, and the group delay of 9 samples (shown in purple) is constant across the frequency band.

*FIR Savitzky-Golay filter frequency response*

Passing the tainted ECG dataset through our tweaked Savitzky-Golay filter, and adjusting for the group delay we obtain:

*Contaminated ECG with non-stationary 50Hz powerline interference (FIR filtering)*

As seen, there are **no signs of ringing and the ST segments are now clearly visible for analysis**. Notice also how the filter (shown in red) has reduced the measurement noise, emphasising the practicality of Savitzky-Golay filter’s for biomedical signal processing.

A Savitzky-Golay may be designed and optimised in ASN FilterScript via the savgolay() function, as follows:

ClearH1; // clear primary filter from cascade interface L = {2, 50,2,24}; interface P = {2, 10,1,4}; Main() Hd=savgolay(L,P,"numeric"); // Design Savitzky-Golay lowpass Num=getnum(Hd); Den={1}; Gain=getgain(Hd);

## Deployment

This filter may now be deployed to variety of domains via the tool’s automatic code generator, enabling rapid deployment in Matlab, Python and embedded Arm Cortex-M devices.

In recent years, major microcontroller IC vendors such as: ST, NXP, TI, ADI, Atmel/Microchip, Cypress, Maxim to name but a few have based their modern 32-bit microcontrollers on Arm’s Cortex-M processor cores. This exciting trend means that algorithms traditionally undertaken in expensive DSPs (digital signal processors) can now be integrated into a powerful low-cost and power efficient microcontroller packed full of a rich assortment of connectivity and peripheral options.

For many IC vendors, the coupling of DSP functionality with the flexibility of a low power microcontroller, has allowed them to offer their customers a generation of so called **32-bit enhanced microcontrollers** suitable for a variety of practical applications. More importantly, this marriage of technologies has also allowed designers working on price critical IoT applications to implement complex algorithmic concepts, while at the same time keeping the overall product cost low and still achieving excellent low power performance.

## Upgrading legacy analog filters with the ASN Filter Designer

Analog filters have been around since the beginning of electronics, ranging from simple inductor-capacitor networks to more advanced active filters with op-amps. As such, there is a rich collection of tried and tested legacy filter designs for a broad range of sensor measurement applications.

ASN’s FilterScript symbolic math scripting language offers designers the ability to take an existing analog filter transfer function and transform it to digital with just a few lines of code. The ASN Filter Designer’s Arm automatic code generator analyses the designed digital filter and then** automatically generates Arm CMSIS-DSP compliant C code** suitable for direct implementation a Cortex-M based microcontroller.

**Arm CMSIS-DSP software framework**

The Arm CMSIS-DSP (Cortex Microcontroller Software Interface Standard) software framework is a rich collection of over sixty DSP functions (including various mathematical functions, such as sine and cosine; IIR/FIR filtering functions, complex math functions, and data types) developed by Arm that have been optimised for their range of Cortex-M processor cores. The framework makes extensive use of highly optimised SIMD (single instruction, multiple data) instructions, that perform multiple identical operations in a single cycle instruction. The SIMD instructions (if supported by the core) coupled together with other optimisations allow engineers to produce highly optimised signal processing applications for Cortex-M based micro-controllers quickly and simply.

## Mathematically modelling an analog circuit

Consider the active pre-emphasis filter shown below. The pre-emphasis filter has found particular use in audio work, since it is necessary to amplify the higher frequencies of the speech spectrum, whilst leaving the lower frequencies unaffected. The R and C values shown are only indented for the example, more practical values will depend on the application.A powerful method of reproducing the magnitude and phases characteristics of the analog filter in a digital implementation, is to mathematically model the circuit. This circuit may be analysed using Kirchhoff’s law, since the sum of currents into the op-amp’s inverting input **must be equal to zero for negative feedback to work correctly** – this results in a transfer function with a negative gain.

Therefore, using Ohm’s law, i.e. \(I=\frac{V}{R}\),

\(\displaystyle\frac{X(s)}{R_3}=-\frac{U(s)}{C_1||R_2 + R_1}

\)

After some algebraic manipulation, it can be seen that an expression for the circuit’s closed loop gain may be expressed as,

\(\displaystyle\frac{X(s)}{U(s)}=-\frac{R_3}{R_1}\frac{\left(s+\frac{1}{R_2C_1}\right)}{\left(s+\frac{R_1+R_2}{R_1R_2C_1}\right)}

\)

substituting the values shown in the circuit diagram into the developed transfer function, yields

\(\displaystyle H(s)=-10\left(\frac{s+1000}{s+11000}\right)

\)

**What sampling rate do we need?**

Analysing the cut-off frequencies in \(H(s)\), we see that the upper frequency is at \(11000 rad/sec\) or \(1.75kHz\). Therefore, setting the sampling rate to \(16kHz\) should be adequate for modelling the filter in the digital domain.

The sampling rate options are avaliabe in the main filter design UI (shown on the left).

**ASN FilterScript**

\(H(s)\) can be easily specified in FilterScript with the `analogtf`

function, as follows:

Nb={1,1000}; Na={1,11000}; Ha=analogtf(Nb,Na,-10,"symbolic");

Notice how the negative gain may also be entered directly into function’s argument. The `symbolic`

keyword generates a symbolic transfer function representation in the command window.

Applying the Bilinear z-transformation via the `bilinear`

command with no pre-warping, i.e.

Hd=bilinear(Ha,0,"symbolic");

Notice how the `bilinear`

command automatically scales numerator coefficients by -1, in order to account for the effect of the negative gain. The complete code is shown below:

Main() Nb={1,1000}; Na={1,11000}; Ha=analogtf(Nb,Na,-10,"symbolic"); Hd=bilinear(Ha,0,"symbolic"); Num=getnum(Hd); Den=getden(Hd); Gain=getgain(Hd);

A comparison of the analog and discrete magnitude and phase spectra is shown below. Analysing the spectra, it can be seen that for a sampling rate of 16kHz the analog and digital filters are almost identical! This demonstrates the relative ease with which a designer can port their existing legacy analog designs into digital.

## Automatic code generation to Arm Cortex-M processors

As mentioned at the beginning of this article, the ASN filter designer’s automatic code generation engine facilitates the export of a designed filter to Cortex-M Arm based processor cores via the CMSIS-DSP software framework. The tool’s built-in analytics and help functions assist the designer in successfully configuring the design for deployment.

Before generating the code, the H2 filter (i.e. the filter designed in FilterScript) needs to be firstly re-optimised (transformed) to an H1 filter (main filter) structure for deployment. The **options** menu can be found under the **P-Z** tab in the main UI.

All floating point IIR filters designs must be based on **Single Precision** arithmetic and either a **Direct Form I** or **Direct Form II Transposed** filter structure. The **Direct Form II Transposed** structure is advocated for floating point implementation by virtue of its higher numerically accuracy.

Quantisation and filter structure settings can be found under the **Q** tab (as shown on the left). Setting **Arithmetic** to **Single Precision** and **Structure** to **Direct Form II Transposed** and clicking on the **Apply** button configures the IIR considered herein for the CMSIS-DSP software framework.

**Arm CMSIS-DSP application C code**

Select the **Arm CMSIS-DSP** framework from the selection box in the filter summary window:

The automatically generated C code based on the CMSIS-DSP framework for direct implementation on an Arm based Cortex-M processor is shown below:

As seen, the automatic code generator generates all initialisation code, scaling and data structures needed to implement the IIR via the CMSIS-DSP library. This code may be directly used in any Cortex-M based development project – a complete Keil MDK example is available on Arm/Keil’s website. Notice that the tool’s code generator produces code for the Cortex-M4 core as default, please refer to the table below for the `#define`

definition required for all supported cores.

`ARM_MATH_CM0` | Cortex-M0 core. | `ARM_MATH_CM4` | Cortex-M4 core. |

`ARM_MATH_CM0PLUS` | Cortex-M0+ core. | `ARM_MATH_CM7` | Cortex-M7 core. |

`ARM_MATH_CM3` | Cortex-M3 core. | ||

`ARM_MATH_ARMV8MBL` | ARMv8M Baseline target (Cortex-M23 core). | ||

`ARM_MATH_ARMV8MML` | ARMv8M Mainline target (Cortex-M33 core). |

The main test loop code (not shown) centres around the `arm_biquad_cascade_df2T_f32()`

function, which performs the filtering operation on a block of input data.

## What have we learned?

The **ASN Filter Designer provides engineers with everything they need** in order to port legacy analog filter designs to a variety of Cortex-M processor cores.

The FilterScript symbolic math scripting language offers designers the ability to take an existing analog filter transfer function and transform it to digital (via the Bilinear z-transform or matched z-transform) with just a few lines of code.

The Arm automatic code generator analyses the designed digital filter and then **automatically generates Arm CMSIS-DSP compliant C code** suitable for direct implementation on a Cortex-M based microcontroller.

**Extra resources**

- Step by step video tutorial of designing an IIR and deploying it to Keil MDK uVision.
- Implementing Biquad IIR filters with the ASN Filter Designer and the Arm CMSIS-DSP software framework (ASN-AN025)
- Keil MDK uVision example IIR filter project
- Step by step instruction video of this tutorial Arm Webinar (requires registration)

### Advanced Solutions Nederland B.V.

Maanlander 47

3824 MN Amersfoort

The Netherlands

Tel: +31 652460840

General enquiries: info@advsolned.com

Technical support: support@advsolned.com

Sales enquiries: sales@advsolned.com