Compare commits

...

2 Commits

Author SHA1 Message Date
nikrozman 8e9a3712ac Remove unnecessary comments, clean up code 2026-03-03 21:42:07 +01:00
nikrozman cb433f76c9 Initial sleep implementation, closes #6 2026-03-03 21:42:06 +01:00
16 changed files with 532 additions and 213 deletions
+17 -17
View File
@@ -5,17 +5,17 @@ A BLE HID mouse that uses the onboard IMU of a **Seeed XIAO nRF52840 Sense** to
## Features ## Features
- **6-DoF gyro + accelerometer** via LSM6DS3 with complementary filter - **6-DoF gyro + accelerometer** via LSM6DS3 with complementary filter
- **Hardware tap detection** single tap = left click, double tap = right click - **Hardware tap detection** - single tap = left click, double tap = right click
- **BLE HID mouse** works natively on Windows, macOS, Linux, Android, iOS - **BLE HID mouse** - works natively on Windows, macOS, Linux, Android, iOS
- **BLE Battery Service** charge level visible in OS Bluetooth settings - **BLE Battery Service** - charge level visible in OS Bluetooth settings
- **Web config UI** (`web/index.html`) configure over BLE from any Chrome/Edge browser, no app install - **Web config UI** (`web/index.html`) - configure over BLE from any Chrome/Edge browser, no app install
- **Flash persistence** config survives power cycles (LittleFS) - **Flash persistence** - config survives power cycles (LittleFS)
- **Live IMU stream** 20 Hz gyro/accel data streamed to the web UI visualiser - **Live IMU stream** - 20 Hz gyro/accel data streamed to the web UI visualiser
- **Live telemetry** temperature, uptime, click counts, gyro bias RMS, recal count - **Live telemetry** - temperature, uptime, click counts, gyro bias RMS, recal count
- **Temperature compensation** gyro drift correction by Δ temperature since last calibration - **Temperature compensation** - gyro drift correction by Δ temperature since last calibration
- **Auto-recalibration** recalibrates automatically after 5 minutes of idle - **Auto-recalibration** - recalibrates automatically after 5 minutes of idle
- **Configurable charge rate** OFF / 50 mA slow / 100 mA fast via BQ25100 HICHG pin - **Configurable charge rate** - OFF / 50 mA slow / 100 mA fast via BQ25100 HICHG pin
- **Boot-loop detection** 3 rapid reboots trigger safe mode (config service disabled, flash wiped) - **Boot-loop detection** - 3 rapid reboots trigger safe mode (config service disabled, flash wiped)
## Hardware ## Hardware
@@ -26,22 +26,22 @@ A BLE HID mouse that uses the onboard IMU of a **Seeed XIAO nRF52840 Sense** to
## LED Status ## LED Status
The XIAO has three user LEDs (active LOW HIGH = off, LOW = on): The XIAO has three user LEDs (active LOW - HIGH = off, LOW = on):
| LED | Pattern | Meaning | | LED | Pattern | Meaning |
|---|---|---| |---|---|---|
| Blue | Single pulse every 10 s | BLE connected (heartbeat) | | Blue | Single pulse every 10 s | BLE connected (heartbeat) |
| Green | Single pulse every 10 s | Advertising / not connected (heartbeat) | | Green | Single pulse every 10 s | Advertising / not connected (heartbeat) |
| Green | Rapid flutter (~10 Hz) | Gyro calibration in progress | | Green | Rapid flutter (~10 Hz) | Gyro calibration in progress |
| Red | Fast blink (continuous) | IMU init failed hardware fault | | Red | Fast blink (continuous) | IMU init failed - hardware fault |
| Red | 3 slow blinks on boot | Boot-loop detected entered safe mode | | Red | 3 slow blinks on boot | Boot-loop detected - entered safe mode |
| Red | 6 rapid blinks | Battery critically low (< 3.10 V) | | Red | 6 rapid blinks | Battery critically low (< 3.10 V) |
> **Blue** = BLE-related state. **Green** = device activity. **Red** = fault only. > **Blue** = BLE-related state. **Green** = device activity. **Red** = fault only.
## Web Config UI ## Web Config UI
Open `web/index.html` in Chrome or Edge (desktop). Requires Web Bluetooth enable it at `chrome://flags/#enable-web-bluetooth` on Linux. Open `web/index.html` in Chrome or Edge (desktop). Requires Web Bluetooth - enable it at `chrome://flags/#enable-web-bluetooth` on Linux.
**Configurable parameters:** **Configurable parameters:**
@@ -56,8 +56,8 @@ Open `web/index.html` in Chrome or Edge (desktop). Requires Web Bluetooth — en
**Commands:** **Commands:**
- **Calibrate Gyro** recalculates bias offset; hold the device still on a flat surface for ~1 s - **Calibrate Gyro** - recalculates bias offset; hold the device still on a flat surface for ~1 s
- **Factory Reset** wipes flash config, restores defaults - **Factory Reset** - wipes flash config, restores defaults
## Building ## Building
+1 -1
View File
@@ -255,7 +255,7 @@ base = base.fuse(
BAT_X + BAT_L, clip_y_start, WALL) BAT_X + BAT_L, clip_y_start, WALL)
) )
# Circular notch in back wall centred on base # Circular notch in back wall - centred on base
notch_cz = rail_z + LID_H notch_cz = rail_z + LID_H
base = base.cut(circular_notch(L, W / 2, notch_cz, NOTCH_R, NOTCH_DEPTH)) base = base.cut(circular_notch(L, W / 2, notch_cz, NOTCH_R, NOTCH_DEPTH))
+7 -7
View File
@@ -1,4 +1,4 @@
; ── PlatformIO project configuration ───────────────────────────────────────── ; PlatformIO project configuration
; Board : Seeed XIAO nRF52840 Sense ; Board : Seeed XIAO nRF52840 Sense
; Core : Adafruit nRF52 Arduino (via Seeed platform-seeedboards) ; Core : Adafruit nRF52 Arduino (via Seeed platform-seeedboards)
; Flash : adafruit-nrfutil over USB serial (same as Arduino IDE) ; Flash : adafruit-nrfutil over USB serial (same as Arduino IDE)
@@ -6,7 +6,7 @@
; First-time setup: ; First-time setup:
; pip install adafruit-nrfutil <- upload tool (once, globally) ; pip install adafruit-nrfutil <- upload tool (once, globally)
; pio run -t upload <- build + flash ; pio run -t upload <- build + flash
; ────────────────────────────────────────────────────────────────────────────── ;
[platformio] [platformio]
src_dir = source src_dir = source
@@ -16,7 +16,7 @@ platform = https://github.com/Seeed-Studio/platform-seeedboards.git
board = seeed-xiao-afruitnrf52-nrf52840 board = seeed-xiao-afruitnrf52-nrf52840
framework = arduino framework = arduino
; ── Upload ──────────────────────────────────────────────────────────────────── ; Upload
; The XIAO uses a UF2 bootloader that accepts firmware via adafruit-nrfutil. ; The XIAO uses a UF2 bootloader that accepts firmware via adafruit-nrfutil.
; Double-tap the reset button to enter bootloader (red LED pulses) before ; Double-tap the reset button to enter bootloader (red LED pulses) before
; flashing if the board isn't auto-reset by the tool. ; flashing if the board isn't auto-reset by the tool.
@@ -25,21 +25,21 @@ upload_speed = 115200
; Uncomment and set the correct port if auto-detect fails: ; Uncomment and set the correct port if auto-detect fails:
; upload_port = COM3 ; upload_port = COM3
; ── Build scripts ───────────────────────────────────────────────────────────── ; Build scripts
extra_scripts = pre:scripts/git_hash.py extra_scripts = pre:scripts/git_hash.py
; ── Build flags ─────────────────────────────────────────────────────────────── ; Build flags
build_flags = build_flags =
-DARDUINO_Seeed_XIAO_nRF52840_Sense -DARDUINO_Seeed_XIAO_nRF52840_Sense
-DNRF52840_XXAA -DNRF52840_XXAA
-DTARGET_SEEED_XIAO_NRF52840_SENSE -DTARGET_SEEED_XIAO_NRF52840_SENSE
; ── Libraries ───────────────────────────────────────────────────────────────── ; Libraries
; bluefruit.h, Adafruit_LittleFS.h, InternalFileSystem.h are bundled with ; bluefruit.h, Adafruit_LittleFS.h, InternalFileSystem.h are bundled with
; the Adafruit nRF52 core and do NOT need to be listed here. ; the Adafruit nRF52 core and do NOT need to be listed here.
; Only external libraries are listed: ; Only external libraries are listed:
lib_deps = lib_deps =
Seeed-Studio/Seeed Arduino LSM6DS3 @ ^2.0.3 Seeed-Studio/Seeed Arduino LSM6DS3 @ ^2.0.3
; ── Serial monitor ──────────────────────────────────────────────────────────── ; Serial monitor
monitor_speed = 115200 monitor_speed = 115200
+4 -4
View File
@@ -8,7 +8,7 @@ Usage: referenced from platformio.ini as:
""" """
import subprocess, os, re import subprocess, os, re
Import("env") # noqa: F821 PlatformIO injects this Import("env") # noqa: F821 - PlatformIO injects this
def get_git_hash(): def get_git_hash():
try: try:
@@ -27,14 +27,14 @@ def get_git_hash():
git_hash = get_git_hash() git_hash = get_git_hash()
print(f"[git_hash] short hash = {git_hash}") print(f"[git_hash] short hash = {git_hash}")
# ── Inject into firmware build ──────────────────────────────────────────────── # Inject into firmware build
env.Append(CPPDEFINES=[("GIT_HASH", f'\\"{git_hash}\\"')]) # noqa: F821 env.Append(CPPDEFINES=[("GIT_HASH", f'\\"{git_hash}\\"')]) # noqa: F821
# ── Write web/version.js ────────────────────────────────────────────────────── # Write web/version.js
web_dir = os.path.join(env.subst("$PROJECT_DIR"), "web") # noqa: F821 web_dir = os.path.join(env.subst("$PROJECT_DIR"), "web") # noqa: F821
ver_file = os.path.join(web_dir, "version.js") ver_file = os.path.join(web_dir, "version.js")
os.makedirs(web_dir, exist_ok=True) os.makedirs(web_dir, exist_ok=True)
with open(ver_file, "w") as f: with open(ver_file, "w") as f:
f.write(f"// Auto-generated by scripts/git_hash.py do not edit\n") f.write(f"// Auto-generated by scripts/git_hash.py - do not edit\n")
f.write(f"const FIRMWARE_BUILD_HASH = '{git_hash}';\n") f.write(f"const FIRMWARE_BUILD_HASH = '{git_hash}';\n")
print(f"[git_hash] wrote {ver_file}") print(f"[git_hash] wrote {ver_file}")
+3 -3
View File
@@ -13,7 +13,7 @@ void initBatteryADC() {
pinMode(PIN_VBAT_ENABLE, OUTPUT); digitalWrite(PIN_VBAT_ENABLE, LOW); pinMode(PIN_VBAT_ENABLE, OUTPUT); digitalWrite(PIN_VBAT_ENABLE, LOW);
pinMode(PIN_VBAT_READ, INPUT); pinMode(PIN_VBAT_READ, INPUT);
analogReference(AR_INTERNAL_3_0); analogReadResolution(12); analogReference(AR_INTERNAL_3_0); analogReadResolution(12);
// Warm up with a few reads (no delay just discard results) // Warm up with a few reads (no delay - just discard results)
for (int i=0; i<8; i++) analogRead(PIN_VBAT_READ); for (int i=0; i<8; i++) analogRead(PIN_VBAT_READ);
} }
@@ -34,7 +34,7 @@ void updateBattery() {
float v = readBatteryVoltage(); int pct = batteryPercent(v); float v = readBatteryVoltage(); int pct = batteryPercent(v);
bool chg = (digitalRead(PIN_CHG) == LOW); bool chg = (digitalRead(PIN_CHG) == LOW);
ChargeStatus status = chg ? (pct >= 99 ? CHGSTAT_FULL : CHGSTAT_CHARGING) : CHGSTAT_DISCHARGING; ChargeStatus status = chg ? (pct >= 99 ? CHGSTAT_FULL : CHGSTAT_CHARGING) : CHGSTAT_DISCHARGING;
// Only write BLE Battery Service when connected blebas.write() blocks on the // Only write BLE Battery Service when connected - blebas.write() blocks on the
// SoftDevice ATT layer and causes 30-40ms loop stalls when called during advertising. // SoftDevice ATT layer and causes 30-40ms loop stalls when called during advertising.
if (Bluefruit.connected()) blebas.write(pct); if (Bluefruit.connected()) blebas.write(pct);
lastChargeStatus = status; lastChargeStatus = status;
@@ -44,7 +44,7 @@ void updateBattery() {
const char* st[] = {"discharging","charging","full"}; const char* st[] = {"discharging","charging","full"};
Serial.print("[BATT] "); Serial.print(v,2); Serial.print("V "); Serial.print("[BATT] "); Serial.print(v,2); Serial.print("V ");
Serial.print(pct); Serial.print("% "); Serial.println(st[status]); Serial.print(pct); Serial.print("% "); Serial.println(st[status]);
// Critical battery alert only blink when not connected to avoid blocking BLE scheduler. // Critical battery alert - only blink when not connected to avoid blocking BLE scheduler.
// 6 × 160ms = 960ms hard block; skip during active connection. // 6 × 160ms = 960ms hard block; skip during active connection.
if (status == CHGSTAT_DISCHARGING && v < BATT_CRITICAL && !Bluefruit.connected()) if (status == CHGSTAT_DISCHARGING && v < BATT_CRITICAL && !Bluefruit.connected())
for (int i=0; i<6; i++) { digitalWrite(LED_RED,LOW); delay(80); digitalWrite(LED_RED,HIGH); delay(80); } for (int i=0; i<6; i++) { digitalWrite(LED_RED,LOW); delay(80); digitalWrite(LED_RED,HIGH); delay(80); }
+10 -10
View File
@@ -8,7 +8,7 @@
using namespace Adafruit_LittleFS_Namespace; using namespace Adafruit_LittleFS_Namespace;
extern File cfgFile; extern File cfgFile;
// ─── BLE Config Service objects ─────────────────────────────────────────────── // BLE Config Service objects
#ifndef GIT_HASH #ifndef GIT_HASH
#define GIT_HASH "unknown" #define GIT_HASH "unknown"
#endif #endif
@@ -26,7 +26,7 @@ BLECharacteristic cfgGitHash (0x1239); // GitHash R 8 bytes (7-char ha
#endif #endif
#endif #endif
// ─── Charge mode ────────────────────────────────────────────────────────────── // Charge mode
void applyChargeMode(ChargeMode mode) { void applyChargeMode(ChargeMode mode) {
switch (mode) { switch (mode) {
case CHARGE_OFF: pinMode(PIN_HICHG, INPUT_PULLUP); break; case CHARGE_OFF: pinMode(PIN_HICHG, INPUT_PULLUP); break;
@@ -37,7 +37,7 @@ void applyChargeMode(ChargeMode mode) {
Serial.print("[CHG] "); Serial.println(n[mode]); Serial.print("[CHG] "); Serial.println(n[mode]);
} }
// ─── Config persistence ─────────────────────────────────────────────────────── // Config persistence
void loadConfig() { void loadConfig() {
InternalFS.begin(); InternalFS.begin();
cfgFile.open(CONFIG_FILENAME, FILE_O_READ); cfgFile.open(CONFIG_FILENAME, FILE_O_READ);
@@ -57,11 +57,11 @@ void saveConfig() {
cfgFile.open(CONFIG_FILENAME, FILE_O_WRITE); cfgFile.open(CONFIG_FILENAME, FILE_O_WRITE);
if (cfgFile) { cfgFile.write((uint8_t*)&cfg, sizeof(cfg)); cfgFile.close(); } if (cfgFile) { cfgFile.write((uint8_t*)&cfg, sizeof(cfg)); cfgFile.close(); }
unsigned long elapsed = millis() - t0; unsigned long elapsed = millis() - t0;
if (elapsed > 5) { Serial.print("[CFG] Saved ("); Serial.print(elapsed); Serial.println("ms flash block)"); } if (elapsed > 5) { Serial.print("[CFG] Saved ("); Serial.print(elapsed); Serial.println("ms - flash block)"); }
else { Serial.println("[CFG] Saved"); } else { Serial.println("[CFG] Saved"); }
} }
// ─── ConfigBlob push ───────────────────────────────────────────────────────── // ConfigBlob push
#ifdef FEATURE_CONFIG_SERVICE #ifdef FEATURE_CONFIG_SERVICE
void pushConfigBlob() { void pushConfigBlob() {
ConfigBlob b; ConfigBlob b;
@@ -103,7 +103,7 @@ void factoryReset() {
Serial.println("[CFG] Factory reset complete"); Serial.println("[CFG] Factory reset complete");
} }
// ─── BLE callbacks ──────────────────────────────────────────────────────────── // BLE callbacks
#ifdef FEATURE_CONFIG_SERVICE #ifdef FEATURE_CONFIG_SERVICE
void onConfigBlobWrite(uint16_t h, BLECharacteristic* c, uint8_t* d, uint16_t l) { void onConfigBlobWrite(uint16_t h, BLECharacteristic* c, uint8_t* d, uint16_t l) {
if (l != sizeof(ConfigBlob)) { Serial.println("[CFG] Bad blob length"); return; } if (l != sizeof(ConfigBlob)) { Serial.println("[CFG] Bad blob length"); return; }
@@ -134,7 +134,7 @@ void onConfigBlobWrite(uint16_t h, BLECharacteristic* c, uint8_t* d, uint16_t l)
setupPhysicalButtons(); // reconfigure pins immediately (no restart needed) setupPhysicalButtons(); // reconfigure pins immediately (no restart needed)
#endif #endif
saveConfig(); saveConfig();
Serial.print("[CFG] Written sens="); Serial.print(cfg.sensitivity,0); Serial.print("[CFG] Written - sens="); Serial.print(cfg.sensitivity,0);
Serial.print(" dz="); Serial.print(cfg.deadZone,3); Serial.print(" dz="); Serial.print(cfg.deadZone,3);
Serial.print(" tapThr="); Serial.print(cfg.tapThreshold); Serial.print(" tapThr="); Serial.print(cfg.tapThreshold);
Serial.print(" tapAction="); Serial.println(cfg.tapAction); Serial.print(" tapAction="); Serial.println(cfg.tapAction);
@@ -153,7 +153,7 @@ void onImuStreamCccd(uint16_t conn_hdl, BLECharacteristic* chr, uint16_t value)
} }
#endif #endif
// ─── BLE config service setup ───────────────────────────────────────────────── // BLE config service setup
void setupConfigService() { void setupConfigService() {
cfgService.begin(); cfgService.begin();
@@ -170,7 +170,7 @@ void setupConfigService() {
cfgCommand.setWriteCallback(onCommandWrite); cfgCommand.setWriteCallback(onCommandWrite);
cfgCommand.begin(); cfgCommand.begin();
// Git hash 8-byte fixed field (7 hex chars + NUL), read-only // Git hash - 8-byte fixed field (7 hex chars + NUL), read-only
cfgGitHash.setProperties(CHR_PROPS_READ); cfgGitHash.setProperties(CHR_PROPS_READ);
cfgGitHash.setPermission(SECMODE_OPEN, SECMODE_NO_ACCESS); cfgGitHash.setPermission(SECMODE_OPEN, SECMODE_NO_ACCESS);
cfgGitHash.setFixedLen(8); cfgGitHash.setFixedLen(8);
@@ -206,7 +206,7 @@ void setupConfigService() {
} }
#endif // FEATURE_CONFIG_SERVICE #endif // FEATURE_CONFIG_SERVICE
// ─── Telemetry push ─────────────────────────────────────────────────────────── // Telemetry push
#ifdef FEATURE_TELEMETRY #ifdef FEATURE_TELEMETRY
void pushTelemetry(unsigned long now) { void pushTelemetry(unsigned long now) {
telem.uptimeSeconds = now / 1000; telem.uptimeSeconds = now / 1000;
+2 -2
View File
@@ -7,7 +7,7 @@ extern BLEHidAdafruit blehid;
static uint8_t physBtnMask = 0; // bitmask of currently-pressed physical buttons static uint8_t physBtnMask = 0; // bitmask of currently-pressed physical buttons
// ─── Setup ──────────────────────────────────────────────────────────────────── // Setup
void setupPhysicalButtons() { void setupPhysicalButtons() {
// Release any held physical buttons before reconfiguring // Release any held physical buttons before reconfiguring
if (physBtnMask && Bluefruit.connected()) { blehid.mouseButtonRelease(); } if (physBtnMask && Bluefruit.connected()) { blehid.mouseButtonRelease(); }
@@ -30,7 +30,7 @@ void setupPhysicalButtons() {
} }
} }
// ─── Poll and report ────────────────────────────────────────────────────────── // Poll and report
// Called every loop iteration (before rate limiter) for immediate response. // Called every loop iteration (before rate limiter) for immediate response.
// Uses active-low logic: INPUT_PULLUP, button connects pin to GND. // Uses active-low logic: INPUT_PULLUP, button connects pin to GND.
void processPhysicalButtons() { void processPhysicalButtons() {
+18 -18
View File
@@ -1,7 +1,7 @@
#pragma once #pragma once
#include <Arduino.h> #include <Arduino.h>
// ─── Feature Flags ──────────────────────────────────────────────────────────── // Feature Flags
#define FEATURE_CONFIG_SERVICE #define FEATURE_CONFIG_SERVICE
#define FEATURE_TELEMETRY #define FEATURE_TELEMETRY
#define FEATURE_IMU_STREAM #define FEATURE_IMU_STREAM
@@ -12,10 +12,10 @@
#define FEATURE_BOOT_LOOP_DETECT #define FEATURE_BOOT_LOOP_DETECT
#define FEATURE_PHYSICAL_BUTTONS #define FEATURE_PHYSICAL_BUTTONS
// ─── Debug ──────────────────────────────────────────────────────────────────── // Debug
// #define DEBUG // #define DEBUG
// ─── ATT table size ─────────────────────────────────────────────────────────── // ATT table size
#define _ATT_BASE 900 #define _ATT_BASE 900
#ifdef FEATURE_CONFIG_SERVICE #ifdef FEATURE_CONFIG_SERVICE
#define _ATT_CFG 100 // +20 for cfgGitHash characteristic #define _ATT_CFG 100 // +20 for cfgGitHash characteristic
@@ -35,7 +35,7 @@
#define ATT_TABLE_SIZE_CALC (_ATT_BASE + _ATT_CFG + _ATT_TELEM + _ATT_STREAM) #define ATT_TABLE_SIZE_CALC (_ATT_BASE + _ATT_CFG + _ATT_TELEM + _ATT_STREAM)
#define ATT_TABLE_SIZE (ATT_TABLE_SIZE_CALC < 1536 ? 1536 : ATT_TABLE_SIZE_CALC) #define ATT_TABLE_SIZE (ATT_TABLE_SIZE_CALC < 1536 ? 1536 : ATT_TABLE_SIZE_CALC)
// ─── IMU register addresses ─────────────────────────────────────────────────── // IMU register addresses
#define REG_CTRL1_XL 0x10 #define REG_CTRL1_XL 0x10
#define REG_TAP_CFG 0x58 #define REG_TAP_CFG 0x58
#define REG_TAP_THS_6D 0x59 #define REG_TAP_THS_6D 0x59
@@ -46,20 +46,20 @@
#define REG_OUT_TEMP_L 0x20 #define REG_OUT_TEMP_L 0x20
#define REG_OUT_TEMP_H 0x21 #define REG_OUT_TEMP_H 0x21
// ─── Pins ───────────────────────────────────────────────────────────────────── // Pins
#define PIN_VBAT_ENABLE (14) #define PIN_VBAT_ENABLE (14)
#define PIN_VBAT_READ (32) #define PIN_VBAT_READ (32)
#define PIN_CHG (23) #define PIN_CHG (23)
#define PIN_HICHG (22) #define PIN_HICHG (22)
// ─── Persistence ────────────────────────────────────────────────────────────── // Persistence
#define CONFIG_FILENAME "/imu_mouse_cfg.bin" #define CONFIG_FILENAME "/imu_mouse_cfg.bin"
#define CONFIG_MAGIC 0xDEAD123DUL #define CONFIG_MAGIC 0xDEAD123DUL
// ─── Physical button sentinel ───────────────────────────────────────────────── // Physical button sentinel
#define BTN_PIN_NONE 0xFF // Stored in btn*Pin when that button is disabled #define BTN_PIN_NONE 0xFF // Stored in btn*Pin when that button is disabled
// ─── Runtime feature-override flags (cfg.featureFlags bitmask) ─────────────── // Runtime feature-override flags (cfg.featureFlags bitmask)
// These mirror the compile-time FEATURE_* defines but can be toggled at runtime // These mirror the compile-time FEATURE_* defines but can be toggled at runtime
// via the web UI and persisted in flash. Bits not listed here are reserved = 0. // via the web UI and persisted in flash. Bits not listed here are reserved = 0.
#define FLAG_TAP_ENABLED 0x01 // Tap detection active (requires restart) #define FLAG_TAP_ENABLED 0x01 // Tap detection active (requires restart)
@@ -67,12 +67,12 @@
#define FLAG_AUTO_RECAL_ENABLED 0x04 // Auto-recalibrate after long idle #define FLAG_AUTO_RECAL_ENABLED 0x04 // Auto-recalibrate after long idle
#define FLAG_ALL_DEFAULT (FLAG_TAP_ENABLED | FLAG_TEMP_COMP_ENABLED | FLAG_AUTO_RECAL_ENABLED) #define FLAG_ALL_DEFAULT (FLAG_TAP_ENABLED | FLAG_TEMP_COMP_ENABLED | FLAG_AUTO_RECAL_ENABLED)
// ─── Enums ──────────────────────────────────────────────────────────────────── // Enums
enum CurveType : uint8_t { CURVE_LINEAR=0, CURVE_SQUARE=1, CURVE_SQRT=2 }; enum CurveType : uint8_t { CURVE_LINEAR=0, CURVE_SQUARE=1, CURVE_SQRT=2 };
enum ChargeMode : uint8_t { CHARGE_OFF=0, CHARGE_SLOW=1, CHARGE_FAST=2 }; enum ChargeMode : uint8_t { CHARGE_OFF=0, CHARGE_SLOW=1, CHARGE_FAST=2 };
enum ChargeStatus: uint8_t { CHGSTAT_DISCHARGING=0, CHGSTAT_CHARGING=1, CHGSTAT_FULL=2 }; enum ChargeStatus: uint8_t { CHGSTAT_DISCHARGING=0, CHGSTAT_CHARGING=1, CHGSTAT_FULL=2 };
// ─── Tap action types ───────────────────────────────────────────────────────── // Tap action types
// TAP_ACTION_KEY: fires a raw HID keycode (tapKey) with optional modifier (tapMod). // TAP_ACTION_KEY: fires a raw HID keycode (tapKey) with optional modifier (tapMod).
// Modifier byte: bit0=Ctrl, bit1=Shift, bit2=Alt, bit3=GUI (same as HID modifier byte). // Modifier byte: bit0=Ctrl, bit1=Shift, bit2=Alt, bit3=GUI (same as HID modifier byte).
enum TapAction : uint8_t { enum TapAction : uint8_t {
@@ -82,7 +82,7 @@ enum TapAction : uint8_t {
TAP_ACTION_KEY = 3, TAP_ACTION_KEY = 3,
}; };
// ─── Config (stored in flash) ───────────────────────────────────────────────── // Config (stored in flash)
struct Config { struct Config {
uint32_t magic; uint32_t magic;
float sensitivity; float sensitivity;
@@ -97,7 +97,7 @@ struct Config {
uint8_t tapMod; // HID modifier byte (used when tapAction == TAP_ACTION_KEY) uint8_t tapMod; // HID modifier byte (used when tapAction == TAP_ACTION_KEY)
float jerkThreshold; // jerk² threshold for tap-freeze detection float jerkThreshold; // jerk² threshold for tap-freeze detection
uint8_t tapFreezeEnabled; // 1 = enable jerk-based cursor freeze during taps uint8_t tapFreezeEnabled; // 1 = enable jerk-based cursor freeze during taps
uint8_t featureFlags; // bitmask of FLAG_* runtime feature overrides uint8_t featureFlags; // bitmask of FLAG_* - runtime feature overrides
uint8_t btnLeftPin; // BTN_PIN_NONE or Arduino pin number (0-10 = D0-D10) uint8_t btnLeftPin; // BTN_PIN_NONE or Arduino pin number (0-10 = D0-D10)
uint8_t btnRightPin; uint8_t btnRightPin;
uint8_t btnMiddlePin; uint8_t btnMiddlePin;
@@ -105,7 +105,7 @@ struct Config {
extern Config cfg; extern Config cfg;
extern const Config CFG_DEFAULTS; extern const Config CFG_DEFAULTS;
// ─── ConfigBlob (over BLE, 25 bytes) ───────────────────────────────────────── // ConfigBlob (over BLE, 25 bytes)
struct __attribute__((packed)) ConfigBlob { struct __attribute__((packed)) ConfigBlob {
float sensitivity; // [0] float sensitivity; // [0]
float deadZone; // [4] float deadZone; // [4]
@@ -119,14 +119,14 @@ struct __attribute__((packed)) ConfigBlob {
uint8_t tapMod; // [18] HID modifier uint8_t tapMod; // [18] HID modifier
uint8_t tapFreezeEnabled; // [19] 1 = enable jerk-based cursor freeze during taps uint8_t tapFreezeEnabled; // [19] 1 = enable jerk-based cursor freeze during taps
float jerkThreshold; // [20] jerk² tap-freeze threshold float jerkThreshold; // [20] jerk² tap-freeze threshold
uint8_t featureFlags; // [24] FLAG_* bitmask runtime feature overrides uint8_t featureFlags; // [24] FLAG_* bitmask - runtime feature overrides
uint8_t btnLeftPin; // [25] BTN_PIN_NONE or Arduino pin (0-10 = D0-D10) uint8_t btnLeftPin; // [25] BTN_PIN_NONE or Arduino pin (0-10 = D0-D10)
uint8_t btnRightPin; // [26] uint8_t btnRightPin; // [26]
uint8_t btnMiddlePin; // [27] uint8_t btnMiddlePin; // [27]
}; };
static_assert(sizeof(ConfigBlob) == 28, "ConfigBlob must be 28 bytes"); static_assert(sizeof(ConfigBlob) == 28, "ConfigBlob must be 28 bytes");
// ─── TelemetryPacket (24 bytes) ─────────────────────────────────────────────── // TelemetryPacket (24 bytes)
#ifdef FEATURE_TELEMETRY #ifdef FEATURE_TELEMETRY
struct __attribute__((packed)) TelemetryPacket { struct __attribute__((packed)) TelemetryPacket {
uint32_t uptimeSeconds; // [0] uint32_t uptimeSeconds; // [0]
@@ -143,7 +143,7 @@ static_assert(sizeof(TelemetryPacket) == 28, "TelemetryPacket must be 28 bytes")
extern TelemetryPacket telem; extern TelemetryPacket telem;
#endif #endif
// ─── ImuPacket (14 bytes) ───────────────────────────────────────────────────── // ImuPacket (14 bytes)
#ifdef FEATURE_IMU_STREAM #ifdef FEATURE_IMU_STREAM
struct __attribute__((packed)) ImuPacket { struct __attribute__((packed)) ImuPacket {
int16_t gyroX_mDPS; // [0] pitch axis (nod up/down → cursor Y) int16_t gyroX_mDPS; // [0] pitch axis (nod up/down → cursor Y)
@@ -159,7 +159,7 @@ struct __attribute__((packed)) ImuPacket {
static_assert(sizeof(ImuPacket) == 14, "ImuPacket must be 14 bytes"); static_assert(sizeof(ImuPacket) == 14, "ImuPacket must be 14 bytes");
#endif #endif
// ─── Tuning constants ───────────────────────────────────────────────────────── // Tuning constants
extern const float ALPHA; extern const float ALPHA;
extern const int LOOP_RATE_MS; extern const int LOOP_RATE_MS;
extern const int BIAS_SAMPLES; extern const int BIAS_SAMPLES;
@@ -185,7 +185,7 @@ extern const float BATT_CRITICAL;
extern const unsigned long AUTO_RECAL_MS; extern const unsigned long AUTO_RECAL_MS;
#endif #endif
// ─── Global state ───────────────────────────────────────────────────────────── // Global state
extern float angleX, angleY; extern float angleX, angleY;
extern float accumX, accumY; extern float accumX, accumY;
extern float gravX, gravY, gravZ; extern float gravX, gravY, gravZ;
+4 -4
View File
@@ -4,7 +4,7 @@
LSM6DS3 imu(I2C_MODE, 0x6A); LSM6DS3 imu(I2C_MODE, 0x6A);
// ─── I2C helpers ────────────────────────────────────────────────────────────── // I2C helpers
void imuWriteReg(uint8_t reg, uint8_t val) { void imuWriteReg(uint8_t reg, uint8_t val) {
// LSM6DS3 is on Wire1 (internal I2C, SDA=P0.17, SCL=P0.16), NOT Wire (external pins 4/5) // LSM6DS3 is on Wire1 (internal I2C, SDA=P0.17, SCL=P0.16), NOT Wire (external pins 4/5)
Wire1.beginTransmission(0x6A); Wire1.write(reg); Wire1.write(val); Wire1.endTransmission(); Wire1.beginTransmission(0x6A); Wire1.write(reg); Wire1.write(val); Wire1.endTransmission();
@@ -16,13 +16,13 @@ uint8_t imuReadReg(uint8_t reg) {
return Wire1.available() ? Wire1.read() : 0; return Wire1.available() ? Wire1.read() : 0;
} }
// ─── Temperature ────────────────────────────────────────────────────────────── // Temperature
float readIMUTemp() { float readIMUTemp() {
int16_t raw = (int16_t)((imuReadReg(REG_OUT_TEMP_H) << 8) | imuReadReg(REG_OUT_TEMP_L)); int16_t raw = (int16_t)((imuReadReg(REG_OUT_TEMP_H) << 8) | imuReadReg(REG_OUT_TEMP_L));
return 25.0f + (float)raw / 256.0f; return 25.0f + (float)raw / 256.0f;
} }
// ─── Calibration ────────────────────────────────────────────────────────────── // Calibration
void calibrateGyroBias() { void calibrateGyroBias() {
Serial.println("[CAL] Hold still..."); Serial.println("[CAL] Hold still...");
double sx=0, sy=0, sz=0; double sx=0, sy=0, sz=0;
@@ -51,7 +51,7 @@ void calibrateGyroBias() {
Serial.print(","); Serial.println(biasGZ,4); Serial.print(","); Serial.println(biasGZ,4);
} }
// ─── Motion curve ───────────────────────────────────────────────────────────── // Motion curve
float applyCurve(float v) { float applyCurve(float v) {
switch (cfg.curve) { switch (cfg.curve) {
case CURVE_SQUARE: return (v >= 0 ? 1.f : -1.f) * v * v; case CURVE_SQUARE: return (v >= 0 ? 1.f : -1.f) * v * v;
+35 -56
View File
@@ -1,27 +1,12 @@
/* /*
* IMU BLE Mouse Seeed XIAO nRF52840 Sense (v3.4) * IMU BLE Mouse - Seeed XIAO nRF52840 Sense (v3.4)
* ================================================================ * ================================================================
* Feature flags — comment out any line to disable that feature.
* ATT table size is computed automatically from enabled features.
* Start with minimal flags to isolate the SoftDevice RAM issue,
* then re-enable one at a time.
*
* MINIMUM (just working mouse, no BLE config): * MINIMUM (just working mouse, no BLE config):
* leave only FEATURE_BATTERY_MONITOR + FEATURE_BOOT_LOOP_DETECT * leave only FEATURE_BATTERY_MONITOR + FEATURE_BOOT_LOOP_DETECT
* *
* RECOMMENDED first test: * RECOMMENDED first test:
* enable FEATURE_CONFIG_SERVICE, keep TAP + STREAM + TELEMETRY off * enable FEATURE_CONFIG_SERVICE, keep TAP + STREAM + TELEMETRY off
* *
* ── Feature flag index ───────────────────────────────────────────
* FEATURE_CONFIG_SERVICE Custom GATT service (ConfigBlob + Command)
* FEATURE_TELEMETRY +24-byte notify characteristic, 1 Hz
* FEATURE_IMU_STREAM +14-byte notify characteristic, ~10 Hz
* FEATURE_TAP_DETECTION LSM6DS3 hardware tap engine → L/R clicks
* FEATURE_TEMP_COMPENSATION Gyro drift correction by temperature delta
* FEATURE_AUTO_RECAL Recalibrate after AUTO_RECAL_MS idle
* FEATURE_BATTERY_MONITOR ADC battery read + BLE Battery Service
* FEATURE_BOOT_LOOP_DETECT .noinit crash counter → safe mode
*
* Dependencies: * Dependencies:
* FEATURE_TELEMETRY requires FEATURE_CONFIG_SERVICE * FEATURE_TELEMETRY requires FEATURE_CONFIG_SERVICE
* FEATURE_IMU_STREAM requires FEATURE_CONFIG_SERVICE * FEATURE_IMU_STREAM requires FEATURE_CONFIG_SERVICE
@@ -38,25 +23,26 @@
#include <Adafruit_LittleFS.h> #include <Adafruit_LittleFS.h>
#include <InternalFileSystem.h> #include <InternalFileSystem.h>
#include "Wire.h" #include "Wire.h"
#include "sleep.h"
// ─── Boot-loop detection ────────────────────────────────────────────────────── // Boot-loop detection
#ifdef FEATURE_BOOT_LOOP_DETECT #ifdef FEATURE_BOOT_LOOP_DETECT
static uint32_t __attribute__((section(".noinit"))) bootCount; static uint32_t __attribute__((section(".noinit"))) bootCount;
static uint32_t __attribute__((section(".noinit"))) bootMagic; static uint32_t __attribute__((section(".noinit"))) bootMagic;
#endif #endif
// ─── BLE Standard Services ──────────────────────────────────────────────────── // BLE Standard Services
BLEDis bledis; BLEDis bledis;
BLEHidAdafruit blehid; BLEHidAdafruit blehid;
#ifdef FEATURE_BATTERY_MONITOR #ifdef FEATURE_BATTERY_MONITOR
BLEBas blebas; BLEBas blebas;
#endif #endif
// ─── Persistence ────────────────────────────────────────────────────────────── // Persistence
using namespace Adafruit_LittleFS_Namespace; using namespace Adafruit_LittleFS_Namespace;
File cfgFile(InternalFS); File cfgFile(InternalFS);
// ─── Config definitions ─────────────────────────────────────────────────────── // Config definitions
Config cfg; Config cfg;
const Config CFG_DEFAULTS = { const Config CFG_DEFAULTS = {
CONFIG_MAGIC, 600.0f, 0.060f, 0.08f, CURVE_LINEAR, 0x00, CHARGE_SLOW, CONFIG_MAGIC, 600.0f, 0.060f, 0.08f, CURVE_LINEAR, 0x00, CHARGE_SLOW,
@@ -65,12 +51,12 @@ const Config CFG_DEFAULTS = {
/*btnLeftPin=*/BTN_PIN_NONE, /*btnRightPin=*/BTN_PIN_NONE, /*btnMiddlePin=*/BTN_PIN_NONE /*btnLeftPin=*/BTN_PIN_NONE, /*btnRightPin=*/BTN_PIN_NONE, /*btnMiddlePin=*/BTN_PIN_NONE
}; };
// ─── Telemetry definition ───────────────────────────────────────────────────── // Telemetry definition
#ifdef FEATURE_TELEMETRY #ifdef FEATURE_TELEMETRY
TelemetryPacket telem = {}; TelemetryPacket telem = {};
#endif #endif
// ─── Tuning constants ───────────────────────────────────────────────────────── // Tuning constants
const float ALPHA = 0.96f; const float ALPHA = 0.96f;
const int LOOP_RATE_MS = 10; const int LOOP_RATE_MS = 10;
const int BIAS_SAMPLES = 200; const int BIAS_SAMPLES = 200;
@@ -96,7 +82,7 @@ const float BATT_CRITICAL = 3.10f;
const unsigned long AUTO_RECAL_MS = 5UL * 60UL * 1000UL; const unsigned long AUTO_RECAL_MS = 5UL * 60UL * 1000UL;
#endif #endif
// ─── Global state definitions ───────────────────────────────────────────────── // Global state definitions
float angleX = 0, angleY = 0; float angleX = 0, angleY = 0;
float accumX = 0, accumY = 0; float accumX = 0, accumY = 0;
// Low-pass filtered gravity estimate in device frame (for roll-independent axis projection) // Low-pass filtered gravity estimate in device frame (for roll-independent axis projection)
@@ -131,10 +117,7 @@ uint32_t loopStalls = 0; // loop iterations where dt > 20ms (behind sch
bool pendingCal = false; bool pendingCal = false;
bool pendingReset = false; bool pendingReset = false;
// ── Jerk-based shock detection freeze cursor during tap impacts ──────────── // Jerk-based shock detection - freeze cursor during tap impacts, doesn't work well yet!
// Jerk = da/dt (rate of change of acceleration). Normal mouse rotation produces
// smooth accel changes (low jerk); a tap is a sharp impulse (very high jerk).
// This cleanly separates taps from any intentional motion regardless of speed.
unsigned long shockFreezeUntil = 0; unsigned long shockFreezeUntil = 0;
float prevAx = 0, prevAy = 0, prevAz = 0; // previous frame's accel for Δa float prevAx = 0, prevAy = 0, prevAz = 0; // previous frame's accel for Δa
const unsigned long SHOCK_FREEZE_MS = 80; // hold freeze after last spike const unsigned long SHOCK_FREEZE_MS = 80; // hold freeze after last spike
@@ -160,7 +143,7 @@ unsigned long bootStartMs = 0;
bool safeMode = false; bool safeMode = false;
bool bootCountCleared = false; bool bootCountCleared = false;
// ─── Advertising ───────────────────────────────────────────────────────────── // Advertising
static void startAdvertising() { static void startAdvertising() {
Bluefruit.Advertising.addFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE); Bluefruit.Advertising.addFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE);
Bluefruit.Advertising.addTxPower(); Bluefruit.Advertising.addTxPower();
@@ -176,7 +159,7 @@ static void startAdvertising() {
Bluefruit.Advertising.start(0); Bluefruit.Advertising.start(0);
} }
// ─── Setup ──────────────────────────────────────────────────────────────────── // Setup
void setup() { void setup() {
Serial.begin(115200); Serial.begin(115200);
unsigned long serialWait = millis(); unsigned long serialWait = millis();
@@ -187,14 +170,14 @@ void setup() {
pinMode(LED_GREEN, OUTPUT); digitalWrite(LED_GREEN, HIGH); pinMode(LED_GREEN, OUTPUT); digitalWrite(LED_GREEN, HIGH);
pinMode(LED_BLUE, OUTPUT); digitalWrite(LED_BLUE, HIGH); pinMode(LED_BLUE, OUTPUT); digitalWrite(LED_BLUE, HIGH);
// ── Boot-loop detection ─────────────────────────────────────────────────── // Boot-loop detection
#ifdef FEATURE_BOOT_LOOP_DETECT #ifdef FEATURE_BOOT_LOOP_DETECT
if (bootMagic != 0xCAFEBABE) { bootMagic = 0xCAFEBABE; bootCount = 0; } if (bootMagic != 0xCAFEBABE) { bootMagic = 0xCAFEBABE; bootCount = 0; }
bootCount++; bootCount++;
Serial.print("[BOOT] count="); Serial.println(bootCount); Serial.print("[BOOT] count="); Serial.println(bootCount);
if (bootCount >= 3) { if (bootCount >= 3) {
bootCount = 0; safeMode = true; bootCount = 0; safeMode = true;
Serial.println("[BOOT] Boot loop safe mode (no config service)"); Serial.println("[BOOT] Boot loop - safe mode (no config service)");
InternalFS.begin(); InternalFS.remove(CONFIG_FILENAME); InternalFS.begin(); InternalFS.remove(CONFIG_FILENAME);
for (int i=0; i<3; i++) { digitalWrite(LED_RED,LOW); delay(150); digitalWrite(LED_RED,HIGH); delay(150); } // fault: red for (int i=0; i<3; i++) { digitalWrite(LED_RED,LOW); delay(150); digitalWrite(LED_RED,HIGH); delay(150); } // fault: red
} }
@@ -213,7 +196,7 @@ void setup() {
Bluefruit.begin(1, 0); Bluefruit.begin(1, 0);
Bluefruit.setTxPower(4); Bluefruit.setTxPower(4);
Bluefruit.setName(safeMode ? "IMU Mouse (safe)" : "IMU Mouse"); Bluefruit.setName(safeMode ? "IMU Mouse (safe)" : "IMU Mouse");
Bluefruit.Periph.setConnInterval(16, 32); // 20-40ms wider interval reduces SoftDevice TX stalls Bluefruit.Periph.setConnInterval(16, 32); // 20-40ms - wider interval reduces SoftDevice TX stalls
Wire1.begin(); // LSM6DS3 is on internal I2C bus (Wire1), must init before imu.begin() Wire1.begin(); // LSM6DS3 is on internal I2C bus (Wire1), must init before imu.begin()
if (imu.begin() != 0) { if (imu.begin() != 0) {
@@ -241,6 +224,8 @@ void setup() {
// Seed previous-accel for jerk detection so first frame doesn't spike // Seed previous-accel for jerk detection so first frame doesn't spike
prevAx = imu.readFloatAccelX(); prevAy = imu.readFloatAccelY(); prevAz = imu.readFloatAccelZ(); prevAx = imu.readFloatAccelX(); prevAy = imu.readFloatAccelY(); prevAz = imu.readFloatAccelZ();
sleepManagerInit();
bledis.setManufacturer("Seeed Studio"); bledis.setManufacturer("Seeed Studio");
bledis.setModel("XIAO nRF52840 Sense"); bledis.setModel("XIAO nRF52840 Sense");
bledis.begin(); bledis.begin();
@@ -261,7 +246,7 @@ void setup() {
#endif #endif
startAdvertising(); startAdvertising();
Serial.print("[OK] Advertising features:"); Serial.print("[OK] Advertising - features:");
#ifdef FEATURE_CONFIG_SERVICE #ifdef FEATURE_CONFIG_SERVICE
Serial.print(" CFG"); Serial.print(" CFG");
#endif #endif
@@ -289,13 +274,14 @@ void setup() {
#ifdef FEATURE_PHYSICAL_BUTTONS #ifdef FEATURE_PHYSICAL_BUTTONS
Serial.print(" PHYSBTN"); Serial.print(" PHYSBTN");
#endif #endif
Serial.print(" SLEEP");
Serial.println(); Serial.println();
bootStartMs = millis(); bootStartMs = millis();
lastTime = lastBattTime = lastHeartbeat = lastTelemetry = millis(); lastTime = lastBattTime = lastHeartbeat = lastTelemetry = millis();
} }
// ─── Loop ───────────────────────────────────────────────────────────────────── // Loop
void loop() { void loop() {
unsigned long now = millis(); unsigned long now = millis();
@@ -303,7 +289,7 @@ void loop() {
#ifdef FEATURE_BOOT_LOOP_DETECT #ifdef FEATURE_BOOT_LOOP_DETECT
if (!bootCountCleared && (now - bootStartMs >= BOOT_SAFE_MS)) { if (!bootCountCleared && (now - bootStartMs >= BOOT_SAFE_MS)) {
bootCount = 0; bootCountCleared = true; bootCount = 0; bootCountCleared = true;
Serial.println("[BOOT] Stable counter cleared"); Serial.println("[BOOT] Stable - counter cleared");
} }
#endif #endif
@@ -335,6 +321,11 @@ void loop() {
#ifdef FEATURE_PHYSICAL_BUTTONS #ifdef FEATURE_PHYSICAL_BUTTONS
processPhysicalButtons(); processPhysicalButtons();
#endif #endif
{
bool idle_for_sleep = (sleepStage == SLEEP_IMU_LP) ? true
: (idleFrames >= IDLE_FRAMES);
if (sleepManagerUpdate(now, idle_for_sleep, Bluefruit.connected())) return;
}
if (now - lastTime < (unsigned long)LOOP_RATE_MS) return; if (now - lastTime < (unsigned long)LOOP_RATE_MS) return;
float dt = (now - lastTime) / 1000.0f; float dt = (now - lastTime) / 1000.0f;
@@ -352,7 +343,7 @@ void loop() {
} }
#endif #endif
// Gyro reads with optional temperature compensation // Gyro reads with optional temperature compensation.
float correction = 0.0f; float correction = 0.0f;
#ifdef FEATURE_TEMP_COMPENSATION #ifdef FEATURE_TEMP_COMPENSATION
if (cfg.featureFlags & FLAG_TEMP_COMP_ENABLED) if (cfg.featureFlags & FLAG_TEMP_COMP_ENABLED)
@@ -366,17 +357,14 @@ void loop() {
float ay = imu.readFloatAccelY(); float ay = imu.readFloatAccelY();
float az = imu.readFloatAccelZ(); float az = imu.readFloatAccelZ();
// ── Jerk-based shock detection freeze cursor during tap impacts ──────── // Jerk-based shock detection - freeze cursor during tap impacts, doesn't work well yet
// Jerk = da/dt. Normal rotation = smooth accel changes (low jerk);
// a tap is a sharp impulse (very high jerk).
float jx = (ax - prevAx) / dt, jy = (ay - prevAy) / dt, jz = (az - prevAz) / dt; float jx = (ax - prevAx) / dt, jy = (ay - prevAy) / dt, jz = (az - prevAz) / dt;
float jerkSq = jx*jx + jy*jy + jz*jz; float jerkSq = jx*jx + jy*jy + jz*jz;
prevAx = ax; prevAy = ay; prevAz = az; prevAx = ax; prevAy = ay; prevAz = az;
bool shocked = cfg.tapFreezeEnabled && ((jerkSq > cfg.jerkThreshold) || (now < shockFreezeUntil)); bool shocked = cfg.tapFreezeEnabled && ((jerkSq > cfg.jerkThreshold) || (now < shockFreezeUntil));
if (cfg.tapFreezeEnabled && jerkSq > cfg.jerkThreshold) shockFreezeUntil = now + SHOCK_FREEZE_MS; if (cfg.tapFreezeEnabled && jerkSq > cfg.jerkThreshold) shockFreezeUntil = now + SHOCK_FREEZE_MS;
// Complementary filter — gx=pitch axis, gz=yaw axis on this board layout // Complementary filter
// During shock: gyro-only integration to avoid accel spike corrupting angles
if (shocked) { if (shocked) {
angleX += gx * dt; angleX += gx * dt;
angleY += gz * dt; angleY += gz * dt;
@@ -385,12 +373,7 @@ void loop() {
angleY = ALPHA*(angleY + gz*dt) + (1.0f - ALPHA)*atan2f(ay, sqrtf(ax*ax + az*az)); angleY = ALPHA*(angleY + gz*dt) + (1.0f - ALPHA)*atan2f(ay, sqrtf(ax*ax + az*az));
} }
// ── Gravity-based axis decomposition ────────────────────────────────────── // Gravity-based axis decomposition
// Low-pass filter accel to get a stable gravity estimate in device frame.
// This lets us project angular velocity onto world-aligned axes regardless
// of how the device is rolled. Device forward (pointing) axis = X.
// Confirmed by diagnostics: GX=roll, GY=nod, GZ=pan in user's hold.
// Skip update during shock to protect the gravity estimate from tap spikes.
const float GRAV_LP = 0.05f; const float GRAV_LP = 0.05f;
if (!shocked) { if (!shocked) {
gravX += GRAV_LP * (ax - gravX); gravX += GRAV_LP * (ax - gravX);
@@ -402,8 +385,6 @@ void loop() {
if (gN < 0.3f) gN = 1.0f; if (gN < 0.3f) gN = 1.0f;
float gnx = gravX/gN, gny = gravY/gN, gnz = gravZ/gN; float gnx = gravX/gN, gny = gravY/gN, gnz = gravZ/gN;
// Screen-right = cross(forward, up) = cross([1,0,0], [gnx,gny,gnz])
// = [0, -gnz, gny]
float ry = -gnz, rz = gny; float ry = -gnz, rz = gny;
float rN = sqrtf(ry*ry + rz*rz); float rN = sqrtf(ry*ry + rz*rz);
if (rN < 0.01f) { ry = -1.0f; rz = 0.0f; rN = 1.0f; } if (rN < 0.01f) { ry = -1.0f; rz = 0.0f; rN = 1.0f; }
@@ -415,11 +396,9 @@ void loop() {
float pitchRate = -(gy*ry + gz*rz); float pitchRate = -(gy*ry + gz*rz);
// Projected rates amplify residual gyro bias (especially GY drift on pitch axis). // Projected rates amplify residual gyro bias (especially GY drift on pitch axis).
// Use a wider dead zone for pitch to prevent constant cursor drift at rest.
float fYaw = (fabsf(yawRate) > cfg.deadZone) ? yawRate : 0.0f; float fYaw = (fabsf(yawRate) > cfg.deadZone) ? yawRate : 0.0f;
float fPitch = (fabsf(pitchRate) > cfg.deadZone * 3.0f) ? pitchRate : 0.0f; float fPitch = (fabsf(pitchRate) > cfg.deadZone * 3.0f) ? pitchRate : 0.0f;
// DIAG: print every 500ms to debug gravity projection — remove when confirmed
#ifdef DEBUG #ifdef DEBUG
{ static unsigned long lastDiag = 0; { static unsigned long lastDiag = 0;
if (now - lastDiag >= 500) { lastDiag = now; if (now - lastDiag >= 500) { lastDiag = now;
@@ -438,7 +417,7 @@ void loop() {
#ifdef FEATURE_AUTO_RECAL #ifdef FEATURE_AUTO_RECAL
if ((cfg.featureFlags & FLAG_AUTO_RECAL_ENABLED) && idle && idleStartMs != 0 && (now - idleStartMs >= AUTO_RECAL_MS)) { if ((cfg.featureFlags & FLAG_AUTO_RECAL_ENABLED) && idle && idleStartMs != 0 && (now - idleStartMs >= AUTO_RECAL_MS)) {
Serial.println("[AUTO-CAL] Long idle recalibrating..."); Serial.println("[AUTO-CAL] Long idle - recalibrating...");
idleStartMs = 0; calibrateGyroBias(); prevAx = imu.readFloatAccelX(); prevAy = imu.readFloatAccelY(); prevAz = imu.readFloatAccelZ(); return; idleStartMs = 0; calibrateGyroBias(); prevAx = imu.readFloatAccelX(); prevAy = imu.readFloatAccelY(); prevAz = imu.readFloatAccelZ(); return;
} }
#endif #endif
@@ -447,7 +426,7 @@ void loop() {
uint8_t flags = 0; uint8_t flags = 0;
if (shocked) { if (shocked) {
// Shock freeze discard accumulated sub-pixel motion and suppress output // Shock freeze - discard accumulated sub-pixel motion and suppress output
accumX = accumY = 0.0f; accumX = accumY = 0.0f;
flags |= 0x08; // bit3 = shock freeze active flags |= 0x08; // bit3 = shock freeze active
} else if (idle) { } else if (idle) {
@@ -471,7 +450,7 @@ void loop() {
lastImuStream = now; lastImuStream = now;
if (now < streamBackoffUntil) { if (now < streamBackoffUntil) {
// Backing off host TX buffer congested, skip to avoid 100ms block // Backing off - host TX buffer congested, skip to avoid 100ms block
} else { } else {
ImuPacket pkt; ImuPacket pkt;
pkt.gyroX_mDPS = (int16_t)constrain(gx*(180.f/PI)*1000.f, -32000, 32000); pkt.gyroX_mDPS = (int16_t)constrain(gx*(180.f/PI)*1000.f, -32000, 32000);
@@ -492,7 +471,7 @@ void loop() {
if (streamConsecFails >= STREAM_BACKOFF_THRESH) { if (streamConsecFails >= STREAM_BACKOFF_THRESH) {
streamBackoffUntil = now + STREAM_BACKOFF_MS; streamBackoffUntil = now + STREAM_BACKOFF_MS;
streamConsecFails = 0; streamConsecFails = 0;
Serial.print("[STREAM] TX congested backing off "); Serial.print("[STREAM] TX congested - backing off ");
Serial.print(STREAM_BACKOFF_MS); Serial.println("ms"); Serial.print(STREAM_BACKOFF_MS); Serial.println("ms");
} }
} }
@@ -508,4 +487,4 @@ void loop() {
} }
} }
#endif #endif
} }
+312
View File
@@ -0,0 +1,312 @@
#include "sleep.h"
#include "imu.h" // config.h REG_* macros
#include <bluefruit.h> // sd_app_evt_wait()
#include "Wire.h"
// Registers not in config.h
#define SLP_CTRL2_G 0x11
#define SLP_CTRL6_C 0x15
#define SLP_CTRL7_G 0x16
#define SLP_WAKE_UP_DUR 0x5C
#define SLP_WAKE_UP_SRC 0x1B
#define LSM_ADDR 0x6A
#define XL_ODR_26HZ 0x20
#define XL_ODR_416HZ 0x60
#define G_ODR_416HZ 0x60
// Module state
volatile SleepStage sleepStage = SLEEP_AWAKE;
volatile bool imuWakeFlag = false;
static unsigned long idleEnteredMs = 0; // when motion pipeline first went idle
static unsigned long wakeSettleMs = 0; // when sleepManagerWakeIMU() was called
static unsigned long lpEnteredMs = 0; // when IMU LP was entered (for recal decision)
static bool wasIdle = false;
static uint8_t savedCtrl1XL = XL_ODR_416HZ;
static uint8_t savedCtrl2G = G_ODR_416HZ;
static volatile bool pendingWakeSettle = false; // always set on wake - 120ms blackout
static volatile bool pendingWakeRecal = false; // set only when recal is also needed
// Only force recalibration after waking from deep sleep, or after the gyro
// has been off long enough for thermal drift to matter (~5 minutes).
static constexpr unsigned long RECAL_AFTER_LP_MS = 5UL * 60UL * 1000UL;
// I2C helpers - Wire1 at 0x6A (SA0 LOW on XIAO nRF52840 Sense)
static uint8_t lsmRead(uint8_t reg) {
Wire1.beginTransmission(LSM_ADDR);
Wire1.write(reg);
Wire1.endTransmission(false);
Wire1.requestFrom(LSM_ADDR, (uint8_t)1);
return Wire1.available() ? Wire1.read() : 0xFF;
}
static void lsmWrite(uint8_t reg, uint8_t val) {
Wire1.beginTransmission(LSM_ADDR);
Wire1.write(reg);
Wire1.write(val);
Wire1.endTransmission();
}
// ISR
static void imuInt1ISR() {
imuWakeFlag = true;
}
// Arm wakeup interrupt
static void armWakeupInterrupt() {
lsmWrite(SLP_WAKE_UP_DUR, (uint8_t)((SLEEP_WAKEUP_DUR & 0x03) << 4));
// Preserve bit7 (tap single/double enable)
uint8_t wuth = lsmRead(REG_WAKE_UP_THS);
wuth = (wuth & 0xC0) | (SLEEP_WAKEUP_THS & 0x3F);
lsmWrite(REG_WAKE_UP_THS, wuth);
// INTERRUPTS_ENABLE=1, SLOPE_FDS=0 (HP filter is gated in LP - must be 0)
uint8_t tcfg = lsmRead(REG_TAP_CFG);
tcfg |= (1 << 7);
tcfg &= ~(1 << 4);
lsmWrite(REG_TAP_CFG, tcfg);
uint8_t md1 = lsmRead(REG_MD1_CFG);
md1 |= (1 << 5);
lsmWrite(REG_MD1_CFG, md1);
// Clear any stale latch BEFORE re-arming the edge interrupt.
(void)lsmRead(SLP_WAKE_UP_SRC);
delay(2);
// Re-attach with RISING - guaranteed clean edge now that latch is cleared
detachInterrupt(digitalPinToInterrupt(IMU_INT1_PIN));
attachInterrupt(digitalPinToInterrupt(IMU_INT1_PIN), imuInt1ISR, RISING);
imuWakeFlag = false;
#ifdef DEBUG
Serial.print("[SLEEP] armWakeup - TAP_CFG=0x"); Serial.print(lsmRead(REG_TAP_CFG), HEX);
Serial.print(" MD1_CFG=0x"); Serial.print(lsmRead(REG_MD1_CFG), HEX);
Serial.print(" WAKE_UP_THS=0x"); Serial.println(lsmRead(REG_WAKE_UP_THS), HEX);
#endif
}
static void disarmWakeupInterrupt() {
// Restore SLOPE_FDS=1 for tap detection HP filter path
uint8_t tcfg = lsmRead(REG_TAP_CFG);
tcfg |= (1 << 4);
lsmWrite(REG_TAP_CFG, tcfg);
// Clear INT1_WU to stop wakeup engine driving INT1 at full rate
uint8_t md1 = lsmRead(REG_MD1_CFG);
md1 &= ~(1 << 5);
lsmWrite(REG_MD1_CFG, md1);
}
// Enter IMU LP
static void enterImuLP() {
if (sleepStage >= SLEEP_IMU_LP) return;
savedCtrl1XL = lsmRead(REG_CTRL1_XL);
savedCtrl2G = lsmRead(SLP_CTRL2_G);
lsmWrite(SLP_CTRL2_G, savedCtrl2G & 0x0F); // gyro off
lsmWrite(REG_CTRL1_XL, (savedCtrl1XL & 0x0F) | XL_ODR_26HZ); // accel 26 Hz
lsmWrite(SLP_CTRL6_C, lsmRead(SLP_CTRL6_C) | (1 << 4)); // XL_HM_MODE=1
lsmWrite(SLP_CTRL7_G, lsmRead(SLP_CTRL7_G) | (1 << 7)); // G_HM_MODE=1
armWakeupInterrupt();
lpEnteredMs = millis();
sleepStage = SLEEP_IMU_LP;
Serial.print("[SLEEP] IMU LP entered - idle for ");
Serial.print((millis() - idleEnteredMs) / 1000); Serial.println("s");
#ifdef DEBUG
Serial.print("[SLEEP] CTRL1_XL=0x"); Serial.print(lsmRead(REG_CTRL1_XL), HEX);
Serial.print(" CTRL2_G=0x"); Serial.print(lsmRead(SLP_CTRL2_G), HEX);
Serial.print(" CTRL6_C=0x"); Serial.print(lsmRead(SLP_CTRL6_C), HEX);
Serial.print(" CTRL7_G=0x"); Serial.println(lsmRead(SLP_CTRL7_G), HEX);
Serial.print("[SLEEP] TAP_CFG=0x"); Serial.print(lsmRead(REG_TAP_CFG), HEX);
Serial.print(" MD1_CFG=0x"); Serial.print(lsmRead(REG_MD1_CFG), HEX);
Serial.print(" WAKE_UP_THS=0x"); Serial.print(lsmRead(REG_WAKE_UP_THS), HEX);
Serial.print(" WAKE_UP_DUR=0x"); Serial.println(lsmRead(SLP_WAKE_UP_DUR), HEX);
#endif
}
// Enter deep sleep
static void enterDeepSleep() {
if (sleepStage >= SLEEP_DEEP) return;
if (sleepStage < SLEEP_IMU_LP) enterImuLP();
sleepStage = SLEEP_DEEP;
Serial.println("[SLEEP] Deep sleep - WFE on INT1");
Serial.flush();
digitalWrite(LED_RED, LOW); delay(80); digitalWrite(LED_RED, HIGH);
while (!imuWakeFlag) {
(void)lsmRead(SLP_WAKE_UP_SRC);
sd_app_evt_wait();
}
}
// Public: wake
void sleepManagerWakeIMU() {
(void)lsmRead(SLP_WAKE_UP_SRC);
lsmWrite(SLP_CTRL6_C, lsmRead(SLP_CTRL6_C) & ~(1 << 4));
lsmWrite(SLP_CTRL7_G, lsmRead(SLP_CTRL7_G) & ~(1 << 7));
lsmWrite(REG_CTRL1_XL, savedCtrl1XL);
lsmWrite(SLP_CTRL2_G, savedCtrl2G);
disarmWakeupInterrupt();
// Only recalibrate if gyro was off long enough for thermal drift to accumulate,
// or if waking from full deep sleep. Short LP naps reuse the existing bias.
unsigned long lpDuration = millis() - lpEnteredMs;
bool needsRecal = (sleepStage == SLEEP_DEEP) || (lpDuration >= RECAL_AFTER_LP_MS);
wakeSettleMs = millis();
pendingWakeSettle = true; // always block output for 120ms
pendingWakeRecal = needsRecal; // additionally recalibrate if needed
wasIdle = false;
idleEnteredMs = 0;
lpEnteredMs = 0;
// Reset motion filter state to prevent a cursor jump on the first frame.
// After sleep: angleX/Y are stale, gravX/Y/Z drifted, accumX/Y is dirty,
// and lastTime is old so dt would be huge on the first loop iteration.
// Zeroing these here means the first frame integrates 0 motion cleanly.
extern float angleX, angleY;
extern float accumX, accumY;
extern float gravX, gravY, gravZ;
extern float prevAx, prevAy, prevAz;
extern unsigned long lastTime;
angleX = angleY = 0.0f;
accumX = accumY = 0.0f;
// Reseed gravity from current accel so projection is correct immediately.
// Can't call imu.readFloat* here (gyro not fully settled), but accel is
// already running - read it directly via Wire1.
// Simpler: just reset to neutral [0,0,1] and let the LP filter converge
// over the first ~20 frames (200 ms) of real use.
gravX = 0.0f; gravY = 0.0f; gravZ = 1.0f;
prevAx = 0.0f; prevAy = 0.0f; prevAz = 0.0f;
// Set lastTime to now so the first dt = 0 rather than (now - sleepEntryTime)
lastTime = millis();
sleepStage = SLEEP_AWAKE;
if (needsRecal)
Serial.println("[SLEEP] Awake - gyro settling, recal needed");
else
Serial.println("[SLEEP] Awake - short LP, reusing existing bias");
}
// Public: init
void sleepManagerInit() {
pinMode(IMU_INT1_PIN, INPUT);
attachInterrupt(digitalPinToInterrupt(IMU_INT1_PIN), imuInt1ISR, RISING);
// Sanity check: WHO_AM_I should return 0x6A for LSM6DS3
uint8_t whoami = imuReadReg(0x0F);
Serial.print("[SLEEP] WHO_AM_I=0x"); Serial.print(whoami, HEX);
if (whoami == 0x6A) Serial.println(" (OK)");
else Serial.println(" (WRONG - I2C not working, sleep disabled)");
if (whoami != 0x6A) return; // don't arm anything if we can't talk to the IMU
Serial.print("[SLEEP] Init - INT1 pin="); Serial.print(IMU_INT1_PIN);
Serial.print(", WU_THS="); Serial.print(SLEEP_WAKEUP_THS);
Serial.print(" (~"); Serial.print(SLEEP_WAKEUP_THS * 7.8f, 0); Serial.print(" mg)");
Serial.print(", IMU_LP after "); Serial.print(SLEEP_IMU_IDLE_MS / 1000); Serial.print("s");
Serial.print(", deep after "); Serial.print(SLEEP_DEEP_IDLE_MS / 1000); Serial.println("s");
}
// Public: per-loop update
// Must be called AFTER idleFrames/idle is updated by the motion pipeline.
// Returns true → caller must skip IMU reads this iteration.
bool sleepManagerUpdate(unsigned long nowMs, bool idle, bool bleConnected) {
// ISR wakeup
if (imuWakeFlag) {
imuWakeFlag = false;
Serial.print("[SLEEP] INT1 fired - stage="); Serial.println((int)sleepStage);
if (sleepStage == SLEEP_DEEP || sleepStage == SLEEP_IMU_LP) {
sleepManagerWakeIMU();
} else {
(void)lsmRead(SLP_WAKE_UP_SRC); // normal-mode edge, clear latch only
}
}
// Gyro settling after wake
if (pendingWakeRecal) {
if (nowMs - wakeSettleMs >= 120) {
pendingWakeRecal = false;
wakeSettleMs = 0;
extern void calibrateGyroBias();
calibrateGyroBias();
Serial.println("[SLEEP] Post-wake recal done");
}
return true;
}
// IMU_LP path
// main.cpp returns early when we return true, so idleFrames never increments
// and the motion pipeline's `idle` flag is stale. Use our own idleEnteredMs
// (captured before LP entry) to drive the deep-sleep countdown independently.
if (sleepStage == SLEEP_IMU_LP) {
// Periodic log: confirms loop is running, shows live INT1 pin level and
// WAKE_UP_SRC register. If INT1_pin never goes high after movement, the
// wakeup engine is not generating an interrupt - check register values.
static unsigned long lastLpLog = 0;
if (nowMs - lastLpLog >= 5000) {
lastLpLog = nowMs;
unsigned long lpSecs = idleEnteredMs ? (nowMs - idleEnteredMs) / 1000 : 0;
Serial.print("[SLEEP] LP tick - idle="); Serial.print(lpSecs);
Serial.print("s INT1="); Serial.print(digitalRead(IMU_INT1_PIN));
Serial.print(" WAKE_UP_SRC=0x"); Serial.println(lsmRead(SLP_WAKE_UP_SRC), HEX);
}
if (!bleConnected && idleEnteredMs != 0
&& (nowMs - idleEnteredMs >= SLEEP_DEEP_IDLE_MS))
{
Serial.println("[SLEEP] Deep sleep threshold reached");
enterDeepSleep();
}
return true;
}
// AWAKE path
if (!idle) {
if (wasIdle) {
Serial.println("[SLEEP] Motion - idle timer reset");
}
wasIdle = false;
idleEnteredMs = 0;
return false;
}
if (!wasIdle) {
wasIdle = true;
idleEnteredMs = nowMs;
Serial.println("[SLEEP] Idle started");
}
unsigned long idleElapsed = nowMs - idleEnteredMs;
// Progress report every 5 s while waiting for LP threshold
#ifdef DEBUG
{ static unsigned long lastReport = 0;
if (nowMs - lastReport >= 5000) { lastReport = nowMs;
Serial.print("[SLEEP] idle="); Serial.print(idleElapsed/1000);
Serial.print("s / LP@"); Serial.print(SLEEP_IMU_IDLE_MS/1000); Serial.println("s");
}
}
#endif
if (idleElapsed >= SLEEP_IMU_IDLE_MS) {
enterImuLP();
return true;
}
return false;
}
+39
View File
@@ -0,0 +1,39 @@
#pragma once
#include <Arduino.h>
// Tuning
#ifndef SLEEP_IMU_IDLE_MS
#define SLEEP_IMU_IDLE_MS (10UL * 1000UL) // 10 s → gyro off, accel LP
#endif
#ifndef SLEEP_DEEP_IDLE_MS
#define SLEEP_DEEP_IDLE_MS (60UL * 1000UL) // 60 s → system deep sleep (no-BLE only)
#endif
// LSM6DS3 wakeup threshold: 1 LSB = 7.8 mg at ±2 g FS (±2g range).
#ifndef SLEEP_WAKEUP_THS
#define SLEEP_WAKEUP_THS 16 // 063
#endif
// Number of consecutive 26 Hz samples that must exceed the threshold.
#ifndef SLEEP_WAKEUP_DUR
#define SLEEP_WAKEUP_DUR 2 // 03
#endif
// GPIO pin connected to LSM6DS3 INT1.
#ifndef IMU_INT1_PIN
#define IMU_INT1_PIN PIN_LSM6DS3TR_C_INT1
#endif
// Public state (read-only from main.cpp)
enum SleepStage : uint8_t {
SLEEP_AWAKE = 0, // normal full-rate operation
SLEEP_IMU_LP = 1, // gyro off, accel LP - nRF awake
SLEEP_DEEP = 2, // system WFE - BLE disconnected only
};
extern volatile SleepStage sleepStage;
extern volatile bool imuWakeFlag;
void sleepManagerInit();
bool sleepManagerUpdate(unsigned long nowMs, bool idle, bool bleConnected);
void sleepManagerWakeIMU();
+7 -18
View File
@@ -6,12 +6,12 @@
extern BLEHidAdafruit blehid; extern BLEHidAdafruit blehid;
// ─── Tap detection setup ────────────────────────────────────────────────────── // Tap detection setup
// REG_TAP_THS_6D bits[4:0] = tapThreshold (131); 1 LSB = FS/32 = 62.5 mg at ±2g. // REG_TAP_THS_6D bits[4:0] = tapThreshold (131); 1 LSB = FS/32 = 62.5 mg at ±2g.
// REG_INT_DUR2 at ODR=416 Hz: // REG_INT_DUR2 at ODR=416 Hz:
// SHOCK[7:6] = 2 → 38 ms max tap duration // SHOCK[7:6] = 2 → 38 ms max tap duration
// QUIET[5:4] = 2 → 19 ms refractory after tap // QUIET[5:4] = 2 → 19 ms refractory after tap
// DUR[3:0] = 6 → 115 ms max inter-tap window for double detection // DUR[3:0] = 6 → 115 ms max inter-tap window for double detection
void applyTapThreshold() { void applyTapThreshold() {
uint8_t thr = cfg.tapThreshold; uint8_t thr = cfg.tapThreshold;
if (thr < 1) thr = 1; if (thr < 1) thr = 1;
@@ -30,18 +30,7 @@ void setupTapDetection() {
Serial.print(" (~"); Serial.print(cfg.tapThreshold * 62.5f, 0); Serial.println(" mg)"); Serial.print(" (~"); Serial.print(cfg.tapThreshold * 62.5f, 0); Serial.println(" mg)");
} }
// ─── Tap processing ─────────────────────────────────────────────────────────── // Tap processing
// Only double-tap is mapped to an action. Single-tap is ignored (it always fires
// before the double is confirmed and cannot be reliably disambiguated on this
// hardware without an unacceptable latency penalty).
//
// The LSM6DS3 sets SINGLE_TAP immediately on first contact — we wait until
// DOUBLE_TAP is set (within the hardware DUR window of 115 ms) before acting.
// An additional TAP_CONFIRM_MS guard ensures the TAP_SRC register has settled.
//
// IMPORTANT: call mouseButtonPress(bitmask) — single arg only. The two-arg
// overload takes (conn_hdl, buttons) and sends the wrong button value.
static enum { TAP_IDLE, TAP_PENDING, TAP_EXECUTING } tapState = TAP_IDLE; static enum { TAP_IDLE, TAP_PENDING, TAP_EXECUTING } tapState = TAP_IDLE;
static unsigned long tapPendingMs = 0; static unsigned long tapPendingMs = 0;
static uint8_t pendingButton = 0; // 0 = key action pending static uint8_t pendingButton = 0; // 0 = key action pending
@@ -83,7 +72,7 @@ static void fireTapAction(unsigned long now) {
} }
void processTaps(unsigned long now) { void processTaps(unsigned long now) {
// ── Release ─────────────────────────────────────────────────────────────── // Release
if (tapState == TAP_EXECUTING) { if (tapState == TAP_EXECUTING) {
if (now - clickDownMs >= CLICK_HOLD_MS) { if (now - clickDownMs >= CLICK_HOLD_MS) {
if (pendingButton) { if (pendingButton) {
@@ -99,7 +88,7 @@ void processTaps(unsigned long now) {
return; return;
} }
// ── Poll TAP_SRC ────────────────────────────────────────────────────────── // Poll TAP_SRC
uint8_t tapSrc = imuReadReg(REG_TAP_SRC); uint8_t tapSrc = imuReadReg(REG_TAP_SRC);
bool tapIA = !!(tapSrc & 0x40); bool tapIA = !!(tapSrc & 0x40);
bool doubleTap = !!(tapSrc & 0x10); bool doubleTap = !!(tapSrc & 0x10);
+60 -60
View File
@@ -1,4 +1,4 @@
// ── UUIDs ──────────────────────────────────────────────────────────────────── // UUIDs
// v3.3: 4 characteristics instead of 10 // v3.3: 4 characteristics instead of 10
const SVC_UUID = '00001234-0000-1000-8000-00805f9b34fb'; const SVC_UUID = '00001234-0000-1000-8000-00805f9b34fb';
const CHR = { const CHR = {
@@ -25,11 +25,11 @@ let device=null, server=null, chars={}, userDisconnected=false;
let currentChargeStatus=0, currentBattPct=null, currentBattVoltage=null; let currentChargeStatus=0, currentBattPct=null, currentBattVoltage=null;
let advancedMode = localStorage.getItem('advanced') === 'true'; let advancedMode = localStorage.getItem('advanced') === 'true';
// ── GATT write queue (prevents "operation already in progress") ─────────────── // GATT write queue (prevents "operation already in progress")
// Serialises all GATT writes. Features: // Serialises all GATT writes. Features:
// • Per-operation 3s timeout hangs don't block the queue forever // • Per-operation 3s timeout - hangs don't block the queue forever
// • Max depth of 2 pending ops drops excess writes when device goes silent // • Max depth of 2 pending ops - drops excess writes when device goes silent
// • gattQueueReset() flushes on disconnect so a reconnect starts clean // • gattQueueReset() flushes on disconnect so a reconnect starts clean
const GATT_TIMEOUT_MS = 3000; const GATT_TIMEOUT_MS = 3000;
const GATT_MAX_DEPTH = 2; const GATT_MAX_DEPTH = 2;
let _gattQueue = Promise.resolve(); let _gattQueue = Promise.resolve();
@@ -45,7 +45,7 @@ function _withTimeout(promise, ms) {
function _enqueue(fn) { function _enqueue(fn) {
if (_gattDepth >= GATT_MAX_DEPTH) { if (_gattDepth >= GATT_MAX_DEPTH) {
return Promise.reject(new Error('GATT queue full device unreachable?')); return Promise.reject(new Error('GATT queue full - device unreachable?'));
} }
_gattDepth++; _gattDepth++;
const p = _gattQueue.then(() => _withTimeout(fn(), GATT_TIMEOUT_MS)); const p = _gattQueue.then(() => _withTimeout(fn(), GATT_TIMEOUT_MS));
@@ -62,7 +62,7 @@ function gattQueueReset() {
_gattDepth = 0; _gattDepth = 0;
} }
// ── Logging ────────────────────────────────────────────────────────────────── // Logging
(function() { (function() {
const _methods = { log: '', warn: 'warn', error: 'err' }; const _methods = { log: '', warn: 'warn', error: 'err' };
for (const [method, type] of Object.entries(_methods)) { for (const [method, type] of Object.entries(_methods)) {
@@ -85,7 +85,7 @@ function log(msg, type='') {
const p2=n=>String(n).padStart(2,'0'), p3=n=>String(n).padStart(3,'0'); const p2=n=>String(n).padStart(2,'0'), p3=n=>String(n).padStart(3,'0');
function cssVar(n) { return getComputedStyle(document.documentElement).getPropertyValue(n).trim(); } function cssVar(n) { return getComputedStyle(document.documentElement).getPropertyValue(n).trim(); }
// ── Connection ─────────────────────────────────────────────────────────────── // Connection
async function doConnect() { async function doConnect() {
if (!navigator.bluetooth) { log('Web Bluetooth not supported.','err'); return; } if (!navigator.bluetooth) { log('Web Bluetooth not supported.','err'); return; }
userDisconnected = false; userDisconnected = false;
@@ -131,27 +131,27 @@ async function discoverServices() {
// Read firmware git hash and check against web build hash // Read firmware git hash and check against web build hash
await checkHashMatch(); await checkHashMatch();
// Telemetry notify (1 Hz) also carries chargeStatus // Telemetry notify (1 Hz) - also carries chargeStatus
chars.telemetry.addEventListener('characteristicvaluechanged', e => parseTelemetry(e.target.value)); chars.telemetry.addEventListener('characteristicvaluechanged', e => parseTelemetry(e.target.value));
await chars.telemetry.startNotifications(); await chars.telemetry.startNotifications();
// Initial read so values show immediately. Also force updateChargeUI() here // Initial read so values show immediately. Also force updateChargeUI() here
// because parseTelemetry() only calls it on a *change*, and currentChargeStatus // because parseTelemetry() only calls it on a *change*, and currentChargeStatus
// starts at 0 (discharging) so a discharging device would never trigger the // starts at 0 (discharging) - so a discharging device would never trigger the
// update and ciStatus would stay at '--'. // update and ciStatus would stay at '--'.
parseTelemetry(await chars.telemetry.readValue()); parseTelemetry(await chars.telemetry.readValue());
updateChargeUI(); updateChargeUI();
// IMU stream subscribed on demand via play button // IMU stream - subscribed on demand via play button
chars.imuStream.addEventListener('characteristicvaluechanged', e => parseImuStream(e.target.value)); chars.imuStream.addEventListener('characteristicvaluechanged', e => parseImuStream(e.target.value));
log('Config service ready (4 chars)','ok'); log('Config service ready (4 chars)','ok');
} catch(e) { } catch(e) {
log(`Service discovery failed: ${e.message}`,'err'); log(`Service discovery failed: ${e.message}`,'err');
// Safe mode device might not have config service // Safe mode device might not have config service
if (e.message.includes('not found')) log('Device may be in safe mode basic mouse only','warn'); if (e.message.includes('not found')) log('Device may be in safe mode - basic mouse only','warn');
} }
// Battery service (standard always present) // Battery service (standard - always present)
try { try {
const bsvc = await server.getPrimaryService('battery_service'); const bsvc = await server.getPrimaryService('battery_service');
const bch = await bsvc.getCharacteristic('battery_level'); const bch = await bsvc.getCharacteristic('battery_level');
@@ -167,7 +167,7 @@ async function discoverServices() {
} catch(e) { log('Battery service unavailable','warn'); } } catch(e) { log('Battery service unavailable','warn'); }
} }
// ── Firmware / web hash mismatch banner ────────────────────────────────────── // Firmware / web hash mismatch banner
async function checkHashMatch() { async function checkHashMatch() {
const banner = document.getElementById('hashMismatchBanner'); const banner = document.getElementById('hashMismatchBanner');
if (!chars.gitHash) return; if (!chars.gitHash) return;
@@ -199,20 +199,20 @@ async function checkHashMatch() {
].join(';'); ].join(';');
banner.innerHTML = banner.innerHTML =
`<span style="font-size:14px">⚠</span>` + `<span style="font-size:14px">⚠</span>` +
`<span>FIRMWARE / WEB MISMATCH ` + `<span>FIRMWARE / WEB MISMATCH - ` +
`firmware <b>${fwHash}</b> · web <b>${webHash}</b> ` + `firmware <b>${fwHash}</b> · web <b>${webHash}</b> - ` +
`flash firmware or reload the page after a <code>pio run</code></span>` + `flash firmware or reload the page after a <code>pio run</code></span>` +
`<button onclick="document.getElementById('hashMismatchBanner').style.display='none'" ` + `<button onclick="document.getElementById('hashMismatchBanner').style.display='none'" ` +
`style="margin-left:8px;background:none;border:1px solid #c04040;color:#ffd0d0;` + `style="margin-left:8px;background:none;border:1px solid #c04040;color:#ffd0d0;` +
`cursor:pointer;padding:2px 8px;font-family:var(--mono);font-size:10px">✕</button>`; `cursor:pointer;padding:2px 8px;font-family:var(--mono);font-size:10px">✕</button>`;
} }
// ── ConfigBlob read / write ────────────────────────────────────────────────── // ConfigBlob read / write
// ConfigBlob layout (25 bytes LE): // ConfigBlob layout (25 bytes LE):
// float sensitivity [0], float deadZone [4], float accelStrength [8] // float sensitivity [0], float deadZone [4], float accelStrength [8]
// uint8 curve [12], uint8 axisFlip [13], uint8 chargeMode [14] // uint8 curve [12], uint8 axisFlip [13], uint8 chargeMode [14]
// uint8 tapThreshold [15], uint8 tapAction [16], uint8 tapKey [17], uint8 tapMod [18], uint8 tapFreezeEnabled [19] // uint8 tapThreshold [15], uint8 tapAction [16], uint8 tapKey [17], uint8 tapMod [18], uint8 tapFreezeEnabled [19]
// float jerkThreshold [20], uint8 featureFlags [24] // float jerkThreshold [20], uint8 featureFlags [24]
async function readConfigBlob() { async function readConfigBlob() {
if (!chars.configBlob) return; if (!chars.configBlob) return;
@@ -238,7 +238,7 @@ async function readConfigBlob() {
if (view.byteLength >= 25) { if (view.byteLength >= 25) {
config.featureFlags = view.getUint8(24); config.featureFlags = view.getUint8(24);
} else { } else {
config.featureFlags = FLAG_ALL_DEFAULT; // old firmware assume all on config.featureFlags = FLAG_ALL_DEFAULT; // old firmware - assume all on
} }
if (view.byteLength >= 28) { if (view.byteLength >= 28) {
config.btnLeftPin = view.getUint8(25); config.btnLeftPin = view.getUint8(25);
@@ -248,7 +248,7 @@ async function readConfigBlob() {
config.btnLeftPin = config.btnRightPin = config.btnMiddlePin = 0xFF; // disabled config.btnLeftPin = config.btnRightPin = config.btnMiddlePin = 0xFF; // disabled
} }
applyConfigToUI(); applyConfigToUI();
log(`Config loaded sens=${config.sensitivity.toFixed(0)} dz=${config.deadZone.toFixed(3)} tapThr=${config.tapThreshold}`,'ok'); log(`Config loaded - sens=${config.sensitivity.toFixed(0)} dz=${config.deadZone.toFixed(3)} tapThr=${config.tapThreshold}`,'ok');
} catch(e) { log(`Config read error: ${e.message}`,'err'); } } catch(e) { log(`Config read error: ${e.message}`,'err'); }
} }
@@ -284,7 +284,7 @@ function applyConfigToUI() {
updatePinDiagram(); updatePinDiagram();
} }
// ── XIAO pin diagram ────────────────────────────────────────────────────────── // XIAO pin diagram
function updatePinDiagram() { function updatePinDiagram() {
const st = getComputedStyle(document.documentElement); const st = getComputedStyle(document.documentElement);
const COL_L = st.getPropertyValue('--ok').trim(); const COL_L = st.getPropertyValue('--ok').trim();
@@ -362,11 +362,11 @@ async function _doWriteConfigBlob() {
try { try {
await gattWrite(chars.configBlob, buf); await gattWrite(chars.configBlob, buf);
log(`Config written sens=${config.sensitivity.toFixed(0)} tapThr=${config.tapThreshold} tapAction=${config.tapAction}`,'ok'); log(`Config written - sens=${config.sensitivity.toFixed(0)} tapThr=${config.tapThreshold} tapAction=${config.tapAction}`,'ok');
} catch(e) { log(`Config write failed: ${e.message}`,'err'); } } catch(e) { log(`Config write failed: ${e.message}`,'err'); }
} }
// ── Individual control handlers ─────────────────────────────────────────────── // Individual control handlers
// These update the local config shadow then write the full blob // These update the local config shadow then write the full blob
function setCurve(val) { function setCurve(val) {
@@ -397,7 +397,7 @@ function setChargeModeUI(val) {
function onCapTapChange(enabled) { function onCapTapChange(enabled) {
writeConfigBlob(); writeConfigBlob();
log('Tap detection ' + (enabled ? 'enabled' : 'disabled') + ' restart device to apply', 'warn'); log('Tap detection ' + (enabled ? 'enabled' : 'disabled') + ' - restart device to apply', 'warn');
} }
function onTapFreezeChange(enabled) { function onTapFreezeChange(enabled) {
@@ -430,7 +430,7 @@ function onTapKeyInput() {
async function sendCalibrate() { async function sendCalibrate() {
if (!chars.command) return; if (!chars.command) return;
try { await gattCmd(chars.command, new Uint8Array([0x01])); log('Calibration sent hold still!','warn'); } try { await gattCmd(chars.command, new Uint8Array([0x01])); log('Calibration sent - hold still!','warn'); }
catch(e) { log(`Calibrate failed: ${e.message}`,'err'); } catch(e) { log(`Calibrate failed: ${e.message}`,'err'); }
} }
function confirmReset() { document.getElementById('overlay').classList.add('show'); } function confirmReset() { document.getElementById('overlay').classList.add('show'); }
@@ -444,22 +444,22 @@ async function doReset() {
} catch(e) { log(`Reset failed: ${e.message}`,'err'); } } catch(e) { log(`Reset failed: ${e.message}`,'err'); }
} }
// ── Telemetry ──────────────────────────────────────────────────────────────── // Telemetry
// TelemetryPacket (28 bytes LE backwards compatible with 24-byte v3.3): // TelemetryPacket (28 bytes LE - backwards compatible with 24-byte v3.3):
// uint32 uptime [0], uint32 leftClicks [4], uint32 rightClicks [8] // uint32 uptime [0], uint32 leftClicks [4], uint32 rightClicks [8]
// float temp [12], float biasRms [16] // float temp [12], float biasRms [16]
// uint16 recalCount [20], uint8 chargeStatus [22], uint8 pad [23] // uint16 recalCount [20], uint8 chargeStatus [22], uint8 pad [23]
// float battVoltage [24] (new in v3.4, absent on older firmware) // float battVoltage [24] (new in v3.4, absent on older firmware)
function parseTelemetry(dv) { function parseTelemetry(dv) {
let view; let view;
try { try {
view = dv instanceof DataView ? new DataView(dv.buffer, dv.byteOffset, dv.byteLength) : new DataView(dv); view = dv instanceof DataView ? new DataView(dv.buffer, dv.byteOffset, dv.byteLength) : new DataView(dv);
} catch(e) { log(`parseTelemetry: DataView wrap failed ${e.message}`,'err'); return; } } catch(e) { log(`parseTelemetry: DataView wrap failed - ${e.message}`,'err'); return; }
if (view.byteLength < 24) { if (view.byteLength < 24) {
const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength); const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
const hex = Array.from(bytes).map(b=>b.toString(16).padStart(2,'0')).join(' '); const hex = Array.from(bytes).map(b=>b.toString(16).padStart(2,'0')).join(' ');
log(`TELEM: expected 24-28B, got ${view.byteLength}B MTU too small? raw: ${hex}`,'err'); log(`TELEM: expected 24-28B, got ${view.byteLength}B - MTU too small? raw: ${hex}`,'err');
return; return;
} }
@@ -473,7 +473,7 @@ function parseTelemetry(dv) {
recalCount = view.getUint16(20, true); recalCount = view.getUint16(20, true);
chargeStatus= view.getUint8(22); chargeStatus= view.getUint8(22);
if (view.byteLength >= 28) battVoltage = view.getFloat32(24, true); if (view.byteLength >= 28) battVoltage = view.getFloat32(24, true);
} catch(e) { log(`parseTelemetry: parse error at offset ${e.message}`,'err'); return; } } catch(e) { log(`parseTelemetry: parse error at offset - ${e.message}`,'err'); return; }
document.getElementById('telTemp').textContent = temp.toFixed(1)+'°'; document.getElementById('telTemp').textContent = temp.toFixed(1)+'°';
document.getElementById('telUptime').textContent = formatUptime(uptime); document.getElementById('telUptime').textContent = formatUptime(uptime);
@@ -504,7 +504,7 @@ function clearTelemetry() {
document.getElementById(id).textContent='--'); document.getElementById(id).textContent='--');
} }
// ── Battery & Charge UI ─────────────────────────────────────────────────────── // Battery & Charge UI
function updateBatteryBar(pct, status) { function updateBatteryBar(pct, status) {
document.getElementById('battBar').style.display='flex'; document.getElementById('battBar').style.display='flex';
document.getElementById('battPct').textContent=pct+'%'; document.getElementById('battPct').textContent=pct+'%';
@@ -528,7 +528,7 @@ function updateChargeUI() {
if (currentBattPct!==null) updateBatteryBar(currentBattPct, currentChargeStatus); if (currentBattPct!==null) updateBatteryBar(currentBattPct, currentChargeStatus);
} }
// ── Advanced toggle ─────────────────────────────────────────────────────── // Advanced toggle
function toggleAdvanced(on) { function toggleAdvanced(on) {
advancedMode = on; advancedMode = on;
localStorage.setItem('advanced', on); localStorage.setItem('advanced', on);
@@ -538,7 +538,7 @@ function toggleAdvanced(on) {
document.getElementById('chargeInfo').style.gridTemplateColumns = on ? '1fr 1fr 1fr 1fr' : '1fr 1fr 1fr'; document.getElementById('chargeInfo').style.gridTemplateColumns = on ? '1fr 1fr 1fr 1fr' : '1fr 1fr 1fr';
} }
// ── IMU Debug Recorder ──────────────────────────────────────────────────────── // IMU Debug Recorder
let debugModalOpen = false; let debugModalOpen = false;
let debugRecording = false; let debugRecording = false;
let debugBuffer = []; let debugBuffer = [];
@@ -631,7 +631,7 @@ function clearDebugRec() {
document.getElementById('debugRecCount').textContent = '0 samples'; document.getElementById('debugRecCount').textContent = '0 samples';
} }
// ── Param display ───────────────────────────────────────────────────────────── // Param display
function updateDisplay(key, val) { function updateDisplay(key, val) {
const map = { const map = {
sensitivity: ['valSensitivity', v=>parseFloat(v).toFixed(0)], sensitivity: ['valSensitivity', v=>parseFloat(v).toFixed(0)],
@@ -644,7 +644,7 @@ function updateDisplay(key, val) {
document.getElementById(id).textContent = fmt(val); document.getElementById(id).textContent = fmt(val);
} }
// ── Status UI ──────────────────────────────────────────────────────────────── // Status UI
function setStatus(state) { function setStatus(state) {
const pill=document.getElementById('statusPill'); const pill=document.getElementById('statusPill');
document.getElementById('statusText').textContent={connected:'CONNECTED',connecting:'CONNECTING…',disconnected:'DISCONNECTED'}[state]; document.getElementById('statusText').textContent={connected:'CONNECTED',connecting:'CONNECTING…',disconnected:'DISCONNECTED'}[state];
@@ -673,7 +673,7 @@ function onDisconnected() {
document.getElementById('badgeCharging').classList.remove('show'); document.getElementById('badgeCharging').classList.remove('show');
document.getElementById('badgeFull').classList.remove('show'); document.getElementById('badgeFull').classList.remove('show');
imuSubscribed = false; vizPaused = true; vizUpdateIndicator(); streamDiagReset(); imuSubscribed = false; vizPaused = true; vizUpdateIndicator(); streamDiagReset();
document.getElementById('orientLabel').textContent = ' not streaming '; document.getElementById('orientLabel').textContent = '- not streaming -';
document.getElementById('hashMismatchBanner').style.display = 'none'; document.getElementById('hashMismatchBanner').style.display = 'none';
clearTelemetry(); clearTelemetry();
if (!userDisconnected && document.getElementById('autoReconnect').checked && savedDevice) { if (!userDisconnected && document.getElementById('autoReconnect').checked && savedDevice) {
@@ -695,11 +695,11 @@ function onDisconnected() {
} }
} }
// ── IMU Stream + Visualiser ────────────────────────────────────────────────── // IMU Stream + Visualiser
// ImuPacket (14 bytes LE): // ImuPacket (14 bytes LE):
// int16 gyroX_mDPS [0], int16 gyroZ_mDPS [2] // int16 gyroX_mDPS [0], int16 gyroZ_mDPS [2]
// int16 accelX_mg [4], int16 accelY_mg [6], int16 accelZ_mg [8] // int16 accelX_mg [4], int16 accelY_mg [6], int16 accelZ_mg [8]
// int8 moveX [10], int8 moveY [11], uint8 flags [12], uint8 pad [13] // int8 moveX [10], int8 moveY [11], uint8 flags [12], uint8 pad [13]
const canvas = document.getElementById('vizCanvas'); const canvas = document.getElementById('vizCanvas');
const ctx = canvas.getContext('2d'); const ctx = canvas.getContext('2d');
const TRAIL_LEN = 120; const TRAIL_LEN = 120;
@@ -707,7 +707,7 @@ let cursorX = canvas.width/2, cursorY = canvas.height/2, trail = [];
let vizPaused = true; let vizPaused = true;
let imuSubscribed = false; let imuSubscribed = false;
// ── Stream diagnostics ──────────────────────────────────────────────────────── // Stream diagnostics
let streamPktCount = 0; // packets received this second let streamPktCount = 0; // packets received this second
let streamPktTotal = 0; // lifetime packet count let streamPktTotal = 0; // lifetime packet count
let streamLastPktT = 0; // timestamp of last packet (for gap detection) let streamLastPktT = 0; // timestamp of last packet (for gap detection)
@@ -722,7 +722,7 @@ function streamDiagReset() {
function streamDiagPkt() { function streamDiagPkt() {
const now = Date.now(); const now = Date.now();
// Gap detection warn if >300ms since last packet while streaming // Gap detection - warn if >300ms since last packet while streaming
if (streamLastPktT) { if (streamLastPktT) {
const gap = now - streamLastPktT; const gap = now - streamLastPktT;
if (gap > 300) log(`[STREAM] gap ${gap}ms (pkt #${streamPktTotal})`, 'warn'); if (gap > 300) log(`[STREAM] gap ${gap}ms (pkt #${streamPktTotal})`, 'warn');
@@ -731,10 +731,10 @@ function streamDiagPkt() {
streamPktCount++; streamPktCount++;
streamPktTotal++; streamPktTotal++;
// Reset freeze watchdog 1.5s without a packet = freeze // Reset freeze watchdog - 1.5s without a packet = freeze
if (streamFreezeTimer) clearTimeout(streamFreezeTimer); if (streamFreezeTimer) clearTimeout(streamFreezeTimer);
streamFreezeTimer = setTimeout(() => { streamFreezeTimer = setTimeout(() => {
log(`[STREAM] FROZEN no packet for 1.5s (total rx: ${streamPktTotal})`, 'err'); log(`[STREAM] FROZEN - no packet for 1.5s (total rx: ${streamPktTotal})`, 'err');
streamFreezeTimer = null; streamFreezeTimer = null;
}, 1500); }, 1500);
@@ -750,7 +750,7 @@ function streamDiagPkt() {
// Roll compensation is done entirely in firmware (calibrateGyroBias computes // Roll compensation is done entirely in firmware (calibrateGyroBias computes
// rollSin/rollCos from boot-pose accel and applies the rotation before moveX/moveY). // rollSin/rollCos from boot-pose accel and applies the rotation before moveX/moveY).
// The web visualiser just uses moveX/moveY directly no re-rotation needed here. // The web visualiser just uses moveX/moveY directly - no re-rotation needed here.
function resetOrient() {} // kept for call-site compatibility function resetOrient() {} // kept for call-site compatibility
function vizUpdateIndicator() { function vizUpdateIndicator() {
@@ -782,7 +782,7 @@ async function vizSetPaused(paused) {
await chars.imuStream.stopNotifications(); await chars.imuStream.stopNotifications();
imuSubscribed = false; imuSubscribed = false;
streamDiagReset(); streamDiagReset();
document.getElementById('orientLabel').textContent = ' not streaming '; document.getElementById('orientLabel').textContent = '- not streaming -';
} catch(e) { log(`IMU stream stop failed: ${e.message}`,'err'); } } catch(e) { log(`IMU stream stop failed: ${e.message}`,'err'); }
} }
vizUpdateIndicator(); vizUpdateIndicator();
@@ -792,7 +792,7 @@ function parseImuStream(dv) {
let view; let view;
try { try {
view = dv instanceof DataView ? new DataView(dv.buffer, dv.byteOffset, dv.byteLength) : new DataView(dv); view = dv instanceof DataView ? new DataView(dv.buffer, dv.byteOffset, dv.byteLength) : new DataView(dv);
} catch(e) { log(`parseImuStream: DataView wrap failed ${e.message}`,'err'); return; } } catch(e) { log(`parseImuStream: DataView wrap failed - ${e.message}`,'err'); return; }
if (view.byteLength < 14) { if (view.byteLength < 14) {
const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength); const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
@@ -811,7 +811,7 @@ function parseImuStream(dv) {
moveX = view.getInt8(10); moveX = view.getInt8(10);
moveY = view.getInt8(11); moveY = view.getInt8(11);
flags = view.getUint8(12); flags = view.getUint8(12);
} catch(e) { log(`parseImuStream: parse error ${e.message}`,'err'); return; } } catch(e) { log(`parseImuStream: parse error - ${e.message}`,'err'); return; }
// Feed debug recorder (even when viz is paused) // Feed debug recorder (even when viz is paused)
feedDebugRow(gyroX, gyroZ, accelX, accelY, accelZ, moveX, moveY, flags); feedDebugRow(gyroX, gyroZ, accelX, accelY, accelZ, moveX, moveY, flags);
@@ -826,7 +826,7 @@ function parseImuStream(dv) {
updateAxisBar('gz', -gyroX, 30000); updateAxisBar('gz', -gyroX, 30000);
if (!idle) { if (!idle) {
// moveX/moveY are already roll-corrected by firmware use them directly // moveX/moveY are already roll-corrected by firmware - use them directly
cursorX = Math.max(4, Math.min(canvas.width - 4, cursorX + moveX * 1.5)); cursorX = Math.max(4, Math.min(canvas.width - 4, cursorX + moveX * 1.5));
cursorY = Math.max(4, Math.min(canvas.height - 4, cursorY + moveY * 1.5)); cursorY = Math.max(4, Math.min(canvas.height - 4, cursorY + moveY * 1.5));
} }
@@ -894,7 +894,7 @@ function drawInitState() {
ctx.fillStyle=cssVar('--canvas-idle-text');ctx.font='10px Share Tech Mono,monospace'; ctx.fillStyle=cssVar('--canvas-idle-text');ctx.font='10px Share Tech Mono,monospace';
ctx.textAlign='center';ctx.fillText('connect to activate stream',W/2,H/2+4);ctx.textAlign='left'; ctx.textAlign='center';ctx.fillText('connect to activate stream',W/2,H/2+4);ctx.textAlign='left';
} }
// ── 3D Orientation Viewer ───────────────────────────────────────────────────── // 3D Orientation Viewer
// Device box: L=115mm (X), W=36mm (Y), H=20mm (Z) // Device box: L=115mm (X), W=36mm (Y), H=20mm (Z)
// Complementary filter mirrors firmware: α=0.96, dt from packet rate (~50ms) // Complementary filter mirrors firmware: α=0.96, dt from packet rate (~50ms)
const ORIENT_ALPHA = 0.96; const ORIENT_ALPHA = 0.96;
@@ -932,7 +932,7 @@ function initOrientViewer() {
orientEdges = new THREE.LineSegments(new THREE.EdgesGeometry(geo), edgeMat); orientEdges = new THREE.LineSegments(new THREE.EdgesGeometry(geo), edgeMat);
orientMesh.add(orientEdges); orientMesh.add(orientEdges);
// "Front" face marker small arrow along +X (length axis) // "Front" face marker - small arrow along +X (length axis)
const arrowGeo = new THREE.ConeGeometry(0.02, 0.07, 6); const arrowGeo = new THREE.ConeGeometry(0.02, 0.07, 6);
arrowGeo.rotateZ(-Math.PI / 2); arrowGeo.rotateZ(-Math.PI / 2);
arrowGeo.translate(DEVICE_L / 2 + 0.04, 0, 0); arrowGeo.translate(DEVICE_L / 2 + 0.04, 0, 0);
@@ -982,7 +982,7 @@ function orientFeedIMU(ax, ay, az, gyX_mDPS, gyZ_mDPS) {
qAccel.copy(orientQ); qAccel.copy(orientQ);
} }
// Gyro integration firmware sends gyroX (pitch) and gyroZ (yaw), mDPS // Gyro integration - firmware sends gyroX (pitch) and gyroZ (yaw), mDPS
// Map to Three.js axes: gyroZ→world Y, gyroX→world X // Map to Three.js axes: gyroZ→world Y, gyroX→world X
const gyRad = gyX_mDPS * (Math.PI / 180) / 1000; const gyRad = gyX_mDPS * (Math.PI / 180) / 1000;
const gzRad = gyZ_mDPS * (Math.PI / 180) / 1000; const gzRad = gyZ_mDPS * (Math.PI / 180) / 1000;
@@ -1001,7 +1001,7 @@ function orientFeedIMU(ax, ay, az, gyX_mDPS, gyZ_mDPS) {
orientRenderer.render(orientScene, orientCamera); orientRenderer.render(orientScene, orientCamera);
} }
// ── Theme ───────────────────────────────────────────────────────────────────── // Theme
const THEMES = ['auto','dark','light']; const THEMES = ['auto','dark','light'];
const THEME_LABELS = {auto:'AUTO',dark:'DARK',light:'LIGHT'}; const THEME_LABELS = {auto:'AUTO',dark:'DARK',light:'LIGHT'};
let themeIdx = 0; let themeIdx = 0;
+8 -8
View File
@@ -39,7 +39,7 @@
<main id="mainContent"> <main id="mainContent">
<!-- ── col-left: cursor motion ──────────────────────────────── --> <!-- col-left: cursor motion -->
<div class="col-left"> <div class="col-left">
<div class="section-label">Motion Parameters</div> <div class="section-label">Motion Parameters</div>
@@ -51,7 +51,7 @@
<div class="param-value" id="valSensitivity">600</div> <div class="param-value" id="valSensitivity">600</div>
</div> </div>
<div class="param"> <div class="param">
<div><div class="param-label">Dead Zone</div><div class="param-desc">Noise floor (rad/s) raise to reduce drift</div></div> <div><div class="param-label">Dead Zone</div><div class="param-desc">Noise floor (rad/s) - raise to reduce drift</div></div>
<input type="range" id="slDeadZone" min="0.005" max="0.2" step="0.005" value="0.06" <input type="range" id="slDeadZone" min="0.005" max="0.2" step="0.005" value="0.06"
oninput="updateDisplay('deadZone',this.value)" onchange="writeConfigBlob()"> oninput="updateDisplay('deadZone',this.value)" onchange="writeConfigBlob()">
<div class="param-value" id="valDeadZone">0.060</div> <div class="param-value" id="valDeadZone">0.060</div>
@@ -134,7 +134,7 @@
</div><!-- /col-left --> </div><!-- /col-left -->
<!-- ── col-mid: button configuration ───────────────────────── --> <!-- col-mid: button configuration -->
<div class="col-mid"> <div class="col-mid">
<div class="section-label">Tap Configuration</div> <div class="section-label">Tap Configuration</div>
@@ -146,7 +146,7 @@
</div> </div>
</div> </div>
<div class="param"> <div class="param">
<div><div class="param-label">Tap Freeze Sensitivity</div><div class="param-desc">Jerk² threshold lower = more aggressive cursor freeze during taps</div></div> <div><div class="param-label">Tap Freeze Sensitivity</div><div class="param-desc">Jerk² threshold - lower = more aggressive cursor freeze during taps</div></div>
<input type="range" id="slJerkThreshold" min="500" max="10000" step="100" value="2000" <input type="range" id="slJerkThreshold" min="500" max="10000" step="100" value="2000"
oninput="updateDisplay('jerkThreshold',this.value)" onchange="writeConfigBlob()"> oninput="updateDisplay('jerkThreshold',this.value)" onchange="writeConfigBlob()">
<div class="param-value" id="valJerkThreshold">2000</div> <div class="param-value" id="valJerkThreshold">2000</div>
@@ -183,7 +183,7 @@
<div class="section-label">Physical Buttons</div> <div class="section-label">Physical Buttons</div>
<div class="card"> <div class="card">
<!-- ── XIAO nRF52840 Sense pin diagram ─────────────────── --> <!-- XIAO nRF52840 Sense pin diagram -->
<div class="xiao-wrap"> <div class="xiao-wrap">
<svg id="xiaoSvg" viewBox="0 0 200 278" xmlns="http://www.w3.org/2000/svg" style="display:block;width:100%;max-width:200px"> <svg id="xiaoSvg" viewBox="0 0 200 278" xmlns="http://www.w3.org/2000/svg" style="display:block;width:100%;max-width:200px">
<!-- USB-C connector --> <!-- USB-C connector -->
@@ -301,7 +301,7 @@
<div class="cmd-grid"> <div class="cmd-grid">
<button class="cmd-btn calibrate" id="btnCal" onclick="sendCalibrate()" disabled> <button class="cmd-btn calibrate" id="btnCal" onclick="sendCalibrate()" disabled>
<span class="cmd-icon"></span><span>Calibrate Gyro</span> <span class="cmd-icon"></span><span>Calibrate Gyro</span>
<span class="cmd-desc">Hold device still recalculates bias + records cal temperature.</span> <span class="cmd-desc">Hold device still - recalculates bias + records cal temperature.</span>
</button> </button>
<button class="cmd-btn reset" id="btnReset" onclick="confirmReset()" disabled> <button class="cmd-btn reset" id="btnReset" onclick="confirmReset()" disabled>
<span class="cmd-icon"></span><span>Factory Reset</span> <span class="cmd-icon"></span><span>Factory Reset</span>
@@ -314,7 +314,7 @@
</div><!-- /col-mid --> </div><!-- /col-mid -->
<!-- ── col-right: live monitoring ───────────────────────────── --> <!-- col-right: live monitoring -->
<div class="col-right"> <div class="col-right">
<div class="section-label">Live Cursor Visualiser</div> <div class="section-label">Live Cursor Visualiser</div>
@@ -350,7 +350,7 @@
<div class="section-label">Device Orientation</div> <div class="section-label">Device Orientation</div>
<div class="card orient-card"> <div class="card orient-card">
<canvas id="orientCanvas"></canvas> <canvas id="orientCanvas"></canvas>
<div style="font-size:9px;color:var(--label);text-align:center;margin-top:6px" id="orientLabel"> not streaming </div> <div style="font-size:9px;color:var(--label);text-align:center;margin-top:6px" id="orientLabel">- not streaming -</div>
</div> </div>
<div class="section-label">Live Telemetry</div> <div class="section-label">Live Telemetry</div>
+5 -5
View File
@@ -34,7 +34,7 @@
--tap-right: rgba(255,61,113,0.35); --tap-right: rgba(255,61,113,0.35);
} }
/* ── Light theme (explicit) ──────────────────────────────────────────────── */ /* Light theme (explicit) */
:root.theme-light { :root.theme-light {
--bg: #f0f2f5; --bg: #f0f2f5;
--panel: #ffffff; --panel: #ffffff;
@@ -66,7 +66,7 @@
} }
/* ── Auto light (OS hint; explicit class overrides) ──────────────────────── */ /* Auto light (OS hint; explicit class overrides) */
@media (prefers-color-scheme: light) { @media (prefers-color-scheme: light) {
:root:not(.theme-dark) { :root:not(.theme-dark) {
--bg: #f0f2f5; --bg: #f0f2f5;
@@ -153,7 +153,7 @@
.col-mid { display:grid; gap:12px; } .col-mid { display:grid; gap:12px; }
.col-right { display:grid; gap:12px; position:sticky; top:80px; } .col-right { display:grid; gap:12px; position:sticky; top:80px; }
/* ── XIAO pin diagram ─────────────────────────────────────── */ /* XIAO pin diagram */
.xiao-wrap { display:flex; flex-direction:column; align-items:center; padding:8px 0 14px; } .xiao-wrap { display:flex; flex-direction:column; align-items:center; padding:8px 0 14px; }
.pin-legend { display:flex; gap:20px; justify-content:center; font-family:var(--mono); font-size:9px; margin-top:10px; letter-spacing:0.08em; } .pin-legend { display:flex; gap:20px; justify-content:center; font-family:var(--mono); font-size:9px; margin-top:10px; letter-spacing:0.08em; }
.pleg.left { color:var(--ok); } .pleg.left { color:var(--ok); }
@@ -161,7 +161,7 @@
.pleg.mid { color:var(--accent); } .pleg.mid { color:var(--accent); }
.xiao-divider { border:none; border-top:1px solid var(--border); margin:0 -20px 12px; } .xiao-divider { border:none; border-top:1px solid var(--border); margin:0 -20px 12px; }
/* ── Responsive ───────────────────────────────────────────── */ /* Responsive */
@media (max-width:1100px) { @media (max-width:1100px) {
main { grid-template-columns:1fr 380px; grid-template-rows:auto auto; } main { grid-template-columns:1fr 380px; grid-template-rows:auto auto; }
.col-left { grid-column:1; grid-row:1; } .col-left { grid-column:1; grid-row:1; }
@@ -288,7 +288,7 @@
.btn-confirm { border-color:var(--accent2); color:var(--accent2); } .btn-confirm { border-color:var(--accent2); color:var(--accent2); }
.btn-confirm:hover { background:var(--accent2); color:var(--bg); } .btn-confirm:hover { background:var(--accent2); color:var(--bg); }
/* ── Debug modal ────────────────────────────────────────────────────────── */ /* Debug modal */
.debug-modal { max-width:720px; padding:20px; border-color:var(--accent); } .debug-modal { max-width:720px; padding:20px; border-color:var(--accent); }
.debug-modal h3 { color:var(--accent); margin-bottom:0; } .debug-modal h3 { color:var(--accent); margin-bottom:0; }
.debug-header { display:flex; justify-content:space-between; align-items:center; margin-bottom:14px; } .debug-header { display:flex; justify-content:space-between; align-items:center; margin-bottom:14px; }