buttons.c 2.02 KB
Newer Older
Rahix's avatar
Rahix committed
1
#include "epicardium.h"
2
3
#include "modules/modules.h"
#include "modules/log.h"
Rahix's avatar
Rahix committed
4
5
6

#include "portexpander.h"
#include "MAX77650-Arduino-Library.h"
7
8
#include "FreeRTOS.h"
#include "timers.h"
Rahix's avatar
Rahix committed
9
10
11

#include <stdint.h>

12
#define FREQ 100
Rahix's avatar
Rahix committed
13
14
15
16
17
static const uint8_t pin_mask[] = {
	[BUTTON_LEFT_BOTTOM]  = 1 << 5,
	[BUTTON_RIGHT_BOTTOM] = 1 << 3,
	[BUTTON_RIGHT_TOP]    = 1 << 6,
};
18
19
static uint8_t last = 0;
static uint8_t memory = 0;
20
static uint8_t display_wake_mask = 0xF;
21
static uint8_t memory_mask = 0xF;
fleur's avatar
fleur committed
22
23
static TimerHandle_t button_timer;
static StaticTimer_t button_timer_buffer;
Rahix's avatar
Rahix committed
24
25
26
27

uint8_t epic_buttons_read(uint8_t mask)
{
	uint8_t ret = 0;
koalo's avatar
koalo committed
28
	if (portexpander_detected() && (mask & 0x7)) {
29
30
31
32
33
		if (hwlock_acquire(HWLOCK_I2C, pdMS_TO_TICKS(100)) < 0) {
			LOG_ERR("buttons", "Can't acquire I2C bus");
			return 0;
		}

34
35
36
37
		/*
		 * Not using PB_Get() here as that performs one I2C transcation
		 * per button.
		 */
Rahix's avatar
Rahix committed
38
39
		uint8_t pin_status = ~portexpander_get();

40
41
		hwlock_release(HWLOCK_I2C);

Rahix's avatar
Rahix committed
42
43
44
45
46
47
48
49
50
51
52
53
54
		for (uint8_t m = 1; m < 0x8; m <<= 1) {
			if (mask & m && pin_status & pin_mask[m]) {
				ret |= m;
			}
		}
	}

	if (mask & BUTTON_RESET && MAX77650_getDebounceStatusnEN0()) {
		ret |= BUTTON_RESET;
	}

	return ret;
}
55
56
57

static void CALLBACK_buttons(){
	last = epic_buttons_read(0xF);
58
59
60
	if(last & memory_mask){
		memory = last;
	}
61
62
63
64
65
66
	if(last & display_wake_mask){
		epic_disp_wake();
	}
}

void epic_buttons_start(){
fleur's avatar
fleur committed
67
68
	if(!button_timer) {
		button_timer = xTimerCreateStatic(
69
70
71
72
73
				"buttons",
				FREQ,
				pdTRUE,
				NULL,
				CALLBACK_buttons,
fleur's avatar
fleur committed
74
				&button_timer_buffer
75
		);
fleur's avatar
fleur committed
76
		xTimerStart(button_timer,0);
77
78
79
80
81
82
83
	}
}

void epic_buttons_set_display_wake_mask(uint8_t mask){
	display_wake_mask = mask;
}

fleur's avatar
fleur committed
84
uint8_t epic_buttons_get(uint8_t mask){
fleur's avatar
fleur committed
85
	if (!button_timer || !xTimerIsTimerActive(button_timer)) {
86
87
		return -ENODATA;
	}
fleur's avatar
fleur committed
88
	return last & mask;
89
90
91
}

void epic_buttons_stop(){
fleur's avatar
fleur committed
92
93
	if (!button_timer || xTimerIsTimerActive(button_timer) == pdFALSE) { return; }
	xTimerStop(button_timer, 0);
94
}
95
96
97
98
99

void epic_buttons_reset_memory(){
	memory = 0;
}

fleur's avatar
fleur committed
100
101
uint8_t epic_buttons_get_memory(uint8_t mask){
	return memory & mask;
102
}