Posts

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_CM0Cortex-M0 core.ARM_MATH_CM4Cortex-M4 core.
ARM_MATH_CM0PLUSCortex-M0+ core.ARM_MATH_CM7Cortex-M7 core.
ARM_MATH_CM3Cortex-M3 core.  
ARM_MATH_ARMV8MBLARMv8M Baseline target (Cortex-M23 core).
ARM_MATH_ARMV8MMLARMv8M 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

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

Upgrading legacy designs based on analog filters

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. However, with the performance requirements of modern IoT (Internet of Things) sensor measurement applications and lower product costs, digital filters integrated into the microcontroller’s application code are becoming the norm, but how can we get the best of both worlds?

Rather than re-inventing the wheel, product designers can take an existing analog filter transfer function, transform it to digital (via a transform) and implement it as digital filter in a microcontroller or DSP (digital signal processor). Although  analog-to-digital transforms have been around for decades, the availability of DSP design tooling for tweaking the ‘transformed digital filter’ has been somewhat limited, hindering the design and validation process.

A 2nd order analog lowpass filter is shown below, and in its simplest form, only 5 components are required to build the filter, which sounds easy. Right?2nd order analog lowpass filter

The pros

The most obvious advantage is that analog filters have an excellent resolution, as there are no ‘number of bits’ to consider. Analog filters have good EMC (electromagnetic compatibility) properties as there is no clock generating noise. There are no effects of aliasing, which is certainly true for the simpler op-amps, which don’t have any fancy chopping or auto-calibration circuitry built into them, and analog designs can be cheap which is great for cost sensitive applications.

Sound great, but what’s the bad news?

Analog filters have several significant disadvantages that affect filter performance, such as component aging, temperature drift and component tolerance. Also, good performance requires good analog design skills and good PCB (printed circuit board) layout, which is hard to find in the contemporary skills market.

These disadvantages make digital filters much more attractive for modern applications, that require high repeatability of characteristics.  Looking at an example, let’s say that you want to manufacture 1000 measurement modules after optimising your filter design. With a digital solution you can be sure that the performance of your filter will be identical in all modules. This is certainly not the case with analog, as component tolerance, component aging and temperature drift mean that each module’s filter will have its own characteristics. Also, an analog filter’s frequency response remains fixed, i.e. a Butterworth filter will always be a Butterworth filter – any changes the frequency response would require physically changing components on the PCB – not ideal!

Digital filters are adaptive and flexible, we can design and implement a filter with any frequency response that we want, deploy it and then update the filter coefficients without changing anything on the PCB! It’s also easy to design digital filters with linear phase and at very low sampling frequencies – two things that are tricky with analog.

Laplace to discrete/digital transforms

The three methods discussed herein essentially involve transforming a Laplace (analog) transfer function, \(H(s)\) into a discrete transfer function, \(H(z)\) such that a tried and tested analog filter that is already used in a design may be implemented on a microcontroller or DSP.

A selection of some useful Laplace to z-transforms are given in table below:

\(
\begin{array}{ccc}\hline
H(s) &\longleftrightarrow & H(z) \\ \hline
1 &\longleftrightarrow & 1 \\
\frac{\displaystyle1}{\displaystyle s}
&\longleftrightarrow& \frac{\displaystyle 1}{\displaystyle 1-z^{\scriptstyle -1}}\\
\frac{\displaystyle 1}{\displaystyle s^{\scriptstyle 2}} &\longleftrightarrow& \frac{\displaystyle
Tz^{\scriptstyle-1}}{\displaystyle (1-z^{\scriptstyle -1})^2}\\
\frac{\displaystyle 1}{\displaystyle s+a}
&\longleftrightarrow&
\frac{\displaystyle 1}{\displaystyle 1-e^{-aT}z^{-1}}\\
\frac{\displaystyle 1}{\displaystyle (s+a)^2}
&\longleftrightarrow& \frac{\displaystyle z^{-1}(1-e^{-aT})}{\displaystyle a(1-z^{-1})(1-e^{-aT}z^{-1})}\\\hline
\end{array}
\)
A table of useful Laplace and z-transforms

