Skip to content

Keyboard

Building and Flashing the Program

Create a new Pico SDK project named usbdev-keyboard.

Create Pico SDK Project
  1. In VSCode, run >Raspberry Pi Pico: New Pico Project in the command palette.
  2. In the dialog below, select C/C++. new-project-dialog

  3. Create a project with the following settings:

    • Name ... Enter the project name.
    • Board type ... Select your board type.
    • Location ... Select the parent directory where the project directory will be created.
    • Stdio support ... Leave Console over USB unchecked when you use LABOPlatform or other USB features because they conflict with each other. You can enable it by editing the CMakeLists.txt file later.
    • Code generation options ... Check Generate C++ code.

new-project

Open Existing Pico SDK Project

Open the project folder in VSCode using one of the following methods:

  • In a command prompt, change the current directory to the project folder and execute code ..
  • In a Explorer, choose the project folder, push Alt+D to focus the address bar, and execute code ..

    vscode-from-explorer

If the folder is already prepared as a Pico SDK project, just proceed with editing and building the project.

If not, you will see the following message at the bottom right corner of VSCode.

do-you-want-to-import

Click Yes and you will see the following window.

import-project

Click Import and the project will be prepared as a Pico SDK project.

When the Do you want to import this project as Raspberry Pi Pico project? message disappears before you click Yes, you can reveal it by clicking the icon notify-icon at the bottom right corner of VSCode.

Clone the pico-jxglib repository from GitHub so the direcory structure looks like this:

├── pico-jxglib/
└── usbdev-keyboard/
    ├── CMakeLists.txt
    ├── usbdev-keyboard.cpp
    └── ...
Clone the Repository

Change the current directory to the parent directory where you want to clone the pico-jxglib repository and run the following commands:

$ git clone https://github.com/ypsitau/pico-jxglib.git
$ cd pico-jxglib
$ git submodule update --init --recursive

pico-jxglib is updated almost daily. If you've already cloned it, run the following command in the pico-jxglib directory to get the latest version:

$ git pull

A directory from a Git repository can safely be moved to another location even after cloning.

Add the following lines to the end of CMakeLists.txt:

CMakeLists.txt
1
2
3
4
target_link_libraries(usbdev-keyboard
    jxglib_USBDevice)
add_subdirectory(${CMAKE_CURRENT_LIST_DIR}/../pico-jxglib pico-jxglib)
jxglib_configure_USBDevice(usbdev-keyboard CFG_TUD_HID 1)

Enable UART or USB stdio as described below.

Enable UART and/or USB stdio

Find the following lines in CMakeLists.txt:

CMakeLists.txt
pico_enable_stdio_uart(your-project 0)
pico_enable_stdio_usb(your-project 0)

You can set the value to 1 to enable stdio or 0 to disable it.

  • pico_enable_stdio_uart() enables UART stdio that uses GPIO0 (UART0 TX) and GPIO1 (UART0 RX).
  • pico_enable_stdio_usb() enables USB stdio that uses the USB interface. Make sure to disable USB stdio when you use USB features because they conflict with each other.

Edit usbdev-keyboard.cpp as follows:

usbdev-keyboard.cpp
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "pico/stdlib.h"
#include "jxglib/GPIO.h"
#include "jxglib/USBDevice/HID.h"

using namespace jxglib;

auto& GPIO_ARROW_LEFT   = GPIO16;
auto& GPIO_ARROW_UP     = GPIO17;
auto& GPIO_ARROW_DOWN   = GPIO18;
auto& GPIO_ARROW_RIGHT  = GPIO19;

class MyKeyboard : public USBDevice::Keyboard {
private:
    int nKeycodePrev_;
public:
    MyKeyboard(USBDevice::Controller& deviceController);
public:
    virtual void OnTick() override;
};

int main(void)
{
    ::stdio_init_all(); 
    USBDevice::Controller deviceController({
            bcdUSB:             0x0200,
            bDeviceClass:       0x00,
            bDeviceSubClass:    0x00,
            bDeviceProtocol:    0x00,
            bMaxPacketSize0:    CFG_TUD_ENDPOINT0_SIZE,
            idVendor:           0xcafe,
            idProduct:          USBDevice::GenerateSpecificProductId(0x4000),
            bcdDevice:          0x0100,
        },
        0x0409,                             // Language ID (English - United States)
        "pico-jxglib sample",               // Manufacturer
        "My Keyboard",                      // Product
        "0123456789ABCDEF",                 // Serial Number
        TUSB_DESC_CONFIG_ATT_REMOTE_WAKEUP);// Configuration Attributes
    MyKeyboard myKeyboard(deviceController);
    deviceController.Initialize();
    myKeyboard.Initialize();
    GPIO_ARROW_LEFT     .init().set_dir_IN().pull_up();
    GPIO_ARROW_UP       .init().set_dir_IN().pull_up();
    GPIO_ARROW_DOWN     .init().set_dir_IN().pull_up();
    GPIO_ARROW_RIGHT    .init().set_dir_IN().pull_up();
    for (;;) {
        Tickable::Tick();
    }
}

MyKeyboard::MyKeyboard(USBDevice::Controller& deviceController) :
    USBDevice::Keyboard(deviceController, "RaspberryPi Pico Keyboard Interface", 0x81),
    nKeycodePrev_{0}
{}

void MyKeyboard::OnTick()
{
    uint8_t reportId = 0;
    uint8_t modifier  = 0;
    uint8_t usageIdTbl[6] = { 0 };
    int nUsageId = 0;
    if (!GPIO_ARROW_LEFT.get())     usageIdTbl[nUsageId++] = HID_KEY_ARROW_LEFT;
    if (!GPIO_ARROW_UP.get())       usageIdTbl[nUsageId++] = HID_KEY_ARROW_UP;
    if (!GPIO_ARROW_DOWN.get())     usageIdTbl[nUsageId++] = HID_KEY_ARROW_DOWN;
    if (!GPIO_ARROW_RIGHT.get())    usageIdTbl[nUsageId++] = HID_KEY_ARROW_RIGHT;
    if (::tud_suspended()) {
        // Wake up host if we are in suspend mode and REMOTE_WAKEUP feature is enabled by host
        if (nUsageId > 0) ::tud_remote_wakeup();
    } else if (!hid_ready()) {
        // do nothing
    } else if (nUsageId > 0) {
        // Send key report
        hid_keyboard_report(reportId, modifier, usageIdTbl);
    } else if (nKeycodePrev_ > 0) {
        // Send empty key report if previously we sent a key report with keycode, to indicate key release
        hid_keyboard_report(reportId, modifier, nullptr);
    }
    nKeycodePrev_ = nUsageId;
}

Build and flash the program to the board.

Build and Flash

The simplest way to build and flash the program is to use the UF2 file generated by the build process. Pico board, a USB cable, and a computer are all you need to get started. Here are the steps to build and flash the program:

  1. Pressing F7 on VSCode will build the project. If this is the first time you build the project, you will see the dialog shown below. Select Pico Using compilers: ... and the build process will start.

    select-a-kit

  2. After building, you can find the generated UF2 file in the build directory.

  3. Connect your Pico to the computer using a USB cable while holding the BOOTSEL button, and it will appear as a mass storage device. Copy the generated UF2 file to this device to flash it. No need to mind the destination directory, just copy it to the root directory of the device.

If you have a debug probe like this, you can also flash the program using OpenOCD and GDB. This is the recommended method for development, as it allows you to debug the program while running it on the board!