Files
air-mouse/source/buttons.cpp
2026-03-24 22:56:21 +01:00

65 lines
2.7 KiB
C++

#include "buttons.h"
#ifdef FEATURE_PHYSICAL_BUTTONS
#include <bluefruit.h>
extern BLEHidAdafruit blehid;
static uint8_t physBtnMask = 0;
static uint8_t rawMaskPrev = 0;
static unsigned long debounceMs = 0;
static const unsigned long DEBOUNCE_MS = 20;
// Setup
void setupPhysicalButtons() {
// Release any held physical buttons before reconfiguring
if (physBtnMask && Bluefruit.connected()) { blehid.mouseButtonRelease(); }
physBtnMask = 0;
if (BTN_LEFT_PIN != BTN_PIN_NONE) pinMode(BTN_LEFT_PIN, INPUT_PULLUP);
if (BTN_RIGHT_PIN != BTN_PIN_NONE) pinMode(BTN_RIGHT_PIN, INPUT_PULLUP);
if (BTN_MIDDLE_PIN != BTN_PIN_NONE) pinMode(BTN_MIDDLE_PIN, INPUT_PULLUP);
bool any = (BTN_LEFT_PIN != BTN_PIN_NONE) || (BTN_RIGHT_PIN != BTN_PIN_NONE)
|| (BTN_MIDDLE_PIN != BTN_PIN_NONE);
if (any) {
Serial.print("[BTN] L=");
BTN_LEFT_PIN == BTN_PIN_NONE ? Serial.print("--") : Serial.print(BTN_LEFT_PIN);
Serial.print(" R=");
BTN_RIGHT_PIN == BTN_PIN_NONE ? Serial.print("--") : Serial.print(BTN_RIGHT_PIN);
Serial.print(" M=");
BTN_MIDDLE_PIN == BTN_PIN_NONE ? Serial.print("--") : Serial.print(BTN_MIDDLE_PIN);
Serial.println();
}
}
// Poll and report
// Called every loop iteration (before rate limiter) for immediate response.
// Uses active-low logic: INPUT_PULLUP, button connects pin to GND.
void processPhysicalButtons() {
if (!Bluefruit.connected()) return;
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 = millis(); }
if (rawMask != physBtnMask && (millis() - debounceMs >= DEBOUNCE_MS)) {
uint8_t newMask = rawMask;
uint8_t pressed = newMask & ~physBtnMask; // bits that just went down
uint8_t released = physBtnMask & ~newMask; // bits that just went up
physBtnMask = newMask;
if (physBtnMask) blehid.mouseButtonPress(physBtnMask);
else blehid.mouseButtonRelease();
if (pressed & MOUSE_BUTTON_LEFT) Serial.println("[BTN] L press");
if (pressed & MOUSE_BUTTON_RIGHT) Serial.println("[BTN] R press");
if (pressed & MOUSE_BUTTON_MIDDLE) Serial.println("[BTN] M press");
if (released & MOUSE_BUTTON_LEFT) Serial.println("[BTN] L release");
if (released & MOUSE_BUTTON_RIGHT) Serial.println("[BTN] R release");
if (released & MOUSE_BUTTON_MIDDLE) Serial.println("[BTN] M release");
}
}
#endif // FEATURE_PHYSICAL_BUTTONS