2 * Copyright © 2012 Keith Packard <keithp@keithp.com>
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; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
20 #include <ao_button.h>
24 #define ao_button_queue(b,v) ao_event_put_isr(AO_EVENT_BUTTON, b, v)
26 #define ao_button_queue(b,v)
29 #define AO_BUTTON_DEBOUNCE_INTERVAL AO_MS_TO_TICKS(50)
31 struct ao_button_state {
36 static struct ao_button_state ao_button_state[AO_BUTTON_COUNT];
38 #define port(q) AO_BUTTON_ ## q ## _PORT
39 #define bit(q) AO_BUTTON_ ## q
40 #define pin(q) AO_BUTTON_ ## q ## _PIN
42 #ifndef AO_BUTTON_INVERTED
43 #define AO_BUTTON_INVERTED 1
46 #if AO_BUTTON_INVERTED
47 /* pins are inverted */
48 #define ao_button_value(b) !ao_gpio_get(port(b), bit(b), pin(b))
50 #define ao_button_value(b) ao_gpio_get(port(b), bit(b), pin(b))
54 _ao_button_get(uint8_t b)
57 #if AO_BUTTON_COUNT > 0
58 case 0: return ao_button_value(0);
60 #if AO_BUTTON_COUNT > 1
61 case 1: return ao_button_value(1);
63 #if AO_BUTTON_COUNT > 2
64 case 2: return ao_button_value(2);
66 #if AO_BUTTON_COUNT > 3
67 case 3: return ao_button_value(3);
69 #if AO_BUTTON_COUNT > 4
70 case 4: return ao_button_value(4);
77 _ao_button_check(uint8_t b)
79 uint8_t value = _ao_button_get(b);
81 if (value != ao_button_state[b].value) {
82 AO_TICK_TYPE now = ao_time();
84 if ((now - ao_button_state[b].time) >= AO_BUTTON_DEBOUNCE_INTERVAL) {
85 ao_button_state[b].value = value;
86 ao_button_queue(b, value);
88 ao_button_state[b].time = now;
93 _ao_button_init(uint8_t b)
95 uint8_t m = ao_arch_irqsave();
96 uint8_t value = _ao_button_get(b);
97 ao_button_state[b].value = value;
98 ao_button_state[b].time = ao_time();
99 ao_button_queue(b, value);
100 ao_arch_irqrestore(m);
105 ao_button_get(uint8_t b)
107 return ao_button_state[b].value;
115 for (b = 0; b < AO_BUTTON_COUNT; b++)
119 #define init(b) do { \
120 ao_enable_port(port(b)); \
122 ao_exti_setup(port(b), bit(b), \
123 AO_BUTTON_MODE|AO_EXTI_MODE_FALLING|AO_EXTI_MODE_RISING|AO_EXTI_PRIORITY_MED, \
125 ao_exti_enable(port(b), bit(b)); \
126 _ao_button_init(b); \
132 #if AO_BUTTON_COUNT > 0
135 #if AO_BUTTON_COUNT > 1
138 #if AO_BUTTON_COUNT > 2
141 #if AO_BUTTON_COUNT > 3
144 #if AO_BUTTON_COUNT > 4