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