81aecad3e26e0053059b65a90b7273a9504d627a
[fw/altos] / src / ao_flight.c
1 /*
2  * Copyright © 2009 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
22 /* Main flight thread. */
23
24 __pdata enum ao_flight_state    ao_flight_state;        /* current flight state */
25 __pdata uint16_t                ao_flight_tick;         /* time of last data */
26 __pdata uint16_t                ao_flight_prev_tick;    /* time of previous data */
27 __pdata int16_t                 ao_flight_accel;        /* filtered acceleration */
28 __pdata int16_t                 ao_flight_pres;         /* filtered pressure */
29 __pdata int16_t                 ao_ground_pres;         /* startup pressure */
30 __pdata int16_t                 ao_ground_accel;        /* startup acceleration */
31 __pdata int16_t                 ao_min_pres;            /* minimum recorded pressure */
32 __pdata uint16_t                ao_launch_tick;         /* time of launch detect */
33 __pdata int16_t                 ao_main_pres;           /* pressure to eject main */
34
35 /*
36  * track min/max data over a long interval to detect
37  * resting
38  */
39 __pdata uint16_t                ao_interval_end;
40 __pdata int16_t                 ao_interval_cur_min_accel;
41 __pdata int16_t                 ao_interval_cur_max_accel;
42 __pdata int16_t                 ao_interval_cur_min_pres;
43 __pdata int16_t                 ao_interval_cur_max_pres;
44 __pdata int16_t                 ao_interval_min_accel;
45 __pdata int16_t                 ao_interval_max_accel;
46 __pdata int16_t                 ao_interval_min_pres;
47 __pdata int16_t                 ao_interval_max_pres;
48
49 __data uint8_t ao_flight_adc;
50 __pdata int16_t ao_raw_accel, ao_raw_accel_prev, ao_raw_pres;
51 __pdata int16_t ao_accel_2g;
52
53 __xdata uint8_t ao_flight_force_idle;
54
55 /* Accelerometer calibration
56  *
57  * We're sampling the accelerometer through a resistor divider which
58  * consists of 5k and 10k resistors. This multiplies the values by 2/3.
59  * That goes into the cc1111 A/D converter, which is running at 11 bits
60  * of precision with the bits in the MSB of the 16 bit value. Only positive
61  * values are used, so values should range from 0-32752 for 0-3.3V. The
62  * specs say we should see 40mV/g (uncalibrated), multiply by 2/3 for what
63  * the A/D converter sees (26.67 mV/g). We should see 32752/3300 counts/mV,
64  * for a final computation of:
65  *
66  * 26.67 mV/g * 32767/3300 counts/mV = 264.8 counts/g
67  *
68  * Zero g was measured at 16000 (we would expect 16384).
69  * Note that this value is only require to tell if the
70  * rocket is standing upright. Once that is determined,
71  * the value of the accelerometer is averaged for 100 samples
72  * to find the resting accelerometer value, which is used
73  * for all further flight computations
74  */
75
76 #define GRAVITY 9.80665
77 /* convert m/s to velocity count */
78 #define VEL_MPS_TO_COUNT(mps) (((int32_t) (((mps) / GRAVITY) * (AO_HERTZ/2))) * (int32_t) ao_accel_2g)
79
80 #define ACCEL_NOSE_UP   (ao_accel_2g >> 2)
81 #define ACCEL_BOOST     ao_accel_2g
82 #define ACCEL_COAST     (ao_accel_2g >> 3)
83 #define ACCEL_INT_LAND  (ao_accel_2g >> 3)
84 #define ACCEL_VEL_MACH  VEL_MPS_TO_COUNT(200)
85 #define ACCEL_VEL_BOOST VEL_MPS_TO_COUNT(5)
86
87 /*
88  * Barometer calibration
89  *
90  * We directly sample the barometer. The specs say:
91  *
92  * Pressure range: 15-115 kPa
93  * Voltage at 115kPa: 2.82
94  * Output scale: 27mV/kPa
95  *
96  * If we want to detect launch with the barometer, we need
97  * a large enough bump to not be fooled by noise. At typical
98  * launch elevations (0-2000m), a 200Pa pressure change cooresponds
99  * to about a 20m elevation change. This is 5.4mV, or about 3LSB.
100  * As all of our calculations are done in 16 bits, we'll actually see a change
101  * of 16 times this though
102  *
103  * 27 mV/kPa * 32767 / 3300 counts/mV = 268.1 counts/kPa
104  */
105
106 #define BARO_kPa        268
107 #define BARO_LAUNCH     (BARO_kPa / 5)  /* .2kPa, or about 20m */
108 #define BARO_APOGEE     (BARO_kPa / 10) /* .1kPa, or about 10m */
109 #define BARO_COAST      (BARO_kPa * 5)  /* 5kpa, or about 500m */
110 #define BARO_MAIN       (BARO_kPa)      /* 1kPa, or about 100m */
111 #define BARO_INT_LAND   (BARO_kPa / 20) /* .05kPa, or about 5m */
112 #define BARO_LAND       (BARO_kPa * 10) /* 10kPa or about 1000m */
113
114 /* We also have a clock, which can be used to sanity check things in
115  * case of other failures
116  */
117
118 #define BOOST_TICKS_MAX AO_SEC_TO_TICKS(15)
119
120 /* This value is scaled in a weird way. It's a running total of accelerometer
121  * readings minus the ground accelerometer reading. That means it measures
122  * velocity, and quite accurately too. As it gets updated 100 times a second,
123  * it's scaled by 100
124  */
125 __pdata int32_t ao_flight_vel;
126 __pdata int32_t ao_min_vel;
127 __pdata int32_t ao_old_vel;
128 __pdata int16_t ao_old_vel_tick;
129 __xdata int32_t ao_raw_accel_sum, ao_raw_pres_sum;
130
131 /* Landing is detected by getting constant readings from both pressure and accelerometer
132  * for a fairly long time (AO_INTERVAL_TICKS)
133  */
134 #define AO_INTERVAL_TICKS       AO_SEC_TO_TICKS(5)
135
136 #define abs(a)  ((a) < 0 ? -(a) : (a))
137
138 void
139 ao_flight(void)
140 {
141         __pdata static uint16_t nsamples = 0;
142
143         ao_flight_adc = ao_adc_head;
144         ao_raw_accel_prev = 0;
145         ao_raw_accel = 0;
146         ao_raw_pres = 0;
147         ao_flight_tick = 0;
148         for (;;) {
149                 ao_wakeup(DATA_TO_XDATA(&ao_flight_adc));
150                 ao_sleep(DATA_TO_XDATA(&ao_adc_head));
151                 while (ao_flight_adc != ao_adc_head) {
152                         __pdata uint8_t ticks;
153                         __pdata int16_t ao_vel_change;
154                         __xdata struct ao_adc *ao_adc;
155                         ao_flight_prev_tick = ao_flight_tick;
156
157                         /* Capture a sample */
158                         ao_adc = &ao_adc_ring[ao_flight_adc];
159                         ao_flight_tick = ao_adc->tick;
160                         ao_raw_accel = ao_adc->accel;
161 #if HAS_ACCEL_REF
162                         /*
163                          * Ok, the math here is a bit tricky.
164                          *
165                          * ao_raw_accel:  ADC output for acceleration
166                          * ao_accel_ref:  ADC output for the 5V reference.
167                          * ao_cook_accel: Corrected acceleration value
168                          * Vcc:           3.3V supply to the CC1111
169                          * Vac:           5V supply to the accelerometer
170                          * accel:         input voltage to accelerometer ADC pin
171                          * ref:           input voltage to 5V reference ADC pin
172                          *
173                          *
174                          * Measured acceleration is ratiometric to Vcc:
175                          *
176                          *     ao_raw_accel   accel
177                          *     ------------ = -----
178                          *        32767        Vcc
179                          *
180                          * Measured 5v reference is also ratiometric to Vcc:
181                          *
182                          *     ao_accel_ref    ref
183                          *     ------------ = -----
184                          *        32767        Vcc
185                          *
186                          *
187                          *      ao_accel_ref = 32767 * (ref / Vcc)
188                          *
189                          * Acceleration is measured ratiometric to the 5V supply,
190                          * so what we want is:
191                          *
192                          *      ao_cook_accel    accel
193                          *      ------------- =  -----
194                          *          32767         ref
195                          *
196                          *
197                          *                      accel    Vcc
198                          *                    = ----- *  ---
199                          *                       Vcc     ref
200                          *
201                          *                      ao_raw_accel       32767
202                          *                    = ------------ *  ------------
203                          *                         32737        ao_accel_ref
204                          *
205                          * Multiply through by 32767:
206                          *
207                          *                      ao_raw_accel * 32767
208                          *      ao_cook_accel = --------------------
209                          *                          ao_accel_ref
210                          *
211                          * Now, the tricky part. Getting this to compile efficiently
212                          * and keeping all of the values in-range.
213                          *
214                          * First off, we need to use a shift of 16 instead of * 32767 as SDCC
215                          * does the obvious optimizations for byte-granularity shifts:
216                          *
217                          *      ao_cook_accel = (ao_raw_accel << 16) / ao_accel_ref
218                          *
219                          * Next, lets check our input ranges:
220                          *
221                          *      0 <= ao_raw_accel <= 0x7fff             (singled ended ADC conversion)
222                          *      0x7000 <= ao_accel_ref <= 0x7fff        (the 5V ref value is close to 0x7fff)
223                          *
224                          * Plugging in our input ranges, we get an output range of 0 - 0x12490,
225                          * which is 17 bits. That won't work. If we take the accel ref and shift
226                          * by a bit, we'll change its range:
227                          *
228                          *      0xe000 <= ao_accel_ref<<1 <= 0xfffe
229                          *
230                          *      ao_cook_accel = (ao_raw_accel << 16) / (ao_accel_ref << 1)
231                          *
232                          * Now the output range is 0 - 0x9248, which nicely fits in 16 bits. It
233                          * is, however, one bit too large for our signed computations. So, we
234                          * take the result and shift that by a bit:
235                          *
236                          *      ao_cook_accel = ((ao_raw_accel << 16) / (ao_accel_ref << 1)) >> 1
237                          *
238                          * This finally creates an output range of 0 - 0x4924. As the ADC only
239                          * provides 11 bits of data, we haven't actually lost any precision,
240                          * just dropped a bit of noise off the low end.
241                          */
242                         ao_raw_accel = (uint16_t) ((((uint32_t) ao_raw_accel << 16) / (ao_accel_ref[ao_flight_adc] << 1))) >> 1;
243                         ao_adc->accel = ao_raw_accel;
244 #endif
245                         ao_raw_pres = ao_adc->pres;
246
247                         ao_flight_accel -= ao_flight_accel >> 4;
248                         ao_flight_accel += ao_raw_accel >> 4;
249                         ao_flight_pres -= ao_flight_pres >> 4;
250                         ao_flight_pres += ao_raw_pres >> 4;
251                         /* Update velocity
252                          *
253                          * The accelerometer is mounted so that
254                          * acceleration yields negative values
255                          * while deceleration yields positive values,
256                          * so subtract instead of add.
257                          */
258                         ticks = ao_flight_tick - ao_flight_prev_tick;
259                         ao_vel_change = ao_ground_accel - (((ao_raw_accel + 1) >> 1) + ((ao_raw_accel_prev + 1) >> 1));
260                         ao_raw_accel_prev = ao_raw_accel;
261
262                         /* one is a common interval */
263                         if (ticks == 1)
264                                 ao_flight_vel += (int32_t) ao_vel_change;
265                         else
266                                 ao_flight_vel += (int32_t) ao_vel_change * (int32_t) ticks;
267
268                         ao_flight_adc = ao_adc_ring_next(ao_flight_adc);
269                 }
270
271                 if (ao_flight_pres < ao_min_pres)
272                         ao_min_pres = ao_flight_pres;
273                 if (ao_flight_vel >= 0) {
274                         if (ao_flight_vel < ao_min_vel)
275                             ao_min_vel = ao_flight_vel;
276                 } else {
277                         if (-ao_flight_vel < ao_min_vel)
278                             ao_min_vel = -ao_flight_vel;
279                 }
280
281                 switch (ao_flight_state) {
282                 case ao_flight_startup:
283
284                         /* startup state:
285                          *
286                          * Collect 512 samples of acceleration and pressure
287                          * data and average them to find the resting values
288                          */
289                         if (nsamples < 512) {
290                                 ao_raw_accel_sum += ao_raw_accel;
291                                 ao_raw_pres_sum += ao_raw_pres;
292                                 ++nsamples;
293                                 continue;
294                         }
295                         ao_ground_accel = ao_raw_accel_sum >> 9;
296                         ao_ground_pres = ao_raw_pres_sum >> 9;
297                         ao_min_pres = ao_ground_pres;
298                         ao_config_get();
299                         ao_main_pres = ao_altitude_to_pres(ao_pres_to_altitude(ao_ground_pres) + ao_config.main_deploy);
300                         ao_accel_2g = ao_config.accel_minus_g - ao_config.accel_plus_g;
301                         ao_flight_vel = 0;
302                         ao_min_vel = 0;
303                         ao_old_vel = ao_flight_vel;
304                         ao_old_vel_tick = ao_flight_tick;
305
306                         /* Check to see what mode we should go to.
307                          *  - Invalid mode if accel cal appears to be out
308                          *  - pad mode if we're upright,
309                          *  - idle mode otherwise
310                          */
311                         ao_config_get();
312                         if (ao_config.accel_plus_g == 0 ||
313                             ao_config.accel_minus_g == 0 ||
314                             ao_flight_accel < ao_config.accel_plus_g - ACCEL_NOSE_UP ||
315                             ao_flight_accel > ao_config.accel_minus_g + ACCEL_NOSE_UP)
316                         {
317                                 /* Detected an accel value outside -1.5g to 1.5g
318                                  * (or uncalibrated values), so we go into invalid mode
319                                  */
320                                 ao_flight_state = ao_flight_invalid;
321                                 /* Allow packet mode in invalid flight state,
322                                  * Still need to be able to fix the problem!
323                                  */
324                                 ao_packet_slave_start();
325
326                         } else if (ao_flight_accel < ao_config.accel_plus_g + ACCEL_NOSE_UP &&
327                                    !ao_flight_force_idle)
328                         {
329                                 /* Set pad mode - we can fly! */
330                                 ao_flight_state = ao_flight_pad;
331
332                                 /* Disable the USB controller in flight mode
333                                  * to save power
334                                  */
335                                 ao_usb_disable();
336
337                                 /* Turn on telemetry system */
338                                 ao_rdf_set(1);
339                                 ao_telemetry_set_interval(AO_TELEMETRY_INTERVAL_PAD);
340
341                                 /* signal successful initialization by turning off the LED */
342                                 ao_led_off(AO_LED_RED);
343                         } else {
344                                 /* Set idle mode */
345                                 ao_flight_state = ao_flight_idle;
346  
347                                 /* Turn on packet system in idle mode */
348                                 ao_packet_slave_start();
349
350                                 /* signal successful initialization by turning off the LED */
351                                 ao_led_off(AO_LED_RED);
352                         }
353                         /* wakeup threads due to state change */
354                         ao_wakeup(DATA_TO_XDATA(&ao_flight_state));
355
356                         break;
357                 case ao_flight_pad:
358
359                         /* Trim velocity
360                          *
361                          * Once a second, remove any velocity from
362                          * a second ago
363                          */
364                         if ((int16_t) (ao_flight_tick - ao_old_vel_tick) >= AO_SEC_TO_TICKS(1)) {
365                                 ao_old_vel_tick = ao_flight_tick;
366                                 ao_flight_vel -= ao_old_vel;
367                                 ao_old_vel = ao_flight_vel;
368                         }
369                         /* pad to boost:
370                          *
371                          * accelerometer: > 2g AND velocity > 5m/s
372                          *             OR
373                          * barometer: > 20m vertical motion
374                          *
375                          * The accelerometer should always detect motion before
376                          * the barometer, but we use both to make sure this
377                          * transition is detected
378                          */
379                         if ((ao_flight_accel < ao_ground_accel - ACCEL_BOOST &&
380                              ao_flight_vel > ACCEL_VEL_BOOST) ||
381                             ao_flight_pres < ao_ground_pres - BARO_LAUNCH)
382                         {
383                                 ao_flight_state = ao_flight_boost;
384                                 ao_launch_tick = ao_flight_tick;
385
386                                 /* start logging data */
387                                 ao_log_start();
388
389                                 /* Increase telemetry rate */
390                                 ao_telemetry_set_interval(AO_TELEMETRY_INTERVAL_FLIGHT);
391
392                                 /* disable RDF beacon */
393                                 ao_rdf_set(0);
394
395                                 /* Record current GPS position by waking up GPS log tasks */
396                                 ao_wakeup(&ao_gps_data);
397                                 ao_wakeup(&ao_gps_tracking_data);
398
399                                 ao_wakeup(DATA_TO_XDATA(&ao_flight_state));
400                                 break;
401                         }
402                         break;
403                 case ao_flight_boost:
404
405                         /* boost to fast:
406                          *
407                          * accelerometer: start to fall at > 1/4 G
408                          *              OR
409                          * time: boost for more than 15 seconds
410                          *
411                          * Detects motor burn out by the switch from acceleration to
412                          * deceleration, or by waiting until the maximum burn duration
413                          * (15 seconds) has past.
414                          */
415                         if (ao_flight_accel > ao_ground_accel + ACCEL_COAST ||
416                             (int16_t) (ao_flight_tick - ao_launch_tick) > BOOST_TICKS_MAX)
417                         {
418                                 ao_flight_state = ao_flight_fast;
419                                 ao_wakeup(DATA_TO_XDATA(&ao_flight_state));
420                                 break;
421                         }
422                         break;
423                 case ao_flight_fast:
424
425                         /* fast to coast:
426                          *
427                          * accelerometer: integrated velocity < 200 m/s
428                          *               OR
429                          * barometer: fall at least 500m from max altitude
430                          *
431                          * This extra state is required to avoid mis-detecting
432                          * apogee due to mach transitions.
433                          *
434                          * XXX this is essentially a single-detector test
435                          * as the 500m altitude change would likely result
436                          * in a loss of the rocket. More data on precisely
437                          * how big a pressure change the mach transition
438                          * generates would be useful here.
439                          */
440                         if (ao_flight_vel < ACCEL_VEL_MACH ||
441                             ao_flight_pres > ao_min_pres + BARO_COAST)
442                         {
443                                 /* set min velocity to current velocity for
444                                  * apogee detect
445                                  */
446                                 ao_min_vel = abs(ao_flight_vel);
447                                 ao_flight_state = ao_flight_coast;
448                                 ao_wakeup(DATA_TO_XDATA(&ao_flight_state));
449                         }
450                         break;
451                 case ao_flight_coast:
452
453                         /* apogee detect: coast to drogue deploy:
454                          *
455                          * barometer: fall at least 10m
456                          *
457                          * It would be nice to use the accelerometer
458                          * to detect apogee as well, but tests have
459                          * shown that flights far from vertical would
460                          * grossly mis-detect apogee. So, for now,
461                          * we'll trust to a single sensor for this test
462                          */
463                         if (ao_flight_pres > ao_min_pres + BARO_APOGEE)
464                         {
465                                 /* ignite the drogue charge */
466                                 ao_ignite(ao_igniter_drogue);
467
468                                 /* slow down the telemetry system */
469                                 ao_telemetry_set_interval(AO_TELEMETRY_INTERVAL_RECOVER);
470
471                                 /* slow down the ADC sample rate */
472                                 ao_timer_set_adc_interval(10);
473
474                                 /*
475                                  * Start recording min/max accel and pres for a while
476                                  * to figure out when the rocket has landed
477                                  */
478                                 /* Set the 'last' limits to max range to prevent
479                                  * early resting detection
480                                  */
481                                 ao_interval_min_accel = 0;
482                                 ao_interval_max_accel = 0x7fff;
483                                 ao_interval_min_pres = 0;
484                                 ao_interval_max_pres = 0x7fff;
485
486                                 /* initialize interval values */
487                                 ao_interval_end = ao_flight_tick + AO_INTERVAL_TICKS;
488
489                                 ao_interval_cur_min_pres = ao_interval_cur_max_pres = ao_flight_pres;
490                                 ao_interval_cur_min_accel = ao_interval_cur_max_accel = ao_flight_accel;
491
492                                 /* and enter drogue state */
493                                 ao_flight_state = ao_flight_drogue;
494                                 ao_wakeup(DATA_TO_XDATA(&ao_flight_state));
495                         }
496
497                         break;
498                 case ao_flight_drogue:
499
500                         /* drogue to main deploy:
501                          *
502                          * barometer: reach main deploy altitude
503                          *
504                          * Would like to use the accelerometer for this test, but
505                          * the orientation of the flight computer is unknown after
506                          * drogue deploy, so we ignore it. Could also detect
507                          * high descent rate using the pressure sensor to
508                          * recognize drogue deploy failure and eject the main
509                          * at that point. Perhaps also use the drogue sense lines
510                          * to notice continutity?
511                          */
512                         if (ao_flight_pres >= ao_main_pres)
513                         {
514                                 ao_ignite(ao_igniter_main);
515                                 ao_flight_state = ao_flight_main;
516                                 ao_wakeup(DATA_TO_XDATA(&ao_flight_state));
517                         }
518
519                         /* fall through... */
520                 case ao_flight_main:
521
522                         /* drogue/main to land:
523                          *
524                          * accelerometer: value stable
525                          *                           AND
526                          * barometer: altitude stable and within 1000m of the launch altitude
527                          */
528
529                         if (ao_flight_pres < ao_interval_cur_min_pres)
530                                 ao_interval_cur_min_pres = ao_flight_pres;
531                         if (ao_flight_pres > ao_interval_cur_max_pres)
532                                 ao_interval_cur_max_pres = ao_flight_pres;
533                         if (ao_flight_accel < ao_interval_cur_min_accel)
534                                 ao_interval_cur_min_accel = ao_flight_accel;
535                         if (ao_flight_accel > ao_interval_cur_max_accel)
536                                 ao_interval_cur_max_accel = ao_flight_accel;
537
538                         if ((int16_t) (ao_flight_tick - ao_interval_end) >= 0) {
539                                 ao_interval_max_pres = ao_interval_cur_max_pres;
540                                 ao_interval_min_pres = ao_interval_cur_min_pres;
541                                 ao_interval_max_accel = ao_interval_cur_max_accel;
542                                 ao_interval_min_accel = ao_interval_cur_min_accel;
543                                 ao_interval_end = ao_flight_tick + AO_INTERVAL_TICKS;
544                                 ao_interval_cur_min_pres = ao_interval_cur_max_pres = ao_flight_pres;
545                                 ao_interval_cur_min_accel = ao_interval_cur_max_accel = ao_flight_accel;
546
547                                 if ((uint16_t) (ao_interval_max_accel - ao_interval_min_accel) < (uint16_t) ACCEL_INT_LAND &&
548                                     ao_flight_pres > ao_ground_pres - BARO_LAND &&
549                                     (uint16_t) (ao_interval_max_pres - ao_interval_min_pres) < (uint16_t) BARO_INT_LAND)
550                                 {
551                                         ao_flight_state = ao_flight_landed;
552
553                                         /* turn off the ADC capture */
554                                         ao_timer_set_adc_interval(0);
555                                         /* Enable RDF beacon */
556                                         ao_rdf_set(1);
557
558                                         ao_wakeup(DATA_TO_XDATA(&ao_flight_state));
559                                 }
560                         }
561                         break;
562                 case ao_flight_landed:
563                         break;
564                 }
565         }
566 }
567
568 static __xdata struct ao_task   flight_task;
569
570 void
571 ao_flight_init(void)
572 {
573         ao_flight_state = ao_flight_startup;
574         ao_add_task(&flight_task, ao_flight, "flight");
575 }