Compare commits

...

34 Commits

Author SHA1 Message Date
nikrozman 4aa369ca73 Double click support 2026-03-24 23:39:06 +01:00
nikrozman a7082c9022 Disable tap detection by default, simplify tracking 2026-03-24 23:30:06 +01:00
nikrozman 14e9c96f55 Improve sleep and add button waking 2026-03-24 23:29:34 +01:00
nikrozman 0fc38a5e1b Simplify tracking 2026-03-24 23:11:17 +01:00
nikrozman 8ab07adfc6 Add button support 2026-03-24 22:56:21 +01:00
nikrozman 2abc226652 Micro-adjust 3D model to support current PCB 2026-03-24 22:54:49 +01:00
nikrozman 5ab13a525a Redesign MCU and PCB mounting 2026-03-24 19:29:40 +01:00
nikrozman 502ea786b0 Better clip-in top mechanism 2026-03-23 19:22:46 +01:00
nikrozman 1486fe13f2 FIx battery quirks 2026-03-19 22:38:04 +01:00
nikrozman 395fd9b839 Implement BLE OTA 2026-03-19 22:11:45 +01:00
nikrozman 87fc2a3574 Update 3D model 2026-03-19 21:47:42 +01:00
nikrozman 5f928d7c92 Don't calibrate while device is moving 2026-03-19 20:19:26 +01:00
nikrozman 532ba4f719 Remove button mapping 2026-03-19 20:18:17 +01:00
nikrozman 19b96c9b21 Better smoothing 2026-03-08 11:56:49 +01:00
Nik Rozman 94f38975bd Better web UI logging 2026-03-04 10:16:08 +01:00
Nik Rozman c325336508 Fix charging bugs, remove disabling charging since its not supported in HW 2026-03-04 08:31:34 +01:00
nikrozman 953edd4065 Report IMU stream more frequently
Looks like the max rate largely depends on end receiver quality - to improve to dynamically lower if queue fills up
2026-03-03 21:51:55 +01:00
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
Nik Rozman 5c36aa041e Initial physical button mapping implementation #4 2026-03-03 11:44:38 +01:00
Nik Rozman dcc50150b8 Make tap freezing configurable, add toggles to other functions, minor UI changes 2026-03-03 08:49:22 +01:00
Nik Rozman 8f63d7c0b5 UI improvements, prepare for config overriding 2026-03-03 08:34:43 +01:00
nikrozman 5c9aa62cda Add samples to help with debugging #2 2026-03-02 23:58:56 +01:00
nikrozman a666304013 Attempt to add jerk correction 2026-03-02 23:53:10 +01:00
nikrozman 4768754bef Better base notch, remove notch from lid 2026-03-02 23:52:45 +01:00
nikrozman 6ecae74483 Add battery voltage reading to web UI, apply fixed VBAT multiplier, closes #3 2026-03-02 21:02:27 +01:00
Nik Rozman c41a2932ba Fix battery voltage readouts 2026-03-02 15:45:01 +01:00
nikrozman ee1d13f177 Fix roll correction, closes #1 2026-03-01 23:13:39 +01:00
nikrozman b3cc319d5e Attempt to fix roll correction 2026-03-01 22:12:23 +01:00
nikrozman 9e481096be Let firmware handle roll correction 2026-03-01 21:53:50 +01:00
nikrozman 11baa814c9 Better TX congestion detection, don't stall on reading battery status 2026-03-01 21:49:59 +01:00
nikrozman 1bd2ecc339 Don't version commit hash 2026-03-01 21:45:15 +01:00
nikrozman 8cb92f9914 Inject commit hash to FW, show on frontend 2026-03-01 21:38:51 +01:00
nikrozman a3b5425d0f IMU visualization 2026-03-01 21:35:36 +01:00
22 changed files with 2032 additions and 538 deletions
+3
View File
@@ -4,3 +4,6 @@
*.pio
*.claude
*.vscode
web/version.js
samples/
firmware_dfu.zip
+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
+152 -239
View File
@@ -1,283 +1,196 @@
# IMU Pointer Enclosure
"""
IMU Pointer Enclosure — v11.7 (Slimmed Corners & Rounded USB-C)
"""
import FreeCAD as App
import FreeCADGui as Gui
import Part
from FreeCAD import Base
doc = App.newDocument("pointer")
doc = App.newDocument("pointer_v11_7")
# Global dimensions
L = 115.0
W = 36.0
H = 20.0
# ─── DIMENSIONS ───────────────────────────────────────────────────────────────
L, W, H = 115.0, 36.0, 22.0
WALL = 3.5
CR = 3.0
CR, CR_I = 8.0, 4.5
TOL = 0.25
EDGE_FILLET = 3.0
# Rail and lid
RAIL_H = 4.5
RAIL_D = 2.0
LIP_H = 2.0
LIP_OVER = 1.5
LIP_EMBED = 0.2
USBC_W, USBC_H, USBC_Z = 12.0, 7.0, 5.0
SPLIT_Z = USBC_Z + USBC_H + 2.5
LID_H = RAIL_H - LIP_H - TOL - 0.55
# MICRO-DETENT Snap Logic
TONGUE_H, TONGUE_T = 2.5, 2.0
GROOVE_H, GROOVE_T = TONGUE_H + TOL, TONGUE_T + TOL
RIDGE_W = 12.0
RIDGE_H = 1.2
RIDGE_PROUD = 1.0 # Snap ridge protrusion
RIDGE_Z_OFF = (TONGUE_H - RIDGE_H) / 2.0
# Board dimensions
PCB_T = 1.0
BRD_L = 21.0
BRD_W = 17.5
BRD_X = WALL
BRD_Y = (W - BRD_W) / 2
PLATFORM_H = 0.5
# ─── IMU BOARD (+1mm Spacing & Slim Corners) ──────────────────────────────────
PCB_T, BRD_L, BRD_W = 3.0, 22.6, 19.6
BRD_X, BRD_Y = WALL, (W - BRD_W) / 2.0
PLATFORM_H, MIC_EXTRA = 1.5, 2.0
MIC_PCB_T = 2.5 # Thicker PCB section (MEMS mic), rounded up from 2.2
BUMP_PROUD = 0.3 # Press-fit nub protrusion into board cavity
BUMP_R = 0.6 # Nub radius (half-sphere)
BRD_Z = WALL + PLATFORM_H
# Clip arms
ARM_LEN = 5.0
ARM_THICK = 1.6
ARM_H = BRD_Z + PCB_T + 0.8
CLIP_TOL = 0.35
# USB-C cutout
USBC_W = 11.0
USBC_H = 7.0
USBC_Z = 4.5
# Battery section
BAT_L = 50.0
BAT_W = 12.0
BAT_H = 12.0
BAT_X = BRD_X + BRD_L + 8.0
BAT_Y = (W - BAT_W) / 2
# ─── BUTTON & BATTERY ─────────────────────────────────────────────────────────
BAT_L, BAT_W, BAT_H = 50.0, 12.0, 12.0
BAT_X, BAT_Y = BRD_X + BRD_L + 8.0 + 5.0, (W - BAT_W) / 2.0
BAT_CLIP_Y = 8.0
BTN_X, BTN_CY, BTN_HOLE_R = 28.0, W / 2.0, 10.0
CAP_SHAFT_R, CAP_SHAFT_H = 9.6, WALL + 1.0 # +1mm taller shaft so cap sits flush
CAP_RIM_R, CAP_RIM_H = 12.0, 1.5
CAP_CAVITY_R, CAP_CAVITY_H = 5.2, 2.5 # Hollow cavity replaces nubbin — clears button dome
BTN_DOME_R, BTN_DOME_SAG = 14.0, 0.6
PCB_BOT_Z = SPLIT_Z + 1.5
POST_H = BRD_Z + PCB_T + MIC_EXTRA + 3.0 - 4.0 # Lowered 4mm for button PCB + button thickness
POST_OFFS_X, POST_OFFS_Y = 4.0, 11.0
LH_R, LH_X, LH_Y_OFFS = 1.5, L - WALL - 3.0, 4.0
BPCB_L, BPCB_W = 16.0, 16.0
# Rounded box helper
def rbox(lx, ly, lz, ox=0, oy=0, oz=0, r=CR):
b = Part.makeBox(lx, ly, lz, Base.Vector(ox, oy, oz))
try:
vert = [e for e in b.Edges
if abs(e.Vertexes[0].Z - e.Vertexes[1].Z) > lz * 0.9]
if vert:
b = b.makeFillet(r, vert)
except Exception:
pass
return b
# ─── HELPERS ──────────────────────────────────────────────────────────────────
# Simple box helper
def box(lx, ly, lz, ox=0, oy=0, oz=0):
return Part.makeBox(lx, ly, lz, Base.Vector(ox, oy, oz))
def rbox(lx, ly, lz, ox=0, oy=0, oz=0, r=CR):
b = box(lx, ly, lz, ox, oy, oz)
try:
edges = [e for e in b.Edges if abs(e.Vertexes[0].X - e.Vertexes[1].X) < 1e-3 and abs(e.Vertexes[0].Y - e.Vertexes[1].Y) < 1e-3]
return b.makeFillet(r, edges) if edges else b
except: return b
# Rounded slot helper
def rounded_slot(depth, w, h, ox, oy, oz, r=None):
if r is None:
r = h / 2.0
def cyl(r, h, cx=0, cy=0, cz=0):
return Part.makeCylinder(r, h, Base.Vector(cx, cy, cz))
r = min(r, h / 2.0, w / 2.0)
def fillet_horiz(solid, r, z_test):
try:
edges = [e for e in solid.Edges if abs(e.Vertexes[0].Z - e.Vertexes[1].Z) < 0.2 and abs((e.Vertexes[0].Z + e.Vertexes[1].Z)/2 - z_test) < 1.5]
return solid.makeFillet(r, edges) if edges else solid
except: return solid
import math
def make_slim_corner(cx, cy, ix, iy):
pw = 0.8 # Much slimmer wall thickness (was 1.5/1.6)
sl = 4.0 # Slightly shorter side length
h = PLATFORM_H + PCB_T + 0.5
cy = oy + w / 2.0
cz = oz + h / 2.0
hw = w / 2.0 - r
x0, y0 = (cx if ix>0 else cx-sl), (cy if iy>0 else cy-pw)
w1 = box(sl, pw, h, x0, y0, WALL)
def pt(cx, cy_v, cz_v, angle_deg, radius):
a = math.radians(angle_deg)
return Base.Vector(
cx,
cy_v + radius * math.cos(a),
cz_v + radius * math.sin(a)
)
x1, y1 = (cx if ix>0 else cx-pw), (cy if iy>0 else cy-sl)
w2 = box(pw, sl, h, x1, y1, WALL)
l_start = pt(ox, cy - hw, cz, 270, r)
l_mid = pt(ox, cy - hw, cz, 180, r)
l_end = pt(ox, cy - hw, cz, 90, r)
arc_left = Part.Arc(l_start, l_mid, l_end).toShape()
px, py = (cx if ix>0 else cx-sl), (cy if iy>0 else cy-sl)
plat = box(sl, sl, PLATFORM_H, px, py, WALL)
line_top = Part.makeLine(
l_end,
pt(ox, cy + hw, cz, 90, r)
)
return plat.fuse(w1).fuse(w2)
r_start = pt(ox, cy + hw, cz, 90, r)
r_mid = pt(ox, cy + hw, cz, 0, r)
r_end = pt(ox, cy + hw, cz, 270, r)
arc_right = Part.Arc(r_start, r_mid, r_end).toShape()
# ═════════════════════════════════════════════════════════════════════════════
# CONSTRUCTION
# ═════════════════════════════════════════════════════════════════════════════
line_bot = Part.makeLine(r_end, l_start)
# BOTTOM SHELL
bot_shell = fillet_horiz(rbox(L, W, SPLIT_Z + TONGUE_H), EDGE_FILLET, 0.0)
bot_shell = bot_shell.cut(rbox(L-WALL*2, W-WALL*2, SPLIT_Z, WALL, WALL, WALL, r=CR_I))
bot_shell = bot_shell.cut(rbox(L-TONGUE_T*2, W-TONGUE_T*2, TONGUE_H+2, TONGUE_T, TONGUE_T, SPLIT_Z, r=CR-TONGUE_T))
wire = Part.Wire([arc_left, line_top, arc_right, line_bot])
face = Part.Face(wire)
# Internal Fusions (Using Slim L-bracket style for MCU)
for cx, cy, ix, iy in [(BRD_X, BRD_Y, 1, 1), (BRD_X+BRD_L, BRD_Y, -1, 1), (BRD_X, BRD_Y+BRD_W, 1, -1), (BRD_X+BRD_L, BRD_Y+BRD_W, -1, -1)]:
bot_shell = bot_shell.fuse(make_slim_corner(cx, cy, ix, iy))
return face.extrude(Base.Vector(depth, 0, 0))
# Press-fit nubs — half-sphere on each L-bracket's inner Y-facing wall (w1)
bump_z = BRD_Z + 1.0 + BUMP_R # Bottom of nub sits 1mm above platform
pw = 0.8; sl = 4.0 # Must match make_slim_corner
for cx, cy, ix, iy in [(BRD_X, BRD_Y, 1, 1), (BRD_X+BRD_L, BRD_Y, -1, 1),
(BRD_X, BRD_Y+BRD_W, 1, -1), (BRD_X+BRD_L, BRD_Y+BRD_W, -1, -1)]:
# w1 wall centre X: midpoint of the sl-long wall extending from corner
mid_x = cx + ix * sl / 2.0
# w1 inner face Y: the face that looks toward the board centre
face_y = cy if iy > 0 else cy - pw # wall origin Y
inner_y = face_y + pw if iy > 0 else face_y # the side facing inward
# iy>0 → bump faces +Y (inward), iy<0 → bump faces -Y (inward)
# Actually: iy>0 means corner is at low-Y side, wall inner face = face_y+pw, bump goes +Y
# iy<0 means corner is at high-Y side, wall inner face = face_y, bump goes -Y
sph = Part.makeSphere(BUMP_R, Base.Vector(mid_x, inner_y, bump_z))
cs = BUMP_R + 0.5
# Clip: keep only the half protruding inward (toward board centre)
if iy > 0:
clip = box(cs*2, cs, cs*2, mid_x - cs, inner_y, bump_z - cs)
else:
clip = box(cs*2, cs, cs*2, mid_x - cs, inner_y - cs, bump_z - cs)
half_sph = sph.common(clip)
bot_shell = bot_shell.fuse(half_sph)
POST_R = 1.75
POST_TAPER_EXTRA = 0.3 # Extra radius at base
POST_TAPER_H = 6.0 # Height over which the taper blends to nominal radius
BACK_POST_SHIFT = POST_R # Shift back posts by half a post diameter
for ox in [-POST_OFFS_X, POST_OFFS_X]:
for oy in [-POST_OFFS_Y, POST_OFFS_Y]:
px = BTN_X + ox + (BACK_POST_SHIFT if ox > 0 else 0)
py = BTN_CY + oy
post = cyl(POST_R, POST_H, px, py, WALL)
# Tapered cone base: wider at bottom, blends to post radius at POST_TAPER_H
taper = Part.makeCone(POST_R + POST_TAPER_EXTRA, POST_R, POST_TAPER_H,
Base.Vector(px, py, WALL))
post = post.fuse(taper)
post = post.cut(cyl(0.5, POST_H + 1, px, py, WALL))
bot_shell = bot_shell.fuse(post)
# Board clip helper
def make_clip(corner_x, corner_y, inward_x, inward_y):
# Rounded USB-C Cut (Pill Shape)
usbc_r = USBC_H / 2.0
usbc_box = box(WALL*4, USBC_W - 2*usbc_r, USBC_H, -1, W/2 - USBC_W/2 + usbc_r, USBC_Z)
usbc_cyl1 = Part.makeCylinder(usbc_r, WALL*4, Base.Vector(-1, W/2 - USBC_W/2 + usbc_r, USBC_Z + usbc_r), Base.Vector(1, 0, 0))
usbc_cyl2 = Part.makeCylinder(usbc_r, WALL*4, Base.Vector(-1, W/2 + USBC_W/2 - usbc_r, USBC_Z + usbc_r), Base.Vector(1, 0, 0))
usbc_rounded = usbc_box.fuse(usbc_cyl1).fuse(usbc_cyl2)
bot_shell = bot_shell.cut(usbc_rounded)
plat_w = ARM_THICK + CLIP_TOL
# Battery bay + retaining tabs
bot_shell = bot_shell.cut(box(BAT_L, BAT_W, 3.0, BAT_X, BAT_Y, WALL))
bat_clip_cy = BAT_Y + BAT_W / 2.0 - BAT_CLIP_Y / 2.0
bot_shell = bot_shell.fuse(box(2.0, BAT_CLIP_Y, BAT_H * 0.55, BAT_X - 2.0, bat_clip_cy, WALL))
bot_shell = bot_shell.fuse(box(2.0, BAT_CLIP_Y, BAT_H * 0.55, BAT_X + BAT_L, bat_clip_cy, WALL))
plat_x = corner_x if inward_x > 0 else corner_x - plat_w
plat_y = corner_y if inward_y > 0 else corner_y - plat_w
# MICRO-DETENT RIDGES: Buried deep, barely protruding
rx0, rz0 = L/2 - RIDGE_W/2, SPLIT_Z + RIDGE_Z_OFF
ridge_bury = 1.5
ridge_total_t = ridge_bury + RIDGE_PROUD
bot_shell = bot_shell.fuse(box(RIDGE_W, ridge_total_t, RIDGE_H, rx0, TONGUE_T - ridge_bury, rz0))
bot_shell = bot_shell.fuse(box(RIDGE_W, ridge_total_t, RIDGE_H, rx0, W - TONGUE_T - RIDGE_PROUD, rz0))
platform = box(
plat_w, plat_w,
PLATFORM_H + PCB_T,
plat_x, plat_y, WALL
)
# TOP SHELL
top_shell = fillet_horiz(rbox(L, W, H-SPLIT_Z, 0, 0, SPLIT_Z), EDGE_FILLET, H)
top_shell = top_shell.cut(rbox(L-WALL*2, W-WALL*2, H-SPLIT_Z-WALL, WALL, WALL, SPLIT_Z, r=CR_I))
ax_ox = corner_x if inward_x > 0 else corner_x - ARM_LEN
ax_oy = corner_y - ARM_THICK - CLIP_TOL if inward_y > 0 else corner_y + CLIP_TOL
arm_x = box(ARM_LEN, ARM_THICK, ARM_H, ax_ox, ax_oy, WALL)
# Groove and Matching Recesses
g_band = rbox(L, W, GROOVE_H, 0, 0, SPLIT_Z, r=CR).cut(rbox(L-GROOVE_T*2, W-GROOVE_T*2, GROOVE_H+2, GROOVE_T, GROOVE_T, SPLIT_Z-1, r=CR-GROOVE_T))
top_shell = top_shell.cut(g_band)
ay_oy = corner_y if inward_y > 0 else corner_y - ARM_LEN
ay_ox = corner_x - ARM_THICK - CLIP_TOL if inward_x > 0 else corner_x + CLIP_TOL
arm_y = box(ARM_THICK, ARM_LEN, ARM_H, ay_ox, ay_oy, WALL)
# Recesses in groove wall — bottom ridges click into these
rec_w = RIDGE_W + TOL*2
rec_d = RIDGE_PROUD + TOL # Slightly deeper than ridge protrusion
top_shell = top_shell.cut(box(rec_w, rec_d, RIDGE_H+TOL, L/2-rec_w/2, GROOVE_T, rz0-TOL/2))
top_shell = top_shell.cut(box(rec_w, rec_d, RIDGE_H+TOL, L/2-rec_w/2, W-GROOVE_T-rec_d, rz0-TOL/2))
corner_block_w = ARM_THICK + CLIP_TOL
cb_ox = corner_x - corner_block_w if inward_x > 0 else corner_x
cb_oy = corner_y - corner_block_w if inward_y > 0 else corner_y
# Button & Cap
top_shell = top_shell.cut(cyl(BTN_HOLE_R, H, BTN_X, BTN_CY, SPLIT_Z))
top_shell = top_shell.cut(Part.makeSphere(BTN_DOME_R, Base.Vector(BTN_X, BTN_CY, H - WALL - BTN_DOME_R + BTN_DOME_SAG)))
cap = cyl(CAP_SHAFT_R, CAP_SHAFT_H).fuse(cyl(CAP_RIM_R, CAP_RIM_H, 0, 0, -CAP_RIM_H))
# Hollow cavity in bottom of shaft — button dome nests inside instead of a protruding nubbin
cap = cap.cut(cyl(CAP_CAVITY_R, CAP_CAVITY_H, 0, 0, -CAP_RIM_H))
cap_placed = cap.copy(); cap_placed.translate(Base.Vector(BTN_X, BTN_CY, H - CAP_SHAFT_H))
corner_block = box(
corner_block_w, corner_block_w, ARM_H,
cb_ox, cb_oy, WALL
)
return platform.fuse(arm_x.fuse(arm_y).fuse(corner_block))
# Base outer body
base = rbox(L, W, H)
# Inner cavity
base = base.cut(
box(L - WALL * 2, W - WALL * 2, H - WALL,
WALL, WALL, WALL)
)
rail_z = H - RAIL_H
groove_h = RAIL_H - LIP_H
# Rail grooves
base = base.cut(
box(L - WALL * 2, RAIL_D, groove_h,
WALL, WALL - RAIL_D, rail_z)
)
base = base.cut(
box(L - WALL * 2, RAIL_D, groove_h,
WALL, W - WALL, rail_z)
)
# Lid lips
lip_z = H - LIP_H
base = base.fuse(
box(L - WALL * 2, LIP_OVER, LIP_H,
WALL, WALL, lip_z)
)
base = base.fuse(
box(L - WALL * 2, LIP_OVER, LIP_H,
WALL, W - WALL - LIP_OVER, lip_z)
)
# Back slot
slot_y0 = WALL - RAIL_D
slot_yw = W - WALL * 2 + RAIL_D * 2
base = base.cut(
box(WALL + 1.0, slot_yw, RAIL_H,
L - WALL, slot_y0, rail_z)
)
# Entry bump
BUMP_H = 0.5
pad_raw = box(WALL, slot_yw, BUMP_H,
L - WALL, slot_y0, rail_z)
pad_trimmed = pad_raw.common(rbox(L, W, H))
base = base.fuse(pad_trimmed)
# Board clips
clip_corners = [
(BRD_X, BRD_Y, +1, +1),
(BRD_X + BRD_L, BRD_Y, -1, +1),
(BRD_X, BRD_Y + BRD_W, +1, -1),
(BRD_X + BRD_L, BRD_Y + BRD_W, -1, -1),
]
for cx, cy, ix, iy in clip_corners:
base = base.fuse(make_clip(cx, cy, ix, iy))
# USB-C opening
base = base.cut(
rounded_slot(
WALL * 3,
USBC_W,
USBC_H,
-WALL,
W / 2 - USBC_W / 2,
USBC_Z
)
)
# Battery recess
base = base.cut(
box(BAT_L, BAT_W, 3.0,
BAT_X, BAT_Y, WALL)
)
clip_y_start = BAT_Y + BAT_W / 2 - BAT_CLIP_Y / 2
base = base.fuse(
box(2.0, BAT_CLIP_Y, BAT_H * 0.55,
BAT_X - 2.0, clip_y_start, WALL)
)
base = base.fuse(
box(2.0, BAT_CLIP_Y, BAT_H * 0.55,
BAT_X + BAT_L, clip_y_start, WALL)
)
# Lid
TAB_W = RAIL_D - TOL + 0.5
LID_L = L - WALL * 2 - TOL
LID_EXTRA_TOL = 0.5
LID_W = (
W - WALL * 2
- (TOL + LID_EXTRA_TOL) * 2
+ TAB_W * 2
)
lid_y0 = WALL + TOL + LID_EXTRA_TOL - TAB_W
lid = box(LID_L, LID_W, LID_H, 0, lid_y0, 0)
lid = lid.cut(
box(WALL * 2, USBC_W + TOL, LID_H + 0.2,
LID_L - WALL,
W / 2 - (USBC_W + TOL) / 2,
-0.1)
)
lid.translate(Base.Vector(WALL + TOL, 0, rail_z))
# Final objects
base_obj = doc.addObject("Part::Feature", "Pointer_Base")
base_obj.Shape = base
base_obj.ViewObject.ShapeColor = (0.12, 0.12, 0.14)
lid_obj = doc.addObject("Part::Feature", "Pointer_Lid")
lid_obj.Shape = lid
lid_obj.ViewObject.ShapeColor = (0.28, 0.28, 0.34)
lid_obj.ViewObject.Transparency = 25
# ─── REGISTER ────────────────────────────────────────────────────────────────
for name, shape, color in [("Shell_Bottom", bot_shell, (0.15, 0.15, 0.18)),
("Shell_Top", top_shell, (0.25, 0.25, 0.32)),
("Button_Cap", cap_placed, (0.7, 0.7, 0.7))]:
obj = doc.addObject("Part::Feature", name)
obj.Shape = shape
obj.ViewObject.ShapeColor = color
doc.recompute()
Gui.activeDocument().activeView().viewIsometric()
Gui.SendMsgToActiveView("ViewFit")
+11 -6
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,18 +25,23 @@ upload_speed = 115200
; Uncomment and set the correct port if auto-detect fails:
; upload_port = COM3
; ── Build flags ───────────────────────────────────────────────────────────────
; Build scripts
; git_hash.py - injects short git hash into firmware + web/version.js
; generate_dfu.py - generates firmware_dfu.zip for OTA upload (requires adafruit-nrfutil)
extra_scripts = pre:scripts/git_hash.py, post:scripts/generate_dfu.py
; 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
+111
View File
@@ -0,0 +1,111 @@
ms,gyroX_mDPS,gyroZ_mDPS,accelX_mg,accelY_mg,accelZ_mg,moveX,moveY,flags
53,2654,-3418,-1914,-2011,7816,1,0,0
158,1324,-2788,-2038,-1965,7618,0,0,0
248,4194,-4958,-1972,-1932,7640,1,0,0
353,9164,-4538,-2229,-1395,7797,1,0,0
443,9654,-5658,-2216,-1850,7761,1,0,0
548,6784,-4538,-2045,-2695,8907,0,0,8
653,-4695,-6358,-1999,-479,4979,0,0,8
743,-285,2881,-2084,-1290,7339,0,0,8
848,-775,-1738,-2177,-1265,8638,0,0,0
953,-12465,1061,-2411,-1295,8169,0,-1,0
1043,5804,5611,-1750,-1631,11380,0,0,8
1149,-3365,-5798,-2116,-1461,7408,0,0,8
1268,-2385,-2788,-1891,-1037,7346,0,0,0
1359,-1965,-618,-2016,-1282,7299,0,0,0
1448,-6795,-2718,-1857,-976,8337,0,0,0
1553,1114,-338,-2006,-1546,7670,0,0,0
1643,-705,-2228,-1974,-828,7469,0,0,0
1749,-17155,-128,-1761,-655,-720,0,0,8
1854,-13725,2181,-1584,4,7077,0,0,8
1958,-705,-3208,-2259,-1596,7595,0,0,0
2049,-7075,11071,-1719,-1978,10915,0,0,8
2153,-4275,-14548,-1705,-856,5439,0,0,8
2243,2304,1341,-1966,-1408,8362,0,0,8
2348,-3089,-3632,-2124,-1835,8562,0,0,0
2453,2374,-4188,-2072,-1443,7111,1,0,0
2543,554,-2298,-2086,-1274,7441,0,0,0
2663,2094,-2928,-2025,-1140,6958,0,0,0
2753,134,-618,-2103,-1371,7872,0,0,0
2843,-9385,2671,-2071,-1233,8861,0,0,0
2963,-11135,3511,-1888,-1374,12893,0,0,8
3053,-1055,-11398,-2221,-1586,6244,0,0,8
3143,20924,-5238,-5474,-2908,5746,0,0,8
3248,8604,-4468,-1443,-349,7376,0,0,8
3353,-3085,-58,-2151,-1654,8338,0,0,8
3443,974,-4678,-1932,-1354,7175,1,0,0
3549,3284,1761,-1980,-1151,8339,0,0,0
3653,-4975,-2648,-2031,-1042,7637,0,0,0
3743,204,-688,-2083,-1310,7454,0,0,0
3848,624,-1178,-2139,-1230,7442,0,0,0
3953,-9735,-1878,-2098,-1199,7625,0,0,0
4043,-5535,10091,-2066,-1651,12571,0,0,8
4149,-3995,-13708,-1964,-1238,5689,0,0,8
4253,6924,3371,49,-2649,7077,0,0,8
4343,5454,-10348,-1555,-436,6547,0,0,8
4448,4194,4981,-2105,-1739,9074,0,0,8
4553,904,-5098,-1935,-1283,8402,1,0,0
4643,1674,-758,-1978,-1211,7202,0,0,0
4748,-2455,-1108,-2001,-1116,7934,0,0,0
4853,-3715,-2158,-2111,-1310,8041,0,0,0
4943,-2385,-618,-2153,-1332,8018,0,0,0
5048,-32000,-29108,9536,-10268,15988,0,0,8
5153,-18695,-2998,-1580,147,6707,0,0,8
5258,-16455,2671,-2461,-2252,8459,0,0,8
5348,-32000,9251,-1555,-2178,12371,0,0,8
5453,7344,-7968,-1775,-1352,4664,0,0,8
5558,7134,-478,-1620,-1572,8487,0,0,8
5648,-845,-3628,-2025,-2149,8102,0,0,0
5753,4054,-1038,-1802,-1613,7898,0,0,0
5858,1394,-3488,-1933,-1464,7686,0,0,0
5948,1744,-1178,-2028,-1610,7994,0,0,0
6053,-7495,-3558,-1996,-1484,7724,0,0,0
6158,-15895,1481,-1772,-1655,13107,0,0,8
6250,-1615,-12728,-1875,-1400,6132,0,0,8
6353,-565,5051,-550,-3014,7815,0,0,8
6458,10564,-9788,-1342,-820,6415,0,0,8
6548,9374,4841,-1761,-1659,9666,0,0,8
6653,-845,-5308,-1693,-1587,7817,0,0,0
6759,4194,-338,-1616,-1276,7454,0,0,0
6848,-355,-3208,-1740,-1636,8304,1,0,0
6953,-145,-1248,-1906,-1650,7992,0,0,0
7058,-16385,2111,-1934,-1912,8066,0,0,0
7148,274,3371,-1647,-1974,13521,0,0,8
7253,-13585,-11258,-1908,-1610,5902,0,0,8
7358,31914,5051,-7768,-850,5010,0,0,8
7448,-2875,-11888,-913,30,5893,0,0,8
7568,7064,1411,-1979,-2262,9181,0,0,8
7658,-1685,-3208,-1719,-1610,7340,0,0,0
7749,-285,221,-1597,-1448,7409,0,0,0
7853,-1755,-1248,-1718,-1584,7830,0,-1,0
7958,-2525,11,-1808,-1567,7926,0,0,0
8048,-3015,-1318,-1836,-1547,7910,0,0,0
8168,2794,6031,-4147,-1770,8318,0,0,8
8259,10914,-898,-1850,-1514,7943,0,0,8
8348,-18975,4351,-2237,-2038,7767,0,0,8
8453,14554,1761,-1931,-2700,13504,0,0,8
8558,-3295,-12588,-2127,-1865,6672,0,0,8
8648,4404,-1668,-1727,-1483,7453,0,0,0
8770,1534,1621,-1824,-1562,7597,0,0,0
8858,1184,-2648,-1992,-1860,8551,1,0,0
8948,-845,-1598,-2006,-1508,7254,0,0,0
9053,-2945,-1738,-1964,-1454,7314,0,0,0
9158,-9315,-1598,-1958,-1579,7259,0,0,0
9263,6084,4071,-1335,-2781,7363,0,0,8
9353,6784,-8108,-1584,-1053,6246,0,0,8
9458,-14285,4071,-2155,-2524,7743,0,0,0
9550,-985,9251,-1583,-2352,13763,0,0,8
9669,-3085,-13708,-1690,-1415,5616,0,0,8
9758,1044,-4958,-1705,-1781,7764,0,0,8
9848,3914,-548,-1952,-1920,7885,0,0,0
9953,3704,-1948,-1886,-1666,7924,0,0,0
10058,-2245,-1598,-1968,-1704,7420,0,0,0
10148,-565,-1948,-1939,-1298,7191,0,0,0
10253,-17785,6661,-2019,-1053,6933,0,0,8
10359,3704,4981,-1727,-1169,8802,0,0,8
10448,-6865,-6568,-2212,-1790,7208,0,0,8
10553,10354,-17908,-5246,-785,4274,0,0,8
10658,3144,-3838,-1077,-523,6910,0,0,8
10763,5734,-2368,-1799,-2524,8694,0,4,0
10853,-1615,-6848,-1354,-1528,7591,0,2,0
10959,-845,-6638,-1054,-1491,7709,1,1,0
1 ms gyroX_mDPS gyroZ_mDPS accelX_mg accelY_mg accelZ_mg moveX moveY flags
2 53 2654 -3418 -1914 -2011 7816 1 0 0
3 158 1324 -2788 -2038 -1965 7618 0 0 0
4 248 4194 -4958 -1972 -1932 7640 1 0 0
5 353 9164 -4538 -2229 -1395 7797 1 0 0
6 443 9654 -5658 -2216 -1850 7761 1 0 0
7 548 6784 -4538 -2045 -2695 8907 0 0 8
8 653 -4695 -6358 -1999 -479 4979 0 0 8
9 743 -285 2881 -2084 -1290 7339 0 0 8
10 848 -775 -1738 -2177 -1265 8638 0 0 0
11 953 -12465 1061 -2411 -1295 8169 0 -1 0
12 1043 5804 5611 -1750 -1631 11380 0 0 8
13 1149 -3365 -5798 -2116 -1461 7408 0 0 8
14 1268 -2385 -2788 -1891 -1037 7346 0 0 0
15 1359 -1965 -618 -2016 -1282 7299 0 0 0
16 1448 -6795 -2718 -1857 -976 8337 0 0 0
17 1553 1114 -338 -2006 -1546 7670 0 0 0
18 1643 -705 -2228 -1974 -828 7469 0 0 0
19 1749 -17155 -128 -1761 -655 -720 0 0 8
20 1854 -13725 2181 -1584 4 7077 0 0 8
21 1958 -705 -3208 -2259 -1596 7595 0 0 0
22 2049 -7075 11071 -1719 -1978 10915 0 0 8
23 2153 -4275 -14548 -1705 -856 5439 0 0 8
24 2243 2304 1341 -1966 -1408 8362 0 0 8
25 2348 -3089 -3632 -2124 -1835 8562 0 0 0
26 2453 2374 -4188 -2072 -1443 7111 1 0 0
27 2543 554 -2298 -2086 -1274 7441 0 0 0
28 2663 2094 -2928 -2025 -1140 6958 0 0 0
29 2753 134 -618 -2103 -1371 7872 0 0 0
30 2843 -9385 2671 -2071 -1233 8861 0 0 0
31 2963 -11135 3511 -1888 -1374 12893 0 0 8
32 3053 -1055 -11398 -2221 -1586 6244 0 0 8
33 3143 20924 -5238 -5474 -2908 5746 0 0 8
34 3248 8604 -4468 -1443 -349 7376 0 0 8
35 3353 -3085 -58 -2151 -1654 8338 0 0 8
36 3443 974 -4678 -1932 -1354 7175 1 0 0
37 3549 3284 1761 -1980 -1151 8339 0 0 0
38 3653 -4975 -2648 -2031 -1042 7637 0 0 0
39 3743 204 -688 -2083 -1310 7454 0 0 0
40 3848 624 -1178 -2139 -1230 7442 0 0 0
41 3953 -9735 -1878 -2098 -1199 7625 0 0 0
42 4043 -5535 10091 -2066 -1651 12571 0 0 8
43 4149 -3995 -13708 -1964 -1238 5689 0 0 8
44 4253 6924 3371 49 -2649 7077 0 0 8
45 4343 5454 -10348 -1555 -436 6547 0 0 8
46 4448 4194 4981 -2105 -1739 9074 0 0 8
47 4553 904 -5098 -1935 -1283 8402 1 0 0
48 4643 1674 -758 -1978 -1211 7202 0 0 0
49 4748 -2455 -1108 -2001 -1116 7934 0 0 0
50 4853 -3715 -2158 -2111 -1310 8041 0 0 0
51 4943 -2385 -618 -2153 -1332 8018 0 0 0
52 5048 -32000 -29108 9536 -10268 15988 0 0 8
53 5153 -18695 -2998 -1580 147 6707 0 0 8
54 5258 -16455 2671 -2461 -2252 8459 0 0 8
55 5348 -32000 9251 -1555 -2178 12371 0 0 8
56 5453 7344 -7968 -1775 -1352 4664 0 0 8
57 5558 7134 -478 -1620 -1572 8487 0 0 8
58 5648 -845 -3628 -2025 -2149 8102 0 0 0
59 5753 4054 -1038 -1802 -1613 7898 0 0 0
60 5858 1394 -3488 -1933 -1464 7686 0 0 0
61 5948 1744 -1178 -2028 -1610 7994 0 0 0
62 6053 -7495 -3558 -1996 -1484 7724 0 0 0
63 6158 -15895 1481 -1772 -1655 13107 0 0 8
64 6250 -1615 -12728 -1875 -1400 6132 0 0 8
65 6353 -565 5051 -550 -3014 7815 0 0 8
66 6458 10564 -9788 -1342 -820 6415 0 0 8
67 6548 9374 4841 -1761 -1659 9666 0 0 8
68 6653 -845 -5308 -1693 -1587 7817 0 0 0
69 6759 4194 -338 -1616 -1276 7454 0 0 0
70 6848 -355 -3208 -1740 -1636 8304 1 0 0
71 6953 -145 -1248 -1906 -1650 7992 0 0 0
72 7058 -16385 2111 -1934 -1912 8066 0 0 0
73 7148 274 3371 -1647 -1974 13521 0 0 8
74 7253 -13585 -11258 -1908 -1610 5902 0 0 8
75 7358 31914 5051 -7768 -850 5010 0 0 8
76 7448 -2875 -11888 -913 30 5893 0 0 8
77 7568 7064 1411 -1979 -2262 9181 0 0 8
78 7658 -1685 -3208 -1719 -1610 7340 0 0 0
79 7749 -285 221 -1597 -1448 7409 0 0 0
80 7853 -1755 -1248 -1718 -1584 7830 0 -1 0
81 7958 -2525 11 -1808 -1567 7926 0 0 0
82 8048 -3015 -1318 -1836 -1547 7910 0 0 0
83 8168 2794 6031 -4147 -1770 8318 0 0 8
84 8259 10914 -898 -1850 -1514 7943 0 0 8
85 8348 -18975 4351 -2237 -2038 7767 0 0 8
86 8453 14554 1761 -1931 -2700 13504 0 0 8
87 8558 -3295 -12588 -2127 -1865 6672 0 0 8
88 8648 4404 -1668 -1727 -1483 7453 0 0 0
89 8770 1534 1621 -1824 -1562 7597 0 0 0
90 8858 1184 -2648 -1992 -1860 8551 1 0 0
91 8948 -845 -1598 -2006 -1508 7254 0 0 0
92 9053 -2945 -1738 -1964 -1454 7314 0 0 0
93 9158 -9315 -1598 -1958 -1579 7259 0 0 0
94 9263 6084 4071 -1335 -2781 7363 0 0 8
95 9353 6784 -8108 -1584 -1053 6246 0 0 8
96 9458 -14285 4071 -2155 -2524 7743 0 0 0
97 9550 -985 9251 -1583 -2352 13763 0 0 8
98 9669 -3085 -13708 -1690 -1415 5616 0 0 8
99 9758 1044 -4958 -1705 -1781 7764 0 0 8
100 9848 3914 -548 -1952 -1920 7885 0 0 0
101 9953 3704 -1948 -1886 -1666 7924 0 0 0
102 10058 -2245 -1598 -1968 -1704 7420 0 0 0
103 10148 -565 -1948 -1939 -1298 7191 0 0 0
104 10253 -17785 6661 -2019 -1053 6933 0 0 8
105 10359 3704 4981 -1727 -1169 8802 0 0 8
106 10448 -6865 -6568 -2212 -1790 7208 0 0 8
107 10553 10354 -17908 -5246 -785 4274 0 0 8
108 10658 3144 -3838 -1077 -523 6910 0 0 8
109 10763 5734 -2368 -1799 -2524 8694 0 4 0
110 10853 -1615 -6848 -1354 -1528 7591 0 2 0
111 10959 -845 -6638 -1054 -1491 7709 1 1 0
+101
View File
@@ -0,0 +1,101 @@
ms,gyroX_mDPS,gyroZ_mDPS,accelX_mg,accelY_mg,accelZ_mg,moveX,moveY,flags
22,-1615,-1388,490,-653,8088,0,0,1
127,-3225,-20638,642,-1626,8062,0,0,8
232,28134,3231,-4,-2987,9007,0,0,8
337,23304,32000,-788,-2774,7141,0,0,8
427,-27375,32000,-1389,-125,4358,0,0,8
532,32000,32000,-813,1591,8309,0,0,8
622,11614,32000,-1680,4802,9191,0,0,8
727,-32000,-32000,-1584,1582,8091,0,0,8
832,-32000,-32000,-1907,-4841,8164,0,0,8
922,32000,-32000,-516,-4739,6249,0,0,8
1027,-32000,32000,1036,-4463,9481,0,0,8
1132,-32000,32000,1527,-4012,10133,0,0,8
1222,32000,32000,431,-4558,10679,0,0,8
1327,32000,7431,-395,-85,1273,0,0,8
1432,32000,-32000,-2574,-1669,6583,0,0,8
1522,32000,-32000,-1241,-1152,7557,0,0,8
1627,8394,32000,1330,-197,9920,0,0,8
1732,-32000,32000,3010,-1147,9109,0,0,8
1822,-18835,32000,3065,2036,5965,0,0,8
1928,7624,-21478,3477,1289,6620,0,0,8
2017,32000,-32000,3441,-173,14186,0,0,8
2122,32000,-32000,3131,-708,9866,0,0,8
2227,-32000,-32000,1951,4893,3125,0,0,8
2332,23724,-32000,-2211,1158,6157,0,0,8
2422,-32000,32000,-2950,-2178,10541,0,0,8
2527,-32000,32000,-1888,-1648,7036,0,0,8
2632,-32000,32000,-1276,2890,7277,0,0,8
2722,-32000,32000,-1426,98,9093,0,0,8
2827,32000,-32000,-963,3726,11083,0,0,8
2947,32000,-32000,-1014,683,7576,0,0,8
3022,-32000,-32000,-1907,4168,4136,0,0,8
3127,13294,-32000,-98,123,9152,0,0,8
3232,-32000,5541,1819,-3706,11170,0,0,8
3322,-32000,32000,4171,-4134,11381,0,0,8
3427,-32000,32000,3301,2672,13136,0,0,8
3547,32000,-16718,-467,-1325,5712,0,0,8
3622,32000,-32000,-1361,-903,3379,0,0,8
3727,-32000,-22808,-915,-2121,10673,0,0,8
3832,-32000,32000,684,-2305,7234,0,0,8
3922,-32000,32000,2752,1440,8629,0,0,8
4027,32000,-32000,2390,8488,12805,0,0,8
4132,32000,-32000,179,-8825,6814,0,0,8
4222,-32000,32000,-1804,330,8674,0,0,8
4327,-32000,32000,749,-2761,8086,0,0,8
4432,32000,-32000,1925,10213,7917,0,0,8
4522,32000,-32000,1509,-5392,12525,0,0,8
4627,-32000,-14758,-2118,1587,11387,0,0,8
4732,-32000,32000,-2454,1181,8622,0,0,8
4822,-32000,32000,-3143,-410,7220,0,0,8
4927,-3295,5961,-3021,2011,5534,0,0,8
5032,32000,32000,-2811,1610,3304,0,0,8
5122,-7215,-14058,-2441,2000,5433,0,0,8
5227,17494,991,1387,3110,5256,0,0,8
5332,26804,32000,5814,-3375,12813,0,0,8
5422,32000,32000,5294,-1148,15988,0,0,8
5527,32000,-32000,6197,6057,5926,0,0,8
5632,32000,-32000,1624,-2200,-1450,0,0,8
5722,-32000,32000,3903,-3211,15988,0,0,8
5827,-31645,32000,4845,3216,12159,0,0,8
5932,32000,-32000,2887,6701,1044,0,0,8
6022,32000,-32000,2135,-7374,3051,0,0,8
6127,-32000,32000,3912,-3769,11455,0,0,8
6232,-19535,32000,2668,-1089,15988,0,0,8
6322,32000,-32000,3034,5062,7107,0,0,8
6427,32000,-32000,1424,-1579,690,0,0,8
6533,-32000,10791,3530,-5723,11332,0,0,8
6622,-32000,32000,4766,-4816,15339,0,0,8
6727,32000,32000,5081,-719,10272,0,0,8
6832,32000,-32000,1938,3361,-169,0,0,8
6937,32000,-32000,2609,-3509,2618,0,0,8
7027,-32000,32000,1979,-2021,10848,0,0,8
7132,-32000,32000,4701,1675,8275,0,0,8
7222,-32000,32000,1546,317,1593,0,0,8
7327,32000,-30368,1482,7474,15988,0,0,8
7447,32000,-32000,1966,92,8261,0,0,8
7522,-985,-5728,-1842,-10103,7470,0,0,8
7627,-32000,32000,1874,1624,6829,0,0,8
7732,13154,-32000,1412,10106,11458,0,0,8
7822,32000,-32000,802,-3234,5995,0,0,8
7927,-32000,32000,2207,-5276,6358,0,0,8
8032,-29055,32000,1160,754,15988,0,0,8
8122,32000,32000,3454,-2017,9495,0,0,8
8227,32000,-32000,635,1623,91,0,0,8
8332,-32000,32000,296,-6341,14428,0,0,8
8422,-32000,32000,3175,1444,9363,0,0,8
8527,32000,-32000,1739,3489,10278,0,0,8
8632,32000,-32000,-756,-7373,10225,0,0,8
8722,-32000,32000,181,-1568,2670,0,0,8
8827,-32000,32000,-1130,2098,15988,0,0,8
8932,32000,-32000,4290,9288,3416,0,0,8
9022,-32000,32000,-873,-8986,5655,0,0,8
9127,-32000,32000,-1324,212,15988,0,0,8
9232,32000,-32000,601,-1361,6462,0,0,8
9322,32000,-32000,745,-1394,1761,0,0,8
9427,-32000,-25258,2857,-3685,12406,0,0,8
9532,32000,-18398,2451,1601,15220,1,2,0
9622,32000,-32000,1236,-7181,13900,0,0,8
9728,-32000,32000,-12,1235,2206,0,0,8
9832,-32000,32000,-674,5741,8810,0,0,8
9922,32000,-32000,-888,-1647,7156,0,0,8
1 ms gyroX_mDPS gyroZ_mDPS accelX_mg accelY_mg accelZ_mg moveX moveY flags
2 22 -1615 -1388 490 -653 8088 0 0 1
3 127 -3225 -20638 642 -1626 8062 0 0 8
4 232 28134 3231 -4 -2987 9007 0 0 8
5 337 23304 32000 -788 -2774 7141 0 0 8
6 427 -27375 32000 -1389 -125 4358 0 0 8
7 532 32000 32000 -813 1591 8309 0 0 8
8 622 11614 32000 -1680 4802 9191 0 0 8
9 727 -32000 -32000 -1584 1582 8091 0 0 8
10 832 -32000 -32000 -1907 -4841 8164 0 0 8
11 922 32000 -32000 -516 -4739 6249 0 0 8
12 1027 -32000 32000 1036 -4463 9481 0 0 8
13 1132 -32000 32000 1527 -4012 10133 0 0 8
14 1222 32000 32000 431 -4558 10679 0 0 8
15 1327 32000 7431 -395 -85 1273 0 0 8
16 1432 32000 -32000 -2574 -1669 6583 0 0 8
17 1522 32000 -32000 -1241 -1152 7557 0 0 8
18 1627 8394 32000 1330 -197 9920 0 0 8
19 1732 -32000 32000 3010 -1147 9109 0 0 8
20 1822 -18835 32000 3065 2036 5965 0 0 8
21 1928 7624 -21478 3477 1289 6620 0 0 8
22 2017 32000 -32000 3441 -173 14186 0 0 8
23 2122 32000 -32000 3131 -708 9866 0 0 8
24 2227 -32000 -32000 1951 4893 3125 0 0 8
25 2332 23724 -32000 -2211 1158 6157 0 0 8
26 2422 -32000 32000 -2950 -2178 10541 0 0 8
27 2527 -32000 32000 -1888 -1648 7036 0 0 8
28 2632 -32000 32000 -1276 2890 7277 0 0 8
29 2722 -32000 32000 -1426 98 9093 0 0 8
30 2827 32000 -32000 -963 3726 11083 0 0 8
31 2947 32000 -32000 -1014 683 7576 0 0 8
32 3022 -32000 -32000 -1907 4168 4136 0 0 8
33 3127 13294 -32000 -98 123 9152 0 0 8
34 3232 -32000 5541 1819 -3706 11170 0 0 8
35 3322 -32000 32000 4171 -4134 11381 0 0 8
36 3427 -32000 32000 3301 2672 13136 0 0 8
37 3547 32000 -16718 -467 -1325 5712 0 0 8
38 3622 32000 -32000 -1361 -903 3379 0 0 8
39 3727 -32000 -22808 -915 -2121 10673 0 0 8
40 3832 -32000 32000 684 -2305 7234 0 0 8
41 3922 -32000 32000 2752 1440 8629 0 0 8
42 4027 32000 -32000 2390 8488 12805 0 0 8
43 4132 32000 -32000 179 -8825 6814 0 0 8
44 4222 -32000 32000 -1804 330 8674 0 0 8
45 4327 -32000 32000 749 -2761 8086 0 0 8
46 4432 32000 -32000 1925 10213 7917 0 0 8
47 4522 32000 -32000 1509 -5392 12525 0 0 8
48 4627 -32000 -14758 -2118 1587 11387 0 0 8
49 4732 -32000 32000 -2454 1181 8622 0 0 8
50 4822 -32000 32000 -3143 -410 7220 0 0 8
51 4927 -3295 5961 -3021 2011 5534 0 0 8
52 5032 32000 32000 -2811 1610 3304 0 0 8
53 5122 -7215 -14058 -2441 2000 5433 0 0 8
54 5227 17494 991 1387 3110 5256 0 0 8
55 5332 26804 32000 5814 -3375 12813 0 0 8
56 5422 32000 32000 5294 -1148 15988 0 0 8
57 5527 32000 -32000 6197 6057 5926 0 0 8
58 5632 32000 -32000 1624 -2200 -1450 0 0 8
59 5722 -32000 32000 3903 -3211 15988 0 0 8
60 5827 -31645 32000 4845 3216 12159 0 0 8
61 5932 32000 -32000 2887 6701 1044 0 0 8
62 6022 32000 -32000 2135 -7374 3051 0 0 8
63 6127 -32000 32000 3912 -3769 11455 0 0 8
64 6232 -19535 32000 2668 -1089 15988 0 0 8
65 6322 32000 -32000 3034 5062 7107 0 0 8
66 6427 32000 -32000 1424 -1579 690 0 0 8
67 6533 -32000 10791 3530 -5723 11332 0 0 8
68 6622 -32000 32000 4766 -4816 15339 0 0 8
69 6727 32000 32000 5081 -719 10272 0 0 8
70 6832 32000 -32000 1938 3361 -169 0 0 8
71 6937 32000 -32000 2609 -3509 2618 0 0 8
72 7027 -32000 32000 1979 -2021 10848 0 0 8
73 7132 -32000 32000 4701 1675 8275 0 0 8
74 7222 -32000 32000 1546 317 1593 0 0 8
75 7327 32000 -30368 1482 7474 15988 0 0 8
76 7447 32000 -32000 1966 92 8261 0 0 8
77 7522 -985 -5728 -1842 -10103 7470 0 0 8
78 7627 -32000 32000 1874 1624 6829 0 0 8
79 7732 13154 -32000 1412 10106 11458 0 0 8
80 7822 32000 -32000 802 -3234 5995 0 0 8
81 7927 -32000 32000 2207 -5276 6358 0 0 8
82 8032 -29055 32000 1160 754 15988 0 0 8
83 8122 32000 32000 3454 -2017 9495 0 0 8
84 8227 32000 -32000 635 1623 91 0 0 8
85 8332 -32000 32000 296 -6341 14428 0 0 8
86 8422 -32000 32000 3175 1444 9363 0 0 8
87 8527 32000 -32000 1739 3489 10278 0 0 8
88 8632 32000 -32000 -756 -7373 10225 0 0 8
89 8722 -32000 32000 181 -1568 2670 0 0 8
90 8827 -32000 32000 -1130 2098 15988 0 0 8
91 8932 32000 -32000 4290 9288 3416 0 0 8
92 9022 -32000 32000 -873 -8986 5655 0 0 8
93 9127 -32000 32000 -1324 212 15988 0 0 8
94 9232 32000 -32000 601 -1361 6462 0 0 8
95 9322 32000 -32000 745 -1394 1761 0 0 8
96 9427 -32000 -25258 2857 -3685 12406 0 0 8
97 9532 32000 -18398 2451 1601 15220 1 2 0
98 9622 32000 -32000 1236 -7181 13900 0 0 8
99 9728 -32000 32000 -12 1235 2206 0 0 8
100 9832 -32000 32000 -674 5741 8810 0 0 8
101 9922 32000 -32000 -888 -1647 7156 0 0 8
+53
View File
@@ -0,0 +1,53 @@
"""
PlatformIO post-build script: generates a Nordic DFU package (.zip) from the
built firmware .hex using adafruit-nrfutil.
The resulting firmware_dfu.zip can be uploaded to the device via:
- nRF Connect mobile app (iOS / Android) after triggering OTA mode
- nRF Connect for Desktop
- adafruit-nrfutil over BLE (advanced)
Trigger OTA mode on the device:
- Send BLE command 0x02 to cfgCommand (0x1236), OR
- Type 'o' in the serial monitor
Usage: referenced from platformio.ini as:
extra_scripts = pre:scripts/git_hash.py, post:scripts/generate_dfu.py
"""
import subprocess, os
Import("env") # noqa: F821 - PlatformIO injects this
def generate_dfu_package(source, target, env):
build_dir = env.subst("$BUILD_DIR")
project_dir = env.subst("$PROJECT_DIR")
hex_path = os.path.join(build_dir, "firmware.hex")
if not os.path.exists(hex_path):
print(f"[generate_dfu] firmware.hex not found at {hex_path}, skipping")
return
out_path = os.path.join(project_dir, "firmware_dfu.zip")
try:
result = subprocess.run(
[
"adafruit-nrfutil", "dfu", "genpkg",
"--dev-type", "0x0052", # nRF52840
"--application", hex_path,
out_path,
],
capture_output=True,
text=True,
)
if result.returncode == 0:
size_kb = os.path.getsize(out_path) / 1024
print(f"[generate_dfu] DFU package ready: firmware_dfu.zip ({size_kb:.1f} KB)")
print(f"[generate_dfu] Upload with nRF Connect after sending OTA command (0x02) via BLE")
else:
print(f"[generate_dfu] adafruit-nrfutil error: {result.stderr.strip()}")
except FileNotFoundError:
print("[generate_dfu] adafruit-nrfutil not found - skipping DFU package generation")
print("[generate_dfu] Install with: pip install adafruit-nrfutil")
env.AddPostAction("$BUILD_DIR/firmware.hex", generate_dfu_package) # noqa: F821
+40
View File
@@ -0,0 +1,40 @@
"""
PlatformIO pre-build script: injects the short git commit hash into firmware
as GIT_HASH (a C string literal), and writes web/version.js so the web UI
can compare against it.
Usage: referenced from platformio.ini as:
extra_scripts = pre:scripts/git_hash.py
"""
import subprocess, os, re
Import("env") # noqa: F821 - PlatformIO injects this
def get_git_hash():
try:
h = subprocess.check_output(
["git", "rev-parse", "--short=7", "HEAD"],
cwd=env.subst("$PROJECT_DIR"), # noqa: F821
stderr=subprocess.DEVNULL,
).decode().strip()
# Verify it looks like a hex hash (safety check)
if re.fullmatch(r"[0-9a-f]{4,12}", h):
return h
except Exception:
pass
return "unknown"
git_hash = get_git_hash()
print(f"[git_hash] short hash = {git_hash}")
# Inject into firmware build
env.Append(CPPDEFINES=[("GIT_HASH", f'\\"{git_hash}\\"')]) # noqa: F821
# 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"const FIRMWARE_BUILD_HASH = '{git_hash}';\n")
print(f"[git_hash] wrote {ver_file}")
+13 -5
View File
@@ -13,14 +13,17 @@ 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);
}
float readBatteryVoltage() {
// 8 quick reads, no delay() calls, no analogReference() change
int32_t raw=0; for (int i=0; i<8; i++) raw += analogRead(PIN_VBAT_READ); raw /= 8;
return (raw / 4096.0f) * 3.0f * 2.0f;
// Seeed XIAO nRF52840 Sense: 1MΩ + 510kΩ voltage divider on VBAT.
// Theoretical ratio is 1510/510 = 2.961, but real resistor tolerances
// shift the actual ratio. Calibrated: 3.90V actual / 3.78V reported → ×1.0317.
return (raw / 4096.0f) * 3.0f * (1510.0f / 510.0f) * 1.0317f;
}
int batteryPercent(float v) {
@@ -31,15 +34,20 @@ 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;
blebas.write(pct);
// 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.notify(pct);
lastChargeStatus = status;
#ifdef FEATURE_TELEMETRY
telem.chargeStatus = (uint8_t)status;
#endif
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]);
if (status == CHGSTAT_DISCHARGING && v < BATT_CRITICAL)
Serial.print(pct); Serial.print("% "); Serial.print(st[status]);
Serial.print(" (PIN_CHG="); Serial.print(digitalRead(PIN_CHG)); Serial.println(")");
// 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); }
}
+44 -16
View File
@@ -1,16 +1,23 @@
#include "ble_config.h"
#include "tap.h"
#include "battery.h"
#include "buttons.h"
#include <Adafruit_LittleFS.h>
#include <InternalFileSystem.h>
using namespace Adafruit_LittleFS_Namespace;
extern File cfgFile;
// ─── BLE Config Service objects ───────────────────────────────────────────────
// BLE Config Service objects
#ifndef GIT_HASH
#define GIT_HASH "unknown"
#endif
#ifdef FEATURE_CONFIG_SERVICE
BLEService cfgService (0x1234);
BLECharacteristic cfgBlob (0x1235); // ConfigBlob R/W 20 bytes
BLECharacteristic cfgCommand (0x1236); // Command W 1 byte
BLECharacteristic cfgGitHash (0x1239); // GitHash R 8 bytes (7-char hash + NUL)
#ifdef FEATURE_TELEMETRY
BLECharacteristic cfgTelemetry(0x1237); // Telemetry R/N 24 bytes
#endif
@@ -19,18 +26,17 @@ BLECharacteristic cfgCommand (0x1236); // Command W 1 byte
#endif
#endif
// ─── Charge mode ──────────────────────────────────────────────────────────────
// Charge mode
void applyChargeMode(ChargeMode mode) {
switch (mode) {
case CHARGE_OFF: pinMode(PIN_HICHG, INPUT_PULLUP); break;
case CHARGE_SLOW: pinMode(PIN_HICHG, OUTPUT); digitalWrite(PIN_HICHG, HIGH); break;
case CHARGE_SLOW: pinMode(PIN_HICHG, INPUT); break;
case CHARGE_FAST: pinMode(PIN_HICHG, OUTPUT); digitalWrite(PIN_HICHG, LOW); break;
}
const char* n[] = {"OFF (~0mA)", "SLOW (50mA)", "FAST (100mA)"};
const char* n[] = {"SLOW (50mA)", "FAST (100mA)"};
Serial.print("[CHG] "); Serial.println(n[mode]);
}
// ─── Config persistence ───────────────────────────────────────────────────────
// Config persistence
void loadConfig() {
InternalFS.begin();
cfgFile.open(CONFIG_FILENAME, FILE_O_READ);
@@ -45,13 +51,16 @@ void loadConfig() {
}
void saveConfig() {
unsigned long t0 = millis();
InternalFS.remove(CONFIG_FILENAME);
cfgFile.open(CONFIG_FILENAME, FILE_O_WRITE);
if (cfgFile) { cfgFile.write((uint8_t*)&cfg, sizeof(cfg)); cfgFile.close(); Serial.println("[CFG] Saved"); }
else { Serial.println("[CFG] ERROR: write failed"); }
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)"); }
else { Serial.println("[CFG] Saved"); }
}
// ─── ConfigBlob push ─────────────────────────────────────────────────────────
// ConfigBlob push
#ifdef FEATURE_CONFIG_SERVICE
void pushConfigBlob() {
ConfigBlob b;
@@ -65,7 +74,9 @@ void pushConfigBlob() {
b.tapAction = (uint8_t)cfg.tapAction;
b.tapKey = cfg.tapKey;
b.tapMod = cfg.tapMod;
b._pad = 0;
b.tapFreezeEnabled = cfg.tapFreezeEnabled;
b.jerkThreshold = cfg.jerkThreshold;
b.featureFlags = cfg.featureFlags;
cfgBlob.write((uint8_t*)&b, sizeof(b));
}
#endif
@@ -88,7 +99,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; }
@@ -98,7 +109,7 @@ void onConfigBlobWrite(uint16_t h, BLECharacteristic* c, uint8_t* d, uint16_t l)
cfg.accelStrength = b->accelStrength;
if (b->curve <= 2) cfg.curve = (CurveType)b->curve;
cfg.axisFlip = b->axisFlip;
if (b->chargeMode <= 2) { cfg.chargeMode = (ChargeMode)b->chargeMode; applyChargeMode(cfg.chargeMode); }
if (b->chargeMode <= 1) { cfg.chargeMode = (ChargeMode)b->chargeMode; applyChargeMode(cfg.chargeMode); }
#ifdef FEATURE_TAP_DETECTION
if (b->tapThreshold >= 1 && b->tapThreshold <= 31) {
cfg.tapThreshold = b->tapThreshold;
@@ -108,8 +119,11 @@ void onConfigBlobWrite(uint16_t h, BLECharacteristic* c, uint8_t* d, uint16_t l)
cfg.tapKey = b->tapKey;
cfg.tapMod = b->tapMod;
#endif
cfg.tapFreezeEnabled = b->tapFreezeEnabled ? 1 : 0;
if (b->jerkThreshold >= 100.0f && b->jerkThreshold <= 50000.0f) cfg.jerkThreshold = b->jerkThreshold;
cfg.featureFlags = b->featureFlags & (FLAG_TAP_ENABLED | FLAG_TEMP_COMP_ENABLED | FLAG_AUTO_RECAL_ENABLED);
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);
@@ -119,6 +133,9 @@ void onCommandWrite(uint16_t h, BLECharacteristic* c, uint8_t* d, uint16_t l) {
if (l < 1) return;
if (d[0] == 0x01) pendingCal = true;
if (d[0] == 0xFF) pendingReset = true;
#ifdef FEATURE_OTA
if (d[0] == 0x02) pendingOTA = true;
#endif
}
#ifdef FEATURE_IMU_STREAM
@@ -128,7 +145,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();
@@ -139,12 +156,20 @@ void setupConfigService() {
cfgBlob.begin();
pushConfigBlob();
cfgCommand.setProperties(CHR_PROPS_WRITE);
cfgCommand.setProperties(CHR_PROPS_WRITE | CHR_PROPS_WRITE_WO_RESP);
cfgCommand.setPermission(SECMODE_OPEN, SECMODE_OPEN);
cfgCommand.setFixedLen(1);
cfgCommand.setWriteCallback(onCommandWrite);
cfgCommand.begin();
// 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);
cfgGitHash.begin();
{ uint8_t buf[8] = {}; strncpy((char*)buf, GIT_HASH, 7); cfgGitHash.write(buf, 8); }
Serial.print("[BUILD] git="); Serial.println(GIT_HASH);
#ifdef FEATURE_TELEMETRY
cfgTelemetry.setProperties(CHR_PROPS_READ | CHR_PROPS_NOTIFY);
cfgTelemetry.setPermission(SECMODE_OPEN, SECMODE_NO_ACCESS);
@@ -173,7 +198,7 @@ void setupConfigService() {
}
#endif // FEATURE_CONFIG_SERVICE
// ─── Telemetry push ───────────────────────────────────────────────────────────
// Telemetry push
#ifdef FEATURE_TELEMETRY
void pushTelemetry(unsigned long now) {
telem.uptimeSeconds = now / 1000;
@@ -184,6 +209,9 @@ void pushTelemetry(unsigned long now) {
telem.leftClicks = statLeftClicks;
telem.rightClicks = statRightClicks;
#endif
#ifdef FEATURE_BATTERY_MONITOR
telem.battVoltage = readBatteryVoltage();
#endif
cfgTelemetry.write ((uint8_t*)&telem, sizeof(telem));
cfgTelemetry.notify((uint8_t*)&telem, sizeof(telem));
}
+1
View File
@@ -7,6 +7,7 @@
extern BLEService cfgService;
extern BLECharacteristic cfgBlob;
extern BLECharacteristic cfgCommand;
extern BLECharacteristic cfgGitHash;
#ifdef FEATURE_TELEMETRY
extern BLECharacteristic cfgTelemetry;
#endif
+96
View File
@@ -0,0 +1,96 @@
#include "buttons.h"
#ifdef FEATURE_PHYSICAL_BUTTONS
#include <bluefruit.h>
extern BLEHidAdafruit blehid;
extern Config cfg;
static uint8_t physBtnMask = 0;
static uint8_t rawMaskPrev = 0;
static unsigned long debounceMs = 0;
static const unsigned long DEBOUNCE_MS = 20;
// Double-press detection for left button
static const unsigned long DOUBLE_PRESS_MS = 400; // max gap between two releases
static const unsigned long KEY_HOLD_MS = 60; // how long to hold the key down
static unsigned long lastLeftReleaseMs = 0;
static unsigned long keyDownUntil = 0;
// Setup
void setupPhysicalButtons() {
// Release any held physical buttons before reconfiguring
if (physBtnMask && Bluefruit.connected()) { blehid.mouseButtonRelease(); }
physBtnMask = 0;
if (BTN_LEFT_PIN != BTN_PIN_NONE) pinMode(BTN_LEFT_PIN, INPUT_PULLUP);
if (BTN_RIGHT_PIN != BTN_PIN_NONE) pinMode(BTN_RIGHT_PIN, INPUT_PULLUP);
if (BTN_MIDDLE_PIN != BTN_PIN_NONE) pinMode(BTN_MIDDLE_PIN, INPUT_PULLUP);
bool any = (BTN_LEFT_PIN != BTN_PIN_NONE) || (BTN_RIGHT_PIN != BTN_PIN_NONE)
|| (BTN_MIDDLE_PIN != BTN_PIN_NONE);
if (any) {
Serial.print("[BTN] L=");
BTN_LEFT_PIN == BTN_PIN_NONE ? Serial.print("--") : Serial.print(BTN_LEFT_PIN);
Serial.print(" R=");
BTN_RIGHT_PIN == BTN_PIN_NONE ? Serial.print("--") : Serial.print(BTN_RIGHT_PIN);
Serial.print(" M=");
BTN_MIDDLE_PIN == BTN_PIN_NONE ? Serial.print("--") : Serial.print(BTN_MIDDLE_PIN);
Serial.println();
}
}
// 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() {
if (!Bluefruit.connected()) return;
unsigned long now = millis();
// Release held key combo after KEY_HOLD_MS
if (keyDownUntil && now >= keyDownUntil) {
uint8_t noKeys[6] = {};
blehid.keyboardReport(0, noKeys);
keyDownUntil = 0;
Serial.println("[BTN] key release");
}
uint8_t rawMask = 0;
if (BTN_LEFT_PIN != BTN_PIN_NONE && digitalRead(BTN_LEFT_PIN) == LOW) rawMask |= MOUSE_BUTTON_LEFT;
if (BTN_RIGHT_PIN != BTN_PIN_NONE && digitalRead(BTN_RIGHT_PIN) == LOW) rawMask |= MOUSE_BUTTON_RIGHT;
if (BTN_MIDDLE_PIN != BTN_PIN_NONE && digitalRead(BTN_MIDDLE_PIN) == LOW) rawMask |= MOUSE_BUTTON_MIDDLE;
if (rawMask != rawMaskPrev) { rawMaskPrev = rawMask; debounceMs = now; }
if (rawMask != physBtnMask && (now - debounceMs >= DEBOUNCE_MS)) {
uint8_t newMask = rawMask;
uint8_t pressed = newMask & ~physBtnMask;
uint8_t released = physBtnMask & ~newMask;
physBtnMask = newMask;
if (physBtnMask) blehid.mouseButtonPress(physBtnMask);
else blehid.mouseButtonRelease();
if (pressed & MOUSE_BUTTON_LEFT) Serial.println("[BTN] L press");
if (pressed & MOUSE_BUTTON_RIGHT) Serial.println("[BTN] R press");
if (pressed & MOUSE_BUTTON_MIDDLE) Serial.println("[BTN] M press");
if (released & MOUSE_BUTTON_LEFT) {
unsigned long gap = lastLeftReleaseMs ? (now - lastLeftReleaseMs) : 0;
Serial.print("[BTN] L release - gap="); Serial.print(gap);
Serial.print("ms (max="); Serial.print(DOUBLE_PRESS_MS); Serial.println("ms)");
// Double-press detection: two short presses → fire key combo
if (lastLeftReleaseMs && (gap <= DOUBLE_PRESS_MS)) {
uint8_t keys[6] = {cfg.tapKey, 0, 0, 0, 0, 0};
blehid.keyboardReport(cfg.tapMod, keys);
keyDownUntil = now + KEY_HOLD_MS;
lastLeftReleaseMs = 0;
Serial.print("[BTN] Double-press → key 0x"); Serial.print(cfg.tapKey, HEX);
Serial.print(" mod 0x"); Serial.println(cfg.tapMod, HEX);
} else {
lastLeftReleaseMs = now;
}
}
if (released & MOUSE_BUTTON_RIGHT) Serial.println("[BTN] R release");
if (released & MOUSE_BUTTON_MIDDLE) Serial.println("[BTN] M release");
}
}
#endif // FEATURE_PHYSICAL_BUTTONS
+7
View File
@@ -0,0 +1,7 @@
#pragma once
#include "config.h"
#ifdef FEATURE_PHYSICAL_BUTTONS
void setupPhysicalButtons();
void processPhysicalButtons();
#endif
+49 -25
View File
@@ -1,23 +1,25 @@
#pragma once
#include <Arduino.h>
// ─── Feature Flags ────────────────────────────────────────────────────────────
// Feature Flags
#define FEATURE_CONFIG_SERVICE
#define FEATURE_TELEMETRY
#define FEATURE_IMU_STREAM
#define FEATURE_TAP_DETECTION
// #define FEATURE_TAP_DETECTION
#define FEATURE_TEMP_COMPENSATION
#define FEATURE_AUTO_RECAL
#define FEATURE_BATTERY_MONITOR
#define FEATURE_BOOT_LOOP_DETECT
#define FEATURE_PHYSICAL_BUTTONS
#define FEATURE_OTA
// ─── Debug ────────────────────────────────────────────────────────────────────
// Debug
// #define DEBUG
// ─── ATT table size ───────────────────────────────────────────────────────────
// ATT table size
#define _ATT_BASE 900
#ifdef FEATURE_CONFIG_SERVICE
#define _ATT_CFG 80
#define _ATT_CFG 100 // +20 for cfgGitHash characteristic
#else
#define _ATT_CFG 0
#endif
@@ -34,7 +36,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
@@ -45,22 +47,37 @@
#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 0xDEAD1239UL
#define CONFIG_MAGIC 0xDEAD123EUL
// ─── Enums ────────────────────────────────────────────────────────────────────
// Physical button pin assignments (hardcoded - set to 0xFF to disable a button)
// Valid pin numbers: 0-10 (Arduino D0-D10 on XIAO nRF52840 Sense)
#define BTN_PIN_NONE 0xFF
#define BTN_LEFT_PIN 1 // D1, active-low to GND
#define BTN_RIGHT_PIN BTN_PIN_NONE // e.g. 1 for D1
#define BTN_MIDDLE_PIN BTN_PIN_NONE // e.g. 2 for D2
// 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)
#define FLAG_TEMP_COMP_ENABLED 0x02 // Temperature gyro-drift compensation
#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
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_SLOW=0, CHARGE_FAST=1 };
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 {
@@ -70,7 +87,7 @@ enum TapAction : uint8_t {
TAP_ACTION_KEY = 3,
};
// ─── Config (stored in flash) ─────────────────────────────────────────────────
// Config (stored in flash)
struct Config {
uint32_t magic;
float sensitivity;
@@ -83,11 +100,14 @@ struct Config {
TapAction tapAction; // what a double-tap does
uint8_t tapKey; // HID keycode (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
uint8_t tapFreezeEnabled; // 1 = enable jerk-based cursor freeze during taps
uint8_t featureFlags; // bitmask of FLAG_* - runtime feature overrides
};
extern Config cfg;
extern const Config CFG_DEFAULTS;
// ─── ConfigBlob (over BLE, 20 bytes) ─────────────────────────────────────────
// ConfigBlob (over BLE, 25 bytes)
struct __attribute__((packed)) ConfigBlob {
float sensitivity; // [0]
float deadZone; // [4]
@@ -99,11 +119,13 @@ struct __attribute__((packed)) ConfigBlob {
uint8_t tapAction; // [16] TapAction enum
uint8_t tapKey; // [17] HID keycode
uint8_t tapMod; // [18] HID modifier
uint8_t _pad; // [19]
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
};
static_assert(sizeof(ConfigBlob) == 20, "ConfigBlob must be 20 bytes");
static_assert(sizeof(ConfigBlob) == 25, "ConfigBlob must be 25 bytes");
// ─── TelemetryPacket (24 bytes) ───────────────────────────────────────────────
// TelemetryPacket (24 bytes)
#ifdef FEATURE_TELEMETRY
struct __attribute__((packed)) TelemetryPacket {
uint32_t uptimeSeconds; // [0]
@@ -114,16 +136,17 @@ struct __attribute__((packed)) TelemetryPacket {
uint16_t recalCount; // [20]
uint8_t chargeStatus; // [22]
uint8_t _pad; // [23]
float battVoltage; // [24] raw battery voltage (V)
};
static_assert(sizeof(TelemetryPacket) == 24, "TelemetryPacket must be 24 bytes");
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 gyroY_mDPS; // [0]
int16_t gyroZ_mDPS; // [2]
int16_t gyroX_mDPS; // [0] pitch axis (nod up/down → cursor Y)
int16_t gyroZ_mDPS; // [2] yaw axis (pan left/right → cursor X)
int16_t accelX_mg; // [4]
int16_t accelY_mg; // [6]
int16_t accelZ_mg; // [8]
@@ -135,8 +158,7 @@ struct __attribute__((packed)) ImuPacket {
static_assert(sizeof(ImuPacket) == 14, "ImuPacket must be 14 bytes");
#endif
// ─── Tuning constants ─────────────────────────────────────────────────────────
extern const float ALPHA;
// Tuning constants
extern const int LOOP_RATE_MS;
extern const int BIAS_SAMPLES;
extern const int IDLE_FRAMES;
@@ -161,8 +183,7 @@ extern const float BATT_CRITICAL;
extern const unsigned long AUTO_RECAL_MS;
#endif
// ─── Global state ─────────────────────────────────────────────────────────────
extern float angleX, angleY;
// Global state
extern float accumX, accumY;
extern float biasGX, biasGY, biasGZ;
extern float calTempC;
@@ -182,6 +203,9 @@ extern float cachedTempC;
extern bool pendingCal;
extern bool pendingReset;
#ifdef FEATURE_OTA
extern bool pendingOTA;
#endif
extern ChargeStatus lastChargeStatus;
extern int idleFrames;
extern unsigned long idleStartMs;
+6 -5
View File
@@ -1,9 +1,10 @@
#include "imu.h"
#include "Wire.h"
#include <math.h>
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();
@@ -15,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;
@@ -33,7 +34,7 @@ void calibrateGyroBias() {
biasGY = (float)(sy/BIAS_SAMPLES);
biasGZ = (float)(sz/BIAS_SAMPLES);
calTempC = readIMUTemp();
angleX = angleY = accumX = accumY = 0.0f;
accumX = accumY = 0.0f;
#ifdef FEATURE_TELEMETRY
statRecalCount++;
@@ -48,7 +49,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;
+158 -77
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, ~100 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
@@ -32,44 +17,46 @@
#include "imu.h"
#include "ble_config.h"
#include "battery.h"
#include "tap.h"
#include "buttons.h"
#include <bluefruit.h>
#include <Adafruit_LittleFS.h>
#include <InternalFileSystem.h>
#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,
/*tapThreshold=*/12, /*tapAction=*/TAP_ACTION_LEFT, /*tapKey=*/0, /*tapMod=*/0
/*tapThreshold=*/12, /*tapAction=*/TAP_ACTION_KEY, /*tapKey=*/0x04, /*tapMod=*/0x03, // Ctrl+Shift+A
/*jerkThreshold=*/2000.0f, /*tapFreezeEnabled=*/1, /*featureFlags=*/FLAG_ALL_DEFAULT
};
// ─── Telemetry definition ─────────────────────────────────────────────────────
// Telemetry definition
#ifdef FEATURE_TELEMETRY
TelemetryPacket telem = {};
#endif
// ─── Tuning constants ─────────────────────────────────────────────────────────
const float ALPHA = 0.96f;
// Tuning constants
const int LOOP_RATE_MS = 10;
const float SMOOTH_ALPHA = 0.65f; // single-pole low-pass for cursor smoothing
const int BIAS_SAMPLES = 200;
const int IDLE_FRAMES = 150;
const unsigned long BATT_REPORT_MS = 20000;
@@ -78,7 +65,7 @@ const unsigned long HEARTBEAT_MS = 10000;
const int HEARTBEAT_DUR = 30;
const unsigned long BOOT_SAFE_MS = 5000;
#ifdef FEATURE_IMU_STREAM
const unsigned long IMU_STREAM_RATE_MS = 50;
const unsigned long IMU_STREAM_RATE_MS = 20;
#endif
const float BATT_FULL = 4.20f;
const float BATT_EMPTY = 3.00f;
@@ -93,8 +80,7 @@ const float BATT_CRITICAL = 3.10f;
const unsigned long AUTO_RECAL_MS = 5UL * 60UL * 1000UL;
#endif
// ─── Global state definitions ─────────────────────────────────────────────────
float angleX = 0, angleY = 0;
// Global state definitions
float accumX = 0, accumY = 0;
float biasGX = 0, biasGY = 0, biasGZ = 0;
float calTempC = 25.0f;
@@ -110,10 +96,25 @@ float cachedTempC = 25.0f;
#ifdef FEATURE_IMU_STREAM
bool imuStreamEnabled = false;
uint32_t streamNotifyFails = 0;
uint32_t streamNotifyOk = 0;
unsigned long lastStreamDiag = 0;
// Back-off state: after STREAM_BACKOFF_THRESH consecutive fails, skip notifies
// for STREAM_BACKOFF_MS to let the SoftDevice HVN TX semaphore drain.
// Without this, every notify() blocks for BLE_GENERIC_TIMEOUT (100ms).
uint8_t streamConsecFails = 0;
unsigned long streamBackoffUntil = 0;
const uint8_t STREAM_BACKOFF_THRESH = 2; // fails before backing off
const unsigned long STREAM_BACKOFF_MS = 500; // cooldown window
#endif
uint32_t loopStalls = 0; // loop iterations where dt > 20ms (behind schedule)
bool pendingCal = false;
bool pendingReset = false;
#ifdef FEATURE_OTA
bool pendingOTA = false;
#endif
ChargeStatus lastChargeStatus = CHGSTAT_DISCHARGING;
@@ -136,7 +137,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();
@@ -152,7 +153,7 @@ static void startAdvertising() {
Bluefruit.Advertising.start(0);
}
// ─── Setup ────────────────────────────────────────────────────────────────────
// Setup
void setup() {
Serial.begin(115200);
unsigned long serialWait = millis();
@@ -163,14 +164,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
}
@@ -189,7 +190,7 @@ void setup() {
Bluefruit.begin(1, 0);
Bluefruit.setTxPower(4);
Bluefruit.setName(safeMode ? "IMU Mouse (safe)" : "IMU Mouse");
Bluefruit.Periph.setConnInterval(12, 24); // 15-30ms — less aggressive, prevents stream disconnect
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) {
@@ -199,7 +200,11 @@ void setup() {
Serial.println("[OK] IMU ready");
#ifdef FEATURE_TAP_DETECTION
setupTapDetection();
if (cfg.featureFlags & FLAG_TAP_ENABLED) setupTapDetection();
#endif
#ifdef FEATURE_PHYSICAL_BUTTONS
setupPhysicalButtons();
#endif
cachedTempC = readIMUTemp();
@@ -211,6 +216,8 @@ void setup() {
calibrateGyroBias();
sleepManagerInit();
bledis.setManufacturer("Seeed Studio");
bledis.setModel("XIAO nRF52840 Sense");
bledis.begin();
@@ -218,7 +225,7 @@ void setup() {
blehid.begin();
#ifdef FEATURE_BATTERY_MONITOR
blebas.begin(); blebas.write(100);
blebas.begin(); blebas.write(batteryPercent(readBatteryVoltage()));
#endif
#ifdef FEATURE_CONFIG_SERVICE
@@ -231,7 +238,7 @@ void setup() {
#endif
startAdvertising();
Serial.print("[OK] Advertising features:");
Serial.print("[OK] Advertising - features:");
#ifdef FEATURE_CONFIG_SERVICE
Serial.print(" CFG");
#endif
@@ -256,13 +263,17 @@ void setup() {
#ifdef FEATURE_BOOT_LOOP_DETECT
Serial.print(" BOOTDET");
#endif
#ifdef FEATURE_PHYSICAL_BUTTONS
Serial.print(" PHYSBTN");
#endif
Serial.print(" SLEEP");
Serial.println();
bootStartMs = millis();
lastTime = lastBattTime = lastHeartbeat = lastTelemetry = millis();
}
// ─── Loop ─────────────────────────────────────────────────────────────────────
// Loop
void loop() {
unsigned long now = millis();
@@ -270,19 +281,39 @@ 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
// Serial commands: 'c' = calibrate, 'r' = factory reset
// Serial commands: 'c' = calibrate, 'r' = factory reset, 'd' = axis diagnostic
static unsigned long diagUntil = 0;
while (Serial.available()) {
char cmd = Serial.read();
if (cmd == 'c') { Serial.println("[SERIAL] Calibrate"); pendingCal = true; }
if (cmd == 'r') { Serial.println("[SERIAL] Reset"); pendingReset = true; }
if (cmd == 'd') { Serial.println("[DIAG] Printing raw gyro for 10s — pan, nod, roll one at a time"); diagUntil = now + 10000; }
#ifdef FEATURE_OTA
if (cmd == 'o') { Serial.println("[SERIAL] OTA DFU"); pendingOTA = true; }
#endif
}
if (pendingCal) { pendingCal = false; calibrateGyroBias(); }
if (pendingReset) { pendingReset = false; factoryReset(); }
#ifdef FEATURE_OTA
if (pendingOTA) {
pendingOTA = false;
Serial.println("[OTA] Disconnecting BLE and entering bootloader DFU mode...");
Serial.flush();
// Gracefully close the BLE connection first so the host can detect the
// disconnect and be ready to see DfuTarg advertise after the reboot.
if (Bluefruit.connected()) {
Bluefruit.disconnect(0);
delay(300);
}
delay(200);
enterOTADfu(); // Adafruit nRF52 core: sets GPREGRET correctly and resets into bootloader OTA mode
}
#endif
// Heartbeat LED
if (now - lastHeartbeat >= HEARTBEAT_MS) {
@@ -296,13 +327,25 @@ void loop() {
#endif
#ifdef FEATURE_TAP_DETECTION
processTaps(now);
if (cfg.featureFlags & FLAG_TAP_ENABLED) processTaps(now);
#endif
#ifdef FEATURE_PHYSICAL_BUTTONS
processPhysicalButtons();
#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;
float dt = (now - lastTime) / 1000.0f;
lastTime = now;
if (dt <= 0.0f || dt > 0.5f) return;
// Threshold 50ms: intentional heartbeat blink (30ms) won't false-trigger;
// real SoftDevice stalls (100ms+) and unexpected delays still get flagged.
if (dt > 0.050f) { loopStalls++; Serial.print("[STALL] dt="); Serial.print(dt*1000.f,1); Serial.print("ms stalls="); Serial.println(loopStalls); }
cachedTempC = readIMUTemp();
@@ -312,38 +355,51 @@ void loop() {
}
#endif
// Gyro reads with optional temperature compensation
float gx, gy, gz;
// Gyro reads with optional temperature compensation.
float correction = 0.0f;
#ifdef FEATURE_TEMP_COMPENSATION
float correction = TEMP_COMP_COEFF_DPS_C * (cachedTempC - calTempC);
gx = (imu.readFloatGyroX() - biasGX - correction) * (PI/180.0f);
gy = (imu.readFloatGyroY() - biasGY - correction) * (PI/180.0f);
gz = (imu.readFloatGyroZ() - biasGZ - correction) * (PI/180.0f);
#else
gx = (imu.readFloatGyroX() - biasGX) * (PI/180.0f);
gy = (imu.readFloatGyroY() - biasGY) * (PI/180.0f);
gz = (imu.readFloatGyroZ() - biasGZ) * (PI/180.0f);
if (cfg.featureFlags & FLAG_TEMP_COMP_ENABLED)
correction = TEMP_COMP_COEFF_DPS_C * (cachedTempC - calTempC);
#endif
float gx = (imu.readFloatGyroX() - biasGX) * (PI/180.0f); // roll (unused for cursor)
float gy = (imu.readFloatGyroY() - biasGY - correction) * (PI/180.0f); // pitch → cursor Y
float gz = (imu.readFloatGyroZ() - biasGZ - correction) * (PI/180.0f); // yaw → cursor X
// Axis diagnostic — send 'd' over serial to enable
if (diagUntil && now < diagUntil) {
static unsigned long lastDiagPrint = 0;
if (now - lastDiagPrint >= 100) { lastDiagPrint = now;
Serial.print("[DIAG] gx="); Serial.print(gx,3);
Serial.print(" gy="); Serial.print(gy,3);
Serial.print(" gz="); Serial.println(gz,3);
}
} else if (diagUntil) { diagUntil = 0; Serial.println("[DIAG] Done"); }
// Direct axis mapping (empirically verified via diagnostic)
float yawRate = gz; // gyroZ = pan left/right → cursor X
float pitchRate = gy; // gyroY = nod up/down → cursor Y
// Dead zone (equal for both axes)
float fYaw = (fabsf(yawRate) > cfg.deadZone) ? yawRate : 0.0f;
float fPitch = (fabsf(pitchRate) > cfg.deadZone) ? pitchRate : 0.0f;
#ifdef DEBUG
{ static unsigned long lastDiag = 0;
if (now - lastDiag >= 500) { lastDiag = now;
Serial.print("[IMU] gyro="); Serial.print(gx,2); Serial.print(","); Serial.print(gy,2); Serial.print(","); Serial.print(gz,2);
Serial.print(" yaw="); Serial.print(yawRate,3); Serial.print(" pitch="); Serial.println(pitchRate,3);
}
}
#endif
float ax = imu.readFloatAccelX();
float ay = imu.readFloatAccelY();
float az = imu.readFloatAccelZ();
// Complementary filter
angleX = ALPHA*(angleX + gx*dt) + (1.0f - ALPHA)*atan2f(ax, sqrtf(ay*ay + az*az));
angleY = ALPHA*(angleY + gy*dt) + (1.0f - ALPHA)*atan2f(ay, sqrtf(ax*ax + az*az));
float fGy = (fabsf(gy) > cfg.deadZone) ? gy : 0.0f;
float fGz = (fabsf(gz) > cfg.deadZone) ? gz : 0.0f;
bool moving = (fGy != 0.0f || fGz != 0.0f);
bool moving = (fPitch != 0.0f || fYaw != 0.0f);
if (moving) { idleFrames = 0; idleStartMs = 0; }
else { idleFrames++; if (idleStartMs == 0) idleStartMs = now; }
bool idle = (idleFrames >= IDLE_FRAMES);
#ifdef FEATURE_AUTO_RECAL
if (idle && idleStartMs != 0 && (now - idleStartMs >= AUTO_RECAL_MS)) {
Serial.println("[AUTO-CAL] Long idle recalibrating...");
if ((cfg.featureFlags & FLAG_AUTO_RECAL_ENABLED) && idle && idleStartMs != 0 && (now - idleStartMs >= AUTO_RECAL_MS)) {
Serial.println("[AUTO-CAL] Long idle - recalibrating...");
idleStartMs = 0; calibrateGyroBias(); return;
}
#endif
@@ -351,15 +407,21 @@ void loop() {
int8_t moveX = 0, moveY = 0;
uint8_t flags = 0;
static float smoothX = 0.0f, smoothY = 0.0f;
if (idle) {
smoothX = smoothY = 0.0f;
accumX = accumY = 0.0f;
flags |= 0x01;
} else {
float rawX = applyAcceleration(applyCurve(-fGz * cfg.sensitivity * dt));
float rawY = applyAcceleration(applyCurve(-fGy * cfg.sensitivity * dt));
float rawX = applyAcceleration(applyCurve(-fYaw * cfg.sensitivity * dt));
float rawY = applyAcceleration(applyCurve(-fPitch * cfg.sensitivity * dt));
if (cfg.axisFlip & 0x01) rawX = -rawX;
if (cfg.axisFlip & 0x02) rawY = -rawY;
accumX += rawX; accumY += rawY;
// Single-pole low-pass smoothing
smoothX = smoothX * (1.0f - SMOOTH_ALPHA) + rawX * SMOOTH_ALPHA;
smoothY = smoothY * (1.0f - SMOOTH_ALPHA) + rawY * SMOOTH_ALPHA;
accumX += smoothX; accumY += smoothY;
moveX = (int8_t)constrain((int)accumX, -127, 127);
moveY = (int8_t)constrain((int)accumY, -127, 127);
accumX -= moveX; accumY -= moveY;
@@ -370,8 +432,13 @@ void loop() {
if (!safeMode && imuStreamEnabled && Bluefruit.connected()
&& (now - lastImuStream >= IMU_STREAM_RATE_MS)) {
lastImuStream = now;
if (now < streamBackoffUntil) {
// Backing off - host TX buffer congested, skip to avoid 100ms block
} else {
float ax = imu.readFloatAccelX(), ay = imu.readFloatAccelY(), az = imu.readFloatAccelZ();
ImuPacket pkt;
pkt.gyroY_mDPS = (int16_t)constrain(gy*(180.f/PI)*1000.f, -32000, 32000);
pkt.gyroX_mDPS = (int16_t)constrain(gx*(180.f/PI)*1000.f, -32000, 32000);
pkt.gyroZ_mDPS = (int16_t)constrain(gz*(180.f/PI)*1000.f, -32000, 32000);
pkt.accelX_mg = (int16_t)constrain(ax*1000.f, -32000, 32000);
pkt.accelY_mg = (int16_t)constrain(ay*1000.f, -32000, 32000);
@@ -380,15 +447,29 @@ void loop() {
pkt.moveY = moveY;
pkt.flags = flags;
pkt._pad = 0;
cfgImuStream.notify((uint8_t*)&pkt, sizeof(pkt));
if (cfgImuStream.notify((uint8_t*)&pkt, sizeof(pkt))) {
streamNotifyOk++;
streamConsecFails = 0;
} else {
streamNotifyFails++;
streamConsecFails++;
if (streamConsecFails >= STREAM_BACKOFF_THRESH) {
streamBackoffUntil = now + STREAM_BACKOFF_MS;
streamConsecFails = 0;
Serial.print("[STREAM] TX congested - backing off ");
Serial.print(STREAM_BACKOFF_MS); Serial.println("ms");
}
}
}
// Periodic stream health report every 10 seconds
if (now - lastStreamDiag >= 10000) {
lastStreamDiag = now;
Serial.print("[STREAM] ok="); Serial.print(streamNotifyOk);
Serial.print(" fail="); Serial.print(streamNotifyFails);
Serial.print(" rate="); Serial.print((streamNotifyOk * 1000UL) / 10000); Serial.println("pkt/s");
streamNotifyOk = 0; streamNotifyFails = 0;
}
}
#endif
#ifdef DEBUG
Serial.print("T="); Serial.print(cachedTempC,1);
Serial.print(" gy="); Serial.print(gy,3);
Serial.print(" gz="); Serial.print(gz,3);
Serial.print(" mx="); Serial.print(moveX);
Serial.print(" my="); Serial.println(moveY);
#endif
}
+364
View File
@@ -0,0 +1,364 @@
#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;
// Post-wake stillness gate: don't calibrate while the device is moving.
// Each axis of the gyro must stay below RECAL_STILL_DPS for RECAL_STILL_FRAMES
// consecutive loop ticks before calibration fires. If the device keeps moving
// past RECAL_WAIT_MAX_MS, recal is skipped and the pre-sleep bias is kept.
static constexpr float RECAL_STILL_DPS = 10.0f; // deg/s per axis
static constexpr uint8_t RECAL_STILL_FRAMES = 10; // ~100 ms at 10 ms/frame
static constexpr unsigned long RECAL_WAIT_MAX_MS = 3000; // give up after 3 s
static uint8_t recalStillFrames = 0;
static unsigned long recalLastWarnMs = 0;
// 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;
}
static volatile bool btnWakeFlag = false;
static void btnWakeISR() {
btnWakeFlag = 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();
// Arm button wake interrupt
#if BTN_LEFT_PIN != BTN_PIN_NONE
btnWakeFlag = false;
attachInterrupt(digitalPinToInterrupt(BTN_LEFT_PIN), btnWakeISR, FALLING);
#endif
// Turn off all LEDs for sleep
digitalWrite(LED_RED, HIGH); digitalWrite(LED_GREEN, HIGH); digitalWrite(LED_BLUE, HIGH);
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, HIGH); digitalWrite(LED_GREEN, HIGH); digitalWrite(LED_BLUE, HIGH);
while (!imuWakeFlag && !btnWakeFlag) {
(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();
// Detach button wake interrupt — normal polling takes over
#if BTN_LEFT_PIN != BTN_PIN_NONE
detachInterrupt(digitalPinToInterrupt(BTN_LEFT_PIN));
#endif
// 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.
extern float accumX, accumY;
extern unsigned long lastTime;
accumX = accumY = 0.0f;
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 (IMU motion or button press)
bool woke = false;
if (imuWakeFlag) {
imuWakeFlag = false;
Serial.print("[SLEEP] INT1 fired - stage="); Serial.println((int)sleepStage);
woke = true;
}
if (btnWakeFlag) {
btnWakeFlag = false;
Serial.print("[SLEEP] Button fired - stage="); Serial.println((int)sleepStage);
woke = true;
}
if (woke) {
if (sleepStage == SLEEP_DEEP || sleepStage == SLEEP_IMU_LP) {
sleepManagerWakeIMU();
} else {
(void)lsmRead(SLP_WAKE_UP_SRC);
}
}
// Post-wake recalibration — gated on device being still
if (pendingWakeRecal) {
if (nowMs - wakeSettleMs < 120) return true; // initial hardware settle
// Sample gyro magnitude; each axis must be below threshold
float gx = fabsf(imu.readFloatGyroX());
float gy = fabsf(imu.readFloatGyroY());
float gz = fabsf(imu.readFloatGyroZ());
bool still = (gx < RECAL_STILL_DPS && gy < RECAL_STILL_DPS && gz < RECAL_STILL_DPS);
if (!still) {
recalStillFrames = 0;
// Rate-limited log so we don't flood serial while waiting
if (nowMs - recalLastWarnMs >= 500) {
recalLastWarnMs = nowMs;
Serial.print("[SLEEP] Waiting for still: gx="); Serial.print(gx, 1);
Serial.print(" gy="); Serial.print(gy, 1);
Serial.print(" gz="); Serial.println(gz, 1);
}
if (nowMs - wakeSettleMs >= RECAL_WAIT_MAX_MS) {
// Device never settled — keep pre-sleep bias rather than corrupt it
pendingWakeRecal = false;
recalStillFrames = 0;
recalLastWarnMs = 0;
Serial.println("[SLEEP] Recal skipped — device still moving after timeout");
}
return true;
}
// Device is still — accumulate consecutive still frames
if (++recalStillFrames < RECAL_STILL_FRAMES) return true;
pendingWakeRecal = false;
recalStillFrames = 0;
recalLastWarnMs = 0;
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 6 // 063
#endif
// Number of consecutive 26 Hz samples that must exceed the threshold.
#ifndef SLEEP_WAKEUP_DUR
#define SLEEP_WAKEUP_DUR 1 // 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();
+4 -15
View File
@@ -6,7 +6,7 @@
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
@@ -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);
+524 -59
View File
@@ -1,34 +1,73 @@
// ── UUIDs ────────────────────────────────────────────────────────────────────
// UUIDs
// v3.3: 4 characteristics instead of 10
const SVC_UUID = '00001234-0000-1000-8000-00805f9b34fb';
const CHR = {
configBlob: '00001235-0000-1000-8000-00805f9b34fb', // ConfigBlob R/W 16 bytes
configBlob: '00001235-0000-1000-8000-00805f9b34fb', // ConfigBlob R/W 20 bytes
command: '00001236-0000-1000-8000-00805f9b34fb', // Command W 1 byte
telemetry: '00001237-0000-1000-8000-00805f9b34fb', // Telemetry R/N 24 bytes
imuStream: '00001238-0000-1000-8000-00805f9b34fb', // ImuStream N 14 bytes
gitHash: '00001239-0000-1000-8000-00805f9b34fb', // GitHash R 8 bytes
};
// Runtime feature-override flag bitmask constants (mirror firmware FLAG_* defines)
const FLAG_TAP_ENABLED = 0x01;
const FLAG_TEMP_COMP_ENABLED = 0x02;
const FLAG_AUTO_RECAL_ENABLED = 0x04;
const FLAG_ALL_DEFAULT = FLAG_TAP_ENABLED | FLAG_TEMP_COMP_ENABLED | FLAG_AUTO_RECAL_ENABLED;
// Local shadow of the current config (kept in sync with device)
const config = { sensitivity:600, deadZone:0.06, accelStrength:0.08, curve:0, axisFlip:0, chargeMode:1,
tapThreshold:12, tapAction:0, tapKey:0, tapMod:0 };
const config = { sensitivity:600, deadZone:0.06, accelStrength:0.08, curve:0, axisFlip:0, chargeMode:0,
tapThreshold:12, tapAction:0, tapKey:0, tapMod:0, tapFreezeEnabled:1, jerkThreshold:2000,
featureFlags:FLAG_ALL_DEFAULT,
};
let device=null, server=null, chars={}, userDisconnected=false;
let currentChargeStatus=0, currentBattPct=null;
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
const GATT_TIMEOUT_MS = 3000;
const GATT_MAX_DEPTH = 2;
let _gattQueue = Promise.resolve();
function gattWrite(char, value) {
const p = _gattQueue.then(() => char.writeValueWithResponse(value));
_gattQueue = p.catch(() => {});
return p;
let _gattDepth = 0;
function _withTimeout(promise, ms) {
return new Promise((resolve, reject) => {
const t = setTimeout(() => {
console.warn(`[GATT] operation timed out after ${ms}ms`);
reject(new Error(`GATT timeout (${ms}ms)`));
}, ms);
promise.then(v => { clearTimeout(t); resolve(v); },
e => { clearTimeout(t); reject(e); });
});
}
function gattCmd(char, value) {
const p = _gattQueue.then(() => char.writeValueWithoutResponse(value));
_gattQueue = p.catch(() => {});
function _enqueue(fn) {
if (_gattDepth >= GATT_MAX_DEPTH) {
console.warn(`[GATT] write dropped - queue depth ${_gattDepth} >= max ${GATT_MAX_DEPTH}`);
return Promise.reject(new Error('GATT queue full - device unreachable?'));
}
_gattDepth++;
const p = _gattQueue.then(() => _withTimeout(fn(), GATT_TIMEOUT_MS));
_gattQueue = p.catch(() => {}).finally(() => { _gattDepth = Math.max(0, _gattDepth - 1); });
return p;
}
// ── Logging ──────────────────────────────────────────────────────────────────
function gattWrite(char, value) { return _enqueue(() => char.writeValueWithResponse(value)); }
function gattCmd (char, value) { return _enqueue(() => char.writeValueWithoutResponse(value)); }
function gattQueueReset() {
console.log('[GATT] queue reset');
// Drain the chain so a reconnect starts with a fresh resolved promise
_gattQueue = Promise.resolve();
_gattDepth = 0;
}
// Logging
(function() {
const _methods = { log: '', warn: 'warn', error: 'err' };
for (const [method, type] of Object.entries(_methods)) {
@@ -51,7 +90,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;
@@ -89,27 +128,34 @@ async function discoverServices() {
chars.command = await svc.getCharacteristic(CHR.command);
chars.telemetry = await svc.getCharacteristic(CHR.telemetry);
chars.imuStream = await svc.getCharacteristic(CHR.imuStream);
chars.gitHash = await svc.getCharacteristic(CHR.gitHash);
// Read config blob and populate UI
await readConfigBlob();
// 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
parseTelemetry(await chars.telemetry.readValue());
// Read firmware git hash and check against web build hash
await checkHashMatch();
// IMU stream — subscribed on demand via play button
// Telemetry notify (1 Hz) - also carries chargeStatus
chars.telemetry.addEventListener('characteristicvaluechanged', e => {
const val = e.target.value; // capture immediately — Chrome reuses the DataView buffer on next notify
parseTelemetry(val);
});
await chars.telemetry.startNotifications();
parseTelemetry(await chars.telemetry.readValue());
updateChargeUI();
// 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');
@@ -125,11 +171,52 @@ async function discoverServices() {
} catch(e) { log('Battery service unavailable','warn'); }
}
// ── ConfigBlob read / write ──────────────────────────────────────────────────
// ConfigBlob layout (20 bytes LE):
// Firmware / web hash mismatch banner
async function checkHashMatch() {
const banner = document.getElementById('hashMismatchBanner');
if (!chars.gitHash) return;
let fwHash = 'unknown';
try {
const dv = await chars.gitHash.readValue();
const bytes = new Uint8Array(dv.buffer, dv.byteOffset, dv.byteLength);
// Find NUL terminator or use full length
let end = bytes.indexOf(0);
if (end === -1) end = bytes.length;
fwHash = new TextDecoder().decode(bytes.subarray(0, end));
} catch(e) { log(`Hash read failed: ${e.message}`, 'warn'); }
// FIRMWARE_BUILD_HASH comes from web/version.js (written by scripts/git_hash.py at build time)
const webHash = (typeof FIRMWARE_BUILD_HASH !== 'undefined') ? FIRMWARE_BUILD_HASH : 'unknown';
log(`Firmware hash: ${fwHash} · Web hash: ${webHash}`, fwHash === webHash ? 'ok' : 'warn');
if (fwHash === 'unknown' || webHash === 'unknown' || fwHash === webHash) {
banner.style.display = 'none';
return;
}
banner.style.cssText = [
'display:flex', 'align-items:center', 'justify-content:center', 'gap:12px',
'background:#7a2020', 'color:#ffd0d0', 'font-family:var(--mono)',
'font-size:11px', 'padding:6px 16px', 'border-bottom:1px solid #c04040',
'position:sticky', 'top:0', 'z-index:100',
].join(';');
banner.innerHTML =
`<span style="font-size:14px">⚠</span>` +
`<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 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 pad [19]
// uint8 curve [12], uint8 axisFlip [13], uint8 chargeMode [14] (0=SLOW 1=FAST)
// 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;
@@ -147,9 +234,18 @@ async function readConfigBlob() {
config.tapAction = view.getUint8(16);
config.tapKey = view.getUint8(17);
config.tapMod = view.getUint8(18);
config.tapFreezeEnabled = view.getUint8(19);
}
if (view.byteLength >= 24) {
config.jerkThreshold = view.getFloat32(20, true);
}
if (view.byteLength >= 25) {
config.featureFlags = view.getUint8(24);
} else {
config.featureFlags = FLAG_ALL_DEFAULT; // old firmware - assume all on
}
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'); }
}
@@ -164,6 +260,10 @@ function applyConfigToUI() {
document.getElementById('flipX').checked = !!(config.axisFlip & 1);
document.getElementById('flipY').checked = !!(config.axisFlip & 2);
setChargeModeUI(config.chargeMode);
document.getElementById('tapFreezeEnabled').checked = !!config.tapFreezeEnabled;
document.getElementById('slJerkThreshold').value = config.jerkThreshold;
updateDisplay('jerkThreshold', config.jerkThreshold);
updateTapFreezeUI(!!config.tapFreezeEnabled);
document.getElementById('slTapThreshold').value = config.tapThreshold;
updateDisplay('tapThreshold', config.tapThreshold);
setTapActionUI(config.tapAction);
@@ -172,8 +272,12 @@ function applyConfigToUI() {
document.getElementById('tapModShift').checked = !!(config.tapMod & 0x02);
document.getElementById('tapModAlt').checked = !!(config.tapMod & 0x04);
document.getElementById('tapModGui').checked = !!(config.tapMod & 0x08);
document.getElementById('capTapEnabled').checked = !!(config.featureFlags & FLAG_TAP_ENABLED);
document.getElementById('capTempComp').checked = !!(config.featureFlags & FLAG_TEMP_COMP_ENABLED);
document.getElementById('capAutoRecal').checked = !!(config.featureFlags & FLAG_AUTO_RECAL_ENABLED);
}
let _writeConfigTimer = null;
function writeConfigBlob() {
clearTimeout(_writeConfigTimer);
@@ -193,9 +297,14 @@ async function _doWriteConfigBlob() {
| (document.getElementById('tapModShift').checked ? 0x02 : 0)
| (document.getElementById('tapModAlt').checked ? 0x04 : 0)
| (document.getElementById('tapModGui').checked ? 0x08 : 0);
config.tapFreezeEnabled = document.getElementById('tapFreezeEnabled').checked ? 1 : 0;
config.jerkThreshold = +document.getElementById('slJerkThreshold').value;
config.featureFlags = (document.getElementById('capTapEnabled').checked ? FLAG_TAP_ENABLED : 0)
| (document.getElementById('capTempComp').checked ? FLAG_TEMP_COMP_ENABLED : 0)
| (document.getElementById('capAutoRecal').checked ? FLAG_AUTO_RECAL_ENABLED : 0);
// config.curve, config.chargeMode, config.tapAction, config.tapKey updated directly
const buf = new ArrayBuffer(20);
const buf = new ArrayBuffer(25);
const view = new DataView(buf);
view.setFloat32(0, config.sensitivity, true);
view.setFloat32(4, config.deadZone, true);
@@ -207,15 +316,17 @@ async function _doWriteConfigBlob() {
view.setUint8(16, config.tapAction);
view.setUint8(17, config.tapKey);
view.setUint8(18, config.tapMod);
view.setUint8(19, 0);
view.setUint8(19, config.tapFreezeEnabled);
view.setFloat32(20, config.jerkThreshold, true);
view.setUint8(24, config.featureFlags);
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) {
@@ -233,15 +344,31 @@ function setChargeMode(val) {
config.chargeMode = val;
setChargeModeUI(val);
writeConfigBlob();
log(`Charge → ${['OFF','SLOW 50mA','FAST 100mA'][val]}`,'warn');
log(`Charge → ${['SLOW 50mA','FAST 100mA'][val]}`,'warn');
}
function setChargeModeUI(val) {
[['chgOff','off'],['chgSlow','slow'],['chgFast','fast']].forEach(([id,cls],i) => {
[['chgSlow','slow'],['chgFast','fast']].forEach(([id,cls],i) => {
const b = document.getElementById(id);
b.classList.remove('active','off','slow','fast');
b.classList.remove('active','slow','fast');
if (i===val) b.classList.add('active', cls);
});
document.getElementById('ciMode').textContent = ['Off (0mA)','50 mA','100 mA'][val] ?? '--';
document.getElementById('ciMode').textContent = ['50 mA','100 mA'][val] ?? '--';
}
function onCapTapChange(enabled) {
writeConfigBlob();
log('Tap detection ' + (enabled ? 'enabled' : 'disabled') + ' - restart device to apply', 'warn');
}
function onTapFreezeChange(enabled) {
config.tapFreezeEnabled = enabled ? 1 : 0;
updateTapFreezeUI(enabled);
writeConfigBlob();
}
function updateTapFreezeUI(enabled) {
const slider = document.getElementById('slJerkThreshold');
// Only grey out when connected (on disconnect, setStatus handles all inputs)
if (device) slider.disabled = !enabled;
}
function setTapAction(val) {
@@ -263,7 +390,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'); }
@@ -277,25 +404,26 @@ async function doReset() {
} catch(e) { log(`Reset failed: ${e.message}`,'err'); }
}
// ── Telemetry ────────────────────────────────────────────────────────────────
// TelemetryPacket (24 bytes LE):
// 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 24B, 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;
}
let uptime, leftClicks, rightClicks, temp, biasRms, recalCount, chargeStatus;
let uptime, leftClicks, rightClicks, temp, biasRms, recalCount, chargeStatus, battVoltage=null;
try {
uptime = view.getUint32(0, true);
leftClicks = view.getUint32(4, true);
@@ -304,7 +432,8 @@ function parseTelemetry(dv) {
biasRms = view.getFloat32(16,true);
recalCount = view.getUint16(20, true);
chargeStatus= view.getUint8(22);
} catch(e) { log(`parseTelemetry: parse error at offset — ${e.message}`,'err'); return; }
if (view.byteLength >= 28) battVoltage = view.getFloat32(24, true);
} 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);
@@ -315,11 +444,17 @@ function parseTelemetry(dv) {
const tEl = document.getElementById('telTemp');
tEl.className = 'telem-val '+(temp>40?'warn':'accent');
// chargeStatus is now delivered via telemetry (no separate characteristic)
if (chargeStatus !== currentChargeStatus) {
currentChargeStatus = chargeStatus;
updateChargeUI();
}
if (battVoltage !== null) {
currentBattVoltage = battVoltage;
document.getElementById('ciVolt').textContent = battVoltage.toFixed(2) + 'V';
const pct = Math.round(Math.min(100, Math.max(0, (battVoltage - 3.00) / (4.20 - 3.00) * 100)));
if (pct !== currentBattPct) { currentBattPct = pct; updateBatteryBar(pct, currentChargeStatus); }
}
}
function formatUptime(s) {
const h=Math.floor(s/3600), m=Math.floor((s%3600)/60), ss=s%60;
@@ -330,7 +465,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+'%';
@@ -354,19 +489,125 @@ function updateChargeUI() {
if (currentBattPct!==null) updateBatteryBar(currentBattPct, currentChargeStatus);
}
// ── Param display ─────────────────────────────────────────────────────────────
// Advanced toggle
function toggleAdvanced(on) {
advancedMode = on;
localStorage.setItem('advanced', on);
document.getElementById('ciVoltItem').style.display = on ? '' : 'none';
document.getElementById('debugBtn').style.display = on ? '' : 'none';
// Switch charge-info grid between 3 and 4 columns
document.getElementById('chargeInfo').style.gridTemplateColumns = on ? '1fr 1fr 1fr 1fr' : '1fr 1fr 1fr';
}
// IMU Debug Recorder
let debugModalOpen = false;
let debugRecording = false;
let debugBuffer = [];
const DEBUG_LIVE_ROWS = 40;
let debugLiveRing = [];
let debugT0 = 0;
function openDebugModal() {
console.log('[DEBUG] modal opened (imuSubscribed=' + imuSubscribed + ')');
debugModalOpen = true;
debugT0 = Date.now();
debugLiveRing = [];
document.getElementById('debugOverlay').classList.add('show');
// Auto-start IMU stream if not already running
if (!imuSubscribed && chars.imuStream) vizSetPaused(false);
}
function closeDebugModal() {
console.log('[DEBUG] modal closed');
debugModalOpen = false;
document.getElementById('debugOverlay').classList.remove('show');
}
function feedDebugRow(gyroX, gyroZ, accelX, accelY, accelZ, moveX, moveY, flags) {
if (!debugModalOpen) return;
const ms = Date.now() - debugT0;
const row = { ms, gyroX, gyroZ, accelX, accelY, accelZ, moveX, moveY, flags };
// Live ring buffer
debugLiveRing.push(row);
if (debugLiveRing.length > DEBUG_LIVE_ROWS) debugLiveRing.shift();
// Recording buffer
if (debugRecording) {
debugBuffer.push(row);
document.getElementById('debugRecCount').textContent = debugBuffer.length + ' samples';
}
// Shock indicator
const shocked = !!(flags & 0x08);
const badge = document.getElementById('debugShockBadge');
badge.classList.toggle('active', shocked);
// Render live table
const tbody = document.getElementById('debugRows');
tbody.innerHTML = '';
for (const r of debugLiveRing) {
const f = [];
if (r.flags & 0x01) f.push('idle');
if (r.flags & 0x02) f.push('tap1');
if (r.flags & 0x04) f.push('tap2');
if (r.flags & 0x08) f.push('shock');
const tr = document.createElement('tr');
if (r.flags & 0x08) tr.className = 'shock-row';
tr.innerHTML =
`<td>${r.ms}</td><td>${r.gyroX}</td><td>${r.gyroZ}</td>` +
`<td>${r.accelX}</td><td>${r.accelY}</td><td>${r.accelZ}</td>` +
`<td>${r.moveX}</td><td>${r.moveY}</td><td>${f.join(' ')}</td>`;
tbody.appendChild(tr);
}
tbody.parentElement.parentElement.scrollTop = tbody.parentElement.parentElement.scrollHeight;
}
function toggleDebugRec() {
debugRecording = !debugRecording;
const btn = document.getElementById('debugRecBtn');
btn.classList.toggle('recording', debugRecording);
btn.textContent = debugRecording ? '■ STOP' : '● REC';
if (debugRecording) { debugBuffer = []; debugT0 = Date.now(); }
document.getElementById('debugRecCount').textContent = debugBuffer.length + ' samples';
}
function saveDebugCSV() {
if (!debugBuffer.length) { log('No recorded data to save','warn'); return; }
const header = 'ms,gyroX_mDPS,gyroZ_mDPS,accelX_mg,accelY_mg,accelZ_mg,moveX,moveY,flags\n';
const rows = debugBuffer.map(r =>
`${r.ms},${r.gyroX},${r.gyroZ},${r.accelX},${r.accelY},${r.accelZ},${r.moveX},${r.moveY},${r.flags}`
).join('\n');
const blob = new Blob([header + rows], { type: 'text/csv' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url; a.download = `imu_debug_${new Date().toISOString().slice(0,19).replace(/:/g,'-')}.csv`;
a.click(); URL.revokeObjectURL(url);
log(`Saved ${debugBuffer.length} samples as CSV`,'ok');
}
function clearDebugRec() {
debugBuffer = [];
debugRecording = false;
const btn = document.getElementById('debugRecBtn');
btn.classList.remove('recording');
btn.textContent = '● REC';
document.getElementById('debugRecCount').textContent = '0 samples';
}
// Param display
function updateDisplay(key, val) {
const map = {
sensitivity: ['valSensitivity', v=>parseFloat(v).toFixed(0)],
deadZone: ['valDeadZone', v=>parseFloat(v).toFixed(3)],
accel: ['valAccel', v=>parseFloat(v).toFixed(2)],
jerkThreshold:['valJerkThreshold',v=>parseFloat(v).toFixed(0)],
tapThreshold: ['valTapThreshold', v=>(parseFloat(v)*62.5).toFixed(0)+' mg'],
};
const [id,fmt] = map[key];
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];
@@ -388,12 +629,15 @@ function setStatus(state) {
function onDisconnected() {
log('Device disconnected','warn');
const savedDevice = device;
gattQueueReset();
chars={}; device=null; server=null;
setStatus('disconnected');
document.getElementById('battBar').style.display='none';
document.getElementById('badgeCharging').classList.remove('show');
document.getElementById('badgeFull').classList.remove('show');
imuSubscribed = false; vizPaused = true; vizUpdateIndicator();
imuSubscribed = false; vizPaused = true; vizUpdateIndicator(); streamDiagReset();
document.getElementById('orientLabel').textContent = '- not streaming -';
document.getElementById('hashMismatchBanner').style.display = 'none';
clearTelemetry();
if (!userDisconnected && document.getElementById('autoReconnect').checked && savedDevice) {
log('Auto-reconnecting…','info');
@@ -414,9 +658,9 @@ function onDisconnected() {
}
}
// ── IMU Stream + Visualiser ──────────────────────────────────────────────────
// IMU Stream + Visualiser
// ImuPacket (14 bytes LE):
// int16 gyroY_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]
// int8 moveX [10], int8 moveY [11], uint8 flags [12], uint8 pad [13]
const canvas = document.getElementById('vizCanvas');
@@ -425,6 +669,55 @@ const TRAIL_LEN = 120;
let cursorX = canvas.width/2, cursorY = canvas.height/2, trail = [];
let vizPaused = true;
let imuSubscribed = false;
let _prevIdle = false;
// 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)
let streamLastRateT = 0; // timestamp of last rate log
let streamFreezeTimer = null; // fires if no packet for >1s while subscribed
function streamDiagReset() {
console.log('[STREAM] diagnostics reset');
streamPktCount = streamPktTotal = streamLastPktT = streamLastRateT = 0;
_prevIdle = false;
if (streamFreezeTimer) { clearTimeout(streamFreezeTimer); streamFreezeTimer = null; }
}
function streamDiagPkt() {
const now = Date.now();
// 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');
}
streamLastPktT = now;
streamPktCount++;
streamPktTotal++;
// 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');
streamFreezeTimer = null;
}, 1500);
// Log rate every 5s
if (streamLastRateT === 0) streamLastRateT = now;
if (now - streamLastRateT >= 5000) {
const rate = (streamPktCount / ((now - streamLastRateT) / 1000)).toFixed(1);
log(`[STREAM] ${rate} pkt/s · total ${streamPktTotal}`, 'info');
streamPktCount = 0;
streamLastRateT = now;
}
}
// 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.
function resetOrient() {} // kept for call-site compatibility
function vizUpdateIndicator() {
const el = document.getElementById('vizLive');
@@ -444,26 +737,32 @@ function vizUpdateIndicator() {
async function vizSetPaused(paused) {
vizPaused = paused;
if (!paused && chars.imuStream && !imuSubscribed) {
console.log('[STREAM] requesting subscribe');
try {
await chars.imuStream.startNotifications();
imuSubscribed = true;
document.getElementById('orientLabel').textContent = 'roll correction active (firmware)';
log('IMU stream subscribed','ok');
} catch(e) { log(`IMU stream start failed: ${e.message}`,'err'); vizPaused = true; }
} else if (paused && imuSubscribed) {
console.log(`[STREAM] requesting unsubscribe (total rx: ${streamPktTotal})`);
try {
await chars.imuStream.stopNotifications();
imuSubscribed = false;
streamDiagReset();
document.getElementById('orientLabel').textContent = '- not streaming -';
} catch(e) { log(`IMU stream stop failed: ${e.message}`,'err'); }
} else {
console.log(`[STREAM] vizSetPaused(${paused}) - no action (imuSubscribed=${imuSubscribed})`);
}
vizUpdateIndicator();
}
function parseImuStream(dv) {
if (vizPaused) return;
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);
@@ -472,31 +771,53 @@ function parseImuStream(dv) {
return;
}
let gyroY, gyroZ, moveX, moveY, flags;
let gyroX, gyroZ, accelX, accelY, accelZ, moveX, moveY, flags;
try {
gyroY = view.getInt16(0, true);
gyroZ = view.getInt16(2, true);
gyroX = view.getInt16(0, true); // GX = pitch axis (nod → cursor Y)
gyroZ = view.getInt16(2, true); // GZ = yaw axis (pan → cursor X)
accelX = view.getInt16(4, true);
accelY = view.getInt16(6, true);
accelZ = view.getInt16(8, true);
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);
if (vizPaused) return;
const idle = !!(flags & 0x01);
const single = !!(flags & 0x02);
const dbl = !!(flags & 0x04);
updateAxisBar('gy', gyroY, 30000);
updateAxisBar('gz', gyroZ, 30000);
// Axis bars: show raw gyro (firmware convention: Z→screen-X, X→screen-Y)
updateAxisBar('gy', -gyroZ, 30000);
updateAxisBar('gz', -gyroX, 30000);
if (!idle) {
// 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));
}
trail.push({x:cursorX, y:cursorY, t:Date.now(), idle});
if (trail.length > TRAIL_LEN) trail.shift();
streamDiagPkt();
if (idle !== _prevIdle) {
console.log(`[STREAM] idle → ${idle ? 'idle' : 'active'} (pkt #${streamPktTotal})`);
_prevIdle = idle;
}
if (single) console.log(`[STREAM] single tap (pkt #${streamPktTotal})`);
if (dbl) console.log(`[STREAM] double tap (pkt #${streamPktTotal})`);
if (single) flashTap('Left');
if (dbl) flashTap('Right');
drawViz(idle);
orientFeedIMU(accelX, accelY, accelZ, gyroX, gyroZ);
}
function updateAxisBar(axis, val, max) {
@@ -551,7 +872,114 @@ 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';
}
// ── Theme ─────────────────────────────────────────────────────────────────────
// 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;
const DEVICE_L = 1.15, DEVICE_W = 0.36, DEVICE_H = 0.20; // metres (Three.js units)
let orientScene, orientCamera, orientRenderer, orientMesh, orientEdges;
let orientQ = new THREE.Quaternion(); // current estimated orientation
let orientLastT = 0;
function initOrientViewer() {
const el = document.getElementById('orientCanvas');
const W = el.clientWidth || 340, H = el.clientHeight || W;
el.width = W; el.height = H;
orientScene = new THREE.Scene();
orientCamera = new THREE.PerspectiveCamera(55, W / H, 0.01, 10);
orientCamera.position.set(0.75, 0.60, 1.10);
orientCamera.lookAt(0, 0, 0);
orientRenderer = new THREE.WebGLRenderer({ canvas: el, antialias: true, alpha: true });
orientRenderer.setSize(W, H);
orientRenderer.setClearColor(0x000000, 0);
// Box geometry
const geo = new THREE.BoxGeometry(DEVICE_L, DEVICE_H, DEVICE_W);
const mat = new THREE.MeshPhongMaterial({
color: 0x1a2230, emissive: 0x050a10, specular: 0x00e5ff,
shininess: 60, transparent: true, opacity: 0.85,
});
orientMesh = new THREE.Mesh(geo, mat);
orientScene.add(orientMesh);
// Wireframe edges
const edgeMat = new THREE.LineBasicMaterial({ color: 0x00e5ff, linewidth: 1 });
orientEdges = new THREE.LineSegments(new THREE.EdgesGeometry(geo), edgeMat);
orientMesh.add(orientEdges);
// "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);
const arrowMesh = new THREE.Mesh(arrowGeo,
new THREE.MeshBasicMaterial({ color: 0x00e5ff }));
orientMesh.add(arrowMesh);
// Lighting
orientScene.add(new THREE.AmbientLight(0xffffff, 0.4));
const dlight = new THREE.DirectionalLight(0xffffff, 0.9);
dlight.position.set(1, 2, 2);
orientScene.add(dlight);
orientRenderer.render(orientScene, orientCamera);
}
function orientUpdateColors() {
// Re-read CSS variables so it adapts to theme changes
const accent = cssVar('--accent').replace('#','');
const c = parseInt(accent, 16);
if (orientEdges) orientEdges.material.color.setHex(c);
}
function orientFeedIMU(ax, ay, az, gyX_mDPS, gyZ_mDPS) {
if (!orientRenderer) return;
const now = Date.now();
const dt = orientLastT ? Math.min((now - orientLastT) / 1000, 0.1) : 0.05;
orientLastT = now;
// Accel in g (packet is in mg)
const axG = ax / 1000, ayG = ay / 1000, azG = az / 1000;
const aNorm = Math.sqrt(axG*axG + ayG*ayG + azG*azG);
// Accel-derived quaternion (gravity reference). LSM6DS3 axes:
// device flat, face up: az ≈ +1g
// Pitch (tilt front up): ay changes; Roll (tilt right side up): ax changes
let qAccel = new THREE.Quaternion();
if (aNorm > 0.5 && aNorm < 2.0) {
// gravity unit vector in device frame
const gx = axG / aNorm, gy = ayG / aNorm, gz = azG / aNorm;
// Align device -Z (down face) with gravity
const up = new THREE.Vector3(0, 1, 0); // Three.js world up
const gVec = new THREE.Vector3(-gx, -gz, gy); // map device→Three axes
gVec.normalize();
qAccel.setFromUnitVectors(gVec, up);
} else {
qAccel.copy(orientQ);
}
// 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;
const dq = new THREE.Quaternion(
gyRad * dt * 0.5, // x
-gzRad * dt * 0.5, // y
0, 1
).normalize();
const qGyro = orientQ.clone().multiply(dq);
// Complementary filter
orientQ.copy(qGyro).slerp(qAccel, 1 - ORIENT_ALPHA);
orientQ.normalize();
orientMesh.quaternion.copy(orientQ);
orientRenderer.render(orientScene, orientCamera);
}
// Theme
const THEMES = ['auto','dark','light'];
const THEME_LABELS = {auto:'AUTO',dark:'DARK',light:'LIGHT'};
let themeIdx = 0;
@@ -567,11 +995,16 @@ function applyTheme(t) {
document.getElementById('themeBtn').querySelector('span').textContent = THEME_LABELS[t];
localStorage.setItem('theme', t);
if (!chars.imuStream) drawInitState();
orientUpdateColors();
}
(function(){
const saved = localStorage.getItem('theme') ?? 'auto';
themeIdx = Math.max(0, THEMES.indexOf(saved));
applyTheme(saved);
initOrientViewer();
// Restore advanced toggle state
document.getElementById('advancedToggle').checked = advancedMode;
if (advancedMode) toggleAdvanced(true);
})();
if (!navigator.bluetooth) {
@@ -579,3 +1012,35 @@ if (!navigator.bluetooth) {
} else {
log('Web Bluetooth ready. Click CONNECT to pair your IMU Mouse.','info');
}
// ─────────────────────────────────────────────────────────────────────────────
// OTA firmware update
//
// The OTAFIX bootloader uses Nordic Legacy DFU (service 00001530-...) which is
// blocklisted in Chrome's Web Bluetooth implementation. Browser-side upload is
// therefore not possible without special flags or a native app wrapper.
//
// What the UI does instead:
// • "Enter DFU Mode" sends command 0x02 via BLE → device reboots as XIAO_DFU
// • User then uploads firmware_dfu.zip via nRF Connect (mobile or desktop)
// ─────────────────────────────────────────────────────────────────────────────
function otaLog(msg, type = 'info') {
log('[OTA] ' + msg, type);
const el = document.getElementById('otaStatus');
if (el) { el.textContent = msg; el.className = 'ota-status' + (type !== 'info' ? ' ota-' + type : ''); }
}
// Send command 0x02 → firmware reboots into XIAO_DFU bootloader mode.
// User then uploads firmware_dfu.zip via nRF Connect.
async function sendOTATrigger() {
if (!chars.command) { otaLog('Not connected', 'err'); return; }
document.getElementById('btnOTA').disabled = true;
try {
await chars.command.writeValueWithResponse(new Uint8Array([0x02]));
otaLog('Device rebooting into DFU mode — connect to XIAO_DFU in nRF Connect', 'ok');
} catch (e) {
otaLog('Failed: ' + e.message, 'err');
document.getElementById('btnOTA').disabled = false;
}
}
+125 -23
View File
@@ -6,9 +6,13 @@
<title>IMU Mouse // Config Terminal</title>
<link href="https://fonts.googleapis.com/css2?family=Share+Tech+Mono&family=Barlow+Condensed:wght@300;400;600;700;900&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/build/three.min.js"></script>
<script src="version.js"></script>
</head>
<body class="disconnected">
<div id="hashMismatchBanner" style="display:none"></div>
<header>
<div>
<div class="logo">IMU<span>·</span>Mouse</div>
@@ -21,16 +25,21 @@
<div class="batt-cells" id="battCells"></div>
<span id="battPct">--%</span>
</div>
<button class="btn btn-debug" id="debugBtn" onclick="openDebugModal()" style="display:none" title="IMU Debug Recorder"><span>DBG</span></button>
<button class="btn btn-theme" id="themeBtn" onclick="cycleTheme()"><span>AUTO</span></button>
<div class="status-pill" id="statusPill"><div class="dot"></div><span id="statusText">DISCONNECTED</span></div>
<button class="btn btn-connect" id="connectBtn" onclick="doConnect()"><span>Connect</span></button>
<button class="btn btn-disconnect" id="disconnectBtn" onclick="doDisconnect()" style="display:none"><span>Disconnect</span></button>
<label class="toggle" title="Auto-Reconnect" style="margin-left:6px;flex-shrink:0"><input type="checkbox" id="autoReconnect"><div class="toggle-track"></div><div class="toggle-thumb"></div></label>
<span style="font-family:var(--mono);font-size:9px;color:var(--label);white-space:nowrap">AUTO-RECONNECT</span>
<label class="toggle" style="margin-left:10px;flex-shrink:0" title="Advanced"><input type="checkbox" id="advancedToggle" onchange="toggleAdvanced(this.checked)"><div class="toggle-track"></div><div class="toggle-thumb"></div></label>
<span style="font-family:var(--mono);font-size:9px;color:var(--label);white-space:nowrap">ADVANCED</span>
</div>
</header>
<main id="mainContent">
<!-- col-left: cursor motion -->
<div class="col-left">
<div class="section-label">Motion Parameters</div>
@@ -42,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>
@@ -77,20 +86,70 @@
<div class="param" style="border-bottom:none;padding:0">
<div><div class="param-label">Charge Mode</div><div class="param-desc">BQ25100 ISET via P0.13 (HICHG)</div></div>
<div class="segmented charge-seg" style="grid-column:2/4">
<button class="seg-btn off" id="chgOff" onclick="setChargeMode(0)" disabled>OFF</button>
<button class="seg-btn slow" id="chgSlow" onclick="setChargeMode(1)" disabled>SLOW · 50mA</button>
<button class="seg-btn fast" id="chgFast" onclick="setChargeMode(2)" disabled>FAST · 100mA</button>
<button class="seg-btn slow" id="chgSlow" onclick="setChargeMode(0)" disabled>SLOW · 50mA</button>
<button class="seg-btn fast" id="chgFast" onclick="setChargeMode(1)" disabled>FAST · 100mA</button>
</div>
</div>
<div class="charge-info">
<div class="charge-info" id="chargeInfo">
<div class="ci-item"><div class="ci-val" id="ciStatus">--</div><div class="ci-lbl">Status</div></div>
<div class="ci-item"><div class="ci-val" id="ciMode">--</div><div class="ci-lbl">Current</div></div>
<div class="ci-item"><div class="ci-val" id="ciPct">--%</div><div class="ci-lbl">Level</div></div>
<div class="ci-item ci-advanced" id="ciVoltItem" style="display:none"><div class="ci-val accent" id="ciVolt">--</div><div class="ci-lbl">Voltage</div></div>
</div>
</div>
<div class="section-label">Axis Configuration</div>
<div class="card">
<div class="flip-row">
<div class="flip-label">Flip X Axis</div>
<div class="param-desc" style="flex:1;font-size:9px;color:var(--label)">Invert left / right</div>
<label class="toggle"><input type="checkbox" id="flipX" onchange="writeConfigBlob()" disabled><div class="toggle-track"></div><div class="toggle-thumb"></div></label>
</div>
<div class="flip-row" style="border-bottom:none">
<div class="flip-label">Flip Y Axis</div>
<div class="param-desc" style="flex:1;font-size:9px;color:var(--label)">Invert up / down</div>
<label class="toggle"><input type="checkbox" id="flipY" onchange="writeConfigBlob()" disabled><div class="toggle-track"></div><div class="toggle-thumb"></div></label>
</div>
</div>
<div class="section-label">Device Capabilities</div>
<div class="card">
<div class="flip-row">
<div class="flip-label">Tap Detection</div>
<div class="param-desc" style="flex:1;font-size:9px;color:var(--label)">Double-tap click action &nbsp;<span class="restart-note">· restart to apply</span></div>
<label class="toggle"><input type="checkbox" id="capTapEnabled" onchange="onCapTapChange(this.checked)" disabled><div class="toggle-track"></div><div class="toggle-thumb"></div></label>
</div>
<div class="flip-row">
<div class="flip-label">Temp Compensation</div>
<div class="param-desc" style="flex:1;font-size:9px;color:var(--label)">Gyro drift correction by temperature</div>
<label class="toggle"><input type="checkbox" id="capTempComp" onchange="writeConfigBlob()" disabled><div class="toggle-track"></div><div class="toggle-thumb"></div></label>
</div>
<div class="flip-row" style="border-bottom:none">
<div class="flip-label">Auto Recalibration</div>
<div class="param-desc" style="flex:1;font-size:9px;color:var(--label)">Recalibrate gyro after long idle period</div>
<label class="toggle"><input type="checkbox" id="capAutoRecal" onchange="writeConfigBlob()" disabled><div class="toggle-track"></div><div class="toggle-thumb"></div></label>
</div>
</div>
</div><!-- /col-left -->
<!-- col-mid: button configuration -->
<div class="col-mid">
<div class="section-label">Tap Configuration</div>
<div class="card">
<div class="param">
<div><div class="param-label">Tap Freeze</div><div class="param-desc">Freeze cursor during tap impacts (jerk detection)</div></div>
<div style="grid-column:2/4;display:flex;justify-content:flex-end;align-items:center">
<label class="toggle"><input type="checkbox" id="tapFreezeEnabled" onchange="onTapFreezeChange(this.checked)" disabled><div class="toggle-track"></div><div class="toggle-thumb"></div></label>
</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>
<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>
</div>
<div class="param">
<div><div class="param-label">Tap Threshold</div><div class="param-desc">Impact force needed · 1 LSB ≈ 62.5 mg at ±2g</div></div>
<input type="range" id="slTapThreshold" min="1" max="31" step="1" value="12"
@@ -121,25 +180,11 @@
</div>
</div>
<div class="section-label">Axis Configuration</div>
<div class="card">
<div class="flip-row">
<div class="flip-label">Flip X Axis</div>
<div class="param-desc" style="flex:1;font-size:9px;color:var(--label)">Invert left / right</div>
<label class="toggle"><input type="checkbox" id="flipX" onchange="writeConfigBlob()" disabled><div class="toggle-track"></div><div class="toggle-thumb"></div></label>
</div>
<div class="flip-row" style="border-bottom:none">
<div class="flip-label">Flip Y Axis</div>
<div class="param-desc" style="flex:1;font-size:9px;color:var(--label)">Invert up / down</div>
<label class="toggle"><input type="checkbox" id="flipY" onchange="writeConfigBlob()" disabled><div class="toggle-track"></div><div class="toggle-thumb"></div></label>
</div>
</div>
<div class="section-label">Device Commands</div>
<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>
@@ -147,11 +192,35 @@
</button>
</div>
<div class="section-label" style="margin-top:8px">Firmware Update (OTA)</div>
<div class="card ota-card" id="otaCard">
<div class="ota-notice">
<div class="ota-notice-icon"></div>
<div>
<div class="ota-notice-title">Browser OTA not available</div>
<div class="ota-notice-body">Chrome blocks the Nordic Legacy DFU service UUID used by this bootloader. Use <strong>nRF Connect</strong> (mobile or desktop) to upload firmware instead.</div>
</div>
</div>
<ol class="ota-steps">
<li>Build firmware: <code>pio run</code> → produces <code>firmware_dfu.zip</code></li>
<li>Click <strong>Enter DFU Mode</strong> below — device reboots as <em>XIAO_DFU</em></li>
<li>Open nRF Connect → connect to <em>XIAO_DFU</em> → DFU → select <code>firmware_dfu.zip</code></li>
</ol>
<div class="ota-btn-row" style="grid-template-columns:1fr">
<button class="cmd-btn ota-trigger" id="btnOTA" onclick="sendOTATrigger()" disabled>
<span class="cmd-icon"></span><span>Enter DFU Mode</span>
<span class="cmd-desc">Reboots device into XIAO_DFU so nRF Connect can upload firmware.</span>
</button>
</div>
<div class="ota-status-row"><div class="ota-status" id="otaStatus"></div></div>
</div>
<div class="section-label" style="margin-top:8px">Event Log</div>
<div class="console" id="console"></div>
</div>
</div><!-- /col-mid -->
<!-- col-right: live monitoring -->
<div class="col-right">
<div class="section-label">Live Cursor Visualiser</div>
@@ -171,11 +240,11 @@
</div>
<div class="viz-axes">
<div class="axis-bar-wrap">
<div class="axis-bar-label"><span>GY (up/down)</span><span id="gyVal">0</span></div>
<div class="axis-bar-label"><span>X (left/right)</span><span id="gyVal">0</span></div>
<div class="axis-bar-track"><div class="axis-bar-fill" id="gyBar"></div><div class="axis-bar-center"></div></div>
</div>
<div class="axis-bar-wrap">
<div class="axis-bar-label"><span>GZ (left/right)</span><span id="gzVal">0</span></div>
<div class="axis-bar-label"><span>Y (up/down)</span><span id="gzVal">0</span></div>
<div class="axis-bar-track"><div class="axis-bar-fill" id="gzBar"></div><div class="axis-bar-center"></div></div>
</div>
</div>
@@ -184,6 +253,12 @@
</div>
</div>
<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>
<div class="section-label">Live Telemetry</div>
<div class="telem-grid">
<div class="telem-cell"><div class="telem-val accent" id="telTemp">--</div><div class="telem-lbl">Temperature °C</div></div>
@@ -197,6 +272,7 @@
</div>
</main>
<div class="overlay" id="overlay">
<div class="modal">
<h3>⚠ Factory Reset</h3>
@@ -208,6 +284,32 @@
</div>
</div>
<div class="overlay" id="debugOverlay">
<div class="modal debug-modal">
<div class="debug-header">
<h3>IMU Debug Recorder</h3>
<div style="display:flex;align-items:center;gap:8px">
<span class="debug-shock-badge" id="debugShockBadge">SHOCK</span>
<button class="debug-close" onclick="closeDebugModal()"></button>
</div>
</div>
<div class="debug-live" id="debugLive">
<table class="debug-table">
<thead><tr>
<th>ms</th><th>gX</th><th>gZ</th><th>aX</th><th>aY</th><th>aZ</th><th>mX</th><th>mY</th><th>flags</th>
</tr></thead>
<tbody id="debugRows"></tbody>
</table>
</div>
<div class="debug-controls">
<button class="debug-rec-btn" id="debugRecBtn" onclick="toggleDebugRec()">● REC</button>
<span class="debug-rec-count" id="debugRecCount">0 samples</span>
<button class="debug-ctrl-btn" onclick="saveDebugCSV()">Save CSV</button>
<button class="debug-ctrl-btn" onclick="clearDebugRec()">Clear</button>
</div>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
+68 -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;
@@ -110,7 +110,7 @@
.logo-sub { font-size:10px; color:var(--label); letter-spacing:0.25em; text-transform:uppercase; margin-top:3px; }
.header-right { margin-left:auto; display:flex; align-items:center; gap:10px; flex-wrap:wrap; justify-content:flex-end; }
.status-pill { display:flex; align-items:center; gap:8px; padding:6px 12px; border:1px solid var(--border); font-size:11px; letter-spacing:0.15em; text-transform:uppercase; color:var(--label); transition:all 0.3s; white-space:nowrap; }
.status-pill { display:flex; align-items:center; gap:8px; height:34px; padding:0 14px; border:1px solid var(--border); font-size:11px; letter-spacing:0.15em; text-transform:uppercase; color:var(--label); transition:all 0.3s; white-space:nowrap; }
.status-pill.connected { border-color:var(--ok); color:var(--ok); }
.status-pill.connecting { border-color:var(--warn); color:var(--warn); }
.dot { width:7px; height:7px; border-radius:50%; background:var(--dim); flex-shrink:0; }
@@ -131,6 +131,8 @@
.btn:disabled { border-color:var(--dim); color:var(--dim); cursor:not-allowed; }
.btn:disabled::before { display:none; }
.btn:disabled:hover { color:var(--dim); }
.btn-debug { border:1px solid var(--dim); color:var(--label); min-width:52px; text-align:center; font-size:10px; height:34px; padding:0 10px; }
.btn-debug::before { background:var(--accent); }
.btn-theme { border:1px solid var(--dim); color:var(--label); min-width:72px; text-align:center; }
.btn-theme::before { background:var(--text); }
@@ -146,10 +148,25 @@
.chg-badge.full { border-color:var(--ok); color:var(--ok); }
.chg-badge.show { display:flex; }
main { max-width:1100px; margin:0 auto; padding:32px 20px 80px; display:grid; grid-template-columns:1fr 380px; gap:16px; align-items:start; }
main { max-width:1440px; margin:0 auto; padding:32px 20px 80px; display:grid; grid-template-columns:1fr 1fr 380px; gap:16px; align-items:start; }
.col-left { display:grid; gap:12px; }
.col-mid { display:grid; gap:12px; }
.col-right { display:grid; gap:12px; position:sticky; top:80px; }
/* Responsive */
@media (max-width:1100px) {
main { grid-template-columns:1fr 380px; grid-template-rows:auto auto; }
.col-left { grid-column:1; grid-row:1; }
.col-mid { grid-column:1; grid-row:2; }
.col-right { grid-column:2; grid-row:1/3; }
}
@media (max-width:700px) {
main { grid-template-columns:1fr; }
.col-left, .col-mid, .col-right { grid-column:1; grid-row:auto; }
.col-right { position:static; }
}
.section-label { font-family:var(--sans); font-size:11px; font-weight:600; letter-spacing:0.3em; text-transform:uppercase; color:var(--label); padding:4px 0; border-bottom:1px solid var(--border); margin-bottom:4px; display:flex; align-items:center; gap:8px; }
.section-label::before { content:'//'; color:var(--accent); font-family:var(--mono); font-size:10px; }
@@ -175,7 +192,6 @@
.seg-btn:last-child { border-right:none; }
.seg-btn.active { background:var(--accent); color:var(--bg); font-weight:bold; }
.seg-btn:disabled { cursor:not-allowed; opacity:0.35; }
.charge-seg .seg-btn.active.off { background:var(--dim); color:#fff; }
.charge-seg .seg-btn.active.slow { background:var(--warn); color:var(--bg); }
.charge-seg .seg-btn.active.fast { background:var(--accent2);color:#fff; }
@@ -222,6 +238,8 @@
.viz-panel { background:var(--panel2); border:1px solid var(--border); padding:16px; }
.viz-header { display:flex; justify-content:space-between; align-items:center; margin-bottom:12px; }
.viz-title { font-family:var(--sans); font-size:11px; font-weight:600; letter-spacing:0.25em; text-transform:uppercase; color:var(--label); }
.orient-card { padding:12px; display:flex; flex-direction:column; align-items:center; }
#orientCanvas { display:block; width:100%; aspect-ratio:1; }
.viz-ctrl-btn { background:none; border:1px solid var(--border); color:var(--label); font-size:11px; line-height:1; padding:3px 8px; cursor:pointer; letter-spacing:0.05em; }
.viz-ctrl-btn:hover { border-color:var(--accent); color:var(--accent); }
.viz-live { font-size:9px; letter-spacing:0.2em; display:block; }
@@ -262,11 +280,35 @@
.btn-confirm { border-color:var(--accent2); color:var(--accent2); }
.btn-confirm:hover { background:var(--accent2); color:var(--bg); }
/* 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; }
.debug-close { background:none; border:1px solid var(--border); color:var(--label); font-size:14px; cursor:pointer; padding:2px 8px; font-family:var(--mono); }
.debug-close:hover { border-color:var(--text); color:var(--text); }
.debug-live { max-height:340px; overflow-y:auto; border:1px solid var(--border); margin-bottom:12px; }
.debug-table { width:100%; border-collapse:collapse; font-family:var(--mono); font-size:10px; }
.debug-table thead { position:sticky; top:0; background:var(--panel); z-index:1; }
.debug-table th { padding:4px 6px; text-align:right; color:var(--label); font-weight:400; border-bottom:1px solid var(--border); letter-spacing:0.1em; text-transform:uppercase; }
.debug-table td { padding:2px 6px; text-align:right; color:var(--text); border-bottom:1px solid color-mix(in srgb, var(--border) 40%, transparent); white-space:nowrap; }
.debug-table td:last-child { text-align:left; color:var(--label); }
.debug-table .shock-row td { color:var(--accent2); }
.debug-controls { display:flex; align-items:center; gap:10px; }
.debug-rec-btn { font-family:var(--mono); font-size:12px; font-weight:700; padding:6px 14px; cursor:pointer; border:1px solid var(--accent2); color:var(--accent2); background:transparent; letter-spacing:0.1em; }
.debug-rec-btn.recording { background:var(--accent2); color:var(--bg); animation:rec-pulse 1s infinite; }
@keyframes rec-pulse { 0%,100%{opacity:1} 50%{opacity:0.6} }
.debug-rec-count { font-family:var(--mono); font-size:10px; color:var(--label); }
.debug-ctrl-btn { font-family:var(--mono); font-size:10px; padding:5px 10px; cursor:pointer; border:1px solid var(--border); color:var(--label); background:transparent; }
.debug-ctrl-btn:hover { border-color:var(--text); color:var(--text); }
.debug-shock-badge { font-family:var(--mono); font-size:9px; letter-spacing:0.15em; padding:2px 8px; border:1px solid var(--border); color:var(--border); opacity:0.3; transition:all 0.15s; }
.debug-shock-badge.active { border-color:var(--accent2); color:var(--accent2); opacity:1; }
.no-ble { grid-column:1/-1; text-align:center; padding:80px 24px; }
.no-ble h2 { font-family:var(--sans); font-size:28px; font-weight:700; color:var(--accent2); margin-bottom:12px; }
.no-ble p { font-size:13px; color:var(--label); line-height:1.8; }
body.disconnected .card { opacity:0.45; pointer-events:none; transition:opacity 0.3s; }
body.disconnected .card.ota-card { opacity:1; pointer-events:auto; } /* OTA works when disconnected too */
body.disconnected .cmd-grid { opacity:0.45; pointer-events:none; transition:opacity 0.3s; }
.tap-key-row { display:flex; align-items:center; gap:10px; padding-top:12px; flex-wrap:wrap; }
@@ -276,8 +318,29 @@
.mod-btn input:checked + span { background:var(--accent); color:var(--bg); border-color:var(--accent); font-weight:bold; }
.mod-btn input:disabled + span { opacity:0.35; cursor:not-allowed; }
.restart-note { color:var(--warn); font-family:var(--mono); font-size:9px; }
.tap-flash { position:absolute; inset:0; pointer-events:none; opacity:0; transition:opacity 0.25s; }
.tap-flash.left { background:radial-gradient(circle at center, var(--tap-left) 0%, transparent 70%); }
.tap-flash.right { background:radial-gradient(circle at center, var(--tap-right) 0%, transparent 70%); }
.tap-flash.show { opacity:1; }
.viz-wrap { position:relative; }
/* ── OTA Firmware Update ── */
.ota-card { display:flex; flex-direction:column; gap:14px; }
.ota-notice { display:flex; gap:12px; align-items:flex-start; padding:10px 12px; background:color-mix(in srgb, var(--warn) 8%, var(--bg)); border-left:3px solid var(--warn); }
.ota-notice-icon { font-size:16px; color:var(--warn); flex-shrink:0; line-height:1.4; }
.ota-notice-title { font-family:var(--sans); font-size:11px; font-weight:700; color:var(--warn); letter-spacing:0.08em; text-transform:uppercase; margin-bottom:4px; }
.ota-notice-body { font-family:var(--mono); font-size:10px; color:var(--label); line-height:1.6; }
.ota-steps { font-family:var(--mono); font-size:10px; color:var(--label); line-height:1.9; margin:0; padding-left:18px; }
.ota-steps code { color:var(--text); }
.ota-steps strong { color:var(--text); }
.ota-steps em { color:var(--accent); font-style:normal; }
.ota-btn-row { display:grid; gap:8px; }
.ota-status-row { min-height:14px; }
.ota-status { font-family:var(--mono); font-size:10px; color:var(--label); }
.ota-status.ota-ok { color:var(--ok); }
.ota-status.ota-err { color:var(--accent2); }
.cmd-btn.ota-trigger::before { background:var(--accent); }
.cmd-btn.ota-trigger:hover { border-color:var(--accent); }