altoslib: Missed a couple of easy mini voltage API changes
[fw/altos] / src / core / 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; version 2 of the License.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
16  */
17
18 #ifndef AO_FLIGHT_TEST
19 #include <ao.h>
20 #endif
21 #include <ao_micropeak.h>
22
23 #define FIX_BITS        16
24
25 #define to_fix16(x) ((int16_t) ((x) * 65536.0 + 0.5))
26 #define to_fix32(x) ((int32_t) ((x) * 65536.0 + 0.5))
27 #define from_fix8(x)    ((x) >> 8)
28 #define from_fix(x)     ((x) >> 16)
29 #define fix8_to_fix16(x)        ((x) << 8)
30 #define fix16_to_fix8(x)        ((x) >> 8)
31
32 #include <ao_kalman.h>
33
34 /* Basic time step (96ms) */
35 #define AO_MK_STEP      to_fix16(0.096)
36 /* step ** 2 / 2 */
37 #define AO_MK_STEP_2_2  to_fix16(0.004608)
38
39 uint32_t        ao_k_pa;                /* 24.8 fixed point */
40 int32_t         ao_k_pa_speed;          /* 16.16 fixed point */
41 int32_t         ao_k_pa_accel;          /* 16.16 fixed point */
42
43 uint32_t        ao_pa;                  /* integer portion */
44 int16_t         ao_pa_speed;            /* integer portion */
45 int16_t         ao_pa_accel;            /* integer portion */
46
47 void
48 ao_microkalman_init(void)
49 {
50         ao_pa = pa;
51         ao_k_pa = pa << 8;
52 }       
53
54 void
55 ao_microkalman_predict(void)
56 {
57         ao_k_pa       += fix16_to_fix8((int32_t) ao_pa_speed * AO_MK_STEP + (int32_t) ao_pa_accel * AO_MK_STEP_2_2);
58         ao_k_pa_speed += (int32_t) ao_pa_accel * AO_MK_STEP;
59 }
60
61 void
62 ao_microkalman_correct(void)
63 {
64         int16_t e;      /* Height error in Pa */
65
66         e = pa - from_fix8(ao_k_pa);
67
68         ao_k_pa       += fix16_to_fix8((int32_t) e * AO_MK_BARO_K0_10);
69         ao_k_pa_speed += (int32_t) e * AO_MK_BARO_K1_10;
70         ao_k_pa_accel += (int32_t) e * AO_MK_BARO_K2_10;
71         ao_pa = from_fix8(ao_k_pa);
72         ao_pa_speed = from_fix(ao_k_pa_speed);
73         ao_pa_accel = from_fix(ao_k_pa_accel);
74 }