Posts

Many IoT applications use a sinewave for estimating the amplitude of an entity of interest – some examples include:

  • Measuring material fatigue/strain with a loadcell – in vehicle and bridge/building applications measuring material fatigue and strain is essential for safety. An AC sinusoidal excitation overcomes the difficulty of dealing with instrumentation electronics DC offsets.
  • Calibrating CT (current transformers) sensors channels – a sinusoid of known amplitude is applied to channel input and the output amplitude is measured.
  • Measuring gas concentration in infra-red gas sensors – the resulting sinusoid’s amplitude is used to provide an estimate of gas concentration.
  • Measuring harmonic amplitudes in power quality smart grids applications – in 50/60Hz  power systems, certain harmonic amplitudes are of interest.
  • ECG biomedical compliance testing – channel compliance with IEC regulations needed for FDA testing typically uses a set of sinewaves at known amplitudes, to ensure that the channel amplitude error is within specification.

In a previous article, we discussed how differentiation could be used to find the peaks and troughs of sinewave, i.e. finding the zero crossing points. However, a much more traditional approach has been to use fullwave rectification, whereby a non-linear operator and lowpass filtering are employed. The concept used is described below:

  1. Remove any DC or low-frequency offsets via a highpass filter.
  2. Apply a non-linear operator via an abs() or sqr() non-linear operator.
  3. Lowpass filter the result to obtain an estimate of the sinusoid’s amplitude.
  4. Scale the amplitude.

Although this sounds easy, care should be taken to understand the effects of how the non-linear operator alters the waveform and affects the estimation of amplitude using lowpass filtering.

IoT application

A typical IoT application using a sinusoid is shown below:

As seen, the waveform can be modelled as:

\(x\left(n\right)=A\,sin\left(2\pi f_ot\right)+B\)

Where, \(f_o\)  is the frequency of oscillation and \(A\) is the amplitude of sinusoid respectively. Notice that the sinusoid is non-linear and symmetrical around the offset, \(B\). Notice also that it has a peak-to-peak amplitude of \(2A\), since specifying an amplitude \(A\) results in a bipolar amplitude of \(±A\). As many microcontrollers employ low-cost unipolar ADCs, the bipolar sinusoid needs to be offset by a DC offset, \(B\) (usually achieved by a resistor network) to ensure that the signal remains within the common-mode range of the ADC input.

As mentioned above, before applying the non-linear operator any DC offsets need to be removed. This can easily be achieved with either an IIR or FIR highpass filter. If using an IIR filter, it should be noted that the filter’s phase and group delay (latency) will significantly increase at the cut-off frequency, so a degree of experimentation is required to find a good trade-off.

After highpass filtering the data, we can apply the non-linear operator. Two popular operators are the abs()and sqr() operators.

Using the abs() operator, the Fourier series of \(\left|A \,sin(2\pi f_ot)\right|\) is shown below:

\(\left|A\ sin(2\pi f_ot)\right|\ =\ \displaystyle A\left[ \frac{2}{\pi}\ -\ \displaystyle\frac{4}{\pi}\normalsize{\sum\limits_{k=1}^{\infty}}\frac{cos(4k\pi f_ot)}{4k^2-1}\right]\)

Analysing the equation, it can be seen that the abs() operation doubles the frequency and that the DC component is actually \(\frac{2A}{\pi}\), as illustrated below.

As seen, lowpass filtering this result in its current form will produce an amplitude estimate of \(\frac{2A}{\pi}\) (dashed red line), which is clearly incorrect for estimating the sinewave’s amplitude, \(A\). However, this can be simply remedied by scaling the amplitude estimates by \(\frac{\pi}{2}\), which removes the bias, leaving the sinewave’s amplitude, \(A\).

Likewise, for a sqr() operator, we can define the resulting waveform using trigonometrical identities, i.e.

\({sin^2(2\pi f_ot)}\ =\ A\left[\displaystyle\frac{1\ -\ cos(4\pi f_ot)}{2}\right]\)

Lowpass filtering this signal requires a correction scaling factor of 2.  

Lowpass filter

Although any lowpass filter will suffice, the moving average filter is used by most developers by virtue of its computational simplicity and noise reduction characteristics. A more detailed explanation of moving average filters can be found here.

A 24th order moving average filter with a post gain of \(\frac{\pi}{2}\) or 1.571 is shown below.

Applying this moving average filter to a sinewave \(f_o=10Hz, A=0.5\), sampled at 500Hz processed with the abs()operator we obtain the following:

As seen, the amplitude estimation of the sinusoid using a lowpass filter and the \(\frac{\pi}{2}\) scaling factor is now correct. However, for real world applications that contain noise, it is considered to be more accurate to measure the RMS amplitude, in which case the scaling factor becomes \(\frac{\pi}{2\sqrt 2} \).

As a final point, these scaling factors are only valid for sinusoidal scaling. If your waveform is non-sinsoidual (e.g. triangular or square) another scaling factor will be required.

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.

AIoT is an exciting new area that combines AI concepts (i.e. ML) with IoT in order to produce state-of-the-art smart embedded solutions. This augmentation of technologies requires a new set of tools to capture real-time IoT sensor data, analyse it, design suitable algorithms and then perform validation of the solution.  After completing validation of the algorithms on the test data, a final hurdle is then how to generate efficient C code of the developed algorithm(s) for an Arm Cortex-M microcontroller for use in an application. These concepts will be discussed herein.

Arm’s Synchronous Data Stream (SDS) Framework provides developers with an easy method of capturing and playing back real-time sensor data for embedded AIoT sensor applications on Arm Cortex-M processors, such as ST Microelectronics’ very popular STM32 family.

The SDS Framework provides embedded developers with a variety of essential tools, such as the ability to record real-world sensor data for analysis and development in tools such as ASN Filter Designer, Python and Matlab. A set of Python utility scripts are available for recording, playback, visualisation and data conversion, where the latter supports the conversion of captured SDS data files into a single CSV file – providing a simple bridge between the ASN Filter Designer and the SDS Framework.

The SDS framework also supports the possibility to playback real-world data for algorithm validation using Arm Virtual Hardware, allowing developers to verify execution of DSP algorithms on Cortex-M targets with off-line tools.

This application note provides AIoT developers with a complete reference guide of how to develop and deploy feature extraction algorithms for use in AIoT applications to STM32 Arm Cortex-M based microcontrollers using STM32CubeIDE or Keil mVision with the Arm SDS framework and ASN Filter Designer. As mentioned above, AIoT system challenges and concepts will also be covered.

Building AIoT systems

Almost all IoT embedded sensor applications require some level of signal processing to enhance sensor data and extract features of interest. However, an obvious hurdle for many developers is how to design, test and deploy efficient algorithms for their application. This is easier said than done, as many software engineers are not well-versed in understanding the mathematical concepts needed to implement algorithms. This is further complicated by the challenge of how to implement algorithms developed by researchers that are not interested/experienced in developing real-time embedded applications.

A possible solution offered by the Mathworks (Embedded Coder) automatically translates Matlab algorithms and functions into C for Arm processors, but its high price tag and steep learning curve make it unattractive for many.

That being said, Arm and its rich ecosystem of partners provide developers with extensive easy-to-use tooling and tried and tested software libraries. Arm’s CMSIS-DSP and CMSIS-NN frameworks for algorithm development and machine learning (ML) are two very popular examples that are open source and are used internationally by tens of thousands of developers.

