[go: up one dir, main page]

RU2242792C2 - Method for fast averaging fir filtering on basis of processor - Google Patents

Method for fast averaging fir filtering on basis of processor Download PDF

Info

Publication number
RU2242792C2
RU2242792C2 RU2002111508/09A RU2002111508A RU2242792C2 RU 2242792 C2 RU2242792 C2 RU 2242792C2 RU 2002111508/09 A RU2002111508/09 A RU 2002111508/09A RU 2002111508 A RU2002111508 A RU 2002111508A RU 2242792 C2 RU2242792 C2 RU 2242792C2
Authority
RU
Russia
Prior art keywords
averaging
samples
filter
sum
processor
Prior art date
Application number
RU2002111508/09A
Other languages
Russian (ru)
Other versions
RU2002111508A (en
Inventor
Р.Н. Напылов (RU)
Р.Н. Напылов
В.И. Пугачёв (RU)
В.И. Пугачёв
А.А. Курицын (RU)
А.А. Курицын
А.И. Иванов (RU)
А.И. Иванов
Р.Г. Шехмаметьев (RU)
Р.Г. Шехмаметьев
Original Assignee
Открытое акционерное общество "Краснодарский ЗИП"
Кубанский государственный технологический университет
Priority date (The priority date is an assumption and is not a legal conclusion. Google has not performed a legal analysis and makes no representation as to the accuracy of the date listed.)
Filing date
Publication date
Application filed by Открытое акционерное общество "Краснодарский ЗИП", Кубанский государственный технологический университет filed Critical Открытое акционерное общество "Краснодарский ЗИП"
Priority to RU2002111508/09A priority Critical patent/RU2242792C2/en
Publication of RU2002111508A publication Critical patent/RU2002111508A/en
Application granted granted Critical
Publication of RU2242792C2 publication Critical patent/RU2242792C2/en

Links

Images

Landscapes

  • Complex Calculations (AREA)

Abstract

FIELD: computer measuring equipment.
SUBSTANCE: method is based on processing of samples when they appear, only by adding operations and comparison operations for determining moments of totals fixing time.
EFFECT: higher effectiveness.
6 dwg, 1 tbl

Description

Изобретение относится к области цифровой измерительной техники, где одной из типичных задач является задача определения среднего значения некоторого сигнала, когда используемый цифровой фильтр должен выделить постоянную составляющую сигнала и подавить все помехи, присутствующие в сигнале в виде флуктуации /1/, С.127. Рекомендуется использовать изобретение в составе средств цифровой обработки электроизмерительных сигналов в качестве способа быстрого взвешенного усреднения выборок при построении цифровых измерительных приборов на базе сигнальных микропроцессоров с ограниченным объемом памяти и вычислительными возможностями.The invention relates to the field of digital measuring technology, where one of the typical tasks is the task of determining the average value of a certain signal, when the digital filter used should isolate the constant component of the signal and suppress all noise present in the signal in the form of fluctuations / 1 /, P.127. It is recommended to use the invention as a part of digital processing of electrical measuring signals as a way to quickly weighted averaged samples while constructing digital measuring devices based on signal microprocessors with limited memory and computing capabilities.

В источнике /1/ - Гутников В.С. Фильтрация измерительных сигналов. - Л.: Энергоатомиздат. Ленингр. отд-ние, 1990, с.160-163 приводится способ КИХ-фильтрации прототипа, реализуемый на базе цифрового вычислительного устройства (ЦВУ) и просматриваемый в структурной схеме на фиг.1. Аналого-цифровой преобразователь (АЦП) 1 вырабатывает коды, пропорциональные мгновенным значениям входного сигнала x(t) с шагом во времени, равным периоду дискретизации КИХ-фильтра 7д, с. Физическая природа входного сигнала может быть любой, поэтому единицы его измерения опущены. Далее эти коды обрабатываются в ЦВУ 2, в качестве которого может выступать любой микропроцессорный элемент, где воспроизводится алгоритм работы цифрового КИХ-фильтра - вычисление взвешенной суммы последовательных значений кода. Указанный алгоритм воспроизводится по структурной схема, представленной блоками 3, 4 и 5. Здесь выборка АЦП, сохраняемая в запоминающем устройстве (ЗУ) 3, поступает на масштабирующее устройство (МУ) 4 и далее на накапливающий сумматор (НСм) 5. Начальная установка МУ и НСм производится с циклом N Тд. При этом в масштабирующем устройстве устанавливается коэффициент передачи а0, а сумматор сбрасывается на нуль. Приходящий после этого выходной сигнал ЗУ запоминается в сумматоре с коэффициентом а0. Далее в МУ устанавливается масштабный коэффициент a1, и в очередном такте 7д сигнал с ЗУ с весом a1 добавляется к сигналу, запомненному раннее в НСм. Всего в накапливающий сумматор поступают N дискретных значений входного сигнала, умноженных на весовые коэффициенты. Полученная таким путем взвешенная сумма есть выходной сигнал КИХ-фильтра. Затем снова производится начальная установка узлов фильтра, и начинается формирование нового выходного сигнала. Таким образом, на формирование одного значения выходного сигнала затрачивается время N Тд, а само значение определяется в соответствии с алгоритмом дискретной фильтрации, приведенном в прототипе на странице 162 и записанном ниже для одного цикла N Тд:In the source / 1 / - Gutnikov V.S. Filtering measuring signals. - L .: Energoatomizdat. Leningra. Otdelniy, 1990, p.160-163 provides a method of FIR filtering of the prototype, implemented on the basis of a digital computing device (CVD) and viewed in the structural diagram of figure 1. An analog-to-digital converter (ADC) 1 generates codes proportional to the instantaneous values of the input signal x (t) with a time step equal to the sampling period of the FIR filter 7 d , s. The physical nature of the input signal can be any, therefore the units of its measurement are omitted. Further, these codes are processed in CVU 2, which can be any microprocessor element, where the algorithm of the digital FIR filter is reproduced - the calculation of the weighted sum of consecutive code values. The indicated algorithm is reproduced according to the block diagram represented by blocks 3, 4, and 5. Here, the ADC sample stored in the storage device (memory) 3 is supplied to the scaling device (MU) 4 and then to the accumulating adder (NSm) 5. The initial installation of the MU and NSm is produced with a cycle of N T d . In this case, the transmission coefficient a 0 is set in the scaling device, and the adder is reset to zero. The memory output signal coming after this is stored in the adder with coefficient a 0 . Next, the scale factor a 1 is set in the MU, and in the next 7 d cycle , a signal from the memory with a weight of a 1 is added to the signal that was previously stored in the NSm. In total, N discrete values of the input signal multiplied by weighting coefficients enter the accumulating adder. The weighted sum obtained in this way is the output signal of the FIR filter. Then again the initial installation of the filter nodes is made, and the formation of a new output signal begins. Thus, the formation of a single value of the output signal takes time N T d , and the value itself is determined in accordance with the discrete filtering algorithm shown in the prototype on page 162 and written below for one cycle N T d :

Figure 00000002
Figure 00000002

где у - результат взвешенной суммы выборок АЦП;where y is the result of the weighted sum of ADC samples;

an - весовое окно;a n - weight window;

х[nТд] - выборка АЦП в текущий момент квантованного времени;x [nT d ] - ADC sample at the current moment of the quantized time;

д - квантованное время, с;nT d is the quantized time, s;

n - номер отсчета квантованного времени (безразмерное время);n is the reference number of the quantized time (dimensionless time);

Тд - период дискретизации, с;T d - the sampling period, s;

N - общее число выборок, используемых для взвешенного суммирования (память КИХ-фильтра).N is the total number of samples used for weighted summation (FIR filter memory).

Если в качестве весового окна выступает одно из распространенных усредняющих окон: Дирихле, Бартлетта, Хэмминга, Парзена или Гаусса, /1/, С.130-135, то описанная схема реализует усредняющий КИХ-фильтр /1/, С.127, осуществляющий взвешенное усреднение выборок входного сигнала.If one of the common averaging windows acts as a weighting window: Dirichlet, Bartlett, Hamming, Parzen or Gauss, / 1 /, С.130-135, then the described circuit implements an averaging FIR filter / 1 /, С.127, which carries out a weighted averaging the samples of the input signal.

При использовании в качестве ЦВУ процессора алгоритм (1) интерпретируется нами как способ усредняющей КИХ-фильтрации, то есть способ обработки выборок входного сигнала, получаемых с помощью АЦП с шагом во времени, равным периоду дискретизации, и последовательно суммируемых процессором с весами an для получения результата взвешенного усреднения у. Схема реализации указанного способа с помощью процессора приводится на фиг.2. Усредняющее окно аn предварительно сохранено в процессоре в виде массива индексируемого счетчиком квантованного времени n. Перед началом цикла усредняющей КИХ-фильтрации в блоке 6 обнуляются накопитель взвешенной суммы S и счетчик квантованного времени n. Далее в блоке 7 осуществляется получение кода выборки АЦП, который затем с весом а0 добавляется к накопителю суммы S в блоке 8. Потом в блоке 9 счетчик квантованного времени инкрементируется, после чего в блоке 10 его значение проверяется на момент завершения цикла усредняющей КИХ-фильтрации. Вначале блок 10 отрабатывает по ветви "Да", и процесс накопления взвешенной суммы вновь переходит к блоку 7, где получается новое значение кода АЦП, которое затем добавляется к накопителю суммы с весом a1, так как на данный момент n уже равен единице. Процесс накопления взвешенной суммы продолжается циклически до момента, пока блок 10 не идентифицирует равенство n числу N. Это событие соответствует завершению цикла усредняющий КИХ-фильтрации, когда квантованное время принимает значение NТд, а накопитель суммы содержит результат взвешенного усреднения всех выборок в объеме N. В этом случае блок 10 отрабатывает по ветви "Нет" для формирования выходного сигнала усредняющего КИХ-фильтра в блоке 11, значение которого принимается равным S.When using the processor as the CVC, we interpret algorithm (1) as a method of averaging FIR filtering, that is, a method of processing samples of the input signal obtained by the ADC with a time step equal to the sampling period and sequentially summed by the processor with weights a n to obtain result of weighted averaging y. A diagram of the implementation of this method using the processor is shown in figure 2. The averaging window a n is previously stored in the processor as an array of quantized time n indexed by a counter. Before the start of the averaging FIR filtering cycle in block 6, the weighted sum accumulator S and the quantized time counter n are reset to zero. Next, in block 7, the ADC sample code is obtained, which is then added with a weight of 0 to the accumulator of the sum S in block 8. Then, in block 9, the quantized time counter is incremented, and then in block 10 its value is checked at the end of the average FIR filtering cycle . At first, block 10 runs along the “Yes” branch, and the process of accumulating the weighted sum goes back to block 7, where a new value of the ADC code is obtained, which is then added to the sum accumulator with a weight of a 1 , since at the moment n is already equal to one. The process of accumulating the weighted sum continues cyclically until the block 10 identifies the equality n to the number N. This event corresponds to the end of the averaging FIR filtering cycle, when the quantized time takes the value NT d , and the accumulator of the sum contains the result of weighted averaging of all samples in the volume N. In this case, block 10 processes along the “No” branch to generate the output signal of the averaging FIR filter in block 11, the value of which is taken to be S.

Описанный способ усредняющей КИХ-фильтрации, реализуемый на основе процессора, полностью эквивалентен алгоритму работы КИХ-фильтра прототипа и имеет следующие недостатки:The described method of averaging FIR filtering, implemented on the basis of the processor, is fully equivalent to the algorithm of the FIR filter of the prototype and has the following disadvantages:

- усредняющее окно должно быть предварительно запомнено в памяти процессора тем большего объема, чем больше точность представления весовых множителей окна и чем больше число выборок используется для взвешенного усреднения. Наличие элемента памяти большого объема может существенно увеличить стоимость аппаратной реализации способа;- the averaging window must be previously stored in the processor memory the larger the more, the greater the accuracy of the representation of the window weighting factors and the more the number of samples is used for weighted averaging. The presence of a large amount of memory element can significantly increase the cost of the hardware implementation of the method;

- нахождение взвешенной суммы по формуле (1) требует выполнения умножений каждой выборки АЦП на весовой множитель an. Далеко не все современные процессоры имеют аппаратный умножитель с разрядностью, удовлетворяющей требуемой разрядности представления окна. Программное же умножение носит "медленный" характер и нуждается в относительно больших вычислительных затратах. Поэтому реализация формулы (1) либо ограничивает снизу время цикла усредняющей КИХ-фильтрации NTд, особенно при большом числе выборок N, а значит, и сужает область применения способа, либо требует использования высокопроизводительных и, соответственно, дорогостоящих процессоров.- finding the weighted sum by the formula (1) requires performing multiplications of each ADC sample by the weight factor a n . Not all modern processors have a hardware multiplier with a capacity that satisfies the required capacity of the window representation. Software multiplication is “slow” in nature and requires relatively large computational costs. Therefore, the implementation of formula (1) either limits the cycle time of the averaging FIR filtering NT d from below, especially with a large number of samples N, which means it narrows the scope of the method or requires the use of high-performance and, accordingly, expensive processors.

Технический результат, достигаемый предлагаемым изобретением, заключается в исключении недостатков прототипа. При этом заявляемый способ быстрой усредняющей КИХ-фильтрации на основе процессора:The technical result achieved by the invention is to eliminate the disadvantages of the prototype. Moreover, the inventive method of fast averaging FIR filtering based on the processor:

- исключает использование памяти процессора для хранения усредняющего окна, что существенно снижает стоимость аппаратной реализации способа, особенно при большом объеме выборок, обрабатываемых для взвешенного усреднения;- eliminates the use of processor memory for storing the averaging window, which significantly reduces the cost of the hardware implementation of the method, especially with a large amount of samples processed for weighted averaging;

- исключает использование операций умножения выборок АЦП на весовые множители, что существенно снижает вычислительные затраты способа и, как следствие, уменьшает время цикла усредняющей КИХ-фильтрации, без использования дорогих и высокопроизводительных процессоров.- eliminates the use of operations of multiplying ADC samples by weighting factors, which significantly reduces the computational cost of the method and, as a result, reduces the cycle time of averaging FIR filtering, without the use of expensive and high-performance processors.

Технический результат достигается за счет использования в качестве усредняющего КИХ-фильтра фильтра среднего высшего порядка, реализуемого "быстрым" способом на одних операциях суммирования, исключая запоминание усредняющего окна, и имеющего дискретную передаточную функцию следующего вида:The technical result is achieved through the use of a FIR filter as an averaging filter of a medium higher order, implemented by the “fast” method in some summation operations, excluding storing the averaging window, and having a discrete transfer function of the following form:

Figure 00000003
Figure 00000003

где W[z] - передаточная функция фильтра среднего высшего порядка;where W [z] is the transfer function of the medium order filter;

z - оператор 7-преобразования;z is the 7-transform operator;

n1 - память фильтра среднего первого порядка;n 1 - memory filter of the middle first order;

r - порядок фильтра.r is the order of the filter.

Данный фильтр, будучи фильтром нижних частот, играет роль звена взвешенного усреднения и обладает уникальным свойством - его импульсная характеристика, в зависимости от выбора порядка фильтра r, аппроксимирует несколько типов распространенных усредняющих окон, обеспечивающих высокое подавление переменных флуктуации входного сигнала /1/, С.130-135, /2/, С.287-297. К этим окнам относятся окна: Дирихле, Бартлетта, Хэмминга, Парзена и Гаусса. На фиг.3 приводится семейство указанных окон, полученных путем вычисления импульсной характеристики фильтра среднего высшего порядка через обратное дискретное преобразование Фурье /1/, С.56, /3/, С.45This filter, being a low-pass filter, plays the role of a weighted averaging link and has a unique property - its impulse response, depending on the choice of filter order r, approximates several types of common averaging windows that provide high suppression of fluctuations in the input signal / 1 /, С. 130-135, / 2 /, S.287-297. These windows include: Dirichlet, Bartlett, Hamming, Parzen and Gauss. Figure 3 shows a family of these windows obtained by calculating the impulse response of a higher order medium filter through the inverse discrete Fourier transform / 1 /, C.56, / 3 /, C.45

Figure 00000004
Figure 00000004

где k - безразмерная линейная частота;where k is the dimensionless linear frequency;

j - мнимая единица;j is the imaginary unit;

N - память фильтра среднего высшего порядка (длительность окна), связанная с параметрами фильтра следующим соотношением:N is the filter memory of a higher order medium (window duration) associated with the filter parameters by the following relation:

N=r· (n1-1)+1,N = r · (n 1 -1) +1,

где N, r, n1 - целые числа.where N, r, n 1 are integers.

N выбрано равным 256. При первом порядке (r=1) импульсная характеристика фильтра среднего аппроксимирует окно Дирихле (естественное окно), при втором - окно Бартлетта, при третьем - окно Хэмминга, при четвертом - Парзена и при пятом - окно Гаусса.N is chosen equal to 256. In the first order (r = 1), the impulse response of the middle filter approximates the Dirichlet window (natural window), in the second - the Bartlett window, in the third - the Hamming window, in the fourth - Parzen and in the fifth - Gaussian window.

Спектры соответствующих окон представлены на фиг.4 и вычислены посредством формулыThe spectra of the corresponding windows are presented in figure 4 and calculated by the formula

Figure 00000005
Figure 00000005

где A(F) - спектр импульсной характеристики фильтра среднего высшего порядка;where A (F) is the spectrum of the impulse response of a medium-order filter;

F - приведенная частота, равная произведению линейной частоты в герцах на длительность окна в секундах /1/, С.128.F is the reduced frequency equal to the product of the linear frequency in hertz and the window duration in seconds / 1 /, С.128.

Из фиг.4 следует, что рассматриваемый фильтр среднего пропускает постоянную составляющую входного сигнала без искажений, а переменные флуктуации подавляет тем сильнее, чем больше частота флуктуации. Это свидетельствует об эквивалентности фильтра среднего высшего порядка усредняющей КИХ-фильтрации. В целях анализа аппроксимирующих свойств фильтра среднего ниже приводится таблица 1, где сведены параметры точных усредняющих окон, взятые на странице 130 прототипа, и параметры их аппроксимаций, вычисленные по спектрам на фиг.4.From figure 4 it follows that the average filter in question passes the constant component of the input signal without distortion, and the fluctuation variable suppresses the stronger, the higher the fluctuation frequency. This indicates the equivalence of the medium-order filter of the average FIR filtering. In order to analyze the approximating properties of the average filter, Table 1 is given below, which summarizes the parameters of the exact averaging windows taken on page 130 of the prototype and the parameters of their approximations calculated from the spectra in Fig. 4.

Из таблицы 1 видно, что фильтры среднего первого, второго и четвертого порядков очень точно аппроксимируют, соответственно, окна Дирихле, Бартлетта и Парзена. Фильтры среднего третьего и пятого порядков, несмотря на то что вид их импульсных характеристик близок к окнам Хэмминга и Гаусса, имеют некоторую ошибку аппроксимации, сохраняя при этом свойства усредняющего КИХ-фильтра. Из таблицы 1 также следует, что с увеличением порядка фильтра среднего параметр hL, уменьшается, а Fh, увеличивается. Это показывает, что подбором порядка, в зависимости от конкретных задач усредняющей КИХ-фильтрации, можно разрешать компромисс между шириной полосы пропускания фильтра (Fh) и подавлением флуктуации за ее пределами (hL).From table 1 it can be seen that the first, second and fourth order average filters very accurately approximate, respectively, the Dirichlet, Bartlett and Parzen windows. Filters of the middle third and fifth orders, despite the fact that the shape of their impulse characteristics are close to the Hamming and Gaussian windows, have some approximation error, while preserving the properties of the averaging FIR filter. From table 1 it also follows that with an increase in the order of the average filter, the parameter h L decreases, and F h increases. This shows that by choosing the order, depending on the specific tasks of averaging FIR filtering, a compromise can be resolved between the filter bandwidth (F h ) and the suppression of fluctuations beyond its limits (h L ).

Способ быстрой усредняющей КИХ-фильтрации на основе процессора базируется на том, что передаточная функция фильтра среднего высшего порядка реализуема без хранения усредняющего окна и использования операций умножения. Для вывода данного способа рассмотрим следующее.The processor-based method of fast FIR averaging filtering is based on the fact that the transfer function of a medium-order filter is feasible without storing the averaging window and using multiplication operations. To output this method, consider the following.

Учитывая, что z-образы выходного и входного сигнала фильтра связаны через передаточную функцию соотношениемGiven that the z-images of the output and input filter signal are connected through the transfer function by the ratio

y[z]=W[z]· x[z],y [z] = W [z] · x [z],

где y[z] - z-образ выходного сигнала фильтра;where y [z] is the z-image of the filter output signal;

x[z] - z-образ входного сигнала фильтра,x [z] is the z-image of the input filter signal,

и раскладывая числитель передаточной функции в бином Ньютона /4/, получимand expanding the numerator of the transfer function in Newton’s bin / 4 /, we obtain

Figure 00000006
Figure 00000006

где С i r - сочетания из r по i, определяемые какwhere c i r - combinations of r by i, defined as

Figure 00000007
Figure 00000007

Далее. Дробь 1/(1-z-1) есть не что иное, как передаточная функция дискретного сумматора. Тогда дробь 1/(1-z-1)r в выражении (7) есть передаточная функция многократного сумматора кратности r, образуемого из последовательного соединения сумматоров в количестве r штук, когда на вход последующего сумматора подается выход предыдущего. Кроме того, выражение z-m1.i есть передаточная функция звена чистого запаздывания на т1-i тактов квантованного времени, которое в зависимости (7) показывает, как разнесены во времени значения выходного сигнала многократного сумматора, используемые для формирования выходного сигнала всего фильтра. На основании сказанного, переходя от z-образов в выражении (7) к оригиналам, получимFurther. The fraction 1 / (1-z -1 ) is nothing but the transfer function of a discrete adder. Then the fraction 1 / (1-z -1 ) r in expression (7) is the transfer function of a multiple adder of multiplicity r, formed from a series connection of adders in the amount of r pieces, when the output of the previous adder is input to the next adder. In addition, the expression z −m1.i is the transfer function of the net delay unit by t 1 −i clock cycles of the quantized time, which, depending on (7), shows how the values of the output signal of the multiple adder used to generate the output signal of the entire filter are separated in time. Based on the foregoing, passing from z-images in expression (7) to the originals, we obtain

Figure 00000008
Figure 00000008

где Sr[n] -многократная сумма выборок входного сигнала х[п] на n-том отсчете квантованного времени;where S r [n] is the multiple sum of samples of the input signal x [n] at the n-th sample of the quantized time;

r - кратность многократной суммы, равная порядку фильтра среднего.r is the multiplicity of a multiple sum equal to the order of the average filter.

Поскольку длительность импульсной характеристики фильтра среднего составляет N отсчетов квантованного времени, процесс взвешенного усреднения выборок входного сигнала может закончиться только при n, равном N-1. Тогда, подставляя в выражение (9) вместо n величину N-1, с учетом зависимости (4), найдемSince the duration of the impulse response of the average filter is N samples of quantized time, the process of weighted averaging of samples of the input signal can end only with n equal to N-1. Then, substituting the quantity N-1 in expression (9) instead of n, taking into account dependence (4), we find

Figure 00000009
Figure 00000009

Заметим, что при i, равном r, аргумент многократной суммы становится отрицательным.Note that for i equal to r, the multiple sum argument becomes negative.

В этом случае ее значение можно считать нулевым и выкинуть из рассмотрения:In this case, its value can be considered zero and thrown out of consideration:

Figure 00000010
Figure 00000010

Делая подстановку (i=r-i) и учитывая свойства сочетаний (С r-i r i r ), выражение (11) преобразуется к более удобному окончательному видуBy substituting (i = ri) and taking into account the properties of the combinations (C ri r = C i r ), expression (11) is transformed to a more convenient final form

Figure 00000011
Figure 00000011

Полученное выражение есть алгоритм способа быстрой усредняющей КИХ-фильтрации на основе процессора. Из него следует, что процесс взвешенного усреднения входного сигнала заключается в накоплении многократной суммы выборок по мере их поступления от АЦП, значение которой фиксируется исключительно для r отсчетов времени с номерами: n1-r, 2n1-r, 3n1-r, и так далее до r• n1-r. Затем, для формирования окончательного результата усреднения, осуществляется однократное суммирование зафиксированных сумм с соответствующими весами: (-1)r-1· C 1 r /n r 1 , (-1)r-3• C 2 r /n r 1 и так далее до С r r /n r 1 . Число указанных весов не зависит от длительности импульсной характеристики фильтра среднего, то есть не зависит от N, и равно его порядку.The resulting expression is an algorithm of the method of fast averaging FIR filtering based on the processor. It follows that the process of weighted averaging of the input signal consists in accumulating a multiple sum of samples as they arrive from the ADC, the value of which is fixed exclusively for r time samples with numbers: n 1 -r, 2n 1 -r, 3n 1 -r, and so on up to r • n 1 -r. Then, to form the final result of averaging, a single summation of the fixed amounts is carried out with the corresponding weights: (-1) r-1 · C 1 r / n r 1 , (-1) r-3 • C 2 r / n r 1 and so on to C r r / n r 1 . The number of these weights does not depend on the duration of the impulse response of the average filter, that is, it does not depend on N, and is equal to its order.

Таким образом, в заявляемом способе усредняющей КИХ-фильтрации обработка выборок в темпе их появления построена только на операциях суммирования и сравнения для определения моментов времени фиксации сумм. Кроме того, усредняющее окно, аппроксимируемое фильтром среднего, явно не присутствует в алгоритме (12), что исключает использования памяти процессора для его хранения. Выигрыш в вычислительной сложности по сравнению с прототипом, за счет исключения операций умножения выборок входного сигнала на усредняющее окно, будет детально рассмотрен в разделе сведений, подтверждающих возможность осуществления изобретения.Thus, in the claimed method of averaging FIR filtering, the processing of samples at the rate of their appearance is based only on the operations of summation and comparison to determine the moments of time for fixing the sums. In addition, the averaging window approximated by the average filter is clearly not present in algorithm (12), which eliminates the use of processor memory for storing it. The gain in computational complexity compared to the prototype, due to the exclusion of operations of multiplying the samples of the input signal by the averaging window, will be examined in detail in the information section confirming the possibility of carrying out the invention.

Перечень фигурList of figures

Фиг.1 - Структурная схема КИХ-фильтра прототипа на базе цифрового вычислительного устройства.Figure 1 - Block diagram of the FIR filter of the prototype based on a digital computing device.

Фиг.2 - Схема реализации способа усредняющей КИХ-фильтрации прототипа с помощью процессора.Figure 2 - Scheme of the implementation of the method of averaging FIR filtering of the prototype using the processor.

Фиг.3 - Семейство усредняющих окон, аппроксимируемых фильтром среднего высшего порядка.Figure 3 - A family of averaging windows approximated by a medium order filter.

Фиг.4 - Спектры усредняющих окон, аппроксимируемых фильтром среднего высшего порядка.Figure 4 - Spectra of averaging windows approximated by a medium order filter.

Фиг.5 - Схема реализации способа быстрой усредняющей КИХ-фильтрации на основе процессора.5 is a diagram of the implementation of the method of fast averaging FIR filtering based on the processor.

Фиг.6 - Вычислительные затраты способа быстрой усредняющей КИХ-фильтрации на основе процессора.6 - Computational costs of the method of fast averaging FIR filtering based on the processor.

Заявляемый способ быстрой усредняющей КИХ-фильтрации на основе процессора осуществим при использовании микропроцессорных элементов: сигнальных микропроцессоров, микроконтроллеров со встроенным АЦП или имеющих возможность ввода двоичного кода от внешнего АЦП. В качестве примера указанных микропроцессорных элементов могут рассматриваться следующие микросхемы зарубежных производителей, используемые в России /5/:The inventive method of fast averaging FIR filtering based on the processor is feasible using microprocessor elements: signal microprocessors, microcontrollers with built-in ADCs or with the ability to enter binary code from an external ADC. The following microcircuits of foreign manufacturers used in Russia / 5 / can be considered as an example of these microprocessor elements:

- микроконтроллер 68НС705В32 семейства НС05 фирмы Motorola, имеющий 8-разрядное многоканальное АЦП, объем постоянной памяти в размере 32 Кбайт и работающий на тактовой частоте 2 МГц;- Motorola 68НС705В32 microcontroller family НС05 from Motorola, having an 8-bit multichannel ADC, the amount of permanent memory of 32 Kbytes and operating at a clock frequency of 2 MHz;

- микроконтроллер M430P325I семейства MSP430 фирмы Texas Instruments, имеющий 14-разрядное или 12-разрядное многоканальное АЦП, объем постоянной памяти в размере 16 Кбайт и работающий на тактовой частоте до 3 МГц;- Microcontroller M430P325I family MSP430 company Texas Instruments, having a 14-bit or 12-bit multi-channel ADC, the amount of permanent memory of 16 KB and operating at a clock frequency of up to 3 MHz;

- микроконтроллер ADuC812 семейства MicroConverter™ фирмы Analog Devices, имеющий 12-разрядное многоканальное АЦП, работающий на тактовой частоте 12 МГц и позволяющий адресовать до 16 Мбайт памяти данных и 64 Кбайт памяти программ;- Microcontroller ADuC812 microcontroller family of Analog Devices company, which has a 12-bit multi-channel ADC, clocked at 12 MHz and allows addressing up to 16 MB of data memory and 64 KB of program memory;

- микроконтроллер Z86C84 семейства Z8 фирмы Zilog, имеющий 8-разрядное многоканальное АЦП, объем постоянной памяти в размере 4 Кбайт и работающий на тактовой частоте 16 МГц;- Zilog microcontroller Z86C84 of the Z8 family, which has an 8-bit multichannel ADC, the amount of read-only memory is 4 KB and operates at a clock frequency of 16 MHz;

- новый микроконтроллер AT Mega603L семейства AVR фирмы ATMEL, имеющий 10-разрядное многоканальное АЦП, объем постоянной памяти в размере 64 Кбайт, оперативной памяти в размере 4 Кбайт и работающий на тактовой частоте 4 МГц.- A new ATEL ATR Mega603L microcontroller from the ATMEL family, featuring a 10-bit multichannel ADC, 64 Kbytes of permanent memory, 4 Kbytes of RAM and 4 MHz clock speed.

Все указанные микроконтроллеры имеют развитую систему внутренних таймеров, позволяющую управлять периодом дискретизации встроенных АЦП.All of these microcontrollers have a developed system of internal timers, which allows you to control the sampling period of the built-in ADCs.

На микроконтроллер отводится роль программного осуществления способа быстрой усредняющей КИХ-фильтрации в соответствии с алгоритмом (12). Последовательное получение выборок входного сигнала с помощью встроенного АЦП синхронизируется внутренним таймером микроконтроллера, задающим период дискретизации Тд. Все вычислительные операции, приходящиеся на одну выборку АЦП, должны вложится по времени в интервал периода дискретизации, который существенно меньше для заявляемого способа усредняющей КИХ-фильтрации по сравнению с прототипом. В целях детализации рассмотрим пример осуществления способа быстрой усредняющей КИХ-фильтрации для фильтра среднего 3-го порядка, аппроксимирующего окно Хэмминга (фиг.3).The role of software implementation of the fast averaging FIR filtering method in accordance with the algorithm (12) is assigned to the microcontroller. Sequential acquisition of samples of the input signal using the built-in ADC is synchronized by the internal timer of the microcontroller, specifying the sampling period T d . All computational operations falling on one ADC sample should be time-invested in the interval of the sampling period, which is significantly less for the proposed method of averaging FIR filtering in comparison with the prototype. For the sake of detail, let us consider an example of the implementation of the fast averaging FIR filtering method for a third-order medium filter approximating a Hamming window (Fig. 3).

Пусть длительность импульсной характеристики фильтра составляет 256 отсчета квантованного времени, когда номера отсчетов n могут изменяться от 0 до 255. На основании выражения (4) легко установить, что параметр n1 должен иметь значение 86. Только в этом случае N=3• (86-1)+1=256. Подставляя числовые значения в (12), с учетом сочетаний (8) получим алгоритм способа быстрой усредняющей КИХ-фильтрацииLet the filter impulse response duration be 256 samples of the quantized time, when the numbers of samples n can vary from 0 to 255. Based on expression (4), it is easy to establish that parameter n 1 must have the value 86. Only in this case N = 3 • (86 -1) + 1 = 256. Substituting the numerical values in (12), taking into account combinations (8), we obtain the algorithm of the fast averaging FIR filtering method

Figure 00000012
Figure 00000012

где S3[n] - троекратная сумма выборок входного сигнала на n-том отсчете квантованного времени.where S 3 [n] is three times the sum of samples of the input signal at the n-th sample of the quantized time.

Как видно, фиксация сумм требуется для n с номерами 83, 169 и 255.As you can see, fixing the sums is required for n with numbers 83, 169 and 255.

На фиг.5 представлена схема осуществления алгоритма (13) на основе процессора.Figure 5 presents a diagram of the implementation of the algorithm (13) based on the processor.

1) Перед началом цикла усредняющей КИХ-фильтрации в блоке 12 обнуляются: накопитель суммы S1, накопитель двукратной суммы S2, накопитель троекратной суммы S3, а также счетчик квантованного времени n;1) Before the start of the averaging FIR filtering cycle in block 12, the following are reset: the accumulator of the sum S 1 , the accumulator of the double sum S 2 , the accumulator of the triple sum S 3 , and also the quantized time counter n;

