Full step-by-step guide with photos: PaperMatik Cyberdeck: Build a Pocket E-Paper Claude Code Terminal
What you'll build
A tiny computer that folds shut like a clamshell. The lid holds an e-paper screen. The base holds a small keyboard. You type a question and press Enter. Claude Code answers on the screen.
Claude doesn't run inside the case. It runs on your Mac, with all its normal tools. This screen is the window. It talks to your Mac over Wi-Fi, so there are no cables.
This project is the screen half. The keyboard half is the Paper Claude — Keyboard Relay project. You need both.
How it works
- You type on the CardKB keyboard. The Stick sends each key to the PaperMono by radio.
- The PaperMono shows your message and sends it to your Mac over Wi-Fi.
- A small helper on your Mac, called the bridge, passes it to Claude Code.
- Claude's answer comes back and appears on the screen, a few letters at a time.
The screen looks like the real Claude Code terminal. A little mascot in the corner shows what Claude is doing. A tiny terminal means it is running a command. A pencil means it is editing a file.
What you need
- M5Stack PaperMono
- The Keyboard Relay project: an M5StickC Plus or PLUS2, a CardKB keyboard and a Grove cable
- A Mac with Claude Code installed and signed in
- Wi-Fi on 2.4 GHz, the same network as your Mac
- Optional: the PaperMatik VI case (STL files below) and 2 × M3×25 bolts with nuts
Set it up
1. Set up your Mac
Download paperclaude-mac.zip from the files below. Unzip it and double-click setup.command.
Pick a folder Claude may work in. The setup then prints four lines that start with BRIDGE_. They are already copied for you.
2. Add your settings
Open include/secrets.h in this project. Paste the four lines. Then add your Wi-Fi name and password.
No Wi-Fi? Leave the name empty. Then plug the PaperMono into your Mac with USB. It works the same way.
3. Deploy
Deploy this project to the PaperMono. Then deploy the Keyboard Relay project to the Stick. The two boards find each other by themselves.
4. Say hi
Switch both boards on. The screen shows a welcome box. It checks off each part as it connects: keyboard, Wi-Fi, Mac and Claude. Then type hi and press Enter.
Build the case
The PaperMatik VI case folds everything into one small box. Print the three parts in PLA with no supports.
- Press the keyboard into the base. Add the Stick and plug in the Grove cable.
- Lay the bezel face down. Drop the PaperMono in, screen down.
- Press the lid onto the bezel until it clicks in.
- Push an M3 bolt through each hinge and add a nut. Stop when the lid holds its angle.
- Open it up. If the screen is upside down, type
/flipand press Enter.
Keys to know
- Enter sends. Tab starts a new line.
- Up and Down turn the page.
- Esc stops Claude.
- Y or N answers when Claude asks for permission.
/newstarts a fresh chat.- Button B on the PaperMono cleans the screen.
Good to know
- Your Mac must stay awake. Keep its lid open and stay on the same Wi-Fi.
- Only 2.4 GHz Wi-Fi works. The PaperMono can't see 5 GHz networks.
- Claude can really act. Anyone with the keyboard can ask Claude to change files in the folder you picked. Pick that folder with care.
- Long answers get cut short on the screen. The full answer is saved on your Mac.
- Battery numbers are a guess. They come from the battery voltage.
Wiring diagram

