Remove unnecessary comments, clean up code

This commit is contained in:
2026-03-03 21:38:32 +01:00
parent cb433f76c9
commit 8e9a3712ac
16 changed files with 197 additions and 331 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
- **6-DoF gyro + accelerometer** via LSM6DS3 with complementary filter
- **Hardware tap detection** single tap = left click, double tap = right click
- **BLE HID mouse** works natively on Windows, macOS, Linux, Android, iOS
- **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
- **Flash persistence** config survives power cycles (LittleFS)
- **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
- **Temperature compensation** gyro drift correction by Δ temperature since last calibration
- **Auto-recalibration** recalibrates automatically after 5 minutes of idle
- **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)
- **Hardware tap detection** - single tap = left click, double tap = right click
- **BLE HID mouse** - works natively on Windows, macOS, Linux, Android, iOS
- **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
- **Flash persistence** - config survives power cycles (LittleFS)
- **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
- **Temperature compensation** - gyro drift correction by Δ temperature since last calibration
- **Auto-recalibration** - recalibrates automatically after 5 minutes of idle
- **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)
## Hardware
@@ -26,22 +26,22 @@ A BLE HID mouse that uses the onboard IMU of a **Seeed XIAO nRF52840 Sense** to
## 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 |
|---|---|---|
| Blue | Single pulse every 10 s | BLE connected (heartbeat) |
| Green | Single pulse every 10 s | Advertising / not connected (heartbeat) |
| Green | Rapid flutter (~10 Hz) | Gyro calibration in progress |
| Red | Fast blink (continuous) | IMU init failed hardware fault |
| Red | 3 slow blinks on boot | Boot-loop detected entered safe mode |
| Red | Fast blink (continuous) | IMU init failed - hardware fault |
| Red | 3 slow blinks on boot | Boot-loop detected - entered safe mode |
| Red | 6 rapid blinks | Battery critically low (< 3.10 V) |
> **Blue** = BLE-related state. **Green** = device activity. **Red** = fault only.
## 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:**
@@ -56,8 +56,8 @@ Open `web/index.html` in Chrome or Edge (desktop). Requires Web Bluetooth — en
**Commands:**
- **Calibrate Gyro** recalculates bias offset; hold the device still on a flat surface for ~1 s
- **Factory Reset** wipes flash config, restores defaults
- **Calibrate Gyro** - recalculates bias offset; hold the device still on a flat surface for ~1 s
- **Factory Reset** - wipes flash config, restores defaults
## Building
+1 -1
View File
@@ -255,7 +255,7 @@ base = base.fuse(
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
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
; Core : Adafruit nRF52 Arduino (via Seeed platform-seeedboards)
; Flash : adafruit-nrfutil over USB serial (same as Arduino IDE)
@@ -6,7 +6,7 @@
; First-time setup:
; pip install adafruit-nrfutil <- upload tool (once, globally)
; pio run -t upload <- build + flash
; ──────────────────────────────────────────────────────────────────────────────
;
[platformio]
src_dir = source
@@ -16,7 +16,7 @@ platform = https://github.com/Seeed-Studio/platform-seeedboards.git
board = seeed-xiao-afruitnrf52-nrf52840
framework = arduino
; ── Upload ────────────────────────────────────────────────────────────────────
; Upload
; The XIAO uses a UF2 bootloader that accepts firmware via adafruit-nrfutil.
; Double-tap the reset button to enter bootloader (red LED pulses) before
; 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:
; upload_port = COM3
; ── Build scripts ─────────────────────────────────────────────────────────────
; Build scripts
extra_scripts = pre:scripts/git_hash.py
; ── Build flags ───────────────────────────────────────────────────────────────
; Build flags
build_flags =
-DARDUINO_Seeed_XIAO_nRF52840_Sense
-DNRF52840_XXAA
-DTARGET_SEEED_XIAO_NRF52840_SENSE
; ── Libraries ─────────────────────────────────────────────────────────────────
; Libraries
; bluefruit.h, Adafruit_LittleFS.h, InternalFileSystem.h are bundled with
; the Adafruit nRF52 core and do NOT need to be listed here.
; Only external libraries are listed:
lib_deps =
Seeed-Studio/Seeed Arduino LSM6DS3 @ ^2.0.3
; ── Serial monitor ────────────────────────────────────────────────────────────
; Serial monitor
monitor_speed = 115200
+4 -4
View File
@@ -8,7 +8,7 @@ Usage: referenced from platformio.ini as:
"""
import subprocess, os, re
Import("env") # noqa: F821 PlatformIO injects this
Import("env") # noqa: F821 - PlatformIO injects this
def get_git_hash():
try:
@@ -27,14 +27,14 @@ def get_git_hash():
git_hash = get_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
# ── Write web/version.js ──────────────────────────────────────────────────────
# Write web/version.js
web_dir = os.path.join(env.subst("$PROJECT_DIR"), "web") # noqa: F821
ver_file = os.path.join(web_dir, "version.js")
os.makedirs(web_dir, exist_ok=True)
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")
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_READ, INPUT);
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);
}
@@ -34,7 +34,7 @@ void updateBattery() {
float v = readBatteryVoltage(); int pct = batteryPercent(v);
bool chg = (digitalRead(PIN_CHG) == LOW);
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.
if (Bluefruit.connected()) blebas.write(pct);
lastChargeStatus = status;
@@ -44,7 +44,7 @@ void updateBattery() {
const char* st[] = {"discharging","charging","full"};
Serial.print("[BATT] "); Serial.print(v,2); Serial.print("V ");
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.
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); }
+10 -10
View File
@@ -8,7 +8,7 @@
using namespace Adafruit_LittleFS_Namespace;
extern File cfgFile;
// ─── BLE Config Service objects ───────────────────────────────────────────────
// BLE Config Service objects
#ifndef GIT_HASH
#define GIT_HASH "unknown"
#endif
@@ -26,7 +26,7 @@ BLECharacteristic cfgGitHash (0x1239); // GitHash R 8 bytes (7-char ha
#endif
#endif
// ─── Charge mode ──────────────────────────────────────────────────────────────
// Charge mode
void applyChargeMode(ChargeMode mode) {
switch (mode) {
case CHARGE_OFF: pinMode(PIN_HICHG, INPUT_PULLUP); break;
@@ -37,7 +37,7 @@ void applyChargeMode(ChargeMode mode) {
Serial.print("[CHG] "); Serial.println(n[mode]);
}
// ─── Config persistence ───────────────────────────────────────────────────────
// Config persistence
void loadConfig() {
InternalFS.begin();
cfgFile.open(CONFIG_FILENAME, FILE_O_READ);
@@ -57,11 +57,11 @@ void saveConfig() {
cfgFile.open(CONFIG_FILENAME, FILE_O_WRITE);
if (cfgFile) { cfgFile.write((uint8_t*)&cfg, sizeof(cfg)); cfgFile.close(); }
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"); }
}
// ─── ConfigBlob push ─────────────────────────────────────────────────────────
// ConfigBlob push
#ifdef FEATURE_CONFIG_SERVICE
void pushConfigBlob() {
ConfigBlob b;
@@ -103,7 +103,7 @@ void factoryReset() {
Serial.println("[CFG] Factory reset complete");
}
// ─── BLE callbacks ────────────────────────────────────────────────────────────
// BLE callbacks
#ifdef FEATURE_CONFIG_SERVICE
void onConfigBlobWrite(uint16_t h, BLECharacteristic* c, uint8_t* d, uint16_t l) {
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)
#endif
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(" tapThr="); Serial.print(cfg.tapThreshold);
Serial.print(" tapAction="); Serial.println(cfg.tapAction);
@@ -153,7 +153,7 @@ void onImuStreamCccd(uint16_t conn_hdl, BLECharacteristic* chr, uint16_t value)
}
#endif
// ─── BLE config service setup ─────────────────────────────────────────────────
// BLE config service setup
void setupConfigService() {
cfgService.begin();
@@ -170,7 +170,7 @@ void setupConfigService() {
cfgCommand.setWriteCallback(onCommandWrite);
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.setPermission(SECMODE_OPEN, SECMODE_NO_ACCESS);
cfgGitHash.setFixedLen(8);
@@ -206,7 +206,7 @@ void setupConfigService() {
}
#endif // FEATURE_CONFIG_SERVICE
// ─── Telemetry push ───────────────────────────────────────────────────────────
// Telemetry push
#ifdef FEATURE_TELEMETRY
void pushTelemetry(unsigned long now) {
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
// ─── Setup ────────────────────────────────────────────────────────────────────
// Setup
void setupPhysicalButtons() {
// Release any held physical buttons before reconfiguring
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.
// Uses active-low logic: INPUT_PULLUP, button connects pin to GND.
void processPhysicalButtons() {
+18 -18
View File
@@ -1,7 +1,7 @@
#pragma once
#include <Arduino.h>
// ─── Feature Flags ────────────────────────────────────────────────────────────
// Feature Flags
#define FEATURE_CONFIG_SERVICE
#define FEATURE_TELEMETRY
#define FEATURE_IMU_STREAM
@@ -12,10 +12,10 @@
#define FEATURE_BOOT_LOOP_DETECT
#define FEATURE_PHYSICAL_BUTTONS
// ─── Debug ────────────────────────────────────────────────────────────────────
// Debug
// #define DEBUG
// ─── ATT table size ───────────────────────────────────────────────────────────
// ATT table size
#define _ATT_BASE 900
#ifdef FEATURE_CONFIG_SERVICE
#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 (ATT_TABLE_SIZE_CALC < 1536 ? 1536 : ATT_TABLE_SIZE_CALC)
// ─── IMU register addresses ───────────────────────────────────────────────────
// IMU register addresses
#define REG_CTRL1_XL 0x10
#define REG_TAP_CFG 0x58
#define REG_TAP_THS_6D 0x59
@@ -46,20 +46,20 @@
#define REG_OUT_TEMP_L 0x20
#define REG_OUT_TEMP_H 0x21
// ─── Pins ─────────────────────────────────────────────────────────────────────
// Pins
#define PIN_VBAT_ENABLE (14)
#define PIN_VBAT_READ (32)
#define PIN_CHG (23)
#define PIN_HICHG (22)
// ─── Persistence ──────────────────────────────────────────────────────────────
// Persistence
#define CONFIG_FILENAME "/imu_mouse_cfg.bin"
#define CONFIG_MAGIC 0xDEAD123DUL
// ─── Physical button sentinel ─────────────────────────────────────────────────
// Physical button sentinel
#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
// 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)
@@ -67,12 +67,12 @@
#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)
// ─── Enums ────────────────────────────────────────────────────────────────────
// Enums
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 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).
// Modifier byte: bit0=Ctrl, bit1=Shift, bit2=Alt, bit3=GUI (same as HID modifier byte).
enum TapAction : uint8_t {
@@ -82,7 +82,7 @@ enum TapAction : uint8_t {
TAP_ACTION_KEY = 3,
};
// ─── Config (stored in flash) ─────────────────────────────────────────────────
// Config (stored in flash)
struct Config {
uint32_t magic;
float sensitivity;
@@ -97,7 +97,7 @@ struct Config {
uint8_t tapMod; // HID modifier byte (used when tapAction == TAP_ACTION_KEY)
float jerkThreshold; // jerk² threshold for tap-freeze detection
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 btnRightPin;
uint8_t btnMiddlePin;
@@ -105,7 +105,7 @@ struct Config {
extern Config cfg;
extern const Config CFG_DEFAULTS;
// ─── ConfigBlob (over BLE, 25 bytes) ─────────────────────────────────────────
// ConfigBlob (over BLE, 25 bytes)
struct __attribute__((packed)) ConfigBlob {
float sensitivity; // [0]
float deadZone; // [4]
@@ -119,14 +119,14 @@ struct __attribute__((packed)) ConfigBlob {
uint8_t tapMod; // [18] HID modifier
uint8_t tapFreezeEnabled; // [19] 1 = enable jerk-based cursor freeze during taps
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 btnRightPin; // [26]
uint8_t btnMiddlePin; // [27]
};
static_assert(sizeof(ConfigBlob) == 28, "ConfigBlob must be 28 bytes");
// ─── TelemetryPacket (24 bytes) ───────────────────────────────────────────────
// TelemetryPacket (24 bytes)
#ifdef FEATURE_TELEMETRY
struct __attribute__((packed)) TelemetryPacket {
uint32_t uptimeSeconds; // [0]
@@ -143,7 +143,7 @@ static_assert(sizeof(TelemetryPacket) == 28, "TelemetryPacket must be 28 bytes")
extern TelemetryPacket telem;
#endif
// ─── ImuPacket (14 bytes) ─────────────────────────────────────────────────────
// ImuPacket (14 bytes)
#ifdef FEATURE_IMU_STREAM
struct __attribute__((packed)) ImuPacket {
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");
#endif
// ─── Tuning constants ─────────────────────────────────────────────────────────
// Tuning constants
extern const float ALPHA;
extern const int LOOP_RATE_MS;
extern const int BIAS_SAMPLES;
@@ -185,7 +185,7 @@ extern const float BATT_CRITICAL;
extern const unsigned long AUTO_RECAL_MS;
#endif
// ─── Global state ─────────────────────────────────────────────────────────────
// Global state
extern float angleX, angleY;
extern float accumX, accumY;
extern float gravX, gravY, gravZ;
+4 -4
View File
@@ -4,7 +4,7 @@
LSM6DS3 imu(I2C_MODE, 0x6A);
// ─── I2C helpers ──────────────────────────────────────────────────────────────
// I2C helpers
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)
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;
}
// ─── Temperature ──────────────────────────────────────────────────────────────
// Temperature
float readIMUTemp() {
int16_t raw = (int16_t)((imuReadReg(REG_OUT_TEMP_H) << 8) | imuReadReg(REG_OUT_TEMP_L));
return 25.0f + (float)raw / 256.0f;
}
// ─── Calibration ──────────────────────────────────────────────────────────────
// Calibration
void calibrateGyroBias() {
Serial.println("[CAL] Hold still...");
double sx=0, sy=0, sz=0;
@@ -51,7 +51,7 @@ void calibrateGyroBias() {
Serial.print(","); Serial.println(biasGZ,4);
}
// ─── Motion curve ─────────────────────────────────────────────────────────────
// Motion curve
float applyCurve(float v) {
switch (cfg.curve) {
case CURVE_SQUARE: return (v >= 0 ? 1.f : -1.f) * v * v;
+24 -65
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):
* leave only FEATURE_BATTERY_MONITOR + FEATURE_BOOT_LOOP_DETECT
*
* RECOMMENDED first test:
* 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:
* FEATURE_TELEMETRY requires FEATURE_CONFIG_SERVICE
* FEATURE_IMU_STREAM requires FEATURE_CONFIG_SERVICE
@@ -40,24 +25,24 @@
#include "Wire.h"
#include "sleep.h"
// ─── Boot-loop detection ──────────────────────────────────────────────────────
// Boot-loop detection
#ifdef FEATURE_BOOT_LOOP_DETECT
static uint32_t __attribute__((section(".noinit"))) bootCount;
static uint32_t __attribute__((section(".noinit"))) bootMagic;
#endif
// ─── BLE Standard Services ────────────────────────────────────────────────────
// BLE Standard Services
BLEDis bledis;
BLEHidAdafruit blehid;
#ifdef FEATURE_BATTERY_MONITOR
BLEBas blebas;
#endif
// ─── Persistence ──────────────────────────────────────────────────────────────
// Persistence
using namespace Adafruit_LittleFS_Namespace;
File cfgFile(InternalFS);
// ─── Config definitions ───────────────────────────────────────────────────────
// Config definitions
Config cfg;
const Config CFG_DEFAULTS = {
CONFIG_MAGIC, 600.0f, 0.060f, 0.08f, CURVE_LINEAR, 0x00, CHARGE_SLOW,
@@ -66,12 +51,12 @@ const Config CFG_DEFAULTS = {
/*btnLeftPin=*/BTN_PIN_NONE, /*btnRightPin=*/BTN_PIN_NONE, /*btnMiddlePin=*/BTN_PIN_NONE
};
// ─── Telemetry definition ─────────────────────────────────────────────────────
// Telemetry definition
#ifdef FEATURE_TELEMETRY
TelemetryPacket telem = {};
#endif
// ─── Tuning constants ─────────────────────────────────────────────────────────
// Tuning constants
const float ALPHA = 0.96f;
const int LOOP_RATE_MS = 10;
const int BIAS_SAMPLES = 200;
@@ -97,7 +82,7 @@ const float BATT_CRITICAL = 3.10f;
const unsigned long AUTO_RECAL_MS = 5UL * 60UL * 1000UL;
#endif
// ─── Global state definitions ─────────────────────────────────────────────────
// Global state definitions
float angleX = 0, angleY = 0;
float accumX = 0, accumY = 0;
// Low-pass filtered gravity estimate in device frame (for roll-independent axis projection)
@@ -132,10 +117,7 @@ uint32_t loopStalls = 0; // loop iterations where dt > 20ms (behind sch
bool pendingCal = false;
bool pendingReset = false;
// ── Jerk-based shock detection freeze cursor during tap impacts ────────────
// 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.
// Jerk-based shock detection - freeze cursor during tap impacts, doesn't work well yet!
unsigned long shockFreezeUntil = 0;
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
@@ -161,7 +143,7 @@ unsigned long bootStartMs = 0;
bool safeMode = false;
bool bootCountCleared = false;
// ─── Advertising ─────────────────────────────────────────────────────────────
// Advertising
static void startAdvertising() {
Bluefruit.Advertising.addFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE);
Bluefruit.Advertising.addTxPower();
@@ -177,7 +159,7 @@ static void startAdvertising() {
Bluefruit.Advertising.start(0);
}
// ─── Setup ────────────────────────────────────────────────────────────────────
// Setup
void setup() {
Serial.begin(115200);
unsigned long serialWait = millis();
@@ -188,14 +170,14 @@ void setup() {
pinMode(LED_GREEN, OUTPUT); digitalWrite(LED_GREEN, HIGH);
pinMode(LED_BLUE, OUTPUT); digitalWrite(LED_BLUE, HIGH);
// ── Boot-loop detection ───────────────────────────────────────────────────
// Boot-loop detection
#ifdef FEATURE_BOOT_LOOP_DETECT
if (bootMagic != 0xCAFEBABE) { bootMagic = 0xCAFEBABE; bootCount = 0; }
bootCount++;
Serial.print("[BOOT] count="); Serial.println(bootCount);
if (bootCount >= 3) {
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);
for (int i=0; i<3; i++) { digitalWrite(LED_RED,LOW); delay(150); digitalWrite(LED_RED,HIGH); delay(150); } // fault: red
}
@@ -214,7 +196,7 @@ void setup() {
Bluefruit.begin(1, 0);
Bluefruit.setTxPower(4);
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()
if (imu.begin() != 0) {
@@ -242,8 +224,6 @@ void setup() {
// Seed previous-accel for jerk detection so first frame doesn't spike
prevAx = imu.readFloatAccelX(); prevAy = imu.readFloatAccelY(); prevAz = imu.readFloatAccelZ();
// Sleep manager init: must come after calibrateGyroBias() and imu.begin().
// Unconditional — sleep.h is always included, no feature flag needed.
sleepManagerInit();
bledis.setManufacturer("Seeed Studio");
@@ -266,7 +246,7 @@ void setup() {
#endif
startAdvertising();
Serial.print("[OK] Advertising features:");
Serial.print("[OK] Advertising - features:");
#ifdef FEATURE_CONFIG_SERVICE
Serial.print(" CFG");
#endif
@@ -301,7 +281,7 @@ void setup() {
lastTime = lastBattTime = lastHeartbeat = lastTelemetry = millis();
}
// ─── Loop ─────────────────────────────────────────────────────────────────────
// Loop
void loop() {
unsigned long now = millis();
@@ -309,7 +289,7 @@ void loop() {
#ifdef FEATURE_BOOT_LOOP_DETECT
if (!bootCountCleared && (now - bootStartMs >= BOOT_SAFE_MS)) {
bootCount = 0; bootCountCleared = true;
Serial.println("[BOOT] Stable counter cleared");
Serial.println("[BOOT] Stable - counter cleared");
}
#endif
@@ -341,11 +321,6 @@ void loop() {
#ifdef FEATURE_PHYSICAL_BUTTONS
processPhysicalButtons();
#endif
// Sleep manager runs every iteration — must not be gated by LOOP_RATE_MS
// because it needs to catch the imuWakeFlag set by the ISR promptly.
// Pass idle=false when in IMU_LP (idleFrames is stale since gyro reads
// are skipped); the manager tracks its own idle timestamp internally.
{
bool idle_for_sleep = (sleepStage == SLEEP_IMU_LP) ? true
: (idleFrames >= IDLE_FRAMES);
@@ -369,8 +344,6 @@ void loop() {
#endif
// Gyro reads with optional temperature compensation.
// (sleepManagerUpdate above already returns early when in IMU_LP/DEEP)
float correction = 0.0f;
#ifdef FEATURE_TEMP_COMPENSATION
if (cfg.featureFlags & FLAG_TEMP_COMP_ENABLED)
@@ -384,17 +357,14 @@ void loop() {
float ay = imu.readFloatAccelY();
float az = imu.readFloatAccelZ();
// ── Jerk-based shock detection freeze cursor during tap impacts ────────
// Jerk = da/dt. Normal rotation = smooth accel changes (low jerk);
// a tap is a sharp impulse (very high jerk).
// Jerk-based shock detection - freeze cursor during tap impacts, doesn't work well yet
float jx = (ax - prevAx) / dt, jy = (ay - prevAy) / dt, jz = (az - prevAz) / dt;
float jerkSq = jx*jx + jy*jy + jz*jz;
prevAx = ax; prevAy = ay; prevAz = az;
bool shocked = cfg.tapFreezeEnabled && ((jerkSq > cfg.jerkThreshold) || (now < shockFreezeUntil));
if (cfg.tapFreezeEnabled && jerkSq > cfg.jerkThreshold) shockFreezeUntil = now + SHOCK_FREEZE_MS;
// Complementary filter — gx=pitch axis, gz=yaw axis on this board layout
// During shock: gyro-only integration to avoid accel spike corrupting angles
// Complementary filter
if (shocked) {
angleX += gx * dt;
angleY += gz * dt;
@@ -403,12 +373,7 @@ void loop() {
angleY = ALPHA*(angleY + gz*dt) + (1.0f - ALPHA)*atan2f(ay, sqrtf(ax*ax + az*az));
}
// ── 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.
// Gravity-based axis decomposition
const float GRAV_LP = 0.05f;
if (!shocked) {
gravX += GRAV_LP * (ax - gravX);
@@ -420,8 +385,6 @@ void loop() {
if (gN < 0.3f) gN = 1.0f;
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 rN = sqrtf(ry*ry + rz*rz);
if (rN < 0.01f) { ry = -1.0f; rz = 0.0f; rN = 1.0f; }
@@ -433,11 +396,9 @@ void loop() {
float pitchRate = -(gy*ry + gz*rz);
// 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 fPitch = (fabsf(pitchRate) > cfg.deadZone * 3.0f) ? pitchRate : 0.0f;
// DIAG: print every 500ms to debug gravity projection — remove when confirmed
#ifdef DEBUG
{ static unsigned long lastDiag = 0;
if (now - lastDiag >= 500) { lastDiag = now;
@@ -456,18 +417,16 @@ void loop() {
#ifdef FEATURE_AUTO_RECAL
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;
}
#endif
// (sleep manager already called above, before LOOP_RATE_MS gate)
int8_t moveX = 0, moveY = 0;
uint8_t flags = 0;
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;
flags |= 0x08; // bit3 = shock freeze active
} else if (idle) {
@@ -491,7 +450,7 @@ void loop() {
lastImuStream = now;
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 {
ImuPacket pkt;
pkt.gyroX_mDPS = (int16_t)constrain(gx*(180.f/PI)*1000.f, -32000, 32000);
@@ -512,7 +471,7 @@ void loop() {
if (streamConsecFails >= STREAM_BACKOFF_THRESH) {
streamBackoffUntil = now + STREAM_BACKOFF_MS;
streamConsecFails = 0;
Serial.print("[STREAM] TX congested backing off ");
Serial.print("[STREAM] TX congested - backing off ");
Serial.print(STREAM_BACKOFF_MS); Serial.println("ms");
}
}
+22 -34
View File
@@ -1,8 +1,3 @@
/*
* sleep.cpp — IMU Mouse low-power manager (LSM6DS3TR-C + nRF52840)
* See sleep.h for full documentation.
*/
#include "sleep.h"
#include "imu.h" // config.h REG_* macros
#include <bluefruit.h> // sd_app_evt_wait()
@@ -15,7 +10,6 @@
#define SLP_WAKE_UP_DUR 0x5C
#define SLP_WAKE_UP_SRC 0x1B
// LSM6DS3 I2C address — SA0 tied LOW on XIAO Sense → 0x6A (NOT 0x6B)
#define LSM_ADDR 0x6A
#define XL_ODR_26HZ 0x20
@@ -33,14 +27,14 @@ static unsigned long lpEnteredMs = 0; // when IMU LP was entered (for recal
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 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)
// 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);
@@ -65,40 +59,37 @@ static void imuInt1ISR() {
static void armWakeupInterrupt() {
lsmWrite(SLP_WAKE_UP_DUR, (uint8_t)((SLEEP_WAKEUP_DUR & 0x03) << 4));
// Preserve bit7 (tap single/double enable) written by tap.cpp
// 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)
// 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);
// OR in INT1_WU (bit5), preserve tap routing bits
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.
// If INT1 is already high from a previous event, RISING will never fire
// because no low→high edge will occur. Reading WAKE_UP_SRC de-asserts INT1.
(void)lsmRead(SLP_WAKE_UP_SRC);
// Small delay to let the INT1 line settle low before we arm the edge detect
delay(2);
// Re-attach with RISING guaranteed clean edge now that latch is cleared
// 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; // discard any flag set before the re-arm
imuWakeFlag = false;
Serial.print("[SLEEP] armWakeup — TAP_CFG=0x"); Serial.print(lsmRead(REG_TAP_CFG), HEX);
#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
}
// Disarm — restore registers for normal HP operation
static void disarmWakeupInterrupt() {
// Restore SLOPE_FDS=1 for tap detection HP filter path
uint8_t tcfg = lsmRead(REG_TAP_CFG);
@@ -127,10 +118,10 @@ static void enterImuLP() {
lpEnteredMs = millis();
sleepStage = SLEEP_IMU_LP;
Serial.print("[SLEEP] IMU LP entered idle for ");
Serial.print("[SLEEP] IMU LP entered - idle for ");
Serial.print((millis() - idleEnteredMs) / 1000); Serial.println("s");
// Full register readback — confirms chip actually accepted all writes
#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);
@@ -139,10 +130,7 @@ static void enterImuLP() {
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);
// Expected when working:
// CTRL1_XL=0x2_ (ODR=26Hz, _ = FS bits) CTRL2_G=0x0_ (ODR=off)
// CTRL6_C bit4=1 (XL_HM_MODE) CTRL7_G bit7=1 (G_HM_MODE)
// TAP_CFG=0x80 MD1_CFG=0x20 WAKE_UP_THS=0x01
#endif
}
// Enter deep sleep
@@ -151,7 +139,7 @@ static void enterDeepSleep() {
if (sleepStage < SLEEP_IMU_LP) enterImuLP();
sleepStage = SLEEP_DEEP;
Serial.println("[SLEEP] Deep sleep WFE on INT1");
Serial.println("[SLEEP] Deep sleep - WFE on INT1");
Serial.flush();
digitalWrite(LED_RED, LOW); delay(80); digitalWrite(LED_RED, HIGH);
@@ -199,7 +187,7 @@ void sleepManagerWakeIMU() {
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.
// 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;
@@ -209,9 +197,9 @@ void sleepManagerWakeIMU() {
sleepStage = SLEEP_AWAKE;
if (needsRecal)
Serial.println("[SLEEP] Awake gyro settling, recal needed");
Serial.println("[SLEEP] Awake - gyro settling, recal needed");
else
Serial.println("[SLEEP] Awake short LP, reusing existing bias");
Serial.println("[SLEEP] Awake - short LP, reusing existing bias");
}
// Public: init
@@ -223,11 +211,11 @@ void sleepManagerInit() {
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)");
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("[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");
@@ -242,7 +230,7 @@ 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);
Serial.print("[SLEEP] INT1 fired - stage="); Serial.println((int)sleepStage);
if (sleepStage == SLEEP_DEEP || sleepStage == SLEEP_IMU_LP) {
sleepManagerWakeIMU();
} else {
@@ -269,12 +257,12 @@ bool sleepManagerUpdate(unsigned long nowMs, bool idle, bool bleConnected) {
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.
// 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("[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);
}
@@ -290,7 +278,7 @@ bool sleepManagerUpdate(unsigned long nowMs, bool idle, bool bleConnected) {
// AWAKE path
if (!idle) {
if (wasIdle) {
Serial.println("[SLEEP] Motion idle timer reset");
Serial.println("[SLEEP] Motion - idle timer reset");
}
wasIdle = false;
idleEnteredMs = 0;
+5 -75
View File
@@ -1,43 +1,7 @@
/*
* sleep.h — IMU Mouse low-power manager
* =====================================================================
* Two-stage sleep strategy for the Seeed XIAO nRF52840 Sense:
*
* STAGE 1 — IMU low-power (entered after SLEEP_IMU_IDLE_MS of no motion)
* • Gyroscope powered down (CTRL2_G ODR = 0000)
* • Accelerometer → LP 26 Hz (CTRL1_XL ODR = 0010, XL_HM_MODE=1)
* • LSM6DS3 wakeup-interrupt armed (MD1_CFG INT1_WU=1)
* • nRF52840 stays awake, BLE advertising/connected continues
* • Current: ~0.19 mA accel only vs ~0.90 mA combo HP
*
* STAGE 2 — System deep sleep (entered after SLEEP_DEEP_IDLE_MS of no motion)
* • Only entered when BLE is NOT connected (i.e. no web-UI/host attached)
* • Gyro still off, accel still in LP
* • nRF52840 goes into sd_app_evt_wait() — SoftDevice manages radio
* • Wake: IMU INT1 GPIO interrupt → ISR sets wakeFlag, loop resumes
* • On wake: gyro re-enabled, full-rate accel restored, bias re-calibrated
*
* Integration
* -----------
* 1. #include "sleep.h" in main.cpp (already done below)
* 2. Call sleepManagerInit() once in setup(), after imu.begin().
* 3. Call sleepManagerUpdate(now, idle, Bluefruit.connected())
* at the top of loop() (before the early-return on LOOP_RATE_MS).
* 4. The manager returns immediately; it never blocks the loop.
*
* Pin assignment
* --------------
* LSM6DS3 INT1 → XIAO P0.11 (digital pin 3 on the 10-pin header)
* Change IMU_INT1_PIN below if your wiring differs.
* =====================================================================
*/
#pragma once
#include <Arduino.h>
// ── Tuning ──────────────────────────────────────────────────────────────────
// Time of no-motion before each sleep stage kicks in.
// These are deliberately conservative — tighten to taste.
// Tuning
#ifndef SLEEP_IMU_IDLE_MS
#define SLEEP_IMU_IDLE_MS (10UL * 1000UL) // 10 s → gyro off, accel LP
#endif
@@ -46,64 +10,30 @@
#endif
// LSM6DS3 wakeup threshold: 1 LSB = 7.8 mg at ±2 g FS (±2g range).
// The wakeup engine uses a slope filter (difference between consecutive samples
// at 26 Hz, so each sample is ~38 ms apart).
// Too low = wakes on keyboard/desk vibration. Too high = misses gentle pick-up.
// 8 LSB × 7.8 mg ≈ 62 mg — filters desk vibration, fires on deliberate movement.
// Raise to 1216 if still waking from vibration; lower to 4 if too sluggish.
#ifndef SLEEP_WAKEUP_THS
#define SLEEP_WAKEUP_THS 16 // 063
#endif
// Number of consecutive 26 Hz samples that must exceed the threshold.
// 2 samples = ~77 ms of sustained movement required before wakeup fires.
// This is the most effective filter against single-shot vibration spikes
// (keyboard strikes, desk bumps) which are impulsive rather than sustained.
#ifndef SLEEP_WAKEUP_DUR
#define SLEEP_WAKEUP_DUR 2 // 03
#endif
// GPIO pin connected to LSM6DS3 INT1.
// On XIAO nRF52840 Sense, INT1 = P0.11 (internal trace, not on user header).
// The Adafruit nRF52 BSP exposes this as PIN_LSM6DS3TR_C_INT1 — always use
// that constant, never a bare number whose Arduino index is BSP-dependent.
#ifndef IMU_INT1_PIN
#define IMU_INT1_PIN PIN_LSM6DS3TR_C_INT1
#endif
// ── Public state (read-only from main.cpp) ───────────────────────────────────
// 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
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; // set by INT1 ISR, cleared by manager
extern volatile bool imuWakeFlag;
// ── API ──────────────────────────────────────────────────────────────────────
/**
* Call once in setup() after imu.begin().
* Configures INT1 GPIO and arms the LSM6DS3 wakeup interrupt (always-on,
* even in normal mode — it simply won't fire unless the device is still).
*/
void sleepManagerInit();
/**
* Call every loop() iteration.
* @param nowMs millis() timestamp
* @param idle true when the motion pipeline reports no cursor movement
* @param bleConnected Bluefruit.connected()
*
* Returns true if the caller should skip IMU reads this iteration
* (i.e. we are in SLEEP_IMU_LP or just woke up and are re-initialising).
*/
bool sleepManagerUpdate(unsigned long nowMs, bool idle, bool bleConnected);
/**
* Re-arms the LSM6DS3 after wake-from-deep-sleep.
* Called internally by sleepManagerUpdate(); exposed so calibrateGyroBias()
* can also call it if it needs to know sleep state.
*/
void sleepManagerWakeIMU();
+7 -18
View File
@@ -6,12 +6,12 @@
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_INT_DUR2 at ODR=416 Hz:
// SHOCK[7:6] = 2 → 38 ms max tap duration
// QUIET[5:4] = 2 → 19 ms refractory after tap
// DUR[3:0] = 6 → 115 ms max inter-tap window for double detection
// SHOCK[7:6] = 2 → 38 ms max tap duration
// QUIET[5:4] = 2 → 19 ms refractory after tap
// DUR[3:0] = 6 → 115 ms max inter-tap window for double detection
void applyTapThreshold() {
uint8_t thr = cfg.tapThreshold;
if (thr < 1) thr = 1;
@@ -30,18 +30,7 @@ void setupTapDetection() {
Serial.print(" (~"); Serial.print(cfg.tapThreshold * 62.5f, 0); Serial.println(" mg)");
}
// ─── 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.
// Tap processing
static enum { TAP_IDLE, TAP_PENDING, TAP_EXECUTING } tapState = TAP_IDLE;
static unsigned long tapPendingMs = 0;
static uint8_t pendingButton = 0; // 0 = key action pending
@@ -83,7 +72,7 @@ static void fireTapAction(unsigned long now) {
}
void processTaps(unsigned long now) {
// ── Release ───────────────────────────────────────────────────────────────
// Release
if (tapState == TAP_EXECUTING) {
if (now - clickDownMs >= CLICK_HOLD_MS) {
if (pendingButton) {
@@ -99,7 +88,7 @@ void processTaps(unsigned long now) {
return;
}
// ── Poll TAP_SRC ──────────────────────────────────────────────────────────
// Poll TAP_SRC
uint8_t tapSrc = imuReadReg(REG_TAP_SRC);
bool tapIA = !!(tapSrc & 0x40);
bool doubleTap = !!(tapSrc & 0x10);
+60 -60
View File
@@ -1,4 +1,4 @@
// ── UUIDs ────────────────────────────────────────────────────────────────────
// UUIDs
// v3.3: 4 characteristics instead of 10
const SVC_UUID = '00001234-0000-1000-8000-00805f9b34fb';
const CHR = {
@@ -25,11 +25,11 @@ let device=null, server=null, chars={}, userDisconnected=false;
let currentChargeStatus=0, currentBattPct=null, currentBattVoltage=null;
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:
// • Per-operation 3s timeout hangs don't block the queue forever
// • Max depth of 2 pending ops drops excess writes when device goes silent
// • gattQueueReset() flushes on disconnect so a reconnect starts clean
// • Per-operation 3s timeout - hangs don't block the queue forever
// • Max depth of 2 pending ops - drops excess writes when device goes silent
// • gattQueueReset() flushes on disconnect so a reconnect starts clean
const GATT_TIMEOUT_MS = 3000;
const GATT_MAX_DEPTH = 2;
let _gattQueue = Promise.resolve();
@@ -45,7 +45,7 @@ function _withTimeout(promise, ms) {
function _enqueue(fn) {
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++;
const p = _gattQueue.then(() => _withTimeout(fn(), GATT_TIMEOUT_MS));
@@ -62,7 +62,7 @@ function gattQueueReset() {
_gattDepth = 0;
}
// ── Logging ──────────────────────────────────────────────────────────────────
// Logging
(function() {
const _methods = { log: '', warn: 'warn', error: 'err' };
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');
function cssVar(n) { return getComputedStyle(document.documentElement).getPropertyValue(n).trim(); }
// ── Connection ───────────────────────────────────────────────────────────────
// Connection
async function doConnect() {
if (!navigator.bluetooth) { log('Web Bluetooth not supported.','err'); return; }
userDisconnected = false;
@@ -131,27 +131,27 @@ async function discoverServices() {
// Read firmware git hash and check against web build hash
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));
await chars.telemetry.startNotifications();
// Initial read so values show immediately. Also force updateChargeUI() here
// 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 '--'.
parseTelemetry(await chars.telemetry.readValue());
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));
log('Config service ready (4 chars)','ok');
} catch(e) {
log(`Service discovery failed: ${e.message}`,'err');
// 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 {
const bsvc = await server.getPrimaryService('battery_service');
const bch = await bsvc.getCharacteristic('battery_level');
@@ -167,7 +167,7 @@ async function discoverServices() {
} catch(e) { log('Battery service unavailable','warn'); }
}
// ── Firmware / web hash mismatch banner ──────────────────────────────────────
// Firmware / web hash mismatch banner
async function checkHashMatch() {
const banner = document.getElementById('hashMismatchBanner');
if (!chars.gitHash) return;
@@ -199,20 +199,20 @@ async function checkHashMatch() {
].join(';');
banner.innerHTML =
`<span style="font-size:14px">⚠</span>` +
`<span>FIRMWARE / WEB MISMATCH ` +
`firmware <b>${fwHash}</b> · web <b>${webHash}</b> ` +
`<span>FIRMWARE / WEB MISMATCH - ` +
`firmware <b>${fwHash}</b> · web <b>${webHash}</b> - ` +
`flash firmware or reload the page after a <code>pio run</code></span>` +
`<button onclick="document.getElementById('hashMismatchBanner').style.display='none'" ` +
`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>`;
}
// ── ConfigBlob read / write ──────────────────────────────────────────────────
// ConfigBlob read / write
// ConfigBlob layout (25 bytes LE):
// float sensitivity [0], float deadZone [4], float accelStrength [8]
// uint8 curve [12], uint8 axisFlip [13], uint8 chargeMode [14]
// uint8 tapThreshold [15], uint8 tapAction [16], uint8 tapKey [17], uint8 tapMod [18], uint8 tapFreezeEnabled [19]
// float jerkThreshold [20], uint8 featureFlags [24]
// float sensitivity [0], float deadZone [4], float accelStrength [8]
// uint8 curve [12], uint8 axisFlip [13], uint8 chargeMode [14]
// uint8 tapThreshold [15], uint8 tapAction [16], uint8 tapKey [17], uint8 tapMod [18], uint8 tapFreezeEnabled [19]
// float jerkThreshold [20], uint8 featureFlags [24]
async function readConfigBlob() {
if (!chars.configBlob) return;
@@ -238,7 +238,7 @@ async function readConfigBlob() {
if (view.byteLength >= 25) {
config.featureFlags = view.getUint8(24);
} 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) {
config.btnLeftPin = view.getUint8(25);
@@ -248,7 +248,7 @@ async function readConfigBlob() {
config.btnLeftPin = config.btnRightPin = config.btnMiddlePin = 0xFF; // disabled
}
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'); }
}
@@ -284,7 +284,7 @@ function applyConfigToUI() {
updatePinDiagram();
}
// ── XIAO pin diagram ──────────────────────────────────────────────────────────
// XIAO pin diagram
function updatePinDiagram() {
const st = getComputedStyle(document.documentElement);
const COL_L = st.getPropertyValue('--ok').trim();
@@ -362,11 +362,11 @@ async function _doWriteConfigBlob() {
try {
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'); }
}
// ── Individual control handlers ───────────────────────────────────────────────
// Individual control handlers
// These update the local config shadow then write the full blob
function setCurve(val) {
@@ -397,7 +397,7 @@ function setChargeModeUI(val) {
function onCapTapChange(enabled) {
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) {
@@ -430,7 +430,7 @@ function onTapKeyInput() {
async function sendCalibrate() {
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'); }
}
function confirmReset() { document.getElementById('overlay').classList.add('show'); }
@@ -444,22 +444,22 @@ async function doReset() {
} catch(e) { log(`Reset failed: ${e.message}`,'err'); }
}
// ── Telemetry ────────────────────────────────────────────────────────────────
// TelemetryPacket (28 bytes LE backwards compatible with 24-byte v3.3):
// uint32 uptime [0], uint32 leftClicks [4], uint32 rightClicks [8]
// float temp [12], float biasRms [16]
// uint16 recalCount [20], uint8 chargeStatus [22], uint8 pad [23]
// float battVoltage [24] (new in v3.4, absent on older firmware)
// Telemetry
// TelemetryPacket (28 bytes LE - backwards compatible with 24-byte v3.3):
// uint32 uptime [0], uint32 leftClicks [4], uint32 rightClicks [8]
// float temp [12], float biasRms [16]
// uint16 recalCount [20], uint8 chargeStatus [22], uint8 pad [23]
// float battVoltage [24] (new in v3.4, absent on older firmware)
function parseTelemetry(dv) {
let view;
try {
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) {
const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
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;
}
@@ -473,7 +473,7 @@ function parseTelemetry(dv) {
recalCount = view.getUint16(20, true);
chargeStatus= view.getUint8(22);
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('telUptime').textContent = formatUptime(uptime);
@@ -504,7 +504,7 @@ function clearTelemetry() {
document.getElementById(id).textContent='--');
}
// ── Battery & Charge UI ───────────────────────────────────────────────────────
// Battery & Charge UI
function updateBatteryBar(pct, status) {
document.getElementById('battBar').style.display='flex';
document.getElementById('battPct').textContent=pct+'%';
@@ -528,7 +528,7 @@ function updateChargeUI() {
if (currentBattPct!==null) updateBatteryBar(currentBattPct, currentChargeStatus);
}
// ── Advanced toggle ───────────────────────────────────────────────────────
// Advanced toggle
function toggleAdvanced(on) {
advancedMode = 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';
}
// ── IMU Debug Recorder ────────────────────────────────────────────────────────
// IMU Debug Recorder
let debugModalOpen = false;
let debugRecording = false;
let debugBuffer = [];
@@ -631,7 +631,7 @@ function clearDebugRec() {
document.getElementById('debugRecCount').textContent = '0 samples';
}
// ── Param display ─────────────────────────────────────────────────────────────
// Param display
function updateDisplay(key, val) {
const map = {
sensitivity: ['valSensitivity', v=>parseFloat(v).toFixed(0)],
@@ -644,7 +644,7 @@ function updateDisplay(key, val) {
document.getElementById(id).textContent = fmt(val);
}
// ── Status UI ────────────────────────────────────────────────────────────────
// Status UI
function setStatus(state) {
const pill=document.getElementById('statusPill');
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('badgeFull').classList.remove('show');
imuSubscribed = false; vizPaused = true; vizUpdateIndicator(); streamDiagReset();
document.getElementById('orientLabel').textContent = ' not streaming ';
document.getElementById('orientLabel').textContent = '- not streaming -';
document.getElementById('hashMismatchBanner').style.display = 'none';
clearTelemetry();
if (!userDisconnected && document.getElementById('autoReconnect').checked && savedDevice) {
@@ -695,11 +695,11 @@ function onDisconnected() {
}
}
// ── IMU Stream + Visualiser ──────────────────────────────────────────────────
// IMU Stream + Visualiser
// ImuPacket (14 bytes LE):
// int16 gyroX_mDPS [0], int16 gyroZ_mDPS [2]
// int16 accelX_mg [4], int16 accelY_mg [6], int16 accelZ_mg [8]
// int8 moveX [10], int8 moveY [11], uint8 flags [12], uint8 pad [13]
// int16 gyroX_mDPS [0], int16 gyroZ_mDPS [2]
// int16 accelX_mg [4], int16 accelY_mg [6], int16 accelZ_mg [8]
// int8 moveX [10], int8 moveY [11], uint8 flags [12], uint8 pad [13]
const canvas = document.getElementById('vizCanvas');
const ctx = canvas.getContext('2d');
const TRAIL_LEN = 120;
@@ -707,7 +707,7 @@ let cursorX = canvas.width/2, cursorY = canvas.height/2, trail = [];
let vizPaused = true;
let imuSubscribed = false;
// ── Stream diagnostics ────────────────────────────────────────────────────────
// Stream diagnostics
let streamPktCount = 0; // packets received this second
let streamPktTotal = 0; // lifetime packet count
let streamLastPktT = 0; // timestamp of last packet (for gap detection)
@@ -722,7 +722,7 @@ function streamDiagReset() {
function streamDiagPkt() {
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) {
const gap = now - streamLastPktT;
if (gap > 300) log(`[STREAM] gap ${gap}ms (pkt #${streamPktTotal})`, 'warn');
@@ -731,10 +731,10 @@ function streamDiagPkt() {
streamPktCount++;
streamPktTotal++;
// Reset freeze watchdog 1.5s without a packet = freeze
// Reset freeze watchdog - 1.5s without a packet = freeze
if (streamFreezeTimer) clearTimeout(streamFreezeTimer);
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;
}, 1500);
@@ -750,7 +750,7 @@ function streamDiagPkt() {
// Roll compensation is done entirely in firmware (calibrateGyroBias computes
// 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 vizUpdateIndicator() {
@@ -782,7 +782,7 @@ async function vizSetPaused(paused) {
await chars.imuStream.stopNotifications();
imuSubscribed = false;
streamDiagReset();
document.getElementById('orientLabel').textContent = ' not streaming ';
document.getElementById('orientLabel').textContent = '- not streaming -';
} catch(e) { log(`IMU stream stop failed: ${e.message}`,'err'); }
}
vizUpdateIndicator();
@@ -792,7 +792,7 @@ function parseImuStream(dv) {
let view;
try {
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) {
const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
@@ -811,7 +811,7 @@ function parseImuStream(dv) {
moveX = view.getInt8(10);
moveY = view.getInt8(11);
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)
feedDebugRow(gyroX, gyroZ, accelX, accelY, accelZ, moveX, moveY, flags);
@@ -826,7 +826,7 @@ function parseImuStream(dv) {
updateAxisBar('gz', -gyroX, 30000);
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));
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.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)
// Complementary filter mirrors firmware: α=0.96, dt from packet rate (~50ms)
const ORIENT_ALPHA = 0.96;
@@ -932,7 +932,7 @@ function initOrientViewer() {
orientEdges = new THREE.LineSegments(new THREE.EdgesGeometry(geo), edgeMat);
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);
arrowGeo.rotateZ(-Math.PI / 2);
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);
}
// 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
const gyRad = gyX_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);
}
// ── Theme ─────────────────────────────────────────────────────────────────────
// Theme
const THEMES = ['auto','dark','light'];
const THEME_LABELS = {auto:'AUTO',dark:'DARK',light:'LIGHT'};
let themeIdx = 0;
+8 -8
View File
@@ -39,7 +39,7 @@
<main id="mainContent">
<!-- ── col-left: cursor motion ──────────────────────────────── -->
<!-- col-left: cursor motion -->
<div class="col-left">
<div class="section-label">Motion Parameters</div>
@@ -51,7 +51,7 @@
<div class="param-value" id="valSensitivity">600</div>
</div>
<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"
oninput="updateDisplay('deadZone',this.value)" onchange="writeConfigBlob()">
<div class="param-value" id="valDeadZone">0.060</div>
@@ -134,7 +134,7 @@
</div><!-- /col-left -->
<!-- ── col-mid: button configuration ───────────────────────── -->
<!-- col-mid: button configuration -->
<div class="col-mid">
<div class="section-label">Tap Configuration</div>
@@ -146,7 +146,7 @@
</div>
</div>
<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"
oninput="updateDisplay('jerkThreshold',this.value)" onchange="writeConfigBlob()">
<div class="param-value" id="valJerkThreshold">2000</div>
@@ -183,7 +183,7 @@
<div class="section-label">Physical Buttons</div>
<div class="card">
<!-- ── XIAO nRF52840 Sense pin diagram ─────────────────── -->
<!-- XIAO nRF52840 Sense pin diagram -->
<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">
<!-- USB-C connector -->
@@ -301,7 +301,7 @@
<div class="cmd-grid">
<button class="cmd-btn calibrate" id="btnCal" onclick="sendCalibrate()" disabled>
<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 class="cmd-btn reset" id="btnReset" onclick="confirmReset()" disabled>
<span class="cmd-icon"></span><span>Factory Reset</span>
@@ -314,7 +314,7 @@
</div><!-- /col-mid -->
<!-- ── col-right: live monitoring ───────────────────────────── -->
<!-- col-right: live monitoring -->
<div class="col-right">
<div class="section-label">Live Cursor Visualiser</div>
@@ -350,7 +350,7 @@
<div class="section-label">Device Orientation</div>
<div class="card orient-card">
<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 class="section-label">Live Telemetry</div>
+5 -5
View File
@@ -34,7 +34,7 @@
--tap-right: rgba(255,61,113,0.35);
}
/* ── Light theme (explicit) ──────────────────────────────────────────────── */
/* Light theme (explicit) */
:root.theme-light {
--bg: #f0f2f5;
--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) {
:root:not(.theme-dark) {
--bg: #f0f2f5;
@@ -153,7 +153,7 @@
.col-mid { display:grid; gap:12px; }
.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; }
.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); }
@@ -161,7 +161,7 @@
.pleg.mid { color:var(--accent); }
.xiao-divider { border:none; border-top:1px solid var(--border); margin:0 -20px 12px; }
/* ── Responsive ───────────────────────────────────────────── */
/* Responsive */
@media (max-width:1100px) {
main { grid-template-columns:1fr 380px; grid-template-rows:auto auto; }
.col-left { grid-column:1; grid-row:1; }
@@ -288,7 +288,7 @@
.btn-confirm { border-color:var(--accent2); color:var(--accent2); }
.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 h3 { color:var(--accent); margin-bottom:0; }
.debug-header { display:flex; justify-content:space-between; align-items:center; margin-bottom:14px; }