2) Далее в блоке 13 осуществляется получение текущей выборки АЦП с последующим наращиванием суммы, двукратной суммы и троекратной суммы в блоках 14, 15 и 16 соответственно;2) Next, in block 13, the current ADC sample is obtained with the subsequent increase in the amount, twofold sum and triple sum in blocks 14, 15 and 16, respectively;

3) После наращивания троекратной суммы следует система проверок, состоящая из блоков 17, 18, 19, которая в начале полностью отрабатывает по ветвям "Нет", и цикл усредняющей КИХ-фильграции переходит к блоку 20;3) After building up the triplicate amount, a verification system follows, consisting of blocks 17, 18, 19, which at the beginning completely fulfills the “No” branches, and the cycle of averaging FIR filtering proceeds to block 20;

4) В блоке 20 инкрементируется счетчик квантованного времени n, после чего все повторяется, начиная со второго пункта - происходит непрерывное получение выборок АЦП и накопление троекратной суммы;4) In block 20, the counter of the quantized time n is incremented, after which everything is repeated, starting from the second paragraph — the ADC samples are continuously obtained and the triplicate amount is accumulated;

5) Процесс накопления троекратной суммы осуществляется до тех пор, пока блок 17 не идентифицирует момент равенства счетчика n числу 83. Этот случай соответствует событию, когда троекратная сумма приняла значение S3[83]. Поэтому блок 17 отрабатывает по ветви "Да" для сохранения ее значения в фиксаторе А в блоке 21;5) The process of accumulating a three-fold sum is carried out until block 17 identifies the moment the counter n is equal to the number 83. This case corresponds to the event when the three-fold sum assumes the value S 3 [83]. Therefore, block 17 fulfills the branch "Yes" to save its value in the latch A in block 21;

