From f0397a117fb7f6a5fb6b09f514fadb69fc5c2575 Mon Sep 17 00:00:00 2001 From: "Robin P. Clark" Date: Mon, 29 Jul 2013 12:35:04 +0100 Subject: [PATCH] filtering low pass, naive implementation compared to up-binary-scaled --- embedded_c_book/fo_filter/fo_filter.c | 69 +++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 embedded_c_book/fo_filter/fo_filter.c diff --git a/embedded_c_book/fo_filter/fo_filter.c b/embedded_c_book/fo_filter/fo_filter.c new file mode 100644 index 0000000..01b752c --- /dev/null +++ b/embedded_c_book/fo_filter/fo_filter.c @@ -0,0 +1,69 @@ +#include + +/* + * compile with: gcc fo_filter.c -o fo_filter + * run as : $ ./fo_filter + * + * shows how the standard lp first order filter, give a steady signal + * truncates it and gives a low result + * + */ +short int threeup_filter, pa2_an2; +short int naive_filter; +double fp; + +#define INT16 short int +INT16 filter16(INT16 var, int depth); +#define ADRES 0x1FC + +main() +{ + + int i; + INT16 var,fvar; + + var = ADRES; + + for (i = 0; i < 150; i++) { + + fp = (fp * 7.0 + (double) ADRES) / 8.0; + + naive_filter = (naive_filter * 7 + ADRES) / 8; // old filter + + threeup_filter = (((threeup_filter << 3) - threeup_filter) >> 3) + ADRES; + + fvar = filter16(var,3); + + printf(" iteration: %d naive_filter = %x threeup_filter = %x fvar = %x fp = %lf\n", i, naive_filter, threeup_filter, fvar, fp); + } +} + + + + + +#define BINARY_FILTER_SCALE 8 +/* with BINARY_FILTER_SCALE set to 8, depth valid between 2 and 7 */ +/* with a depth of 2 what we are saying is + * * result = (old_result * 3.0 + new_val ) / 4.0) + * * with a depth of 3 + * * result = (old_result * 7.0 + new_val ) / 8.0) + * * */ +INT16 filter16(INT16 var, int depth) +{ + + long v = var, v2; + static long oldv; + + printf(" v = %lx oldv = %lx: ", v, oldv); + v <<= BINARY_FILTER_SCALE; // scale up + printf(" v = %lx : ", v); + v2 = (oldv << depth) - oldv + v; + v2 >>= depth; + oldv = v2; + printf(" v = %lx oldv = %lx ", v, oldv); + + return (v2 >> BINARY_FILTER_SCALE); + + +}