From 369c5a213dc4cf805b7dd2e2393901b33e67e500 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pablo=20Mart=C3=ADnez?= <58857054+elpekenin@users.noreply.github.com> Date: Fri, 7 Apr 2023 12:41:53 +0200 Subject: Add layer-cycle example (#19069) Co-authored-by: Drashna Jaelre --- docs/feature_layers.md | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) (limited to 'docs') diff --git a/docs/feature_layers.md b/docs/feature_layers.md index f8cb53eda4..8503603ffe 100644 --- a/docs/feature_layers.md +++ b/docs/feature_layers.md @@ -127,6 +127,54 @@ layer_state_t layer_state_set_user(layer_state_t state) { } ``` +### Example: Keycode to cycle through layers + +This example shows how to implement a custom keycode to cycle through a range of layers. + +```c +// Define the keycode, `QK_USER` avoids collisions with existing keycodes +enum keycodes { + KC_CYCLE_LAYERS = QK_USER, +}; + +// 1st layer on the cycle +#define LAYER_CYCLE_START 0 +// Last layer on the cycle +#define LAYER_CYCLE_END 4 + +// Add the behaviour of this new keycode +bool process_record_user(uint16_t keycode, keyrecord_t *record) { + switch (keycode) { + case KC_CYCLE_LAYERS: + // Our logic will happen on presses, nothing is done on releases + if (!record->event.pressed) { + // We've already handled the keycode (doing nothing), let QMK know so no further code is run unnecessarily + return false; + } + + uint8_t current_layer = get_highest_layer(layer_state); + + // Check if we are within the range, if not quit + if (curent_layer > LAYER_CYCLE_END || current_layer < LAYER_CYCLE_START) { + return false; + } + + uint8_t next_layer = current_layer + 1; + if (next_layer > LAYER_CYCLE_END) { + next_layer = LAYER_CYCLE_START; + } + layer_move(next_layer); + return false; + + // Process other keycodes normally + default: + return true; + } +} + +// Place `KC_CYCLE_LAYERS` as a keycode in your keymap +``` + Use the `IS_LAYER_ON_STATE(state, layer)` and `IS_LAYER_OFF_STATE(state, layer)` macros to check the status of a particular layer. Outside of `layer_state_set_*` functions, you can use the `IS_LAYER_ON(layer)` and `IS_LAYER_OFF(layer)` macros to check global layer state. -- cgit v1.2.3