6) Далее процесс накопления троекратной суммы продолжается до момента равенства n числу 169, что сопровождается отработкой по ветви "Да" блока 18. В этом случае троекратная сумма имеет значение S3[169], которое сохраняется в фиксаторе В в блоке 22;6) Next, the process of accumulating a three-fold sum continues until the number n is equal to 169, which is accompanied by working off the block 18 on the Yes branch. In this case, the three-fold sum has the value S 3 [169], which is stored in the latch B in block 22;

7) После этого процесс накопления троекратной суммы вновь продолжается до тех пор, пока блок 19 не идентифицирует момент равенства счетчика n числу 255. Этот случай соответствует завершению цикла усредняющей КИХ-фильтрации, когда квантованное время принимает значение N Тд, а троекратная сумма становится равной S3[255];7) After this, the process of accumulating a triple sum continues again until block 19 identifies the moment the counter n is equal to 255. This case corresponds to the end of the averaging FIR filtering cycle, when the quantized time takes the value N T d , and the triple sum becomes equal S 3 [255];

8) После завершения цикла усредняющей КИХ-фильтрации и сохранения последнего значения троекратной суммы в фиксаторе С в блоке 23 остается однократно вычислить результат взвешенного усреднения, используя содержимое фиксаторов, что и осуществляется в соответствии с формулой (13) в блоке 24.8) After completing the cycle of averaging FIR filtering and storing the last value of the triple sum in the clamp C in block 23, it remains to calculate the result of the weighted averaging once using the contents of the clamps, which is done in accordance with formula (13) in block 24.

