/* ========================================================================== typewriter-keys.ino ยท a 1940s typewriter as a USB keyboard (Spellworks, agent D) STARTER CODE, NOT YET TESTED ON HARDWARE. Prove it on the bench with three or four keys before wiring all of them. One small magnet rides on each key lever; one analog Hall sensor sits under it on a sensor strip. Three CD74HC4067 multiplexers (16 channels each) bring up to 48 sensors into the RP2040's three analog pins. The firmware learns each key's rest and pressed readings in a calibration pass, then turns each key into a USB keyboard press with hysteresis and a short lockout. The carriage return lever closes a microswitch: that is Enter, the cast. Board: Raspberry Pi Pico (RP2040), Arduino core "Raspberry Pi Pico/RP2040" by Earle Philhower (arduino-pico). Tools > USB Stack: the default (Pico SDK): the built-in Keyboard library only works with that stack. Uses the core's Keyboard and EEPROM libraries; the USB serial port still works for calibration printouts. HID polling is set to 1 ms below. Wiring CD74HC4067 x3: S0..S3 of all three tied together to GP2..GP5, EN to GND, SIG of mux 0/1/2 to GP26/GP27/GP28 (ADC0..2), VCC 3.3 V (sensors and muxes on 3.3 V, not 5 V). Hall sensors: analog, ratiometric, 3.3 V supply, output to a mux input. RETURN_PIN: microswitch at the return lever's stop, to GND. CAL_PIN: a small button to GND (calibration / test mode). Modes normal type away calibration hold CAL at power-up, or hold it 2 s while running test mode hold CAL and the return lever at power-up: types 1,000 lines (spells and wishes) with human-ish timing, for the soak test ========================================================================== */ #include #include #include // arduino-pico asks the host to poll HID every 10 ms by default; 1 ms keeps the // keystroke-to-glass budget (overrides a weak symbol in the core's USB.cpp) int usb_hid_poll_interval = 1; const uint8_t SEL_PINS[4] = { 2, 3, 4, 5 }; const uint8_t MUX_ADC[3] = { 26, 27, 28 }; #define RETURN_PIN 6 #define CAL_PIN 7 #define NCH 48 /* thresholds, as a fraction of each key's calibrated travel */ #define PRESS_AT 0.60f #define RELEASE_AT 0.35f #define KEY_LOCKOUT_MS 30 #define RETURN_LOCKOUT_MS 150 #define MIN_DELTA 120 // counts (of 4095) between rest and pressed, or the channel is ignored (to confirm) /* what each channel types: mux 0 = channels 0..15, mux 1 = 16..31, mux 2 = 32..47. Edit this table while wiring: the calibration printout shows which channel moved. */ enum : uint16_t { K_NONE = 0, K_SHIFT = 0x100, K_BACK = 0x101 }; const uint16_t KEYMAP[NCH] = { '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', // 0..9 top row (no 1 key on most machines) 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', // 10..19 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', // 20..29 'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/', // 30..39 ' ', K_BACK, K_SHIFT, '\'', K_NONE, K_NONE, K_NONE, K_NONE // 40 space bar, 41 backspace, 42 shift basket, 43 extra }; /* calibration, stored in flash */ #define CAL_MAGIC 0x46414D31UL // "FAM1" struct Cal { uint32_t magic; uint16_t rest[NCH]; uint16_t full[NCH]; }; Cal cal; bool calValid = false; /* state */ uint16_t raw[NCH]; bool down[NCH]; uint32_t lastPress[NCH]; bool shiftHeld = false; bool returnDown = false; uint32_t lastReturn = 0; uint32_t calHeldSince = 0; /* -------------------------------------------------------------------------- scanning: 16 select steps x 3 muxes read in parallel, about 3 kHz -------------------------------------------------------------------------- */ void scanAll() { for (uint8_t s = 0; s < 16; s++) { for (uint8_t b = 0; b < 4; b++) digitalWrite(SEL_PINS[b], (s >> b) & 1); delayMicroseconds(8); // let the mux and the sensor output settle for (uint8_t m = 0; m < 3; m++) raw[m * 16 + s] = analogRead(MUX_ADC[m]); } } float travel(uint8_t ch) { int32_t span = (int32_t)cal.full[ch] - (int32_t)cal.rest[ch]; // either magnet polarity works if (abs(span) < MIN_DELTA) return 0.f; return (float)((int32_t)raw[ch] - (int32_t)cal.rest[ch]) / (float)span; } /* -------------------------------------------------------------------------- keys -------------------------------------------------------------------------- */ void onPress(uint8_t ch) { uint16_t k = KEYMAP[ch]; if (k == K_NONE) return; if (k == K_SHIFT) { Keyboard.press(KEY_LEFT_SHIFT); shiftHeld = true; return; } if (k == K_BACK) { Keyboard.write(KEY_BACKSPACE); return; } // write = press + release at once, so a key held against the platen never auto-repeats Keyboard.write((uint8_t)k); } void onRelease(uint8_t ch) { if (KEYMAP[ch] == K_SHIFT) { Keyboard.release(KEY_LEFT_SHIFT); shiftHeld = false; } } void processKeys(uint32_t now) { if (!calValid) return; for (uint8_t ch = 0; ch < NCH; ch++) { if (KEYMAP[ch] == K_NONE) continue; float t = travel(ch); if (!down[ch]) { if (t > PRESS_AT && now - lastPress[ch] >= KEY_LOCKOUT_MS) { down[ch] = true; lastPress[ch] = now; onPress(ch); } } else if (t < RELEASE_AT) { down[ch] = false; onRelease(ch); } } } void processReturn(uint32_t now) { bool closed = digitalRead(RETURN_PIN) == LOW; if (closed && !returnDown && now - lastReturn >= RETURN_LOCKOUT_MS) { Keyboard.write(KEY_RETURN); // the cast lastReturn = now; } returnDown = closed; } /* -------------------------------------------------------------------------- calibration -------------------------------------------------------------------------- */ void blink(int n, int ms) { for (int i = 0; i < n; i++) { digitalWrite(LED_BUILTIN, HIGH); delay(ms); digitalWrite(LED_BUILTIN, LOW); delay(ms); } } void calibrate() { Keyboard.releaseAll(); Serial.println(F("\n== calibration ==")); Serial.println(F("Hands off the keys for 2 seconds...")); blink(6, 80); uint32_t sum[NCH] = { 0 }; uint32_t n = 0; uint32_t t0 = millis(); while (millis() - t0 < 2000) { scanAll(); for (uint8_t ch = 0; ch < NCH; ch++) sum[ch] += raw[ch]; n++; } for (uint8_t ch = 0; ch < NCH; ch++) { cal.rest[ch] = sum[ch] / n; cal.full[ch] = cal.rest[ch]; } Serial.println(F("Now press every key once, slowly, all the way down.")); Serial.println(F("Press the calibration button when you are done.")); digitalWrite(LED_BUILTIN, HIGH); while (digitalRead(CAL_PIN) == LOW) delay(5); // wait for the button to be let go delay(50); while (digitalRead(CAL_PIN) == HIGH) { scanAll(); for (uint8_t ch = 0; ch < NCH; ch++) { int32_t d = (int32_t)raw[ch] - cal.rest[ch]; int32_t best = (int32_t)cal.full[ch] - cal.rest[ch]; if (abs(d) > abs(best)) { cal.full[ch] = raw[ch]; if (abs(d) > MIN_DELTA && abs(best) <= MIN_DELTA) { Serial.print(F(" moved: channel ")); Serial.print(ch); Serial.print(F(" ('")); Serial.write(KEYMAP[ch] < 0x100 && KEYMAP[ch] >= 32 ? (char)KEYMAP[ch] : '?'); Serial.println(F("')")); } } } } digitalWrite(LED_BUILTIN, LOW); cal.magic = CAL_MAGIC; EEPROM.put(0, cal); EEPROM.commit(); calValid = true; Serial.println(F("ch key rest full delta")); int good = 0; for (uint8_t ch = 0; ch < NCH; ch++) { if (KEYMAP[ch] == K_NONE) continue; int32_t d = (int32_t)cal.full[ch] - cal.rest[ch]; char line[48]; char key = KEYMAP[ch] < 0x100 ? (char)KEYMAP[ch] : (KEYMAP[ch] == K_SHIFT ? 'S' : 'B'); snprintf(line, sizeof line, "%2u '%c' %4u %4u %5ld %s", ch, key, cal.rest[ch], cal.full[ch], (long)d, abs(d) < MIN_DELTA ? " <- no movement" : ""); Serial.println(line); if (abs(d) >= MIN_DELTA) good++; } Serial.print(good); Serial.println(F(" keys calibrated. Saved.")); blink(2, 300); while (digitalRead(CAL_PIN) == LOW) delay(5); } /* -------------------------------------------------------------------------- test mode: 1,000 casts with human-ish timing -------------------------------------------------------------------------- */ const char* const PHRASES[] = { "awaken", "wake up familiar", "ember", "loom", "wire", "static", "garage", "feed", "grove", "mirror", "typewriter", "open please", "light the roots", "sing ember", "hush", "goodnight", "i wish the desert would remember us", "hello old friend", "love tram", "dragonfly", "listen" }; void testMode() { Serial.println(F("== test mode: 1000 casts. Press the calibration button to stop. ==")); delay(3000); const int count = sizeof(PHRASES) / sizeof(PHRASES[0]); for (int i = 1; i <= 1000; i++) { const char* p = PHRASES[random(count)]; for (const char* c = p; *c; c++) { Keyboard.write((uint8_t)*c); delay(random(70, 240)); if (digitalRead(CAL_PIN) == LOW) { Serial.println(F("stopped")); return; } } Keyboard.write(KEY_RETURN); Serial.print(F("cast ")); Serial.println(i); delay(random(3000, 6000)); } Serial.println(F("1000 casts done.")); } /* -------------------------------------------------------------------------- setup + loop -------------------------------------------------------------------------- */ void setup() { pinMode(LED_BUILTIN, OUTPUT); for (uint8_t p : SEL_PINS) pinMode(p, OUTPUT); pinMode(RETURN_PIN, INPUT_PULLUP); pinMode(CAL_PIN, INPUT_PULLUP); analogReadResolution(12); Serial.begin(115200); Keyboard.begin(); EEPROM.begin(512); // arduino-pico emulates 256 to 4096 bytes; commit() writes flash EEPROM.get(0, cal); calValid = cal.magic == CAL_MAGIC; delay(300); bool cal_ = digitalRead(CAL_PIN) == LOW; bool ret = digitalRead(RETURN_PIN) == LOW; if (cal_ && ret) testMode(); else if (cal_ || !calValid) calibrate(); } void loop() { uint32_t now = millis(); scanAll(); processKeys(now); processReturn(now); // hold the calibration button for 2 s to calibrate again if (digitalRead(CAL_PIN) == LOW) { if (!calHeldSince) calHeldSince = now; if (now - calHeldSince > 2000) { calHeldSince = 0; calibrate(); } } else { calHeldSince = 0; } }