Low pass filter for DC motor current measurements - Page 1
Forum section: electronics / general

author: krisRaba
author_rank: Regular Contributor
timestamp: November 24, 2020, 12:43:33 pm
content: Hi,I use STM32 MCU in my project but the problem is general, not platform related, I think.DC motor current is sampled with 100kHz rate (PWM is 50kHz, current sensor bandwidth limited to 20kHz), 2x in the middle of PWM ON state, 2x in the middle of PWM OFF state, but these 4 samples are then averaged. I think that it can be assumed that sampling rate is 25kHz then.Motor current doesn't look too nice, which is normal, and measured signal has a lot of high frequency noise. I would like to get rid of that noise because I want to use this signal as feedback for current PID regulator.I don't need 25kHz bandwidth, in my opinion 1kHz would be enough so it could be averaged or decimated. But even with 25 samples averaging to reduce 25kHz to 1kHz the signal looks bad.You can see the plot below (the red line). Without averaging it looks even worse. The green line is a simulation of FIR filter. It is not fully adequate because it filters that averaged 1kHz signal instead of source 25kHz but definitely I would prefer that green shape instead of red shapeMy question and the problem is the implementation. Because I get ISR after collecting 4 samples (End Of Sequence event when using injected conversions, samples stored in 4 JDRx registers) I would like to spread calculations over all ISR calls instead of huge overhead of batch calculations at 1kHz rate (so in each 25th ISR call).If I understand it correctly, FIR filters use "taps" and taps count is equal to coefficients count. Tap count would be also the number of input samples taken for calculations, right? Something like moving window - at each call it would use the newest sample and (tap-1) number of older ones.Example C functions that I've found use batch calculations (i.ehttp://www.iowahills.com/Example%20Code/FIRFloatingPtImplementation.txt) but first of all I don't need 25kHz samplingSo I am not sure how to implement that.. Should I average these 25 samples to get 1kHz, then call LPF calculations and then feed the curennt PID regulator? Or call LPF for 25kHz samples, then average or decimate, and then feed the PID?Any idea for real life implementation?Or maybe LPF is not needed here and the current PID should be tuned less aggressive? But I would like to have quick response so I can't downtune it too much. And HF noise in the feedback doesn't help

author: ace1903
author_rank: Regular Contributor
timestamp: November 24, 2020, 01:39:57 pm
content: The waveform looks strange for DC motor. Are you using a brushed DC motor?What is time/div on X axis? Are you using H bridge with the current sensor in series with the motor?Only a purely resistive load can produce a waveform with this shape.That is why it is important to know what is the sample rate for the current shown in the graphic and where the sensor is placed in the schematic.Averaging current in ON and OFF state sounds strange. Please provide more info about what you measured and what you want to achieve.

author: krisRaba
author_rank: Regular Contributor
timestamp: November 24, 2020, 02:21:50 pm
content: Oh, sorry for being unclear.The plot is not a PWM cycle. It is the averaged current measurement at specified setpoints. So it represents mentioned above 1kHz signal (average of 25 samples, which are an average of 4 samples). Because of limited interface bandwidth in reality it is every 10th sample because it is printed in task executed every 10ms, so plot is 100ksps.At the beginning current PID is OFF, then it is turned on and 750mA is requested (scale in Amps), next step is at 0mA requested, then -400mA, then 0mA again, 750mA once again and 0mA...About the ON and OFF sampling.. In theory at these points you can measure average current of a DC (somebody told me that and I believed him). I decided to measure 4 such points to have at least 2x more samples than the sensor bandwidth (Nyquist).The idea was also to compensate the lag introduced by hall current sensor. Manufacturer specifies typical delay but it can vary from part to part, it is not guaranteed. What I have noticed is that if you for example hit with your sampling point a little bit before the middle of delayed signal in ON phase and sample will be too low in value you will also hit the earlier point in OFF phase when the sample is proportionally to high in value, so average of that should give the real valueBut maybe it is not proper approach, I don't know.

author: krisRaba
author_rank: Regular Contributor
timestamp: November 24, 2020, 02:24:36 pm
content: Oh, and yes. It is H-bridge and ACS hall sensor in series with motor windings...