Таким образом, в заявляемом способе быстрой усредняющей КИХ-фильтрации на основе процессора обработка выборок входного сигнала в темпе их появления построена только на операциях суммирования и сравнения. Кроме того, усредняющее окно, аппроксимируемое фильтром среднего, явно не присутствует в алгоритме способа, что исключает использования элементов памяти для его хранения. Выигрыш в вычислительной сложности по сравнению с прототипом за счет исключения операций умножения выборок входного сигнала на усредняющее окно рассмотрим детальнее.Thus, in the inventive method of fast averaging FIR filtering based on the processor, the processing of samples of the input signal at the rate of their appearance is based only on the operations of summation and comparison. In addition, the averaging window approximated by the average filter is clearly not present in the method algorithm, which excludes the use of memory elements for storing it. The gain in computational complexity compared to the prototype due to the exclusion of operations of multiplying the samples of the input signal by the averaging window is considered in more detail.

Вычислительные затраты, приходящиеся на каждую выборку входного сигнала, определяются блоками 14, 15, 16, 17, 18. Блок проверки момента достижения конца цикла КИХ-фильтрации 19 и блок инкремента счетчика квантованного времени 20 в рассмотрение не входят, так как присутствуют и в алгоритме обработки выборок АЦП прототипа.The computational costs attributable to each sample of the input signal are determined by blocks 14, 15, 16, 17, 18. The unit for checking the moment of reaching the end of the FIR filtering cycle 19 and the increment unit of the quantized time counter 20 are not considered, since they are also present in the algorithm processing prototype ADC samples.