The Bilinear z-transform (BZT)

The Bilinear z-transform (BZT), simply converts an analog transfer function, \(H(s)\) into a discrete transfer function, \(H(z)\) by replacing all \(s\) terms with the following:

\(\displaystyle
s=\frac{2}{T}\frac{1-z^{-1}}{1+z^{-1}} \label{bzt}\)

where, \(T\) is the discrete system’s sampling period. However, substituting \(s=j\Omega\) and \(z=e^{jwT}\) into the BZT equation and simplifying, notice that there is actually a non-linear relationship between the analog, \(\Omega\) and discrete, \(w\) frequencies. This relationship is shown below, and is due to the nonlinearity of the arctangent function.

\(\displaystyle\omega=2\tan^{-1}\left(\frac{\Omega T}{2}\right)\label{bzt_warp_def1}\)

Analysing the equation, it can be seen that the equally spaced  analog frequencies in the range \( -\infty\lt\Omega\lt\infty\) are nonlinearly compressed in the frequency range \( -\pi\lt w\lt\pi\) in the discrete domain. This relationship is referred to as frequency warping, and may be compensated for by pre-warping the analog frequencies by:

\(\displaystyle
\Omega_c=\frac{2}{T}\tan\left(\frac{\Omega_d T}{2}\right)
\label{bzt_warp_def2}
\)

where, \(\displaystyle\Omega_c\) is the compensated or pre-warped analog frequency, and \(\displaystyle\Omega_d\) is the desired analog frequency.

The ASN FilterScript command \(\texttt{bilinear}\) may be used convert a Laplace transfer function into its discrete equivalent using the BZT transform. An example is given below.

The Impulse Invariant Transform

The second transform, is referred to as the impulse invariant transform (IIT), since the poles of the Laplace transfer function are converted into their discrete equivalents, such that the discrete impulse response, \(h(n)\) is identical to a regularly sampled representation of the analog impulse response (i.e., \(h(n)=h(nT)\), where \(T\) is the sampling rate, and \(t=nT\)). The IIT is a much more tedious transformation technique than the BZT, since the Laplace transfer function must be firstly expanded using partial fractions before applying the transform.

The transformation technique is defined below:

\(\displaystyle
\frac{K}{s+a} \quad\longrightarrow\quad
\frac{K}{1-e^{-aT}z^{-1}} \label{iit_def}
\)

This method suffers from several constraints, since it does not allow for the transformation of zeros or individual constant terms (once expanded), and must have a high sampling rate in order to overcome the effects of spectral aliasing. Indeed, the effects of aliasing hinder this method considerably, such that the method should only be used when the requirement is to match the analog transfer function’s impulse response, since the resulting discrete model may have a different magnitude and phase spectrum (frequency response) to that of the original analog system. Consequently, the impulse invariant method is unsuitable for modelling highpass filters, and is therefore limited to the modelling of lowpass or bandpass type filters.

Due to the aforementioned limitations of the IIT method, it is currently not supported in ASN Filterscript.

The Matched-z transformation

Another analog to discrete modelling technique is the matched-z transformation. As the name suggests, the transform converts the poles and zeros from the analog transfer function directly into poles and zeros in the z-plane. The transformation is described below, where \(T\) is the sampling rate.

\(\displaystyle
\frac{\prod\limits_{k=1}^q(s+b_k)}{\prod\limits_{k=1}^p(s+a_k)}
\quad\longrightarrow\quad
\frac{\prod\limits_{k=1}^q(1-e^{-b_kT}z^{-1})}{\prod\limits_{k=1}^p(1-e^{-a_kT}z^{-1})}
\label{matchedz_def}
\)

Analysing the transform equation, it can be seen that the transformed z-plane poles will be identical to the poles obtained with the impulse invariant method. However, notice that the positions of the zeros will be different, since the impulse invariant method cannot transform them.