author: T3sl4co1l
author_rank: Super Contributor
timestamp: November 24, 2020, 06:11:54 pm
content: Are the PWM and sample rate coherent (e.g. same timer trigger source)?If so, this seems like a setup for failure. How far can PWM vary, before it's impossible to squeeze two samples into one half? And what does that do to the weighting of the samples, over the waveform?Problem is you're aliasing the harmonics. Hopefully to zero, but this isn't easy to achieve in practice, over the full range of PWM settings.I'd be more comfortable with simply sampling the waveform at some multiple. For very low or high PWM settings, the samples largely fall on a single slope, so average out correctly; for very middle settings, the samples largely fall on complementary slopes, so average out correctly; the case when a peak partitions samples unequally may not average out so well, and the tolerable error determines the multiplier.It's not impossible, if you know the typical current waveform (a slightly bent triangle?), to adjust it in software. It might be measured (calibrated), or estimated. It would be a function of PWM setting, supply voltage, and (instantaneous, or averaged over some range of time) current. Establishing the relationship of three variables might not be trivial, but maybe it turns out one or another can be knocked out easily (voltage should be a simple proportion, and current may not have much effect if saturation isn't occurring, and while the current remains continuous).You might consider sampling orthogonally, or at least at some ratio that's likely to average out ripple over a reasonable time frame. The averaging filter would have a time constant around the... LCM or GCD, I always forget which, of the two frequencies. And you can still do instantaneous (peak) detection for control/fault purposes, with the error band set appropriately to allow for the samples sometimes landing on peaks or valleys.Tim

author: krisRaba
author_rank: Regular Contributor
timestamp: November 24, 2020, 08:07:15 pm
content: Hi Tim,thank you for your answer. I am not sure if I get your point properly. Sorry for that question but do you have experience with motor control and related measurements or you reply using general knowledge that could be used as general guide by similarities? Because some sentences doesn't match with my understanding and I am confused.First of all - sampling. Why in your opinion PWM synchronized trigger is a setup for failure? IIRC I have seen in many documents that ADC trigger SHOULD be synchronized because current waveform is strictly related to PWM waveform so random trigger would create a big mess (one time you hit the bottom of the waveform, other time somewhere in the middle etc) . When trigger is synchronized you always hit the same points.Current waveform more or less looks like this:https://www.edn.com/wp-content/uploads/media-1049945-c0135-figure2a.gifYou have even mentioned the rounded triangle so it seems you know that. This current waveform dances around average current (the bias). See the attachement below which contains edited image linked above.In phase correct PWM timer ZERO is in the middle of the ON state or the OFF state, the center of opposite state is the timer overflow point. So it is easy to trigger ADC on these particular moments.Of course world is not ideal, current waveforms either, so even on this image you can see that average current floats a little bit and doesn't fit my blue line perfectly all the time. It can be also a problem in these measurements. On my DSO I can see that during shaft rotation this waveform dances up and down so average current changes quite a lot. It may be related to commutation and load changes (it is a geared motor).Additional thing is the lag introduced by ACS current sensor. In 20kHz bandwidth mode output signal is delayed 5ms so my ADC triggers are delayed as well to match the current feedback, not the generated PWM.So at the moment on EOS trigger I have 4 samples like on my edited plot and they are averaged. Maybe I should switch to measure only the middle of ON states...In my case these current waveforms are much more rounded because of filtering in the ACS. When I switch to 80kHz bandwith waveforms are more like these on image but I would also need to increase sampling rate to at least 2*80kHz (Nyquist) which is not needed as 1kHz is enough for meThing that seems to be tricky, when I think of it now, is 20kHz bandwidth for 50kHz signal.. hmm.. I hope that it is properly filtered in the ACS. I have to check the response with 80kHz once again and compare...What do you mean by aliasing harmonics? With a waveform and sampling like on my image?