Пусть разрядность выборки АЦП составляет 16 бит (знаковых). Для того чтобы не было переполнения многократных сумм при 256 суммированиях, в рассматриваемом алгоритме сумма должна иметь разрядность не менее 24 бита, двукратная сумма - не менее 31 бита и троекратная - не менее 37 бит. При использовании процессора с 16-разрядной арифметикой указанные суммы вычисляются соответственно за 2, 2 и 3 операции суммирования. Таким образом, с учетом того что операции сравнения в блоках 17 и 18 обычно эквивалентны по затратам трем, четырем операциям суммирования, получается, что вычислительные затраты алгоритма на фиг.5 составляют 16 эквивалентных суммирований на каждую выборку АЦП.Let the bit capacity of the ADC sample is 16 bits (sign). In order to avoid overflow of multiple sums with 256 sums, in the considered algorithm, the sum should have a bit capacity of at least 24 bits, a double sum of at least 31 bits and a triple sum of at least 37 bits. When using a processor with 16-bit arithmetic, the indicated amounts are calculated for 2, 2, and 3 summing operations, respectively. Thus, taking into account the fact that the comparison operations in blocks 17 and 18 are usually equivalent in cost to three or four summation operations, it turns out that the computational costs of the algorithm in Fig. 5 are 16 equivalent summations for each ADC sample.