The Arm CMSIS-DSP software framework is particularly interesting as it provides IoT developers with a rich collection of fast mathematical and vector functions, interpolation functions, digital filtering (FIR/IIR) and adaptive filtering (LMS) functions, motor control functions (e.g. PID controller), complex math functions and supports various data types, including fixed and floating point. The important point to make here is that all of these functions have been optimised for Arm Cortex-M processors, allowing you to focus on your application rather than worrying about optimisation.  

The Arm-CMSIS framework solutions are strengthened by Arm partners ASN and Qeexo who provide developers with easy-to-use real-time filtering, feature extraction (ASN Filter Designer) and ML tooling (AutoML) and reference designs, expediting the development of AIoT applications, including industrial, audio and biomedical. These solutions have been optimised for Arm processors with the help of Arm’s architecture experts and insider knowledge of compiler workings.

AIoT system building blocks

An essential pre-building block in any AIoT system is the feature extraction algorithm. The challenge for any feature extraction algorithm is to extract and enhance any relevant sensor data features in noisy or undesirable circumstances and then pass them onto the ML model in order to provide an accurate classification.  The concept is illustrated below:

As seen above, an AIoT system may actually contain multiple feature blocks per sensor and in some cases fuse the features locally before sending them onto the ML model for classification such that the system may then draw a conclusion. The challenge is therefore how to capture sensor data for training and design suitable algorithms to extract features of interest.

Feature extraction algorithms: challenges and solutions

The challenge for any feature extraction algorithm is to extract and enhance any relevant data features in noisy data or undesirable circumstances and then pass them onto the ML model in order to provide an accurate classification. Unfortunately, many ML models perform badly, due to poor quality data and insufficient training data.   An obvious challenge for AIoT is how do we obtain the training data in the first place? In many cases, this is extremely challenging as data pertaining to faults (such as preventive maintenance) is hard to come by, as many plant managers are reluctant to break their working production lines or processes to provide developers with training data.

In the absence of adequate training data, feature extraction based on science and mathematics is a prudent alternative, as less training data is required, and in general, the quality of the feature estimate is higher as knowledge of the underlying process is used. Examples include: obtaining accurate pulse and heart rate estimates from ECG and PPG sensors in smartwatch applications when a subject is moving.  For industrial sensors, such as loadcells, pressure, temperature, gas and accelerometer sensors the challenge is amplified, as harsh operating conditions and the sheer variety of the applications needed for I4.0 process control applications complicate the design significantly.

Example: Infrared gas sensor

Consider the following application for gas concentration measurement from an Infrared gas sensor. The requirement is to determine the peak-to-peak amplitude of the sinusoid in order to get an estimate of gas concentration – where the bigger amplitude is the higher the gas concentration will be.

Analysing the Figure, it can be seen that the sinusoid is corrupted with measurement noise (shown in blue), and any estimate based on the blue signal will have a high degree of uncertainty about it – which is not very useful for getting an accurate reading of gas concentration! After cleaning the sinusoid with a digital filter (red line), we obtain a much more accurate and usable signal for our gas concentration estimation challenge. But how do we obtain the amplitude?

Knowing that the gradient at the peaks is zero, a relatively easy and robust way of finding the peaks of the sinusoid is via numerical differentiation, i.e. computing the difference between sample values and then looking for the zero-crossing points in the differentiated data. Armed with the positions and amplitudes of the peaks, we can take the average and easily obtain the amplitude and frequency.  Notice that any DC offsets and low-frequency baseline wander will be removed via the differentiation operation.

This is just a simple example of how to extract the properties of a sinusoid in real-time using science and mathematics and an understanding of the underlying process without the need for ML training data.

AIoT feature extraction smart sensor design workflow

Arm’s Synchronous Data Stream (SDS) Framework provides developers with an easy method of capturing and playing back real-time sensor data for embedded AIoT sensor applications on Arm Cortex-M processors. A set of Python utility scripts are available for recording, playback, visualisation and data conversion, where the latter supports the conversion of captured SDS data files into a single CSV file – providing a simple bridge between the ASN Filter Designer and the SDS Framework.

An AIoT smart sensor design workflow using the ASN Filter Designer and the SDS Framework is shown below.

As seen above, three major components constitute the AIoT design workflow.

  1. Arm SDS Framework: capturing IoT sensor data and converting it to CSV format.
  2. ASN Filter Designer: importing the CSV datafile and then analysing the data. Based on the data analysis, a suitable filter can be designed together with other filters and IP blocks in order to build feature extraction algorithms for ML applications.
  3. Application deployment: Generating optimised C code and combining the design with an application for use on an Arm microcontroller.

The SDS Framework can be used with all major demo boards, including ST’s Discovery kit and Nucleo boards. SDS Python utilities are used to convert the captured *.sds and *.yaml files into a CSV file for import into the ASN Filter Designer, as discussed in the following section.

Data Import Wizard

The ASN Filter Designer’s comprehensive data import wizard can delimitate and import a variety of multi-column IoT datasets in CSV or TXT form.

As seen in the video, a generated CSV file can be dragged and dropped onto the signal analyser canvas, bringing up the data import wizard. The import wizard will automatically check the imported data for errors (such as NaNs, Infs etc) and then order the data into columns. Any header line data can be skipped by setting the Skip Headerlines value respectively.

For the example considered herein, the data is actually triaxial accelerometer data (i.e. X, Y and Z axes) with an extra column for the timebase. Therefore, if we wish to import the X-axis data, we can simply click on the header for the second column (B).   The tool will then ask you to recheck the data, and upon clicking on ‘Save’ will save the selected data as a single-column CSV file (needed for the ASN Filter Designer). This new CSV file can then be streamed via the tool’s signal generator for algorithm development.

Deploying to Arm Cortex-M processors

After completing the design process, the designed filter(s) can be deployed to STM32CubeIDE or Arm/Keil uVision for integration into an application project. Depending on the functionality of the ASN Filter Designer’s signal chain, two software frameworks are available: Arm’s CMSIS-DSP and ASN’s ANSI C DSP.

The ANSI C DSP framework was developed with close collaboration with Arm’s architecture team, providing outstanding computational performance that is required for real or complex coefficient floating-point designs that use multiple filters and mathematical functions in a signal chain. The Arm CMSIS-DSP framework on the other hand is an excellent choice for implementing both fixed-point and floating-point filters, but is limited to real coefficient single FIR filter or one IIR Biquad cascade with no extra mathematical functions.

A benchmark comparison for both frameworks is shown below for an 8th IIR filter running on three different Arm cores. As seen, the ASN Framework is slightly faster (lower means better performance) than the Arm Framework.

Framework Benchmarks: lower number of clock cycles means higher performance.

Arm CMSIS-DSP wizard

Professional licence users may expedite the deployment by using the Arm deployment wizard. The tool will automatically analyse your design and choose a suitable Framework. If the design cannot be exported via the Arm CMSIS-DSP framework, the tool will suggest that you use the ASN ANSI C framework and launch the code generation wizard.

Note that the built-in AI will automatically determine the best settings for your design based on the quantisation settings chosen.

Clicking on Deploy will automatically analyse your complete filter cascade and convert any extra filters in the cascade into an H1 (primary) for implementation. Upon completion, the tool will then launch the C code generation wizard.

CMSIS-DSP C code generation

Depending on which C framework is used, the C code generator wizard will automatically generate the C code needed for your design. For developers using the Arm CMSIS-DSP framework, a single C file is generated for use with an MDK5 software pack. The MDK5 pack is available from Arm Keil’s software pack repository, providing several complete filtering examples based on the ASN Filter Designer’s code generator using the Arm CMSIS-DSP library.