author: T3sl4co1l
author_rank: Super Contributor
timestamp: November 24, 2020, 11:47:12 pm
content: Oh yeah, I forgot to discuss phase-correct PWM. You should be able to trigger on each timer count peak, which is in the middle of each slope and away from the switching edges.Switching edges do transmit a lot of noise, but I don't consider this an insurmountable obstacle; if your system is noisy, that's your problem, and soon to be others's (emissions), once wired up! Keep it clean in the first place.Hall effect sensors are usually well-behaved, so even if the measured signal has a lot of CM and DM noise on it, the reading should be okay. (An especially big problem in H-bridge inverters -- it may pay to add even minor filtering at the inverter output, or CM filtering to the sensor.)It also wasn't clear to me how many samples you were managing. One on each  peak seems reasonable; four distributed over the cycle doesn't seem so easily done, or inevitably fails at some PWM settings.There's also the matter of propagation delay; presumably the timer, and ADC capture or conversion, aren't perfectly synchronized, but have some cycles of delay, or aperture window. (If this can be done through a hardware event system or whatever, it should be just a few cycles, not bad. I forget offhand which STM32 offer features like this.) Timing errors manifest in the same way that jitter errors manifest as high-frequency noise (SINAD) in traditional ADC systems (look up articles discussing the matter). In this case with the waveform generally known, you can see intuitively that a delayed sample on the rising slope will have a greater error than the same delay on the falling slope, and therefore read an erroneous DC offset after averaging the two together.Harmonics being aliased to DC, is what you're doing with synchronous sampling. Consider sampling at exactly Fs = Fsw. Adjust the phase. When the phase aligns to one peak, you measure, well, that peak; when it aligns to the other, well, you know. And there's the middle somewhere inbetween. If you look at the measured value with respect to phase, indeed, you can reconstruct the original waveform -- even though you've not sampled nearly fast enough to acquire the waveform in realtime. Indeed, this is just equivalent time sampling.If we look at the process in the frequency domain, we have a signal with a large DC component, a modest fundamental, and harmonics generally going as 1/N^2 (a triangular wave). This is on top of the general PWM signal, which has harmonics that go as sin(pi D) or something like that. So as D varies, there will be periodic notches in the spectrum. (If we consider the worst-case distribution for any D, we can just ignore this aspect.)The "bent" wave will have somewhat stronger low harmonics; at worst, going as 1/N, the limiting case for a square wave. The "bend" implies a sort of interpolation between the two cases; the underlying mechanism is an L/R characteristic of the load. Or.. wait, would that be higher frequency harmonics, not lower? Well, whatever, depends which way the L/R characteristic is.So we mix this signal, with the sampling signal. The sampling signal is a sequence of sampling apertures: impulses where the current waveform is sampled, and zero everywhere else, where its value is ignored. We mix these by multiplication in the time domain, which is equivalent to convolution in the frequency domain.Convolution is the process of shifting one function with respect to the other, and adding up the total for each case. The output is the curve of totals as a function of shift.Since the sampling signal is periodic impulses, we don't have to consider every possible shift value for the convolution, only the harmonics. Since, for any non-harmonic offset, the sample function is simply zero; and on a harmonic, it looks identical to itself.So the convolution is simply the original signal, repeated on top of itself, shifted by every harmonic.So, the fundamental shows up with equal amplitudes at 0, +/-Fsw, +/-2Fsw, etc.; and the 2nd harmonic at 0, +/-Fsw, +/-2Fsw, etc.; and so on.All the harmonics are aliased to zero (and everywhere else), and contribute to the total measurement, according to their relative phases and amplitudes.Which of course is why, as we vary the phase between Fsw and Fs, we reconstruct the waveform as the DC component -- equivalent time sampling.So, that's what I mean by aliased harmonics. Apologies if this is too basic, I don't know how much signals theory you know. Or if this is too advanced, then it probably flew over your head... In which case, you should find it very illuminating to study -- at first the Fourier transform seems bizarre, or remarkable, but once understood, it's actually quite obvious, or perhaps not even very interesting (in the sense "all mathematical theorems are either obvious, or wrong").My concern is really this: if the sampling per cycle is rather sparse, it's probably better to have it phased randomly (or at least that phase rotate over a small prime number of cycles, say), than to have it fixed.The sparsity is determined by the acceptable measurement error. If DC current is 10A and ripple is 1Apk, and allowable error is 10%, then the ripple needs to be filtered to less than 1A. Which is almost trivial -- sampling on  peaks and averaging pairwise will do just fine. The worst possible error is for very small PWM, where one sample is nearly on top of the ripple peak, and the other is some way down the opposite slope; the average between peak and zero is 0.5A, a mere 5% of the total, well within the allowable error.If the phase is coherent, but not fixed to a special part of the cycle (the phase-correct timer peaks), then the error can be worse. Worst possible error being always sampling on one peak, +10% say. Or somehow getting off beat and sampling the other peak, -10%, the difference being 20%, an unacceptable error (I'm not sure how the phase would just flip randomly, I'm just saying for sake of argument here).Whereas if the error needs to be say 1% or less, you should have more than a few samples per cycle, maybe tens of them. That can be within a single cycle, or scattered evenly over multiple cycles (assuming the cycles themselves don't change much from one to the next, i.e., PWM setting doesn't change quickly).If you can sample more times per cycle, you can cover more points on the waveform regardless of their relative phase, and the aliasing error goes down. If you sample four times, equally spaced, then even if one sample hits the peak and the others hit parts of the slopes (and even if one or two are on a steeper slope so they incur a higher error from delay), the total error must be less; presumably about half of the two-sample case, so, maybe 2.5% or so.If you don't have / can't afford a higher sampling rate, then I think you should consider a regularly rotating phase, so that you are still taking samples evenly throughout the waveform, they're just spread out over multiple cycles. Use a sliding-average filter at the repeat rate (e.g., a 80kHz sample rate and 100kHz switching frequency, repeats every 20kHz: use a 4-wide filter window) and the ripple error will be as low as a sample rate that many times higher; the downside of course is the total bandwidth is lower. Presumably, this would be acceptable (e.g., just measuring current for monitoring purposes, or for control purposes with a load of similar or lesser bandwidth), otherwise you'd choose the higher sample rate in the first place (sampling multiple times per cycle is a good plan for general average-current-mode controls, and many times higher still would be required for peak-current-mode control, but I would strongly recommend just using a comparator and latch in that case -- hardware which is sometimes even available in MCUs!).Whereas, sampling four times, unequally spaced, is setting up a whole host of concerns:- How close can you really space them?- How accurately can you time them?- What should they be timed to?- Can you avoid sampling on the switching edges, for all PWM settings? (Should you? -- As mentioned above, I would say your analog/EMC design should be good enough that this doesn't cause an issue. But that's probably because I don't find that too big of a challenge to solve, and YMMV.)- How does the ADC error change with rate? (Hopefully it doesn't, but it could, who knows?)- How do you handle the edge cases you've created? If you ignore the cases, then under some conditions, for example, you'll try and stomp on one ADC acquisition already in-progress, trying to make it acquire another. What happens then? Or if you adjust the ADC clock to speed it up, are you poisoning the ENOB? (Typically, SAR ADCs can be modestly overclocked, if you don't mind that only so-and-so many HSBs are correct. A 1MS/s 12-bit ADC might still deliver 7 or 8 bits at twice the clock rate.)The nature of this argument is not necessarily one of raw numerical fidelity. It's a matter of structural consistency and simplicity. By making the system adaptive and complicated, you've invitedso many more problemsonto yourself, and you are leaving behind all the theoretical tools that normally guide you.I do admit, such a complaint also resembles an argument from authority, or from orthodoxy: "we do it this way because we've always done it this way and it is the right way to do things!" In this case at least, there is good (theoretical) justification underlying that tradition -- and, so far at least, I haven't seen any justification for moving away from that approach. A simple motor control surely isn't pushing any limits in terms of control bandwidth, say. (There are good reasons why one might research a more experimental method -- hence this is not, in fact, an argument from orthodoxy.)On the other hand, if you don't know any theory (whether the traditional way, or advanced techniques, or some other imagined alternative--), this still sounds like an argument from authority. That is, you simply don't have any way to evaluate the alternatives, you don't know enough to work through them; and all you see are people suggesting that it be done this or that way, and their opinions don't seem any more authoritative than your own ideas.Now -- if you did want to research those advanced methods -- you have to re-derive all of those theories, based on your, patterned sampling strategy, or whatever exactly you might be doing. You will spend an awful lot of time doing so, and still quite a lot of time ironing out the bugs in the software that runs it; and the greater complexity will take up more code space, maybe more memory, and more CPU time. Is it really worth the investment?And indeed, you can do arbitrary sampling schemes: in fact, there's a lot of newer theory on the matter, many people have dedicatedyearsof their lives to help figure this stuff out -- there's a reason it stands beside traditional signals theory (such as periodic discrete-time DSP), because what's traditional/classical is easy and useful, and what's new is hard to work with...But if you wish to follow that path, there are tools to help out with that, and the results can be astonishing -- random-sampled L1-norm analysis can yield scarily good fidelity, from very little data indeed. The price you pay is all the CPU cycles figuring out how to fit the data. If CPU performance continues to trend toward infinity while ADCs remain limited (by the current/speed tradeoff of their analog components), we'll see more and more application of these techniques.(Though it would be hard to justify (or even relate) these particular methods to mere motor control, if not entirely impossible for hard real-time controls!)Tim