В прототипе требуется осуществлять умножение каждой выборки на весовой множитель, разрядность которого обычно не ниже разрядности АЦП. Программное умножение 16-разрядной выборки на 16-разрядный весовой множитель требует, как минимум, шестнадцать 32-разрядных сдвигов и суммировании, каждые из которых эквивалентны двум операциям суммирования. Кроме того, в цикле сдвигов и суммировании требуется осуществлять, как минимум, две операции сравнения для идентификации состояния очередного бита множителя и проверки конца цикла, каждая из которых также эквивалента трем суммированиям. Из этого следует, что вычислительные затраты на программное умножение составляют около 160 эквивалентных суммировании на каждую выборку АЦП, что на порядок больше, нежели в алгоритме на фиг.5.In the prototype, it is required to multiply each sample by a weight factor, the capacity of which is usually not lower than the capacity of the ADC. Programmatically multiplying a 16-bit sample by a 16-bit weighting factor requires at least sixteen 32-bit shifts and summing, each of which is equivalent to two summing operations. In addition, in a shift and sum cycle, at least two comparison operations are required to identify the state of the next bit of the multiplier and check the end of the cycle, each of which is also equivalent to three sums. From this it follows that the computational cost of software multiplication is about 160 equivalent to the summation for each ADC sample, which is an order of magnitude greater than in the algorithm in figure 5.