A detailed help tutorial is available by clicking on the Show me button. 

ASN ANSI C DSP code generation

For developers using the ASN ANSI C DSP framework, the code wizard should be used.

NB. The wizard will produce a CodeBlocks project in order to get you started. The following section describes in detail the steps needed for using the generated code in a STM32CUBE-IDE project. Please refer to the ANSI C SDK user guide for step-by-step instructions on how to use the generated code in other IDEs. 

A PDF version of this article is available as an application note.

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.

Over the decades Microsoft has produced various programming languages (e.g. C#, F#, Visual Basic) and flavours of their .NET paradigm, such as the very popular 4.x .NET Framework.  

C# is very popular among Windows developers, as it is based on objected orientated programming concepts together with a few other pearls, such as automatic memory management (something that had to be handled manually in C++), in an attempt to provide many of the advantages of C++ in a much more simplified way.

These pros combined with the .NET Framework’s extensive charting library, UI toolbox, Networking, ML engine libraries and general ease of use in Microsoft Visual Studio was one of the primary reasons that many Windows-based scientific programs (e.g. ASN Filter Designer) were developed using the C# language and .NET Framework.

Over the last few years, Microsoft has tried to consolidate their .NET solution into a single, fast, cross-platform solution with the advent of the .NET Core paradigm. .NET Core is an open-source framework for developing Windows, web applications, services, and mobile applications and it can be run on Windows, Mac and Linux. Microsoft contends that .NET Core is much faster than the .NET Framework since the architecture has been completely rewritten to make it modular, lightweight, fast and cross-platform compatible.

DSP filtering library for C# .NET applications

For many modern scientific applications digital filtering of datasets is just one of the many components needed for an algorithm. This could be extracting ECG and PPG biomedical features, cancelling powerline interference or removing the noise from a dataset. In many cases, it is desirable to perform the filtering in real-time on streaming data as part of an algorithm updating dashboard analytics.

ASN Filter Designer provides .NET developers with an automatic code generator and SDK for developing high-performance data filtering applications in C#.

The tool’s project wizard bundles all of the necessary SDK framework files needed to run a designed filter cascade without the need for any other dependencies or 3rd party plugins. The deployed code is fully compatible with Microsoft Visual Studio and all .NET versions.

A complete overview of the SDK is available here.

 

 

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.

ASN Filter Designer v5 with easy-to-use code generators to C, Python and C#, for fast and efficient application development. Hardware agnostic.

Filter mit unendlicher Impulsantwort (IIR) sind für eine Vielzahl von Sensormessanwendungen nützlich, einschließlich der Entfernung von Messrauschen und der Unterdrückung unerwünschter Komponenten, wie z. B. Stromleitungsstörungen. Obwohl mehrere praktische Implementierungen für den IIR existieren, bietet die Struktur Direct form II Transposed die beste numerische Genauigkeit für die Fließkomma-Implementierung. Wenn jedoch eine Festkomma-Implementierung auf einem Mikrocontroller in Betracht gezogen wird, gilt die Struktur Direkte Form I aufgrund ihres großen Akkumulators, der eventuelle Zwischenüberläufe aufnimmt, als die beste Wahl. Diese Application Note befasst sich speziell mit dem Entwurf und der Implementierung von IIR-Biquad-Filtern auf einem Cortex-M-basierten Mikrocontroller mit dem ASN Filter Designer sowohl für Fließkomma- als auch für Festkomma-Anwendungen über das Arm CMSIS-DSP Software-Framework.

Es werden auch Details (einschließlich eines Referenzbeispielprojekts) zur Implementierung des IIR-Filters in Arm/Keils MDK-Industriestandard-Cortex-M-Mikrocontroller-Entwicklungskit gegeben.

Einführung

ASN Filter Designer bietet Ingenieuren eine leistungsfähige DSP-Experimentierplattform, die den Entwurf, das Experimentieren und den Einsatz komplexer IIR- und FIR (Finite Impulse Response)-Digitalfilterdesigns für eine Vielzahl von Sensormessanwendungen ermöglicht. Die fortschrittliche Funktionalität des Tools umfasst einen grafikbasierten Echtzeit-Filterdesigner, mehrere Filterblöcke, verschiedene mathematische I/O-Blöcke, symbolisches Live-Mathe-Scripting und Echtzeit-Signalanalyse (über einen integrierten Signalanalysator). Diese Vorteile in Verbindung mit der automatischen Dokumentation und Code-Generierungsfunktionalität ermöglichen es Ingenieuren, ein digitales Filter innerhalb von Minuten statt Stunden zu entwerfen und zu validieren.

Das Arm CMSIS-DSP (Cortex Microcontroller Software Interface Standard) Software-Framework ist eine reichhaltige Sammlung von über sechzig DSP-Funktionen (einschließlich verschiedener mathematischer Funktionen wie Sinus und Kosinus; IIR/FIR-Filterfunktionen, komplexe mathematische Funktionen und Datentypen), die von Arm entwickelt und für die Cortex-M-Prozessorkerne optimiert wurden.

Das Framework macht ausgiebig Gebrauch von hoch optimierten SIMD-Befehlen (Single Instruction, Multiple Data), die mehrere identische Operationen in einem einzigen Befehlszyklus ausführen. Die SIMD-Befehle (sofern vom Core unterstützt) in Verbindung mit anderen Optimierungen ermöglichen es Ingenieuren, schnell und einfach hochoptimierte Signalverarbeitungsanwendungen für Cortex-M-basierte Mikrocontroller zu erstellen.

Der ASN Filter Designer unterstützt das CMSIS-DSP Software-Framework vollständig, indem er über seine Code-Generierungs-Engine automatisch optimierten C-Code auf Basis der DSP-Funktionen des Frameworks erzeugt.

Entwurf von IIR-Filtern mit dem ASN Filter Designer

Der ASN Filter Designer bietet Ingenieuren eine einfach zu bedienende, intuitive grafische Design-Entwicklungsplattform für den Entwurf von digitalen IIR- und FIR-Filtern. Das Echtzeit-Entwurfsparadigma des Tools nutzt grafische Entwurfsmarker, die es dem Designer ermöglichen, seine Anforderungen an den Größen-Frequenzgang in Echtzeit einfach zu zeichnen und zu modifizieren, während das Tool automatisch die exakten Spezifikationen für sie ausfüllt.

Betrachten Sie den Entwurf der folgenden technischen Spezifikation:

Fs:  500Hz
Durchlassband-Frequenz:  0-40Hz
Typ:  Tiefpass
Verfahren:  Elliptisch
Sperrbanddämpfung @ 125Hz:   ≥ 80 dB
Passband ripple:  < 0.1dB
Ordnung  Klein wie möglich

Durch die grafische Eingabe der Spezifikationen in den ASN Filter Designer und die Feinabstimmung der Positionen der Entwurfsmarker entwirft das Tool das Filter automatisch als Biquad-Kaskade (diese Terminologie wird in den folgenden Abschnitten erläutert), wählt automatisch die erforderliche Filterordnung und erzeugt im Wesentlichen automatisch die genaue technische Spezifikation des Filters!

Der Frequenzgang eines elliptischen IIR-Tiefpassfilters 5. Ordnung, der die Spezifikationen erfüllt, ist unten dargestellt:

Tiefpaßfilter 5. Ordnung

Dieses Tiefpaßfilter 5. Ordnung bildet die Grundlage für die hier geführte Diskussion.

Biquad-IIR-Filter

Die hier besprochene IIR-Filter-Implementierung wird als Biquad bezeichnet, da sie zwei Pole und zwei Nullstellen hat, wie in Abbildung 1 dargestellt. Die Biquad-Implementierung ist besonders nützlich für Festkomma-Implementierungen, da die Auswirkungen der Quantisierung und der numerischen Stabilität minimiert werden. Der Gesamterfolg jeder Biquad-Implementierung hängt jedoch von der verfügbaren Zahlengenauigkeit ab, die ausreichend sein muss, um sicherzustellen, dass die quantisierten Pole immer innerhalb des Einheitskreises liegen.

Direkte Form I (Biquad) IIR-Filterrealisierung und Übertragungsfunktion

Abbildung 1: Direkte Form I (Biquad) IIR-Filterrealisierung und Übertragungsfunktion

Bei der Analyse von Abbildung 1 ist zu erkennen, dass die Biquad-Struktur eigentlich aus zwei Rückkopplungspfaden (skaliert mit \(a_1\) und \(a_2\)), drei Vorwärtspfaden (skaliert mit \(b_0, b_1\) und \(b_2\)) und einer Abschnittsverstärkung \(K\) besteht. Somit kann die Filterfunktion von Abbildung 1 durch die folgende einfache rekursive Gleichung zusammengefasst werden:

\(\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)\)

