Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added ON-OFF button support #318

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions lib/bmi160/BMI160.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,12 @@ uint8_t BMI160::getDeviceID() {
return buffer[0];
}

void BMI160::deinit() {
// Issue a soft-reset to bring the device into a clean state
setRegister(BMI160_RA_CMD, BMI160_CMD_SOFT_RESET);
delay(12);
}

/** Verify the SPI connection.
* Make sure the device is connected and responds as expected.
* @return True if connection is valid, false otherwise
Expand Down
5 changes: 3 additions & 2 deletions lib/bmi160/BMI160.h
Original file line number Diff line number Diff line change
Expand Up @@ -564,6 +564,7 @@ class BMI160 {
BMI160AccelRange accelRange = BMI160_ACCEL_RANGE_4G,
BMI160DLPFMode accelFilterMode = BMI160_DLPF_MODE_OSR4
);
void deinit();
bool testConnection();

uint8_t getGyroRate();
Expand Down Expand Up @@ -749,7 +750,7 @@ class BMI160 {
uint8_t getInterruptLatch();
void setInterruptLatch(uint8_t latch);
void resetInterrupt();

bool getGyroDrdy();
void waitForGyroDrdy();
void waitForAccelDrdy();
Expand All @@ -764,4 +765,4 @@ class BMI160 {
uint8_t devAddr;
};

#endif /* _BMI160_H_ */
#endif /* _BMI160_H_ */
152 changes: 152 additions & 0 deletions src/button.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
#include "button.h"

#include <climits>

#if ESP32
#include <driver/rtc_io.h>
#include <esp_sleep.h>
#endif

#include "GlobalVars.h"

#ifdef ON_OFF_BUTTON_PIN

void IRAM_ATTR buttonInterruptHandler() {
if (OnOffButton::getInstance().buttonPressed) {
return;
}

OnOffButton::getInstance().signalPressStart();
}

void OnOffButton::setup() {
#if ESP8266
digitalWrite(D0, LOW);
pinMode(D0, OUTPUT);
pinMode(ON_OFF_BUTTON_PIN, INPUT);
#endif

#if ESP32
pinMode(
ON_OFF_BUTTON_PIN,
BUTTON_ACTIVE_LEVEL == 0 ? INPUT_PULLUP : INPUT_PULLDOWN
);

esp_deep_sleep_enable_gpio_wakeup(
1 << ON_OFF_BUTTON_PIN,
BUTTON_ACTIVE_LEVEL == 0 ? ESP_GPIO_WAKEUP_GPIO_LOW : ESP_GPIO_WAKEUP_GPIO_HIGH
);

#ifdef BUTTON_IMU_ENABLE_PIN
pinMode(BUTTON_IMU_ENABLE_PIN, OUTPUT);
gpio_hold_dis(static_cast<gpio_num_t>(BUTTON_IMU_ENABLE_PIN));
digitalWrite(BUTTON_IMU_ENABLE_PIN, BUTTON_IMU_ENABLE_ACTIVE_LEVEL);
#endif

gpio_deep_sleep_hold_en();
#endif

attachInterrupt(
ON_OFF_BUTTON_PIN,
buttonInterruptHandler,
BUTTON_ACTIVE_LEVEL == 0 ? FALLING : RISING
);
}

void OnOffButton::tick() {
#ifdef BUTTON_AUTO_SLEEP_TIME_SECONDS
uint64_t autoSleepElapsed = millis() - lastActivityMillis;

if (autoSleepElapsed >= BUTTON_AUTO_SLEEP_TIME_SECONDS * 1e3) {
goToSleep();
}
#endif

#if defined(BUTTON_BATTERY_VOLTAGE_THRESHOLD) && BATTERY_MONITOR == BAT_EXTERNAL
if (battery.getVoltage() >= BUTTON_BATTERY_VOLTAGE_THRESHOLD) {
batteryBad = false;
} else if (!batteryBad) {
batteryBad = true;
batteryBadSinceMillis = millis();
}

if (batteryBad) {
uint64_t batteryBadElapsed = millis() - batteryBadSinceMillis;

if (batteryBadElapsed >= batteryBadTimeoutSeconds * 1e3) {
goToSleep();
}
}
#endif

if (!buttonPressed) {
return;
}

uint64_t timeTaken = millis() - buttonPressStartMillis;

if (getButton() && timeTaken < longPressSeconds * 1e3) {
return;
}

if (timeTaken >= longPressSeconds * 1e3) {
goToSleep();
}

buttonPressed = false;
}

