]> git.donarmstrong.com Git - qmk_firmware.git/blob - docs/custom_quantum_functions.md
Add kb and user level keyboard initialization functions (#3113)
[qmk_firmware.git] / docs / custom_quantum_functions.md
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.md) will help you understand what is going on at a more fundamental level.
6
7 ## A Word on Core vs Keyboards vs Keymap
8
9 We have structured QMK as a hierarchy:
10
11 * Core (`_quantum`)
12   * Keyboard/Revision (`_kb`)
13     * Keymap (`_user`)
14
15 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.
16
17 When defining functions at the Keyboard/Revision level it is important that your `_kb()` implementation call `_user()` before executing anything else- otherwise the keymap level function will never be called.
18
19 # Custom Keycodes
20
21 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.
22
23 ## Defining a New Keycode
24
25 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.
26
27
28 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.
29
30 ```c
31 enum my_keycodes {
32   FOO = SAFE_RANGE,
33   BAR
34 };
35 ```
36
37 ## Programming the Behavior of Any Keycode
38
39 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.
40
41 These function are called every time a key is pressed or released.
42
43 ### Example `process_record_user()` Implementation
44
45 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.
46
47 ```c
48 bool process_record_user(uint16_t keycode, keyrecord_t *record) {
49   switch (keycode) {
50     case FOO:
51       if (record->event.pressed) {
52         // Do something when pressed
53       } else {
54         // Do something else when release
55       }
56       return false; // Skip all further processing of this key
57     case KC_ENTER:
58       // Play a tone when enter is pressed
59       if (record->event.pressed) {
60         PLAY_NOTE_ARRAY(tone_qwerty);
61       }
62       return true; // Let QMK send the enter press/release events
63     default:
64       return true; // Process all other keycodes normally
65   }
66 }
67 ```
68
69 ### `process_record_*` Function Documentation
70
71 * Keyboard/Revision: `bool process_record_kb(uint16_t keycode, keyrecord_t *record)`
72 * Keymap: `bool process_record_user(uint16_t keycode, keyrecord_t *record)`
73
74 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.
75
76 The `record` argument contains information about the actual press:
77
78 ```c
79 keyrecord_t record {
80   keyevent_t event {
81     keypos_t key {
82       uint8_t col
83       uint8_t row
84     }
85     bool     pressed
86     uint16_t time
87   }
88 }
89 ```
90
91 # LED Control
92
93 QMK provides methods to read the 5 LEDs defined as part of the HID spec:
94
95 * `USB_LED_NUM_LOCK`
96 * `USB_LED_CAPS_LOCK`
97 * `USB_LED_SCROLL_LOCK`
98 * `USB_LED_COMPOSE`
99 * `USB_LED_KANA`
100
101 These five constants correspond to the positional bits of the host LED state.
102 There are two ways to get the host LED state:
103
104 * by implementing `led_set_user()`
105 * by calling `host_keyboard_leds()`
106
107 ## `led_set_user()`
108
109 This function will be called when the state of one of those 5 LEDs changes. It receives the LED state as a parameter.
110 Use the `IS_LED_ON(usb_led, led_name)` and `IS_LED_OFF(usb_led, led_name)` macros to check the LED status.
111
112 !> `host_keyboard_leds()` may already reflect a new value before `led_set_user()` is called.
113
114 ### Example `led_set_user()` Implementation
115
116 ```c
117 void led_set_user(uint8_t usb_led) {
118     if (IS_LED_ON(usb_led, USB_LED_NUM_LOCK)) {
119         PORTB |= (1<<0);
120     } else {
121         PORTB &= ~(1<<0);
122     }
123     if (IS_LED_ON(usb_led, USB_LED_CAPS_LOCK)) {
124         PORTB |= (1<<1);
125     } else {
126         PORTB &= ~(1<<1);
127     }
128     if (IS_LED_ON(usb_led, USB_LED_SCROLL_LOCK)) {
129         PORTB |= (1<<2);
130     } else {
131         PORTB &= ~(1<<2);
132     }
133     if (IS_LED_ON(usb_led, USB_LED_COMPOSE)) {
134         PORTB |= (1<<3);
135     } else {
136         PORTB &= ~(1<<3);
137     }
138     if (IS_LED_ON(usb_led, USB_LED_KANA)) {
139         PORTB |= (1<<4);
140     } else {
141         PORTB &= ~(1<<4);
142     }
143 }
144 ```
145
146 ### `led_set_*` Function Documentation
147
148 * Keyboard/Revision: `void led_set_kb(uint8_t usb_led)`
149 * Keymap: `void led_set_user(uint8_t usb_led)`
150
151 ## `host_keyboard_leds()`
152
153 Call this function to get the last received LED state. This is useful for reading the LED state outside `led_set_*`, e.g. in [`matrix_scan_user()`](#matrix-scanning-code).
154 For convenience, you can use the `IS_HOST_LED_ON(led_name)` and `IS_HOST_LED_OFF(led_name)` macros instead of calling and checking `host_keyboard_leds()` directly.
155
156 ## Setting Physical LED State
157
158 Some keyboard implementations provide convenience methods for setting the state of the physical LEDs.
159
160 ### Ergodox Boards
161
162 The Ergodox implementations provide `ergodox_right_led_1`/`2`/`3_on`/`off()` to turn individual LEDs on or off, as well as `ergodox_right_led_on`/`off(uint8_t led)` to turn them on or off by their index.
163
164 In addition, it is possible to specify the brightness level of all LEDs with `ergodox_led_all_set(uint8_t n)`; of individual LEDs with `ergodox_right_led_1`/`2`/`3_set(uint8_t n)`; or by index with `ergodox_right_led_set(uint8_t led, uint8_t n)`.
165
166 Ergodox boards also define `LED_BRIGHTNESS_LO` for the lowest brightness and `LED_BRIGHTNESS_HI` for the highest brightness (which is the default).
167
168 # Keyboard Initialization Code
169
170 There are several steps in the keyboard initialization process.  Depending on what you want to do, it will influence which function you should use.
171
172 These are the three main initialization functions, listed in the order that they're called.
173
174 * `keyboard_pre_init_*` - Happens before most anything is started. Good for hardware setup that you want running very early.
175 * `matrix_init_*` - Happens midway through the firmware's startup process. Hardware is initialized, but features may not be yet.
176 * `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.
177
178 !> For most people, the `keyboard_post_init_user` function is what you want to call.  For instance, this is where you want to set up things for RGB Underglow.
179
180 ## Keyboard Pre Initialization code
181
182 This runs very early during startup, even before the USB has been started. 
183
184 Shortly after this, the matrix is initialized.
185
186 For most users, this shouldn't be used, as it's primarily for hardware oriented initialization. 
187
188 However, if you have hardware stuff that you need initialized, this is the best place for it (such as initializing LED pins).
189
190 ### Example `keyboard_pre_init_user()` Implementation
191
192 This example, at the keyboard level, sets up B1, B2, and B3 as LED pins.
193
194 ```c
195 void keyboard_pre_init_user(void) {
196   // Call the keyboard pre init code.
197
198   // Set our LED pins as output
199   DDRB |= (1<<1);
200   DDRB |= (1<<2);
201   DDRB |= (1<<3);
202 }
203 ```
204
205 ### `keyboard_pre_init_*` Function Documentation
206
207 * Keyboard/Revision: `void keyboard_pre_init_kb(void)`
208 * Keymap: `void keyboard_pre_init_user(void)`
209
210 ## Matrix Initialization Code
211
212 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. 
213
214 This is useful for setting up stuff that you may need elsewhere, but isn't hardware related nor is dependant on where it's started. 
215
216
217 ### `matrix_init_*` Function Documentation
218
219 * Keyboard/Revision: `void matrix_init_kb(void)`
220 * Keymap: `void matrix_init_user(void)`
221
222
223 ## Keyboard Post Initialization code
224
225 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.
226
227
228 ### Example `keyboard_post_init_user()` Implementation
229
230 This example, running after everything else has initialized, sets up the rgb underglow configuration.
231
232 ```c
233 void keyboard_post_init_user(void) {
234   // Call the post init code.
235   rgblight_enable_noeeprom(); // enables Rgb, without saving settings
236   rgblight_sethsv_noeeprom(180, 255, 255): // sets the color to teal/cyan without saving
237   rgblight_mode_noeeprom(RGBLIGHT_MODE_BREATHING + 3); // sets mode to Fast breathing without saving
238 }
239 ```
240
241 ### `keyboard_post_init_*` Function Documentation
242
243 * Keyboard/Revision: `void keyboard_post_init_kb(void)`
244 * Keymap: `void keyboard_post_init_user(void)`
245
246 # Matrix Scanning Code
247
248 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.
249
250 ### Example `matrix_scan_*` Implementation
251
252 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/Uq7gcHh).
253
254 ### `matrix_scan_*` Function Documentation
255
256 * Keyboard/Revision: `void matrix_scan_kb(void)`
257 * Keymap: `void matrix_scan_user(void)`
258
259 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.
260
261 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.
262
263
264 # Keyboard Idling/Wake Code
265
266 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.
267
268 This is controlled by two functions: `suspend_power_down_*` and `suspend_wakeup_init_*`, which are called when the system is board is idled and when it wakes up, respectively.
269
270
271 ### Example suspend_power_down_user() and suspend_wakeup_init_user() Implementation
272
273 This example, at the keyboard level, sets up B1, B2, and B3 as LED pins.
274
275 ```c
276 void suspend_power_down_user(void)
277 {
278     rgb_matrix_set_suspend_state(true);
279 }
280
281 void suspend_wakeup_init_user(void)
282 {
283     rgb_matrix_set_suspend_state(false);
284 }
285 ```
286
287 ### Keyboard suspend/wake  Function Documentation
288
289 * Keyboard/Revision: `void suspend_power_down_kb(void)` and `void suspend_wakeup_init_user(void)`
290 * Keymap: `void suspend_power_down_kb(void)` and `void suspend_wakeup_init_user(void)`
291
292 # Layer Change Code
293
294 This runs code every time that the layers get changed.  This can be useful for layer indication, or custom layer handling.
295
296 ### Example `layer_state_set_*` Implementation
297
298 This example shows how to set the [RGB Underglow](feature_rgblight.md) lights based on the layer, using the Planck as an example
299
300 ```c
301 uint32_t layer_state_set_user(uint32_t state) {
302     switch (biton32(state)) {
303     case _RAISE:
304         rgblight_setrgb (0x00,  0x00, 0xFF);
305         break;
306     case _LOWER:
307         rgblight_setrgb (0xFF,  0x00, 0x00);
308         break;
309     case _PLOVER:
310         rgblight_setrgb (0x00,  0xFF, 0x00);
311         break;
312     case _ADJUST:
313         rgblight_setrgb (0x7A,  0x00, 0xFF);
314         break;
315     default: //  for any other layers, or the default layer
316         rgblight_setrgb (0x00,  0xFF, 0xFF);
317         break;
318     }
319   return state;
320 }
321 ```
322 ### `layer_state_set_*` Function Documentation
323
324 * Keyboard/Revision: `void uint32_t layer_state_set_kb(uint32_t state)`
325 * Keymap: `uint32_t layer_state_set_user(uint32_t state)`
326
327 The `state` is the bitmask of the active layers, as explained in the [Keymap Overview](keymap.md#keymap-layer-status)
328
329
330 # Persistent Configuration (EEPROM)
331
332 This allows you to configure persistent settings for your keyboard.  These settings are stored in the EEPROM of your controller, and are retained even after power loss. The settings can be read with `eeconfig_read_kb` and `eeconfig_read_user`, and can be written to using `eeconfig_update_kb` and `eeconfig_update_user`. This is useful for features that you want to be able to toggle (like toggling rgb layer indication).  Additionally, you can use `eeconfig_init_kb` and `eeconfig_init_user` to set the default values for the EEPROM. 
333
334 The complicated part here, is that there are a bunch of ways that you can store and access data via EEPROM, and there is no "correct" way to do this.  However, you only have a DWORD (4 bytes) for each function.
335
336 Keep in mind that EEPROM has a limited number of writes. While this is very high, it's not the only thing writing to the EEPROM, and if you write too often, you can potentially drastically shorten the life of your MCU.
337
338 * If you don't understand the example, then you may want to avoid using this feature, as it is rather complicated. 
339
340 ### Example Implementation
341
342 This is an example of how to add settings, and read and write it. We're using the user keymap for the example here.  This is a complex function, and has a lot going on.  In fact, it uses a lot of the above functions to work! 
343
344
345 In your keymap.c file, add this to the top:
346 ```
347 typedef union {
348   uint32_t raw;
349   struct {
350     bool     rgb_layer_change :1;
351   };
352 } user_config_t;
353
354 user_config_t user_config;
355 ```
356
357 This sets up a 32 bit structure that we can store settings with in memory, and write to the EEPROM. Using this removes the need to define variables, since they're defined in this structure. Remember that `bool` (boolean) values use 1 bit, `uint8_t` uses 8 bits, `uint16_t` uses up 16 bits.  You can mix and match, but changing the order can cause issues, as it will change the values that are read and written. 
358
359 We're using `rgb_layer_change`, for the `layer_state_set_*` function, and use `matrix_init_user` and `process_record_user` to configure everything. 
360
361 Now, using the `matrix_init_user` code above, you want to add `eeconfig_read_user()` to it, to populate the structure you've just created. And you can then immediately use this structure to control functionality in your keymap.  And It should look like: 
362 ```
363 void matrix_init_user(void) {
364   // Call the keymap level matrix init.
365
366   // Read the user config from EEPROM
367   user_config.raw = eeconfig_read_user();
368
369   // Set default layer, if enabled
370   if (user_config.rgb_layer_change) {
371     rgblight_enable_noeeprom();
372     rgblight_sethsv_noeeprom_cyan(); 
373     rgblight_mode_noeeprom(1);
374   }
375 }
376 ```
377 The above function will use the EEPROM config immediately after reading it, to set the default layer's RGB color. The "raw" value of it is converted in a usable structure based on the "union" that you created above. 
378
379 ```
380 uint32_t layer_state_set_user(uint32_t state) {
381     switch (biton32(state)) {
382     case _RAISE:
383         if (user_config.rgb_layer_change) { rgblight_sethsv_noeeprom_magenta(); rgblight_mode_noeeprom(1); }
384         break;
385     case _LOWER:
386         if (user_config.rgb_layer_change) { rgblight_sethsv_noeeprom_red(); rgblight_mode_noeeprom(1); }
387         break;
388     case _PLOVER:
389         if (user_config.rgb_layer_change) { rgblight_sethsv_noeeprom_green(); rgblight_mode_noeeprom(1); }
390         break;
391     case _ADJUST:
392         if (user_config.rgb_layer_change) { rgblight_sethsv_noeeprom_white(); rgblight_mode_noeeprom(1); }
393         break;
394     default: //  for any other layers, or the default layer
395         if (user_config.rgb_layer_change) { rgblight_sethsv_noeeprom_cyan(); rgblight_mode_noeeprom(1); }
396         break;
397     }
398   return state;
399 }
400 ```
401 This will cause the RGB underglow to be changed ONLY if the value was enabled.  Now to configure this value, create a new keycode for `process_record_user` called `RGB_LYR` and `EPRM`. Additionally, we want to make sure that if you use the normal RGB codes, that it turns off  Using the example above, make it look this:
402 ```
403
404 bool process_record_user(uint16_t keycode, keyrecord_t *record) {
405   switch (keycode) {
406     case FOO:
407       if (record->event.pressed) {
408         // Do something when pressed
409       } else {
410         // Do something else when release
411       }
412       return false; // Skip all further processing of this key
413     case KC_ENTER:
414         // Play a tone when enter is pressed
415         if (record->event.pressed) {
416             PLAY_NOTE_ARRAY(tone_qwerty);
417         }
418         return true; // Let QMK send the enter press/release events
419     case EPRM:
420         if (record->event.pressed) {
421             eeconfig_init(); // resets the EEPROM to default
422         }
423         return false;
424     case RGB_LYR:  // This allows me to use underglow as layer indication, or as normal
425         if (record->event.pressed) { 
426             user_config.rgb_layer_change ^= 1; // Toggles the status
427             eeconfig_update_user(user_config.raw); // Writes the new status to EEPROM
428             if (user_config.rgb_layer_change) { // if layer state indication is enabled, 
429                 layer_state_set(layer_state);   // then immediately update the layer color
430             }
431         }
432         return false; break;
433     case RGB_MODE_FORWARD ... RGB_MODE_GRADIENT: // For any of the RGB codes (see quantum_keycodes.h, L400 for reference)
434         if (record->event.pressed) { //This disables layer indication, as it's assumed that if you're changing this ... you want that disabled
435             if (user_config.rgb_layer_change) {        // only if this is enabled 
436                 user_config.rgb_layer_change = false;  // disable it, and 
437                 eeconfig_update_user(user_config.raw); // write the setings to EEPROM
438             }
439         }
440         return true; break;
441     default:
442       return true; // Process all other keycodes normally
443   }
444 }
445 ```
446 And lastly, you want to add the `eeconfig_init_user` function, so that when the EEPROM is reset, you can specify default values, and even custom actions. For example, if you want to set rgb layer indication by default, and save the default valued. 
447
448 ```
449 void eeconfig_init_user(void) {  // EEPROM is getting reset! 
450   user_config.rgb_layer_change = true; // We want this enabled by default
451   eeconfig_update_user(user_config.raw); // Write default value to EEPROM now
452
453   // use the non noeeprom versions, to write these values to EEPROM too
454   rgblight_enable(); // Enable RGB by default
455   rgblight_sethsv_cyan();  // Set it to CYAN by default
456   rgblight_mode(1); // set to solid by default
457 }
458 ```
459
460 And you're done.  The RGB layer indication will only work if you want it to. And it will be saved, even after unplugging the board. And if you use any of the RGB codes, it will disable the layer indication, so that it stays on the mode and color that you set it to. 
461
462 ### 'EECONFIG' Function Documentation
463
464 * Keyboard/Revision: `void eeconfig_init_kb(void)`, `uint32_t eeconfig_read_kb(void)` and `void eeconfig_update_kb(uint32_t val)`
465 * Keymap: `void eeconfig_init_user(void)`, `uint32_t eeconfig_read_user(void)` and `void eeconfig_update_user(uint32_t val)`
466
467 The `val` is the value of the data that you want to write to EEPROM.  And the `eeconfig_read_*` function return a 32 bit (DWORD) value from the EEPROM.