aboutsummaryrefslogtreecommitdiff
path: root/src/button.c
blob: dc52265e550dbf41d41ae35c7303f933f4779e12 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <avr/io.h>
#include <stdint.h>

#include "button.h"
#include "rtc.h"

enum ButtonState check_button_state();

void button_tick() {
  enum ButtonState button_state = check_button_state();
  switch (button_state) {
  case BUTTON_PRESSED:
    if (seconds <= 10)
      seconds = 0;
    else
      seconds -= 10;
    break;
  case BUTTON_LONG_PRESSED:
    seconds += 10;
    break;
  default:
    break;
  }
}

bool is_button_active = false;
uint16_t button_tick_count = 0;

enum ButtonState check_button_state() {
  if (is_button_active && button_tick_count >= LONG_PRESS_TICK_COUNT) {
    button_tick_count = 0;
    is_button_active = false;
    return BUTTON_LONG_PRESSED;
  }

  bool in_debounce_period = is_button_active && button_tick_count > 0 &&
                            button_tick_count < DEBOUNCE_TICK_COUNT;

  // Ignore readings from debounce period
  if (!in_debounce_period) {
    DDRA &= ~(1 << PA0);
    PORTA &= ~(1 << PA0);
    is_button_active = (PINA & (1 << PA0)) == 0;
  }

  if (is_button_active) {
    button_tick_count++;
  } else {
    if (button_tick_count >= DEBOUNCE_TICK_COUNT) {
      button_tick_count = 0;
      return BUTTON_PRESSED;
    }
  }

  return BUTTON_IDLE;
}