.H
#ifndef __FILTER_H
#define __FILTER_H
typedef unsigned char uint8_t;
typedef unsigned short int uint16_t;
typedef unsigned int uint32_t;
#define MAX_RANGE 10
typedef struct filter{
float av_x;
float data_y[MAX_RANGE];
float k_data[MAX_RANGE];
float direction;
float range;
float av_y;
uint16_t w;
}s_filter_t;
float filter_process(float new_x ,float new_y);
#endif
.C
#include "filter.h"
#include "stdio.h"
#define kal_Q 0.0001
#define kal_R 0.011
s_filter_t g_filter ;
uint8_t first = 0;
float Kalman(float measure,uint8_t op_flg);
float Kalman(float measure,uint8_t op_flg)
{
float x_mid,kg,p_mid;
static float x_last = 0,p_last = 0;
float x_now,p_now;
if(op_flg)
{
x_mid = x_last;
p_mid = p_last + kal_Q;
kg = p_mid / (p_mid + kal_R);
x_now = x_mid + kg * (measure - x_mid);
p_now = (1 - kg)*p_mid;
p_last = p_now;
x_last = x_now;
}
else
{
x_last = measure;
p_last = kal_Q;
}
return x_now;
}
float filter_process(float new_x ,float new_y){
uint8_t i = 0;
float temp = 0;
float rtn = 0;
if(first < MAX_RANGE){
g_filter.av_x = new_x;
g_filter.data_y[first] = new_y;
g_filter.direction = 0;
g_filter.range = 1;
g_filter.av_y = 0;
g_filter.w = 10;
first ++ ;
Kalman(new_y, 0);
return new_y;
}
if(new_y > (g_filter.av_y + g_filter.range)){
new_y = g_filter.av_y + g_filter.range;
}
if(new_y < (g_filter.av_y - g_filter.range)){
new_y = g_filter.av_y - g_filter.range;
}
for(i = 0;i<(MAX_RANGE-1);i++){
g_filter.data_y[i] = g_filter.data_y[i+1];
}
g_filter.av_x = new_x;
g_filter.data_y[MAX_RANGE-1] = new_y;
for(i = 0; i < (MAX_RANGE - 1) ;i++){
g_filter.k_data[i] = (g_filter.data_y[i+1] - g_filter.data_y[i])/(g_filter.av_x);
}
g_filter.av_y = 0;
for( i = 0;i<MAX_RANGE;i++){
temp += g_filter.k_data[i];
g_filter.av_y += g_filter.data_y[i];
}
g_filter.av_y = g_filter.av_y/MAX_RANGE;
g_filter.direction = temp / MAX_RANGE;
g_filter.av_y = Kalman(g_filter.av_y, 1);
rtn = (g_filter.av_x * g_filter.direction) + g_filter.av_y;
return rtn;
}
|