/*
 * FBKW.h
 *
 *  Created on: Nov 20, 2024
 *      Author: herli
 */

#ifndef INC_FBKW_H_
#define INC_FBKW_H_
#include "main.h"

extern TIM_HandleTypeDef htim4;

extern uint8_t CKP_PULSE_AVAILABLE;
extern uint8_t FBKW_PID_OPEN;
extern volatile uint32_t IC_SYNCOUT;
extern volatile uint32_t IC_CKP2;
extern volatile float RPM;
extern float refClock;
extern uint8_t safetySHUTOFF;


extern float errorFBKW;
extern float targetFBKW;
extern float Kp;
extern float Ki;
extern float intFBKWerror; 		//add += error * tstep

extern float FBKW_DEMAND;
extern float FBKW_DC;
extern float FBKW_FEEDBACK;

extern float B_FB_KW;
extern float B_FB_NW;
extern uint8_t forceDC;


typedef struct PID
{
    float Kp;              // Proportional gain constant
    float Ki;              // Integral gain constant
    float Kd;              // Derivative gain constant
    float Kaw;             // Anti-windup gain constant
    float Bias;             // Output bias
    float T_C;             // Time constant for derivative filtering
    float T;               // Time step
    float max;             // Max command
    float min;             // Min command
    float max_rate;        // Max rate of change of the command
    float integral;        // Integral term
    float err_prev;        // Previous error
    float deriv_prev;      // Previous derivative
    float command_sat_prev;// Previous saturated command
    float command_prev;    // Previous command
} PID;
extern PID myPID;	 //antes era volatile

extern void FBKW_RESET_CKP_COUNT();
extern void FBKW_PIDInterrupt();
extern void FBKW_PROCESS_CKP_PULSE();
extern void updatePIDfreq(struct PID *pid, uint8_t millis);

extern void definePID(struct PID *pid, float Kp, float Ki, float Kd, float Kaw, float Bias, float T_C, float T, float max, float min, float max_rate, float integral, float err_prev, float deriv_prev, float command_sat_prev, float command_prev);
extern void initPID(struct PID *pid, float T_C, float T);

extern void UpdateFBKW_MODULATION(TIM_HandleTypeDef* pwmHandle, uint32_t pwmChannel, float dutyCycle);
extern float UpdateFBKW_DEMAND(float FBKW);
float UpdateFBKW_OpenDutyCycle(float RPM);
extern void UpdatePID(struct PID *pid);

float F_clamp(float val, float min, float max);
#endif /* INC_FBKW_H_ */