Bei der Analyse der Gleichung fällt auf, dass die Biquad-Implementierung nur vier Additionen (die nur einen Akkumulator benötigen) und fünf Multiplikationen erfordert, was auf jedem Cortex-M-Mikrocontroller leicht untergebracht werden kann. Die Abschnittsverstärkung K kann auch vor der Implementierung mit den Vorwärtswegkoeffizienten vormultipliziert werden.

Eine Sammlung von Biquad-Filtern wird als Biquad-Kaskade bezeichnet, wie unten dargestellt.

Eine Sammlung von Biquad-Filtern wird als Biquad-Kaskade bezeichnet

Der ASN Filter Designer kann eine Kaskade von bis zu 50 Biquads entwerfen und implementieren (nur Professional Edition).

Fließkomma-Implementierung

Bei der Implementierung eines Filters in Fließkomma (d. h. unter Verwendung von Arithmetik mit doppelter oder einfacher Genauigkeit) gelten Direct Form II-Strukturen als bessere Wahl als die Direct Form I-Struktur. Die Direct Form II Transposed-Struktur gilt als die numerisch genaueste für die Fließkomma-Implementierung, da die unerwünschten Effekte der numerischen Übersättigung minimiert werden, wie bei der Analyse der Differenzgleichungen zu sehen ist.

Direct Form II Transposed-Struktur, Übertragungsfunktion und Differenzengleichungen

Abbildung 2 – Direct Form II Transposed-Struktur, Übertragungsfunktion und Differenzengleichungen

Die Filter Zusammenfassung (siehe Abbildung 3) bietet dem Designer einen detaillierten Überblick über das entworfene Filter, einschließlich einer ausführlichen Zusammenfassung der technischen Spezifikationen und der Filterkoeffizienten, was einen schnellen und einfachen Weg zur Dokumentation Ihres Entwurfs darstellt.

Der ASN Filter Designer unterstützt den Entwurf und die Implementierung sowohl von Single Section als auch von Biquad (Standardeinstellung) IIR-Filtern. Da das CMSIS-DSP-Framework jedoch keine direkte Unterstützung für Single Section IIR-Filter bietet, wird diese Funktion in dieser Application Note nicht behandelt.

Die Implementierung des CMSIS-DSP-Software-Frameworks erfordert die Vorzeicheninversion (d. h. das Umkehren des Vorzeichens) der Rückkopplungskoeffizienten. Um dies zu ermöglichen, kehrt die automatische Code-Generierungs-Engine des Tools das Vorzeichen der Rückkopplungskoeffizienten bei Bedarf automatisch um. In diesem Fall wird der Satz von Differenzgleichungen zu,

ASN Filter Designer: Filterzusammenfassung

\(y(n)=b_0 x(n)+w_1 (n-1)\)
\(w_1 (n)= b_1 x(n)+a_1 y(n)+w_2 (n-1)\)
\(w_2 (n)= b_2 x(n)+a_2 y(n)\)

Abbildung 3: ASN Filter Designer: Filterzusammenfassung

Automatische Code-Generierung für Arm-Prozessorkerne über CMSIS-DSP

Die automatische Code-Generierungs-Engine des ASN Filter Designers erleichtert den Export eines entworfenen Filters auf Cortex-M Arm-basierte Prozessoren über das CMSIS-DSP Software-Framework. Die integrierten Analyse- und Hilfefunktionen des Tools unterstützen den Designer bei der erfolgreichen Konfiguration des Designs für den Einsatz.

Alle Entwürfe von Fließkomma-IIR-Filtern müssen auf Single-Precision-Arithmetik und entweder auf einer Direct Form I oder Direct Form II Transposed-Filterstruktur basieren. Wie im vorherigen Abschnitt beschrieben, wird die Direct Form II Transposed-Struktur aufgrund ihrer höheren numerischen Genauigkeit für die Fließkomma-Implementierung befürwortet.

Die Einstellungen für Quantisierung und Filterstruktur finden Sie unter der Registerkarte Q (wie links dargestellt). Durch Einstellen von Arithmetic auf Single Precision und Structure auf Direct Form II Transposed und Klicken auf die Schaltfläche Apply wird die hier betrachtete IIR für das Software-Framework CMSIS-DSP konfiguriert.

Wählen Sie das Arm CMSIS-DSP-Framework aus der Auswahlbox im Filterübersichtsfenster aus:

Der automatisch generierte C-Code auf Basis des CMSIS-DSP-Frameworks für die direkte Implementierung auf einem Arm-basierten Cortex-M-Prozessor ist unten dargestellt:

Der automatisch generierte C-Code auf Basis des CMSIS-DSP-Frameworks für die direkte Implementierung auf einem Arm-basierten Cortex-M-Prozessor

Wie man sieht, generiert der automatische Code-Generator den gesamten Initialisierungscode, die Skalierung und die Datenstrukturen, die für die Implementierung des IIR über die CMSIS-DSP-Bibliothek benötigt werden. Dieser Code kann direkt in jedem Cortex-M-basierten Entwicklungsprojekt verwendet werden – ein vollständiges Keil-MDK-Beispiel ist auf der Website von Arm/Keil verfügbar. Beachten Sie, dass der Code-Generator des Werkzeugs standardmäßig Code für den Cortex-M4-Kern erzeugt. Bitte entnehmen Sie der folgenden Tabelle die #define-Definition, die für alle unterstützten Kerne erforderlich ist.

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).

Die automatische Code-Generierung von IIR-Filtern mit komplexen Koeffizienten wird derzeit nicht unterstützt.

Implementieren des Filters im Arm Keil’s MDK

Wie im vorherigen Abschnitt erwähnt, kann der vom Arm CMSIS-DSP Code-Generator erzeugte Code direkt in jedem Cortex-M-basierten Entwicklungsprojekt-Tooling verwendet werden, wie z. B. Arm Keils Industriestandard μVision MDK (Mikrocontroller-Entwicklungskit).

Ein komplettes μVision-Beispiel-IIR-Biquad-Filterprojekt kann von Keils Website heruntergeladen werden und ist, wie unten zu sehen, so einfach wie das Kopieren und Einfügen des Codes und das Vornehmen kleiner Anpassungen am Code.

