diff --git a/include/fpc_pid.h b/include/fpc_pid.h index 6de3d74..e561a7d 100644 --- a/include/fpc_pid.h +++ b/include/fpc_pid.h @@ -6,41 +6,33 @@ * @brief * Safety-oriented fixed-point PID controller API. * + * Gains, signals, bounds and the sample period are @c fxp_t values. The + * integral is accumulated in a wide @c fxp_acc_t, so contributions smaller + * than one LSB per step are kept, and every result outside its range + * saturates and is reported. + * + * @par Storage + * Controllers are caller-owned. Declare a @c struct fpc_pid with any + * storage duration and pass its address to fpc_pid_init(). Its members are + * private to the library. + * * @par Threading contract - * fpc inherits a **single-writer / many-readers** contract from its - * backing allocator. For a given controller instance: - * - One context may call the mutating functions: @c fpc_pid_init, - * @c fpc_pid_deinit, @c fpc_pid_reset, @c fpc_pid_set_config, - * @c fpc_pid_set_mode, @c fpc_pid_compute. - * - Any number of contexts may call the read-only @c fpc_pid_get_config - * and @c fpc_pid_get_state concurrently with the single writer. - * - Two mutating contexts that share an instance must be serialised - * by the caller. + * A controller is not internally synchronised. Calls on the same instance + * must be serialised by the caller; distinct instances are independent. */ #ifndef FPC_PID_H_ #define FPC_PID_H_ #include "fpc_status.h" +#include "fxp.h" #include -struct fpc_pid; - -/** - * Maximum value `fpc_pid_config.d_filter_alpha` may take, and the value - * that disables derivative smoothing. Numerically `65536` — i.e. the - * Q16.16 representation of `1.0`. The field itself is `uint32_t`, so the - * value fits with room to spare. - */ -#define FPC_PID_D_FILTER_ALPHA_MAX (65536U) - /** - * @struct fpc_pid - * @brief Opaque handle to a PID controller instance. - * - * This structure is managed by an internal allocator and should never be - * accessed directly. It stores all state required for PID computation. + * Maximum value of @c fpc_pid_config.d_filter_alpha, and the value that + * disables derivative smoothing (1.0). */ +#define FPC_PID_D_FILTER_ALPHA_MAX FXP_ONE /** * @enum fpc_pid_mode @@ -59,273 +51,181 @@ enum fpc_pid_mode { * @struct fpc_pid_config * @brief PID controller configuration. * - * The controller implements the discrete PID algorithm: + * The controller implements the continuous law * * \f[ - * u(t) = K_p \cdot e(t) + K_i \cdot \sum{e(t)} + K_d \cdot \frac{d e(t)}{d t} + * u(t) = K_p e(t) + K_i \int e(t)\,dt + K_d \frac{de(t)}{dt} * \f] * - * The implementation evaluates the proportional, integral, and derivative - * terms as integer ratios over the configured sample time \f$ \Delta t \f$: + * discretised with sample period \f$ \Delta t \f$: * * \f[ - * u[k] = \frac{K_p}{\Delta t} \cdot e[k] + \frac{K_i}{\Delta t} \cdot - * \sum_{i=0}^{k} e[i] - * + \frac{K_d}{\Delta t} \cdot (e[k] - e[k-1]) + * u[k] = K_p e[k] + \sum_{i=0}^{k} (K_i \Delta t)\, e[i] + D[k] * \f] * - * The derivative term uses exponential smoothing with coefficient \f$ \alpha - * \f$: + * The derivative term is smoothed with coefficient \f$ \alpha \f$: * * \f[ - * D[k] = D[k-1] + \frac{\alpha}{65536} \cdot \left(D_{raw}[k] - D[k-1]\right) + * D[k] = D[k-1] + \alpha \left(\frac{K_d}{\Delta t}(e[k] - e[k-1]) + * - D[k-1]\right) * \f] * - * where \f$ D_{raw}[k] = \frac{K_d}{\Delta t} \cdot (e[k] - e[k-1]) \f$ and - * \f$ \alpha \in [0, 65536] \f$ is a Q16.16 smoothing coefficient. - * - * @note `kp`, `ki`, `kd`, the integral term, the filtered derivative, and the - * output are stored as signed `int32_t` controller units. Only - * `d_filter_alpha` is expressed in Q16.16. - * @note `d_filter_alpha = 65536U` disables smoothing; smaller values apply - * stronger low-pass filtering. - * - * @post Configuration validation ensures: - * - dt > 0 (positive sample time) - * - out_min <= out_max (valid output range) - * - integral_min <= integral_max (valid integral bounds) - * - d_filter_alpha <= 65536 (valid smoothing coefficient) + * The discrete gains \f$ K_i \Delta t \f$ and \f$ K_d / \Delta t \f$ are + * derived once when a configuration is applied. @c dt is in the time unit of + * @c ki and @c kd; choose a unit in which @c dt is exactly representable, such + * as milliseconds for a 1 kHz loop (@c dt = 1.0, @c ki in 1/ms). + * + * @details + * - ::kp proportional gain. + * - ::ki integral gain, per unit of @c dt time. + * - ::kd derivative gain, in units of @c dt time. + * - ::dt sample period; must be positive. + * - ::out_min, ::out_max inclusive output bounds. + * - ::integral_min, ::integral_max inclusive bounds on the integral term, + * applied to the wide accumulator (anti-windup). + * - ::d_filter_alpha derivative smoothing coefficient in + * [0, @ref FPC_PID_D_FILTER_ALPHA_MAX]; the maximum disables smoothing. + * + * A configuration is rejected when @c dt is not positive, a lower bound + * exceeds its upper bound, @c d_filter_alpha is out of range, or a derived + * gain saturates or rounds to zero from a nonzero gain. */ struct fpc_pid_config { - int32_t kp; /**< Proportional gain numerator divided by dt at runtime */ - int32_t ki; /**< Integral gain numerator divided by dt at runtime */ - int32_t kd; /**< Derivative gain numerator divided by dt at runtime */ - int32_t dt; /**< Sample time in ticks (must be > 0) */ - int32_t out_min; /**< Minimum output clamp (inclusive) */ - int32_t out_max; /**< Maximum output clamp (inclusive) */ - int32_t integral_min; /**< Minimum integral term (inclusive) */ - int32_t integral_max; /**< Maximum integral term (inclusive) */ - uint32_t d_filter_alpha; /**< Derivative smoothing coefficient (Q16.16, - 0-65536) */ + fxp_t kp; + fxp_t ki; + fxp_t kd; + fxp_t dt; + fxp_t out_min; + fxp_t out_max; + fxp_t integral_min; + fxp_t integral_max; + fxp_t d_filter_alpha; }; /** - * @struct fpc_pid_state - * @brief Runtime PID state for diagnostics and tuning. - * - * This structure provides access to internal controller state for: - * - Online tuning adjustments - * - Controller performance monitoring - * - Mode transition handling - * - * @note The state values are raw controller units returned by the runtime - * implementation; they are not Q16.16-encoded values. + * @struct fpc_pid + * @brief Caller-owned PID controller instance. Members are private. */ -struct fpc_pid_state { - int32_t integral; /**< Current integral term */ - int32_t prev_error; /**< Previous error value e[k-1] */ - int32_t filtered_derivative; /**< Smoothed derivative term D[k] */ - int32_t last_output; /**< Last computed output u[k] */ - enum fpc_pid_mode mode; /**< Current operating mode */ +struct fpc_pid { + struct fpc_pid_config cfg; /**< @private Applied configuration. */ + fxp_t ki_dt; /**< @private ki * dt */ + fxp_t kd_dt; /**< @private kd / dt */ + fxp_acc_t integral; /**< @private Integral accumulator. */ + fxp_t prev_error; /**< @private e[k-1] */ + fxp_t filtered_derivative; /**< @private D[k] */ + fxp_t last_output; /**< @private u[k] */ + fxp_t manual_output; /**< @private Manual-mode output. */ + uint_least8_t mode; /**< @private enum fpc_pid_mode */ }; /** - * @brief Initialize the PID controller pool. - * - * @return enum fpc_status Status code indicating success or failure. - * - * @pre No pre-initialization required. - * @post The pool allocator is initialized and ready for fpc_pid_init() calls. - * @note Must be called before any PID controller instances can be created. - * @see fpc_pid_init() + * @struct fpc_pid_state + * @brief Runtime PID state for diagnostics and tuning. */ -enum fpc_status fpc_pid_pool_init(void); +struct fpc_pid_state { + fxp_t integral; /**< Integral term, rounded to fxp_t. */ + fxp_t prev_error; /**< Previous error e[k-1]. */ + fxp_t filtered_derivative; /**< Smoothed derivative term D[k]. */ + fxp_t last_output; /**< Last output u[k]. */ + enum fpc_pid_mode mode; /**< Current operating mode. */ +}; /** - * @brief Create and initialize a new PID controller instance. - * - * @param ctx Pointer to store the controller handle (output). - * @param cfg Configuration structure with controller gains and bounds. - * - * @return enum fpc_status Status code indicating success or failure. + * @brief Initialise a PID controller in auto mode with cleared state. * * @retval FPC_STATUS_OK on success. - * @retval FPC_STATUS_NULL_PTR if ctx is NULL. - * @retval FPC_STATUS_INVALID_PARAM if cfg contains invalid parameters. - * @retval FPC_STATUS_NOT_INITIALIZED if pool initialization failed. - * @retval FPC_STATUS_POOL_FULL if no free controller slots available. - * - * @pre fpc_pid_pool_init() must have been called successfully. - * @post *ctx is set to a valid controller handle on success. - * @post Controller is in AUTO mode with integral term initialized to zero. - * @note The controller inherits configuration immediately; changes to cfg - * after return do not affect the controller. + * @retval FPC_STATUS_NULL_PTR if @p pid is NULL. + * @retval FPC_STATUS_INVALID_PARAM if @p cfg is NULL or invalid (see + * @ref fpc_pid_config). @p pid is left uninitialised. */ -enum fpc_status fpc_pid_init(struct fpc_pid **ctx, +enum fpc_status fpc_pid_init(struct fpc_pid *pid, const struct fpc_pid_config *cfg); /** - * @brief Deinitialize a PID controller instance and return it to the pool. - * - * @param ctx Controller handle to deinitialize. + * @brief Clear the integral, derivative and error history. * - * @return enum fpc_status Status code indicating success or failure. + * The last output becomes the manual output in manual mode, and 0 otherwise. * * @retval FPC_STATUS_OK on success. - * @retval FPC_STATUS_NULL_PTR if ctx is NULL. - * @retval FPC_STATUS_NOT_INITIALIZED if ctx is not a valid initialized - * controller. - * - * @pre fpc_pid_init() must have been called with ctx. - * @post ctx is no longer valid and cannot be used after return. - * @note The controller state is released back to the pool. + * @retval FPC_STATUS_NULL_PTR if @p pid is NULL. + * @retval FPC_STATUS_NOT_INITIALIZED if @p pid has not been initialised. */ -enum fpc_status fpc_pid_deinit(struct fpc_pid *ctx); +enum fpc_status fpc_pid_reset(struct fpc_pid *pid); /** - * @brief Reset a PID controller to its initial state. - * - * @param ctx Controller handle to reset. + * @brief Apply a new configuration, keeping runtime state. * - * @return enum fpc_status Status code indicating success or failure. + * The integral, last output and manual output are clamped to the new bounds. * * @retval FPC_STATUS_OK on success. - * @retval FPC_STATUS_NULL_PTR if ctx is NULL. - * @retval FPC_STATUS_NOT_INITIALIZED if ctx is not a valid initialized - * controller. - * - * @pre fpc_pid_init() must have been called with ctx. - * @post The integral term, previous error, and filtered derivative are zeroed. - * @post If in MANUAL mode, last_output retains the manual value. - * @post If in AUTO mode, last_output is set to zero. + * @retval FPC_STATUS_SATURATED if any state was clamped. + * @retval FPC_STATUS_NULL_PTR if @p pid is NULL. + * @retval FPC_STATUS_NOT_INITIALIZED if @p pid has not been initialised. + * @retval FPC_STATUS_INVALID_PARAM if @p cfg is NULL or invalid; the + * controller is unchanged. */ -enum fpc_status fpc_pid_reset(struct fpc_pid *ctx); - -/** - * @brief Update a PID controller's configuration parameters. - * - * @param ctx Controller handle to update. - * @param cfg New configuration structure. - * - * @return enum fpc_status Status code indicating success or failure. - * - * @retval FPC_STATUS_OK on success. - * @retval FPC_STATUS_NULL_PTR if ctx is NULL. - * @retval FPC_STATUS_INVALID_PARAM if cfg is NULL or contains invalid - * parameters. - * @retval FPC_STATUS_NOT_INITIALIZED if ctx is not a valid initialized - * controller. - * @retval FPC_STATUS_SATURATED if internal state was clamped. - * - * @pre fpc_pid_init() must have been called with ctx. - * @post All configuration parameters are updated atomically. - * @post Integral term is clamped to integral_min..integral_max if out of - * bounds. - * @post last_output is clamped to out_min..out_max if out of bounds. - * @note The controller does not reset on configuration change; state persists. - */ -enum fpc_status fpc_pid_set_config(struct fpc_pid *ctx, +enum fpc_status fpc_pid_set_config(struct fpc_pid *pid, const struct fpc_pid_config *cfg); /** - * @brief Copy a PID controller's current configuration. - * - * @param ctx Controller handle to read. - * @param cfg Buffer to store configuration (output). - * - * @return enum fpc_status Status code indicating success or failure. + * @brief Read the applied configuration. * * @retval FPC_STATUS_OK on success. - * @retval FPC_STATUS_NULL_PTR if ctx or cfg is NULL. - * @retval FPC_STATUS_NOT_INITIALIZED if ctx is not a valid initialized - * controller. - * - * @pre fpc_pid_init() must have been called with ctx. - * @post *cfg contains a snapshot of the current configuration. - * @note Reflects any configuration changes made via fpc_pid_set_config(). + * @retval FPC_STATUS_NULL_PTR if @p pid or @p cfg is NULL. + * @retval FPC_STATUS_NOT_INITIALIZED if @p pid has not been initialised. */ -enum fpc_status fpc_pid_get_config(const struct fpc_pid *ctx, +enum fpc_status fpc_pid_get_config(const struct fpc_pid *pid, struct fpc_pid_config *cfg); /** - * @brief Change PID controller operating mode. + * @brief Switch between auto and manual mode. * - * @param ctx Controller handle to update. - * @param mode Desired operating mode (AUTO or MANUAL). - * @param manual_output Output value to use in MANUAL mode. + * Entering manual mode holds @p manual_output, clamped to the output bounds. + * Returning to auto mode re-biases the integral so that the next output, for + * an unchanged error, equals the last output (bumpless transfer). * - * @return enum fpc_status Status code indicating success or failure. + * @param pid Controller instance. + * @param mode Requested mode. + * @param manual_output Output to hold in manual mode; ignored for auto mode. * * @retval FPC_STATUS_OK on success. - * @retval FPC_STATUS_NULL_PTR if ctx is NULL. - * @retval FPC_STATUS_INVALID_PARAM if mode is invalid. - * @retval FPC_STATUS_NOT_INITIALIZED if ctx is not a valid initialized - * controller. - * @retval FPC_STATUS_SATURATED if manual_output was clamped to - * out_min..out_max. - * - * @pre fpc_pid_init() must have been called with ctx. - * @post When switching from MANUAL to AUTO, the integral term is rebalanced - * to maintain output continuity (anti-windup). - * @post When switching to MANUAL, last_output is set to the clamped - * manual_output value. - * @post When switching to AUTO, the integral term is adjusted to account for - * the proportional and derivative contributions to the current output. + * @retval FPC_STATUS_SATURATED if the manual output or the re-biased integral + * was clamped. + * @retval FPC_STATUS_NULL_PTR if @p pid is NULL. + * @retval FPC_STATUS_NOT_INITIALIZED if @p pid has not been initialised. + * @retval FPC_STATUS_INVALID_PARAM if @p mode is not a valid mode. */ -enum fpc_status fpc_pid_set_mode(struct fpc_pid *ctx, enum fpc_pid_mode mode, - int32_t manual_output); +enum fpc_status fpc_pid_set_mode(struct fpc_pid *pid, enum fpc_pid_mode mode, + fxp_t manual_output); /** - * @brief Compute the PID output for a given setpoint and measurement. + * @brief Run one controller step. * - * @param ctx Controller handle to use for computation. - * @param setpoint Target value (setpoint). - * @param measurement Current process value (measurement). - * @param output Computed control output (output). + * In manual mode, records the error and returns the held output. * - * @return enum fpc_status Status code indicating success or failure. + * @param pid Controller instance. + * @param setpoint Desired value. + * @param measurement Measured value. + * @param[out] output Controller output u[k]. * - * @retval FPC_STATUS_OK on success with no clamping. - * @retval FPC_STATUS_NULL_PTR if ctx or output is NULL. - * @retval FPC_STATUS_NOT_INITIALIZED if ctx is not a valid initialized - * controller. - * @retval FPC_STATUS_OVERFLOW if an intermediate value cannot be represented as - * int32_t. - * @retval FPC_STATUS_SATURATED if output or integral term was clamped. - * - * @pre fpc_pid_init() must have been called with ctx. - * @post On `FPC_STATUS_OK` or `FPC_STATUS_SATURATED`, *output contains the - * computed PID value clamped to out_min..out_max. - * @post In AUTO mode with no overflow: computes full PID with proportional, - * integral, and derivative terms and updates the controller state. - * @post In MANUAL mode: returns last_output without computation, updates - * prev_error, and clears the filtered derivative state. - * @note Error is computed as: error = setpoint - measurement - * @note If overflow is detected, the controller holds the previous output and - * returns FPC_STATUS_OVERFLOW. + * @retval FPC_STATUS_OK on success. + * @retval FPC_STATUS_SATURATED if the error, the error change, the raw + * derivative, the integral or the output was clamped; @p output + * holds the clamped result. + * @retval FPC_STATUS_NULL_PTR if @p pid or @p output is NULL. + * @retval FPC_STATUS_NOT_INITIALIZED if @p pid has not been initialised. */ -enum fpc_status fpc_pid_compute(struct fpc_pid *ctx, int32_t setpoint, - int32_t measurement, int32_t *output); +enum fpc_status fpc_pid_compute(struct fpc_pid *pid, fxp_t setpoint, + fxp_t measurement, fxp_t *output); /** - * @brief Retrieve the current runtime state of a PID controller. - * - * @param ctx Controller handle to read. - * @param state Buffer to store controller state (output). - * - * @return enum fpc_status Status code indicating success or failure. + * @brief Read the runtime state. * * @retval FPC_STATUS_OK on success. - * @retval FPC_STATUS_NULL_PTR if ctx or state is NULL. - * @retval FPC_STATUS_NOT_INITIALIZED if ctx is not a valid initialized - * controller. - * - * @pre fpc_pid_init() must have been called with ctx. - * @post *state contains a snapshot of the current internal state. - * @note This function is useful for diagnostics, logging, and mode transition - * logic. + * @retval FPC_STATUS_NULL_PTR if @p pid or @p state is NULL. + * @retval FPC_STATUS_NOT_INITIALIZED if @p pid has not been initialised. */ -enum fpc_status fpc_pid_get_state(const struct fpc_pid *ctx, +enum fpc_status fpc_pid_get_state(const struct fpc_pid *pid, struct fpc_pid_state *state); #endif /* FPC_PID_H_ */ diff --git a/src/pid_controller.c b/src/pid_controller.c index f692c79..09f0049 100644 --- a/src/pid_controller.c +++ b/src/pid_controller.c @@ -6,606 +6,309 @@ * @brief * Fixed-point PID controller implementation. * - * Provides the concrete implementation of the PID API declared in @ref - * fpc_pid.h. Instances are allocated from a fixed-size pool configured via @ref - * fpc_config.h. The controller operates on Q16.16 fixed-point numbers and - * follows the discrete PID equations documented in the header, including - * optional derivative smoothing. + * Implements the PID API declared in @ref fpc_pid.h. The integral term is + * held in a wide accumulator scaled by 2^FXP_FRAC_BITS and is narrowed only + * when it is combined into an output. * - * @note Public API functions are documented in the header; internal helper - * functions are marked @internal. + * The unchecked wide sums cannot overflow in any fxp format. With W-bit + * words, fxp guarantees FXP_FRAC_BITS <= W - 2, so the integral accumulator + * and the widened derivative (an fxp_t times FXP_ONE) are each at most + * 2^(2W-3) in magnitude and any product of two fxp_t is at most 2^(2W-2). + * Every sum of two such terms and one product stays below 2^(2W-1). + * + * @note Public API functions are documented in the header; internal helpers are + * marked @internal. */ -#include "../include/fpc_config.h" #include "../include/fpc_pid.h" -#include "pool.h" -#include #include +#include -/** @internal */ -struct fpc_pid { - pool_id_t pool_id; - uint_least8_t initialized; - uint_least8_t mode; - uint16_t reserved; - int32_t manual_output; - int32_t kp; - int32_t ki; - int32_t kd; - int32_t dt; - int32_t out_min; - int32_t out_max; - int32_t integral_min; - int32_t integral_max; - uint32_t d_filter_alpha; - int32_t integral; - int32_t prev_error; - int32_t filtered_derivative; - int32_t last_output; -}; - -#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) -_Static_assert(sizeof(struct fpc_pid) <= POOL_ITEM_SIZE, - "POOL_ITEM_SIZE too small for struct fpc_pid"); -#endif - -static struct pool_t fpc_pid_pool_storage = {0}; -static pool_handle_t fpc_pid_pool_handle = NULL; +/* ================ INTERNAL HELPERS ===================================== */ -/** - * @brief Clamp a 64-bit value to the int32_t range. - * - * @param value Value to clamp. - * @param min Minimum allowed value (inclusive). - * @param max Maximum allowed value (inclusive). - * @param clamped Output flag set to true if clamping occurred. - * - * @return int32_t Clamped value. - * - * @pre clamped must be a valid pointer. - * @post *clamped is set to true if and only if value was outside [min, max]. - */ -static int32_t -fpc_clamp_int32(int64_t value, int32_t min, int32_t max, bool *clamped) +/** @internal Widen an fxp_t to the accumulator scale. */ +static fxp_acc_t +fpc_pid_widen(fxp_t value) { - int64_t bounded_value = value; - - if (bounded_value < (int64_t)min) { - bounded_value = (int64_t)min; - *clamped = true; - } else if (bounded_value > (int64_t)max) { - bounded_value = (int64_t)max; - *clamped = true; - } - - return (int32_t)bounded_value; + return (fxp_acc_t)value * (fxp_acc_t)FXP_ONE; } -/** - * @brief Validate PID configuration parameters. - * - * @param cfg Configuration to validate. - * - * @return bool true if configuration is valid, false otherwise. - * - * @pre cfg may be NULL. - * @post Returns false if cfg is NULL or if any parameter is invalid. - * @note Valid configuration requires: - * - cfg is non-NULL - * - dt > 0 (positive sample time) - * - out_min <= out_max (valid output bounds) - * - integral_min <= integral_max (valid integral bounds) - * - d_filter_alpha <= 65536 (valid smoothing coefficient) - */ -static bool -fpc_pid_config_is_valid(const struct fpc_pid_config *cfg) +/** @internal Clamp a wide value to the scaled bounds [lo, hi]. */ +static fxp_acc_t +fpc_pid_clamp_acc(fxp_acc_t value, fxp_t lo, fxp_t hi, bool *clamped) { - if (cfg == NULL) { - return false; - } + const fxp_acc_t wide_lo = fpc_pid_widen(lo); + const fxp_acc_t wide_hi = fpc_pid_widen(hi); - if (cfg->dt <= 0) { - return false; - } - - if (cfg->out_min > cfg->out_max) { - return false; - } - - if (cfg->integral_min > cfg->integral_max) { - return false; + if (value < wide_lo) { + *clamped = true; + return wide_lo; } - - if (cfg->d_filter_alpha > FPC_PID_D_FILTER_ALPHA_MAX) { - return false; + if (value > wide_hi) { + *clamped = true; + return wide_hi; } - - return true; + return value; } -/** - * @brief Validate and retrieve a writable PID controller pointer. - * - * @param ctx Controller handle to validate. - * @param valid_ctx Pointer to store the validated handle (output). - * - * @return enum fpc_status Status code indicating validation result. - * - * @retval FPC_STATUS_OK if ctx is valid and initialized. - * @retval FPC_STATUS_NULL_PTR if ctx or valid_ctx is NULL. - * @retval FPC_STATUS_NOT_INITIALIZED if pool or controller is not initialized. - * - * @pre Pool must be initialized via fpc_pid_pool_init(). - * @post *valid_ctx is set to ctx on success. - * @note This function ensures the controller handle corresponds to an actual - * allocated pool slot and has been initialized. - */ -static enum fpc_status -fpc_pid_get_valid_pointer(struct fpc_pid *ctx, struct fpc_pid **valid_ctx) +/** @internal Clamp an fxp_t to [lo, hi]. */ +static fxp_t +fpc_pid_clamp(fxp_t value, fxp_t lo, fxp_t hi, bool *clamped) { - const void *pool_ptr = NULL; + bool hit = false; + fxp_t result = fxp_clamp_wide((fxp_wide_t)value, lo, hi, &hit); - if ((ctx == NULL) || (valid_ctx == NULL)) { - return FPC_STATUS_NULL_PTR; - } - - if (fpc_pid_pool_handle == NULL) { - return FPC_STATUS_NOT_INITIALIZED; - } - - if (ctx->initialized == 0U) { - return FPC_STATUS_NOT_INITIALIZED; - } - - pool_ptr = pool_get_pointer(fpc_pid_pool_handle, ctx->pool_id); - if (pool_ptr != (const void *)ctx) { - return FPC_STATUS_NOT_INITIALIZED; + if (hit) { + *clamped = true; } + return result; +} - *valid_ctx = ctx; - return FPC_STATUS_OK; +/** @internal Check a derived gain: false if it saturated or vanished. */ +static bool +fpc_pid_gain_valid(enum fxp_status st, fxp_t gain, fxp_t derived) +{ + return (st == FXP_OK) && ((gain == 0) || (derived != 0)); } /** - * @brief Validate and retrieve a read-only PID controller pointer. - * - * @param ctx Controller handle to validate. - * @param valid_ctx Pointer to store the validated const handle (output). - * - * @return enum fpc_status Status code indicating validation result. - * - * @retval FPC_STATUS_OK if ctx is valid and initialized. - * @retval FPC_STATUS_NULL_PTR if ctx or valid_ctx is NULL. - * @retval FPC_STATUS_NOT_INITIALIZED if pool or controller is not initialized. + * @internal Validate @p cfg and derive its discrete gains. * - * @pre Pool must be initialized via fpc_pid_pool_init(). - * @post *valid_ctx is set to ctx on success. - * @note This function is identical to fpc_pid_get_valid_pointer() but for - * const pointers used in getter functions. + * @return true if @p cfg can be applied; the outputs are then set. */ -static enum fpc_status -fpc_pid_get_valid_const_pointer(const struct fpc_pid *ctx, - const struct fpc_pid **valid_ctx) +static bool +fpc_pid_derive(const struct fpc_pid_config *cfg, fxp_t *ki_dt, fxp_t *kd_dt) { - const void *pool_ptr = NULL; - - if ((ctx == NULL) || (valid_ctx == NULL)) { - return FPC_STATUS_NULL_PTR; - } - - if (fpc_pid_pool_handle == NULL) { - return FPC_STATUS_NOT_INITIALIZED; - } + enum fxp_status st; - if (ctx->initialized == 0U) { - return FPC_STATUS_NOT_INITIALIZED; + if ((cfg == NULL) || (cfg->dt <= 0) || (cfg->out_min > cfg->out_max) + || (cfg->integral_min > cfg->integral_max) + || (cfg->d_filter_alpha < 0) + || (cfg->d_filter_alpha > FPC_PID_D_FILTER_ALPHA_MAX)) { + return false; } - pool_ptr = pool_get_pointer(fpc_pid_pool_handle, ctx->pool_id); - if (pool_ptr != (const void *)ctx) { - return FPC_STATUS_NOT_INITIALIZED; + st = fxp_mul_chk(cfg->ki, cfg->dt, ki_dt); + if (!fpc_pid_gain_valid(st, cfg->ki, *ki_dt)) { + return false; } - *valid_ctx = ctx; - return FPC_STATUS_OK; + st = fxp_div_chk(cfg->kd, cfg->dt, kd_dt); + return fpc_pid_gain_valid(st, cfg->kd, *kd_dt); } -/** - * @brief Copy configuration from a struct to a PID controller instance. - * - * @param ctx Controller instance to update. - * @param cfg Configuration structure to copy. - * - * @pre ctx and cfg must be valid pointers. - * @post Controller's gain parameters and bounds are updated. - * @note This is an internal helper; configuration validation is done by caller. - */ -static void -fpc_pid_copy_config(struct fpc_pid *ctx, const struct fpc_pid_config *cfg) +/** @internal A controller is initialised once a positive dt is applied. */ +static bool +fpc_pid_ready(const struct fpc_pid *pid) { - ctx->kp = cfg->kp; - ctx->ki = cfg->ki; - ctx->kd = cfg->kd; - ctx->dt = cfg->dt; - ctx->out_min = cfg->out_min; - ctx->out_max = cfg->out_max; - ctx->integral_min = cfg->integral_min; - ctx->integral_max = cfg->integral_max; - ctx->d_filter_alpha = cfg->d_filter_alpha; + return pid->cfg.dt > 0; } -/** - * @brief Set manual output value with bounds checking. - * - * @param ctx Controller instance to update. - * @param manual_output Desired manual output value. - * - * @return enum fpc_status Status code indicating success or saturation. - * - * @retval FPC_STATUS_OK if value is within bounds. - * @retval FPC_STATUS_SATURATED if value was clamped to out_min..out_max. - * - * @pre ctx must be a valid initialized controller. - * @post manual_output is clamped to the valid output range. - * @post last_output is also updated to match manual_output. - * @note This function is called when entering MANUAL mode or updating - * manual output while in MANUAL mode. - */ +/** @internal Check the instance pointer and its initialisation. */ static enum fpc_status -fpc_pid_set_manual_output(struct fpc_pid *ctx, int32_t manual_output) +fpc_pid_check(const struct fpc_pid *pid) { - bool clamped = false; - - ctx->manual_output = fpc_clamp_int32( - (int64_t)manual_output, ctx->out_min, ctx->out_max, &clamped); - ctx->last_output = ctx->manual_output; - return clamped ? FPC_STATUS_SATURATED : FPC_STATUS_OK; -} - -/** - * @copydoc fpc_pid_pool_init() - */ -enum fpc_status -fpc_pid_pool_init(void) -{ - if (pool_init(&fpc_pid_pool_storage) != POOL_OK) { - return FPC_STATUS_NOT_INITIALIZED; + if (pid == NULL) { + return FPC_STATUS_NULL_PTR; } - - fpc_pid_pool_handle = &fpc_pid_pool_storage; - return FPC_STATUS_OK; + return fpc_pid_ready(pid) ? FPC_STATUS_OK : FPC_STATUS_NOT_INITIALIZED; } -/** - * @copydoc fpc_pid_init() - */ +/* ================ PUBLIC API =========================================== */ + enum fpc_status -fpc_pid_init(struct fpc_pid **ctx, const struct fpc_pid_config *cfg) +fpc_pid_init(struct fpc_pid *pid, const struct fpc_pid_config *cfg) { - pool_id_t pool_id; - void *pool_ptr = NULL; - struct fpc_pid *pid = NULL; - pool_status_t pool_status; + static const struct fpc_pid zero = {0}; + fxp_t ki_dt = 0; + fxp_t kd_dt = 0; - if (ctx == NULL) { + if (pid == NULL) { return FPC_STATUS_NULL_PTR; } - *ctx = NULL; - - if (!fpc_pid_config_is_valid(cfg)) { + *pid = zero; + if (!fpc_pid_derive(cfg, &ki_dt, &kd_dt)) { return FPC_STATUS_INVALID_PARAM; } - if (fpc_pid_pool_handle == NULL) { - return FPC_STATUS_NOT_INITIALIZED; - } - - pool_status = pool_acquire(fpc_pid_pool_handle, &pool_id); - if (pool_status == POOL_ERR_FULL) { - return FPC_STATUS_POOL_FULL; - } - - if (pool_status != POOL_OK) { - return FPC_STATUS_NOT_INITIALIZED; - } - - pool_status = - pool_get_pointer_checked(fpc_pid_pool_handle, pool_id, &pool_ptr); - if (pool_status != POOL_OK) { - (void)pool_release(fpc_pid_pool_handle, pool_id); - return FPC_STATUS_NOT_INITIALIZED; - } - - pid = (struct fpc_pid *)pool_ptr; - pid->pool_id = pool_id; - pid->initialized = 1U; + pid->cfg = *cfg; + pid->ki_dt = ki_dt; + pid->kd_dt = kd_dt; pid->mode = (uint_least8_t)FPC_PID_MODE_AUTO; - pid->manual_output = 0; - fpc_pid_copy_config(pid, cfg); - pid->integral = 0; - pid->prev_error = 0; - pid->filtered_derivative = 0; - pid->last_output = 0; - - *ctx = pid; - return FPC_STATUS_OK; -} - -/** - * @copydoc fpc_pid_deinit() - */ -enum fpc_status -fpc_pid_deinit(struct fpc_pid *ctx) -{ - struct fpc_pid *valid_ctx = NULL; - enum fpc_status status; - - status = fpc_pid_get_valid_pointer(ctx, &valid_ctx); - if (status != FPC_STATUS_OK) { - return status; - } - - if (pool_release(fpc_pid_pool_handle, valid_ctx->pool_id) != POOL_OK) { - return FPC_STATUS_NOT_INITIALIZED; - } - return FPC_STATUS_OK; } -/** - * @copydoc fpc_pid_reset() - */ enum fpc_status -fpc_pid_reset(struct fpc_pid *ctx) +fpc_pid_reset(struct fpc_pid *pid) { - struct fpc_pid *valid_ctx = NULL; - enum fpc_status status; + enum fpc_status status = fpc_pid_check(pid); - status = fpc_pid_get_valid_pointer(ctx, &valid_ctx); if (status != FPC_STATUS_OK) { return status; } - valid_ctx->integral = 0; - valid_ctx->prev_error = 0; - valid_ctx->filtered_derivative = 0; - valid_ctx->last_output = - ((enum fpc_pid_mode)valid_ctx->mode == FPC_PID_MODE_MANUAL) - ? valid_ctx->manual_output - : 0; + pid->integral = 0; + pid->prev_error = 0; + pid->filtered_derivative = 0; + pid->last_output = ((enum fpc_pid_mode)pid->mode == FPC_PID_MODE_MANUAL) + ? pid->manual_output + : 0; return FPC_STATUS_OK; } -/** - * @copydoc fpc_pid_set_config() - */ enum fpc_status -fpc_pid_set_config(struct fpc_pid *ctx, const struct fpc_pid_config *cfg) +fpc_pid_set_config(struct fpc_pid *pid, const struct fpc_pid_config *cfg) { - struct fpc_pid *valid_ctx = NULL; - enum fpc_status status; + enum fpc_status status = fpc_pid_check(pid); + fxp_t ki_dt = 0; + fxp_t kd_dt = 0; bool clamped = false; - if (!fpc_pid_config_is_valid(cfg)) { - return FPC_STATUS_INVALID_PARAM; - } - - status = fpc_pid_get_valid_pointer(ctx, &valid_ctx); if (status != FPC_STATUS_OK) { return status; } - - fpc_pid_copy_config(valid_ctx, cfg); - valid_ctx->integral = fpc_clamp_int32( - (int64_t)valid_ctx->integral, valid_ctx->integral_min, - valid_ctx->integral_max, &clamped); - valid_ctx->last_output = - fpc_clamp_int32((int64_t)valid_ctx->last_output, valid_ctx->out_min, - valid_ctx->out_max, &clamped); - - if ((enum fpc_pid_mode)valid_ctx->mode == FPC_PID_MODE_MANUAL) { - if (fpc_pid_set_manual_output(valid_ctx, - valid_ctx->manual_output) - == FPC_STATUS_SATURATED) { - clamped = true; - } + if (!fpc_pid_derive(cfg, &ki_dt, &kd_dt)) { + return FPC_STATUS_INVALID_PARAM; } + pid->cfg = *cfg; + pid->ki_dt = ki_dt; + pid->kd_dt = kd_dt; + pid->integral = fpc_pid_clamp_acc(pid->integral, cfg->integral_min, + cfg->integral_max, &clamped); + pid->last_output = fpc_pid_clamp(pid->last_output, cfg->out_min, + cfg->out_max, &clamped); + pid->manual_output = fpc_pid_clamp(pid->manual_output, cfg->out_min, + cfg->out_max, &clamped); return clamped ? FPC_STATUS_SATURATED : FPC_STATUS_OK; } -/** - * @copydoc fpc_pid_get_config() - */ enum fpc_status -fpc_pid_get_config(const struct fpc_pid *ctx, struct fpc_pid_config *cfg) +fpc_pid_get_config(const struct fpc_pid *pid, struct fpc_pid_config *cfg) { - const struct fpc_pid *valid_ctx = NULL; - enum fpc_status status; + enum fpc_status status = fpc_pid_check(pid); if (cfg == NULL) { return FPC_STATUS_NULL_PTR; } - - status = fpc_pid_get_valid_const_pointer(ctx, &valid_ctx); if (status != FPC_STATUS_OK) { return status; } - cfg->kp = valid_ctx->kp; - cfg->ki = valid_ctx->ki; - cfg->kd = valid_ctx->kd; - cfg->dt = valid_ctx->dt; - cfg->out_min = valid_ctx->out_min; - cfg->out_max = valid_ctx->out_max; - cfg->integral_min = valid_ctx->integral_min; - cfg->integral_max = valid_ctx->integral_max; - cfg->d_filter_alpha = valid_ctx->d_filter_alpha; + *cfg = pid->cfg; return FPC_STATUS_OK; } -/** - * @copydoc fpc_pid_set_mode() - */ enum fpc_status -fpc_pid_set_mode(struct fpc_pid *ctx, enum fpc_pid_mode mode, - int32_t manual_output) +fpc_pid_set_mode(struct fpc_pid *pid, enum fpc_pid_mode mode, + fxp_t manual_output) { - struct fpc_pid *valid_ctx = NULL; - enum fpc_status status; + enum fpc_status status = fpc_pid_check(pid); bool clamped = false; - if ((mode != FPC_PID_MODE_AUTO) && (mode != FPC_PID_MODE_MANUAL)) { - return FPC_STATUS_INVALID_PARAM; - } - - status = fpc_pid_get_valid_pointer(ctx, &valid_ctx); if (status != FPC_STATUS_OK) { return status; } - - if (mode == FPC_PID_MODE_MANUAL) { - valid_ctx->mode = (uint_least8_t)FPC_PID_MODE_MANUAL; - return fpc_pid_set_manual_output(valid_ctx, manual_output); + if ((mode != FPC_PID_MODE_AUTO) && (mode != FPC_PID_MODE_MANUAL)) { + return FPC_STATUS_INVALID_PARAM; } - if ((enum fpc_pid_mode)valid_ctx->mode == FPC_PID_MODE_MANUAL) { - const int64_t proportional64 = - ((int64_t)valid_ctx->kp * (int64_t)valid_ctx->prev_error) - / (int64_t)valid_ctx->dt; - const int64_t rebias64 = - (int64_t)valid_ctx->last_output - proportional64 - - (int64_t)valid_ctx->filtered_derivative; - valid_ctx->integral = - fpc_clamp_int32(rebias64, valid_ctx->integral_min, - valid_ctx->integral_max, &clamped); + if (mode == FPC_PID_MODE_MANUAL) { + pid->mode = (uint_least8_t)FPC_PID_MODE_MANUAL; + pid->manual_output = + fpc_pid_clamp(manual_output, pid->cfg.out_min, + pid->cfg.out_max, &clamped); + pid->last_output = pid->manual_output; + } else if ((enum fpc_pid_mode)pid->mode == FPC_PID_MODE_MANUAL) { + /* I = u - Kp e - D, so the next output repeats u. */ + const fxp_acc_t rebias = + fpc_pid_widen(pid->last_output) + - ((fxp_acc_t)pid->cfg.kp * (fxp_acc_t)pid->prev_error) + - fpc_pid_widen(pid->filtered_derivative); + pid->integral = + fpc_pid_clamp_acc(rebias, pid->cfg.integral_min, + pid->cfg.integral_max, &clamped); + pid->mode = (uint_least8_t)FPC_PID_MODE_AUTO; + } else { + /* Already in auto mode. */ } - valid_ctx->mode = (uint_least8_t)FPC_PID_MODE_AUTO; return clamped ? FPC_STATUS_SATURATED : FPC_STATUS_OK; } -/** - * @copydoc fpc_pid_compute() - */ enum fpc_status -fpc_pid_compute(struct fpc_pid *ctx, int32_t setpoint, int32_t measurement, - int32_t *output) +fpc_pid_compute(struct fpc_pid *pid, fxp_t setpoint, fxp_t measurement, + fxp_t *output) { - struct fpc_pid *valid_ctx = NULL; - enum fpc_status status; - int64_t error64; - int64_t integral_delta64; - int64_t derivative_delta64; - int64_t proportional64; - int64_t raw_output64; - int64_t filtered_derivative64; - int64_t derivative_step64; - int32_t error; - int32_t error_delta; - int32_t raw_derivative; - bool integral_clamped = false; - bool output_clamped = false; + enum fpc_status status = fpc_pid_check(pid); + bool clamped = false; + fxp_t error = 0; + fxp_t error_delta = 0; + fxp_t raw_derivative = 0; + fxp_t narrowed = 0; + fxp_acc_t acc; if (output == NULL) { return FPC_STATUS_NULL_PTR; } - - *output = 0; - - status = fpc_pid_get_valid_pointer(ctx, &valid_ctx); if (status != FPC_STATUS_OK) { return status; } - error64 = (int64_t)setpoint - (int64_t)measurement; - if ((error64 > (int64_t)INT32_MAX) || (error64 < (int64_t)INT32_MIN)) { - *output = valid_ctx->last_output; - return FPC_STATUS_OVERFLOW; + if (fxp_sub_chk(setpoint, measurement, &error) != FXP_OK) { + clamped = true; } - error = (int32_t)error64; - if ((enum fpc_pid_mode)valid_ctx->mode == FPC_PID_MODE_MANUAL) { - valid_ctx->prev_error = error; - valid_ctx->filtered_derivative = 0; - *output = valid_ctx->last_output; - return FPC_STATUS_OK; + if ((enum fpc_pid_mode)pid->mode == FPC_PID_MODE_MANUAL) { + pid->prev_error = error; + pid->filtered_derivative = 0; + *output = pid->last_output; + return clamped ? FPC_STATUS_SATURATED : FPC_STATUS_OK; } - error64 = (int64_t)error - (int64_t)valid_ctx->prev_error; - if ((error64 > (int64_t)INT32_MAX) || (error64 < (int64_t)INT32_MIN)) { - *output = valid_ctx->last_output; - return FPC_STATUS_OVERFLOW; + if (fxp_sub_chk(error, pid->prev_error, &error_delta) != FXP_OK) { + clamped = true; } - error_delta = (int32_t)error64; - - integral_delta64 = - ((int64_t)valid_ctx->ki * (int64_t)error) / (int64_t)valid_ctx->dt; - derivative_delta64 = ((int64_t)valid_ctx->kd * (int64_t)error_delta) - / (int64_t)valid_ctx->dt; - proportional64 = - ((int64_t)valid_ctx->kp * (int64_t)error) / (int64_t)valid_ctx->dt; - - if ((derivative_delta64 > (int64_t)INT32_MAX) - || (derivative_delta64 < (int64_t)INT32_MIN)) { - *output = valid_ctx->last_output; - return FPC_STATUS_OVERFLOW; + if (fxp_mul_chk(pid->kd_dt, error_delta, &raw_derivative) != FXP_OK) { + clamped = true; } + pid->filtered_derivative = fxp_lerp( + pid->filtered_derivative, raw_derivative, pid->cfg.d_filter_alpha); + + /* Anti-windup acts on the wide accumulator, before narrowing. */ + pid->integral = fpc_pid_clamp_acc( + fxp_acc_mac(pid->integral, pid->ki_dt, error), + pid->cfg.integral_min, pid->cfg.integral_max, &clamped); - raw_derivative = (int32_t)derivative_delta64; - derivative_step64 = ((int64_t)valid_ctx->d_filter_alpha - * ((int64_t)raw_derivative - - (int64_t)valid_ctx->filtered_derivative)) - / FPC_PID_D_FILTER_ALPHA_MAX; - filtered_derivative64 = - (int64_t)valid_ctx->filtered_derivative + derivative_step64; - - if ((filtered_derivative64 > (int64_t)INT32_MAX) - || (filtered_derivative64 < (int64_t)INT32_MIN)) { - *output = valid_ctx->last_output; - return FPC_STATUS_OVERFLOW; + acc = fxp_acc_mac(pid->integral, pid->cfg.kp, error); + acc = fxp_acc_mac(acc, pid->filtered_derivative, FXP_ONE); + if (fxp_acc_narrow_chk(acc, &narrowed) != FXP_OK) { + clamped = true; } - valid_ctx->integral = - fpc_clamp_int32((int64_t)valid_ctx->integral + integral_delta64, - valid_ctx->integral_min, valid_ctx->integral_max, - &integral_clamped); - valid_ctx->filtered_derivative = (int32_t)filtered_derivative64; - - raw_output64 = proportional64 + (int64_t)valid_ctx->integral - + (int64_t)valid_ctx->filtered_derivative; - valid_ctx->last_output = - fpc_clamp_int32(raw_output64, valid_ctx->out_min, - valid_ctx->out_max, &output_clamped); - valid_ctx->prev_error = error; - *output = valid_ctx->last_output; - - return (integral_clamped || output_clamped) ? FPC_STATUS_SATURATED - : FPC_STATUS_OK; + pid->last_output = fpc_pid_clamp(narrowed, pid->cfg.out_min, + pid->cfg.out_max, &clamped); + pid->prev_error = error; + *output = pid->last_output; + return clamped ? FPC_STATUS_SATURATED : FPC_STATUS_OK; } -/** - * @copydoc fpc_pid_get_state() - */ enum fpc_status -fpc_pid_get_state(const struct fpc_pid *ctx, struct fpc_pid_state *state) +fpc_pid_get_state(const struct fpc_pid *pid, struct fpc_pid_state *state) { - const struct fpc_pid *valid_ctx = NULL; - enum fpc_status status; + enum fpc_status status = fpc_pid_check(pid); if (state == NULL) { return FPC_STATUS_NULL_PTR; } - - status = fpc_pid_get_valid_const_pointer(ctx, &valid_ctx); if (status != FPC_STATUS_OK) { return status; } - state->integral = valid_ctx->integral; - state->prev_error = valid_ctx->prev_error; - state->filtered_derivative = valid_ctx->filtered_derivative; - state->last_output = valid_ctx->last_output; - state->mode = (enum fpc_pid_mode)valid_ctx->mode; + state->integral = fxp_acc_narrow_sat(pid->integral); + state->prev_error = pid->prev_error; + state->filtered_derivative = pid->filtered_derivative; + state->last_output = pid->last_output; + state->mode = (enum fpc_pid_mode)pid->mode; return FPC_STATUS_OK; } diff --git a/tests/test_pid.c b/tests/test_pid.c index 75feed6..8ac649c 100644 --- a/tests/test_pid.c +++ b/tests/test_pid.c @@ -1,47 +1,69 @@ -#include "../include/fpc_config.h" #include "../include/fpc_pid.h" #include "test_harness.h" #include #include -#include -#include + +/* Signals are raw fxp_t words. Expected values are exact under the default + * round-to-nearest-even policy. */ + +#define GAIN_0_2 ((fxp_t)13107) /* 0.199997 in Q16.16 */ static struct fpc_pid_config test_config(void) { - struct fpc_pid_config cfg = {.kp = 1000, - .ki = 500, - .kd = 200, - .dt = 1000, + struct fpc_pid_config cfg = {.kp = FXP_ONE, + .ki = FXP_ONE / 2, + .kd = GAIN_0_2, + .dt = FXP_ONE, .out_min = -100, .out_max = 100, .integral_min = -50, .integral_max = 50, - .d_filter_alpha - = FPC_PID_D_FILTER_ALPHA_MAX}; + .d_filter_alpha = + FPC_PID_D_FILTER_ALPHA_MAX}; return cfg; } -TEST_CASE(test_pool_init_required) +static struct fpc_pid_config +wide_config(void) { - struct fpc_pid *ctx = NULL; struct fpc_pid_config cfg = test_config(); - TEST_ASSERT(fpc_pid_init(&ctx, &cfg) == FPC_STATUS_NOT_INITIALIZED); - TEST_ASSERT(ctx == NULL); + cfg.out_min = -1000; + cfg.out_max = 1000; + cfg.integral_min = -1000; + cfg.integral_max = 1000; + return cfg; +} + +/* Only one term enabled; wide bounds so nothing clamps. */ +static struct fpc_pid_config +term_config(fxp_t kp, fxp_t ki, fxp_t kd, fxp_t dt) +{ + struct fpc_pid_config cfg = {.kp = kp, + .ki = ki, + .kd = kd, + .dt = dt, + .out_min = FXP_MIN, + .out_max = FXP_MAX, + .integral_min = FXP_MIN, + .integral_max = FXP_MAX, + .d_filter_alpha = + FPC_PID_D_FILTER_ALPHA_MAX}; + + return cfg; } TEST_CASE(test_init_and_get_config) { - struct fpc_pid *ctx = NULL; + struct fpc_pid pid; struct fpc_pid_config cfg = test_config(); struct fpc_pid_config copy; + struct fpc_pid_state state; - TEST_ASSERT(fpc_pid_pool_init() == FPC_STATUS_OK); - TEST_ASSERT(fpc_pid_init(&ctx, &cfg) == FPC_STATUS_OK); - TEST_ASSERT(ctx != NULL); - TEST_ASSERT(fpc_pid_get_config(ctx, ©) == FPC_STATUS_OK); + TEST_ASSERT(fpc_pid_init(&pid, &cfg) == FPC_STATUS_OK); + TEST_ASSERT(fpc_pid_get_config(&pid, ©) == FPC_STATUS_OK); TEST_ASSERT(copy.kp == cfg.kp); TEST_ASSERT(copy.ki == cfg.ki); TEST_ASSERT(copy.kd == cfg.kd); @@ -51,278 +73,418 @@ TEST_CASE(test_init_and_get_config) TEST_ASSERT(copy.integral_min == cfg.integral_min); TEST_ASSERT(copy.integral_max == cfg.integral_max); TEST_ASSERT(copy.d_filter_alpha == cfg.d_filter_alpha); - TEST_ASSERT(fpc_pid_deinit(ctx) == FPC_STATUS_OK); + TEST_ASSERT(fpc_pid_get_state(&pid, &state) == FPC_STATUS_OK); + TEST_ASSERT(state.integral == 0); + TEST_ASSERT(state.last_output == 0); + TEST_ASSERT(state.mode == FPC_PID_MODE_AUTO); } TEST_CASE(test_invalid_config_rejected) { - struct fpc_pid *ctx = NULL; + struct fpc_pid pid; struct fpc_pid_config cfg = test_config(); TEST_ASSERT(fpc_pid_init(NULL, &cfg) == FPC_STATUS_NULL_PTR); - TEST_ASSERT(fpc_pid_init(&ctx, NULL) == FPC_STATUS_INVALID_PARAM); + TEST_ASSERT(fpc_pid_init(&pid, NULL) == FPC_STATUS_INVALID_PARAM); cfg.dt = 0; - TEST_ASSERT(fpc_pid_init(&ctx, &cfg) == FPC_STATUS_INVALID_PARAM); + TEST_ASSERT(fpc_pid_init(&pid, &cfg) == FPC_STATUS_INVALID_PARAM); + cfg.dt = -FXP_ONE; + TEST_ASSERT(fpc_pid_init(&pid, &cfg) == FPC_STATUS_INVALID_PARAM); cfg = test_config(); cfg.out_min = 10; cfg.out_max = 0; - TEST_ASSERT(fpc_pid_init(&ctx, &cfg) == FPC_STATUS_INVALID_PARAM); + TEST_ASSERT(fpc_pid_init(&pid, &cfg) == FPC_STATUS_INVALID_PARAM); cfg = test_config(); cfg.integral_min = 10; cfg.integral_max = 0; - TEST_ASSERT(fpc_pid_init(&ctx, &cfg) == FPC_STATUS_INVALID_PARAM); + TEST_ASSERT(fpc_pid_init(&pid, &cfg) == FPC_STATUS_INVALID_PARAM); cfg = test_config(); - cfg.d_filter_alpha = FPC_PID_D_FILTER_ALPHA_MAX + 1U; - TEST_ASSERT(fpc_pid_init(&ctx, &cfg) == FPC_STATUS_INVALID_PARAM); + cfg.d_filter_alpha = FPC_PID_D_FILTER_ALPHA_MAX + 1; + TEST_ASSERT(fpc_pid_init(&pid, &cfg) == FPC_STATUS_INVALID_PARAM); + cfg.d_filter_alpha = -1; + TEST_ASSERT(fpc_pid_init(&pid, &cfg) == FPC_STATUS_INVALID_PARAM); + + /* ki * dt saturates. */ + cfg = term_config(0, FXP_MAX, 0, FXP_INT(2)); + TEST_ASSERT(fpc_pid_init(&pid, &cfg) == FPC_STATUS_INVALID_PARAM); + /* ki * dt rounds to zero. */ + cfg = term_config(0, FXP_RAW(1), 0, FXP_ONE / 4); + TEST_ASSERT(fpc_pid_init(&pid, &cfg) == FPC_STATUS_INVALID_PARAM); + /* kd / dt saturates. */ + cfg = term_config(0, 0, FXP_ONE, FXP_RAW(1)); + TEST_ASSERT(fpc_pid_init(&pid, &cfg) == FPC_STATUS_INVALID_PARAM); + /* kd / dt rounds to zero. */ + cfg = term_config(0, 0, FXP_RAW(1), FXP_INT(4)); + TEST_ASSERT(fpc_pid_init(&pid, &cfg) == FPC_STATUS_INVALID_PARAM); + TEST_ASSERT(fpc_pid_reset(&pid) == FPC_STATUS_NOT_INITIALIZED); + + /* Zero gains are valid at any dt. */ + cfg = term_config(0, 0, 0, FXP_RAW(1)); + TEST_ASSERT(fpc_pid_init(&pid, &cfg) == FPC_STATUS_OK); +} + +TEST_CASE(test_dt_scales_i_and_d_only) +{ + struct fpc_pid pid; + struct fpc_pid_config cfg; + fxp_t output = 0; + + /* P ignores dt. */ + cfg = term_config(FXP_INT(2), 0, 0, FXP_INT(10)); + TEST_ASSERT(fpc_pid_init(&pid, &cfg) == FPC_STATUS_OK); + TEST_ASSERT(fpc_pid_compute(&pid, FXP_INT(3), 0, &output) + == FPC_STATUS_OK); + TEST_ASSERT(output == FXP_INT(6)); + + /* I adds ki * dt * e per step. */ + cfg = term_config(0, FXP_ONE, 0, FXP_INT(2)); + TEST_ASSERT(fpc_pid_init(&pid, &cfg) == FPC_STATUS_OK); + TEST_ASSERT(fpc_pid_compute(&pid, FXP_INT(3), 0, &output) + == FPC_STATUS_OK); + TEST_ASSERT(output == FXP_INT(6)); + TEST_ASSERT(fpc_pid_compute(&pid, FXP_INT(3), 0, &output) + == FPC_STATUS_OK); + TEST_ASSERT(output == FXP_INT(12)); + + /* D is kd / dt times the change in error. */ + cfg = term_config(0, 0, FXP_INT(4), FXP_INT(2)); + TEST_ASSERT(fpc_pid_init(&pid, &cfg) == FPC_STATUS_OK); + TEST_ASSERT(fpc_pid_compute(&pid, FXP_INT(3), 0, &output) + == FPC_STATUS_OK); + TEST_ASSERT(output == FXP_INT(6)); + TEST_ASSERT(fpc_pid_compute(&pid, FXP_INT(3), 0, &output) + == FPC_STATUS_OK); + TEST_ASSERT(output == 0); +} + +TEST_CASE(test_integral_keeps_sub_lsb_contributions) +{ + struct fpc_pid pid; + /* ki * dt = 60 LSB of gain; with e = 990 LSB each step adds + * 59400 / 65536 = 0.906 LSB to the integral. */ + struct fpc_pid_config cfg = term_config(0, FXP_RAW(1), 0, FXP_INT(60)); + struct fpc_pid_state state; + fxp_t output = 0; + uint32_t i; + + TEST_ASSERT(fpc_pid_init(&pid, &cfg) == FPC_STATUS_OK); + for (i = 0U; i < 100000U; ++i) { + TEST_ASSERT(fpc_pid_compute(&pid, 990, 0, &output) + == FPC_STATUS_OK); + } + + /* 100000 * 59400 / 65536 = 90637.2. Narrowing each step would give + * 0 (truncate) or 100000 (round to nearest). */ + TEST_ASSERT(fpc_pid_get_state(&pid, &state) == FPC_STATUS_OK); + TEST_ASSERT(state.integral == 90637); + TEST_ASSERT(output == 90637); +} + +TEST_CASE(test_anti_windup_clamps_accumulator) +{ + struct fpc_pid pid; + struct fpc_pid_config cfg = term_config(0, FXP_ONE, 0, FXP_ONE); + struct fpc_pid_state state; + fxp_t output = 0; + uint32_t i; + + cfg.integral_min = -5; + cfg.integral_max = 5; + TEST_ASSERT(fpc_pid_init(&pid, &cfg) == FPC_STATUS_OK); + for (i = 0U; i < 10U; ++i) { + TEST_ASSERT(fpc_pid_compute(&pid, 10, 0, &output) + == FPC_STATUS_SATURATED); + } + TEST_ASSERT(output == 5); + + /* No stored windup: one negative step leaves the bound at once. */ + TEST_ASSERT(fpc_pid_compute(&pid, -1, 0, &output) == FPC_STATUS_OK); + TEST_ASSERT(output == 4); + TEST_ASSERT(fpc_pid_get_state(&pid, &state) == FPC_STATUS_OK); + TEST_ASSERT(state.integral == 4); } TEST_CASE(test_saturation_reporting) { - struct fpc_pid *ctx = NULL; + struct fpc_pid pid; struct fpc_pid_config cfg = test_config(); - int32_t output = 0; + fxp_t output = 0; - TEST_ASSERT(fpc_pid_pool_init() == FPC_STATUS_OK); - TEST_ASSERT(fpc_pid_init(&ctx, &cfg) == FPC_STATUS_OK); - TEST_ASSERT(fpc_pid_compute(ctx, 10000, 0, &output) + TEST_ASSERT(fpc_pid_init(&pid, &cfg) == FPC_STATUS_OK); + TEST_ASSERT(fpc_pid_compute(&pid, 10000, 0, &output) == FPC_STATUS_SATURATED); TEST_ASSERT(output == 100); - TEST_ASSERT(fpc_pid_compute(ctx, -10000, 0, &output) + TEST_ASSERT(fpc_pid_compute(&pid, -10000, 0, &output) == FPC_STATUS_SATURATED); TEST_ASSERT(output == -100); - TEST_ASSERT(fpc_pid_deinit(ctx) == FPC_STATUS_OK); } -TEST_CASE(test_state_retrieval) +TEST_CASE(test_extreme_inputs_saturate) { - struct fpc_pid *ctx = NULL; - struct fpc_pid_config cfg = test_config(); + struct fpc_pid pid; + struct fpc_pid_config cfg = term_config(FXP_MIN, 0, 0, FXP_ONE); struct fpc_pid_state state; - int32_t output = 0; + fxp_t output = 0; - cfg.out_min = -1000; - cfg.out_max = 1000; - cfg.integral_min = -1000; - cfg.integral_max = 1000; + /* The error saturates instead of holding the last output. */ + TEST_ASSERT(fpc_pid_init(&pid, &cfg) == FPC_STATUS_OK); + TEST_ASSERT(fpc_pid_compute(&pid, FXP_MAX, FXP_MIN, &output) + == FPC_STATUS_SATURATED); + TEST_ASSERT(output == FXP_MIN); + TEST_ASSERT(fpc_pid_get_state(&pid, &state) == FPC_STATUS_OK); + TEST_ASSERT(state.prev_error == FXP_MAX); + + /* kp * e = 2^62 narrows out of range. */ + TEST_ASSERT(fpc_pid_compute(&pid, FXP_MIN, 0, &output) + == FPC_STATUS_SATURATED); + TEST_ASSERT(output == FXP_MAX); + + /* The change in error and the raw derivative saturate. */ + cfg = term_config(0, 0, FXP_MIN, FXP_ONE); + TEST_ASSERT(fpc_pid_init(&pid, &cfg) == FPC_STATUS_OK); + TEST_ASSERT(fpc_pid_compute(&pid, FXP_MAX, 0, &output) + == FPC_STATUS_SATURATED); + TEST_ASSERT(output == FXP_MIN); + TEST_ASSERT(fpc_pid_compute(&pid, FXP_MIN, 0, &output) + == FPC_STATUS_SATURATED); + TEST_ASSERT(output == FXP_MAX); +} - TEST_ASSERT(fpc_pid_pool_init() == FPC_STATUS_OK); - TEST_ASSERT(fpc_pid_init(&ctx, &cfg) == FPC_STATUS_OK); - TEST_ASSERT(fpc_pid_compute(ctx, 1000, 500, &output) == FPC_STATUS_OK); - TEST_ASSERT(fpc_pid_get_state(ctx, &state) == FPC_STATUS_OK); - TEST_ASSERT(state.integral > 0); +TEST_CASE(test_state_retrieval) +{ + struct fpc_pid pid; + struct fpc_pid_config cfg = wide_config(); + struct fpc_pid_state state; + fxp_t output = 0; + + /* P = 500, I = 250, D = 0.2 * 500 = 99.998 -> 100. */ + TEST_ASSERT(fpc_pid_init(&pid, &cfg) == FPC_STATUS_OK); + TEST_ASSERT(fpc_pid_compute(&pid, 1000, 500, &output) == FPC_STATUS_OK); + TEST_ASSERT(output == 850); + TEST_ASSERT(fpc_pid_get_state(&pid, &state) == FPC_STATUS_OK); + TEST_ASSERT(state.integral == 250); TEST_ASSERT(state.prev_error == 500); TEST_ASSERT(state.filtered_derivative == 100); - TEST_ASSERT(state.last_output == output); + TEST_ASSERT(state.last_output == 850); TEST_ASSERT(state.mode == FPC_PID_MODE_AUTO); - TEST_ASSERT(fpc_pid_deinit(ctx) == FPC_STATUS_OK); } TEST_CASE(test_derivative_filtering) { - struct fpc_pid *ctx = NULL; - struct fpc_pid_config cfg = test_config(); + struct fpc_pid pid; + struct fpc_pid_config cfg = term_config(0, 0, FXP_ONE, FXP_ONE); struct fpc_pid_state state; - int32_t output = 0; - - cfg.kp = 0; - cfg.ki = 0; - cfg.kd = 1000; - cfg.out_min = -1000; - cfg.out_max = 1000; - cfg.integral_min = -1000; - cfg.integral_max = 1000; - cfg.d_filter_alpha = 32768U; + fxp_t output = 0; - TEST_ASSERT(fpc_pid_pool_init() == FPC_STATUS_OK); - TEST_ASSERT(fpc_pid_init(&ctx, &cfg) == FPC_STATUS_OK); - TEST_ASSERT(fpc_pid_compute(ctx, 1000, 0, &output) == FPC_STATUS_OK); + cfg.d_filter_alpha = FXP_ONE / 2; + TEST_ASSERT(fpc_pid_init(&pid, &cfg) == FPC_STATUS_OK); + TEST_ASSERT(fpc_pid_compute(&pid, 1000, 0, &output) == FPC_STATUS_OK); TEST_ASSERT(output == 500); - TEST_ASSERT(fpc_pid_get_state(ctx, &state) == FPC_STATUS_OK); + TEST_ASSERT(fpc_pid_get_state(&pid, &state) == FPC_STATUS_OK); TEST_ASSERT(state.filtered_derivative == 500); - TEST_ASSERT(fpc_pid_compute(ctx, 1000, 0, &output) == FPC_STATUS_OK); + TEST_ASSERT(fpc_pid_compute(&pid, 1000, 0, &output) == FPC_STATUS_OK); TEST_ASSERT(output == 250); - TEST_ASSERT(fpc_pid_get_state(ctx, &state) == FPC_STATUS_OK); + TEST_ASSERT(fpc_pid_get_state(&pid, &state) == FPC_STATUS_OK); TEST_ASSERT(state.filtered_derivative == 250); - TEST_ASSERT(fpc_pid_deinit(ctx) == FPC_STATUS_OK); } TEST_CASE(test_reset_clears_runtime_state) { - struct fpc_pid *ctx = NULL; + struct fpc_pid pid; struct fpc_pid_config cfg = test_config(); struct fpc_pid_state state; - int32_t output = 0; + fxp_t output = 0; - TEST_ASSERT(fpc_pid_pool_init() == FPC_STATUS_OK); - TEST_ASSERT(fpc_pid_init(&ctx, &cfg) == FPC_STATUS_OK); - TEST_ASSERT(fpc_pid_compute(ctx, 1000, 0, &output) + TEST_ASSERT(fpc_pid_init(&pid, &cfg) == FPC_STATUS_OK); + TEST_ASSERT(fpc_pid_compute(&pid, 1000, 0, &output) == FPC_STATUS_SATURATED); - TEST_ASSERT(fpc_pid_reset(ctx) == FPC_STATUS_OK); - TEST_ASSERT(fpc_pid_get_state(ctx, &state) == FPC_STATUS_OK); + TEST_ASSERT(fpc_pid_reset(&pid) == FPC_STATUS_OK); + TEST_ASSERT(fpc_pid_get_state(&pid, &state) == FPC_STATUS_OK); TEST_ASSERT(state.integral == 0); TEST_ASSERT(state.prev_error == 0); TEST_ASSERT(state.filtered_derivative == 0); TEST_ASSERT(state.last_output == 0); - TEST_ASSERT(fpc_pid_deinit(ctx) == FPC_STATUS_OK); + + /* In manual mode the held output survives a reset. */ + TEST_ASSERT(fpc_pid_set_mode(&pid, FPC_PID_MODE_MANUAL, 30) + == FPC_STATUS_OK); + TEST_ASSERT(fpc_pid_reset(&pid) == FPC_STATUS_OK); + TEST_ASSERT(fpc_pid_get_state(&pid, &state) == FPC_STATUS_OK); + TEST_ASSERT(state.last_output == 30); } TEST_CASE(test_set_config_clamps_state) { - struct fpc_pid *ctx = NULL; + struct fpc_pid pid; struct fpc_pid_config cfg = test_config(); struct fpc_pid_config tighter_cfg = test_config(); + struct fpc_pid_config bad_cfg = test_config(); struct fpc_pid_state state; - int32_t output = 0; + fxp_t output = 0; tighter_cfg.out_min = -10; tighter_cfg.out_max = 10; tighter_cfg.integral_min = -5; tighter_cfg.integral_max = 5; + bad_cfg.dt = 0; - TEST_ASSERT(fpc_pid_pool_init() == FPC_STATUS_OK); - TEST_ASSERT(fpc_pid_init(&ctx, &cfg) == FPC_STATUS_OK); - TEST_ASSERT(fpc_pid_compute(ctx, 1000, 0, &output) + TEST_ASSERT(fpc_pid_init(&pid, &cfg) == FPC_STATUS_OK); + TEST_ASSERT(fpc_pid_compute(&pid, 1000, 0, &output) == FPC_STATUS_SATURATED); - TEST_ASSERT(fpc_pid_set_config(ctx, &tighter_cfg) + TEST_ASSERT(fpc_pid_set_config(&pid, &bad_cfg) + == FPC_STATUS_INVALID_PARAM); + TEST_ASSERT(fpc_pid_set_config(&pid, NULL) == FPC_STATUS_INVALID_PARAM); + TEST_ASSERT(fpc_pid_get_state(&pid, &state) == FPC_STATUS_OK); + TEST_ASSERT(state.integral == 50); + TEST_ASSERT(state.last_output == 100); + + TEST_ASSERT(fpc_pid_set_config(&pid, &tighter_cfg) == FPC_STATUS_SATURATED); - TEST_ASSERT(fpc_pid_get_state(ctx, &state) == FPC_STATUS_OK); - TEST_ASSERT(state.integral <= 5); - TEST_ASSERT(state.last_output <= 10); - TEST_ASSERT(fpc_pid_deinit(ctx) == FPC_STATUS_OK); -} - -TEST_CASE(test_pool_exhaustion) -{ - struct fpc_pid *ctx[FPC_MAX_INSTANCES] = {0}; - struct fpc_pid *extra = NULL; - struct fpc_pid_config cfg = test_config(); - uint16_t i; - - TEST_ASSERT(fpc_pid_pool_init() == FPC_STATUS_OK); - for (i = 0U; i < FPC_MAX_INSTANCES; ++i) { - TEST_ASSERT(fpc_pid_init(&ctx[i], &cfg) == FPC_STATUS_OK); - } - - TEST_ASSERT(fpc_pid_init(&extra, &cfg) == FPC_STATUS_POOL_FULL); - TEST_ASSERT(extra == NULL); - - for (i = 0U; i < FPC_MAX_INSTANCES; ++i) { - TEST_ASSERT(fpc_pid_deinit(ctx[i]) == FPC_STATUS_OK); - } + TEST_ASSERT(fpc_pid_get_state(&pid, &state) == FPC_STATUS_OK); + TEST_ASSERT(state.integral == 5); + TEST_ASSERT(state.last_output == 10); + TEST_ASSERT(fpc_pid_set_config(&pid, &tighter_cfg) == FPC_STATUS_OK); + + /* A held manual output is clamped to the new bounds. */ + TEST_ASSERT(fpc_pid_set_config(&pid, &cfg) == FPC_STATUS_OK); + TEST_ASSERT(fpc_pid_set_mode(&pid, FPC_PID_MODE_MANUAL, 80) + == FPC_STATUS_OK); + TEST_ASSERT(fpc_pid_set_config(&pid, &tighter_cfg) + == FPC_STATUS_SATURATED); + TEST_ASSERT(fpc_pid_compute(&pid, 0, 0, &output) == FPC_STATUS_OK); + TEST_ASSERT(output == 10); } TEST_CASE(test_manual_mode_and_bumpless_return) { - struct fpc_pid *ctx = NULL; - struct fpc_pid_config cfg = test_config(); + struct fpc_pid pid; + struct fpc_pid_config cfg = wide_config(); struct fpc_pid_state state; - int32_t output = 0; + fxp_t output = 0; - cfg.out_min = -1000; - cfg.out_max = 1000; - cfg.integral_min = -1000; - cfg.integral_max = 1000; cfg.ki = 0; cfg.kd = 0; - TEST_ASSERT(fpc_pid_pool_init() == FPC_STATUS_OK); - TEST_ASSERT(fpc_pid_init(&ctx, &cfg) == FPC_STATUS_OK); - TEST_ASSERT(fpc_pid_set_mode(ctx, FPC_PID_MODE_MANUAL, 300) + TEST_ASSERT(fpc_pid_init(&pid, &cfg) == FPC_STATUS_OK); + TEST_ASSERT(fpc_pid_set_mode(&pid, FPC_PID_MODE_MANUAL, 300) == FPC_STATUS_OK); - TEST_ASSERT(fpc_pid_compute(ctx, 1000, 900, &output) == FPC_STATUS_OK); + TEST_ASSERT(fpc_pid_compute(&pid, 1000, 900, &output) == FPC_STATUS_OK); TEST_ASSERT(output == 300); - TEST_ASSERT(fpc_pid_get_state(ctx, &state) == FPC_STATUS_OK); + TEST_ASSERT(fpc_pid_get_state(&pid, &state) == FPC_STATUS_OK); TEST_ASSERT(state.mode == FPC_PID_MODE_MANUAL); TEST_ASSERT(state.prev_error == 100); - TEST_ASSERT(fpc_pid_set_mode(ctx, FPC_PID_MODE_AUTO, 0) + TEST_ASSERT(fpc_pid_set_mode(&pid, FPC_PID_MODE_AUTO, 0) == FPC_STATUS_OK); - TEST_ASSERT(fpc_pid_get_state(ctx, &state) == FPC_STATUS_OK); + TEST_ASSERT(fpc_pid_get_state(&pid, &state) == FPC_STATUS_OK); TEST_ASSERT(state.mode == FPC_PID_MODE_AUTO); TEST_ASSERT(state.integral == 200); - TEST_ASSERT(fpc_pid_compute(ctx, 1000, 900, &output) == FPC_STATUS_OK); + TEST_ASSERT(fpc_pid_compute(&pid, 1000, 900, &output) == FPC_STATUS_OK); TEST_ASSERT(output == 300); - TEST_ASSERT(fpc_pid_deinit(ctx) == FPC_STATUS_OK); + + /* Auto to auto changes nothing. */ + TEST_ASSERT(fpc_pid_set_mode(&pid, FPC_PID_MODE_AUTO, 0) + == FPC_STATUS_OK); + TEST_ASSERT(fpc_pid_get_state(&pid, &state) == FPC_STATUS_OK); + TEST_ASSERT(state.integral == 200); +} + +TEST_CASE(test_bumpless_rebias_clamps) +{ + struct fpc_pid pid; + struct fpc_pid_config cfg = test_config(); + struct fpc_pid_state state; + fxp_t output = 0; + + /* Re-biasing needs I = 90 - 10 = 80, above integral_max = 50. */ + TEST_ASSERT(fpc_pid_init(&pid, &cfg) == FPC_STATUS_OK); + TEST_ASSERT(fpc_pid_set_mode(&pid, FPC_PID_MODE_MANUAL, 90) + == FPC_STATUS_OK); + TEST_ASSERT(fpc_pid_compute(&pid, 10, 0, &output) == FPC_STATUS_OK); + TEST_ASSERT(fpc_pid_set_mode(&pid, FPC_PID_MODE_AUTO, 0) + == FPC_STATUS_SATURATED); + TEST_ASSERT(fpc_pid_get_state(&pid, &state) == FPC_STATUS_OK); + TEST_ASSERT(state.integral == 50); } TEST_CASE(test_manual_mode_clamps_output) { - struct fpc_pid *ctx = NULL; + struct fpc_pid pid; struct fpc_pid_config cfg = test_config(); - int32_t output = 0; + fxp_t output = 0; - TEST_ASSERT(fpc_pid_pool_init() == FPC_STATUS_OK); - TEST_ASSERT(fpc_pid_init(&ctx, &cfg) == FPC_STATUS_OK); - TEST_ASSERT(fpc_pid_set_mode(ctx, FPC_PID_MODE_MANUAL, 1000) + TEST_ASSERT(fpc_pid_init(&pid, &cfg) == FPC_STATUS_OK); + TEST_ASSERT(fpc_pid_set_mode(&pid, FPC_PID_MODE_MANUAL, 1000) + == FPC_STATUS_SATURATED); + TEST_ASSERT(fpc_pid_compute(&pid, 0, 0, &output) == FPC_STATUS_OK); + TEST_ASSERT(output == 100); + TEST_ASSERT(fpc_pid_compute(&pid, FXP_MAX, FXP_MIN, &output) == FPC_STATUS_SATURATED); - TEST_ASSERT(fpc_pid_compute(ctx, 0, 0, &output) == FPC_STATUS_OK); TEST_ASSERT(output == 100); - TEST_ASSERT(fpc_pid_deinit(ctx) == FPC_STATUS_OK); } TEST_CASE(test_null_and_invalid_runtime_calls) { - struct fpc_pid *ctx = NULL; + struct fpc_pid pid = {0}; struct fpc_pid_config cfg = test_config(); struct fpc_pid_config copy; - int32_t output = 0; struct fpc_pid_state state; + fxp_t output = 0; - TEST_ASSERT(fpc_pid_pool_init() == FPC_STATUS_OK); TEST_ASSERT(fpc_pid_reset(NULL) == FPC_STATUS_NULL_PTR); + TEST_ASSERT(fpc_pid_set_config(NULL, &cfg) == FPC_STATUS_NULL_PTR); TEST_ASSERT(fpc_pid_get_config(NULL, ©) == FPC_STATUS_NULL_PTR); - TEST_ASSERT(fpc_pid_get_config(ctx, NULL) == FPC_STATUS_NULL_PTR); TEST_ASSERT(fpc_pid_set_mode(NULL, FPC_PID_MODE_MANUAL, 0) == FPC_STATUS_NULL_PTR); TEST_ASSERT(fpc_pid_get_state(NULL, &state) == FPC_STATUS_NULL_PTR); - TEST_ASSERT(fpc_pid_get_state(ctx, NULL) == FPC_STATUS_NULL_PTR); TEST_ASSERT(fpc_pid_compute(NULL, 0, 0, &output) == FPC_STATUS_NULL_PTR); - TEST_ASSERT(fpc_pid_compute(ctx, 0, 0, NULL) == FPC_STATUS_NULL_PTR); - TEST_ASSERT(fpc_pid_init(&ctx, &cfg) == FPC_STATUS_OK); - TEST_ASSERT(fpc_pid_deinit(ctx) == FPC_STATUS_OK); - TEST_ASSERT(fpc_pid_compute(ctx, 1000, 0, &output) + /* A zeroed instance is not initialised. */ + TEST_ASSERT(fpc_pid_reset(&pid) == FPC_STATUS_NOT_INITIALIZED); + TEST_ASSERT(fpc_pid_set_config(&pid, &cfg) == FPC_STATUS_NOT_INITIALIZED); - TEST_ASSERT(fpc_pid_reset(ctx) == FPC_STATUS_NOT_INITIALIZED); - TEST_ASSERT(fpc_pid_set_mode(ctx, FPC_PID_MODE_AUTO, 0) + TEST_ASSERT(fpc_pid_get_config(&pid, ©) + == FPC_STATUS_NOT_INITIALIZED); + TEST_ASSERT(fpc_pid_set_mode(&pid, FPC_PID_MODE_AUTO, 0) + == FPC_STATUS_NOT_INITIALIZED); + TEST_ASSERT(fpc_pid_get_state(&pid, &state) + == FPC_STATUS_NOT_INITIALIZED); + TEST_ASSERT(fpc_pid_compute(&pid, 1000, 0, &output) == FPC_STATUS_NOT_INITIALIZED); -} - -TEST_CASE(test_overflow_detection) -{ - struct fpc_pid *ctx = NULL; - struct fpc_pid_config cfg = test_config(); - int32_t output = 0; - TEST_ASSERT(fpc_pid_pool_init() == FPC_STATUS_OK); - TEST_ASSERT(fpc_pid_init(&ctx, &cfg) == FPC_STATUS_OK); - TEST_ASSERT(fpc_pid_compute(ctx, INT32_MAX, INT32_MIN, &output) - == FPC_STATUS_OVERFLOW); - TEST_ASSERT(output == 0); - TEST_ASSERT(fpc_pid_deinit(ctx) == FPC_STATUS_OK); + TEST_ASSERT(fpc_pid_init(&pid, &cfg) == FPC_STATUS_OK); + TEST_ASSERT(fpc_pid_get_config(&pid, NULL) == FPC_STATUS_NULL_PTR); + TEST_ASSERT(fpc_pid_get_state(&pid, NULL) == FPC_STATUS_NULL_PTR); + TEST_ASSERT(fpc_pid_compute(&pid, 0, 0, NULL) == FPC_STATUS_NULL_PTR); + TEST_ASSERT(fpc_pid_set_mode(&pid, (enum fpc_pid_mode)2, 0) + == FPC_STATUS_INVALID_PARAM); } void run_pid_tests(void) { - run_test(test_pool_init_required, "pool_init_required"); run_test(test_init_and_get_config, "init_and_get_config"); run_test(test_invalid_config_rejected, "invalid_config_rejected"); + run_test(test_dt_scales_i_and_d_only, "dt_scales_i_and_d_only"); + run_test(test_integral_keeps_sub_lsb_contributions, + "integral_keeps_sub_lsb_contributions"); + run_test(test_anti_windup_clamps_accumulator, + "anti_windup_clamps_accumulator"); run_test(test_saturation_reporting, "saturation_reporting"); + run_test(test_extreme_inputs_saturate, "extreme_inputs_saturate"); run_test(test_state_retrieval, "state_retrieval"); run_test(test_derivative_filtering, "derivative_filtering"); run_test(test_reset_clears_runtime_state, "reset_clears_runtime_state"); run_test(test_set_config_clamps_state, "set_config_clamps_state"); - run_test(test_pool_exhaustion, "pool_exhaustion"); run_test(test_manual_mode_and_bumpless_return, "manual_mode_and_bumpless_return"); + run_test(test_bumpless_rebias_clamps, "bumpless_rebias_clamps"); run_test(test_manual_mode_clamps_output, "manual_mode_clamps_output"); run_test(test_null_and_invalid_runtime_calls, "null_and_invalid_runtime_calls"); - run_test(test_overflow_detection, "overflow_detection"); }