Build a wireless keyboard relay that sends encrypted keystrokes from an M5Stack Stick to a paired receiver. This project combines the CardKB mini keyboard with an ESP32-based M5Stack Stick to create a compact input device that communicates securely over a custom encrypted link protocol. The guide includes a wiring diagram showing how to connect the CardKB via I2C, a complete parts list, and all necessary firmware code.
Followers will learn how to set up the keyboard hardware, establish an encrypted wireless connection between paired devices, monitor battery status, and test the relay using the serial monitor. The assembly process is straightforward, and the included firmware handles key polling, session management, and acknowledgment tracking automatically.
Wiring diagram

Gather all the parts
Assemble it in 5 steps
1. What this is
This is the keyboard half of Paper Claude, a pocket Claude Code terminal on an e-paper screen. The Stick reads the CardKB keyboard and sends each key over encrypted ESP-NOW radio to the PaperMono. Each key has a sequence number and is resent every 150 ms until the PaperMono sends an ACK back. You also need the companion project, "Paper Claude — PaperMono terminal". Its firmware must use the same include/link.h.
- Parts: 1 × M5StickC Plus (tested) or M5StickC PLUS2, 1 × M5Stack CardKB v1.1, and 1 × Grove cable (it comes with the CardKB).
- No Wi-Fi password or account is needed on this board.
2. Plug the CardKB into the Stick
Push one end of the Grove cable into the CardKB and the other end into the Grove port on the bottom of the Stick. The plug only fits one way. The four wires: black = GND (ground), red = 5V (power for the keyboard), yellow = SDA to G32 (data), white = SCL to G33 (clock). The keyboard answers at I2C address 0x5F. The Stick asks it for a key every 5 ms.
- The Serial Monitor (115200 baud) prints 'KEYBOARD FOUND at 0x5F' once the CardKB is seen, and 'KEYBOARD MISSING' if the cable comes loose.
- Use the CardKB v1.1 (the one with an ATmega chip), not the newer CardKB2. The CardKB2 has not been tried with this firmware.
3. Pair with the PaperMono
Pairing is automatic. No MAC addresses are built in. 1) Switch on the PaperMono first, then the Stick. 2) The Stick sends a pairing request (DISCOVER) on every Wi-Fi channel. 3) The PaperMono answers with an OFFER. Both boards save each other's MAC address in flash (NVS) and switch to encrypted packets. The Serial Monitor shows 'LINK paired with ...'. If ACKs stop, the Stick scans the channels again to follow the PaperMono. If the partner is silent for 10 s, each side forgets it and listens for pairing again.
- Private link (recommended): the built-in radio keys are public, so anyone with this code could read your keystrokes over the air. Copy include/pair_keys.example.h to include/pair_keys.h in BOTH projects. Put the same random PAIR_PMK and PAIR_LMK bytes in both. Make the bytes on a Mac with: python3 -c "import os;print(', '.join(f'0x{b:02x}' for b in os.urandom(16)))" (run it twice, once for each key). Never share or publish your pair_keys.h.
- Without pair_keys.h, link.h falls back to the public default keys, so the two boards pair out of the box.
- Automatic pairing is new and has not run on real hardware yet. Earlier builds, which had both MAC addresses built in, were tested for days.
4. Meet the critter
The screen is upright (portrait). An orange pixel critter runs at about 30 fps on its own core, so drawing never slows down typing. Typing: each letter flies up and becomes a star, and Backspace drops the newest one. Enter: the stars fuse into a comet that flies off to Claude. Claude working: an orange star pulses in the sky with a spinner word and a timer. Reply: a comet comes back and lands, then a small party. Claude asks something: it hops and waves under a '?'. Link down: the sky dims and it shows 'no mono' or 'no mac'. Idle: it wanders, hops, flips, dances, chases a firefly and naps, and the backlight dims while it naps. Button A (front): next trick. Button B (side): drops a cookie. Low battery shows a blinking icon.
- Claude's state (working, reply, question) comes inside the PaperMono's ACK packets, so it only shows while the link is up.
5. Serial monitor and testing tips
At 115200 baud the Stick prints STICK READY, KEYBOARD FOUND, LINK paired with ..., and one DELIVERED line for each key. Characters you type into the serial monitor are sent like real keys. Every 10 s it prints one battery line as JSON.
- The firmware ran on an M5StickC Plus (1.1). The PLUS2 has not been tested. It should work: it has the same Grove pins, and M5Unified detects the board when it starts.
Review all connections
1. Connections between "cardkb1" and "ESP32"
Deploy the firmware
#include <M5Unified.h>
#include <Wire.h>
#include <atomic>
#include "link.h"
#include "battery.h"
#include "stick_mascot.h"
// M5Unified uses controller 1 for the Stick's PMIC; Grove gets controller 0.
static TwoWire keyboardBus(0);
static QueueHandle_t keys;
static std::atomic<uint32_t> acknowledged{0}, lastAckAt{0};
static uint32_t sessionId, nextSeq = 1, sentKeys = 0;
static bool keyboardFound = false;
static uint8_t lastKey = 0;
static int8_t batteryPercent = -1;
static uint16_t batteryMv = 0;
static uint8_t charging = 0;
// The mascot lives on its own task (core 0) so drawing never delays key polling.
// Only that task touches the mascot and the display; the loop talks to it
// through this queue and a few atomics.
struct UiEvent { uint8_t type, value; }; // type 0 = key, 1 = button
static StickMascot mascot;
static QueueHandle_t uiEvents;
static PeerLink mono("mono");
static uint8_t myMac[6];
static std::atomic<uint8_t> agentState{StickMascot::Unknown}, wantBrightness{255};
static std::atomic<int8_t> uiBattery{-1};
static std::atomic<bool> uiCharging{false};
static void receive(const uint8_t* mac, const uint8_t* data, int len) {
Pairing offer;
if (readPairing(data, len, offer)) {
// A Mono answered our DISCOVER. Ignore offers meant for another Stick.
if (offer.type == OFFER && !memcmp(offer.mac, myMac, 6)) mono.want(mac);
return;
}
if (len != sizeof(Packet) || !mono.is(mac)) return;
Packet p; memcpy(&p, data, sizeof(p));
if (p.magic != MAGIC || p.type != ACK || p.session != sessionId) return;
acknowledged.store(p.seq);
lastAckAt.store(millis());
mono.heard();
// Newer Mono firmware reports what Claude is doing in its ACKs.
if ((p.batteryMv & 0xFF00) == AGENT_TAG) agentState.store(p.batteryMv & 0xFF);
}
static void notifyUi(uint8_t type, uint8_t value) {
UiEvent e = {type, value};
xQueueSend(uiEvents, &e, 0);
}
static void renderTask(void*) {
// Whole frame if memory allows, otherwise draw it in horizontal bands.
int bands = 1;
uint16_t* pixels = nullptr;
for (; bands <= 8 && !pixels; bands *= 2)
pixels = static_cast<uint16_t*>(heap_caps_malloc(sg::W * (sg::H / bands) * 2, MALLOC_CAP_8BIT));
bands /= 2;
Serial.printf("UI bands=%d free=%u largest=%u\n", bands, unsigned(ESP.getFreeHeap()), unsigned(ESP.getMaxAllocHeap()));
if (!pixels) vTaskDelete(nullptr);
sg::Surface surface;
surface.px = pixels;
mascot.begin(millis(), esp_random());
uint32_t frames = 0, drawMs = 0, renderUs = 0, statsAt = millis();
for (;;) {
uint32_t began = millis();
UiEvent e;
while (xQueueReceive(uiEvents, &e, 0) == pdTRUE) {
if (e.type == 0) mascot.key(e.value); else mascot.button(e.value);
}
uint32_t ack = lastAckAt.load();
mascot.status(ack && began - ack < 3500, agentState.load(), uiBattery.load(), uiCharging.load());
mascot.update(began);
for (int b = 0; b < bands; ++b) {
surface.y0 = b * (sg::H / bands); surface.rows = sg::H / bands;
uint32_t t0 = micros();
mascot.render(surface);
renderUs += micros() - t0;
M5.Display.pushImage(0, surface.y0, sg::W, surface.rows, pixels);
}
wantBrightness.store(mascot.brightness());
uint32_t spent = millis() - began;
drawMs += spent; ++frames;
if (began - statsAt >= 20000) {
Serial.printf("UI fps=%.1f frame_ms=%.1f render_ms=%.1f\n", frames * 1000.f / (began - statsAt), float(drawMs) / frames, renderUs / 1000.f / frames);
#ifdef SM_PROFILE
Serial.print("UI layers_ms sky/aurora/far/fx/planet/props/mascot/front:");
for (uint32_t& v : mascot.profile) { Serial.printf(" %.1f", v / 1000.f / frames); v = 0; }
Serial.println();
#endif
frames = 0; drawMs = 0; renderUs = 0; statsAt = began;
}
vTaskDelay(pdMS_TO_TICKS(spent < 31 ? 33 - spent : 2)); // ~30 fps, always yield
}
}
static void enqueue(uint8_t key) {
if (!key) return;
if (xQueueSend(keys, &key, 0) != pdTRUE) {
Serial.println("ERROR: key buffer full");
return;
}
lastKey = key;
notifyUi(0, key);
Serial.printf("KEY %02X queued\n", key);
}
void setup() {
Serial.begin(115200);
auto cfg = M5.config();
cfg.internal_imu = false; cfg.internal_rtc = false;
cfg.internal_mic = false; cfg.internal_spk = false;
M5.begin(cfg);
M5.Display.setRotation(2);
M5.Display.setBrightness(255);
M5.Display.setSwapBytes(true); // the renderer writes native RGB565
M5.Display.fillScreen(0);
keys = xQueueCreate(256, sizeof(uint8_t));
uiEvents = xQueueCreate(64, sizeof(UiEvent));
sessionId = esp_random();
keyboardBus.begin(32, 33, 100000);
keyboardBus.setTimeOut(20);
if (!keys || !uiEvents || !startLink(receive) || !mono.begin()) {
Serial.println("FATAL: link initialization failed");
while (true) delay(1000);
}
ownMac(myMac);
Serial.printf("STICK READY board=%d MAC=%s channel=%u SDA=32 SCL=33 mono=%s\n",
int(M5.getBoard()), WiFi.macAddress().c_str(), CHANNEL, mono.known() ? mono.text().c_str() : "none");
xTaskCreatePinnedToCore(renderTask, "mascot", 8192, nullptr, 1, nullptr, 0);
}
void loop() {
static uint32_t batteryAt = 0;
static uint32_t pollAt = 0, probeAt = 0, lightAt = 0, helloAt = 0, retryAt = 0;
static uint8_t brightness = 255;
static Packet pending;
static bool waiting = false;
uint32_t now = millis();
M5.update();
static uint8_t loggedAgent = 254;
if (agentState.load() != loggedAgent) { loggedAgent = agentState.load(); Serial.printf("AGENT %u\n", loggedAgent); }
if (M5.BtnA.wasClicked()) notifyUi(1, 0);
if (M5.BtnB.wasClicked()) notifyUi(1, 1);
// The backlight is on the PMIC's I2C bus, which belongs to this task.
if (now - lightAt >= 60) {
lightAt = now;
uint8_t want = wantBrightness.load();
if (brightness != want) {
brightness = brightness < want ? uint8_t(min(int(want), brightness + 6)) : uint8_t(max(int(want), brightness - 3));
M5.Display.setBrightness(brightness);
}
}
if (!batteryAt || now - batteryAt >= 10000) {
batteryAt = now;
batteryPercent = M5.Power.getBatteryLevel();
batteryMv = M5.Power.getBatteryVoltage();
auto charge = M5.Power.getChargeState();
charging = m5::charge_states_any_charging.contains(charge) ? 1 :
m5::charge_states_any_not_charging.contains(charge) ? 2 : 0;
uiBattery.store(batteryPercent); uiCharging.store(charging == 1);
Serial.printf("{\"type\":\"battery\",\"percent\":%ld,\"millivolts\":%d,\"charge_state\":\"%s\"}\n",
long(M5.Power.getBatteryLevel()), int(M5.Power.getBatteryVoltage()), batteryChargeState());
}
// Find the Mono again if its access point changed channels. Only scan after
// losing ACKs, so typing on an established link stays on the same channel.
static uint32_t channelAt = 0;
if ((!lastAckAt.load() || now - lastAckAt.load() > 3500) && now - channelAt > 450) {
channelAt = now;
uint8_t channel; wifi_second_chan_t second;
esp_wifi_get_channel(&channel, &second);
esp_wifi_set_channel(channel % 13 + 1, WIFI_SECOND_CHAN_NONE);
}
if (now - probeAt >= 1000) {
probeAt = now;
keyboardBus.beginTransmission(0x5f);
bool found = keyboardBus.endTransmission() == 0;
if (found != keyboardFound) Serial.printf("KEYBOARD %s at 0x5F\n", found ? "FOUND" : "MISSING");
keyboardFound = found;
}
if (keyboardFound && now - pollAt >= 5) {
pollAt = now;
if (keyboardBus.requestFrom(uint8_t(0x5f), uint8_t(1)) == 1) enqueue(keyboardBus.read());
}
// USB injection exercises the exact same wireless path as physical keys.
while (Serial.available()) enqueue(Serial.read());
if (waiting && acknowledged.load() == pending.seq) {
if (pending.type == KEY) {
++sentKeys;
Serial.printf("DELIVERED seq=%u key=%02X\n", unsigned(pending.seq), pending.key);
}
waiting = false;
}
if (!waiting) {
uint8_t key;
bool hasKey = xQueueReceive(keys, &key, 0) == pdTRUE;
if (hasKey || now - helloAt >= 500) { // twice a second keeps Claude's state fresh
pending = Packet{};
pending.session = sessionId; pending.seq = nextSeq++;
pending.type = hasKey ? KEY : HELLO;
pending.key = hasKey ? key : 0;
pending.keyboard = keyboardFound;
pending.battery = batteryPercent; pending.batteryMv = batteryMv; pending.charging = charging;
waiting = true; retryAt = now - 150; helloAt = now;
}
}
mono.service();
if (waiting && now - retryAt >= 150) {
retryAt = now;
// Without a partner, ask any Mono with our keys to pair (on every channel
// the scan above visits). Keys stay queued until a Mono answers.
if (mono.known()) mono.send(&pending, sizeof(pending));
else sendPairing(DISCOVER, myMac);
}
delay(1);
}Download project files
Remix this project
Make it yours in one click
Open a full copy of this project in your own Schematik workspace, diagram, code, parts, and assembly steps included. Swap the sensor, add features, or redesign the whole thing with AI. The author's original stays untouched.




