altos/stmf0: Have fast ADC ring buffer code use wrap-around
[fw/altos] / src / stmf0 / ao_adc_fast.h
1 /*
2  * Copyright © 2015 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_ADC_FAST_H_
19 #define _AO_ADC_FAST_H_
20
21 void
22 ao_adc_read(uint16_t *dest, int len);
23
24 void
25 ao_adc_init(void);
26
27 /* Total ring size in samples */
28 #define AO_ADC_RING_SIZE        256
29
30 extern uint16_t ao_adc_ring[AO_ADC_RING_SIZE];
31
32 #define ao_adc_ring_step(pos,inc)       (((pos) + (inc)) & (AO_ADC_RING_SIZE - 1))
33
34 extern uint16_t ao_adc_ring_head, ao_adc_ring_remain;
35 extern uint16_t ao_adc_running;
36
37 /*
38  * Place to start fetching values from
39  */
40 static inline uint16_t
41 ao_adc_ring_tail(void)
42 {
43         return (ao_adc_ring_head - ao_adc_ring_remain) & (AO_ADC_RING_SIZE - 1);
44 }
45
46 void
47 _ao_adc_start(void);
48
49 /*
50  * Space available to write ADC values into
51  */
52 static inline uint16_t
53 _ao_adc_space(void)
54 {
55         /* Free to end of buffer? */
56         if (ao_adc_ring_remain <= ao_adc_ring_head)
57                 return AO_ADC_RING_SIZE - ao_adc_ring_head;
58
59         /* no, return just the unused entries beyond head */
60         return AO_ADC_RING_SIZE - ao_adc_ring_remain;
61 }
62
63 static inline uint16_t
64 ao_adc_get(uint16_t n)
65 {
66         ao_arch_block_interrupts();
67         while (ao_adc_ring_remain < n) {
68                 if (!ao_adc_running)
69                         _ao_adc_start();
70                 ao_sleep(&ao_adc_ring_head);
71         }
72         ao_arch_release_interrupts();
73         return ao_adc_ring_tail();
74 }
75
76 static inline void
77 ao_adc_ack(uint16_t n)
78 {
79         ao_arch_block_interrupts();
80         ao_adc_ring_remain -= n;
81         if (!ao_adc_running)
82                 _ao_adc_start();
83         ao_arch_release_interrupts();
84 }
85
86 #endif /* _AO_ADC_FAST_H_ */