Das Beispielprojekt nutzt die leistungsstarken Simulationsmöglichkeiten von μVision und ermöglicht die Evaluierung des IIR-Filters auf M0-, M3-, M4- bzw. M7-Cores. Als zusätzlicher Bonus kann auch der Logik-Analysator von μVision verwendet werden, so dass Vergleiche zwischen dem Signal-Analysator des ASN Filter Designers und der Realität auf einem Cortex-M-Kern möglich sind.

Festkomma-Implementierung

Wie bereits erwähnt, ist die direkte Form I-Filterstruktur die beste Wahl für die Festkomma-Implementierung. Vor der Implementierung der Differenzgleichung auf einem Festkommaprozessor müssen jedoch einige wichtige Überlegungen zur Datenskalierung berücksichtigt werden. Da das CMSIS-DSP-Framework nur die Datentypen Q15 und Q31 für IIR-Filter unterstützt, bezieht sich die folgende Diskussion auf eine Implementierung auf einer 16-Bit-Wort-Architektur, d. h. auf Q15.

Quantisierung

Um die Koeffizienten und Ein-/Ausgangszahlen korrekt darzustellen, wird die Systemwortlänge (16 Bit für die Zwecke dieser Application Note) zunächst in ihre Anzahl an Ganzzahlen und Nachkommastellen aufgeteilt. Das allgemeine Format ist gegeben durch:

Q Num of Integers.Fraction length

Wenn wir annehmen, dass alle Datenwerte innerhalb eines Maximal-/Minimalbereichs von \(\pm 1\) liegen, können wir das Format Q0.15 verwenden, um alle Zahlen entsprechend darzustellen. Beachten Sie, dass das Q0.15-Format (oder einfach Q15) ein Maximum von \(\displaystyle 1-2^{-15}=0.9999=0x7FFF\) und ein Minimum von \(-1=0x8000\) (Zweierkomplement-Format) darstellt.

Der ASN Filter Designer kann für die Festkomma-Q15-Arithmetik konfiguriert werden, indem die Spezifikationen für die Wortlänge und die Fraktale Länge in der Registerkarte Q eingestellt werden (siehe Abschnitt Konfiguration für die Details). Ein offensichtliches Problem, das sich bei Biquads zeigt, ist jedoch der Zahlenbereich der Koeffizienten. Da Pole überall innerhalb des Einheitskreises platziert werden können, wird das resultierende Polynom, das für die Implementierung benötigt wird, oft im Bereich \(\pm 2\) liegen, was eine Q14-Arithmetik erfordern würde. Um dieses Problem zu umgehen, werden alle Zähler- und Nennerkoeffizienten über einen biquadischen Post-Scaling-Faktor skaliert, wie unten beschrieben.

Post-Scaling-Faktor

Um sicherzustellen, dass die Koeffizienten in die Spezifikationen für die Wortlänge und die fraktionale Länge passen, enthalten alle IIR-Filter einen Post-Scaling-Faktor, der die Zähler- und Nennerkoeffizienten entsprechend skaliert. Als Folge dieser Skalierung muss der Post-Scaling-Faktor in die Filterstruktur einbezogen werden, um einen korrekten Betrieb zu gewährleisten.

Das Konzept der Post-Scaling wird im Folgenden für eine Biquad-Implementierung der direkten Form I dargestellt.

Das Konzept der Post-Scaling für eine Biquad-Implementierung der direkten Form I

Abbildung 4: Direkte Form I-Struktur mit Post-Scaling

Durch Vormultiplikation der Zählerkoeffizienten mit der Querschnittsverstärkung \(K\) kann nun jeder Koeffizient mit \(G\) skaliert werden, d. h. \(\displaystyle b_0=\frac{b_0}{G}, b_1=\frac{b_1}{G}, a_1=\frac{a_1}{G}, a_2=\frac{a_2}{G}\) usw. Daraus ergibt sich nun die folgende Differenzengleichung:

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

Alle im Tool implementierten IIR-Strukturen beinhalten das Konzept des Post-Scaling-Faktors. Diese Skalierung ist für die Implementierung über das Arm CMSIS-DSP-Framework obligatorisch – weitere Details finden Sie im Abschnitt “Konfiguration”.

Verstehen der Filterzusammenfassung

Um die in der ASN Filter Designer Filterzusammenfassung dargestellten Informationen vollständig zu verstehen, zeigt das folgende Beispiel die Filterkoeffizienten, die mit Double Precision Arithmetik und mit Fixed Point Q15 Quantisierung erhalten wurden.

Anwendung der Festkomma-Q15-Arithmetik (beachten Sie die Auswirkungen der Quantisierung auf die Koeffizientenwerte):

Konfigurieren des ASN Filter Designers für Festkomma-Arithmetik

Um ein IIR-Fixed-Point-Filter über das CMSIS-DSP-Framework zu implementieren, müssen alle Designs auf der Fixed-Point-Arithmetik (entweder Q15 oder Q31) und der Direct-Form-I-Filterstruktur basieren.

Die Einstellungen für Quantisierung und Filterstruktur finden Sie unter der Registerkarte Q (wie links dargestellt): Wenn Sie Arithmetic auf Fixed Point und Structure auf Direct Form I einstellen und auf die Schaltfläche Apply klicken, wird die hier betrachtete IIR für das CMSIS-DSP-Software-Framework konfiguriert.

Der Post-Scaling-Faktor ist im CMSIS-DSP-Software-Framework tatsächlich als \( \log_2 G\) implementiert (d. h. eine nach links verschobene Skalierungsoperation, wie in Abbildung 4 dargestellt).

Eingebaute Analytik: Das Tool analysiert automatisch die Filterkoeffizienten der Kaskade und wählt einen geeigneten Skalierungsfaktor. Wie oben zu sehen, ist der größte Minimalwert -1,63143, daher ist ein Post-Scaling-Faktor von 2 erforderlich, um alle Koeffizienten in die Q15-Arithmetik “einzupassen”.

Vergleich von Spektren, die durch unterschiedliche Rechenregeln erhalten wurden

Um die Übersichtlichkeit und die allgemeine Berechnungsgeschwindigkeit zu verbessern, zeigt der ASN Filter Designer nur Spektren (d.h. Magnitude, Phase usw.) an, die auf den aktuellen arithmetischen Regeln basieren. Dies ist etwas anders als bei anderen Werkzeugen, die Multispektren anzeigen, die durch (z. B.) Festkomma– und Doppelpräzisionsarithmetik erhalten wurden. Für alle Benutzer, die Spektren vergleichen möchten, können Sie einfach zwischen den arithmetischen Einstellungen wechseln, indem Sie die Arithmetic methode ändern. Der Designer berechnet dann automatisch die Filterkoeffizienten unter Verwendung der gewählten Rechenregeln und der aktuellen technischen Spezifikation neu. Das Diagramm wird dann unter Verwendung der aktuellen Zoom-Einstellungen aktualisiert.

Automatische Code-Generierung für das Arm CMSIS-DSP-Framework

Wie bei der Fließkomma-Arithmetik wählen Sie das Arm CMSIS-DSP-Framework aus der Auswahlbox im Filter-Übersichtsfenster aus:

Der automatisch generierte C-Code auf Basis des CMSIS-DSP-Frameworks für die direkte Implementierung auf einem Arm-basierten Cortex-M-Prozessor ist unten dargestellt:

