altos: clear CPU port 1 interrupt flag when handled
[fw/altos] / src / make-altitude
1 #!/usr/bin/nickle -f
2 /*
3  * Pressure Sensor Model, version 1.1
4  *
5  * written by Holly Grimes
6  *
7  * Uses the International Standard Atmosphere as described in
8  *   "A Quick Derivation relating altitude to air pressure" (version 1.03)
9  *    from the Portland State Aerospace Society, except that the atmosphere
10  *    is divided into layers with each layer having a different lapse rate.
11  *
12  * Lapse rate data for each layer was obtained from Wikipedia on Sept. 1, 2007
13  *    at site <http://en.wikipedia.org/wiki/International_Standard_Atmosphere
14  *
15  * Height measurements use the local tangent plane.  The postive z-direction is up.
16  *
17  * All measurements are given in SI units (Kelvin, Pascal, meter, meters/second^2).
18  *   The lapse rate is given in Kelvin/meter, the gas constant for air is given
19  *   in Joules/(kilogram-Kelvin).
20  */
21
22 const real GRAVITATIONAL_ACCELERATION = -9.80665;
23 const real AIR_GAS_CONSTANT = 287.053;
24 const int NUMBER_OF_LAYERS = 7;
25 const real MAXIMUM_ALTITUDE = 84852;
26 const real MINIMUM_PRESSURE = 0.3734;
27 const real LAYER0_BASE_TEMPERATURE = 288.15;
28 const real LAYER0_BASE_PRESSURE = 101325;
29
30 /* lapse rate and base altitude for each layer in the atmosphere */
31 const real[NUMBER_OF_LAYERS] lapse_rate = {
32         -0.0065, 0.0, 0.001, 0.0028, 0.0, -0.0028, -0.002
33 };
34 const int[NUMBER_OF_LAYERS] base_altitude = {
35         0, 11000, 20000, 32000, 47000, 51000, 71000
36 };
37
38
39 /* outputs atmospheric pressure associated with the given altitude. altitudes
40    are measured with respect to the mean sea level */
41 real altitude_to_pressure(real altitude) {
42
43    real base_temperature = LAYER0_BASE_TEMPERATURE;
44    real base_pressure = LAYER0_BASE_PRESSURE;
45
46    real pressure;
47    real base; /* base for function to determine pressure */
48    real exponent; /* exponent for function to determine pressure */
49    int layer_number; /* identifies layer in the atmosphere */
50    int delta_z; /* difference between two altitudes */
51
52    if (altitude > MAXIMUM_ALTITUDE) /* FIX ME: use sensor data to improve model */
53       return 0;
54
55    /* calculate the base temperature and pressure for the atmospheric layer
56       associated with the inputted altitude */
57    for(layer_number = 0; layer_number < NUMBER_OF_LAYERS - 1 && altitude > base_altitude[layer_number + 1]; layer_number++) {
58       delta_z = base_altitude[layer_number + 1] - base_altitude[layer_number];
59       if (lapse_rate[layer_number] == 0.0) {
60          exponent = GRAVITATIONAL_ACCELERATION * delta_z
61               / AIR_GAS_CONSTANT / base_temperature;
62          base_pressure *= exp(exponent);
63       }
64       else {
65          base = (lapse_rate[layer_number] * delta_z / base_temperature) + 1.0;
66          exponent = GRAVITATIONAL_ACCELERATION /
67               (AIR_GAS_CONSTANT * lapse_rate[layer_number]);
68          base_pressure *= pow(base, exponent);
69       }
70       base_temperature += delta_z * lapse_rate[layer_number];
71    }
72
73    /* calculate the pressure at the inputted altitude */
74    delta_z = altitude - base_altitude[layer_number];
75    if (lapse_rate[layer_number] == 0.0) {
76       exponent = GRAVITATIONAL_ACCELERATION * delta_z
77            / AIR_GAS_CONSTANT / base_temperature;
78       pressure = base_pressure * exp(exponent);
79    }
80    else {
81       base = (lapse_rate[layer_number] * delta_z / base_temperature) + 1.0;
82       exponent = GRAVITATIONAL_ACCELERATION /
83            (AIR_GAS_CONSTANT * lapse_rate[layer_number]);
84       pressure = base_pressure * pow(base, exponent);
85    }
86
87    return pressure;
88 }
89
90
91 /* outputs the altitude associated with the given pressure. the altitude
92    returned is measured with respect to the mean sea level */
93 real pressure_to_altitude(real pressure) {
94
95    real next_base_temperature = LAYER0_BASE_TEMPERATURE;
96    real next_base_pressure = LAYER0_BASE_PRESSURE;
97
98    real altitude;
99    real base_pressure;
100    real base_temperature;
101    real base; /* base for function to determine base pressure of next layer */
102    real exponent; /* exponent for function to determine base pressure
103                              of next layer */
104    real coefficient;
105    int layer_number; /* identifies layer in the atmosphere */
106    int delta_z; /* difference between two altitudes */
107
108    if (pressure < 0)  /* illegal pressure */
109       return -1;
110    if (pressure < MINIMUM_PRESSURE) /* FIX ME: use sensor data to improve model */
111       return MAXIMUM_ALTITUDE;
112
113    /* calculate the base temperature and pressure for the atmospheric layer
114       associated with the inputted pressure. */
115    layer_number = -1;
116    do {
117       layer_number++;
118       base_pressure = next_base_pressure;
119       base_temperature = next_base_temperature;
120       delta_z = base_altitude[layer_number + 1] - base_altitude[layer_number];
121       if (lapse_rate[layer_number] == 0.0) {
122          exponent = GRAVITATIONAL_ACCELERATION * delta_z
123               / AIR_GAS_CONSTANT / base_temperature;
124          next_base_pressure *= exp(exponent);
125       }
126       else {
127          base = (lapse_rate[layer_number] * delta_z / base_temperature) + 1.0;
128          exponent = GRAVITATIONAL_ACCELERATION /
129               (AIR_GAS_CONSTANT * lapse_rate[layer_number]);
130          next_base_pressure *= pow(base, exponent);
131       }
132       next_base_temperature += delta_z * lapse_rate[layer_number];
133    }
134    while(layer_number < NUMBER_OF_LAYERS - 1 && pressure < next_base_pressure);
135
136    /* calculate the altitude associated with the inputted pressure */
137    if (lapse_rate[layer_number] == 0.0) {
138       coefficient = (AIR_GAS_CONSTANT / GRAVITATIONAL_ACCELERATION)
139                                                     * base_temperature;
140       altitude = base_altitude[layer_number]
141                     + coefficient * log(pressure / base_pressure);
142    }
143    else {
144       base = pressure / base_pressure;
145       exponent = AIR_GAS_CONSTANT * lapse_rate[layer_number]
146                                        / GRAVITATIONAL_ACCELERATION;
147       coefficient = base_temperature / lapse_rate[layer_number];
148       altitude = base_altitude[layer_number]
149                       + coefficient * (pow(base, exponent) - 1);
150    }
151
152    return altitude;
153 }
154
155 real feet_to_meters(real feet)
156 {
157     return feet * (12 * 2.54 / 100);
158 }
159
160 real meters_to_feet(real meters)
161 {
162     return meters / (12 * 2.54 / 100);
163 }
164
165 /*
166  * Values for our MP3H6115A pressure sensor
167  *
168  * From the data sheet:
169  *
170  * Pressure range: 15-115 kPa
171  * Voltage at 115kPa: 2.82
172  * Output scale: 27mV/kPa
173  *
174  *
175  * 27 mV/kPa * 2047 / 3300 counts/mV = 16.75 counts/kPa
176  * 2.82V * 2047 / 3.3 counts/V = 1749 counts/115 kPa
177  */
178
179 real counts_per_kPa = 27 * 2047 / 3300;
180 real counts_at_101_3kPa = 1674;
181
182 real fraction_to_kPa(real fraction)
183 {
184         return (fraction + 0.095) / 0.009;
185 }
186
187
188 real count_to_kPa(real count) = fraction_to_kPa(count / 2047);
189
190 typedef struct {
191         real m, b;
192         int m_i, b_i;
193 } line_t;
194
195 line_t best_fit(real[] values, int first, int last) {
196        real sum_x = 0, sum_x2 = 0, sum_y = 0, sum_xy = 0;
197        int n = last - first + 1;
198        real m, b;
199        int m_i, b_i;
200
201        for (int i = first; i <= last; i++) {
202                sum_x += i;
203                sum_x2 += i**2;
204                sum_y += values[i];
205                sum_xy += values[i] * i;
206        }
207        m = (n*sum_xy - sum_y*sum_x) / (n*sum_x2 - sum_x**2);
208        b = sum_y/n - m*(sum_x/n);
209        return (line_t) { m = m, b = b };
210 }
211
212 real count_to_altitude(real count) {
213      return pressure_to_altitude(count_to_kPa(count) * 1000);
214 }
215
216 real fraction_to_altitude(real frac) = pressure_to_altitude(fraction_to_kPa(frac) * 1000);
217
218 int num_samples = 1024;
219
220 real[num_samples] alt = { [n] = fraction_to_altitude(n/(num_samples - 1)) };
221
222 int num_part = 128;
223 int seg_len = num_samples / num_part;
224
225 line_t [dim(alt) / seg_len] fit = {
226         [n] = best_fit(alt, n * seg_len, n * seg_len + seg_len - 1)
227 };
228
229 int[num_samples/seg_len + 1]    alt_part;
230
231 alt_part[0] = floor (fit[0].b + 0.5);
232 alt_part[dim(fit)] = floor(fit[dim(fit)-1].m * dim(fit) * seg_len + fit[dim(fit)-1].b + 0.5);
233
234 for (int i = 0; i < dim(fit) - 1; i++) {
235         real    here, there;
236         here = fit[i].m * (i+1) * seg_len + fit[i].b;
237         there = fit[i+1].m * (i+1) * seg_len + fit[i+1].b;
238         alt_part[i+1] = floor ((here + there) / 2 + 0.5);
239 }
240
241 real count_to_fit_altitude(int count) {
242         int     sub = count // seg_len;
243         int     off = count % seg_len;
244         line_t  l = fit[sub];
245         real r_v;
246         real i_v;
247
248         r_v = count * l.m + l.b;
249         i_v = (alt_part[sub] * (seg_len - off) + alt_part[sub+1] * off) / seg_len;
250         return i_v;
251 }
252
253 real max_error = 0;
254 int max_error_count = 0;
255 real total_error = 0;
256
257 for (int count = 0; count < num_samples; count++) {
258         real    kPa = fraction_to_kPa(count / (num_samples - 1));
259         real    meters = pressure_to_altitude(kPa * 1000);
260
261         real    meters_approx = count_to_fit_altitude(count);
262         real    error = abs(meters - meters_approx);
263
264         total_error += error;
265         if (error > max_error) {
266                 max_error = error;
267                 max_error_count = count;
268         }
269 #       printf ("       %7d,    /* %6.2g kPa %5d count approx %d */\n",
270 #               floor (meters + 0.5), kPa, count, floor(count_to_fit_altitude(count) + 0.5));
271 }
272
273 printf ("/*max error %f at %7.3f%%. Average error %f*/\n", max_error, max_error_count / (num_samples - 1) * 100, total_error / num_samples);
274
275 printf ("#define NALT %d\n", dim(alt_part));
276 printf ("#define ALT_FRAC_BITS %d\n", floor (log2(32768/(dim(alt_part)-1)) + 0.1));
277
278 for (int i = 0; i < dim(alt_part); i++) {
279         real fraction = i / (dim(alt_part) - 1);
280         real kPa = fraction_to_kPa(fraction);
281         printf ("%9d, /* %6.2f kPa %7.3f%% */\n",
282                 alt_part[i], kPa, fraction * 100);
283 }