Assemble it in 3 steps
1. Get the two halves and the Mac ready
Paper Claude has two devices. This project is the screen half: an M5Stack PaperMono (C153) with no extra wiring. The keyboard half is the companion project "Paper Claude — Keyboard Relay" (M5StickC Plus or PLUS2 + CardKB on a Grove cable), published at https://www.schematik.io/projects/encrypted-keyboard-relay-955v. You also need a Mac with Claude Code installed and signed in, and a 2.4 GHz Wi-Fi network that both the Mac and the PaperMono can join.
- Build the Keyboard Relay first so you can type as soon as the screen is running.
- The Mac-side bridge (paperclaude-mac, Python 3.13+) is in the project's Supporting files, inside paperclaude-mono-schematik.zip.
2. Charge and switch on the PaperMono
Plug the PaperMono into the Mac with a USB-C data cable. It charges its built-in 1150 mAh battery from USB. A short press of the side power button switches it on or resets it; a double press switches it off.
- Use a cable that carries data, not a charge-only cable: the USB link to the bridge needs it.
- Do not bend or press hard on the e-paper glass: a cracked panel cannot be repaired.
3. Optional printed case
If you print the PaperMatik VI case, the PaperMono sits in it upside down compared with desk use. Close the case with 2 × M3×25 bolts and 2 × M3 nyloc nuts, finger-tight plus a quarter turn. After the first start, type /flip once so the text reads the right way up; the setting is remembered.
- Over-tightening the bolts can crack the printed case or press on the e-paper panel.
Deploy the firmware
#include <M5Unified.h>
#include <Preferences.h>
#include <ArduinoJson.h>
#include <atomic>
#include "link.h"
#include "editor.h"
#include "chat_layout.h"
#include "network.h"
#include "paper_ui.h"
// 3 = USB on the left (desk use). 1 = USB on the right (foldable cyberdeck lid).
#ifndef PAPERCLAUDE_ROTATION
#define PAPERCLAUDE_ROTATION 3
#endif
constexpr int W = ui::W, H = ui::H;
// Refresh levels, weakest first. FAST is a 1-bit partial update (about 0.1 s).
// TEXT is a clean full-screen refresh (about 0.5 s). DEEP is the slow one.
enum : uint8_t { R_NONE, R_FAST, R_TEXT, R_DEEP };
// Everything is drawn with FAST updates. They leave faint ghosts, so the
// firmware counts changed pixels: 1 point per 4000 (a full page of new text is
// about 15). One clean TEXT refresh runs at the next pause once SOFT is
// reached, or at once at HARD. M5Stack suggests a full refresh about every 10
// fast ones; this is far fewer by choice. Lower these numbers if ghosts show.
constexpr float GHOST_SOFT = 60, GHOST_HARD = 150;
constexpr uint32_t PAUSE_MS = 2500;
// Typing effect: the reply appears a few letters per screen update. One update
// takes about 0.13 s whatever its size, so 3 letters is about 22 per second.
// Use 1 for strict letter-by-letter (about 7 per second). A reply that is far
// ahead of the typing (TYPE_CATCH_UP letters) is typed faster.
constexpr uint32_t TYPE_CHARS = 3, TYPE_CATCH_UP = 600, ALL_CELLS = 0xFFFFFFFFu;
constexpr uint32_t STREAM_GAP_MS = 1000; // slowest pace for streamed reply text
static PeerLink stick("stick");
static M5Canvas canvas(&M5.Display);
static pg::Surface surface;
static uint8_t* previous;
static QueueHandle_t keys, hostFrames;
static SemaphoreHandle_t serialLock;
static Editor draft;
static ui::Screen screen;
static ui::State st;
static std::atomic<uint32_t> keyboardAt{0};
static std::atomic<bool> keyboardOK{false};
static std::atomic<int> stickBattery{-1}, stickBatteryMv{0}, stickCharging{0};
static uint32_t seenSession, seenSeq;
static bool seenAny = false;
static String bootId, pendingId, pendingText, requestId;
static uint32_t promptNumber = 0, retryAt = 0, hostAt = 0, dirtyAt = 0, drawnAt = 0, toastUntil = 0;
static uint32_t drawnPhase = 0, linkKey = 0, batteryAt = 0, viewSeq = 0;
static uint32_t fastMs = 0, fullMs = 0, renderMs = 0, partials = 0;
static uint8_t want = R_DEEP, rotation = PAPERCLAUDE_ROTATION;
static bool urgent = true, saveDraft = false, napping = false;
static float ghost = 0;
static uint32_t typed = 0; // reply cells typed so far
static bool typeAll = true, typePending = false;
// Fast updates draw a weaker black than a clean refresh. So finished text gets
// one clean refresh: after a reply (or a page of it) is typed, and on page
// turns. Set to false for fast updates only (fewer flashes, grayer text).
constexpr bool CRISP_TEXT = true;
static bool crispDue = false;
// A click on the power button shows a blank white screen for BLANK_MS, then
// the terminal comes back. A second click brings it back early.
constexpr uint32_t BLANK_MS = 10000;
static bool blank = false, blankDrawn = false;
static uint32_t blankUntil = 0;
static std::string chatPrompt, chatReply; // last prompt and reply seen in chat mode
static int monoBattery = -1;
static void request(uint8_t level, bool now = true) {
if (level > want) want = level;
if (now) urgent = true;
}
static void sendJson(const JsonDocument& doc) {
String line; serializeJson(doc, line);
if (paper_network::send(line)) return;
xSemaphoreTake(serialLock, portMAX_DELAY);
Serial.println(line);
xSemaphoreGive(serialLock);
}
static void handleKey(const uint8_t* mac, const uint8_t* data, int len) {
Pairing ask;
if (readPairing(data, len, ask)) {
// A Stick with our keys wants a partner: answer and pair with it.
if (ask.type == DISCOVER && !memcmp(ask.mac, mac, 6)) { sendPairing(OFFER, mac); stick.want(mac); }
return;
}
if (len != sizeof(Packet) || !stick.is(mac)) return;
Packet p; memcpy(&p, data, sizeof(p));
if (p.magic != MAGIC || (p.type != KEY && p.type != HELLO)) return;
stick.heard(); keyboardAt.store(millis()); keyboardOK.store(p.keyboard);
stickBattery.store(p.battery); stickBatteryMv.store(p.batteryMv); stickCharging.store(p.charging);
if (!seenAny || p.session != seenSession || p.seq != seenSeq) {
if (p.type == KEY && xQueueSend(keys, &p.key, 0) != pdTRUE) return;
seenSession = p.session; seenSeq = p.seq; seenAny = true;
}
p.type = ACK;
stick.send(&p, sizeof(p));
}
// Schematik builds with Arduino-ESP32 3.x, whose ESP-NOW receive callback
// passes an esp_now_recv_info; 2.x (espressif32@6.12.0) passes the MAC directly.
#if ESP_ARDUINO_VERSION_MAJOR >= 3
static void receiveKey(const esp_now_recv_info_t* info, const uint8_t* data, int len) {
handleKey(info->src_addr, data, len);
}
#else
static void receiveKey(const uint8_t* mac, const uint8_t* data, int len) { handleKey(mac, data, len); }
#endif
// Read USB on its own task: the panel's full refresh must not block transport.
static void usbReader(void*) {
String line; line.reserve(24576);
bool overflow = false;
for (;;) {
while (Serial.available()) {
char c = Serial.read();
if (c == '\n') {
if (!overflow && line.startsWith("{")) {
auto* doc = new JsonDocument;
if (!deserializeJson(*doc, line)) {
(*doc)["_usb"] = true; // only USB may change the Wi-Fi settings
if (xQueueSend(hostFrames, &doc, pdMS_TO_TICKS(100)) != pdTRUE) delete doc;
} else delete doc;
}
line = ""; overflow = false;
} else if (c != '\r') {
if (line.length() < 24576) line += c; else overflow = true;
}
}
vTaskDelay(pdMS_TO_TICKS(2));
}
}
// The Mac sends UTF-8. The screen font has one byte per cell: ASCII, Latin-1
// and a few symbols, all inside U+0020..U+00FF (see tools/make_font.py).
static std::string cells(const char* utf8) {
std::string out;
if (!utf8) return out;
for (const uint8_t* p = reinterpret_cast<const uint8_t*>(utf8); *p; ++p) {
if (*p < 0x80) out += char(*p);
else if ((*p == 0xC2 || *p == 0xC3) && (p[1] & 0xC0) == 0x80) { out += char(((*p & 3) << 6) | (p[1] & 0x3F)); ++p; }
else { out += '?'; while ((p[1] & 0xC0) == 0x80) ++p; }
}
return out;
}
static void toast(const char* text, uint32_t ms = 4000) {
st.toast = text; toastUntil = millis() + ms; request(R_FAST);
}
static void active() { st.lastActiveAt = millis(); }
static void changed() { request(R_FAST); dirtyAt = millis(); saveDraft = true; }
static void persistDraft() {
Preferences p;
if (p.begin("paperclaude", false)) { p.putString("draft", draft.text.c_str()); p.end(); saveDraft = false; }
}
static void setRotation(uint8_t next) {
rotation = next == 1 ? 1 : 3;
M5.Display.setRotation(rotation);
Preferences p;
if (p.begin("paperclaude", false)) { p.putUChar("rot", rotation); p.end(); }
request(R_DEEP);
}
static void sendPending() {
JsonDocument d; d["type"] = st.mode == "question" ? "answer" : "prompt";
d["id"] = pendingId; d["text"] = pendingText;
if (st.mode == "question") d["request_id"] = requestId;
sendJson(d); retryAt = millis();
}
static void submit() {
if (draft.text.empty() || pendingId.length()) return;
// Commands the device handles by itself.
if (draft.text == "/flip" || draft.text == "/clean") {
if (draft.text == "/flip") setRotation(rotation == 1 ? 3 : 1); else request(R_DEEP);
draft.text.clear(); draft.cursor = 0; saveDraft = true; dirtyAt = millis();
return;
}
if (st.busy && st.mode != "question") { toast("Still working. Esc stops Claude."); return; }
if (st.mode == "approval") return;
pendingId = bootId + "-" + String(++promptNumber);
pendingText = draft.text.c_str();
sendPending(); request(R_FAST);
}
static void decide(bool allow) {
if (st.mode != "approval") return;
JsonDocument d; d["type"] = "decision"; d["request_id"] = requestId;
d["allow"] = allow; sendJson(d);
toast(allow ? "Allowed." : "Denied.", 2500);
}
static void stop() {
JsonDocument d; d["type"] = "stop"; sendJson(d);
if (st.busy) toast("Stopping\x85", 2500);
}
static void turnPage(int amount) {
int next = std::max(0, std::min(st.page + amount, screen.pages(st) - 1));
if (next == st.page) return;
st.page = next;
// A page that is already typed out is shown crisp at once, like an e-reader.
request(CRISP_TEXT && (typeAll || typed >= screen.cellsThroughPage(st)) ? R_TEXT : R_FAST);
}
// Draw the screen and send it to the panel. FAST pushes only the changed box.
static void flush() {
const uint32_t now = millis();
uint8_t level = want;
st.sending = pendingId.length() > 0;
screen.render(surface, st, now);
drawnPhase = ui::phase(st, now);
napping = ui::mood(st, now) == ui::Mood::Nap;
renderMs = millis() - now;
if (blank) { surface.fill(pg::WHITE); level = R_TEXT; }
const uint8_t* pixels = surface.px;
if (level == R_FAST) {
int x0 = W, y0 = H, x1 = -1, y1 = -1;
uint32_t count = 0;
for (int y = 0; y < H; ++y) {
const uint8_t* a = pixels + y * W; const uint8_t* b = previous + y * W;
if (!memcmp(a, b, W)) continue;
int left = 0, right = W - 1;
while (a[left] == b[left]) ++left;
while (a[right] == b[right]) --right;
for (int x = left; x <= right; ++x) count += a[x] != b[x];
x0 = std::min(x0, left); x1 = std::max(x1, right); y0 = std::min(y0, y); y1 = y;
}
if (x1 >= 0) {
M5.Display.setEpdMode(m5gfx::epd_mode_t::epd_fastest);
M5.Display.setClipRect(x0, y0, x1 - x0 + 1, y1 - y0 + 1);
canvas.pushSprite(0, 0); M5.Display.clearClipRect();
M5.Display.display(x0, y0, x1 - x0 + 1, y1 - y0 + 1); M5.Display.waitDisplay();
memcpy(previous, pixels, W * H);
ghost += count / 4000.f; ++partials;
fastMs = millis() - now;
}
} else {
M5.Display.setEpdMode(level == R_DEEP ? m5gfx::epd_mode_t::epd_quality : m5gfx::epd_mode_t::epd_text);
canvas.pushSprite(0, 0);
M5.Display.display(); M5.Display.waitDisplay();
memcpy(previous, pixels, W * H);
ghost = 0; partials = 0;
fullMs = millis() - now;
}
want = R_NONE; urgent = false; typePending = false; drawnAt = millis();
}
static void screenshot() {
// 1 bit per pixel as hex, 200 characters per row. 1 = white.
xSemaphoreTake(serialLock, portMAX_DELAY);
Serial.printf("SHOT1 %d %d\n", W, H);
char row[W / 4 + 1]; row[W / 4] = '\n';
for (int y = 0; y < H; ++y) {
const uint8_t* line = previous + y * W;
for (int x = 0; x < W; x += 4) {
int v = (line[x] >= 128) << 3 | (line[x + 1] >= 128) << 2 | (line[x + 2] >= 128) << 1 | (line[x + 3] >= 128);
row[x / 4] = "0123456789abcdef"[v];
}
Serial.write(reinterpret_cast<uint8_t*>(row), sizeof(row));
}
Serial.println("SHOT END"); xSemaphoreGive(serialLock);
}
static void readBattery() {
// Voltage and level reads are safe on this task. Never open the charger
// status gate: it stalls this board's shared I2C bus until a power cycle.
monoBattery = M5.Power.getBatteryLevel(); batteryAt = millis();
}
static void viewMessage(JsonDocument& d) {
const uint32_t now = millis();
std::string prompt = cells(d["prompt"] | ""), reply = cells(d["reply"] | ""), notice = cells(d["notice"] | "");
std::string mode = d["mode"] | "chat", status = cells(d["status"] | "Ready"), activity = cells(d["activity"] | "");
if (activity.empty() && status.compare(0, 6, "Using ") == 0) activity = status.substr(6);
const bool busy = d["busy"] | false, wasReady = ui::ready(st);
const bool grew = reply.size() > st.reply.size() && reply.compare(0, st.reply.size(), st.reply) == 0;
const bool redrawn = prompt != st.prompt || notice != st.notice || mode != st.mode || (reply != st.reply && !grew);
if (redrawn || grew) { ++st.contentRev; active(); }
if (mode == "chat") {
// A reply that arrives while Claude works is typed out. Anything that is
// already complete (old conversation, /new, /history) shows at once.
const bool continues = reply.size() >= chatReply.size() && reply.compare(0, chatReply.size(), chatReply) == 0;
if (prompt != chatPrompt || !wasReady) { typeAll = !busy; typed = 0; }
else if (!continues && !typeAll) {
size_t common = 0;
while (common < reply.size() && common < chatReply.size() && reply[common] == chatReply[common]) ++common;
if (common < reply.size() && common * 10 < chatReply.size() * 9) typed = 0; // a different text: start again
}
chatPrompt = prompt; chatReply = reply;
}
if (mode != st.mode || (d["jump"] | false)) st.page = 0;
st.prompt = prompt; st.reply = reply; st.notice = notice; st.mode = mode;
requestId = d["request_id"] | "";
std::string model = cells(d["model"] | "Claude"), permission = d["permission_mode"] | "default", cwd = cells(d["cwd"] | "");
bool chrome = model != st.model || permission != st.permission || status != st.status || activity != st.activity || (!cwd.empty() && cwd != st.cwd);
st.model = model; st.permission = permission; st.status = status; st.activity = activity;
if (!cwd.empty()) st.cwd = cwd;
st.hasView = true;
if (busy && !st.busy) {
st.busySince = now - (d["busy_ms"] | 0u); st.verbSeed = esp_random(); st.outcome = ui::OUT_NONE; active();
} else if (!busy && st.busy) {
st.turnMs = now - st.busySince; st.doneAt = now; active();
std::string outcome = d["outcome"] | "";
st.outcome = outcome == "ok" ? ui::OUT_OK : outcome == "stopped" ? ui::OUT_STOPPED : outcome == "error" ? ui::OUT_ERROR : ui::OUT_NONE;
}
const bool turned = busy != st.busy;
st.busy = busy;
// Streamed text is paced; everything else shows at once. All of it uses
// fast updates; the ghost budget in loop() decides when to clean.
if (turned && !busy) crispDue = true;
if (CRISP_TEXT && ((redrawn && !busy && typeAll) || wasReady != ui::ready(st))) request(R_TEXT);
else if (redrawn || turned || chrome || wasReady != ui::ready(st)) request(R_FAST);
else if (grew) request(R_FAST, false);
}
static void hostMessage(JsonDocument& d) {
hostAt = millis();
String type = d["type"] | "";
if (type == "view") {
uint32_t seq = d["seq"] | 0u;
if (seq != viewSeq) { viewSeq = seq; viewMessage(d); }
JsonDocument ack; ack["type"] = "view_ack"; ack["seq"] = seq; sendJson(ack);
} else if (type == "accepted" && pendingId == (d["id"] | "")) {
// Preserve text typed after Enter while the link was busy.
if (draft.text.compare(0, pendingText.length(), pendingText.c_str()) == 0)
draft.text.erase(0, pendingText.length());
draft.cursor = draft.text.size(); pendingId = ""; pendingText = ""; changed();
} else if (type == "rejected" && pendingId == (d["id"] | "")) {
pendingId = ""; pendingText = ""; toast(cells(d["reason"] | "Try again").c_str());
} else if (type == "ping") {
readBattery();
JsonDocument pong; pong["type"] = "pong"; pong["view_seq"] = viewSeq;
pong["keyboard"] = keyboardOK.load() && keyboardAt.load() && millis() - keyboardAt.load() < 3500;
pong["draft_chars"] = draft.text.size();
pong["width"] = W; pong["height"] = H; pong["permission_mode"] = st.permission;
pong["backlight"] = false; pong["rotation"] = rotation;
pong["wifi"] = paper_network::online(); pong["wifi_configured"] = paper_network::state.load() != 0;
pong["net_state"] = paper_network::state.load(); pong["wifi_status"] = int(WiFi.status()); pong["rssi"] = WiFi.RSSI(); pong["channel"] = WiFi.channel();
pong["fast_ms"] = fastMs; pong["full_ms"] = fullMs; pong["render_ms"] = renderMs;
pong["partials"] = partials; pong["ghost"] = int(ghost);
if (keyboardAt.load() && millis() - keyboardAt.load() < 15000) {
pong["stick_battery"]["percent"] = stickBattery.load();
pong["stick_battery"]["millivolts"] = stickBatteryMv.load();
pong["stick_battery"]["charge_state"] = stickCharging.load() == 1 ? "charging" : stickCharging.load() == 2 ? "not_charging" : "unknown";
}
pong["battery"]["percent"] = monoBattery;
pong["battery"]["millivolts"] = M5.Power.getBatteryVoltage();
pong["battery"]["charge_state"] = "unknown";
sendJson(pong);
} else if (type == "config") {
if (d["rotation"].is<int>() && uint8_t(d["rotation"].as<int>()) != rotation) setRotation(d["rotation"].as<int>());
} else if (type == "diagnostic" && String(d["command"] | "") == "screenshot") screenshot();
else if ((type == "wifi_setup" || type == "wifi_forget") && d["_usb"].is<bool>()) {
// Sent by the Mac's setup_wifi.py over USB. The reply always goes to USB.
bool ok = type == "wifi_forget" ? paper_network::forget() :
paper_network::configure(d["ssid"] | "", d["password"] | "", d["host"] | "", d["identity"] | "",
d["psk"] | "", uint16_t(d["port"] | 0));
JsonDocument r; r["type"] = "wifi_setup_result"; r["ok"] = ok; r["id"] = d["id"] | "";
String out; serializeJson(r, out);
xSemaphoreTake(serialLock, portMAX_DELAY); Serial.println(out); Serial.flush(); xSemaphoreGive(serialLock);
if (ok) { toast(type == "wifi_forget" ? "Wi-Fi forgotten. Restarting\x85" : "Wi-Fi saved. Restarting\x85"); flush(); delay(500); ESP.restart(); }
else toast("Wi-Fi setup was rejected");
}
}
void setup() {
Serial.setRxBufferSize(32768); Serial.begin(115200); delay(300);
serialLock = xSemaphoreCreateMutex();
pinMode(47, INPUT_PULLUP); pinMode(48, OUTPUT_OPEN_DRAIN);
for (int i = 0; i < 18; ++i) { digitalWrite(48, LOW); delayMicroseconds(10); digitalWrite(48, HIGH); delayMicroseconds(10); }
pinMode(47, OUTPUT_OPEN_DRAIN); digitalWrite(47, LOW); delayMicroseconds(10);
digitalWrite(48, HIGH); delayMicroseconds(10); digitalWrite(47, HIGH); delayMicroseconds(10);
pinMode(47, INPUT); pinMode(48, INPUT);
Preferences p;
if (p.begin("paperclaude", false)) {
draft.text = p.getString("draft", "").c_str();
// Remember the mounting direction, so a later build cannot flip the screen.
if (!p.isKey("rot")) p.putUChar("rot", PAPERCLAUDE_ROTATION);
rotation = p.getUChar("rot", PAPERCLAUDE_ROTATION) == 1 ? 1 : 3; p.end();
}
auto cfg = M5.config(); cfg.clear_display = false;
cfg.internal_imu = cfg.internal_rtc = cfg.internal_mic = cfg.internal_spk = false;
M5.begin(cfg); M5.Display.setAutoDisplay(false); M5.Display.setRotation(rotation);
if (M5.Display.width() != W || M5.Display.height() != H) {
Serial.println("FATAL PaperMono display detection failed"); while (true) delay(1000);
}
canvas.setPsram(true); canvas.setColorDepth(lgfx::color_depth_t::grayscale_8bit);
previous = static_cast<uint8_t*>(ps_malloc(W * H));
keys = xQueueCreate(256, sizeof(uint8_t)); hostFrames = xQueueCreate(8, sizeof(JsonDocument*));
if (!canvas.createSprite(W, H) || !previous || !keys || !hostFrames || !serialLock || !startLink(receiveKey) || !stick.begin()) {
Serial.println("FATAL allocation or radio"); while (true) delay(1000);
}
surface.px = static_cast<uint8_t*>(canvas.getBuffer()); surface.w = W; surface.h = H;
memset(previous, 255, W * H); bootId = String(esp_random(), HEX);
draft.columns = ui::DRAFT_COLS;
M5.Display.setBrightness(0); // the front light stays off
if (draft.text.size() > Editor::LIMIT) draft.text.resize(Editor::LIMIT);
draft.cursor = draft.text.size();
st.draft = &draft; st.bootAt = st.lastActiveAt = millis();
readBattery();
xTaskCreate(usbReader, "usb-reader", 8192, nullptr, 3, nullptr);
if (!paper_network::begin(hostFrames)) {
Serial.println("Wi-Fi task allocation failed; USB available");
}
flush();
JsonDocument hello; hello["type"] = "hello"; hello["firmware"] = "paper-claude-5";
hello["boot"] = bootId; sendJson(hello);
}
void loop() {
M5.update();
if (M5.BtnA.wasClicked()) { active(); turnPage(-1); }
if (M5.BtnB.wasClicked()) request(R_TEXT); // short press: clean full refresh
if (M5.BtnPWR.wasClicked()) { // read from the PMIC by M5.update() on this task
blank = !blank; blankDrawn = false; blankUntil = millis() + BLANK_MS; request(R_TEXT);
}
if (M5.BtnA.wasReleaseFor(1200) && !pendingId.length()) { draft.text.clear(); draft.cursor = 0; active(); changed(); }
if (M5.BtnB.wasReleaseFor(1200)) request(R_DEEP);
if (M5.Touch.getCount()) {
auto t = M5.Touch.getDetail();
if (t.wasPressed()) {
active();
switch (ui::Screen::hit(st, t.x, t.y)) {
case ui::Hit::Prev: turnPage(-1); break;
case ui::Hit::Next: turnPage(1); break;
case ui::Hit::Allow: decide(true); break;
case ui::Hit::Deny: decide(false); break;
case ui::Hit::Main: if (st.busy && st.mode != "question") stop(); else submit(); break;
default: break;
}
}
}
JsonDocument* frame;
while (xQueueReceive(hostFrames, &frame, 0) == pdTRUE) { hostMessage(*frame); delete frame; }
uint8_t k;
while (xQueueReceive(keys, &k, 0) == pdTRUE) {
active();
if (k == 27) { // Esc stops Claude, or finishes the typing effect at once
if (!st.busy && st.revealing) { typeAll = true; request(R_FAST); } else stop();
continue;
}
if (k == 0xb5 || k == 0xb6) { turnPage(k == 0xb5 ? -1 : 1); continue; }
if (st.mode == "approval") { if (k == 'y' || k == 'Y') decide(true); else if (k == 'n' || k == 'N') decide(false); continue; }
if (k == '\r' || k == '\n') { submit(); continue; }
if (k == '\t') k = '\n';
if (!pendingId.length() && draft.key(k)) { st.lastKeyAt = millis(); ++st.keyCount; changed(); }
}
stick.service();
const uint32_t now = millis();
if (pendingId.length() && now - retryAt > 2000) sendPending();
if (saveDraft && now - dirtyAt > 1500) persistDraft();
if (!st.toast.empty() && int32_t(now - toastUntil) >= 0) { st.toast.clear(); request(R_FAST); }
if (now - batteryAt > 60000) readBattery();
// Links and batteries. Battery numbers move in steps of 5 to save refreshes.
st.net = paper_network::state.load(); st.viaWifi = paper_network::online();
st.hostOnline = hostAt && now - hostAt < 12000;
st.keyboard = keyboardAt.load() && now - keyboardAt.load() < 3500 && keyboardOK.load();
const int stick = stickBattery.load();
if (monoBattery >= 0 && (st.battery < 0 || abs(monoBattery - st.battery) >= 4)) st.battery = (monoBattery + 2) / 5 * 5;
if (stick >= 0 && (st.stickBattery < 0 || abs(stick - st.stickBattery) >= 4)) st.stickBattery = (stick + 2) / 5 * 5;
st.stickCharging = stickCharging.load() == 1;
const uint32_t links = st.net | st.viaWifi << 3 | st.hostOnline << 4 | st.keyboard << 5 | st.stickCharging << 6 |
uint32_t(st.battery + 1) << 8 | uint32_t(st.stickBattery + 1) << 16;
if (links != linkKey) { linkKey = links; request(R_FAST); }
// Typing effect. It stops at the end of the page and goes on when you turn it.
const bool wasRevealing = st.revealing;
st.revealing = false;
if (ui::ready(st) && st.mode == "chat" && !typeAll) {
const uint32_t total = screen.cellsTotal(st), target = std::min(total, screen.cellsThroughPage(st));
typed = std::max(std::min(typed, total), screen.cellsBeforePage(st));
if (typed < target) {
st.revealing = true;
if (!typePending) {
const uint32_t backlog = target - typed;
typed += std::min(backlog, backlog > TYPE_CATCH_UP ? backlog / 150 : TYPE_CHARS);
typePending = true; active(); request(R_FAST);
}
} else if (!st.busy && typed >= total) typeAll = true; // all typed
}
st.revealCells = typeAll ? ALL_CELLS : typed;
if (wasRevealing && !st.revealing) { if (!st.busy) { st.doneAt = now; crispDue = true; } request(R_FAST); }
if (crispDue && !st.busy && !st.revealing) { crispDue = false; if (CRISP_TEXT) request(R_TEXT); }
// The clock moves the picture only in slow beats and on mood changes.
if (ui::phase(st, now) != drawnPhase) {
// Falling asleep is the quiet moment to wipe any ghosts.
request(ui::mood(st, now) == ui::Mood::Nap && !napping && ghost >= 3 ? R_TEXT : R_FAST);
}
// Clean up ghosts at a pause, or at once when there are too many.
if (ghost >= GHOST_HARD) request(R_TEXT);
else if (ghost >= GHOST_SOFT && now - st.lastActiveAt > PAUSE_MS && now - drawnAt > 1500) request(R_TEXT);
if (blank && int32_t(now - blankUntil) >= 0) { blank = false; request(R_TEXT); }
if (blank) { // stay white: draw it once, hold everything else until it ends
if (!blankDrawn) { flush(); blankDrawn = true; }
} else if (want && (urgent ? now - drawnAt >= (st.revealing ? 5u : 40u) : now - drawnAt >= STREAM_GAP_MS)) flush();
delay(2);
}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.