Wie beim Fließkommafilter generiert der automatische Code-Generator den gesamten Initialisierungscode, die Skalierung und die Datenstrukturen, die zur Implementierung des IIR über die CMSIS-DSP-Bibliothek benötigt werden. Dieser Code kann direkt in jedem Cortex-M-basierten Entwicklungsprojekt verwendet werden – ein vollständiges Keil-MDK-Beispiel ist auf der Website von Arm/Keil verfügbar. Beachten Sie, dass der Code-Generator des Werkzeugs standardmäßig Code für den Cortex-M4-Kern erzeugt. Bitte entnehmen Sie der folgenden Tabelle die #define -Definition, die für alle unterstützten Kerne erforderlich ist.

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).

Der Hauptcode der Testschleife (nicht gezeigt) dreht sich um die Funktion arm_biquad_cascade_df2T_f32(), die die Filterung eines Blocks von Eingangsdaten durchführt.

IIR-Filter mit komplexen Koeffizienten werden derzeit nicht unterstützt.

Validierung des Entwurfs mit dem Signal Analyser

Ein Entwurf kann mit dem Signal Analyser validiert werden, wobei sowohl Zeit- als auch Frequenzbereichsdiagramme unterstützt werden. Ein umfassender Signalgenerator ist vollständig in den Signalanalysator integriert, so dass die Entwickler ihre Filter mit einer Vielzahl von Eingangssignalen testen können, wie z. B. Sinuswellen, weißes Rauschen oder sogar externe Testdaten.

Für Festkomma-Implementierungen erlaubt das Tool den Entwicklern, die Overflow-Arithmetikregeln als: Saturate oder Wrap. Außerdem kann die Accumulator Word Length zwischen 16 und 40 Bit eingestellt werden, so dass die Entwickler schnell die optimalen Einstellungen für ihre Anwendung finden können.

 

Zusätzliche Ressourcen

  1. Digital signal processing: principles, algorithms and applications, J.Proakis and D.Manoloakis
  2. Digital signal processing: a practical approach, E.Ifeachor and B.Jervis.
  3. Digital filters and signal processing, L.Jackson.
  4. Step by step video tutorial of designing an IIR and deploying it to Keil MDK uVision.
  5. Implementing Biquad IIR filters with the ASN Filter Designer and the Arm CMSIS-DSP software framework (ASN-AN025)
  6. Keil MDK uVision example IIR filter project

Un filtre numérique est un algorithme mathématique qui opère sur un ensemble de données numériques (par exemple, des données de capteur) afin d’extraire les informations intéressantes et de supprimer toute information indésirable. Parmi les applications de ce type de technologie, citons la suppression des anomalies dans les données de capteurs ou même le nettoyage du bruit sur un signal mesuré pour faciliter l’analyse des données. Mais comment choisir le meilleur type de filtre numérique pour notre application ? Et quelles sont les différences entre un filtre RII et un filtre RIF?

Les filtres numériques sont divisés en deux catégories :

  • Réponse impulsionnelle infinie (RII)
  • Réponse impulsionnelle finie (RIF)

Comme leur nom l’indique, chaque type de filtre est classé en fonction de la longueur de sa réponse impulsionnelle. Toutefois, avant de commencer une analyse mathématique détaillée, il est prudent d’apprécier les différences de performances et de caractéristiques de chaque type de filtre.

Exemple

Afin d’illustrer les différences entre un RII et un RIF, la réponse en fréquence d’un RIF d’ordre 14 (ligne pleine) et d’un RII de type I de Chebyshev d’ordre 4 (ligne pointillée) est présentée ci-dessous à la figure 1. Remarquez que bien que les spectres d’amplitude aient un degré d’atténuation similaire, le spectre de phase du filtre RII est non linéaire dans la bande passante (\(\small 0\rightarrow7.5Hz\)), et devient très non linéaire à la fréquence de coupure, \(\small f_c=7.5Hz\). Notez également que le filtre RIF nécessite un plus grand nombre de coefficients (15 contre 10 pour le RII) pour correspondre aux caractéristiques d’atténuation du RII.

RIF vs RII : réponse en fréquence d'un FIR d'ordre 14 (ligne pleine), et d'un IIR de type I de Chebyshev d'ordre 4 (ligne pointillée) ; Filtre RIF, Filtre RII
Figure 1: Figure 1 : RIF vs RII : réponse en fréquence d’un RIF de 14ème ordre (ligne pleine), et d’un RII de type I de Tchebychev de 4ème ordre (ligne pointillée)

Ce ne sont là que quelques-unes des différences entre les deux types de filtres. Un résumé détaillé des principaux avantages et inconvénients de chaque type de filtre va maintenant suivre.

Filtres RII

Les filtres RII (Réponse impulsionnelle infinie) sont généralement choisis pour les applications où la phase linéaire n’est pas trop importante et où la mémoire est limitée. Ils ont été largement déployés dans l’égalisation audio, le traitement du signal des capteurs biomédicaux, les capteurs intelligents IoT/IIoT et les applications de télécommunication/RF à haut débit.

Avantages

  • Faible coût de mise en œuvre: nécessite moins de coefficients et de mémoire que les filtres RIF pour satisfaire un ensemble similaire de spécifications, à savoir la fréquence de coupure et l’atténuation de la bande d’arrêt
  • Faible latence: : sconvient aux applications de contrôle en temps réel et aux applications RF à très haut débit en raison du faible nombre de coefficients
  • Équivalent analogique: peut être utilisé pour imiter les caractéristiques des filtres analogiques en utilisant des transformations de mappage dans le plan s-z

Inconvénients

  • Caractéristiques de phase non linéaires: Les caractéristiques de phase d’un filtre RII sont généralement non linéaires, en particulier à proximité des fréquences de coupure. Des filtres d’égalisation passe-tout peuvent être utilisés afin d’améliorer les caractéristiques de phase de la bande passante
  • Analyse plus détaillée : Nécessite plus d’analyse de mise à l’échelle et de débordement numérique lorsqu’il est implémenté en virgule fixe. La structure du filtre de forme directe II est particulièrement sensible aux effets de la quantification, et nécessite une attention particulière lors de la phase de conception
  • Stabilité numérique: : Moins stable numériquement que leurs homologues RIF (réponse impulsionnelle finie), en raison des chemins de rétroaction

Filtres RIF

Les filtres RIF (réponse impulsionnelle finie) sont généralement choisis pour les applications où la phase linéaire est importante et où une quantité décente de mémoire et de performance de calcul est disponible. Ils sont largement utilisés dans les applications d’amélioration des signaux audio et biomédicaux. Leur structure entièrement nulle (discutée ci-dessous) garantit qu’ils ne deviennent jamais instables pour n’importe quel type de signal d’entrée, ce qui leur donne un net avantage sur les filtres RII.

Avantages

  • Phase linéaire: Les RIF peuvent être facilement conçus pour avoir une phase linéaire. Cela signifie qu’aucune distorsion de phase n’est introduite dans le signal à filtrer, car toutes les fréquences sont décalées dans le temps de la même quantité – ce qui maintient leurs relations harmoniques relatives (c’est-à-dire un retard de groupe et de phase constant). Ce n’est certainement pas le cas avec les filtres RII, qui ont une caractéristique de phase non linéaire
  • Stabilité: Comme les filtresRIF n’utilisent pas les valeurs de sortie précédentes pour calculer leur sortie actuelle, c’est-à-dire qu’ils n’ont pas de rétroaction, ils ne peuvent jamais devenir instables pour tout type de signal d’entrée, ce qui leur donne un avantage distinct sur les filtres RII
  • Réponse en fréquence arbitraire: : La fonction firarb() fde Parks-McClellan et ASN FilterScript permet la conception d’un RIF avec une réponse en amplitude arbitraire. Cela signifie qu’un RIF peut être personnalisé plus facilement qu’un RII
  • Performance à point fixe: les effets de la quantification sont moins sévères que ceux d’un RII

