custom_matrix.md (2679B)
1 # Custom Matrix 2 3 QMK provides a mechanism to supplement or replace the default matrix scanning routine with your own code. 4 5 The reasons to use this feature include: 6 7 * Extra hardware between the keyboard's switches and MCU pins 8 * I/O multiplexer 9 * Line decoder 10 * Irregular switch matrix 11 * Simultaneous use of `COL2ROW` and `ROW2COL` 12 13 ## Prerequisites 14 15 Implementing custom matrix usually involves compilation of an additional source file. It is recommended that for consistency, this file is called `matrix.c`. 16 17 Add a new file to your keyboard directory: 18 ``` 19 keyboards/<keyboard>/matrix.c 20 ``` 21 22 And to configure compilation for the new file, add this to your `rules.mk`: 23 ```make 24 SRC += matrix.c 25 ``` 26 27 ## 'lite' 28 29 Provides a default implementation for various scanning functions, reducing the boilerplate code when implementing custom matrix. 30 To configure it, add this to your `rules.mk`: 31 32 ```make 33 CUSTOM_MATRIX = lite 34 ``` 35 36 And implement the following functions in a `matrix.c` file in your keyboard folder: 37 38 ```c 39 void matrix_init_custom(void) { 40 // TODO: initialize hardware here 41 } 42 43 bool matrix_scan_custom(matrix_row_t current_matrix[]) { 44 bool matrix_has_changed = false; 45 46 // TODO: add matrix scanning routine here 47 48 return matrix_has_changed; 49 } 50 ``` 51 52 53 ## Full Replacement 54 55 When more control over the scanning routine is required, you can choose to implement the full scanning routine. 56 To configure it, add this to your rules.mk: 57 58 ```make 59 CUSTOM_MATRIX = yes 60 ``` 61 62 And implement the following functions in a `matrix.c` file in your keyboard folder: 63 64 ```c 65 matrix_row_t matrix_get_row(uint8_t row) { 66 // TODO: return the requested row data 67 } 68 69 void matrix_print(void) { 70 // TODO: use print() to dump the current matrix state to console 71 } 72 73 void matrix_init(void) { 74 // TODO: initialize hardware and global matrix state here 75 76 // Unless hardware debouncing - Init the configured debounce routine 77 debounce_init(); 78 79 // This *must* be called for correct keyboard behavior 80 matrix_init_kb(); 81 } 82 83 uint8_t matrix_scan(void) { 84 bool changed = false; 85 86 // TODO: add matrix scanning routine here 87 88 // Unless hardware debouncing - use the configured debounce routine 89 changed = debounce(raw_matrix, matrix, changed); 90 91 // This *must* be called for correct keyboard behavior 92 matrix_scan_kb(); 93 94 return changed; 95 } 96 ``` 97 98 And also provide defaults for the following callbacks: 99 100 ```c 101 __attribute__((weak)) void matrix_init_kb(void) { matrix_init_user(); } 102 103 __attribute__((weak)) void matrix_scan_kb(void) { matrix_scan_user(); } 104 105 __attribute__((weak)) void matrix_init_user(void) {} 106 107 __attribute__((weak)) void matrix_scan_user(void) {} 108 ```