void OnOffButton::onBeforeSleep(std::function<void()> callback) {
callbacks.push_back(callback);
}

void OnOffButton::signalTrackerMoved() { lastActivityMillis = millis(); }

OnOffButton& OnOffButton::getInstance() { return instance; }

bool OnOffButton::getButton() {
static constexpr uint8_t circularBufferBitCount
= sizeof(buttonCircularBuffer) * CHAR_BIT;

bool isPressed = digitalRead(ON_OFF_BUTTON_PIN) == BUTTON_ACTIVE_LEVEL;
buttonCircularBuffer = buttonCircularBuffer << 1 | isPressed;

auto popCount = __builtin_popcount(buttonCircularBuffer);
return popCount >= circularBufferBitCount / 2;
}

void OnOffButton::signalPressStart() {
buttonPressed = true;
buttonPressStartMillis = millis();
buttonCircularBuffer = UINT64_MAX;
}

void OnOffButton::emitOnBeforeSleep() {
for (auto& callback : callbacks) {
callback();
}
}

void OnOffButton::goToSleep() {
emitOnBeforeSleep();

#if defined(BUTTON_IMU_ENABLE_PIN) && ESP32
digitalWrite(BUTTON_IMU_ENABLE_PIN, LOW);
gpio_hold_en(static_cast<gpio_num_t>(BUTTON_IMU_ENABLE_PIN));
#endif

ledManager.pattern(100, 100, 3);

while (buttonPressed && getButton())
;

#if ESP8266
ESP.deepSleep(0);
#elif ESP32
esp_deep_sleep_start();
#endif
}

OnOffButton OnOffButton::instance;