Inconvénients

  • Exigences élevées en termes de calcul et de mémoire: Les RIF nécessitent généralement beaucoup plus de coefficients pour obtenir une coupure nette que leurs homologues RII. Il en résulte qu’ils nécessitent beaucoup plus de mémoire et un nombre beaucoup plus élevé d’opérations MAC (multiple and accumulate). Toutefois, les architectures de microcontrôleurs modernes basées sur les cœurs Cortex-M d’Arm incluent désormais un support matériel DSP via SIMD (instruction de signal, données multiples) qui accélère considérablement l’opération de filtrage.
  • Latence plus élevée: le nombre plus élevé de coefficients signifie qu’en général, un RIF est moins adapté qu’un RII pour les applications rapides à haut débit. Cela devient problématique pour les applications de contrôle en boucle fermée en temps réel, où un filtre RIF peut avoir un retard de groupe trop important pour atteindre la stabilité de la boucle
  • Pas d’équivalent analogique: : à l’aide de la transformation Bilinéaire, appariée en z (s-z mapping), un filtre analogique peut être facilement transformé en un filtre RII équivalent. Cependant, cela n’est pas possible pour un RIF car il n’a pas d’équivalent analogique

Définitions mathématiques

Comme nous l’avons vu dans l’introduction, les noms RII et RIF proviennent des définitions mathématiques de chaque type de filtre, c’est-à-dire qu’un filtre RII est catégorisé par sa réponse impulsionnelle théoriquement infinie,

 

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

 

et un RIF catégorisé par sa réponse impulsionnelle finie,


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

Nous allons maintenant analyser successivement les propriétés mathématiques de chaque type de filtre.

Définition du filtre RII

Comme nous l’avons vu plus haut, un filtre RII est catégorisé par sa réponse impulsionnelle théoriquement infinie,

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

En pratique, il n’est pas possible de calculer la sortie d’un RII à l’aide de cette équation. Par conséquent, l’équation peut être réécrite en termes d’un nombre fini de pôles \(\small p\) et de zéros \(\small q\), comme défini par l’équation de différence linéaire à coefficient constant donnée par:

 

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

 

où, \(\small a_k\) et \(\small b_k\) sont les coefficients polynomiaux du dénominateur et du numérateur du filtre, dont les racines sont égales aux pôles et aux zéros du filtre, respectivement. Ainsi, une relation entre l’équation différentielle et la transformée en z (fonction de transfert) peut donc être définie en utilisant la propriété de retard de la transformée en z telle que,

 

\(\displaystyle
\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}}
\)

 

Comme on le voit, la fonction de transfert est une représentation du filtre dans le domaine fréquentiel. Remarquez également que les pôles agissent sur les données de sortie, et les zéros sur les données d’entrée. Since the poles act on the output data, and affect stability,Puisque les pôles agissent sur les données de sortie et affectent la stabilité, il est essentiel que leurs rayons restent à l’intérieur du cercle unitaire (i.e. <1) pour la stabilité BIBO (bounded input, bounded output). Les rayons des zéros sont moins critiques, car ils n’affectent pas la stabilité du filtre. C’est la principale raison pour laquelle les filtres RIF (réponse impulsionnelle finie) tout-zéro sont toujours stables.

Stabilité BIBO

Un système linéaire invariant dans le temps (LTI) (tel qu’un filtre numérique) est dit stable à entrée bornée et sortie bornée, ou stable BIBO, si chaque entrée bornée donne lieu à une sortie bornée, comme suit

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

Où, \(\small h(k)\) est la réponse impulsionnelle du système LTI. En analysant cette équation, il devrait être clair que le critère de stabilité BIBO ne sera satisfait que si les pôles du système se trouvent à l’intérieur du cercle unitaire, puisque la ROC (région de convergence) du système doit inclure le cercle unitaire. Par conséquent, il suffit de dire qu’un signal d’entrée borné produira toujours un signal de sortie borné si tous les pôles se trouvent à l’intérieur du cercle unitaire.

Les zéros, par contre, ne sont pas contraints par cette exigence et, par conséquent, peuvent se trouver n’importe où sur le plan z, puisqu’ils n’affectent pas directement la stabilité du système. Par conséquent, une analyse de la stabilité du système peut être entreprise en calculant d’abord les racines de la fonction de transfert (c’est-à-dire les racines des polynômes du numérateur et du dénominateur), puis en traçant les pôles et les zéros correspondants sur le plan zéro.

Une situation intéressante se présente si l’un des pôles se trouve sur le cercle unitaire, car le système est dit marginalement stable, puisqu’il n’est ni stable ni instable. Bien que les systèmes marginalement stables ne soient pas stables BIBO, ils ont été exploités par les concepteurs d’oscillateurs numériques, car leur réponse impulsionnelle fournit une méthode simple pour générer des ondes sinusoïdales, qui se sont avérées précieuses dans le domaine des télécommunications.

Filtres RII biquad

La mise en œuvre du filtre RII dont il est question ici est dite biquad, car elle comporte deux pôles et deux zéros, comme l’illustre la figure 2 ci-dessous. L’implémentation biquad est particulièrement utile pour les implémentations en virgule fixe, car les effets de la quantification et de la stabilité numérique sont minimisés. Cependant, le succès global de toute implémentation biquad dépend de la précision numérique disponible, qui doit être suffisante pour garantir que les pôles quantifiés sont toujours à l’intérieur du cercle unitaire.

Réalisation et fonction de transfert d'un filtre RII de forme directe I (biquad) ; Forme directe ; Filtre biquad

Figure 2 : Réalisation et fonction de transfert d’un filtre RII de forme directe I (biquad)

En analysant la figure 2, on constate que la structure biquad est en fait composée de deux chemins de rétroaction (mis à l’échelle par (scaled by \(\small a_1\) et \(\small a_2\)), tde trois chemins de rétroaction (mis à l’échelle par \(\small b_0, b_1\) et \(\small b_2\)) et d’un gain de section, \(\small K\).Ainsi, l’opération de filtrage de la figure 1 peut être résumée par l’équation récursive simple suivante :

\(\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)\)


En analysant l’équation, on remarque que l’implémentation biquad ne nécessite que quatre additions (qui ne requièrent qu’un seul accumulateur) et cinq multiplications, ce qui peut être facilement accommodé sur n’importe quel microcontrôleur Cortex-M. Le gain de section, \(\small K\) , peut également être prémultiplié avec les coefficients de la voie directe avant l’implémentation.

Une collection de filtres Biquad est appelée une cascade Biquad, comme illustré ci-dessous.

Cascade Biquad ; Filtre Biquad

Le ASN Filter Designer peut concevoir et implémenter une cascade de jusqu’à 50 biquads (édition professionnelle seulement).

Implémentation en virgule flottante


Lors de l’implémentation d’un filtre en virgule flottante (c’est-à-dire en utilisant l’arithmétique de double ou simple précision) les structures Direct Form II sont considérées comme un meilleur choix que la structure Direct Form I. La structure de forme directe II transposée est considérée comme la plus précise numériquement pour une implémentation en virgule flottante, car les effets indésirables de l’amortissement numérique sont minimisés, comme on peut le voir en analysant les équations de différence.

Structure de la forme directe II transposée, fonction de transfert et équations de différence ; filtres RII ; filtres Biquad.

