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