src-avr: Suspend interrupts while switching stacks
[fw/altos] / src-avr / ao.h
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_H_
19 #define _AO_H_
20
21 #include <stdint.h>
22 #include <stdio.h>
23 #include <string.h>
24 #include <stddef.h>
25 #ifdef AVR
26 #include "avr.h"
27 #else
28 #include "cc1111.h"
29 #endif
30 #include "ao_pins.h"
31
32 #define TRUE 1
33 #define FALSE 0
34
35 /* Convert a __data pointer into an __xdata pointer */
36 #define DATA_TO_XDATA(a)        ((void __xdata *) ((uint8_t) (a) | 0xff00))
37
38 /* Stack runs from above the allocated __data space to 0xfe, which avoids
39  * writing to 0xff as that triggers the stack overflow indicator
40  */
41 #ifdef AVR
42 #define AO_STACK_SIZE   128
43 #else
44 #define AO_STACK_START  0x90
45 #define AO_STACK_END    0xfe
46 #define AO_STACK_SIZE   (AO_STACK_END - AO_STACK_START + 1)
47 #endif
48
49 /* An AltOS task */
50 struct ao_task {
51         __xdata void *wchan;            /* current wait channel (NULL if running) */
52         uint16_t alarm;                 /* abort ao_sleep time */
53 #ifdef AVR
54         uint8_t *sp;                    /* saved stack pointer */
55 #else
56         uint8_t stack_count;            /* amount of saved stack */
57 #endif
58         uint8_t task_id;                /* unique id */
59         __code char *name;              /* task name */
60         uint8_t stack[AO_STACK_SIZE];   /* saved stack */
61 };
62
63 extern __xdata struct ao_task *__data ao_cur_task;
64
65 #define AO_NUM_TASKS            16      /* maximum number of tasks */
66 #define AO_NO_TASK              0       /* no task id */
67
68 /*
69  ao_task.c
70  */
71
72 /* Suspend the current task until wchan is awoken.
73  * returns:
74  *  0 on normal wake
75  *  1 on alarm
76  */
77 uint8_t
78 ao_sleep(__xdata void *wchan);
79
80 /* Wake all tasks sleeping on wchan */
81 void
82 ao_wakeup(__xdata void *wchan);
83
84 /* set an alarm to go off in 'delay' ticks */
85 void
86 ao_alarm(uint16_t delay);
87
88 /* Yield the processor to another task */
89 #ifdef AVR
90 void ao_yield(void) __attribute__((naked));
91 #else
92 void
93 ao_yield(void) __naked;
94 #endif
95
96 /* Add a task to the run queue */
97 void
98 ao_add_task(__xdata struct ao_task * task, void (*start)(void), __code char *name) __reentrant;
99
100 /* Terminate the current task */
101 void
102 ao_exit(void);
103
104 /* Dump task info to console */
105 void
106 ao_task_info(void);
107
108 /* Start the scheduler. This will not return */
109 void
110 ao_start_scheduler(void);
111
112 /*
113  * ao_panic.c
114  */
115
116 #define AO_PANIC_NO_TASK        1       /* AO_NUM_TASKS is not large enough */
117 #define AO_PANIC_DMA            2       /* Attempt to start DMA while active */
118 #define AO_PANIC_MUTEX          3       /* Mis-using mutex API */
119 #define AO_PANIC_EE             4       /* Mis-using eeprom API */
120 #define AO_PANIC_LOG            5       /* Failing to read/write log data */
121 #define AO_PANIC_CMD            6       /* Too many command sets registered */
122 #define AO_PANIC_STDIO          7       /* Too many stdio handlers registered */
123 #define AO_PANIC_REBOOT         8       /* Reboot failed */
124 #define AO_PANIC_FLASH          9       /* Invalid flash part (or wrong blocksize) */
125 #define AO_PANIC_USB            10      /* Trying to send USB packet while busy */
126 #define AO_PANIC_BT             11      /* Communications with bluetooth device failed */
127
128 /* Stop the operating system, beeping and blinking the reason */
129 void
130 ao_panic(uint8_t reason);
131
132 /*
133  * ao_timer.c
134  */
135
136 /* Our timer runs at 100Hz */
137 #define AO_HERTZ                100
138 #define AO_MS_TO_TICKS(ms)      ((ms) / (1000 / AO_HERTZ))
139 #define AO_SEC_TO_TICKS(s)      ((s) * AO_HERTZ)
140
141 /* Returns the current time in ticks */
142 uint16_t
143 ao_time(void);
144
145 /* Suspend the current task until ticks time has passed */
146 void
147 ao_delay(uint16_t ticks);
148
149 /* Set the ADC interval */
150 void
151 ao_timer_set_adc_interval(uint8_t interval) __critical;
152
153 /* Timer interrupt */
154 void
155 ao_timer_isr(void) __interrupt(9);
156
157 /* Initialize the timer */
158 void
159 ao_timer_init(void);
160
161 /* Initialize the hardware clock. Must be called first */
162 void
163 ao_clock_init(void);
164
165 /*
166  * One set of samples read from the A/D converter or telemetry
167  */
168 struct ao_adc {
169         uint16_t        tick;           /* tick when the sample was read */
170         int16_t         accel;          /* accelerometer */
171         int16_t         pres;           /* pressure sensor */
172         int16_t         temp;           /* temperature sensor */
173         int16_t         v_batt;         /* battery voltage */
174         int16_t         sense_d;        /* drogue continuity sense */
175         int16_t         sense_m;        /* main continuity sense */
176 };
177
178 #if HAS_ADC
179
180 #if HAS_ACCEL
181 #ifndef HAS_ACCEL_REF
182 #error Please define HAS_ACCEL_REF
183 #endif
184 #else
185 #define HAS_ACCEL_REF 0
186 #endif
187
188 /*
189  * ao_adc.c
190  */
191
192 #define AO_ADC_RING     32
193 #define ao_adc_ring_next(n)     (((n) + 1) & (AO_ADC_RING - 1))
194 #define ao_adc_ring_prev(n)     (((n) - 1) & (AO_ADC_RING - 1))
195
196
197 /*
198  * A/D data is stored in a ring, with the next sample to be written
199  * at ao_adc_head
200  */
201 extern volatile __xdata struct ao_adc   ao_adc_ring[AO_ADC_RING];
202 extern volatile __data uint8_t          ao_adc_head;
203 #if HAS_ACCEL_REF
204 extern volatile __xdata uint16_t        ao_accel_ref[AO_ADC_RING];
205 #endif
206
207 /* Trigger a conversion sequence (called from the timer interrupt) */
208 void
209 ao_adc_poll(void);
210
211 /* Suspend the current task until another A/D sample is converted */
212 void
213 ao_adc_sleep(void);
214
215 /* Get a copy of the last complete A/D sample set */
216 void
217 ao_adc_get(__xdata struct ao_adc *packet);
218
219 /* The A/D interrupt handler */
220
221 void
222 ao_adc_isr(void) __interrupt(1);
223
224 /* Initialize the A/D converter */
225 void
226 ao_adc_init(void);
227
228 #endif /* HAS_ADC */
229
230 /*
231  * ao_beep.c
232  */
233
234 /*
235  * Various pre-defined beep frequencies
236  *
237  * frequency = 1/2 (24e6/32) / beep
238  */
239
240 #define AO_BEEP_LOW     150     /* 2500Hz */
241 #define AO_BEEP_MID     94      /* 3989Hz */
242 #define AO_BEEP_HIGH    75      /* 5000Hz */
243 #define AO_BEEP_OFF     0       /* off */
244
245 #define AO_BEEP_g       240     /* 1562.5Hz */
246 #define AO_BEEP_gs      227     /* 1652Hz (1655Hz) */
247 #define AO_BEEP_aa      214     /* 1752Hz (1754Hz) */
248 #define AO_BEEP_bbf     202     /* 1856Hz (1858Hz) */
249 #define AO_BEEP_bb      190     /* 1974Hz (1969Hz) */
250 #define AO_BEEP_cc      180     /* 2083Hz (2086Hz) */
251 #define AO_BEEP_ccs     170     /* 2205Hz (2210Hz) */
252 #define AO_BEEP_dd      160     /* 2344Hz (2341Hz) */
253 #define AO_BEEP_eef     151     /* 2483Hz (2480Hz) */
254 #define AO_BEEP_ee      143     /* 2622Hz (2628Hz) */
255 #define AO_BEEP_ff      135     /* 2778Hz (2784Hz) */
256 #define AO_BEEP_ffs     127     /* 2953Hz (2950Hz) */
257 #define AO_BEEP_gg      120     /* 3125Hz */
258 #define AO_BEEP_ggs     113     /* 3319Hz (3311Hz) */
259 #define AO_BEEP_aaa     107     /* 3504Hz (3508Hz) */
260 #define AO_BEEP_bbbf    101     /* 3713Hz (3716Hz) */
261 #define AO_BEEP_bbb     95      /* 3947Hz (3937Hz) */
262 #define AO_BEEP_ccc     90      /* 4167Hz (4171Hz) */
263 #define AO_BEEP_cccs    85      /* 4412Hz (4419Hz) */
264 #define AO_BEEP_ddd     80      /* 4688Hz (4682Hz) */
265 #define AO_BEEP_eeef    76      /* 4934Hz (4961Hz) */
266 #define AO_BEEP_eee     71      /* 5282Hz (5256Hz) */
267 #define AO_BEEP_fff     67      /* 5597Hz (5568Hz) */
268 #define AO_BEEP_fffs    64      /* 5859Hz (5899Hz) */
269 #define AO_BEEP_ggg     60      /* 6250Hz */
270
271 /* Set the beeper to the specified tone */
272 void
273 ao_beep(uint8_t beep);
274
275 /* Turn on the beeper for the specified time */
276 void
277 ao_beep_for(uint8_t beep, uint16_t ticks) __reentrant;
278
279 /* Initialize the beeper */
280 void
281 ao_beep_init(void);
282
283 /*
284  * ao_led.c
285  */
286
287 #define AO_LED_NONE     0
288
289 /* Turn on the specified LEDs */
290 void
291 ao_led_on(uint8_t colors);
292
293 /* Turn off the specified LEDs */
294 void
295 ao_led_off(uint8_t colors);
296
297 /* Set all of the LEDs to the specified state */
298 void
299 ao_led_set(uint8_t colors);
300
301 /* Toggle the specified LEDs */
302 void
303 ao_led_toggle(uint8_t colors);
304
305 /* Turn on the specified LEDs for the indicated interval */
306 void
307 ao_led_for(uint8_t colors, uint16_t ticks) __reentrant;
308
309 /* Initialize the LEDs */
310 void
311 ao_led_init(uint8_t enable);
312
313 /*
314  * ao_romconfig.c
315  */
316
317 #define AO_ROMCONFIG_VERSION    2
318
319 struct ao_romconfig {
320         uint16_t        version;
321         uint16_t        check;
322         uint16_t        serial_number;
323         uint32_t        radio_cal;
324 };
325
326 #ifdef AVR
327 extern __code struct ao_romconfig ao_romconfig __attribute__ ((section("romconfig")));
328 #else
329 extern __code __at (0x00a0) struct ao_romconfig ao_romconfig;
330 #endif
331
332 #if HAS_USB
333 #ifdef AVR
334 extern const uint8_t ao_usb_descriptors [];
335 #else
336 extern __code __at (0x00aa) uint8_t ao_usb_descriptors [];
337 #endif
338 #endif
339
340 /*
341  * ao_usb.c
342  */
343
344 /* Put one character to the USB output queue */
345 void
346 ao_usb_putchar(char c);
347
348 /* Get one character from the USB input queue */
349 char
350 ao_usb_getchar(void);
351
352 /* Poll for a charcter on the USB input queue.
353  * returns AO_READ_AGAIN if none are available
354  */
355 char
356 ao_usb_pollchar(void);
357
358 /* Flush the USB output queue */
359 void
360 ao_usb_flush(void);
361
362 #if HAS_USB
363 /* USB interrupt handler */
364 void
365 ao_usb_isr(void) __interrupt(6);
366 #endif
367
368 /* Enable the USB controller */
369 void
370 ao_usb_enable(void);
371
372 /* Disable the USB controller */
373 void
374 ao_usb_disable(void);
375
376 /* Initialize the USB system */
377 void
378 ao_usb_init(void);
379
380 /*
381  * ao_cmd.c
382  */
383
384 enum ao_cmd_status {
385         ao_cmd_success = 0,
386         ao_cmd_lex_error = 1,
387         ao_cmd_syntax_error = 2,
388 };
389
390 extern __xdata uint16_t ao_cmd_lex_i;
391 extern __xdata uint32_t ao_cmd_lex_u32;
392 extern __xdata char     ao_cmd_lex_c;
393 extern __xdata enum ao_cmd_status ao_cmd_status;
394
395 void
396 ao_cmd_lex(void);
397
398 void
399 ao_cmd_put8(uint8_t v);
400
401 void
402 ao_cmd_put16(uint16_t v);
403
404 void
405 ao_cmd_white(void);
406
407 void
408 ao_cmd_hex(void);
409
410 void
411 ao_cmd_decimal(void);
412
413 uint8_t
414 ao_match_word(__code char *word);
415
416 struct ao_cmds {
417         void            (*func)(void);
418         const char      *help;
419 };
420
421 void
422 ao_cmd_register(__code struct ao_cmds *cmds);
423
424 void
425 ao_cmd_init(void);
426
427 #if HAS_CMD_FILTER
428 /*
429  * Provided by an external module to filter raw command lines
430  */
431 uint8_t
432 ao_cmd_filter(void);
433 #endif
434
435 /*
436  * ao_dma.c
437  */
438
439 /* Allocate a DMA channel. the 'done' parameter will be set when the
440  * dma is finished and will be used to wakeup any waiters
441  */
442
443 uint8_t
444 ao_dma_alloc(__xdata uint8_t * done);
445
446 /* Setup a DMA channel */
447 void
448 ao_dma_set_transfer(uint8_t id,
449                     void __xdata *srcaddr,
450                     void __xdata *dstaddr,
451                     uint16_t count,
452                     uint8_t cfg0,
453                     uint8_t cfg1);
454
455 /* Start a DMA channel */
456 void
457 ao_dma_start(uint8_t id);
458
459 /* Manually trigger a DMA channel */
460 void
461 ao_dma_trigger(uint8_t id);
462
463 /* Abort a running DMA transfer */
464 void
465 ao_dma_abort(uint8_t id);
466
467 /* DMA interrupt routine */
468 void
469 ao_dma_isr(void) __interrupt(8);
470
471 /*
472  * ao_mutex.c
473  */
474
475 void
476 ao_mutex_get(__xdata uint8_t *ao_mutex) __reentrant;
477
478 void
479 ao_mutex_put(__xdata uint8_t *ao_mutex) __reentrant;
480
481 /*
482  * Storage interface, provided by one of the eeprom or flash
483  * drivers
484  */
485
486 /* Total bytes of available storage */
487 extern __xdata uint32_t ao_storage_total;
488
489 /* Block size - device is erased in these units. At least 256 bytes */
490 extern __xdata uint32_t ao_storage_block;
491
492 /* Byte offset of config block. Will be ao_storage_block bytes long */
493 extern __xdata uint32_t ao_storage_config;
494
495 /* Storage unit size - device reads and writes must be within blocks of this size. Usually 256 bytes. */
496 extern __xdata uint16_t ao_storage_unit;
497
498 #define AO_STORAGE_ERASE_LOG    (ao_storage_config + AO_CONFIG_MAX_SIZE)
499
500 /* Initialize above values. Can only be called once the OS is running */
501 void
502 ao_storage_setup(void) __reentrant;
503
504 /* Write data. Returns 0 on failure, 1 on success */
505 uint8_t
506 ao_storage_write(uint32_t pos, __xdata void *buf, uint16_t len) __reentrant;
507
508 /* Read data. Returns 0 on failure, 1 on success */
509 uint8_t
510 ao_storage_read(uint32_t pos, __xdata void *buf, uint16_t len) __reentrant;
511
512 /* Erase a block of storage. This always clears ao_storage_block bytes */
513 uint8_t
514 ao_storage_erase(uint32_t pos) __reentrant;
515
516 /* Flush any pending writes to stable storage */
517 void
518 ao_storage_flush(void) __reentrant;
519
520 /* Initialize the storage code */
521 void
522 ao_storage_init(void);
523
524 /*
525  * Low-level functions wrapped by ao_storage.c
526  */
527
528 /* Read data within a storage unit */
529 uint8_t
530 ao_storage_device_read(uint32_t pos, __xdata void *buf, uint16_t len) __reentrant;
531
532 /* Write data within a storage unit */
533 uint8_t
534 ao_storage_device_write(uint32_t pos, __xdata void *buf, uint16_t len) __reentrant;
535
536 /* Initialize low-level device bits */
537 void
538 ao_storage_device_init(void);
539
540 /* Print out information about flash chips */
541 void
542 ao_storage_device_info(void) __reentrant;
543
544 /*
545  * ao_log.c
546  */
547
548 /* We record flight numbers in the first record of
549  * the log. Tasks may wait for this to be initialized
550  * by sleeping on this variable.
551  */
552 extern __xdata uint16_t ao_flight_number;
553
554 extern __pdata uint32_t ao_log_current_pos;
555 extern __pdata uint32_t ao_log_end_pos;
556 extern __pdata uint32_t ao_log_start_pos;
557 extern __xdata uint8_t  ao_log_running;
558 extern __xdata enum flight_state ao_log_state;
559
560 /* required functions from the underlying log system */
561
562 /* Return the flight number from the given log slot, 0 if none */
563 uint16_t
564 ao_log_flight(uint8_t slot);
565
566 /* Flush the log */
567 void
568 ao_log_flush(void);
569
570 /* Logging thread main routine */
571 void
572 ao_log(void);
573
574 /* functions provided in ao_log.c */
575
576 /* Figure out the current flight number */
577 void
578 ao_log_scan(void) __reentrant;
579
580 /* Return the position of the start of the given log slot */
581 uint32_t
582 ao_log_pos(uint8_t slot);
583
584 /* Start logging to eeprom */
585 void
586 ao_log_start(void);
587
588 /* Stop logging */
589 void
590 ao_log_stop(void);
591
592 /* Initialize the logging system */
593 void
594 ao_log_init(void);
595
596 /* Write out the current flight number to the erase log */
597 void
598 ao_log_write_erase(uint8_t pos);
599
600 /* Returns true if there are any logs stored in eeprom */
601 uint8_t
602 ao_log_present(void);
603
604 /* Returns true if there is no more storage space available */
605 uint8_t
606 ao_log_full(void);
607
608 /*
609  * ao_log_big.c
610  */
611
612 /*
613  * The data log is recorded in the eeprom as a sequence
614  * of data packets.
615  *
616  * Each packet starts with a 4-byte header that has the
617  * packet type, the packet checksum and the tick count. Then
618  * they all contain 2 16 bit values which hold packet-specific
619  * data.
620  *
621  * For each flight, the first packet
622  * is FLIGHT packet, indicating the serial number of the
623  * device and a unique number marking the number of flights
624  * recorded by this device.
625  *
626  * During flight, data from the accelerometer and barometer
627  * are recorded in SENSOR packets, using the raw 16-bit values
628  * read from the A/D converter.
629  *
630  * Also during flight, but at a lower rate, the deployment
631  * sensors are recorded in DEPLOY packets. The goal here is to
632  * detect failure in the deployment circuits.
633  *
634  * STATE packets hold state transitions as the flight computer
635  * transitions through different stages of the flight.
636  */
637 #define AO_LOG_FLIGHT           'F'
638 #define AO_LOG_SENSOR           'A'
639 #define AO_LOG_TEMP_VOLT        'T'
640 #define AO_LOG_DEPLOY           'D'
641 #define AO_LOG_STATE            'S'
642 #define AO_LOG_GPS_TIME         'G'
643 #define AO_LOG_GPS_LAT          'N'
644 #define AO_LOG_GPS_LON          'W'
645 #define AO_LOG_GPS_ALT          'H'
646 #define AO_LOG_GPS_SAT          'V'
647 #define AO_LOG_GPS_DATE         'Y'
648
649 #define AO_LOG_POS_NONE         (~0UL)
650
651 struct ao_log_record {
652         char                    type;
653         uint8_t                 csum;
654         uint16_t                tick;
655         union {
656                 struct {
657                         int16_t         ground_accel;
658                         uint16_t        flight;
659                 } flight;
660                 struct {
661                         int16_t         accel;
662                         int16_t         pres;
663                 } sensor;
664                 struct {
665                         int16_t         temp;
666                         int16_t         v_batt;
667                 } temp_volt;
668                 struct {
669                         int16_t         drogue;
670                         int16_t         main;
671                 } deploy;
672                 struct {
673                         uint16_t        state;
674                         uint16_t        reason;
675                 } state;
676                 struct {
677                         uint8_t         hour;
678                         uint8_t         minute;
679                         uint8_t         second;
680                         uint8_t         flags;
681                 } gps_time;
682                 int32_t         gps_latitude;
683                 int32_t         gps_longitude;
684                 struct {
685                         int16_t         altitude;
686                         uint16_t        unused;
687                 } gps_altitude;
688                 struct {
689                         uint16_t        svid;
690                         uint8_t         unused;
691                         uint8_t         c_n;
692                 } gps_sat;
693                 struct {
694                         uint8_t         year;
695                         uint8_t         month;
696                         uint8_t         day;
697                         uint8_t         extra;
698                 } gps_date;
699                 struct {
700                         uint16_t        d0;
701                         uint16_t        d1;
702                 } anon;
703         } u;
704 };
705
706 /* Write a record to the eeprom log */
707 uint8_t
708 ao_log_data(__xdata struct ao_log_record *log) __reentrant;
709
710 /*
711  * ao_flight.c
712  */
713
714 enum ao_flight_state {
715         ao_flight_startup = 0,
716         ao_flight_idle = 1,
717         ao_flight_pad = 2,
718         ao_flight_boost = 3,
719         ao_flight_fast = 4,
720         ao_flight_coast = 5,
721         ao_flight_drogue = 6,
722         ao_flight_main = 7,
723         ao_flight_landed = 8,
724         ao_flight_invalid = 9
725 };
726
727 extern __pdata enum ao_flight_state     ao_flight_state;
728
729 extern __pdata uint16_t                 ao_launch_time;
730 extern __xdata uint8_t                  ao_flight_force_idle;
731
732 /* Flight thread */
733 void
734 ao_flight(void);
735
736 /* Initialize flight thread */
737 void
738 ao_flight_init(void);
739
740 /*
741  * ao_flight_nano.c
742  */
743
744 void
745 ao_flight_nano_init(void);
746
747 /*
748  * ao_sample.c
749  */
750
751 /*
752  * Barometer calibration
753  *
754  * We directly sample the barometer. The specs say:
755  *
756  * Pressure range: 15-115 kPa
757  * Voltage at 115kPa: 2.82
758  * Output scale: 27mV/kPa
759  *
760  * If we want to detect launch with the barometer, we need
761  * a large enough bump to not be fooled by noise. At typical
762  * launch elevations (0-2000m), a 200Pa pressure change cooresponds
763  * to about a 20m elevation change. This is 5.4mV, or about 3LSB.
764  * As all of our calculations are done in 16 bits, we'll actually see a change
765  * of 16 times this though
766  *
767  * 27 mV/kPa * 32767 / 3300 counts/mV = 268.1 counts/kPa
768  */
769
770 /* Accelerometer calibration
771  *
772  * We're sampling the accelerometer through a resistor divider which
773  * consists of 5k and 10k resistors. This multiplies the values by 2/3.
774  * That goes into the cc1111 A/D converter, which is running at 11 bits
775  * of precision with the bits in the MSB of the 16 bit value. Only positive
776  * values are used, so values should range from 0-32752 for 0-3.3V. The
777  * specs say we should see 40mV/g (uncalibrated), multiply by 2/3 for what
778  * the A/D converter sees (26.67 mV/g). We should see 32752/3300 counts/mV,
779  * for a final computation of:
780  *
781  * 26.67 mV/g * 32767/3300 counts/mV = 264.8 counts/g
782  *
783  * Zero g was measured at 16000 (we would expect 16384).
784  * Note that this value is only require to tell if the
785  * rocket is standing upright. Once that is determined,
786  * the value of the accelerometer is averaged for 100 samples
787  * to find the resting accelerometer value, which is used
788  * for all further flight computations
789  */
790
791 #define GRAVITY 9.80665
792
793 /*
794  * Above this height, the baro sensor doesn't work
795  */
796 #define AO_MAX_BARO_HEIGHT      12000
797
798 /*
799  * Above this speed, baro measurements are unreliable
800  */
801 #define AO_MAX_BARO_SPEED       200
802
803 #define ACCEL_NOSE_UP   (ao_accel_2g >> 2)
804
805 /*
806  * Speed and acceleration are scaled by 16 to provide a bit more
807  * resolution while still having reasonable range. Note that this
808  * limits speed to 2047m/s (around mach 6) and acceleration to
809  * 2047m/s² (over 200g)
810  */
811
812 #define AO_M_TO_HEIGHT(m)       ((int16_t) (m))
813 #define AO_MS_TO_SPEED(ms)      ((int16_t) ((ms) * 16))
814 #define AO_MSS_TO_ACCEL(mss)    ((int16_t) ((mss) * 16))
815
816 extern __pdata uint16_t ao_sample_tick;         /* time of last data */
817 extern __pdata int16_t  ao_sample_pres;         /* most recent pressure sensor reading */
818 extern __pdata int16_t  ao_sample_alt;          /* MSL of ao_sample_pres */
819 extern __pdata int16_t  ao_sample_height;       /* AGL of ao_sample_pres */
820 extern __data uint8_t   ao_sample_adc;          /* Ring position of last processed sample */
821
822 #if HAS_ACCEL
823 extern __pdata int16_t  ao_sample_accel;        /* most recent accel sensor reading */
824 #endif
825
826 extern __xdata int16_t  ao_ground_pres;         /* startup pressure */
827 extern __xdata int16_t  ao_ground_height;       /* MSL of ao_ground_pres */
828
829 #if HAS_ACCEL
830 extern __xdata int16_t  ao_ground_accel;        /* startup acceleration */
831 extern __xdata int16_t  ao_accel_2g;            /* factory accel calibration */
832 extern __xdata int32_t  ao_accel_scale;         /* sensor to m/s² conversion */
833 #endif
834
835 void ao_sample_init(void);
836
837 /* returns FALSE in preflight mode, TRUE in flight mode */
838 uint8_t ao_sample(void);
839
840 /*
841  * ao_kalman.c
842  */
843
844 #define to_fix16(x) ((int16_t) ((x) * 65536.0 + 0.5))
845 #define to_fix32(x) ((int32_t) ((x) * 65536.0 + 0.5))
846 #define from_fix(x)     ((x) >> 16)
847
848 extern __pdata int16_t                  ao_height;      /* meters */
849 extern __pdata int16_t                  ao_speed;       /* m/s * 16 */
850 extern __pdata int16_t                  ao_accel;       /* m/s² * 16 */
851 extern __pdata int16_t                  ao_max_height;  /* max of ao_height */
852
853 extern __pdata int16_t                  ao_error_h;
854 extern __pdata int16_t                  ao_error_h_sq_avg;
855
856 #if HAS_ACCEL
857 extern __pdata int16_t                  ao_error_a;
858 #endif
859
860 void ao_kalman(void);
861
862 /*
863  * ao_report.c
864  */
865
866 void
867 ao_report_init(void);
868
869 /*
870  * ao_convert.c
871  *
872  * Given raw data, convert to SI units
873  */
874
875 /* pressure from the sensor to altitude in meters */
876 int16_t
877 ao_pres_to_altitude(int16_t pres) __reentrant;
878
879 int16_t
880 ao_altitude_to_pres(int16_t alt) __reentrant;
881
882 int16_t
883 ao_temp_to_dC(int16_t temp) __reentrant;
884
885 /*
886  * ao_dbg.c
887  *
888  * debug another telemetrum board
889  */
890
891 /* Send a byte to the dbg target */
892 void
893 ao_dbg_send_byte(uint8_t byte);
894
895 /* Receive a byte from the dbg target */
896 uint8_t
897 ao_dbg_recv_byte(void);
898
899 /* Start a bulk transfer to/from dbg target memory */
900 void
901 ao_dbg_start_transfer(uint16_t addr);
902
903 /* End a bulk transfer to/from dbg target memory */
904 void
905 ao_dbg_end_transfer(void);
906
907 /* Write a byte to dbg target memory */
908 void
909 ao_dbg_write_byte(uint8_t byte);
910
911 /* Read a byte from dbg target memory */
912 uint8_t
913 ao_dbg_read_byte(void);
914
915 /* Enable dbg mode, switching use of the pins */
916 void
917 ao_dbg_debug_mode(void);
918
919 /* Reset the dbg target */
920 void
921 ao_dbg_reset(void);
922
923 void
924 ao_dbg_init(void);
925
926 /*
927  * ao_serial.c
928  */
929
930 #if HAS_SERIAL_1
931 #ifndef USE_SERIAL_STDIN
932 #error Please define USE_SERIAL_STDIN
933 #endif
934
935 void
936 ao_serial_rx1_isr(void) __interrupt(3);
937
938 void
939 ao_serial_tx1_isr(void) __interrupt(14);
940
941 char
942 ao_serial_getchar(void) __critical;
943
944 #if USE_SERIAL_STDIN
945 char
946 ao_serial_pollchar(void) __critical;
947
948 void
949 ao_serial_set_stdin(uint8_t stdin);
950 #endif
951
952 void
953 ao_serial_putchar(char c) __critical;
954
955 void
956 ao_serial_drain(void) __critical;
957
958 #define AO_SERIAL_SPEED_4800    0
959 #define AO_SERIAL_SPEED_9600    1
960 #define AO_SERIAL_SPEED_19200   2
961 #define AO_SERIAL_SPEED_57600   3
962
963 void
964 ao_serial_set_speed(uint8_t speed);
965
966 void
967 ao_serial_init(void);
968 #endif
969
970 /*
971  * ao_spi.c
972  */
973
974 void
975 ao_spi_send(void __xdata *block, uint16_t len) __reentrant;
976
977 void
978 ao_spi_recv(void __xdata *block, uint16_t len) __reentrant;
979
980 void
981 ao_spi_init(void);
982
983 /*
984  * ao_gps.c
985  */
986
987 #define AO_GPS_NUM_SAT_MASK     (0xf << 0)
988 #define AO_GPS_NUM_SAT_SHIFT    (0)
989
990 #define AO_GPS_VALID            (1 << 4)
991 #define AO_GPS_RUNNING          (1 << 5)
992 #define AO_GPS_DATE_VALID       (1 << 6)
993 #define AO_GPS_COURSE_VALID     (1 << 7)
994
995 extern __xdata uint16_t ao_gps_tick;
996
997 struct ao_gps_data {
998         uint8_t                 year;
999         uint8_t                 month;
1000         uint8_t                 day;
1001         uint8_t                 hour;
1002         uint8_t                 minute;
1003         uint8_t                 second;
1004         uint8_t                 flags;
1005         int32_t                 latitude;       /* degrees * 10⁷ */
1006         int32_t                 longitude;      /* degrees * 10⁷ */
1007         int16_t                 altitude;       /* m */
1008         uint16_t                ground_speed;   /* cm/s */
1009         uint8_t                 course;         /* degrees / 2 */
1010         uint8_t                 hdop;           /* * 5 */
1011         int16_t                 climb_rate;     /* cm/s */
1012         uint16_t                h_error;        /* m */
1013         uint16_t                v_error;        /* m */
1014 };
1015
1016 struct ao_gps_sat_data {
1017         uint8_t         svid;
1018         uint8_t         c_n_1;
1019 };
1020
1021 #define AO_MAX_GPS_TRACKING     12
1022
1023 struct ao_gps_tracking_data {
1024         uint8_t                 channels;
1025         struct ao_gps_sat_data  sats[AO_MAX_GPS_TRACKING];
1026 };
1027
1028 extern __xdata uint8_t ao_gps_mutex;
1029 extern __xdata struct ao_gps_data ao_gps_data;
1030 extern __xdata struct ao_gps_tracking_data ao_gps_tracking_data;
1031
1032 void
1033 ao_gps(void);
1034
1035 void
1036 ao_gps_print(__xdata struct ao_gps_data *gps_data);
1037
1038 void
1039 ao_gps_tracking_print(__xdata struct ao_gps_tracking_data *gps_tracking_data);
1040
1041 void
1042 ao_gps_init(void);
1043
1044 /*
1045  * ao_gps_report.c
1046  */
1047
1048 void
1049 ao_gps_report(void);
1050
1051 void
1052 ao_gps_report_init(void);
1053
1054 /*
1055  * ao_telemetry.c
1056  */
1057
1058 #define AO_MAX_CALLSIGN                 8
1059
1060 struct ao_telemetry {
1061         uint16_t                serial;
1062         uint16_t                flight;
1063         uint8_t                 flight_state;
1064         int16_t                 accel;
1065         int16_t                 ground_accel;
1066         union {
1067                 struct {
1068                         int16_t                 speed;
1069                         int16_t                 unused;
1070                 } k;
1071                 int32_t         flight_vel;
1072         } u;
1073         int16_t                 height;
1074         int16_t                 ground_pres;
1075         int16_t                 accel_plus_g;
1076         int16_t                 accel_minus_g;
1077         struct ao_adc           adc;
1078         struct ao_gps_data      gps;
1079         char                    callsign[AO_MAX_CALLSIGN];
1080         struct ao_gps_tracking_data     gps_tracking;
1081 };
1082
1083 struct ao_telemetry_tiny {
1084         uint16_t                serial;
1085         uint16_t                flight;
1086         uint8_t                 flight_state;
1087         int16_t                 height;         /* AGL in meters */
1088         int16_t                 speed;          /* in m/s * 16 */
1089         int16_t                 accel;          /* in m/s² * 16 */
1090         int16_t                 ground_pres;    /* sensor units */
1091         struct ao_adc           adc;            /* raw ADC readings */
1092         char                    callsign[AO_MAX_CALLSIGN];
1093 };
1094
1095 /*
1096  * ao_radio_recv tacks on rssi and status bytes
1097  */
1098 struct ao_telemetry_recv {
1099         struct ao_telemetry     telemetry;
1100         int8_t                  rssi;
1101         uint8_t                 status;
1102 };
1103
1104 struct ao_telemetry_tiny_recv {
1105         struct ao_telemetry_tiny        telemetry_tiny;
1106         int8_t                          rssi;
1107         uint8_t                         status;
1108 };
1109
1110 /* Set delay between telemetry reports (0 to disable) */
1111
1112 #define AO_TELEMETRY_INTERVAL_PAD       AO_MS_TO_TICKS(1000)
1113 #define AO_TELEMETRY_INTERVAL_FLIGHT    AO_MS_TO_TICKS(100)
1114 #define AO_TELEMETRY_INTERVAL_RECOVER   AO_MS_TO_TICKS(1000)
1115
1116 void
1117 ao_telemetry_set_interval(uint16_t interval);
1118
1119 void
1120 ao_rdf_set(uint8_t rdf);
1121
1122 void
1123 ao_telemetry_init(void);
1124
1125 void
1126 ao_telemetry_tiny_init(void);
1127
1128 /*
1129  * ao_radio.c
1130  */
1131
1132 extern __xdata uint8_t  ao_radio_dma;
1133 extern __xdata uint8_t ao_radio_dma_done;
1134 extern __xdata uint8_t ao_radio_done;
1135 extern __xdata uint8_t ao_radio_mutex;
1136
1137 void
1138 ao_radio_general_isr(void) __interrupt(16);
1139
1140 void
1141 ao_radio_get(uint8_t len);
1142
1143 #define ao_radio_put() ao_mutex_put(&ao_radio_mutex)
1144
1145 void
1146 ao_radio_set_packet(void);
1147
1148 void
1149 ao_radio_send(__xdata void *data, uint8_t size) __reentrant;
1150
1151 uint8_t
1152 ao_radio_recv(__xdata void *data, uint8_t size) __reentrant;
1153
1154 void
1155 ao_radio_recv_abort(void);
1156
1157 void
1158 ao_radio_rdf(int ms);
1159
1160 void
1161 ao_radio_rdf_abort(void);
1162
1163 void
1164 ao_radio_idle(void);
1165
1166 void
1167 ao_radio_init(void);
1168
1169 /*
1170  * ao_monitor.c
1171  */
1172
1173 extern const char const * const ao_state_names[];
1174
1175 void
1176 ao_monitor(void);
1177
1178 #define AO_MONITORING_OFF       0
1179 #define AO_MONITORING_FULL      1
1180 #define AO_MONITORING_TINY      2
1181
1182 void
1183 ao_set_monitor(uint8_t monitoring);
1184
1185 void
1186 ao_monitor_init(uint8_t led, uint8_t monitoring) __reentrant;
1187
1188 /*
1189  * ao_stdio.c
1190  */
1191
1192 #define AO_READ_AGAIN   ((char) -1)
1193
1194 struct ao_stdio {
1195         char    (*pollchar)(void);
1196         void    (*putchar)(char c) __reentrant;
1197         void    (*flush)(void);
1198         uint8_t echo;
1199 };
1200
1201 extern __xdata struct ao_stdio ao_stdios[];
1202 extern __data int8_t ao_cur_stdio;
1203 extern __data int8_t ao_num_stdios;
1204
1205 void
1206 flush(void);
1207
1208 extern __xdata uint8_t ao_stdin_ready;
1209
1210 uint8_t
1211 ao_echo(void);
1212
1213 int8_t
1214 ao_add_stdio(char (*pollchar)(void),
1215              void (*putchar)(char) __reentrant,
1216              void (*flush)(void)) __reentrant;
1217
1218 #ifdef AVR
1219 void
1220 ao_stdio_init(void);
1221 #else
1222 #define ao_stdio_init()
1223 #endif
1224
1225 /*
1226  * ao_ignite.c
1227  */
1228
1229 enum ao_igniter {
1230         ao_igniter_drogue = 0,
1231         ao_igniter_main = 1
1232 };
1233
1234 void
1235 ao_ignite(enum ao_igniter igniter);
1236
1237 enum ao_igniter_status {
1238         ao_igniter_unknown,     /* unknown status (ambiguous voltage) */
1239         ao_igniter_ready,       /* continuity detected */
1240         ao_igniter_active,      /* igniter firing */
1241         ao_igniter_open,        /* open circuit detected */
1242 };
1243
1244 enum ao_igniter_status
1245 ao_igniter_status(enum ao_igniter igniter);
1246
1247 void
1248 ao_igniter_init(void);
1249
1250 /*
1251  * ao_config.c
1252  */
1253
1254 #define AO_CONFIG_MAJOR 1
1255 #define AO_CONFIG_MINOR 4
1256
1257 struct ao_config {
1258         uint8_t         major;
1259         uint8_t         minor;
1260         uint16_t        main_deploy;
1261         int16_t         accel_plus_g;           /* changed for minor version 2 */
1262         uint8_t         radio_channel;
1263         char            callsign[AO_MAX_CALLSIGN + 1];
1264         uint8_t         apogee_delay;           /* minor version 1 */
1265         int16_t         accel_minus_g;          /* minor version 2 */
1266         uint32_t        radio_cal;              /* minor version 3 */
1267         uint32_t        flight_log_max;         /* minor version 4 */
1268 };
1269
1270 extern __xdata struct ao_config ao_config;
1271
1272 #define AO_CONFIG_MAX_SIZE      128
1273
1274 void
1275 ao_config_get(void);
1276
1277 void
1278 ao_config_put(void);
1279
1280 void
1281 ao_config_init(void);
1282
1283 /*
1284  * ao_rssi.c
1285  */
1286
1287 void
1288 ao_rssi_set(int rssi_value);
1289
1290 void
1291 ao_rssi_init(uint8_t rssi_led);
1292
1293 /*
1294  * ao_product.c
1295  *
1296  * values which need to be defined for
1297  * each instance of a product
1298  */
1299
1300 extern const char ao_version[];
1301 extern const char ao_manufacturer[];
1302 extern const char ao_product[];
1303
1304 /*
1305  * Fifos
1306  */
1307
1308 #define AO_FIFO_SIZE    32
1309
1310 struct ao_fifo {
1311         uint8_t insert;
1312         uint8_t remove;
1313         char    fifo[AO_FIFO_SIZE];
1314 };
1315
1316 #define ao_fifo_insert(f,c) do { \
1317         (f).fifo[(f).insert] = (c); \
1318         (f).insert = ((f).insert + 1) & (AO_FIFO_SIZE-1); \
1319 } while(0)
1320
1321 #define ao_fifo_remove(f,c) do {\
1322         c = (f).fifo[(f).remove]; \
1323         (f).remove = ((f).remove + 1) & (AO_FIFO_SIZE-1); \
1324 } while(0)
1325
1326 #define ao_fifo_full(f)         ((((f).insert + 1) & (AO_FIFO_SIZE-1)) == (f).remove)
1327 #define ao_fifo_empty(f)        ((f).insert == (f).remove)
1328
1329 /*
1330  * ao_packet.c
1331  *
1332  * Packet-based command interface
1333  */
1334
1335 #define AO_PACKET_MAX           64
1336 #define AO_PACKET_SYN           (uint8_t) 0xff
1337
1338 struct ao_packet {
1339         uint8_t         addr;
1340         uint8_t         len;
1341         uint8_t         seq;
1342         uint8_t         ack;
1343         uint8_t         d[AO_PACKET_MAX];
1344         uint8_t         callsign[AO_MAX_CALLSIGN];
1345 };
1346
1347 struct ao_packet_recv {
1348         struct ao_packet        packet;
1349         int8_t                  rssi;
1350         uint8_t                 status;
1351 };
1352
1353 extern __xdata struct ao_packet_recv ao_rx_packet;
1354 extern __xdata struct ao_packet ao_tx_packet;
1355 extern __xdata struct ao_task   ao_packet_task;
1356 extern __xdata uint8_t ao_packet_enable;
1357 extern __xdata uint8_t ao_packet_master_sleeping;
1358 extern __pdata uint8_t ao_packet_rx_len, ao_packet_rx_used, ao_packet_tx_used;
1359
1360 void
1361 ao_packet_send(void);
1362
1363 uint8_t
1364 ao_packet_recv(void);
1365
1366 void
1367 ao_packet_flush(void);
1368
1369 void
1370 ao_packet_putchar(char c) __reentrant;
1371
1372 char
1373 ao_packet_pollchar(void) __critical;
1374
1375 /* ao_packet_master.c */
1376
1377 void
1378 ao_packet_master_init(void);
1379
1380 /* ao_packet_slave.c */
1381
1382 void
1383 ao_packet_slave_start(void);
1384
1385 void
1386 ao_packet_slave_stop(void);
1387
1388 void
1389 ao_packet_slave_init(uint8_t enable);
1390
1391 /* ao_btm.c */
1392
1393 /* Shared by USB, so the USB code calls this function */
1394 void
1395 ao_btm_isr(void);
1396
1397 void
1398 ao_btm_init(void);
1399
1400 /* ao_debug_avr.c */
1401 void
1402 ao_debug_init(void);
1403
1404 #endif /* _AO_H_ */