На фиг.6 представлены результаты численных экспериментов на ЭВМ по определению вычислительных затрат способа быстрой усредняющей КИХ-фильтрации на основе процессора для различных порядков фильтра среднего. Видно, что число эквивалентных суммирований Z, приходящихся на одну выборку АЦП, не столько зависит от объема обрабатываемых выборок N, сколько от порядка фильтра среднего r. На практике для обеспечения высокого подавления переменных флуктуации входного сигнала, пятого порядка фильтра (окно Гаусса) более чем достаточно, при этом объем вычислительных затрат остается существенно ниже, чем в прототипе, для которого на фиг.5 он показан пунктиром.Figure 6 presents the results of numerical computer experiments to determine the computational cost of a fast averaging FIR filtering method based on a processor for various orders of the average filter. It can be seen that the number of equivalent summations Z per one ADC sample does not so much depend on the volume of processed samples N, but on the order of the average filter r. In practice, to ensure high suppression of variable fluctuations in the input signal, a fifth-order filter (Gaussian window) is more than enough, while the amount of computational cost remains significantly lower than in the prototype, for which it is shown in dashed lines in Fig. 5.

Источники информацииSources of information

1. Гутников В.С. Фильтрация измерительных сигналов. - Л.: Энергоатомиздат. Ленингр. отд-ние, 1990. - 192 с.: ил. (прототип).1. Gutnikov V.S. Filtering measuring signals. - L .: Energoatomizdat. Leningra. Otdel., 1990 .-- 192 pp., ill. (prototype).

2. Макс Ж. Методы и техника обработки сигналов при физических измерениях: В 2-х томах. Пер. с франц. - М.: Мир, 1983. - Т.1, С.287-297.2. Max J. Methods and techniques for processing signals in physical measurements: In 2 volumes. Per. with french - M .: Mir, 1983.- T.1, S.287-297.

3. Арутюнов П.А. Теория и применение алгоритмических измерений. - М.: Энергоатомиздат, 1990. - С.45.3. Arutyunov P.A. Theory and application of algorithmic measurements. - M .: Energoatomizdat, 1990. - P.45.

4. Бронштейн И.Н., Семендяев К.А. Справочник по математике. М., 1967. - С.163-164.4. Bronstein I.N., Semendyaev K.A. Math reference. M., 1967. - S.163-164.

5. Современные микроконтроллеры: Архитектура, средства проектирования, примеры применения, ресурсы сети Интернет. © "Телесистемы". Под ред. Коршуна И.В.; Составление, пер. с англ. и литературная обработка Горбунова Б.Б. - М.: Издательство "Аким", 1998. - 272 с., ил.5. Modern microcontrollers: Architecture, design tools, application examples, Internet resources. © "Telesystems". Ed. Korshun I.V .; Compilation, trans. from English and literary processing Gorbunova BB - M .: Akim Publishing House, 1998. - 272 p., Ill.

