ff543cc43ec8916c0c5475f5246fd43cbb5054d5
[fw/altos] / src / kernel / ao_microkalman.c
1 /*
2  * Copyright © 2013 Keith Packard <keithp@keithp.com>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
17  */
18
19 #ifndef AO_FLIGHT_TEST
20 #include <ao.h>
21 #endif
22 #include <ao_micropeak.h>
23
24 #define FIX_BITS        16
25
26 #define to_fix_v(x) ((int16_t) ((x) * 65536.0 + 0.5))
27 #define to_fix_k(x) ((int32_t) ((x) * 65536.0 + 0.5))
28 #define from_fix8(x)    ((x) >> 8)
29 #define from_fix(x)     ((x) >> 16)
30 #define fix8_to_fix_v(x)        ((x) << 8)
31 #define fix16_to_fix8(x)        ((x) >> 8)
32
33 #include <ao_kalman.h>
34
35 /* Basic time step (96ms) */
36 #define AO_MK_STEP      to_fix_v(0.096)
37 /* step ** 2 / 2 */
38 #define AO_MK_STEP_2_2  to_fix_v(0.004608)
39
40 uint32_t        ao_k_pa;                /* 24.8 fixed point */
41 int32_t         ao_k_pa_speed;          /* 16.16 fixed point */
42 int32_t         ao_k_pa_accel;          /* 16.16 fixed point */
43
44 uint32_t        ao_pa;                  /* integer portion */
45 int16_t         ao_pa_speed;            /* integer portion */
46 int16_t         ao_pa_accel;            /* integer portion */
47
48 void
49 ao_microkalman_init(void)
50 {
51         ao_pa = pa;
52         ao_k_pa = pa << 8;
53 }
54
55 void
56 ao_microkalman_predict(void)
57 {
58         ao_k_pa       += fix16_to_fix8((int32_t) ao_pa_speed * AO_MK_STEP + (int32_t) ao_pa_accel * AO_MK_STEP_2_2);
59         ao_k_pa_speed += (int32_t) ao_pa_accel * AO_MK_STEP;
60 }
61
62 void
63 ao_microkalman_correct(void)
64 {
65         int16_t e;      /* Height error in Pa */
66
67         e = pa - from_fix8(ao_k_pa);
68
69         ao_k_pa       += fix16_to_fix8((int32_t) e * AO_MK_BARO_K0_10);
70         ao_k_pa_speed += (int32_t) e * AO_MK_BARO_K1_10;
71         ao_k_pa_accel += (int32_t) e * AO_MK_BARO_K2_10;
72         ao_pa = from_fix8(ao_k_pa);
73         ao_pa_speed = from_fix(ao_k_pa_speed);
74         ao_pa_accel = from_fix(ao_k_pa_accel);
75 }