Compare commits

..

16 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
15 changed files with 560 additions and 601 deletions
+2 -1
View File
@@ -5,4 +5,5 @@
*.claude
*.vscode
web/version.js
samples/
samples/
firmware_dfu.zip
+157 -251
View File
@@ -1,290 +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
TOL = 0.25
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
# Circular notch
NOTCH_R = (USBC_W + TOL) / 2
NOTCH_DEPTH = WALL + 2.0
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
# ─── HELPERS ──────────────────────────────────────────────────────────────────
# Circular notch helper
def circular_notch(face_x, cy, cz, r, depth):
circle = Part.makeCircle(r, Base.Vector(face_x, cy, cz), Base.Vector(1, 0, 0))
face = Part.Face(Part.Wire(circle))
return face.extrude(Base.Vector(-depth, 0, 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
# 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
x0, y0 = (cx if ix>0 else cx-sl), (cy if iy>0 else cy-pw)
w1 = box(sl, pw, h, x0, y0, WALL)
x1, y1 = (cx if ix>0 else cx-pw), (cy if iy>0 else cy-sl)
w2 = box(pw, sl, h, x1, y1, WALL)
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)
return plat.fuse(w1).fuse(w2)
cy = oy + w / 2.0
cz = oz + h / 2.0
hw = w / 2.0 - r
# ═════════════════════════════════════════════════════════════════════════════
# CONSTRUCTION
# ═════════════════════════════════════════════════════════════════════════════
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)
)
# 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))
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()
# 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))
line_top = Part.makeLine(
l_end,
pt(ox, cy + hw, cz, 90, r)
)
# 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)
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()
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)
line_bot = Part.makeLine(r_end, l_start)
# 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)
wire = Part.Wire([arc_left, line_top, arc_right, line_bot])
face = Part.Face(wire)
# 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))
return face.extrude(Base.Vector(depth, 0, 0))
# 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))
# 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))
# Board clip helper
def make_clip(corner_x, corner_y, inward_x, inward_y):
# 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)
plat_w = ARM_THICK + CLIP_TOL
# 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))
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
# 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))
platform = box(
plat_w, plat_w,
PLATFORM_H + PCB_T,
plat_x, plat_y, WALL
)
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)
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)
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
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)
)
# Circular notch in back wall - centred on base
notch_cz = rail_z + LID_H
base = base.cut(circular_notch(L, W / 2, notch_cz, NOTCH_R, NOTCH_DEPTH))
# 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.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")
+4 -2
View File
@@ -25,8 +25,10 @@ upload_speed = 115200
; Uncomment and set the correct port if auto-detect fails:
; upload_port = COM3
; Build scripts
extra_scripts = pre:scripts/git_hash.py
; 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 =
+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
+3 -2
View File
@@ -36,14 +36,15 @@ void updateBattery() {
ChargeStatus status = chg ? (pct >= 99 ? CHGSTAT_FULL : CHGSTAT_CHARGING) : CHGSTAT_DISCHARGING;
// Only write BLE Battery Service when connected - blebas.write() blocks on the
// SoftDevice ATT layer and causes 30-40ms loop stalls when called during advertising.
if (Bluefruit.connected()) blebas.write(pct);
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]);
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())
+9 -17
View File
@@ -26,14 +26,13 @@ BLECharacteristic cfgGitHash (0x1239); // GitHash R 8 bytes (7-char ha
#endif
#endif
// Charge mode
// Charge mode
void applyChargeMode(ChargeMode mode) {
switch (mode) {
case CHARGE_OFF: pinMode(PIN_HICHG, INPUT_PULLUP); break;
case CHARGE_SLOW: pinMode(PIN_HICHG, OUTPUT); digitalWrite(PIN_HICHG, HIGH); break;
case CHARGE_FAST: pinMode(PIN_HICHG, OUTPUT); digitalWrite(PIN_HICHG, LOW); 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]);
}
@@ -78,9 +77,6 @@ void pushConfigBlob() {
b.tapFreezeEnabled = cfg.tapFreezeEnabled;
b.jerkThreshold = cfg.jerkThreshold;
b.featureFlags = cfg.featureFlags;
b.btnLeftPin = cfg.btnLeftPin;
b.btnRightPin = cfg.btnRightPin;
b.btnMiddlePin = cfg.btnMiddlePin;
cfgBlob.write((uint8_t*)&b, sizeof(b));
}
#endif
@@ -113,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;
@@ -126,13 +122,6 @@ void onConfigBlobWrite(uint16_t h, BLECharacteristic* c, uint8_t* d, uint16_t l)
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);
// btnXPin: accept BTN_PIN_NONE (0xFF) or a valid Arduino pin number (0-10 = D0-D10)
cfg.btnLeftPin = (b->btnLeftPin <= 10 || b->btnLeftPin == BTN_PIN_NONE) ? b->btnLeftPin : BTN_PIN_NONE;
cfg.btnRightPin = (b->btnRightPin <= 10 || b->btnRightPin == BTN_PIN_NONE) ? b->btnRightPin : BTN_PIN_NONE;
cfg.btnMiddlePin = (b->btnMiddlePin <= 10 || b->btnMiddlePin == BTN_PIN_NONE) ? b->btnMiddlePin : BTN_PIN_NONE;
#ifdef FEATURE_PHYSICAL_BUTTONS
setupPhysicalButtons(); // reconfigure pins immediately (no restart needed)
#endif
saveConfig();
Serial.print("[CFG] Written - sens="); Serial.print(cfg.sensitivity,0);
Serial.print(" dz="); Serial.print(cfg.deadZone,3);
@@ -144,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
@@ -164,7 +156,7 @@ 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);
+59 -15
View File
@@ -4,8 +4,18 @@
#include <bluefruit.h>
extern BLEHidAdafruit blehid;
extern Config cfg;
static uint8_t physBtnMask = 0; // bitmask of currently-pressed physical buttons
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() {
@@ -13,19 +23,19 @@ void setupPhysicalButtons() {
if (physBtnMask && Bluefruit.connected()) { blehid.mouseButtonRelease(); }
physBtnMask = 0;
if (cfg.btnLeftPin != BTN_PIN_NONE) pinMode(cfg.btnLeftPin, INPUT_PULLUP);
if (cfg.btnRightPin != BTN_PIN_NONE) pinMode(cfg.btnRightPin, INPUT_PULLUP);
if (cfg.btnMiddlePin != BTN_PIN_NONE) pinMode(cfg.btnMiddlePin, INPUT_PULLUP);
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 = (cfg.btnLeftPin != BTN_PIN_NONE) || (cfg.btnRightPin != BTN_PIN_NONE)
|| (cfg.btnMiddlePin != BTN_PIN_NONE);
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=");
cfg.btnLeftPin == BTN_PIN_NONE ? Serial.print("--") : Serial.print(cfg.btnLeftPin);
BTN_LEFT_PIN == BTN_PIN_NONE ? Serial.print("--") : Serial.print(BTN_LEFT_PIN);
Serial.print(" R=");
cfg.btnRightPin == BTN_PIN_NONE ? Serial.print("--") : Serial.print(cfg.btnRightPin);
BTN_RIGHT_PIN == BTN_PIN_NONE ? Serial.print("--") : Serial.print(BTN_RIGHT_PIN);
Serial.print(" M=");
cfg.btnMiddlePin == BTN_PIN_NONE ? Serial.print("--") : Serial.print(cfg.btnMiddlePin);
BTN_MIDDLE_PIN == BTN_PIN_NONE ? Serial.print("--") : Serial.print(BTN_MIDDLE_PIN);
Serial.println();
}
}
@@ -36,16 +46,50 @@ void setupPhysicalButtons() {
void processPhysicalButtons() {
if (!Bluefruit.connected()) return;
uint8_t newMask = 0;
if (cfg.btnLeftPin != BTN_PIN_NONE && digitalRead(cfg.btnLeftPin) == LOW) newMask |= MOUSE_BUTTON_LEFT;
if (cfg.btnRightPin != BTN_PIN_NONE && digitalRead(cfg.btnRightPin) == LOW) newMask |= MOUSE_BUTTON_RIGHT;
if (cfg.btnMiddlePin != BTN_PIN_NONE && digitalRead(cfg.btnMiddlePin) == LOW) newMask |= MOUSE_BUTTON_MIDDLE;
unsigned long now = millis();
if (newMask != physBtnMask) {
// 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();
Serial.print("[BTN] mask=0x"); Serial.println(physBtnMask, HEX);
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");
}
}
+16 -17
View File
@@ -5,12 +5,13 @@
#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
// #define DEBUG
@@ -54,10 +55,14 @@
// Persistence
#define CONFIG_FILENAME "/imu_mouse_cfg.bin"
#define CONFIG_MAGIC 0xDEAD123DUL
#define CONFIG_MAGIC 0xDEAD123EUL
// Physical button sentinel
#define BTN_PIN_NONE 0xFF // Stored in btn*Pin when that button is disabled
// 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
@@ -69,7 +74,7 @@
// 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
@@ -98,9 +103,6 @@ struct Config {
float jerkThreshold; // jerk² threshold for tap-freeze detection
uint8_t tapFreezeEnabled; // 1 = enable jerk-based cursor freeze during taps
uint8_t featureFlags; // bitmask of FLAG_* - runtime feature overrides
uint8_t btnLeftPin; // BTN_PIN_NONE or Arduino pin number (0-10 = D0-D10)
uint8_t btnRightPin;
uint8_t btnMiddlePin;
};
extern Config cfg;
extern const Config CFG_DEFAULTS;
@@ -120,11 +122,8 @@ struct __attribute__((packed)) ConfigBlob {
uint8_t tapFreezeEnabled; // [19] 1 = enable jerk-based cursor freeze during taps
float jerkThreshold; // [20] jerk² tap-freeze threshold
uint8_t featureFlags; // [24] FLAG_* bitmask - runtime feature overrides
uint8_t btnLeftPin; // [25] BTN_PIN_NONE or Arduino pin (0-10 = D0-D10)
uint8_t btnRightPin; // [26]
uint8_t btnMiddlePin; // [27]
};
static_assert(sizeof(ConfigBlob) == 28, "ConfigBlob must be 28 bytes");
static_assert(sizeof(ConfigBlob) == 25, "ConfigBlob must be 25 bytes");
// TelemetryPacket (24 bytes)
#ifdef FEATURE_TELEMETRY
@@ -159,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;
@@ -185,10 +183,8 @@ 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 gravX, gravY, gravZ;
extern float biasGX, biasGY, biasGZ;
extern float calTempC;
extern float cachedTempC;
@@ -207,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;
+1 -3
View File
@@ -34,9 +34,7 @@ void calibrateGyroBias() {
biasGY = (float)(sy/BIAS_SAMPLES);
biasGZ = (float)(sz/BIAS_SAMPLES);
calTempC = readIMUTemp();
angleX = angleY = accumX = accumY = 0.0f;
// Seed gravity estimate from current accel so projection is correct immediately
gravX = imu.readFloatAccelX(); gravY = imu.readFloatAccelY(); gravZ = imu.readFloatAccelZ();
accumX = accumY = 0.0f;
#ifdef FEATURE_TELEMETRY
statRecalCount++;
+59 -74
View File
@@ -17,7 +17,6 @@
#include "imu.h"
#include "ble_config.h"
#include "battery.h"
#include "tap.h"
#include "buttons.h"
#include <bluefruit.h>
#include <Adafruit_LittleFS.h>
@@ -46,9 +45,8 @@ File cfgFile(InternalFS);
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,
/*jerkThreshold=*/2000.0f, /*tapFreezeEnabled=*/1, /*featureFlags=*/FLAG_ALL_DEFAULT,
/*btnLeftPin=*/BTN_PIN_NONE, /*btnRightPin=*/BTN_PIN_NONE, /*btnMiddlePin=*/BTN_PIN_NONE
/*tapThreshold=*/12, /*tapAction=*/TAP_ACTION_KEY, /*tapKey=*/0x04, /*tapMod=*/0x03, // Ctrl+Shift+A
/*jerkThreshold=*/2000.0f, /*tapFreezeEnabled=*/1, /*featureFlags=*/FLAG_ALL_DEFAULT
};
// Telemetry definition
@@ -56,9 +54,9 @@ const Config CFG_DEFAULTS = {
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;
@@ -82,11 +80,8 @@ 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;
// Low-pass filtered gravity estimate in device frame (for roll-independent axis projection)
float gravX = 0, gravY = 0, gravZ = 1.0f;
float biasGX = 0, biasGY = 0, biasGZ = 0;
float calTempC = 25.0f;
float cachedTempC = 25.0f;
@@ -116,11 +111,10 @@ float cachedTempC = 25.0f;
uint32_t loopStalls = 0; // loop iterations where dt > 20ms (behind schedule)
bool pendingCal = false;
bool pendingReset = false;
#ifdef FEATURE_OTA
bool pendingOTA = false;
#endif
// Jerk-based shock detection - freeze cursor during tap impacts, doesn't work well yet!
unsigned long shockFreezeUntil = 0;
float prevAx = 0, prevAy = 0, prevAz = 0; // previous frame's accel for Δa
const unsigned long SHOCK_FREEZE_MS = 80; // hold freeze after last spike
ChargeStatus lastChargeStatus = CHGSTAT_DISCHARGING;
@@ -221,8 +215,6 @@ void setup() {
#endif
calibrateGyroBias();
// Seed previous-accel for jerk detection so first frame doesn't spike
prevAx = imu.readFloatAccelX(); prevAy = imu.readFloatAccelY(); prevAz = imu.readFloatAccelZ();
sleepManagerInit();
@@ -293,15 +285,35 @@ void loop() {
}
#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(); prevAx = imu.readFloatAccelX(); prevAy = imu.readFloatAccelY(); prevAz = imu.readFloatAccelZ(); }
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) {
@@ -349,62 +361,32 @@ void loop() {
if (cfg.featureFlags & FLAG_TEMP_COMP_ENABLED)
correction = TEMP_COMP_COEFF_DPS_C * (cachedTempC - calTempC);
#endif
float gx = (imu.readFloatGyroX() - biasGX - correction) * (PI/180.0f);
float gy = (imu.readFloatGyroY() - biasGY - correction) * (PI/180.0f);
float gz = (imu.readFloatGyroZ() - biasGZ - correction) * (PI/180.0f);
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
float ax = imu.readFloatAccelX();
float ay = imu.readFloatAccelY();
float az = imu.readFloatAccelZ();
// 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"); }
// Jerk-based shock detection - freeze cursor during tap impacts, doesn't work well yet
float jx = (ax - prevAx) / dt, jy = (ay - prevAy) / dt, jz = (az - prevAz) / dt;
float jerkSq = jx*jx + jy*jy + jz*jz;
prevAx = ax; prevAy = ay; prevAz = az;
bool shocked = cfg.tapFreezeEnabled && ((jerkSq > cfg.jerkThreshold) || (now < shockFreezeUntil));
if (cfg.tapFreezeEnabled && jerkSq > cfg.jerkThreshold) shockFreezeUntil = now + SHOCK_FREEZE_MS;
// 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
// Complementary filter
if (shocked) {
angleX += gx * dt;
angleY += gz * dt;
} else {
angleX = ALPHA*(angleX + gx*dt) + (1.0f - ALPHA)*atan2f(ax, sqrtf(ay*ay + az*az));
angleY = ALPHA*(angleY + gz*dt) + (1.0f - ALPHA)*atan2f(ay, sqrtf(ax*ax + az*az));
}
// Gravity-based axis decomposition
const float GRAV_LP = 0.05f;
if (!shocked) {
gravX += GRAV_LP * (ax - gravX);
gravY += GRAV_LP * (ay - gravY);
gravZ += GRAV_LP * (az - gravZ);
}
float gN = sqrtf(gravX*gravX + gravY*gravY + gravZ*gravZ);
if (gN < 0.3f) gN = 1.0f;
float gnx = gravX/gN, gny = gravY/gN, gnz = gravZ/gN;
float ry = -gnz, rz = gny;
float rN = sqrtf(ry*ry + rz*rz);
if (rN < 0.01f) { ry = -1.0f; rz = 0.0f; rN = 1.0f; }
ry /= rN; rz /= rN;
// Yaw (cursor X) = angular velocity component around gravity (vertical)
// Pitch (cursor Y) = angular velocity component around screen-right
float yawRate = gx*gnx + gy*gny + gz*gnz;
float pitchRate = -(gy*ry + gz*rz);
// Projected rates amplify residual gyro bias (especially GY drift on pitch axis).
float fYaw = (fabsf(yawRate) > cfg.deadZone) ? yawRate : 0.0f;
float fPitch = (fabsf(pitchRate) > cfg.deadZone * 3.0f) ? pitchRate : 0.0f;
// 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("[PROJ] grav="); Serial.print(gnx,2); Serial.print(","); Serial.print(gny,2); Serial.print(","); Serial.print(gnz,2);
Serial.print(" R="); Serial.print(ry,2); Serial.print(","); Serial.print(rz,2);
Serial.print(" gyro="); Serial.print(gx,2); Serial.print(","); Serial.print(gy,2); Serial.print(","); Serial.print(gz,2);
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);
}
}
@@ -418,18 +400,17 @@ void loop() {
#ifdef FEATURE_AUTO_RECAL
if ((cfg.featureFlags & FLAG_AUTO_RECAL_ENABLED) && idle && idleStartMs != 0 && (now - idleStartMs >= AUTO_RECAL_MS)) {
Serial.println("[AUTO-CAL] Long idle - recalibrating...");
idleStartMs = 0; calibrateGyroBias(); prevAx = imu.readFloatAccelX(); prevAy = imu.readFloatAccelY(); prevAz = imu.readFloatAccelZ(); return;
idleStartMs = 0; calibrateGyroBias(); return;
}
#endif
int8_t moveX = 0, moveY = 0;
uint8_t flags = 0;
if (shocked) {
// Shock freeze - discard accumulated sub-pixel motion and suppress output
accumX = accumY = 0.0f;
flags |= 0x08; // bit3 = shock freeze active
} else if (idle) {
static float smoothX = 0.0f, smoothY = 0.0f;
if (idle) {
smoothX = smoothY = 0.0f;
accumX = accumY = 0.0f;
flags |= 0x01;
} else {
@@ -437,7 +418,10 @@ void loop() {
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;
@@ -452,6 +436,7 @@ void loop() {
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.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);
+79 -27
View File
@@ -34,6 +34,17 @@ static volatile bool pendingWakeRecal = false; // set only when recal is also
// 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);
@@ -50,11 +61,16 @@ static void lsmWrite(uint8_t reg, uint8_t val) {
Wire1.endTransmission();
}
// ISR
// 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));
@@ -116,6 +132,15 @@ static void enterImuLP() {
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 ");
@@ -142,9 +167,9 @@ static void enterDeepSleep() {
Serial.println("[SLEEP] Deep sleep - WFE on INT1");
Serial.flush();
digitalWrite(LED_RED, LOW); delay(80); digitalWrite(LED_RED, HIGH);
digitalWrite(LED_RED, HIGH); digitalWrite(LED_GREEN, HIGH); digitalWrite(LED_BLUE, HIGH);
while (!imuWakeFlag) {
while (!imuWakeFlag && !btnWakeFlag) {
(void)lsmRead(SLP_WAKE_UP_SRC);
sd_app_evt_wait();
}
@@ -161,6 +186,11 @@ void sleepManagerWakeIMU() {
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;
@@ -175,24 +205,9 @@ void sleepManagerWakeIMU() {
lpEnteredMs = 0;
// Reset motion filter state to prevent a cursor jump on the first frame.
// After sleep: angleX/Y are stale, gravX/Y/Z drifted, accumX/Y is dirty,
// and lastTime is old so dt would be huge on the first loop iteration.
// Zeroing these here means the first frame integrates 0 motion cleanly.
extern float angleX, angleY;
extern float accumX, accumY;
extern float gravX, gravY, gravZ;
extern float prevAx, prevAy, prevAz;
extern unsigned long lastTime;
angleX = angleY = 0.0f;
accumX = accumY = 0.0f;
// Reseed gravity from current accel so projection is correct immediately.
// Can't call imu.readFloat* here (gyro not fully settled), but accel is
// already running - read it directly via Wire1.
// Simpler: just reset to neutral [0,0,1] and let the LP filter converge
// over the first ~20 frames (200 ms) of real use.
gravX = 0.0f; gravY = 0.0f; gravZ = 1.0f;
prevAx = 0.0f; prevAy = 0.0f; prevAz = 0.0f;
// Set lastTime to now so the first dt = 0 rather than (now - sleepEntryTime)
lastTime = millis();
sleepStage = SLEEP_AWAKE;
@@ -227,26 +242,63 @@ void sleepManagerInit() {
// Returns true → caller must skip IMU reads this iteration.
bool sleepManagerUpdate(unsigned long nowMs, bool idle, bool bleConnected) {
// ISR wakeup
// 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); // normal-mode edge, clear latch only
(void)lsmRead(SLP_WAKE_UP_SRC);
}
}
// Gyro settling after wake
// Post-wake recalibration — gated on device being still
if (pendingWakeRecal) {
if (nowMs - wakeSettleMs >= 120) {
pendingWakeRecal = false;
wakeSettleMs = 0;
extern void calibrateGyroBias();
calibrateGyroBias();
Serial.println("[SLEEP] Post-wake recal done");
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;
}
+2 -2
View File
@@ -11,12 +11,12 @@
// LSM6DS3 wakeup threshold: 1 LSB = 7.8 mg at ±2 g FS (±2g range).
#ifndef SLEEP_WAKEUP_THS
#define SLEEP_WAKEUP_THS 16 // 063
#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 2 // 03
#define SLEEP_WAKEUP_DUR 1 // 03
#endif
// GPIO pin connected to LSM6DS3 INT1.
+70 -61
View File
@@ -16,10 +16,10 @@ 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,
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,
btnLeftPin:0xFF, btnRightPin:0xFF, btnMiddlePin:0xFF };
};
let device=null, server=null, chars={}, userDisconnected=false;
let currentChargeStatus=0, currentBattPct=null, currentBattVoltage=null;
@@ -37,7 +37,10 @@ let _gattDepth = 0;
function _withTimeout(promise, ms) {
return new Promise((resolve, reject) => {
const t = setTimeout(() => reject(new Error(`GATT timeout (${ms}ms)`)), ms);
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); });
});
@@ -45,6 +48,7 @@ function _withTimeout(promise, ms) {
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++;
@@ -57,6 +61,7 @@ function gattWrite(char, value) { return _enqueue(() => char.writeValueWithRespo
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;
@@ -132,12 +137,11 @@ async function discoverServices() {
await checkHashMatch();
// Telemetry notify (1 Hz) - also carries chargeStatus
chars.telemetry.addEventListener('characteristicvaluechanged', e => parseTelemetry(e.target.value));
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();
// Initial read so values show immediately. Also force updateChargeUI() here
// because parseTelemetry() only calls it on a *change*, and currentChargeStatus
// starts at 0 (discharging) - so a discharging device would never trigger the
// update and ciStatus would stay at '--'.
parseTelemetry(await chars.telemetry.readValue());
updateChargeUI();
@@ -210,7 +214,7 @@ async function checkHashMatch() {
// 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 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]
@@ -240,13 +244,6 @@ async function readConfigBlob() {
} else {
config.featureFlags = FLAG_ALL_DEFAULT; // old firmware - assume all on
}
if (view.byteLength >= 28) {
config.btnLeftPin = view.getUint8(25);
config.btnRightPin = view.getUint8(26);
config.btnMiddlePin = view.getUint8(27);
} else {
config.btnLeftPin = config.btnRightPin = config.btnMiddlePin = 0xFF; // disabled
}
applyConfigToUI();
log(`Config loaded - sens=${config.sensitivity.toFixed(0)} dz=${config.deadZone.toFixed(3)} tapThr=${config.tapThreshold}`,'ok');
} catch(e) { log(`Config read error: ${e.message}`,'err'); }
@@ -278,38 +275,8 @@ function applyConfigToUI() {
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);
document.getElementById('btnLeftPin').value = config.btnLeftPin;
document.getElementById('btnRightPin').value = config.btnRightPin;
document.getElementById('btnMiddlePin').value = config.btnMiddlePin;
updatePinDiagram();
}
// XIAO pin diagram
function updatePinDiagram() {
const st = getComputedStyle(document.documentElement);
const COL_L = st.getPropertyValue('--ok').trim();
const COL_R = st.getPropertyValue('--accent2').trim();
const COL_M = st.getPropertyValue('--accent').trim();
const DEF_F = '#0c1828', DEF_S = '#162234';
for (let i = 0; i <= 10; i++) {
const el = document.getElementById(`xiaoPin${i}`);
if (el) { el.setAttribute('fill', DEF_F); el.setAttribute('stroke', DEF_S); }
}
const apply = (pin, col) => {
if (pin > 10) return;
const el = document.getElementById(`xiaoPin${pin}`);
if (el) { el.setAttribute('fill', col); el.setAttribute('stroke', col); }
};
const l = parseInt(document.getElementById('btnLeftPin').value, 10);
const r = parseInt(document.getElementById('btnRightPin').value, 10);
const m = parseInt(document.getElementById('btnMiddlePin').value, 10);
if (l <= 10) apply(l, COL_L);
if (r <= 10) apply(r, COL_R);
if (m <= 10) apply(m, COL_M);
}
let _writeConfigTimer = null;
function writeConfigBlob() {
@@ -337,11 +304,7 @@ async function _doWriteConfigBlob() {
| (document.getElementById('capAutoRecal').checked ? FLAG_AUTO_RECAL_ENABLED : 0);
// config.curve, config.chargeMode, config.tapAction, config.tapKey updated directly
config.btnLeftPin = parseInt(document.getElementById('btnLeftPin').value, 10);
config.btnRightPin = parseInt(document.getElementById('btnRightPin').value, 10);
config.btnMiddlePin = parseInt(document.getElementById('btnMiddlePin').value, 10);
const buf = new ArrayBuffer(28);
const buf = new ArrayBuffer(25);
const view = new DataView(buf);
view.setFloat32(0, config.sensitivity, true);
view.setFloat32(4, config.deadZone, true);
@@ -356,9 +319,6 @@ async function _doWriteConfigBlob() {
view.setUint8(19, config.tapFreezeEnabled);
view.setFloat32(20, config.jerkThreshold, true);
view.setUint8(24, config.featureFlags);
view.setUint8(25, config.btnLeftPin);
view.setUint8(26, config.btnRightPin);
view.setUint8(27, config.btnMiddlePin);
try {
await gattWrite(chars.configBlob, buf);
@@ -384,15 +344,15 @@ 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) {
@@ -484,7 +444,6 @@ 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();
@@ -493,6 +452,8 @@ function parseTelemetry(dv) {
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) {
@@ -547,6 +508,7 @@ let debugLiveRing = [];
let debugT0 = 0;
function openDebugModal() {
console.log('[DEBUG] modal opened (imuSubscribed=' + imuSubscribed + ')');
debugModalOpen = true;
debugT0 = Date.now();
debugLiveRing = [];
@@ -555,6 +517,7 @@ function openDebugModal() {
if (!imuSubscribed && chars.imuStream) vizSetPaused(false);
}
function closeDebugModal() {
console.log('[DEBUG] modal closed');
debugModalOpen = false;
document.getElementById('debugOverlay').classList.remove('show');
}
@@ -651,7 +614,7 @@ function setStatus(state) {
pill.className='status-pill '+state;
document.body.className=state;
const cBtn=document.getElementById('connectBtn'), dBtn=document.getElementById('disconnectBtn');
const inputs=document.querySelectorAll('input[type=range],.seg-btn,.toggle input,.cmd-btn,#tapKeyHex,.mod-btn input,.pin-select');
const inputs=document.querySelectorAll('input[type=range],.seg-btn,.toggle input,.cmd-btn,#tapKeyHex,.mod-btn input');
if (state==='connected') {
cBtn.style.display='none'; dBtn.style.display='';
inputs.forEach(el=>el.disabled=false);
@@ -706,6 +669,7 @@ 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
@@ -715,7 +679,9 @@ 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; }
}
@@ -771,6 +737,7 @@ 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;
@@ -778,12 +745,15 @@ async function vizSetPaused(paused) {
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();
}
@@ -817,6 +787,7 @@ function parseImuStream(dv) {
feedDebugRow(gyroX, gyroZ, accelX, accelY, accelZ, moveX, moveY, flags);
if (vizPaused) return;
const idle = !!(flags & 0x01);
const single = !!(flags & 0x02);
const dbl = !!(flags & 0x04);
@@ -835,6 +806,13 @@ function parseImuStream(dv) {
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);
@@ -1018,7 +996,6 @@ function applyTheme(t) {
localStorage.setItem('theme', t);
if (!chars.imuStream) drawInitState();
orientUpdateColors();
updatePinDiagram();
}
(function(){
const saved = localStorage.getItem('theme') ?? 'auto';
@@ -1035,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;
}
}
+26 -119
View File
@@ -86,9 +86,8 @@
<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" id="chargeInfo">
@@ -181,122 +180,6 @@
</div>
</div>
<div class="section-label">Physical Buttons</div>
<div class="card">
<!-- XIAO nRF52840 Sense pin diagram -->
<div class="xiao-wrap">
<svg id="xiaoSvg" viewBox="0 0 200 278" xmlns="http://www.w3.org/2000/svg" style="display:block;width:100%;max-width:200px">
<!-- USB-C connector -->
<rect x="72" y="4" width="56" height="28" rx="7" fill="#080e18" stroke="#162234" stroke-width="1.5"/>
<rect x="82" y="10" width="36" height="5" rx="1.5" fill="#0e1c30"/><rect x="82" y="18" width="36" height="5" rx="1.5" fill="#0e1c30"/>
<text x="100" y="30" text-anchor="middle" font-size="5.5" fill="#162234" font-family="Share Tech Mono,monospace">USB·C</text>
<!-- PCB board -->
<rect x="22" y="29" width="156" height="244" rx="9" fill="#080e18" stroke="#142030" stroke-width="1.5"/>
<!-- Corner holes -->
<circle cx="34" cy="41" r="3.5" fill="#040810" stroke="#0e1c2c" stroke-width="0.8"/>
<circle cx="166" cy="41" r="3.5" fill="#040810" stroke="#0e1c2c" stroke-width="0.8"/>
<circle cx="34" cy="261" r="3.5" fill="#040810" stroke="#0e1c2c" stroke-width="0.8"/>
<circle cx="166" cy="261" r="3.5" fill="#040810" stroke="#0e1c2c" stroke-width="0.8"/>
<!-- Board silk label -->
<text x="100" y="52" text-anchor="middle" font-size="5.5" fill="#142030" font-family="Share Tech Mono,monospace">XIAO nRF52840 Sense</text>
<!-- Antenna outline -->
<rect x="130" y="34" width="34" height="22" rx="2" fill="none" stroke="#0e1c2c" stroke-width="0.7" stroke-dasharray="2,2"/>
<text x="147" y="48" text-anchor="middle" font-size="5" fill="#0e1c2c" font-family="Share Tech Mono,monospace">ANT</text>
<!-- SoC -->
<rect x="60" y="78" width="80" height="72" rx="3" fill="#0c1828" stroke="#142030" stroke-width="0.8"/>
<text x="100" y="112" text-anchor="middle" font-size="7" fill="#1e3858" font-family="Share Tech Mono,monospace" font-weight="bold">nRF52840</text>
<text x="100" y="123" text-anchor="middle" font-size="5.5" fill="#102030" font-family="Share Tech Mono,monospace">HOLYIOT</text>
<!-- BGA dots (decorative) -->
<g fill="#0c1a2a"><circle cx="74" cy="94" r="1.8"/><circle cx="82" cy="94" r="1.8"/><circle cx="90" cy="94" r="1.8"/><circle cx="98" cy="94" r="1.8"/><circle cx="106" cy="94" r="1.8"/><circle cx="114" cy="94" r="1.8"/><circle cx="74" cy="102" r="1.8"/><circle cx="82" cy="102" r="1.8"/><circle cx="90" cy="102" r="1.8"/><circle cx="98" cy="102" r="1.8"/><circle cx="106" cy="102" r="1.8"/><circle cx="114" cy="102" r="1.8"/><circle cx="74" cy="140" r="1.8"/><circle cx="82" cy="140" r="1.8"/><circle cx="90" cy="140" r="1.8"/><circle cx="98" cy="140" r="1.8"/><circle cx="106" cy="140" r="1.8"/><circle cx="114" cy="140" r="1.8"/></g>
<!-- IMU chip -->
<rect x="72" y="176" width="56" height="44" rx="3" fill="#0a1420" stroke="#122030" stroke-width="0.8"/>
<text x="100" y="196" text-anchor="middle" font-size="5.5" fill="#142030" font-family="Share Tech Mono,monospace">LSM6DS3</text>
<text x="100" y="207" text-anchor="middle" font-size="5" fill="#0e1c2c" font-family="Share Tech Mono,monospace">IMU</text>
<!-- Charger IC -->
<rect x="36" y="228" width="30" height="26" rx="2" fill="#0a1420" stroke="#122030" stroke-width="0.8"/>
<text x="51" y="244" text-anchor="middle" font-size="4.5" fill="#0e1c2c" font-family="Share Tech Mono,monospace">BQ25100</text>
<!-- LED indicators -->
<circle cx="142" cy="168" r="3.5" fill="#0a1a0a" stroke="#0e180e" stroke-width="0.8"/>
<circle cx="152" cy="168" r="3.5" fill="#1a0a0a" stroke="#180e0e" stroke-width="0.8"/>
<circle cx="162" cy="168" r="3.5" fill="#0a0a1a" stroke="#0e0e18" stroke-width="0.8"/>
<text x="152" y="178" text-anchor="middle" font-size="4.5" fill="#0e1c2c" font-family="Share Tech Mono,monospace">LED</text>
<!-- Left traces -->
<g stroke="#142030" stroke-width="2"><line x1="22" y1="62" x2="9" y2="62"/><line x1="22" y1="94" x2="9" y2="94"/><line x1="22" y1="126" x2="9" y2="126"/><line x1="22" y1="158" x2="9" y2="158"/><line x1="22" y1="190" x2="9" y2="190"/><line x1="22" y1="222" x2="9" y2="222"/><line x1="22" y1="254" x2="9" y2="254"/></g>
<!-- Right traces -->
<g stroke="#142030" stroke-width="2"><line x1="178" y1="62" x2="191" y2="62"/><line x1="178" y1="94" x2="191" y2="94"/><line x1="178" y1="126" x2="191" y2="126"/><line x1="178" y1="158" x2="191" y2="158"/><line x1="178" y1="190" x2="191" y2="190"/><line x1="178" y1="222" x2="191" y2="222"/><line x1="178" y1="254" x2="191" y2="254"/></g>
<!-- Left pads D0-D6 (arduino 0-6) -->
<circle id="xiaoPin0" cx="9" cy="62" r="7" fill="#0c1828" stroke="#162234" stroke-width="1.5"/>
<circle id="xiaoPin1" cx="9" cy="94" r="7" fill="#0c1828" stroke="#162234" stroke-width="1.5"/>
<circle id="xiaoPin2" cx="9" cy="126" r="7" fill="#0c1828" stroke="#162234" stroke-width="1.5"/>
<circle id="xiaoPin3" cx="9" cy="158" r="7" fill="#0c1828" stroke="#162234" stroke-width="1.5"/>
<circle id="xiaoPin4" cx="9" cy="190" r="7" fill="#0c1828" stroke="#162234" stroke-width="1.5"/>
<circle id="xiaoPin5" cx="9" cy="222" r="7" fill="#0c1828" stroke="#162234" stroke-width="1.5"/>
<circle id="xiaoPin6" cx="9" cy="254" r="7" fill="#0c1828" stroke="#162234" stroke-width="1.5"/>
<!-- Right pads D7-D10 (arduino 7-10) -->
<circle id="xiaoPin7" cx="191" cy="62" r="7" fill="#0c1828" stroke="#162234" stroke-width="1.5"/>
<circle id="xiaoPin8" cx="191" cy="94" r="7" fill="#0c1828" stroke="#162234" stroke-width="1.5"/>
<circle id="xiaoPin9" cx="191" cy="126" r="7" fill="#0c1828" stroke="#162234" stroke-width="1.5"/>
<circle id="xiaoPin10" cx="191" cy="158" r="7" fill="#0c1828" stroke="#162234" stroke-width="1.5"/>
<!-- RST / GND / 3V3 (non-configurable) -->
<circle cx="191" cy="190" r="7" fill="#0c1828" stroke="#102028" stroke-width="1.5"/>
<circle cx="191" cy="222" r="7" fill="#0c1828" stroke="#201010" stroke-width="1.5"/>
<circle cx="191" cy="254" r="7" fill="#0c1828" stroke="#102010" stroke-width="1.5"/>
<!-- Left labels D0-D6 -->
<g font-size="7" font-family="Share Tech Mono,monospace" fill="#1e3858"><text x="24" y="65">D0</text><text x="24" y="97">D1</text><text x="24" y="129">D2</text><text x="24" y="161">D3</text><text x="24" y="193">D4</text><text x="24" y="225">D5</text><text x="24" y="257">D6</text></g>
<g font-size="5.5" font-family="Share Tech Mono,monospace" fill="#112030"><text x="36" y="65">A0</text><text x="36" y="97">A1</text><text x="36" y="129">A2</text><text x="36" y="161">A3</text><text x="36" y="193">SDA</text><text x="36" y="225">SCL</text><text x="36" y="257">TX</text></g>
<!-- Right labels D7-D10 -->
<g font-size="7" font-family="Share Tech Mono,monospace" text-anchor="end" fill="#1e3858"><text x="176" y="65">D7</text><text x="176" y="97">D8</text><text x="176" y="129">D9</text><text x="176" y="161">D10</text></g>
<g font-size="5.5" font-family="Share Tech Mono,monospace" text-anchor="end" fill="#112030"><text x="162" y="65">RX</text><text x="162" y="97">SCK</text><text x="162" y="129">MISO</text><text x="162" y="161">MOSI</text></g>
<!-- RST/GND/3V3 labels -->
<g font-size="7" font-family="Share Tech Mono,monospace" text-anchor="end" fill="#0e1c2c"><text x="176" y="193">RST</text></g>
<g font-size="7" font-family="Share Tech Mono,monospace" text-anchor="end" fill="#1a0808"><text x="176" y="225">GND</text></g>
<g font-size="7" font-family="Share Tech Mono,monospace" text-anchor="end" fill="#081a08"><text x="176" y="257">3V3</text></g>
</svg>
<div class="pin-legend">
<span class="pleg left">● Left</span>
<span class="pleg right">● Right</span>
<span class="pleg mid">● Middle</span>
</div>
</div>
<hr class="xiao-divider">
<div class="flip-row" style="align-items:center;padding-top:4px">
<div class="flip-label">Left Click</div>
<div class="param-desc" style="flex:1;font-size:9px;color:var(--label)">Pin wired to GND when pressed</div>
<select class="pin-select" id="btnLeftPin" onchange="updatePinDiagram();writeConfigBlob()" disabled>
<option value="255">None</option>
<option value="0">D0</option><option value="1">D1</option><option value="2">D2</option>
<option value="3">D3</option><option value="4">D4</option><option value="5">D5</option>
<option value="6">D6</option><option value="7">D7</option><option value="8">D8</option>
<option value="9">D9</option><option value="10">D10</option>
</select>
</div>
<div class="flip-row" style="align-items:center">
<div class="flip-label">Right Click</div>
<div class="param-desc" style="flex:1;font-size:9px;color:var(--label)">Pin wired to GND when pressed</div>
<select class="pin-select" id="btnRightPin" onchange="updatePinDiagram();writeConfigBlob()" disabled>
<option value="255">None</option>
<option value="0">D0</option><option value="1">D1</option><option value="2">D2</option>
<option value="3">D3</option><option value="4">D4</option><option value="5">D5</option>
<option value="6">D6</option><option value="7">D7</option><option value="8">D8</option>
<option value="9">D9</option><option value="10">D10</option>
</select>
</div>
<div class="flip-row" style="align-items:center;border-bottom:none">
<div class="flip-label">Middle Click</div>
<div class="param-desc" style="flex:1;font-size:9px;color:var(--label)">Pin wired to GND when pressed</div>
<select class="pin-select" id="btnMiddlePin" onchange="updatePinDiagram();writeConfigBlob()" disabled>
<option value="255">None</option>
<option value="0">D0</option><option value="1">D1</option><option value="2">D2</option>
<option value="3">D3</option><option value="4">D4</option><option value="5">D5</option>
<option value="6">D6</option><option value="7">D7</option><option value="8">D8</option>
<option value="9">D9</option><option value="10">D10</option>
</select>
</div>
<div style="padding:8px 0 2px;font-size:9px;color:var(--label);font-family:var(--mono)">
Pull-up built-in · wire button between chosen pin and GND
</div>
</div>
<div class="section-label">Device Commands</div>
<div class="cmd-grid">
<button class="cmd-btn calibrate" id="btnCal" onclick="sendCalibrate()" disabled>
@@ -309,6 +192,29 @@
</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>
@@ -366,6 +272,7 @@
</div>
</main>
<div class="overlay" id="overlay">
<div class="modal">
<h3>⚠ Factory Reset</h3>
+20 -10
View File
@@ -153,13 +153,6 @@
.col-mid { display:grid; gap:12px; }
.col-right { display:grid; gap:12px; position:sticky; top:80px; }
/* XIAO pin diagram */
.xiao-wrap { display:flex; flex-direction:column; align-items:center; padding:8px 0 14px; }
.pin-legend { display:flex; gap:20px; justify-content:center; font-family:var(--mono); font-size:9px; margin-top:10px; letter-spacing:0.08em; }
.pleg.left { color:var(--ok); }
.pleg.right { color:var(--accent2); }
.pleg.mid { color:var(--accent); }
.xiao-divider { border:none; border-top:1px solid var(--border); margin:0 -20px 12px; }
/* Responsive */
@media (max-width:1100px) {
@@ -199,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; }
@@ -316,6 +308,7 @@
.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; }
@@ -326,11 +319,28 @@
.mod-btn input:disabled + span { opacity:0.35; cursor:not-allowed; }
.restart-note { color:var(--warn); font-family:var(--mono); font-size:9px; }
.pin-select { background:var(--bg); color:var(--text); border:1px solid var(--border); font-family:var(--mono); font-size:11px; padding:3px 6px; cursor:pointer; min-width:80px; }
.pin-select:disabled { color:var(--dim); border-color:var(--dim); cursor:not-allowed; }
.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); }