Mozzi  version v2.0
sound synthesis library for Arduino
DCfilter.h
1 /*
2  * DCfilter.h
3  *
4  * This file is part of Mozzi.
5  *
6  * Copyright 2012-2024 Tim Barrass and the Mozzi Team
7  *
8  * Mozzi is licensed under the GNU Lesser General Public Licence (LGPL) Version 2.1 or later.
9  *
10  */
11 
12 #ifndef DCFILTER_H
13 #define DCFILTER_H
14 
15 /*
16 tb2010 adapted from:
17 robert bristow-johnson, DSP Trick: Fixed-Point DC Blocking Filter with Noise-Shaping
18 http://www.dspguru.com/book/export/html/126
19 
20 y[n] = x[n] - x[n-1] + a * y[n-1]
21 
22 Where y[n] is the output at the current time n, and x[n] is the input at the current time n.
23 
24 also, see DC Blocker Algorithms, http://www.ingelec.uns.edu.ar/pds2803/materiales/articulos/04472252.pdf
25  */
26 
27 /**
28 A DC-blocking filter useful for highlighting changes in control signals.
29 The output of the filter settles to 0 if the incoming signal stays constant. If the input changes, the
30 filter output swings to track the change and eventually settles back to 0.
31 */
32 class DCfilter
33 {
34 public:
35 /**
36 Instantiate a DC-blocking filter.
37 @param pole sets the responsiveness of the filter,
38 how long it takes to settle to 0 if the input signal levels out at a constant value.
39 */
40  DCfilter(float pole):acc(0),prev_x(0),prev_y(0)
41  {
42  A = (int)(32768.0*(1.0 - pole));
43  }
44 
45 /* almost original
46  // timing: 20us
47  int next(int x)
48  {
49  setPin13High();
50  acc -= prev_x;
51  prev_x = (long)x<<15;
52  acc += prev_x;
53  acc -= A*prev_y;
54  prev_y = acc>>15; // quantization happens here
55  int filtered = (int)prev_y;
56  // acc has y[n] in upper 17 bits and -e[n] in lower 15 bits
57  setPin13Low();
58  return filtered;
59  }
60  */
61 
62  /**
63  Filter the incoming value and return the result.
64  @param x the value to filter
65  @return filtered signal
66  */
67  // timing :8us
68  inline
69  int next(int x)
70  {
71  acc += ((long)(x-prev_x)<<16)>>1;
72  prev_x = x;
73  acc -= (long)A*prev_y; // acc has y[n] in upper 17 bits and -e[n] in lower 15 bits
74  prev_y = (acc>>16)<<1; // faster than >>15 but loses bit 0
75  if (acc & 32784) prev_y += 1; // adds 1 if it was in the 0 bit position lost in the shifts above
76  return prev_y;
77  }
78 
79 private:
80  long acc;
81  int prev_x, prev_y,A;
82 };
83 
84 /**
85 @example 05.Control_Filters/DCFilter/DCFilter.ino
86 This example demonstrates the DCFilter class.
87 */
88 
89 #endif // #ifndef DCFILTER_H