Figure 00000013
Figure 00000013

Claims (1)

Способ быстрой усредняющей КИХ-фильтрации на основе процессора, заключающийся в том, что с помощью аналого-цифрового преобразователя получают выборки входного сигнала, которые подвергают взвешенному усреднению, последовательно во времени, с помощью процессора, отличающийся тем, что накапливают многократную сумму выборок входного сигнала, значение которой фиксируют для r моментов квантованного времени с номерами n1 - r , 2n1-r, 3n1 - r, и так далее до r • n1 - r , где r - кратность накапливаемой суммы, n1 - целый параметр, связанный с общим объёмом суммируемых выборок N соотношением:A method of fast averaging FIR filtering based on a processor, which consists in the fact that using an analog-to-digital converter, samples of the input signal are obtained, which are subjected to weighted averaging, sequentially in time, using a processor, characterized in that they accumulate a multiple sum of samples of the input signal, the value of which is fixed for r moments of quantized time with numbers n 1 - r, 2n 1 -r, 3n 1 - r, and so on up to r • n 1 - r, where r is the multiplicity of the accumulated sum, n 1 is a whole parameter related with the total amount of sum sampling N by the ratio:
Figure 00000014
Figure 00000014
затем зафиксированные значения многократной суммы однократно суммируют с целыми весами в соответствии с формулой:then the fixed values of the multiple amount are summed once with whole weights in accordance with the formula:
Figure 00000015
Figure 00000015
где у - результат взвешенного усреднения выборок аналого-цифрового преобразователя;where y is the result of weighted averaging of samples of the analog-to-digital converter; Sr[i·n1-r] - зафиксированные значения многократной суммы кратности r;S r [i · n 1 -r] - fixed values of multiple sums of multiplicity r; С i r - целые веса, определяемые как сочетания из r по i:FROM i r - integer weights, defined as combinations of r by i:
RU2002111508/09A 2002-04-29 2002-04-29 Method for fast averaging fir filtering on basis of processor RU2242792C2 (en)

Priority Applications (1)

Application Number Priority Date Filing Date Title
RU2002111508/09A RU2242792C2 (en) 2002-04-29 2002-04-29 Method for fast averaging fir filtering on basis of processor

Applications Claiming Priority (1)

Application Number Priority Date Filing Date Title
RU2002111508/09A RU2242792C2 (en) 2002-04-29 2002-04-29 Method for fast averaging fir filtering on basis of processor

Publications (2)

Publication Number Publication Date
RU2002111508A RU2002111508A (en) 2003-11-10
RU2242792C2 true RU2242792C2 (en) 2004-12-20

Family

ID=34387056

Family Applications (1)

Application Number Title Priority Date Filing Date
RU2002111508/09A RU2242792C2 (en) 2002-04-29 2002-04-29 Method for fast averaging fir filtering on basis of processor

Country Status (1)

Country Link
RU (1) RU2242792C2 (en)

Citations (3)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
EP1168615A1 (en) * 2000-06-27 2002-01-02 Texas Instruments Incorporated Transpose FIR filter architecture
US20020010727A1 (en) * 1998-09-25 2002-01-24 Gregory A. Hughes Area efficient fir filter with programmable coefficients
RU2178949C2 (en) * 1996-10-04 2002-01-27 Моторола, Инк. Filtering coprocessor

Patent Citations (3)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
RU2178949C2 (en) * 1996-10-04 2002-01-27 Моторола, Инк. Filtering coprocessor
US20020010727A1 (en) * 1998-09-25 2002-01-24 Gregory A. Hughes Area efficient fir filter with programmable coefficients
EP1168615A1 (en) * 2000-06-27 2002-01-02 Texas Instruments Incorporated Transpose FIR filter architecture

Non-Patent Citations (1)

* Cited by examiner, † Cited by third party
Title
ГУТНИКОВ В.С. Фильтрация измерительных сигналов. - Л.: Энергоатомиздат, Ленинградское отделение, 1990, с.160-163. *

Similar Documents

Publication Publication Date Title
Portnoff Implementation of the digital phase vocoder using the fast Fourier transform
Chan et al. Analysis of quantization errors in the direct form for finite impulse response digital filters
Bomar Finite wordlength effects
US11263293B2 (en) Digital sample rate conversion
Dixit et al. IIR filters using Xilinx System Generator for FPGA implementation
RU2242792C2 (en) Method for fast averaging fir filtering on basis of processor
Ferdi Impulse invariance-based method for the computation of fractional integral of order 0< α< 1
CN114142830A (en) FPGA (field programmable Gate array) implementation method of full-precision low-pass IIR (Infinite Impulse response) filter
Tymchenko et al. Efficient calculation methods of subtraction signals convolution
CN107193784B (en) Implementation method and system of sinc interpolation with high precision and low hardware complexity
Barsainya et al. Minimum multiplier implementation of a comb filter using lattice wave digital filter
Anastassopoulos et al. Method for designing half-band delta-modulation FIR filters
Bryukhanov A method of analysis of periodic processes in nonautonomous discrete-time systems with quantization
Ahmed et al. FPGA based implementation of a multiplier-less fir filter for ECG signal processing
RU64798U1 (en) ADAPTIVE MULTI-SCALE DECOMPOSITION DEVICE
CN100561863C (en) Digital recursive filter device
Ali et al. Multirate FIR Filter Using Radix Sort Booth Algorithm In Xilinx System Generator
Xu et al. FPGA-based solution for real-time tracking of time-varying harmonics and power disturbances
Bailey et al. Simulation of filter structures for fixed-point implementation
Pesetskaya et al. Mathematical simulation of digital filters with finite pulse characteristics
Meyer-Baese Infinite impulse response (IIR) digital filters
Sakib et al. Use of single bin Fourier transform algorithm for high speed tone detection and parallel processing
Goldberg A continuous recursive DFT analyzer--The discrete coherent memory filter
Mihov et al. FPGA Implementation of Combined High-pass and Notch Filter
Pinheiro et al. Fixed-point implementation of infinite impulse response notch filters

Legal Events

Date Code Title Description
MM4A The patent is invalid due to non-payment of fees

Effective date: 20050430