# Filtering values, any suggestions for a more efficient method ?

#### ParysPommy

Joined Sep 8, 2019
2
I’m putting together low cost, low(ish) tech alarms for small motorbikes and scooters. This is the first uP project I’ve tackled for a long time. Most of my time has been spent working with PLC systems in ladder logic, VB , and a language similar to Pascal. I’m using a basic compiler for the pic program

The design uses a PIC12F675 and a tilt / vib sensor connected to the external interrupt (GP2).

The program detects tampering as follows: The ISR increments a 16 bit variable when triggered by the vib sensor, the software monitors the ISR once a second. If the counts exceed a set point the siren is ‘beeped’ as a warning. A 4 element word array stores the ISR variable value for the last few seconds. Each second the array contents are shuffled up one element and the latest ISR variable value is moved to the lowest array element. Next, a running average for the array is calculated; if it exceeds a set point the alarm is triggered.

The idea of the running average is to filter single large bumps yet trigger reliably if moved for a few consecutive seconds.

My logic works nicely, but I’ve only got half a dozen bytes of ram free. I’m going through the general logic to free up a bit of RAM but I’m stuck with thinking up a more efficient method of making the software immune to short sharp bumps

Does anyone have any suggestions for a more efficient approach to software filtering?

Cheers

Malcolm

#### MrChips

Joined Oct 2, 2009
24,982
Welcome to AAC!

Here is a simple algorithm for calculating a moving average over N-points.

Create a holding register named SUM.
The data type of SUM must be larger than N-times each data point.
Create an average value named AVG.

1) Acquire a data point X.
2) Accumulate SUM = SUM + (X - AVG)
3) Calculate the average value AVG = SUM / N

N can be any integer value. In embedded systems, N is a power of 2 for computational efficiency.

#### joeyd999

Joined Jun 6, 2011
4,477
A simple 1st order FIR (equivalent to an analog RC filter):

Y(n) = aX(n) + (1-a)Y(n-1)

The filter coefficient a is fractional (you'll have to do some fixed point math) and smaller a is more filtering with slower response.

#### ParysPommy

Joined Sep 8, 2019
2
Many thanks for the suggestions.
I'll give them a shot in the evening or so.
Cheers
Malcolm

#### MrChips

Joined Oct 2, 2009
24,982
Note that the methods suggested in posts #2 and #3 are the same.

The fractional value a is the same as 1/N.