#endif
69 changes: 69 additions & 0 deletions src/button.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/*
SlimeVR Code is placed under the MIT license
Copyright (c) 2025 Gorbit99 & SlimeVR Contributors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#pragma once

#include <Arduino.h>

#include <cstdint>
#include <functional>
#include <vector>

#include "GlobalVars.h"

#ifdef ON_OFF_BUTTON_PIN

class OnOffButton {
public:
void setup();
void tick();
void onBeforeSleep(std::function<void()> callback);
void signalTrackerMoved();

static OnOffButton& getInstance();

private:
OnOffButton() = default;
static OnOffButton instance;

static constexpr float longPressSeconds = 1.0f;
static constexpr float batteryBadTimeoutSeconds = 10.0f;

bool getButton();
void signalPressStart();
void emitOnBeforeSleep();
void goToSleep();

bool buttonPressed = false;
uint64_t buttonPressStartMillis = 0;
uint64_t buttonCircularBuffer = 0;
std::vector<std::function<void()>> callbacks;
bool batteryBad = false;
uint64_t batteryBadSinceMillis = 0;

uint64_t lastActivityMillis = 0;

friend void IRAM_ATTR buttonInterruptHandler();
};

#endif
8 changes: 8 additions & 0 deletions src/debug.h
Original file line number Diff line number Diff line change
Expand Up @@ -100,4 +100,12 @@
#define FIRMWARE_VERSION "UNKNOWN"
#endif

#ifndef BUTTON_ACTIVE_LEVEL
#define BUTTON_ACTIVE_LEVEL 0
#endif

#ifndef BUTTON_IMU_ENABLE_ACTIVE_LEVEL
#define BUTTON_IMU_ENABLE_ACTIVE_LEVEL 1
#endif

#endif // SLIMEVR_DEBUG_H_
15 changes: 15 additions & 0 deletions src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
#include "GlobalVars.h"
#include "Wire.h"
#include "batterymonitor.h"
#include "button.h"
#include "credentials.h"
#include "globals.h"
#include "logging/Logger.h"
Expand Down Expand Up @@ -57,6 +58,11 @@ void setup() {
Serial.println();
Serial.println();

#ifdef ON_OFF_BUTTON_PIN
OnOffButton::getInstance().setup();
OnOffButton::getInstance().onBeforeSleep([]() { sensorManager.deinitAll(); });
#endif

logger.info("SlimeVR v" FIRMWARE_VERSION " starting up...");

statusManager.setStatus(SlimeVR::Status::LOADING, true);
Expand Down Expand Up @@ -118,6 +124,15 @@ void loop() {
sensorManager.update();
battery.Loop();
ledManager.update();

#ifdef ON_OFF_BUTTON_PIN
OnOffButton::getInstance().tick();

if (!sensorManager.allAtRest()) {
OnOffButton::getInstance().signalTrackerMoved();
}
#endif

#ifdef TARGET_LOOPTIME_MICROS
long elapsed = (micros() - loopTime);
if (elapsed < TARGET_LOOPTIME_MICROS) {
Expand Down
16 changes: 16 additions & 0 deletions src/sensors/SensorManager.h
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,22 @@ class SensorManager {
return ImuID::Unknown;
}

void deinitAll() {
for (auto& sensor : m_Sensors) {
sensor->deinit();
}
}

bool allAtRest() {
for (auto& sensor : m_Sensors) {
if (!sensor->isAtRest()) {
return false;
}
}

return true;
}

private:
SlimeVR::Logging::Logger m_Logger;

Expand Down
4 changes: 4 additions & 0 deletions src/sensors/bmi160sensor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1181,3 +1181,7 @@ void BMI160Sensor::getMagnetometerXYZFromBuffer(
*z = ((int16_t)data[5] << 8) | data[4];
#endif
}

void BMI160Sensor::deinit() { imu.deinit(); }

bool BMI160Sensor::isAtRest() { return sfusion.getRestDetected(); }
3 changes: 3 additions & 0 deletions src/sensors/bmi160sensor.h
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,9 @@ class BMI160Sensor : public Sensor {

bool getTemperature(float* out);

void deinit() final;
bool isAtRest() final;

private:
BMI160 imu{};
int axisRemap;
Expand Down
2 changes: 2 additions & 0 deletions src/sensors/bno055sensor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,5 @@ void BNO055Sensor::motionLoop() {
}

void BNO055Sensor::startCalibration(int calibrationType) {}

void BNO055Sensor::deinit() { imu.enterSuspendMode(); }
1 change: 1 addition & 0 deletions src/sensors/bno055sensor.h
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ class BNO055Sensor : public Sensor {
void motionSetup() override final;
void motionLoop() override final;
void startCalibration(int calibrationType) override final;
void deinit() final;

private:
Adafruit_BNO055 imu;
Expand Down
8 changes: 8 additions & 0 deletions src/sensors/bno080sensor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,10 @@ void BNO080Sensor::motionSetup() {
imu.enableRawMagnetometer(10);
#endif

#ifdef BUTTON_AUTO_SLEEP_TIME_SECONDS
imu.enableStabilityClassifier(500);
#endif

lastReset = 0;
lastData = millis();
working = true;
Expand Down Expand Up @@ -298,3 +302,7 @@ void BNO080Sensor::startCalibration(int calibrationType) {
// it's always enabled except accelerometer
// that is disabled 30 seconds after startup
}

void BNO080Sensor::deinit() { imu.softReset(); }

bool BNO080Sensor::isAtRest() { return imu.getStabilityClassifier() == 1; }
2 changes: 2 additions & 0 deletions src/sensors/bno080sensor.h
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ class BNO080Sensor : public Sensor {
void startCalibration(int calibrationType) override final;
SensorStatus getSensorState() override final;
void setFlag(uint16_t flagId, bool state) override final;
void deinit() final;
bool isAtRest() final;

protected:
// forwarding constructor
Expand Down
2 changes: 2 additions & 0 deletions src/sensors/icm20948sensor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -987,3 +987,5 @@ ICM_20948_Status_e ICM_20948::initializeDMP(void) {
return worstResult;
}
#endif // OVERRIDEDMPSETUP

void ICM20948Sensor::deinit() { imu.swReset(); }
Loading
Loading