-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathmovingaveragefilter.ts
67 lines (62 loc) · 2.3 KB
/
movingaveragefilter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
namespace automation {
/**
* A moving average filter
*/
//% fixedInstances
export class MovingAverageFilter {
private length: number;
private values: number[];
private insertion: number;
private sum: number;
constructor() {
this.setLength(5);
}
/**
* Sets the number of samples in the filter
* @param length number of samples in the moving average filter
*/
//% blockId=automationMASetLength block="set %filter|length to %length"
//% group="Filters" blockGap=8
setLength(length: number) {
this.length = length >> 0;
this.values = undefined;
this.insertion = 0;
this.sum = 0;
}
/**
* Adds a new value to the filter and computes the filtered value
* @param newValue
*/
//% blockId=automationMAFilter block="%filter|filter %newValue"
//% group="Filters" blockGap=8
filter(newValue: number): number {
// no filtering!
if (this.length <= 1) return newValue;
// initialize data with the current new value
if (!this.values) {
for(let i = 0; i < this.length; ++i) {
this.values[i] = newValue;
}
this.sum = newValue * this.length;
}
// remove previous value
const oldValue = this.values[this.insertion];
// swap a value in place
this.values[this.insertion] = newValue;
// update sum
this.sum += newValue - oldValue;
// update index
this.insertion = (this.insertion + 1) % this.length;
// compute average
return this.sum / this.length;
}
}
//% fixedInstance block="moving average filter 1"
export const movingAverageFilter1 = new MovingAverageFilter();
//% fixedInstance block="moving average filter 2"
export const movingAverageFilter2 = new MovingAverageFilter();
//% fixedInstance block="moving average filter 3"
export const movingAverageFilter3 = new MovingAverageFilter();
//% fixedInstance block="moving average filter 4"
export const movingAverageFilter4 = new MovingAverageFilter();
}