2 #include <hardware/sensors.h>
8 void add_to_buff(struct circ_buff* circ_buff, float val)
10 if (circ_buff->count < circ_buff->size)
12 circ_buff->buff[circ_buff->count] = val;
17 circ_buff->idx = circ_buff->idx % circ_buff->size;
18 circ_buff->buff[circ_buff->idx] = val;
23 static unsigned int partition(float* list, unsigned int left,
24 unsigned int right, unsigned int pivot_index)
27 unsigned int store_index = left;
29 float pivot_value = list[pivot_index];
31 // swap list[pivotIndex] and list[right]
32 aux = list[pivot_index];
33 list[pivot_index] = list[right];
36 for (i = left; i < right; i++)
38 if (list[i] < pivot_value)
40 // swap list[store_index] and list[i]
41 aux = list[store_index];
42 list[store_index] = list[i];
47 //swap list[right] and list[store_index]
49 list[right] = list[store_index];
50 list[store_index] = aux;
54 /* http://en.wikipedia.org/wiki/Quickselect */
55 float median(float* queue, unsigned int size)
57 unsigned int left = 0;
58 unsigned int right = size - 1;
59 unsigned int pivot_index;
60 unsigned int median_index = (right / 2);
63 memcpy(temp, queue, size * sizeof(float));
65 /* If the list has only one element return it */
69 while (left < right) {
70 pivot_index = (left + right) / 2;
71 pivot_index = partition(temp, left, right, pivot_index);
72 if (pivot_index == median_index)
73 return temp[median_index];
74 else if (pivot_index > median_index)
75 right = pivot_index - 1;
77 left = pivot_index + 1;
83 void denoise_median(struct sensors_event_t* data, struct sensor_info_t* info)
88 struct filter* f_data = (struct filter*) info->filter;
96 add_to_buff(f_data->x_buff, x);
97 add_to_buff(f_data->y_buff, y);
98 add_to_buff(f_data->z_buff, z);
100 x = median(f_data->x_buff->buff, f_data->x_buff->count);
101 y = median(f_data->y_buff->buff, f_data->y_buff->count);
102 z = median(f_data->z_buff->buff, f_data->z_buff->count);