Improved sensor read interference, added sensor disable. Added button test.

This commit is contained in:
ThePendulum
2026-11-22 02:27:56 +01:00
parent 6f252ff5e5
commit 170020b134
+143 -33
View File
@@ -48,7 +48,11 @@ constexpr int PIN_BUTTON_RIGHT = PA10;
constexpr int PIN_IMU_SCL = PB6;
constexpr int PIN_IMU_SDA = PB7;
constexpr unsigned long IMU_RETRY_INTERVAL = 250; // ms, after a supply dip the IMU is usually back quickly
// the IMU only drives crash detection and the tilt easter egg, false skips it entirely and leaves the I2C bus alone
constexpr bool IMU_ENABLE = false;
// a hung I2C bus costs up to 100ms per transaction (the core's fixed timeout), so retries back off while it keeps failing
constexpr unsigned long IMU_RETRY_MIN = 250; // ms, after a supply dip the IMU is usually back quickly
constexpr unsigned long IMU_RETRY_MAX = 10000; // ms
constexpr unsigned long IMU_RESET_TIME = 110; // ms, the IMU needs ~100ms after a reset before it takes configuration
// MPU9250/9255, configured like CrashRecorder but only buffering the accelerometer
@@ -153,14 +157,78 @@ constexpr int BUCK_OFF = LOW;
constexpr int ANIMATION_FPS = 30;
constexpr int ANIMATION_INTERVAL = lround(1000 / ANIMATION_FPS);
constexpr unsigned long SLOW_IMU_LOG = 10; // ms, logs IMU tasks that hold up the lights and buttons this long
Button pedal(PIN_PEDAL);
Button pedalForward(PIN_PEDAL_FORWARD);
Button pedalReverse(PIN_PEDAL_REVERSE);
Button buttonMode(PIN_BUTTON_MODE);
Button buttonLeft(PIN_BUTTON_LEFT);
Button buttonRight(PIN_BUTTON_RIGHT);
/* takes the first closed sample as the press and only accepts the release once the contact stayed open for
BUTTON_RELEASE_TIME, so bounces and brief dropouts while held count as one press. unlike the Button library it doesn't
sample the level once 100ms after the first edge, which turned every dropout of the old, worn switches into a release
and a second press (ButtonTest, 2026-11-19)
the replacement panel switches bounce for at most ~5ms, and quick presses come ~90ms apart (ButtonTest, 2026-11-22) */
constexpr unsigned long BUTTON_RELEASE_TIME = 30; // ms
class ContactButton {
public:
static constexpr bool PRESSED = LOW;
static constexpr bool RELEASED = HIGH;
explicit ContactButton(uint8_t pin) : pin(pin) {}
void begin() {
pinMode(pin, INPUT_PULLUP);
}
bool read() {
const unsigned long now = millis();
if (digitalRead(pin) == PRESSED) {
lastClosed = now;
if (state == RELEASED) {
state = PRESSED;
pressedPending = true;
}
} else if (state == PRESSED && now - lastClosed >= BUTTON_RELEASE_TIME) {
state = RELEASED;
releasedPending = true;
}
return state;
}
// separate flags, so checking one can't swallow the other
bool pressed() {
read();
return take(pressedPending);
}
bool released() {
read();
return take(releasedPending);
}
private:
static bool take(bool& pending) {
const bool was = pending;
pending = false;
return was;
}
uint8_t pin;
bool state = RELEASED;
unsigned long lastClosed = 0;
bool pressedPending = false;
bool releasedPending = false;
};
ContactButton buttonMode(PIN_BUTTON_MODE);
ContactButton buttonLeft(PIN_BUTTON_LEFT);
ContactButton buttonRight(PIN_BUTTON_RIGHT);
Adafruit_NeoPixel ledsTail(LEDS_TAIL_LENGTH, LEDS_TAIL_PIN, NEO_GRBW + NEO_KHZ800);
Adafruit_NeoPixel ledsHeadLeft(LEDS_HEAD_LENGTH, LEDS_LEFT_PIN, NEO_GRBW + NEO_KHZ800);
@@ -221,6 +289,9 @@ bool indicatorRightActive = false;
ImuState imuState = IMU_MISSING;
unsigned long imuStateSince = 0;
bool imuMissingReported = false; // only the first failure of an outage is logged
bool imuHealthy = false; // passed a health check since it was last connected
unsigned long imuRetryInterval = IMU_RETRY_MIN;
uint8_t imuLastAddress = 0; // probed first on reconnect, saves a timeout on the unused address
uint8_t imuAddress = 0;
uint8_t imuWhoAmI = 0;
unsigned long lastFifoRead = 0;
@@ -315,7 +386,8 @@ void beginWire() {
// the IMU can reset halfway through a transfer, likely browning out when the motor stalls against a wall, and keep
// holding SDA low, which blocks the bus until power is cut. clocking SCL until it lets go and sending a STOP frees it,
// restarting Wire also clears the I2C peripheral if it got stuck busy
void recoverWire() {
// returns false when SDA or SCL is still held low, probing would then only wait for timeouts
bool recoverWire() {
constexpr int PULSE = 5; // us, ~100kHz
constexpr int MAX_CLOCKS = 16;
@@ -340,7 +412,11 @@ void recoverWire() {
digitalWrite(PIN_IMU_SDA, HIGH);
delayMicroseconds(PULSE);
const bool released = digitalRead(PIN_IMU_SDA) == HIGH && digitalRead(PIN_IMU_SCL) == HIGH;
beginWire();
return released;
}
void setImuState(ImuState state, unsigned long now) {
@@ -355,20 +431,34 @@ void imuFailed(const char* message, unsigned long now) {
imuMissingReported = true;
}
// a quick retry after a one-off dip, backing off while it keeps failing
imuRetryInterval = imuHealthy ? IMU_RETRY_MIN : min(imuRetryInterval * 2, IMU_RETRY_MAX);
imuHealthy = false;
setImuState(IMU_MISSING, now);
}
// first half of connecting, configureImu() finishes after IMU_RESET_TIME without blocking the loop
void connectImu(unsigned long now, bool recover = true) {
if (recover) {
recoverWire();
if (recover && !recoverWire()) {
imuFailed("IMU BUS HELD LOW, CRASH DETECTION DISABLED UNTIL IT IS BACK", now);
return;
}
imuAddress = 0;
for (const uint8_t address : IMU_ADDRESSES) {
// the last known address first, the other one only gets probed when that fails
uint8_t addresses[] = {IMU_ADDRESSES[0], IMU_ADDRESSES[1]};
if (imuLastAddress == addresses[1]) {
addresses[0] = IMU_ADDRESSES[1];
addresses[1] = IMU_ADDRESSES[0];
}
for (const uint8_t address : addresses) {
if (readRegisters(address, IMU_REG_WHO_AM_I, &imuWhoAmI, 1)) {
imuAddress = address;
imuLastAddress = address;
break;
}
}
@@ -439,6 +529,8 @@ void checkImuHealth(unsigned long now) {
}
imuSamples = 0;
imuHealthy = true;
imuRetryInterval = IMU_RETRY_MIN;
float streamDifference = -1; // g, largest axis difference, -1 when the direct read failed
// a byte lost without a read error shifts the stream onto another axis, which still looks sane but never shows a crash
@@ -648,8 +740,10 @@ void setup() {
Serial.begin(9600);
randomSeed(micros() ^ HAL_GetUIDw0() ^ HAL_GetUIDw1());
beginWire();
connectImu(millis(), false);
if (IMU_ENABLE) {
beginWire();
connectImu(millis(), false);
}
ledsTail.clear();
ledsHeadLeft.clear();
@@ -1326,9 +1420,9 @@ void handleIndicatorPress(Direction direction, unsigned long now) {
}
// both buttons are never pressed at exactly the same time, so the first one already started its indicator
Button& otherButton = direction == LEFT ? buttonRight : buttonLeft;
ContactButton& otherButton = direction == LEFT ? buttonRight : buttonLeft;
if (otherButton.read() == Button::PRESSED) {
if (otherButton.read() == ContactButton::PRESSED) {
indicatorCombo = true;
indicatorLeftActive = false;
indicatorRightActive = false;
@@ -1391,7 +1485,7 @@ void loop() {
handleIndicatorPress(RIGHT, now);
}
if (indicatorCombo && buttonLeft.read() != Button::PRESSED && buttonRight.read() != Button::PRESSED) {
if (indicatorCombo && buttonLeft.read() != ContactButton::PRESSED && buttonRight.read() != ContactButton::PRESSED) {
indicatorCombo = false;
}
@@ -1427,27 +1521,10 @@ void loop() {
travellingBackward = isReversing;
}
if (!isOff && imuState == IMU_RUNNING && now - lastFifoRead >= FIFO_INTERVAL) {
lastFifoRead = now;
readFifo(now);
}
if (!isOff && imuState == IMU_RUNNING && now - lastImuHealth >= IMU_HEALTH_INTERVAL) {
lastImuHealth = now;
checkImuHealth(now);
}
if (imuState == IMU_STARTING && now - imuStateSince >= IMU_RESET_TIME) {
configureImu(now);
}
// retry while missing, so a supply dip or reseating a wire doesn't need a reboot
if (imuState == IMU_MISSING && now - imuStateSince >= IMU_RETRY_INTERVAL) {
connectImu(now);
}
// lights first, the IMU gets the time left until the next frame
if (!isOff && now - lastFrame >= ANIMATION_INTERVAL) {
lastFrame += ANIMATION_INTERVAL;
// after a stall continue from now, catching up would render the missed frames back to back
lastFrame = now - lastFrame >= 2 * ANIMATION_INTERVAL ? now : lastFrame + ANIMATION_INTERVAL;
animationFrame += 1;
stableAnimationFrame += 1;
@@ -1455,6 +1532,39 @@ void loop() {
render();
}
// at most one IMU task per loop, so a slow one can't stack with another
const unsigned long imuStart = millis();
const char* imuTask = nullptr;
if (!IMU_ENABLE || isOff) {
// nothing to do
} else if (imuState == IMU_RUNNING && now - lastImuHealth >= IMU_HEALTH_INTERVAL) {
lastImuHealth = now;
imuTask = "HEALTH CHECK";
checkImuHealth(now);
} else if (imuState == IMU_RUNNING && now - lastFifoRead >= FIFO_INTERVAL) {
lastFifoRead = now;
imuTask = "FIFO READ";
readFifo(now);
} else if (imuState == IMU_STARTING && now - imuStateSince >= IMU_RESET_TIME) {
imuTask = "CONFIGURE";
configureImu(now);
} else if (imuState == IMU_MISSING && now - imuStateSince >= imuRetryInterval) {
// retry while missing, so a supply dip or reseating a wire doesn't need a reboot
imuTask = "RECONNECT";
connectImu(now);
}
const unsigned long imuTime = millis() - imuStart;
if (imuTask && imuTime >= SLOW_IMU_LOG) {
Serial.print("SLOW IMU ");
Serial.print(imuTask);
Serial.print(" ");
Serial.print(imuTime);
Serial.println(" MS");
}
if (shuttingDown && now - shutdownStart >= SHUTDOWN_DURATION) {
powerOff();
}