]> www.fi.muni.cz Git - bike-lights.git/blob - buttons.c
buttons: long/short keypress detection
[bike-lights.git] / buttons.c
1 #include <avr/io.h>
2 #include <avr/interrupt.h>
3
4 #include "lights.h"
5
6 static uint16_t button_start[N_BUTTONS];
7 static unsigned char button_pressed[N_BUTTONS];
8
9 void init_buttons()
10 {
11         // MCUCR |= _BV(ISC00); // any edge generates IRQ
12         // GIMSK |= _BV(INT0); // enable INT0
13         DDRB &= ~(_BV(PB6) | _BV(PB0));
14         PORTB |= _BV(PB6) | _BV(PB0);
15
16         // log_byte(PORTB);
17 }
18
19 extern unsigned char led1_counter;
20
21 static void inline long_press(unsigned char n)
22 {
23         led_set_status(2);
24 }
25
26 static void inline short_press(unsigned char n)
27 {
28         led_set_status(1);
29 }
30
31 void timer_check_buttons()
32 {
33         unsigned char pinb = PINB;
34         unsigned char i;
35         unsigned char port_states[N_BUTTONS] = {
36                 pinb & _BV(PB6),
37                 pinb & _BV(PB0),
38         };
39         for (i = 0; i < N_BUTTONS; i++) {
40                 if (!port_states[i]) { // is pressed
41                         if (button_pressed[i] == 0) {
42                                 // begin of button press
43                                 button_pressed[i] = 1;
44                                 button_start[i] = jiffies;
45 #if 0
46                                 // log_byte(0xC0);
47                                 // log_word(jiffies);
48 #endif
49                         } else if (button_pressed[i] == 1) {
50                                 // been already pressed
51                                 uint16_t duration = jiffies - button_start[i];
52                                 if (duration > 80) {
53                                         // long button press
54                                         button_pressed[i] = 2;
55                                         long_press(i);
56                                 }
57                         }
58                 } else { // is not pressed
59                         if (button_pressed[i]) { // just depressed
60                                 uint16_t duration = jiffies - button_start[i];
61 #if 1
62                                 log_byte(0xC1);
63                                 log_word(duration);
64                                 log_flush();
65 #endif
66                                 button_pressed[i] = 0;
67                                 if (duration > 6 && duration < 30)
68                                         short_press(i);
69                         }
70                 }
71         }
72 }
73
74 #if 0
75 ISR(INT0_vect)
76 {
77         unsigned char tmpval = PINB & _BV(PB6);
78
79         gpio_set(GPIO_LED2, tmpval);
80         log_byte(0xbb);
81         log_flush();
82 }
83 #endif
84