]> git.donarmstrong.com Git - qmk_firmware.git/blob - keyboards/handwired/xealous/debounce.c
Simplify split_common Code significantly (#4772)
[qmk_firmware.git] / keyboards / handwired / xealous / debounce.c
1 #include <string.h>
2 #include "config.h"
3 #include "matrix.h"
4 #include "timer.h"
5 #include "quantum.h"
6
7 #ifndef DEBOUNCING_DELAY
8 #   define DEBOUNCING_DELAY 5
9 #endif
10
11 //Debouncing counters
12 typedef uint8_t debounce_counter_t;
13 #define DEBOUNCE_COUNTER_MODULO 250
14 #define DEBOUNCE_COUNTER_INACTIVE 251
15
16 static debounce_counter_t *debounce_counters;
17
18 void debounce_init(uint8_t num_rows)
19 {
20   debounce_counters = malloc(num_rows*MATRIX_COLS);
21   memset(debounce_counters, DEBOUNCE_COUNTER_INACTIVE, num_rows*MATRIX_COLS);
22 }
23
24 void update_debounce_counters(uint8_t num_rows, uint8_t current_time)
25 {
26   for (uint8_t row = 0; row < num_rows; row++)
27   {
28     for (uint8_t col = 0; col < MATRIX_COLS; col++)
29     {
30       if (debounce_counters[row*MATRIX_COLS + col] != DEBOUNCE_COUNTER_INACTIVE)
31       {
32         if (TIMER_DIFF(current_time, debounce_counters[row*MATRIX_COLS + col], DEBOUNCE_COUNTER_MODULO) >= DEBOUNCING_DELAY) {
33           debounce_counters[row*MATRIX_COLS + col] = DEBOUNCE_COUNTER_INACTIVE;
34         }
35       }
36     }
37   }
38 }
39
40 void transfer_matrix_values(matrix_row_t raw[], matrix_row_t cooked[], uint8_t num_rows, uint8_t current_time)
41 {
42     for (uint8_t row = 0; row < num_rows; row++)
43     {
44       matrix_row_t delta = raw[row] ^ cooked[row];
45
46       for (uint8_t col = 0; col < MATRIX_COLS; col++)
47       {
48           if (debounce_counters[row*MATRIX_COLS + col] == DEBOUNCE_COUNTER_INACTIVE && (delta & (1<<col)))
49           {
50               debounce_counters[row*MATRIX_COLS + col] = current_time;
51               cooked[row] ^= (1 << col);
52           }
53       }
54     }
55 }
56
57 void debounce(matrix_row_t raw[], matrix_row_t cooked[], uint8_t num_rows, bool changed)
58 {
59     uint8_t current_time = timer_read() % DEBOUNCE_COUNTER_MODULO;
60
61     update_debounce_counters(num_rows, current_time);
62     transfer_matrix_values(raw, cooked, num_rows, current_time);
63 }