author: ace1903
author_rank: Regular Contributor
timestamp: November 25, 2020, 08:50:27 am
content: Trying to see the wider picture here.DC brushed motor fed with 50KHz?Current up to 1A at 50Khz in combination with brushes means EMI everywhere.ACS sensors are based on Hall effect plus built-in chopping amplifier plus built-in DSP.ACS line has huge noise floor specified in the datasheet, they are good for currents up to 1000A but the lowest range is 5A and with currents less than 1A SNR is disappointing.Built-in DSP and choppers will filter out anything more than 20KHz much more than you expect.When using 50KHz careful design of H-bridge is needed. Some of the stuff that you call noise can be cross conduction currents.My advice is to lower the switching frequency to something like 15KHz and do the test with low inductance ohmic load and then a second test with resistor plus fixed inductor.It will give you a clue where the problem is and how to address it.To me, this 50KHz looks more like an academic project than a mass-market product.Geared DC motor is much more limited by mechanical parameters like the inertia of moving parts than the speed of the control loop.

author: Siwastaja
author_rank: Super Contributor
timestamp: November 25, 2020, 10:04:07 am
content: Just measure once, always during on-time. This necessitates some minimum duty cycle, but it can be quite low, like a few %.Assume the motor runs in CCM. Measure exactly in the middle of the on-time. This way, the only sampleisthe average current! It's measured in the middle of the rising part of the triangle wave, hence it's the average. At very low currents, the motor falls in DCM and the indicated current is more than the actual average, but usually this isn't a problem.This is easy to implement using a timer module which counts upwards and downwards (think about counting 0..1000..0 and the PWM setpoint at 800 would mean it turns on at 800 and the back off again at 800). ADC can be triggered at the max count, or even fancier, a few numbers before it to account for triggering delay.Also when you trig in the middle of on-time, you don't get switching noise.I've always done it this way and my ADC readings seem to be very low-noise and look good without any filtering at all, but you can always add some simple averaging.

