aboutsummaryrefslogtreecommitdiffstats
path: root/docs/getting_started_introduction.md
blob: 6dc51b82b7354975c86d35294ed5ad6d98669364 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# Introduction

This page attempts to explain the basic information you need to know to work with the QMK project. It assumes that you are familiar with navigating a Unix shell, but does not assume you are familiar with C or with compiling using make.

## Basic QMK Structure

QMK is a fork of [Jun Wako](https://github.com/tmk)'s [tmk_keyboard](https://github.com/tmk/tmk_keyboard) project. The original TMK code, with modifications, can be found in the `tmk_core` folder. The QMK additions to the project may be found in the `quantum` folder. Keyboard projects may be found in the `handwired` and `keyboard` folders.

### Userspace Structure

Within the folder `users` is a directory for each user. This is a place for users to put code that they might use between keyboards. See the docs for [Userspace feature](feature_userspace.md) for more information.

### Keyboard Project Structure

Within the folder `keyboards`, its subfolder `handwired` and its vendor and manufacture subdirectories e.g. `clueboard` is a directory for each keyboard project, for example `qmk_firmware/keyboards/clueboard/2x1800`. Within it, you'll find the following structure:

* `keymaps/`: Different keymaps that can be built
* `rules.mk`: The file that sets the default "make" options. Do not edit this file directly, instead use a keymap specific `rules.mk`.
* `config.h`: The file that sets the default compile time options. Do not edit this file directly, instead use a keymap specific `config.h`.
* `info.json`: The file used for setting layout for QMK Configurator. See [Configurator Support](reference_configurator_support.md) for more information.
* `readme.md`: A brief overview of the keyboard.
* `<keyboardName>.h`: This file is where the keyboard layout is defined against the keyboard's switch matrix.
* `<keyboardName>.c`: This file is where you can find custom code for the keyboard.  

For more information on project structure, see [QMK Keyboard Guidelines](hardware_keyboard_guidelines.md).

### Keymap Structure

In every keymap folder, the following files may be found. Only `keymap.c` is required, and if the rest of the files are not found the default options will be chosen.

* `config.h`: the options to configure your keymap
* `keymap.c`: all of your keymap code, required
* `rules.mk`: the features of QMK that are enabled
* `readme.md`: a description of your keymap, how others might use it, and explanations of features. Please upload images to a service like imgur.

# The `config.h` File

There are 3 possible `config.h` locations:

* keyboard (`/keyboards/<keyboard>/config.h`)
* userspace (`/users/<user>/config.h`)
* keymap (`/keyboards/<keyboard>/keymaps/<keymap>/config.h`)

The build system automatically picks up the config files in the above order. If you wish to override any setting set by a previous `config.h` you will need to first include some boilerplate code for the settings you wish to change.

```
#pragma once
```

Then to override a setting from the previous `config.h` file you must `#undef` and then `#define` the setting again.

The boilerplate code and setting look like this together:

```
#pragma once

// overrides go here!
#undef MY_SETTING
#define MY_SETTING 4
```
n365' href='#n365'>365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
# How to Customize Your Keyboard's Behavior

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.

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.

## A Word on Core vs Keyboards vs Keymap :id=a-word-on-core-vs-keyboards-vs-keymap

We have structured QMK as a hierarchy:

* Core (`_quantum`)
  * Keyboard/Revision (`_kb`)
    * Keymap (`_user`)

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.

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.

# Custom Keycodes

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.

## Defining a New Keycode

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.


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.

```c
enum my_keycodes {
  FOO = SAFE_RANGE,
  BAR
};
```

## Programming the Behavior of Any Keycode :id=programming-the-behavior-of-any-keycode

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.

These function are called every time a key is pressed or released.

### Example `process_record_user()` Implementation

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.

```c
bool process_record_user(uint16_t keycode, keyrecord_t *record) {
  switch (keycode) {
    case FOO:
      if (record->event.pressed) {
        // Do something when pressed
      } else {
        // Do something else when release
      }
      return false; // Skip all further processing of this key
    case KC_ENTER:
      // Play a tone when enter is pressed
      if (record->event.pressed) {
        PLAY_NOTE_ARRAY(tone_qwerty);
      }
      return true; // Let QMK send the enter press/release events
    default:
      return true; // Process all other keycodes normally
  }
}
```

### `process_record_*` Function Documentation

* Keyboard/Revision: `bool process_record_kb(uint16_t keycode, keyrecord_t *record)`
* Keymap: `bool process_record_user(uint16_t keycode, keyrecord_t *record)`

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.

The `record` argument contains information about the actual press:

```c
keyrecord_t record {
  keyevent_t event {
    keypos_t key {
      uint8_t col
      uint8_t row
    }
    bool     pressed
    uint16_t time
  }
}
```

# LED Control

QMK provides methods to read 5 of the LEDs defined in the HID spec:

* Num Lock
* Caps Lock
* Scroll Lock
* Compose
* Kana

There are two ways to get the lock LED state:

* by implementing `bool led_update_kb(led_t led_state)` or `_user(led_t led_state)`; or
* by calling `led_t host_keyboard_led_state()`

!> `host_keyboard_led_state()` may already reflect a new value before `led_update_user()` is called.

Two more deprecated functions exist that provide the LED state as a `uint8_t`:

* `uint8_t led_set_kb(uint8_t usb_led)` and `_user(uint8_t usb_led)`
* `uint8_t host_keyboard_leds()`

## `led_update_user()`

This function will be called when the state of one of those 5 LEDs changes. It receives the LED state as a struct parameter.

By convention, return `true` from `led_update_user()` to get the `led_update_kb()` hook to run its code, and
return `false` when you would prefer not to run the code in `led_update_kb()`.

Some examples include:

  - overriding the LEDs to use them for something else like layer indication
    - return `false` because you do not want the `_kb()` function to run, as it would override your layer behavior.
  - play a sound when an LED turns on or off.
    - return `true` because you want the `_kb` function to run, and this is in addition to the default LED behavior.

?> Because the `led_set_*` functions return `void` instead of `bool`, they do not allow for overriding the keyboard LED control, and thus it's recommended to use `led_update_*` instead.

### Example `led_update_kb()` Implementation

```c
bool led_update_kb(led_t led_state) {
    bool res = led_update_user(led_state);
    if(res) {
        // writePin sets the pin high for 1 and low for 0.
        // In this example the pins are inverted, setting
        // it low/0 turns it on, and high/1 turns the LED off.
        // This behavior depends on whether the LED is between the pin
        // and VCC or the pin and GND.
        writePin(B0, !led_state.num_lock);
        writePin(B1, !led_state.caps_lock);
        writePin(B2, !led_state.scroll_lock);
        writePin(B3, !led_state.compose);
        writePin(B4, !led_state.kana);
    }
    return res;
}
```

### Example `led_update_user()` Implementation

This incomplete example would play a sound if Caps Lock is turned on or off. It returns `true`, because you also want the LEDs to maintain their state.

```c
#ifdef AUDIO_ENABLE
  float caps_on[][2] = SONG(CAPS_LOCK_ON_SOUND);
  float caps_off[][2] = SONG(CAPS_LOCK_OFF_SOUND);
#endif

bool led_update_user(led_t led_state) {
    #ifdef AUDIO_ENABLE
    static uint8_t caps_state = 0;
    if (caps_state != led_state.caps_lock) {
        led_state.caps_lock ? PLAY_SONG(caps_on) : PLAY_SONG(caps_off);
        caps_state = led_state.caps_lock;
    }
    #endif
    return true;
}
```

### `led_update_*` Function Documentation

* Keyboard/Revision: `bool led_update_kb(led_t led_state)`
* Keymap: `bool led_update_user(led_t led_state)`

## `host_keyboard_led_state()`

Call this function to get the last received LED state as a `led_t`. This is useful for reading the LED state outside `led_update_*`, e.g. in [`matrix_scan_user()`](#matrix-scanning-code).

## Setting Physical LED State

Some keyboard implementations provide convenience methods for setting the state of the physical LEDs.

### Ergodox Boards

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.

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)`.

Ergodox boards also define `LED_BRIGHTNESS_LO` for the lowest brightness and `LED_BRIGHTNESS_HI` for the highest brightness (which is the default).

# Keyboard Initialization Code

There are several steps in the keyboard initialization process.  Depending on what you want to do, it will influence which function you should use.

These are the three main initialization functions, listed in the order that they're called.

* `keyboard_pre_init_*` - Happens before most anything is started. Good for hardware setup that you want running very early.
* `matrix_init_*` - Happens midway through the firmware's startup process. Hardware is initialized, but features may not be yet.
* `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.

!> 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.

## Keyboard Pre Initialization code

This runs very early during startup, even before the USB has been started. 

Shortly after this, the matrix is initialized.

For most users, this shouldn't be used, as it's primarily for hardware oriented initialization. 

However, if you have hardware stuff that you need initialized, this is the best place for it (such as initializing LED pins).

### Example `keyboard_pre_init_user()` Implementation

This example, at the keyboard level, sets up B0, B1, B2, B3, and B4 as LED pins.

```c
void keyboard_pre_init_user(void) {
  // Call the keyboard pre init code.

  // Set our LED pins as output
  setPinOutput(B0);
  setPinOutput(B1);
  setPinOutput(B2);
  setPinOutput(B3);
  setPinOutput(B4);
}
```

### `keyboard_pre_init_*` Function Documentation

* Keyboard/Revision: `void keyboard_pre_init_kb(void)`
* Keymap: `void keyboard_pre_init_user(void)`

## Matrix Initialization Code

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. 

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. 


### `matrix_init_*` Function Documentation

* Keyboard/Revision: `void matrix_init_kb(void)`
* Keymap: `void matrix_init_user(void)`


## Keyboard Post Initialization code

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.


### Example `keyboard_post_init_user()` Implementation

This example, running after everything else has initialized, sets up the rgb underglow configuration.