Remove unnecessary comments, clean up code
This commit is contained in:
+3
-3
@@ -13,7 +13,7 @@ void initBatteryADC() {
|
||||
pinMode(PIN_VBAT_ENABLE, OUTPUT); digitalWrite(PIN_VBAT_ENABLE, LOW);
|
||||
pinMode(PIN_VBAT_READ, INPUT);
|
||||
analogReference(AR_INTERNAL_3_0); analogReadResolution(12);
|
||||
// Warm up with a few reads (no delay — just discard results)
|
||||
// Warm up with a few reads (no delay - just discard results)
|
||||
for (int i=0; i<8; i++) analogRead(PIN_VBAT_READ);
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ void updateBattery() {
|
||||
float v = readBatteryVoltage(); int pct = batteryPercent(v);
|
||||
bool chg = (digitalRead(PIN_CHG) == LOW);
|
||||
ChargeStatus status = chg ? (pct >= 99 ? CHGSTAT_FULL : CHGSTAT_CHARGING) : CHGSTAT_DISCHARGING;
|
||||
// Only write BLE Battery Service when connected — blebas.write() blocks on the
|
||||
// Only write BLE Battery Service when connected - blebas.write() blocks on the
|
||||
// SoftDevice ATT layer and causes 30-40ms loop stalls when called during advertising.
|
||||
if (Bluefruit.connected()) blebas.write(pct);
|
||||
lastChargeStatus = status;
|
||||
@@ -44,7 +44,7 @@ void updateBattery() {
|
||||
const char* st[] = {"discharging","charging","full"};
|
||||
Serial.print("[BATT] "); Serial.print(v,2); Serial.print("V ");
|
||||
Serial.print(pct); Serial.print("% "); Serial.println(st[status]);
|
||||
// Critical battery alert — only blink when not connected to avoid blocking BLE scheduler.
|
||||
// Critical battery alert - only blink when not connected to avoid blocking BLE scheduler.
|
||||
// 6 × 160ms = 960ms hard block; skip during active connection.
|
||||
if (status == CHGSTAT_DISCHARGING && v < BATT_CRITICAL && !Bluefruit.connected())
|
||||
for (int i=0; i<6; i++) { digitalWrite(LED_RED,LOW); delay(80); digitalWrite(LED_RED,HIGH); delay(80); }
|
||||
|
||||
+10
-10
@@ -8,7 +8,7 @@
|
||||
using namespace Adafruit_LittleFS_Namespace;
|
||||
extern File cfgFile;
|
||||
|
||||
// ─── BLE Config Service objects ───────────────────────────────────────────────
|
||||
// BLE Config Service objects
|
||||
#ifndef GIT_HASH
|
||||
#define GIT_HASH "unknown"
|
||||
#endif
|
||||
@@ -26,7 +26,7 @@ BLECharacteristic cfgGitHash (0x1239); // GitHash R 8 bytes (7-char ha
|
||||
#endif
|
||||
#endif
|
||||
|
||||
// ─── Charge mode ──────────────────────────────────────────────────────────────
|
||||
// Charge mode
|
||||
void applyChargeMode(ChargeMode mode) {
|
||||
switch (mode) {
|
||||
case CHARGE_OFF: pinMode(PIN_HICHG, INPUT_PULLUP); break;
|
||||
@@ -37,7 +37,7 @@ void applyChargeMode(ChargeMode mode) {
|
||||
Serial.print("[CHG] "); Serial.println(n[mode]);
|
||||
}
|
||||
|
||||
// ─── Config persistence ───────────────────────────────────────────────────────
|
||||
// Config persistence
|
||||
void loadConfig() {
|
||||
InternalFS.begin();
|
||||
cfgFile.open(CONFIG_FILENAME, FILE_O_READ);
|
||||
@@ -57,11 +57,11 @@ void saveConfig() {
|
||||
cfgFile.open(CONFIG_FILENAME, FILE_O_WRITE);
|
||||
if (cfgFile) { cfgFile.write((uint8_t*)&cfg, sizeof(cfg)); cfgFile.close(); }
|
||||
unsigned long elapsed = millis() - t0;
|
||||
if (elapsed > 5) { Serial.print("[CFG] Saved ("); Serial.print(elapsed); Serial.println("ms — flash block)"); }
|
||||
if (elapsed > 5) { Serial.print("[CFG] Saved ("); Serial.print(elapsed); Serial.println("ms - flash block)"); }
|
||||
else { Serial.println("[CFG] Saved"); }
|
||||
}
|
||||
|
||||
// ─── ConfigBlob push ─────────────────────────────────────────────────────────
|
||||
// ConfigBlob push
|
||||
#ifdef FEATURE_CONFIG_SERVICE
|
||||
void pushConfigBlob() {
|
||||
ConfigBlob b;
|
||||
@@ -103,7 +103,7 @@ void factoryReset() {
|
||||
Serial.println("[CFG] Factory reset complete");
|
||||
}
|
||||
|
||||
// ─── BLE callbacks ────────────────────────────────────────────────────────────
|
||||
// BLE callbacks
|
||||
#ifdef FEATURE_CONFIG_SERVICE
|
||||
void onConfigBlobWrite(uint16_t h, BLECharacteristic* c, uint8_t* d, uint16_t l) {
|
||||
if (l != sizeof(ConfigBlob)) { Serial.println("[CFG] Bad blob length"); return; }
|
||||
@@ -134,7 +134,7 @@ void onConfigBlobWrite(uint16_t h, BLECharacteristic* c, uint8_t* d, uint16_t l)
|
||||
setupPhysicalButtons(); // reconfigure pins immediately (no restart needed)
|
||||
#endif
|
||||
saveConfig();
|
||||
Serial.print("[CFG] Written — sens="); Serial.print(cfg.sensitivity,0);
|
||||
Serial.print("[CFG] Written - sens="); Serial.print(cfg.sensitivity,0);
|
||||
Serial.print(" dz="); Serial.print(cfg.deadZone,3);
|
||||
Serial.print(" tapThr="); Serial.print(cfg.tapThreshold);
|
||||
Serial.print(" tapAction="); Serial.println(cfg.tapAction);
|
||||
@@ -153,7 +153,7 @@ void onImuStreamCccd(uint16_t conn_hdl, BLECharacteristic* chr, uint16_t value)
|
||||
}
|
||||
#endif
|
||||
|
||||
// ─── BLE config service setup ─────────────────────────────────────────────────
|
||||
// BLE config service setup
|
||||
void setupConfigService() {
|
||||
cfgService.begin();
|
||||
|
||||
@@ -170,7 +170,7 @@ void setupConfigService() {
|
||||
cfgCommand.setWriteCallback(onCommandWrite);
|
||||
cfgCommand.begin();
|
||||
|
||||
// Git hash — 8-byte fixed field (7 hex chars + NUL), read-only
|
||||
// Git hash - 8-byte fixed field (7 hex chars + NUL), read-only
|
||||
cfgGitHash.setProperties(CHR_PROPS_READ);
|
||||
cfgGitHash.setPermission(SECMODE_OPEN, SECMODE_NO_ACCESS);
|
||||
cfgGitHash.setFixedLen(8);
|
||||
@@ -206,7 +206,7 @@ void setupConfigService() {
|
||||
}
|
||||
#endif // FEATURE_CONFIG_SERVICE
|
||||
|
||||
// ─── Telemetry push ───────────────────────────────────────────────────────────
|
||||
// Telemetry push
|
||||
#ifdef FEATURE_TELEMETRY
|
||||
void pushTelemetry(unsigned long now) {
|
||||
telem.uptimeSeconds = now / 1000;
|
||||
|
||||
+2
-2
@@ -7,7 +7,7 @@ extern BLEHidAdafruit blehid;
|
||||
|
||||
static uint8_t physBtnMask = 0; // bitmask of currently-pressed physical buttons
|
||||
|
||||
// ─── Setup ────────────────────────────────────────────────────────────────────
|
||||
// Setup
|
||||
void setupPhysicalButtons() {
|
||||
// Release any held physical buttons before reconfiguring
|
||||
if (physBtnMask && Bluefruit.connected()) { blehid.mouseButtonRelease(); }
|
||||
@@ -30,7 +30,7 @@ void setupPhysicalButtons() {
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Poll and report ──────────────────────────────────────────────────────────
|
||||
// Poll and report
|
||||
// Called every loop iteration (before rate limiter) for immediate response.
|
||||
// Uses active-low logic: INPUT_PULLUP, button connects pin to GND.
|
||||
void processPhysicalButtons() {
|
||||
|
||||
+18
-18
@@ -1,7 +1,7 @@
|
||||
#pragma once
|
||||
#include <Arduino.h>
|
||||
|
||||
// ─── Feature Flags ────────────────────────────────────────────────────────────
|
||||
// Feature Flags
|
||||
#define FEATURE_CONFIG_SERVICE
|
||||
#define FEATURE_TELEMETRY
|
||||
#define FEATURE_IMU_STREAM
|
||||
@@ -12,10 +12,10 @@
|
||||
#define FEATURE_BOOT_LOOP_DETECT
|
||||
#define FEATURE_PHYSICAL_BUTTONS
|
||||
|
||||
// ─── Debug ────────────────────────────────────────────────────────────────────
|
||||
// Debug
|
||||
// #define DEBUG
|
||||
|
||||
// ─── ATT table size ───────────────────────────────────────────────────────────
|
||||
// ATT table size
|
||||
#define _ATT_BASE 900
|
||||
#ifdef FEATURE_CONFIG_SERVICE
|
||||
#define _ATT_CFG 100 // +20 for cfgGitHash characteristic
|
||||
@@ -35,7 +35,7 @@
|
||||
#define ATT_TABLE_SIZE_CALC (_ATT_BASE + _ATT_CFG + _ATT_TELEM + _ATT_STREAM)
|
||||
#define ATT_TABLE_SIZE (ATT_TABLE_SIZE_CALC < 1536 ? 1536 : ATT_TABLE_SIZE_CALC)
|
||||
|
||||
// ─── IMU register addresses ───────────────────────────────────────────────────
|
||||
// IMU register addresses
|
||||
#define REG_CTRL1_XL 0x10
|
||||
#define REG_TAP_CFG 0x58
|
||||
#define REG_TAP_THS_6D 0x59
|
||||
@@ -46,20 +46,20 @@
|
||||
#define REG_OUT_TEMP_L 0x20
|
||||
#define REG_OUT_TEMP_H 0x21
|
||||
|
||||
// ─── Pins ─────────────────────────────────────────────────────────────────────
|
||||
// Pins
|
||||
#define PIN_VBAT_ENABLE (14)
|
||||
#define PIN_VBAT_READ (32)
|
||||
#define PIN_CHG (23)
|
||||
#define PIN_HICHG (22)
|
||||
|
||||
// ─── Persistence ──────────────────────────────────────────────────────────────
|
||||
// Persistence
|
||||
#define CONFIG_FILENAME "/imu_mouse_cfg.bin"
|
||||
#define CONFIG_MAGIC 0xDEAD123DUL
|
||||
|
||||
// ─── Physical button sentinel ─────────────────────────────────────────────────
|
||||
// Physical button sentinel
|
||||
#define BTN_PIN_NONE 0xFF // Stored in btn*Pin when that button is disabled
|
||||
|
||||
// ─── Runtime feature-override flags (cfg.featureFlags bitmask) ───────────────
|
||||
// Runtime feature-override flags (cfg.featureFlags bitmask)
|
||||
// These mirror the compile-time FEATURE_* defines but can be toggled at runtime
|
||||
// via the web UI and persisted in flash. Bits not listed here are reserved = 0.
|
||||
#define FLAG_TAP_ENABLED 0x01 // Tap detection active (requires restart)
|
||||
@@ -67,12 +67,12 @@
|
||||
#define FLAG_AUTO_RECAL_ENABLED 0x04 // Auto-recalibrate after long idle
|
||||
#define FLAG_ALL_DEFAULT (FLAG_TAP_ENABLED | FLAG_TEMP_COMP_ENABLED | FLAG_AUTO_RECAL_ENABLED)
|
||||
|
||||
// ─── Enums ────────────────────────────────────────────────────────────────────
|
||||
// Enums
|
||||
enum CurveType : uint8_t { CURVE_LINEAR=0, CURVE_SQUARE=1, CURVE_SQRT=2 };
|
||||
enum ChargeMode : uint8_t { CHARGE_OFF=0, CHARGE_SLOW=1, CHARGE_FAST=2 };
|
||||
enum ChargeStatus: uint8_t { CHGSTAT_DISCHARGING=0, CHGSTAT_CHARGING=1, CHGSTAT_FULL=2 };
|
||||
|
||||
// ─── Tap action types ─────────────────────────────────────────────────────────
|
||||
// Tap action types
|
||||
// TAP_ACTION_KEY: fires a raw HID keycode (tapKey) with optional modifier (tapMod).
|
||||
// Modifier byte: bit0=Ctrl, bit1=Shift, bit2=Alt, bit3=GUI (same as HID modifier byte).
|
||||
enum TapAction : uint8_t {
|
||||
@@ -82,7 +82,7 @@ enum TapAction : uint8_t {
|
||||
TAP_ACTION_KEY = 3,
|
||||
};
|
||||
|
||||
// ─── Config (stored in flash) ─────────────────────────────────────────────────
|
||||
// Config (stored in flash)
|
||||
struct Config {
|
||||
uint32_t magic;
|
||||
float sensitivity;
|
||||
@@ -97,7 +97,7 @@ struct Config {
|
||||
uint8_t tapMod; // HID modifier byte (used when tapAction == TAP_ACTION_KEY)
|
||||
float jerkThreshold; // jerk² threshold for tap-freeze detection
|
||||
uint8_t tapFreezeEnabled; // 1 = enable jerk-based cursor freeze during taps
|
||||
uint8_t featureFlags; // bitmask of FLAG_* — runtime feature overrides
|
||||
uint8_t featureFlags; // bitmask of FLAG_* - runtime feature overrides
|
||||
uint8_t btnLeftPin; // BTN_PIN_NONE or Arduino pin number (0-10 = D0-D10)
|
||||
uint8_t btnRightPin;
|
||||
uint8_t btnMiddlePin;
|
||||
@@ -105,7 +105,7 @@ struct Config {
|
||||
extern Config cfg;
|
||||
extern const Config CFG_DEFAULTS;
|
||||
|
||||
// ─── ConfigBlob (over BLE, 25 bytes) ─────────────────────────────────────────
|
||||
// ConfigBlob (over BLE, 25 bytes)
|
||||
struct __attribute__((packed)) ConfigBlob {
|
||||
float sensitivity; // [0]
|
||||
float deadZone; // [4]
|
||||
@@ -119,14 +119,14 @@ struct __attribute__((packed)) ConfigBlob {
|
||||
uint8_t tapMod; // [18] HID modifier
|
||||
uint8_t tapFreezeEnabled; // [19] 1 = enable jerk-based cursor freeze during taps
|
||||
float jerkThreshold; // [20] jerk² tap-freeze threshold
|
||||
uint8_t featureFlags; // [24] FLAG_* bitmask — runtime feature overrides
|
||||
uint8_t featureFlags; // [24] FLAG_* bitmask - runtime feature overrides
|
||||
uint8_t btnLeftPin; // [25] BTN_PIN_NONE or Arduino pin (0-10 = D0-D10)
|
||||
uint8_t btnRightPin; // [26]
|
||||
uint8_t btnMiddlePin; // [27]
|
||||
};
|
||||
static_assert(sizeof(ConfigBlob) == 28, "ConfigBlob must be 28 bytes");
|
||||
|
||||
// ─── TelemetryPacket (24 bytes) ───────────────────────────────────────────────
|
||||
// TelemetryPacket (24 bytes)
|
||||
#ifdef FEATURE_TELEMETRY
|
||||
struct __attribute__((packed)) TelemetryPacket {
|
||||
uint32_t uptimeSeconds; // [0]
|
||||
@@ -143,7 +143,7 @@ static_assert(sizeof(TelemetryPacket) == 28, "TelemetryPacket must be 28 bytes")
|
||||
extern TelemetryPacket telem;
|
||||
#endif
|
||||
|
||||
// ─── ImuPacket (14 bytes) ─────────────────────────────────────────────────────
|
||||
// ImuPacket (14 bytes)
|
||||
#ifdef FEATURE_IMU_STREAM
|
||||
struct __attribute__((packed)) ImuPacket {
|
||||
int16_t gyroX_mDPS; // [0] pitch axis (nod up/down → cursor Y)
|
||||
@@ -159,7 +159,7 @@ struct __attribute__((packed)) ImuPacket {
|
||||
static_assert(sizeof(ImuPacket) == 14, "ImuPacket must be 14 bytes");
|
||||
#endif
|
||||
|
||||
// ─── Tuning constants ─────────────────────────────────────────────────────────
|
||||
// Tuning constants
|
||||
extern const float ALPHA;
|
||||
extern const int LOOP_RATE_MS;
|
||||
extern const int BIAS_SAMPLES;
|
||||
@@ -185,7 +185,7 @@ extern const float BATT_CRITICAL;
|
||||
extern const unsigned long AUTO_RECAL_MS;
|
||||
#endif
|
||||
|
||||
// ─── Global state ─────────────────────────────────────────────────────────────
|
||||
// Global state
|
||||
extern float angleX, angleY;
|
||||
extern float accumX, accumY;
|
||||
extern float gravX, gravY, gravZ;
|
||||
|
||||
+4
-4
@@ -4,7 +4,7 @@
|
||||
|
||||
LSM6DS3 imu(I2C_MODE, 0x6A);
|
||||
|
||||
// ─── I2C helpers ──────────────────────────────────────────────────────────────
|
||||
// I2C helpers
|
||||
void imuWriteReg(uint8_t reg, uint8_t val) {
|
||||
// LSM6DS3 is on Wire1 (internal I2C, SDA=P0.17, SCL=P0.16), NOT Wire (external pins 4/5)
|
||||
Wire1.beginTransmission(0x6A); Wire1.write(reg); Wire1.write(val); Wire1.endTransmission();
|
||||
@@ -16,13 +16,13 @@ uint8_t imuReadReg(uint8_t reg) {
|
||||
return Wire1.available() ? Wire1.read() : 0;
|
||||
}
|
||||
|
||||
// ─── Temperature ──────────────────────────────────────────────────────────────
|
||||
// Temperature
|
||||
float readIMUTemp() {
|
||||
int16_t raw = (int16_t)((imuReadReg(REG_OUT_TEMP_H) << 8) | imuReadReg(REG_OUT_TEMP_L));
|
||||
return 25.0f + (float)raw / 256.0f;
|
||||
}
|
||||
|
||||
// ─── Calibration ──────────────────────────────────────────────────────────────
|
||||
// Calibration
|
||||
void calibrateGyroBias() {
|
||||
Serial.println("[CAL] Hold still...");
|
||||
double sx=0, sy=0, sz=0;
|
||||
@@ -51,7 +51,7 @@ void calibrateGyroBias() {
|
||||
Serial.print(","); Serial.println(biasGZ,4);
|
||||
}
|
||||
|
||||
// ─── Motion curve ─────────────────────────────────────────────────────────────
|
||||
// Motion curve
|
||||
float applyCurve(float v) {
|
||||
switch (cfg.curve) {
|
||||
case CURVE_SQUARE: return (v >= 0 ? 1.f : -1.f) * v * v;
|
||||
|
||||
+24
-65
@@ -1,27 +1,12 @@
|
||||
/*
|
||||
* IMU BLE Mouse — Seeed XIAO nRF52840 Sense (v3.4)
|
||||
* IMU BLE Mouse - Seeed XIAO nRF52840 Sense (v3.4)
|
||||
* ================================================================
|
||||
* Feature flags — comment out any line to disable that feature.
|
||||
* ATT table size is computed automatically from enabled features.
|
||||
* Start with minimal flags to isolate the SoftDevice RAM issue,
|
||||
* then re-enable one at a time.
|
||||
*
|
||||
* MINIMUM (just working mouse, no BLE config):
|
||||
* leave only FEATURE_BATTERY_MONITOR + FEATURE_BOOT_LOOP_DETECT
|
||||
*
|
||||
* RECOMMENDED first test:
|
||||
* enable FEATURE_CONFIG_SERVICE, keep TAP + STREAM + TELEMETRY off
|
||||
*
|
||||
* ── Feature flag index ───────────────────────────────────────────
|
||||
* FEATURE_CONFIG_SERVICE Custom GATT service (ConfigBlob + Command)
|
||||
* FEATURE_TELEMETRY +24-byte notify characteristic, 1 Hz
|
||||
* FEATURE_IMU_STREAM +14-byte notify characteristic, ~10 Hz
|
||||
* FEATURE_TAP_DETECTION LSM6DS3 hardware tap engine → L/R clicks
|
||||
* FEATURE_TEMP_COMPENSATION Gyro drift correction by temperature delta
|
||||
* FEATURE_AUTO_RECAL Recalibrate after AUTO_RECAL_MS idle
|
||||
* FEATURE_BATTERY_MONITOR ADC battery read + BLE Battery Service
|
||||
* FEATURE_BOOT_LOOP_DETECT .noinit crash counter → safe mode
|
||||
*
|
||||
* Dependencies:
|
||||
* FEATURE_TELEMETRY requires FEATURE_CONFIG_SERVICE
|
||||
* FEATURE_IMU_STREAM requires FEATURE_CONFIG_SERVICE
|
||||
@@ -40,24 +25,24 @@
|
||||
#include "Wire.h"
|
||||
#include "sleep.h"
|
||||
|
||||
// ─── Boot-loop detection ──────────────────────────────────────────────────────
|
||||
// Boot-loop detection
|
||||
#ifdef FEATURE_BOOT_LOOP_DETECT
|
||||
static uint32_t __attribute__((section(".noinit"))) bootCount;
|
||||
static uint32_t __attribute__((section(".noinit"))) bootMagic;
|
||||
#endif
|
||||
|
||||
// ─── BLE Standard Services ────────────────────────────────────────────────────
|
||||
// BLE Standard Services
|
||||
BLEDis bledis;
|
||||
BLEHidAdafruit blehid;
|
||||
#ifdef FEATURE_BATTERY_MONITOR
|
||||
BLEBas blebas;
|
||||
#endif
|
||||
|
||||
// ─── Persistence ──────────────────────────────────────────────────────────────
|
||||
// Persistence
|
||||
using namespace Adafruit_LittleFS_Namespace;
|
||||
File cfgFile(InternalFS);
|
||||
|
||||
// ─── Config definitions ───────────────────────────────────────────────────────
|
||||
// Config definitions
|
||||
Config cfg;
|
||||
const Config CFG_DEFAULTS = {
|
||||
CONFIG_MAGIC, 600.0f, 0.060f, 0.08f, CURVE_LINEAR, 0x00, CHARGE_SLOW,
|
||||
@@ -66,12 +51,12 @@ const Config CFG_DEFAULTS = {
|
||||
/*btnLeftPin=*/BTN_PIN_NONE, /*btnRightPin=*/BTN_PIN_NONE, /*btnMiddlePin=*/BTN_PIN_NONE
|
||||
};
|
||||
|
||||
// ─── Telemetry definition ─────────────────────────────────────────────────────
|
||||
// Telemetry definition
|
||||
#ifdef FEATURE_TELEMETRY
|
||||
TelemetryPacket telem = {};
|
||||
#endif
|
||||
|
||||
// ─── Tuning constants ─────────────────────────────────────────────────────────
|
||||
// Tuning constants
|
||||
const float ALPHA = 0.96f;
|
||||
const int LOOP_RATE_MS = 10;
|
||||
const int BIAS_SAMPLES = 200;
|
||||
@@ -97,7 +82,7 @@ const float BATT_CRITICAL = 3.10f;
|
||||
const unsigned long AUTO_RECAL_MS = 5UL * 60UL * 1000UL;
|
||||
#endif
|
||||
|
||||
// ─── Global state definitions ─────────────────────────────────────────────────
|
||||
// Global state definitions
|
||||
float angleX = 0, angleY = 0;
|
||||
float accumX = 0, accumY = 0;
|
||||
// Low-pass filtered gravity estimate in device frame (for roll-independent axis projection)
|
||||
@@ -132,10 +117,7 @@ uint32_t loopStalls = 0; // loop iterations where dt > 20ms (behind sch
|
||||
bool pendingCal = false;
|
||||
bool pendingReset = false;
|
||||
|
||||
// ── Jerk-based shock detection — freeze cursor during tap impacts ────────────
|
||||
// Jerk = da/dt (rate of change of acceleration). Normal mouse rotation produces
|
||||
// smooth accel changes (low jerk); a tap is a sharp impulse (very high jerk).
|
||||
// This cleanly separates taps from any intentional motion regardless of speed.
|
||||
// Jerk-based shock detection - freeze cursor during tap impacts, doesn't work well yet!
|
||||
unsigned long shockFreezeUntil = 0;
|
||||
float prevAx = 0, prevAy = 0, prevAz = 0; // previous frame's accel for Δa
|
||||
const unsigned long SHOCK_FREEZE_MS = 80; // hold freeze after last spike
|
||||
@@ -161,7 +143,7 @@ unsigned long bootStartMs = 0;
|
||||
bool safeMode = false;
|
||||
bool bootCountCleared = false;
|
||||
|
||||
// ─── Advertising ─────────────────────────────────────────────────────────────
|
||||
// Advertising
|
||||
static void startAdvertising() {
|
||||
Bluefruit.Advertising.addFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE);
|
||||
Bluefruit.Advertising.addTxPower();
|
||||
@@ -177,7 +159,7 @@ static void startAdvertising() {
|
||||
Bluefruit.Advertising.start(0);
|
||||
}
|
||||
|
||||
// ─── Setup ────────────────────────────────────────────────────────────────────
|
||||
// Setup
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
unsigned long serialWait = millis();
|
||||
@@ -188,14 +170,14 @@ void setup() {
|
||||
pinMode(LED_GREEN, OUTPUT); digitalWrite(LED_GREEN, HIGH);
|
||||
pinMode(LED_BLUE, OUTPUT); digitalWrite(LED_BLUE, HIGH);
|
||||
|
||||
// ── Boot-loop detection ───────────────────────────────────────────────────
|
||||
// Boot-loop detection
|
||||
#ifdef FEATURE_BOOT_LOOP_DETECT
|
||||
if (bootMagic != 0xCAFEBABE) { bootMagic = 0xCAFEBABE; bootCount = 0; }
|
||||
bootCount++;
|
||||
Serial.print("[BOOT] count="); Serial.println(bootCount);
|
||||
if (bootCount >= 3) {
|
||||
bootCount = 0; safeMode = true;
|
||||
Serial.println("[BOOT] Boot loop — safe mode (no config service)");
|
||||
Serial.println("[BOOT] Boot loop - safe mode (no config service)");
|
||||
InternalFS.begin(); InternalFS.remove(CONFIG_FILENAME);
|
||||
for (int i=0; i<3; i++) { digitalWrite(LED_RED,LOW); delay(150); digitalWrite(LED_RED,HIGH); delay(150); } // fault: red
|
||||
}
|
||||
@@ -214,7 +196,7 @@ void setup() {
|
||||
Bluefruit.begin(1, 0);
|
||||
Bluefruit.setTxPower(4);
|
||||
Bluefruit.setName(safeMode ? "IMU Mouse (safe)" : "IMU Mouse");
|
||||
Bluefruit.Periph.setConnInterval(16, 32); // 20-40ms — wider interval reduces SoftDevice TX stalls
|
||||
Bluefruit.Periph.setConnInterval(16, 32); // 20-40ms - wider interval reduces SoftDevice TX stalls
|
||||
|
||||
Wire1.begin(); // LSM6DS3 is on internal I2C bus (Wire1), must init before imu.begin()
|
||||
if (imu.begin() != 0) {
|
||||
@@ -242,8 +224,6 @@ void setup() {
|
||||
// Seed previous-accel for jerk detection so first frame doesn't spike
|
||||
prevAx = imu.readFloatAccelX(); prevAy = imu.readFloatAccelY(); prevAz = imu.readFloatAccelZ();
|
||||
|
||||
// Sleep manager init: must come after calibrateGyroBias() and imu.begin().
|
||||
// Unconditional — sleep.h is always included, no feature flag needed.
|
||||
sleepManagerInit();
|
||||
|
||||
bledis.setManufacturer("Seeed Studio");
|
||||
@@ -266,7 +246,7 @@ void setup() {
|
||||
#endif
|
||||
|
||||
startAdvertising();
|
||||
Serial.print("[OK] Advertising — features:");
|
||||
Serial.print("[OK] Advertising - features:");
|
||||
#ifdef FEATURE_CONFIG_SERVICE
|
||||
Serial.print(" CFG");
|
||||
#endif
|
||||
@@ -301,7 +281,7 @@ void setup() {
|
||||
lastTime = lastBattTime = lastHeartbeat = lastTelemetry = millis();
|
||||
}
|
||||
|
||||
// ─── Loop ─────────────────────────────────────────────────────────────────────
|
||||
// Loop
|
||||
void loop() {
|
||||
unsigned long now = millis();
|
||||
|
||||
@@ -309,7 +289,7 @@ void loop() {
|
||||
#ifdef FEATURE_BOOT_LOOP_DETECT
|
||||
if (!bootCountCleared && (now - bootStartMs >= BOOT_SAFE_MS)) {
|
||||
bootCount = 0; bootCountCleared = true;
|
||||
Serial.println("[BOOT] Stable — counter cleared");
|
||||
Serial.println("[BOOT] Stable - counter cleared");
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -341,11 +321,6 @@ void loop() {
|
||||
#ifdef FEATURE_PHYSICAL_BUTTONS
|
||||
processPhysicalButtons();
|
||||
#endif
|
||||
|
||||
// Sleep manager runs every iteration — must not be gated by LOOP_RATE_MS
|
||||
// because it needs to catch the imuWakeFlag set by the ISR promptly.
|
||||
// Pass idle=false when in IMU_LP (idleFrames is stale since gyro reads
|
||||
// are skipped); the manager tracks its own idle timestamp internally.
|
||||
{
|
||||
bool idle_for_sleep = (sleepStage == SLEEP_IMU_LP) ? true
|
||||
: (idleFrames >= IDLE_FRAMES);
|
||||
@@ -369,8 +344,6 @@ void loop() {
|
||||
#endif
|
||||
|
||||
// Gyro reads with optional temperature compensation.
|
||||
// (sleepManagerUpdate above already returns early when in IMU_LP/DEEP)
|
||||
|
||||
float correction = 0.0f;
|
||||
#ifdef FEATURE_TEMP_COMPENSATION
|
||||
if (cfg.featureFlags & FLAG_TEMP_COMP_ENABLED)
|
||||
@@ -384,17 +357,14 @@ void loop() {
|
||||
float ay = imu.readFloatAccelY();
|
||||
float az = imu.readFloatAccelZ();
|
||||
|
||||
// ── Jerk-based shock detection — freeze cursor during tap impacts ────────
|
||||
// Jerk = da/dt. Normal rotation = smooth accel changes (low jerk);
|
||||
// a tap is a sharp impulse (very high jerk).
|
||||
// Jerk-based shock detection - freeze cursor during tap impacts, doesn't work well yet
|
||||
float jx = (ax - prevAx) / dt, jy = (ay - prevAy) / dt, jz = (az - prevAz) / dt;
|
||||
float jerkSq = jx*jx + jy*jy + jz*jz;
|
||||
prevAx = ax; prevAy = ay; prevAz = az;
|
||||
bool shocked = cfg.tapFreezeEnabled && ((jerkSq > cfg.jerkThreshold) || (now < shockFreezeUntil));
|
||||
if (cfg.tapFreezeEnabled && jerkSq > cfg.jerkThreshold) shockFreezeUntil = now + SHOCK_FREEZE_MS;
|
||||
|
||||
// Complementary filter — gx=pitch axis, gz=yaw axis on this board layout
|
||||
// During shock: gyro-only integration to avoid accel spike corrupting angles
|
||||
// Complementary filter
|
||||
if (shocked) {
|
||||
angleX += gx * dt;
|
||||
angleY += gz * dt;
|
||||
@@ -403,12 +373,7 @@ void loop() {
|
||||
angleY = ALPHA*(angleY + gz*dt) + (1.0f - ALPHA)*atan2f(ay, sqrtf(ax*ax + az*az));
|
||||
}
|
||||
|
||||
// ── Gravity-based axis decomposition ──────────────────────────────────────
|
||||
// Low-pass filter accel to get a stable gravity estimate in device frame.
|
||||
// This lets us project angular velocity onto world-aligned axes regardless
|
||||
// of how the device is rolled. Device forward (pointing) axis = X.
|
||||
// Confirmed by diagnostics: GX=roll, GY=nod, GZ=pan in user's hold.
|
||||
// Skip update during shock to protect the gravity estimate from tap spikes.
|
||||
// Gravity-based axis decomposition
|
||||
const float GRAV_LP = 0.05f;
|
||||
if (!shocked) {
|
||||
gravX += GRAV_LP * (ax - gravX);
|
||||
@@ -420,8 +385,6 @@ void loop() {
|
||||
if (gN < 0.3f) gN = 1.0f;
|
||||
float gnx = gravX/gN, gny = gravY/gN, gnz = gravZ/gN;
|
||||
|
||||
// Screen-right = cross(forward, up) = cross([1,0,0], [gnx,gny,gnz])
|
||||
// = [0, -gnz, gny]
|
||||
float ry = -gnz, rz = gny;
|
||||
float rN = sqrtf(ry*ry + rz*rz);
|
||||
if (rN < 0.01f) { ry = -1.0f; rz = 0.0f; rN = 1.0f; }
|
||||
@@ -433,11 +396,9 @@ void loop() {
|
||||
float pitchRate = -(gy*ry + gz*rz);
|
||||
|
||||
// Projected rates amplify residual gyro bias (especially GY drift on pitch axis).
|
||||
// Use a wider dead zone for pitch to prevent constant cursor drift at rest.
|
||||
float fYaw = (fabsf(yawRate) > cfg.deadZone) ? yawRate : 0.0f;
|
||||
float fPitch = (fabsf(pitchRate) > cfg.deadZone * 3.0f) ? pitchRate : 0.0f;
|
||||
|
||||
// DIAG: print every 500ms to debug gravity projection — remove when confirmed
|
||||
#ifdef DEBUG
|
||||
{ static unsigned long lastDiag = 0;
|
||||
if (now - lastDiag >= 500) { lastDiag = now;
|
||||
@@ -456,18 +417,16 @@ void loop() {
|
||||
|
||||
#ifdef FEATURE_AUTO_RECAL
|
||||
if ((cfg.featureFlags & FLAG_AUTO_RECAL_ENABLED) && idle && idleStartMs != 0 && (now - idleStartMs >= AUTO_RECAL_MS)) {
|
||||
Serial.println("[AUTO-CAL] Long idle — recalibrating...");
|
||||
Serial.println("[AUTO-CAL] Long idle - recalibrating...");
|
||||
idleStartMs = 0; calibrateGyroBias(); prevAx = imu.readFloatAccelX(); prevAy = imu.readFloatAccelY(); prevAz = imu.readFloatAccelZ(); return;
|
||||
}
|
||||
#endif
|
||||
|
||||
// (sleep manager already called above, before LOOP_RATE_MS gate)
|
||||
|
||||
int8_t moveX = 0, moveY = 0;
|
||||
uint8_t flags = 0;
|
||||
|
||||
if (shocked) {
|
||||
// Shock freeze — discard accumulated sub-pixel motion and suppress output
|
||||
// Shock freeze - discard accumulated sub-pixel motion and suppress output
|
||||
accumX = accumY = 0.0f;
|
||||
flags |= 0x08; // bit3 = shock freeze active
|
||||
} else if (idle) {
|
||||
@@ -491,7 +450,7 @@ void loop() {
|
||||
lastImuStream = now;
|
||||
|
||||
if (now < streamBackoffUntil) {
|
||||
// Backing off — host TX buffer congested, skip to avoid 100ms block
|
||||
// Backing off - host TX buffer congested, skip to avoid 100ms block
|
||||
} else {
|
||||
ImuPacket pkt;
|
||||
pkt.gyroX_mDPS = (int16_t)constrain(gx*(180.f/PI)*1000.f, -32000, 32000);
|
||||
@@ -512,7 +471,7 @@ void loop() {
|
||||
if (streamConsecFails >= STREAM_BACKOFF_THRESH) {
|
||||
streamBackoffUntil = now + STREAM_BACKOFF_MS;
|
||||
streamConsecFails = 0;
|
||||
Serial.print("[STREAM] TX congested — backing off ");
|
||||
Serial.print("[STREAM] TX congested - backing off ");
|
||||
Serial.print(STREAM_BACKOFF_MS); Serial.println("ms");
|
||||
}
|
||||
}
|
||||
|
||||
+22
-34
@@ -1,8 +1,3 @@
|
||||
/*
|
||||
* sleep.cpp — IMU Mouse low-power manager (LSM6DS3TR-C + nRF52840)
|
||||
* See sleep.h for full documentation.
|
||||
*/
|
||||
|
||||
#include "sleep.h"
|
||||
#include "imu.h" // config.h REG_* macros
|
||||
#include <bluefruit.h> // sd_app_evt_wait()
|
||||
@@ -15,7 +10,6 @@
|
||||
#define SLP_WAKE_UP_DUR 0x5C
|
||||
#define SLP_WAKE_UP_SRC 0x1B
|
||||
|
||||
// LSM6DS3 I2C address — SA0 tied LOW on XIAO Sense → 0x6A (NOT 0x6B)
|
||||
#define LSM_ADDR 0x6A
|
||||
|
||||
#define XL_ODR_26HZ 0x20
|
||||
@@ -33,14 +27,14 @@ static unsigned long lpEnteredMs = 0; // when IMU LP was entered (for recal
|
||||
static bool wasIdle = false;
|
||||
static uint8_t savedCtrl1XL = XL_ODR_416HZ;
|
||||
static uint8_t savedCtrl2G = G_ODR_416HZ;
|
||||
static volatile bool pendingWakeSettle = false; // always set on wake — 120ms blackout
|
||||
static volatile bool pendingWakeSettle = false; // always set on wake - 120ms blackout
|
||||
static volatile bool pendingWakeRecal = false; // set only when recal is also needed
|
||||
|
||||
// Only force recalibration after waking from deep sleep, or after the gyro
|
||||
// has been off long enough for thermal drift to matter (~5 minutes).
|
||||
static constexpr unsigned long RECAL_AFTER_LP_MS = 5UL * 60UL * 1000UL;
|
||||
|
||||
// I2C helpers — Wire1 at 0x6A (SA0 LOW on XIAO nRF52840 Sense)
|
||||
// I2C helpers - Wire1 at 0x6A (SA0 LOW on XIAO nRF52840 Sense)
|
||||
static uint8_t lsmRead(uint8_t reg) {
|
||||
Wire1.beginTransmission(LSM_ADDR);
|
||||
Wire1.write(reg);
|
||||
@@ -65,40 +59,37 @@ static void imuInt1ISR() {
|
||||
static void armWakeupInterrupt() {
|
||||
lsmWrite(SLP_WAKE_UP_DUR, (uint8_t)((SLEEP_WAKEUP_DUR & 0x03) << 4));
|
||||
|
||||
// Preserve bit7 (tap single/double enable) written by tap.cpp
|
||||
// Preserve bit7 (tap single/double enable)
|
||||
uint8_t wuth = lsmRead(REG_WAKE_UP_THS);
|
||||
wuth = (wuth & 0xC0) | (SLEEP_WAKEUP_THS & 0x3F);
|
||||
lsmWrite(REG_WAKE_UP_THS, wuth);
|
||||
|
||||
// INTERRUPTS_ENABLE=1, SLOPE_FDS=0 (HP filter is gated in LP — must be 0)
|
||||
// INTERRUPTS_ENABLE=1, SLOPE_FDS=0 (HP filter is gated in LP - must be 0)
|
||||
uint8_t tcfg = lsmRead(REG_TAP_CFG);
|
||||
tcfg |= (1 << 7);
|
||||
tcfg &= ~(1 << 4);
|
||||
lsmWrite(REG_TAP_CFG, tcfg);
|
||||
|
||||
// OR in INT1_WU (bit5), preserve tap routing bits
|
||||
uint8_t md1 = lsmRead(REG_MD1_CFG);
|
||||
md1 |= (1 << 5);
|
||||
lsmWrite(REG_MD1_CFG, md1);
|
||||
|
||||
// Clear any stale latch BEFORE re-arming the edge interrupt.
|
||||
// If INT1 is already high from a previous event, RISING will never fire
|
||||
// because no low→high edge will occur. Reading WAKE_UP_SRC de-asserts INT1.
|
||||
(void)lsmRead(SLP_WAKE_UP_SRC);
|
||||
// Small delay to let the INT1 line settle low before we arm the edge detect
|
||||
delay(2);
|
||||
|
||||
// Re-attach with RISING — guaranteed clean edge now that latch is cleared
|
||||
// Re-attach with RISING - guaranteed clean edge now that latch is cleared
|
||||
detachInterrupt(digitalPinToInterrupt(IMU_INT1_PIN));
|
||||
attachInterrupt(digitalPinToInterrupt(IMU_INT1_PIN), imuInt1ISR, RISING);
|
||||
imuWakeFlag = false; // discard any flag set before the re-arm
|
||||
imuWakeFlag = false;
|
||||
|
||||
Serial.print("[SLEEP] armWakeup — TAP_CFG=0x"); Serial.print(lsmRead(REG_TAP_CFG), HEX);
|
||||
#ifdef DEBUG
|
||||
Serial.print("[SLEEP] armWakeup - TAP_CFG=0x"); Serial.print(lsmRead(REG_TAP_CFG), HEX);
|
||||
Serial.print(" MD1_CFG=0x"); Serial.print(lsmRead(REG_MD1_CFG), HEX);
|
||||
Serial.print(" WAKE_UP_THS=0x"); Serial.println(lsmRead(REG_WAKE_UP_THS), HEX);
|
||||
#endif
|
||||
}
|
||||
|
||||
// Disarm — restore registers for normal HP operation
|
||||
static void disarmWakeupInterrupt() {
|
||||
// Restore SLOPE_FDS=1 for tap detection HP filter path
|
||||
uint8_t tcfg = lsmRead(REG_TAP_CFG);
|
||||
@@ -127,10 +118,10 @@ static void enterImuLP() {
|
||||
|
||||
lpEnteredMs = millis();
|
||||
sleepStage = SLEEP_IMU_LP;
|
||||
Serial.print("[SLEEP] IMU LP entered — idle for ");
|
||||
Serial.print("[SLEEP] IMU LP entered - idle for ");
|
||||
Serial.print((millis() - idleEnteredMs) / 1000); Serial.println("s");
|
||||
|
||||
// Full register readback — confirms chip actually accepted all writes
|
||||
#ifdef DEBUG
|
||||
Serial.print("[SLEEP] CTRL1_XL=0x"); Serial.print(lsmRead(REG_CTRL1_XL), HEX);
|
||||
Serial.print(" CTRL2_G=0x"); Serial.print(lsmRead(SLP_CTRL2_G), HEX);
|
||||
Serial.print(" CTRL6_C=0x"); Serial.print(lsmRead(SLP_CTRL6_C), HEX);
|
||||
@@ -139,10 +130,7 @@ static void enterImuLP() {
|
||||
Serial.print(" MD1_CFG=0x"); Serial.print(lsmRead(REG_MD1_CFG), HEX);
|
||||
Serial.print(" WAKE_UP_THS=0x"); Serial.print(lsmRead(REG_WAKE_UP_THS), HEX);
|
||||
Serial.print(" WAKE_UP_DUR=0x"); Serial.println(lsmRead(SLP_WAKE_UP_DUR), HEX);
|
||||
// Expected when working:
|
||||
// CTRL1_XL=0x2_ (ODR=26Hz, _ = FS bits) CTRL2_G=0x0_ (ODR=off)
|
||||
// CTRL6_C bit4=1 (XL_HM_MODE) CTRL7_G bit7=1 (G_HM_MODE)
|
||||
// TAP_CFG=0x80 MD1_CFG=0x20 WAKE_UP_THS=0x01
|
||||
#endif
|
||||
}
|
||||
|
||||
// Enter deep sleep
|
||||
@@ -151,7 +139,7 @@ static void enterDeepSleep() {
|
||||
if (sleepStage < SLEEP_IMU_LP) enterImuLP();
|
||||
|
||||
sleepStage = SLEEP_DEEP;
|
||||
Serial.println("[SLEEP] Deep sleep — WFE on INT1");
|
||||
Serial.println("[SLEEP] Deep sleep - WFE on INT1");
|
||||
Serial.flush();
|
||||
|
||||
digitalWrite(LED_RED, LOW); delay(80); digitalWrite(LED_RED, HIGH);
|
||||
@@ -199,7 +187,7 @@ void sleepManagerWakeIMU() {
|
||||
accumX = accumY = 0.0f;
|
||||
// Reseed gravity from current accel so projection is correct immediately.
|
||||
// Can't call imu.readFloat* here (gyro not fully settled), but accel is
|
||||
// already running — read it directly via Wire1.
|
||||
// already running - read it directly via Wire1.
|
||||
// Simpler: just reset to neutral [0,0,1] and let the LP filter converge
|
||||
// over the first ~20 frames (200 ms) of real use.
|
||||
gravX = 0.0f; gravY = 0.0f; gravZ = 1.0f;
|
||||
@@ -209,9 +197,9 @@ void sleepManagerWakeIMU() {
|
||||
|
||||
sleepStage = SLEEP_AWAKE;
|
||||
if (needsRecal)
|
||||
Serial.println("[SLEEP] Awake — gyro settling, recal needed");
|
||||
Serial.println("[SLEEP] Awake - gyro settling, recal needed");
|
||||
else
|
||||
Serial.println("[SLEEP] Awake — short LP, reusing existing bias");
|
||||
Serial.println("[SLEEP] Awake - short LP, reusing existing bias");
|
||||
}
|
||||
|
||||
// Public: init
|
||||
@@ -223,11 +211,11 @@ void sleepManagerInit() {
|
||||
uint8_t whoami = imuReadReg(0x0F);
|
||||
Serial.print("[SLEEP] WHO_AM_I=0x"); Serial.print(whoami, HEX);
|
||||
if (whoami == 0x6A) Serial.println(" (OK)");
|
||||
else Serial.println(" (WRONG — I2C not working, sleep disabled)");
|
||||
else Serial.println(" (WRONG - I2C not working, sleep disabled)");
|
||||
|
||||
if (whoami != 0x6A) return; // don't arm anything if we can't talk to the IMU
|
||||
|
||||
Serial.print("[SLEEP] Init — INT1 pin="); Serial.print(IMU_INT1_PIN);
|
||||
Serial.print("[SLEEP] Init - INT1 pin="); Serial.print(IMU_INT1_PIN);
|
||||
Serial.print(", WU_THS="); Serial.print(SLEEP_WAKEUP_THS);
|
||||
Serial.print(" (~"); Serial.print(SLEEP_WAKEUP_THS * 7.8f, 0); Serial.print(" mg)");
|
||||
Serial.print(", IMU_LP after "); Serial.print(SLEEP_IMU_IDLE_MS / 1000); Serial.print("s");
|
||||
@@ -242,7 +230,7 @@ bool sleepManagerUpdate(unsigned long nowMs, bool idle, bool bleConnected) {
|
||||
// ISR wakeup
|
||||
if (imuWakeFlag) {
|
||||
imuWakeFlag = false;
|
||||
Serial.print("[SLEEP] INT1 fired — stage="); Serial.println((int)sleepStage);
|
||||
Serial.print("[SLEEP] INT1 fired - stage="); Serial.println((int)sleepStage);
|
||||
if (sleepStage == SLEEP_DEEP || sleepStage == SLEEP_IMU_LP) {
|
||||
sleepManagerWakeIMU();
|
||||
} else {
|
||||
@@ -269,12 +257,12 @@ bool sleepManagerUpdate(unsigned long nowMs, bool idle, bool bleConnected) {
|
||||
if (sleepStage == SLEEP_IMU_LP) {
|
||||
// Periodic log: confirms loop is running, shows live INT1 pin level and
|
||||
// WAKE_UP_SRC register. If INT1_pin never goes high after movement, the
|
||||
// wakeup engine is not generating an interrupt — check register values.
|
||||
// wakeup engine is not generating an interrupt - check register values.
|
||||
static unsigned long lastLpLog = 0;
|
||||
if (nowMs - lastLpLog >= 5000) {
|
||||
lastLpLog = nowMs;
|
||||
unsigned long lpSecs = idleEnteredMs ? (nowMs - idleEnteredMs) / 1000 : 0;
|
||||
Serial.print("[SLEEP] LP tick — idle="); Serial.print(lpSecs);
|
||||
Serial.print("[SLEEP] LP tick - idle="); Serial.print(lpSecs);
|
||||
Serial.print("s INT1="); Serial.print(digitalRead(IMU_INT1_PIN));
|
||||
Serial.print(" WAKE_UP_SRC=0x"); Serial.println(lsmRead(SLP_WAKE_UP_SRC), HEX);
|
||||
}
|
||||
@@ -290,7 +278,7 @@ bool sleepManagerUpdate(unsigned long nowMs, bool idle, bool bleConnected) {
|
||||
// AWAKE path
|
||||
if (!idle) {
|
||||
if (wasIdle) {
|
||||
Serial.println("[SLEEP] Motion — idle timer reset");
|
||||
Serial.println("[SLEEP] Motion - idle timer reset");
|
||||
}
|
||||
wasIdle = false;
|
||||
idleEnteredMs = 0;
|
||||
|
||||
+5
-75
@@ -1,43 +1,7 @@
|
||||
/*
|
||||
* sleep.h — IMU Mouse low-power manager
|
||||
* =====================================================================
|
||||
* Two-stage sleep strategy for the Seeed XIAO nRF52840 Sense:
|
||||
*
|
||||
* STAGE 1 — IMU low-power (entered after SLEEP_IMU_IDLE_MS of no motion)
|
||||
* • Gyroscope powered down (CTRL2_G ODR = 0000)
|
||||
* • Accelerometer → LP 26 Hz (CTRL1_XL ODR = 0010, XL_HM_MODE=1)
|
||||
* • LSM6DS3 wakeup-interrupt armed (MD1_CFG INT1_WU=1)
|
||||
* • nRF52840 stays awake, BLE advertising/connected continues
|
||||
* • Current: ~0.19 mA accel only vs ~0.90 mA combo HP
|
||||
*
|
||||
* STAGE 2 — System deep sleep (entered after SLEEP_DEEP_IDLE_MS of no motion)
|
||||
* • Only entered when BLE is NOT connected (i.e. no web-UI/host attached)
|
||||
* • Gyro still off, accel still in LP
|
||||
* • nRF52840 goes into sd_app_evt_wait() — SoftDevice manages radio
|
||||
* • Wake: IMU INT1 GPIO interrupt → ISR sets wakeFlag, loop resumes
|
||||
* • On wake: gyro re-enabled, full-rate accel restored, bias re-calibrated
|
||||
*
|
||||
* Integration
|
||||
* -----------
|
||||
* 1. #include "sleep.h" in main.cpp (already done below)
|
||||
* 2. Call sleepManagerInit() once in setup(), after imu.begin().
|
||||
* 3. Call sleepManagerUpdate(now, idle, Bluefruit.connected())
|
||||
* at the top of loop() (before the early-return on LOOP_RATE_MS).
|
||||
* 4. The manager returns immediately; it never blocks the loop.
|
||||
*
|
||||
* Pin assignment
|
||||
* --------------
|
||||
* LSM6DS3 INT1 → XIAO P0.11 (digital pin 3 on the 10-pin header)
|
||||
* Change IMU_INT1_PIN below if your wiring differs.
|
||||
* =====================================================================
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include <Arduino.h>
|
||||
|
||||
// ── Tuning ──────────────────────────────────────────────────────────────────
|
||||
// Time of no-motion before each sleep stage kicks in.
|
||||
// These are deliberately conservative — tighten to taste.
|
||||
// Tuning
|
||||
#ifndef SLEEP_IMU_IDLE_MS
|
||||
#define SLEEP_IMU_IDLE_MS (10UL * 1000UL) // 10 s → gyro off, accel LP
|
||||
#endif
|
||||
@@ -46,64 +10,30 @@
|
||||
#endif
|
||||
|
||||
// LSM6DS3 wakeup threshold: 1 LSB = 7.8 mg at ±2 g FS (±2g range).
|
||||
// The wakeup engine uses a slope filter (difference between consecutive samples
|
||||
// at 26 Hz, so each sample is ~38 ms apart).
|
||||
// Too low = wakes on keyboard/desk vibration. Too high = misses gentle pick-up.
|
||||
// 8 LSB × 7.8 mg ≈ 62 mg — filters desk vibration, fires on deliberate movement.
|
||||
// Raise to 12–16 if still waking from vibration; lower to 4 if too sluggish.
|
||||
#ifndef SLEEP_WAKEUP_THS
|
||||
#define SLEEP_WAKEUP_THS 16 // 0–63
|
||||
#endif
|
||||
|
||||
// Number of consecutive 26 Hz samples that must exceed the threshold.
|
||||
// 2 samples = ~77 ms of sustained movement required before wakeup fires.
|
||||
// This is the most effective filter against single-shot vibration spikes
|
||||
// (keyboard strikes, desk bumps) which are impulsive rather than sustained.
|
||||
#ifndef SLEEP_WAKEUP_DUR
|
||||
#define SLEEP_WAKEUP_DUR 2 // 0–3
|
||||
#endif
|
||||
|
||||
// GPIO pin connected to LSM6DS3 INT1.
|
||||
// On XIAO nRF52840 Sense, INT1 = P0.11 (internal trace, not on user header).
|
||||
// The Adafruit nRF52 BSP exposes this as PIN_LSM6DS3TR_C_INT1 — always use
|
||||
// that constant, never a bare number whose Arduino index is BSP-dependent.
|
||||
#ifndef IMU_INT1_PIN
|
||||
#define IMU_INT1_PIN PIN_LSM6DS3TR_C_INT1
|
||||
#endif
|
||||
|
||||
// ── Public state (read-only from main.cpp) ───────────────────────────────────
|
||||
// Public state (read-only from main.cpp)
|
||||
enum SleepStage : uint8_t {
|
||||
SLEEP_AWAKE = 0, // normal full-rate operation
|
||||
SLEEP_IMU_LP = 1, // gyro off, accel LP — nRF awake
|
||||
SLEEP_DEEP = 2, // system WFE — BLE disconnected only
|
||||
SLEEP_IMU_LP = 1, // gyro off, accel LP - nRF awake
|
||||
SLEEP_DEEP = 2, // system WFE - BLE disconnected only
|
||||
};
|
||||
|
||||
extern volatile SleepStage sleepStage;
|
||||
extern volatile bool imuWakeFlag; // set by INT1 ISR, cleared by manager
|
||||
extern volatile bool imuWakeFlag;
|
||||
|
||||
// ── API ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Call once in setup() after imu.begin().
|
||||
* Configures INT1 GPIO and arms the LSM6DS3 wakeup interrupt (always-on,
|
||||
* even in normal mode — it simply won't fire unless the device is still).
|
||||
*/
|
||||
void sleepManagerInit();
|
||||
|
||||
/**
|
||||
* Call every loop() iteration.
|
||||
* @param nowMs millis() timestamp
|
||||
* @param idle true when the motion pipeline reports no cursor movement
|
||||
* @param bleConnected Bluefruit.connected()
|
||||
*
|
||||
* Returns true if the caller should skip IMU reads this iteration
|
||||
* (i.e. we are in SLEEP_IMU_LP or just woke up and are re-initialising).
|
||||
*/
|
||||
bool sleepManagerUpdate(unsigned long nowMs, bool idle, bool bleConnected);
|
||||
|
||||
/**
|
||||
* Re-arms the LSM6DS3 after wake-from-deep-sleep.
|
||||
* Called internally by sleepManagerUpdate(); exposed so calibrateGyroBias()
|
||||
* can also call it if it needs to know sleep state.
|
||||
*/
|
||||
void sleepManagerWakeIMU();
|
||||
+7
-18
@@ -6,12 +6,12 @@
|
||||
|
||||
extern BLEHidAdafruit blehid;
|
||||
|
||||
// ─── Tap detection setup ──────────────────────────────────────────────────────
|
||||
// Tap detection setup
|
||||
// REG_TAP_THS_6D bits[4:0] = tapThreshold (1–31); 1 LSB = FS/32 = 62.5 mg at ±2g.
|
||||
// REG_INT_DUR2 at ODR=416 Hz:
|
||||
// SHOCK[7:6] = 2 → 38 ms max tap duration
|
||||
// QUIET[5:4] = 2 → 19 ms refractory after tap
|
||||
// DUR[3:0] = 6 → 115 ms max inter-tap window for double detection
|
||||
// SHOCK[7:6] = 2 → 38 ms max tap duration
|
||||
// QUIET[5:4] = 2 → 19 ms refractory after tap
|
||||
// DUR[3:0] = 6 → 115 ms max inter-tap window for double detection
|
||||
void applyTapThreshold() {
|
||||
uint8_t thr = cfg.tapThreshold;
|
||||
if (thr < 1) thr = 1;
|
||||
@@ -30,18 +30,7 @@ void setupTapDetection() {
|
||||
Serial.print(" (~"); Serial.print(cfg.tapThreshold * 62.5f, 0); Serial.println(" mg)");
|
||||
}
|
||||
|
||||
// ─── Tap processing ───────────────────────────────────────────────────────────
|
||||
// Only double-tap is mapped to an action. Single-tap is ignored (it always fires
|
||||
// before the double is confirmed and cannot be reliably disambiguated on this
|
||||
// hardware without an unacceptable latency penalty).
|
||||
//
|
||||
// The LSM6DS3 sets SINGLE_TAP immediately on first contact — we wait until
|
||||
// DOUBLE_TAP is set (within the hardware DUR window of 115 ms) before acting.
|
||||
// An additional TAP_CONFIRM_MS guard ensures the TAP_SRC register has settled.
|
||||
//
|
||||
// IMPORTANT: call mouseButtonPress(bitmask) — single arg only. The two-arg
|
||||
// overload takes (conn_hdl, buttons) and sends the wrong button value.
|
||||
|
||||
// Tap processing
|
||||
static enum { TAP_IDLE, TAP_PENDING, TAP_EXECUTING } tapState = TAP_IDLE;
|
||||
static unsigned long tapPendingMs = 0;
|
||||
static uint8_t pendingButton = 0; // 0 = key action pending
|
||||
@@ -83,7 +72,7 @@ static void fireTapAction(unsigned long now) {
|
||||
}
|
||||
|
||||
void processTaps(unsigned long now) {
|
||||
// ── Release ───────────────────────────────────────────────────────────────
|
||||
// Release
|
||||
if (tapState == TAP_EXECUTING) {
|
||||
if (now - clickDownMs >= CLICK_HOLD_MS) {
|
||||
if (pendingButton) {
|
||||
@@ -99,7 +88,7 @@ void processTaps(unsigned long now) {
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Poll TAP_SRC ──────────────────────────────────────────────────────────
|
||||
// Poll TAP_SRC
|
||||
uint8_t tapSrc = imuReadReg(REG_TAP_SRC);
|
||||
bool tapIA = !!(tapSrc & 0x40);
|
||||
bool doubleTap = !!(tapSrc & 0x10);
|
||||
|
||||
Reference in New Issue
Block a user