custom_quantum_functions.md (20951B)
1 # How to Customize Your Keyboard's Behavior 2 3 For a lot of people a custom keyboard is about more than sending button presses to your computer. You want to be able to do things that are more complex than simple button presses and macros. QMK has hooks that allow you to inject code, override functionality, and otherwise customize how your keyboard behaves in different situations. 4 5 This page does not assume any special knowledge about QMK, but reading [Understanding QMK](understanding_qmk) will help you understand what is going on at a more fundamental level. 6 7 ## A Word on Core vs Keyboards vs Keymap {#a-word-on-core-vs-keyboards-vs-keymap} 8 9 We have structured QMK as a hierarchy: 10 11 * Core (`_quantum`) 12 * Community Module (`_<module>`) 13 * Community Module -> Keyboard/Revision (`_<module>_kb`) 14 * Community Module -> Keymap (`_<module>_user`) 15 * Keyboard/Revision (`_kb`) 16 * Keymap (`_user`) 17 18 Each of the functions described below can be defined with a `_kb()` suffix or a `_user()` suffix. We intend for you to use the `_kb()` suffix at the Keyboard/Revision level, while the `_user()` suffix should be used at the Keymap level. 19 20 When defining functions at the Keyboard/Revision level it is important that your `_kb()` implementation call `_user()` at an appropriate location, otherwise the keymap level function will never be called. 21 22 Functions at the `_<module>_xxx()` level are intended to allow keyboards or keymaps to override or enhance the processing associated with a [community module](/features/community_modules). 23 24 When defining module overrides such as `process_record_<module>()`, the same pattern should be used; the module must invoke `process_record_<module>_kb()` as appropriate. 25 26 # Custom Keycodes 27 28 By far the most common task is to change the behavior of an existing keycode or to create a new keycode. From a code standpoint the mechanism for each is very similar. 29 30 ## Defining a New Keycode 31 32 The first step to creating your own custom keycode(s) is to enumerate them. This means both naming them and assigning a unique number to that keycode. Rather than limit custom keycodes to a fixed range of numbers QMK provides the `SAFE_RANGE` macro. You can use `SAFE_RANGE` when enumerating your custom keycodes to guarantee that you get a unique number. 33 34 35 Here is an example of enumerating 2 keycodes. After adding this block to your `keymap.c` you will be able to use `FOO` and `BAR` inside your keymap. 36 37 ```c 38 enum my_keycodes { 39 FOO = SAFE_RANGE, 40 BAR 41 }; 42 ``` 43 44 ## Programming the Behavior of Any Keycode {#programming-the-behavior-of-any-keycode} 45 46 When you want to override the behavior of an existing key, or define the behavior for a new key, you should use the `process_record_kb()` and `process_record_user()` functions. These are called by QMK during key processing before the actual key event is handled. If these functions return `true` QMK will process the keycodes as usual. That can be handy for extending the functionality of a key rather than replacing it. If these functions return `false` QMK will skip the normal key handling, and it will be up to you to send any key up or down events that are required. 47 48 These function are called every time a key is pressed or released. 49 50 ### Example `process_record_user()` Implementation 51 52 This example does two things. It defines the behavior for a custom keycode called `FOO`, and it supplements our Enter key by playing a tone whenever it is pressed. 53 54 ```c 55 bool process_record_user(uint16_t keycode, keyrecord_t *record) { 56 switch (keycode) { 57 case FOO: 58 if (record->event.pressed) { 59 // Do something when pressed 60 } else { 61 // Do something else when release 62 } 63 return false; // Skip all further processing of this key 64 case KC_ENTER: 65 // Play a tone when enter is pressed 66 if (record->event.pressed) { 67 PLAY_SONG(tone_qwerty); 68 } 69 return true; // Let QMK send the enter press/release events 70 default: 71 return true; // Process all other keycodes normally 72 } 73 } 74 ``` 75 76 ### `process_record_*` Function Documentation 77 78 * Keyboard/Revision: `bool process_record_kb(uint16_t keycode, keyrecord_t *record)` 79 * Keymap: `bool process_record_user(uint16_t keycode, keyrecord_t *record)` 80 81 The `keycode` argument is whatever is defined in your keymap, eg `MO(1)`, `KC_L`, etc. You should use a `switch...case` block to handle these events. 82 83 The `record` argument contains information about the actual press: 84 85 ```c 86 keyrecord_t record { 87 keyevent_t event { 88 keypos_t key { 89 uint8_t col 90 uint8_t row 91 } 92 bool pressed 93 uint16_t time 94 } 95 } 96 ``` 97 98 # Keyboard Initialization Code 99 100 There are several steps in the keyboard initialization process. Depending on what you want to do, it will influence which function you should use. 101 102 These are the three main initialization functions, listed in the order that they're called. 103 104 * `keyboard_pre_init_*` - Happens before most anything is started. Good for hardware setup that you want running very early. 105 * `matrix_init_*` - Happens midway through the firmware's startup process. Hardware is initialized, but features may not be yet. 106 * `keyboard_post_init_*` - Happens at the end of the firmware's startup process. This is where you'd want to put "customization" code, for the most part. 107 108 ::: warning 109 For most people, the `keyboard_post_init_user` function is what you want to implement. For instance, this is where you want to set up things for RGB Underglow. 110 ::: 111 112 ## Keyboard Pre Initialization code 113 114 This runs very early during startup, even before the USB has been started. 115 116 Shortly after this, the matrix is initialized. 117 118 For most users, this shouldn't be used, as it's primarily for hardware oriented initialization. 119 120 However, if you have hardware stuff that you need initialized, this is the best place for it (such as initializing LED pins). 121 122 ### Example `keyboard_pre_init_user()` Implementation 123 124 This example, at the keyboard level, sets up B0, B1, B2, B3, and B4 as LED pins. 125 126 ```c 127 void keyboard_pre_init_user(void) { 128 // Call the keyboard pre init code. 129 130 // Set our LED pins as output 131 gpio_set_pin_output(B0); 132 gpio_set_pin_output(B1); 133 gpio_set_pin_output(B2); 134 gpio_set_pin_output(B3); 135 gpio_set_pin_output(B4); 136 } 137 ``` 138 139 ### `keyboard_pre_init_*` Function Documentation 140 141 * Keyboard/Revision: `void keyboard_pre_init_kb(void)` 142 * Keymap: `void keyboard_pre_init_user(void)` 143 144 ## Matrix Initialization Code 145 146 This is called when the matrix is initialized, and after some of the hardware has been set up, but before many of the features have been initialized. 147 148 This is useful for setting up stuff that you may need elsewhere, but isn't hardware related nor is dependent on where it's started. 149 150 151 ### `matrix_init_*` Function Documentation 152 153 * Keyboard/Revision: `void matrix_init_kb(void)` 154 * Keymap: `void matrix_init_user(void)` 155 156 ### Low-level Matrix Overrides Function Documentation {#low-level-matrix-overrides} 157 158 * GPIO pin initialisation: `void matrix_init_pins(void)` 159 * This needs to perform the low-level initialisation of all row and column pins. By default this will initialise the input/output state of each of the GPIO pins listed in `MATRIX_ROW_PINS` and `MATRIX_COL_PINS`, based on whether or not the keyboard is set up for `ROW2COL`, `COL2ROW`, or `DIRECT_PINS`. Should the keyboard designer override this function, no initialisation of pin state will occur within QMK itself, instead deferring to the keyboard's override. 160 * `COL2ROW`-based row reads: `void matrix_read_cols_on_row(matrix_row_t current_matrix[], uint8_t current_row)` 161 * `ROW2COL`-based column reads: `void matrix_read_rows_on_col(matrix_row_t current_matrix[], uint8_t current_col, matrix_row_t row_shifter)` 162 * `DIRECT_PINS`-based reads: `void matrix_read_cols_on_row(matrix_row_t current_matrix[], uint8_t current_row)` 163 * These three functions need to perform the low-level retrieval of matrix state of relevant input pins, based on the matrix type. Only one of the functions should be implemented, if needed. By default this will iterate through `MATRIX_ROW_PINS` and `MATRIX_COL_PINS`, configuring the inputs and outputs based on whether or not the keyboard is set up for `ROW2COL`, `COL2ROW`, or `DIRECT_PINS`. Should the keyboard designer override this function, no manipulation of matrix GPIO pin state will occur within QMK itself, instead deferring to the keyboard's override. 164 165 ## Keyboard Post Initialization code 166 167 This is ran as the very last task in the keyboard initialization process. This is useful if you want to make changes to certain features, as they should be initialized by this point. 168 169 170 ### Example `keyboard_post_init_user()` Implementation 171 172 This example, running after everything else has initialized, sets up the rgb underglow configuration. 173 174 ```c 175 void keyboard_post_init_user(void) { 176 // Call the post init code. 177 rgblight_enable_noeeprom(); // enables Rgb, without saving settings 178 rgblight_sethsv_noeeprom(180, 255, 255); // sets the color to teal/cyan without saving 179 rgblight_mode_noeeprom(RGBLIGHT_MODE_BREATHING + 3); // sets mode to Fast breathing without saving 180 } 181 ``` 182 183 ### `keyboard_post_init_*` Function Documentation 184 185 * Keyboard/Revision: `void keyboard_post_init_kb(void)` 186 * Keymap: `void keyboard_post_init_user(void)` 187 188 # Matrix Scanning Code 189 190 Whenever possible you should customize your keyboard by using `process_record_*()` and hooking into events that way, to ensure that your code does not have a negative performance impact on your keyboard. However, in rare cases it is necessary to hook into the matrix scanning. Be extremely careful with the performance of code in these functions, as it will be called at least 10 times per second. 191 192 ### Example `matrix_scan_*` Implementation 193 194 This example has been deliberately omitted. You should understand enough about QMK internals to write this without an example before hooking into such a performance sensitive area. If you need help please [open an issue](https://github.com/qmk/qmk_firmware/issues/new) or [chat with us on Discord](https://discord.gg/qmk). 195 196 ### `matrix_scan_*` Function Documentation 197 198 * Keyboard/Revision: `void matrix_scan_kb(void)` 199 * Keymap: `void matrix_scan_user(void)` 200 201 This function gets called at every matrix scan, which is basically as often as the MCU can handle. Be careful what you put here, as it will get run a lot. 202 203 You should use this function if you need custom matrix scanning code. It can also be used for custom status output (such as LEDs or a display) or other functionality that you want to trigger regularly even when the user isn't typing. 204 205 # Keyboard housekeeping 206 207 * Keyboard/Revision: `void housekeeping_task_kb(void)` 208 * Keymap: `void housekeeping_task_user(void)` 209 210 This function gets called at the end of all QMK processing, before starting the next iteration. You can safely assume that QMK has dealt with the last matrix scan at the time that these functions are invoked -- layer states have been updated, USB reports have been sent, LEDs have been updated, and displays have been drawn. 211 212 Similar to `matrix_scan_*`, these are called as often as the MCU can handle. To keep your board responsive, it's suggested to do as little as possible during these function calls, potentially throttling their behaviour if you do indeed require implementing something special. 213 214 ### Example `void housekeeping_task_user(void)` implementation 215 216 This example will show you how to use `void housekeeping_task_user(void)` to turn off [RGB Light](features/rgblight). For RGB Matrix, the [builtin](features/rgb_matrix#additional-configh-options) `RGB_MATRIX_TIMEOUT` should be used. 217 218 First, add the following lines to your keymap's `config.h`: 219 220 ```c 221 #define RGBLIGHT_SLEEP // enable rgblight_suspend() and rgblight_wakeup() in keymap.c 222 #define RGBLIGHT_TIMEOUT 900000 // ms to wait until rgblight time out, 900K ms is 15min. 223 ``` 224 225 Next, add the following code to your `keymap.c`: 226 227 ```c 228 static uint32_t key_timer; // timer for last keyboard activity, use 32bit value and function to make longer idle time possible 229 static void refresh_rgb(void); // refreshes the activity timer and RGB, invoke whenever any activity happens 230 static void check_rgb_timeout(void); // checks if enough time has passed for RGB to timeout 231 bool is_rgb_timeout = false; // store if RGB has timed out or not in a boolean 232 233 void refresh_rgb(void) { 234 key_timer = timer_read32(); // store time of last refresh 235 if (is_rgb_timeout) 236 { 237 is_rgb_timeout = false; 238 rgblight_wakeup(); 239 } 240 } 241 void check_rgb_timeout(void) { 242 if (!is_rgb_timeout && timer_elapsed32(key_timer) > RGBLIGHT_TIMEOUT) // check if RGB has already timeout and if enough time has passed 243 { 244 rgblight_suspend(); 245 is_rgb_timeout = true; 246 } 247 } 248 /* Then, call the above functions from QMK's built in post processing functions like so */ 249 /* Runs at the end of each scan loop, check if RGB timeout has occurred or not */ 250 void housekeeping_task_user(void) { 251 #ifdef RGBLIGHT_TIMEOUT 252 check_rgb_timeout(); 253 #endif 254 } 255 /* Runs after each key press, check if activity occurred */ 256 void post_process_record_user(uint16_t keycode, keyrecord_t *record) { 257 #ifdef RGBLIGHT_TIMEOUT 258 if (record->event.pressed) 259 refresh_rgb(); 260 #endif 261 } 262 /* Runs after each encoder tick, check if activity occurred */ 263 void post_encoder_update_user(uint8_t index, bool clockwise) { 264 #ifdef RGBLIGHT_TIMEOUT 265 refresh_rgb(); 266 #endif 267 } 268 ``` 269 270 # Keyboard Idling/Wake Code 271 272 If the board supports it, it can be "idled", by stopping a number of functions. A good example of this is RGB lights or backlights. This can save on power consumption, or may be better behavior for your keyboard. 273 274 This is controlled by two functions: `suspend_power_down_*` and `suspend_wakeup_init_*`, which are called when the system board is idled and when it wakes up, respectively. 275 276 277 ### Example `suspend_power_down_user()` and `suspend_wakeup_init_user()` Implementation 278 279 280 ```c 281 void suspend_power_down_user(void) { 282 // code will run multiple times while keyboard is suspended 283 } 284 285 void suspend_wakeup_init_user(void) { 286 // code will run on keyboard wakeup 287 } 288 ``` 289 290 ### Keyboard suspend/wake Function Documentation 291 292 * Keyboard/Revision: `void suspend_power_down_kb(void)` and `void suspend_wakeup_init_user(void)` 293 * Keymap: `void suspend_power_down_kb(void)` and `void suspend_wakeup_init_user(void)` 294 295 296 # Keyboard Shutdown/Reboot Code {#keyboard-shutdown-reboot-code} 297 298 This function gets called whenever the firmware is reset, whether it's a soft reset or reset to the bootloader. This is the spot to use for any sort of cleanup, as this happens right before the actual reset. And it can be useful for turning off different systems (such as RGB, onboard screens, etc). 299 300 Additionally, it differentiates between the soft reset (eg, rebooting back into the firmware) or jumping to the bootloader. 301 302 Certain tasks are performed during shutdown too. The keyboard is cleared, music and midi is stopped (if enabled), the shutdown chime is triggered (if audio is enabled), and haptic is stopped. 303 304 If `jump_to_bootloader` is set to `true`, this indicates that the board will be entering the bootloader for a new firmware flash, whereas `false` indicates that this is happening for a soft reset and will load the firmware agaim immediately (such as when using `QK_REBOOT` or `QK_CLEAR_EEPROM`). 305 306 As there is a keyboard and user level function, returning `false` for the user function will disable the keyboard level function, allowing for customization. 307 308 ::: tip 309 Bootmagic does not trigger `shutdown_*()` as it happens before most of the initialization process. 310 ::: 311 312 ### Example `shutdown_kb()` Implementation 313 314 ```c 315 bool shutdown_kb(bool jump_to_bootloader) { 316 if (!shutdown_user(jump_to_bootloader)) { 317 return false; 318 } 319 320 if (jump_to_bootloader) { 321 // red for bootloader 322 rgb_matrix_set_color_all(RGB_OFF); 323 } else { 324 // off for soft reset 325 rgb_matrix_set_color_all(RGB_GREEN); 326 } 327 // force flushing -- otherwise will never happen 328 rgb_matrix_update_pwm_buffers(); 329 return true; 330 } 331 ``` 332 333 ### Example `shutdown_user()` Implementation 334 335 ```c 336 bool shutdown_user(bool jump_to_bootloader) { 337 if (jump_to_bootloader) { 338 // red for bootloader 339 rgb_matrix_set_color_all(RGB_RED); 340 } else { 341 // off for soft reset 342 rgb_matrix_set_color_all(RGB_OFF); 343 } 344 // force flushing -- otherwise will never happen 345 rgb_matrix_update_pwm_buffers(); 346 // false to not process kb level 347 return false; 348 } 349 ``` 350 351 ### Keyboard shutdown/reboot Function Documentation 352 353 * Keyboard/Revision: `bool shutdown_kb(bool jump_to_bootloader)` 354 * Keymap: `bool shutdown_user(bool jump_to_bootloader)` 355 356 # Deferred Execution {#deferred-execution} 357 358 QMK has the ability to execute a callback after a specified period of time, rather than having to manually manage timers. To enable this functionality, set `DEFERRED_EXEC_ENABLE = yes` in rules.mk. 359 360 ## Deferred executor callbacks 361 362 All _deferred executor callbacks_ have a common function signature and look like: 363 364 ```c 365 uint32_t my_callback(uint32_t trigger_time, void *cb_arg) { 366 /* do something */ 367 bool repeat = my_deferred_functionality(); 368 return repeat ? 500 : 0; 369 } 370 ``` 371 372 The first argument `trigger_time` is the intended time of execution. If other delays prevent executing at the exact trigger time, this allows for "catch-up" or even skipping intervals, depending on the required behaviour. 373 374 The second argument `cb_arg` is the same argument passed into `defer_exec()` below, and can be used to access state information from the original call context. 375 376 The return value is the number of milliseconds to use if the function should be repeated -- if the callback returns `0` then it's automatically unregistered. In the example above, a hypothetical `my_deferred_functionality()` is invoked to determine if the callback needs to be repeated -- if it does, it reschedules for a `500` millisecond delay, otherwise it informs the deferred execution background task that it's done, by returning `0`. 377 378 ::: tip 379 Note that the returned delay will be applied to the intended trigger time, not the time of callback invocation. This allows for generally consistent timing even in the face of occasional late execution. 380 ::: 381 382 ## Deferred executor registration 383 384 Once a callback has been defined, it can be scheduled using the following API: 385 386 ```c 387 deferred_token my_token = defer_exec(1500, my_callback, NULL); 388 ``` 389 390 The first argument is the number of milliseconds to wait until executing `my_callback` -- in the case above, `1500` milliseconds, or 1.5 seconds. 391 392 The third parameter is the `cb_arg` that gets passed to the callback at the point of execution. This value needs to be valid at the time the callback is invoked -- a local function value will be destroyed before the callback is executed and should not be used. If this is not required, `NULL` should be used. 393 394 The return value is a `deferred_token` that can consequently be used to cancel the deferred executor callback before it's invoked. If a failure occurs, the returned value will be `INVALID_DEFERRED_TOKEN`. Usually this will be as a result of supplying `0` to the delay, or a `NULL` for the callback. The other failure case is if there are too many deferred executions "in flight" -- this can be increased by changing the limit, described below. 395 396 ## Extending a deferred execution 397 398 The `deferred_token` returned by `defer_exec()` can be used to extend a the duration a pending execution waits before it gets invoked: 399 ```c 400 // This will re-delay my_token's future execution such that it is invoked 800ms after the current time 401 extend_deferred_exec(my_token, 800); 402 ``` 403 404 ## Cancelling a deferred execution 405 406 The `deferred_token` returned by `defer_exec()` can be used to cancel a pending execution before it gets invoked: 407 ```c 408 // This will cancel my_token's future execution 409 cancel_deferred_exec(my_token); 410 ``` 411 412 Once a token has been canceled, it should be considered invalid. Reusing the same token is not supported. 413 414 ## Deferred callback limits 415 416 There are a maximum number of deferred callbacks that can be scheduled, controlled by the value of the define `MAX_DEFERRED_EXECUTORS`. 417 418 If registrations fail, then you can increase this value in your keyboard or keymap `config.h` file, for example to 16 instead of the default 8: 419 420 ```c 421 #define MAX_DEFERRED_EXECUTORS 16 422 ``` 423 424 # Advanced topics {#advanced-topics} 425 426 This page used to encompass a large set of features. We have moved many sections that used to be part of this page to their own pages. Everything below this point is simply a redirect so that people following old links on the web find what they're looking for. 427 428 ## Layer Change Code {#layer-change-code} 429 430 [Layer change code](feature_layers#layer-change-code) 431 432 ## Persistent Configuration (EEPROM) {#persistent-configuration-eeprom} 433 434 [Persistent Configuration (EEPROM)](feature_eeprom)