IIR Filters - Theory and Implementation (STM32)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

This is great! Thanks for sharing

👍︎︎ 3 👤︎︎ u/jimjongiLL 📅︎︎ Sep 08 2021 🗫︎ replies

Your YT channel is pure gold! For which - thank you!

👍︎︎ 3 👤︎︎ u/Glupender 📅︎︎ Sep 09 2021 🗫︎ replies

Phil's lab is truly great, thanks a lot

👍︎︎ 3 👤︎︎ u/sukritaz 📅︎︎ Sep 10 2021 🗫︎ replies

For anyone interested, arm has libraries to implement IIR filters on a buffer using Q15/Q32 number system.

Those libraries are useful when using DMA buffers, but just make sure to use double buffering when sampling times are shorter than processing times.

https://arm-software.github.io/CMSIS_5/DSP/html/group__IIR__Lattice.html

👍︎︎ 2 👤︎︎ u/Suspicious-RNG 📅︎︎ Sep 10 2021 🗫︎ replies

SFAIK, Tony Fisher's "mkfilter" is still out there. It's no longer online but the command line tools are.

👍︎︎ 1 👤︎︎ u/ArkyBeagle 📅︎︎ Sep 10 2021 🗫︎ replies
Captions
in this video we'll be looking at irr filters their theory and also implementation on an stm32 based microcontroller such as the one you're seeing right here this is the little brain board connected up to an 8xl 355 accelerometer we're reading the data and then using one of our irr filters to then filter the data so let's get started a big thank you to jlc pcb who are sponsoring this video and have also produced and manufactured the little brain board you saw and which we'll be running our irr filters on it turns out that jlc pcb actually has these purple pcbs available now and i'll be giving that a try for some future projects if you'd like to find the little brain board design files as well as the source code i'm using these videos you can go to my github repository at github.com pms67 navigate to the little brain stm32f4 sensor board directory and you can find all the firmware the rtos firmware all the libraries schematics and keycad design files and so forth another big thank you also to altium for sponsoring this video i use outing for my work and for more complicated projects for pcb designs hardware designs and so forth altium is actually offering a free trial of outing designer and if you can go to outing.com yt phil's lab you can get a free trial for yourself to see what altium designer is all about in this video we'll be covering the theory and implementation of iir filters i won't be covering all of ir theory as there's very much to it but i'll show some recommended reading in the description and in this video as well we will look at a rough overview of digital filters and why they are needed then we'll compare fir versus ir filters look at ir theory ir design how we can come up with our own ir filters and then finally we'll look at an implementation of those filters on an stm32 based embedded system in real time digital filters are a huge part of digital signal processing primarily they are used when we need to separate signals do signal restoration for example smoothing removing unwanted frequencies and so on in essence it's a single input single output system in most cases so on the input side on the left here we have this incoming signal corrupted with for example high frequency noise you can see these wheels over here now if we pass us through a digital filter which we've designed correctly we might get something like this on the output so the underlying trend of the signal is still there but we've removed the majority of this high frequency noise which is a good thing in this case now since we're on the digital domain we are working with a fixed sampling time which i'll call capital t which is related to the sampling frequency as one over f of s now according to nyquist that means our maximum frequencies are limited such as the maximum frequency must be less than the sampling rate over two a second observation is that we now are working with arrays of discrete evenly spaced numbers and these are evenly spaced in time and we typically call these samples i will denote my input arrays or my input samples with x and then in square brackets n where n is the sample number and output will typically be noted by y again with the square brackets n denoting my sample number as you can see here here's a plot of sample number versus sample we have discrete evenly spaced numbers both in the x dimension and the y dimension an important point with filters in general is how we can actually characterize them now for a digital filter we might look at time domain properties for example the impulse response now the impulse response is something if you pass an array for example one followed by all zeros into a digital filter what is the output of that filter and we term that impulse response and that's this could be something that looks like this but that can completely characterize a linear discrete and time invariant filter another way of looking at a filter is characterizing it by its frequency domain properties for example the gain and phase plots so if i pass in a sinusoidal signal of amplitude a into a filter my output the filter if it's linear discrete time and time invariant will be of the same frequency but my amplitude will be changed for example with b and i might introduce a phase shift which i typically note by phi now if i plot this response of putting in various different sinusoidal signals and measuring their output change i can do what's called a body plot so a frequency doing plot which is the gain versus the frequency as well as the phase versus the frequency so these are two ways we can characterize our filters and determine if they're suitable for our applications now before continuing with this video i'd highly recommend you watch the fyr filter design and software implementation video that you can find on my channel and that'll teach you a bit more about fir filters and see how they might be different to ir filters here i'll just give you a brief overview before we dive into ir filters what the main differences are just looking at the name themselves fir stands for finite impulse response and iar stands for infinite impulse response so you can see on the right here the top is for example a finite infrared response filter so if i hit for example this system this filter then the output will decay to zero at some point in time the impulse response is finite however if i for example hit this ir filter the impulse response it'll decay over time but it will never quite reach a steady state value because it consists of decaying exponentials in terms of performance and speed fir has a greater performance that means it can separate frequencies better it might have steeper roll-offs and so forth so it is essentially more powerful however it is a lot more power hungry than an iar filter an iir filter is much faster to implement and run for example on an embedded real-time system another point to note is for higher order iir filters these can become unstable whereas an fir filter is always stable now the ease of design is another thing typically fir filters are quite straightforward to design but when you need to change their properties that becomes a bit harder and you have to redesign the filter whereas irr filters a lot of the times will have certain parameters you can vary to quickly change the filter characteristics now let's look at some ir filter theory i said before ir stands for infinite infos response essentially the impulse response is composed of decaying exponentials ir filters are sometimes also called recursive filters because they actually use feedback to bypass a longer convolution and we'll see how they do that in a second so if you remember back or see the fir filter video for fir filters we have to perform a pretty heavy convolution to get our filter output iir uses some of the output feed it back to compute the new sample so in that way it can be much quicker or simpler to implement here's the general form of an irr filter and don't worry this looks like a lot but it's actually quite simple our output is y of n so y our output at sample n and that composed of multiplying constants by our input samples so a naught times x of the current sample plus a1 times x of the previous sample and so on and we can have an arbitrary length of coefficients here and then we also add to our current output multiples of our previous outputs multiplied by these coefficients so b1 b2 all the way to b sub big b so you can see here it's b1 times the previous output plus b2 times the output before the previous output and so on we can write this as a sum of course to make this a bit neater so essentially we're summing and multiplying the inputs and we're summing and multiplying previous outputs now a and b are called the filter coefficients and we can twiddle or vary those to change the filter responses and characteristics now with the sum from the previous slide it was kind of hard to see what's actually going on so often it's quite useful to look at a block diagram view right here and this is the general form of an irr filter and there's many different forms you'll see on the internet or in books but here we have our input on the left we have these blocks these triangles are gain terms and they're essentially just multiplications and then we have a sum over here these z to the minus one or z to the minus two z to the minus a terms are essentially sample delays so that z to the minus one means one delay z to minus two means two sample delays and so forth so here we're multiplying delaying and then adding all these terms together now we're feeding the sum into the next summing station which is essentially our feedback section of our irr filter so we take our output multiplied by some constant delay it and add it back to these samples over here which we multiplied and delayed and we can do that for an arbitrary amount of feedback and different coefficients so this is a quite nice overview of what the irr filter structure in general looks like and shows quite nicely these feed forward and these feedback terms now the question of course is how we can actually choose these filter coefficients so for example a0 a1 b0 b1 how many coefficients do we actually need to give us for example a desired time domain or frequency domain response or characteristics so we might want a bandpass filter or low pass filter high pass filter and so on how do we choose these coefficients now there are actually quite a few different methods to do that there are online tools or matlab which i'll show you in just a second which will compute these coefficients for you to get required filter characteristics there are also standard filter types for example butterworth chebyshev vessel and so forth another way of getting your iir coefficients is via an optimization algorithm so you might have a sort of cost function because you want some desired frequency response and you will essentially twiddle with these coefficients until you get that desired frequency response and of course we can run an optimization algorithm to do that a more straightforward way something you can also do by hand a lot of times is using analog prototypes writing a differential equation and then discretizing that differential equation to give you a difference equation and that will actually turn into an ir filter and i actually have a full video of how to discretize and implement emulations of analog filters and it's called real-time software implementation of analog filters and you can find it on my channel on the link in the description below we'll also go through a simple analog prototype from an rc low-pass filter in this video just to show you another method is also to use the z-transform to analyze what these coefficients actually do through the frequency response and i'll go through that in this video as well now as you can see there's many different methods and it's actually not quite as straightforward as fir filter design a quick google search if you type in online ir filter designer you can get quite a few different links that'll actually help you design irr filters one of my favorite ones is this micromodel.com dsp unfortunately for the basic addition it's limited to a i think fourth order filter but you can choose low pass high pass you can choose different types of filter you can see the response and then also the coefficients of the filter so i recommend you check that out and have a play around with it matlab and their signal processing toolbox also have an irr filter designer i believe there's an app for that as well in matlab and that's really useful if you want to design irr filters quickly now i'd like to go through the z transform method as well as the analog prototype method but let's start with the z transform method and just a warning there's some maths ahead again i have a video on how to use the z transform which is a bit more detailed and i'll leave a link to that in the description box below but let's look at a very simple first order irr filter and i've written the equation for that here so the output y of n is one minus alpha where alpha is some sort of constant that goes between zero and one so this constant times x of n which is my current input sample plus alpha times y of n minus 1. so i'm feeding back my previous output sample multiplying it by alpha and adding it to this term so very simple difference equation and this is a first order irr filter now in comparison to the general form you can see that one minus alpha is actually my a0 constant or coefficient and alpha is actually my b1 coefficient so simply by varying alpha i can change these filter parameters and properties and then see what there's actually changes in the frequency domain but let's go through the maths first so starting up here we have our difference equation to get the frequency response we need to take the z transform and again please see my video on the channel on how to actually do that in detail i'll just run through it quickly here so i take my z transform rearrange it to give my transfer function which is the ratio of output to input and that turns out to be one minus alpha over one minus alpha times z to the minus one now remembering our theory z to the minus one is actually equal to e to the minus j theta and using euler's identity i can convert that to cos theta minus j sine theta now g in terms of theta and i'll talk in a second what theta actually is is then equal to one minus alpha divided by one minus alpha times cos theta plus j times alpha times sine theta so we get a complex representation over here so we can take the magnitude to get the filter gain versus frequency so this is really useful so taking the magnitude i've worked out the maths for you we can plot this it's not the nicest equation but we can plot this in just a second now we can note that theta is actually the normalized angular frequency so theta by definition is omega times t which is our sampling period and omega is 2 pi f where f is our frequency of interest and that means it's 2 pi f over f s which is our sampling frequency we can plot this equation over here which we've got by the z transform starting from our initial irr filter description and see how varying alpha changes the response of this filter so here i've plotted that exact equation so g of f in terms of alpha and my assembly frequency f of s and i've set my f of s at 10 hertz and i can actually change that here as you can see because of the nyquist limit i'm only running from 0 hertz on my x-axis to 5 hertz which is fs over 2 on my x-axis on my y-axis i have my magnitude that goes all the way from 1 so if i put a dc signal in i will get the same amplitude dc signal out and as my frequency increases my gain of this filter drops so this is a low pass filter the low frequency content is relatively unaffected whereas high frequency content is attenuated i can also play with my alpha coefficient to actually see how that changes the frequency response so i've done alpha all the way up almost to one you can see that actually increases the effect of my low pass filtering and if i decrease alpha that actually decreases the effect of my low pass filtering so essentially alpha as it's ranging from zero to one determines how much i'm filtering this signal and it's quite nice to play around and plot this just to get a feel for how these irr filters work and how the parameters can change now in contrast to fir filters all i have to do is change my alpha term here to actually change my filter i don't have to completely redesign my filter so that's pretty cool and the benefit of irr filters a second method of designing irr filters i'd like to show you is that of the analog prototyping method so for example if i have a simple electrical circuit for example this rc filter which is a low pass filter i have my input voltage here my output voltage on the other side a resistor and capacitor seeing this as an ideal circuit the current the resistor is the same as the current with the capacitor then i can use kirchhoff's laws so v in minus v out of r is the current through resistor that's equal to the capacitor current which is c times the rate of change of the voltage across the capacitor which is simply dv out by dt then rearranging getting all the v outs on one side and the v in on the other side i have a differential equation however this is in the continuous time domain and i want to go to the digital domain or the discrete time domain so i have to discretize i can let dv by dt or a first order derivative approximately be equal to vn minus vn minus 1 divided by t which is the sampling time and that's the euler approximation and that comes from a first order taylor series of expansion plugging that into the differential equation and discretizing and then also rearranging we form this difference equation so we have v out sample n is this constant over here so t over t plus rc times v in which is the input plus another constant times the previous output so v out of n minus one and as you can see this form is very very familiar to us already again this is a first order irr filter which we got from our analog prototype rc filter this coefficient over here is pretty much a naught and this coefficient over here is b1 if we look at the general form of an irr filter and when we implement this this actually emulates an analog rc low pass filter so let's have a look at this on an stm32 system right now so here we are in the stm32 cube ide development environment and from the previous video where we wrote a driver for an adxl355 accelerometer i'll be using the code so essentially from that video all i got was the raw accelerometer readings x y and z axes and i would like to perform some low pass filtering using our irr filter so i've made a really simple header file for this filter i have a struct which includes my alpha which is my coefficient for my filter going from 0 to 1 and i have a float which is an output of the filter so i need to store my output because i'm using this for my feedback to compute the new output sample then i have an initialization routine which essentially just checks if the alpha value is within range of zero to one and then resets my output to zero i also need a filter update routine of course and that computes the new output sample so i get my input pass through and i compute my new output sample and that's pretty much it so let's go over to the c file and see how these functions are implemented so the first order ir init function just checks if the filter coefficients are bounded correctly and then i store them in my struct so i check if it's below zero i set it to zero if it's above one i set it to one otherwise i simply just store it then i reset my filter output and that's about it now the interesting routine is this update routine let's see how to do that now if i pull up my slide to the left here this is the difference equation or the irr filter we'd like to implement what it's telling us is that the new output so let's write the output is 1 minus the filter coefficient which is alpha times our current input which is in which is part of the function and i add to that alpha times the previous output which is stored in our struct so i just need to access that and that's it so you can see here all i've done is transfer from our irr difference equation into the code as very straightforward very direct and quite intuitive actually the output is some constant times the current input plus a constant times the previous output and i store all that in my new output sample then i return the filter output going into my main.c i need to of course include my new header file in my new code i am defining my irr filter alpha which i then just can change and play around with to about 0.5 somewhere in the middle just as a starting value then of course i need to define my struct which i'll call filt i need to initialize my lower pass filter so i need to pass it my alpha value and that'll then set also the output to zero and this board actually supports usb so i'll actually be streaming my raw accelerometer data and my filtered solar data via usb and we can plot that and see how the filter is performing so every time i get an interrupt for my data ready pin this fires and in my main loop i check then i read the accelerations and then i actually filter my accelerometer reading for this example i'm just going to filter one axis the x-axis so i pass the struct by reference then also this acceleration value which is raw now when it's ready to send the data via the virtual comport or usb i simply pass the raw accelerator reading as well as the filtered output so let's upload this code to the board and see what our filter actually does all right so i'm going to upload my code to the board by clicking this arrow over here it compiles and waits for the debugger connection and then it uploads it now i'm using this tool called the serial oscilloscope and if you google that it's actually quite a useful tool to plot things streamed via for example a virtual com port so i'll open that choose my serial port which is created by my stm32 and you can see i'm getting quite a lot of samples through here i can click on the scope and now if i move and you see my red trace is my raw data from the accelerometer and my green trace is the filter data from our simple first order irr filter as you can see all the high frequency noise is nicely attenuated but my underlying trend is still there and this is a really really simple ir filter but this is perfectly fine for something such as sensor smoothing or signal smoothing so this is really cool and a very simple implementation so i hope you enjoyed this video if you did please give it a thumbs up hit subscribe if you haven't already and thank you so much i'll see you in the next video
Info
Channel: Phil’s Lab
Views: 25,863
Rating: undefined out of 5
Keywords:
Id: QRMe02kzVkA
Channel Id: undefined
Length: 19min 47sec (1187 seconds)
Published: Tue Sep 07 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.