Figure 3 – Structure transposée de forme directe II, fonction de transfert et équations de différence

Le résumé du filtre (montré dans la Figure 4) fournit au concepteur une vue d’ensemble détaillée du filtre conçu, y compris un résumé détaillé des spécifications techniques et des coefficients du filtre, qui présente une voie rapide et simple pour documenter votre conception.

Le ASN Filter Designer supporte la conception et l’implémentation des filtres RII à section unique et Biquad (réglage par défaut).

Filtre Biquad ASN Filter Designer DSP

 

Figure 4 : spécification détaillée.

 

Définition RIF

En retournant l’équation de différence de coefficient constant linéaire du RII, c’est-à-dire

 

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

 

Remarquez que lorsque nous mettons les coefficients \(\small a_k\) (c’est-à-dire la rétroaction) à zéro, la définition se réduit à notre définition originale du filtre RIF, ce qui signifie que le calcul RIF est juste basé sur les valeurs d’entrée passées et présentes, à savoir:

 

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

 

Implémentation

Bien qu’il existe plusieurs implémentations pratiques pour les RIF, la structure de forme directe et son cousin transposé sont peut-être les plus couramment utilisés, et en tant que tels, tous les coefficients de filtre conçus sont destinés à être implémentés dans une structure de forme directe.

La structure de forme directe et l’équation de différence associée sont présentées ci-dessous. La forme directe est préconisée pour la mise en œuvre en virgule fixe en vertu du concept d’accumulateur unique.

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

Forme directe ; Structure de forme directe

La structure recommandée (par défaut) dans l’ASN Filter Designer est la structure Direct Form Transposed, car elle offre une précision numérique supérieure lors de l’utilisation de l’arithmétique à virgule flottante. Ceci peut être facilement vu en analysant les équations de différence ci-dessous (utilisées pour l’implémentation), car les effets indésirables de l’amortissement numérique sont minimisés, puisque l’addition en virgule flottante est effectuée sur des nombres de magnitude similaire.

\(\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}\)

Forme directe Transposée

Qu’avons-nous appris ?

Les filtres numériques se répartissent dans les deux catégories suivantes :

  • Réponse impulsionnelle infinie (RII)
  • Réponse impulsionnelle finie (RIF)

Les filtres RII (Réponse impulsionnelle infinie) sont généralement choisis pour des applications où la phase linéaire n’est pas trop importante et où la mémoire est limitée. Ils ont été largement déployés dans l’égalisation audio, le traitement du signal des capteurs biomédicaux, les capteurs intelligents IoT/IIoT et les applications de télécommunication/RF à haut débit.

Les filtres RIF (réponse impulsionnelle finie) sont généralement choisis pour les applications où la phase linéaire est importante et où une quantité décente de mémoire et de performances de calcul sont disponibles. Ils ont été largement déployés dans les applications d’amélioration des signaux audio et biomédicaux.

ASN Filter Designer fournit aux ingénieurs tout ce dont ils ont besoin pour concevoir, expérimenter et déployer des filtres numériques complexes RII et RIF pour une variété d’applications de mesure de capteurs. Ces avantages couplés avec la documentation automatique et la fonctionnalité de génération de code permettent aux ingénieurs de concevoir et valider un filtre numérique RII/RIF en quelques minutes plutôt qu’en quelques heures.

Download demo now

Licencing information


Many Audio/acoustics engineers, researchers and audio hobbyists work with DSP (Digital Signal Processing). In this article, you’ll find out how the ASN Filter Designer helps both experienced audio engineers and engineers where DSP is not their daily job to create digital filters for audio and speech.

For whom?

If you are an audio/acoustics engineer, researcher or even a hobbyist with a little bit of DSP knowledge: ASN Filter Designer is for you! The tool offers the following benefits:

  • Intuitive and easy to use.
  • Logarithmic frequency axis.
  • 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:


Sampling frequency

The sampling frequency may be specified up to 4 decimal places

This 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

Long FIR filters may be constructed, where this is limited to 200 for streaming audio applications.

Logarithmic frequency axis

Perform detailed analysis across the complete audio spectrum 20Hz-20kHz.   

Audio and user data playback streaming

Signal Generator Controller: 
Choose what you want to listen to; Adjust the amplitude of the input signal
Signal Generator Controller:
Choose what you want to listen to; Adjust the amplitude of the input signal

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, 44.1 and 48kHz. sampling rates. There is no restriction as to the length of the .wav file.

You may add extra signals to input audio stream

Use the signal generator to add sinewaves and white noise to the data stream.

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

speech and audio engineer researcher working on DSP digital filters microphone headphone

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

Read review here:

Top marks from Jacob Beningo

Joseph Yiu ARM Cortex ASN Filter Designer DSP portrait

New book on Arm’s latest processors:  The Definitive Guide to Arm Cortex-M23 and Cortex-M33 Processors. The book is written by Joseph Yiu, Arm’s resident architecture guru. It features benchmarks and experiments with our DSP filter design tooling (ASN Filter Designer) using CMSIS-DSP for Arm’s latest processors

We’re proud that Dr. Sanjeev Sarpal, Director of AI at Advanced Solutions Nederland has provided support in the digital filter design topic. We’re also very pleased to announce that Joseph Yiu’s new book features a chapter on the ASN Filter Designer for AI/IoT applications using the M23 and M33 Cortex-M cores. Advanced Solutions Nederland works closely with Arm’s DSP/architecture team for AI/DSP solutions using their cores. We’re currently working with Arm on releasing whitepapers on the Cortex-M55.

Armv8-M architecture and its features

The Definitive Guide to Arm® Cortex®-M23 and Cortex-M33 Processors focuses on the Armv8-M architecture and the features that are available in the Cortex-M23 and Cortex- M33 processors.

This book covers a range of topics, including:

  • the instruction set
  • the programmer’s model
  • interrupt handling
  • OS support
  • debug features

It demonstrates how to create software for the Cortex-M23 and Cortex-M33 processors by way of a range of examples. This enables embedded software developers to understand the Armv8-M architecture.

Worked out examples with ASN Filter Designer

Joseph Yiu’s new book features a chapter on the ASN Filter Designer for AI/IoT applications using the M23 and M33 Cortex-M cores. Our Director of AI, Dr. Sanjeev Sarpal, has provided support.

“The ASN Filter Designer Professional software supports a wide range of filter types. Its design allows filters to be designed via an interactive user interface, where various parameters can be adjusted and the design’s output can immediately be viewed. It also supports the simulation of the filter’s response so that the simulation outputs can be examined to determine whether the filter meets the requirements of the application. An added bonus, for developers creating software for Cortex-M processors, is that it generates C code that directly call CMSIS-DSP library functions (the designed filters can also be exported to C/C++, Python, Matlab, etc.).”

Joseph Yiu ASN Filter Designer Defining the frequency response of the filter
Defining the frequency response of the filter

“A number of commercial filter-design software tools are designed specifically for filter-design tasks and make it easier tot analyze a filters’ characteristics. For software developers who are not familiar with filter designs, these tools can be a great help” (p. 820). Thereby, Joseph Yiu uses the ASN Filter Designer for worked out examples. He creates a low pass biquad filter for a system with 48kHz sampling rate and with single-precision floating-point data type.

Definitive Guide Arm Cortex Joseph Yiu ASN Filter Designer

Order your copy here

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

What are Finite Impulse Respsonse (FIR) Filters? And how to design FIR Filters in ASN Filter Designer and which filters does ASN Filter Designer support?