The ASN Filterscript command \(\texttt{mztrans}\) is available for this method.

A detailed example

In order to demonstrate the ease of transforming analog filters into their discrete/digital equivalents using the analog to discrete transforms, an example of modelling with the BZT will now follow for a 2nd order lowpass analog filter.

A generalised 2nd order lowpass analog filter is given by:

\(\displaystyle
H(s)=\frac{w_c^2}{s^2+2\zeta w_c s + w_c^2}
\)

where, \(w_c=2\pi f_c\) is the cut-off frequency and \(\zeta\) sets the damping of the filter,  where a  \(\zeta=1/\sqrt{2}\) is said to be critically damped or equal to -3dB at \(w_c\). Many analog engineers choose to specify a quality factor, \(Q =  \displaystyle\frac{1}{2\zeta}\) or peaking factor for their designs. Substituting \(Q\) into \(H(s)\), we obtain:

\(\displaystyle
H(s)=\frac{w_c^2}{s^2+ \displaystyle{\frac{w_c}{Q}s} + w_c^2}
\)

Analysing, \(H(s)\) notice that \(Q=1/\sqrt{2} = 0.707\) also results in a critically damped response. Various values of \(Q\) are shown below, and as seen when \(Q>1/\sqrt{2}\) peaking occurs.

Values of Q

2nd order lowpass filter prototype magnitude spectrum for various value of Q:
notice that when \(Q>1/\sqrt{2}\) peaking occurs.

Before applying the BZT in ASN FilterScript, the analog transfer function must be specified in an analog filter object. The following code sets up an analog filter object for the 2nd order lowpass prototype considered herein:
[code language=”java”]
Main()

wc=2*pi*fc;
Nb={0,0,wc^2};
Na={1,wc/Q,wc^2};

Ha=analogtf(Nb,Na,1,"symbolic"); // make analog filter object
[/code]
The \(\texttt{symbolic}\) keyword generates a symbolic transfer function representation in the command window. For a sampling rate of \(f_s=500Hz\) and \(f_c=30Hz\) and \(Q=0.707\), we obtain:

ASN FilterScript analog command

Applying the BZT via the \(\texttt{bilinear}\) command without prewarping,
[code language=”java” light=”true”] Hd=bilinear(Ha,0,"symbolic"); [/code]
bilinear transformation

The complete frequency response of the transformed digital filter is shown below, where it can be seen that the at \(30Hz\) the magnitude is \(-3dB\) and the phase is \( -90^{\circ}\), which is as expected. Notice also how the filter’s magnitude roll-off  is affected by the double zero pair at Nyquist (see the z-plane chart below), leading to differences from its analog cousin. Pole-zero chart 2nd order LPF

2nd order LPF

The pole-zero positions may be tweaked within ASN Filterscript or via the ASN Filter Designer’s interactive pole-zero z-plane plot editor by just using the mouse!

Implementation

The complete code for transforming a generalised 2nd order analog  lowpass filter prototype into its digital equivalent using the BZT via ASN FilterScript is given below:
[code language=”java”]

ClearH1; // clear primary filter from cascade
interface Q = {0.1,10,0.02,0.707};
interface fc = {10,200,10,40};

Main()

wc=2*pi*fc;
Nb={0,0,wc^2};
Na={1,wc/Q,wc^2};

Ha=analogtf(Nb,Na,1,"symbolic"); // make analog filter object
Hd=bilinear(Ha,0,"symbolic"); // transform Ha via BZT into digital object, Hd

Num=getnum(Hd);
Den=getden(Hd);
Gain=getgain(Hd);

[/code]

ASN Filter Designer Box

Download demo now

Licencing information


Author

  • Dr. Sanjeev Sarpal

    Sanjeev is an AIoT visionary and expert in signals and systems with a track record of successfully developing over 25 commercial products. He is a Distinguished Arm Ambassador and advises top international blue chip companies on their AIoT solutions and strategies for I4.0, telemedicine, smart healthcare, smart grids and smart buildings.

    View all posts