diff --git a/src/core/main_task.c b/src/core/main_task.c index 3f5fa4c..4ab9902 100644 --- a/src/core/main_task.c +++ b/src/core/main_task.c @@ -29,6 +29,10 @@ volatile GlobalState_t globalState; +// Used to measure the actual respiratory frequency +static uint32_t lastCycleCount; +static TickType_t startBPMCheckTime; + static const char *globalStateDescr[] = { "welcome", "welcome_wait_cal", @@ -39,6 +43,8 @@ static const char *globalStateDescr[] = { }; static void setGlobalState(GlobalState_t newState, bool notifyMotor, bool populateDisplay); +static void resetBPMCheck(); +static void checkBPM(); void initMainTask() { @@ -109,6 +115,8 @@ void MainTask(void *pvParameters) upd_params(buttons_pressed); if (BUTTON_PRESSED(buttons_pressed, button_startstop)) { setGlobalState(run, true, false); + // Reset actual BPM measurement when moving from stop to run + resetBPMCheck(); } break; @@ -118,6 +126,8 @@ void MainTask(void *pvParameters) setGlobalState(stop, true, false); } + checkBPM(); + break; case critical_failure: break; @@ -174,6 +184,25 @@ static void setGlobalState( GlobalState_t newState, } } +static void resetBPMCheck() { + DEBUG_PRINT("Reset BPMCheck"); + lastCycleCount = cycleCount; + startBPMCheckTime = xTaskGetTickCount(); +} + +static void checkBPM() { + TickType_t elapsedTime = xTaskGetTickCount() - startBPMCheckTime; + if (elapsedTime > pdMS_TO_TICKS(BPM_CHECK_PERIOD_MS)) { + uint8_t measuredBPM = ((uint8_t) (cycleCount - lastCycleCount)) / BPM_CHECK_PERIOD_PER_MIN; + DEBUG_PRINT("Measured BPM: %u", measuredBPM); + if (ABS(((int8_t) measuredBPM) - ((int8_t) bpm)) > BPM_TOL) { + sendNewAlarm(abnFreq); + } + + resetBPMCheck(); + } +} + // TODO: move, nothing to do here void check_volume(uint32_t actual_vol) { // Convert target tidal volume to tens µl diff --git a/src/core/main_task.h b/src/core/main_task.h index be146d7..721ceb3 100644 --- a/src/core/main_task.h +++ b/src/core/main_task.h @@ -16,6 +16,10 @@ #define ALARM_AUTO_UNMUTE_DELAY 120 * 1000L +#define BPM_CHECK_PERIOD_MS 60 * 1000L +#define BPM_CHECK_PERIOD_PER_MIN 1 +#define BPM_TOL 2 + // MAIN wake-up notification #define MAIN_NOTIF_ALARM 0x01 diff --git a/src/core/motor_control.c b/src/core/motor_control.c index ee04307..a206bae 100644 --- a/src/core/motor_control.c +++ b/src/core/motor_control.c @@ -112,8 +112,7 @@ static TickType_t boundedWaitTime; static bool waitTimeoutAllowed; static int32_t cycle_volume; -static uint32_t cycleCount; - +volatile uint32_t cycleCount; #if DEBUG_MOTOR static const char *state_names[] = { diff --git a/src/core/motor_control.h b/src/core/motor_control.h index ed75250..40c5cc6 100644 --- a/src/core/motor_control.h +++ b/src/core/motor_control.h @@ -109,6 +109,8 @@ extern volatile BreathState_t breathState; */ extern volatile MotorErrorState_t motorErrorState; +extern volatile uint32_t cycleCount; + /** @init_motor Initialize the motor state machine */ void init_motor();