author: krisRaba
author_rank: Regular Contributor
timestamp: November 25, 2020, 11:35:41 am
content: Whoa, that's a lot of text and information!Thank you for your reply.First of all I would like to correct my mistake about ACS output signal delay.. it is 5us for 20kHz bandwidth, not 5ms as I wroteFor 50kHz PWM it would be weird to delay ADC trigger for 5ms when cycle duration is 20usQuote from: T3sl4co1l on November 24, 2020, 11:47:12 pmI am able to trigger ADC in the middle, PWM timer counts up and down so everything is easily done in the hardware. The point is that I have to delay the trigger (also in hardware) because of the lag in ACS so I can't say that sampling is done away from PWM edges anymore... It would be perfect solution for measuring current on shunt resistor with (in theory) zero delay. In my case at some PWM duties my delayed sampling hits the PWM switching edgesH-bridge switching and primary current are (let's say "almost" here) in phase with PWM signals from MCU. Only the ACS sensor output is delayed. But on DSO there are no spikes on the output waveform so maybe it is not a problem at all.Quote from: T3sl4co1l on November 24, 2020, 11:47:12 pmGenerating the triggers is not a problem, I think. But there is no hardware support for calculations on the fly so sooner or later MCU has to manage them in the software. I can use DMA and a large buffer for samples but then ISR or regular task has to handle larger amount of data. ISR per cycle seems to be an overkill for the purpose. Large buffer (multiple samples per PWM cycle) and batch calculations at 1kHz rate sound like heavy CPU load for me.But I agree that average of multiple samples per cycle would give much better results than single point or double point sampling.Quote from: T3sl4co1l on November 24, 2020, 11:47:12 pmEverything is triggered in hardware. It is rather standard functionality for MCU. But you may be right that averaging samples from ON and OFF states middles brings more problems than advantages...Quote from: T3sl4co1l on November 24, 2020, 11:47:12 pmThank you for detailed explanation. I am somewhere in the middle, I think. Signals theory was quite understandable in collegeBut after many years, because it wasn't used in practice, it sounds a little bit likeand with limited time it is sometimes hard to assimilate again the basics. At the moment it is much easier for me to configure MCU hardware, use various available interconnections and mechanisms than post-process sampled signalsQuote from: T3sl4co1l on November 24, 2020, 11:47:12 pmHigher sampling rate is possible, as I wrote above, but I am not sure if the cost of CPU load is worth it, especially if I plan to update my current loop at 1kHz rate (2kHz would be the worst case, I think). So I don't care about individual peaks, their shape etc.and I am interested in the average current for control purposes. I do have internal comparators that can kill PWM signal cycle-by-cycle (OCREFclear option) when defined signal value is exceeded but at the moment I have it disabled.So the point is to get best average of current just before every current loop update. I am not sure if i.e. 10-20 samples per cycle x50 cycles is worth it if other techniques could provide similar results with lower CPU load. Actually I would love to have some hardware feature that could be fed with samples and average them without CPU intervention.But I like the idea of rotating phase which would result in something like equivalent sampling... but I am not sure how many samples it should collect to average 1kHz period good enough. PWM duty should be constant between current loop calls but the motor load can change and it results in current change as well. So I can't assume that current shape for every PWM cycle is identical.Quote from: T3sl4co1l on November 24, 2020, 11:47:12 pmThat are good questions. I could bet that you are a PhD in a collegeBut as I wrote, I am not very keen for oversampling, overclocking etc. if my goal is to have current average every 1msQuote from: T3sl4co1l on November 24, 2020, 11:47:12 pmYou may be right. But there are some tasks to do where you know that a lot of knowledge has to be gained first, nobody did that before or you have no idea how someone did that and unfortunately someone asked you to do it as wellOn the other hand you have tasks as standard and common as wooden stick, everybody does that, and you don't want and probably you even shouldn't reinvent the wheel, bring super-advanced high-tech, newest algorithms etc. DC motor control doesn't sound like the first category to meQuote from: T3sl4co1l on November 24, 2020, 11:47:12 pmYeah, I definitely prefer standard approach in this case.So what would you suggest for most adequate average of current, available each 1ms to update current loop, in conditions I have described above?In the meantime I have to check if 80kHz output signal dances as much as 20kHz. Unfortunately the motor is geared and I don't have any chance to see how it works without the gearhead.

author: krisRaba
author_rank: Regular Contributor
timestamp: November 25, 2020, 12:05:14 pm
content: Quote from: ace1903 on November 25, 2020, 08:50:27 amWhy do you think so? 50kHz PWM results in lower current ripple. Currents up to 4AQuote from: ace1903 on November 25, 2020, 08:50:27 amNot sure if there is any DSP inside. I think it's just analog amplifier with some filters.But I agree about SNR at low currents.Quote from: ace1903 on November 25, 2020, 08:50:27 amProper care was taken. It is okQuote from: ace1903 on November 25, 2020, 08:50:27 am50kHz is recommended by the manufacturer because of quite low windings inductance and they use the same frequency in their controllers. Not only for academic purposesQuote from: ace1903 on November 25, 2020, 08:50:27 amI agree. I think the purpose of high frequency is staying in CCM mode, not the mechanical response.

author: krisRaba
author_rank: Regular Contributor
timestamp: November 25, 2020, 12:11:26 pm
content: Quote from: Siwastaja on November 25, 2020, 10:04:07 amI think that because of high frequency motor is in CCM most of the time.Quote from: Siwastaja on November 25, 2020, 10:04:07 amThe problem is that ACS output is delayed and I am not sure if it is 5us for all conditions or maybe it can vary.. So my "middle of the rising part of the triangle wave" is somewhere else, not in the middle of generated ON stateQuote from: Siwastaja on November 25, 2020, 10:04:07 amOk, thank you.

author: Kleinstein
author_rank: Super Contributor
timestamp: November 25, 2020, 12:37:17 pm
content: The current sensor is likely just analog. There could be some chopper operation be included.Any low pass filtering will add some delay and this makes it difficult to still find the middle of the on phase as a defined point in time.The main point is likely to avoid the switching times. I would consider using some analog filtering, maybe in the 10 kHz range, possibly high order and than sample a relatively large number of points and do some averaging. The filtering is mainly to suppress higher harmonics. Filtering the residual ripple is more from averaging and thus in the digital domain.One should not overdo filtering (analog or digital), as the added delay can effect the control loop. The control loop will usually also do some kind of low pass filtering. So it would not react much to the fast fluctuations anyway. The differential part needs some care not to include too much of the higher frequencies. A real PID regulator need another upper frequency limit as a 4 th parameter !Part of the shown fluctuations could be due to a borderline regulator, not noise. For a test one could compare 2 cases with different regulator gain.

author: Siwastaja
author_rank: Super Contributor
timestamp: November 25, 2020, 03:24:55 pm
content: I always try to choose the current sensing solution so that its bandwidth (-3dB) is at very least twice or so the PWM frequency.If you have to use the sensor you have now, real cycle-by-cycle current measurement is out of window anyway, so I would try to just increase the number of ADC measurements so you get more per cycle than just four, then average the shit out of them. I have also done this on past, I think I had a project with 16 ADC measurements per cycle and that averaged quite nicely despite one of the samples possibly hitting exactly at the noisy switching edge; but it just contributed 1/16 of the total average (per cycle). You may want to dither the PWM value so it doesn't get to the exact same point every cycle at certain unlucky PWM setpoints.All STM32 MCUs I know of have at least 1MSPS ADCs, so maybe try setting it to sample at 1MSPS instead of 100kSPS, and report back what happens to the noise. You could just set it free-running for now, it would be interesting to see.Current feedback needs to have quite some bandwidth, though. Seeing you have low-inductance motor so you "need" 50kHz for low current ripple, that also means you probably also need some 10-20kHz control bandwidth for the current. Do you have any alternative protective current limit, even an inaccurate one like Rds_on sensing or desat detection?IMHO, changing to a current measurement with more BW (say, some 100kHz if you just measure motor current, or some 200kHz if you measure bottom leg of the transistor) would be the simplest and most optimum solution; then you can just run the current control loop at the PWM frequency - for example, timer trigs ADC, ADC completion trigs PID ISR and also set Analog Watchdog to trig another highest-priority shutdown interrupt in case of overcurrent, or use the timer break input, and either way you do it, it will react quickly.

author: krisRaba
author_rank: Regular Contributor
timestamp: November 27, 2020, 12:48:55 pm
content: Quote from: Kleinstein on November 25, 2020, 12:37:17 pmInteresting, it may sound weird but I totally forgot about R/C filter between ACS and MCUMy previous comparison was made near ACS output pin so before R/C filterIt may sound even more stupid but I have found it during scratching my head recently and wondering why there is (almost) no difference between 20kHz and 80kHz output mode when measured on TP near MCU input pin (and I was sure that I have seen such difference before).It is not high order as you would suggest but it is present and does something- 100R/100nF so fc=15.9kHz. It would be better suited for 20kHz and for 50kHz PWM it cuts very low, I think. But at the moment I am not sure if I should leave it or change it. For control loop I need average current anyway and average levels match quite well so with lower ripple the measurement error would be lower even if sampling point is not perfectly aligned.Quote from: Kleinstein on November 25, 2020, 12:37:17 pmI don't use D part for current regulator so it is PI type actually.I can force constant PWM duty (current control loop disabled) and fluctuations are present as well so it is not only a result of better or worse regulation.Quote from: Siwastaja on November 25, 2020, 03:24:55 pmUnfortunately I have to use the setup as it isMaybe with some thoughts for the futureMultiple samples per cycle will better represent each cycle but as I wrote above - it is filtered but "noise" comes from fluctuations visible over wider timespan. Probably I should test this setup with fixed resistor+coil and see the results. At the moment I presume that fluctuations come from slight changes in the motor load during rotation.Quote from: Siwastaja on November 25, 2020, 03:24:55 pmMy interface has very limited bandwidth so it would have to buffer some period and then push it away to PC. Maybe I will do it later...Quote from: Siwastaja on November 25, 2020, 03:24:55 pmYou may be right with the control bandwidth. We will see. I saw in original controler's specification that current control loop is 25kHz but I assumed that it is "up to" or they are kidding meBut maybe not...About the "need" you can see on attached plots that even with so high PWM freq motor current is not a DC levelWith higher inductance it would be, I think.About the limits - I have an option of OCREFclear (to turn off PWM cycle till next timer update when comparator says so, but with overfiltered signal it may not work perfectly) and as a last resort the PSU handles overloads very well.Quote from: Siwastaja on November 25, 2020, 03:24:55 pmYeah, in future designs it could be a good idea.

author: krisRaba
author_rank: Regular Contributor
timestamp: December 03, 2020, 09:11:22 am
content: Topic suddenly diedNo more suggestions related to presented waveforms captured with DSO?