﻿

# Exponential Filter

Jan 8th, 2021
842
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. /* Exponential Filter for sound sampling
2.  *
3.  *  This allows slower decay of the signal. Best used with floating point arithmetic.
4.  *
5.  *  Steps are:
6.  *
7.  *  Get a 10 bit sample
8.  *  Remove background noise
9.  *  Adjust gain
10.  *  An 8 bit filter
11.  *  Convert 8 bit filter to floating point
12.  *  Apply filter to adjusted gain
13.  *  You get resultant signal.
14.  *
15.  */
16.
17.
18. float micLev = 0.0;
19. int sample;
20. int sampleAdj;
21.
22. // Floating exponential filter
23. float expAdjF;
24. uint8_t weighting = 128;
25. float weightingF = 0.02;                       // Need to translate 0-255 to a reasonable floating point range.
26.
27.
28. uint8_t soundSquelch = 5;        // Adjustable squelch.
29. uint8_t sampleGain   = 10;        // Adjustable gain.
30.
31. #define MIC_PIN A5
32.
33.
34. void setup() {
35.   Serial.begin(115200);
36.   analogReference(EXTERNAL);
37. }
38.
39.
40. void loop() {
41.
42.   long    micIn;
43.
44.   micIn = analogRead(MIC_PIN);
45.
46.   micLev = ((micLev * 31) + micIn) / 32;          // Smooth it out over the last 32 samples for automatic centering.
47.   micIn -= micLev;                                // Let's center it to 0 now
48.   micIn = abs(micIn);                             // And get the absolute value of each sample
49.
50.
51.   // Translate uint8_t weighting to a floating point value.
52.
53.   weightingF = (float)(weighting+1)/500.0;           // Limits should be .002 to .512
54.
55.
56.
57.
58. // Squelching and smoothing of an analog signal for volume reactive routines.
59. //Using a ternary operator, the resultant sample is either 0 or it's a bit smoothed out with the last sample.
60.   sample = (micIn <= soundSquelch) ? 0 : (sample * 3 + micIn) / 4;
61.
62. // Adjust the gain.
63.   sampleAdj = sample * sampleGain / 40 + sample / 16;
64.
65. // Floating exponential filter weighting.
66.   expAdjF = (weightingF * (float)sampleAdj + (1.0-weightingF) * expAdjF);
67.
68.
69.     Serial.print("0:"); Serial.print(0);
70. //  Serial.print(",micIn:"); Serial.print(micIn);
71. //  Serial.print(",sample:"); Serial.print(sample);
72.   Serial.print(",sampleAdj:"); Serial.print(sampleAdj);
73.   Serial.print(",expadjF:"); Serial.print(expAdjF);
74.   Serial.print(",weightingF:"); Serial.print(weightingF,3);
75.
76. //  Serial.print(",Max:"); Serial.print(255);
77. //  Serial.print(",Min:"); Serial.print(-160);
78.   Serial.println(" ");
79.
80.
81. /*  Serial.print("sampleAdj:\t"); Serial.print(sampleAdj);
82.   Serial.print("Max:500");Serial.print(512);
83.   Serial.print("Min:0");Serial.println(" ");
84. */
85.
86. }
RAW Paste Data