file_path
stringlengths
20
207
content
stringlengths
5
3.85M
size
int64
5
3.85M
lang
stringclasses
9 values
avg_line_length
float64
1.33
100
max_line_length
int64
4
993
alphanum_fraction
float64
0.26
0.93
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/potentiometer.h
/** ****************************************************************************** * @file potentiometer.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains the definitions and functions prototypes for the * Potentiometer component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup Potentiometer */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef POTENTIOMETER_H #define POTENTIOMETER_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "mc_type.h" #include "regular_conversion_manager.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup Potentiometer * @{ */ /* Exported types ------------------------------------------------------------*/ /** * @brief Handle structure of a Potentiometer component. * * A potentiometer component aims at measuring the voltage * across a potentiometer thanks to an ADC. * * This structure contains all the information needed for a Potentiometer * component instance to work. * * See the @ref Potentiometer component documentation for more details. */ typedef struct { uint16_t * PotMeasArray; /**< @brief Array for storing raw potentiometer measures * * This field must point to a reserved array of uint16_t * prior to calling the POT_Init() function. The size of * this array must be @f$2^{LPFilterBandwidthPOW2}@f$. * * See #LPFilterBandwidthPOW2. */ uint32_t PotValueAccumulator; /**< @brief accumulated potentiometer measures */ uint8_t LPFilterBandwidthPOW2; /**< @brief Number of measures used to compute the average * value, expressed as a power of 2 * * For instance, if the number of measures is 16, the * value of this field must be 4 since @f$16 = 2^4@f$. * * This field must be set prior to calling POT_Init() */ uint8_t LPFilterBandwidth; /**< @brief Number of measures used to compute the average value * * This value is set to @f$2^{LPFilterBandwidthPOW2}@f$ by * the POT_Init() function. * * See #LPFilterBandwidthPOW2. */ uint8_t Index; /**< @brief position where the next measure will be put in #PotMeqsArray */ uint8_t PotRegConvHandle; /**< @brief Handle on the [Regular Conversion Manager](#RCM) * to manage the measures of the potentiometer */ bool Valid; /**< @brief Indicates the validity of #PotValueAccumulator * * See the @ref Potentiometer documentation for more details. */ } Potentiometer_Handle_t; /* Exported functions ------------------------------------------------------- */ /* Potentiometer component initialization */ void POT_Init(Potentiometer_Handle_t *pHandle); /* Clears the state of a Potentiometer component */ void POT_Clear(Potentiometer_Handle_t *pHandle); /* Measures the voltage of the potentiometer */ void POT_TakeMeasurement(Potentiometer_Handle_t *pHandle, uint16_t rawValue); /* Returns the current potentiometer value */ uint16_t POT_GetValue(Potentiometer_Handle_t *pHandle); /* Returns true if the current potentiometer value is valid */ bool POT_ValidValueAvailable(Potentiometer_Handle_t *pHandle); /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* POTENTIOMETER_H */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
4,888
C
40.084033
111
0.491203
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/hso.h
/** ****************************************************************************** * @file hso.h * @author Piak Electronic Design B.V. * @brief This file is part of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 Piak Electronic Design B.V. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** */ /* hso.h */ #ifndef _HSO_H_ #define _HSO_H_ #include "fixpmath.h" #include <stdbool.h> #include <stddef.h> #include <string.h> /* memset */ #define HSO_setflag_TrackAngle HSO_setFlag_TrackAngle /* HSO_setflag_TrackAngle is deprecated */ typedef struct _HSO_Params_ { float_t Flux_Wb; float_t CrossOver_Hz; float_t isrTime_s; float_t FullScaleVoltage_V; float_t FullScaleFreq_Hz; float_t speedPole_rps; bool flag_FilterAdaptive; float_t Filter_adapt_fmin_Hz; float_t Filter_adapt_fmax_Hz; float_t CheckDirBW_Hz; } HSO_Params; #define HSO_SIZE_WORDS (120) /* Size in words, plus a margin */ typedef struct _HSO_Obj_ { /* Contents of this structure is not public */ uint16_t reserved[HSO_SIZE_WORDS]; } HSO_Obj; typedef HSO_Obj* HSO_Handle; /* initialization */ static inline HSO_Handle HSO_init(void *pMemory, const size_t size) { HSO_Handle handle = (HSO_Handle) NULL; if (size >= sizeof(HSO_Obj)) { handle = (HSO_Handle) pMemory; memset(pMemory, 0, size); } return (handle); } extern void HSO_setParams(HSO_Handle handle, const HSO_Params *pParams); /* functional */ extern void HSO_run(HSO_Handle handle, Voltages_Uab_t *pVback_ab, const fixp30_t Correction); extern void HSO_adjustAngle_pu(HSO_Handle handle, const fixp30_t rotation_pu); extern void HSO_clear(HSO_Handle handle); extern void HSO_flip_angle(HSO_Handle handle); /* accessors */ extern fixp30_t HSO_getAngle_pu(const HSO_Handle handle); extern fixp30_t HSO_getCheckDir(const HSO_Handle handle); extern void HSO_getCosSinTh_ab(const HSO_Handle handle, FIXP_CosSin_t *pCosSinTh); extern FIXP_CosSin_t HSO_getCosSin(const HSO_Handle handle); extern fixp30_t HSO_getDelta_theta_pu(const HSO_Handle handle); extern fixp30_t HSO_getEmfSpeed_pu(const HSO_Handle handle); extern Vector_ab_t HSO_getFlux_ab_Wb(const HSO_Handle handle); extern fixp30_t HSO_getFluxAmpl_Wb(const HSO_Handle handle); extern fixp30_t HSO_getFluxRef_Wb(const HSO_Handle handle); extern fixp30_t HSO_getKoffset(const HSO_Handle handle); extern fixp30_t HSO_getSpeedLP_pu(const HSO_Handle handle); extern float_t HSO_getSpeedPole_rps(const HSO_Handle handle); extern void HSO_setAngle_pu(HSO_Handle handle, const fixp30_t theta); extern void HSO_setCrossOver_Hz(HSO_Handle handle, const float_t CrossOver_Hz); extern void HSO_setCrossOver_pu(HSO_Handle handle, const fixp30_t CrossOver_pu); extern void HSO_setFlag_TrackAngle(HSO_Handle handle, const bool value); extern void HSO_setFluxPolar_pu(HSO_Handle handle, const fixp30_t angle_pu, const fixp30_t magn_pu); extern void HSO_setFluxRef_Wb(HSO_Handle handle, const fixp30_t FluxWb); extern void HSO_setKoffset(HSO_Handle handle, const fixp30_t value); extern void HSO_setMaxCrossOver_Hz(HSO_Handle handle, const float_t value); extern void HSO_setMinCrossOver_Hz(HSO_Handle handle, const float_t value); extern void HSO_setObserverRatio(HSO_Handle handle, const float_t value); extern void HSO_setSpeedPole_rps(HSO_Handle handle, const float_t value); #endif /* _HSO_H_ */ /* end of hso.h */ /************************ (C) COPYRIGHT 2023 Piak Electronic Design B.V. *****END OF FILE****/
4,059
C
29.074074
100
0.655087
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/speed_ctrl.h
/** ****************************************************************************** * @file speed_ctrl.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * Speed & Torque Control component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup SpeednTorqCtrl */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __SPEEDCTRLCLASS_H #define __SPEEDCTRLCLASS_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "mc_type.h" #include "pid_regulator.h" #include "speed_pos_fdbk.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup SpeednTorqCtrl * @{ */ /* Exported types ------------------------------------------------------------*/ /** * @brief Speed Control parameters definition */ typedef struct { MC_ControlMode_t Mode; /*!< Modality of STC. It can be one of these two settings: STC_TORQUE_MODE to enable the Torque mode or STC_SPEED_MODE to enable the Speed mode.*/ int16_t TargetFinal; /*!< Backup of hTargetFinal to be applied in the last step.*/ int32_t SpeedRefUnitExt; /*!< Current mechanical rotor speed reference expressed in SPEED_UNIT multiplied by 65536.*/ uint32_t DutyCycleRef; /*!< Current pulse reference.*/ uint32_t RampRemainingStep;/*!< Number of steps remaining to complete the ramp.*/ PID_Handle_t * PISpeed; /*!< The regulator used to perform the speed control loop.*/ SpeednPosFdbk_Handle_t * SPD;/*!< The speed sensor used to perform the speed regulation.*/ int32_t IncDecAmount; /*!< Increment/decrement amount to be applied to the reference value at each CalcSpeedReference.*/ uint16_t STCFrequencyHz; /*!< Frequency on which the user updates the torque reference calling STC_CalcTorqueReference method expressed in Hz */ uint16_t MaxAppPositiveMecSpeedUnit; /*!< Application maximum positive value of the rotor mechanical speed. Expressed in the unit defined by #SPEED_UNIT.*/ uint16_t MinAppPositiveMecSpeedUnit; /*!< Application minimum positive value of the rotor mechanical speed. Expressed in the unit defined by #SPEED_UNIT.*/ int16_t MaxAppNegativeMecSpeedUnit; /*!< Application maximum negative value of the rotor mechanical speed. Expressed in the unit defined by #SPEED_UNIT.*/ int16_t MinAppNegativeMecSpeedUnit; /*!< Application minimum negative value of the rotor mechanical speed. Expressed in the unit defined by #SPEED_UNIT.*/ uint16_t MaxPositiveDutyCycle; /*!< Maximum positive value of motor torque. This value represents actually the maximum Iq current expressed in digit.*/ MC_ControlMode_t ModeDefault; /*!< Default STC modality.*/ int16_t MecSpeedRefUnitDefault; /*!< Default mechanical rotor speed reference expressed in the unit defined by #SPEED_UNIT.*/ uint16_t DutyCycleRefDefault; /*!< Default pulse reference.*/ } SpeednTorqCtrl_Handle_t; /* It initializes all the object variables */ void STC_Init( SpeednTorqCtrl_Handle_t * pHandle, PID_Handle_t * oPI, SpeednPosFdbk_Handle_t * oSPD ); /* It resets the integral term of speed regulator */ void STC_Clear( SpeednTorqCtrl_Handle_t * pHandle ); /* Get the current mechanical rotor speed reference. Expressed in the unit defined by SPEED_UNIT.*/ int16_t STC_GetMecSpeedRefUnit( SpeednTorqCtrl_Handle_t * pHandle ); /* Get the current motor duty cycle reference. */ uint16_t STC_GetDutyCycleRef(SpeednTorqCtrl_Handle_t *pHandle); /* Set the mode of the speed controller (Torque mode or Speed mode)*/ void STC_SetControlMode( SpeednTorqCtrl_Handle_t * pHandle, MC_ControlMode_t bMode ); /* Get the mode of the speed controller. */ MC_ControlMode_t STC_GetControlMode( SpeednTorqCtrl_Handle_t * pHandle ); /* Starts the execution of a ramp using new target and duration. */ bool STC_ExecRamp( SpeednTorqCtrl_Handle_t * pHandle, int16_t hTargetFinal, uint32_t hDurationms ); /* It computes the new value of motor speed reference */ uint16_t STC_CalcSpeedReference(SpeednTorqCtrl_Handle_t *pHandle); /* It interrupts the execution of any previous ramp command.*/ void STC_StopRamp( SpeednTorqCtrl_Handle_t * pHandle ); /* Get the Default mechanical rotor speed reference. Expressed in the unit defined by SPEED_UNIT.*/ int16_t STC_GetMecSpeedRefUnitDefault( SpeednTorqCtrl_Handle_t * pHandle ); /* Returns the Application maximum positive rotor mechanical speed. Expressed in the unit defined by SPEED_UNIT.*/ uint16_t STC_GetMaxAppPositiveMecSpeedUnit( SpeednTorqCtrl_Handle_t * pHandle ); /* Returns the Application minimum negative rotor mechanical speed. Expressed in the unit defined by SPEED_UNIT.*/ int16_t STC_GetMinAppNegativeMecSpeedUnit( SpeednTorqCtrl_Handle_t * pHandle ); /* Check if the settled speed ramp has been completed.*/ bool STC_RampCompleted( SpeednTorqCtrl_Handle_t * pHandle ); /* Stop the execution of speed ramp. */ bool STC_StopSpeedRamp( SpeednTorqCtrl_Handle_t * pHandle ); /* It sets in real time the speed sensor utilized by the 6step. */ void STC_SetSpeedSensor( SpeednTorqCtrl_Handle_t * pHandle, SpeednPosFdbk_Handle_t * oSPD ); /* It returns the speed sensor utilized by the 6step. */ SpeednPosFdbk_Handle_t * STC_GetSpeedSensor( SpeednTorqCtrl_Handle_t * pHandle ); /* Force the speed reference to the current speed */ void STC_ForceSpeedReferenceToCurrentSpeed( SpeednTorqCtrl_Handle_t * pHandle ); /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* __SPEEDCTRLCLASS_H */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
7,351
C
43.557575
114
0.578969
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/speed_potentiometer.h
/** ****************************************************************************** * @file speed_potentiometer.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains the definitions and functions prototypes for the * Speed Potentiometer component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup SpeedPotentiometer */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef SPEED_POTENTIOMETER_H #define SPEED_POTENTIOMETER_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "potentiometer.h" #include "mc_interface.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup Potentiometer * @{ */ /** @addtogroup SpeedPotentiometer * @{ */ /* Exported types ------------------------------------------------------------*/ /** * @brief Handle structure of a Speed Potentiometer component. * * A Speed Potentiometer component reads the value set on a potentiometer * and uses it to set the rotation speed reference of a motor. To get potentiometer * values, an instance of a Potentiometer component is used. * * This structure contains all the information needed for a Speed Potentiometer * component instance to work. * * See the @ref SpeedPotentiometer component documentation for more details. */ typedef struct { Potentiometer_Handle_t Pot; /**< @brief Instance of the @ref Potentiometer component used * to read the potentiometer * * This structure must be set prior to calling POT_Init(). See * the @ref Potentiometer component for all details. */ MCI_Handle_t *pMCI; /**< @brief Motor Control interface structure of the target motor * * This field must be set prior to calling POT_Init() */ uint32_t RampSlope; /**< @brief Acceleration to use when setting the speed reference in #SPEED_UNIT/s. * * This field must be set prior to calling POT_Init() */ uint16_t ConversionFactor; /**< @brief Factor to convert speed between u16digit and #SPEED_UNIT. * * This field must be set prior to calling POT_Init() */ uint16_t SpeedAdjustmentRange; /**< @brief Represents the range used to trigger a speed ramp command. In u16digits * * This field must be set prior to calling POT_Init() */ uint16_t MinimumSpeed; /**< @brief Minimum settable speed expressed in #SPEED_UNIT * * This field must be set prior to calling POT_Init() */ uint16_t LastSpeedRefSet; /**< @brief Last speed reference set to the target motor. In u16digit */ bool IsRunning; /**< @brief Used to track the transitions of the motor to and from the `RUN` state */ } SpeedPotentiometer_Handle_t; /* Exported functions ------------------------------------------------------- */ /* Initializes a Speed Potentiometer component */ void SPDPOT_Init(SpeedPotentiometer_Handle_t *pHandle); /* Clears the state of a Speed Potentiometer component */ void SPDPOT_Clear(SpeedPotentiometer_Handle_t *pHandle); /* Reads the value of the potentiometer of a Speed Potentiometer component and sets * the rotation speed reference of the motor it targets acordingly */ bool SPDPOT_Run(SpeedPotentiometer_Handle_t *pHandle, uint16_t rawValue); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* SPEED_POTENTIOMETER_H */
4,710
C
37.933884
119
0.516561
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/revup_ctrl.h
/** ****************************************************************************** * @file revup_ctrl.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * RevUpCtrl component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup RevUpCtrlFOC */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef REVUP_CTRL_H #define REVUP_CTRL_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "mc_type.h" #include "speed_torq_ctrl.h" #include "virtual_speed_sensor.h" #include "sto_speed_pos_fdbk.h" #include "pwm_curr_fdbk.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup RevUpCtrl * @{ */ /** @addtogroup RevUpCtrlFOC * @{ */ /* Exported constants --------------------------------------------------------*/ /** * @brief Maximum number of phases allowed for RevUp process. * */ #define RUC_MAX_PHASE_NUMBER 5u /** * @brief RevUpCtrl_PhaseParams_t structure used for phases definition * */ typedef struct { uint16_t hDurationms; /**< @brief Duration of the RevUp phase. This parameter is expressed in millisecond.*/ int16_t hFinalMecSpeedUnit; /**< @brief Mechanical speed assumed by VSS at the end of the RevUp phase. Expressed in the unit defined by #SPEED_UNIT */ int16_t hFinalTorque; /**< @brief Motor torque reference imposed by STC at the end of RevUp phase. This value represents actually the Iq current expressed in digit.*/ void *pNext; /**< @brief Pointer on the next phase section to proceed This parameter is NULL for the last element. */ } RevUpCtrl_PhaseParams_t; /** * @brief Handle structure of the RevUpCtrl. * */ typedef struct { uint16_t hRUCFrequencyHz; /**< @brief Frequency call to main RevUp procedure RUC_Exec. This parameter is equal to speed loop frequency. */ int16_t hStartingMecAngle; /**< @brief Starting angle of programmed RevUp.*/ uint16_t hPhaseRemainingTicks; /**< @brief Number of clock events remaining to complete the phase. */ int16_t hDirection; /**< @brief Motor direction. This parameter can be any value -1 or +1 */ RevUpCtrl_PhaseParams_t *pCurrentPhaseParams; /**< @brief Pointer on the current RevUp phase processed. */ RevUpCtrl_PhaseParams_t ParamsData[RUC_MAX_PHASE_NUMBER]; /**< @brief Start up Phases sequences used by RevUp controller. Up to five phases can be used for the start up. */ uint8_t bPhaseNbr; /**< @brief Number of phases relative to the programmed RevUp sequence. This parameter can be any value from 1 to 5 */ uint8_t bFirstAccelerationStage; /**< @brief Indicates the phase to start the final acceleration. At start of this stage sensor-less algorithm cleared.*/ uint16_t hMinStartUpValidSpeed; /**< @brief Minimum rotor speed required to validate the startup. This parameter is expressed in SPPED_UNIT */ uint16_t hMinStartUpFlySpeed; /**< @brief Minimum rotor speed required to validate the on the fly. This parameter is expressed in the unit defined by #SPEED_UNIT */ int16_t hOTFFinalRevUpCurrent; /**< @brief Final targetted torque for OTF phase. */ uint16_t hOTFSection1Duration; /**< @brief On-the-fly phase duration, millisecond. This parameter is expressed in millisecond.*/ bool OTFStartupEnabled; /**< @brief Flag for OTF feature activation. Feature disabled when set to false */ uint8_t bOTFRelCounter; /**< @brief Counts the number of reliability of state observer */ bool OTFSCLowside; /**< @brief Flag to indicate status of low side switchs. This parameter can be true when Low Sides switch is ON otherwise set to false. */ bool EnteredZone1; /**< @brief Flag to indicate that the minimum rotor speed has been reached. */ uint8_t bResetPLLTh; /**< @brief Threshold to reset PLL during OTF */ uint8_t bResetPLLCnt; /**< @brief Counter to reset PLL during OTF when the threshold is reached. */ uint8_t bStageCnt; /**< @brief Counter of executed phases. This parameter can be any value from 0 to 5 */ RevUpCtrl_PhaseParams_t OTFPhaseParams; /**< @brief RevUp phase parameter of OTF feature.*/ SpeednTorqCtrl_Handle_t *pSTC; /**< @brief Speed and torque controller object used by RevUpCtrl.*/ VirtualSpeedSensor_Handle_t *pVSS; /**< @brief Virtual speed sensor object used by RevUpCtrl.*/ STO_Handle_t *pSNSL; /**< @brief STO sensor object used by OTF startup.*/ PWMC_Handle_t *pPWM; /**< @brief PWM object used by OTF startup.*/ } RevUpCtrl_Handle_t; /* Exported functions ------------------------------------------------------- */ /* Initializes and configures the RevUpCtrl Component */ void RUC_Init(RevUpCtrl_Handle_t *pHandle, SpeednTorqCtrl_Handle_t *pSTC, VirtualSpeedSensor_Handle_t *pVSS, STO_Handle_t *pSNSL, PWMC_Handle_t *pPWM); /* Initializes the internal RevUp controller state */ void RUC_Clear(RevUpCtrl_Handle_t *pHandle, int16_t hMotorDirection); /* Main Rev-Up controller procedure executing overall programmed phases */ bool RUC_Exec(RevUpCtrl_Handle_t *pHandle); /* Main Rev-Up controller procedure that executes overall programmed phases and on-the-fly startup handling */ bool RUC_OTF_Exec(RevUpCtrl_Handle_t *pHandle); /* Provide current state of Rev-Up controller procedure */ bool RUC_Completed(RevUpCtrl_Handle_t *pHandle); /* Allows to exit from RevUp process at the current Rotor speed */ void RUC_Stop(RevUpCtrl_Handle_t *pHandle); /* Checks that alignment and first acceleration stage are completed */ bool RUC_FirstAccelerationStageReached(RevUpCtrl_Handle_t *pHandle); /* Allows to modify duration (ms unit) of a selected phase */ void RUC_SetPhaseDurationms(RevUpCtrl_Handle_t *pHandle, uint8_t bPhase, uint16_t hDurationms); /* Allows to modify targeted mechanical speed of a selected phase */ void RUC_SetPhaseFinalMecSpeedUnit(RevUpCtrl_Handle_t *pHandle, uint8_t bPhase, int16_t hFinalMecSpeedUnit); /* Allows to modify targeted the motor torque of a selected phase */ void RUC_SetPhaseFinalTorque(RevUpCtrl_Handle_t *pHandle, uint8_t bPhase, int16_t hFinalTorque); /* Allows to read duration set in selected phase */ uint16_t RUC_GetPhaseDurationms(RevUpCtrl_Handle_t *pHandle, uint8_t bPhase); /* Allows to read targeted Rotor speed set in selected phase */ int16_t RUC_GetPhaseFinalMecSpeedUnit(RevUpCtrl_Handle_t *pHandle, uint8_t bPhase); /* Allows to read targeted motor torque set in selected phase */ int16_t RUC_GetPhaseFinalTorque(RevUpCtrl_Handle_t *pHandle, uint8_t bPhase); /* Allows to read total number of programmed phases */ uint8_t RUC_GetNumberOfPhases(RevUpCtrl_Handle_t *pHandle); /* It is used to check if this stage is used for align motor */ uint8_t RUC_IsAlignStageNow(RevUpCtrl_Handle_t *pHandle); /* Allows to read status of On The Fly (OTF) feature */ bool RUC_Get_SCLowsideOTF_Status(RevUpCtrl_Handle_t *pHandle); /* Allows to read a programmed phase */ bool RUC_GetPhase(RevUpCtrl_Handle_t *pHandle, uint8_t phaseNumber, RevUpCtrl_PhaseParams_t *phaseData); /* Allows to configure a Rev-Up phase */ bool RUC_SetPhase(RevUpCtrl_Handle_t *pHandle, uint8_t phaseNumber, RevUpCtrl_PhaseParams_t *phaseData); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* REVUP_CTRL_H */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
10,262
C
45.22973
120
0.53206
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/pid_regulator.h
/** ****************************************************************************** * @file pid_regulator.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * PID reulator component of the Motor Control SDK. * * The PID regulator component provides the functions needed to implement * a proportional–integral–derivative controller. * * See @link PIDRegulator @endlink for more details. * ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup PIDRegulator */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef PIDREGULATOR_H #define PIDREGULATOR_H /* Includes ------------------------------------------------------------------*/ #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup PIDRegulator * @{ */ /** * @brief Handle of a PID component * * This structure holds all the parameters needed to implement * a proportional-integral-derivative controller function. * It also stores upper and lower limits used to saturate the * integral term and the output values of the controller. * * A pointer on a structure of this type is passed to each * function of the @ref PIDRegulator "PID Regulator component". */ typedef struct { int16_t hDefKpGain; /**< @brief Default value of @f$K_{pg}@f$, the numerator of the proportional gain. * * The value of this field is copied into #hKpGain when the component is initialized. * @see PID_HandleInit(). */ int16_t hDefKiGain; /**< @brief Default value of @f$K_{ig}@f$, the numerator if the integral gain * * The value of this field is copied into #hKiGain when the component is initialized. * @see PID_HandleInit(). */ int16_t hKpGain; /**< @brief @f$K_{pg}@f$, numerator of the proportional gain of the PID Regulator component */ int16_t hKiGain; /**< @brief @f$K_{ig}@f$, numerator of the integral gain of the PID Regulator component */ int32_t wIntegralTerm; /**< @brief integral term of the PID Regulator * * This value is updated on each call to the PI_Controller() or PID_Controller() functions. It * contains the integral term before being divided by @f$K_{id}@f$, the divisor of the integral * gain: * * @f[ * K_{ig}\times\sum_{k=0}^t{\epsilon_k} * @f] * * This field is reset to 0 when the component is initialized. * @see PID_HandleInit(). */ int32_t wUpperIntegralLimit; /**< @brief Upper limit used to saturate the integral term of the PID Regulator * * The integral term, #wIntegralTerm is capped to the value of this field. */ int32_t wLowerIntegralLimit; /**< @brief Lower limit used to saturate the integral term of the PID Regulator * * The integral term, #wIntegralTerm is floored to the value of this field. */ int16_t hUpperOutputLimit; /**< @brief Upper limit used to saturate the output of the PID Regulator * * The output of the PI or PID regulator function is capped to the valud of this field. * @see PI_Controller() and PID_Controller() */ int16_t hLowerOutputLimit; /**< @brief Lower limit used to saturate the output of the PID Regulator * * The output of the PI or PID regulator function is floored to the valud of this field. * @see PI_Controller() and PID_Controller() */ uint16_t hKpDivisor; /**< @brief @f$K_{pd}@f$, divisor of the proportional gain * * Used in conjuction with @f$K_{pg}@f$, the proportional gain numerator to allow for obtaining * fractional gain values. * * If #FULL_MISRA_C_COMPLIANCY is not defined the divisor is implemented through * algebrical right shifts to speed up the execution of the controller functions. Only in this * case does this parameter specify the number of right shifts to be executed. */ uint16_t hKiDivisor; /**< @brief @f$K_{id}@f$, divisor of the integral gain gain * * Used in conjuction with @f$K_{ig}@f$, the integral gain numerator to allow for obtaining * fractional gain values. * * If #FULL_MISRA_C_COMPLIANCY is not defined the divisor is implemented through * algebrical right shifts to speed up the execution of the controller functions. Only in this * case does this parameter specify the number of right shifts to be executed. */ uint16_t hKpDivisorPOW2; /**< @brief @f$K_{pd}@f$, divisor of the proportional gain, expressed as power of 2. * * E.g. if the divisor of the proportional gain is 512, the value of this field is 9 * as @f$2^9 = 512@f$ */ uint16_t hKiDivisorPOW2; /**< @brief @f$K_{id}@f$, divisor of the integral gain, expressed as power of 2. * * E.g. if the divisor of the integral gain is 512, the value of this field is 9 * as @f$2^9 = 512@f$ */ int16_t hDefKdGain; /**< @brief Default value of @f$K_{dg}@f$, the numerator of the derivative gain. * * The value of this field is copied into #hKdGain when the component is initialized. * @see PID_HandleInit(). */ int16_t hKdGain; /**< @brief @f$K_{dg}@f$, numerator of the derivative gain of the PID Regulator component */ uint16_t hKdDivisor; /**< @brief @f$K_{dd}@f$, divisor of the derivative gain gain * * Used in conjuction with @f$K_{dg}@f$, the derivative gain numerator to allow for obtaining * fractional gain values. * * If #FULL_MISRA_C_COMPLIANCY is not defined the divisor is implemented through * algebrical right shifts to speed up the execution of the controller functions. Only in this * case does this parameter specify the number of right shifts to be executed. */ uint16_t hKdDivisorPOW2; /**< @brief @f$K_{dd}@f$, divisor of the derivative gain, expressed as power of 2. * * E.g. if the divisor of the integral gain is 512, the value of this field is 9 * as @f$2^9 = 512@f$ */ int32_t wPrevProcessVarError; /**< @brief previous process variable used by the derivative part of the PID component * * This value is updated on each call to the PI_Controller() or PID_Controller() functions. * * This field is reset to 0 when the component is initialized. * @see PID_HandleInit(). */ } PID_Handle_t; /* Initializes the handle of a PID component */ void PID_HandleInit(PID_Handle_t *pHandle); /* Sets the numerator of Kp, the proportional gain of a PID component */ void PID_SetKP(PID_Handle_t *pHandle, int16_t hKpGain); /* Updates the numerator of Ki, the integral gain of a PID component */ void PID_SetKI(PID_Handle_t *pHandle, int16_t hKiGain); /* Returns the numerator of Kp, the proportional gain of a PID component */ int16_t PID_GetKP(PID_Handle_t *pHandle); /* Returns the numerator of Ki, the integral gain of a PID component */ int16_t PID_GetKI(PID_Handle_t *pHandle); /* Returns the default value of the numerator of Kp, the proportional gain of a PID component */ int16_t PID_GetDefaultKP(PID_Handle_t *pHandle); /* Returns the default value of the numerator of Ki, the integral gain of a PID component */ int16_t PID_GetDefaultKI(PID_Handle_t *pHandle); /* Sets the value of the integral term of a PID component */ void PID_SetIntegralTerm(PID_Handle_t *pHandle, int32_t wIntegralTermValue); /* Returns the divisor of Kp, the proportional gain of a PID component */ uint16_t PID_GetKPDivisor(PID_Handle_t *pHandle); /* Returns the power of two that makes the divisor of Kp, the proportional gain of a PID component */ uint16_t PID_GetKPDivisorPOW2(PID_Handle_t *pHandle); /* Sets the power of two that makes the divisor of Kp, the proportional gain of a PID component */ void PID_SetKPDivisorPOW2(PID_Handle_t *pHandle, uint16_t hKpDivisorPOW2); /* Returns the divisor of Ki, the integral gain of a PID component */ uint16_t PID_GetKIDivisor(PID_Handle_t *pHandle); /* Returns the power of two that makes the divisor of Ki, the inegral gain of a PID component */ uint16_t PID_GetKIDivisorPOW2(PID_Handle_t * pHandle); /* Sets the power of two that makes the divisor of Ki, the integral gain of a PID component */ void PID_SetKIDivisorPOW2(PID_Handle_t *pHandle, uint16_t hKiDivisorPOW2); /* Sets the lower limit of the integral term of a PID component */ void PID_SetLowerIntegralTermLimit(PID_Handle_t *pHandle, int32_t wLowerLimit); /* Sets the upper limit of the integral term of a PID component */ void PID_SetUpperIntegralTermLimit(PID_Handle_t *pHandle, int32_t wUpperLimit); /* Sets the lower output limit of a PID component */ void PID_SetLowerOutputLimit(PID_Handle_t *pHandle, int16_t hLowerLimit); /* Sets the upper output limit of a PID component */ void PID_SetUpperOutputLimit(PID_Handle_t *pHandle, int16_t hUpperLimit); /* Sets the value of the previous process error of a PID component */ void PID_SetPrevError(PID_Handle_t *pHandle, int32_t wPrevProcessVarError); /* Sets the numerator of Kd, the derivative gain of a PID component */ void PID_SetKD(PID_Handle_t *pHandle, int16_t hKdGain); /* Returns the numerator of Kd, the derivativz gain of a PID component */ int16_t PID_GetKD(PID_Handle_t *pHandle); /* Returns the divisor of Kd, the derivative gain of a PID component */ uint16_t PID_GetKDDivisor(PID_Handle_t *pHandle); /* Returns the power of two that makes the divisor of Kd, the derivative gain of a PID component */ uint16_t PID_GetKDDivisorPOW2(PID_Handle_t *pHandle); /* Sets the power of two that makes the divisor of Kd, the derivative gain of a PID component */ void PID_SetKDDivisorPOW2(PID_Handle_t *pHandle, uint16_t hKdDivisorPOW2); /* * Computes the output of a PI Regulator component, sum of its proportional * and integral terms */ int16_t PI_Controller(PID_Handle_t *pHandle, int32_t wProcessVarError); /* * Computes the output of a PID Regulator component, sum of its proportional, * integral and derivative terms */ int16_t PID_Controller(PID_Handle_t *pHandle, int32_t wProcessVarError); /** * @} */ /** * @} */ #endif /*PIDREGULATOR_H*/ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
13,380
C
52.310757
130
0.538939
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/enc_align_ctrl.h
/** ****************************************************************************** * @file enc_align_ctrl.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * Encoder Alignment Control component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup EncAlignCtrl */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef ENCALIGNCTRLCLASS_H #define ENCALIGNCTRLCLASS_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "mc_type.h" #include "speed_torq_ctrl.h" #include "virtual_speed_sensor.h" #include "encoder_speed_pos_fdbk.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup EncAlignCtrl * @{ */ /** * @brief This structure is used to handle an instance of EncAlignCtrl component */ typedef struct { SpeednTorqCtrl_Handle_t *pSTC; /*!< Speed and torque controller object used by EAC. */ VirtualSpeedSensor_Handle_t *pVSS; /*!< Virtual speed sensor object used by EAC. */ ENCODER_Handle_t *pENC; /*!< Encoder object used by EAC. */ uint16_t hRemainingTicks; /*!< Number of tick events remaining to complete the alignment. */ bool EncAligned; /*!< This flag is true if the encoder has been aligned at least once, false if has not. */ bool EncRestart; /*!< This flag is used to force a restart of the motor after the encoder alignment. It is true if a restart is programmed otherwise, it is false*/ uint16_t hEACFrequencyHz; /*!< EAC_Exec() function calling frequency, in Hz. */ int16_t hFinalTorque; /*!< Motor torque reference imposed by STC at the end of programmed alignment. This value actually is the Iq current expressed in digit. */ int16_t hElAngle; /*!< Electrical angle of programmed alignment expressed in s16degrees [(rotor angle unit)](measurement_units.md). */ uint16_t hDurationms; /*!< Duration of the programmed alignment expressed in milliseconds.*/ uint8_t bElToMecRatio; /*!< Coefficient used to transform electrical to mechanical quantities and vice-versa. It usually coincides with motor pole pairs number. */ } EncAlign_Handle_t; /* Exported functions ------------------------------------------------------- */ /* Function used to initialize an instance of the EncAlignCtrl component */ void EAC_Init(EncAlign_Handle_t *pHandle, SpeednTorqCtrl_Handle_t *pSTC, VirtualSpeedSensor_Handle_t *pVSS, ENCODER_Handle_t *pENC); /* Function used to start the encoder alignment procedure */ void EAC_StartAlignment(EncAlign_Handle_t *pHandle); /* Function used to execute the encoder alignment controller */ bool EAC_Exec(EncAlign_Handle_t *pHandle); /* It returns true if the encoder has been aligned at least one time */ bool EAC_IsAligned(EncAlign_Handle_t *pHandle); /* It sets a restart after an encoder alignment */ void EAC_SetRestartState(EncAlign_Handle_t *pHandle, bool restart); /* Returns true if a restart after an encoder alignment has been requested */ bool EAC_GetRestartState(EncAlign_Handle_t *pHandle); /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* ENCALIGNCTRLCLASS_H */ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
4,259
C
39.571428
118
0.576192
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/datalog.h
/** ****************************************************************************** * @file datalog.h * @author Piak Electronic Design B.V. * @brief This file is part of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 Piak Electronic Design B.V. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** */ /* datalog.h */ #ifndef __DATALOG_H #define __DATALOG_H #include <stddef.h> #include <stdint.h> #include <stdbool.h> #define DATALOG_NUM_CHANNELS (7) /* Number of allocated channels */ #define DATALOG_SAMPLE_COUNT (60) /* Number of samples */ /* Max payload = 128 bytes */ #define DATALOG_SAMPLE_TYPE int16_t /* Type of the samples */ typedef enum _DATALOG_TRIGGER_STATE_e_ { DATALOG_TRIGGER_STATE_Idle, DATALOG_TRIGGER_STATE_Armed, DATALOG_TRIGGER_STATE_Running, DATALOG_TRIGGER_STATE_Holding, } DATALOG_TRIGGER_STATE_e; typedef enum _DATALOG_TRIGGER_EDGE_DIRECTION_e_ { DATALOG_TRIGGER_EDGE_DIRECTION_Rising, DATALOG_TRIGGER_EDGE_DIRECTION_Falling, DATALOG_TRIGGER_EDGE_DIRECTION_Both, } DATALOG_TRIGGER_EDGE_DIRECTION_e; typedef enum _DATALOG_TRIGGER_MODE_e_ { DATALOG_TRIGGER_MODE_Normal, /* Log starts when triggered, hold when done */ DATALOG_TRIGGER_MODE_Rolling, /* Keep sampling to memory, do not hold */ } DATALOG_TRIGGER_MODE_e; typedef struct _DATALOG_TRIGGER_s_ { // Trigger configuration and state int channel; DATALOG_SAMPLE_TYPE level; DATALOG_TRIGGER_MODE_e mode; DATALOG_TRIGGER_STATE_e state; DATALOG_TRIGGER_EDGE_DIRECTION_e edge; uint16_t preTrigger; bool justArmed; } DATALOG_TRIGGER_s; typedef struct _DATALOG_CHANNEL_s_ { bool bEnabled; void* pSource; DATALOG_SAMPLE_TYPE samples[DATALOG_SAMPLE_COUNT]; DATALOG_SAMPLE_TYPE currentSample; DATALOG_SAMPLE_TYPE lastSample; } DATALOG_CHANNEL_s; typedef enum _DATALOG_STATE_e_ { DATALOG_STATE_Idle, /* Not armed, will not start logging */ DATALOG_STATE_Armed, /* Armed, will start logging when triggered */ DATALOG_STATE_Running, /* Actively logging */ DATALOG_STATE_Holding, /* Holding, waiting for client to download data, then release */ } DATALOG_STATE_e; typedef enum _DATALOG_COMMAND_e_ { DATALOG_COMMAND_None, /* No command at present */ DATALOG_COMMAND_Arm, /* Release from Holding if holding, Arm trigger for next cycle */ DATALOG_COMMAND_Stop, /* stop datalog */ } DATALOG_COMMAND_e; typedef struct _DATALOG_Obj_ { uint16_t nextSampleIdx; uint16_t endSampleIdx; uint16_t dataStartIdx; uint16_t triggerIdx; DATALOG_STATE_e state; DATALOG_COMMAND_e command; DATALOG_TRIGGER_s trigger; DATALOG_CHANNEL_s channel[DATALOG_NUM_CHANNELS]; uint16_t downsample; uint16_t downsamplecounter; /* Debug control */ bool bClear; bool bArmTrigger; bool bClearHold; } DATALOG_Obj; typedef DATALOG_Obj* DATALOG_Handle; DATALOG_Handle DATALOG_init(void* pMemory, const size_t numBytes); void DATALOG_setup(DATALOG_Handle handle); void DATALOG_run(DATALOG_Handle handle); void DATALOG_setChannel(DATALOG_Handle handle, uint16_t channel, DATALOG_SAMPLE_TYPE* pSample); void DATALOG_setCommand(DATALOG_Handle handle, const DATALOG_COMMAND_e command); void DATALOG_getChannelBuffer(DATALOG_Handle handle, const int channel, DATALOG_SAMPLE_TYPE** ppBuffer, uint16_t* pSizeBytes); #endif /* __DATALOG_H */ /* end of datalog.h */ /************************ (C) COPYRIGHT 2023 Piak Electronic Design B.V. *****END OF FILE****/
3,953
C
27.652174
126
0.657981
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/cordic_defs.h
/** ****************************************************************************** * @file cordic_defs.h * @author Piak Electronic Design B.V. * @brief This file is part of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 Piak Electronic Design B.V. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** */ /* cordic_defs.h */ /* Reduced definition of cordic module registers, based on LL driver */ #ifndef _CORDIC_DEFS_H_ #define _CORDIC_DEFS_H_ /* Register macros from stm32g4xx.h */ /** @addtogroup Exported_macros * @{ */ #define SET_BIT(REG, BIT) ((REG) |= (BIT)) #define CLEAR_BIT(REG, BIT) ((REG) &= ~(BIT)) #define READ_BIT(REG, BIT) ((REG) & (BIT)) #define CLEAR_REG(REG) ((REG) = (0x0)) #define WRITE_REG(REG, VAL) ((REG) = (VAL)) #define READ_REG(REG) ((REG)) #define MODIFY_REG(REG, CLEARMASK, SETMASK) WRITE_REG((REG), (((READ_REG(REG)) & (~(CLEARMASK))) | (SETMASK))) #define POSITION_VAL(VAL) (__CLZ(__RBIT(VAL))) /* from core_cm4.h */ #define __IO volatile /*!< Defines 'read / write' permissions */ /* CORDIC from stm32g431xx.h */ /******************************************************************************/ /* */ /* CORDIC calculation unit */ /* */ /******************************************************************************/ /******************* Bit definition for CORDIC_CSR register *****************/ #define CORDIC_CSR_FUNC_Pos (0U) #define CORDIC_CSR_FUNC_Msk (0xFUL << CORDIC_CSR_FUNC_Pos) /*!< 0x0000000F */ #define CORDIC_CSR_FUNC CORDIC_CSR_FUNC_Msk /*!< Function */ #define CORDIC_CSR_FUNC_0 (0x1UL << CORDIC_CSR_FUNC_Pos) /*!< 0x00000001 */ #define CORDIC_CSR_FUNC_1 (0x2UL << CORDIC_CSR_FUNC_Pos) /*!< 0x00000002 */ #define CORDIC_CSR_FUNC_2 (0x4UL << CORDIC_CSR_FUNC_Pos) /*!< 0x00000004 */ #define CORDIC_CSR_FUNC_3 (0x8UL << CORDIC_CSR_FUNC_Pos) /*!< 0x00000008 */ #define CORDIC_CSR_PRECISION_Pos (4U) #define CORDIC_CSR_PRECISION_Msk (0xFUL << CORDIC_CSR_PRECISION_Pos) /*!< 0x000000F0 */ #define CORDIC_CSR_PRECISION CORDIC_CSR_PRECISION_Msk /*!< Precision */ #define CORDIC_CSR_PRECISION_0 (0x1UL << CORDIC_CSR_PRECISION_Pos) /*!< 0x00000010 */ #define CORDIC_CSR_PRECISION_1 (0x2UL << CORDIC_CSR_PRECISION_Pos) /*!< 0x00000020 */ #define CORDIC_CSR_PRECISION_2 (0x4UL << CORDIC_CSR_PRECISION_Pos) /*!< 0x00000040 */ #define CORDIC_CSR_PRECISION_3 (0x8UL << CORDIC_CSR_PRECISION_Pos) /*!< 0x00000080 */ #define CORDIC_CSR_SCALE_Pos (8U) #define CORDIC_CSR_SCALE_Msk (0x7UL << CORDIC_CSR_SCALE_Pos) /*!< 0x00000700 */ #define CORDIC_CSR_SCALE CORDIC_CSR_SCALE_Msk /*!< Scaling factor */ #define CORDIC_CSR_SCALE_0 (0x1UL << CORDIC_CSR_SCALE_Pos) /*!< 0x00000100 */ #define CORDIC_CSR_SCALE_1 (0x2UL << CORDIC_CSR_SCALE_Pos) /*!< 0x00000200 */ #define CORDIC_CSR_SCALE_2 (0x4UL << CORDIC_CSR_SCALE_Pos) /*!< 0x00000400 */ #define CORDIC_CSR_IEN_Pos (16U) #define CORDIC_CSR_IEN_Msk (0x1UL << CORDIC_CSR_IEN_Pos) /*!< 0x00010000 */ #define CORDIC_CSR_IEN CORDIC_CSR_IEN_Msk /*!< Interrupt Enable */ #define CORDIC_CSR_DMAREN_Pos (17U) #define CORDIC_CSR_DMAREN_Msk (0x1UL << CORDIC_CSR_DMAREN_Pos) /*!< 0x00020000 */ #define CORDIC_CSR_DMAREN CORDIC_CSR_DMAREN_Msk /*!< DMA Read channel Enable */ #define CORDIC_CSR_DMAWEN_Pos (18U) #define CORDIC_CSR_DMAWEN_Msk (0x1UL << CORDIC_CSR_DMAWEN_Pos) /*!< 0x00040000 */ #define CORDIC_CSR_DMAWEN CORDIC_CSR_DMAWEN_Msk /*!< DMA Write channel Enable */ #define CORDIC_CSR_NRES_Pos (19U) #define CORDIC_CSR_NRES_Msk (0x1UL << CORDIC_CSR_NRES_Pos) /*!< 0x00080000 */ #define CORDIC_CSR_NRES CORDIC_CSR_NRES_Msk /*!< Number of results in WDATA register */ #define CORDIC_CSR_NARGS_Pos (20U) #define CORDIC_CSR_NARGS_Msk (0x1UL << CORDIC_CSR_NARGS_Pos) /*!< 0x00100000 */ #define CORDIC_CSR_NARGS CORDIC_CSR_NARGS_Msk /*!< Number of arguments in RDATA register */ #define CORDIC_CSR_RESSIZE_Pos (21U) #define CORDIC_CSR_RESSIZE_Msk (0x1UL << CORDIC_CSR_RESSIZE_Pos) /*!< 0x00200000 */ #define CORDIC_CSR_RESSIZE CORDIC_CSR_RESSIZE_Msk /*!< Width of output data */ #define CORDIC_CSR_ARGSIZE_Pos (22U) #define CORDIC_CSR_ARGSIZE_Msk (0x1UL << CORDIC_CSR_ARGSIZE_Pos) /*!< 0x00400000 */ #define CORDIC_CSR_ARGSIZE CORDIC_CSR_ARGSIZE_Msk /*!< Width of input data */ #define CORDIC_CSR_RRDY_Pos (31U) #define CORDIC_CSR_RRDY_Msk (0x1UL << CORDIC_CSR_RRDY_Pos) /*!< 0x80000000 */ #define CORDIC_CSR_RRDY CORDIC_CSR_RRDY_Msk /*!< Result Ready Flag */ /******************* Bit definition for CORDIC_WDATA register ***************/ #define CORDIC_WDATA_ARG_Pos (0U) #define CORDIC_WDATA_ARG_Msk (0xFFFFFFFFUL << CORDIC_WDATA_ARG_Pos) /*!< 0xFFFFFFFF */ #define CORDIC_WDATA_ARG CORDIC_WDATA_ARG_Msk /*!< Input Argument */ /******************* Bit definition for CORDIC_RDATA register ***************/ #define CORDIC_RDATA_RES_Pos (0U) #define CORDIC_RDATA_RES_Msk (0xFFFFFFFFUL << CORDIC_RDATA_RES_Pos) /*!< 0xFFFFFFFF */ #define CORDIC_RDATA_RES CORDIC_RDATA_RES_Msk /*!< Output Result */ typedef struct { __IO uint32_t CSR; /*!< CORDIC control and status register, Address offset: 0x00 */ __IO uint32_t WDATA; /*!< CORDIC argument register, Address offset: 0x04 */ __IO uint32_t RDATA; /*!< CORDIC result register, Address offset: 0x08 */ } CORDIC_Local_TypeDef; #define LCORDIC ((CORDIC_Local_TypeDef *) (0x40000000UL + 0x00020000UL + 0x0C00UL)) #define HAL_IS_BIT_CLR(REG, BIT) (((REG) & (BIT)) == 0U) /* -------------------------------------------- */ #define __STATIC_INLINE static inline #define LL_CORDIC_FLAG_RRDY CORDIC_CSR_RRDY #define LL_CORDIC_IT_IEN CORDIC_CSR_IEN /*!< Result Ready interrupt enable */ #define LL_CORDIC_FUNCTION_COSINE (0x00000000U) /*!< Cosine */ #define LL_CORDIC_FUNCTION_SINE ((uint32_t)(CORDIC_CSR_FUNC_0)) /*!< Sine */ #define LL_CORDIC_FUNCTION_PHASE ((uint32_t)(CORDIC_CSR_FUNC_1)) /*!< Phase */ #define LL_CORDIC_FUNCTION_MODULUS ((uint32_t)(CORDIC_CSR_FUNC_1 | CORDIC_CSR_FUNC_0)) /*!< Modulus */ #define LL_CORDIC_FUNCTION_ARCTANGENT ((uint32_t)(CORDIC_CSR_FUNC_2)) /*!< Arctangent */ #define LL_CORDIC_FUNCTION_HCOSINE ((uint32_t)(CORDIC_CSR_FUNC_2 | CORDIC_CSR_FUNC_0)) /*!< Hyperbolic Cosine */ #define LL_CORDIC_FUNCTION_HSINE ((uint32_t)(CORDIC_CSR_FUNC_2 | CORDIC_CSR_FUNC_1)) /*!< Hyperbolic Sine */ #define LL_CORDIC_FUNCTION_HARCTANGENT ((uint32_t)(CORDIC_CSR_FUNC_2 | CORDIC_CSR_FUNC_1 | CORDIC_CSR_FUNC_0))/*!< Hyperbolic Arctangent */ #define LL_CORDIC_FUNCTION_NATURALLOG ((uint32_t)(CORDIC_CSR_FUNC_3)) /*!< Natural Logarithm */ #define LL_CORDIC_FUNCTION_SQUAREROOT ((uint32_t)(CORDIC_CSR_FUNC_3 | CORDIC_CSR_FUNC_0)) /*!< Square Root */ #define LL_CORDIC_PRECISION_1CYCLE ((uint32_t)(CORDIC_CSR_PRECISION_0)) #define LL_CORDIC_PRECISION_2CYCLES ((uint32_t)(CORDIC_CSR_PRECISION_1)) #define LL_CORDIC_PRECISION_3CYCLES ((uint32_t)(CORDIC_CSR_PRECISION_1 | CORDIC_CSR_PRECISION_0)) #define LL_CORDIC_PRECISION_4CYCLES ((uint32_t)(CORDIC_CSR_PRECISION_2)) #define LL_CORDIC_PRECISION_5CYCLES ((uint32_t)(CORDIC_CSR_PRECISION_2 | CORDIC_CSR_PRECISION_0)) #define LL_CORDIC_PRECISION_6CYCLES ((uint32_t)(CORDIC_CSR_PRECISION_2 | CORDIC_CSR_PRECISION_1)) #define LL_CORDIC_PRECISION_7CYCLES ((uint32_t)(CORDIC_CSR_PRECISION_2 | CORDIC_CSR_PRECISION_1 | CORDIC_CSR_PRECISION_0)) #define LL_CORDIC_PRECISION_8CYCLES ((uint32_t)(CORDIC_CSR_PRECISION_3)) #define LL_CORDIC_PRECISION_9CYCLES ((uint32_t)(CORDIC_CSR_PRECISION_3 | CORDIC_CSR_PRECISION_0)) #define LL_CORDIC_PRECISION_10CYCLES ((uint32_t)(CORDIC_CSR_PRECISION_3 | CORDIC_CSR_PRECISION_1)) #define LL_CORDIC_PRECISION_11CYCLES ((uint32_t)(CORDIC_CSR_PRECISION_3 | CORDIC_CSR_PRECISION_1 | CORDIC_CSR_PRECISION_0)) #define LL_CORDIC_PRECISION_12CYCLES ((uint32_t)(CORDIC_CSR_PRECISION_3 | CORDIC_CSR_PRECISION_2)) #define LL_CORDIC_PRECISION_13CYCLES ((uint32_t)(CORDIC_CSR_PRECISION_3 | CORDIC_CSR_PRECISION_2 | CORDIC_CSR_PRECISION_0)) #define LL_CORDIC_PRECISION_14CYCLES ((uint32_t)(CORDIC_CSR_PRECISION_3 | CORDIC_CSR_PRECISION_2 | CORDIC_CSR_PRECISION_1)) #define LL_CORDIC_PRECISION_15CYCLES ((uint32_t)(CORDIC_CSR_PRECISION_3 | CORDIC_CSR_PRECISION_2 | CORDIC_CSR_PRECISION_1 | CORDIC_CSR_PRECISION_0)) #define LL_CORDIC_SCALE_0 (0x00000000U) #define LL_CORDIC_SCALE_1 ((uint32_t)(CORDIC_CSR_SCALE_0)) #define LL_CORDIC_SCALE_2 ((uint32_t)(CORDIC_CSR_SCALE_1)) #define LL_CORDIC_SCALE_3 ((uint32_t)(CORDIC_CSR_SCALE_1 | CORDIC_CSR_SCALE_0)) #define LL_CORDIC_SCALE_4 ((uint32_t)(CORDIC_CSR_SCALE_2)) #define LL_CORDIC_SCALE_5 ((uint32_t)(CORDIC_CSR_SCALE_2 | CORDIC_CSR_SCALE_0)) #define LL_CORDIC_SCALE_6 ((uint32_t)(CORDIC_CSR_SCALE_2 | CORDIC_CSR_SCALE_1)) #define LL_CORDIC_SCALE_7 ((uint32_t)(CORDIC_CSR_SCALE_2 | CORDIC_CSR_SCALE_1 | CORDIC_CSR_SCALE_0)) #define LL_CORDIC_NBWRITE_1 (0x00000000U) /*!< One 32-bits write containing either only one 32-bit data input (Q1.31 format), or two 16-bit data input (Q1.15 format) packed in one 32 bits Data */ #define LL_CORDIC_NBWRITE_2 CORDIC_CSR_NARGS /*!< Two 32-bit write containing two 32-bits data input (Q1.31 format) */ #define LL_CORDIC_NBREAD_1 (0x00000000U) /*!< One 32-bits read containing either only one data output (Q1.15 format) packed in one 32 bits Data */ #define LL_CORDIC_NBREAD_2 CORDIC_CSR_NRES /*!< Two 32-bit Data containing two 32-bits data output */ #define LL_CORDIC_INSIZE_32BITS (0x00000000U) /*!< 32 bits input data size (Q1.31 format) */ #define LL_CORDIC_INSIZE_16BITS CORDIC_CSR_ARGSIZE /*!< 16 bits input data size (Q1.15 format) */ #define LL_CORDIC_OUTSIZE_32BITS (0x00000000U) /*!< 32 bits output data size (Q1.31 format) */ #define LL_CORDIC_OUTSIZE_16BITS CORDIC_CSR_RESSIZE /*!< 16 bits output data size (Q1.15 format) */ #define LL_CORDIC_DMA_REG_DATA_IN (0x00000000U) /*!< Get address of input data register */ #define LL_CORDIC_DMA_REG_DATA_OUT (0x00000001U) /*!< Get address of output data register */ #endif /* _CORDIC_DEFS_H_ */ /* end of cordic_defs.h */ /************************ (C) COPYRIGHT 2023 Piak Electronic Design B.V. *****END OF FILE****/
12,750
C
68.677595
154
0.541412
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/mp_one_touch_tuning.h
/** ****************************************************************************** * @file mp_one_touch_tuning.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for * for the One Touch Tuning component ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup OneTouchTuning */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef MP_ONE_TOUCH_TUNING_H #define MP_ONE_TOUCH_TUNING_H /* Includes ------------------------------------------------------------------*/ #include "mc_type.h" #include "pid_regulator.h" #include "sto_pll_speed_pos_fdbk.h" #include "speed_torq_ctrl.h" #include "ramp_ext_mngr.h" /** @addtogroup STM32_PMSM_MC_Library * @{ */ /** @addtogroup OneTouchTuning * @{ */ /** @defgroup OneTouchTuning_class_exported_types OneTouchTuning class exported types * @{ */ /** * @brief Public OneTouchTuning class definition */ /** * @brief OneTouchTuning class parameters definition */ typedef const struct { RampExtMngr_Handle_t rampExtMngrParams; /*!< Ramp manager used by SCC.*/ float fBWdef; /*!< Default bandwidth of speed regulator.*/ float fMeasWin; /*!< Duration of measurement window for speed and current Iq, expressed in seconds.*/ uint8_t bPolesPairs; /*!< Number of motor poles pairs.*/ uint16_t hMaxPositiveTorque;/*!< Maximum positive value of motor torque. This value represents actually the maximum Iq current expressed in digit.*/ float fCurrtRegStabTimeSec; /*!< Current regulation stabilization time in seconds.*/ float fOttLowSpeedPerc; /*!< OTT lower speed percentage.*/ float fOttHighSpeedPerc; /*!< OTT higher speed percentage.*/ float fSpeedStabTimeSec; /*!< Speed stabilization time in seconds.*/ float fTimeOutSec; /*!< Timeout for speed stabilization.*/ float fSpeedMargin; /*!< Speed margin percentage to validate speed ctrl.*/ int32_t wNominalSpeed; /*!< Nominal speed set by the user expressed in RPM.*/ float spdKp; /*!< Initial KP factor of the speed regulator to be tuned.*/ float spdKi; /*!< Initial KI factor of the speed regulator to be tuned.*/ float spdKs; /*!< Initial antiwindup factor of the speed regulator to be tuned.*/ float fRshunt; /*!< Value of shunt resistor.*/ float fAmplificationGain; /*!< Current sensing amplification gain.*/ } OTT_Params_t, *pOTT_Params_t; /** * @brief OTT_State_t enum type definition, it lists all the possible OTT state machine states. */ typedef enum { OTT_IDLE, OTT_NOMINAL_SPEED_DET, OTT_DYNAMICS_DET_RAMP_DOWN, OTT_DYNAMICS_DET_SET_TORQUE, OTT_DYNAMICS_DETECTION, OTT_RAMP_DOWN_H_SPEED, OTT_H_SPEED_TEST, OTT_RAMP_DOWN_L_SPEED, OTT_L_SPEED_TEST, OTT_TORQUE_STEP, OTT_END } OTT_State_t; /** * @brief OneTouchTuning class members definition */ typedef struct { SpeednPosFdbk_Handle_t *pSpeedSensor; /*!< Related speed sensor used. */ pFOCVars_t pFOCVars; /*!< Related structure of FOC vars.*/ PID_Handle_t *pPIDSpeed; /*!< Related speed controller used. */ SpeednTorqCtrl_Handle_t *pSTC; /*!< Speed and torque controller used.*/ RampExtMngr_Handle_t *pREMng; /*!< Ramp manager used.*/ int16_t hFDetIq[2]; /*!< Array used to store Iq measurements done during F estimation.*/ float fFDetOmega[2]; /*!< Array used to store Omega values during F estimation.*/ float fF; /*!< Stores the last F estimation.*/ float fOmegaTh; /*!< Stores the last omega threshold.*/ float fTau; /*!< Stores the last computed mechanical time constant.*/ float fJ; /*!< Stores the last J estimation.*/ float fBW; /*!< Bandwidth of speed regulator.*/ OTT_State_t bState; /*!< State macchine state.*/ int32_t wIqsum; /*!< Sum of measured Iq.*/ int32_t wSpeed01Hzsum; /*!< Sum of average mechanical speed.*/ uint16_t hIqCnt; /*!< Counter for Iq acquisitions.*/ int32_t wCnt; /*!< 32bit counter.*/ int16_t hSpeed01HzMean; /*!< Mean value of mechanical speed.*/ int16_t hSpeed01HzDelta; /*!< Delta speed between mechanical speed.*/ uint16_t hCurRegStabCnt; /*!< Stabilization counter.*/ uint16_t hJdetCnt; /*!< Counter to measure the mechanical time constant.*/ float fEstNominalSpdRPM; /*!< Estimated nominal speed.*/ int16_t hIqNominal; /*!< Current measured at nominal speed steady state.*/ int16_t hIqAcc; /*!< Current used to accelerate the motor.*/ int16_t hTargetLRPM; /*!< Lower speed used for OTT.*/ int16_t hTargetHRPM; /*!< Higher speed used for OTT.*/ uint16_t hMeasWinTicks; /*!< Number of ticks of the measurement window.*/ uint16_t hCurRegStabTks; /*!< Number of ticks for current regulation stabilization time.*/ uint16_t hSpeedStabTks; /*!< Number of ticks for speed stabilization time.*/ bool bPI_Tuned; /*!< True is PI is tuned, false otherwise.*/ float fKp; /*!< Computed Kp.*/ float fKi; /*!< Computed Ki.*/ int8_t stabCnt; /*!< Stabilization counter.*/ float fSpeed; /*!< Internal target reference.*/ uint16_t hTimeOutTks; /*!< Number of tick for timeout.*/ uint8_t bPolesPairs; /*!< Motor poles pairs.*/ uint16_t hMaxPositiveTorque;/*!< Maximum positive value of motor torque. This value represents actually the maximum Iq current expressed in digit.*/ float fRPMTh; /*!< Speed threshold for mecchanical constant time estimation.*/ int32_t wNominalSpeed; /*!< Nominal speed set by the user expressed in RPM.*/ float spdKp; /*!< KP factor of the speed regulator to be tuned.*/ float spdKi; /*!< KI factor of the speed regulator to be tuned.*/ float spdKs; /*!< Antiwindup factor of the speed regulator to be tuned.*/ float spdIntTerm; /*!< Integral term of the speed regulator to be tuned.*/ float spdAntiWindTerm; /*!< Antiwindup term of the speed regulator to be tuned.*/ float fKe; /*!< Stores the last Ke estimation.*/ pOTT_Params_t pOTT_Params_str; /**< OTT parameters */ } OTT_Handle_t; /** * @} */ /** * @brief Initializes all the object variables, usually it has to be called * once right after object creation. * @param this related object of class COTT. * @param pOTT_Init pointer to the OTT init structure. * @retval none. */ void OTT_Init(OTT_Handle_t *pHandle); /** * @brief It should be called before each motor restart. It initialize * internal state of OTT. * @param this related object of class COTT. * @retval none. */ void OTT_Clear(OTT_Handle_t *pHandle); /** * @brief It should be called at MF and execute the OTT algorithm. * @param this related object of class COTT. * @retval none. */ void OTT_MF(OTT_Handle_t *pHandle); /** * @brief It should be called in START_RUN state. It begins the OTT procedure. * @param this related object of class COTT. * @retval none. */ void OTT_SR(OTT_Handle_t *pHandle); /** * @brief Call this method before start motor to force new OTT procedure. * @param this related object of class COTT. * @retval none. */ void OTT_ForceTuning(OTT_Handle_t *pHandle); /** * @brief It returns the nominal speed estimated by OTT. * @param this related object of class COTT. * @retval uint32_t It returns the nominal speed estimated by OTT, it is a * floating point number codified into a 32bit integer. */ uint32_t OTT_GetNominalSpeed(OTT_Handle_t *pHandle); /** * @brief It returns the number of states of OTT. * @param this related object of class COTT. * @retval uint8_t It returns the number of states of Selfcommissioning procedure. */ uint8_t OTT_GetSteps(OTT_Handle_t *pHandle); /** * @brief It returns the state of OTT. * @param this related object of class COTT. * @retval uint8_t It returns the state of OTT. */ uint8_t OTT_GetState(OTT_Handle_t *pHandle); /** * @brief It returns true if OTT procedure has been completed, false otherwise. * @param this related object of class COTT. * @retval bool It returns true if OTT procedure has been completed, false otherwise. */ bool OTT_IsSpeedPITuned(OTT_Handle_t *pHandle); /** * @brief It returns the nominal speed estimated by OTT in RPM. * @param this related object of class COTT. * @retval float It returns the nominal speed in RPM estimated by OTT. */ float OTT_fGetNominalSpeedRPM(OTT_Handle_t *pHandle); /** * @brief Sets the number of motor poles pairs. * @param this related object of class COTT. * @param bPP Number of motor poles pairs to be set. * @retval none */ void OTT_SetPolesPairs(OTT_Handle_t *pHandle, uint8_t bPP); /** * @brief Change the nominal current. * @param this related object of class COTT. * @param hNominalCurrent This value represents actually the maximum Iq current expressed in digit. * @retval none */ void OTT_SetNominalCurrent(OTT_Handle_t *pHandle, uint16_t hNominalCurrent); /** * @brief Change the speed regulator bandwidth. * @param this related object of class COTT. * @param fBW Current regulator bandwidth espressed in rad/s. * @retval none */ void OTT_SetSpeedRegulatorBandwidth(OTT_Handle_t *pHandle, float fBW); /** * @brief Get the speed regulator bandwidth. * @param this related object of class COTT. * @retval float Current regulator bandwidth espressed in rad/s. */ float OTT_GetSpeedRegulatorBandwidth(OTT_Handle_t *pHandle); /** * @brief Get the measured inertia of the motor. * @param this related object of class COTT. * @retval float Measured inertia of the motor expressed in Kgm^2. */ float OTT_GetJ(OTT_Handle_t *pHandle); /** * @brief Get the measured friction of the motor. * @param this related object of class COTT. * @retval float Measured friction of the motor expressed in Nms. */ float OTT_GetF(OTT_Handle_t *pHandle); /** * @brief Set the nominal speed according motor datasheet. * This function shall be called before the start * of the MP procedure. * @param this related object of class COTT. * @param wNominalSpeed Nominal speed expressed in RPM. * @retval none */ void OTT_SetNominalSpeed(OTT_Handle_t *pHandle, int32_t wNominalSpeed); /** * @brief Store the Ke measured by the SCC for the OTT purpouses. * @param this related object of class COTT. * @param fKe Last measured Ke. * @retval none */ void OTT_SetKe(OTT_Handle_t *pHandle, float fKe); /** * @brief It should be called before each motor stop. * @param this related object of class COTT. * @retval none. */ void OTT_Stop(OTT_Handle_t *pHandle); /** * @brief Return true if the motor has been already profiled. * @param this related object of class COTT. * @retval bool true if the if the motor has been already profiled, * false otherwise. */ bool OTT_IsMotorAlreadyProfiled(OTT_Handle_t *pHandle); /** * @} */ /** * @} */ #endif /* MP_ONE_TOUCH_TUNING_H */ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
12,153
C
36.054878
98
0.629886
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/demag_mgt.h
/** ****************************************************************************** * @file f0xx_bemf_ADC_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * Sensorless Bemf acquisition with ADC component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup SpeednPosFdbk_Bemf */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef DEMAGMGT_H #define DEMAGMGT_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "speed_ctrl.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup Demag_management * @{ */ /** * @brief This structure is used to handle the data of an instance of the Demagnetization Management component * */ typedef struct { uint16_t PWMCycles; /*!< Counter of the PWM cycles elapsed from the last step change */ uint16_t DemagCounterThreshold; /*!< Number of PWM cycles for phase demagnetization */ uint16_t DemagMinimumSpeedUnit; /*!< Speed threshold for minimum demagnetization time */ uint16_t RevUpDemagSpeedConv; /*!< Convertion factor between speed and demagnetization time */ uint16_t RunDemagSpeedConv; /*!< Open loop convertion factor between speed and demagnetization time during */ uint16_t DemagMinimumThreshold; /*!< Minimum demagnetization time */ uint8_t PWMScaling; } Demag_Handle_t; /* Exported functions --------------------------------------------------------*/ /* It initializes all the object variables. */ void DMG_Init( Demag_Handle_t *pHandle ); /* It resets the ADC status and empties arrays. */ void DMG_Clear( Demag_Handle_t *pHandle ); /* It configures the sensorless parameters for the following step. */ void DMG_IncreaseDemagCounter(Demag_Handle_t *pHandle); /* It configures the sensorless parameters for the following step. */ uint16_t DMG_GetDemagCounter(Demag_Handle_t *pHandle); /* It computes the demagnetization time during revup procedure. */ bool DMG_IsDemagTElapsed(Demag_Handle_t *pHandle ); /* It computes the demagnetization time in closed loop operation.*/ void DMG_CalcRevUpDemagT(Demag_Handle_t *pHandle, SpeednTorqCtrl_Handle_t *pHandleSTC ); /* It computes the demagnetization time in closed loop operation.*/ void DMG_CalcRunDemagT(Demag_Handle_t *pHandle, SpeednTorqCtrl_Handle_t *pHandleSTC ); /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* BEMFADCFDBK_H */ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
3,209
C
33.148936
118
0.608912
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/math_defs.h
/** ****************************************************************************** * @file math_defs.h * @author Piak Electronic Design B.V. * @brief This file is part of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 Piak Electronic Design B.V. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** */ #ifndef _math_defs_h #define _math_defs_h // System includes. #include <stdlib.h> #include <math.h> // Max Cos table _MTL = 2^k. // Actual length = _MTL+1. #define _MTL 128 // Position of binary point. #define _MNB 30 // Cos table. #include "cos_tab_128.h" // Maximum bits of precision. #define _BITS 24 // Maximum number of Cordic iterations. #define _MAXI _BITS+1 // Float DQ structure prototype. typedef struct _DQF { // z = {x + j*y} complex pair. float x, y; // r = |z|, th = atan2(y, x). float r, th, thr; // Cordic consts. float g, K; // pi/2, pi, and 2*pi. float hpi, pi, pi2; // Cordic tables. float atan[_MAXI], gain[_MAXI], conv[_MAXI]; // Cordic precision. int n; } dqf, *DQF; // Int DQ structure prototype. typedef struct _DQI { // z = {x + j*y} complex pair. int x, y; // r = |z|, th = atan2(y, x). int r, th, thr; float rf, thf; // Cordic consts. int g, K; // pi/2, pi, 2*pi and 1. int hpi, pi, pi2, one; // Cordic tables. int atan[_MAXI], gain[_MAXI], conv[_MAXI]; // Cordic & bit precision. int n, b; } dqi, *DQI; // Long DQ structure prototype. typedef struct _DQL { // z = {x + j*y} complex pair. long x, y; // r = |z|, th = atan2(y, x). long long r, th, thr; float rf, thf; // Cordic consts. long long g, K; // pi/2, pi, 2*pi and 1. long long hpi, pi, pi2, one; // Cordic tables. long long atan[_MAXI], gain[_MAXI], conv[_MAXI]; // Cordic & bit precision. int n, b; } dql, *DQL; // Cos, Sin poly size. #define _CSSN 6 // Atan poly size. #define _ATAN 7 // MNB: 2^_MNB. #define _ONEI 1073741824L #define _ZERO 0L // Maximum limit. #define _MPL _ONEI // Float 1.0/6.0 and 2.0/pi. #define _SIXIF 0.166666666f #define _HPIIF 0.636619772f // _MNB: 1.0/6.0 and 2.0/pi. #define _SIXII 178956971L #define _HPIII 683565276L // Float pi/2, pi, and 2*pi. #define _HPIF 1.570796326f #define _PIF 3.141592653f #define _PIF2 6.283185307f // _MNB: pi/2, pi, and 2*pi. #define _HPII 1686629714L #define _PII 3373259427L #define _PII2 6746518853L // Float Cordic convergence & gain factors. #define _CCNF 0.607252935f #define _CGNF 0.858785336f // _MNB: Cordic convergence & gain factors. #define _CCNI 652032874L #define _CGNI 922113734L // cstl[k] = _RNDL(csti[k]*((float) _MPL)). static long _cstl[4*_MTL+2]; // ccsl[k] = _RNDL(ccsf[k]*((float) _MPL)). static long _ccsl[_CSSN] = { 1073741824, -536870908, 44739216, -1491255, 26587, -280 }; // csnl[k] = _RNDL(csnf[k]*((float) _MPL)). static long _csnl[_CSSN] = { 1073741824, -178956970, 8947847, -213040, 2956, -26 }; #define _MAX(x, y) ((x) > (y) ? (x) : (y)) #define _MIN(x, y) ((x) < (y) ? (x) : (y)) #define _SGNF(x) ((float) (((x) >= 0.0f) - ((x) < 0.0f))) #define _SGNI(x) ((int) (((x) >= 0) - ((x) < 0))) // Inline: (float) round((float) x). static inline float _RNDF(float x) { // Round from zero. if (x >= 0.0f) return (float) ((int) (x + 0.5f)); else return (float) ((int) (x - 0.5f)); } // Inline: (int) round((float) x). static inline int _RNDI(float x) { // Round from zero. if (x >= 0.0f) return (int) (x + 0.5f); else return (int) (x - 0.5f); } // Inline: (long) round((float) x). static inline long _RNDL(float x) { // Round from zero. if (x >= 0.0f) return (long) (x + 0.5f); else return (long) (x - 0.5f); } // Inline: (long long) round((float) x). static inline long long _RNDLL(float x) { // Round from zero. if (x >= 0.0f) return (long long) (x + 0.5f); else return (long long) (x - 0.5f); } // Inline: (int) round(log2f((float) m)). static inline int log2i(int m) { // Initialize. int p2 = 0, k = 1; // Find p2, m <= 2^p2. while (k < m) { p2++; k <<= 1; } // Return p2. return p2; } // // Approximate 1/(x-1) for x = 2^k, e.g. for // k = 2, 1/(4-1) = 1/3 = 1/4 + 1/16 + 1/64 + ... // to b bits of precision. // static inline long fracgen(int k, int b) { // long e, z; // Initialize. e = 1L << b; z = 0; // e = 2^-k, z = e + e*e + e*e*e + ... while (e >>= k) z += e; return z; } // Function prototypes. void cos_sin_poly_L(DQL zi); void cos_sin_tabl_L(DQL zi, int m); void cos_sin_tabl_LX(DQL zi, int m); // #endif // End math_defs.h /************************ (C) COPYRIGHT 2023 Piak Electronic Design B.V. *****END OF FILE****/
5,069
C
19.609756
94
0.554942
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/trajectory_ctrl.h
/** ****************************************************************************** * @file trajectory_ctrl.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides all definitions and functions prototypes for the * the Position Control component of the Motor Control SDK. * ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup PositionControl */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef TRAJCTRL_H #define TRAJCTRL_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "mc_type.h" #include "speed_torq_ctrl.h" #include "enc_align_ctrl.h" #define RADTOS16 10430.378350470452725f /* 2^15/Pi */ #ifndef M_PI #define M_PI 3.14159265358979323846f #endif #define Z_ALIGNMENT_DURATION 2.0f /* 2 seconds */ #define Z_ALIGNMENT_NB_ROTATION (2.0f * M_PI) /* 1 turn in 2 seconds allowed to find the "Z" signal */ /** @addtogroup MCSDK * @{ */ /** @addtogroup PositionControl * @{ */ typedef enum { TC_READY_FOR_COMMAND = 0, TC_MOVEMENT_ON_GOING = 1, TC_TARGET_POSITION_REACHED = 2, TC_FOLLOWING_ON_GOING = 3 } PosCtrlStatus_t; typedef enum { TC_AWAITING_FOR_ALIGNMENT = 0, TC_ZERO_ALIGNMENT_START = 1, TC_ALIGNMENT_COMPLETED = 2, TC_ABSOLUTE_ALIGNMENT_NOT_SUPPORTED = 3, /* Encoder sensor without "Z" output signal */ TC_ABSOLUTE_ALIGNMENT_SUPPORTED = 4, TC_ALIGNMENT_ERROR = 5, } AlignStatus_t; /** * @brief Handle of a Position Control component */ typedef struct { float MovementDuration; /**< @brief Total duration of the programmed movement */ float StartingAngle; /**< @brief Current mechanical position */ float FinalAngle; /**< @brief Target mechanical position including start position */ float AngleStep; /**< @brief Target mechanical position */ float SubStep[6]; /**< @brief Sub step interval time of acceleration and deceleration phases */ float SubStepDuration; /**< @brief Sub step time duration of sequence : acceleration / cruise / deceleration */ float ElapseTime; /**< @brief Elapse time during trajectory movement execution */ float SamplingTime; /**< @brief Sampling time at which the movement regulation is called (at 1/MEDIUM_FREQUENCY_TASK_RATE) */ float Jerk; /**< @brief Angular jerk, rate of change of the angular acceleration with respect to time */ float CruiseSpeed; /**< @brief Angular velocity during the time interval after acceleration and before deceleration */ float Acceleration; /**< @brief Angular acceleration in rad/s^2 */ float Omega; /**< @brief Estimated angular speed in rad/s */ float OmegaPrev; /**< @brief Previous estimated angular speed of frame (N-1) */ float Theta; /**< @brief Current angular position */ float ThetaPrev; /**< @brief Angular position of frame (N-1) */ uint8_t ReceivedTh; /**< @brief At startup of follow mode, need to receive two angles to compute the speed and acceleration */ bool PositionControlRegulation; /**< @brief Flag to activate the position control regulation */ bool EncoderAbsoluteAligned; /**< @brief Flag to indicate that absolute zero alignment is done */ int16_t MecAngleOffset; /**< @brief Store rotor mechanical angle offset */ uint32_t TcTick; /**< @brief Tick counter in follow mode */ float SysTickPeriod; /**< @brief Time base of follow mode */ PosCtrlStatus_t PositionCtrlStatus; /**< @brief Trajectory execution status */ AlignStatus_t AlignmentCfg; /**< @brief Indicates that zero index is supported for absolute alignment */ AlignStatus_t AlignmentStatus; /**< @brief Alignment procedure status */ ENCODER_Handle_t *pENC; /**< @brief Pointer on handler of the current instance of the encoder component */ SpeednTorqCtrl_Handle_t *pSTC; /**< @brief Speed and torque controller object used by the Position Regulator */ PID_Handle_t *PIDPosRegulator; /**< @brief PID controller object used by the Position Regulator */ } PosCtrl_Handle_t; /* Exported functions ------------------------------------------------------- */ /* Initializes Trajectory Control component handler */ void TC_Init(PosCtrl_Handle_t *pHandle, PID_Handle_t *pPIDPosReg, SpeednTorqCtrl_Handle_t *pSTC, ENCODER_Handle_t *pENC); /* Configures the trapezoidal speed trajectory */ bool TC_MoveCommand(PosCtrl_Handle_t *pHandle, float startingAngle, float angleStep, float movementDuration); /* Follows an angular position command */ void TC_FollowCommand(PosCtrl_Handle_t *pHandle, float Angle); /* Proceeds on the position control loop */ void TC_PositionRegulation(PosCtrl_Handle_t *pHandle); /* Executes the programmed trajectory movement */ void TC_MoveExecution(PosCtrl_Handle_t *pHandle); /* Updates the angular position */ void TC_FollowExecution(PosCtrl_Handle_t *pHandle); /* Handles the alignment phase at starting before any position commands */ void TC_EncAlignmentCommand(PosCtrl_Handle_t *pHandle); /* Checks if time allowed for movement is completed */ bool TC_RampCompleted(PosCtrl_Handle_t *pHandle); /* Sets the absolute zero mechanical position */ void TC_EncoderReset(PosCtrl_Handle_t *pHandle); /* Returns the current rotor mechanical angle, expressed in radiant */ float TC_GetCurrentPosition(PosCtrl_Handle_t *pHandle); /* Returns the target rotor mechanical angle, expressed in radiant */ float TC_GetTargetPosition(PosCtrl_Handle_t *pHandle); /* Returns the duration used to execute the movement, expressed in seconds */ float TC_GetMoveDuration(PosCtrl_Handle_t *pHandle); /* Returns the status of the position control execution */ PosCtrlStatus_t TC_GetControlPositionStatus(PosCtrl_Handle_t *pHandle); /* Returns the status after the rotor alignment phase */ AlignStatus_t TC_GetAlignmentStatus(PosCtrl_Handle_t *pHandle); /* Increments Tick counter used in follow mode */ void TC_IncTick(PosCtrl_Handle_t *pHandle); /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* TRAJCTRL_H */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
7,387
C
40.740113
120
0.606471
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/open_loop.h
/** ****************************************************************************** * @file open_loop.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * Open Loop component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup OpenLoop */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef OPENLOOPCLASS_H #define OPENLOOPCLASS_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "mc_type.h" #include "virtual_speed_sensor.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup OpenLoop * @{ */ /** * @brief OpenLoop_Handle_t structure used for phases definition */ typedef struct { int16_t hDefaultVoltage; /**< @brief Default Open loop phase voltage. */ bool VFMode; /**< @brief Flag to enable Voltage versus Frequency mode (V/F mode). */ int16_t hVFOffset; /**< @brief Minimum Voltage to apply when frequency is equal to zero. */ int16_t hVFSlope; /**< @brief Slope of V/F curve: Voltage = (hVFSlope)*Frequency + hVFOffset. */ int16_t hVoltage; /**< @brief Current Open loop phase voltage. */ VirtualSpeedSensor_Handle_t *pVSS; /**< @brief Allow access on mechanical speed measured. */ } OpenLoop_Handle_t; /* Exported functions ------------------------------------------------------- */ /* Initializes OpenLoop variables */ void OL_Init(OpenLoop_Handle_t *pHandle, VirtualSpeedSensor_Handle_t *pVSS); /* Sets Vqd according to open loop phase voltage */ qd_t OL_VqdConditioning(const OpenLoop_Handle_t *pHandle); /* Sets new open loop phase voltage */ void OL_UpdateVoltage(OpenLoop_Handle_t *pHandle, int16_t hNewVoltage); /* Gets open loop phase voltage */ int16_t OL_GetVoltage( OpenLoop_Handle_t *pHandle ); /* Computes phase voltage to apply according to average mechanical speed (V/F Mode) */ void OL_Calc(OpenLoop_Handle_t *pHandle); /* Activates of the Voltage versus Frequency mode (V/F mode) */ void OL_VF(OpenLoop_Handle_t *pHandle, bool VFEnabling); /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* OPENLOOPCLASS_H */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
2,968
C
29.927083
115
0.563005
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/sto_speed_pos_fdbk.h
/** ****************************************************************************** * @file sto_speed_pos_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains definitions and functions prototypes common to all * State Observer based Speed & Position Feedback components of the Motor * Control SDK (the CORDIC and PLL implementations). ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup SpeednPosFdbk */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef STO_SPEEDNPOSFDBK_H #define STO_SPEEDNPOSFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "speed_pos_fdbk.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup SpeednPosFdbk * @{ */ /** @brief PWM & Current Sensing component handle type */ typedef struct STO_Handle STO_Handle_t; //cstat !MISRAC2012-Rule-2.4 typedef void (*STO_ForceConvergency1_Cb_t)(STO_Handle_t *pHandle); typedef void (*STO_ForceConvergency2_Cb_t)(STO_Handle_t *pHandle); typedef void (*STO_OtfResetPLL_Cb_t)(STO_Handle_t *pHandle); typedef bool (*STO_SpeedReliabilityCheck_Cb_t)(const STO_Handle_t *pHandle); /** * @brief Handle of the Speed and Position Feedback STO component. * */ struct STO_Handle { SpeednPosFdbk_Handle_t *_Super; /**< @brief Speed and torque component handler. */ STO_ForceConvergency1_Cb_t pFctForceConvergency1; /**< @brief Function to force observer convergence. */ STO_ForceConvergency2_Cb_t pFctForceConvergency2; /**< @brief Function to force observer convergence. */ STO_OtfResetPLL_Cb_t pFctStoOtfResetPLL; /**< @brief Function to reset on the fly start-up. */ STO_SpeedReliabilityCheck_Cb_t pFctSTO_SpeedReliabilityCheck; /**< @brief Function to check the speed reliability. */ }; /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*STO_SPEEDNPOSFDBK_H*/ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
2,727
C
32.679012
129
0.561056
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/polpulse.h
/** ****************************************************************************** * @file polpulse.h * @author Piak Electronic Design B.V. * @brief This file is part of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 Piak Electronic Design B.V. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** */ /* polpulse.h */ #ifndef _POLPULSE_H_ #define _POLPULSE_H_ #include "fixpmath.h" #include <stddef.h> #define POLPULSE_NUMSAMPLES 6 typedef enum _POLPULSE_State_e_ { POLPULSE_STATE_Idle, POLPULSE_STATE_Clear, POLPULSE_STATE_Precalcs, POLPULSE_STATE_WaitDecay, POLPULSE_STATE_WaitPulse, POLPULSE_STATE_Postcalcs, POLPULSE_STATE_PostcalcsComplete, } POLPULSE_State_e; typedef struct _POLPULSE_Params_ { float_t VoltageScale; float_t Ts; float_t Lsd; float_t PulseCurrentGoal_A; uint16_t N; /* Number of pulse-periods */ uint16_t Nd; /* Number of decay-periods */ uint16_t N_Angles; /* Number of directions to pulse in */ } POLPULSE_Params; typedef struct _POLPULSE_Angles_ { /* Planned pulse angle, in per-unit and cos/sin */ FIXP_CosSin_t Phasor; fixp30_t PulseAngle; } POLPULSE_Angles; typedef struct _POLPULSE_Data_ { /* Sampled data */ Currents_Iab_t IabSample; /* Iab at end of pulse */ } POLPULSE_Data; #define POLPULSE_SIZE_WORDS (120) /* Size in words, plus a margin */ typedef struct _POLPULSE_Obj_ { /* Contents of this structure is not public */ uint16_t reserved[POLPULSE_SIZE_WORDS]; } POLPULSE_Obj; typedef POLPULSE_Obj* POLPULSE_Handle; /* Initialization */ POLPULSE_Handle POLPULSE_init(void *pMemory, const size_t size); void POLPULSE_setParams(POLPULSE_Obj *obj, const POLPULSE_Params *pParams); /* Functional */ void POLPULSE_run(POLPULSE_Obj *obj, const Currents_Iab_t *pIab_pu, const Voltages_Uab_t *pUab_pu, const fixp30_t angle); void POLPULSE_runBackground(POLPULSE_Obj *obj, const fixp_t oneoverUdc_pu, const fixp30_t Udc_pu); void POLPULSE_clearTriggerPulse(POLPULSE_Obj *obj); bool POLPULSE_isBusy(POLPULSE_Obj *obj); void POLPULSE_resetState(POLPULSE_Obj *obj); void POLPULSE_stopPulse(POLPULSE_Obj *obj); void POLPULSE_trigger(POLPULSE_Obj *obj); /* Accessors */ fixp30_t POLPULSE_getAngleEstimated(const POLPULSE_Obj *obj); float_t POLPULSE_getCurrentGoal(const POLPULSE_Obj *obj); uint16_t POLPULSE_getDecayPeriods(const POLPULSE_Obj *obj); Duty_Dab_t POLPULSE_getDutyAB(const POLPULSE_Obj *obj); uint16_t POLPULSE_getNumAngles(const POLPULSE_Obj *obj); bool POLPULSE_getOverruleDuty(const POLPULSE_Obj *obj); fixp30_t POLPULSE_getPulseDuty(const POLPULSE_Obj *obj); uint16_t POLPULSE_getPulsePeriods(const POLPULSE_Obj *obj); POLPULSE_State_e POLPULSE_getState(const POLPULSE_Obj *obj); bool POLPULSE_getTriggerPulse(const POLPULSE_Obj *obj); void POLPULSE_setCurrentGoal(POLPULSE_Obj *obj, const float_t currentgoal); void POLPULSE_setDecayPeriods(POLPULSE_Obj *obj, const uint16_t periods); void POLPULSE_setLsd(POLPULSE_Obj *obj, const float_t Lsd); void POLPULSE_setNumAngles(POLPULSE_Obj *obj, const uint16_t angles); void POLPULSE_setPulseDone(POLPULSE_Obj *obj); void POLPULSE_setPulsePeriods(POLPULSE_Obj *obj, const uint16_t periods); #endif /* _POLPULSE_H_ */ /* end of polpulse.h */ /************************ (C) COPYRIGHT 2023 Piak Electronic Design B.V. *****END OF FILE****/
4,028
C
33.435897
121
0.635055
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/mcptl.h
/** ****************************************************************************** * @file mcptl.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware definitions of the Motor control protocol transport layer * of the Motor Control SDK. * ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef MC_TRANSPORT_LAYER #define MC_TRANSPORT_LAYER #include <stdbool.h> #define MCTL_SYNC ( uint8_t )0xAU #define MCTL_ASYNC ( uint8_t )0x9U #define MCTL_SYNC_NOT_EXPECTED 1 typedef struct MCTL_Handle MCTL_Handle_t; //cstat !MISRAC2012-Rule-2.4 typedef bool (* MCTL_GetBuf)(MCTL_Handle_t *pHandle, void **buffer, uint8_t syncAsync); typedef uint8_t (* MCTL_SendPacket)(MCTL_Handle_t *pHandle, void *txBuffer, uint16_t txDataLength, uint8_t syncAsync); typedef uint8_t *(* MCTL_RXpacketProcess)(MCTL_Handle_t *pHandle, uint16_t *packetLength); typedef enum { available = 0, writeLock = 1, pending = 2, readLock = 3, } buff_access_t; typedef struct { uint8_t *buffer; uint16_t length; buff_access_t state; #ifdef MCP_DEBUG_METRICS /* Debug metrics */ uint16_t SentNumber; uint16_t PendingNumber; uint16_t RequestedNumber; /* End of Debug metrics */ #endif } MCTL_Buff_t; struct MCTL_Handle { MCTL_GetBuf fGetBuffer; MCTL_SendPacket fSendPacket; MCTL_RXpacketProcess fRXPacketProcess; uint16_t txSyncMaxPayload; uint16_t txAsyncMaxPayload; bool MCP_PacketAvailable; /* Packet available for Motor control protocol*/ } ; bool MCTL_decodeCRCData(MCTL_Handle_t *pHandle); #endif /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
2,260
C
28.75
118
0.60885
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/pidregdqx_current.h
/** ****************************************************************************** * @file pidregdqx_current.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * PID current regulator of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup PIDRegdqx */ #ifndef _PIDREGDQX_CURRENT_H_ #define _PIDREGDQX_CURRENT_H_ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "fixpmath.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup PIDRegdqx * @{ */ /** * @brief PID current regulator handler definition */ typedef struct _PIDREGDQX_CURRENT_s_ { /* configuration */ FIXP_scaled_t Kp_fps; /*!< @brief Kp gain expressed in fps */ FIXP_scaled_t Wi_fps; /*!< @brief Ki gain expressed in fps */ float KpAlign; /*!< @brief Kp gain applied during Rs DC estmation procedure */ float Kp; /*!< @brief Kp gain */ float current_scale; /*!< @brief current scaling factor */ float voltage_scale; /*!< @brief voltage scaling factor */ float pid_freq_hz; /*!< @brief frequency at which is called the PID regulator */ float freq_scale_hz; /*!< @brief frequecy scaling factor */ float duty_limit; /*!< @brief duty cycle limit */ /* limits */ fixp24_t maxModulation_squared; /*!< @brief maximum modulation squared value */ fixp24_t MaxD; /*!< @brief D upper limit */ fixp24_t MinD; /*!< @brief D lower limit */ fixp24_t MaxQ; /*!< @brief Q upper limit */ fixp24_t MinQ; /*!< @brief Q lower limit */ /* process */ fixp24_t wfsT; /*!< @brief conversion factor */ fixp24_t ErrD; /*!< @brief D-current error */ fixp24_t ErrQ; /*!< @brief Q-current error */ fixp24_t UpD; /*!< @brief D proportional result */ fixp24_t UpQ; /*!< @brief Q proportional result */ fixp24_t UiD; /*!< @brief D integral term */ fixp24_t UiQ; /*!< @brief Q integral term */ fixp30_t OutD; /*!< @brief PID output on d-axis */ fixp30_t OutQ; /*!< @brief PID output on q-axis */ fixp24_t compensation; /*!< @brief bus voltage compensation */ bool clippedD; /*!< @brief clipping status flag on D output */ bool clippedQ; /*!< @brief clipping status flag on Q output */ bool clipped; /*!< @brief overvall clipping status flag */ bool crosscompON; /*!< @brief cross coupling compensation activation flag */ } PIDREGDQX_CURRENT_s; void PIDREGDQX_CURRENT_init( PIDREGDQX_CURRENT_s * pHandle, const float current_scale, const float voltage_scale, const float pid_freq_hz, const float freq_scale_hz, const float duty_limit ); void PIDREGDQX_CURRENT_run( PIDREGDQX_CURRENT_s* pHandle, const fixp30_t errD, const fixp30_t errQ, const fixp30_t felec_pu); bool PIDREGDQX_CURRENT_getClipped( PIDREGDQX_CURRENT_s* pHandle ); float PIDREGDQX_CURRENT_getKp_si( PIDREGDQX_CURRENT_s* pHandle ); fixp_t PIDREGDQX_CURRENT_getOutD(PIDREGDQX_CURRENT_s* pHandle); fixp_t PIDREGDQX_CURRENT_getOutQ(PIDREGDQX_CURRENT_s* pHandle); float PIDREGDQX_CURRENT_getWi_si( PIDREGDQX_CURRENT_s* pHandle ); void PIDREGDQX_CURRENT_setKp_si(PIDREGDQX_CURRENT_s* pHandle, const float Kp_si); void PIDREGDQX_CURRENT_setKpWiRLmargin_si( PIDREGDQX_CURRENT_s* pHandle, const float Rsi, const float Lsi, const float margin); void PIDREGDQX_CURRENT_setWi_si(PIDREGDQX_CURRENT_s* pHandle, const float Wi_si); void PIDREGDQX_CURRENT_setUiD_pu( PIDREGDQX_CURRENT_s* pHandle, const fixp30_t Ui); void PIDREGDQX_CURRENT_setUiQ_pu( PIDREGDQX_CURRENT_s* pHandle, const fixp30_t Ui); void PIDREGDQX_CURRENT_setCompensation(PIDREGDQX_CURRENT_s* pHandle, const fixp24_t compensation); void PIDREGDQX_CURRENT_setOutputLimitsD( PIDREGDQX_CURRENT_s* pHandle, const fixp30_t max_pu, const fixp30_t min_pu); void PIDREGDQX_CURRENT_setOutputLimitsQ( PIDREGDQX_CURRENT_s* pHandle, const fixp30_t max_pu, const fixp30_t min_pu); void PIDREGDQX_CURRENT_setMaxModulation_squared( PIDREGDQX_CURRENT_s* pHandle, const float duty_limit); /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* _PIDREGDQX_CURRENT_H_ */ /* end of pidregdqx_current.h */
5,331
C
44.18644
127
0.572313
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/mp_self_com_ctrl.h
/** ****************************************************************************** * @file mp_self_com_ctrl.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for * for the SelfComCtrl component ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef MP_SELF_COM_CTRL_H #define MP_SELF_COM_CTRL_H /* Includes ------------------------------------------------------------------*/ #include "mc_type.h" #include "pwm_curr_fdbk.h" #include "ramp_ext_mngr.h" #include "bus_voltage_sensor.h" #include "speed_pos_fdbk.h" #include "virtual_speed_sensor.h" #include "open_loop.h" #include "circle_limitation.h" #include "pid_regulator.h" #include "revup_ctrl.h" #include "speed_torq_ctrl.h" #include "r_divider_bus_voltage_sensor.h" #include "sto_pll_speed_pos_fdbk.h" #include "mp_one_touch_tuning.h" #include "mp_hall_tuning.h" /** @addtogroup STM32_PMSM_MC_Library * @{ */ /** @addtogroup SelfComCtrl * @{ */ #define RSCURRLEVELNUM 4u #define EMF_BUFF_VAL 5u #define CMD_SC_STOP 0u #define CMD_SC_START 1u #define CMD_HT_START 2u #define CMD_HT_RESTART 3u #define CMD_HT_ABORT 4u #define CMD_HT_END 5u #define CMD_PPD_START 6u #define PB_CHARACTERIZATION_DISABLE 0 /** @defgroup SelfComCtrl_class_private_types SelfComCtrl class private types * @{ */ /** * @brief LS detection states */ typedef enum { LSDET_DECAY, LSDET_HOLD, LSDET_RISE } LSDetState_t; /** * @brief KE detection states */ typedef enum { KEDET_REVUP, KEDET_DETECTION, KEDET_SET_OBS_PARAMS, KEDET_STABILIZEPLL, KEDET_RUN, KEDET_RESTART } KEDetState_t; /** * @brief SCC_State_t enum type definition, it lists all the possible SCC state machine states. */ typedef enum { SCC_IDLE, SCC_DUTY_DETECTING_PHASE, SCC_ALIGN_PHASE, SCC_RS_DETECTING_PHASE_RAMP, SCC_RS_DETECTING_PHASE, SCC_LS_DETECTING_PHASE, SCC_WAIT_RESTART, SCC_RESTART_SCC, SCC_KE_DETECTING_PHASE, SCC_PHASE_STOP, SCC_CALIBRATION_END, SCC_PP_DETECTION_RAMP, SCC_PP_DETECTION_PHASE_RAMP, SCC_PP_DETECTION_PHASE } SCC_State_t; /** * @brief KE detection speed ramp status */ typedef enum { RampIdle, /* Ramp not started yet */ RampOngoing, /* Ramp is ongoing */ RampSucces, /* The motor has been accelerated up to the target speed */ MotorStill, /* Motor didn't move at all */ LoseControl, /* Motor start to follow acceleration but didn't reach the target speed */ } AccResult_t; /** * @brief SelfComCtrl parameters definition */ typedef struct { RampExtMngr_Handle_t rampExtMngrParams; /*!< Ramp manager used by SCC.*/ float fRshunt; /*!< Value of shunt resistor.*/ float fAmplificationGain; /*!< Current sensing amplification gain.*/ float fVbusConvFactor; /*!< Bus voltage conversion factor.*/ float fVbusPartitioningFactor; /*!< Bus voltage partitioning factor. (Vmcu / Bus voltage conversion factor).*/ float fRVNK; /*!< Power stage calibration factor. (Measured experimentally).*/ float fRSMeasCurrLevelMax; /*!< Maximum level of DC current used for RS measurement.*/ uint16_t hDutyRampDuration; /*!< Duration of voltage ramp executed for the duty cycle determination stage.*/ uint16_t hAlignmentDuration; /*!< Duration of the alignment stage.*/ uint16_t hRSDetectionDuration; /*!< Duration of R detection stage.*/ float fLdLqRatio; /*!< Ld vs Lq ratio.*/ float fCurrentBW; /*!< Bandwidth of current regulator.*/ uint8_t bPBCharacterization; /*!< Set to 1 for characterization of power board, otherwise false.*/ int32_t wNominalSpeed; /*!< Nominal speed set by the user expressed in RPM.*/ uint16_t hPWMFreqHz; /*!< PWM frequency used for the test.*/ uint8_t bFOCRepRate; /*!< FOC repetition rate used for the test.*/ float fMCUPowerSupply; /*!< MCU Power Supply */ float IThreshold; } SCC_Params_t, *pSCC_Params_t; /** * * @brief Handle structure of the SelfComCtrl. */ typedef struct { PWMC_Handle_t *pPWMC; /*!< Current feedback and PWM object used.*/ RDivider_Handle_t *pVBS; /*!< Bus voltage sensor used.*/ pFOCVars_t pFOCVars; /*!< Related structure of FOC vars.*/ MCI_Handle_t *pMCI; /*!< State machine of related MC.*/ VirtualSpeedSensor_Handle_t *pVSS; /*!< VSS used.*/ CircleLimitation_Handle_t *pCLM; /*!< Circle limitation used.*/ PID_Handle_t *pPIDIq; /*!< Iq PID used.*/ PID_Handle_t *pPIDId; /*!< Id PID used.*/ RevUpCtrl_Handle_t *pRevupCtrl; /*!< RUC used.*/ STO_PLL_Handle_t *pSTO; /*!< State Observer used.*/ SpeednTorqCtrl_Handle_t *pSTC; /*!< Speed and torque controller used.*/ OTT_Handle_t *pOTT; HT_Handle_t *pHT; SCC_State_t sm_state; /*!< SCC state machine state.*/ RampExtMngr_Handle_t *pREMng; /*!< Ramp manager used.*/ uint16_t hDutyMax; /*!< Duty cycle to be applied to reach the target current.*/ LSDetState_t LSDetState;/*!< Internal state during LS detection. */ KEDetState_t KEDetState;/*!< Internal state during KE detection. */ float fTPWM; /*!< PWM period in second. */ float fFocRate; /*!< FOC execution rate. */ float fPP; /*!< Motor poles pairs. */ int16_t hMax_voltage; /*!< Maximum readable voltage. */ float fMax_current; /*!< Maximum readable current. */ float fTargetCurr; /*!< Instantaneous value of target current used for R estimation.*/ float fLastTargetCurr; /*!< Last value of set nominal current used for R estimation.*/ float fRSCurrLevelStep; /*!< Step of current used for R estimation.*/ float fBusV; /*!< Stores the last Vbus measurement.*/ float fRS; /*!< Stores the last R estimation.*/ float fLS; /*!< Stores the last L estimation.*/ float fKe; /*!< Stores the last Ke estimation.*/ float fImaxArray[RSCURRLEVELNUM]; /*!< Array to store current measurement values for R estimation.*/ float fVmaxArray[RSCURRLEVELNUM]; /*!< Array to store voltage measurement values for R estimation.*/ uint8_t bRSCurrLevelTests; /*!< Counter to store I and V values for R estimation.*/ float fImax; /*!< Stores the last current measurement done, it will be used to compute the 63% for electrical time constant measurement.*/ float fItau; /*!< Stores the last computed electrical time constant.*/ uint8_t bDutyDetTest; /*!< Number of test done in duty determination phase.*/ uint32_t wLSTimeCnt; /*!< Time counter for LS determination.*/ uint32_t wLSTestCnt; /*!< Counter for LS tests. */ float fLSsum; /*!< Sum of estimated LS for mean.*/ float fIsum; /*!< Sum of measured current for mean.*/ float fVsum; /*!< Sum of estimated voltage for mean.*/ uint32_t wICnt; /*!< Counter of I and V acquired.*/ uint32_t index; /*!< Counter of I and V acquired.*/ float fIqsum; /*!< Sum of measured Iq for mean.*/ float fVqsum; /*!< Sum of measured Vq for mean.*/ float fVdsum; /*!< Sum of measured Vd for mean.*/ float fFesum; /*!< Sum of electrical frequency for mean.*/ uint32_t wKeAcqCnt; /*!< Counter of Iq, Vq and Vd acquired.*/ float fEstNominalSpdRPM;/*!< Estimated nominal speed.*/ float k1, k2; /*!< Coefficient computed for state observer tuning.*/ int8_t stabCnt; /*!< Stabilization counter.*/ float fLdLqRatio; /*!< Ld vs Lq ratio.*/ int32_t wNominalSpeed; /*!< Nominal speed set by the user expressed in RPM.*/ int32_t wMaxOLSpeed; /*!< Maximum speed that can be sustained in the startup.*/ uint32_t wAccRPMs; /*!< Acceleration ramp for the motor expressed in RMP/s.*/ bool accRampLock; /*!< It become true if the motor follow the acceleration. */ float fEm_val[EMF_BUFF_VAL]; /*!< Buffer used for linear regression (BEMF amplitude).*/ float fw_val[EMF_BUFF_VAL]; /*!< Buffer used for linear regression (Angular velocity).*/ uint16_t hVal_ctn; /*!< Counter for the buffer used for linear regression.*/ bool startComputation; /*!< It becomes true if the buffer used for linear regression has been filled.*/ uint16_t hTimeOutCnt; /*!< Time out counter to assert the motor still condition during acceleration ramp.*/ uint32_t wLoseControlAtRPM; /*!< Last speed forced before loosing control during acceleration ramp.*/ AccResult_t res; /*!< Result state of the last acceleration ramp.*/ float fLastValidI; /*!< Last valid current measurement during SCC_DUTY_DETECTING_PHASE */ uint16_t hMFCount; /*!< Counter of MF to be wait after OC or loose control.*/ uint16_t hMFTimeout; /*!< Counter of MF to be wait after OC or loose control.*/ float fCurrentBW; /*!< Bandwidth of speed regulator.*/ uint8_t bMPOngoing; /*!< It is 1 if MP is ongoing, 0 otherwise.*/ uint32_t wSpeedThToValidateStartupRPM; /*!< Speed threshold to validate the startup.*/ float IaBuff[256]; bool detectBemfState; bool polePairDetection; //profiler ppDetection uint32_t ppDtcCnt; /*!< Counter of pole pairs detection time.*/ pSCC_Params_t pSCC_Params_str; /**< SelfComCtrl parameters */ } SCC_Handle_t; /** * @brief Initializes all the object variables, usually it has to be called * once right after object creation. * @param this related object of class CSCC. * @retval none. */ void SCC_Init(SCC_Handle_t *pHandle); /** * @brief It should be called before each motor restart. * @param this related object of class CSCC. * @retval bool It return false if function fails to start the SCC. */ bool SCC_Start(SCC_Handle_t *pHandle); /** * @brief It should be called before each motor stop. * @param this related object of class CSCC. * @retval none. */ void SCC_Stop(SCC_Handle_t *pHandle); /** * @brief It feed the required phase voltage to the inverter. * @param this related object of class CSCC. * @retval It returns the code error 'MC_DURATION' if any, 'MC_NO_ERROR' * otherwise. These error codes are defined in mc_type.h */ uint16_t SCC_SetPhaseVoltage(SCC_Handle_t *pHandle); /** * @brief Medium frequency task. * @param this related object of class CSCC. * @retval none */ void SCC_MF(SCC_Handle_t *pHandle); /** * @brief Check overcurrent during RL detetction and restart the procedure * with less current. * @param this related object of class CSCC. * @retval none. */ void SCC_CheckOC_RL(SCC_Handle_t *pHandle); uint8_t SCC_CMD(SCC_Handle_t *pHandle, uint16_t rxLength, uint8_t *rxBuffer, int16_t txSyncFreeSpace, uint16_t *txLength, uint8_t *txBuffer); void SCC_SetNominalCurrent(SCC_Handle_t *pHandle, float fCurrent); void SCC_SetLdLqRatio(SCC_Handle_t *pHandle, float fLdLqRatio); void SCC_SetNominalSpeed(SCC_Handle_t *pHandle, int32_t wNominalSpeed); void SCC_SetPolesPairs(SCC_Handle_t *pHandle, uint8_t bPP); void SCC_SetCurrentBandwidth(SCC_Handle_t *pHandle, float fCurrentBW); uint8_t SCC_GetState(SCC_Handle_t *pHandle); uint8_t SCC_GetSteps(SCC_Handle_t *pHandle); uint8_t SCC_GetFOCRepRate(SCC_Handle_t *pHandle); uint16_t SCC_GetPWMFrequencyHz(SCC_Handle_t *pHandle); uint32_t SCC_GetRs(SCC_Handle_t *pHandle); uint32_t SCC_GetLs(SCC_Handle_t *pHandle); uint32_t SCC_GetKe(SCC_Handle_t *pHandle); uint32_t SCC_GetVbus(SCC_Handle_t *pHandle); float SCC_GetNominalCurrent(SCC_Handle_t *pHandle); float SCC_GetLdLqRatio(SCC_Handle_t *pHandle); int32_t SCC_GetNominalSpeed(SCC_Handle_t *pHandle); float SCC_GetCurrentBandwidth(SCC_Handle_t *pHandle); float SCC_GetStartupCurrentAmp(SCC_Handle_t *pHandle); int32_t SCC_GetEstMaxAcceleration(SCC_Handle_t *pHandle); int32_t SCC_GetEstMaxOLSpeed(SCC_Handle_t *pHandle); float SCC_GetResistorOffset(SCC_Handle_t *pHandle); uint16_t SCC_GetUnderVoltageThreshold(SCC_Handle_t *pHandle); uint16_t SCC_GetOverVoltageThreshold(SCC_Handle_t *pHandle); void SCC_SetOverVoltageThreshold(SCC_Handle_t *pHandle,uint16_t value); void SCC_SetUnderVoltageThreshold(SCC_Handle_t *pHandle,uint16_t value); void SCC_SetPBCharacterization(SCC_Handle_t *pHandle,uint8_t value); void SCC_SetResistorOffset(SCC_Handle_t *pHandle,float Offset); /** * @} */ /** * @} */ /** * @} */ #endif /*MP_SELF_COM_CTRL_H*/ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
13,913
C
39.68421
141
0.619061
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/speed_regulator_potentiometer.h
/** ****************************************************************************** * @file speed_regulator_potentiometer.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * Speed Regulator Potentiometer component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup SpeedRegulatorPotentiometer */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef SPEEDREGULATOR_H #define SPEEDREGULATOR_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "speed_torq_ctrl.h" #include "regular_conversion_manager.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup SpeedRegulatorPotentiometer * @{ */ /** * @brief structure used for external speed regulator * */ typedef struct { RegConv_t SpeedRegConv; SpeednTorqCtrl_Handle_t *pSTC; /**< Speed and torque controller object used by the Speed Regulator.*/ uint16_t ConversionFactor; /**< Factor to convert speed between u16digit and #SPEED_UNIT. */ uint16_t LatestConv; /**< Contains the latest potentiometer converted value expressed in u16digit format */ uint16_t AvSpeedReg_d; /**< Contains the latest available average speed expressed in u16digit */ //uint16_t uint16_t LowPassFilterBW; /**< Used to configure the first order software filter bandwidth. hLowPassFilterBW = SRP_CalcSpeedReading call rate [Hz]/ FilterBandwidth[Hz] */ uint16_t SpeedAdjustmentRange; /**< Represents the range used to trigger a speed ramp command*/ uint16_t MinimumSpeedRange; /**< Minimum settable speed expressed in u16digit*/ uint16_t MaximumSpeedRange; /**< Maximum settable speed expressed in u16digit*/ uint32_t RampSlope; /**< Speed variation in SPPED_UNIT/s. */ uint16_t *aBuffer; /**< Buffer used to compute average value.*/ uint8_t elem; /**< Number of stored elements in the average buffer.*/ uint8_t index; /**< Index of last stored element in the average buffer.*/ uint8_t convHandle; /**< Handle on the regular conversion */ bool OutOfSynchro; /**< Check of the matching between potentiometer setting and measured speed */ } SRP_Handle_t; /* Initializes a Speed Regulator Potentiometer component */ void SRP_Init(SRP_Handle_t *pHandle, SpeednTorqCtrl_Handle_t *pSTC); /* Clears a Speed Regulator Potentiometer component */ void SRP_Clear( SRP_Handle_t * pHandle ); /* Reads the potentiometer of an SRP component to compute an average speed reference */ bool SRP_CalcAvSpeedReg( SRP_Handle_t * pHandle ); /* Reads the potentiometer of an SRP component and filters it to compute an average speed reference */ bool SRP_CalcAvSpeedRegFilt( SRP_Handle_t * pHandle, uint16_t rawValue ); bool SRP_ExecPotRamp( SRP_Handle_t * pHandle ); bool SRP_CheckSpeedRegSync( SRP_Handle_t * pHandle ); uint16_t SRP_GetSpeedReg_d( SRP_Handle_t * pHandle ); uint16_t SRP_GetAvSpeedReg_d( SRP_Handle_t * pHandle ); uint16_t SRP_GetAvSpeedReg_SU( SRP_Handle_t * pHandle ); /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* SPEEDREGULATOR_H */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
4,104
C
39.643564
112
0.599172
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/profiler_impedest.h
/** ****************************************************************************** * @file profiler_impedest.h * @author Piak Electronic Design B.V. * @brief This file is part of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 Piak Electronic Design B.V. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** */ /* profiler_impedest.h */ #ifndef _PROFILER_IMPEDEST_H_ #define _PROFILER_IMPEDEST_H_ #include "profiler_types.h" typedef struct _PROFILER_IMPEDEST_Obj_ { /* Configuration */ fixp30_t isrPeriod_ms; /* ISR period in milliseconds, always < 1.0 */ float_t fullScaleCurrent_A; float_t fullScaleVoltage_V; fixp30_t injectFreqKhz; /* Frequency to inject, in kHz */ bool flag_inject; fixp30_t inject_ref; /* Reference for magnitude of injected signal */ fixp30_t filt; /* Filter constant for demodulated signal */ /* State */ fixp30_t angle_inject_pu; /* Angle of the injected signal */ fixp30_t inject_out; /* Injected signal */ fixp30_t dither; Vector_dq_t U_demod_lp1; Vector_dq_t I_demod_lp1; Vector_dq_t U_demod_lp2; Vector_dq_t I_demod_lp2; /* Output */ float_t Rs; float_t Ls; } PROFILER_IMPEDEST_Obj; typedef PROFILER_IMPEDEST_Obj *PROFILER_IMPEDEST_Handle; void PROFILER_IMPEDEST_init(PROFILER_IMPEDEST_Handle handle); void PROFILER_IMPEDEST_setParams(PROFILER_IMPEDEST_Obj *obj, PROFILER_Params *pParams); void PROFILER_IMPEDEST_run(PROFILER_IMPEDEST_Obj *obj, fixp30_t Ua_pu, fixp30_t Ia_pu); void PROFILER_IMPEDEST_calculate(PROFILER_IMPEDEST_Obj *obj); /* Accessors */ /* Getters */ fixp30_t PROFILER_IMPEDEST_getInject(PROFILER_IMPEDEST_Obj *obj); float_t PROFILER_IMPEDEST_getLs(PROFILER_IMPEDEST_Obj *obj); float_t PROFILER_IMPEDEST_getRs(PROFILER_IMPEDEST_Obj *obj); /* Setters */ void PROFILER_IMPEDEST_setFlagInject(PROFILER_IMPEDEST_Obj *obj, const bool value); void PROFILER_IMPEDEST_setInjectFreq_kHz(PROFILER_IMPEDEST_Obj *obj, const fixp30_t value); void PROFILER_IMPEDEST_setInjectRef(PROFILER_IMPEDEST_Obj *obj, const fixp30_t value); #endif /* _PROFILER_IMPEDEST_H_ */ /* end of profiler_impedest.h */ /************************ (C) COPYRIGHT 2023 Piak Electronic Design B.V. *****END OF FILE****/
2,689
C
29.91954
94
0.631833
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/encoder_speed_pos_fdbk.h
/** ****************************************************************************** * @file encoder_speed_pos_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * Encoder Speed & Position Feedback component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup Encoder */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef ENCODER_SPEEDNPOSFDBK_H #define ENCODER_SPEEDNPOSFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "speed_pos_fdbk.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup SpeednPosFdbk * @{ */ /** @addtogroup Encoder * @{ */ /* Exported constants --------------------------------------------------------*/ #define GPIO_NoRemap_TIMx ((uint32_t)(0)) #define ENC_DMA_PRIORITY DMA_Priority_High #define ENC_SPEED_ARRAY_SIZE ((uint8_t)16) /* 2^4 */ /** * @brief ENCODER class parameters definition */ typedef struct { SpeednPosFdbk_Handle_t _Super; /*!< SpeednPosFdbk handle definition. */ TIM_TypeDef *TIMx; /*!< Timer used for ENCODER sensor management.*/ uint32_t SpeedSamplingFreqUnit; /*!< Frequency at which motor speed is to be computed. It must be equal to the frequency at which function SPD_CalcAvrgMecSpeedUnit is called.*/ int32_t DeltaCapturesBuffer[ENC_SPEED_ARRAY_SIZE]; /*!< Buffer used to store captured variations of timer counter*/ uint32_t U32MAXdivPulseNumber; /*!< It stores U32MAX/hPulseNumber */ uint16_t SpeedSamplingFreqHz; /*!< Frequency (Hz) at which motor speed is to be computed. */ /* SW Settings */ uint16_t PulseNumber; /*!< Number of pulses per revolution, provided by each of the two encoder signals, multiplied by 4 */ volatile uint16_t TimerOverflowNb; /*!< Number of overflows occurred since last speed measurement event*/ uint16_t PreviousCapture; /*!< Timer counter value captured during previous speed measurement event*/ uint8_t SpeedBufferSize; /*!< Size of the buffer used to calculate the average speed. It must be <= 16.*/ bool SensorIsReliable; /*!< Flag to indicate sensor/decoding is not properly working.*/ uint32_t ICx_Filter; /*!< Input Capture filter selection */ volatile uint8_t DeltaCapturesIndex; /*!< Buffer index */ bool TimerOverflowError; /*!< true if the number of overflow occurred is greater than 'define' ENC_MAX_OVERFLOW_NB*/ } ENCODER_Handle_t; /* IRQ implementation of the TIMER ENCODER */ void *ENC_IRQHandler(void *pHandleVoid); /* It initializes the hardware peripherals (TIMx, GPIO and NVIC) * required for the speed position sensor management using ENCODER * sensors */ void ENC_Init(ENCODER_Handle_t *pHandle); /* Clear software FIFO where are "pushed" rotor angle variations captured */ void ENC_Clear(ENCODER_Handle_t *pHandle); /* It calculates the rotor electrical and mechanical angle, on the basis * of the instantaneous value of the timer counter */ int16_t ENC_CalcAngle(ENCODER_Handle_t *pHandle); /* The method generates a capture event on a channel, computes & stores average mechanical speed */ bool ENC_CalcAvrgMecSpeedUnit(ENCODER_Handle_t *pHandle, int16_t *pMecSpeedUnit); /* It set instantaneous rotor mechanical angle */ void ENC_SetMecAngle(ENCODER_Handle_t *pHandle, int16_t hMecAngle); /** * @} */ /** * @} */ /** @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*ENCODER_SPEEDNPOSFDBK_H*/ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
4,886
C
39.388429
117
0.543389
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/circle_limitation.h
/** ****************************************************************************** * @file circle_limitation.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * Circle Limitation component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup CircleLimitation */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef CIRCLELIMITATION_H #define CIRCLELIMITATION_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup CircleLimitation * @{ */ /** * @brief CircleLimitation component parameters definition */ typedef struct { uint16_t MaxModule; /**< Circle limitation maximum allowed module */ uint16_t MaxVd; /**< Circle limitation maximum allowed module */ } CircleLimitation_Handle_t; /* Exported functions ------------------------------------------------------- */ /* Returns the saturated @f$v_q, v_d@f$ component values */ qd_t Circle_Limitation(const CircleLimitation_Handle_t *pHandle, qd_t Vqd); /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* CIRCLELIMITATION_H */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
2,001
C
27.197183
85
0.509745
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/pidreg_speed.h
/** ****************************************************************************** * @file pidreg_speed.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * PID speed regulator of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup PIDRegSpeed */ #ifndef _PIDREG_SPEED_H_ #define _PIDREG_SPEED_H_ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "fixpmath.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup PIDRegSpeed * @{ */ /** * @brief PID speed regulator handler definition */ typedef struct _PIDREG_SPEED_s_ { /* configuration */ FIXP_scaled_t Kp_fps; /*!< @brief Kp gain expressed in fps */ FIXP_scaled_t Ki_fps; /*!< @brief Ki gain expressed in fps */ fixp24_t dither; /*!< @brief dithering variable */ float current_scale; /*!< @brief current scaling factor */ float frequency_scale; /*!< @brief frequency scalimg factor */ float pid_freq_hz; /*!< @brief Frequency at which the PID is called */ /* limits */ fixp24_t Max; /*!< @brief upper PID limit in A_pu */ fixp24_t Min; /*!< @brief lower PID limit in A_pu */ /* process */ fixp24_t Err; /*!< @brief speed error */ fixp24_t Up; /*!< @brief proportional result */ fixp24_t Ui; /*!< @brief integral result */ fixp30_t Out; /*!< @brief PID output result */ bool clipped; /*!< @brief clipping status flag */ } PIDREG_SPEED_s; void PIDREG_SPEED_init( PIDREG_SPEED_s* pHandle, const float current_scale, const float frequency_scale, const float pid_freq_hz ); fixp30_t PIDREG_SPEED_run(PIDREG_SPEED_s* pHandle, const fixp30_t err); fixp30_t PIDREG_SPEED2_run( PIDREG_SPEED_s* pHandle, const fixp30_t err, const fixp30_t errIncSpd); bool PIDREG_SPEED_getClipped( PIDREG_SPEED_s* pHandle ); float PIDREG_SPEED_getKp_si( PIDREG_SPEED_s* pHandle ); float PIDREG_SPEED_getKi_si( PIDREG_SPEED_s* pHandle ); void PIDREG_SPEED_setKp_si(PIDREG_SPEED_s* pHandle, const float Kp_si); void PIDREG_SPEED_setKi_si(PIDREG_SPEED_s* pHandle, const float Ki_si); void PIDREG_SPEED_setUi_pu( PIDREG_SPEED_s* pHandle, const fixp30_t Ui); void PIDREG_SPEED_setOutputLimits(PIDREG_SPEED_s* pHandle, const fixp30_t max_pu, const fixp30_t min_pu); fixp30_t PIDREG_SPEED_getOutputLimitMax(PIDREG_SPEED_s* pHandle); fixp30_t PIDREG_SPEED_getOutputLimitMin(PIDREG_SPEED_s* pHandle); /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* _PIDREG_SPEED_H_ */
3,264
C
32.316326
105
0.581189
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/sto_pll_speed_pos_fdbk.h
/** ****************************************************************************** * @file sto_pll_speed_pos_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * State Observer + PLL Speed & Position Feedback component of the Motor * Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup SpeednPosFdbk_STO_PLL */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef STO_PLL_SPEEDNPOSFDBK_H #define STO_PLL_SPEEDNPOSFDBK_H /* Includes ------------------------------------------------------------------*/ #include "speed_pos_fdbk.h" #include "sto_speed_pos_fdbk.h" #include "pid_regulator.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup SpeednPosFdbk_STO_PLL * @{ */ /** * @brief Handle of the Speed and Position Feedback STO PLL component. * */ typedef struct { SpeednPosFdbk_Handle_t _Super; /**< @brief Speed and torque component handler. */ int16_t hC1; /*!< @brief State observer constant @f$ C_1 @f$. * * Can be computed as : @f$ (F_1 × R_s) / (L_s × State Observer Execution Rate) @f$ \n * @f$ F_1 @f$ in Hertz [**Hz**]. \n * @f$ R_s @f$ in Ohm @f$[\Omega]@f$. \n * @f$ L_s @f$ in Henry [**H**]. \n * State Observer Execution Rate in Hertz [**Hz**]. */ int16_t hC2; /**< @brief State observer constant @f$ C_2 @f$. * * Can be computed as : @f$ (F_1 × K_1) / (State Observer Execution Rate) @f$ \n * @f$ F_1 @f$ in Hertz [**Hz**]. \n * @f$ K_1 @f$ being one of the two observer gains. \n observer execution rate [Hz] being K1 one of the two observer gains */ int16_t hC3; /*!< Variable containing state observer constant * * Can be computed as : @f$ (F_1 × Max Application Speed × Motor Bemf Constant × √2) / (L_S × Max Measurable Current × State Observer Execution Rate) @f$ \n * @f$ F_1 @f$ in Hertz [**Hz**]. \n * Max Application Speed in Rotation per minute [**rpm**]. \n * Motor Bemf Constant in Voltage line to line root mean square per kilo-rpm [**Vllrms/krpm**]. \n * @f$ L_s @f$ in Henry [**H**]. \n * Max Measurable Current in Ampere [**A**]. \n * State Observer Execution Rate in Hertz [**Hz**]. */ int16_t hC4; /**< @brief State Observer constant @f$ C_4 @f$. * * Can be computed as @f$ K_2 × Max Measurable Current / (Max Application Speed × Motor Bemf Constant × √2 × F_2 × State Observer Execution Rate) @f$ \n * @f$ K_2 @f$ being one of the two observer gains. \n * Max Measurable Current in Ampere [**A**]. \n * Max Application Speed in Rotation per minute [**rpm**]. \n * Motor Bemf Constant in Voltage line to line root mean square per kilo-rpm [**Vllrms/krpm**]. \n * State Observer Execution Rate in Hertz [**Hz**]. \n */ int16_t hC5; /**< @brief State observer constant @f$ C_5 @f$. * * Can be computed as @f$ F_1 × Max Measurable Voltage / (2 × L_s × Max Measurable Current × State Observer Execution Rate) @f$ \n * @f$ F_1 @f$ in Hertz [**Hz**]. \n * Max Measurable Voltage in Volt [**V**]. \n * @f$ L_s @f$ in Henry [**H**]. \n * Max Measurable Current in Ampere [**A**]. \n * State Observer Execution Rate in Hertz [**Hz**]. */ int16_t hC6; /**< @brief State observer constant @f$ C_6 @f$. Computed with a specific procedure starting from the other constants. */ int16_t hF1; /**< @brief State observer scaling factor @f$ F_1 @f$. */ int16_t hF2; /**< @brief State observer scaling factor @f$ F_2 @f$. */ int16_t hF3; /**< @brief State observer scaling factor @f$ F_3 @f$. */ uint16_t F3POW2; /**< @brief State observer scaling factor @f$ F_3 @f$ expressed as power of 2. * * E.g. If gain divisor is 512 the value must be 9 because @f$ 2^9 = 512 @f$. */ PID_Handle_t PIRegulator; /**< @brief PI regulator component handle, used for PLL implementation */ int32_t Ialfa_est; /**< @brief Estimated @f$ I_{alpha} @f$ current. */ int32_t Ibeta_est; /**< @brief Estimated @f$ I_{beta} @f$ current. */ int32_t wBemf_alfa_est; /**< @brief Estimated Bemf alpha. */ int32_t wBemf_beta_est; /**< @brief Estimated Bemf beta. */ int16_t hBemf_alfa_est; /**< @brief Estimated Bemf alpha in int16_t format. */ int16_t hBemf_beta_est; /**< @brief Estimated Bemf beta in int16_t format. */ int16_t Speed_Buffer[64]; /**< @brief Estimated speed FIFO, it contains latest SpeedBufferSizeDpp speed measurements [**DPP**]. */ uint8_t Speed_Buffer_Index; /**< @brief Index of latest estimated speed in buffer Speed_Buffer[]. */ bool IsSpeedReliable; /**< @brief Estimated speed reliability information. * * Updated during speed average computation in STO_PLL_CalcAvrgMecSpeedUnit, * True if the speed measurement variance is lower than threshold VariancePercentage. */ uint8_t ConsistencyCounter; /**< @brief Counter of passed tests for start-up validation. */ uint8_t ReliabilityCounter; /**< @brief Counter for checking reliability of Bemf and speed. */ bool IsAlgorithmConverged; /**< @brief Observer convergence flag. */ bool IsBemfConsistent; /**< @brief Reliability of estimated Bemf flag. * * Updated by STO_PLL_CalcAvrgMecSpeedUnit, set to true when observed Bemfs are consistent with expectation. */ int32_t Obs_Bemf_Level; /**< @brief Magnitude of observed Bemf level squared. */ int32_t Est_Bemf_Level; /**< @brief Magnitude of estimated Bemf Level squared based on speed measurement. */ bool EnableDualCheck; /**< @brief Enable additional reliability check based on observed Bemf. */ int32_t DppBufferSum; /**< @brief Sum of speed buffer elements [**DPP**]. */ int16_t SpeedBufferOldestEl; /**< @brief Oldest element of the speed buffer. */ uint8_t SpeedBufferSizeUnit; /**< @brief Depth of FIFO used to calculate the average estimated speed exported by SPD_GetAvrgMecSpeedUnit. * Must be an integer number in range[1..64]. */ uint8_t SpeedBufferSizeDpp; /**< @brief Depth of FIFO used to calculate both average estimated speed exported by SPD_GetElSpeedDpp and state observer equations. * Must be an integer number between 1 and SpeedBufferSizeUnit */ uint16_t VariancePercentage; /**< @brief Maximum allowed variance of speed estimation. */ uint8_t SpeedValidationBand_H; /**< @brief Upper bound below which the estimated speed is still acceptable * despite exceeding the force stator electrical frequency * during start-up. The measurement unit is 1/16 of forced * speed. */ uint8_t SpeedValidationBand_L; /**< @brief Lower bound above which the estimated speed is still acceptable * despite subceeding the force stator electrical frequency * during start-up. The measurement unit is 1/16 of forced * speed. */ uint16_t MinStartUpValidSpeed; /**< @brief Absolute value of minimum mechanical * speed required to validate the start-up. * Expressed in the unit defined by #SPEED_UNIT. */ uint8_t StartUpConsistThreshold; /**< @brief Number of consecutive tests on speed * consistency to be passed before * validating the start-up. */ uint8_t Reliability_hysteresys; /**< @brief Number of failed consecutive reliability tests * before returning a speed check fault to _Super.bSpeedErrorNumber. */ uint8_t BemfConsistencyCheck; /**< @brief Degree of consistency of the observed Bemfs. \n * Must be an integer number ranging from 1 (very high * consistency) down to 64 (very poor consistency). */ uint8_t BemfConsistencyGain; /**< @brief Gain to be applied when checking Bemfs consistency. \n * Default value is 64 (neutral), max value 105 * (x1.64 amplification), min value 1 (/64 attenuation). */ uint16_t MaxAppPositiveMecSpeedUnit; /**< @brief Maximum positive value of rotor speed. \n * Expressed in the unit defined by #SPEED_UNIT. * Can be x1.1 greater than max application speed. */ uint16_t F1LOG; /**< @brief @f$ F_1 @f$ gain divisor expressed as power of 2. * * E.g. if gain divisor is 512 the value must be 9 because @f$ 2^9 = 512 @f$. */ uint16_t F2LOG; /**< @brief @f$ F_2 @f$ gain divisor expressed as power of 2. * * E.g. if gain divisor is 512 the value must be 9 because @f$ 2^9 = 512 @f$. */ uint16_t SpeedBufferSizeDppLOG; /**< @brief bSpeedBufferSizedpp expressed as power of 2. * * E.g. if gain divisor is 512 the value must be 9 because @f$ 2^9 = 512 @f$. */ bool ForceConvergency; /**< @brief Variable to force observer convergence. */ bool ForceConvergency2; /**< @brief Variable to force observer convergence. */ int8_t hForcedDirection; /**< @brief Variable to force rotation direction. */ } STO_PLL_Handle_t; /* Exported functions ------------------------------------------------------- */ /* Initializes the handler of STate Observer (STO) PLL component */ void STO_PLL_Init(STO_PLL_Handle_t *pHandle); /* Necessary empty return to implement fictitious IRQ_Handler */ void STO_PLL_Return(STO_PLL_Handle_t *pHandle, uint8_t flag); /* Clears state observer component by re-initializing private variables in the handler */ void STO_PLL_Clear(STO_PLL_Handle_t *pHandle); /* Calculates the estimated electrical angle */ int16_t STO_PLL_CalcElAngle(STO_PLL_Handle_t *pHandle, Observer_Inputs_t *pInputs); /* Computes and returns the average mechanical speed */ bool STO_PLL_CalcAvrgMecSpeedUnit(STO_PLL_Handle_t *pHandle, int16_t *pMecSpeedUnit); /* Resets the PLL integral term during on-the-fly startup */ void STO_OTF_ResetPLL(STO_Handle_t *pHandle); /* Resets the PLL integral term */ void STO_ResetPLL(STO_PLL_Handle_t *pHandle); /* Checks if the state observer algorithm converged */ bool STO_PLL_IsObserverConverged(STO_PLL_Handle_t *pHandle, int16_t *phForcedMecSpeedUnit); /* Computes and updates the average electrical speed */ void STO_PLL_CalcAvrgElSpeedDpp(STO_PLL_Handle_t *pHandle); /* Exports estimated Bemf alpha-beta from the handler */ alphabeta_t STO_PLL_GetEstimatedBemf(STO_PLL_Handle_t *pHandle); /* Exports from the handler the stator current alpha-beta as estimated by state observer */ alphabeta_t STO_PLL_GetEstimatedCurrent(STO_PLL_Handle_t *pHandle); /* Stores in the handler the new values for observer gains */ void STO_PLL_SetObserverGains(STO_PLL_Handle_t *pHandle, int16_t hhC1, int16_t hhC2); /* Exports current observer gains from the handler to parameters hhC2 and hhC4 */ void STO_PLL_GetObserverGains(STO_PLL_Handle_t *pHandle, int16_t *phC2, int16_t *phC4); /* Exports the current PLL gains from the handler to parameters pPgain and pIgain */ void STO_GetPLLGains(STO_PLL_Handle_t *pHandle, int16_t *pPgain, int16_t *pIgain); /* Stores in the handler the new values for PLL gains */ void STO_SetPLLGains(STO_PLL_Handle_t *pHandle, int16_t hPgain, int16_t hIgain); /* Empty function. Could be declared to set instantaneous information on rotor mechanical angle */ void STO_PLL_SetMecAngle(STO_PLL_Handle_t *pHandle, int16_t hMecAngle); /* Sends locking info for PLL */ void STO_SetPLL(STO_PLL_Handle_t *pHandle, int16_t hElSpeedDpp, int16_t hElAngle); /* Exports estimated Bemf squared level stored in the handler */ int32_t STO_PLL_GetEstimatedBemfLevel(STO_PLL_Handle_t *pHandle); /* Exports observed Bemf squared level stored in the handler */ int32_t STO_PLL_GetObservedBemfLevel(STO_PLL_Handle_t *pHandle); /* Enables/Disables additional reliability check based on observed Bemf */ void STO_PLL_BemfConsistencyCheckSwitch(STO_PLL_Handle_t *pHandle, bool bSel); /* Checks if the Bemf is consistent */ bool STO_PLL_IsBemfConsistent(STO_PLL_Handle_t *pHandle); /* Checks the value of the variance */ bool STO_PLL_IsVarianceTight(const STO_Handle_t *pHandle); /* Forces the state-observer to declare convergency */ void STO_PLL_ForceConvergency1(STO_Handle_t *pHandle); /* Forces the state-observer to declare convergency */ void STO_PLL_ForceConvergency2(STO_Handle_t *pHandle); /* Sets the Absolute value of minimum mechanical speed required to validate the start-up */ void STO_SetMinStartUpValidSpeedUnit(STO_PLL_Handle_t *pHandle, uint16_t hMinStartUpValidSpeed); /* Sets the rotation direction in the handler */ __weak void STO_SetDirection(STO_PLL_Handle_t *pHandle, int8_t direction); /** * @} */ /** * @} */ #endif /*STO_PLL_SPEEDNPOSFDBK_H*/ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
17,398
C
60.698581
200
0.498506
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/fixpmath_types.h
/** ****************************************************************************** * @file fixpmath_types.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains the structure definitions of the vectors * used in Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup FixpMath */ #ifndef _FIXPMATH_TYPES_H_ #define _FIXPMATH_TYPES_H_ #include <stdbool.h> typedef struct { fixp30_t cos; fixp30_t sin; } FIXP_CosSin_t; typedef struct { fixp30_t A; /*!< @brief value of @f$\alpha@f$ encoded in fixed-point 30Bit format */ fixp30_t B; /*!< @brief value of @f$\beta@f$ encoded in fixed-point 30Bit format */ } Vector_ab_t; typedef struct { fixp30_t D; /*!< @brief value in D direction encoded in fixed-point 30Bit format */ fixp30_t Q; /*!< @brief value in D direction encoded in fixed-point 30Bit format */ } Vector_dq_t; typedef struct { fixp30_t R; /*!< @brief value of phase R encoded in fixed-point 30Bit format */ fixp30_t S; /*!< @brief value of phase S encoded in fixed-point 30Bit format */ fixp30_t T; /*!< @brief value of phase T encoded in fixed-point 30Bit format */ } Vector_rst; typedef Vector_rst Currents_Irst_t; typedef struct { uint_least8_t numValid; bool validR; bool validS; bool validT; } CurrentReconstruction_t; typedef Vector_rst Voltages_Urst_t; typedef Vector_ab_t Currents_Iab_t; typedef Vector_dq_t Currents_Idq_t; typedef Vector_dq_t Voltages_Udq_t; typedef Vector_ab_t Voltages_Uab_t; typedef Vector_dq_t Duty_Ddq_t; typedef Vector_ab_t Duty_Dab_t; typedef Vector_rst Duty_Drst_t; #endif /* _FIXPMATH_TYPES_H_ */ /* end of fixpmath_types.h */
2,283
C
27.197531
95
0.586509
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/bemf_speed_pos_fdbk.h
/** ****************************************************************************** * @file bemf_speed_pos_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains definitions and functions prototypes common to all * six-step sensorless based Speed & Position Feedback components of the Motor * Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup SpeednPosFdbk_Bemf */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __BEMF_SPEEDNPOSFDBK_H #define __BEMF_SPEEDNPOSFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "speed_pos_fdbk.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup SpeednPosFdbk * @{ */ /** @defgroup SpeednPosFdbk_Bemf Six-Step Back-EMF sensing * * @brief Back-EMF sensing components of the Motor Control SDK for G4XX, G0XX, F0XX and C0XX. * * These components fulfill two functions in a Motor Control subsystem: * * - The sensing of the Back-EMF * - The detection of the zero-crossing point and the estimation of the rotor position * * The ADC should be triggered by the timers used to generate the duty cycles for the PWM. * * Several implementation of Six-Step Back-EMF sensing components are provided by the Motor Control * SDK to account for the specificities of the application: * * - The selected MCU: the number of ADCs available on a given MCU, the presence of injected channels, * for instance, lead to different implementation of this feature * - The presence of comparators for or a resistor networks that allows the sampling during * the PWM ON period * * All these implementations are built on a base Six-Step Back-EMF sensing component that they extend * and that provides the functions and data that are common to all of them. This base component is * never used directly as it does not provide a complete implementation of the features. * @{ */ /* Exported types ------------------------------------------------------------*/ /** @brief Sensorless Bemf Sensing component handle type */ typedef struct Bemf_Handle Bemf_Handle_t; typedef void ( *Bemf_ForceConvergency1_Cb_t )( Bemf_Handle_t * pHandle ); typedef void ( *Bemf_ForceConvergency2_Cb_t )( Bemf_Handle_t * pHandle ); typedef void ( *Bemf_OtfResetPLL_Cb_t )( Bemf_Handle_t * pHandle ); typedef bool ( *Bemf_SpeedReliabilityCheck_Cb_t )( const Bemf_Handle_t * pHandle ); /** * @brief SpeednPosFdbk handle definition */ struct Bemf_Handle { SpeednPosFdbk_Handle_t * _Super; Bemf_ForceConvergency1_Cb_t pFctForceConvergency1; Bemf_ForceConvergency2_Cb_t pFctForceConvergency2; Bemf_OtfResetPLL_Cb_t pFctBemfOtfResetPLL; Bemf_SpeedReliabilityCheck_Cb_t pFctBemf_SpeedReliabilityCheck; }; /** * @} */ /** * @} */ /** @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*__BEMF_SPEEDNPOSFDBK_H*/ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
3,649
C
33.112149
103
0.611674
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/cos_tab_128.h
/** ****************************************************************************** * @file cos_tab_128.h * @author Piak Electronic Design B.V. * @brief This file is part of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 Piak Electronic Design B.V. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** */ #ifndef _cos_128_h #define _cos_128_h // Cos table: _RNDL(cos(i*pi/(2*_MTL))*(2 << _MNB)) static long _cst_128[_MTL+1] = { 1073741824, 1073660973, 1073418433, 1073014240, 1072448455, 1071721163, 1070832474, 1069782521, 1068571464, 1067199483, 1065666786, 1063973603, 1062120190, 1060106826, 1057933813, 1055601479, 1053110176, 1050460278, 1047652185, 1044686319, 1041563127, 1038283080, 1034846671, 1031254418, 1027506862, 1023604567, 1019548121, 1015338134, 1010975242, 1006460100, 1001793390, 996975812, 992008094, 986890984, 981625251, 976211688, 970651112, 964944360, 959092290, 953095785, 946955747, 940673101, 934248793, 927683790, 920979082, 914135678, 907154608, 900036924, 892783698, 885396022, 877875009, 870221790, 862437520, 854523370, 846480531, 838310216, 830013654, 821592095, 813046808, 804379079, 795590213, 786681534, 777654384, 768510122, 759250125, 749875788, 740388522, 730789757, 721080937, 711263525, 701339000, 691308855, 681174602, 670937767, 660599890, 650162530, 639627258, 628995660, 618269338, 607449906, 596538995, 585538248, 574449320, 563273883, 552013618, 540670223, 529245404, 517740883, 506158392, 494499676, 482766489, 470960600, 459083786, 447137835, 435124548, 423045732, 410903207, 398698801, 386434353, 374111709, 361732726, 349299266, 336813204, 324276419, 311690799, 299058239, 286380643, 273659918, 260897982, 248096755, 235258165, 222384147, 209476638, 196537583, 183568930, 170572633, 157550647, 144504935, 131437462, 118350194, 105245103, 92124163, 78989349, 65842639, 52686014, 39521455, 26350943, 13176464, 0 }; #endif // cos_128.h /************************ (C) COPYRIGHT 2023 Piak Electronic Design B.V. *****END OF FILE****/
2,511
C
44.672726
94
0.655516
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/ics_dd_pwmncurrfdbk.h
/** ****************************************************************************** * @file ics_dd_pwmncurrfdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * ICS DD PWM current feedback component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup PWMnCurrFdbk_ICS_DD */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __ICS_DD_PWMNCURRFDBK_H #define __ICS_DD_PWMNCURRFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @defgroup PWMnCurrFdbk_ICS_DD Insulated Current Sensing Parameters * * @brief Common definitions for Insulated Current Sensors based PWM & Current Feedback components * @{ */ #define GPIO_NoRemap_TIM1 ((uint32_t)(0)) #define SHIFTED_TIMs ((uint8_t) 1) #define NO_SHIFTED_TIMs ((uint8_t) 0) /** * @brief ICS_DD parameters definition */ typedef struct { TIM_TypeDef *TIMx; /**< It contains the pointer to the timer used for PWM generation. It must equal to TIM1 if bInstanceNbr is equal to 1, to TIM8 otherwise */ uint16_t Tw; /**< It is used for switching the context in dual MC. It contains biggest delay (expressed in counter ticks) between the counter crest and ADC latest trigger */ uint8_t InstanceNbr; /**< Instance number with reference to PWMC base class. It is necessary to properly synchronize TIM8 with TIM1 at peripheral initializations */ uint8_t FreqRatio; /**< It is used in case of dual MC to synchronize TIM1 and TIM8. It has effect only on the second instanced object and must be equal to the ratio between the two PWM frequencies (higher/lower). Supported values are 1, 2 or 3 */ uint8_t IsHigherFreqTim; /**< When bFreqRatio is greather than 1 this param is used to indicate if this instance is the one with the highest frequency. Allowed value are: HIGHER_FREQ or LOWER_FREQ */ uint8_t IaChannel; /**< ADC channel used for conversion of current Ia. It must be equal to ADC_CHANNEL_x x= 0, ..., 15*/ uint8_t IbChannel; /**< ADC channel used for conversion of current Ib. It must be equal to ADC_CHANNEL_x x= 0, ..., 15*/ uint8_t RepetitionCounter; /**< It expresses the number of PWM periods to be elapsed before compare registers are updated again. In particular: RepetitionCounter= (2* #PWM periods)-1 */ } ICS_Params_t; /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*__ICS_DD_PWMNCURRFDBK_H*/ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
4,576
C
40.234234
100
0.439467
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/fixpmath.h
/** ****************************************************************************** * @file fixpmath.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains the fixed-point format definitions used * in Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup FixpMath */ #ifndef _FIXPMATH_H_ #define _FIXPMATH_H_ /* Global default format */ #define FIXP_FMT (24) /* Per unit internal format is q24 */ #ifdef FIXP_PRECISION_FLOAT #define FIXP_FMT_MPY (16777216.0f) /* Must be 2^FIXP_FMT */ #else #define FIXP_FMT_MPY (16777216.0L) /* Must be 2^FIXP_FMT */ #endif #ifdef FIXP_CORDIC_INLINE #include "mc_cordic.h" #endif /* FIXP_CORDIC_INLINE */ #include <stdint.h> /* int32_t */ #include <math.h> /* float_t, 2PI */ #ifndef M_TWOPI #define M_TWOPI 6.283185307179586476925286766559L #endif #define MATH_TWO_PI (M_TWOPI) typedef int32_t fixp_t; /* Internal multiply macro */ #define FIXP_MPY(a, b, n) ( (fixp_t)(((int64_t) (a) * (b)) >> (n)) ) /* Conversion from floating point to fixed point */ #ifdef FIXP_PRECISION_FLOAT #define FIXP(A) (fixp_t) ((A) * FIXP_FMT_MPY) #define FIXP0(A) (fixp0_t) ((A) * 1.0f) #define FIXP1(A) (fixp1_t) ((A) * 2.0f) #define FIXP2(A) (fixp2_t) ((A) * 4.0f) #define FIXP3(A) (fixp3_t) ((A) * 8.0f) #define FIXP4(A) (fixp4_t) ((A) * 16.0f) #define FIXP5(A) (fixp5_t) ((A) * 32.0f) #define FIXP6(A) (fixp6_t) ((A) * 64.0f) #define FIXP7(A) (fixp7_t) ((A) * 128.0f) #define FIXP8(A) (fixp8_t) ((A) * 256.0f) #define FIXP9(A) (fixp9_t) ((A) * 512.0f) #define FIXP10(A) (fixp10_t) ((A) * 1024.0f) #define FIXP11(A) (fixp11_t) ((A) * 2048.0f) #define FIXP12(A) (fixp10_t) ((A) * 4096.0f) #define FIXP13(A) (fixp13_t) ((A) * 8192.0f) #define FIXP14(A) (fixp14_t) ((A) * 16384.0f) #define FIXP15(A) (fixp15_t) ((A) * 32768.0f) #define FIXP16(A) (fixp16_t) ((A) * 65536.0f) #define FIXP17(A) (fixp17_t) ((A) * 131072.0f) #define FIXP18(A) (fixp18_t) ((A) * 262144.0f) #define FIXP19(A) (fixp19_t) ((A) * 524288.0f) #define FIXP20(A) (fixp20_t) ((A) * 1048576.0f) #define FIXP21(A) (fixp21_t) ((A) * 2097152.0f) #define FIXP22(A) (fixp22_t) ((A) * 4194304.0f) #define FIXP23(A) (fixp23_t) ((A) * 8388608.0f) #define FIXP24(A) (fixp24_t) ((A) * 16777216.0f) #define FIXP25(A) (fixp25_t) ((A) * 33554432.0f) #define FIXP26(A) (fixp26_t) ((A) * 67108864.0f) #define FIXP27(A) (fixp27_t) ((A) * 134217728.0f) #define FIXP28(A) (fixp28_t) ((A) * 268435456.0f) #define FIXP29(A) (fixp29_t) ((A) * 536870912.0f) #define FIXP30(A) (fixp30_t) ((A) * 1073741824.0f) #define FIXP31(A) (fixp31_t) ((A) * 2147483648.0f) #else /* FIXP_PRECISION_FLOAT */ #define FIXP(A) (fixp_t) ((A) * FIXP_FMT_MPY) #define FIXP0(A) (fixp0_t) ((A) * 1.0L) #define FIXP1(A) (fixp1_t) ((A) * 2.0L) #define FIXP2(A) (fixp2_t) ((A) * 4.0L) #define FIXP3(A) (fixp3_t) ((A) * 8.0L) #define FIXP4(A) (fixp4_t) ((A) * 16.0L) #define FIXP5(A) (fixp5_t) ((A) * 32.0L) #define FIXP6(A) (fixp6_t) ((A) * 64.0L) #define FIXP7(A) (fixp7_t) ((A) * 128.0L) #define FIXP8(A) (fixp8_t) ((A) * 256.0L) #define FIXP9(A) (fixp9_t) ((A) * 512.0L) #define FIXP10(A) (fixp10_t) ((A) * 1024.0L) #define FIXP11(A) (fixp11_t) ((A) * 2048.0L) #define FIXP12(A) (fixp10_t) ((A) * 4096.0L) #define FIXP13(A) (fixp13_t) ((A) * 8192.0L) #define FIXP14(A) (fixp14_t) ((A) * 16384.0L) #define FIXP15(A) (fixp15_t) ((A) * 32768.0L) #define FIXP16(A) (fixp16_t) ((A) * 65536.0L) #define FIXP17(A) (fixp17_t) ((A) * 131072.0L) #define FIXP18(A) (fixp18_t) ((A) * 262144.0L) #define FIXP19(A) (fixp19_t) ((A) * 524288.0L) #define FIXP20(A) (fixp20_t) ((A) * 1048576.0L) #define FIXP21(A) (fixp21_t) ((A) * 2097152.0L) #define FIXP22(A) (fixp22_t) ((A) * 4194304.0L) #define FIXP23(A) (fixp23_t) ((A) * 8388608.0L) #define FIXP24(A) (fixp24_t) ((A) * 16777216.0L) #define FIXP25(A) (fixp25_t) ((A) * 33554432.0L) #define FIXP26(A) (fixp26_t) ((A) * 67108864.0L) #define FIXP27(A) (fixp27_t) ((A) * 134217728.0L) #define FIXP28(A) (fixp28_t) ((A) * 268435456.0L) #define FIXP29(A) (fixp29_t) ((A) * 536870912.0L) #define FIXP30(A) (fixp30_t) ((A) * 1073741824.0L) #define FIXP31(A) (fixp31_t) ((A) * 2147483648.0L) #endif /* FIXP_PRECISION_FLOAT */ /* Conversion between two fixed point scales */ #define FIXPtoFIXP29(A) ((long) (A) << (29 - FIXP_FMT)) /* ToDo: take sign of shift into account */ #define FIXPtoFIXP30(A) ((long) (A) << (30 - FIXP_FMT)) #define FIXPtoFIXP31(A) ((long) (A) << (31 - FIXP_FMT)) #define FIXP30_toFIXP(A) ((long) (A) >> (30 - FIXP_FMT)) /* Conversion to float */ #define FIXP_toF(A) ((float_t)(((float_t) (A)) / FIXP_FMT_MPY)) #ifdef FIXP_PRECISION_FLOAT #define FIXP8_toF(A) ((float_t)(((float_t) (A)) / 256.0f)) #define FIXP11_toF(A) ((float_t)(((float_t) (A)) / 2048.0f)) #define FIXP15_toF(A) ((float_t)(((float_t) (A)) / 32768.0f)) #define FIXP16_toF(A) ((float_t)(((float_t) (A)) / 65536.0f)) #define FIXP20_toF(A) ((float_t)(((float_t) (A)) / 1048576.0f)) #define FIXP24_toF(A) ((float_t)(((float_t) (A)) / 16777216.0f)) #define FIXP29_toF(A) ((float_t)(((float_t) (A)) / 536870912.0f)) #define FIXP30_toF(A) ((float_t)(((float_t) (A)) / 1073741824.0f)) #define FIXP31_toF(A) ((float_t)(((float_t) (A)) / 2147483648.0f)) #else /* FIXP_PRECISION_FLOAT */ #define FIXP8_toF(A) ((float_t)(((float_t) (A)) / 256.0L)) #define FIXP11_toF(A) ((float_t)(((float_t) (A)) / 2048.0L)) #define FIXP15_toF(A) ((float_t)(((float_t) (A)) / 32768.0L)) #define FIXP16_toF(A) ((float_t)(((float_t) (A)) / 65536.0L)) #define FIXP20_toF(A) ((float_t)(((float_t) (A)) / 1048576.0L)) #define FIXP24_toF(A) ((float_t)(((float_t) (A)) / 16777216.0L)) #define FIXP29_toF(A) ((float_t)(((float_t) (A)) / 536870912.0L)) #define FIXP30_toF(A) ((float_t)(((float_t) (A)) / 1073741824.0L)) #define FIXP31_toF(A) ((float_t)(((float_t) (A)) / 2147483648.0L)) #endif /* FIXP_PRECISION_FLOAT */ /* Multiplication */ #define FIXP_mpy(a, b) FIXP_MPY((a), (b), FIXP_FMT) #define FIXP1_mpy(a, b) FIXP_MPY((a), (b), 1) #define FIXP2_mpy(a, b) FIXP_MPY((a), (b), 2) #define FIXP3_mpy(a, b) FIXP_MPY((a), (b), 3) #define FIXP4_mpy(a, b) FIXP_MPY((a), (b), 4) #define FIXP5_mpy(a, b) FIXP_MPY((a), (b), 5) #define FIXP6_mpy(a, b) FIXP_MPY((a), (b), 6) #define FIXP7_mpy(a, b) FIXP_MPY((a), (b), 7) #define FIXP8_mpy(a, b) FIXP_MPY((a), (b), 8) #define FIXP9_mpy(a, b) FIXP_MPY((a), (b), 9) #define FIXP10_mpy(a, b) FIXP_MPY((a), (b), 10) #define FIXP11_mpy(a, b) FIXP_MPY((a), (b), 11) #define FIXP12_mpy(a, b) FIXP_MPY((a), (b), 12) #define FIXP13_mpy(a, b) FIXP_MPY((a), (b), 13) #define FIXP14_mpy(a, b) FIXP_MPY((a), (b), 14) #define FIXP15_mpy(a, b) FIXP_MPY((a), (b), 15) #define FIXP16_mpy(a, b) FIXP_MPY((a), (b), 16) #define FIXP17_mpy(a, b) FIXP_MPY((a), (b), 17) #define FIXP18_mpy(a, b) FIXP_MPY((a), (b), 18) #define FIXP19_mpy(a, b) FIXP_MPY((a), (b), 19) #define FIXP20_mpy(a, b) FIXP_MPY((a), (b), 20) #define FIXP21_mpy(a, b) FIXP_MPY((a), (b), 21) #define FIXP22_mpy(a, b) FIXP_MPY((a), (b), 22) #define FIXP23_mpy(a, b) FIXP_MPY((a), (b), 23) #define FIXP24_mpy(a, b) FIXP_MPY((a), (b), 24) #define FIXP25_mpy(a, b) FIXP_MPY((a), (b), 25) #define FIXP26_mpy(a, b) FIXP_MPY((a), (b), 26) #define FIXP27_mpy(a, b) FIXP_MPY((a), (b), 27) #define FIXP28_mpy(a, b) FIXP_MPY((a), (b), 28) #define FIXP29_mpy(a, b) FIXP_MPY((a), (b), 29) #define FIXP30_mpy(a, b) FIXP_MPY((a), (b), 30) #define FIXP31_mpy(a, b) FIXP_MPY((a), (b), 31) /* Division */ #define FIXP_DIV(a, b, n) ((fixp_t)((((int64_t) (a)) << (n)) / (b))) #define FIXP_div(a, b) FIXP_DIV((a), (b), FIXP_FMT) #define FIXP30_div(a, b) FIXP_DIV((a), (b), 30) /* ToDo Saturating mpy not implemented, using standard mpy instead */ #define FIXP_rsmpy(a, b) FIXP_MPY((a), (b), FIXP_FMT) #define FIXP1_rsmpy(a, b) FIXP_MPY((a), (b), 1) #define FIXP2_rsmpy(a, b) FIXP_MPY((a), (b), 2) #define FIXP3_rsmpy(a, b) FIXP_MPY((a), (b), 3) #define FIXP4_rsmpy(a, b) FIXP_MPY((a), (b), 4) #define FIXP5_rsmpy(a, b) FIXP_MPY((a), (b), 5) #define FIXP6_rsmpy(a, b) FIXP_MPY((a), (b), 6) #define FIXP7_rsmpy(a, b) FIXP_MPY((a), (b), 7) #define FIXP8_rsmpy(a, b) FIXP_MPY((a), (b), 8) #define FIXP9_rsmpy(a, b) FIXP_MPY((a), (b), 9) #define FIXP10_rsmpy(a, b) FIXP_MPY((a), (b), 10) #define FIXP11_rsmpy(a, b) FIXP_MPY((a), (b), 11) #define FIXP12_rsmpy(a, b) FIXP_MPY((a), (b), 12) #define FIXP13_rsmpy(a, b) FIXP_MPY((a), (b), 13) #define FIXP14_rsmpy(a, b) FIXP_MPY((a), (b), 14) #define FIXP15_rsmpy(a, b) FIXP_MPY((a), (b), 15) #define FIXP16_rsmpy(a, b) FIXP_MPY((a), (b), 16) #define FIXP17_rsmpy(a, b) FIXP_MPY((a), (b), 17) #define FIXP18_rsmpy(a, b) FIXP_MPY((a), (b), 18) #define FIXP19_rsmpy(a, b) FIXP_MPY((a), (b), 19) #define FIXP20_rsmpy(a, b) FIXP_MPY((a), (b), 20) #define FIXP21_rsmpy(a, b) FIXP_MPY((a), (b), 21) #define FIXP22_rsmpy(a, b) FIXP_MPY((a), (b), 22) #define FIXP23_rsmpy(a, b) FIXP_MPY((a), (b), 23) #define FIXP24_rsmpy(a, b) FIXP_MPY((a), (b), 24) #define FIXP25_rsmpy(a, b) FIXP_MPY((a), (b), 25) #define FIXP26_rsmpy(a, b) FIXP_MPY((a), (b), 26) #define FIXP27_rsmpy(a, b) FIXP_MPY((a), (b), 27) #define FIXP28_rsmpy(a, b) FIXP_MPY((a), (b), 28) #define FIXP29_rsmpy(a, b) FIXP_MPY((a), (b), 29) #define FIXP30_rsmpy(a, b) FIXP_MPY((a), (b), 30) /* Division by bitshift */ #define _FIXPdiv2(a) ((a) >> 1) #define _FIXPdiv4(a) ((a) >> 2) #define _FIXPdiv8(a) ((a) >> 3) /* Included after all the _FIXPNrsmpy() macros */ #include "fixpmpyxufloat.h" /* Trigonometric * (All implemented as functions, below) */ /* Saturation */ #define FIXP_sat(A, V_MAX, V_MIN) ((A) > (V_MAX) ? (V_MAX) : (A) < (V_MIN) ? (V_MIN) : (A)) /* Absolute */ #define FIXP_abs(A) ((A) >= 0 ? (A) : -(A)) #define FIXP30_abs(A) FIXP_abs(A) typedef fixp_t fixp1_t; typedef fixp_t fixp2_t; typedef fixp_t fixp3_t; typedef fixp_t fixp4_t; typedef fixp_t fixp5_t; typedef fixp_t fixp6_t; typedef fixp_t fixp7_t; typedef fixp_t fixp8_t; typedef fixp_t fixp9_t; typedef fixp_t fixp10_t; typedef fixp_t fixp11_t; typedef fixp_t fixp12_t; typedef fixp_t fixp13_t; typedef fixp_t fixp14_t; typedef fixp_t fixp15_t; typedef fixp_t fixp16_t; /*!< @brief fixed-point 16 Bit format */ typedef fixp_t fixp17_t; typedef fixp_t fixp18_t; typedef fixp_t fixp19_t; typedef fixp_t fixp20_t; typedef fixp_t fixp21_t; typedef fixp_t fixp22_t; typedef fixp_t fixp23_t; typedef fixp_t fixp24_t; /*!< @brief fixed-point 24 Bit format */ typedef fixp_t fixp25_t; typedef fixp_t fixp26_t; typedef fixp_t fixp27_t; typedef fixp_t fixp28_t; typedef fixp_t fixp29_t; typedef fixp_t fixp30_t; /*!< @brief fixed-point 30 Bit format */ typedef fixp_t fixp31_t; typedef int_least8_t fixpFmt_t; typedef struct { fixp_t value; fixpFmt_t fixpFmt; } FIXP_scaled_t; #include "fixpmath_types.h" void FIXPSCALED_floatToFIXPscaled(const float value, FIXP_scaled_t *pFps); void FIXPSCALED_floatToFIXPscaled_exp(const float value, FIXP_scaled_t *pFps, fixpFmt_t exponent); float FIXPSCALED_FIXPscaledToFloat(const FIXP_scaled_t *pFps); void FIXPSCALED_doubleToFIXPscaled(const double value, FIXP_scaled_t *pFps); void FIXPSCALED_calculateScaleFactor( const fixpFmt_t source_fixpFmt, const fixpFmt_t target_fixpFmt, const float source_fullscale, const float target_fullscale, const float datascale_factor, FIXP_scaled_t *pFps); static inline fixp_t FIXP_mpyFIXPscaled(const fixp_t a, const FIXP_scaled_t *pFps) { /* Returned value is in the same format as parameter a */ return FIXP_MPY(a, pFps->value, pFps->fixpFmt); } void FIXP30_CosSinPU(const fixp30_t angle_pu, FIXP_CosSin_t *pCosSin); void FIXP30_polar(const fixp30_t x, const fixp30_t y, fixp30_t *pAngle_pu, fixp30_t *pMagnitude); /* Function declarations */ void FIXPMATH_init(void); fixp_t FIXP_mag(const fixp_t a, const fixp_t b); fixp30_t FIXP30_mag(const fixp30_t a, const fixp30_t b); fixp24_t FIXP24_atan2_PU(fixp24_t beta, fixp24_t alpha); fixp29_t FIXP29_atan2_PU(fixp30_t beta, fixp30_t alpha); fixp30_t FIXP30_atan2_PU(fixp30_t beta, fixp30_t alpha); fixp_t FIXP_cos(fixp_t angle_rad); fixp_t FIXP_cos_PU(fixp_t angle_pu); fixp30_t FIXP30_cos_PU(fixp30_t angle_pu); fixp30_t FIXP30_sin_PU(fixp30_t angle_pu); fixp_t FIXP_exp(fixp_t power); fixp30_t FIXP30_sqrt(const fixp30_t value); fixp24_t FIXP24_sqrt(const fixp24_t value); #endif /* _FIXPMATH_H_ */ /* end of fixpmath.h */
12,794
C
38.613003
99
0.620447
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/revup_ctrl_sixstep.h
/** ****************************************************************************** * @file revup_ctrl_sixstep.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * Six-step variant of the Rev up control component of the Motor Control * SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup RevUpCtrl6S */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef REVUP_CTRL_SIXSTEP_H #define REVUP_CTRL_SIXSTEP_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "mc_type.h" #include "speed_ctrl.h" #include "virtual_speed_sensor.h" #include "bus_voltage_sensor.h" #include "power_stage_parameters.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup RevUpCtrl * @{ */ /** @addtogroup RevUpCtrl6S * @{ */ /* Exported constants --------------------------------------------------------*/ /** * @brief Maximum number of phases allowed for RevUp process. * */ #define RUC_MAX_PHASE_NUMBER 5u /** * @brief RevUpCtrl_PhaseParams_t structure used for phases definition * */ typedef struct { uint16_t hDurationms; /* Duration of the RevUp phase. This parameter is expressed in millisecond.*/ int16_t hFinalMecSpeedUnit; /* Mechanical speed assumed by VSS at the end of the RevUp phase. Expressed in the unit defined by #SPEED_UNIT */ uint16_t hFinalPulse; /**< @brief Final pulse factor according to sensed Vbus value This field parameter is dedicated to 6-Step use */ void * pNext; /* Pointer on the next phase section to proceed This parameter is NULL for the last element.*/ } RevUpCtrl_PhaseParams_t; /** * * */ typedef struct { uint16_t hRUCFrequencyHz; /* Frequency call to main RevUp procedure RUC_Exec. This parameter is equal to speed loop frequency. */ int16_t hStartingMecAngle; /* Starting angle of programmed RevUp.*/ uint16_t hPhaseRemainingTicks; /* Number of clock events remaining to complete the phase. */ int16_t hDirection; /* Motor direction. This parameter can be any value -1 or +1 */ RevUpCtrl_PhaseParams_t *pCurrentPhaseParams; /* Pointer on the current RevUp phase processed. */ RevUpCtrl_PhaseParams_t ParamsData[RUC_MAX_PHASE_NUMBER]; /* Start up Phases sequences used by RevUp controller. Up to five phases can be used for the start up. */ uint16_t PulseUpdateFactor; /**< @brief Used to update the 6-Step rev-up pulse to the actual Vbus value. This field parameter is dedicated to 6-Step use */ uint8_t bPhaseNbr; /* Number of phases relative to the programmed RevUp sequence. This parameter can be any value from 1 to 5 */ uint8_t bFirstAccelerationStage; /* Indicate the phase to start the final acceleration. At start of this stage sensor-less algorithm cleared.*/ uint16_t hMinStartUpValidSpeed; /* Minimum rotor speed required to validate the startup. This parameter is expressed in SPPED_UNIT */ bool EnteredZone1; /**< @brief Flag to indicate that the minimum rotor speed has been reached. */ uint8_t bStageCnt; /**< @brief Counter of executed phases. This parameter can be any value from 0 to 5 */ SpeednTorqCtrl_Handle_t *pSTC; /**< @brief Speed and torque controller object used by RevUpCtrl.*/ VirtualSpeedSensor_Handle_t *pVSS; /**< @brief Virtual speed sensor object used by RevUpCtrl.*/ } RevUpCtrl_Handle_t; /* Exported functions ------------------------------------------------------- */ /* Initializes and configures the RevUpCtrl Component */ void RUC_Init(RevUpCtrl_Handle_t *pHandle, SpeednTorqCtrl_Handle_t *pSTC, VirtualSpeedSensor_Handle_t *pVSS); /* Initializes the internal RevUp controller state */ void RUC_Clear(RevUpCtrl_Handle_t *pHandle, int16_t hMotorDirection); /* Updates the pulse according to sensed Vbus value */ void RUC_UpdatePulse(RevUpCtrl_Handle_t *pHandle, BusVoltageSensor_Handle_t *BusVHandle); /* Main Rev-Up controller procedure executing overall programmed phases. */ bool RUC_Exec(RevUpCtrl_Handle_t *pHandle); /* Provide current state of Rev-Up controller procedure */ bool RUC_Completed(RevUpCtrl_Handle_t *pHandle); /* Allows to exit from RevUp process at the current Rotor speed. */ void RUC_Stop(RevUpCtrl_Handle_t *pHandle); /* Checks that alignment and first acceleration stage are completed. */ bool RUC_FirstAccelerationStageReached(RevUpCtrl_Handle_t *pHandle); /* Checks that minimum speed is reached. */ bool RUC_ObserverSpeedReached( RevUpCtrl_Handle_t * pHandle); /* Allows to modify duration (ms unit) of a selected phase. */ void RUC_SetPhaseDurationms(RevUpCtrl_Handle_t *pHandle, uint8_t bPhase, uint16_t hDurationms); /* Allows to modify targeted mechanical speed of a selected phase. */ void RUC_SetPhaseFinalMecSpeedUnit(RevUpCtrl_Handle_t *pHandle, uint8_t bPhase, int16_t hFinalMecSpeedUnit); /* Function used to set the final Pulse targeted at the end of a specific phase. */ void RUC_SetPhaseFinalPulse(RevUpCtrl_Handle_t *pHandle, uint8_t bPhase, uint16_t hFinalTorque); /* Allows to read duration set in selected phase. */ uint16_t RUC_GetPhaseDurationms(RevUpCtrl_Handle_t *pHandle, uint8_t bPhase); /* Allows to read targeted Rotor speed set in selected phase. */ int16_t RUC_GetPhaseFinalMecSpeedUnit(RevUpCtrl_Handle_t *pHandle, uint8_t bPhase); /* Function used to read the Final pulse factor of a specific RevUp phase */ int16_t RUC_GetPhaseFinalPulse(RevUpCtrl_Handle_t *pHandle, uint8_t bPhase); /* Allows to read total number of programmed phases */ uint8_t RUC_GetNumberOfPhases(RevUpCtrl_Handle_t *pHandle); /* It is used to check if this stage is used for align motor. */ uint8_t RUC_IsAlignStageNow(RevUpCtrl_Handle_t * pHandle); /* Allows to read a programmed phase. */ bool RUC_GetPhase(RevUpCtrl_Handle_t *pHandle, uint8_t phaseNumber, RevUpCtrl_PhaseParams_t *phaseData); /* Allows to configure a Rev-Up phase. */ bool RUC_SetPhase(RevUpCtrl_Handle_t *pHandle, uint8_t phaseNumber, RevUpCtrl_PhaseParams_t *phaseData); /* It is used to check the spinning direction of the motor. */ int16_t RUC_GetDirection(RevUpCtrl_Handle_t * pHandle); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* REVUP_CTRL_SIXSTEP_H */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
7,545
C
37.304568
115
0.62505
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/pwmc_3pwm.h
/** ****************************************************************************** * @file pwmc_3pwm.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * pwmc_3pwm component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup pwmc_3pwm */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __PWMC_3PWM_H #define __PWMC_3PWM_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "pwm_common_sixstep.h" /** * @addtogroup MCSDK * @{ */ /** * @addtogroup pwm_curr_fdbk_6s * @{ */ /** * @addtogroup pwmc_3pwm * @{ */ /* Exported constants --------------------------------------------------------*/ /* Exported types ------------------------------------------------------------*/ /** * @brief ThreePwm parameters definition */ typedef struct { TIM_TypeDef * TIMx; /*!< It contains the pointer to the timer used for PWM generation. */ uint8_t RepetitionCounter; /*!< It expresses the number of PWM periods to be elapsed before compare registers are updated again. In particular: RepetitionCounter= (2* #PWM periods)-1*/ uint32_t OCPolarity; /*!< timer channel output polarity.*/ GPIO_TypeDef * pwm_en_u_port; /*!< phase u enable driver signal GPIO port */ uint16_t pwm_en_u_pin; /*!< phase u enable driver signal pin */ GPIO_TypeDef * pwm_en_v_port; /*!< phase v enable driver signal GPIO port */ uint16_t pwm_en_v_pin; /*!< phase v enable driver signal pin */ GPIO_TypeDef * pwm_en_w_port; /*!< phase w enable driver signal GPIO port */ uint16_t pwm_en_w_pin; /*!< phase w enable driver signal pin */ } ThreePwm_Params_t; /** * @brief Handle structure of the PWMC_ThreePwm Component */ typedef struct { PWMC_Handle_t _Super; /*!< */ bool FastDemag; /*!< This flag is set when the fast-demagmatization is activated.*/ bool Oversampling; /*!< This flag is set when the bemf oversampling feature is enabled.*/ bool FastDemagUpdated; /*!< This flag is set when fast-demagmatization is configuration is switched off.*/ uint32_t NegOCPolarity; /*!< Channel output opposite polarity.*/ uint32_t NegOCNPolarity; /*!< Complementary channel output opposite polarity. */ uint16_t DemagCounter; ThreePwm_Params_t const * pParams_str; } PWMC_ThreePwm_Handle_t; /* Exported functions ------------------------------------------------------- */ /** * It initializes TIMx and NVIC */ void ThreePwm_Init( PWMC_ThreePwm_Handle_t * pHandle ); /** * It updates the stored duty cycle variable. */ void PWMC_SetPhaseVoltage( PWMC_Handle_t * pHandle, uint16_t DutyCycle ); /** * It writes the duty cycle into shadow timer registers. */ void ThreePwm_LoadNextStep( PWMC_ThreePwm_Handle_t * pHandle, int16_t Direction ); /** * It uploads the duty cycle into timer registers. */ bool ThreePwm_ApplyNextStep( PWMC_ThreePwm_Handle_t * pHandle ); /** * It uploads the duty cycle into timer registers. */ bool ThreePwm_IsFastDemagUpdated( PWMC_ThreePwm_Handle_t * pHandle ); /** * It resets the polarity of the timer PWM channel outputs to default */ void ThreePwm_ResetOCPolarity( PWMC_ThreePwm_Handle_t * pHandle ); /** * It turns on low sides switches. This function is intended to be * used for charging boot capacitors of driving section. It has to be * called each motor start-up when using high voltage drivers */ void ThreePwm_TurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks); /** * This function enables the PWM outputs */ void ThreePwm_SwitchOnPWM( PWMC_Handle_t * pHdl ); /** * It disables PWM generation on the proper Timer peripheral acting on * MOE bit and reset the TIM status */ void ThreePwm_SwitchOffPWM( PWMC_Handle_t * pHdl ); /** * It sets the capcture compare of the timer channel used for ADC triggering */ void ThreePwm_SetADCTriggerChannel( PWMC_Handle_t * pHdl, uint16_t SamplingPoint ); /** * It is used to check if an overcurrent occurred since last call. */ uint16_t ThreePwm_IsOverCurrentOccurred( PWMC_Handle_t * pHdl ); /** * It contains the Break event interrupt */ void * ThreePwm_BRK_IRQHandler( PWMC_ThreePwm_Handle_t * pHandle ); /** * It is used to return the fast demag flag. */ uint8_t ThreePwm_FastDemagFlag( PWMC_Handle_t * pHdl ); /** * It increases the demagnetization counter in the update event. */ void ThreePwm_UpdatePwmDemagCounter( PWMC_ThreePwm_Handle_t * pHandle ); /** * It disables the update event and the updated of the demagnetization counter. */ void ThreePwm_DisablePwmDemagCounter( PWMC_ThreePwm_Handle_t * pHandle ); /** * @} */ /** * @} */ /** @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*__PWMC_3PWM_H*/ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
5,841
C
30.75
115
0.580722
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/mc_polpulse.h
/** ****************************************************************************** * @file mc_polpulse.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * PolPulse application component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup MC_PolPulse */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef _MC_POLPULSE_H_ #define _MC_POLPULSE_H_ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "polpulse.h" #include "pwm_curr_fdbk.h" #include "speed_pos_fdbk_hso.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup MC_PolPulse * @{ */ /* Exported defines ------------------------------------------------------------*/ /* Exported types ------------------------------------------------------------*/ /** * @brief PolPulse application handler structure * * This structure holds the components and parameters needed to implement the PolPulse * * A pointer on a structure of this type is passed to each * function of the @ref MC_PolPulse. */ typedef struct { POLPULSE_Obj PolpulseObj; /*!< @brief pointer on polPulse component handler.*/ PWMC_Handle_t * pPWM; /*!< @brief pointer PWM current feedback component handler .*/ SPD_Handle_t *pSPD; /*!< @brief pointer on sensorless component handler.*/ TIM_TypeDef * TIMx; /*!< @brief timer used for PWM generation.*/ int16_t pulse_countdown; /*!< @brief pulse counter.*/ bool flagPolePulseActivation; /*!< @brief PolPulse activation flag.*/ }MC_PolPulse_Handle_t; void MC_POLPULSE_init(MC_PolPulse_Handle_t *pHandle, POLPULSE_Params *params, FLASH_Params_t const *flashParams); void MC_POLPULSE_SetAngle(MC_PolPulse_Handle_t *pHandle, const fixp30_t angle_pu); void MC_POLPULSE_run(MC_PolPulse_Handle_t *pHandle, const fixp30_t angle_pu); void PulseCountDown(MC_PolPulse_Handle_t *pHandle); /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* _MC_POLPULSE_H_ */ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
2,872
C
31.647727
97
0.539345
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/profiler_types.h
/** ****************************************************************************** * @file profiler_types.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions for the * profiler component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup Profiler */ #ifndef _PROFILER_TYPES_H_ #define _PROFILER_TYPES_H_ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "mc_type.h" #include "speed_torq_ctrl_hso.h" #include "mc_curr_ctrl.h" #include "speed_pos_fdbk_hso.h" #include "mc_polpulse.h" #include "bus_voltage.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup Profiler * @{ */ /** * @brief Handle of profiler motor component * * This structure holds all the components needed to run the profiler * * A pointer on a structure of this type is passed to main * functions of the @ref Profiler. */ typedef struct { FOCVars_t* pFocVars; /*!< @brief todo */ SPD_Handle_t *pSPD; /*!< @brief todo */ STC_Handle_t *pSTC; /*!< @brief todo */ POLPULSE_Obj *pPolpulse; /*!< @brief todo */ CurrCtrl_Handle_t *pCurrCtrl; /*!< @brief todo */ PWMC_Handle_t * pPWM; /*!< @brief todo */ BusVoltageSensor_Handle_t *pVBus; /*!< @brief todo */ }ProfilerMotor_Handle_t; /** * @brief todo */ typedef ProfilerMotor_Handle_t* MOTOR_Handle; /** * @brief todo */ typedef struct _PROFILER_Params_ { /* General parameters */ float_t isrFreq_Hz; float_t background_rate_hz; /*!< @brief todo */ float_t fullScaleFreq_Hz; /*!< @brief todo */ float_t fullScaleCurrent_A; /*!< @brief todo */ float_t fullScaleVoltage_V; /*!< @brief todo */ float_t voltagefilterpole_rps; /*!< @brief todo */ float_t PolePairs; /*!< @brief todo */ /* DC / AC measurments */ float_t dcac_PowerDC_goal_W; /*!< @brief todo */ float_t dcac_DCmax_current_A; /*!< @brief todo */ float_t dcac_duty_maxgoal; /*!< @brief todo */ float_t dcac_dc_measurement_time_s; /*!< @brief todo */ float_t dcac_ac_measurement_time_s; /*!< @brief todo */ float_t dcac_duty_ramping_time_s; /*!< @brief todo */ float_t dcac_current_ramping_time_s; /*!< @brief todo */ float_t dcac_ac_freq_Hz; /*!< @brief todo */ bool glue_dcac_fluxestim_on; /*!< @brief skip ramp down and ramp up */ /* Flux estimation */ float_t fluxestim_measurement_time_s; /*!< @brief todo */ float_t fluxestim_Idref_A; /*!< @brief todo */ float_t fluxestim_current_ramping_time_s; /*!< @brief todo */ float_t fluxestim_speed_Hz; /*!< @brief todo */ float_t fluxestim_speed_ramping_time_s; /*!< @brief todo */ } PROFILER_Params; /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* _PROFILER_TYPES_H_ */ /* end of profiler_types.h */
3,821
C
31.117647
88
0.506412
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/F7xx/Src/r3_1_f7xx_pwm_curr_fdbk.c
/** ****************************************************************************** * @file r3_1_f7xx_pwm_curr_fdbk.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement current sensor * class to be stantiated when the three shunts current sensing * topology is used. * * It is specifically designed for STM32F7XX microcontrollers. * + MCU peripheral and handle initialization function * + three shunt current sensing * + space vector modulation function * + ADC sampling function * ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * * @ingroup R3_1_F7XX_pwm_curr_fdbk */ /* Includes ------------------------------------------------------------------*/ #include "r3_1_f7xx_pwm_curr_fdbk.h" #include "pwm_common.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup R3_1_pwm_curr_fdbk * @{ */ /* Private defines -----------------------------------------------------------*/ #define TIMxCCER_MASK_CH123 ((uint16_t) (LL_TIM_CHANNEL_CH1|LL_TIM_CHANNEL_CH1N|\ LL_TIM_CHANNEL_CH2|LL_TIM_CHANNEL_CH2N|\ LL_TIM_CHANNEL_CH3|LL_TIM_CHANNEL_CH3N)) /* DIR bits of TIM1 CR1 register identification for correct check of Counting direction detection*/ #define DIR_MASK 0x0010u /* binary value: 0000000000010000 */ /* Private typedef -----------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ __STATIC_INLINE uint16_t R3_1_WriteTIMRegisters( PWMC_Handle_t * pHdl, uint16_t hCCR4Reg ); void R3_1_HFCurrentsCalibrationAB( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ); void R3_1_HFCurrentsCalibrationC( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ); /* Private functions ---------------------------------------------------------*/ /* Local redefinition of both LL_TIM_OC_EnablePreload & LL_TIM_OC_DisablePreload */ __STATIC_INLINE void __LL_TIM_OC_EnablePreload(TIM_TypeDef *TIMx, uint32_t Channel) { register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); register volatile uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); SET_BIT(*pReg, (TIM_CCMR1_OC1PE << SHIFT_TAB_OCxx[iChannel])); } __STATIC_INLINE void __LL_TIM_OC_DisablePreload(TIM_TypeDef *TIMx, uint32_t Channel) { register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); register volatile uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); CLEAR_BIT(*pReg, (TIM_CCMR1_OC1PE << SHIFT_TAB_OCxx[iChannel])); } /* * @brief Initializes @p TIMx peripheral with @p pHdl handler for PWM generation. * */ __weak void R3_1_Init( PWMC_R3_1_Handle_t * pHandle ) { TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; if ( ( uint32_t )pHandle == ( uint32_t )&pHandle->_Super ) { /* disable IT and flags in case of LL driver usage * workaround for unwanted interrupt enabling done by LL driver */ LL_ADC_DisableIT_EOCS( ADCx ); LL_ADC_ClearFlag_EOCS( ADCx ); LL_ADC_DisableIT_JEOS( ADCx ); LL_ADC_ClearFlag_JEOS( ADCx ); /* disable main TIM counter to ensure * a synchronous start by TIM2 trigger */ LL_TIM_DisableCounter( TIMx ); if ( TIMx == TIM1 ) { /* TIM1 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph( LL_DBGMCU_APB2_GRP1_TIM1_STOP ); /* ADC External Trigger Injected source set to LL_ADC_INJ_TRIG_EXT_TIM1_CH4 in ADC Init */ } #if defined(TIM8) else { /* TIM8 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph( LL_DBGMCU_APB2_GRP1_TIM8_STOP ); /* ADC External Trigger Injected source set to LL_ADC_INJ_TRIG_EXT_TIM8_CH4 in ADC Init */ } #endif LL_TIM_ClearFlag_BRK( TIMx ); LL_TIM_EnableIT_BRK( TIMx ); /* Enable PWM channel */ LL_TIM_CC_EnableChannel( TIMx, TIMxCCER_MASK_CH123 ); /* ADC Enable (must be done after calibration) */ LL_ADC_Enable( ADCx ); /* reset regular conversion sequencer length set by cubeMX */ LL_ADC_REG_SetSequencerLength( ADCx, LL_ADC_REG_SEQ_SCAN_DISABLE ); /* ADCx Injected conversions end interrupt enabling */ LL_ADC_ClearFlag_JEOS( ADCx ); LL_ADC_EnableIT_JEOS( ADCx ); pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_RISING; /* reset injected conversion sequencer length set by cubeMX */ LL_ADC_INJ_SetSequencerLength( ADCx, LL_ADC_INJ_SEQ_SCAN_DISABLE ); /* Clear the flags */ pHandle->_Super.DTTest = 0u; } } /* * @brief Stores in @p pHdl handler the calibrated @p offsets. * */ __weak void R3_1_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 pHandle->PhaseAOffset = offsets->phaseAOffset; pHandle->PhaseBOffset = offsets->phaseBOffset; pHandle->PhaseCOffset = offsets->phaseCOffset; pHdl->offsetCalibStatus = true; } /* * @brief Reads the calibrated @p offsets stored in @p pHdl. * */ __weak void R3_1_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 offsets->phaseAOffset = pHandle->PhaseAOffset; offsets->phaseBOffset = pHandle->PhaseBOffset; offsets->phaseCOffset = pHandle->PhaseCOffset; } /* * @brief Stores into the @p pHdl the voltage present on Ia and Ib current * feedback analog channels when no current is flowing into the motor. * */ __weak void R3_1_CurrentReadingCalibration( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; volatile PWMC_GetPhaseCurr_Cb_t GetPhaseCurrCbSave; volatile PWMC_SetSampPointSectX_Cb_t SetSampPointSectXCbSave; if (false == pHandle->_Super.offsetCalibStatus) { /* Save callback routines */ GetPhaseCurrCbSave = pHandle->_Super.pFctGetPhaseCurrents; SetSampPointSectXCbSave = pHandle->_Super.pFctSetADCSampPointSectX; pHandle->PhaseAOffset = 0u; pHandle->PhaseBOffset = 0u; pHandle->PhaseCOffset = 0u; pHandle->PolarizationCounter = 0u; /* It forces inactive level on TIMx CHy and CHyN */ LL_TIM_CC_DisableChannel(TIMx, TIMxCCER_MASK_CH123); /* Offset calibration for A & B phases */ /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R3_1_HFCurrentsCalibrationAB; pHandle->_Super.pFctSetADCSampPointSectX = &R3_1_SetADCSampPointCalibration; pHandle->CalibSector = SECTOR_5; /* Required to force first polarization conversion on SECTOR_5*/ pHandle->_Super.Sector = SECTOR_5; R3_1_SwitchOnPWM( &pHandle->_Super ); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd( TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter ); R3_1_SwitchOffPWM( &pHandle->_Super ); /* Offset calibration for C phase */ /* Reset PolarizationCounter */ pHandle->PolarizationCounter = 0u; /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R3_1_HFCurrentsCalibrationC; /* "Phase C current calibration to verify" */ pHandle->CalibSector = SECTOR_1; /* Required to force first polarization conversion on SECTOR_1*/ pHandle->_Super.Sector = SECTOR_1; R3_1_SwitchOnPWM( &pHandle->_Super ); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd( TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter ); R3_1_SwitchOffPWM( &pHandle->_Super ); /* Shift of N bits to divide for the NB_ CONVERSIONS = 16= 2^N with N = 4 */ pHandle->PhaseAOffset >>= 3; pHandle->PhaseBOffset >>= 3; pHandle->PhaseCOffset >>= 3; if (0U == pHandle->_Super.SWerror) { pHandle->_Super.offsetCalibStatus = true; } else { /* nothing to do */ } /* Change back function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = GetPhaseCurrCbSave; pHandle->_Super.pFctSetADCSampPointSectX = SetSampPointSectXCbSave; } /* It over write TIMx CCRy wrongly written by FOC during calibration so as to force 50% duty cycle on the three inverer legs */ /* Disable TIMx preload */ __LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH1); __LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH2); __LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH3); LL_TIM_OC_SetCompareCH1( TIMx, pHandle->Half_PWMPeriod ); LL_TIM_OC_SetCompareCH2( TIMx, pHandle->Half_PWMPeriod ); LL_TIM_OC_SetCompareCH3( TIMx, pHandle->Half_PWMPeriod ); __LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH1); __LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH2); __LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH3); /* It re-enable drive of TIMx CHy and CHyN by TIMx CHyRef*/ LL_TIM_CC_EnableChannel(TIMx, TIMxCCER_MASK_CH123); /* sector and phase sequence for the switch on phase */ pHandle->_Super.Sector = SECTOR_5; pHandle->_Super.BrakeActionLock = false; } /* * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p pStator_Currents ab_t format. * */ __weak void R3_1_GetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; int32_t wAux; uint16_t hReg1; uint16_t hReg2; uint8_t bSector; /* disable ADC trigger source */ LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); bSector = ( uint8_t )( pHandle->_Super.Sector ); hReg1 = (ADCx->JDR1)*2; hReg2 = (ADCx->JDR2)*2; switch ( bSector ) { case SECTOR_4: case SECTOR_5: { /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ wAux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( hReg1 ); /* Saturation of Ia */ if ( wAux < -INT16_MAX ) { pStator_Currents->a = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->a = INT16_MAX; } else { pStator_Currents->a = ( int16_t )wAux; } /* Ib = PhaseBOffset - ADC converted value) */ wAux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( hReg2 ); /* Saturation of Ib */ if ( wAux < -INT16_MAX ) { pStator_Currents->b = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->b = INT16_MAX; } else { pStator_Currents->b = ( int16_t )wAux; } } break; case SECTOR_6: case SECTOR_1: { /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ wAux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( hReg1 ); /* Saturation of Ib */ if ( wAux < -INT16_MAX ) { pStator_Currents->b = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->b = INT16_MAX; } else { pStator_Currents->b = ( int16_t )wAux; } /* Ic = PhaseCOffset - ADC converted value) */ /* Ia = -Ic -Ib */ wAux = ( int32_t )( pHandle->PhaseCOffset ) - ( int32_t )( hReg2 ); wAux = -wAux - ( int32_t )pStator_Currents->b; /* Saturation of Ia */ if ( wAux > INT16_MAX ) { pStator_Currents->a = INT16_MAX; } else if ( wAux < -INT16_MAX ) { pStator_Currents->a = -INT16_MAX; } else { pStator_Currents->a = ( int16_t )wAux; } } break; case SECTOR_2: case SECTOR_3: { /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ wAux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( hReg1 ); /* Saturation of Ia */ if ( wAux < -INT16_MAX ) { pStator_Currents->a = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->a = INT16_MAX; } else { pStator_Currents->a = ( int16_t )wAux; } /* Ic = PhaseCOffset - ADC converted value) */ /* Ib = -Ic -Ia */ wAux = ( int32_t )( pHandle->PhaseCOffset ) - ( int32_t )( hReg2 ); wAux = -wAux - ( int32_t )pStator_Currents->a; /* Saturation of Ib */ if ( wAux > INT16_MAX ) { pStator_Currents->b = INT16_MAX; } else if ( wAux < -INT16_MAX ) { pStator_Currents->b = -INT16_MAX; } else { pStator_Currents->b = ( int16_t )wAux; } } break; default: { } break; } pHandle->_Super.Ia = pStator_Currents->a; pHandle->_Super.Ib = pStator_Currents->b; pHandle->_Super.Ic = -pStator_Currents->a - pStator_Currents->b; } /* * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p Iab ab_t format. Specific to overmodulation. * */ __weak void R3_1_GetPhaseCurrents_OVM( PWMC_Handle_t * pHdl, ab_t * Iab ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; uint8_t Sector; int32_t Aux; uint32_t ADCDataReg1; uint32_t ADCDataReg2; /* disable ADC trigger source */ LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); Sector = ( uint8_t )pHandle->_Super.Sector; ADCDataReg1 = (ADCx->JDR1) * 2; ADCDataReg2 = (ADCx->JDR2) * 2; switch ( Sector ) { case SECTOR_4: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { // Ib not available, use estimated Ib Aux = ( int32_t )( pHandle->_Super.IbEst ); } else { /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg2 ); } /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_5: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { // Ia not available, use estimated Ia Aux = ( int32_t )( pHandle->_Super.IaEst ); } else { Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg2 ); /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_6: /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IcEst ; /* -Ic */ Aux -= ( int32_t )Iab->b; } else { /* Ia = -Ic -Ib */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->b; /* Ia */ } /* Saturation of Ia */ if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else { Iab->a = ( int16_t )Aux; } break; case SECTOR_1: /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IbEst; } else { Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } /* Ia = -Ic -Ib */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->b; /* Ia */ /* Saturation of Ia */ if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else { Iab->a = ( int16_t )Aux; } break; case SECTOR_2: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IaEst; } else { Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } /* Ib = -Ic -Ia */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ /* Saturation of Ib */ if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_3: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { /* Ib = -Ic -Ia */ Aux = ( int32_t ) pHandle->_Super.IcEst; /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ } else { /* Ib = -Ic -Ia */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ } /* Saturation of Ib */ if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; default: break; } pHandle->_Super.Ia = Iab->a; pHandle->_Super.Ib = Iab->b; pHandle->_Super.Ic = -Iab->a - Iab->b; } /* * @brief Implementation of PWMC_GetPhaseCurrents to be performed during calibration. * * It sums up injected conversion data into PhaseCOffset to compute the offset * introduced in the current feedback network. It is required to properly configure * ADC inputs before in order to enable offset computation. * * @param pHdl: Pointer on the target component instance. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ __weak void R3_1_HFCurrentsCalibrationAB( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; /* disable ADC trigger source */ LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); if ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { pHandle->PhaseAOffset += (ADCx->JDR1); pHandle->PhaseBOffset += (ADCx->JDR2); pHandle->PolarizationCounter++; } /* during offset calibration no current is flowing in the phases */ pStator_Currents->a = 0; pStator_Currents->b = 0; } /* * @brief Implementation of PWMC_GetPhaseCurrents to be performed during calibration. * * It sums up injected conversion data into PhaseCOffset to compute the offset * introduced in the current feedback network. It is required to properly configure * ADC inputs before in order to enable offset computation. * * @param pHdl: Pointer on the target component instance. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ __weak void R3_1_HFCurrentsCalibrationC( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; /* disable ADC trigger source */ LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); if ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { pHandle->PhaseCOffset += (ADCx->JDR2); pHandle->PolarizationCounter++; } /* during offset calibration no current is flowing in the phases */ pStator_Currents->a = 0; pStator_Currents->b = 0; } /* * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors of driving section. It has to be * called each motor start-up when using high voltage drivers. * * @param pHdl: Handler of the current instance of the PWM component * @param ticks: Timer ticks value to be applied * Min value: 0 (low sides ON) * Max value: PWM_PERIOD_CYCLES/2 (low sides OFF) */ __weak void R3_1_TurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = true; /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /*Turn on the three low side switches */ LL_TIM_OC_SetCompareCH1( TIMx, ticks ); LL_TIM_OC_SetCompareCH2( TIMx, ticks ); LL_TIM_OC_SetCompareCH3( TIMx, ticks ); /* Wait until next update */ while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == RESET ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { /* Enable signals activation */ LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } return; } /* * @brief Enables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_1_SwitchOnPWM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = false; /* Set all duty to 50% */ LL_TIM_OC_SetCompareCH1(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH2(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH3(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH4(TIMx, (uint32_t)(pHandle->Half_PWMPeriod - 5u)); /* wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE; LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { if ( LL_TIM_CC_IsEnabledChannel(TIMx, TIMxCCER_MASK_CH123) != 0u ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Enable Update IRQ */ LL_TIM_EnableIT_UPDATE( TIMx ); return; } /* * @brief Disables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_1_SwitchOffPWM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* Disable UPDATE ISR */ LL_TIM_DisableIT_UPDATE( TIMx ); pHandle->_Super.TurnOnLowSidesAction = false; /* Main PWM Output Disable */ LL_TIM_DisableAllOutputs(TIMx); if ( pHandle->_Super.BrakeActionLock == true ) { } else { if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* wait for a new PWM period to flush last HF task */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); return; } /* * @brief Writes into peripheral registers the new duty cycles and sampling point. * * @param pHdl: Handler of the current instance of the PWM component. * @param hCCR4Reg: New capture/compare register value, written in timer clock counts. * @retval Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ __STATIC_INLINE uint16_t R3_1_WriteTIMRegisters( PWMC_Handle_t * pHdl, uint16_t hCCR4Reg ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint16_t hAux; LL_TIM_OC_SetCompareCH1 ( TIMx, pHandle->_Super.CntPhA ); LL_TIM_OC_SetCompareCH2 ( TIMx, pHandle->_Super.CntPhB ); LL_TIM_OC_SetCompareCH3 ( TIMx, pHandle->_Super.CntPhC ); LL_TIM_OC_SetCompareCH4 ( TIMx, hCCR4Reg ); /* Limit for update event */ /* Check the TIMx TRGO source. If it is set to OC4REF, an update event has occurred and thus the FOC rate is too high */ if (LL_TIM_CC_IsEnabledChannel(TIMx, LL_TIM_CHANNEL_CH4)) { hAux = MC_DURATION; } else { hAux = MC_NO_ERROR; } if ( pHandle->_Super.SWerror == 1u ) { hAux = MC_DURATION; pHandle->_Super.SWerror = 0u; } return hAux; } /* * @brief Configures the ADC for the current sampling during calibration. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ __weak uint16_t R3_1_SetADCSampPointCalibration( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* Set rising edge trigger (default) */ pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_RISING; pHandle->_Super.Sector = pHandle->CalibSector; return R3_1_WriteTIMRegisters( &pHandle->_Super, ( uint16_t )( pHandle->Half_PWMPeriod ) - 1u ); } /* * @brief Configures the ADC for the current sampling related to sector X (X = [1..6] ). * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ __weak uint16_t R3_1_SetADCSampPointSectX( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif uint16_t hCntSmp; uint16_t hDeltaDuty; register uint16_t lowDuty = pHdl->lowDuty; register uint16_t midDuty = pHdl->midDuty; /* Check if sampling AB in the middle of PWM is possible */ if ( ( uint16_t )( pHandle->Half_PWMPeriod - lowDuty ) > pHandle->pParams_str->Tafter ) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled which corresponds * to sector 5 */ pHandle->_Super.Sector = SECTOR_5; /* set sampling point trigger in the middle of PWM period */ hCntSmp = ( uint32_t )( pHandle->Half_PWMPeriod ) - 1u; } else { /* ADC Injected sequence configuration. The stator phase with minimum value of complementary duty cycle is set as first. In every sector there is always one phase with maximum complementary duty, one with minimum complementary duty and one with variable complementary duty. In this case, phases with variable complementary duty and with maximum duty are converted and the first will be always the phase with variable complementary duty cycle */ /* Crossing Point Searching */ hDeltaDuty = ( uint16_t )( lowDuty - midDuty ); /* Definition of crossing point */ if ( hDeltaDuty > ( uint16_t )( pHandle->Half_PWMPeriod - lowDuty ) * 2u ) { /* Tbefore = 2*Ts + Tc, where Ts = Sampling time of ADC, Tc = Conversion Time of ADC */ hCntSmp = lowDuty - pHandle->pParams_str->Tbefore; } else { /* Tafter = DT + max(Trise, Tnoise) */ hCntSmp = lowDuty + pHandle->pParams_str->Tafter; if ( hCntSmp >= pHandle->Half_PWMPeriod ) { /* It must be changed the trigger direction from positive to negative to sample after middle of PWM*/ pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_FALLING; hCntSmp = ( 2u * pHandle->Half_PWMPeriod ) - hCntSmp - 1u; } } } return R3_1_WriteTIMRegisters( &pHandle->_Super, hCntSmp); } /* * @brief Configures the ADC for the current sampling related to sector X (X = [1..6] ) in case of overmodulation. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ uint16_t R3_1_SetADCSampPointSectX_OVM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ uint16_t SamplingPoint; uint16_t DeltaDuty; pHandle->_Super.useEstCurrent = false; DeltaDuty = ( uint16_t )( pHdl->lowDuty - pHdl->midDuty ); /* case 1 (cf user manual) */ if (( uint16_t )( pHandle->Half_PWMPeriod - pHdl->lowDuty ) > pHandle->pParams_str->Tafter) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled which corresponds * to sector 4 or 5 */ pHandle->_Super.Sector = SECTOR_5; /* set sampling point trigger in the middle of PWM period */ SamplingPoint = pHandle->Half_PWMPeriod - (uint16_t) 1; } else /* case 2 (cf user manual) */ { if (DeltaDuty >= pHandle->pParams_str->Tcase2) { SamplingPoint = pHdl->lowDuty - pHandle->pParams_str->Tbefore; } else { /* case 3 (cf user manual) */ if ((pHandle->Half_PWMPeriod - pHdl->lowDuty) > pHandle->pParams_str->Tcase3) { /* ADC trigger edge must be changed from positive to negative */ pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_FALLING; SamplingPoint = pHdl->lowDuty + pHandle->pParams_str->Tsampling; } else { SamplingPoint = pHandle->Half_PWMPeriod-1; pHandle->_Super.useEstCurrent = true; } } } return R3_1_WriteTIMRegisters( &pHandle->_Super, SamplingPoint ); } /* * @brief Contains the TIMx Update event interrupt. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void * R3_1_TIMx_UP_IRQHandler( PWMC_R3_1_Handle_t * pHandle ) { TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; /* reset ADC external trigger edge */ LL_ADC_INJ_StopConversionExtTrig(ADCx); ADCx->JSQR = pHandle->pParams_str->ADCConfig[pHandle->_Super.Sector]; /* enable ADC trigger source */ LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH4); /* reset ADC external trigger edge */ LL_ADC_INJ_StartConversionExtTrig(ADCx, pHandle->ADCTriggerEdge); /* reset default edge detection trigger */ pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_RISING; return &( pHandle->_Super.Motor ); } /* * @brief Sets the PWM mode for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_1_RLDetectionModeEnable( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; if ( pHandle->_Super.RLDetectionMode == false ) { /* Channel1 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH1, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH1N ); LL_TIM_OC_SetCompareCH1( TIMx, 0u ); /* Channel2 configuration */ if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_ACTIVE ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_INACTIVE ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else { } /* Channel3 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH3, LL_TIM_OCMODE_PWM2 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3N ); } pHandle->_Super.pFctGetPhaseCurrents = &R3_1_RLGetPhaseCurrents; pHandle->_Super.pFctTurnOnLowSides = &R3_1_RLTurnOnLowSides; pHandle->_Super.pFctSwitchOnPwm = &R3_1_RLSwitchOnPWM; pHandle->_Super.pFctSwitchOffPwm = &R3_1_SwitchOffPWM; pHandle->_Super.RLDetectionMode = true; } /* * @brief Disables the PWM mode for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_1_RLDetectionModeDisable( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; if ( pHandle->_Super.RLDetectionMode == true ) { /* Channel1 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH1, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1 ); if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH1N ); } else { } LL_TIM_OC_SetCompareCH1( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) >> 1 ); /* Channel2 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2 ); if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else { } LL_TIM_OC_SetCompareCH2( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) >> 1 ); /* Channel3 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH3, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH3 ); if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH3N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3N ); } else { } LL_TIM_OC_SetCompareCH3( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) >> 1 ); pHandle->_Super.pFctGetPhaseCurrents = &R3_1_GetPhaseCurrents; pHandle->_Super.pFctTurnOnLowSides = &R3_1_TurnOnLowSides; pHandle->_Super.pFctSwitchOnPwm = &R3_1_SwitchOnPWM; pHandle->_Super.pFctSwitchOffPwm = &R3_1_SwitchOffPWM; pHandle->_Super.RLDetectionMode = false; } } /* * @brief Sets the PWM dutycycle for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. * @param hDuty: Duty cycle to apply, written in uint16_t. * @retval Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ uint16_t R3_1_RLDetectionModeSetDuty( PWMC_Handle_t * pHdl, uint16_t hDuty ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint32_t val; uint16_t hAux; val = ( ( uint32_t )( pHandle->Half_PWMPeriod ) * ( uint32_t )( hDuty ) ) >> 16; pHandle->_Super.CntPhA = ( uint16_t )( val ); /* TIM1 Channel 1 Duty Cycle configuration. * In RL Detection mode only the Up-side device of Phase A are controlled*/ LL_TIM_OC_SetCompareCH1(TIMx, ( uint32_t )pHandle->_Super.CntPhA); /* set the sector that correspond to Phase A and B sampling */ pHdl->Sector = SECTOR_4; /* Limit for update event */ /* Check the status flag. If an update event has occurred before to set new values of regs the FOC rate is too high */ if (LL_TIM_CC_IsEnabledChannel(TIMx, LL_TIM_CHANNEL_CH4)) { hAux = MC_DURATION; } else { hAux = MC_NO_ERROR; } if ( pHandle->_Super.SWerror == 1u ) { hAux = MC_DURATION; pHandle->_Super.SWerror = 0u; } return hAux; } /* * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p pStator_Currents ab_t format. * * Specific to RL. */ static void R3_1_RLGetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; int32_t wAux; /* disable ADC trigger source */ LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); wAux = (int32_t)( pHandle->PhaseBOffset ) - (int32_t)(ADCx->JDR2)*2; /* Check saturation */ if ( wAux > -INT16_MAX ) { if ( wAux < INT16_MAX ) { } else { wAux = INT16_MAX; } } else { wAux = -INT16_MAX; } pStator_Currents->a = (int16_t)wAux; pStator_Currents->b = (int16_t)wAux; } /* * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors * of driving section. It has to be called at each motor start-up when * using high voltage drivers. * This function is specific for RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. * @param ticks: Duty cycle of the boot capacitors charge, specific to motor. */ static void R3_1_RLTurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /*Turn on the phase A low side switch */ LL_TIM_OC_SetCompareCH1 ( TIMx, 0u ); /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Wait until next update */ while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } return; } /* * @brief Enables PWM generation on the proper Timer peripheral. * * This function is specific for RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. */ static void R3_1_RLSwitchOnPWM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); LL_TIM_OC_SetCompareCH1( TIMx, 1u ); LL_TIM_OC_SetCompareCH4( TIMx, ( pHandle->Half_PWMPeriod ) - 5u ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE; LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { if ( ( TIMx->CCER & TIMxCCER_MASK_CH123 ) != 0u ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* enable TIMx update interrupt*/ LL_TIM_EnableIT_UPDATE( TIMx ); return; } /* * @brief Turns on low sides switches and start ADC triggering. * * This function is specific for MP phase. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_1_RLTurnOnLowSidesAndStart( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); LL_TIM_OC_SetCompareCH1 ( TIMx, 0x0u ); LL_TIM_OC_SetCompareCH2 ( TIMx, 0x0u ); LL_TIM_OC_SetCompareCH3 ( TIMx, 0x0u ); LL_TIM_OC_SetCompareCH4( TIMx, ( pHandle->Half_PWMPeriod - 5u)); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE ; LL_TIM_EnableAllOutputs ( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } pHdl->Sector = SECTOR_4; /* ADC External Trigger Injected source set to LL_ADC_INJ_TRIG_EXT_TIM1_CH4 in ADC Init */ LL_ADC_INJ_StartConversionExtTrig(ADCx,LL_ADC_INJ_TRIG_EXT_RISING); LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH4); LL_TIM_EnableIT_UPDATE( TIMx ); return; } /** * @} */ /** * @} */ /** * @} */ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
49,994
C
29.596695
143
0.613314
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/F7xx/Src/ics_f7xx_pwm_curr_fdbk.c
/** ****************************************************************************** * @file ics_f7xx_pwm_curr_fdbk.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement the ICS * PWM current feedback component for F7XX of the Motor Control SDK. ******************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup ICS_F7XX_pwm_curr_fdbk */ /* Includes ------------------------------------------------------------------*/ #include "ics_f7xx_pwm_curr_fdbk.h" #include "pwm_common.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup ICS_pwm_curr_fdbk * @{ */ #define TIMxCCER_MASK_CH123 (LL_TIM_CHANNEL_CH1 | LL_TIM_CHANNEL_CH1N | LL_TIM_CHANNEL_CH2| LL_TIM_CHANNEL_CH2N |\ LL_TIM_CHANNEL_CH3 | LL_TIM_CHANNEL_CH3N) void ICS_HFCurrentsCalibration( PWMC_Handle_t * pHandle, ab_t * pStator_Currents ); /* * @brief Initializes TIMx, ADC, GPIO and NVIC for current reading * in ICS configuration using STM32F30X. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void ICS_Init( PWMC_ICS_Handle_t * pHandle ) { TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; if ( ( uint32_t )pHandle == ( uint32_t )&pHandle->_Super ) { /* disable IT and flags in case of LL driver usage * workaround for unwanted interrupt enabling done by LL driver */ LL_ADC_DisableIT_EOCS( ADC1 ); LL_ADC_ClearFlag_EOCS( ADC1 ); LL_ADC_DisableIT_JEOS( ADC1 ); LL_ADC_ClearFlag_JEOS( ADC1 ); LL_ADC_DisableIT_EOCS( ADC2 ); LL_ADC_ClearFlag_EOCS( ADC2 ); LL_ADC_DisableIT_JEOS( ADC2 ); LL_ADC_ClearFlag_JEOS( ADC2 ); /* disable main TIM counter to ensure * a synchronous start by TIM2 trigger */ LL_TIM_DisableCounter( TIMx ); /* Enables the TIMx Preload on CC1 Register */ LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH1 ); /* Enables the TIMx Preload on CC2 Register */ LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH2 ); /* Enables the TIMx Preload on CC3 Register */ LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH3 ); /* Enables the TIMx Preload on CC4 Register */ LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH4 ); LL_TIM_ClearFlag_BRK( TIMx ); LL_TIM_EnableIT_BRK( TIMx ); /* Enable PWM channel */ LL_TIM_CC_EnableChannel( TIMx, TIMxCCER_MASK_CH123 ); if ( pHandle->pParams_str->TIMx == TIM1 ) { /* TIM1 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph( LL_DBGMCU_APB2_GRP1_TIM1_STOP ); } else { /* TIM8 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph( LL_DBGMCU_APB2_GRP1_TIM8_STOP ); } /* ADC1 and ADC2 registers configuration ---------------------------------*/ /* Enable ADC1 and ADC2 */ LL_ADC_Enable( ADC1 ); LL_ADC_Enable( ADC2 ); /* reset regular conversion sequencer length set by cubeMX */ LL_ADC_REG_SetSequencerLength( ADC1, LL_ADC_REG_SEQ_SCAN_DISABLE ); /* ADC1 Injected conversions end interrupt enabling */ LL_ADC_ClearFlag_JEOS( ADC1 ); LL_ADC_EnableIT_JEOS( ADC1 ); pHandle->_Super.DTTest = 0u; } } /* * @brief Stores in @p pHdl handler the calibrated @p offsets. * */ __weak void ICS_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_ICS_Handle_t *pHandle = (PWMC_ICS_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 pHandle->PhaseAOffset = offsets->phaseAOffset; pHandle->PhaseBOffset = offsets->phaseBOffset; pHdl->offsetCalibStatus = true; } /* * @brief Reads the calibrated @p offsets stored in @p pHdl. * */ __weak void ICS_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_ICS_Handle_t *pHandle = (PWMC_ICS_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 offsets->phaseAOffset = pHandle->PhaseAOffset; offsets->phaseBOffset = pHandle->PhaseBOffset; } /* * @brief Stores into the @p pHdl handler the voltage present on Ia and * Ib current feedback analog channels when no current is flowing into the * motor. * */ __weak void ICS_CurrentReadingCalibration( PWMC_Handle_t * pHdl ) { PWMC_ICS_Handle_t * pHandle = ( PWMC_ICS_Handle_t * ) pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; if (false == pHandle->_Super.offsetCalibStatus) { pHandle->PhaseAOffset = 0u; pHandle->PhaseBOffset = 0u; pHandle->PolarizationCounter = 0u; /* Force inactive level on TIMx CHy and TIMx CHyN */ LL_TIM_CC_DisableChannel( TIMx, TIMxCCER_MASK_CH123 ); /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &ICS_HFCurrentsCalibration; ICS_SwitchOnPWM( &pHandle->_Super ); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd( TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter ); ICS_SwitchOffPWM( &pHandle->_Super ); pHandle->PhaseAOffset >>= 3; pHandle->PhaseBOffset >>= 3; if (0U == pHandle->_Super.SWerror) { pHandle->_Super.offsetCalibStatus = true; } else { /* nothing to do */ } /* Change back function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &ICS_GetPhaseCurrents; } /* It over write TIMx CCRy wrongly written by FOC during calibration so as to force 50% duty cycle on the three inverer legs */ /* Disable TIMx preload */ LL_TIM_OC_DisablePreload( TIMx, LL_TIM_CHANNEL_CH1 ); LL_TIM_OC_DisablePreload( TIMx, LL_TIM_CHANNEL_CH2 ); LL_TIM_OC_DisablePreload( TIMx, LL_TIM_CHANNEL_CH3 ); LL_TIM_OC_SetCompareCH1( TIMx, pHandle->Half_PWMPeriod ); LL_TIM_OC_SetCompareCH2( TIMx, pHandle->Half_PWMPeriod ); LL_TIM_OC_SetCompareCH3( TIMx, pHandle->Half_PWMPeriod ); LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH1 ); LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH2 ); LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH3 ); /* Set back TIMx CCER register */ LL_TIM_CC_EnableChannel( TIMx, TIMxCCER_MASK_CH123 ); } /* * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p pStator_Currents ab_t format. * */ __weak void ICS_GetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { int32_t aux; uint16_t reg; PWMC_ICS_Handle_t * pHandle = ( PWMC_ICS_Handle_t * ) pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* disable ADC trigger */ LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); /* Ia = (hPhaseAOffset)-(PHASE_A_ADC_CHANNEL vale) */ reg = ( uint16_t )( ( ADC1->JDR1 ) << 1 ); aux = ( int32_t )( reg ) - ( int32_t )( pHandle->PhaseAOffset ); /* Saturation of Ia */ if ( aux < -INT16_MAX ) { pStator_Currents->a = -INT16_MAX; } else if ( aux > INT16_MAX ) { pStator_Currents->a = INT16_MAX; } else { pStator_Currents->a = ( int16_t )aux; } /* Ib = (hPhaseBOffset)-(PHASE_B_ADC_CHANNEL value) */ reg = ( uint16_t )( ( ADC2->JDR1 ) << 1 ); aux = ( int32_t )( reg ) - ( int32_t )( pHandle->PhaseBOffset ); /* Saturation of Ib */ if ( aux < -INT16_MAX ) { pStator_Currents->b = -INT16_MAX; } else if ( aux > INT16_MAX ) { pStator_Currents->b = INT16_MAX; } else { pStator_Currents->b = ( int16_t )aux; } pHandle->_Super.Ia = pStator_Currents->a; pHandle->_Super.Ib = pStator_Currents->b; pHandle->_Super.Ic = -pStator_Currents->a - pStator_Currents->b; } /* * @brief Sums up injected conversion data into wPhaseXOffset. * * It is called only during current calibration. * * @param pHdl: Handler of the current instance of the PWM component. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ __weak void ICS_HFCurrentsCalibration( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { PWMC_ICS_Handle_t * pHandle = ( PWMC_ICS_Handle_t * ) pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* disable ADC trigger */ LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH4 ); if ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { pHandle->PhaseAOffset += ADC1->JDR1; pHandle->PhaseBOffset += ADC2->JDR1; pHandle->PolarizationCounter++; } /* during offset calibration no current is flowing in the phases */ pStator_Currents->a = 0; pStator_Currents->b = 0; } /* * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors of driving section. It has to be * called on each motor start-up when using high voltage drivers. * * @param pHdl: Handler of the current instance of the PWM component. * @param ticks: Timer ticks value to be applied * Min value: 0 (low sides ON) * Max value: PWM_PERIOD_CYCLES/2 (low sides OFF) */ __weak void ICS_TurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ) { PWMC_ICS_Handle_t * pHandle = ( PWMC_ICS_Handle_t * ) pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = true; /*Turn on the three low side switches */ LL_TIM_OC_SetCompareCH1( TIMx, ticks ); LL_TIM_OC_SetCompareCH2( TIMx, ticks ); LL_TIM_OC_SetCompareCH3( TIMx, ticks ); LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == RESET ) {} /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* * @brief Enables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void ICS_SwitchOnPWM( PWMC_Handle_t * pHdl ) { PWMC_ICS_Handle_t * pHandle = ( PWMC_ICS_Handle_t * ) pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = false; /* Enable TIMx preload and ADC trigger on next update */ LL_TIM_OC_SetCompareCH1(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH2(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH3(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH4(TIMx, (uint32_t)(pHandle->Half_PWMPeriod - 5u)); /* It clears ADCs JSTRT and JEOC bits */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Disable */ LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { if ( LL_TIM_CC_IsEnabledChannel(TIMx, TIMxCCER_MASK_CH123) != 0u ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Enable Update IRQ */ LL_TIM_EnableIT_UPDATE( TIMx ); } /* * @brief Disables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void ICS_SwitchOffPWM( PWMC_Handle_t * pHdl ) { PWMC_ICS_Handle_t * pHandle = ( PWMC_ICS_Handle_t * ) pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* Disable UPDATE ISR */ LL_TIM_DisableIT_UPDATE( TIMx ); pHandle->_Super.TurnOnLowSidesAction = false; /* Main PWM Output Disable */ LL_TIM_DisableAllOutputs(TIMx); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } /* wait for a new PWM period to flush last HF task */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); } /* * @brief Writes into peripheral registers the new duty cycle and sampling point. * * @param pHdl: Handler of the current instance of the PWM component. * @param SamplingPoint: Point at which the ADC will be triggered, written in timer clock counts. * @retval Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ __weak uint16_t ICS_WriteTIMRegisters( PWMC_Handle_t * pHdl ) { uint16_t aux; PWMC_ICS_Handle_t * pHandle = ( PWMC_ICS_Handle_t * ) pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; LL_TIM_OC_SetCompareCH1( TIMx, pHandle->_Super.CntPhA ); LL_TIM_OC_SetCompareCH2( TIMx, pHandle->_Super.CntPhB ); LL_TIM_OC_SetCompareCH3( TIMx, pHandle->_Super.CntPhC ); /* Limit for update event */ /* Check the status of SOFOC flag. If it is set, an update event has occurred and thus the FOC rate is too high */ if ( LL_TIM_CC_IsEnabledChannel(TIMx, LL_TIM_CHANNEL_CH4)) { aux = MC_DURATION; } else { aux = MC_NO_ERROR; } return aux; } /* * @brief Contains the TIMx Update event interrupt. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void * ICS_TIMx_UP_IRQHandler( PWMC_ICS_Handle_t * pHandle ) { TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH4 ); return &( pHandle->_Super.Motor ); } /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
15,091
C
30.906977
128
0.637599
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/F7xx/Src/r3_2_f7xx_pwm_curr_fdbk.c
/** ****************************************************************************** * @file r3_2_f7xx_pwm_curr_fdbk.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement current sensor * class to be stantiated when the three shunts current sensing * topology is used. * * It is specifically designed for STM32F7XX * microcontrollers and implements the successive sampling of two motor * current using two ADCs. * + MCU peripheral and handle initialization fucntion * + three shunt current sensing * + space vector modulation function * + ADC sampling function * ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * * @ingroup R3_2_F7XX_pwm_curr_fdbk */ /* Includes ------------------------------------------------------------------*/ #include "r3_2_f7xx_pwm_curr_fdbk.h" #include "pwm_common.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup R3_2_pwm_curr_fdbk * @{ */ /* Private defines -----------------------------------------------------------*/ /* #define SAMPLING_POINT_DEBUG */ /* ADC SMPx mask */ #define TIMxCCER_MASK_CH123 ((uint16_t) (LL_TIM_CHANNEL_CH1|LL_TIM_CHANNEL_CH1N|\ LL_TIM_CHANNEL_CH2|LL_TIM_CHANNEL_CH2N|\ LL_TIM_CHANNEL_CH3|LL_TIM_CHANNEL_CH3N)) /* Private function prototypes -----------------------------------------------*/ __STATIC_INLINE uint16_t R3_2_WriteTIMRegisters( PWMC_Handle_t * pHdl, uint16_t hCCR4Reg ); void R3_2_HFCurrentsCalibrationAB( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ); void R3_2_HFCurrentsCalibrationC( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ); static void R3_2_RLGetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ); static void R3_2_RLTurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ); static void R3_2_RLSwitchOnPWM( PWMC_Handle_t * pHdl ); /* Private functions ---------------------------------------------------------*/ /* Local redefinition of both LL_TIM_OC_EnablePreload & LL_TIM_OC_DisablePreload */ __STATIC_INLINE void __LL_TIM_OC_EnablePreload(TIM_TypeDef *TIMx, uint32_t Channel) { register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); register volatile uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); SET_BIT(*pReg, (TIM_CCMR1_OC1PE << SHIFT_TAB_OCxx[iChannel])); } __STATIC_INLINE void __LL_TIM_OC_DisablePreload(TIM_TypeDef *TIMx, uint32_t Channel) { register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); register volatile uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); CLEAR_BIT(*pReg, (TIM_CCMR1_OC1PE << SHIFT_TAB_OCxx[iChannel])); } /* * @brief Initializes TIMx, ADC, GPIO, DMA1 and NVIC for current reading * in three shunt topology using STM32F30X and two ADCs. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void R3_2_Init( PWMC_R3_2_Handle_t * pHandle ) { TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx_1 = pHandle->pParams_str->ADCDataReg1[0]; ADC_TypeDef * ADCx_2 = pHandle->pParams_str->ADCDataReg2[0]; if ( ( uint32_t )pHandle == ( uint32_t )&pHandle->_Super ) { LL_ADC_DisableIT_EOCS( ADCx_1 ); LL_ADC_ClearFlag_EOCS( ADCx_1 ); LL_ADC_DisableIT_JEOS( ADCx_1 ); LL_ADC_ClearFlag_JEOS( ADCx_1 ); LL_ADC_DisableIT_EOCS( ADCx_2 ); LL_ADC_ClearFlag_EOCS( ADCx_2 ); LL_ADC_DisableIT_JEOS( ADCx_2 ); LL_ADC_ClearFlag_JEOS( ADCx_2 ); /* disable main TIM counter to ensure * a synchronous start by TIM2 trigger */ LL_TIM_DisableCounter( TIMx ); /* Timer break-in enabling */ LL_TIM_ClearFlag_BRK( TIMx ); LL_TIM_EnableIT_BRK( TIMx ); /* Enable PWM channel */ LL_TIM_CC_EnableChannel( TIMx, TIMxCCER_MASK_CH123 ); if ( pHandle->pParams_str->TIMx == TIM1 ) { /* TIM1 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph( LL_DBGMCU_APB2_GRP1_TIM1_STOP ); pHandle->ADC_ExternalTriggerInjected = LL_ADC_INJ_TRIG_EXT_TIM1_CH4; } else { /* TIM8 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph( LL_DBGMCU_APB2_GRP1_TIM8_STOP ); pHandle->ADC_ExternalTriggerInjected = LL_ADC_INJ_TRIG_EXT_TIM8_CH4; } /* ADCx_1 and ADCx_2 registers configuration ---------------------------------*/ /* Enable ADCx_1 and ADCx_2 */ LL_ADC_Enable( ADCx_1 ); LL_ADC_Enable( ADCx_2 ); /* ADCx_1 Injected conversions end interrupt enabling */ LL_ADC_ClearFlag_JEOS( ADCx_1 ); LL_ADC_EnableIT_JEOS( ADCx_1 ); /* reset injected conversion sequencer length set by cubeMX */ LL_ADC_INJ_SetSequencerLength( ADCx_1, LL_ADC_INJ_SEQ_SCAN_DISABLE ); LL_ADC_INJ_SetSequencerLength( ADCx_2, LL_ADC_INJ_SEQ_SCAN_DISABLE ); pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_RISING; pHandle->_Super.DTTest = 0u; } } /* * @brief Stores in @p pHdl handler the calibrated @p offsets. * */ __weak void R3_2_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 pHandle->PhaseAOffset = offsets->phaseAOffset; pHandle->PhaseBOffset = offsets->phaseBOffset; pHandle->PhaseCOffset = offsets->phaseCOffset; pHdl->offsetCalibStatus = true; } /* * @brief Reads the calibrated @p offsets stored in @p pHdl. * */ __weak void R3_2_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 offsets->phaseAOffset = pHandle->PhaseAOffset; offsets->phaseBOffset = pHandle->PhaseBOffset; offsets->phaseCOffset = pHandle->PhaseCOffset; } /* * @brief Stores into the @p pHdl handler the voltage present on Ia and * Ib current feedback analog channels when no current is flowing into the * motor. * */ __weak void R3_2_CurrentReadingCalibration( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; volatile PWMC_GetPhaseCurr_Cb_t GetPhaseCurrCbSave; volatile PWMC_SetSampPointSectX_Cb_t SetSampPointSectXCbSave; if (false == pHandle->_Super.offsetCalibStatus) { /* Save callback routines */ GetPhaseCurrCbSave = pHandle->_Super.pFctGetPhaseCurrents; SetSampPointSectXCbSave = pHandle->_Super.pFctSetADCSampPointSectX; pHandle->PhaseAOffset = 0u; pHandle->PhaseBOffset = 0u; pHandle->PhaseCOffset = 0u; pHandle->PolarizationCounter = 0u; LL_TIM_CC_DisableChannel(TIMx, TIMxCCER_MASK_CH123); /* Offset calibration for A & B phases */ /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R3_2_HFCurrentsCalibrationAB; pHandle->_Super.pFctSetADCSampPointSectX = &R3_2_SetADCSampPointCalibration; pHandle->CalibSector = SECTOR_4; /* Required to force first polarization conversion on SECTOR_4*/ pHandle->_Super.Sector = SECTOR_4; R3_2_SwitchOnPWM( &pHandle->_Super ); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd( TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter ); R3_2_SwitchOffPWM( &pHandle->_Super ); /* Offset calibration for C phase */ /* Reset PolarizationCounter */ pHandle->PolarizationCounter = 0u; /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R3_2_HFCurrentsCalibrationC; pHandle->CalibSector = SECTOR_1; /* Required to force first polarization conversion on SECTOR_1*/ pHandle->_Super.Sector = SECTOR_1; R3_2_SwitchOnPWM( &pHandle->_Super ); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd( TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter ); R3_2_SwitchOffPWM( &pHandle->_Super ); pHandle->PhaseAOffset >>= 3; pHandle->PhaseBOffset >>= 3; pHandle->PhaseCOffset >>= 3; if (0U == pHandle->_Super.SWerror) { pHandle->_Super.offsetCalibStatus = true; } else { /* nothing to do */ } /* Change back function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = GetPhaseCurrCbSave; pHandle->_Super.pFctSetADCSampPointSectX = SetSampPointSectXCbSave; } /* It over write TIMx CCRy wrongly written by FOC during calibration so as to force 50% duty cycle on the three inverer legs */ /* Disable TIMx preload */ __LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH1); __LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH2); __LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH3); LL_TIM_OC_SetCompareCH1( TIMx, pHandle->Half_PWMPeriod ); LL_TIM_OC_SetCompareCH2( TIMx, pHandle->Half_PWMPeriod ); LL_TIM_OC_SetCompareCH3( TIMx, pHandle->Half_PWMPeriod ); __LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH1); __LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH2); __LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH3); /* It re-enable drive of TIMx CHy and CHyN by TIMx CHyRef*/ LL_TIM_CC_EnableChannel(TIMx, TIMxCCER_MASK_CH123); /* sector and phase sequence for the switch on phase */ pHandle->_Super.Sector = SECTOR_4; } /* * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p pStator_Currents ab_t format. * */ __weak void R3_2_GetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; int32_t wAux; uint16_t hReg1; uint16_t hReg2; uint8_t bSector; /* disable ADC trigger source */ LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); bSector = pHandle->_Super.Sector; hReg1 = pHandle->pParams_str->ADCDataReg1[bSector]->JDR1 * 2; hReg2 = pHandle->pParams_str->ADCDataReg2[bSector]->JDR1 * 2; switch ( bSector ) { case SECTOR_4: case SECTOR_5: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ wAux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( hReg1 ); /* Saturation of Ia */ if ( wAux < -INT16_MAX ) { pStator_Currents->a = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->a = INT16_MAX; } else { pStator_Currents->a = ( int16_t )wAux; } /* Ib = PhaseBOffset - ADC converted value) */ wAux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( hReg2 ); /* Saturation of Ib */ if ( wAux < -INT16_MAX ) { pStator_Currents->b = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->b = INT16_MAX; } else { pStator_Currents->b = ( int16_t )wAux; } break; case SECTOR_6: case SECTOR_1: /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ wAux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( hReg1 ); /* Saturation of Ib */ if ( wAux < -INT16_MAX ) { pStator_Currents->b = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->b = INT16_MAX; } else { pStator_Currents->b = ( int16_t )wAux; } /* Ic = PhaseCOffset - ADC converted value) */ /* Ia = -Ic -Ib */ wAux = ( int32_t )( pHandle->PhaseCOffset ) - ( int32_t )( hReg2 ); wAux = -wAux - ( int32_t )pStator_Currents->b; /* Saturation of Ia */ if ( wAux > INT16_MAX ) { pStator_Currents->a = INT16_MAX; } else if ( wAux < -INT16_MAX ) { pStator_Currents->a = -INT16_MAX; } else { pStator_Currents->a = ( int16_t )wAux; } break; case SECTOR_2: case SECTOR_3: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ wAux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( hReg1 ); /* Saturation of Ia */ if ( wAux < -INT16_MAX ) { pStator_Currents->a = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->a = INT16_MAX; } else { pStator_Currents->a = ( int16_t )wAux; } /* Ic = PhaseCOffset - ADC converted value) */ /* Ib = -Ic -Ia */ wAux = ( int32_t )( pHandle->PhaseCOffset ) - ( int32_t )( hReg2 ); wAux = -wAux - ( int32_t )pStator_Currents->a; /* Saturation of Ib */ if ( wAux > INT16_MAX ) { pStator_Currents->b = INT16_MAX; } else if ( wAux < -INT16_MAX ) { pStator_Currents->b = -INT16_MAX; } else { pStator_Currents->b = ( int16_t )wAux; } break; default: break; } pHandle->_Super.Ia = pStator_Currents->a; pHandle->_Super.Ib = pStator_Currents->b; pHandle->_Super.Ic = -pStator_Currents->a - pStator_Currents->b; } /* * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p Iab ab_t format. Specific to overmodulation. * */ __weak void R3_2_GetPhaseCurrents_OVM( PWMC_Handle_t * pHdl, ab_t * Iab ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint8_t Sector; int32_t Aux; uint32_t ADCDataReg1; uint32_t ADCDataReg2; /* disable ADC trigger source */ LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); Sector = ( uint8_t )pHandle->_Super.Sector; ADCDataReg1 = pHandle->pParams_str->ADCDataReg1[Sector]->JDR1 * 2; ADCDataReg2 = pHandle->pParams_str->ADCDataReg2[Sector]->JDR1 * 2; switch ( Sector ) { case SECTOR_4: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { // Ib not available, use estimated Ib Aux = ( int32_t )( pHandle->_Super.IbEst ); } else { /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg2 ); } /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_5: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { // Ia not available, use estimated Ia Aux = ( int32_t )( pHandle->_Super.IaEst ); } else { Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg2 ); /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_6: /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IcEst ; /* -Ic */ Aux -= ( int32_t )Iab->b; } else { /* Ia = -Ic -Ib */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->b; /* Ia */ } /* Saturation of Ia */ if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else { Iab->a = ( int16_t )Aux; } break; case SECTOR_1: /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IbEst; } else { Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } /* Ia = -Ic -Ib */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->b; /* Ia */ /* Saturation of Ia */ if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else { Iab->a = ( int16_t )Aux; } break; case SECTOR_2: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IaEst; } else { Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } /* Ib = -Ic -Ia */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ /* Saturation of Ib */ if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_3: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { /* Ib = -Ic -Ia */ Aux = ( int32_t ) pHandle->_Super.IcEst; /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ } else { /* Ib = -Ic -Ia */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ } /* Saturation of Ib */ if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; default: break; } pHandle->_Super.Ia = Iab->a; pHandle->_Super.Ib = Iab->b; pHandle->_Super.Ic = -Iab->a - Iab->b; } /* * @brief Implementation of PWMC_GetPhaseCurrents to be performed during calibration. * * It sums up injected conversion data into PhaseAOffset and wPhaseBOffset * to compute the offset introduced in the current feedback network. It is required to * properly configure ADC inputs before in order to enable offset computation. * * @param pHdl: Pointer on the target component instance. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ __weak void R3_2_HFCurrentsCalibrationAB( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* disable ADC trigger source */ LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); if ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { pHandle->PhaseAOffset += pHandle->pParams_str->ADCDataReg1[pHandle->CalibSector]->JDR1; pHandle->PhaseBOffset += pHandle->pParams_str->ADCDataReg2[pHandle->CalibSector]->JDR1; pHandle->PolarizationCounter++; } /* during offset calibration no current is flowing in the phases */ pStator_Currents->a = 0; pStator_Currents->b = 0; } /* * @brief Implementation of PWMC_GetPhaseCurrents to be performed during calibration. * * It sums up injected conversion data into PhaseCOffset to compute the offset * introduced in the current feedback network. It is required to properly configure * ADC inputs before in order to enable offset computation. * * @param pHdl: Pointer on the target component instance. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ __weak void R3_2_HFCurrentsCalibrationC( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* disable ADC trigger source */ LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); if ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { pHandle->PhaseCOffset += pHandle->pParams_str->ADCDataReg2[pHandle->CalibSector]->JDR1; pHandle->PolarizationCounter++; } /* during offset calibration no current is flowing in the phases */ pStator_Currents->a = 0; pStator_Currents->b = 0; } /* * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors of driving section. It has to be * called each motor start-up when using high voltage drivers. * * @param pHdl: Handler of the current instance of the PWM component * @param ticks: Timer ticks value to be applied * Min value: 0 (low sides ON) * Max value: PWM_PERIOD_CYCLES/2 (low sides OFF) */ __weak void R3_2_TurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = true; /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /*Turn on the three low side switches */ LL_TIM_OC_SetCompareCH1( TIMx, ticks ); LL_TIM_OC_SetCompareCH2( TIMx, ticks ); LL_TIM_OC_SetCompareCH3( TIMx, ticks ); /* Wait until next update */ while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == RESET ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } return; } /* * @brief Enables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_2_SwitchOnPWM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = false; /* Set all duty to 50% */ LL_TIM_OC_SetCompareCH1(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH2(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH3(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH4(TIMx, (uint32_t)(pHandle->Half_PWMPeriod - 5u)); /* wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE; LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { if ( LL_TIM_CC_IsEnabledChannel(TIMx,TIMxCCER_MASK_CH123) != 0u ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Enable Update IRQ */ LL_TIM_EnableIT_UPDATE( TIMx ); return; } /* * @brief Disables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_2_SwitchOffPWM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* Disable UPDATE ISR */ LL_TIM_DisableIT_UPDATE( TIMx ); pHandle->_Super.TurnOnLowSidesAction = false; /* Main PWM Output Disable */ LL_TIM_DisableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } /* wait for a new PWM period to flush last HF task */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); return; } /* * @brief Writes into peripheral registers the new duty cycles and sampling point. * * @param pHdl: Handler of the current instance of the PWM component. * @param hCCR4Reg: New capture/compare register value, written in timer clock counts. * @retval Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ __STATIC_INLINE uint16_t R3_2_WriteTIMRegisters( PWMC_Handle_t * pHdl, uint16_t hCCR4Reg ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint16_t hAux; LL_TIM_OC_SetCompareCH1( TIMx, pHandle->_Super.CntPhA ); LL_TIM_OC_SetCompareCH2( TIMx, pHandle->_Super.CntPhB ); LL_TIM_OC_SetCompareCH3( TIMx, pHandle->_Super.CntPhC ); LL_TIM_OC_SetCompareCH4( TIMx, hCCR4Reg ); /* Limit for update event */ /* Check the if TIMx CH4 is enabled. If it is set, an update event has occurred and thus the FOC rate is too high */ if (LL_TIM_CC_IsEnabledChannel(TIMx, LL_TIM_CHANNEL_CH4)) { hAux = MC_DURATION; } else { hAux = MC_NO_ERROR; } if ( pHandle->_Super.SWerror == 1u ) { hAux = MC_DURATION; pHandle->_Super.SWerror = 0u; } return hAux; } /* * @brief Configures the ADC for the current sampling during calibration. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ __weak uint16_t R3_2_SetADCSampPointCalibration( PWMC_Handle_t * pHdl) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* Set rising edge trigger (default) */ pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_RISING; pHandle->_Super.Sector = pHandle->CalibSector; return R3_2_WriteTIMRegisters( &pHandle->_Super, (uint32_t)(pHandle->Half_PWMPeriod - 1u) ); } /* * @brief Configures the ADC for the current sampling related to sector X (X = [1..6] ). * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ __weak uint16_t R3_2_SetADCSampPointSectX( PWMC_Handle_t * pHdl) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif uint16_t hCntSmp; uint16_t hDeltaDuty; register uint16_t lowDuty = pHdl->lowDuty; register uint16_t midDuty = pHdl->midDuty; /* Check if sampling AB in the middle of PWM is possible */ if ( ( uint16_t )( pHandle->Half_PWMPeriod - lowDuty ) > pHandle->pParams_str->hTafter ) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled which corresponds * to sector 4 */ pHandle->_Super.Sector = SECTOR_4; /* set sampling point trigger in the middle of PWM period */ hCntSmp = ( uint32_t )( pHandle->Half_PWMPeriod ) - 1u; } else { /* ADC Injected sequence configuration. The stator phase with minimum value of complementary duty cycle is set as first. In every sector there is always one phase with maximum complementary duty, one with minimum complementary duty and one with variable complementary duty. In this case, phases with variable complementary duty and with maximum duty are converted and the first will be always the phase with variable complementary duty cycle */ /* Crossing Point Searching */ hDeltaDuty = ( uint16_t )( lowDuty - midDuty ); /* Definition of crossing point */ if ( hDeltaDuty > ( uint16_t )( pHandle->Half_PWMPeriod - lowDuty ) * 2u ) { /* hTbefore = 2*Ts + Tc, where Ts = Sampling time of ADC, Tc = Conversion Time of ADC */ hCntSmp = lowDuty - pHandle->pParams_str->hTbefore; } else { /* hTafter = DT + max(Trise, Tnoise) */ hCntSmp = lowDuty + pHandle->pParams_str->hTafter; if ( hCntSmp >= pHandle->Half_PWMPeriod ) { /* It must be changed the trigger direction from positive to negative to sample after middle of PWM*/ pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_FALLING; hCntSmp = ( 2u * pHandle->Half_PWMPeriod ) - hCntSmp - 1u; } } } return R3_2_WriteTIMRegisters( &pHandle->_Super, hCntSmp ); } /* * @brief Configures the ADC for the current sampling related to sector X (X = [1..6] ) in case of overmodulation. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ uint16_t R3_2_SetADCSampPointSectX_OVM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ uint16_t SamplingPoint; uint16_t DeltaDuty; pHandle->_Super.useEstCurrent = false; DeltaDuty = ( uint16_t )( pHdl->lowDuty - pHdl->midDuty ); /* case 1 (cf user manual) */ if (( uint16_t )( pHandle->Half_PWMPeriod - pHdl->lowDuty ) > pHandle->pParams_str->hTafter) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled which corresponds * to sector 4 or 5 */ pHandle->_Super.Sector = SECTOR_5; /* set sampling point trigger in the middle of PWM period */ SamplingPoint = pHandle->Half_PWMPeriod - (uint16_t) 1; } else /* case 2 (cf user manual) */ { if (DeltaDuty >= pHandle->pParams_str->Tcase2) { SamplingPoint = pHdl->lowDuty - pHandle->pParams_str->hTbefore; } else { /* case 3 (cf user manual) */ if ((pHandle->Half_PWMPeriod - pHdl->lowDuty) > pHandle->pParams_str->Tcase3) { /* ADC trigger edge must be changed from positive to negative */ pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_FALLING; SamplingPoint = pHdl->lowDuty + pHandle->pParams_str->Tsampling; } else { SamplingPoint = pHandle->Half_PWMPeriod-1; pHandle->_Super.useEstCurrent = true; } } } return R3_2_WriteTIMRegisters( &pHandle->_Super, SamplingPoint ); } /* * @brief Contains the TIMx Update event interrupt. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void * R3_2_TIMx_UP_IRQHandler( PWMC_R3_2_Handle_t * pHandle ) { TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx_1 = pHandle->pParams_str->ADCDataReg1[0]; ADC_TypeDef * ADCx_2 = pHandle->pParams_str->ADCDataReg2[0]; /* Disabling trigger to avoid unwanted conversion */ LL_ADC_INJ_StopConversionExtTrig(ADCx_1); LL_ADC_INJ_StopConversionExtTrig(ADCx_2); /* Set next current channel according to sector */ ADCx_1->JSQR = pHandle->pParams_str->ADCConfig1[pHandle->_Super.Sector]; ADCx_2->JSQR = pHandle->pParams_str->ADCConfig2[pHandle->_Super.Sector]; LL_ADC_INJ_SetTriggerSource(ADCx_1,pHandle->ADC_ExternalTriggerInjected); LL_ADC_INJ_SetTriggerSource(ADCx_2,pHandle->ADC_ExternalTriggerInjected); /* enable ADC trigger source */ LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH4); LL_ADC_INJ_StartConversionExtTrig(ADCx_1, pHandle->ADCTriggerEdge); LL_ADC_INJ_StartConversionExtTrig(ADCx_2, pHandle->ADCTriggerEdge); /* reset default edge detection trigger */ pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_RISING; return &( pHandle->_Super.Motor ); } /* * @brief Sets the PWM mode for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_2_RLDetectionModeEnable( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; if ( pHandle->_Super.RLDetectionMode == false ) { /* Channel1 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH1, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH1N ); LL_TIM_OC_SetCompareCH1( TIMx, 0u ); /* Channel2 configuration */ if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_ACTIVE ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_INACTIVE ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else { } /* Channel3 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH3, LL_TIM_OCMODE_PWM2 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3N ); } pHandle->_Super.pFctGetPhaseCurrents = &R3_2_RLGetPhaseCurrents; pHandle->_Super.pFctTurnOnLowSides = &R3_2_RLTurnOnLowSides; pHandle->_Super.pFctSwitchOnPwm = &R3_2_RLSwitchOnPWM; pHandle->_Super.pFctSwitchOffPwm = &R3_2_SwitchOffPWM; pHandle->_Super.RLDetectionMode = true; } /* * @brief Disables the PWM mode for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_2_RLDetectionModeDisable( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; if ( pHandle->_Super.RLDetectionMode == true ) { /* Channel1 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH1, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1 ); if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH1N ); } else { } LL_TIM_OC_SetCompareCH1( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) >> 1 ); /* Channel2 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2 ); if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else { } LL_TIM_OC_SetCompareCH2( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) >> 1 ); /* Channel3 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH3, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH3 ); if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH3N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3N ); } else { } LL_TIM_OC_SetCompareCH3( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) >> 1 ); pHandle->_Super.pFctGetPhaseCurrents = &R3_2_GetPhaseCurrents; pHandle->_Super.pFctTurnOnLowSides = &R3_2_TurnOnLowSides; pHandle->_Super.pFctSwitchOnPwm = &R3_2_SwitchOnPWM; pHandle->_Super.pFctSwitchOffPwm = &R3_2_SwitchOffPWM; pHandle->_Super.RLDetectionMode = false; } } /* * @brief Sets the PWM dutycycle for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. * @param hDuty: Duty cycle to apply, written in uint16_t. * @retval Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ uint16_t R3_2_RLDetectionModeSetDuty( PWMC_Handle_t * pHdl, uint16_t hDuty ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint32_t val; uint16_t hAux; val = ( ( uint32_t )( pHandle->Half_PWMPeriod ) * ( uint32_t )( hDuty ) ) >> 16; pHandle->_Super.CntPhA = ( uint16_t )( val ); /* TIM1 Channel 1 Duty Cycle configuration. * In RL Detection mode only the Up-side device of Phase A are controlled*/ LL_TIM_OC_SetCompareCH1(TIMx, ( uint32_t )pHandle->_Super.CntPhA); /* set the sector that correspond to Phase A and B sampling */ pHdl->Sector = SECTOR_4; /* Limit for update event */ /* Check the status flag. If an update event has occurred before to set new values of regs the FOC rate is too high */ if (LL_TIM_CC_IsEnabledChannel(TIMx, LL_TIM_CHANNEL_CH4)) { hAux = MC_DURATION; } else { hAux = MC_NO_ERROR; } if ( pHandle->_Super.SWerror == 1u ) { hAux = MC_DURATION; pHandle->_Super.SWerror = 0u; } return hAux; } /* * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p pStator_Currents ab_t format. * * Specific to RL. */ static void R3_2_RLGetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; int32_t wAux; /* disable ADC trigger source */ LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); wAux = (int32_t)( pHandle->PhaseBOffset ) - (int32_t)(pHandle->pParams_str->ADCDataReg2[pHandle->_Super.Sector]->JDR1)*2; /* Check saturation */ if ( wAux > -INT16_MAX ) { if ( wAux < INT16_MAX ) { } else { wAux = INT16_MAX; } } else { wAux = -INT16_MAX; } pStator_Currents->a = (int16_t)wAux; pStator_Currents->b = (int16_t)wAux; } /* * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors * of driving section. It has to be called at each motor start-up when * using high voltage drivers. * This function is specific for RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. * @param ticks: Duty cycle of the boot capacitors charge, specific to motor. */ static void R3_2_RLTurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /*Turn on the phase A low side switch */ LL_TIM_OC_SetCompareCH1 ( TIMx, 0u ); /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Wait until next update */ while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } return; } /* * @brief Enables PWM generation on the proper Timer peripheral. * * This function is specific for RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. */ static void R3_2_RLSwitchOnPWM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); LL_TIM_OC_SetCompareCH1( TIMx, 1u ); LL_TIM_OC_SetCompareCH4( TIMx, ( pHandle->Half_PWMPeriod ) - 5u ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE; LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { if ( ( TIMx->CCER & TIMxCCER_MASK_CH123 ) != 0u ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* enable TIMx update interrupt*/ LL_TIM_EnableIT_UPDATE( TIMx ); return; } /* * @brief Turns on low sides switches and start ADC triggering. * * This function is specific for MP phase. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_2_RLTurnOnLowSidesAndStart( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx_1 = pHandle->pParams_str->ADCDataReg1[0]; ADC_TypeDef * ADCx_2 = pHandle->pParams_str->ADCDataReg2[0]; /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); LL_TIM_OC_SetCompareCH1 ( TIMx, 0x0u ); LL_TIM_OC_SetCompareCH2 ( TIMx, 0x0u ); LL_TIM_OC_SetCompareCH3 ( TIMx, 0x0u ); LL_TIM_OC_SetCompareCH4( TIMx, ( pHandle->Half_PWMPeriod - 5u)); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE ; LL_TIM_EnableAllOutputs ( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } pHdl->Sector = SECTOR_4; LL_ADC_INJ_SetTriggerSource( ADCx_1, pHandle->ADC_ExternalTriggerInjected); LL_ADC_INJ_SetTriggerSource( ADCx_2, pHandle->ADC_ExternalTriggerInjected); LL_ADC_INJ_StartConversionExtTrig(ADCx_1,LL_ADC_INJ_TRIG_EXT_RISING); LL_ADC_INJ_StartConversionExtTrig(ADCx_2,LL_ADC_INJ_TRIG_EXT_RISING); LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH4); LL_TIM_EnableIT_UPDATE( TIMx ); return; } /* * @brief Sets ADC sampling points. * * This function is specific for MP phase. Specific to F4XX, F7XX, L4XX and H5XX. * * @param pHdl: Handler of the current instance of the PWM component. */ void RLSetADCSampPoint( PWMC_Handle_t * pHdl ) { /* dummy sector setting to get correct Ia value */ pHdl->Sector = SECTOR_4; return; } /** * @} */ /** * @} */ /** * @} */ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
51,096
C
30.232885
143
0.618052
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/F7xx/Inc/r3_2_f7xx_pwm_curr_fdbk.h
/** ****************************************************************************** * @file r3_2_f7xx_pwm_curr_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * R3_F7XX_pwm_curr_fdbk component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup R3_2_F7XX_pwm_curr_fdbk */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __R3_2_F7XX_PWMNCURRFDBK_H #define __R3_2_F7XX_PWMNCURRFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "pwm_curr_fdbk.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup R3_2_pwm_curr_fdbk * @{ */ /* Exported types ------------------------------------------------------- */ /* * @brief R3_2_F7XX_pwm_curr_fdbk component parameters structure definition. */ typedef const struct { TIM_TypeDef * TIMx; /* Timer used for PWM generation.*/ ADC_TypeDef *ADCDataReg1[6]; ADC_TypeDef *ADCDataReg2[6]; uint32_t ADCConfig1 [6] ; /* Values of JSQR for first ADC for 6 sectors. */ uint32_t ADCConfig2 [6] ; /* Values of JSQR for second ADC for 6 sectors. */ /* Dual MC parameters --------------------------------------------------------*/ uint16_t Tw; /* Used for switching the context in dual MC. It contains biggest delay (expressed in counter ticks) between the counter crest and ADC latest trigger. Specific to F4XX and F7XX.*/ uint16_t hTafter; /* Sum of dead time plus max value between rise time and noise time express in number of TIM clocks. Specific to F4XX and F7XX.*/ uint16_t hTbefore; /* Sampling time express in number of TIM clocks. Specific to F4XX and F7XX.*/ uint16_t Tsampling; /* Sampling time express in number of TIM clocks.*/ uint16_t Tcase2; /* Sampling time express in number of TIM clocks.*/ uint16_t Tcase3; /* Sampling time express in number of TIM clocks.*/ uint16_t hDeadTime; /* Dead time in number of TIM clock cycles. If CHxN are enabled, it must contain the dead time to be generated by the microcontroller, otherwise it expresses the maximum dead time generated by driving network. Specific to F4XX and F7XX. */ uint8_t bFreqRatio; /* Used in case of dual MC to synchronize TIM1 and TIM8. It has effect only on the second instanced object and must be equal to the ratio between the two PWM frequencies (higher/lower). Supported values are 1, 2 or 3. */ uint8_t bIsHigherFreqTim; /* When bFreqRatio is greater than 1 this param is used to indicate if this instance is the one with the highest frequency. Allowed value are: HIGHER_FREQ or LOWER_FREQ. */ /* PWM Driving signals initialization ----------------------------------------*/ uint8_t RepetitionCounter; /* Expresses the number of PWM periods to be elapsed before compare registers are updated again. In particular: RepetitionCounter= (2* #PWM periods)-1*/ } R3_2_Params_t; /* * @brief Handles an instance of the R3_F7XX_pwm_curr_fdbk component. */ typedef struct { PWMC_Handle_t _Super; /* Base component handler. */ uint32_t PhaseAOffset; /* Offset of Phase A current sensing network. */ uint32_t PhaseBOffset; /* Offset of Phase B current sensing network. */ uint32_t PhaseCOffset; /* Offset of Phase C current sensing network. */ uint32_t ADC_ExternalTriggerInjected; /* External trigger selection for ADC peripheral. */ uint32_t ADCTriggerEdge; /* Trigger edge selection for ADC peripheral. Specific to F4XX, F7XX and L4XX. */ uint16_t Half_PWMPeriod; /* Half PWM Period in timer clock counts. */ uint8_t CalibSector; /* Space vector sector number during calibration. Specific to F4XX, F7XX and L4XX. */ volatile uint8_t PolarizationCounter; /* Number of conversions performed during the calibration phase. */ R3_2_Params_t const *pParams_str; } PWMC_R3_2_Handle_t; /* Exported functions ------------------------------------------------------- */ /* Initializes TIMx, ADC, GPIO, DMA1 and NVIC for current reading * in three shunt topology using STM32F30X and two ADCs. */ void R3_2_Init( PWMC_R3_2_Handle_t * pHandle ); /* * Stores into the handler the voltage present on Ia and * Ib current feedback analog channels when no current is flowing into the motor. */ void R3_2_CurrentReadingCalibration( PWMC_Handle_t * pHdl ); /* * Computes and stores in the handler the latest converted motor phase currents in ab_t format. */ void R3_2_GetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * Iab ); /* * Computes and stores in the handler the latest converted motor phase currents in ab_t format. Specific to overmodulation. */ void R3_2_GetPhaseCurrents_OVM( PWMC_Handle_t * pHdl, ab_t * Iab ); /* * Turns on low sides switches. */ void R3_2_TurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ); /* * Enables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_2_SwitchOnPWM( PWMC_Handle_t * pHdl ); /* * Disables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_2_SwitchOffPWM( PWMC_Handle_t * pHdl ); /* * Configures the ADC for the current sampling during calibration. */ uint16_t R3_2_SetADCSampPointCalibration( PWMC_Handle_t * pHdl); /* * Configures the ADC for the current sampling related to sector X (X = [1..6] ). */ uint16_t R3_2_SetADCSampPointSectX( PWMC_Handle_t * pHdl); /* * Configures the ADC for the current sampling related to sector X (X = [1..6] ) in case of overmodulation. */ uint16_t R3_2_SetADCSampPointSectX_OVM( PWMC_Handle_t * pHdl); /* * Sets the PWM mode during RL Detection Mode. */ void R3_2_RLDetectionModeEnable( PWMC_Handle_t * pHdl ); /* * Disables the PWM mode during RL Detection Mode. */ void R3_2_RLDetectionModeDisable( PWMC_Handle_t * pHdl ); /* * Set the PWM dutycycle during RL Detection Mode. */ uint16_t R3_2_RLDetectionModeSetDuty( PWMC_Handle_t * pHdl, uint16_t hDuty ); /* * Contains the TIMx Update event interrupt */ void * R3_2_TIMx_UP_IRQHandler( PWMC_R3_2_Handle_t * pHdl ); /* * Contains the TIMx Break1/2 for overvoltage event interrupt. */ void * R3_2_OVP_IRQHandler( PWMC_R3_2_Handle_t * pHdl ); /* * Contains the TIMx Break1/2 for overcurrent event interrupt */ void * R3_2_OCP_IRQHandler( PWMC_R3_2_Handle_t * pHdl ); /* * Turns on low sides switches and start ADC triggering. */ void R3_2_RLTurnOnLowSidesAndStart( PWMC_Handle_t * pHdl ); /* * Sets ADC sampling points. */ void RLSetADCSampPoint( PWMC_Handle_t * pHdl ); /* * Stores in the handler the calibrated offsets. */ void R3_2_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /* * Reads the calibrated offsets stored in the handler. */ void R3_2_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*__R3_F7XX_PWMNCURRFDBK_H*/ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
9,193
C
37.308333
124
0.540629
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/F7xx/Inc/r3_1_f7xx_pwm_curr_fdbk.h
/** ****************************************************************************** * @file r3_1_f7xx_pwm_curr_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * R3_1_F7XX_pwm_curr_fdbk component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup R3_1_F7XX_pwm_curr_fdbk */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __R3_1_F7XX_PWMCURRFDBK_H #define __R3_1_F7XX_PWMCURRFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "pwm_curr_fdbk.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup R3_1_pwm_curr_fdbk * @{ */ #define GPIO_NoRemap_TIM1 ((uint32_t)(0)) #define SHIFTED_TIMs ((uint8_t) 1) #define NO_SHIFTED_TIMs ((uint8_t) 0) #define NONE ((uint8_t)(0x00)) #define EXT_MODE ((uint8_t)(0x01)) #define INT_MODE ((uint8_t)(0x02)) /* Exported types ------------------------------------------------------- */ /* * R3_1_F7XX_pwm_curr_fdbk component parameters definition. */ typedef const struct { TIM_TypeDef * TIMx; /* Timer used for PWM generation. */ ADC_TypeDef * ADCx; /* ADC peripheral to be used. */ uint32_t ADCConfig[6] ; /* Stores ADC sequence for the 6 sectors. */ uint16_t Tafter; /* Sum of dead time plus max value between rise time and noise time expressed in number of TIM clocks. */ uint16_t Tbefore; /* Sampling time expressed in number of TIM clocks.*/ uint16_t Tsampling; /* Sampling time expressed in number of TIM clocks.*/ uint16_t Tcase2; /* Sampling time expressed in number of TIM clocks.*/ uint16_t Tcase3; /* Sampling time expressed in number of TIM clocks.*/ uint8_t RepetitionCounter; /* Expresses the number of PWM periods to be elapsed before compare registers are updated again. In particular: RepetitionCounter= (2* #PWM periods)-1*/ } R3_1_Params_t; /* * @brief This structure is used to handle an instance of the * R3_1_F7XX_pwm_curr_fdbk component. */ typedef struct { PWMC_Handle_t _Super; /* Base component handler. */ uint32_t PhaseAOffset; /* Offset of Phase A current sensing network. */ uint32_t PhaseBOffset; /* Offset of Phase B current sensing network. */ uint32_t PhaseCOffset; /* Offset of Phase C current sensing network. */ uint32_t ADC_ExternalTriggerInjected; /* External ADC trigger source. */ uint32_t ADCTriggerEdge; /* External ADC trigger edge. */ uint16_t Half_PWMPeriod; /* Half PWM Period in timer clock counts. */ uint8_t CalibSector; /* Space vector sector number during calibration. */ volatile uint8_t PolarizationCounter; /* Number of conversions performed during the calibration phase. */ R3_1_Params_t const *pParams_str; } PWMC_R3_1_Handle_t; /* Exported functions ------------------------------------------------------- */ /* Initializes peripherals for current reading and PWM generation * in three shunts configuration using STM32F302x8 *****/ void R3_1_Init( PWMC_R3_1_Handle_t * pHandle ); /* Disables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_1_SwitchOffPWM( PWMC_Handle_t * pHdl ); /* * Enables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_1_SwitchOnPWM( PWMC_Handle_t * pHdl ); /* * Turns on low sides switches. */ void R3_1_TurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ); /* * Computes and stores in the handler the latest converted motor phase currents in ab_t format. */ void R3_1_GetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ); /* * Computes and stores in the handler the latest converted motor phase currents in ab_t format. Specific to overmodulation. */ void R3_1_GetPhaseCurrents_OVM( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ); /* * Stores into handler component variables the offset voltage on Ia and * Ib current feedback analog channels when no current is flowing into the * motor. */ void R3_1_CurrentReadingCalibration( PWMC_Handle_t * pHdl ); /* * Configures the ADC for the current sampling during calibration. */ uint16_t R3_1_SetADCSampPointCalibration( PWMC_Handle_t * pHdl); /* * Configures the ADC for the current sampling related to sector X (X = [1..6] ). */ uint16_t R3_1_SetADCSampPointSectX( PWMC_Handle_t * pHdl); /* * Configures the ADC for the current sampling related to sector (X = [1..6] ) in case of overmodulation. */ uint16_t R3_1_SetADCSampPointSectX_OVM( PWMC_Handle_t * pHdl); /* * Contains the TIMx Update event interrupt. */ void * R3_1_TIMx_UP_IRQHandler( PWMC_R3_1_Handle_t * pHdl ); /* * Sets the calibrated offset. */ void R3_1_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /* * Reads the calibrated offsets. */ void R3_1_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /* * Sets the PWM mode for R/L detection. */ void R3_1_RLDetectionModeEnable( PWMC_Handle_t * pHdl ); /* * Disables the PWM mode for R/L detection. */ void R3_1_RLDetectionModeDisable( PWMC_Handle_t * pHdl ); /* * Sets the PWM dutycycle for R/L detection. */ uint16_t R3_1_RLDetectionModeSetDuty( PWMC_Handle_t * pHdl, uint16_t hDuty ); /* Computes and stores in @p pHdl handler the latest converted motor phase currents in @p pStator_Currents ab_t format. */ static void R3_1_RLGetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ); /* * Turns on low sides switches. */ static void R3_1_RLTurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ); /* * Enables PWM generation on the proper Timer peripheral. */ static void R3_1_RLSwitchOnPWM( PWMC_Handle_t * pHdl ); /* * Turns on low sides switches and start ADC triggering. */ void R3_1_RLTurnOnLowSidesAndStart( PWMC_Handle_t * pHdl ); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*__R3_1_F7XX_PWMNCURRFDBK_H*/ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
7,406
C
31.774336
124
0.57764
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/F7xx/Inc/ics_f7xx_pwm_curr_fdbk.h
/** ****************************************************************************** * @file ics_f7xx_pwm_curr_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * ICS PWM current feedback component for F7XX of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup ICS_F7XX_pwm_curr_fdbk */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __ICS_F7XX_PWMNCURRFDBK_H #define __ICS_F7XX_PWMNCURRFDBK_H #include "pwm_curr_fdbk.h" #include "ics_dd_pwmncurrfdbk.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup ICS_pwm_curr_fdbk * @{ */ #define SOFOC 0x0008u /* This flag is reset at the beginning of FOC and it is set in the TIM UP IRQ. If at the end of FOC this flag is set, it means that FOC rate is too high and thus an error is generated */ /* * PWM and Current Feedback ICS handle. */ typedef struct { PWMC_Handle_t _Super; /* Base component handler. */ uint32_t PhaseAOffset; /* Offset of Phase A current sensing network. */ uint32_t PhaseBOffset; /* Offset of Phase B current sensing network. */ uint16_t Half_PWMPeriod; /* Half PWM Period in timer clock counts. */ volatile uint8_t PolarizationCounter; /* Number of conversions performed during the calibration phase. */ ICS_Params_t *pParams_str; } PWMC_ICS_Handle_t; /* Exported functions ------------------------------------------------------- */ /* * Initializes TIMx, ADC, GPIO and NVIC for current reading * in ICS configuration using STM32F4XX. */ void ICS_Init( PWMC_ICS_Handle_t * pHandle ); /* * Sums up injected conversion data into wPhaseXOffset. */ void ICS_CurrentReadingCalibration( PWMC_Handle_t * pHandle ); /* * Computes and stores in the handler the latest converted motor phase currents in ab_t format. */ void ICS_GetPhaseCurrents( PWMC_Handle_t * pHandle, ab_t * pStator_Currents ); /* * Turns on low sides switches. */ void ICS_TurnOnLowSides( PWMC_Handle_t * pHandle, uint32_t ticks ); /* * Enables PWM generation on the proper Timer peripheral acting on MOE bit. */ void ICS_SwitchOnPWM( PWMC_Handle_t * pHandle ); /* * Disables PWM generation on the proper Timer peripheral acting on MOE bit. */ void ICS_SwitchOffPWM( PWMC_Handle_t * pHandle ); /* * Writes into peripheral registers the new duty cycle and sampling point. */ uint16_t ICS_WriteTIMRegisters( PWMC_Handle_t * pHandle ); void * ICS_IRQHandler( PWMC_Handle_t * pHandle, unsigned char flag ); /* * Contains the TIMx Update event interrupt. */ void * ICS_TIMx_UP_IRQHandler( PWMC_ICS_Handle_t * pHandle ); /* * Contains the TIMx Break1 event interrupt. */ void * ICS_BRK_IRQHandler( PWMC_ICS_Handle_t * pHdl ); /* * Stores in the handler the calibrated offsets. */ void ICS_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /* * Reads the calibrated offsets stored in the handler. */ void ICS_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*__ICS_F7XX_PWMNCURRFDBK_H*/ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
4,017
C
26.902778
107
0.606423
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/L4xx/Src/r3_1_l4xx_pwm_curr_fdbk.c
/** ****************************************************************************** * @file r3_1_l4xx_pwm_curr_fdbk.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement current sensor * class to be stantiated when the three shunts current sensing * topology is used. * * It is specifically designed for STM32L4XX microcontrollers and * implements the successive sampling of two motor current using only one ADC. * + MCU peripheral and handle initialization function * + three shunt current sensing * + space vector modulation function * + ADC sampling function * ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * * @ingroup R3_1_L4XX_pwm_curr_fdbk */ /* Includes ------------------------------------------------------------------*/ #include "r3_1_l4xx_pwm_curr_fdbk.h" #include "pwm_common.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup R3_1_pwm_curr_fdbk * @{ */ /* Private defines -----------------------------------------------------------*/ #define TIMxCCER_MASK_CH123 ((uint16_t) (LL_TIM_CHANNEL_CH1|LL_TIM_CHANNEL_CH1N|\ LL_TIM_CHANNEL_CH2|LL_TIM_CHANNEL_CH2N|\ LL_TIM_CHANNEL_CH3|LL_TIM_CHANNEL_CH3N)) /* DIR bits of TIM1 CR1 register identification for correct check of Counting direction detection*/ #define DIR_MASK 0x0010u /* binary value: 0000000000010000 */ /* Private typedef -----------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ void R3_1_HFCurrentsCalibrationAB( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ); void R3_1_HFCurrentsCalibrationC( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ); uint16_t R3_1_WriteTIMRegisters( PWMC_Handle_t * pHdl, uint16_t hCCR4Reg ); /* Private functions ---------------------------------------------------------*/ /* Local redefinition of both LL_TIM_OC_EnablePreload & LL_TIM_OC_DisablePreload */ __STATIC_INLINE void __LL_TIM_OC_EnablePreload(TIM_TypeDef *TIMx, uint32_t Channel) { register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); register volatile uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); SET_BIT(*pReg, (TIM_CCMR1_OC1PE << SHIFT_TAB_OCxx[iChannel])); } __STATIC_INLINE void __LL_TIM_OC_DisablePreload(TIM_TypeDef *TIMx, uint32_t Channel) { register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); register volatile uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); CLEAR_BIT(*pReg, (TIM_CCMR1_OC1PE << SHIFT_TAB_OCxx[iChannel])); } /* * @brief Initializes TIMx, ADC, GPIO, DMA1 and NVIC for current reading * in three shunt topology using one ADC. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void R3_1_Init( PWMC_R3_1_Handle_t * pHandle ) { TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; if ( ( uint32_t )pHandle == ( uint32_t )&pHandle->_Super ) { /* disable IT and flags in case of LL driver usage * workaround for unwanted interrupt enabling done by LL driver */ LL_ADC_DisableIT_EOC( ADCx ); LL_ADC_ClearFlag_EOC( ADCx ); LL_ADC_DisableIT_JEOC( ADCx ); LL_ADC_ClearFlag_JEOC( ADCx ); /* disable main TIM counter to ensure * a synchronous start by TIM2 trigger */ LL_TIM_DisableCounter( TIMx ); if ( TIMx == TIM1 ) { /* TIM1 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph( LL_DBGMCU_APB2_GRP1_TIM1_STOP ); } #if defined(TIM8) else { /* TIM8 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph( LL_DBGMCU_APB2_GRP1_TIM8_STOP ); } #endif LL_TIM_ClearFlag_BRK( TIMx ); LL_TIM_ClearFlag_BRK2( TIMx ); LL_TIM_EnableIT_BRK( TIMx ); /* Enable PWM channel */ LL_TIM_CC_EnableChannel( TIMx, TIMxCCER_MASK_CH123 ); LL_ADC_StartCalibration( ADCx, LL_ADC_SINGLE_ENDED ); while ( LL_ADC_IsCalibrationOnGoing( ADCx ) ) { } /* ADC Enable (must be done after calibration) */ LL_ADC_Enable( ADCx ); /* reset regular conversion sequencer length set by cubeMX */ LL_ADC_REG_SetSequencerLength( ADCx, LL_ADC_REG_SEQ_SCAN_DISABLE ); /* Queue Of Context Mode for injected channels Enabling */ LL_ADC_INJ_SetQueueMode(ADCx, LL_ADC_INJ_QUEUE_2CONTEXTS_END_EMPTY); /* Flush JSQR settings done by CubeMX */ LL_ADC_INJ_StartConversion(ADCx); LL_ADC_INJ_StopConversion(ADCx); /* Disable TIMx ADC trigger */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); /* Enable ADC injected end of sequence interrupt */ LL_ADC_ClearFlag_JEOS( ADCx ); LL_ADC_EnableIT_JEOS( ADCx ); pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_RISING; /* Clear the flags */ pHandle->_Super.DTTest = 0u; } } /* * @brief Stores in @p pHdl handler the calibrated @p offsets. * */ __weak void R3_1_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 pHandle->PhaseAOffset = offsets->phaseAOffset; pHandle->PhaseBOffset = offsets->phaseBOffset; pHandle->PhaseCOffset = offsets->phaseCOffset; pHdl->offsetCalibStatus = true; } /* * @brief Reads the calibrated @p offsets stored in @p pHdl. * */ __weak void R3_1_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 offsets->phaseAOffset = pHandle->PhaseAOffset; offsets->phaseBOffset = pHandle->PhaseBOffset; offsets->phaseCOffset = pHandle->PhaseCOffset; } /* * @brief Stores into the @p pHdl the voltage present on Ia and Ib current * feedback analog channels when no current is flowing into the motor. * */ __weak void R3_1_CurrentReadingCalibration( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; volatile PWMC_GetPhaseCurr_Cb_t GetPhaseCurrCbSave; volatile PWMC_SetSampPointSectX_Cb_t SetSampPointSectXCbSave; if (false == pHandle->_Super.offsetCalibStatus) { /* Save callback routines */ GetPhaseCurrCbSave = pHandle->_Super.pFctGetPhaseCurrents; SetSampPointSectXCbSave = pHandle->_Super.pFctSetADCSampPointSectX; pHandle->PhaseAOffset = 0u; pHandle->PhaseBOffset = 0u; pHandle->PhaseCOffset = 0u; pHandle->PolarizationCounter = 0u; /* It forces inactive level on TIMx CHy and CHyN */ LL_TIM_CC_DisableChannel(TIMx, TIMxCCER_MASK_CH123); /* Offset calibration for A & B phases */ /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R3_1_HFCurrentsCalibrationAB; pHandle->_Super.pFctSetADCSampPointSectX = &R3_1_SetADCSampPointCalibration; pHandle->CalibSector = SECTOR_5; /* Required to force first polarization conversion on SECTOR_5*/ pHandle->_Super.Sector = SECTOR_5; R3_1_SwitchOnPWM( &pHandle->_Super ); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd( TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter ); R3_1_SwitchOffPWM( &pHandle->_Super ); /* Offset calibration for C phase */ /* Reset PolarizationCounter */ pHandle->PolarizationCounter = 0u; /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R3_1_HFCurrentsCalibrationC; /* "Phase C current calibration to verify" */ pHandle->CalibSector = SECTOR_1; /* Required to force first polarization conversion on SECTOR_1*/ pHandle->_Super.Sector = SECTOR_1; R3_1_SwitchOnPWM( &pHandle->_Super ); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd( TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter ); R3_1_SwitchOffPWM( &pHandle->_Super ); /* Shift of N bits to divide for the NB_ CONVERSIONS = 16= 2^N with N = 4 */ pHandle->PhaseAOffset >>= 4; pHandle->PhaseBOffset >>= 4; pHandle->PhaseCOffset >>= 4; if (0U == pHandle->_Super.SWerror) { pHandle->_Super.offsetCalibStatus = true; } else { /* nothing to do */ } /* Change back function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = GetPhaseCurrCbSave; pHandle->_Super.pFctSetADCSampPointSectX = SetSampPointSectXCbSave; } /* It over write TIMx CCRy wrongly written by FOC during calibration so as to force 50% duty cycle on the three inverer legs */ /* Disable TIMx preload */ __LL_TIM_OC_DisablePreload( TIMx, LL_TIM_CHANNEL_CH1 ); __LL_TIM_OC_DisablePreload( TIMx, LL_TIM_CHANNEL_CH2 ); __LL_TIM_OC_DisablePreload( TIMx, LL_TIM_CHANNEL_CH3 ); LL_TIM_OC_SetCompareCH1( TIMx, pHandle->Half_PWMPeriod ); LL_TIM_OC_SetCompareCH2( TIMx, pHandle->Half_PWMPeriod ); LL_TIM_OC_SetCompareCH3( TIMx, pHandle->Half_PWMPeriod ); __LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH1 ); __LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH2 ); __LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH3 ); /* It re-enable drive of TIMx CHy and CHyN by TIMx CHyRef*/ LL_TIM_CC_EnableChannel(TIMx, TIMxCCER_MASK_CH123); /* sector and phase sequence for the switch on phase */ pHandle->_Super.Sector = SECTOR_5; pHandle->_Super.BrakeActionLock = false; } /* * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p Iab ab_t format. * */ __weak void R3_1_GetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; int32_t wAux; uint32_t hReg1; uint32_t hReg2; uint8_t bSector; /* disable ADC trigger source */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); bSector = ( uint8_t )( pHandle->_Super.Sector ); hReg1 = ADCx->JDR1; hReg2 = ADCx->JDR2; switch ( bSector ) { case SECTOR_4: case SECTOR_5: { /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ wAux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( hReg1 ); /* Saturation of Ia */ if ( wAux < -INT16_MAX ) { pStator_Currents->a = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->a = INT16_MAX; } else { pStator_Currents->a = ( int16_t )wAux; } /* Ib = PhaseBOffset - ADC converted value) */ wAux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( hReg2 ); /* Saturation of Ib */ if ( wAux < -INT16_MAX ) { pStator_Currents->b = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->b = INT16_MAX; } else { pStator_Currents->b = ( int16_t )wAux; } } break; case SECTOR_6: case SECTOR_1: { /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ wAux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( hReg1 ); /* Saturation of Ib */ if ( wAux < -INT16_MAX ) { pStator_Currents->b = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->b = INT16_MAX; } else { pStator_Currents->b = ( int16_t )wAux; } /* Ic = PhaseCOffset - ADC converted value) */ /* Ia = -Ic -Ib */ wAux = ( int32_t )( pHandle->PhaseCOffset ) - ( int32_t )( hReg2 ); wAux = -wAux - ( int32_t )pStator_Currents->b; /* Saturation of Ia */ if ( wAux > INT16_MAX ) { pStator_Currents->a = INT16_MAX; } else if ( wAux < -INT16_MAX ) { pStator_Currents->a = -INT16_MAX; } else { pStator_Currents->a = ( int16_t )wAux; } } break; case SECTOR_2: case SECTOR_3: { /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ wAux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( hReg1 ); /* Saturation of Ia */ if ( wAux < -INT16_MAX ) { pStator_Currents->a = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->a = INT16_MAX; } else { pStator_Currents->a = ( int16_t )wAux; } /* Ic = PhaseCOffset - ADC converted value) */ /* Ib = -Ic -Ia */ wAux = ( int32_t )( pHandle->PhaseCOffset ) - ( int32_t )( hReg2 ); wAux = -wAux - ( int32_t )pStator_Currents->a; /* Saturation of Ib */ if ( wAux > INT16_MAX ) { pStator_Currents->b = INT16_MAX; } else if ( wAux < -INT16_MAX ) { pStator_Currents->b = -INT16_MAX; } else { pStator_Currents->b = ( int16_t )wAux; } } break; default: { } break; } pHandle->_Super.Ia = pStator_Currents->a; pHandle->_Super.Ib = pStator_Currents->b; pHandle->_Super.Ic = -pStator_Currents->a - pStator_Currents->b; } /* * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p Iab ab_t format. Specific to overmodulation. * */ __weak void R3_1_GetPhaseCurrents_OVM( PWMC_Handle_t * pHdl, ab_t * Iab ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; uint8_t Sector; int32_t Aux; uint32_t ADCDataReg1; uint32_t ADCDataReg2; /* disable ADC trigger source */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); Sector = ( uint8_t )pHandle->_Super.Sector; ADCDataReg1 = ADCx->JDR1;; ADCDataReg2 = ADCx->JDR2; switch ( Sector ) { case SECTOR_4: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { // Ib not available, use estimated Ib Aux = ( int32_t )( pHandle->_Super.IbEst ); } else { /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg2 ); } /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_5: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { // Ia not available, use estimated Ia Aux = ( int32_t )( pHandle->_Super.IaEst ); } else { Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg2 ); /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_6: /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IcEst ; /* -Ic */ Aux -= ( int32_t )Iab->b; } else { /* Ia = -Ic -Ib */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->b; /* Ia */ } /* Saturation of Ia */ if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else { Iab->a = ( int16_t )Aux; } break; case SECTOR_1: /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IbEst; } else { Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } /* Ia = -Ic -Ib */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->b; /* Ia */ /* Saturation of Ia */ if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else { Iab->a = ( int16_t )Aux; } break; case SECTOR_2: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IaEst; } else { Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } /* Ib = -Ic -Ia */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ /* Saturation of Ib */ if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_3: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { /* Ib = -Ic -Ia */ Aux = ( int32_t ) pHandle->_Super.IcEst; /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ } else { /* Ib = -Ic -Ia */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ } /* Saturation of Ib */ if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; default: break; } pHandle->_Super.Ia = Iab->a; pHandle->_Super.Ib = Iab->b; pHandle->_Super.Ic = -Iab->a - Iab->b; } /* * @brief Implementation of PWMC_GetPhaseCurrents to be performed during calibration. * * It sums up injected conversion data into PhaseAOffset and wPhaseBOffset * to compute the offset introduced in the current feedback network. It is required to * properly configure ADC inputs before in order to enable offset computation. * * @param pHdl: Pointer on the target component instance. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ __weak void R3_1_HFCurrentsCalibrationAB( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; /* disable ADC trigger source */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); if ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { pHandle->PhaseAOffset += ADCx->JDR1; pHandle->PhaseBOffset += ADCx->JDR2; pHandle->PolarizationCounter++; } /* during offset calibration no current is flowing in the phases */ pStator_Currents->a = 0; pStator_Currents->b = 0; } /* * @brief Implementation of PWMC_GetPhaseCurrents to be performed during calibration. * * It sums up injected conversion data into PhaseCOffset to compute the offset * introduced in the current feedback network. It is required to properly configure * ADC inputs before in order to enable offset computation. * * @param pHdl: Pointer on the target component instance. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ __weak void R3_1_HFCurrentsCalibrationC( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; /* disable ADC trigger source */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); if ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { pHandle->PhaseCOffset += ADCx->JDR2; pHandle->PolarizationCounter++; } /* during offset calibration no current is flowing in the phases */ pStator_Currents->a = 0; pStator_Currents->b = 0; } /* * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors of driving section. It has to be * called each motor start-up when using high voltage drivers. * * @param pHdl: Handler of the current instance of the PWM component * @param ticks: Timer ticks value to be applied * Min value: 0 (low sides ON) * Max value: PWM_PERIOD_CYCLES/2 (low sides OFF) */ __weak void R3_1_TurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = true; /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /*Turn on the three low side switches */ LL_TIM_OC_SetCompareCH1( TIMx, ticks ); LL_TIM_OC_SetCompareCH2( TIMx, ticks ); LL_TIM_OC_SetCompareCH3( TIMx, ticks ); /* Wait until next update */ while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == RESET ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { /* Enable signals activation */ LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } return; } /* * @brief Enables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_1_SwitchOnPWM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = false; /* Set all duty to 50% */ LL_TIM_OC_SetCompareCH1(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH2(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH3(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH4(TIMx, (uint32_t)(pHandle->Half_PWMPeriod - 5u)); /* wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE; LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { if ( LL_TIM_CC_IsEnabledChannel(TIMx, TIMxCCER_MASK_CH123) != 0u ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Enable Update IRQ */ LL_TIM_EnableIT_UPDATE( TIMx ); return; } /* * @brief Disables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_1_SwitchOffPWM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* Disable UPDATE ISR */ LL_TIM_DisableIT_UPDATE( TIMx ); pHandle->_Super.TurnOnLowSidesAction = false; /* Main PWM Output Disable */ LL_TIM_DisableAllOutputs(TIMx); if ( pHandle->_Super.BrakeActionLock == true ) { } else { if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* wait for a new PWM period to flush last HF task */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); return; } /* * @brief Writes into peripheral registers the new duty cycles and sampling point. * * @param pHdl: Handler of the current instance of the PWM component. * @param hCCR4Reg: New capture/compare register value, written in timer clock counts. * @retval Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ __weak uint16_t R3_1_WriteTIMRegisters( PWMC_Handle_t * pHdl, uint16_t hCCR4Reg ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint16_t hAux; LL_TIM_OC_SetCompareCH1 (TIMx,pHandle->_Super.CntPhA); LL_TIM_OC_SetCompareCH2 (TIMx,pHandle->_Super.CntPhB); LL_TIM_OC_SetCompareCH3 (TIMx,pHandle->_Super.CntPhC); LL_TIM_OC_SetCompareCH4 (TIMx, hCCR4Reg); /* Limit for update event */ /* Check the TIMx TRGO source. If it is set to OC4REF, an update event has occurred and thus the FOC rate is too high */ if (((TIMx->CR2) & TIM_CR2_MMS_Msk) != LL_TIM_TRGO_RESET ) { hAux = MC_DURATION; } else { hAux = MC_NO_ERROR; } if ( pHandle->_Super.SWerror == 1u ) { hAux = MC_DURATION; pHandle->_Super.SWerror = 0u; } return hAux; } /* * @brief Configures the ADC for the current sampling during calibration. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ __weak uint16_t R3_1_SetADCSampPointCalibration( PWMC_Handle_t * pHdl) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* Set rising edge trigger (default) */ pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_RISING; pHandle->_Super.Sector = pHandle->CalibSector; return R3_1_WriteTIMRegisters( &pHandle->_Super, ( uint16_t )( pHandle->Half_PWMPeriod ) - 1u ); } /* * @brief Configures the ADC for the current sampling related to sector X (X = [1..6] ). * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ __weak uint16_t R3_1_SetADCSampPointSectX( PWMC_Handle_t * pHdl) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif uint16_t hCntSmp; uint16_t hDeltaDuty; register uint16_t lowDuty = pHdl->lowDuty; register uint16_t midDuty = pHdl->midDuty; /* Check if sampling AB in the middle of PWM is possible */ if ( ( uint16_t )( pHandle->Half_PWMPeriod - lowDuty ) > pHandle->pParams_str->hTafter ) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled which corresponds * to sector 5 */ pHandle->_Super.Sector = SECTOR_5; /* set sampling point trigger in the middle of PWM period */ hCntSmp = ( uint32_t )( pHandle->Half_PWMPeriod ) - 1u; } else { /* ADC Injected sequence configuration. The stator phase with minimum value of complementary duty cycle is set as first. In every sector there is always one phase with maximum complementary duty, one with minimum complementary duty and one with variable complementary duty. In this case, phases with variable complementary duty and with maximum duty are converted and the first will be always the phase with variable complementary duty cycle */ /* Crossing Point Searching */ hDeltaDuty = ( uint16_t )( lowDuty - midDuty ); /* Definition of crossing point */ if ( hDeltaDuty > ( uint16_t )( pHandle->Half_PWMPeriod - lowDuty ) * 2u ) { /* hTbefore = 2*Ts + Tc, where Ts = Sampling time of ADC, Tc = Conversion Time of ADC */ hCntSmp = lowDuty - pHandle->pParams_str->hTbefore; } else { /* hTafter = DT + max(Trise, Tnoise) */ hCntSmp = lowDuty + pHandle->pParams_str->hTafter; if ( hCntSmp >= pHandle->Half_PWMPeriod ) { /* It must be changed the trigger direction from positive to negative to sample after middle of PWM*/ pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_FALLING; hCntSmp = ( 2u * pHandle->Half_PWMPeriod ) - hCntSmp - 1u; } } } return R3_1_WriteTIMRegisters( &pHandle->_Super, hCntSmp ); } /* * @brief Configures the ADC for the current sampling related to sector X (X = [1..6] ) in case of overmodulation. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ uint16_t R3_1_SetADCSampPointSectX_OVM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ uint16_t SamplingPoint; uint16_t DeltaDuty; pHandle->_Super.useEstCurrent = false; DeltaDuty = ( uint16_t )( pHdl->lowDuty - pHdl->midDuty ); /* case 1 (cf user manual) */ if (( uint16_t )( pHandle->Half_PWMPeriod - pHdl->lowDuty ) > pHandle->pParams_str->hTafter) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled which corresponds * to sector 4 or 5 */ pHandle->_Super.Sector = SECTOR_5; /* set sampling point trigger in the middle of PWM period */ SamplingPoint = pHandle->Half_PWMPeriod - (uint16_t) 1; } else /* case 2 (cf user manual) */ { if (DeltaDuty >= pHandle->pParams_str->Tcase2) { SamplingPoint = pHdl->lowDuty - pHandle->pParams_str->hTbefore; } else { /* case 3 (cf user manual) */ if ((pHandle->Half_PWMPeriod - pHdl->lowDuty) > pHandle->pParams_str->Tcase3) { /* ADC trigger edge must be changed from positive to negative */ pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_FALLING; SamplingPoint = pHdl->lowDuty + pHandle->pParams_str->Tsampling; } else { SamplingPoint = pHandle->Half_PWMPeriod-1; pHandle->_Super.useEstCurrent = true; } } } return R3_1_WriteTIMRegisters( &pHandle->_Super, SamplingPoint ); } /* * @brief Contains the TIMx Update event interrupt. * * @param pHandle: Handler of the current instance of the PWM component. */ void * R3_1_TIMx_UP_IRQHandler( PWMC_R3_1_Handle_t * pHandle ) { TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; /* Change channels keeping equal to 1 element the sequencer length */ ADCx->JSQR = pHandle->pParams_str->ADCConfig[pHandle->_Super.Sector]|pHandle->ADCTriggerEdge; LL_ADC_INJ_StartConversion(ADCx); /* enable ADC trigger source */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_OC4REF); /* reset default edge detection trigger */ pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_RISING; return &( pHandle->_Super.Motor ); } /* * @brief Sets the PWM mode for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_1_RLDetectionModeEnable( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; if ( pHandle->_Super.RLDetectionMode == false ) { /* Channel1 configuration */ LL_TIM_OC_SetMode( TIMx, LL_TIM_CHANNEL_CH1, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH1N ); LL_TIM_OC_SetCompareCH1( TIMx, 0u ); /* Channel2 configuration */ if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_OC_SetMode( TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_ACTIVE ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_OC_SetMode( TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_INACTIVE ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else { } /* Channel3 configuration */ LL_TIM_OC_SetMode( TIMx, LL_TIM_CHANNEL_CH3, LL_TIM_OCMODE_PWM2 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3N ); } pHandle->_Super.pFctGetPhaseCurrents = &R3_1_RLGetPhaseCurrents; pHandle->_Super.pFctTurnOnLowSides = &R3_1_RLTurnOnLowSides; pHandle->_Super.pFctSwitchOnPwm = &R3_1_RLSwitchOnPWM; pHandle->_Super.pFctSwitchOffPwm = &R3_1_SwitchOffPWM; pHandle->_Super.RLDetectionMode = true; } /* * @brief Disables the PWM mode for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_1_RLDetectionModeDisable( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; if ( pHandle->_Super.RLDetectionMode == true ) { /* Repetition Counter of TIM1 User value reactivation BEGIN*/ /* The folowing while cycles ensure the identification of the positive counting mode of TIM1 * for correct reactivation of Repetition Counter value of TIM1.*/ /* Wait the change of Counter Direction of TIM1 from Up-Direction to Down-Direction*/ while ( ( TIMx->CR1 & DIR_MASK ) == 0u ) { } /* Wait the change of Counter Direction of TIM1 from Down-Direction to Up-Direction.*/ while ( ( TIMx->CR1 & DIR_MASK ) == DIR_MASK ) { } /* Channel1 configuration */ LL_TIM_OC_SetMode( TIMx, LL_TIM_CHANNEL_CH1, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1 ); if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH1N ); } else { } LL_TIM_OC_SetCompareCH1( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) >> 1 ); /* Channel2 configuration */ LL_TIM_OC_SetMode( TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2 ); if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else { } LL_TIM_OC_SetCompareCH2( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) >> 1 ); /* Channel3 configuration */ LL_TIM_OC_SetMode( TIMx, LL_TIM_CHANNEL_CH3, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH3 ); if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH3N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3N ); } else { } LL_TIM_OC_SetCompareCH3( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) >> 1 ); pHandle->_Super.pFctGetPhaseCurrents = &R3_1_GetPhaseCurrents; pHandle->_Super.pFctTurnOnLowSides = &R3_1_TurnOnLowSides; pHandle->_Super.pFctSwitchOnPwm = &R3_1_SwitchOnPWM; pHandle->_Super.pFctSwitchOffPwm = &R3_1_SwitchOffPWM; pHandle->_Super.RLDetectionMode = false; } } /* * @brief Sets the PWM dutycycle for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. * @param hDuty: Duty cycle to apply, written in uint16_t. * @retval Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ uint16_t R3_1_RLDetectionModeSetDuty( PWMC_Handle_t * pHdl, uint16_t hDuty ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint32_t val; uint16_t hAux; val = ( ( uint32_t )( pHandle->Half_PWMPeriod ) * ( uint32_t )( hDuty ) ) >> 16; pHandle->_Super.CntPhA = ( uint16_t )( val ); /* set sector in order to sample phase B */ pHandle->_Super.Sector = SECTOR_4; /* TIM1 Channel 1 Duty Cycle configuration. * In RL Detection mode only the Up-side device of Phase A are controlled*/ LL_TIM_OC_SetCompareCH1(TIMx, ( uint32_t )pHandle->_Super.CntPhA); /* Limit for update event */ /* Check the status flag. If an update event has occurred before to set new values of regs the FOC rate is too high */ if (((TIMx->CR2) & TIM_CR2_MMS_Msk) != LL_TIM_TRGO_RESET ) { hAux = MC_DURATION; } else { hAux = MC_NO_ERROR; } if ( pHandle->_Super.SWerror == 1u ) { hAux = MC_DURATION; pHandle->_Super.SWerror = 0u; } return hAux; } /* * @brief Computes and stores into @p pHandle latest converted motor phase currents * during RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ void R3_1_RLGetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; int32_t wAux; /* disable ADC trigger source */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); wAux = (int32_t)( pHandle->PhaseBOffset ) - (int32_t)ADCx->JDR2; /* Check saturation */ if ( wAux > -INT16_MAX ) { if ( wAux < INT16_MAX ) { } else { wAux = INT16_MAX; } } else { wAux = -INT16_MAX; } /* First value read of Phase B*/ pStator_Currents->a = ( int16_t )( wAux ); pStator_Currents->b = ( int16_t )( wAux ); } /* * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors * of driving section. It has to be called at each motor start-up when * using high voltage drivers. * This function is specific for RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. * @param ticks: Duty cycle of the boot capacitors charge, specific to motor. */ void R3_1_RLTurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /*Turn on the phase A low side switch */ LL_TIM_OC_SetCompareCH1(TIMx, 0u); /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Wait until next update */ while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs(TIMx); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } return; } /* * @brief Enables PWM generation on the proper Timer peripheral. * * This function is specific for RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_1_RLSwitchOnPWM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; pHandle->_Super.TurnOnLowSidesAction = false; /* The following while cycles ensure the identification of the nergative counting mode of TIM1 * for correct modification of Repetition Counter value of TIM1.*/ /* Wait the change of Counter Direction of TIM1 from Down-Direction to Up-Direction*/ while ( ( TIMx->CR1 & DIR_MASK ) == DIR_MASK ) { } /* Wait the change of Counter Direction of TIM1 from Up-Direction to Down-Direction*/ while ( ( TIMx->CR1 & DIR_MASK ) == 0u ) { } /* Set channel 1 Compare/Capture register to 1 */ LL_TIM_OC_SetCompareCH1(TIMx, 1u); /* Set channel 4 Compare/Capture register to trig ADC in the middle of the PWM period */ LL_TIM_OC_SetCompareCH4(TIMx,(( uint32_t )( pHandle->Half_PWMPeriod ) - 5u)); LL_TIM_ClearFlag_UPDATE( TIMx ); /* Clear flag to wait next update */ while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE; LL_TIM_EnableAllOutputs(TIMx); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { if ( ( TIMx->CCER & TIMxCCER_MASK_CH123 ) != 0u ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* set the sector that correspond to Phase A and B sampling * B will be sampled by ADCx_1 */ pHdl->Sector = SECTOR_4; LL_ADC_INJ_StartConversion( ADCx ); /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* enable TIMx update interrupt*/ LL_TIM_EnableIT_UPDATE( TIMx ); return; } /* * @brief Turns on low sides switches and start ADC triggering. * * This function is specific for MP phase. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_1_RLTurnOnLowSidesAndStart( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); LL_TIM_OC_SetCompareCH1( TIMx, 0x0u ); LL_TIM_OC_SetCompareCH2( TIMx, 0x0u ); LL_TIM_OC_SetCompareCH3( TIMx, 0x0u ); LL_TIM_OC_SetCompareCH4( TIMx, ( pHandle->Half_PWMPeriod - 5u)); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE ; LL_TIM_EnableAllOutputs ( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } pHdl->Sector = SECTOR_4; /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Enable Update IRQ */ LL_TIM_EnableIT_UPDATE( TIMx ); return; } /** * @} */ /** * @} */ /** * @} */ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
51,532
C
29.747613
143
0.614705
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/L4xx/Src/r3_2_l4xx_pwm_curr_fdbk.c
/** ****************************************************************************** * @file r3_2_l4xx_pwm_curr_fdbk.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement current sensor * class to be stantiated when the three shunts current sensing * topology is used. * * It is specifically designed for STM32L4XX microcontrollers and * implements the successive sampling of two motor current using two ADCs. * + MCU peripheral and handle initialization fucntion * + three shunt current sensing * + space vector modulation function * + ADC sampling function * ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup R3_2_L4XX_pwm_curr_fdbk */ /* Includes ------------------------------------------------------------------*/ #include "r3_2_l4xx_pwm_curr_fdbk.h" #include "pwm_common.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup R3_2_pwm_curr_fdbk * @{ */ /* Private defines -----------------------------------------------------------*/ #define TIMxCCER_MASK_CH123 ((uint16_t) (LL_TIM_CHANNEL_CH1|LL_TIM_CHANNEL_CH1N|\ LL_TIM_CHANNEL_CH2|LL_TIM_CHANNEL_CH2N|\ LL_TIM_CHANNEL_CH3|LL_TIM_CHANNEL_CH3N)) /* Private function prototypes -----------------------------------------------*/ uint16_t R3_2_WriteTIMRegisters( PWMC_Handle_t * pHdl, uint16_t hCCR4Reg ); void R3_2_HFCurrentsCalibrationAB( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ); void R3_2_HFCurrentsCalibrationC( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ); static void R3_2_RLGetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ); static void R3_2_RLTurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ); static void R3_2_RLSwitchOnPWM( PWMC_Handle_t * pHdl ); /* Local redefinition of both LL_TIM_OC_EnablePreload & LL_TIM_OC_DisablePreload */ __STATIC_INLINE void __LL_TIM_OC_EnablePreload(TIM_TypeDef *TIMx, uint32_t Channel) { register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); register volatile uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); SET_BIT(*pReg, (TIM_CCMR1_OC1PE << SHIFT_TAB_OCxx[iChannel])); } __STATIC_INLINE void __LL_TIM_OC_DisablePreload(TIM_TypeDef *TIMx, uint32_t Channel) { register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); register volatile uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); CLEAR_BIT(*pReg, (TIM_CCMR1_OC1PE << SHIFT_TAB_OCxx[iChannel])); } /* * @brief Initializes TIMx, ADC, GPIO, DMA1 and NVIC for current reading * in three shunt topology using two ADCs. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void R3_2_Init( PWMC_R3_2_Handle_t * pHandle ) { TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef *ADCx_1 = pHandle->pParams_str->ADCDataReg1[0]; ADC_TypeDef *ADCx_2 = pHandle->pParams_str->ADCDataReg2[0]; if ( ( uint32_t )pHandle == ( uint32_t )&pHandle->_Super ) { LL_ADC_DisableIT_EOC( ADCx_1 ); LL_ADC_ClearFlag_EOC( ADCx_1 ); LL_ADC_DisableIT_JEOC( ADCx_1 ); LL_ADC_ClearFlag_JEOC( ADCx_1 ); LL_ADC_DisableIT_EOC( ADCx_2 ); LL_ADC_ClearFlag_EOC( ADCx_2 ); LL_ADC_DisableIT_JEOC( ADCx_2 ); LL_ADC_ClearFlag_JEOC( ADCx_2 ); /* disable main TIM counter to ensure * a synchronous start by TIM2 trigger */ LL_TIM_DisableCounter( TIMx ); LL_TIM_ClearFlag_BRK( TIMx ); LL_TIM_ClearFlag_BRK2( TIMx ); LL_TIM_EnableIT_BRK( TIMx ); /* Enable PWM channel */ LL_TIM_CC_EnableChannel( TIMx, TIMxCCER_MASK_CH123 ); if ( pHandle->pParams_str->TIMx == TIM1 ) { /* TIM1 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph( LL_DBGMCU_APB2_GRP1_TIM1_STOP ); pHandle->ADC_ExternalTriggerInjected = LL_ADC_INJ_TRIG_EXT_TIM1_TRGO; } else { /* TIM8 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph( LL_DBGMCU_APB2_GRP1_TIM8_STOP ); pHandle->ADC_ExternalTriggerInjected = LL_ADC_INJ_TRIG_EXT_TIM8_TRGO; } LL_ADC_StartCalibration( ADCx_1, LL_ADC_SINGLE_ENDED ); LL_ADC_StartCalibration( ADCx_2, LL_ADC_SINGLE_ENDED ); while ( LL_ADC_IsCalibrationOnGoing( ADCx_1 ) && LL_ADC_IsCalibrationOnGoing( ADCx_2) ) { } LL_ADC_Enable( ADCx_1 ); LL_ADC_Enable( ADCx_2 ); /* Queue Of Context Mode for injected channels Enabling */ LL_ADC_INJ_SetQueueMode(ADCx_1, LL_ADC_INJ_QUEUE_2CONTEXTS_END_EMPTY); LL_ADC_INJ_SetQueueMode(ADCx_2, LL_ADC_INJ_QUEUE_2CONTEXTS_END_EMPTY); /* Flush JSQR settings done by CubeMX */ LL_ADC_INJ_StartConversion(ADCx_1); LL_ADC_INJ_StartConversion(ADCx_2); LL_ADC_INJ_StopConversion(ADCx_1); LL_ADC_INJ_StopConversion(ADCx_2); /* Disable TIMx ADC trigger */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); /* Enable ADCx_1 injected end of sequence interrupt */ LL_ADC_ClearFlag_JEOS( ADCx_1 ); LL_ADC_EnableIT_JEOS( ADCx_1 ); pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_RISING; pHandle->_Super.DTTest = 0u; } } /* * @brief Stores in @p pHdl handler the calibrated @p offsets. * */ __weak void R3_2_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 pHandle->PhaseAOffset = offsets->phaseAOffset; pHandle->PhaseBOffset = offsets->phaseBOffset; pHandle->PhaseCOffset = offsets->phaseCOffset; pHdl->offsetCalibStatus = true; } /* * @brief Reads the calibrated @p offsets stored in @p pHdl. * */ __weak void R3_2_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 offsets->phaseAOffset = pHandle->PhaseAOffset; offsets->phaseBOffset = pHandle->PhaseBOffset; offsets->phaseCOffset = pHandle->PhaseCOffset; } /* * @brief Stores into the @p pHdl handler the voltage present on Ia and * Ib current feedback analog channels when no current is flowing into the * motor. * */ __weak void R3_2_CurrentReadingCalibration( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; volatile PWMC_GetPhaseCurr_Cb_t GetPhaseCurrCbSave; volatile PWMC_SetSampPointSectX_Cb_t SetSampPointSectXCbSave; if (false == pHandle->_Super.offsetCalibStatus) { /* Save callback routines */ GetPhaseCurrCbSave = pHandle->_Super.pFctGetPhaseCurrents; SetSampPointSectXCbSave = pHandle->_Super.pFctSetADCSampPointSectX; pHandle->PhaseAOffset = 0u; pHandle->PhaseBOffset = 0u; pHandle->PhaseCOffset = 0u; pHandle->PolarizationCounter = 0u; LL_TIM_CC_DisableChannel(TIMx, TIMxCCER_MASK_CH123); /* Offset calibration for A & B phases */ /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R3_2_HFCurrentsCalibrationAB; pHandle->_Super.pFctSetADCSampPointSectX = &R3_2_SetADCSampPointCalibration; pHandle->CalibSector = SECTOR_4; /* Required to force first polarization conversion on SECTOR_4*/ pHandle->_Super.Sector = SECTOR_4; R3_2_SwitchOnPWM( &pHandle->_Super ); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd( TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter ); R3_2_SwitchOffPWM( &pHandle->_Super ); /* Offset calibration for C phase */ /* Reset PolarizationCounter */ pHandle->PolarizationCounter = 0u; /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R3_2_HFCurrentsCalibrationC; pHandle->CalibSector = SECTOR_1; /* Required to force first polarization conversion on SECTOR_1*/ pHandle->_Super.Sector = SECTOR_1; R3_2_SwitchOnPWM( &pHandle->_Super ); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd( TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter ); R3_2_SwitchOffPWM( &pHandle->_Super ); pHandle->PhaseAOffset >>= 4; pHandle->PhaseBOffset >>= 4; pHandle->PhaseCOffset >>= 4; if (0U == pHandle->_Super.SWerror) { pHandle->_Super.offsetCalibStatus = true; } else { /* nothing to do */ } /* Change back function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = GetPhaseCurrCbSave; pHandle->_Super.pFctSetADCSampPointSectX = SetSampPointSectXCbSave; } /* It over write TIMx CCRy wrongly written by FOC during calibration so as to force 50% duty cycle on the three inverer legs */ /* Disable TIMx preload */ __LL_TIM_OC_DisablePreload( TIMx, LL_TIM_CHANNEL_CH1 ); __LL_TIM_OC_DisablePreload( TIMx, LL_TIM_CHANNEL_CH2 ); __LL_TIM_OC_DisablePreload( TIMx, LL_TIM_CHANNEL_CH3 ); LL_TIM_OC_SetCompareCH1( TIMx, pHandle->Half_PWMPeriod ); LL_TIM_OC_SetCompareCH2( TIMx, pHandle->Half_PWMPeriod ); LL_TIM_OC_SetCompareCH3( TIMx, pHandle->Half_PWMPeriod ); __LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH1 ); __LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH2 ); __LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH3 ); /* It re-enable drive of TIMx CHy and CHyN by TIMx CHyRef*/ LL_TIM_CC_EnableChannel(TIMx, TIMxCCER_MASK_CH123); /* sector and phase sequence for the switch on phase */ pHandle->_Super.Sector = SECTOR_4; pHandle->_Super.BrakeActionLock = false; } /* * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p pStator_Currents ab_t format. * */ __weak void R3_2_GetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; int32_t wAux; uint16_t hReg1; uint16_t hReg2; uint8_t bSector; /* disable ADC trigger source */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); bSector = pHandle->_Super.Sector; hReg1 = pHandle->pParams_str->ADCDataReg1[bSector]->JDR1; hReg2 = pHandle->pParams_str->ADCDataReg2[bSector]->JDR1; switch ( bSector ) { case SECTOR_4: case SECTOR_5: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ wAux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( hReg1 ); /* Saturation of Ia */ if ( wAux < -INT16_MAX ) { pStator_Currents->a = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->a = INT16_MAX; } else { pStator_Currents->a = ( int16_t )wAux; } /* Ib = PhaseBOffset - ADC converted value) */ wAux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( hReg2 ); /* Saturation of Ib */ if ( wAux < -INT16_MAX ) { pStator_Currents->b = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->b = INT16_MAX; } else { pStator_Currents->b = ( int16_t )wAux; } break; case SECTOR_6: case SECTOR_1: /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ wAux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( hReg1 ); /* Saturation of Ib */ if ( wAux < -INT16_MAX ) { pStator_Currents->b = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->b = INT16_MAX; } else { pStator_Currents->b = ( int16_t )wAux; } /* Ic = PhaseCOffset - ADC converted value) */ /* Ia = -Ic -Ib */ wAux = ( int32_t )( pHandle->PhaseCOffset ) - ( int32_t )( hReg2 ); wAux = -wAux - ( int32_t )pStator_Currents->b; /* Saturation of Ia */ if ( wAux > INT16_MAX ) { pStator_Currents->a = INT16_MAX; } else if ( wAux < -INT16_MAX ) { pStator_Currents->a = -INT16_MAX; } else { pStator_Currents->a = ( int16_t )wAux; } break; case SECTOR_2: case SECTOR_3: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ wAux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( hReg1 ); /* Saturation of Ia */ if ( wAux < -INT16_MAX ) { pStator_Currents->a = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->a = INT16_MAX; } else { pStator_Currents->a = ( int16_t )wAux; } /* Ic = PhaseCOffset - ADC converted value) */ /* Ib = -Ic -Ia */ wAux = ( int32_t )( pHandle->PhaseCOffset ) - ( int32_t )( hReg2 ); wAux = -wAux - ( int32_t )pStator_Currents->a; /* Saturation of Ib */ if ( wAux > INT16_MAX ) { pStator_Currents->b = INT16_MAX; } else if ( wAux < -INT16_MAX ) { pStator_Currents->b = -INT16_MAX; } else { pStator_Currents->b = ( int16_t )wAux; } break; default: break; } pHandle->_Super.Ia = pStator_Currents->a; pHandle->_Super.Ib = pStator_Currents->b; pHandle->_Super.Ic = -pStator_Currents->a - pStator_Currents->b; } /* * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p Iab ab_t format. Specific to overmodulation. * */ __weak void R3_2_GetPhaseCurrents_OVM( PWMC_Handle_t * pHdl, ab_t * Iab ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint8_t Sector; int32_t Aux; uint32_t ADCDataReg1; uint32_t ADCDataReg2; /* disable ADC trigger source */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); Sector = ( uint8_t )pHandle->_Super.Sector; ADCDataReg1 = pHandle->pParams_str->ADCDataReg1[Sector]->JDR1; ADCDataReg2 = pHandle->pParams_str->ADCDataReg2[Sector]->JDR1; switch ( Sector ) { case SECTOR_4: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { // Ib not available, use estimated Ib Aux = ( int32_t )( pHandle->_Super.IbEst ); } else { /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg2 ); } /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_5: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { // Ia not available, use estimated Ia Aux = ( int32_t )( pHandle->_Super.IaEst ); } else { Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg2 ); /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_6: /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IcEst ; /* -Ic */ Aux -= ( int32_t )Iab->b; } else { /* Ia = -Ic -Ib */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->b; /* Ia */ } /* Saturation of Ia */ if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else { Iab->a = ( int16_t )Aux; } break; case SECTOR_1: /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IbEst; } else { Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } /* Ia = -Ic -Ib */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->b; /* Ia */ /* Saturation of Ia */ if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else { Iab->a = ( int16_t )Aux; } break; case SECTOR_2: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IaEst; } else { Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } /* Ib = -Ic -Ia */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ /* Saturation of Ib */ if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_3: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { /* Ib = -Ic -Ia */ Aux = ( int32_t ) pHandle->_Super.IcEst; /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ } else { /* Ib = -Ic -Ia */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ } /* Saturation of Ib */ if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; default: break; } pHandle->_Super.Ia = Iab->a; pHandle->_Super.Ib = Iab->b; pHandle->_Super.Ic = -Iab->a - Iab->b; } /* * @brief Implementation of PWMC_GetPhaseCurrents to be performed during calibration. * * It sums up injected conversion data into PhaseAOffset and wPhaseBOffset * to compute the offset introduced in the current feedback network. It is required to * properly configure ADC inputs before in order to enable offset computation. * * @param pHdl: Pointer on the target component instance. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ __weak void R3_2_HFCurrentsCalibrationAB( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* disable ADC trigger source */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); if ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { pHandle->PhaseAOffset += pHandle->pParams_str->ADCDataReg1[pHandle->CalibSector]->JDR1; pHandle->PhaseBOffset += pHandle->pParams_str->ADCDataReg2[pHandle->CalibSector]->JDR1; pHandle->PolarizationCounter++; } /* during offset calibration no current is flowing in the phases */ pStator_Currents->a = 0; pStator_Currents->b = 0; } /* * @brief Implementation of PWMC_GetPhaseCurrents to be performed during calibration. * * It sums up injected conversion data into PhaseCOffset to compute the offset * introduced in the current feedback network. It is required to properly configure * ADC inputs before in order to enable offset computation. * * @param pHdl: Pointer on the target component instance. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ __weak void R3_2_HFCurrentsCalibrationC( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* disable ADC trigger source */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); if ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { pHandle->PhaseCOffset += pHandle->pParams_str->ADCDataReg2[pHandle->CalibSector]->JDR1; pHandle->PolarizationCounter++; } /* during offset calibration no current is flowing in the phases */ pStator_Currents->a = 0; pStator_Currents->b = 0; } /* * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors of driving section. It has to be * called each motor start-up when using high voltage drivers. * * @param pHdl: Handler of the current instance of the PWM component * @param ticks: Timer ticks value to be applied * Min value: 0 (low sides ON) * Max value: PWM_PERIOD_CYCLES/2 (low sides OFF) */ __weak void R3_2_TurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = true; /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /*Turn on the three low side switches */ LL_TIM_OC_SetCompareCH1( TIMx, ticks ); LL_TIM_OC_SetCompareCH2( TIMx, ticks ); LL_TIM_OC_SetCompareCH3( TIMx, ticks ); /* Wait until next update */ while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == RESET ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { /* Enable signals activation */ LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } return; } /* * @brief Enables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_2_SwitchOnPWM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = false; /* Set all duty to 50% */ LL_TIM_OC_SetCompareCH1(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH2(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH3(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH4(TIMx, (uint32_t)(pHandle->Half_PWMPeriod - 5u)); /* wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE; LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { if ( LL_TIM_CC_IsEnabledChannel(TIMx, TIMxCCER_MASK_CH123) != 0u ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Enable Update IRQ */ LL_TIM_EnableIT_UPDATE( TIMx ); return; } /* * @brief Disables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_2_SwitchOffPWM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* Disable UPDATE ISR */ LL_TIM_DisableIT_UPDATE( TIMx ); pHandle->_Super.TurnOnLowSidesAction = false; LL_TIM_DisableAllOutputs(TIMx); /* Main PWM Output Disable */ if ( pHandle->_Super.BrakeActionLock == true ) { } else { if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* wait to flush last HF task */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); return; } /* * @brief Writes into peripheral registers the new duty cycles and sampling point. * * @param pHdl: Handler of the current instance of the PWM component. * @param hCCR4Reg: New capture/compare register value, written in timer clock counts. * @retval Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ __weak uint16_t R3_2_WriteTIMRegisters( PWMC_Handle_t * pHdl, uint16_t hCCR4Reg ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint16_t hAux; LL_TIM_OC_SetCompareCH1( TIMx, pHandle->_Super.CntPhA ); LL_TIM_OC_SetCompareCH2( TIMx, pHandle->_Super.CntPhB ); LL_TIM_OC_SetCompareCH3( TIMx, pHandle->_Super.CntPhC ); LL_TIM_OC_SetCompareCH4( TIMx, hCCR4Reg); /* Limit for update event */ /* Check the TIMx TRGO source. If it is set to OC4REF, an update event has occurred and thus the FOC rate is too high */ if (((TIMx->CR2) & TIM_CR2_MMS_Msk) != LL_TIM_TRGO_RESET ) { hAux = MC_DURATION; } else { hAux = MC_NO_ERROR; } if ( pHandle->_Super.SWerror == 1u ) { hAux = MC_DURATION; pHandle->_Super.SWerror = 0u; } return hAux; } /* * @brief Configures the ADC for the current sampling during calibration. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ __weak uint16_t R3_2_SetADCSampPointCalibration( PWMC_Handle_t * pHdl) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* Set rising edge trigger (default) */ pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_RISING; pHandle->_Super.Sector = pHandle->CalibSector; return R3_2_WriteTIMRegisters( &pHandle->_Super, ( uint16_t )( pHandle->Half_PWMPeriod ) - 1u ); } /* * @brief Configures the ADC for the current sampling related to sector X (X = [1..6] ). * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ __weak uint16_t R3_2_SetADCSampPointSectX( PWMC_Handle_t * pHdl) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif uint16_t hCntSmp; uint16_t hDeltaDuty; register uint16_t lowDuty = pHdl->lowDuty; register uint16_t midDuty = pHdl->midDuty; /* Check if sampling AB in the middle of PWM is possible */ if ( ( uint16_t )( pHandle->Half_PWMPeriod - lowDuty ) > pHandle->pParams_str->hTafter ) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled which corresponds * to sector 4 */ pHandle->_Super.Sector = SECTOR_4; /* set sampling point trigger in the middle of PWM period */ hCntSmp = ( uint32_t )( pHandle->Half_PWMPeriod ) - 1u; } else { /* ADC Injected sequence configuration. The stator phase with minimum value of complementary duty cycle is set as first. In every sector there is always one phase with maximum complementary duty, one with minimum complementary duty and one with variable complementary duty. In this case, phases with variable complementary duty and with maximum duty are converted and the first will be always the phase with variable complementary duty cycle */ /* Crossing Point Searching */ hDeltaDuty = ( uint16_t )( lowDuty - midDuty ); /* Definition of crossing point */ if ( hDeltaDuty > ( uint16_t )( pHandle->Half_PWMPeriod - lowDuty ) * 2u ) { /* hTbefore = 2*Ts + Tc, where Ts = Sampling time of ADC, Tc = Conversion Time of ADC */ hCntSmp = lowDuty - pHandle->pParams_str->hTbefore; } else { /* hTafter = DT + max(Trise, Tnoise) */ hCntSmp = lowDuty + pHandle->pParams_str->hTafter; if ( hCntSmp >= pHandle->Half_PWMPeriod ) { /* It must be changed the trigger direction from positive to negative to sample after middle of PWM*/ pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_FALLING; hCntSmp = ( 2u * pHandle->Half_PWMPeriod ) - hCntSmp - 1u; } } } return R3_2_WriteTIMRegisters( &pHandle->_Super, hCntSmp ); } /* * @brief Configures the ADC for the current sampling related to sector X (X = [1..6] ) in case of overmodulation. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ uint16_t R3_2_SetADCSampPointSectX_OVM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ uint16_t SamplingPoint; uint16_t DeltaDuty; pHandle->_Super.useEstCurrent = false; DeltaDuty = ( uint16_t )( pHdl->lowDuty - pHdl->midDuty ); /* case 1 (cf user manual) */ if (( uint16_t )( pHandle->Half_PWMPeriod - pHdl->lowDuty ) > pHandle->pParams_str->hTafter) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled which corresponds * to sector 4 or 5 */ pHandle->_Super.Sector = SECTOR_5; /* set sampling point trigger in the middle of PWM period */ SamplingPoint = pHandle->Half_PWMPeriod - (uint16_t) 1; } else /* case 2 (cf user manual) */ { if (DeltaDuty >= pHandle->pParams_str->Tcase2) { SamplingPoint = pHdl->lowDuty - pHandle->pParams_str->hTbefore; } else { /* case 3 (cf user manual) */ if ((pHandle->Half_PWMPeriod - pHdl->lowDuty) > pHandle->pParams_str->Tcase3) { /* ADC trigger edge must be changed from positive to negative */ pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_FALLING; SamplingPoint = pHdl->lowDuty + pHandle->pParams_str->Tsampling; } else { SamplingPoint = pHandle->Half_PWMPeriod-1; pHandle->_Super.useEstCurrent = true; } } } return R3_2_WriteTIMRegisters( &pHandle->_Super, SamplingPoint ); } /* * @brief Contains the TIMx Update event interrupt. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void * R3_2_TIMx_UP_IRQHandler( PWMC_R3_2_Handle_t * pHandle ) { TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef *ADCx_1 = pHandle->pParams_str->ADCDataReg1[0]; ADC_TypeDef *ADCx_2 = pHandle->pParams_str->ADCDataReg2[0]; /* Change channels keeping equal to 1 element the sequencer length */ pHandle->pParams_str->ADCDataReg1[pHandle->_Super.Sector]->JSQR = pHandle->pParams_str->ADCConfig1[pHandle->_Super.Sector]|pHandle->ADCTriggerEdge; pHandle->pParams_str->ADCDataReg2[pHandle->_Super.Sector]->JSQR = pHandle->pParams_str->ADCConfig2[pHandle->_Super.Sector]|pHandle->ADCTriggerEdge; LL_ADC_INJ_StartConversion(ADCx_1); LL_ADC_INJ_StartConversion(ADCx_2); /* enable ADC trigger source */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_OC4REF); /* reset default edge detection trigger */ pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_RISING; return &( pHandle->_Super.Motor ); } /* * @brief Sets the PWM mode for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_2_RLDetectionModeEnable( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; if ( pHandle->_Super.RLDetectionMode == false ) { /* Channel1 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH1, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH1N ); LL_TIM_OC_SetCompareCH1( TIMx, 0u ); /* Channel2 configuration */ if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_ACTIVE ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_INACTIVE ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else { } /* Channel3 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH3, LL_TIM_OCMODE_PWM2 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3N ); } pHandle->_Super.pFctGetPhaseCurrents = &R3_2_RLGetPhaseCurrents; pHandle->_Super.pFctTurnOnLowSides = &R3_2_RLTurnOnLowSides; pHandle->_Super.pFctSwitchOnPwm = &R3_2_RLSwitchOnPWM; pHandle->_Super.pFctSwitchOffPwm = &R3_2_SwitchOffPWM; pHandle->_Super.RLDetectionMode = true; } /* * @brief Disables the PWM mode for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_2_RLDetectionModeDisable( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; if ( pHandle->_Super.RLDetectionMode == true ) { /* Channel1 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH1, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1 ); if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH1N ); } else { } LL_TIM_OC_SetCompareCH1( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) >> 1 ); /* Channel2 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2 ); if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else { } LL_TIM_OC_SetCompareCH2( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) >> 1 ); /* Channel3 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH3, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH3 ); if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH3N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3N ); } else { } LL_TIM_OC_SetCompareCH3( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) >> 1 ); pHandle->_Super.pFctGetPhaseCurrents = &R3_2_GetPhaseCurrents; pHandle->_Super.pFctTurnOnLowSides = &R3_2_TurnOnLowSides; pHandle->_Super.pFctSwitchOnPwm = &R3_2_SwitchOnPWM; pHandle->_Super.pFctSwitchOffPwm = &R3_2_SwitchOffPWM; pHandle->_Super.RLDetectionMode = false; } } /* * @brief Sets the PWM dutycycle for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. * @param hDuty: Duty cycle to apply, written in uint16_t. * @retval Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ uint16_t R3_2_RLDetectionModeSetDuty( PWMC_Handle_t * pHdl, uint16_t hDuty ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint32_t val; uint16_t hAux; val = ( ( uint32_t )( pHandle->Half_PWMPeriod ) * ( uint32_t )( hDuty ) ) >> 16; pHandle->_Super.CntPhA = ( uint16_t )( val ); /* TIM1 Channel 1 Duty Cycle configuration. * In RL Detection mode only the Up-side device of Phase A are controlled*/ LL_TIM_OC_SetCompareCH1(TIMx, ( uint32_t )pHandle->_Super.CntPhA); /* set the sector that correspond to Phase A and B sampling */ pHdl->Sector = SECTOR_4; /* Limit for update event */ /* Check the status flag. If an update event has occurred before to set new values of regs the FOC rate is too high */ if (((TIMx->CR2) & TIM_CR2_MMS_Msk) != LL_TIM_TRGO_RESET ) { hAux = MC_DURATION; } else { hAux = MC_NO_ERROR; } if ( pHandle->_Super.SWerror == 1u ) { hAux = MC_DURATION; pHandle->_Super.SWerror = 0u; } return hAux; } /* * @brief Computes and stores into @p pHandle latest converted motor phase currents * during RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ static void R3_2_RLGetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; int32_t wAux; /* disable ADC trigger source */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); wAux = (int32_t)( pHandle->PhaseBOffset ) - (int32_t)pHandle->pParams_str->ADCDataReg2[pHandle->_Super.Sector]->JDR1; /* Check saturation */ if ( wAux > -INT16_MAX ) { if ( wAux < INT16_MAX ) { } else { wAux = INT16_MAX; } } else { wAux = -INT16_MAX; } pStator_Currents->a = (int16_t)wAux; pStator_Currents->b = (int16_t)wAux; } /* * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors * of driving section. It has to be called at each motor start-up when * using high voltage drivers. * This function is specific for RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. * @param ticks: Duty cycle of the boot capacitors charge, specific to motor. */ static void R3_2_RLTurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /*Turn on the phase A low side switch */ LL_TIM_OC_SetCompareCH1 ( TIMx, 0u ); /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Wait until next update */ while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } return; } /* * @brief Enables PWM generation on the proper Timer peripheral. * * This function is specific for RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. */ static void R3_2_RLSwitchOnPWM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); LL_TIM_OC_SetCompareCH1( TIMx, 1u ); LL_TIM_OC_SetCompareCH4( TIMx, ( pHandle->Half_PWMPeriod ) - 5u ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE ; LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { if ( ( TIMx->CCER & TIMxCCER_MASK_CH123 ) != 0u ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* enable TIMx update interrupt*/ LL_TIM_EnableIT_UPDATE( TIMx ); return; } /* * @brief Turns on low sides switches and start ADC triggering. * * This function is specific for MP phase. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_2_RLTurnOnLowSidesAndStart( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef *ADCx_1 = pHandle->pParams_str->ADCDataReg1[0]; ADC_TypeDef *ADCx_2 = pHandle->pParams_str->ADCDataReg2[0]; /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); LL_TIM_OC_SetCompareCH1( TIMx, 0x0u ); LL_TIM_OC_SetCompareCH2( TIMx, 0x0u ); LL_TIM_OC_SetCompareCH3( TIMx, 0x0u ); LL_TIM_OC_SetCompareCH4( TIMx, ( pHandle->Half_PWMPeriod - 5u)); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE ; LL_TIM_EnableAllOutputs ( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } pHdl->Sector = SECTOR_4; LL_ADC_INJ_SetTriggerSource( ADCx_1, pHandle->ADC_ExternalTriggerInjected); LL_ADC_INJ_SetTriggerSource( ADCx_2, pHandle->ADC_ExternalTriggerInjected); LL_ADC_INJ_StartConversion( ADCx_1 ); LL_ADC_INJ_StartConversion( ADCx_2 ); LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH4); LL_TIM_EnableIT_UPDATE( TIMx ); return; } /* * @brief Sets ADC sampling points. * * This function is specific for MP phase. Specific to F4XX, F7XX, L4XX and H5XX. * * @param pHdl: Handler of the current instance of the PWM component. */ void RLSetADCSampPoint( PWMC_Handle_t * pHdl ) { /* dummy sector setting to get correct Ia value */ pHdl->Sector = SECTOR_4; return; } /** * @} */ /** * @} */ /** * @} */ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
51,350
C
30.216413
149
0.618169
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/L4xx/Src/ics_l4xx_pwm_curr_fdbk.c
/** ****************************************************************************** * @file ics_l4xx_pwm_curr_fdbk.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement the ICS * PWM current feedback component for L4xx of the Motor Control SDK. ******************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * * @ingroup ICS_L4XX_pwm_curr_fdbk */ /* Includes ------------------------------------------------------------------*/ #include "ics_l4xx_pwm_curr_fdbk.h" #include "pwm_common.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup ICS_pwm_curr_fdbk * @{ */ /* ADC registers reset values */ #define TIMxCCER_MASK_CH123 (LL_TIM_CHANNEL_CH1 | LL_TIM_CHANNEL_CH2 | LL_TIM_CHANNEL_CH3 | \ LL_TIM_CHANNEL_CH1N | LL_TIM_CHANNEL_CH2N | LL_TIM_CHANNEL_CH3N) void ICS_HFCurrentsCalibration( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ); /* * @brief Initializes TIMx, ADC, GPIO and NVIC for current reading * in ICS configuration using STM32F30X. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void ICS_Init( PWMC_ICS_Handle_t * pHandle ) { TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx_1 = pHandle->pParams_str->ADCx_1; ADC_TypeDef * ADCx_2 = pHandle->pParams_str->ADCx_2; if ( ( uint32_t )pHandle == ( uint32_t )&pHandle->_Super ) { /* disable IT and flags in case of LL driver usage * workaround for unwanted interrupt enabling done by LL driver */ LL_ADC_DisableIT_EOC( ADCx_1 ); LL_ADC_ClearFlag_EOC( ADCx_1 ); LL_ADC_DisableIT_JEOC( ADCx_1 ); LL_ADC_ClearFlag_JEOC( ADCx_1 ); LL_ADC_DisableIT_EOC( ADCx_2 ); LL_ADC_ClearFlag_EOC( ADCx_2 ); LL_ADC_DisableIT_JEOC( ADCx_2 ); LL_ADC_ClearFlag_JEOC( ADCx_2 ); /* disable main TIM counter to ensure * a synchronous start by TIM2 trigger */ LL_TIM_DisableCounter( TIMx ); /* Enables the TIMx Preload on CC1 Register */ LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH1 ); /* Enables the TIMx Preload on CC2 Register */ LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH2 ); /* Enables the TIMx Preload on CC3 Register */ LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH3 ); /* Enables the TIMx Preload on CC4 Register */ LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH4 ); /* Always enable BKIN for safety feature */ LL_TIM_ClearFlag_BRK( TIMx ); LL_TIM_ClearFlag_BRK2( TIMx ); LL_TIM_EnableIT_BRK( TIMx ); LL_TIM_SetCounter( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) - 1u ); /* Enable PWM channel */ LL_TIM_CC_EnableChannel( TIMx, TIMxCCER_MASK_CH123 ); if ( TIMx == TIM1 ) { /* TIM1 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph( LL_DBGMCU_APB2_GRP1_TIM1_STOP ); } #if defined(TIM8) else { /* TIM8 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph( LL_DBGMCU_APB2_GRP1_TIM8_STOP ); } #endif /* ADCx_1 and ADCx_2 registers configuration ---------------------------------*/ /* ADCx_1 and ADCx_2 registers reset */ LL_ADC_EnableInternalRegulator( ADCx_1 ); LL_ADC_EnableInternalRegulator( ADCx_2 ); /* Wait for Regulator Startup time, once for both */ volatile uint32_t wait_loop_index = ((LL_ADC_DELAY_INTERNAL_REGUL_STAB_US / 10UL) * (SystemCoreClock / (100000UL * 2UL))); while(wait_loop_index != 0UL) { wait_loop_index--; } LL_ADC_StartCalibration( ADCx_1, LL_ADC_SINGLE_ENDED ); while ( LL_ADC_IsCalibrationOnGoing( ADCx_1 ) ) { } LL_ADC_StartCalibration( ADCx_2, LL_ADC_SINGLE_ENDED ); while ( LL_ADC_IsCalibrationOnGoing( ADCx_2 ) ) { } /* ADCx_1 and ADCx_2 registers configuration ---------------------------------*/ /* Enable ADCx_1 and ADCx_2 */ LL_ADC_Enable( ADCx_1 ); LL_ADC_Enable( ADCx_2 ); /* reset regular conversion sequencer length set by cubeMX */ LL_ADC_REG_SetSequencerLength( ADCx_1, LL_ADC_REG_SEQ_SCAN_DISABLE ); /* ADCx_1 Injected conversions end interrupt enabling */ LL_ADC_ClearFlag_JEOC( ADCx_1 ); LL_ADC_EnableIT_JEOC( ADCx_1 ); LL_ADC_INJ_SetQueueMode( ADCx_1, LL_ADC_INJ_QUEUE_2CONTEXTS_END_EMPTY ); LL_ADC_INJ_SetQueueMode( ADCx_2, LL_ADC_INJ_QUEUE_2CONTEXTS_END_EMPTY ); LL_ADC_INJ_StartConversion( ADCx_1 ); LL_ADC_INJ_StartConversion( ADCx_2 ); /* Clear the flags */ pHandle->_Super.DTTest = 0u; } } /* * @brief Stores in @p pHdl handler the calibrated @p offsets. * */ __weak void ICS_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_ICS_Handle_t *pHandle = (PWMC_ICS_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 pHandle->PhaseAOffset = offsets->phaseAOffset; pHandle->PhaseBOffset = offsets->phaseBOffset; pHdl->offsetCalibStatus = true; } /* * @brief Reads the calibrated @p offsets stored in @p pHdl. * */ __weak void ICS_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_ICS_Handle_t *pHandle = (PWMC_ICS_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 offsets->phaseAOffset = pHandle->PhaseAOffset; offsets->phaseBOffset = pHandle->PhaseBOffset; } /* * @brief Stores into the @p pHdl handler the voltage present on Ia and * Ib current feedback analog channels when no current is flowing into the * motor. * */ __weak void ICS_CurrentReadingCalibration( PWMC_Handle_t * pHdl ) { PWMC_ICS_Handle_t * pHandle = ( PWMC_ICS_Handle_t * ) pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; if (false == pHandle->_Super.offsetCalibStatus) { pHandle->PhaseAOffset = 0u; pHandle->PhaseBOffset = 0u; pHandle->PolarizationCounter = 0u; /* Force inactive level on TIMx CHy and TIMx CHyN */ LL_TIM_CC_DisableChannel( TIMx, TIMxCCER_MASK_CH123 ); /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &ICS_HFCurrentsCalibration; ICS_SwitchOnPWM( &pHandle->_Super ); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd( TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter ); ICS_SwitchOffPWM( &pHandle->_Super ); pHandle->PhaseAOffset /= NB_CONVERSIONS; pHandle->PhaseBOffset /= NB_CONVERSIONS; if (0U == pHandle->_Super.SWerror) { pHandle->_Super.offsetCalibStatus = true; } else { /* nothing to do */ } /* Change back function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &ICS_GetPhaseCurrents; } /* It over write TIMx CCRy wrongly written by FOC during calibration so as to force 50% duty cycle on the three inverer legs */ /* Disable TIMx preload */ LL_TIM_OC_DisablePreload( TIMx, LL_TIM_CHANNEL_CH1 ); LL_TIM_OC_DisablePreload( TIMx, LL_TIM_CHANNEL_CH2 ); LL_TIM_OC_DisablePreload( TIMx, LL_TIM_CHANNEL_CH3 ); LL_TIM_OC_SetCompareCH1( TIMx, pHandle->Half_PWMPeriod ); LL_TIM_OC_SetCompareCH2( TIMx, pHandle->Half_PWMPeriod ); LL_TIM_OC_SetCompareCH3( TIMx, pHandle->Half_PWMPeriod ); LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH1 ); LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH2 ); LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH3 ); /* Set back TIMx CCER register */ LL_TIM_CC_EnableChannel( TIMx, TIMxCCER_MASK_CH123 ); pHandle->_Super.BrakeActionLock = false; } /* * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p pStator_Currents ab_t format. * */ __weak void ICS_GetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { int32_t aux; uint16_t reg; PWMC_ICS_Handle_t * pHandle = ( PWMC_ICS_Handle_t * ) pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx_1 = pHandle->pParams_str->ADCx_1; ADC_TypeDef * ADCx_2 = pHandle->pParams_str->ADCx_2; /* disable ADC trigger */ LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); /* Ia = (hPhaseAOffset)-(PHASE_A_ADC_CHANNEL value) */ reg = ( uint16_t )( ADCx_1->JDR1 ); aux = ( int32_t )( reg ) - ( int32_t )( pHandle->PhaseAOffset ); /* Saturation of Ia */ if ( aux < -INT16_MAX ) { pStator_Currents->a = -INT16_MAX; } else if ( aux > INT16_MAX ) { pStator_Currents->a = INT16_MAX; } else { pStator_Currents->a = ( int16_t )aux; } /* Ib = (hPhaseBOffset)-(PHASE_B_ADC_CHANNEL value) */ reg = ( uint16_t )( ADCx_2->JDR1 ); aux = ( int32_t )( reg ) - ( int32_t )( pHandle->PhaseBOffset ); /* Saturation of Ib */ if ( aux < -INT16_MAX ) { pStator_Currents->b = -INT16_MAX; } else if ( aux > INT16_MAX ) { pStator_Currents->b = INT16_MAX; } else { pStator_Currents->b = ( int16_t )aux; } pHandle->_Super.Ia = pStator_Currents->a; pHandle->_Super.Ib = pStator_Currents->b; pHandle->_Super.Ic = -pStator_Currents->a - pStator_Currents->b; } /* * @brief Sums up injected conversion data into wPhaseXOffset. * * It is called only during current calibration. * * @param pHdl: Handler of the current instance of the PWM component. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ __weak void ICS_HFCurrentsCalibration( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { PWMC_ICS_Handle_t * pHandle = ( PWMC_ICS_Handle_t * ) pHdl; ADC_TypeDef * ADCx_1 = pHandle->pParams_str->ADCx_1; ADC_TypeDef * ADCx_2 = pHandle->pParams_str->ADCx_2; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* disable ADC trigger */ LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH4 ); if ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { pHandle->PhaseAOffset += ADCx_1->JDR1; pHandle->PhaseBOffset += ADCx_2->JDR1; pHandle->PolarizationCounter++; } /* during offset calibration no current is flowing in the phases */ pStator_Currents->a = 0; pStator_Currents->b = 0; } /* * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors of driving section. It has to be * called on each motor start-up when using high voltage drivers. * * @param pHdl: Handler of the current instance of the PWM component. * @param ticks: Timer ticks value to be applied * Min value: 0 (low sides ON) * Max value: PWM_PERIOD_CYCLES/2 (low sides OFF) */ __weak void ICS_TurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ) { PWMC_ICS_Handle_t * pHandle = ( PWMC_ICS_Handle_t * ) pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = true; /*Turn on the three low side switches */ LL_TIM_OC_SetCompareCH1 ( TIMx, ticks ); LL_TIM_OC_SetCompareCH2 ( TIMx, ticks ); LL_TIM_OC_SetCompareCH3 ( TIMx, ticks ); LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == RESET ) {} /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } return; } /* * @brief Enables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void ICS_SwitchOnPWM( PWMC_Handle_t * pHdl ) { PWMC_ICS_Handle_t * pHandle = ( PWMC_ICS_Handle_t * ) pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = false; /* Set all duty to 50% */ LL_TIM_OC_SetCompareCH1(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH2(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH3(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH4(TIMx, (uint32_t)(pHandle->Half_PWMPeriod - 5u)); /* wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE; LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { if ( LL_TIM_CC_IsEnabledChannel(TIMx, TIMxCCER_MASK_CH123) != 0u ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Enable Update IRQ */ LL_TIM_EnableIT_UPDATE( TIMx ); return; } /* * @brief Disables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void ICS_SwitchOffPWM( PWMC_Handle_t * pHdl ) { PWMC_ICS_Handle_t * pHandle = ( PWMC_ICS_Handle_t * ) pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* Disable UPDATE ISR */ LL_TIM_DisableIT_UPDATE( TIMx ); pHandle->_Super.TurnOnLowSidesAction = false; /* Main PWM Output Disable */ LL_TIM_DisableAllOutputs(TIMx); if ( pHandle->_Super.BrakeActionLock == true ) { } else { if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* wait for a new PWM period to flush last HF task */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); return; } /* * @brief Writes into peripheral registers the new duty cycle and sampling point. * * @param pHdl: Handler of the current instance of the PWM component. * @param SamplingPoint: Point at which the ADC will be triggered, written in timer clock counts. * @retval Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ __weak uint16_t ICS_WriteTIMRegisters( PWMC_Handle_t * pHdl ) { uint16_t aux; PWMC_ICS_Handle_t * pHandle = ( PWMC_ICS_Handle_t * ) pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; LL_TIM_OC_SetCompareCH1( TIMx, pHandle->_Super.CntPhA ); LL_TIM_OC_SetCompareCH2( TIMx, pHandle->_Super.CntPhB ); LL_TIM_OC_SetCompareCH3( TIMx, pHandle->_Super.CntPhC ); /* Limit for update event */ /* Check the status of SOFOC flag. If it is set, an update event has occurred and thus the FOC rate is too high */ if ( LL_TIM_CC_IsEnabledChannel(TIMx, LL_TIM_CHANNEL_CH4)) { aux = MC_DURATION; } else { aux = MC_NO_ERROR; } return aux; } /* * @brief Contains the TIMx Update event interrupt. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void * ICS_TIMx_UP_IRQHandler( PWMC_ICS_Handle_t * pHandle ) { ADC_TypeDef * ADCx_1 = pHandle->pParams_str->ADCx_1; ADC_TypeDef * ADCx_2 = pHandle->pParams_str->ADCx_2; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* set JSQR register */ ADCx_1->JSQR = ( uint32_t ) pHandle->ADCConfig1; ADCx_2->JSQR = ( uint32_t ) pHandle->ADCConfig2; LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH4 ); return &( pHandle->_Super.Motor ); } /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
17,037
C
30.906367
132
0.636321
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/L4xx/Inc/r3_1_l4xx_pwm_curr_fdbk.h
/** ****************************************************************************** * @file r3_1_l4xx_pwm_curr_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * r3_1_l4xx_pwm_curr_fdbk component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup R3_1_L4XX_pwm_curr_fdbk */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __R3_1_L4XX_PWMCURRFDBK_H #define __R3_1_L4XX_PWMCURRFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "pwm_curr_fdbk.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup R3_1_pwm_curr_fdbk * @{ */ #define GPIO_NoRemap_TIM1 ((uint32_t)(0)) #define SHIFTED_TIMs ((uint8_t) 1) #define NO_SHIFTED_TIMs ((uint8_t) 0) #define NONE ((uint8_t)(0x00)) #define EXT_MODE ((uint8_t)(0x01)) #define INT_MODE ((uint8_t)(0x02)) /* Exported types ------------------------------------------------------- */ /* * @brief R3_1_L4XX_pwm_curr_fdbk component parameters definition. */ typedef const struct { /* Current reading A/D Conversions initialization -----------------------------*/ ADC_TypeDef * ADCx; /* ADC peripheral to be used. */ TIM_TypeDef * TIMx; /* Timer used for PWM generation. */ uint32_t ADCConfig [6] ; /* Stores ADC sequence for the 6 sectors. */ uint16_t hTafter; /* Sum of dead time plus max value between rise time and noise time expressed in number of TIM clocks. */ uint16_t hTbefore; /* Sampling time expressed in number of TIM clocks. */ uint16_t Tsampling; /* Sampling time expressed in number of TIM clocks. */ uint16_t Tcase2; /* Sampling time expressed in number of TIM clocks. */ uint16_t Tcase3; /* Sampling time expressed in number of TIM clocks. */ uint16_t hDAC_OCP_Threshold; /* Value of analog reference expressed as 16bit unsigned integer. Ex. 0 = 0V ; 65536 = VDD_DAC.*/ uint16_t hDAC_OVP_Threshold; /* Value of analog reference expressed as 16bit unsigned integer. Ex. 0 = 0V ; 65536 = VDD_DAC.*/ uint8_t RepetitionCounter; /* Expresses the number of PWM periods to be elapsed before compare registers are updated again. In particular: RepetitionCounter= (2* #PWM periods)-1*/ } R3_1_Params_t; /* * This structure is used to handle an instance of the R3_1_L4XX_pwm_curr_fdbk component. */ typedef struct { PWMC_Handle_t _Super; /*!< Base component handler. */ uint32_t PhaseAOffset; /*!< Offset of Phase A current sensing network. */ uint32_t PhaseBOffset; /*!< Offset of Phase B current sensing network. */ uint32_t PhaseCOffset; /*!< Offset of Phase C current sensing network. */ volatile uint32_t ADCTriggerEdge; /* External trigger edge selection for ADC peripheral. */ uint16_t Half_PWMPeriod; /* Half PWM Period in timer clock counts. */ uint16_t ADC_ExternalTriggerInjected; /* Trigger selection for ADC peripheral.*/ uint8_t CalibSector; /* Space vector sector number during calibration. */ volatile uint8_t PolarizationCounter; /* Number of conversions performed during the calibration phase. */ R3_1_Params_t const *pParams_str; } PWMC_R3_1_Handle_t; /* Exported functions ------------------------------------------------------- */ /* Initializes peripherals for current reading and PWM generation * in three shunts configuration using STM32F302x8 *****/ void R3_1_Init( PWMC_R3_1_Handle_t * pHandle ); /* Disables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_1_SwitchOffPWM( PWMC_Handle_t * pHdl ); /* * Enables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_1_SwitchOnPWM( PWMC_Handle_t * pHdl ); /* * Turns on low sides switches. */ void R3_1_TurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ); /* * Computes and stores in the handler the latest converted motor phase currents in ab_t format. */ void R3_1_GetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ); /* * Computes and stores in the handler the latest converted motor phase currents in ab_t format. Specific to overmodulation. */ void R3_1_GetPhaseCurrents_OVM( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ); /* * Stores into the handler the voltage present on Ia and * Ib current feedback analog channels when no current is flowing into the motor. */ void R3_1_CurrentReadingCalibration( PWMC_Handle_t * pHdl ); /* * Configures the ADC for the current sampling during calibration. */ uint16_t R3_1_SetADCSampPointCalibration( PWMC_Handle_t * pHdl); /* * Configures the ADC for the current sampling related to sector X (X = [1..6] ). */ uint16_t R3_1_SetADCSampPointSectX( PWMC_Handle_t * pHdl); /* * Configures the ADC for the current sampling related to sector X (X = [1..6] ) in case of overmodulation. */ uint16_t R3_1_SetADCSampPointSectX_OVM( PWMC_Handle_t * pHdl); /* * Contains the TIMx Update event interrupt. */ void * R3_1_TIMx_UP_IRQHandler( PWMC_R3_1_Handle_t * pHandle ); /* * Sets the PWM mode for R/L detection. */ void R3_1_RLDetectionModeEnable( PWMC_Handle_t * pHdl ); /* * Disables the PWM mode for R/L detection. */ void R3_1_RLDetectionModeDisable( PWMC_Handle_t * pHdl ); /* * Sets the PWM dutycycle for R/L detection. */ uint16_t R3_1_RLDetectionModeSetDuty( PWMC_Handle_t * pHdl, uint16_t hDuty ); /* * Computes and stores in the handler the latest converted motor phase currents in ab_t format. */ void R3_1_RLGetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ); /* * Turns on low sides switches. */ void R3_1_RLTurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ); /* * Enables PWM generation on the proper Timer peripheral. */ void R3_1_RLSwitchOnPWM( PWMC_Handle_t * pHdl ); /* * Disables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_1_RLSwitchOffPWM( PWMC_Handle_t * pHdl ); /* * Turns on low sides switches and start ADC triggering. */ void R3_1_RLTurnOnLowSidesAndStart( PWMC_Handle_t * pHdl ); /* * Sets ADC sampling points. */ void RLSetADCSampPoint( PWMC_Handle_t * pHdl ); /* * Sets the calibrated offset. */ void R3_1_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /* * Reads the calibrated offsets. */ void R3_1_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*__R3_1_L4XX_PWMNCURRFDBK_H*/ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
7,943
C
32.661017
124
0.585547
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/L4xx/Inc/ics_l4xx_pwm_curr_fdbk.h
/** ****************************************************************************** * @file ics_l4xx_pwm_curr_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * ICS PWM current feedback component for F30x of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup ICS_L4XX_pwm_curr_fdbk */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __ICS_L4XX_PWMCURRFDBK_H #define __ICS_L4XX_PWMCURRFDBK_H /* Includes ------------------------------------------------------------------*/ #include "pwm_curr_fdbk.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup ICS_pwm_curr_fdbk * @{ */ #define NONE ((uint8_t)(0x00)) #define EXT_MODE ((uint8_t)(0x01)) #define INT_MODE ((uint8_t)(0x02)) #define SOFOC 0x0008u /* This flag is reset at the beginning of FOC and it is set in the TIM UP IRQ. If at the end of FOC this flag is set, it means that FOC rate is too high and thus an error is generated */ /* * @brief ICS_L4XX_pwm_curr_fdbk component parameters definition */ typedef const struct { /* Dual MC parameters --------------------------------------------------------*/ uint8_t FreqRatio; /* Used in case of dual MC to synchronize TIM1 and TIM8. It has effect only on the second instanced object and must be equal to the ratio between the two PWM frequencies (higher/lower). Supported values are 1, 2 or 3 */ uint8_t IsHigherFreqTim; /* When FreqRatio is greater than 1 this param is used to indicate if this instance is the one with the highest frequency. Allowed values are: HIGHER_FREQ or LOWER_FREQ */ /* Current reading A/D Conversions initialization -----------------------------*/ ADC_TypeDef *ADCx_1; /* First ADC peripheral to be used.*/ ADC_TypeDef *ADCx_2; /* Second ADC peripheral to be used.*/ uint8_t IaChannel; /* ADC channel used for conversion of current Ia. It must be equal to ADC_CHANNEL_x, x ∈ [0 ; 15]. */ uint8_t IbChannel; /* ADC channel used for conversion of current Ib. It must be equal to ADC_CHANNEL_x, x ∈ [0 ; 15]. */ /* PWM generation parameters --------------------------------------------------*/ uint8_t RepetitionCounter; /* Expresses the number of PWM periods to be elapsed before compare registers are updated again. In particular: RepetitionCounter= (2* #PWM periods)-1*/ TIM_TypeDef * TIMx; /* Timer used for PWM generation. Equal to TIM1 if bInstanceNbr is equal to 1, equal to TIM8 otherwise. */ } ICS_Params_t; /* * PWMnCurrFdbk ICS L4XX handle */ typedef struct { PWMC_Handle_t _Super; /* Base component handler. */ uint32_t PhaseAOffset; /* Offset of Phase A current sensing network. */ uint32_t PhaseBOffset; /* Offset of Phase B current sensing network. */ uint16_t Half_PWMPeriod; /* Half PWM Period in timer clock counts. */ volatile uint8_t PolarizationCounter; /* Number of conversions performed during the calibration phase. */ uint32_t ADCConfig1; /* Value for ADC CR2 to properly configure current sampling during the context switching. Either defined in PWMC_ICS_Handle_t or in ICS_Params_t. */ uint32_t ADCConfig2; /* Value for ADC CR2 to properly configure current sampling during the context switching. Either defined in PWMC_ICS_Handle_t or in ICS_Params_t. */ ICS_Params_t *pParams_str; } PWMC_ICS_Handle_t; /* Exported functions ------------------------------------------------------- */ /* * Initializes TIMx, ADC, GPIO and NVIC for current reading * in ICS configuration using STM32F30X. */ void ICS_Init( PWMC_ICS_Handle_t * pHandle ); /* * Sums up injected conversion data into wPhaseXOffset. */ void ICS_CurrentReadingCalibration( PWMC_Handle_t * pHandle ); /* * Computes and stores in the handler the latest converted motor phase currents in ab_t format. */ void ICS_GetPhaseCurrents( PWMC_Handle_t * pHandle, ab_t * pStator_Currents ); /* * Turns on low sides switches. */ void ICS_TurnOnLowSides( PWMC_Handle_t * pHandle, uint32_t ticks ); /* * Enables PWM generation on the proper Timer peripheral acting on MOE bit. */ void ICS_SwitchOnPWM( PWMC_Handle_t * pHandle ); /* * Disables PWM generation on the proper Timer peripheral acting on MOE bit. */ void ICS_SwitchOffPWM( PWMC_Handle_t * pHandle ); /* * Writes into peripheral registers the new duty cycle and sampling point. */ uint16_t ICS_WriteTIMRegisters( PWMC_Handle_t * pHandle ); /* * Sums up injected conversion data into wPhaseXOffset. */ void ICS_HFCurrentsCalibration( PWMC_Handle_t * pHandle, ab_t * pStator_Currents ); /* * Contains the TIMx Update event interrupt. */ void * ICS_TIMx_UP_IRQHandler( PWMC_ICS_Handle_t * pHandle ); /* * Contains the TIMx Break1 event interrupt. */ void * ICS_BRK_IRQHandler( PWMC_ICS_Handle_t * pHandle ); /* * Contains the TIMx Break2 event interrupt. */ void * ICS_BRK2_IRQHandler( PWMC_ICS_Handle_t * pHandle ); /* * Stores in the handler the calibrated offsets. */ void ICS_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /* * Reads the calibrated offsets stored in the handler. */ void ICS_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*__ICS_L4XX_PWMCURRFDBK_H*/ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
7,346
C
34.839024
107
0.526001
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/L4xx/Inc/r3_2_l4xx_pwm_curr_fdbk.h
/** ****************************************************************************** * @file r3_2_l4xx_pwm_curr_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * r3_4_f30x_pwm_curr_fdbk component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup R3_2_L4XX_pwm_curr_fdbk */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __R3_2_L4XX_PWMNCURRFDBK_H #define __R3_2_L4XX_PWMNCURRFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "pwm_curr_fdbk.h" /* Exported defines --------------------------------------------------------*/ #define GPIO_NoRemap_TIM1 ((uint32_t)(0)) #define SHIFTED_TIMs ((uint8_t) 1) #define NO_SHIFTED_TIMs ((uint8_t) 0) #define NONE ((uint8_t)(0x00)) #define EXT_MODE ((uint8_t)(0x01)) #define INT_MODE ((uint8_t)(0x02)) /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup R3_2_pwm_curr_fdbk * @{ */ /* Exported types ------------------------------------------------------- */ /* * @brief R3_2_L4XX_pwm_curr_fdbk component parameters definition */ typedef const struct { TIM_TypeDef * TIMx; /* Timer used for PWM generation.*/ uint32_t ADCConfig1[6]; /* Values of JSQR for first ADC for 6 sectors. */ uint32_t ADCConfig2[6]; /* Values of JSQR for second ADC for 6 sectors. */ ADC_TypeDef * ADCDataReg1[6]; /* Contains the Address of ADC read value for one phase and all the 6 sectors. */ ADC_TypeDef * ADCDataReg2[6]; /* Contains the Address of ADC read value for one phase and all the 6 sectors. */ /* PWM generation parameters --------------------------------------------------*/ uint16_t hTafter; /* Sum of dead time plus max value between rise time and noise time express in number of TIM clocks.*/ uint16_t Tsampling; /* Sampling time express in number of TIM clocks.*/ uint16_t hTbefore; /* Sampling time express in number of TIM clocks.*/ uint16_t Tcase2; /* Sampling time express in number of TIM clocks.*/ uint16_t Tcase3; /* Sampling time express in number of TIM clocks.*/ /* DAC settings --------------------------------------------------------------*/ uint16_t hDAC_OCP_Threshold; /* Value of analog reference expressed as 16bit unsigned integer. Ex. 0 = 0V ; 65536 = VDD_DAC.*/ uint16_t hDAC_OVP_Threshold; /* Value of analog reference expressed as 16bit unsigned integer. Ex. 0 = 0V ; 65536 = VDD_DAC.*/ /* Dual MC parameters --------------------------------------------------------*/ uint8_t bFreqRatio; /* Used in case of dual MC to synchronize TIM1 and TIM8. It has effect only on the second instanced object and must be equal to the ratio between the two PWM frequencies (higher/lower). Supported values are 1, 2 or 3 */ uint8_t bIsHigherFreqTim; /* When bFreqRatio is greater than 1 this param is used to indicate if this instance is the one with the highest frequency. Allowed value are: HIGHER_FREQ or LOWER_FREQ */ /* PWM Driving signals initialization ----------------------------------------*/ uint8_t RepetitionCounter; /* It expresses the number of PWM periods to be elapsed before compare registers are updated again. In particular: RepetitionCounter= (2* #PWM periods)-1*/ } R3_2_Params_t; /* * @brief Handles an instance of the R3_2_L4XX_pwm_curr_fdbk component. */ typedef struct { PWMC_Handle_t _Super; /* Base component handler. */ uint32_t PhaseAOffset; /* Offset of Phase A current sensing network. */ uint32_t PhaseBOffset; /* Offset of Phase B current sensing network. */ uint32_t PhaseCOffset; /* Offset of Phase C current sensing network. */ uint32_t ADC_ExternalTriggerInjected; /* External trigger selection for ADC peripheral.*/ volatile uint32_t ADCTriggerEdge; /* Trigger edge selection for ADC peripheral. Specific to F4XX, F7XX and L4XX.*/ uint16_t Half_PWMPeriod; /* Half PWM Period in timer clock counts. */ uint8_t CalibSector; /* Space vector sector number during calibration. Specific to F4XX, F7XX and L4XX. */ volatile uint8_t PolarizationCounter; /* Number of conversions performed during the calibration phase. */ R3_2_Params_t *pParams_str; } PWMC_R3_2_Handle_t; /* Exported functions ------------------------------------------------------- */ /* * Initializes TIMx, ADC, GPIO, DMA1 and NVIC for current reading * in three shunt topology using STM32F30X and two ADCs. */ void R3_2_Init( PWMC_R3_2_Handle_t * pHandle ); /* * Stores into the handler the voltage present on Ia and Ib current * feedback analog channels when no current is flowing into the motor. */ void R3_2_CurrentReadingCalibration( PWMC_Handle_t * pHdl ); /* * Computes and stores in the handler the latest converted motor phase currents in ab_t format. */ void R3_2_GetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * Iab ); /* * Computes and stores in the handler the latest converted motor phase currents in ab_t format. Specific to overmodulation. */ void R3_2_GetPhaseCurrents_OVM( PWMC_Handle_t * pHdl, ab_t * Iab ); /* * Turns on low sides switches. */ void R3_2_TurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ); /* * Enables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_2_SwitchOnPWM( PWMC_Handle_t * pHdl ); /* * Disables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_2_SwitchOffPWM( PWMC_Handle_t * pHdl ); /* * Configures the ADC for the current sampling during calibration. */ uint16_t R3_2_SetADCSampPointCalibration( PWMC_Handle_t * pHdl); /* * Configures the ADC for the current sampling related to sector X (X = [1..6] ). */ uint16_t R3_2_SetADCSampPointSectX( PWMC_Handle_t * pHdl); /* * Configures the ADC for the current sampling related to sector X (X = [1..6] ) in case of overmodulation. */ uint16_t R3_2_SetADCSampPointSectX_OVM( PWMC_Handle_t * pHdl); /* * Contains the TIMx Update event interrupt. */ void * R3_2_TIMx_UP_IRQHandler( PWMC_R3_2_Handle_t * pHdl ); /* * Set the PWM mode for R/L detection. */ void R3_2_RLDetectionModeEnable( PWMC_Handle_t * pHdl ); /* * Disables the PWM mode for R/L detection. */ void R3_2_RLDetectionModeDisable( PWMC_Handle_t * pHdl ); /* * Set the PWM dutycycle for R/L detection. */ uint16_t R3_2_RLDetectionModeSetDuty( PWMC_Handle_t * pHdl, uint16_t hDuty ); /* * Turns on low sides switches and start ADC triggering. */ void R3_2_RLTurnOnLowSidesAndStart( PWMC_Handle_t * pHdl ); /* * Sets ADC sampling points. */ void RLSetADCSampPoint( PWMC_Handle_t * pHdl ); /* * Stores in the handler the calibrated offsets. */ void R3_2_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /* * Reads the calibrated offsets stored in the handler. */ void R3_2_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*__R3_2_L4XX_PWMNCURRFDBK_H*/ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
9,198
C
36.70082
124
0.52968
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/F3xx/Src/ics_f30x_pwm_curr_fdbk.c
/** ****************************************************************************** * @file ics_f30x_pwm_curr_fdbk.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement the ICS * PWM current feedback component for F30X of the Motor Control SDK. ******************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * * @ingroup ICS_F30X_pwm_curr_fdbk */ /* Includes ------------------------------------------------------------------*/ #include "ics_f30x_pwm_curr_fdbk.h" #include "pwm_common.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** * @defgroup ICS_pwm_curr_fdbk ICS 2 ADCs PWM & Current Feedback * * @brief ICS, 2 ADCs, PWM & Current Feedback implementation for F30X, F4XX, F7XX, G4XX and L4XX MCUs * * This component is used in applications based on STM32 MCUs * and using an Insulated Current Sensors topology. * * @{ */ /* ADC registers reset values */ #define TIMxCCER_MASK_CH123 (LL_TIM_CHANNEL_CH1 | LL_TIM_CHANNEL_CH2 | LL_TIM_CHANNEL_CH3 | \ LL_TIM_CHANNEL_CH1N | LL_TIM_CHANNEL_CH2N | LL_TIM_CHANNEL_CH3N) #define CONV_STARTED ((uint32_t) (0x8)) #define CONV_FINISHED ((uint32_t) (0xC)) #define FLAGS_CLEARED ((uint32_t) (0x0)) /** * @brief Initializes TIMx, ADC, GPIO and NVIC for current reading * in ICS configuration using STM32F30X. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void ICS_Init( PWMC_ICS_Handle_t * pHandle ) { TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx_1 = pHandle->pParams_str->ADCx_1; ADC_TypeDef * ADCx_2 = pHandle->pParams_str->ADCx_2; if ( ( uint32_t )pHandle == ( uint32_t )&pHandle->_Super ) { /* disable IT and flags in case of LL driver usage * workaround for unwanted interrupt enabling done by LL driver */ LL_ADC_DisableIT_EOC( ADCx_1 ); LL_ADC_ClearFlag_EOC( ADCx_1 ); LL_ADC_DisableIT_JEOC( ADCx_1 ); LL_ADC_ClearFlag_JEOC( ADCx_1 ); LL_ADC_DisableIT_EOC( ADCx_2 ); LL_ADC_ClearFlag_EOC( ADCx_2 ); LL_ADC_DisableIT_JEOC( ADCx_2 ); LL_ADC_ClearFlag_JEOC( ADCx_2 ); /* disable main TIM counter to ensure * a synchronous start by TIM2 trigger */ LL_TIM_DisableCounter( TIMx ); /* Enables the TIMx Preload on CC1 Register */ LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH1 ); /* Enables the TIMx Preload on CC2 Register */ LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH2 ); /* Enables the TIMx Preload on CC3 Register */ LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH3 ); /* Enables the TIMx Preload on CC4 Register */ LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH4 ); /* Clear pending BRK */ LL_TIM_ClearFlag_BRK( TIMx ); LL_TIM_ClearFlag_BRK2( TIMx ); LL_TIM_EnableIT_BRK( TIMx ); /* Prepare timer for synchronization */ LL_TIM_GenerateEvent_UPDATE( TIMx ); if ( pHandle->pParams_str->FreqRatio == 2u ) { if ( pHandle->pParams_str->IsHigherFreqTim == HIGHER_FREQ ) { if ( pHandle->pParams_str->RepetitionCounter == 3u ) { /* Set TIMx repetition counter to 1 */ LL_TIM_SetRepetitionCounter( TIMx, 1 ); LL_TIM_GenerateEvent_UPDATE( TIMx ); /* Repetition counter will be set to 3 at next Update */ LL_TIM_SetRepetitionCounter( TIMx, 3 ); } } LL_TIM_SetCounter( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) - 1u ); } else /* FreqRatio equal to 1 or 3 */ { if ( pHandle->_Super.Motor == M1 ) { if ( pHandle->pParams_str->RepetitionCounter == 1u ) { LL_TIM_SetCounter( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) - 1u ); } else if ( pHandle->pParams_str->RepetitionCounter == 3u ) { /* Set TIMx repetition counter to 1 */ LL_TIM_SetRepetitionCounter( TIMx, 1 ); LL_TIM_GenerateEvent_UPDATE( TIMx ); /* Repetition counter will be set to 3 at next Update */ LL_TIM_SetRepetitionCounter( TIMx, 3 ); } } } /* Enable PWM channel */ LL_TIM_CC_EnableChannel( TIMx, TIMxCCER_MASK_CH123 ); if ( TIMx == TIM1 ) { /* TIM1 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph( LL_DBGMCU_APB2_GRP1_TIM1_STOP ); } #if defined(TIM8) else { /* TIM8 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph( LL_DBGMCU_APB2_GRP1_TIM8_STOP ); } #endif /* ADCx_1 and ADCx_2 registers configuration ---------------------------------*/ /* ADCx_1 and ADCx_2 registers reset */ LL_ADC_EnableInternalRegulator( ADCx_1 ); LL_ADC_EnableInternalRegulator( ADCx_2 ); /* Wait for Regulator Startup time, once for both */ volatile uint32_t wait_loop_index = ((LL_ADC_DELAY_INTERNAL_REGUL_STAB_US / 10UL) * (SystemCoreClock / (100000UL * 2UL))); while(wait_loop_index != 0UL) { wait_loop_index--; } LL_ADC_StartCalibration( ADCx_1, LL_ADC_SINGLE_ENDED ); while ( LL_ADC_IsCalibrationOnGoing( ADCx_1 ) ) { } LL_ADC_StartCalibration( ADCx_2, LL_ADC_SINGLE_ENDED ); while ( LL_ADC_IsCalibrationOnGoing( ADCx_2 ) ) { } /* ADCx_1 and ADCx_2 registers configuration ---------------------------------*/ /* Enable ADCx_1 and ADCx_2 */ LL_ADC_Enable( ADCx_1 ); LL_ADC_Enable( ADCx_2 ); /* reset regular conversion sequencer length set by cubeMX */ LL_ADC_REG_SetSequencerLength( ADCx_1, LL_ADC_REG_SEQ_SCAN_DISABLE ); /* ADCx_1 Injected conversions end interrupt enabling */ LL_ADC_ClearFlag_JEOC( ADCx_1 ); LL_ADC_EnableIT_JEOC( ADCx_1 ); LL_ADC_INJ_SetQueueMode( ADCx_1, LL_ADC_INJ_QUEUE_2CONTEXTS_END_EMPTY ); LL_ADC_INJ_SetQueueMode( ADCx_2, LL_ADC_INJ_QUEUE_2CONTEXTS_END_EMPTY ); /* Flush ADC queue */ LL_ADC_INJ_StopConversion( ADCx_1 ); LL_ADC_INJ_StopConversion( ADCx_2 ); /* Clear the flags */ pHandle->_Super.DTTest = 0u; } } /** * @brief Stores in @p pHdl handler the calibrated @p offsets. * * @param pHdl: Handler of the current instance of the PWM component. * @param offsets: Phase offset. */ __weak void ICS_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_ICS_Handle_t *pHandle = (PWMC_ICS_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 pHandle->PhaseAOffset = offsets->phaseAOffset; pHandle->PhaseBOffset = offsets->phaseBOffset; pHdl->offsetCalibStatus = true; } /** * @brief Reads the calibrated @p offsets stored in @p pHdl. * * @param pHdl: Handler of the current instance of the PWM component. * @param offsets: Phase offset. */ __weak void ICS_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_ICS_Handle_t *pHandle = (PWMC_ICS_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 offsets->phaseAOffset = pHandle->PhaseAOffset; offsets->phaseBOffset = pHandle->PhaseBOffset; } /** * @brief Stores into the @p pHdl handler the voltage present on Ia and * Ib current feedback analog channels when no current is flowing into the * motor. * * Called ICS_CurrentReadingPolarization in G4XX. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void ICS_CurrentReadingCalibration( PWMC_Handle_t * pHdl ) { PWMC_ICS_Handle_t * pHandle = ( PWMC_ICS_Handle_t * ) pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; if (false == pHandle->_Super.offsetCalibStatus) { pHandle->PhaseAOffset = 0u; pHandle->PhaseBOffset = 0u; pHandle->PolarizationCounter = 0u; /* Force inactive level on TIMx CHy and TIMx CHyN */ LL_TIM_CC_DisableChannel( TIMx, TIMxCCER_MASK_CH123 ); /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &ICS_HFCurrentsCalibration; ICS_SwitchOnPWM( &pHandle->_Super ); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd( TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter ); ICS_SwitchOffPWM( &pHandle->_Super ); pHandle->PhaseAOffset /= NB_CONVERSIONS; pHandle->PhaseBOffset /= NB_CONVERSIONS; if (0U == pHandle->_Super.SWerror) { pHandle->_Super.offsetCalibStatus = true; } else { /* nothing to do */ } /* Change back function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &ICS_GetPhaseCurrents; } /* It over write TIMx CCRy wrongly written by FOC during calibration so as to force 50% duty cycle on the three inverer legs */ /* Disable TIMx preload */ LL_TIM_OC_DisablePreload( TIMx, LL_TIM_CHANNEL_CH1 ); LL_TIM_OC_DisablePreload( TIMx, LL_TIM_CHANNEL_CH2 ); LL_TIM_OC_DisablePreload( TIMx, LL_TIM_CHANNEL_CH3 ); LL_TIM_OC_SetCompareCH1( TIMx, pHandle->Half_PWMPeriod ); LL_TIM_OC_SetCompareCH2( TIMx, pHandle->Half_PWMPeriod ); LL_TIM_OC_SetCompareCH3( TIMx, pHandle->Half_PWMPeriod ); LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH1 ); LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH2 ); LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH3 ); /* Set back TIMx CCER register */ LL_TIM_CC_EnableChannel( TIMx, TIMxCCER_MASK_CH123 ); pHandle->_Super.BrakeActionLock = false; } /** * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p pStator_Currents ab_t format. * * @param pHdl: Handler of the current instance of the PWM component. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ __weak void ICS_GetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { int32_t aux; uint16_t reg; PWMC_ICS_Handle_t * pHandle = ( PWMC_ICS_Handle_t * ) pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx_1 = pHandle->pParams_str->ADCx_1; ADC_TypeDef * ADCx_2 = pHandle->pParams_str->ADCx_2; /* disable ADC trigger */ LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); /* Ia = (hPhaseAOffset)-(PHASE_A_ADC_CHANNEL value) */ reg = ( uint16_t )( ADCx_1->JDR1 ); aux = ( int32_t )( reg ) - ( int32_t )( pHandle->PhaseAOffset ); /* Saturation of Ia */ if ( aux < -INT16_MAX ) { pStator_Currents->a = -INT16_MAX; } else if ( aux > INT16_MAX ) { pStator_Currents->a = INT16_MAX; } else { pStator_Currents->a = ( int16_t )aux; } /* Ib = (hPhaseBOffset)-(PHASE_B_ADC_CHANNEL value) */ reg = ( uint16_t )( ADCx_2->JDR1 ); aux = ( int32_t )( reg ) - ( int32_t )( pHandle->PhaseBOffset ); /* Saturation of Ib */ if ( aux < -INT16_MAX ) { pStator_Currents->b = -INT16_MAX; } else if ( aux > INT16_MAX ) { pStator_Currents->b = INT16_MAX; } else { pStator_Currents->b = ( int16_t )aux; } pHandle->_Super.Ia = pStator_Currents->a; pHandle->_Super.Ib = pStator_Currents->b; pHandle->_Super.Ic = -pStator_Currents->a - pStator_Currents->b; } /** * @brief Sums up injected conversion data into wPhaseXOffset. * * It is called only during current calibration. * Called ICS_HFCurrentsPolarization in G4XX. * * @param pHdl: Handler of the current instance of the PWM component. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ __weak void ICS_HFCurrentsCalibration( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { PWMC_ICS_Handle_t * pHandle = ( PWMC_ICS_Handle_t * ) pHdl; ADC_TypeDef * ADCx_1 = pHandle->pParams_str->ADCx_1; ADC_TypeDef * ADCx_2 = pHandle->pParams_str->ADCx_2; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* disable ADC trigger */ LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH4 ); if ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { pHandle->PhaseAOffset += ADCx_1->JDR1; pHandle->PhaseBOffset += ADCx_2->JDR1; pHandle->PolarizationCounter++; } /* during offset calibration no current is flowing in the phases */ pStator_Currents->a = 0; pStator_Currents->b = 0; } /** * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors of driving section. It has to be * called on each motor start-up when using high voltage drivers. * * @param pHdl: Handler of the current instance of the PWM component. * @param ticks: Timer ticks value to be applied * Min value: 0 (low sides ON) * Max value: PWM_PERIOD_CYCLES/2 (low sides OFF) */ __weak void ICS_TurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ) { PWMC_ICS_Handle_t * pHandle = ( PWMC_ICS_Handle_t * ) pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = true; /*Turn on the three low side switches */ LL_TIM_OC_SetCompareCH1 ( TIMx, ticks ); LL_TIM_OC_SetCompareCH2 ( TIMx, ticks ); LL_TIM_OC_SetCompareCH3 ( TIMx, ticks ); LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == RESET ) ; /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } return; } /** * @brief Enables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void ICS_SwitchOnPWM( PWMC_Handle_t * pHdl ) { PWMC_ICS_Handle_t * pHandle = ( PWMC_ICS_Handle_t * ) pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = false; /* Set all duty to 50% */ LL_TIM_OC_SetCompareCH1(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH2(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH3(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH4(TIMx, (uint32_t)(pHandle->Half_PWMPeriod - 5u)); /* wait for new PWM period */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { if ( LL_TIM_CC_IsEnabledChannel(TIMx, TIMxCCER_MASK_CH123) != 0u ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Enable Update IRQ */ LL_TIM_EnableIT_UPDATE( TIMx ); return; } /** * @brief Disables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void ICS_SwitchOffPWM( PWMC_Handle_t * pHdl ) { PWMC_ICS_Handle_t * pHandle = ( PWMC_ICS_Handle_t * ) pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* Disable UPDATE ISR */ LL_TIM_DisableIT_UPDATE( TIMx ); pHandle->_Super.TurnOnLowSidesAction = false; /* Main PWM Output Disable */ LL_TIM_DisableAllOutputs(TIMx); if ( pHandle->_Super.BrakeActionLock == true ) { } else { if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* wait for new PWM period to flush last HF task */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); return; } /** * @brief Writes into peripheral registers the new duty cycle and sampling point. * * @param pHdl: Handler of the current instance of the PWM component. * @retval uint16_t Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ __weak uint16_t ICS_WriteTIMRegisters( PWMC_Handle_t * pHdl ) { uint16_t aux; PWMC_ICS_Handle_t * pHandle = ( PWMC_ICS_Handle_t * ) pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; LL_TIM_OC_SetCompareCH1( TIMx, pHandle->_Super.CntPhA ); LL_TIM_OC_SetCompareCH2( TIMx, pHandle->_Super.CntPhB ); LL_TIM_OC_SetCompareCH3( TIMx, pHandle->_Super.CntPhC ); /* Limit for update event */ /* Check the status of SOFOC flag. If it is set, an update event has occurred and thus the FOC rate is too high */ if ( LL_TIM_CC_IsEnabledChannel(TIMx, LL_TIM_CHANNEL_CH4)) { aux = MC_DURATION; } else { aux = MC_NO_ERROR; } return aux; } /** * @brief Contains the TIMx Update event interrupt. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void * ICS_TIMx_UP_IRQHandler( PWMC_ICS_Handle_t * pHandle ) { ADC_TypeDef * ADCx_1 = pHandle->pParams_str->ADCx_1; ADC_TypeDef * ADCx_2 = pHandle->pParams_str->ADCx_2; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* set JSQR register */ ADCx_1->JSQR = ( uint32_t ) pHandle->ADCConfig1; ADCx_2->JSQR = ( uint32_t ) pHandle->ADCConfig2; LL_ADC_INJ_StartConversion( ADCx_1 ); LL_ADC_INJ_StartConversion( ADCx_2 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH4 ); return &( pHandle->_Super.Motor ); } /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
19,157
C
31.252525
132
0.631884
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/F3xx/Src/r3_2_f30x_pwm_curr_fdbk.c
/** ****************************************************************************** * @file r3_2_f30x_pwm_curr_fdbk.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement current sensor * class to be stantiated when the three shunts current sensing * topology is used. * * It is specifically designed for STM32F30X * microcontrollers and implements the successive sampling of two motor * current using two ADCs. * + MCU peripheral and handle initialization function * + three shunt current sensing * + space vector modulation function * + ADC sampling function * ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup R3_2_F30X_pwm_curr_fdbk */ /* Includes ------------------------------------------------------------------*/ #include "r3_2_f30x_pwm_curr_fdbk.h" #include "pwm_common.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** * @defgroup R3_2_pwm_curr_fdbk R3 2 ADCs PWM & Current Feedback * * @brief 3-Shunt, 2 ADCs, PWM & Current Feedback implementation for F30X, F4XX, F7XX, G4XX, H5XX, H7XX and L4XX MCUs * * This component is used in applications based on STM32 MCUs, using a three * shunt resistors current sensing topology and 2 ADCs peripherals to acquire the current * values. * * @{ */ /* Private defines -----------------------------------------------------------*/ #define TIMxCCER_MASK_CH123 ((uint16_t) (LL_TIM_CHANNEL_CH1|LL_TIM_CHANNEL_CH1N|\ LL_TIM_CHANNEL_CH2|LL_TIM_CHANNEL_CH2N|\ LL_TIM_CHANNEL_CH3|LL_TIM_CHANNEL_CH3N)) #define CCMR2_CH4_DISABLE 0x8FFFu // /* Private typedef -----------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ static void R3_2_TIMxInit( TIM_TypeDef * TIMx, PWMC_Handle_t * pHdl ); static void R3_2_ADCxInit( ADC_TypeDef * ADCx ); __STATIC_INLINE uint16_t R3_2_WriteTIMRegisters( PWMC_Handle_t * pHdl, uint16_t hCCR4Reg ); static void R3_2_HFCurrentsPolarizationAB( PWMC_Handle_t * pHdl,ab_t * Iab ); static void R3_2_HFCurrentsPolarizationC( PWMC_Handle_t * pHdl, ab_t * Iab ); static void R3_2_SetAOReferenceVoltage( uint32_t DAC_Channel, uint16_t hDACVref ); uint16_t R3_2_SetADCSampPointPolarization( PWMC_Handle_t * pHdl) ; static void R3_2_RLGetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ); static void R3_2_RLTurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ); static void R3_2_RLSwitchOnPWM( PWMC_Handle_t * pHdl ); /** * @brief Initializes TIMx, ADC, GPIO, DMA1 and NVIC for current reading * in three shunt topology shared ADC. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void R3_2_Init( PWMC_R3_2_Handle_t * pHandle ) { R3_2_OPAMPParams_t const *OPAMPParams = pHandle->pParams_str->OPAMPParams; COMP_TypeDef * COMP_OCPAx = pHandle->pParams_str->CompOCPASelection; COMP_TypeDef * COMP_OCPBx = pHandle->pParams_str->CompOCPBSelection; COMP_TypeDef * COMP_OCPCx = pHandle->pParams_str->CompOCPCSelection; COMP_TypeDef * COMP_OVPx = pHandle->pParams_str->CompOVPSelection; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx_1 = pHandle->pParams_str->ADCDataReg1[0]; ADC_TypeDef * ADCx_2 = pHandle->pParams_str->ADCDataReg2[0]; /*Checks that _Super is the first member of the structure PWMC_R3_2_Handle_t */ if ( ( uint32_t )pHandle == ( uint32_t )&pHandle->_Super ) { /* Disables IT and flags in case of LL driver usage * workaround for unwanted interrupt enabling done by LL driver */ LL_ADC_DisableIT_EOC( ADCx_1 ); LL_ADC_ClearFlag_EOC( ADCx_1 ); LL_ADC_DisableIT_JEOC( ADCx_1 ); LL_ADC_ClearFlag_JEOC( ADCx_1 ); LL_ADC_DisableIT_EOC( ADCx_2 ); LL_ADC_ClearFlag_EOC( ADCx_2 ); LL_ADC_DisableIT_JEOC( ADCx_2 ); LL_ADC_ClearFlag_JEOC( ADCx_2 ); if ( TIMx == TIM1 ) { /* TIM1 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph( LL_DBGMCU_APB2_GRP1_TIM1_STOP ); } else { /* TIM8 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph( LL_DBGMCU_APB2_GRP1_TIM8_STOP ); } if ( OPAMPParams != NULL ) { LL_OPAMP_Enable(OPAMPParams->OPAMPSelect_1[0]); LL_OPAMP_Enable(OPAMPParams->OPAMPSelect_2[0]); } /* Overcurrent protection phase A */ if ( COMP_OCPAx != NULL ) { /* Inverting input*/ if ( pHandle->pParams_str->CompOCPAInvInput_MODE != EXT_MODE ) { if ( LL_COMP_GetInputMinus( COMP_OCPAx ) == LL_COMP_INPUT_MINUS_DAC1_CH1 ) { R3_2_SetAOReferenceVoltage( LL_DAC_CHANNEL_1, ( uint16_t )( pHandle->pParams_str->DAC_OCP_Threshold ) ); } #if defined(DAC_CHANNEL2_SUPPORT) else if ( LL_COMP_GetInputMinus( COMP_OCPAx ) == LL_COMP_INPUT_MINUS_DAC1_CH2 ) { R3_2_SetAOReferenceVoltage( LL_DAC_CHANNEL_2, ( uint16_t )( pHandle->pParams_str->DAC_OCP_Threshold ) ); } #endif else { } } /* Output */ LL_COMP_Enable ( COMP_OCPAx ); LL_COMP_Lock( COMP_OCPAx ); } /* Overcurrent protection phase B */ if ( COMP_OCPBx != NULL ) { LL_COMP_Enable ( COMP_OCPBx ); LL_COMP_Lock( COMP_OCPBx ); } /* Overcurrent protection phase C */ if ( COMP_OCPCx != NULL ) { LL_COMP_Enable ( COMP_OCPCx ); LL_COMP_Lock( COMP_OCPCx ); } /* Overvoltage protection */ if ( COMP_OVPx != NULL ) { /* Inverting input*/ if ( pHandle->pParams_str->CompOVPInvInput_MODE != EXT_MODE ) { if ( LL_COMP_GetInputMinus( COMP_OVPx ) == LL_COMP_INPUT_MINUS_DAC1_CH1 ) { R3_2_SetAOReferenceVoltage( LL_DAC_CHANNEL_1, ( uint16_t )( pHandle->pParams_str->DAC_OVP_Threshold ) ); } #if defined(DAC_CHANNEL2_SUPPORT) else if ( LL_COMP_GetInputMinus( COMP_OVPx ) == LL_COMP_INPUT_MINUS_DAC1_CH2 ) { R3_2_SetAOReferenceVoltage( LL_DAC_CHANNEL_2, ( uint16_t )( pHandle->pParams_str->DAC_OVP_Threshold ) ); } #endif else { } } /* Output */ LL_COMP_Enable ( COMP_OVPx ); LL_COMP_Lock( COMP_OVPx ); } if (LL_ADC_IsEnabled (ADCx_1) == 0) { R3_2_ADCxInit (ADCx_1); /* Only the Interrupt of the first ADC is enabled. * As Both ADCs are fired by HW at the same moment * It is safe to consider that both conversions are ready at the same time*/ LL_ADC_ClearFlag_JEOS( ADCx_1 ); LL_ADC_EnableIT_JEOS( ADCx_1 ); } else { /* Nothing to do ADCx_1 already configured */ } if (LL_ADC_IsEnabled (ADCx_2) == 0) { R3_2_ADCxInit (ADCx_2); } else { /* Nothing to do ADCx_2 already configured */ } R3_2_TIMxInit( TIMx, &pHandle->_Super ); } } /** * @brief Initializes @p ADCx peripheral for current sensing. * * Specific to F30X, G4XX and H7XX. * * @param ADCx: ADC instance peripheral. */ static void R3_2_ADCxInit( ADC_TypeDef * ADCx ) { if ( LL_ADC_IsInternalRegulatorEnabled(ADCx) == 0u) { /* Enables ADC internal voltage regulator */ LL_ADC_EnableInternalRegulator(ADCx); /* Waits for Regulator Startup time, once for both */ /* Note: Variable divided by 2 to compensate partially */ /* CPU processing cycles, scaling in us split to not */ /* exceed 32 bits register capacity and handle low frequency. */ volatile uint32_t wait_loop_index = ((LL_ADC_DELAY_INTERNAL_REGUL_STAB_US / 10UL) * (SystemCoreClock / (100000UL * 2UL))); while(wait_loop_index != 0UL) { wait_loop_index--; } } LL_ADC_StartCalibration( ADCx, LL_ADC_SINGLE_ENDED ); while ( LL_ADC_IsCalibrationOnGoing( ADCx) == 1u) {} /* Enables ADC (must be done after calibration) */ /* ADC5-140924: Enabling the ADC by setting ADEN bit soon after polling ADCAL=0 * following a calibration phase, could have no effect on ADC * within certain AHB/ADC clock ratio. */ while ( LL_ADC_IsActiveFlag_ADRDY( ADCx ) == 0u) { LL_ADC_Enable( ADCx ); } /* Clears JSQR from CubeMX setting to avoid unwanted conversion*/ LL_ADC_INJ_StartConversion( ADCx ); LL_ADC_INJ_StopConversion(ADCx); /* TODO: check if not already done by MX */ LL_ADC_INJ_SetQueueMode( ADCx, LL_ADC_INJ_QUEUE_2CONTEXTS_END_EMPTY ); } /** * @brief Initializes @p TIMx peripheral with @p pHdl handler for PWM generation. * * Specific to F30X, G4XX and H7XX. * * @param TIMx: Timer instance peripheral. * @param pHdl: Handler of the current instance of the PWM component. */ static void R3_2_TIMxInit( TIM_TypeDef * TIMx, PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ uint32_t Brk2Timeout = 1000; /* disable main TIM counter to ensure * a synchronous start by TIM2 trigger */ LL_TIM_DisableCounter( TIMx ); LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); /* Enables the TIMx Preload on CC1 Register */ LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH1 ); /* Enables the TIMx Preload on CC2 Register */ LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH2 ); /* Enables the TIMx Preload on CC3 Register */ LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH3 ); /* Enables the TIMx Preload on CC4 Register */ LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH4 ); /* Prepare timer for synchronization */ LL_TIM_GenerateEvent_UPDATE( TIMx ); if ( pHandle->pParams_str->FreqRatio == 2u ) { if ( pHandle->pParams_str->IsHigherFreqTim == HIGHER_FREQ ) { if ( pHandle->pParams_str->RepetitionCounter == 3u ) { /* Set TIMx repetition counter to 1 */ LL_TIM_SetRepetitionCounter( TIMx, 1 ); LL_TIM_GenerateEvent_UPDATE( TIMx ); /* Repetition counter will be set to 3 at next Update */ LL_TIM_SetRepetitionCounter( TIMx, 3 ); } } LL_TIM_SetCounter( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) - 1u ); } else /* bFreqRatio equal to 1 or 3 */ { if ( pHandle->_Super.Motor == M1 ) { if ( pHandle->pParams_str->RepetitionCounter == 3u ) { /* Set TIMx repetition counter to 1 */ LL_TIM_SetRepetitionCounter( TIMx, 1 ); LL_TIM_GenerateEvent_UPDATE( TIMx ); /* Repetition counter will be set to 3 at next Update */ LL_TIM_SetRepetitionCounter( TIMx, 3 ); } LL_TIM_SetCounter( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) - 1u ); } else { } } LL_TIM_ClearFlag_BRK( TIMx ); while ((LL_TIM_IsActiveFlag_BRK2 (TIMx) == 1u) && (Brk2Timeout != 0u) ) { LL_TIM_ClearFlag_BRK2( TIMx ); Brk2Timeout--; } LL_TIM_EnableIT_BRK( TIMx ); /* Enable PWM channel */ LL_TIM_CC_EnableChannel( TIMx, TIMxCCER_MASK_CH123 ); } /** * @brief Stores in @p pHdl handler the calibrated @p offsets. * * Absent in H7XX. * * @param pHdl: Handler of the current instance of the PWM component. * @param offsets: Phase offset. */ __weak void R3_2_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 pHandle->PhaseAOffset = offsets->phaseAOffset; pHandle->PhaseBOffset = offsets->phaseBOffset; pHandle->PhaseCOffset = offsets->phaseCOffset; pHdl->offsetCalibStatus = true; } /** * @brief Reads the calibrated @p offsets stored in @p pHdl. * * Absent in H7XX. * * @param pHdl: Handler of the current instance of the PWM component. * @param offsets: Phase offset. */ __weak void R3_2_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 offsets->phaseAOffset = pHandle->PhaseAOffset; offsets->phaseBOffset = pHandle->PhaseBOffset; offsets->phaseCOffset = pHandle->PhaseCOffset; } /** * @brief Stores into the @p pHdl the voltage present on Ia and Ib current * feedback analog channels when no current is flowing into the motor. * * Called R3_2_CurrentReadingCalibration in F4XX, F7XX and L4XX. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_2_CurrentReadingPolarization( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ volatile PWMC_GetPhaseCurr_Cb_t GetPhaseCurrCbSave; volatile PWMC_SetSampPointSectX_Cb_t SetSampPointSectXCbSave; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx_1 = pHandle->pParams_str->ADCDataReg1[0]; ADC_TypeDef * ADCx_2 = pHandle->pParams_str->ADCDataReg2[0]; if (true == pHandle->_Super.offsetCalibStatus) { LL_ADC_INJ_StartConversion( ADCx_1 ); LL_ADC_INJ_StartConversion( ADCx_2 ); } else { /* Save callback routines */ GetPhaseCurrCbSave = pHandle->_Super.pFctGetPhaseCurrents; SetSampPointSectXCbSave = pHandle->_Super.pFctSetADCSampPointSectX; pHandle->PhaseAOffset = 0u; pHandle->PhaseBOffset = 0u; pHandle->PhaseCOffset = 0u; pHandle->PolarizationCounter = 0u; /* It forces inactive level on TIMx CHy and CHyN */ LL_TIM_CC_DisableChannel(TIMx, TIMxCCER_MASK_CH123); /* Offset calibration for all phases */ /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R3_2_HFCurrentsPolarizationAB; pHandle->_Super.pFctSetADCSampPointSectX = &R3_2_SetADCSampPointPolarization; pHandle->ADC_ExternalPolarityInjected = (uint16_t) LL_ADC_INJ_TRIG_EXT_RISING; /* We want to polarize calibration Phase A and Phase B, so we select SECTOR_5 */ pHandle->PolarizationSector=SECTOR_5; /* Required to force first polarization conversion on SECTOR_5*/ pHandle->_Super.Sector = SECTOR_5; R3_2_SwitchOnPWM( &pHandle->_Super ); /* IF CH4 is enabled, it means that JSQR is now configured to sample polarization current*/ //while ( LL_TIM_CC_IsEnabledChannel(TIMx, LL_TIM_CHANNEL_CH4) == 0u ) //{ //} while ( ((TIMx->CR2) & TIM_CR2_MMS_Msk) != LL_TIM_TRGO_OC4REF ) { } /* It is the right time to start the ADC without unwanted conversion */ /* Start ADC to wait for external trigger. This is series dependant*/ LL_ADC_INJ_StartConversion( ADCx_1 ); LL_ADC_INJ_StartConversion( ADCx_2 ); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd( TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter ); R3_2_SwitchOffPWM( &pHandle->_Super ); /* Offset calibration for C phase */ pHandle->PolarizationCounter = 0u; /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R3_2_HFCurrentsPolarizationC; /* We want to polarize Phase C, so we select SECTOR_1 */ pHandle->PolarizationSector=SECTOR_1; /* Required to force first polarization conversion on SECTOR_1*/ pHandle->_Super.Sector = SECTOR_1; R3_2_SwitchOnPWM( &pHandle->_Super ); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd( TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter ); R3_2_SwitchOffPWM( &pHandle->_Super ); pHandle->PhaseAOffset /= NB_CONVERSIONS; pHandle->PhaseBOffset /= NB_CONVERSIONS; pHandle->PhaseCOffset /= NB_CONVERSIONS; if (0U == pHandle->_Super.SWerror) { pHandle->_Super.offsetCalibStatus = true; } else { /* nothing to do */ } /* Change back function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = GetPhaseCurrCbSave; pHandle->_Super.pFctSetADCSampPointSectX = SetSampPointSectXCbSave; } /* It over write TIMx CCRy wrongly written by FOC during calibration so as to force 50% duty cycle on the three inverer legs */ /* Disable TIMx preload */ LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH1); LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH2); LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH3); LL_TIM_OC_SetCompareCH1 (TIMx, pHandle->Half_PWMPeriod); LL_TIM_OC_SetCompareCH2 (TIMx, pHandle->Half_PWMPeriod); LL_TIM_OC_SetCompareCH3 (TIMx, pHandle->Half_PWMPeriod); /* Enable TIMx preload */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH1); LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH2); LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH3); /* It re-enable drive of TIMx CHy and CHyN by TIMx CHyRef*/ LL_TIM_CC_EnableChannel(TIMx, TIMxCCER_MASK_CH123); /* At the end of calibration, all phases are at 50% we will sample A&B */ pHandle->_Super.Sector=SECTOR_5; pHandle->_Super.BrakeActionLock = false; } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__( ( section ( ".ccmram" ) ) ) #endif #endif /** * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p Iab ab_t format. * * @param pHdl: Handler of the current instance of the PWM component. * @param Iab: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ __weak void R3_2_GetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * Iab ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint8_t Sector; int32_t Aux; uint32_t ADCDataReg1; uint32_t ADCDataReg2; Sector = ( uint8_t )pHandle->_Super.Sector; ADCDataReg1 = pHandle->pParams_str->ADCDataReg1[Sector]->JDR1; ADCDataReg2 = pHandle->pParams_str->ADCDataReg2[Sector]->JDR1; /* disable ADC trigger source */ //LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); switch ( Sector ) { case SECTOR_4: case SECTOR_5: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg2 ); /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_6: case SECTOR_1: /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } /* Ia = -Ic -Ib */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->b; /* Ia */ /* Saturation of Ia */ if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else { Iab->a = ( int16_t )Aux; } break; case SECTOR_2: case SECTOR_3: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } /* Ib = -Ic -Ia */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ /* Saturation of Ib */ if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; default: break; } pHandle->_Super.Ia = Iab->a; pHandle->_Super.Ib = Iab->b; pHandle->_Super.Ic = -Iab->a - Iab->b; } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__( ( section ( ".ccmram" ) ) ) #endif #endif /** * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p Iab ab_t format. Specific to overmodulation. * * Absent in H7XX. * * @param pHdl: Handler of the current instance of the PWM component. * @param Iab: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ __weak void R3_2_GetPhaseCurrents_OVM( PWMC_Handle_t * pHdl, ab_t * Iab ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint8_t Sector; int32_t Aux; uint32_t ADCDataReg1; uint32_t ADCDataReg2; /* disable ADC trigger source */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); Sector = ( uint8_t )pHandle->_Super.Sector; ADCDataReg1 = pHandle->pParams_str->ADCDataReg1[Sector]->JDR1; ADCDataReg2 = pHandle->pParams_str->ADCDataReg2[Sector]->JDR1; switch ( Sector ) { case SECTOR_4: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { // Ib not available, use estimated Ib Aux = ( int32_t )( pHandle->_Super.IbEst ); } else { /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg2 ); } /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_5: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { // Ia not available, use estimated Ia Aux = ( int32_t )( pHandle->_Super.IaEst ); } else { Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg2 ); /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_6: /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IcEst ; /* -Ic */ Aux -= ( int32_t )Iab->b; } else { /* Ia = -Ic -Ib */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->b; /* Ia */ } /* Saturation of Ia */ if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else { Iab->a = ( int16_t )Aux; } break; case SECTOR_1: /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IbEst; } else { Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } /* Ia = -Ic -Ib */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->b; /* Ia */ /* Saturation of Ia */ if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else { Iab->a = ( int16_t )Aux; } break; case SECTOR_2: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IaEst; } else { Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } /* Ib = -Ic -Ia */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ /* Saturation of Ib */ if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_3: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { /* Ib = -Ic -Ia */ Aux = ( int32_t ) pHandle->_Super.IcEst; /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ } else { /* Ib = -Ic -Ia */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ } /* Saturation of Ib */ if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; default: break; } pHandle->_Super.Ia = Iab->a; pHandle->_Super.Ib = Iab->b; pHandle->_Super.Ic = -Iab->a - Iab->b; } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__( ( section ( ".ccmram" ) ) ) #endif #endif /** * @brief Configures the ADC for the current sampling during calibration. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. Called R3_2_SetADCSampPointCalibration in F4XX, F7XX and L4XX. * * @param pHdl: Handler of the current instance of the PWM component. * @retval uint16_t Return value of R3_1_WriteTIMRegisters. */ uint16_t R3_2_SetADCSampPointPolarization( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ pHandle->_Super.Sector = pHandle->PolarizationSector; return R3_2_WriteTIMRegisters( &pHandle->_Super, ( pHandle->Half_PWMPeriod - (uint16_t) 1 ) ); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__( ( section ( ".ccmram" ) ) ) #endif #endif /** * @brief Configures the ADC for the current sampling related to sector X (X = [1..6] ). * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval uint16_t Return value of R3_1_WriteTIMRegisters. */ uint16_t R3_2_SetADCSampPointSectX( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ uint16_t SamplingPoint; uint16_t DeltaDuty; /* Verify that sampling is possible in the middle of PWM by checking the smallest duty cycle */ if ( ( uint16_t )( pHandle->Half_PWMPeriod - pHdl->lowDuty ) > pHandle->pParams_str->Tafter ) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled which corresponds * to sector 4 or 5 */ pHandle->_Super.Sector = SECTOR_5; /* set sampling point trigger in the middle of PWM period */ SamplingPoint = pHandle->Half_PWMPeriod - (uint16_t) 1; } else { /* In this case it is necessary to convert phases with Maximum and variable complementary duty cycle.*/ /* ADC Injected sequence configuration. The stator phase with minimum value of complementary duty cycle is set as first. In every sector there is always one phase with maximum complementary duty, one with minimum complementary duty and one with variable complementary duty. In this case, phases with variable complementary duty and with maximum duty are converted and the first will be always the phase with variable complementary duty cycle */ DeltaDuty = ( uint16_t )( pHdl->lowDuty - pHdl->midDuty ); /* Definition of crossing point */ if ( DeltaDuty > ( uint16_t )( pHandle->Half_PWMPeriod - pHdl->lowDuty ) * 2u ) { SamplingPoint = pHdl->lowDuty - pHandle->pParams_str->Tbefore; } else { SamplingPoint = pHdl->lowDuty + pHandle->pParams_str->Tafter; if ( SamplingPoint >= pHandle->Half_PWMPeriod ) { /* ADC trigger edge must be changed from positive to negative */ pHandle->ADC_ExternalPolarityInjected = (uint16_t) LL_ADC_INJ_TRIG_EXT_FALLING; SamplingPoint = ( 2u * pHandle->Half_PWMPeriod ) - SamplingPoint - (uint16_t) 1; } } } return R3_2_WriteTIMRegisters( &pHandle->_Super, SamplingPoint ); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__( ( section ( ".ccmram" ) ) ) #endif #endif /** * @brief Configures the ADC for the current sampling related to sector X (X = [1..6] ) in case of overmodulation. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * Absent in H7XX. * * @param pHdl: Handler of the current instance of the PWM component. * @retval uint16_t Return value of R3_1_WriteTIMRegisters. */ uint16_t R3_2_SetADCSampPointSectX_OVM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ uint16_t SamplingPoint; uint16_t DeltaDuty; pHandle->_Super.useEstCurrent = false; DeltaDuty = ( uint16_t )( pHdl->lowDuty - pHdl->midDuty ); /* case 1 (cf user manual) */ if (( uint16_t )( pHandle->Half_PWMPeriod - pHdl->lowDuty ) > pHandle->pParams_str->Tafter) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled which corresponds * to sector 4 or 5 */ pHandle->_Super.Sector = SECTOR_5; /* set sampling point trigger in the middle of PWM period */ SamplingPoint = pHandle->Half_PWMPeriod - (uint16_t) 1; } else /* case 2 (cf user manual) */ { if (DeltaDuty >= pHandle->pParams_str->Tcase2) { SamplingPoint = pHdl->lowDuty - pHandle->pParams_str->Tbefore; } else { /* case 3 (cf user manual) */ if ((pHandle->Half_PWMPeriod - pHdl->lowDuty) > pHandle->pParams_str->Tcase3) { /* ADC trigger edge must be changed from positive to negative */ pHandle->ADC_ExternalPolarityInjected = (uint16_t) LL_ADC_INJ_TRIG_EXT_FALLING; SamplingPoint = pHdl->lowDuty + pHandle->pParams_str->Tsampling; } else { SamplingPoint = pHandle->Half_PWMPeriod-1; pHandle->_Super.useEstCurrent = true; } } } return R3_2_WriteTIMRegisters( &pHandle->_Super, SamplingPoint ); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__( ( section ( ".ccmram" ) ) ) #endif #endif /* * @brief Writes into peripheral registers the new duty cycle and sampling point. * * @param pHdl: Handler of the current instance of the PWM component. * @param SamplingPoint: Point at which the ADC will be triggered, written in timer clock counts. * @retval uint16_t Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ __STATIC_INLINE uint16_t R3_2_WriteTIMRegisters( PWMC_Handle_t * pHdl, uint16_t SamplingPoint ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint16_t Aux; LL_TIM_OC_SetCompareCH1 ( TIMx, (uint32_t) pHandle->_Super.CntPhA ); LL_TIM_OC_SetCompareCH2 ( TIMx, (uint32_t) pHandle->_Super.CntPhB ); LL_TIM_OC_SetCompareCH3 ( TIMx, (uint32_t) pHandle->_Super.CntPhC ); LL_TIM_OC_SetCompareCH4( TIMx, (uint32_t) SamplingPoint ); /* Limit for update event */ // if ( LL_TIM_CC_IsEnabledChannel(TIMx, LL_TIM_CHANNEL_CH4) == 1u ) if (((TIMx->CR2) & TIM_CR2_MMS_Msk) != LL_TIM_TRGO_RESET ) { Aux = MC_DURATION; } else { Aux = MC_NO_ERROR; } return Aux; } /** * @brief Implementation of PWMC_GetPhaseCurrents to be performed during polarization. * * It sums up injected conversion data into PhaseAOffset and * PhaseBOffset to compute the offset introduced in the current feedback * network. It is required to properly configure ADC inputs before in order to enable * the offset computation. Called R3_2_HFCurrentsCalibrationAB in F4XX, F7XX and L4XX. * * @param pHdl: Handler of the current instance of the PWM component. * @param Iab: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ static void R3_2_HFCurrentsPolarizationAB( PWMC_Handle_t * pHdl, ab_t * Iab ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint32_t ADCDataReg1 = pHandle->pParams_str->ADCDataReg1[pHandle->PolarizationSector]->JDR1; uint32_t ADCDataReg2 = pHandle->pParams_str->ADCDataReg2[pHandle->PolarizationSector]->JDR1; /* disable ADC trigger source */ //LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); if ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { pHandle-> PhaseAOffset += ADCDataReg1; pHandle-> PhaseBOffset += ADCDataReg2; pHandle->PolarizationCounter++; } /* during offset calibration no current is flowing in the phases */ Iab->a = 0; Iab->b = 0; } /** * @brief Implementation of PWMC_GetPhaseCurrents to be performed during polarization. * * It sums up injected conversion data into PhaseCOffset to compute the * offset introduced in the current feedback * network. It is required to proper configure ADC inputs before enabling * the offset computation. Called R3_2_HFCurrentsCalibrationC in F4XX, F7XX and L4XX. * * @param pHdl: Handler of the current instance of the PWM component. * @param Iab: Pointer to the structure that will receive motor current * of phase A and B in ElectricalValue format. */ static void R3_2_HFCurrentsPolarizationC( PWMC_Handle_t * pHdl, ab_t * Iab ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint32_t ADCDataReg2 = pHandle->pParams_str->ADCDataReg2[pHandle->PolarizationSector]->JDR1; /* disable ADC trigger source */ //LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); if ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { /* Phase C is read from SECTOR_1, second value */ pHandle-> PhaseCOffset += ADCDataReg2; pHandle->PolarizationCounter++; } /* during offset calibration no current is flowing in the phases */ Iab->a = 0; Iab->b = 0; } /** * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors of driving section. It has to be * called on each motor start-up when using high voltage drivers. * * @param pHdl: Handler of the current instance of the PWM component. * @param ticks: Timer ticks value to be applied * Min value: 0 (low sides ON) * Max value: PWM_PERIOD_CYCLES/2 (low sides OFF) */ __weak void R3_2_TurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = true; /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( pHandle->pParams_str->TIMx ); /*Turn on the three low side switches */ LL_TIM_OC_SetCompareCH1( TIMx, ticks ); LL_TIM_OC_SetCompareCH2( TIMx, ticks ); LL_TIM_OC_SetCompareCH3( TIMx, ticks ); /* Wait until next update */ while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0u ) {} /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } return; } /** * @brief Enables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_2_SwitchOnPWM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = false; /* Set all duty to 50% */ LL_TIM_OC_SetCompareCH1(TIMx, ((uint32_t) pHandle->Half_PWMPeriod / (uint32_t) 2)); LL_TIM_OC_SetCompareCH2(TIMx, ((uint32_t) pHandle->Half_PWMPeriod / (uint32_t) 2)); LL_TIM_OC_SetCompareCH3(TIMx, ((uint32_t) pHandle->Half_PWMPeriod / (uint32_t) 2)); LL_TIM_OC_SetCompareCH4(TIMx, ((uint32_t) pHandle->Half_PWMPeriod - (uint32_t) 5)); /* wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0u ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE; LL_TIM_EnableAllOutputs ( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { if ( ( TIMx->CCER & TIMxCCER_MASK_CH123 ) != 0u ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Enable Update IRQ */ LL_TIM_EnableIT_UPDATE( TIMx ); } /** * @brief Disables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_2_SwitchOffPWM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* Disable UPDATE ISR */ LL_TIM_DisableIT_UPDATE( TIMx ); pHandle->_Super.TurnOnLowSidesAction = false; /* Main PWM Output Disable */ LL_TIM_DisableAllOutputs( TIMx ); if ( pHandle->_Super.BrakeActionLock == true ) { } else { if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* wait for a new PWM period to flush last HF task */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0u ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__( ( section ( ".ccmram" ) ) ) #endif #endif /** * @brief Contains the TIMx Update event interrupt. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void * R3_2_TIMx_UP_IRQHandler( PWMC_R3_2_Handle_t * pHandle ) { TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; R3_2_OPAMPParams_t const *OPAMPParams = pHandle->pParams_str->OPAMPParams; uint32_t OpampConfig; OPAMP_TypeDef *operationAmp; if ( OPAMPParams != NULL ) { /* We can not change OPAMP source if ADC acquisition is ongoing (Dual motor with internal opamp use case)*/ while (0x0u != pHandle->pParams_str->ADCDataReg1[pHandle->_Super.Sector]->JSQR) {} OpampConfig = OPAMPParams->OPAMPConfig1[pHandle->_Super.Sector]; operationAmp = OPAMPParams->OPAMPSelect_1[pHandle->_Super.Sector]; MODIFY_REG(operationAmp->CSR, OPAMP_CSR_VPSEL, OpampConfig); OpampConfig = OPAMPParams->OPAMPConfig2[pHandle->_Super.Sector]; operationAmp = OPAMPParams->OPAMPSelect_2[pHandle->_Super.Sector]; MODIFY_REG(operationAmp->CSR, OPAMP_CSR_VPSEL, OpampConfig); } pHandle->pParams_str->ADCDataReg1[pHandle->_Super.Sector]->JSQR = pHandle->pParams_str->ADCConfig1[pHandle->_Super.Sector] | (uint32_t) pHandle->ADC_ExternalPolarityInjected; pHandle->pParams_str->ADCDataReg2[pHandle->_Super.Sector]->JSQR = pHandle->pParams_str->ADCConfig2[pHandle->_Super.Sector] | (uint32_t) pHandle->ADC_ExternalPolarityInjected; /* enable ADC trigger source */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_OC4REF); pHandle->ADC_ExternalPolarityInjected = (uint16_t)LL_ADC_INJ_TRIG_EXT_RISING; return &( pHandle->_Super.Motor ); } /** * @brief Configures the analog output used for protection thresholds. * * Specific to F30X, G4XX and H7XX. * * @param DAC_Channel: the selected DAC channel. * This parameter can be: * @arg DAC_Channel_1: DAC Channel1 selected. * @arg DAC_Channel_2: DAC Channel2 selected. * @param hDACVref: Value of DAC reference expressed as 16bit unsigned integer. * Ex. 0 = 0V 65536 = VDD_DAC. */ static void R3_2_SetAOReferenceVoltage( uint32_t DAC_Channel, uint16_t hDACVref ) { LL_DAC_ConvertData12LeftAligned ( DAC1, DAC_Channel, hDACVref ); /* Enable DAC Channel */ LL_DAC_TrigSWConversion ( DAC1, DAC_Channel ); if (LL_DAC_IsEnabled ( DAC1, DAC_Channel ) == 1u ) { /* If DAC is already enable, we wait LL_DAC_DELAY_VOLTAGE_SETTLING_US*/ uint32_t wait_loop_index = ((LL_DAC_DELAY_VOLTAGE_SETTLING_US) * (SystemCoreClock / (1000000UL * 2UL))); while(wait_loop_index != 0UL) { wait_loop_index--; } } else { /* If DAC is not enabled, we must wait LL_DAC_DELAY_STARTUP_VOLTAGE_SETTLING_US*/ LL_DAC_Enable ( DAC1, DAC_Channel ); uint32_t wait_loop_index = ((LL_DAC_DELAY_STARTUP_VOLTAGE_SETTLING_US) * (SystemCoreClock / (1000000UL * 2UL))); while(wait_loop_index != 0UL) { wait_loop_index--; } } } /** * @brief Sets the PWM mode for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_2_RLDetectionModeEnable( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; if ( pHandle->_Super.RLDetectionMode == false ) { /* Channel1 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH1, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH1N ); LL_TIM_OC_SetCompareCH1( TIMx, 0u ); /* Channel2 configuration */ if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_ACTIVE ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_INACTIVE ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else { } /* Channel3 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH3, LL_TIM_OCMODE_PWM2 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3N ); } pHandle->_Super.pFctGetPhaseCurrents = &R3_2_RLGetPhaseCurrents; pHandle->_Super.pFctTurnOnLowSides = &R3_2_RLTurnOnLowSides; pHandle->_Super.pFctSwitchOnPwm = &R3_2_RLSwitchOnPWM; pHandle->_Super.pFctSwitchOffPwm = &R3_2_SwitchOffPWM; pHandle->_Super.RLDetectionMode = true; } /** * @brief Disables the PWM mode for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_2_RLDetectionModeDisable( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; if ( pHandle->_Super.RLDetectionMode == true ) { /* Channel1 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH1, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1 ); if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH1N ); } else { } LL_TIM_OC_SetCompareCH1( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) >> 1 ); /* Channel2 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2 ); if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else { } LL_TIM_OC_SetCompareCH2( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) >> 1 ); /* Channel3 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH3, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH3 ); if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH3N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3N ); } else { } LL_TIM_OC_SetCompareCH3( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) >> 1 ); pHandle->_Super.pFctGetPhaseCurrents = &R3_2_GetPhaseCurrents; pHandle->_Super.pFctTurnOnLowSides = &R3_2_TurnOnLowSides; pHandle->_Super.pFctSwitchOnPwm = &R3_2_SwitchOnPWM; pHandle->_Super.pFctSwitchOffPwm = &R3_2_SwitchOffPWM; pHandle->_Super.RLDetectionMode = false; } } /** * @brief Sets the PWM dutycycle for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. * @param hDuty: Duty cycle to apply, written in uint16_t. * @retval uint16_t Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ uint16_t R3_2_RLDetectionModeSetDuty( PWMC_Handle_t * pHdl, uint16_t hDuty ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint32_t val; uint16_t hAux; val = ( ( uint32_t )( pHandle->Half_PWMPeriod ) * ( uint32_t )( hDuty ) ) >> 16; pHandle->_Super.CntPhA = ( uint16_t )( val ); LL_TIM_OC_SetCompareCH1(TIMx, ( uint32_t )pHandle->_Super.CntPhA); /* set the sector that correspond to Phase A and B sampling */ pHdl->Sector = SECTOR_4; /* Limit for update event */ /* Check the status flag. If an update event has occurred before to set new values of regs the FOC rate is too high */ if (((TIMx->CR2) & TIM_CR2_MMS_Msk) != LL_TIM_TRGO_RESET ) { hAux = MC_DURATION; } else { hAux = MC_NO_ERROR; } if ( pHandle->_Super.SWerror == 1u ) { hAux = MC_DURATION; pHandle->_Super.SWerror = 0u; } return hAux; } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__( ( section ( ".ccmram" ) ) ) #endif #endif /** * @brief Computes and stores into @p pHdl latest converted motor phase currents * during RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ static void R3_2_RLGetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; int32_t wAux; /* disable ADC trigger source */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); wAux = ((int32_t)pHandle->PhaseBOffset) - ((int32_t)(pHandle->pParams_str->ADCDataReg2[pHandle->_Super.Sector]->JDR1)); /* Check saturation */ if ( wAux > -INT16_MAX ) { if ( wAux < INT16_MAX ) { } else { wAux = INT16_MAX; } } else { wAux = -INT16_MAX; } pStator_Currents->a = (int16_t)wAux; pStator_Currents->b = (int16_t)wAux; } /** * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors * of driving section. It has to be called at each motor start-up when * using high voltage drivers. * This function is specific for RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. * @param ticks: Duty cycle of the boot capacitors charge, specific to motor. */ static void R3_2_RLTurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /*Turn on the phase A low side switch */ LL_TIM_OC_SetCompareCH1 ( TIMx, 0u ); /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Wait until next update */ while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } return; } /** * @brief Enables PWM generation on the proper Timer peripheral. * * This function is specific for RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. */ static void R3_2_RLSwitchOnPWM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx_1 = pHandle->pParams_str->ADCDataReg1[0]; ADC_TypeDef * ADCx_2 = pHandle->pParams_str->ADCDataReg2[0]; /* wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); LL_TIM_OC_SetCompareCH1( TIMx, 1u ); LL_TIM_OC_SetCompareCH4( TIMx, ( pHandle->Half_PWMPeriod ) - 5u ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* enable TIMx update interrupt*/ LL_TIM_EnableIT_UPDATE( TIMx ); /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE ; LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { if ( ( TIMx->CCER & TIMxCCER_MASK_CH123 ) != 0u ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* set the sector that correspond to Phase A and B sampling * B will be sampled by ADCx_1 */ pHdl->Sector = SECTOR_4; LL_ADC_INJ_StartConversion( ADCx_1 ); LL_ADC_INJ_StartConversion( ADCx_2 ); return; } /** * @brief Turns on low sides switches and start ADC triggering. * * This function is specific for MP phase. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_2_RLTurnOnLowSidesAndStart( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); LL_TIM_OC_SetCompareCH1( TIMx, 0x0u ); LL_TIM_OC_SetCompareCH2( TIMx, 0x0u ); LL_TIM_OC_SetCompareCH3( TIMx, 0x0u ); LL_TIM_OC_SetCompareCH4( TIMx, ( pHandle->Half_PWMPeriod - 5u)); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE ; LL_TIM_EnableAllOutputs ( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } pHdl->Sector = SECTOR_4; LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH4); LL_TIM_EnableIT_UPDATE( TIMx ); return; } /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
62,502
C
31.069266
176
0.613788
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/F3xx/Src/r3_1_f30x_pwm_curr_fdbk.c
/** ****************************************************************************** * @file r3_1_f30x_pwm_curr_fdbk.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement current sensor * class to be stantiated when the three shunts current sensing * topology is used. * * It is specifically designed for STM32F30X * microcontrollers and implements the successive sampling of two motor * current using only one ADC. * + MCU peripheral and handle initialization function * + three shunt current sensing * + space vector modulation function * + ADC sampling function * ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * * @ingroup R3_1_F30X_pwm_curr_fdbk */ /* Includes ------------------------------------------------------------------*/ #include "r3_1_f30x_pwm_curr_fdbk.h" #include "pwm_common.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** * @defgroup R3_1_pwm_curr_fdbk R3 1 ADC PWM & Current Feedback * * @brief 3-Shunt, 1 ADC, PWM & Current Feedback implementation for F0XX, F30X, F4XX, F7XX, G0XX, G4XX, H5XX, C0XX and L4XX MCUs. * * This component is used in applications based on F0XX, F30X, F4XX, F7XX, G0XX, G4XX, H5XX, C0XX and L4XX MCUs, using a three * shunt resistors current sensing topology and 1 ADC peripheral to acquire the current * values. * * @{ */ /* Private defines -----------------------------------------------------------*/ #define TIMxCCER_MASK_CH123 ((uint16_t) (LL_TIM_CHANNEL_CH1|LL_TIM_CHANNEL_CH1N|\ LL_TIM_CHANNEL_CH2|LL_TIM_CHANNEL_CH2N|\ LL_TIM_CHANNEL_CH3|LL_TIM_CHANNEL_CH3N)) #define CCMR2_CH4_DISABLE 0x8FFFu // /* Private typedef -----------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ static void R3_1_TIMxInit( TIM_TypeDef * TIMx, PWMC_Handle_t * pHdl ); static void R3_1_ADCxInit( ADC_TypeDef * ADCx ); __STATIC_INLINE uint16_t R3_1_WriteTIMRegisters( PWMC_Handle_t * pHdl, uint16_t hCCR4Reg ); static void R3_1_HFCurrentsPolarizationAB( PWMC_Handle_t * pHdl,ab_t * Iab ); static void R3_1_HFCurrentsPolarizationC( PWMC_Handle_t * pHdl, ab_t * Iab ); static void R3_1_SetAOReferenceVoltage( uint32_t DAC_Channel, uint16_t hDACVref ); uint16_t R3_1_SetADCSampPointPolarization( PWMC_Handle_t * pHdl) ; static void R3_1_RLGetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ); static void R3_1_RLTurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ); static void R3_1_RLSwitchOnPWM( PWMC_Handle_t * pHdl ); /** * @brief Initializes TIMx, ADC, GPIO, DMA1 and NVIC for current reading * in three shunt topology one ADC. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void R3_1_Init( PWMC_R3_1_Handle_t * pHandle ) { COMP_TypeDef * COMP_OCPAx = pHandle->pParams_str->CompOCPASelection; COMP_TypeDef * COMP_OCPBx = pHandle->pParams_str->CompOCPBSelection; COMP_TypeDef * COMP_OCPCx = pHandle->pParams_str->CompOCPCSelection; COMP_TypeDef * COMP_OVPx = pHandle->pParams_str->CompOVPSelection; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; /*Check that _Super is the first member of the structure PWMC_R3_1_Handle_t */ if ( ( uint32_t )pHandle == ( uint32_t )&pHandle->_Super ) { /* disable IT and flags in case of LL driver usage * workaround for unwanted interrupt enabling done by LL driver */ LL_ADC_DisableIT_EOC( ADCx ); LL_ADC_ClearFlag_EOC( ADCx ); LL_ADC_DisableIT_JEOC( ADCx ); LL_ADC_ClearFlag_JEOC( ADCx ); if ( TIMx == TIM1 ) { /* TIM1 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph( LL_DBGMCU_APB2_GRP1_TIM1_STOP ); } #ifdef TIM8 else { /* TIM8 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph( LL_DBGMCU_APB2_GRP1_TIM8_STOP ); } #endif /* Over current protection phase A */ if ( COMP_OCPAx != NULL ) { /* Inverting input*/ if ( pHandle->pParams_str->CompOCPAInvInput_MODE != EXT_MODE ) { if ( LL_COMP_GetInputMinus( COMP_OCPAx ) == LL_COMP_INPUT_MINUS_DAC1_CH1 ) { R3_1_SetAOReferenceVoltage( LL_DAC_CHANNEL_1, ( uint16_t )( pHandle->pParams_str->DAC_OCP_Threshold ) ); } #if defined(DAC_CHANNEL2_SUPPORT) else if ( LL_COMP_GetInputMinus( COMP_OCPAx ) == LL_COMP_INPUT_MINUS_DAC1_CH2 ) { R3_1_SetAOReferenceVoltage( LL_DAC_CHANNEL_2, ( uint16_t )( pHandle->pParams_str->DAC_OCP_Threshold ) ); } #endif else { } } /* Output */ LL_COMP_Enable ( COMP_OCPAx ); LL_COMP_Lock( COMP_OCPAx ); } /* Over current protection phase B */ if ( COMP_OCPBx != NULL ) { LL_COMP_Enable ( COMP_OCPBx ); LL_COMP_Lock( COMP_OCPBx ); } /* Over current protection phase C */ if ( COMP_OCPCx != NULL ) { LL_COMP_Enable ( COMP_OCPCx ); LL_COMP_Lock( COMP_OCPCx ); } /* Over voltage protection */ if ( COMP_OVPx != NULL ) { /* Inverting input*/ if ( pHandle->pParams_str->CompOVPInvInput_MODE != EXT_MODE ) { if ( LL_COMP_GetInputMinus( COMP_OVPx ) == LL_COMP_INPUT_MINUS_DAC1_CH1 ) { R3_1_SetAOReferenceVoltage( LL_DAC_CHANNEL_1, ( uint16_t )( pHandle->pParams_str->DAC_OVP_Threshold ) ); } #if defined(DAC_CHANNEL2_SUPPORT) else if ( LL_COMP_GetInputMinus( COMP_OVPx ) == LL_COMP_INPUT_MINUS_DAC1_CH2 ) { R3_1_SetAOReferenceVoltage( LL_DAC_CHANNEL_2, ( uint16_t )( pHandle->pParams_str->DAC_OVP_Threshold ) ); } #endif else { } } /* Output */ LL_COMP_Enable ( COMP_OVPx ); LL_COMP_Lock( COMP_OVPx ); } if (LL_ADC_IsEnabled (ADCx) == 0) { R3_1_ADCxInit (ADCx); /* Only the Interrupt of the first ADC is enabled. * As Both ADCs are fired by HW at the same moment * It is safe to consider that both conversion are ready at the same time*/ LL_ADC_ClearFlag_JEOS( ADCx ); LL_ADC_EnableIT_JEOS( ADCx ); } else { /* Nothing to do ADCx_1 already configured */ } R3_1_TIMxInit( TIMx, &pHandle->_Super ); } } /** * @brief Initializes @p ADCx peripheral for current sensing. * * Specific to F30X and G4XX. * * @param ADCx: ADC instance peripheral */ static void R3_1_ADCxInit( ADC_TypeDef * ADCx ) { if ( LL_ADC_IsInternalRegulatorEnabled(ADCx) == 0u) { /* Enable ADC internal voltage regulator */ LL_ADC_EnableInternalRegulator(ADCx); /* Wait for Regulator Startup time */ /* Note: Variable divided by 2 to compensate partially */ /* CPU processing cycles, scaling in us split to not */ /* exceed 32 bits register capacity and handle low frequency. */ volatile uint32_t wait_loop_index = ((LL_ADC_DELAY_INTERNAL_REGUL_STAB_US / 10UL) * (SystemCoreClock / (100000UL * 2UL))); while(wait_loop_index != 0UL) { wait_loop_index--; } } LL_ADC_StartCalibration( ADCx, LL_ADC_SINGLE_ENDED ); while ( LL_ADC_IsCalibrationOnGoing( ADCx) == 1u) {} /* ADC Enable (must be done after calibration) */ /* ADC5-140924: Enabling the ADC by setting ADEN bit soon after polling ADCAL=0 * following a calibration phase, could have no effect on ADC * within certain AHB/ADC clock ratio. */ while ( LL_ADC_IsActiveFlag_ADRDY( ADCx ) == 0u) { LL_ADC_Enable( ADCx ); } /* Clear JSQR from CubeMX setting to avoid not wanting conversion*/ LL_ADC_INJ_StartConversion( ADCx ); LL_ADC_INJ_StopConversion(ADCx); /* TODO: check if not already done by MX */ LL_ADC_INJ_SetQueueMode( ADCx, LL_ADC_INJ_QUEUE_2CONTEXTS_END_EMPTY ); } /** * @brief It initializes TIMx peripheral for PWM generation. * * Specific to F30X and G4XX. * * @param TIMx: Timer to be initialized. * @param pHdl: Handler of the current instance of the PWM component. */ static void R3_1_TIMxInit( TIM_TypeDef * TIMx, PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ uint32_t Brk2Timeout = 1000; /* disable main TIM counter to ensure * a synchronous start by TIM2 trigger */ LL_TIM_DisableCounter( TIMx ); LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); /* Enables the TIMx Preload on CC1 Register */ LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH1 ); /* Enables the TIMx Preload on CC2 Register */ LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH2 ); /* Enables the TIMx Preload on CC3 Register */ LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH3 ); /* Enables the TIMx Preload on CC4 Register */ LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH4 ); /* Prepare timer for synchronization */ LL_TIM_GenerateEvent_UPDATE( TIMx ); if ( pHandle->pParams_str->FreqRatio == 2u ) { if ( pHandle->pParams_str->IsHigherFreqTim == HIGHER_FREQ ) { if ( pHandle->pParams_str->RepetitionCounter == 3u ) { /* Set TIMx repetition counter to 1 */ LL_TIM_SetRepetitionCounter( TIMx, 1 ); LL_TIM_GenerateEvent_UPDATE( TIMx ); /* Repetition counter will be set to 3 at next Update */ LL_TIM_SetRepetitionCounter( TIMx, 3 ); } } LL_TIM_SetCounter( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) - 1u ); } else /* bFreqRatio equal to 1 or 3 */ { if ( pHandle->_Super.Motor == M1 ) { if ( pHandle->pParams_str->RepetitionCounter == 1u ) { LL_TIM_SetCounter( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) - 1u ); } else if ( pHandle->pParams_str->RepetitionCounter == 3u ) { /* Set TIMx repetition counter to 1 */ LL_TIM_SetRepetitionCounter( TIMx, 1 ); LL_TIM_GenerateEvent_UPDATE( TIMx ); /* Repetition counter will be set to 3 at next Update */ LL_TIM_SetRepetitionCounter( TIMx, 3 ); } else { } } else { } } LL_TIM_ClearFlag_BRK( TIMx ); while ((LL_TIM_IsActiveFlag_BRK2 (TIMx) == 1u) && (Brk2Timeout != 0u) ) { LL_TIM_ClearFlag_BRK2( TIMx ); Brk2Timeout--; } LL_TIM_EnableIT_BRK( TIMx ); /* Enable PWM channel */ LL_TIM_CC_EnableChannel( TIMx, TIMxCCER_MASK_CH123 ); } /** * @brief Stores in @p pHdl handler the calibrated @p offsets. * * @param pHdl: Handler of the current instance of the PWM component. * @param offsets: Phase offset. */ __weak void R3_1_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 pHandle->PhaseAOffset = offsets->phaseAOffset; pHandle->PhaseBOffset = offsets->phaseBOffset; pHandle->PhaseCOffset = offsets->phaseCOffset; pHdl->offsetCalibStatus = true; } /** * @brief Reads the calibrated @p offsets stored in @p pHdl. * * @param pHdl: Handler of the current instance of the PWM component. * @param offsets: Phase offset. */ __weak void R3_1_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 offsets->phaseAOffset = pHandle->PhaseAOffset; offsets->phaseBOffset = pHandle->PhaseBOffset; offsets->phaseCOffset = pHandle->PhaseCOffset; } /** * @brief Stores into the @p pHdl the voltage present on Ia and Ib current * feedback analog channels when no current is flowing into the motor. * * Called R3_1_CurrentReadingCalibration in every other MCU except for G4XX. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_1_CurrentReadingPolarization( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; volatile PWMC_GetPhaseCurr_Cb_t GetPhaseCurrCbSave; volatile PWMC_SetSampPointSectX_Cb_t SetSampPointSectXCbSave; if (false == pHandle->_Super.offsetCalibStatus) { /* Save callback routines */ GetPhaseCurrCbSave = pHandle->_Super.pFctGetPhaseCurrents; SetSampPointSectXCbSave = pHandle->_Super.pFctSetADCSampPointSectX; pHandle->PhaseAOffset = 0u; pHandle->PhaseBOffset = 0u; pHandle->PhaseCOffset = 0u; pHandle->PolarizationCounter = 0u; /* It forces inactive level on TIMx CHy and CHyN */ LL_TIM_CC_DisableChannel(TIMx, TIMxCCER_MASK_CH123); /* Offset calibration for all phases */ /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R3_1_HFCurrentsPolarizationAB; pHandle->_Super.pFctSetADCSampPointSectX = &R3_1_SetADCSampPointPolarization; pHandle->ADC_ExternalPolarityInjected = (uint16_t) LL_ADC_INJ_TRIG_EXT_RISING; /* We want to polarize calibration Phase A and Phase B, so we select SECTOR_5 */ pHandle->PolarizationSector=SECTOR_5; /* Required to force first polarization conversion on SECTOR_5*/ pHandle->_Super.Sector = SECTOR_5; R3_1_SwitchOnPWM( &pHandle->_Super ); /* IF CH4 is enabled, it means that JSQR is now configured to sample polarization current*/ //while ( LL_TIM_CC_IsEnabledChannel(TIMx, LL_TIM_CHANNEL_CH4) == 0u ) //{ //} while ( ((TIMx->CR2) & TIM_CR2_MMS_Msk) != LL_TIM_TRGO_OC4REF ) { } /* It is the right time to start the ADC without unwanted conversion */ /* Start ADC to wait for external trigger. This is series dependant*/ LL_ADC_INJ_StartConversion( ADCx ); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd( TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter ); R3_1_SwitchOffPWM( &pHandle->_Super ); /* Offset calibration for C phase */ pHandle->PolarizationCounter = 0u; /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R3_1_HFCurrentsPolarizationC; /* We want to polarize Phase C, so we select SECTOR_1 */ pHandle->PolarizationSector=SECTOR_1; /* Required to force first polarization conversion on SECTOR_1*/ pHandle->_Super.Sector = SECTOR_1; R3_1_SwitchOnPWM( &pHandle->_Super ); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd( TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter ); R3_1_SwitchOffPWM( &pHandle->_Super ); pHandle->PhaseAOffset /= NB_CONVERSIONS; pHandle->PhaseBOffset /= NB_CONVERSIONS; pHandle->PhaseCOffset /= NB_CONVERSIONS; if (0U == pHandle->_Super.SWerror) { pHandle->_Super.offsetCalibStatus = true; } else { /* nothing to do */ } /* restore function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = GetPhaseCurrCbSave; pHandle->_Super.pFctSetADCSampPointSectX = SetSampPointSectXCbSave; } /* It over write TIMx CCRy wrongly written by FOC during calibration so as to force 50% duty cycle on the three inverer legs */ /* Disable TIMx preload */ LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH1); LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH2); LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH3); LL_TIM_OC_SetCompareCH1 (TIMx, pHandle->Half_PWMPeriod); LL_TIM_OC_SetCompareCH2 (TIMx, pHandle->Half_PWMPeriod); LL_TIM_OC_SetCompareCH3 (TIMx, pHandle->Half_PWMPeriod); /* Enable TIMx preload */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH1); LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH2); LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH3); /* It re-enable drive of TIMx CHy and CHyN by TIMx CHyRef*/ LL_TIM_CC_EnableChannel(TIMx, TIMxCCER_MASK_CH123); /* At the end of calibration, all phases are at 50% we will sample A&B */ pHandle->_Super.Sector=SECTOR_5; pHandle->_Super.BrakeActionLock = false; } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__( ( section ( ".ccmram" ) ) ) #endif #endif /** * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p Iab ab_t format. * * @param pHdl: Handler of the current instance of the PWM component. * @param Iab: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ __weak void R3_1_GetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * Iab ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; uint8_t Sector; int32_t Aux; uint32_t ADCDataReg1; uint32_t ADCDataReg2; Sector = ( uint8_t )pHandle->_Super.Sector; ADCDataReg1 = ADCx->JDR1; ADCDataReg2 = ADCx->JDR2; /* disable ADC trigger source */ //LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); switch ( Sector ) { case SECTOR_4: case SECTOR_5: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg2 ); /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_6: case SECTOR_1: /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } /* Ia = -Ic -Ib */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->b; /* Ia */ /* Saturation of Ia */ if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else { Iab->a = ( int16_t )Aux; } break; case SECTOR_2: case SECTOR_3: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } /* Ib = -Ic -Ia */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ /* Saturation of Ib */ if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; default: break; } pHandle->_Super.Ia = Iab->a; pHandle->_Super.Ib = Iab->b; pHandle->_Super.Ic = -Iab->a - Iab->b; } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__( ( section ( ".ccmram" ) ) ) #endif #endif /** * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p Iab ab_t format. Specific to overmodulation. * * @param pHdl: Handler of the current instance of the PWM component. * @param Iab: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ __weak void R3_1_GetPhaseCurrents_OVM( PWMC_Handle_t * pHdl, ab_t * Iab ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; uint8_t Sector; int32_t Aux; uint32_t ADCDataReg1; uint32_t ADCDataReg2; /* disable ADC trigger source */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); Sector = ( uint8_t )pHandle->_Super.Sector; ADCDataReg1 = ADCx->JDR1; ADCDataReg2 = ADCx->JDR2; switch ( Sector ) { case SECTOR_4: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { // Ib not available, use estimated Ib Aux = ( int32_t )( pHandle->_Super.IbEst ); } else { /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg2 ); } /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_5: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { // Ia not available, use estimated Ia Aux = ( int32_t )( pHandle->_Super.IaEst ); } else { Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg2 ); /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_6: /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IcEst ; /* -Ic */ Aux -= ( int32_t )Iab->b; } else { /* Ia = -Ic -Ib */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->b; /* Ia */ } /* Saturation of Ia */ if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else { Iab->a = ( int16_t )Aux; } break; case SECTOR_1: /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IbEst; } else { Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } /* Ia = -Ic -Ib */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->b; /* Ia */ /* Saturation of Ia */ if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else { Iab->a = ( int16_t )Aux; } break; case SECTOR_2: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IaEst; } else { Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } /* Ib = -Ic -Ia */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ /* Saturation of Ib */ if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_3: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { /* Ib = -Ic -Ia */ Aux = ( int32_t ) pHandle->_Super.IcEst; /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ } else { /* Ib = -Ic -Ia */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ } /* Saturation of Ib */ if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; default: break; } pHandle->_Super.Ia = Iab->a; pHandle->_Super.Ib = Iab->b; pHandle->_Super.Ic = -Iab->a - Iab->b; } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__( ( section ( ".ccmram" ) ) ) #endif #endif /** * @brief Configures the ADC for the current sampling during calibration. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. Called R3_1_SetADCSampPointCalibration in every other MCU. * * @param pHdl: Handler of the current instance of the PWM component. * @retval uint16_t Returns the return value of R3_1_WriteTIMRegisters. */ uint16_t R3_1_SetADCSampPointPolarization( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ pHandle->_Super.Sector = pHandle->PolarizationSector; return R3_1_WriteTIMRegisters( &pHandle->_Super, ( pHandle->Half_PWMPeriod - (uint16_t) 1 ) ); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__( ( section ( ".ccmram" ) ) ) #endif #endif /** * @brief Configures the ADC for the current sampling related to sector X (X = [1..6] ). * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval uint16_t Returns the return value of R3_1_WriteTIMRegisters. */ uint16_t R3_1_SetADCSampPointSectX( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ uint16_t SamplingPoint; uint16_t DeltaDuty; /* Verify that sampling is possible in the middle of PWM by checking the smallest duty cycle */ if ( ( uint16_t )( pHandle->Half_PWMPeriod - pHdl->lowDuty ) > pHandle->pParams_str->Tafter ) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled which corresponds * to sector 4 or 5 */ pHandle->_Super.Sector = SECTOR_5; /* set sampling point trigger in the middle of PWM period */ SamplingPoint = pHandle->Half_PWMPeriod - (uint16_t) 1; } else { /* In this case it is necessary to convert phases with Maximum and variable complementary duty cycle.*/ /* ADC Injected sequence configuration. The stator phase with minimum value of complementary duty cycle is set as first. In every sector there is always one phase with maximum complementary duty, one with minimum complementary duty and one with variable complementary duty. In this case, phases with variable complementary duty and with maximum duty are converted and the first will be always the phase with variable complementary duty cycle */ DeltaDuty = ( uint16_t )( pHdl->lowDuty - pHdl->midDuty ); /* Definition of crossing point */ if ( DeltaDuty > ( uint16_t )( pHandle->Half_PWMPeriod - pHdl->lowDuty ) * 2u ) { SamplingPoint = pHdl->lowDuty - pHandle->pParams_str->Tbefore; } else { SamplingPoint = pHdl->lowDuty + pHandle->pParams_str->Tafter; if ( SamplingPoint >= pHandle->Half_PWMPeriod ) { /* ADC trigger edge must be changed from positive to negative */ pHandle->ADC_ExternalPolarityInjected = (uint16_t) LL_ADC_INJ_TRIG_EXT_FALLING; SamplingPoint = ( 2u * pHandle->Half_PWMPeriod ) - SamplingPoint - (uint16_t) 1; } } } return R3_1_WriteTIMRegisters( &pHandle->_Super, SamplingPoint ); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__( ( section ( ".ccmram" ) ) ) #endif #endif /** * @brief Configures the ADC for the current sampling related to sector X (X = [1..6] ) in case of overmodulation. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval uint16_t Returns the return value of R3_1_WriteTIMRegisters. */ uint16_t R3_1_SetADCSampPointSectX_OVM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ uint16_t SamplingPoint; uint16_t DeltaDuty; pHandle->_Super.useEstCurrent = false; DeltaDuty = ( uint16_t )( pHdl->lowDuty - pHdl->midDuty ); /* case 1 (cf user manual) */ if (( uint16_t )( pHandle->Half_PWMPeriod - pHdl->lowDuty ) > pHandle->pParams_str->Tafter) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled which corresponds * to sector 4 or 5 */ pHandle->_Super.Sector = SECTOR_5; /* set sampling point trigger in the middle of PWM period */ SamplingPoint = pHandle->Half_PWMPeriod - (uint16_t) 1; } else /* case 2 (cf user manual) */ { if (DeltaDuty >= pHandle->pParams_str->Tcase2) { SamplingPoint = pHdl->lowDuty - pHandle->pParams_str->Tbefore; } else { /* case 3 (cf user manual) */ if ((pHandle->Half_PWMPeriod - pHdl->lowDuty) > pHandle->pParams_str->Tcase3) { /* ADC trigger edge must be changed from positive to negative */ pHandle->ADC_ExternalPolarityInjected = (uint16_t) LL_ADC_INJ_TRIG_EXT_FALLING; SamplingPoint = pHdl->lowDuty + pHandle->pParams_str->Tsampling; } else { SamplingPoint = pHandle->Half_PWMPeriod-1; pHandle->_Super.useEstCurrent = true; } } } return R3_1_WriteTIMRegisters( &pHandle->_Super, SamplingPoint ); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__( ( section ( ".ccmram" ) ) ) #endif #endif /** * @brief Writes into peripheral registers the new duty cycle and sampling point. * * @param pHdl: Handler of the current instance of the PWM component. * @param SamplingPoint: Point at which the ADC will be triggered, written in timer clock counts. * @retval uint16_t Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ __STATIC_INLINE uint16_t R3_1_WriteTIMRegisters( PWMC_Handle_t * pHdl, uint16_t SamplingPoint ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint16_t Aux; LL_TIM_OC_SetCompareCH1 ( TIMx, (uint32_t) pHandle->_Super.CntPhA ); LL_TIM_OC_SetCompareCH2 ( TIMx, (uint32_t) pHandle->_Super.CntPhB ); LL_TIM_OC_SetCompareCH3 ( TIMx, (uint32_t) pHandle->_Super.CntPhC ); LL_TIM_OC_SetCompareCH4( TIMx, (uint32_t) SamplingPoint ); /* Limit for update event */ // if ( LL_TIM_CC_IsEnabledChannel(TIMx, LL_TIM_CHANNEL_CH4) == 1u ) if (((TIMx->CR2) & TIM_CR2_MMS_Msk) != LL_TIM_TRGO_RESET ) { Aux = MC_DURATION; } else { Aux = MC_NO_ERROR; } return Aux; } /** * @brief Implementation of PWMC_GetPhaseCurrents to be performed during polarization. * * It sums up injected conversion data into PhaseAOffset and * PhaseBOffset to compute the offset introduced in the current feedback * network. It is required to properly configure ADC inputs before in order to enable * the offset computation. Called R3_1_HFCurrentsCalibrationAB in every other MCU except for G4XX. * * @param pHdl: Handler of the current instance of the PWM component. * @param Iab: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ static void R3_1_HFCurrentsPolarizationAB( PWMC_Handle_t * pHdl, ab_t * Iab ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; uint32_t ADCDataReg1 = ADCx->JDR1; uint32_t ADCDataReg2 = ADCx->JDR2; /* disable ADC trigger source */ //LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); if ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { pHandle-> PhaseAOffset += ADCDataReg1; pHandle-> PhaseBOffset += ADCDataReg2; pHandle->PolarizationCounter++; } /* during offset calibration no current is flowing in the phases */ Iab->a = 0; Iab->b = 0; } /** * @brief Implementation of PWMC_GetPhaseCurrents to be performed during polarization. * * It sums up injected conversion data into PhaseCOffset to compute the offset * introduced in the current feedback network. It is required to properly configure * ADC inputs before in order to enable offset computation. Called R3_1_HFCurrentsCalibrationC in every other MCU. * * @param pHdl: Handler of the current instance of the PWM component. * @param Iab: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ static void R3_1_HFCurrentsPolarizationC( PWMC_Handle_t * pHdl, ab_t * Iab ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; uint32_t ADCDataReg2 = ADCx->JDR2; /* disable ADC trigger source */ //LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); if ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { /* Phase C is read from SECTOR_1, second value */ pHandle-> PhaseCOffset += ADCDataReg2; pHandle->PolarizationCounter++; } /* during offset calibration no current is flowing in the phases */ Iab->a = 0; Iab->b = 0; } /** * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors of driving section. It has to be * called on each motor start-up when using high voltage drivers. * * @param pHdl: Handler of the current instance of the PWM component. * @param ticks: Timer ticks value to be applied * Min value: 0 (low sides ON) * Max value: PWM_PERIOD_CYCLES/2 (low sides OFF) */ __weak void R3_1_TurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = true; /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( pHandle->pParams_str->TIMx ); /*Turn on the three low side switches */ LL_TIM_OC_SetCompareCH1( TIMx, ticks ); LL_TIM_OC_SetCompareCH2( TIMx, ticks ); LL_TIM_OC_SetCompareCH3( TIMx, ticks ); /* Wait until next update */ while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0u ) {} /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } return; } /** * @brief Enables PWM generation on the proper Timer peripheral. * * This function is specific for RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_1_SwitchOnPWM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = false; /* Set all duty to 50% */ LL_TIM_OC_SetCompareCH1(TIMx, ((uint32_t) pHandle->Half_PWMPeriod / (uint32_t) 2)); LL_TIM_OC_SetCompareCH2(TIMx, ((uint32_t) pHandle->Half_PWMPeriod / (uint32_t) 2)); LL_TIM_OC_SetCompareCH3(TIMx, ((uint32_t) pHandle->Half_PWMPeriod / (uint32_t) 2)); LL_TIM_OC_SetCompareCH4(TIMx, ((uint32_t) pHandle->Half_PWMPeriod - (uint32_t) 5)); /* wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0u ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE; LL_TIM_EnableAllOutputs ( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { if ( ( TIMx->CCER & TIMxCCER_MASK_CH123 ) != 0u ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Enable Update IRQ */ LL_TIM_EnableIT_UPDATE( TIMx ); } /** * @brief Disables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_1_SwitchOffPWM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* Disable UPDATE ISR */ LL_TIM_DisableIT_UPDATE( TIMx ); pHandle->_Super.TurnOnLowSidesAction = false; /* Main PWM Output Disable */ LL_TIM_DisableAllOutputs( TIMx ); if ( pHandle->_Super.BrakeActionLock == true ) { } else { if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* wait for a new PWM period to flush last HF task */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0u ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__( ( section ( ".ccmram" ) ) ) #endif #endif /** * @brief Contains the TIMx Update event interrupt. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void * R3_1_TIMx_UP_IRQHandler( PWMC_R3_1_Handle_t * pHandle ) { TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; ADCx->JSQR = pHandle->pParams_str->ADCConfig[pHandle->_Super.Sector] | ((uint32_t) pHandle->ADC_ExternalPolarityInjected); /* enable ADC trigger source */ //LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH4); LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_OC4REF); pHandle->ADC_ExternalPolarityInjected = (uint16_t)LL_ADC_INJ_TRIG_EXT_RISING; return &( pHandle->_Super.Motor ); } /** * @brief Configures the analog output used for protection thresholds. * * Specific to F30X and G4XX. * * @param DAC_Channel: the selected DAC channel. * This parameter can be: * @arg DAC_Channel_1: DAC Channel1 selected. * @arg DAC_Channel_2: DAC Channel2 selected. * @param hDACVref: Value of DAC reference expressed as 16bit unsigned integer. * Ex. 0 = 0V 65536 = VDD_DAC. */ static void R3_1_SetAOReferenceVoltage( uint32_t DAC_Channel, uint16_t hDACVref ) { LL_DAC_ConvertData12LeftAligned ( DAC1, DAC_Channel, hDACVref ); /* Enable DAC Channel */ LL_DAC_TrigSWConversion ( DAC1, DAC_Channel ); if (LL_DAC_IsEnabled ( DAC1, DAC_Channel ) == 1u ) { /* If DAC is already enable, we wait LL_DAC_DELAY_VOLTAGE_SETTLING_US*/ uint32_t wait_loop_index = ((LL_DAC_DELAY_VOLTAGE_SETTLING_US) * (SystemCoreClock / (1000000UL * 2UL))); while(wait_loop_index != 0UL) { wait_loop_index--; } } else { /* If DAC is not enabled, we must wait LL_DAC_DELAY_STARTUP_VOLTAGE_SETTLING_US*/ LL_DAC_Enable ( DAC1, DAC_Channel ); uint32_t wait_loop_index = ((LL_DAC_DELAY_STARTUP_VOLTAGE_SETTLING_US) * (SystemCoreClock / (1000000UL * 2UL))); while(wait_loop_index != 0UL) { wait_loop_index--; } } } /** * @brief Sets the PWM mode for R/L detection. * * Specific to F30X, F4XX, L4XX and G4XX. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_1_RLDetectionModeEnable( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; if ( pHandle->_Super.RLDetectionMode == false ) { /* Channel1 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH1, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH1N ); LL_TIM_OC_SetCompareCH1( TIMx, 0u ); /* Channel2 configuration */ if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_ACTIVE ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_INACTIVE ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else { } /* Channel3 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH3, LL_TIM_OCMODE_PWM2 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3N ); } pHandle->_Super.pFctGetPhaseCurrents = &R3_1_RLGetPhaseCurrents; pHandle->_Super.pFctTurnOnLowSides = &R3_1_RLTurnOnLowSides; pHandle->_Super.pFctSwitchOnPwm = &R3_1_RLSwitchOnPWM; pHandle->_Super.pFctSwitchOffPwm = &R3_1_SwitchOffPWM; pHandle->_Super.RLDetectionMode = true; } /** * @brief Disables the PWM mode for R/L detection. * * Specific to F30X, F4XX, L4XX and G4XX. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_1_RLDetectionModeDisable( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; if ( pHandle->_Super.RLDetectionMode == true ) { /* Repetition Counter of TIM1 User value reactivation BEGIN*/ /* The folowing while cycles ensure the identification of the positive counting mode of TIM1 * for correct reactivation of Repetition Counter value of TIM1.*/ /* Wait the change of Counter Direction of TIM1 from Up-Direction to Down-Direction*/ while ( ( TIMx->CR1 & TIM_CR1_DIR_Msk ) == LL_TIM_COUNTERMODE_UP ) { } /* Wait the change of Counter Direction of TIM1 from Down-Direction to Up-Direction.*/ while ( ( TIMx->CR1 & TIM_CR1_DIR_Msk ) == LL_TIM_COUNTERMODE_DOWN ) { } /* Repetition Counter of TIM1 User value reactivation END*/ /* Channel1 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH1, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1 ); if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH1N ); } else { } LL_TIM_OC_SetCompareCH1( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) >> 1 ); /* Channel2 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2 ); if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else { } LL_TIM_OC_SetCompareCH2( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) >> 1 ); /* Channel3 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH3, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH3 ); if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH3N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3N ); } else { } LL_TIM_OC_SetCompareCH3( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) >> 1 ); /* ADCx Injected discontinuous mode disable */ LL_ADC_INJ_SetSequencerDiscont( pHandle->pParams_str->ADCx, LL_ADC_INJ_SEQ_DISCONT_DISABLE ); pHandle->_Super.pFctGetPhaseCurrents = &R3_1_GetPhaseCurrents; pHandle->_Super.pFctTurnOnLowSides = &R3_1_TurnOnLowSides; pHandle->_Super.pFctSwitchOnPwm = &R3_1_SwitchOnPWM; pHandle->_Super.pFctSwitchOffPwm = &R3_1_SwitchOffPWM; pHandle->_Super.RLDetectionMode = false; } } /** * @brief Sets the PWM dutycycle for R/L detection. * * Specific to F30X, F4XX, L4XX and G4XX. * * @param pHdl: Handler of the current instance of the PWM component. * @param hDuty: Duty cycle to apply, written in uint16_t. * @retval uint16_t Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ uint16_t R3_1_RLDetectionModeSetDuty( PWMC_Handle_t * pHdl, uint16_t hDuty ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint32_t val; uint16_t hAux; val = ( ( uint32_t )( pHandle->Half_PWMPeriod ) * ( uint32_t )( hDuty ) ) >> 16; pHandle->_Super.CntPhA = ( uint16_t )( val ); /* set sector in order to sample phase B */ pHandle->_Super.Sector = SECTOR_4; /* TIM1 Channel 1 Duty Cycle configuration. * In RL Detection mode only the Up-side device of Phase A are controlled*/ LL_TIM_OC_SetCompareCH1(TIMx, ( uint32_t )pHandle->_Super.CntPhA); /* Limit for update event */ /* If an update event has occurred before to set new values of regs the FOC rate is too high */ if (((TIMx->CR2) & TIM_CR2_MMS_Msk) != LL_TIM_TRGO_RESET ) { hAux = MC_DURATION; } else { hAux = MC_NO_ERROR; } if ( pHandle->_Super.SWerror == 1u ) { hAux = MC_DURATION; pHandle->_Super.SWerror = 0u; } return hAux; } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__( ( section ( ".ccmram" ) ) ) #endif #endif /** * @brief Computes and stores into @p pHandle latest converted motor phase currents * during RL detection phase. * * Specific to F30X, F4XX, L4XX and G4XX. * * @param pHdl: Handler of the current instance of the PWM component. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ static void R3_1_RLGetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; int32_t wAux; /* disable ADC trigger source */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); wAux = (int32_t)( pHandle->PhaseBOffset ) - ADCx->JDR2; /* Check saturation */ if ( wAux > -INT16_MAX ) { if ( wAux < INT16_MAX ) { } else { wAux = INT16_MAX; } } else { wAux = -INT16_MAX; } pStator_Currents->a = (int16_t)wAux; pStator_Currents->b = (int16_t)wAux; } /** * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors * of driving section. It has to be called at each motor start-up when * using high voltage drivers. * This function is specific for RL detection phase. Specific to F30X, F4XX, L4XX and G4XX. * * @param pHdl: Handler of the current instance of the PWM component. * @param ticks: Duty cycle of the boot capacitors charge, specific to motor. */ static void R3_1_RLTurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /*Turn on the phase A low side switch */ LL_TIM_OC_SetCompareCH1 ( TIMx, 0u ); /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Wait until next update */ while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } return; } /** * @brief Enables PWM generation on the proper Timer peripheral. * * This function is specific for RL detection phase. Specific to F30X, F4XX, L4XX and G4XX. * * @param pHdl: Handler of the current instance of the PWM component. */ static void R3_1_RLSwitchOnPWM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; pHandle->_Super.TurnOnLowSidesAction = false; /* The folowing while cycles ensure the identification of the nergative counting mode of TIM1 * for correct modification of Repetition Counter value of TIM1.*/ /* Wait the change of Counter Direction of TIM1 from Down-Direction to Up-Direction*/ while ( ( TIMx->CR1 & TIM_CR1_DIR_Msk ) == LL_TIM_COUNTERMODE_DOWN ) { } /* Wait the change of Counter Direction of TIM1 from Up-Direction to Down-Direction*/ while ( ( TIMx->CR1 & TIM_CR1_DIR_Msk ) == LL_TIM_COUNTERMODE_UP ) { } /* Set channel 1 Compare/Capture register to 1 */ LL_TIM_OC_SetCompareCH1(TIMx, 1u); /* Set channel 4 Compare/Capture register to trig ADC in the middle of the PWM period */ LL_TIM_OC_SetCompareCH4(TIMx,(( uint32_t )( pHandle->Half_PWMPeriod ) - 5u)); LL_TIM_ClearFlag_UPDATE( TIMx ); /* Clear flag to wait next update */ while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE; LL_TIM_EnableAllOutputs(TIMx); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { if ( ( TIMx->CCER & TIMxCCER_MASK_CH123 ) != 0u ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* set the sector that correspond to Phase A and B sampling * B will be sampled by ADCx_1 */ pHdl->Sector = SECTOR_4; LL_ADC_INJ_StartConversion( ADCx ); /* enable TIMx update interrupt*/ LL_TIM_EnableIT_UPDATE( TIMx ); return; } /** * @brief Turns on low sides switches and start ADC triggering. * * This function is specific for MP phase. Specific to F30X, F4XX, L4XX and G4XX. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_1_RLTurnOnLowSidesAndStart( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); LL_TIM_OC_SetCompareCH1( TIMx, 0x0u ); LL_TIM_OC_SetCompareCH2( TIMx, 0x0u ); LL_TIM_OC_SetCompareCH3( TIMx, 0x0u ); LL_TIM_OC_SetCompareCH4( TIMx, ( pHandle->Half_PWMPeriod - 5u)); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE ; LL_TIM_EnableAllOutputs ( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } pHdl->Sector = SECTOR_5; /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Enable Update IRQ */ LL_TIM_EnableIT_UPDATE( TIMx ); return; } /** * @} */ /** * @} */ /** * @} */ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
62,658
C
30.758236
143
0.612771
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/F3xx/Inc/ics_f30x_pwm_curr_fdbk.h
/** ****************************************************************************** * @file ics_f30x_pwm_curr_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * ICS PWM current feedback component for F30x of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup ICS_F30X_pwm_curr_fdbk */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __ICS_F30X_PWMCURRFDBK_H #define __ICS_F30X_PWMCURRFDBK_H /* Includes ------------------------------------------------------------------*/ #include "pwm_curr_fdbk.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup ICS_pwm_curr_fdbk * @{ */ #define NONE ((uint8_t)(0x00)) #define EXT_MODE ((uint8_t)(0x01)) #define INT_MODE ((uint8_t)(0x02)) #define SOFOC 0x0008u /**< This flag is reset at the beginning of FOC and it is set in the TIM UP IRQ. If at the end of FOC this flag is set, it means that FOC rate is too high and thus an error is generated */ /** * @brief Current feedback component parameters structure definition for ICS configuration. Common to every MCU except F0XX, G0XX and H7XX. */ typedef struct { /* Dual MC parameters --------------------------------------------------------*/ uint8_t FreqRatio; /*!< Used in case of dual MC to synchronize TIM1 and TIM8. It has effect only on the second instanced object and must be equal to the ratio between the two PWM frequencies (higher/lower). Supported values are 1, 2 or 3. */ uint8_t IsHigherFreqTim; /*!< When FreqRatio is greater than 1 this param is used to indicate if this instance is the one with the highest frequency. Allowed values are: HIGHER_FREQ or LOWER_FREQ. */ /* Current reading A/D Conversions initialization -----------------------------*/ ADC_TypeDef * ADCx_1; /*!< First ADC peripheral to be used.*/ ADC_TypeDef * ADCx_2; /*!< Second ADC peripheral to be used.*/ uint8_t IaChannel; /*!< ADC channel used for conversion of current Ia. It must be equal to ADC_CHANNEL_x, x ∈ [0 ; 15]. Specific to F30X and L4XX. */ uint8_t IbChannel; /*!< ADC channel used for conversion of current Ib. It must be equal to ADC_CHANNEL_x, x ∈ [0 ; 15]. Specific to F30X and L4XX. */ /* PWM generation parameters --------------------------------------------------*/ uint8_t RepetitionCounter; /*!< Expresses the number of PWM periods to be elapsed before compare registers are updated again. In particular: @f$ RepetitionCounter\ =\ (2\times PWM\ Periods)\ -\ 1 @f$ */ TIM_TypeDef * TIMx; /*!< Timer used for PWM generation. Equal to TIM1 if bInstanceNbr is equal to 1, equal to TIM8 otherwise. */ } ICS_Params_t; /** * @brief PWM and Current Feedback ICS handle. Common to every MCU except F0XX, G0XX and H7XX. */ typedef struct { PWMC_Handle_t _Super; /*!< Base component handler. */ uint32_t PhaseAOffset; /**< Offset of Phase A current sensing network. */ uint32_t PhaseBOffset; /**< Offset of Phase B current sensing network. */ uint16_t Half_PWMPeriod; /**< Half PWM Period in timer clock counts. */ volatile uint8_t PolarizationCounter; /*!< Number of conversions performed during the calibration phase. */ uint32_t ADCConfig1; /**< Value for ADC CR2 to properly configure current sampling during the context switching. Either defined in PWMC_ICS_Handle_t or in ICS_Params_t. Absent in F4XX. */ uint32_t ADCConfig2; /**< Value for ADC CR2 to properly configure current sampling during the context switching. Either defined in PWMC_ICS_Handle_t or in ICS_Params_t. Absent in F4XX. */ ICS_Params_t const *pParams_str; /*! */ } PWMC_ICS_Handle_t; /* Exported functions ------------------------------------------------------- */ /* * Initializes TIMx, ADC, GPIO and NVIC for current reading * in ICS configuration using STM32F30X. */ void ICS_Init( PWMC_ICS_Handle_t * pHandle ); /* * Sums up injected conversion data into wPhaseXOffset. */ void ICS_CurrentReadingCalibration( PWMC_Handle_t * pHandle ); /* * Computes and stores in the handler the latest converted motor phase currents in ab_t format. */ void ICS_GetPhaseCurrents( PWMC_Handle_t * pHandle, ab_t * pStator_Currents ); /* * Turns on low sides switches. */ void ICS_TurnOnLowSides( PWMC_Handle_t * pHandle, uint32_t ticks ); /* * Enables PWM generation on the proper Timer peripheral acting on MOE bit. */ void ICS_SwitchOnPWM( PWMC_Handle_t * pHandle ); /* * Disables PWM generation on the proper Timer peripheral acting on MOE bit. */ void ICS_SwitchOffPWM( PWMC_Handle_t * pHandle ); /* * Writes into peripheral registers the new duty cycle and sampling point. */ uint16_t ICS_WriteTIMRegisters( PWMC_Handle_t * pHandle ); /* * Sums up injected conversion data into wPhaseXOffset. */ void ICS_HFCurrentsCalibration( PWMC_Handle_t * pHandle, ab_t * pStator_Currents ); /* * Contains the TIMx Update event interrupt. */ void * ICS_TIMx_UP_IRQHandler( PWMC_ICS_Handle_t * pHandle ); /* * Contains the TIMx Break1 event interrupt. */ void * ICS_BRK_IRQHandler( PWMC_ICS_Handle_t * pHandle ); /* * Contains the TIMx Break2 event interrupt. */ void * ICS_BRK2_IRQHandler( PWMC_ICS_Handle_t * pHandle ); /* * Stores in the handler the calibrated offsets. */ void ICS_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /* * Reads the calibrated offsets stored in the handler. */ void ICS_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*__ICS_F30X_PWMCURRFDBK_H*/ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
7,622
C
36.367647
141
0.530832
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/F3xx/Inc/r3_1_f30x_pwm_curr_fdbk.h
/** ****************************************************************************** * @file r3_1_f30X_pwm_curr_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * R3_1_f30X_pwm_curr_fdbk component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup R3_1_F30X_pwm_curr_fdbk */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef R3_1_F30X_PWMCURRFDBK_H #define R3_1_F30X_PWMCURRFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "pwm_curr_fdbk.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup R3_1_pwm_curr_fdbk * @{ */ #define GPIO_NoRemap_TIM1 ((uint32_t)(0)) #define SHIFTED_TIMs ((uint8_t) 1) #define NO_SHIFTED_TIMs ((uint8_t) 0) #define NONE ((uint8_t)(0x00)) #define EXT_MODE ((uint8_t)(0x01)) #define INT_MODE ((uint8_t)(0x02)) /* Exported types ------------------------------------------------------- */ /** * @brief Current feedback component parameters structure definition for 1 ADC configuration. Common to every MCU except G4XX and H7XX. */ typedef const struct { /* HW IP involved -----------------------------*/ ADC_TypeDef * ADCx; /*!< ADC peripheral to be used. Absent in F0XX and G0XX. */ TIM_TypeDef * TIMx; /*!< Timer used for PWM generation. */ COMP_TypeDef * CompOCPASelection; /*!< Internal comparator used for Phase A protection. Specific to F30X and G4XX. */ COMP_TypeDef * CompOCPBSelection; /*!< Internal comparator used for Phase B protection. Specific to F30X and G4XX. */ COMP_TypeDef * CompOCPCSelection; /*!< Internal comparator used for Phase C protection. Specific to F30X and G4XX. */ COMP_TypeDef * CompOVPSelection; /*!< Internal comparator used for Over Voltage protection. Specific to F30X and G4XX. */ uint32_t ADCConfig [6] ; /*!< Stores ADC sequence for the 6 sectors. */ /* PWM generation parameters --------------------------------------------------*/ uint16_t Tafter; /*!< Sum of dead time plus max value between rise time and noise time expressed in number of TIM clocks. */ uint16_t Tbefore; /*!< Sampling time expressed in number of TIM clocks. */ uint16_t Tsampling; /*!< Sampling time expressed in number of TIM clocks. */ uint16_t Tcase2; /*!< Sampling time expressed in number of TIM clocks. */ uint16_t Tcase3; /*!< Sampling time expressed in number of TIM clocks. */ /* DAC settings --------------------------------------------------------------*/ uint16_t DAC_OCP_Threshold; /*!< Value of analog reference expressed as 16bit unsigned integer. Specific to F30X, G4XX and L4XX. \n Ex. 0 = 0V ; 65536 = VDD_DAC. */ uint16_t DAC_OVP_Threshold; /*!< Value of analog reference expressed as 16bit unsigned integer. Specific to F30X, G4XX and L4XX. \n Ex. 0 = 0V ; 65536 = VDD_DAC. */ /* PWM Driving signals initialization ----------------------------------------*/ uint8_t RepetitionCounter; /*!< Expresses the number of PWM periods to be elapsed before compare registers are updated again. In particular: @f$ RepetitionCounter\ =\ (2\times PWM\ Periods)\ -\ 1 @f$ */ /* Internal COMP settings ----------------------------------------------------*/ uint8_t CompOCPAInvInput_MODE; /*!< COMPx inverting input mode. Specific to F30X and G4XX. \n It must be either equal to EXT_MODE or INT_MODE. */ uint8_t CompOCPBInvInput_MODE; /*!< COMPx inverting input mode. Specific to F30X and G4XX. \n It must be either equal to EXT_MODE or INT_MODE. */ uint8_t CompOCPCInvInput_MODE; /*!< COMPx inverting input mode. Specific to F30X and G4XX. \n It must be either equal to EXT_MODE or INT_MODE. */ uint8_t CompOVPInvInput_MODE; /*!< COMPx inverting input mode. Specific to F30X and G4XX. \n It must be either equal to EXT_MODE or INT_MODE. */ /* Dual MC parameters --------------------------------------------------------*/ uint8_t FreqRatio; /*!< Used in case of dual MC to synchronize TIM1 and TIM8. Specific to F30X. \n It has effect only on the second instanced object and must be equal to the ratio between the two PWM frequencies (higher/lower). Supported values are 1, 2 or 3. */ uint8_t IsHigherFreqTim; /*!< When bFreqRatio is greater than 1 this param is used to indicate if this instance is the one with the highest frequency. Specific to F30X. \n Allowed value are: HIGHER_FREQ or LOWER_FREQ. */ } R3_1_Params_t; /** * @brief This structure is used to handle an instance of the * PWM and current feedback component. */ typedef struct { PWMC_Handle_t _Super; /*!< Base component handler. */ uint32_t PhaseAOffset; /*!< Offset of Phase A current sensing network. */ uint32_t PhaseBOffset; /*!< Offset of Phase B current sensing network. */ uint32_t PhaseCOffset; /*!< Offset of Phase C current sensing network. */ uint16_t Half_PWMPeriod; /*!< Half PWM Period in timer clock counts. */ uint16_t ADC_ExternalTriggerInjected; /*!< External ADC trigger source. Absent in G4XX. */ uint16_t ADC_ExternalPolarityInjected; volatile uint8_t PolarizationCounter; /*!< Number of conversions performed during the calibration phase. */ uint8_t PolarizationSector; /* Sector selected during calibration phase. Specific to F30XX and G4XX. Named CalibSector in every other MCU. */ R3_1_Params_t * pParams_str; } PWMC_R3_1_Handle_t; /* Exported functions ------------------------------------------------------- */ /* * Initializes TIMx, ADC, GPIO, DMA1 and NVIC for current reading * in three shunt topology using STM32F30X and ADC. */ void R3_1_Init( PWMC_R3_1_Handle_t * pHandle ); /* * Stores into the handle the voltage present on Ia and * Ib current feedback analog channels when no current is flowing into the * motor. */ void R3_1_CurrentReadingPolarization( PWMC_Handle_t * pHdl ); /* * Computes and return latest converted motor phase currents motor. */ void R3_1_GetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * Iab ); /* * Computes and return latest converted motor phase currents motor. */ void R3_1_GetPhaseCurrents_OVM( PWMC_Handle_t * pHdl, ab_t * Iab ); /* * Turns on low sides switches. */ void R3_1_TurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ); /* * Enables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_1_SwitchOnPWM( PWMC_Handle_t * pHdl ); /* * Disables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_1_SwitchOffPWM( PWMC_Handle_t * pHdl ); /* * Configures the ADC for the current sampling . */ uint16_t R3_1_SetADCSampPointSectX( PWMC_Handle_t * pHdl ); /* * Configures the ADC for the current sampling. Specific to overmodulation. */ uint16_t R3_1_SetADCSampPointSectX_OVM( PWMC_Handle_t * pHdl ); /* * Contains the TIMx Update event interrupt. */ void * R3_1_TIMx_UP_IRQHandler( PWMC_R3_1_Handle_t * pHdl ); /* * Sets the PWM mode for R/L detection. */ void R3_1_RLDetectionModeEnable( PWMC_Handle_t * pHdl ); /* * Disables the PWM mode for R/L detection. */ void R3_1_RLDetectionModeDisable( PWMC_Handle_t * pHdl ); /* * Sets the PWM dutycycle for R/L detection. */ uint16_t R3_1_RLDetectionModeSetDuty( PWMC_Handle_t * pHdl, uint16_t hDuty ); /* * Turns on low sides switches and start ADC triggering. */ void R3_1_RLTurnOnLowSidesAndStart( PWMC_Handle_t * pHdl ); /* * Sets the calibrated offsets. */ void R3_1_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /* * Reads the calibrated offsets. */ void R3_1_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*R3_1_F30X_PWMNCURRFDBK_H*/ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
9,907
C
38.791165
143
0.541133
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/F3xx/Inc/r3_2_f30x_pwm_curr_fdbk.h
/** ****************************************************************************** * @file R3_2_f30x_pwm_curr_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * R3_2_F30X_pwm_curr_fdbk component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup R3_2_F30X_pwm_curr_fdbk */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef R3_2_F30X_PWMNCURRFDBK_H #define R3_2_F30X_PWMNCURRFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "pwm_curr_fdbk.h" /* Exported defines --------------------------------------------------------*/ #define NONE ((uint8_t)(0x00)) #define EXT_MODE ((uint8_t)(0x01)) #define INT_MODE ((uint8_t)(0x02)) /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup R3_2_pwm_curr_fdbk * @{ */ /* Exported types ------------------------------------------------------- */ /** * @brief Current feedback component 2-OPAMP parameters structure definition. Specific to F30X and H7XX. */ typedef struct { /* First OPAMP settings ------------------------------------------------------*/ OPAMP_TypeDef *OPAMPSelect_1 [6] ; /*!< Define for each sector first conversion which OPAMP is involved - Null otherwise */ OPAMP_TypeDef *OPAMPSelect_2 [6] ; /*!< Define for each sector second conversion which OPAMP is involved - Null otherwise */ uint32_t OPAMPConfig1 [6]; /*!< Defines the OPAMP_CSR_OPAMPINTEN and the OPAMP_CSR_VPSEL config for each ADC conversions. */ uint32_t OPAMPConfig2 [6]; /*!< Defines the OPAMP_CSR_OPAMPINTEN and the OPAMP_CSR_VPSEL config for each ADC conversions. */ } R3_2_OPAMPParams_t; /** * @brief Current feedback component parameters structure definition for 2 ADCs configuration. Common to every MCU except F0XX and G0XX. */ typedef struct { /* HW IP involved -----------------------------*/ TIM_TypeDef * TIMx; /*!< Timer used for PWM generation.*/ R3_2_OPAMPParams_t const *OPAMPParams; /*!< Pointer to the 2-OPAMP params struct. It must be #MC_NULL if internal OPAMP are not used. Specific to F30X and H7XX.*/ COMP_TypeDef * CompOCPASelection; /*!< Internal comparator used for Phase A protection. Specific to F30X, G4XX and H7XX.*/ COMP_TypeDef * CompOCPBSelection; /*!< Internal comparator used for Phase B protection. Specific to F30X, G4XX and H7XX.*/ COMP_TypeDef * CompOCPCSelection; /*!< Internal comparator used for Phase C protection. Specific to F30X, G4XX and H7XX.*/ COMP_TypeDef * CompOVPSelection; /*!< Internal comparator used for Over Voltage protection. Specific to F30X, G4XX and H7XX.*/ ADC_TypeDef * ADCDataReg1[6]; /*!< Contains the Address of ADC read value for one phase and all the 6 sectors. */ ADC_TypeDef * ADCDataReg2[6]; /*!< Contains the Address of ADC read value for one phase and all the 6 sectors. */ uint32_t ADCConfig1 [6] ; /*!< Values of JSQR for first ADC for 6 sectors. */ uint32_t ADCConfig2 [6] ; /*!< Values of JSQR for second ADC for 6 sectors. */ /* PWM generation parameters --------------------------------------------------*/ uint16_t Tafter; /*!< Sum of dead time plus max value between rise time and noise time expressed in number of TIM clocks. */ uint16_t Tsampling; /*!< Sampling time expressed in number of TIM clocks. Absent in H7XX. */ uint16_t Tbefore; /*!< Sampling time expressed in number of TIM clocks.*/ uint16_t Tcase2; /*!< Sampling time expressed in number of TIM clocks. Absent in H7XX. */ uint16_t Tcase3; /*!< Sampling time expressed in number of TIM clocks. Absent in H7XX. */ /* DAC settings --------------------------------------------------------------*/ uint16_t DAC_OCP_Threshold; /*!< Value of analog reference expressed as 16bit unsigned integer. Specific to F30X, G4XX, H7XX and L4XX. \n Ex. 0 = 0V ; 65536 = VDD_DAC. */ uint16_t DAC_OVP_Threshold; /*!< Value of analog reference expressed as 16bit unsigned integer. Specific to F30X, G4XX, H7XX and L4XX. \n Ex. 0 = 0V ; 65536 = VDD_DAC.*/ /* PWM Driving signals initialization ----------------------------------------*/ uint8_t RepetitionCounter; /*!< Expresses the number of PWM periods to be elapsed before compare registers are updated again. In particular: @f$ RepetitionCounter\ =\ (2\times PWM\ Periods)\ -\ 1 @f$ */ /* Internal COMP settings ----------------------------------------------------*/ uint8_t CompOCPAInvInput_MODE; /*!< COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. Specific to F30X, G4XX and H7XX. */ uint8_t CompOCPBInvInput_MODE; /*!< COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. Specific to F30X, G4XX and H7XX. */ uint8_t CompOCPCInvInput_MODE; /*!< COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. Specific to F30X, G4XX and H7XX. */ uint8_t CompOVPInvInput_MODE; /*!< COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. Specific to F30X, G4XX and H7XX. */ /* Dual MC parameters --------------------------------------------------------*/ uint8_t FreqRatio; /*!< Used in case of dual MC to synchronize TIM1 and TIM8. It has effect only on the second instanced object and must be equal to the ratio between the two PWM frequencies (higher/lower). Supported values are 1, 2 or 3 */ uint8_t IsHigherFreqTim; /*!< When FreqRatio is greater than 1 this param is used to indicate if this instance is the one with the highest frequency. Allowed values are: HIGHER_FREQ or LOWER_FREQ */ } R3_2_Params_t; /** * @brief Handles an instance of the current feedback component for 2 ADCs configuration. Common to every MCU except F0XX and G0XX. */ typedef struct { PWMC_Handle_t _Super; /*!< Base component handler. */ uint32_t PhaseAOffset; /*!< Offset of Phase A current sensing network. */ uint32_t PhaseBOffset; /*!< Offset of Phase B current sensing network. */ uint32_t PhaseCOffset; /*!< Offset of Phase C current sensing network. */ uint16_t Half_PWMPeriod; /*!< Half PWM Period in timer clock counts. */ uint16_t ADC_ExternalTriggerInjected; /*!< External trigger selection for ADC peripheral.*/ uint16_t ADC_ExternalPolarityInjected; volatile uint8_t PolarizationCounter; /*!< Number of conversions performed during the calibration phase. */ uint8_t PolarizationSector; /*!< Sector selected during calibration phase. Specific to F30X, G4XX and H7XX. */ R3_2_Params_t const * pParams_str; } PWMC_R3_2_Handle_t; /* Exported functions ------------------------------------------------------- */ /* * Initializes TIMx, ADC, GPIO, DMA1 and NVIC for current reading * in three shunt topology using STM32F30X and shared ADC. */ void R3_2_Init( PWMC_R3_2_Handle_t * pHandle ); /* * Stores into the handle the voltage present on Ia and * Ib current feedback analog channels when no current is flowing into the * motor. */ void R3_2_CurrentReadingPolarization( PWMC_Handle_t * pHdl ); /* * Computes and stores in the handler the latest converted motor phase currents in ab_t format. */ void R3_2_GetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * Iab ); /* * Computes and stores in the handler the latest converted motor phase currents in ab_t format. Specific to overmodulation. */ void R3_2_GetPhaseCurrents_OVM( PWMC_Handle_t * pHdl, ab_t * Iab ); /* * Turns on low sides switches. */ void R3_2_TurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ); /* * Enables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_2_SwitchOnPWM( PWMC_Handle_t * pHdl ); /* * Disables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_2_SwitchOffPWM( PWMC_Handle_t * pHdl ); /* * Configures the ADC for the current sampling related to sector X (X = [1..6] ). */ uint16_t R3_2_SetADCSampPointSectX( PWMC_Handle_t * pHdl ); /* * Configures the ADC for the current sampling related to sector X (X = [1..6] ) in case of overmodulation. */ uint16_t R3_2_SetADCSampPointSectX_OVM( PWMC_Handle_t * pHdl ); /* * Contains the TIMx Update event interrupt. */ void * R3_2_TIMx_UP_IRQHandler( PWMC_R3_2_Handle_t * pHdl ); /* * Sets the PWM mode for R/L detection. */ void R3_2_RLDetectionModeEnable( PWMC_Handle_t * pHdl ); /* * Disables the PWM mode for R/L detection. */ void R3_2_RLDetectionModeDisable( PWMC_Handle_t * pHdl ); /* * Sets the PWM dutycycle for R/L detection. */ uint16_t R3_2_RLDetectionModeSetDuty( PWMC_Handle_t * pHdl, uint16_t hDuty ); /* * Turns on low sides switches and start ADC triggering. */ void R3_2_RLTurnOnLowSidesAndStart( PWMC_Handle_t * pHdl ); /* * Stores in the handler the calibrated offsets. */ void R3_2_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /* * Reads the calibrated offsets stored in the handler. */ void R3_2_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*R3_2_F30X_PWMNCURRFDBK_H*/ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
11,672
C
42.55597
161
0.537868
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/G0xx/Src/r1_g0xx_pwm_curr_fdbk - Without DMA.c
/** ****************************************************************************** * @file r1_g0xx_pwm_curr_fdbk.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement current sensor * class to be stantiated when the single shunt current sensing * topology is used. * * It is specifically designed for STM32G0XX microcontrollers and * implements the successive sampling of motor current using only one ADC. * + MCU peripheral and handle initialization fucntion * + three shunt current sensing * + space vector modulation function * + ADC sampling function * ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * Redistribution and use in source and binary forms, with or without * modification, are permitted, provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of other * contributors to this software may be used to endorse or promote products * derived from this software without specific written permission. * 4. This software, including modifications and/or derivative works of this * software, must execute solely and exclusively on microcontroller or * microprocessor devices manufactured by or for STMicroelectronics. * 5. Redistribution and use of this software other than as permitted under * this license is void and will automatically terminate your rights under * this license. * * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT * SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "pwm_curr_fdbk.h" #include "r1_g0xx_pwm_curr_fdbk.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** * @defgroup R1_G0XX_pwm_curr_fdbk G0 R1 1 ADC PWM & Current Feedback * * @brief STM32G0, 1-Shunt, 1 ADC, PWM & Current Feedback implementation * * This component is used in applications based on an STM32G0 MCU, using a one * shunt resistor current sensing topology and one ADC peripheral to acquire the current * values. * * * @{ */ /* Private Defines -----------------------------------------------------------*/ #define DR_OFFSET 0x40u #define ADC1_DR_Address ADC1_BASE + DR_OFFSET #define NB_CONVERSIONS 16u #define REGULAR ((uint8_t)0u) #define BOUNDARY_1 ((uint8_t)1u) /* Two small, one big */ #define BOUNDARY_2 ((uint8_t)2u) /* Two big, one small */ #define BOUNDARY_3 ((uint8_t)3u) /* Three equal */ #define INVERT_NONE 0u #define INVERT_A 1u #define INVERT_B 2u #define INVERT_C 3u #define SAMP_NO 0u #define SAMP_IA 1u #define SAMP_IB 2u #define SAMP_IC 3u #define SAMP_NIA 4u #define SAMP_NIB 5u #define SAMP_NIC 6u #define SAMP_OLDA 7u #define SAMP_OLDB 8u #define SAMP_OLDC 9u #define CH1NORMAL 0x0060u #define CH2NORMAL 0x6000u #define CH3NORMAL 0x0060u #define CH4NORMAL 0x7000u #define CCMR1_PRELOAD_DISABLE_MASK 0xF7F7u #define CCMR2_PRELOAD_DISABLE_MASK 0xFFF7u #define CCMR1_PRELOAD_ENABLE_MASK 0x0808u #define CCMR2_PRELOAD_ENABLE_MASK 0x0008u /* DMA ENABLE mask */ #define CCR_ENABLE_Set ((uint32_t)0x00000001u) #define CCR_ENABLE_Reset ((uint32_t)0xFFFFFFFEu) #define CR2_JEXTSEL_Reset ((uint32_t)0xFFFF8FFFu) #define CR2_JEXTTRIG_Set ((uint32_t)0x00008000u) #define CR2_JEXTTRIG_Reset ((uint32_t)0xFFFF7FFFu) #define TIM_DMA_ENABLED_CC1 0x0200u #define TIM_DMA_ENABLED_CC2 0x0400u #define TIM_DMA_ENABLED_CC3 0x0800u #define CR2_ADON_Set ((uint32_t)0x00000001u) /* ADC SMPx mask */ #define SMPR1_SMP_Set ((uint32_t) (0x00000007u)) #define SMPR2_SMP_Set ((uint32_t) (0x00000007u)) #define CR2_EXTTRIG_SWSTART_Set ((u32)0x00500000) #define ADC1_CR2_EXTTRIG_SWSTART_BB 0x42248158u #define ADCx_IRQn ADC1_COMP_IRQn #define TIMx_UP_IRQn TIM1_BRK_UP_TRG_COM_IRQn /* Constant values -----------------------------------------------------------*/ static const uint8_t REGULAR_SAMP_CUR1[6] = {SAMP_NIC,SAMP_NIC,SAMP_NIA,SAMP_NIA,SAMP_NIB,SAMP_NIB}; static const uint8_t REGULAR_SAMP_CUR2[6] = {SAMP_IA,SAMP_IB,SAMP_IB,SAMP_IC,SAMP_IC,SAMP_IA}; static const uint8_t BOUNDR1_SAMP_CUR2[6] = {SAMP_IB,SAMP_IB,SAMP_IC,SAMP_IC,SAMP_IA,SAMP_IA}; static const uint8_t BOUNDR2_SAMP_CUR1[6] = {SAMP_IA,SAMP_IB,SAMP_IB,SAMP_IC,SAMP_IC,SAMP_IA}; static const uint8_t BOUNDR2_SAMP_CUR2[6] = {SAMP_IC,SAMP_IA,SAMP_IA,SAMP_IB,SAMP_IB,SAMP_IC}; /* Private function prototypes -----------------------------------------------*/ void R1G0XX_1ShuntMotorVarsInit(PWMC_Handle_t *pHdl); void R1G0XX_1ShuntMotorVarsRestart(PWMC_Handle_t *pHdl); void R1G0XX_TIMxInit(TIM_TypeDef* TIMx, PWMC_Handle_t *pHdl); /* Private functions ---------------------------------------------------------*/ /** * @brief It initializes TIM1, ADC, GPIO, DMA1 and NVIC for single shunt current * reading configuration using STM32F0XX family. * @param pHdl: handler of the current instance of the PWM component * @retval none */ void R1G0XX_Init(PWMC_R1_G0_Handle_t *pHandle) { uint16_t hTIM1_CR1; if ((uint32_t)pHandle == (uint32_t)&pHandle->_Super) { R1G0XX_1ShuntMotorVarsInit(&pHandle->_Super); LL_DBGMCU_APB2_GRP1_FreezePeriph(LL_DBGMCU_APB2_GRP1_TIM1_STOP); R1G0XX_TIMxInit(TIM1, &pHandle->_Super); /* DMA Event related to ADC conversion*/ /* DMA channel configuration ----------------------------------------------*/ LL_DMA_SetMemoryAddress(DMA1, LL_DMA_CHANNEL_1, (uint32_t)pHandle->hCurConv); LL_DMA_SetPeriphAddress(DMA1, LL_DMA_CHANNEL_1, (uint32_t)ADC1_DR_Address); LL_DMA_SetDataLength(DMA1, LL_DMA_CHANNEL_1, 2u); /* DMA1 channel 1 will be enabled after the CurrentReadingCalibration */ /* Start calibration of ADC1 */ LL_ADC_StartCalibration(ADC1); while(LL_ADC_IsCalibrationOnGoing(ADC1) == 1); (READ_BIT(ADC1->CR,ADC_CR_ADCAL) == RESET)?(LL_ADC_ReadReg(ADC1,DR)):(0); /* Enable ADC */ ADC1->CFGR1 &= ~ADC_EXTERNALTRIGCONVEDGE_RISINGFALLING; LL_ADC_REG_SetDMATransfer(ADC1, LL_ADC_REG_DMA_TRANSFER_NONE); LL_ADC_Enable(ADC1); /* Wait ADC Ready */ while (LL_ADC_IsActiveFlag_ADRDY(ADC1)==RESET) {} /* set the shadow variable bADCSMP2 to the current ADC SMP2 value */ pHandle->bADCSMP2 = LL_ADC_GetSamplingTimeCommonChannels (ADC1, LL_ADC_SAMPLINGTIME_COMMON_2); R1G0XX_1ShuntMotorVarsRestart(&pHandle->_Super); LL_DMA_EnableIT_TC(DMA1, LL_DMA_CHANNEL_1); LL_TIM_EnableCounter(TIM1); hTIM1_CR1 = TIM1->CR1; hTIM1_CR1 |= TIM_CR1_CEN; pHandle->_Super.DTTest = 0u; pHandle->_Super.DTCompCnt = pHandle->_Super.hDTCompCnt; } } /** * @brief It initializes TIMx for PWM generation, * active vector insertion and adc triggering. * @param TIMx Timer to be initialized * @param pHdl: handler of the current instance of the PWM component * @retval none */ __weak void R1G0XX_TIMxInit(TIM_TypeDef* TIMx, PWMC_Handle_t *pHdl) { PWMC_R1_G0_Handle_t *pHandle = (PWMC_R1_G0_Handle_t *)pHdl; LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH1); LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH2); LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH3); if ((pHandle->_Super.LowSideOutputs)== LS_PWM_TIMER) { LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH1N); LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH2N); LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH3N); } LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH1); LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH2); LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH3); LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH4); LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH5); LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH6); LL_TIM_OC_SetDeadTime(TIMx, (pHandle->pParams_str->hDeadTime)/2u); } /** * @brief It stores into handler the voltage present on the * current feedback analog channel when no current is flowin into the * motor * @param pHdl: handler of the current instance of the PWM component * @retval none */ __weak void R1G0XX_CurrentReadingCalibration(PWMC_Handle_t *pHdl) { uint8_t bIndex = 0u; uint32_t wPhaseOffset = 0u; PWMC_R1_G0_Handle_t *pHandle = (PWMC_R1_G0_Handle_t *)pHdl; /* Set the CALIB flags to indicate the ADC calibartion phase*/ pHandle->hFlags |= CALIB; /* ADC Channel and sampling time config for current reading */ ADC1->CHSELR = 1 << pHandle->pParams_str->hIChannel; /* Disable DMA1 Channel1 */ LL_DMA_DisableChannel(DMA1, LL_DMA_CHANNEL_1); /* ADC Channel used for current reading are read in order to get zero currents ADC values*/ while (bIndex< NB_CONVERSIONS) { /* Software start of conversion */ LL_ADC_REG_StartConversion(ADC1); /* Wait until end of regular conversion */ while (LL_ADC_IsActiveFlag_EOC(ADC1)==RESET) {} wPhaseOffset += LL_ADC_REG_ReadConversionData12(ADC1); bIndex++; } pHandle->hPhaseOffset = (uint16_t)(wPhaseOffset/NB_CONVERSIONS); /* Reset the CALIB flags to indicate the end of ADC calibartion phase*/ pHandle->hFlags &= (~CALIB); } /** * @brief First initialization of class members * @param pHdl: handler of the current instance of the PWM component * @retval none */ __weak void R1G0XX_1ShuntMotorVarsInit(PWMC_Handle_t *pHdl) { PWMC_R1_G0_Handle_t *pHandle = (PWMC_R1_G0_Handle_t *)pHdl; /* Init motor vars */ pHandle->hPhaseOffset=0u; pHandle->bInverted_pwm_new=INVERT_NONE; pHandle->hFlags &= (~STBD3); pHandle->hFlags &= (~DSTEN); /* After reset value of dvDutyValues */ pHandle->_Super.hCntPhA = pHandle->Half_PWMPeriod >> 1; pHandle->_Super.hCntPhB = pHandle->Half_PWMPeriod >> 1; pHandle->_Super.hCntPhC = pHandle->Half_PWMPeriod >> 1; /* Default value of DutyValues */ pHandle->hCntSmp1 = (pHandle->Half_PWMPeriod >> 1) - pHandle->pParams_str->hTbefore; pHandle->hCntSmp2 = (pHandle->Half_PWMPeriod >> 1) + pHandle->pParams_str->hTafter; TIM1->CCR4 = pHandle->hCntSmp1; /* First point */ TIM1->CCR6 = pHandle->hCntSmp2; /* Second point */ /* Init of "regular" conversion registers */ pHandle->bRegConvRequested = 0u; pHandle->bRegConvIndex = 0u; } /** * @brief Initialization of class members after each motor start * @param pHdl: handler of the current instance of the PWM component * @retval none */ __weak void R1G0XX_1ShuntMotorVarsRestart(PWMC_Handle_t *pHdl) { PWMC_R1_G0_Handle_t *pHandle = (PWMC_R1_G0_Handle_t *)pHdl; /* Default value of DutyValues */ pHandle->hCntSmp1 = (pHandle->Half_PWMPeriod >> 1) - pHandle->pParams_str->hTbefore; pHandle->hCntSmp2 = (pHandle->Half_PWMPeriod >> 1) + pHandle->pParams_str->hTafter; pHandle->bInverted_pwm_new=INVERT_NONE; pHandle->hFlags &= (~STBD3); /*STBD3 cleared*/ TIM1->CCR4 = pHandle->hCntSmp1; /* First point */ TIM1->CCR6 = pHandle->hCntSmp2; /* Second point */ /* After start value of dvDutyValues */ pHandle->_Super.hCntPhA = pHandle->Half_PWMPeriod >> 1; pHandle->_Super.hCntPhB = pHandle->Half_PWMPeriod >> 1; pHandle->_Super.hCntPhC = pHandle->Half_PWMPeriod >> 1; /* Set the default previous value of Phase A,B,C current */ pHandle->hCurrAOld=0; pHandle->hCurrBOld=0; } /** * @brief It computes and return latest converted motor phase currents motor * @param pHdl: handler of the current instance of the PWM component * @retval Curr_Components Ia and Ib current in Curr_Components format */ __weak void R1G0XX_GetPhaseCurrents(PWMC_Handle_t *pHdl,Curr_Components* pStator_Currents) { int32_t wAux; int16_t hCurrA = 0; int16_t hCurrB = 0; int16_t hCurrC = 0; uint8_t bCurrASamp = 0u; uint8_t bCurrBSamp = 0u; uint8_t bCurrCSamp = 0u; PWMC_R1_G0_Handle_t *pHandle = (PWMC_R1_G0_Handle_t *)pHdl; /* Disabling the External triggering for ADCx*/ LL_ADC_REG_SetTriggerSource (ADC1, LL_ADC_REG_TRIG_SOFTWARE); /* Reset the update flag to indicate the start of FOC algorithm*/ LL_TIM_ClearFlag_UPDATE(TIM1); /* First sampling point */ wAux = (int32_t)(pHandle->hCurConv[0]) - (int32_t)(pHandle->hPhaseOffset); /* Check saturation */ wAux = (wAux > S16_MIN) ? ((wAux < S16_MAX) ? wAux : S16_MAX) : S16_MIN; switch (pHandle->sampCur1) { case SAMP_IA: hCurrA = (int16_t)(wAux); bCurrASamp = 1u; break; case SAMP_IB: hCurrB = (int16_t)(wAux); bCurrBSamp = 1u; break; case SAMP_IC: hCurrC = (int16_t)(wAux); bCurrCSamp = 1u; break; case SAMP_NIA: wAux = -wAux; hCurrA = (int16_t)(wAux); bCurrASamp = 1u; break; case SAMP_NIB: wAux = -wAux; hCurrB = (int16_t)(wAux); bCurrBSamp = 1u; break; case SAMP_NIC: wAux = -wAux; hCurrC = (int16_t)(wAux); bCurrCSamp = 1u; break; case SAMP_OLDA: hCurrA = pHandle->hCurrAOld; bCurrASamp = 1u; break; case SAMP_OLDB: hCurrB = pHandle->hCurrBOld; bCurrBSamp = 1u; break; default: break; } /* Second sampling point */ wAux = (int32_t)(pHandle->hCurConv[1]) - (int32_t)(pHandle->hPhaseOffset); wAux = (wAux > S16_MIN) ? ((wAux < S16_MAX) ? wAux : S16_MAX) : S16_MIN; switch (pHandle->sampCur2) { case SAMP_IA: hCurrA = (int16_t)(wAux); bCurrASamp = 1u; break; case SAMP_IB: hCurrB = (int16_t)(wAux); bCurrBSamp = 1u; break; case SAMP_IC: hCurrC = (int16_t)(wAux); bCurrCSamp = 1u; break; case SAMP_NIA: wAux = -wAux; hCurrA = (int16_t)(wAux); bCurrASamp = 1u; break; case SAMP_NIB: wAux = -wAux; hCurrB = (int16_t)(wAux); bCurrBSamp = 1u; break; case SAMP_NIC: wAux = -wAux; hCurrC = (int16_t)(wAux); bCurrCSamp = 1u; break; default: break; } /* Computation of the third value */ if (bCurrASamp == 0u) { wAux = -((int32_t)(hCurrB)) -((int32_t)(hCurrC)); /* Check saturation */ wAux = (wAux > S16_MIN) ? ((wAux < S16_MAX) ? wAux : S16_MAX) : S16_MIN; hCurrA = (int16_t)wAux; } if (bCurrBSamp == 0u) { wAux = -((int32_t)(hCurrA)) -((int32_t)(hCurrC)); /* Check saturation */ wAux = (wAux > S16_MIN) ? ((wAux < S16_MAX) ? wAux : S16_MAX) : S16_MIN; hCurrB = (int16_t)wAux; } if (bCurrCSamp == 0u) { wAux = -((int32_t)(hCurrA)) -((int32_t)(hCurrB)); /* Check saturation */ wAux = (wAux > S16_MIN) ? ((wAux < S16_MAX) ? wAux : S16_MAX) : S16_MIN; hCurrC = (int16_t)wAux; } /* hCurrA, hCurrB, hCurrC values are the sampled values */ pHandle->hCurrAOld = hCurrA; pHandle->hCurrBOld = hCurrB; pStator_Currents->qI_Component1 = hCurrA; pStator_Currents->qI_Component2 = hCurrB; pHandle->_Super.hIa = pStator_Currents->qI_Component1; pHandle->_Super.hIb = pStator_Currents->qI_Component2; pHandle->_Super.hIc = -pStator_Currents->qI_Component1 - pStator_Currents->qI_Component2; if (pHandle->bRegConvRequested != 0u) { /* Exec regular conversion @ bRegConvIndex */ uint8_t bRegConvCh = pHandle->bRegConvCh[pHandle->bRegConvIndex]; /* Set Sampling time and channel */ ADC1->CHSELR = 1 << bRegConvCh; if (pHandle->bADCSMP2 != pHandle->bRegSmpTime[bRegConvCh] ) { LL_ADC_SetSamplingTimeCommonChannels (ADC1, LL_ADC_SAMPLINGTIME_COMMON_2, pHandle->bRegSmpTime[bRegConvCh]); pHandle->bADCSMP2 = pHandle->bRegSmpTime[bRegConvCh]; } /* Enable ADC1 EOC DMA */ LL_ADC_REG_SetDMATransfer(ADC1, LL_ADC_REG_DMA_TRANSFER_NONE); /* Start ADC */ LL_ADC_REG_StartConversion(ADC1); /* Flags the regular conversion ongoing */ pHandle->hFlags |= REGCONVONGOING; } } /** * @brief It turns on low sides switches. This function is intended to be * used for charging boot capacitors of driving section. It has to be * called each motor start-up when using high voltage drivers * @param pHdl: handler of the current instance of the PWM component * @retval none */ __weak void R1G0XX_TurnOnLowSides(PWMC_Handle_t *pHdl) { PWMC_R1_G0_Handle_t *pHandle = (PWMC_R1_G0_Handle_t *)pHdl; pHandle->_Super.bTurnOnLowSidesAction = TRUE; TIM1->CCR1 = 0u; TIM1->CCR2 = 0u; TIM1->CCR3 = 0u; LL_TIM_ClearFlag_UPDATE(TIM1); while (LL_TIM_IsActiveFlag_UPDATE(TIM1) == RESET) {} /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs(TIM1); if ((pHandle->_Super.LowSideOutputs)== ES_GPIO) { LL_GPIO_SetOutputPin(pHandle->pParams_str->hCh1NPort, pHandle->pParams_str->hCh1NPin); LL_GPIO_SetOutputPin(pHandle->pParams_str->hCh2NPort, pHandle->pParams_str->hCh2NPin); LL_GPIO_SetOutputPin(pHandle->pParams_str->hCh3NPort, pHandle->pParams_str->hCh3NPin); } return; } /** * @brief It enables PWM generation on the proper Timer peripheral acting on * MOE bit, enaables the single shunt distortion and reset the TIM status * @param pHdl: handler of the current instance of the PWM component * @retval none */ __weak void R1G0XX_SwitchOnPWM(PWMC_Handle_t *pHdl) { PWMC_R1_G0_Handle_t *pHandle = (PWMC_R1_G0_Handle_t *)pHdl; pHandle->_Super.bTurnOnLowSidesAction = FALSE; /* enable break Interrupt */ LL_TIM_ClearFlag_BRK(TIM1); LL_TIM_EnableIT_BRK(TIM1); LL_TIM_ClearFlag_UPDATE(TIM1); while (LL_TIM_IsActiveFlag_UPDATE(TIM1)==RESET) {} LL_TIM_ClearFlag_UPDATE(TIM1); /* Set all duty to 50% */ /* Set ch4 ch6 for triggering */ /* Clear Update Flag */ LL_TIM_OC_SetCompareCH1(TIM1,(uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH2(TIM1,(uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH3(TIM1,(uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH4(TIM1,(((uint32_t)(pHandle->Half_PWMPeriod >> 1)) + (uint32_t)pHandle->pParams_str->hTafter)); LL_TIM_OC_SetCompareCH6(TIM1,(uint32_t)(pHandle->Half_PWMPeriod - 1u)); // CHO : temporary discard ch6 while (LL_TIM_IsActiveFlag_UPDATE(TIM1)==RESET) {} /* dirty trick because the DMA is fired as soon as channel is enabled ...*/ LL_DMA_EnableChannel(DMA1, LL_DMA_CHANNEL_1); LL_DMA_DisableChannel(DMA1, LL_DMA_CHANNEL_1); LL_DMA_SetDataLength(DMA1, LL_DMA_CHANNEL_1, 2u); LL_DMA_EnableChannel(DMA1, LL_DMA_CHANNEL_1); /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs(TIM1); /* TIM output trigger 2 for ADC */ LL_TIM_SetTriggerOutput2(TIM1, LL_TIM_TRGO2_OC4_RISING_OC6_RISING); /* Main PWM Output Enable */ LL_TIM_ClearFlag_UPDATE(TIM1); LL_TIM_EnableIT_UPDATE(TIM1); if ((pHandle->_Super.LowSideOutputs)== ES_GPIO) { LL_GPIO_SetOutputPin(pHandle->pParams_str->hCh1NPort, pHandle->pParams_str->hCh1NPin); LL_GPIO_SetOutputPin(pHandle->pParams_str->hCh2NPort, pHandle->pParams_str->hCh2NPin); LL_GPIO_SetOutputPin(pHandle->pParams_str->hCh3NPort, pHandle->pParams_str->hCh3NPin); } /* Enabling distortion for single shunt */ pHandle->hFlags |= DSTEN; return; } /** * @brief It disables PWM generation on the proper Timer peripheral acting on * MOE bit, disables the single shunt distortion and reset the TIM status * @param pHdl: handler of the current instance of the PWM component * @retval none */ __weak void R1G0XX_SwitchOffPWM(PWMC_Handle_t *pHdl) { uint16_t hAux; PWMC_R1_G0_Handle_t *pHandle = (PWMC_R1_G0_Handle_t *)pHdl; pHandle->_Super.bTurnOnLowSidesAction = FALSE; /* Main PWM Output Disable */ LL_TIM_DisableAllOutputs(TIM1); if ((pHandle->_Super.LowSideOutputs)== ES_GPIO) { LL_GPIO_ResetOutputPin(pHandle->pParams_str->hCh1NPort, pHandle->pParams_str->hCh1NPin); LL_GPIO_ResetOutputPin(pHandle->pParams_str->hCh2NPort, pHandle->pParams_str->hCh2NPin); LL_GPIO_ResetOutputPin(pHandle->pParams_str->hCh3NPort, pHandle->pParams_str->hCh3NPin); } /* Disable UPDATE ISR */ LL_TIM_DisableIT_UPDATE(TIM1); /* Disable break interrupt */ LL_TIM_DisableIT_BRK(TIM1); /*Clear potential ADC Ongoing conversion*/ if (LL_ADC_REG_IsConversionOngoing (ADC1)) { LL_ADC_REG_StopConversion (ADC1); while ( LL_ADC_REG_IsConversionOngoing(ADC1)) { } } LL_ADC_REG_SetTriggerSource (ADC1, LL_ADC_REG_TRIG_SOFTWARE); /* Disabling distortion for single */ pHandle->hFlags &= (~DSTEN); while (LL_TIM_IsActiveFlag_UPDATE(TIM1)==RESET) {} /* Set all duty to 50% */ hAux = pHandle->Half_PWMPeriod >> 1; TIM1->CCR1 = hAux; TIM1->CCR2 = hAux; TIM1->CCR3 = hAux; return; } /** * @brief Implementation of the single shunt algorithm to setup the * TIM1 register and DMA buffers values for the next PWM period. * @param pHdl: handler of the current instance of the PWM component * @retval uint16_t It returns #MC_DURATION if the TIMx update occurs * before the end of FOC algorithm else returns #MC_NO_ERROR */ __weak uint16_t R1G0XX_CalcDutyCycles(PWMC_Handle_t *pHdl) { int16_t hDeltaDuty_0; int16_t hDeltaDuty_1; uint16_t hDutyV_0 = 0u; uint16_t hDutyV_1 = 0u; uint16_t hDutyV_2 = 0u; uint8_t bSector; uint8_t bStatorFluxPos; uint16_t hAux; PWMC_R1_G0_Handle_t *pHandle = (PWMC_R1_G0_Handle_t *)pHdl; bSector = (uint8_t)pHandle->_Super.hSector; if ((pHandle->hFlags & DSTEN) != 0u) { switch (bSector) { case SECTOR_1: hDutyV_2 = pHandle->_Super.hCntPhA; hDutyV_1 = pHandle->_Super.hCntPhB; hDutyV_0 = pHandle->_Super.hCntPhC; break; case SECTOR_2: hDutyV_2 = pHandle->_Super.hCntPhB; hDutyV_1 = pHandle->_Super.hCntPhA; hDutyV_0 = pHandle->_Super.hCntPhC; break; case SECTOR_3: hDutyV_2 = pHandle->_Super.hCntPhB; hDutyV_1 = pHandle->_Super.hCntPhC; hDutyV_0 = pHandle->_Super.hCntPhA; break; case SECTOR_4: hDutyV_2 = pHandle->_Super.hCntPhC; hDutyV_1 = pHandle->_Super.hCntPhB; hDutyV_0 = pHandle->_Super.hCntPhA; break; case SECTOR_5: hDutyV_2 = pHandle->_Super.hCntPhC; hDutyV_1 = pHandle->_Super.hCntPhA; hDutyV_0 = pHandle->_Super.hCntPhB; break; case SECTOR_6: hDutyV_2 = pHandle->_Super.hCntPhA; hDutyV_1 = pHandle->_Super.hCntPhC; hDutyV_0 = pHandle->_Super.hCntPhB; break; default: break; } /* Compute delta duty */ hDeltaDuty_0 = (int16_t)(hDutyV_1) - (int16_t)(hDutyV_0); hDeltaDuty_1 = (int16_t)(hDutyV_2) - (int16_t)(hDutyV_1); /* Check region */ if ((uint16_t)hDeltaDuty_0<=pHandle->pParams_str->hTMin) { if ((uint16_t)hDeltaDuty_1<=pHandle->pParams_str->hTMin) { bStatorFluxPos = BOUNDARY_3; } else { bStatorFluxPos = BOUNDARY_2; } } else { if ((uint16_t)hDeltaDuty_1>pHandle->pParams_str->hTMin) { bStatorFluxPos = REGULAR; } else { bStatorFluxPos = BOUNDARY_1; } } if (bStatorFluxPos == REGULAR) { pHandle->bInverted_pwm_new = INVERT_NONE; } else if (bStatorFluxPos == BOUNDARY_1) /* Adjust the lower */ { switch (bSector) { case SECTOR_5: case SECTOR_6: if (pHandle->_Super.hCntPhA - pHandle->pParams_str->hHTMin - hDutyV_0 > pHandle->pParams_str->hTMin) { pHandle->bInverted_pwm_new = INVERT_A; pHandle->_Super.hCntPhA -=pHandle->pParams_str->hHTMin; if (pHandle->_Super.hCntPhA < hDutyV_1) { hDutyV_1 = pHandle->_Super.hCntPhA; } } else { bStatorFluxPos = BOUNDARY_3; if ((pHandle->hFlags & STBD3) == 0u) { pHandle->bInverted_pwm_new = INVERT_A; pHandle->_Super.hCntPhA -=pHandle->pParams_str->hHTMin; pHandle->hFlags |= STBD3; } else { pHandle->bInverted_pwm_new = INVERT_B; pHandle->_Super.hCntPhB -=pHandle->pParams_str->hHTMin; pHandle->hFlags &= (~STBD3); } } break; case SECTOR_2: case SECTOR_1: if (pHandle->_Super.hCntPhB - pHandle->pParams_str->hHTMin - hDutyV_0 > pHandle->pParams_str->hTMin) { pHandle->bInverted_pwm_new = INVERT_B; pHandle->_Super.hCntPhB -=pHandle->pParams_str->hHTMin; if (pHandle->_Super.hCntPhB < hDutyV_1) { hDutyV_1 = pHandle->_Super.hCntPhB; } } else { bStatorFluxPos = BOUNDARY_3; if ((pHandle->hFlags & STBD3) == 0u) { pHandle->bInverted_pwm_new = INVERT_A; pHandle->_Super.hCntPhA -=pHandle->pParams_str->hHTMin; pHandle->hFlags |= STBD3; } else { pHandle->bInverted_pwm_new = INVERT_B; pHandle->_Super.hCntPhB -=pHandle->pParams_str->hHTMin; pHandle->hFlags &= (~STBD3); } } break; case SECTOR_4: case SECTOR_3: if (pHandle->_Super.hCntPhC - pHandle->pParams_str->hHTMin - hDutyV_0 > pHandle->pParams_str->hTMin) { pHandle->bInverted_pwm_new = INVERT_C; pHandle->_Super.hCntPhC -=pHandle->pParams_str->hHTMin; if (pHandle->_Super.hCntPhC < hDutyV_1) { hDutyV_1 = pHandle->_Super.hCntPhC; } } else { bStatorFluxPos = BOUNDARY_3; if ((pHandle->hFlags & STBD3) == 0u) { pHandle->bInverted_pwm_new = INVERT_A; pHandle->_Super.hCntPhA -=pHandle->pParams_str->hHTMin; pHandle->hFlags |= STBD3; } else { pHandle->bInverted_pwm_new = INVERT_B; pHandle->_Super.hCntPhB -=pHandle->pParams_str->hHTMin; pHandle->hFlags &= (~STBD3); } } break; default: break; } } else if (bStatorFluxPos == BOUNDARY_2) /* Adjust the middler */ { switch (bSector) { case SECTOR_4: case SECTOR_5: /* Invert B */ pHandle->bInverted_pwm_new = INVERT_B; pHandle->_Super.hCntPhB -=pHandle->pParams_str->hHTMin; if (pHandle->_Super.hCntPhB > 0xEFFFu) { pHandle->_Super.hCntPhB = 0u; } break; case SECTOR_2: case SECTOR_3: /* Invert A */ pHandle->bInverted_pwm_new = INVERT_A; pHandle->_Super.hCntPhA -=pHandle->pParams_str->hHTMin; if (pHandle->_Super.hCntPhA > 0xEFFFu) { pHandle->_Super.hCntPhA = 0u; } break; case SECTOR_6: case SECTOR_1: /* Invert C */ pHandle->bInverted_pwm_new = INVERT_C; pHandle->_Super.hCntPhC -=pHandle->pParams_str->hHTMin; if (pHandle->_Super.hCntPhC > 0xEFFFu) { pHandle->_Super.hCntPhC = 0u; } break; default: break; } } else { if ((pHandle->hFlags & STBD3) == 0u) { pHandle->bInverted_pwm_new = INVERT_A; pHandle->_Super.hCntPhA -=pHandle->pParams_str->hHTMin; pHandle->hFlags |= STBD3; } else { pHandle->bInverted_pwm_new = INVERT_B; pHandle->_Super.hCntPhB -=pHandle->pParams_str->hHTMin; pHandle->hFlags &= (~STBD3); } } if (bStatorFluxPos == REGULAR) /* Regular zone */ { /* First point */ /* if ((hDutyV_1 - hDutyV_0 - pHandle->pParams_str->hDeadTime)> pHandle->pParams_str->hMaxTrTs) { pHandle->hCntSmp1 = hDutyV_0 + hDutyV_1 + pHandle->pParams_str->hDeadTime; pHandle->hCntSmp1 >>= 1; } else { */ pHandle->hCntSmp1 = hDutyV_1 - pHandle->pParams_str->hTbefore; /* }*/ /* Second point */ /* if ((hDutyV_2 - hDutyV_1 - pHandle->pParams_str->hDeadTime)> pHandle->pParams_str->hMaxTrTs) { pHandle->hCntSmp2 = hDutyV_1 + hDutyV_2 + pHandle->pParams_str->hDeadTime; pHandle->hCntSmp2 >>= 1; } else {*/ pHandle->hCntSmp2 = hDutyV_2 - pHandle->pParams_str->hTbefore; /* }*/ } if (bStatorFluxPos == BOUNDARY_1) /* Two small, one big */ { /* First point */ /* if ((hDutyV_1 - hDutyV_0 - pHandle->pParams_str->hDeadTime)> pHandle->pParams_str->hMaxTrTs) { pHandle->hCntSmp1 = hDutyV_0 + hDutyV_1 + pHandle->pParams_str->hDeadTime; pHandle->hCntSmp1 >>= 1; } else { */ pHandle->hCntSmp1 = hDutyV_1 - pHandle->pParams_str->hTbefore; /* }*/ /* Second point */ pHandle->hCntSmp2 = pHandle->Half_PWMPeriod - pHandle->pParams_str->hHTMin + pHandle->pParams_str->hTSample; } if (bStatorFluxPos == BOUNDARY_2) /* Two big, one small */ { /* First point */ /* if ((hDutyV_2 - hDutyV_1 - pHandle->pParams_str->hDeadTime)>= pHandle->pParams_str->hMaxTrTs) { pHandle->hCntSmp1 = hDutyV_1 + hDutyV_2 + pHandle->pParams_str->hDeadTime; pHandle->hCntSmp1 >>= 1; } else { */ pHandle->hCntSmp1 = hDutyV_2 - pHandle->pParams_str->hTbefore; /* }*/ /* Second point */ pHandle->hCntSmp2 = pHandle->Half_PWMPeriod - pHandle->pParams_str->hHTMin + pHandle->pParams_str->hTSample; } if (bStatorFluxPos == BOUNDARY_3) { /* First point */ pHandle->hCntSmp1 = hDutyV_0-pHandle->pParams_str->hTbefore; /* Dummy trigger */ /* Second point */ pHandle->hCntSmp2 = pHandle->Half_PWMPeriod - pHandle->pParams_str->hHTMin + pHandle->pParams_str->hTSample; } } else { pHandle->bInverted_pwm_new = INVERT_NONE; bStatorFluxPos = REGULAR; } /* Update Timer Ch 4,6 for ADC triggering and books the queue*/ /* LL_TIM_OC_DisablePreload(TIM1, LL_TIM_CHANNEL_CH4); LL_TIM_OC_DisablePreload(TIM1, LL_TIM_CHANNEL_CH6); TIM1->CCR4 = 0x0u; TIM1->CCR6 = 0xFFFFu; LL_TIM_OC_EnablePreload(TIM1, LL_TIM_CHANNEL_CH4); LL_TIM_OC_EnablePreload(TIM1, LL_TIM_CHANNEL_CH6); */ /* Update ADC Trigger */ TIM1->CCR4 = pHandle->hCntSmp1; /* First point */ TIM1->CCR6 = pHandle->hCntSmp2; /* Second point */ if (bStatorFluxPos == REGULAR) { LL_TIM_SetTriggerOutput2(TIM1, LL_TIM_TRGO2_OC4_RISING_OC6_RISING); // LL_TIM_SetCH5CombinedChannels(TIM1, LL_TIM_GROUPCH5_NONE); MODIFY_REG(TIM1->CCR5, (0x7 << 29), LL_TIM_GROUPCH5_NONE); } else { switch (pHandle->bInverted_pwm_new) { case INVERT_A: //LL_TIM_SetCH5CombinedChannels(TIM1, LL_TIM_GROUPCH5_OC1REFC); MODIFY_REG(TIM1->CCR5, (0x7 << 29), LL_TIM_GROUPCH5_OC1REFC); break; case INVERT_B: //LL_TIM_SetCH5CombinedChannels(TIM1, LL_TIM_GROUPCH5_OC2REFC); MODIFY_REG(TIM1->CCR5, (0x7 << 29), LL_TIM_GROUPCH5_OC2REFC); break; case INVERT_C: //LL_TIM_SetCH5CombinedChannels(TIM1, LL_TIM_GROUPCH5_OC3REFC); MODIFY_REG(TIM1->CCR5, (0x7 << 29), LL_TIM_GROUPCH5_OC3REFC); break; default: break; } LL_TIM_SetTriggerOutput2(TIM1, LL_TIM_TRGO2_OC4_RISING_OC6_FALLING); } /* Update Timer Ch 1,2,3 (These value are required before update event) */ TIM1->CCR1 = pHandle->_Super.hCntPhA; TIM1->CCR2 = pHandle->_Super.hCntPhB; TIM1->CCR3 = pHandle->_Super.hCntPhC; LL_GPIO_ResetOutputPin (GPIOB, LL_GPIO_PIN_3); /*check software error*/ if (LL_TIM_IsActiveFlag_UPDATE(TIM1)) { hAux = MC_DURATION; LL_GPIO_SetOutputPin (GPIOB, LL_GPIO_PIN_10); while (1) { } } else { hAux = MC_NO_ERROR; } if (pHandle->_Super.SWerror == 1u) { hAux = MC_DURATION; pHandle->_Super.SWerror = 0u; } if ((pHandle->hFlags & REGCONVONGOING)==0u) { } else { pHandle->hRegConvValue[pHandle->bRegConvIndex] = (uint16_t)(ADC1->DR); /* ADC Channel and sampling time config for current reading */ ADC1->CHSELR = 1u << pHandle->pParams_str->hIChannel; /* Enable ADC1 EOC DMA */ LL_ADC_REG_SetDMATransfer(ADC1, LL_ADC_REG_DMA_TRANSFER_LIMITED); /* Clear regular conversion ongoing flag */ pHandle->hFlags &= (uint16_t)~REGCONVONGOING; /* Prepare next conversion */ pHandle->bRegConvIndex++; if (pHandle->bRegConvIndex >= pHandle->bRegConvRequested) { pHandle->bRegConvIndex = 0u; } } /* The following instruction can be executed after Update handler before the get phase current (Second EOC) */ /* Set the current sampled */ if (bStatorFluxPos == REGULAR) /* Regual zone */ { pHandle->sampCur1 = REGULAR_SAMP_CUR1[bSector]; pHandle->sampCur2 = REGULAR_SAMP_CUR2[bSector]; } if (bStatorFluxPos == BOUNDARY_1) /* Two small, one big */ { pHandle->sampCur1 = REGULAR_SAMP_CUR1[bSector]; pHandle->sampCur2 = BOUNDR1_SAMP_CUR2[bSector]; } if (bStatorFluxPos == BOUNDARY_2) /* Two big, one small */ { pHandle->sampCur1 = BOUNDR2_SAMP_CUR1[bSector]; pHandle->sampCur2 = BOUNDR2_SAMP_CUR2[bSector]; } if (bStatorFluxPos == BOUNDARY_3) { if (pHandle->bInverted_pwm_new == INVERT_A) { pHandle->sampCur1 = SAMP_OLDB; pHandle->sampCur2 = SAMP_IA; } if (pHandle->bInverted_pwm_new == INVERT_B) { pHandle->sampCur1 = SAMP_OLDA; pHandle->sampCur2 = SAMP_IB; } } /* Limit for the Get Phase current (Second EOC Handler) */ return (hAux); } /** * @brief R1_G0XX implement MC IRQ function TIMER Update * @param this related object * @retval void* It returns always #MC_NULL */ __weak void R1G0XX_TIMx_UP_IRQHandler(PWMC_Handle_t *pHdl) { LL_ADC_REG_SetTriggerSource (ADC1, LL_ADC_REG_TRIG_EXT_TIM1_TRGO2); LL_ADC_REG_StartConversion (ADC1); } /** * @brief Execute a regular conversion. * The function is not re-entrant (can't executed twice at the same time) * It returns 0xFFFF in case of conversion error. * @param pHdl: handler of the current instance of the PWM component, ADC channel to be converted * @param bChannel ADC channel used for the regular conversion * @retval uint16_t It returns converted value or oxFFFF for conversion error */ __weak uint16_t R1G0XX_ExecRegularConv(PWMC_Handle_t *pHdl, uint8_t bChannel) { uint16_t hRetVal = 0xFFFFu; uint8_t i; bool bRegChFound = FALSE; PWMC_R1_G0_Handle_t *pHandle = (PWMC_R1_G0_Handle_t *)pHdl; if (bChannel < 18u) { /* Check if the channel has been already requested */ for (i = 0u; i < pHandle->bRegConvRequested; i++) { if (pHandle->bRegConvCh[i] == bChannel) { hRetVal = pHandle->hRegConvValue[i]; bRegChFound = TRUE; break; } } if (bRegChFound == FALSE) { if (pHandle->bRegConvRequested < MAX_REG_CONVERSIONS) { /* Add new channel to the list */ pHandle->bRegConvCh[pHandle->bRegConvRequested] = bChannel; i = pHandle->bRegConvRequested; pHandle->bRegConvRequested++; } } if ((pHandle->hFlags & CALIB) == 0u) { if ((TIM1->DIER & LL_TIM_DIER_UIE)!= LL_TIM_DIER_UIE) { /* If the Timer update IT is not enabled, the PWM is switch Off */ /* We can start the "regular" conversion immediately */ /* Otherwise, the conversion is done within High frequency task after the current sampling*/ /* Set Sampling time and channel */ ADC1->CHSELR = 1u << bChannel; if (pHandle->bADCSMP2 != pHandle->bRegSmpTime[bChannel] ) { LL_ADC_SetSamplingTimeCommonChannels (ADC1, LL_ADC_SAMPLINGTIME_COMMON_2, pHandle->bRegSmpTime[bChannel]); pHandle->bADCSMP2 = pHandle->bRegSmpTime[bChannel]; } /* Disable ADC1 EOC DMA */ LL_ADC_REG_SetDMATransfer(ADC1, LL_ADC_REG_DMA_TRANSFER_NONE); /* Disabling the External triggering for ADCx*/ LL_ADC_REG_SetTriggerSource (ADC1, LL_ADC_REG_TRIG_SOFTWARE ); /* Clear EOC */ LL_ADC_ClearFlag_EOC(ADC1); /* Start ADC */ LL_ADC_REG_StartConversion(ADC1); /* Wait EOC */ while (LL_ADC_IsActiveFlag_EOC(ADC1) == RESET) { } /* Read the "Regular" conversion (Not related to current sampling) */ hRetVal = LL_ADC_REG_ReadConversionData12(ADC1); pHandle->hRegConvValue[i] = hRetVal; /* Enable ADC1 EOC DMA */ LL_ADC_REG_SetDMATransfer(ADC1, LL_ADC_REG_DMA_TRANSFER_LIMITED); } } } return hRetVal; } /** * @brief It sets the specified sampling time for the specified ADC channel * on ADCx. It must be called once for each channel utilized by user * @param pHdl: handler of the current instance of the PWM component * @retval none */ __weak void R1G0XX_ADC_SetSamplingTime(PWMC_Handle_t *pHdl, ADConv_t ADConv_struct) { PWMC_R1_G0_Handle_t *pHandle = (PWMC_R1_G0_Handle_t *)pHdl; if (ADConv_struct.Channel < 18u) { if (ADConv_struct.SamplTime < 8u) { pHandle->bRegSmpTime[ADConv_struct.Channel] = ADConv_struct.SamplTime; /* Select sampling time common 2 for all regular channels */ /* sampling time common 1 is dedicated to current sampling time */ MODIFY_REG (ADC1->SMPR, 1<<(ADConv_struct.Channel+ADC_SMPR_SMPSEL0_BITOFFSET_POS), 1<<(ADConv_struct.Channel+ADC_SMPR_SMPSEL0_BITOFFSET_POS)); } } } /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
39,351
C
30.059195
148
0.621433
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/G0xx/Src/g0xx_bemf_ADC_fdbk.c
/** ****************************************************************************** * @file g0xx_bemf_ADC_fdbk.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement Bemf sensing * class to be stantiated when the six-step sensorless driving mode * topology is used. * * It is specifically designed for STM32G0XX * microcontrollers and implements the sensing using one ADC with * DMA support. * + MCU peripheral and handle initialization fucntion * + ADC sampling function * ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup SpeednPosFdbk_Bemf */ /* Includes ------------------------------------------------------------------*/ #include "g0xx_bemf_ADC_fdbk.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup SpeednPosFdbk * @{ */ /** @addtogroup SpeednPosFdbk_Bemf * @{ */ /* Private defines -----------------------------------------------------------*/ #define MAX_PSEUDO_SPEED ((int16_t)0x7FFF) #define PHASE_U 0u #define PHASE_V 1u #define PHASE_W 2u /* Private function prototypes -----------------------------------------------*/ void BADC_CalcAvrgElSpeedDpp( Bemf_ADC_Handle_t * pHandle ); /* Private functions ---------------------------------------------------------*/ /* * @brief Initializes ADC1, DMA and NVIC for three bemf voltages reading * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_Init( Bemf_ADC_Handle_t *pHandle) { if ( ( uint32_t )pHandle == ( uint32_t )&pHandle->_Super ) { /* disable IT and flags in case of LL driver usage * workaround for unwanted interrupt enabling done by LL driver */ LL_ADC_DisableIT_EOC( ADC1 ); LL_ADC_ClearFlag_EOC( ADC1 ); LL_ADC_DisableIT_EOS( ADC1 ); LL_ADC_ClearFlag_EOS( ADC1 ); /* ADC Calibration */ LL_ADC_StartCalibration( ADC1 ); while ((LL_ADC_IsCalibrationOnGoing(ADC1) == SET) || (LL_ADC_REG_IsConversionOngoing(ADC1) == SET) || (LL_ADC_REG_IsStopConversionOngoing(ADC1) == SET) || (LL_ADC_IsDisableOngoing(ADC1) == SET)) { /* wait */ } /* Enables the ADC peripheral */ LL_ADC_Enable( ADC1 ); LL_ADC_SetSamplingTimeCommonChannels(ADC1, LL_ADC_SAMPLINGTIME_COMMON_1, LL_ADC_SAMPLINGTIME_1CYCLE_5); /* Wait ADC Ready */ while ( LL_ADC_IsActiveFlag_ADRDY( ADC1 ) == RESET ) { /* wait */ } /* DMA1 Channel1 Config */ LL_DMA_SetMemoryAddress( DMA1, LL_DMA_CHANNEL_1, ( uint32_t )pHandle->ADC1_DMA_converted ); LL_DMA_SetPeriphAddress( DMA1, LL_DMA_CHANNEL_1, ( uint32_t )&ADC1->DR ); LL_DMA_SetDataLength(DMA1, LL_DMA_CHANNEL_1, 1 ); /* We allow ADC usage for regular conversion on Systick*/ pHandle->ADCRegularLocked=false; uint16_t hMinReliableElSpeedUnit = pHandle->_Super.hMinReliableMecSpeedUnit * pHandle->_Super.bElToMecRatio; uint16_t hMaxReliableElSpeedUnit = pHandle->_Super.hMaxReliableMecSpeedUnit * pHandle->_Super.bElToMecRatio; uint8_t bSpeedBufferSize; uint8_t bIndex; uint16_t MinBemfTime; /* Adjustment factor: minimum measurable speed is x time less than the minimum reliable speed */ hMinReliableElSpeedUnit /= 4U; /* Adjustment factor: maximum measurable speed is x time greater than the maximum reliable speed */ hMaxReliableElSpeedUnit *= 2U; pHandle->OvfFreq = (uint16_t)(pHandle->TIMClockFreq / 65536U); /* SW Init */ if (0U == hMinReliableElSpeedUnit) { /* Set fixed to 150 ms */ pHandle->BemfTimeout = 150U; } else { /* Set accordingly the min reliable speed */ /* 1000 comes from mS * 6 comes from the fact that sensors are toggling each 60 deg = 360/6 deg */ pHandle->BemfTimeout = (1000U * (uint16_t)SPEED_UNIT) / (6U * hMinReliableElSpeedUnit); } /* Align MaxPeriod and MinPeriod to a multiple of Overflow.*/ pHandle->MaxPeriod = (pHandle->BemfTimeout * pHandle->OvfFreq) / 1000U * 65536UL; MinBemfTime = ((1000U * (uint16_t)SPEED_UNIT) << 8) / (6U * hMaxReliableElSpeedUnit); pHandle->MinPeriod = ((MinBemfTime * pHandle->OvfFreq) >> 8) / 1000U * 65536UL; pHandle->SatSpeed = hMaxReliableElSpeedUnit; pHandle->PseudoPeriodConv = ((pHandle->TIMClockFreq / 6U) / pHandle->_Super.hMeasurementFrequency) * pHandle->_Super.DPPConvFactor; if (0U == hMaxReliableElSpeedUnit) { pHandle->MinPeriod = ((uint32_t)SPEED_UNIT * (pHandle->TIMClockFreq / 6UL)); } else { pHandle->MinPeriod = (((uint32_t)SPEED_UNIT * (pHandle->TIMClockFreq / 6UL)) / hMaxReliableElSpeedUnit); } pHandle->PWMNbrPSamplingFreq = ((pHandle->_Super.hMeasurementFrequency * pHandle->PWMFreqScaling) / pHandle->SpeedSamplingFreqHz) - 1U; pHandle->pSensing_Params = &(pHandle->Pwm_OFF); pHandle->IsOnSensingEnabled = false; pHandle->ElPeriodSum = 0; pHandle->ZcEvents = 0; pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold; /* Erase speed buffer */ bSpeedBufferSize = pHandle->SpeedBufferSize; for (bIndex = 0u; bIndex < bSpeedBufferSize; bIndex++) { pHandle->SpeedBufferDpp[bIndex] = (int32_t)pHandle->MaxPeriod; } LL_TIM_EnableCounter(pHandle->pParams_str->LfTim); } } /* * @brief Resets the ADC status * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_Clear( Bemf_ADC_Handle_t *pHandle ) { /* Disabling of DMA Interrupt Event configured */ LL_DMA_DisableIT_TC( DMA1, LL_DMA_CHANNEL_1 ); LL_ADC_REG_StopConversion( ADC1 ); /* Disable ADC DMA request*/ ADC1->CFGR1 &= ~ADC_CFGR1_DMAEN; /* Clear Transmission Complete Flag of DMA1 Channel1 */ LL_DMA_ClearFlag_TC1( DMA1 ); /* Clear EOC */ LL_ADC_ClearFlag_EOC( ADC1 ); /* We allow ADC usage for regular conversion on Systick*/ pHandle->ADCRegularLocked=false; pHandle->ZcEvents = 0; pHandle->ElPeriodSum = 0; /* Acceleration measurement not implemented.*/ pHandle->_Super.hMecAccelUnitP = 0; pHandle->BufferFilled = 0U; pHandle->CompSpeed = 0; /* Initialize speed buffer index */ pHandle->SpeedFIFOIdx = 0U; pHandle->_Super.hElAngle = 0; /* Clear speed error counter */ pHandle->_Super.bSpeedErrorNumber = 0; pHandle->IsLoopClosed=false; pHandle->IsAlgorithmConverged = false; } /* * @brief Starts bemf ADC conversion of the phase depending on current step * @param pHandle: handler of the current instance of the Bemf_ADC component * @param step: current step of the six-step sequence */ __weak void BADC_Start(Bemf_ADC_Handle_t *pHandle, uint8_t step) { pHandle->ADCRegularLocked=true; LL_ADC_REG_StopConversion( ADC1 ); /* Enable ADC DMA request*/ LL_ADC_REG_SetDMATransfer( ADC1, LL_ADC_REG_DMA_TRANSFER_UNLIMITED ); /* Enables the DMA1 Channel1 peripheral */ LL_DMA_EnableChannel( DMA1, LL_DMA_CHANNEL_1 ); /* Clear Pending Interrupt Bits */ LL_DMA_ClearFlag_TC1( DMA1 ); /* DMA Interrupt Event configuration */ LL_DMA_EnableIT_TC( DMA1, LL_DMA_CHANNEL_1 ); /* enable ADC source trigger */ LL_ADC_REG_SetTriggerSource (ADC1, LL_ADC_REG_TRIG_EXT_TIM1_TRGO2); LL_ADC_REG_SetTriggerEdge (ADC1, LL_ADC_REG_TRIG_EXT_FALLING); LL_ADC_SetSamplingTimeCommonChannels (ADC1, LL_ADC_SAMPLINGTIME_COMMON_1, LL_ADC_SAMPLINGTIME_1CYCLE_5 ); switch (step) { case STEP_1: case STEP_4: BADC_SelectAdcChannel(pHandle, PHASE_W); break; case STEP_2: case STEP_5: BADC_SelectAdcChannel(pHandle, PHASE_V); break; case STEP_3: case STEP_6: BADC_SelectAdcChannel(pHandle, PHASE_U); break; default: break; } LL_ADC_REG_StartConversion(ADC1); } /* * @brief Stops bemf ADC conversion * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_Stop(Bemf_ADC_Handle_t *pHandle) { LL_ADC_REG_StopConversion( ADC1 ); /* Clear Transmission Complete Flag of DMA1 Channel1 */ LL_DMA_ClearFlag_TC1( DMA1 ); /* Clear EOC */ LL_ADC_ClearFlag_EOC( ADC1 ); } /* * @brief Enables the speed loop (low frequency) timer * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_SpeedMeasureOn(Bemf_ADC_Handle_t *pHandle) { LL_TIM_ClearFlag_UPDATE(pHandle->pParams_str->LfTim); LL_TIM_EnableIT_UPDATE(pHandle->pParams_str->LfTim); } /* * @brief Disables the speed loop (low frequency) timer * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_SpeedMeasureOff(Bemf_ADC_Handle_t *pHandle) { LL_TIM_DisableIT_UPDATE(pHandle->pParams_str->LfTim); } /* * @brief Configures the ADC for the current sampling. * It sets the sampling point via TIM1_Ch4 value, the ADC sequence * and channels. * @param pHandle: handler of the current instance of the Bemf_ADC component * @param pHandlePWMC: handler of the current instance of the PWMC component * @param pHandleSTC: handler of the current instance of the Speed Control component */ __weak void BADC_SetSamplingPoint(Bemf_ADC_Handle_t *pHandle, PWMC_Handle_t *pHandlePWMC, SpeednTorqCtrl_Handle_t *pHandleSTC ) { if ((pHandleSTC->ModeDefault == MCM_SPEED_MODE) && (pHandle->DriveMode == VM)) { if (!(pHandle->IsOnSensingEnabled) && (pHandlePWMC->CntPh > pHandle->OnSensingEnThres)) { pHandle->IsOnSensingEnabled=true; pHandle->pSensing_Params = &(pHandle->Pwm_ON); } else if ((pHandle->IsOnSensingEnabled) && (pHandlePWMC->CntPh < pHandle->OnSensingDisThres)) { pHandle->IsOnSensingEnabled=false; pHandle->pSensing_Params = &(pHandle->Pwm_OFF); } else { } } else { pHandle->IsOnSensingEnabled=false; pHandle->pSensing_Params = &(pHandle->Pwm_OFF); } if (true == pHandle->pParams_str->gpio_divider_available) LL_GPIO_ResetOutputPin( pHandle->pParams_str->bemf_divider_port, pHandle->pParams_str->bemf_divider_pin ); PWMC_SetADCTriggerChannel( pHandlePWMC, pHandle->pSensing_Params->SamplingPoint); } /* * @brief Gets last bemf value and checks for zero crossing detection. * Updates speed loop timer and electrical angle accordingly. * @param pHandle: handler of the current instance of the Bemf_ADC component * @param pHandlePWMC: handler of the current instance of the PWMC component * @retval True if zero has been crossed, false otherwise */ __weak bool BADC_IsZcDetected( Bemf_ADC_Handle_t *pHandle, PWMC_Handle_t *pHandlePWMC) { uint16_t AdcValue = pHandle->ADC1_DMA_converted[0]; bool ZcDetection = false; pHandle->DemagCounter++; if ( pHandle->DemagCounter > pHandle->DemagCounterThreshold) { if (pHandle->ZcDetected == false) { switch(pHandlePWMC->Step) { case STEP_1: pHandle->BemfLastValues[2] = AdcValue; if(pHandle->Direction == 1) { if (AdcValue < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_60_PHASE_SHIFT / 2; } } else { if (AdcValue > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = S16_120_PHASE_SHIFT + S16_60_PHASE_SHIFT / 2; } } break; case STEP_2: pHandle->BemfLastValues[1] = AdcValue; if(pHandle->Direction == 1) { if (AdcValue > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = S16_60_PHASE_SHIFT / 2; } } else { if (AdcValue < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_120_PHASE_SHIFT - S16_60_PHASE_SHIFT / 2; } } break; case STEP_3: pHandle->BemfLastValues[0] = AdcValue; if(pHandle->Direction == 1) { if (AdcValue < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = S16_60_PHASE_SHIFT + S16_60_PHASE_SHIFT / 2; } } else { if (AdcValue > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_60_PHASE_SHIFT - S16_60_PHASE_SHIFT / 2; } } break; case STEP_4: pHandle->BemfLastValues[2] = AdcValue; if(pHandle->Direction == 1) { if (AdcValue > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = S16_120_PHASE_SHIFT + S16_60_PHASE_SHIFT / 2; } } else { if (AdcValue < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_60_PHASE_SHIFT / 2; } } break; case STEP_5: pHandle->BemfLastValues[1] = AdcValue; if(pHandle->Direction == 1) { if (AdcValue < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_120_PHASE_SHIFT - S16_60_PHASE_SHIFT / 2; } } else { if (AdcValue > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = S16_60_PHASE_SHIFT / 2; } } break; case STEP_6: pHandle->BemfLastValues[0] = AdcValue; if(pHandle->Direction == 1) { if (AdcValue > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_60_PHASE_SHIFT - S16_60_PHASE_SHIFT / 2; } } else { if (AdcValue < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = S16_60_PHASE_SHIFT + S16_60_PHASE_SHIFT / 2; } } break; } if (true == ZcDetection) { pHandle->MeasuredElAngle += (S16_60_PHASE_SHIFT/2) - (int16_t)((uint32_t)(pHandle->Zc2CommDelay * S16_60_PHASE_SHIFT)>>9); if (pHandle->ZcEvents > pHandle->StartUpConsistThreshold) { pHandle->IsAlgorithmConverged = true; } pHandle->ZcDetected = true; pHandle->ZcEvents++; switch(pHandlePWMC->Step) { case STEP_1: case STEP_3: case STEP_5: if(pHandle->Direction == 1) { pHandle->ZC_Counter_Down = LL_TIM_GetCounter(pHandle->pParams_str->LfTim); pHandle->ZC_Counter_Last = pHandle->ZC_Counter_Down; } else { pHandle->ZC_Counter_Up = LL_TIM_GetCounter(pHandle->pParams_str->LfTim); pHandle->ZC_Counter_Last = pHandle->ZC_Counter_Up; } break; case STEP_2: case STEP_4: case STEP_6: if(pHandle->Direction == 1) { pHandle->ZC_Counter_Up = LL_TIM_GetCounter(pHandle->pParams_str->LfTim); pHandle->ZC_Counter_Last = pHandle->ZC_Counter_Up; } else { pHandle->ZC_Counter_Down = LL_TIM_GetCounter(pHandle->pParams_str->LfTim); pHandle->ZC_Counter_Last = pHandle->ZC_Counter_Down; } break; } if (true == pHandle->IsAlgorithmConverged) { uint32_t tempReg = (uint32_t )(pHandle->PseudoPeriodConv / ((pHandle->LowFreqTimerPsc + 1) * (pHandle->AvrElSpeedDpp * pHandle->Direction))); LL_TIM_SetAutoReload(pHandle->pParams_str->LfTim,pHandle->ZC_Counter_Last + (((uint32_t)((pHandle->Zc2CommDelay) * tempReg)) >> 9) ); } } } } return ZcDetection; } /* * @brief This method must be called - at least - with the same periodicity * on which speed control is executed. It computes and returns - through * parameter hMecSpeedUnit - the rotor average mechanical speed, * expressed in Unit. Average is computed considering a FIFO depth * equal to SpeedBufferSizeUnit. Moreover it also computes and returns * the reliability state of the sensor. * @param pHandle: handler of the current instance of the Bemf_ADC component * @param pMecSpeedUnit pointer to int16_t, used to return the rotor average * mechanical speed (expressed in the unit defined by SPEED_UNIT) * @retval bool speed sensor reliability, measured with reference to parameters * Reliability_hysteresys, VariancePercentage and SpeedBufferSize * true = sensor information is reliable * false = sensor information is not reliable */ __weak bool BADC_CalcAvrgMecSpeedUnit( Bemf_ADC_Handle_t * pHandle, int16_t * pMecSpeedUnit ) { bool bReliability; pHandle->_Super.hElSpeedDpp = pHandle->AvrElSpeedDpp; if (0 == pHandle->AvrElSpeedDpp) { /* Speed is too low */ *pMecSpeedUnit = 0; } else { /* Check if speed is not to fast */ if (pHandle->AvrElSpeedDpp != MAX_PSEUDO_SPEED) { pHandle->DeltaAngle = pHandle->MeasuredElAngle - pHandle->_Super.hElAngle; pHandle->CompSpeed = (int16_t)((int32_t)(pHandle->DeltaAngle) / (int32_t)(pHandle->PWMNbrPSamplingFreq)); /* Convert el_dpp to MecUnit */ *pMecSpeedUnit = (int16_t)((pHandle->AvrElSpeedDpp * (int32_t)pHandle->_Super.hMeasurementFrequency * (int32_t)SPEED_UNIT ) / ((int32_t)(pHandle->_Super.DPPConvFactor) * (int32_t)(pHandle->_Super.bElToMecRatio)) ); } else { *pMecSpeedUnit = (int16_t)pHandle->SatSpeed; } } bReliability = SPD_IsMecSpeedReliable(&pHandle->_Super, pMecSpeedUnit); pHandle->_Super.hAvrMecSpeedUnit = *pMecSpeedUnit; BADC_CalcAvrgElSpeedDpp (pHandle); return (bReliability); } /* * @brief Returns false if calculated speed is out of reliability ranges * @param pHandle: handler of the current instance of the Bemf_ADC component * @retval bool: reliability flag */ __weak bool BADC_IsSpeedReliable( Bemf_ADC_Handle_t *pHandle ) { bool SpeedError = false; if ( pHandle->_Super.hAvrMecSpeedUnit > pHandle->_Super.hMaxReliableMecSpeedUnit ) { SpeedError = true; } if ( pHandle->_Super.hAvrMecSpeedUnit < pHandle->_Super.hMinReliableMecSpeedUnit ) { SpeedError = true; } return ( SpeedError ); } /* * @brief Forces the rotation direction * @param pHandle: handler of the current instance of the Bemf_ADC component * @param direction: imposed direction */ __weak void BADC_SetDirection( Bemf_ADC_Handle_t * pHandle, uint8_t direction ) { if (MC_NULL == pHandle) { /* Nothing to do */ } else { pHandle->Direction = direction; } } /* * @brief Internally performs a checks necessary to state whether * the bemf algorithm converged. To be periodically called * during motor open-loop ramp-up (e.g. at the same frequency of * SPD_CalcElAngle), it returns true if the estimated angle and speed * can be considered reliable, false otherwise * @param pHandle: handler of the current instance of the Bemf_ADC component * * @retval bool sensor reliability state */ __weak bool BADC_IsObserverConverged( Bemf_ADC_Handle_t * pHandle ) { return pHandle->IsAlgorithmConverged; } /* * @brief Configures the proper ADC channel according to the current * step corresponding to the floating phase. To be periodically called * at least at every step change. * @param pHandle: handler of the current instance of the Bemf_ADC component * @param Phase: Floating phase for bemf acquisition */ void BADC_SelectAdcChannel(Bemf_ADC_Handle_t * pHandle, uint8_t Phase) { while (LL_ADC_REG_IsConversionOngoing(ADC1)) { LL_ADC_REG_StopConversion(ADC1); while(LL_ADC_REG_IsStopConversionOngoing(ADC1)); } /* Sampling time configuration */ /* Regular sequence configuration */ LL_ADC_REG_SetSequencerChannels(ADC1, __LL_ADC_DECIMAL_NB_TO_CHANNEL(pHandle->pParams_str->AdcChannel[Phase])); LL_ADC_ClearFlag_EOC(ADC1); } /* * @brief Updates the estimated electrical angle. * @param pHandle: handler of the current instance of the Bemf_ADC component * @retval int16_t rotor electrical angle (s16Degrees) */ __weak int16_t BADC_CalcElAngle(Bemf_ADC_Handle_t * pHandle) { int16_t retValue; if (pHandle->_Super.hElSpeedDpp != MAX_PSEUDO_SPEED) { if (false == pHandle->IsLoopClosed) { pHandle->MeasuredElAngle += pHandle->_Super.hElSpeedDpp; pHandle->PrevRotorFreq = pHandle->_Super.hElSpeedDpp; pHandle->_Super.hElAngle += pHandle->_Super.hElSpeedDpp + pHandle->CompSpeed; } else { pHandle->_Super.hElAngle = pHandle->MeasuredElAngle; } } else { pHandle->_Super.hElAngle += pHandle->PrevRotorFreq; } retValue = pHandle->_Super.hElAngle; return (retValue); } /* * @brief Must be called - at least - with the same periodicity * on which speed control is executed. It computes and update component * variable hElSpeedDpp that is estimated average electrical speed * expressed in dpp used for instance in observer equations. * Average is computed considering a FIFO depth equal to * bSpeedBufferSizedpp. * @param pHandle: handler of the current instance of the Bemf_ADC component */ void BADC_CalcAvrgElSpeedDpp( Bemf_ADC_Handle_t * pHandle ) { uint32_t wCaptBuf; /* used to validate the average speed measurement */ if (pHandle->BufferFilled < pHandle->SpeedBufferSize) { pHandle->BufferFilled++; } else { /* Nothing to do */ } if (false == pHandle->IsLoopClosed) { if (pHandle->VirtualElSpeedDpp == 0) pHandle->Counter_Period = 0xFFFF; else pHandle->Counter_Period = ( uint32_t )(pHandle->PseudoPeriodConv / ((pHandle->LowFreqTimerPsc + 1) * pHandle->VirtualElSpeedDpp)); } else { pHandle->Counter_Period = pHandle->ZC_Counter_Last + pHandle->Last_Zc2Comm_Delay; } wCaptBuf = pHandle->Counter_Period * (pHandle->LowFreqTimerPsc + 1); /* Filtering to fast speed... could be a glitch ? */ /* the MAX_PSEUDO_SPEED is temporary in the buffer, and never included in average computation*/ if (wCaptBuf < pHandle->MinPeriod) { /* Nothing to do */ } else { pHandle->ElPeriodSum -= pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx]; /* value we gonna removed from the accumulator */ if (wCaptBuf >= pHandle->MaxPeriod) { pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx] = (int32_t)pHandle->MaxPeriod * pHandle->Direction; } else { pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx] = (int32_t)wCaptBuf ; pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx] *= pHandle->Direction; pHandle->ElPeriodSum += pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx]; } /* Update pointers to speed buffer */ pHandle->SpeedFIFOIdx++; if (pHandle->SpeedFIFOIdx == pHandle->SpeedBufferSize) { pHandle->SpeedFIFOIdx = 0U; } if (((pHandle->BufferFilled < pHandle->SpeedBufferSize) && (wCaptBuf != 0U)) || (false == pHandle->IsLoopClosed)) { uint32_t tempReg = (pHandle->PseudoPeriodConv / wCaptBuf) * (uint32_t)pHandle->Direction; pHandle->AvrElSpeedDpp = (int16_t)tempReg; } else { /* Average speed allow to smooth the mechanical sensors misalignement */ int32_t tElPeriodSum = 0; uint8_t i; for (i=0; i < pHandle->SpeedBufferSize; i++) { tElPeriodSum += pHandle->SpeedBufferDpp[i]; } pHandle->AvrElSpeedDpp = (int16_t)((int32_t)pHandle->PseudoPeriodConv / (tElPeriodSum / (int32_t)pHandle->SpeedBufferSize)); /* Average value */ } } } /* * @brief Used to calculate instant speed during revup, to * initialize parameters at step change and to select proper ADC channel * for next Bemf acquisitions * @param pHandle: handler of the current instance of the Bemf_ADC component * @param hElSpeedDpp: Mechanical speed imposed by virtual speed component * @param pHandlePWMC: handler of the current instance of the PWMC component */ void BADC_StepChangeEvent(Bemf_ADC_Handle_t * pHandle, int16_t hElSpeedDpp, PWMC_Handle_t *pHandlePWMC) { pHandle->DemagCounter = 0; while (LL_ADC_REG_IsConversionOngoing(ADC1)) { LL_ADC_REG_StopConversion(ADC1); while(LL_ADC_REG_IsStopConversionOngoing(ADC1)); } BADC_Stop(pHandle); pHandle->Last_Zc2Comm_Delay = LL_TIM_GetAutoReload(pHandle->pParams_str->LfTim) - pHandle->ZC_Counter_Last; if (false == pHandle->IsLoopClosed) { if (hElSpeedDpp < 0) { pHandle->VirtualElSpeedDpp = - hElSpeedDpp; } else { pHandle->VirtualElSpeedDpp = hElSpeedDpp; } pHandle->ZcDetected = false; } else { int16_t ElAngleUpdate; if(pHandle->Direction == -1) { ElAngleUpdate = -S16_60_PHASE_SHIFT ; } else { ElAngleUpdate = S16_60_PHASE_SHIFT ; } pHandle->MeasuredElAngle += ElAngleUpdate; if ( false == pHandle->ZcDetected) { LL_TIM_SetAutoReload(pHandle->pParams_str->LfTim,LL_TIM_GetAutoReload(pHandle->pParams_str->LfTim) * 120 / 100); } else { pHandle->ZcDetected = false; } } pHandle->StepUpdate = true; } /* * @brief Calculates and stores in the corresponding variable the demagnetization * time in open loop operation * @param pHandle: handler of the current instance of the Bemf_ADC component */ void BADC_CalcRevUpDemagTime(Bemf_ADC_Handle_t *pHandle) { int16_t hSpeed; hSpeed = (int16_t)((pHandle->VirtualElSpeedDpp * (int32_t)pHandle->_Super.hMeasurementFrequency * (int32_t)SPEED_UNIT ) / ((int32_t)(pHandle->_Super.DPPConvFactor) * (int32_t)(pHandle->_Super.bElToMecRatio)) );; if (hSpeed == 0) { pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold;; } else { pHandle->DemagCounterThreshold = (uint16_t) (pHandle->DemagParams.RevUpDemagSpeedConv / hSpeed); } if (pHandle->DemagCounterThreshold < pHandle->DemagParams.DemagMinimumThreshold) { pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold; } } /* * @brief Calculates and stores in the corresponding variable the demagnetization * time in closed loop operation * @param pHandle: handler of the current instance of the Bemf_ADC component */ void BADC_CalcRunDemagTime(Bemf_ADC_Handle_t *pHandle) { int16_t hSpeed; hSpeed = pHandle->_Super.hAvrMecSpeedUnit; if (hSpeed < 0) hSpeed = - hSpeed; if (hSpeed < pHandle->DemagParams.DemagMinimumSpeedUnit) { pHandle->DemagCounterThreshold = (uint16_t) (pHandle->DemagParams.RunDemagSpeedConv / hSpeed); if (pHandle->DemagCounterThreshold < pHandle->DemagParams.DemagMinimumThreshold) { pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold; } } else { pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold; } } /* * @brief Must be called after switch-over procedure when * virtual speed sensor transition is ended. * @param pHandle: handler of the current instance of the STO component */ void BADC_SetLoopClosed(Bemf_ADC_Handle_t *pHandle) { pHandle->IsLoopClosed=true; } /* * @brief Returns the last acquired bemf value * @param pHandle: handler of the current instance of the Bemf_ADC component * @param phase: motor phase under investigation * @retval uint16_t: Bemf value */ uint16_t BADC_GetLastBemfValue(Bemf_ADC_Handle_t *pHandle, uint8_t phase) { return ((MC_NULL == pHandle) ? 0U : pHandle->BemfLastValues[phase]); } /* * @brief Returns the zero crossing detection flag * @param pHandle: handler of the current instance of the Bemf_ADC component * @retval bool: zero crossing detection flag */ bool BADC_GetBemfZcrFlag(Bemf_ADC_Handle_t *pHandle) { return ((MC_NULL == pHandle) ? 0U : pHandle->ZcDetected); } /* * @brief Returns true if the step needs to be updated * @param pHandle: handler of the current instance of the Bemf_ADC component * @retval bool: step update request */ bool BADC_ClearStepUpdate(Bemf_ADC_Handle_t *pHandle) { bool retValue = (((pHandle->IsLoopClosed == true) && (pHandle->StepUpdate == true)) || (pHandle->IsLoopClosed == false)); pHandle->StepUpdate = false; return retValue; } /* * @brief Configures the parameters for bemf sensing during pwm off-time * @param pHandle: handler of the current instance of the Bemf_ADC component * @param BemfAdcConfig: thresholds and sampling time parameters * @param Zc2CommDelay: delay between bemf zero crossing parameter and step commutation * @param bemfAdcDemagConfig: demagnetization parameters */ void BADC_SetBemfSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfAdcConfig, uint16_t *Zc2CommDelay, Bemf_Demag_Params *bemfAdcDemagConfig) { pHandle->Pwm_OFF.AdcThresholdUp = BemfAdcConfig->AdcThresholdUp; pHandle->Pwm_OFF.AdcThresholdDown = BemfAdcConfig->AdcThresholdDown; pHandle->Pwm_OFF.SamplingPoint = BemfAdcConfig->SamplingPoint; pHandle->Zc2CommDelay = *Zc2CommDelay; pHandle->DemagParams.DemagMinimumSpeedUnit = bemfAdcDemagConfig->DemagMinimumSpeedUnit; pHandle->DemagParams.DemagMinimumThreshold = bemfAdcDemagConfig->DemagMinimumThreshold; } /* * @brief Configures the parameters for bemf sensing during pwm on-time * @param pHandle: handler of the current instance of the Bemf_ADC component * @param BemfOnAdcConfig: thresholds and sampling time parameters * @param OnSensingEnThres: Minimum dudty cycle for on-sensing activation * @param OnSensingDisThres: Minimum duty cycle for on-sensing Deactivationg */ void BADC_SetBemfOnTimeSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfOnAdcConfig, uint16_t *OnSensingEnThres, uint16_t *OnSensingDisThres) { pHandle->Pwm_ON.AdcThresholdUp = BemfOnAdcConfig->AdcThresholdUp; pHandle->Pwm_ON.AdcThresholdDown = BemfOnAdcConfig->AdcThresholdDown; pHandle->Pwm_ON.SamplingPoint = BemfOnAdcConfig->SamplingPoint; pHandle->OnSensingEnThres = *OnSensingEnThres; pHandle->OnSensingDisThres = *OnSensingDisThres; } /* * @brief Gets the parameters for bemf sensing during pwm off-time * @param pHandle: handler of the current instance of the Bemf_ADC component * @param BemfAdcConfig: thresholds and sampling time parameters * @param Zc2CommDelay: delay between bemf zero crossing parameter and step commutation * @param BemfAdcDemagConfig: demagnetization parameters */ void BADC_GetBemfSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfAdcConfig, uint16_t *Zc2CommDelay, Bemf_Demag_Params *BemfAdcDemagConfig) { BemfAdcConfig->AdcThresholdUp = pHandle->Pwm_OFF.AdcThresholdUp; BemfAdcConfig->AdcThresholdDown = pHandle->Pwm_OFF.AdcThresholdDown; BemfAdcConfig->SamplingPoint = pHandle->Pwm_OFF.SamplingPoint; *Zc2CommDelay = pHandle->Zc2CommDelay; BemfAdcDemagConfig->DemagMinimumSpeedUnit = pHandle->DemagParams.DemagMinimumSpeedUnit; BemfAdcDemagConfig->DemagMinimumThreshold = pHandle->DemagParams.DemagMinimumThreshold; } /* * @brief Gets the parameters for bemf sensing during pwm on-time * @param pHandle: handler of the current instance of the Bemf_ADC component * @param BemfOnAdcConfig: thresholds and sampling time parameters * @param OnSensingEnThres: Minimum duty cycle for on-sensing activation * @param OnSensingDisThres: Minimum duty cycle for on-sensing Deactivationg */ void BADC_GetBemfOnTimeSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfOnAdcConfig, uint16_t *OnSensingEnThres, uint16_t *OnSensingDisThres) { BemfOnAdcConfig->AdcThresholdUp = pHandle->Pwm_ON.AdcThresholdUp; BemfOnAdcConfig->AdcThresholdDown = pHandle->Pwm_ON.AdcThresholdDown; BemfOnAdcConfig->SamplingPoint = pHandle->Pwm_ON.SamplingPoint; *OnSensingEnThres = pHandle->OnSensingEnThres; *OnSensingDisThres = pHandle->OnSensingDisThres; } /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
33,739
C
33.783505
167
0.643558
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/G0xx/Src/g0xx_bemf_ADC_OS_fdbk.c
/** ****************************************************************************** * @file g0xx_bemf_ADC_OS_fdbk.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement Bemf sensing * class to be stantiated when the six-step sensorless driving mode * topology is used. Differently from standard implementation, * this one performs multiple acquisition during a PWM cycle. * * It is specifically designed for STM32G0XX * microcontrollers and implements the sensing using one ADC with * DMA support. * + MCU peripheral and handle initialization fucntion * + ADC sampling function * ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup SpeednPosFdbk_Bemf */ /* Includes ------------------------------------------------------------------*/ #include "g0xx_bemf_ADC_OS_fdbk.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup SpeednPosFdbk * @{ */ /** @addtogroup SpeednPosFdbk_Bemf * @{ */ /* Private defines -----------------------------------------------------------*/ #define MAX_PSEUDO_SPEED ((int16_t)0x7FFF) #define PHASE_U 0u #define PHASE_V 1u #define PHASE_W 2u /* Private function prototypes -----------------------------------------------*/ void BADC_CalcAvrgElSpeedDpp( Bemf_ADC_Handle_t * pHandle ); /* Private functions ---------------------------------------------------------*/ /* * @brief Initializes ADC1, DMA and NVIC for three bemf voltages reading * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_Init( Bemf_ADC_Handle_t *pHandle) { uint8_t i; uint32_t tArray; if ( ( uint32_t )pHandle == ( uint32_t )&pHandle->_Super ) { /* disable IT and flags in case of LL driver usage * workaround for unwanted interrupt enabling done by LL driver */ LL_ADC_DisableIT_EOC( ADC1 ); LL_ADC_ClearFlag_EOC( ADC1 ); LL_ADC_DisableIT_EOS( ADC1 ); LL_ADC_ClearFlag_EOS( ADC1 ); /* ADC Calibration */ LL_ADC_StartCalibration( ADC1 ); while ((LL_ADC_IsCalibrationOnGoing(ADC1) == SET) || (LL_ADC_REG_IsConversionOngoing(ADC1) == SET) || (LL_ADC_REG_IsStopConversionOngoing(ADC1) == SET) || (LL_ADC_IsDisableOngoing(ADC1) == SET)) { /* wait */ } /* Enables the ADC peripheral */ LL_ADC_Enable( ADC1 ); LL_ADC_SetSamplingTimeCommonChannels(ADC1, LL_ADC_SAMPLINGTIME_COMMON_1, LL_ADC_SAMPLINGTIME_1CYCLE_5); /* Wait ADC Ready */ while ( LL_ADC_IsActiveFlag_ADRDY( ADC1 ) == RESET ) { /* wait */ } /* DMA1 Channel1 Config */ LL_DMA_SetMemoryAddress( DMA1, LL_DMA_CHANNEL_1, ( uint32_t )pHandle->ADC1_DMA_converted ); LL_DMA_SetPeriphAddress( DMA1, LL_DMA_CHANNEL_1, ( uint32_t )&ADC1->DR ); LL_DMA_SetDataLength(DMA1, LL_DMA_CHANNEL_1, pHandle->OverSamplingRate ); /* We allow ADC usage for regular conversion on Systick*/ pHandle->ADCRegularLocked=false; uint16_t hMinReliableElSpeedUnit = pHandle->_Super.hMinReliableMecSpeedUnit * pHandle->_Super.bElToMecRatio; uint16_t hMaxReliableElSpeedUnit = pHandle->_Super.hMaxReliableMecSpeedUnit * pHandle->_Super.bElToMecRatio; uint8_t bSpeedBufferSize; uint8_t bIndex; uint16_t MinBemfTime; /* Adjustment factor: minimum measurable speed is x time less than the minimum reliable speed */ hMinReliableElSpeedUnit /= 4U; /* Adjustment factor: maximum measurable speed is x time greater than the maximum reliable speed */ hMaxReliableElSpeedUnit *= 2U; pHandle->OvfFreq = (uint16_t)(pHandle->TIMClockFreq / 65536U); /* SW Init */ if (0U == hMinReliableElSpeedUnit) { /* Set fixed to 150 ms */ pHandle->BemfTimeout = 150U; } else { /* Set accordingly the min reliable speed */ /* 1000 comes from mS * 6 comes from the fact that sensors are toggling each 60 deg = 360/6 deg */ pHandle->BemfTimeout = (1000U * (uint16_t)SPEED_UNIT) / (6U * hMinReliableElSpeedUnit); } /* Align MaxPeriod and MinPeriod to a multiple of Overflow.*/ pHandle->MaxPeriod = (pHandle->BemfTimeout * pHandle->OvfFreq) / 1000U * 65536UL; MinBemfTime = ((1000U * (uint16_t)SPEED_UNIT) << 8) / (6U * hMaxReliableElSpeedUnit); pHandle->MinPeriod = ((MinBemfTime * pHandle->OvfFreq) >> 8) / 1000U * 65536UL; pHandle->SatSpeed = hMaxReliableElSpeedUnit; pHandle->PseudoPeriodConv = ((pHandle->TIMClockFreq / 6U) / pHandle->_Super.hMeasurementFrequency) * pHandle->_Super.DPPConvFactor; if (0U == hMaxReliableElSpeedUnit) { pHandle->MinPeriod = ((uint32_t)SPEED_UNIT * (pHandle->TIMClockFreq / 6UL)); } else { pHandle->MinPeriod = (((uint32_t)SPEED_UNIT * (pHandle->TIMClockFreq / 6UL)) / hMaxReliableElSpeedUnit); } pHandle->PWMNbrPSamplingFreq = ((pHandle->_Super.hMeasurementFrequency * pHandle->PWMFreqScaling) / pHandle->SpeedSamplingFreqHz) - 1U; pHandle->pSensing_Params = &(pHandle->Pwm_OFF); pHandle->IsOnSensingEnabled = false; pHandle->ElPeriodSum = 0; pHandle->ZcEvents = 0; pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold; /* Erase speed buffer */ bSpeedBufferSize = pHandle->SpeedBufferSize; for (bIndex = 0u; bIndex < bSpeedBufferSize; bIndex++) { pHandle->SpeedBufferDpp[bIndex] = (int32_t)pHandle->MaxPeriod; } LL_TIM_CC_EnableChannel( pHandle->pParams_str->TIM_Trigger, pHandle->pParams_str->TIM_ADC_Trigger_Channel ); LL_TIM_EnableCounter( pHandle->pParams_str->TIM_Trigger ); tArray = LL_TIM_GetAutoReload(pHandle->pParams_str->TIM_Trigger); LL_TIM_OC_SetCompareCH1( pHandle->pParams_str->TIM_Trigger, pHandle->pSensing_Params->SamplingPoint); for (i=0; i<pHandle->OverSamplingRate; i++) { pHandle->TIM1_pulses[i]= tArray * i + pHandle->Pwm_OFF.SamplingPoint; } LL_TIM_EnableCounter(pHandle->pParams_str->LfTim); } } /* * @brief Resets the ADC status * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_Clear( Bemf_ADC_Handle_t *pHandle ) { /* Disabling of DMA Interrupt Event configured */ LL_DMA_DisableIT_TC( DMA1, LL_DMA_CHANNEL_1 ); LL_ADC_REG_StopConversion( ADC1 ); /* Disable ADC DMA request*/ ADC1->CFGR1 &= ~ADC_CFGR1_DMAEN; /* Clear Transmission Complete Flag of DMA1 Channel1 */ LL_DMA_ClearFlag_TC1( DMA1 ); /* Clear EOC */ LL_ADC_ClearFlag_EOC( ADC1 ); /* We allow ADC usage for regular conversion on Systick*/ pHandle->ADCRegularLocked=false; pHandle->ZcEvents = 0; pHandle->ElPeriodSum = 0; /* Acceleration measurement not implemented.*/ pHandle->_Super.hMecAccelUnitP = 0; pHandle->BufferFilled = 0U; pHandle->CompSpeed = 0; /* Initialize speed buffer index */ pHandle->SpeedFIFOIdx = 0U; pHandle->_Super.hElAngle = 0; /* Clear speed error counter */ pHandle->_Super.bSpeedErrorNumber = 0; pHandle->IsLoopClosed=false; pHandle->IsAlgorithmConverged = false; } /* * @brief Starts bemf ADC conversion of the phase depending on current step * @param pHandle: handler of the current instance of the Bemf_ADC component * @param step: current step of the six-step sequence */ __weak void BADC_Start(Bemf_ADC_Handle_t *pHandle, uint8_t step) { pHandle->ADCRegularLocked=true; LL_ADC_REG_StopConversion( ADC1 ); /* Enable ADC DMA request*/ LL_ADC_REG_SetDMATransfer( ADC1, LL_ADC_REG_DMA_TRANSFER_UNLIMITED ); /* enable ADC source trigger */ LL_ADC_REG_SetTriggerSource (ADC1, LL_ADC_REG_TRIG_EXT_TIM2_TRGO); LL_ADC_REG_SetTriggerEdge (ADC1, LL_ADC_REG_TRIG_EXT_FALLING); LL_ADC_SetSamplingTimeCommonChannels (ADC1, LL_ADC_SAMPLINGTIME_COMMON_1, LL_ADC_SAMPLINGTIME_1CYCLE_5 ); switch (step) { case STEP_1: case STEP_4: BADC_SelectAdcChannel(pHandle, PHASE_W); break; case STEP_2: case STEP_5: BADC_SelectAdcChannel(pHandle, PHASE_V); break; case STEP_3: case STEP_6: BADC_SelectAdcChannel(pHandle, PHASE_U); break; default: break; } LL_DMA_DisableChannel(DMA1, LL_DMA_CHANNEL_1 ); LL_DMA_SetDataLength(DMA1, LL_DMA_CHANNEL_1, pHandle->OverSamplingRate ); LL_DMA_EnableChannel( DMA1, LL_DMA_CHANNEL_1 ); /* Clear Pending Interrupt Bits */ LL_DMA_ClearFlag_TC1( DMA1 ); /* DMA Interrupt Event configuration */ LL_DMA_EnableIT_TC( DMA1, LL_DMA_CHANNEL_1 ); LL_ADC_REG_StartConversion(ADC1); LL_TIM_GenerateEvent_UPDATE(TIM1); } /* * @brief Stops bemf ADC conversion * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_Stop(Bemf_ADC_Handle_t *pHandle) { LL_ADC_REG_StopConversion( ADC1 ); /* Clear Transmission Complete Flag of DMA1 Channel1 */ LL_DMA_ClearFlag_TC1( DMA1 ); /* Clear EOC */ LL_ADC_ClearFlag_EOC( ADC1 ); } /* * @brief Enables the speed loop (low frequency) timer * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_SpeedMeasureOn(Bemf_ADC_Handle_t *pHandle) { LL_TIM_ClearFlag_UPDATE(pHandle->pParams_str->LfTim); LL_TIM_EnableIT_UPDATE(pHandle->pParams_str->LfTim); } /* * @brief Disables the speed loop (low frequency) timer * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_SpeedMeasureOff(Bemf_ADC_Handle_t *pHandle) { LL_TIM_DisableIT_UPDATE(pHandle->pParams_str->LfTim); } /* * @brief Configures the ADC for the current sampling. * It means set the sampling point via TIM1_Ch4 value, the ADC sequence * and channels. * @param pHandle: handler of the current instance of the Bemf_ADC component * @param pHandlePWMC: handler of the current instance of the PWMC component * @param pHandleSTC: handler of the current instance of the Speed Control component */ __weak void BADC_SetSamplingPoint(Bemf_ADC_Handle_t *pHandle, PWMC_Handle_t *pHandlePWMC, SpeednTorqCtrl_Handle_t *pHandleSTC ) { if ((pHandleSTC->ModeDefault == MCM_SPEED_MODE) && (pHandle->DriveMode == VM)) { if (!(pHandle->IsOnSensingEnabled) && (pHandlePWMC->CntPh > pHandle->OnSensingEnThres)) { pHandle->IsOnSensingEnabled=true; pHandle->pSensing_Params = &(pHandle->Pwm_ON); } else if ((pHandle->IsOnSensingEnabled) && (pHandlePWMC->CntPh < pHandle->OnSensingDisThres)) { pHandle->IsOnSensingEnabled=false; pHandle->pSensing_Params = &(pHandle->Pwm_OFF); } else { } } else { pHandle->IsOnSensingEnabled=false; pHandle->pSensing_Params = &(pHandle->Pwm_OFF); } if (true == pHandle->pParams_str->gpio_divider_available) LL_GPIO_ResetOutputPin( pHandle->pParams_str->bemf_divider_port, pHandle->pParams_str->bemf_divider_pin ); LL_TIM_OC_SetCompareCH1( pHandle->pParams_str->TIM_Trigger, pHandle->pSensing_Params->SamplingPoint); } /* * @brief Gets last bemf value and checks for zero crossing detection. * Updates speed loop timer and electrical angle accordingly. * @param pHandle: handler of the current instance of the Bemf_ADC component * @param pHandlePWMC: handler of the current instance of the PWMC component * @retval none */ __weak bool BADC_IsZcDetected( Bemf_ADC_Handle_t *pHandle, PWMC_Handle_t *pHandlePWMC) { uint8_t i; uint32_t DeltaCounter, tZC_Counter = pHandle->ZC_Counter_On_Last; bool ZcDetection = false; pHandle->DemagCounter++; if ( pHandle->DemagCounter >= pHandle->DemagCounterThreshold) { if (pHandle->ZcDetected == false) { for (i=0; i<pHandle->OverSamplingRate; i++) { if (((pHandle->TIM1_pulses[i] > (pHandlePWMC->CntPh + pHandle->SamplingGuard)) && (false == pHandle->IsOnSensingEnabled)) || ((pHandle->TIM1_pulses[i] < (pHandlePWMC->CntPh - pHandle->SamplingGuard)) && (true == pHandle->IsOnSensingEnabled))) { switch(pHandlePWMC->Step) { case STEP_1: pHandle->BemfLastValues[2] = pHandle->ADC1_DMA_converted[i]; if(pHandle->Direction == 1) { if (pHandle->ADC1_DMA_converted[i] < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_60_PHASE_SHIFT / 2; } } else { if (pHandle->ADC1_DMA_converted[i] > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = S16_120_PHASE_SHIFT + S16_60_PHASE_SHIFT / 2; } } break; case STEP_2: pHandle->BemfLastValues[1] = pHandle->ADC1_DMA_converted[i]; if(pHandle->Direction == 1) { if (pHandle->ADC1_DMA_converted[i] > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = S16_60_PHASE_SHIFT / 2; } } else { if (pHandle->ADC1_DMA_converted[i] < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_120_PHASE_SHIFT - S16_60_PHASE_SHIFT / 2; } } break; case STEP_3: pHandle->BemfLastValues[0] = pHandle->ADC1_DMA_converted[i]; if(pHandle->Direction == 1) { if (pHandle->ADC1_DMA_converted[i] < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = S16_60_PHASE_SHIFT + S16_60_PHASE_SHIFT / 2; } } else { if (pHandle->ADC1_DMA_converted[i] > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_60_PHASE_SHIFT - S16_60_PHASE_SHIFT / 2; } } break; case STEP_4: pHandle->BemfLastValues[2] = pHandle->ADC1_DMA_converted[i]; if(pHandle->Direction == 1) { if (pHandle->ADC1_DMA_converted[i] > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = S16_120_PHASE_SHIFT + S16_60_PHASE_SHIFT / 2; } } else { if (pHandle->ADC1_DMA_converted[i] < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_60_PHASE_SHIFT / 2; } } break; case STEP_5: pHandle->BemfLastValues[1] = pHandle->ADC1_DMA_converted[i]; if(pHandle->Direction == 1) { if (pHandle->ADC1_DMA_converted[i] < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_120_PHASE_SHIFT - S16_60_PHASE_SHIFT / 2; } } else { if (pHandle->ADC1_DMA_converted[i] > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = S16_60_PHASE_SHIFT / 2; } } break; case STEP_6: pHandle->BemfLastValues[0] = pHandle->ADC1_DMA_converted[i]; if(pHandle->Direction == 1) { if (pHandle->ADC1_DMA_converted[i] > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_60_PHASE_SHIFT - S16_60_PHASE_SHIFT / 2; } } else { if (pHandle->ADC1_DMA_converted[i] < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = S16_60_PHASE_SHIFT + S16_60_PHASE_SHIFT / 2; } } break; } if (ZcDetection == true) { DeltaCounter = pHandle->TIM1_pulses[pHandle->OverSamplingRate - 1] - pHandle->TIM1_pulses[i]; break; } } else if ((pHandle->TIM1_pulses[i] < (pHandlePWMC->CntPh - pHandle->SamplingGuard)) && (false == pHandle->IsOnSensingEnabled) && (pHandle->ZcDetected == false)) { tZC_Counter = pHandle->ADC1_DMA_converted[i]; } } } if (true == ZcDetection) { pHandle->ZC_Counter_On_Last = tZC_Counter; pHandle->MeasuredElAngle += (S16_60_PHASE_SHIFT/2) - (int16_t)((uint32_t)(pHandle->Zc2CommDelay * S16_60_PHASE_SHIFT)>>9); if (pHandle->ZcEvents > pHandle->StartUpConsistThreshold) { pHandle->IsAlgorithmConverged = true; } pHandle->ZcDetected = true; pHandle->ZcEvents++; switch(pHandlePWMC->Step) { case STEP_1: case STEP_3: case STEP_5: if(pHandle->Direction == 1) { pHandle->ZC_Counter_Down = LL_TIM_GetCounter(pHandle->pParams_str->LfTim) - DeltaCounter/(pHandle->LowFreqTimerPsc + 1); pHandle->ZC_Counter_Last = pHandle->ZC_Counter_Down; } else { pHandle->ZC_Counter_Up = LL_TIM_GetCounter(pHandle->pParams_str->LfTim) - DeltaCounter/(pHandle->LowFreqTimerPsc + 1); pHandle->ZC_Counter_Last = pHandle->ZC_Counter_Up; } break; case STEP_2: case STEP_4: case STEP_6: if(pHandle->Direction == 1) { pHandle->ZC_Counter_Up = LL_TIM_GetCounter(pHandle->pParams_str->LfTim) - DeltaCounter/(pHandle->LowFreqTimerPsc + 1); pHandle->ZC_Counter_Last = pHandle->ZC_Counter_Up; } else { pHandle->ZC_Counter_Down = LL_TIM_GetCounter(pHandle->pParams_str->LfTim) - DeltaCounter/(pHandle->LowFreqTimerPsc + 1); pHandle->ZC_Counter_Last = pHandle->ZC_Counter_Down; } break; } if (true == pHandle->IsAlgorithmConverged) { uint32_t tempReg = (uint32_t )(pHandle->PseudoPeriodConv / ((pHandle->LowFreqTimerPsc + 1) * (pHandle->AvrElSpeedDpp * pHandle->Direction))); LL_TIM_SetAutoReload(pHandle->pParams_str->LfTim,pHandle->ZC_Counter_Last + (((uint32_t)((pHandle->Zc2CommDelay) * tempReg)) >> 9) ); } } } return ZcDetection; } /* * @brief This method must be called - at least - with the same periodicity * on which speed control is executed. It computes and returns - through * parameter hMecSpeedUnit - the rotor average mechanical speed, * expressed in Unit. Average is computed considering a FIFO depth * equal to SpeedBufferSizeUnit. Moreover it also computes and returns * the reliability state of the sensor. * @param pHandle: handler of the current instance of the Bemf_ADC component * @param pMecSpeedUnit pointer to int16_t, used to return the rotor average * mechanical speed (expressed in the unit defined by SPEED_UNIT) * @retval bool speed sensor reliability, measured with reference to parameters * Reliability_hysteresys, VariancePercentage and SpeedBufferSize * true = sensor information is reliable * false = sensor information is not reliable */ __weak bool BADC_CalcAvrgMecSpeedUnit( Bemf_ADC_Handle_t * pHandle, int16_t * pMecSpeedUnit ) { bool bReliability; pHandle->_Super.hElSpeedDpp = pHandle->AvrElSpeedDpp; if (0 == pHandle->AvrElSpeedDpp) { /* Speed is too low */ *pMecSpeedUnit = 0; } else { /* Check if speed is not to fast */ if (pHandle->AvrElSpeedDpp != MAX_PSEUDO_SPEED) { pHandle->DeltaAngle = pHandle->MeasuredElAngle - pHandle->_Super.hElAngle; pHandle->CompSpeed = (int16_t)((int32_t)(pHandle->DeltaAngle) / (int32_t)(pHandle->PWMNbrPSamplingFreq)); /* Convert el_dpp to MecUnit */ *pMecSpeedUnit = (int16_t)((pHandle->AvrElSpeedDpp * (int32_t)pHandle->_Super.hMeasurementFrequency * (int32_t)SPEED_UNIT ) / ((int32_t)(pHandle->_Super.DPPConvFactor) * (int32_t)(pHandle->_Super.bElToMecRatio)) ); } else { *pMecSpeedUnit = (int16_t)pHandle->SatSpeed; } } bReliability = SPD_IsMecSpeedReliable(&pHandle->_Super, pMecSpeedUnit); pHandle->_Super.hAvrMecSpeedUnit = *pMecSpeedUnit; BADC_CalcAvrgElSpeedDpp (pHandle); return (bReliability); } /* * @brief Returns false if calculated speed is out of reliability ranges * @param pHandle: handler of the current instance of the Bemf_ADC component * @retval bool: reliability flag */ __weak bool BADC_IsSpeedReliable( Bemf_ADC_Handle_t *pHandle ) { bool SpeedError = false; if ( pHandle->_Super.hAvrMecSpeedUnit > pHandle->_Super.hMaxReliableMecSpeedUnit ) { SpeedError = true; } if ( pHandle->_Super.hAvrMecSpeedUnit < pHandle->_Super.hMinReliableMecSpeedUnit ) { SpeedError = true; } return ( SpeedError ); } /* * @brief Forces the rotation direction * @param pHandle: handler of the current instance of the Bemf_ADC component * @param direction: imposed direction */ __weak void BADC_SetDirection( Bemf_ADC_Handle_t * pHandle, uint8_t direction ) { if (MC_NULL == pHandle) { /* Nothing to do */ } else { pHandle->Direction = direction; } } /* * @brief Internally performs a checks necessary to state whether * the bemf algorithm converged. To be periodically called * during motor open-loop ramp-up (e.g. at the same frequency of * SPD_CalcElAngle), it returns true if the estimated angle and speed * can be considered reliable, false otherwise * @param pHandle: handler of the current instance of the Bemf_ADC component * * @retval bool sensor reliability state */ __weak bool BADC_IsObserverConverged( Bemf_ADC_Handle_t * pHandle ) { return pHandle->IsAlgorithmConverged; } /* * @brief Configures the proper ADC channel according to the current * step corresponding to the floating phase. To be periodically called * at least at every step change. * @param pHandle: handler of the current instance of the Bemf_ADC component * @param Phase: Floating phase for bemf acquisition */ void BADC_SelectAdcChannel(Bemf_ADC_Handle_t * pHandle, uint8_t Phase) { while (LL_ADC_REG_IsConversionOngoing(ADC1)) { LL_ADC_REG_StopConversion(ADC1); while(LL_ADC_REG_IsStopConversionOngoing(ADC1)); } /* Sampling time configuration */ /* Regular sequence configuration */ LL_ADC_REG_SetSequencerChannels(ADC1, __LL_ADC_DECIMAL_NB_TO_CHANNEL(pHandle->pParams_str->AdcChannel[Phase])); LL_ADC_ClearFlag_EOC(ADC1); } /* * @brief Updates the estimated electrical angle. * @param pHandle: handler of the current instance of the Bemf_ADC component * @retval int16_t rotor electrical angle (s16Degrees) */ __weak int16_t BADC_CalcElAngle(Bemf_ADC_Handle_t * pHandle) { int16_t retValue; if (pHandle->_Super.hElSpeedDpp != MAX_PSEUDO_SPEED) { if (false == pHandle->IsLoopClosed) { pHandle->MeasuredElAngle += pHandle->_Super.hElSpeedDpp; pHandle->PrevRotorFreq = pHandle->_Super.hElSpeedDpp; pHandle->_Super.hElAngle += pHandle->_Super.hElSpeedDpp + pHandle->CompSpeed; } else { pHandle->_Super.hElAngle = pHandle->MeasuredElAngle; } } else { pHandle->_Super.hElAngle += pHandle->PrevRotorFreq; } retValue = pHandle->_Super.hElAngle; return (retValue); } /* * @brief Must be called - at least - with the same periodicity * on which speed control is executed. It computes and update component * variable hElSpeedDpp that is estimated average electrical speed * expressed in dpp used for instance in observer equations. * Average is computed considering a FIFO depth equal to * bSpeedBufferSizedpp. * @param pHandle: handler of the current instance of the Bemf_ADC component */ void BADC_CalcAvrgElSpeedDpp( Bemf_ADC_Handle_t * pHandle ) { uint32_t wCaptBuf; /* used to validate the average speed measurement */ if (pHandle->BufferFilled < pHandle->SpeedBufferSize) { pHandle->BufferFilled++; } else { /* Nothing to do */ } if (false == pHandle->IsLoopClosed) { if (pHandle->VirtualElSpeedDpp == 0) pHandle->Counter_Period = 0xFFFF; else pHandle->Counter_Period = ( uint32_t )(pHandle->PseudoPeriodConv / ((pHandle->LowFreqTimerPsc + 1) * pHandle->VirtualElSpeedDpp)); } else { pHandle->Counter_Period = pHandle->ZC_Counter_Last + pHandle->Last_Zc2Comm_Delay; } wCaptBuf = pHandle->Counter_Period * (pHandle->LowFreqTimerPsc + 1); /* Filtering to fast speed... could be a glitch ? */ /* the MAX_PSEUDO_SPEED is temporary in the buffer, and never included in average computation*/ if (wCaptBuf < pHandle->MinPeriod) { /* Nothing to do */ } else { pHandle->ElPeriodSum -= pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx]; /* value we gonna removed from the accumulator */ if (wCaptBuf >= pHandle->MaxPeriod) { pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx] = (int32_t)pHandle->MaxPeriod * pHandle->Direction; } else { pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx] = (int32_t)wCaptBuf ; pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx] *= pHandle->Direction; pHandle->ElPeriodSum += pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx]; } /* Update pointers to speed buffer */ pHandle->SpeedFIFOIdx++; if (pHandle->SpeedFIFOIdx == pHandle->SpeedBufferSize) { pHandle->SpeedFIFOIdx = 0U; } if (((pHandle->BufferFilled < pHandle->SpeedBufferSize) && (wCaptBuf != 0U)) || (false == pHandle->IsLoopClosed)) { uint32_t tempReg = (pHandle->PseudoPeriodConv / wCaptBuf) * (uint32_t)pHandle->Direction; pHandle->AvrElSpeedDpp = (int16_t)tempReg; } else { /* Average speed allow to smooth the mechanical sensors misalignement */ int32_t tElPeriodSum = 0; uint8_t i; for (i=0; i < pHandle->SpeedBufferSize; i++) { tElPeriodSum += pHandle->SpeedBufferDpp[i]; } pHandle->AvrElSpeedDpp = (int16_t)((int32_t)pHandle->PseudoPeriodConv / (tElPeriodSum / (int32_t)pHandle->SpeedBufferSize)); /* Average value */ } } } /* * @brief Used to calculate instant speed during revup, to * initialize parameters at step change and to select proper ADC channel * for next Bemf acquisitions * @param pHandle: handler of the current instance of the Bemf_ADC component * @param hElSpeedDpp: Mechanical speed imposed by virtual speed component * @param pHandlePWMC: handler of the current instance of the PWMC component */ void BADC_StepChangeEvent(Bemf_ADC_Handle_t * pHandle, int16_t hElSpeedDpp, PWMC_Handle_t *pHandlePWMC) { pHandle->DemagCounter = 0; while (LL_ADC_REG_IsConversionOngoing(ADC1)) { LL_ADC_REG_StopConversion(ADC1); while(LL_ADC_REG_IsStopConversionOngoing(ADC1)); } BADC_Stop(pHandle); pHandle->Last_Zc2Comm_Delay = LL_TIM_GetAutoReload(pHandle->pParams_str->LfTim) - pHandle->ZC_Counter_Last; if (false == pHandle->IsLoopClosed) { if (hElSpeedDpp < 0) { pHandle->VirtualElSpeedDpp = - hElSpeedDpp; } else { pHandle->VirtualElSpeedDpp = hElSpeedDpp; } pHandle->ZcDetected = false; } else { int16_t ElAngleUpdate; if(pHandle->Direction == -1) { ElAngleUpdate = -S16_60_PHASE_SHIFT ; } else { ElAngleUpdate = S16_60_PHASE_SHIFT ; } pHandle->MeasuredElAngle += ElAngleUpdate; if ( false == pHandle->ZcDetected) { LL_TIM_SetAutoReload(pHandle->pParams_str->LfTim,LL_TIM_GetAutoReload(pHandle->pParams_str->LfTim) * 120 / 100); } else { pHandle->ZcDetected = false; } } pHandle->StepUpdate = true; } /* * @brief Calculates and stores in the corresponding variable the demagnetization * time in open loop operation * @param pHandle: handler of the current instance of the Bemf_ADC component */ void BADC_CalcRevUpDemagTime(Bemf_ADC_Handle_t *pHandle) { int16_t hSpeed; hSpeed = (int16_t)((pHandle->VirtualElSpeedDpp * (int32_t)pHandle->_Super.hMeasurementFrequency * (int32_t)SPEED_UNIT ) / ((int32_t)(pHandle->_Super.DPPConvFactor) * (int32_t)(pHandle->_Super.bElToMecRatio)) );; if (hSpeed == 0) { pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold;; } else { pHandle->DemagCounterThreshold = (uint16_t) (pHandle->DemagParams.RevUpDemagSpeedConv / hSpeed); } if (pHandle->DemagCounterThreshold < pHandle->DemagParams.DemagMinimumThreshold) { pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold; } } /* * @brief Calculates and stores in the corresponding variable the demagnetization * time in closed loop operation * @param pHandle: handler of the current instance of the Bemf_ADC component */ void BADC_CalcRunDemagTime(Bemf_ADC_Handle_t *pHandle) { int16_t hSpeed; hSpeed = pHandle->_Super.hAvrMecSpeedUnit; if (hSpeed < 0) hSpeed = - hSpeed; if (hSpeed < pHandle->DemagParams.DemagMinimumSpeedUnit) { pHandle->DemagCounterThreshold = (uint16_t) (pHandle->DemagParams.RunDemagSpeedConv / hSpeed); if (pHandle->DemagCounterThreshold < pHandle->DemagParams.DemagMinimumThreshold) { pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold; } } else { pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold; } } /* * @brief Must be called after switch-over procedure when * virtual speed sensor transition is ended. * @param pHandle: handler of the current instance of the STO component */ void BADC_SetLoopClosed(Bemf_ADC_Handle_t *pHandle) { pHandle->IsLoopClosed=true; } /* * @brief Returns the last acquired bemf value * @param pHandle: handler of the current instance of the Bemf_ADC component * @param phase: motor phase under investigation * @retval uint16_t: Bemf value */ uint16_t BADC_GetLastBemfValue(Bemf_ADC_Handle_t *pHandle, uint8_t phase) { return ((MC_NULL == pHandle) ? 0U : pHandle->BemfLastValues[phase]); } /* * @brief Returns the zero crossing detection flag * @param pHandle: handler of the current instance of the Bemf_ADC component * @retval bool: zero crossing detection flag */ bool BADC_GetBemfZcrFlag(Bemf_ADC_Handle_t *pHandle) { return ((MC_NULL == pHandle) ? 0U : pHandle->ZcDetected); } /* * @brief Returns true if the step needs to be updated * @param pHandle: handler of the current instance of the Bemf_ADC component * @retval bool: step update request */ bool BADC_ClearStepUpdate(Bemf_ADC_Handle_t *pHandle) { bool retValue = (((pHandle->IsLoopClosed == true) && (pHandle->StepUpdate == true)) || (pHandle->IsLoopClosed == false)); pHandle->StepUpdate = false; return retValue; } /* * @brief Configures the parameters for bemf sensing during pwm off-time * @param pHandle: handler of the current instance of the Bemf_ADC component * @param BemfAdcConfig: thresholds and sampling time parameters * @param Zc2CommDelay: delay between bemf zero crossing parameter and step commutation * @param bemfAdcDemagConfig: demagnetization parameters */ void BADC_SetBemfSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfAdcConfig, uint16_t *Zc2CommDelay, Bemf_Demag_Params *bemfAdcDemagConfig) { pHandle->Pwm_OFF.AdcThresholdUp = BemfAdcConfig->AdcThresholdUp; pHandle->Pwm_OFF.AdcThresholdDown = BemfAdcConfig->AdcThresholdDown; pHandle->Pwm_OFF.SamplingPoint = BemfAdcConfig->SamplingPoint; pHandle->Zc2CommDelay = *Zc2CommDelay; pHandle->DemagParams.DemagMinimumSpeedUnit = bemfAdcDemagConfig->DemagMinimumSpeedUnit; pHandle->DemagParams.DemagMinimumThreshold = bemfAdcDemagConfig->DemagMinimumThreshold; } /* * @brief Configures the parameters for bemf sensing during pwm on-time * @param pHandle: handler of the current instance of the Bemf_ADC component * @param BemfOnAdcConfig: thresholds and sampling time parameters * @param OnSensingEnThres: Minimum dudty cycle for on-sensing activation * @param OnSensingDisThres: Minimum duty cycle for on-sensing Deactivationg */ void BADC_SetBemfOnTimeSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfOnAdcConfig, uint16_t *OnSensingEnThres, uint16_t *OnSensingDisThres) { pHandle->Pwm_ON.AdcThresholdUp = BemfOnAdcConfig->AdcThresholdUp; pHandle->Pwm_ON.AdcThresholdDown = BemfOnAdcConfig->AdcThresholdDown; pHandle->Pwm_ON.SamplingPoint = BemfOnAdcConfig->SamplingPoint; pHandle->OnSensingEnThres = *OnSensingEnThres; pHandle->OnSensingDisThres = *OnSensingDisThres; } /* * @brief Gets the parameters for bemf sensing during pwm off-time * @param pHandle: handler of the current instance of the Bemf_ADC component * @param BemfAdcConfig: thresholds and sampling time parameters * @param Zc2CommDelay: delay between bemf zero crossing parameter and step commutation * @param BemfAdcDemagConfig: demagnetization parameters */ void BADC_GetBemfSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfAdcConfig, uint16_t *Zc2CommDelay, Bemf_Demag_Params *BemfAdcDemagConfig) { BemfAdcConfig->AdcThresholdUp = pHandle->Pwm_OFF.AdcThresholdUp; BemfAdcConfig->AdcThresholdDown = pHandle->Pwm_OFF.AdcThresholdDown; BemfAdcConfig->SamplingPoint = pHandle->Pwm_OFF.SamplingPoint; *Zc2CommDelay = pHandle->Zc2CommDelay; BemfAdcDemagConfig->DemagMinimumSpeedUnit = pHandle->DemagParams.DemagMinimumSpeedUnit; BemfAdcDemagConfig->DemagMinimumThreshold = pHandle->DemagParams.DemagMinimumThreshold; } /* * @brief Gets the parameters for bemf sensing during pwm on-time * @param pHandle: handler of the current instance of the Bemf_ADC component * @param BemfOnAdcConfig: thresholds and sampling time parameters * @param OnSensingEnThres: Minimum duty cycle for on-sensing activation * @param OnSensingDisThres: Minimum duty cycle for on-sensing Deactivationg */ void BADC_GetBemfOnTimeSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfOnAdcConfig, uint16_t *OnSensingEnThres, uint16_t *OnSensingDisThres) { BemfOnAdcConfig->AdcThresholdUp = pHandle->Pwm_ON.AdcThresholdUp; BemfOnAdcConfig->AdcThresholdDown = pHandle->Pwm_ON.AdcThresholdDown; BemfOnAdcConfig->SamplingPoint = pHandle->Pwm_ON.SamplingPoint; *OnSensingEnThres = pHandle->OnSensingEnThres; *OnSensingDisThres = pHandle->OnSensingDisThres; } /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
36,321
C
35.249501
167
0.638061
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/G0xx/Src/r3_g0xx_pwm_curr_fdbk.c
/** ****************************************************************************** * @file r3_g0xx_pwm_curr_fdbk.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement current sensor * class to be stantiated when the three shunts current sensing * topology is used. * * It is specifically designed for STM32G0XX microcontrollers and * implements the successive sampling of motor current using only one ADC. * + MCU peripheral and handle initialization fucntion * + three shunt current sensing * + space vector modulation function * + ADC sampling function * ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup R3_G0XX_pwm_curr_fdbk */ /* Includes ------------------------------------------------------------------*/ #include "r3_g0xx_pwm_curr_fdbk.h" #include "pwm_common.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup R3_1_pwm_curr_fdbk * @{ */ /* Private defines -----------------------------------------------------------*/ #define TIMxCCER_MASK_CH123 (LL_TIM_CHANNEL_CH1 | LL_TIM_CHANNEL_CH1N | LL_TIM_CHANNEL_CH2|LL_TIM_CHANNEL_CH2N |\ LL_TIM_CHANNEL_CH3 | LL_TIM_CHANNEL_CH3N) /* Private function prototypes -----------------------------------------------*/ void R3_1_HFCurrentsCalibrationAB(PWMC_Handle_t *pHdl,ab_t* pStator_Currents); void R3_1_HFCurrentsCalibrationC(PWMC_Handle_t *pHdl,ab_t* pStator_Currents); uint16_t R3_1_WriteTIMRegisters(PWMC_Handle_t *pHdl, uint16_t hCCR4Reg); /* Private functions ---------------------------------------------------------*/ /* Local redefinition of both LL_TIM_OC_EnablePreload & LL_TIM_OC_DisablePreload */ __STATIC_INLINE void __LL_TIM_OC_EnablePreload(TIM_TypeDef *TIMx, uint32_t Channel) { register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); register __IO uint32_t *pReg = (__IO uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); SET_BIT(*pReg, (TIM_CCMR1_OC1PE << SHIFT_TAB_OCxx[iChannel])); } __STATIC_INLINE void __LL_TIM_OC_DisablePreload(TIM_TypeDef *TIMx, uint32_t Channel) { register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(LL_TIM_CHANNEL_CH4); register __IO uint32_t *pReg = (__IO uint32_t *)((uint32_t)((uint32_t)(&TIM1->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); CLEAR_BIT(*pReg, (TIM_CCMR1_OC1PE << SHIFT_TAB_OCxx[iChannel])); } /* * @brief Initializes TIM1, ADC1, GPIO, DMA1 and NVIC for three shunt current * reading configuration using STM32G0XX. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_1_Init(PWMC_R3_1_Handle_t *pHandle) { if ((uint32_t)pHandle == (uint32_t)&pHandle->_Super) { /* Peripheral clocks enabling END ----------------------------------------*/ /* Clear TIMx break flag. */ LL_TIM_ClearFlag_BRK( TIM1 ); LL_TIM_EnableIT_BRK( TIM1 ); LL_TIM_SetCounter( TIM1, ( uint32_t )( pHandle->Half_PWMPeriod ) - 1u ); /* Enable PWM channel */ LL_TIM_CC_EnableChannel( TIM1, TIMxCCER_MASK_CH123 ); /* TIM1 Counter Clock stopped when the core is halted */ LL_APB1_GRP1_EnableClock (LL_APB1_GRP1_PERIPH_DBGMCU); LL_DBGMCU_APB2_GRP1_FreezePeriph(LL_DBGMCU_APB2_GRP1_TIM1_STOP); if ( LL_ADC_IsInternalRegulatorEnabled(ADC1) == 0u) { /* Enable ADC internal voltage regulator */ LL_ADC_EnableInternalRegulator(ADC1); /* Wait for Regulator Startup time */ /* Note: Variable divided by 2 to compensate partially */ /* CPU processing cycles, scaling in us split to not */ /* exceed 32 bits register capacity and handle low frequency. */ volatile uint32_t wait_loop_index = ((LL_ADC_DELAY_INTERNAL_REGUL_STAB_US / 10UL) * (SystemCoreClock / (100000UL * 2UL))); while(wait_loop_index != 0UL) { wait_loop_index--; } } /* ADC Calibration */ LL_ADC_StartCalibration(ADC1); while (LL_ADC_IsCalibrationOnGoing(ADC1)) { } /* Enables the ADC peripheral */ LL_ADC_Enable(ADC1); /* Wait ADC Ready */ while ( LL_ADC_IsActiveFlag_ADRDY( ADC1 ) == RESET ) { /* wait */ } /* DMA1 Channel1 Config */ LL_DMA_SetMemoryAddress(DMA1, LL_DMA_CHANNEL_1, (uint32_t)pHandle->ADC1_DMA_converted); LL_DMA_SetPeriphAddress( DMA1, LL_DMA_CHANNEL_1, ( uint32_t )&ADC1->DR ); LL_DMA_SetDataLength(DMA1, LL_DMA_CHANNEL_1, 3); /* Enables the DMA1 Channel1 peripheral */ LL_DMA_EnableChannel(DMA1, LL_DMA_CHANNEL_1); /* set default triggering edge */ pHandle->ADCTriggerEdge = LL_ADC_REG_TRIG_EXT_RISING; /* We allow ADC usage for regular conversion on Systick*/ pHandle->ADCRegularLocked=false; pHandle->_Super.DTTest = 0u; LL_TIM_EnableCounter( TIM1 ); } } /* * @brief Stores in @p pHdl handler the calibrated @p offsets. * */ __weak void R3_1_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 pHandle->PhaseAOffset = offsets->phaseAOffset; pHandle->PhaseBOffset = offsets->phaseBOffset; pHandle->PhaseCOffset = offsets->phaseCOffset; pHdl->offsetCalibStatus = true; } /* * @brief Reads the calibrated @p offsets stored in @p pHdl. * */ __weak void R3_1_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 offsets->phaseAOffset = pHandle->PhaseAOffset; offsets->phaseBOffset = pHandle->PhaseBOffset; offsets->phaseCOffset = pHandle->PhaseCOffset; } /* * @brief Stores into the @p pHdl handler the voltage present on Ia and * Ib current feedback analog channels when no current is flowing into the * motor. * */ __weak void R3_1_CurrentReadingCalibration(PWMC_Handle_t *pHdl) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef* TIMx = TIM1; volatile PWMC_GetPhaseCurr_Cb_t GetPhaseCurrCbSave; volatile PWMC_SetSampPointSectX_Cb_t SetSampPointSectXCbSave; if (false == pHandle->_Super.offsetCalibStatus) { /* Save callback routines */ GetPhaseCurrCbSave = pHandle->_Super.pFctGetPhaseCurrents; SetSampPointSectXCbSave = pHandle->_Super.pFctSetADCSampPointSectX; pHandle->PhaseAOffset = 0u; pHandle->PhaseBOffset = 0u; pHandle->PhaseCOffset = 0u; pHandle->PolarizationCounter = 0u; /* It forces inactive level on TIMx CHy and CHyN */ LL_TIM_CC_DisableChannel( TIMx, TIMxCCER_MASK_CH123 ); /* Offset calibration for A B c phases */ /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R3_1_HFCurrentsCalibrationAB; pHandle->_Super.pFctSetADCSampPointSectX = &R3_1_SetADCSampPointCalibration; pHandle->CalibSector = SECTOR_5; pHandle->_Super.Sector = SECTOR_5; R3_1_SwitchOnPWM(&pHandle->_Super); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd( TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter ); R3_1_SwitchOffPWM(&pHandle->_Super); pHandle->_Super.pFctGetPhaseCurrents = &R3_1_HFCurrentsCalibrationC; pHandle->CalibSector = SECTOR_1; pHandle->_Super.Sector = SECTOR_1; pHandle->PolarizationCounter = 0; R3_1_SwitchOnPWM(&pHandle->_Super); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd( TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter ); R3_1_SwitchOffPWM(&pHandle->_Super); pHandle->_Super.Sector = SECTOR_5; pHandle->PhaseAOffset = pHandle->PhaseAOffset / NB_CONVERSIONS; pHandle->PhaseBOffset = pHandle->PhaseBOffset / NB_CONVERSIONS; pHandle->PhaseCOffset = pHandle->PhaseCOffset / NB_CONVERSIONS; if (0U == pHandle->_Super.SWerror) { pHandle->_Super.offsetCalibStatus = true; } else { /* nothing to do */ } /* restore function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = GetPhaseCurrCbSave; pHandle->_Super.pFctSetADCSampPointSectX = SetSampPointSectXCbSave; } /* It over write TIMx CCRy wrongly written by FOC during calibration so as to force 50% duty cycle on the three inverer legs */ /* Disable TIMx preload */ __LL_TIM_OC_DisablePreload(TIMx,LL_TIM_CHANNEL_CH1); __LL_TIM_OC_DisablePreload(TIMx,LL_TIM_CHANNEL_CH2); __LL_TIM_OC_DisablePreload(TIMx,LL_TIM_CHANNEL_CH3); LL_TIM_OC_SetCompareCH1( TIMx, (uint32_t)pHandle->Half_PWMPeriod ); LL_TIM_OC_SetCompareCH2( TIMx, (uint32_t)pHandle->Half_PWMPeriod ); LL_TIM_OC_SetCompareCH3( TIMx, (uint32_t)pHandle->Half_PWMPeriod ); /* Enable TIMx preload */ __LL_TIM_OC_EnablePreload(TIMx,LL_TIM_CHANNEL_CH1); __LL_TIM_OC_EnablePreload(TIMx,LL_TIM_CHANNEL_CH2); __LL_TIM_OC_EnablePreload(TIMx,LL_TIM_CHANNEL_CH3); /* It re-enable drive of TIMx CHy and CHyN by TIMx CHyRef*/ LL_TIM_CC_EnableChannel( TIMx, TIMxCCER_MASK_CH123 ); pHandle->_Super.BrakeActionLock = false; } /* * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p pStator_Currents ab_t format. * */ __weak void R3_1_GetPhaseCurrents(PWMC_Handle_t *pHdl,ab_t* pStator_Currents) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif int32_t wAux; uint16_t hReg1; uint16_t hReg2; uint8_t bSector; LL_TIM_CC_DisableChannel( TIM1, LL_TIM_CHANNEL_CH4 ); bSector = (uint8_t) pHandle->_Super.Sector; LL_ADC_REG_SetSequencerScanDirection(ADC1, LL_ADC_REG_SEQ_SCAN_DIR_FORWARD); hReg1 = *pHandle->pParams_str->ADCDataReg1[bSector]; hReg2 = *pHandle->pParams_str->ADCDataReg2[bSector]; switch (bSector) { case SECTOR_4: case SECTOR_5: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) ------------------------------*/ wAux = (int32_t)(pHandle->PhaseAOffset)-(int32_t)(hReg1); /* Saturation of Ia */ if ( wAux < -INT16_MAX ) { pStator_Currents->a = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->a = INT16_MAX; } else { pStator_Currents->a= (int16_t)wAux; } /* Ib = PhaseBOffset - ADC converted value) ------------------------------*/ wAux = (int32_t)(pHandle->PhaseBOffset)-(int32_t)(hReg2); /* Saturation of Ib */ if ( wAux < -INT16_MAX ) { pStator_Currents->b = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->b = INT16_MAX; } else { pStator_Currents->b= (int16_t)wAux; } break; case SECTOR_6: case SECTOR_1: /* Current on Phase A is not accessible */ /* Ib = (PhaseBOffset - ADC converted value) ------------------------------*/ wAux = (int32_t)(pHandle->PhaseBOffset)-(int32_t)(hReg1); /* Saturation of Ib */ if ( wAux < -INT16_MAX ) { pStator_Currents->b = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->b = INT16_MAX; } else { pStator_Currents->b= (int16_t)wAux; } wAux = (int32_t)(pHandle->PhaseCOffset)-(int32_t)(hReg2); /* Ia = -Ic -Ib ----------------------------------------------------------*/ wAux =-wAux - (int32_t)pStator_Currents->b; /* Ia */ /* Saturation of Ia */ if ( wAux > INT16_MAX ) { pStator_Currents->a = INT16_MAX; } else if ( wAux < -INT16_MAX ) { pStator_Currents->a = -INT16_MAX; } else { pStator_Currents->a = (int16_t)wAux; } break; case SECTOR_2: case SECTOR_3: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) ------------------------------*/ wAux = (int32_t)(pHandle->PhaseAOffset)-(int32_t)(hReg1); /* Saturation of Ia */ if ( wAux < -INT16_MAX ) { pStator_Currents->a = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->a = INT16_MAX; } else { pStator_Currents->a= (int16_t)wAux; } /* Ic = PhaseCOffset - ADC converted value) ------------------------------*/ wAux = (int32_t)(pHandle->PhaseCOffset)-(int32_t)(hReg2); /* Ib = -Ic -Ia */ wAux = -wAux - (int32_t)pStator_Currents->a; /* Ib */ /* Saturation of Ib */ if ( wAux > INT16_MAX ) { pStator_Currents->b = INT16_MAX; } else if ( wAux < -INT16_MAX ) { pStator_Currents->b = -INT16_MAX; } else { pStator_Currents->b = (int16_t)wAux; } break; default: break; } pHandle->_Super.Ia = pStator_Currents->a; pHandle->_Super.Ib = pStator_Currents->b; pHandle->_Super.Ic = -pStator_Currents->a - pStator_Currents->b; } /* * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p Iab ab_t format. Specific to overmodulation. * */ __weak void R3_1_GetPhaseCurrents_OVM( PWMC_Handle_t * pHdl, ab_t * Iab ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ uint8_t Sector; int32_t Aux; uint32_t ADCDataReg1; uint32_t ADCDataReg2; /* disable ADC trigger source */ LL_TIM_CC_DisableChannel( TIM1, LL_TIM_CHANNEL_CH4 ); LL_ADC_REG_SetSequencerScanDirection(ADC1, LL_ADC_REG_SEQ_SCAN_DIR_FORWARD); Sector = ( uint8_t )pHandle->_Super.Sector; ADCDataReg1 = *pHandle->pParams_str->ADCDataReg1[Sector]; ADCDataReg2 = *pHandle->pParams_str->ADCDataReg2[Sector]; switch ( Sector ) { case SECTOR_4: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { // Ib not available, use estimated Ib Aux = ( int32_t )( pHandle->_Super.IbEst ); } else { /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg2 ); } /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_5: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { // Ia not available, use estimated Ia Aux = ( int32_t )( pHandle->_Super.IaEst ); } else { Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg2 ); /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_6: /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IcEst ; /* -Ic */ Aux -= ( int32_t )Iab->b; } else { /* Ia = -Ic -Ib */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->b; /* Ia */ } /* Saturation of Ia */ if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else { Iab->a = ( int16_t )Aux; } break; case SECTOR_1: /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IbEst; } else { Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } /* Ia = -Ic -Ib */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->b; /* Ia */ /* Saturation of Ia */ if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else { Iab->a = ( int16_t )Aux; } break; case SECTOR_2: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IaEst; } else { Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } /* Ib = -Ic -Ia */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ /* Saturation of Ib */ if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_3: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { /* Ib = -Ic -Ia */ Aux = ( int32_t ) pHandle->_Super.IcEst; /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ } else { /* Ib = -Ic -Ia */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ } /* Saturation of Ib */ if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; default: break; } pHandle->_Super.Ia = Iab->a; pHandle->_Super.Ib = Iab->b; pHandle->_Super.Ic = -Iab->a - Iab->b; } /* * @brief Configures the ADC for the current sampling during calibration. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ __weak uint16_t R3_1_SetADCSampPointCalibration( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif pHandle->ADCTriggerEdge = LL_ADC_REG_TRIG_EXT_RISING; pHandle->_Super.Sector = pHandle->CalibSector; return R3_1_WriteTIMRegisters( pHdl, ( uint16_t )( pHandle->Half_PWMPeriod ) - 1u); } /* * @brief Configures the ADC for the current sampling related to sector X (X = [1..6] ). * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ __weak uint16_t R3_1_SetADCSampPointSectX( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif uint16_t hCntSmp; uint16_t hDeltaDuty; register uint16_t lowDuty = pHdl->lowDuty; register uint16_t midDuty = pHdl->midDuty; /* Check if sampling AB in the middle of PWM is possible */ if ( ( uint16_t )( pHandle->Half_PWMPeriod - lowDuty ) > pHandle->pParams_str->hTafter ) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled which corresponds * to sector 4 (could be also sector 5) */ pHandle->_Super.Sector = SECTOR_5; /* set sampling point trigger in the middle of PWM period */ hCntSmp = ( uint32_t )( pHandle->Half_PWMPeriod ) - 1u; } else { /* In this case it is necessary to convert phases with Maximum and variable complementary duty cycle.*/ /* ADC Injected sequence configuration. The stator phase with minimum value of complementary duty cycle is set as first. In every sector there is always one phase with maximum complementary duty, one with minimum complementary duty and one with variable complementary duty. In this case, phases with variable complementary duty and with maximum duty are converted and the first will be always the phase with variable complementary duty cycle */ /* Crossing Point Searching */ hDeltaDuty = ( uint16_t )( lowDuty - midDuty ); /* Definition of crossing point */ if ( hDeltaDuty > ( uint16_t )( pHandle->Half_PWMPeriod - lowDuty ) * 2u ) { hCntSmp = lowDuty - pHandle->pParams_str->hTbefore; } else { hCntSmp = lowDuty + pHandle->pParams_str->hTafter; if ( hCntSmp >= pHandle->Half_PWMPeriod ) { pHandle->ADCTriggerEdge = LL_ADC_REG_TRIG_EXT_FALLING; hCntSmp = ( 2u * pHandle->Half_PWMPeriod ) - hCntSmp - 1u; } } } return R3_1_WriteTIMRegisters( &pHandle->_Super, hCntSmp ); } /* * @brief Configures the ADC for the current sampling related to sector X (X = [1..6] ) in case of overmodulation. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ uint16_t R3_1_SetADCSampPointSectX_OVM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ uint16_t SamplingPoint; uint16_t DeltaDuty; pHandle->_Super.useEstCurrent = false; DeltaDuty = ( uint16_t )( pHdl->lowDuty - pHdl->midDuty ); /* case 1 (cf user manual) */ if (( uint16_t )( pHandle->Half_PWMPeriod - pHdl->lowDuty ) > pHandle->pParams_str->hTafter) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled which corresponds * to sector 4 or 5 */ pHandle->_Super.Sector = SECTOR_5; /* set sampling point trigger in the middle of PWM period */ SamplingPoint = pHandle->Half_PWMPeriod - (uint16_t) 1; } else /* case 2 (cf user manual) */ { if (DeltaDuty >= pHandle->pParams_str->Tcase2) { SamplingPoint = pHdl->lowDuty - pHandle->pParams_str->hTbefore; } else { /* case 3 (cf user manual) */ if ((pHandle->Half_PWMPeriod - pHdl->lowDuty) > pHandle->pParams_str->Tcase3) { /* ADC trigger edge must be changed from positive to negative */ pHandle->ADCTriggerEdge = LL_ADC_REG_TRIG_EXT_FALLING; SamplingPoint = pHdl->lowDuty + pHandle->pParams_str->Tsampling; } else { SamplingPoint = pHandle->Half_PWMPeriod-1; pHandle->_Super.useEstCurrent = true; } } } return R3_1_WriteTIMRegisters( &pHandle->_Super, SamplingPoint ); } /* * @brief Writes into peripheral registers the new duty cycles and sampling point. * * @param pHdl: Handler of the current instance of the PWM component. * @param hCCR4Reg: New capture/compare register value, written in timer clock counts. * @retval Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ __weak uint16_t R3_1_WriteTIMRegisters(PWMC_Handle_t *pHdl, uint16_t hCCR4Reg) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef* TIMx = TIM1; uint16_t hAux; LL_TIM_OC_SetCompareCH1 ( TIMx, (uint32_t)pHandle->_Super.CntPhA ); LL_TIM_OC_SetCompareCH2 ( TIMx, (uint32_t)pHandle->_Super.CntPhB ); LL_TIM_OC_SetCompareCH3 ( TIMx, (uint32_t)pHandle->_Super.CntPhC ); LL_TIM_OC_SetCompareCH4 ( TIMx, (uint32_t)hCCR4Reg ); /* Re-configuration of CCR4 must be done before the timer update to be taken into account at the next PWM cycle. Otherwise we are too late, we flag a FOC_DURATION error */ if ( LL_TIM_CC_IsEnabledChannel(TIMx, LL_TIM_CHANNEL_CH4)) { hAux = MC_DURATION; } else { hAux = MC_NO_ERROR; } if (pHandle->_Super.SWerror == 1u) { hAux = MC_DURATION; pHandle->_Super.SWerror = 0u; } return hAux; } /* * @brief Implementation of PWMC_GetPhaseCurrents to be performed during calibration. * * It sums up injected conversion data into PhaseAOffset and wPhaseBOffset * to compute the offset introduced in the current feedback network. It is required to * properly configure ADC inputs before in order to enable offset computation. Called R3_1_HFCurrentsPolarizationAB in F30X and G4XX. * * @param pHdl: Pointer on the target component instance. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ __weak void R3_1_HFCurrentsCalibrationAB(PWMC_Handle_t *pHdl, ab_t* pStator_Currents) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = TIM1; uint8_t bSector = pHandle->CalibSector; /* disable ADC trigger */ LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH4 ); if ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { pHandle->PhaseAOffset += *pHandle->pParams_str->ADCDataReg1[bSector]; pHandle->PhaseBOffset += *pHandle->pParams_str->ADCDataReg2[bSector]; pHandle->PolarizationCounter++; } /* during offset calibration no current is flowing in the phases */ pStator_Currents->a = 0; pStator_Currents->b = 0; } /* * @brief Implementation of PWMC_GetPhaseCurrents to be performed during calibration. * * It sums up injected conversion data into PhaseCOffset to compute the offset * introduced in the current feedback network. It is required to properly configure * ADC inputs before in order to enable offset computation. * * @param pHdl: Pointer on the target component instance. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ void R3_1_HFCurrentsCalibrationC( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = TIM1; uint8_t bSector = pHandle->CalibSector; /* disable ADC trigger */ LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH4 ); pHandle->_Super.Sector = SECTOR_1; if ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { pHandle->PhaseCOffset += *pHandle->pParams_str->ADCDataReg2[bSector]; pHandle->PolarizationCounter++; } /* during offset calibration no current is flowing in the phases */ pStator_Currents->a = 0; pStator_Currents->b = 0; } /* * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors of driving section. It has to be * called each motor start-up when using high voltage drivers. * * @param pHdl: Handler of the current instance of the PWM component * @param ticks: Timer ticks value to be applied * Min value: 0 (low sides ON) * Max value: PWM_PERIOD_CYCLES/2 (low sides OFF) */ __weak void R3_1_TurnOnLowSides(PWMC_Handle_t *pHdl, uint32_t ticks) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef* TIMx = TIM1; pHandle->_Super.TurnOnLowSidesAction = true; /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE(TIMx); /*Turn on the three low side switches */ LL_TIM_OC_SetCompareCH1(TIMx, ticks); LL_TIM_OC_SetCompareCH2(TIMx, ticks); LL_TIM_OC_SetCompareCH3(TIMx, ticks); /* Wait until next update */ while (LL_TIM_IsActiveFlag_UPDATE(TIMx)==RESET) {} /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs(TIMx); if ((pHandle->_Super.LowSideOutputs)== ES_GPIO) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } return; } /* * @brief Enables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_1_SwitchOnPWM(PWMC_Handle_t *pHdl) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef* TIMx = TIM1; pHandle->_Super.TurnOnLowSidesAction = false; /* We forbid ADC usage for regular conversion on Systick*/ pHandle->ADCRegularLocked=true; /* Set all duty to 50% */ LL_TIM_OC_SetCompareCH1(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH2(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH3(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH4(TIMx, (uint32_t)(pHandle->Half_PWMPeriod - 5u)); /* Wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE(TIMx); while (LL_TIM_IsActiveFlag_UPDATE(TIMx) == RESET) {} LL_TIM_ClearFlag_UPDATE(TIMx); /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE; LL_TIM_EnableAllOutputs(TIMx); if ((pHandle->_Super.LowSideOutputs)== ES_GPIO) { if ((TIMx->CCER & TIMxCCER_MASK_CH123) != 0u) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* Setting of the DMA Buffer Size.*/ /* NOTE. This register (CNDTRx) must not be written when the DMAy Channel x is ENABLED */ LL_DMA_DisableChannel(DMA1, LL_DMA_CHANNEL_1); /* Write the Buffer size on CNDTR register */ LL_DMA_SetDataLength( DMA1, LL_DMA_CHANNEL_1, 2u ); /* DMA Enabling */ LL_DMA_EnableChannel(DMA1, LL_DMA_CHANNEL_1); /* Clear EOC */ LL_ADC_ClearFlag_EOC(ADC1); /* Enable ADC DMA request*/ LL_ADC_REG_SetDMATransfer(ADC1, LL_ADC_REG_DMA_TRANSFER_LIMITED); /* Clear Pending Interrupt Bits */ LL_DMA_ClearFlag_HT1(DMA1); // TBC: for TC1, GL1 (not cleared ...) /* DMA Interrupt Event configuration */ LL_DMA_EnableIT_TC(DMA1, LL_DMA_CHANNEL_1); /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Enable Update IRQ */ LL_TIM_EnableIT_UPDATE( TIMx ); return; } /* * @brief Disables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_1_SwitchOffPWM(PWMC_Handle_t *pHdl) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef* TIMx = TIM1; /* Enable Update IRQ */ LL_TIM_DisableIT_UPDATE( TIMx ); pHandle->_Super.TurnOnLowSidesAction = false; /* Main PWM Output Disable */ LL_TIM_DisableAllOutputs(TIMx); if ( pHandle->_Super.BrakeActionLock == true ) { } else { if ((pHandle->_Super.LowSideOutputs)== ES_GPIO) { LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* Disabling of DMA Interrupt Event configured */ LL_DMA_DisableIT_TC(DMA1, LL_DMA_CHANNEL_1); LL_ADC_REG_StopConversion(ADC1); /* Disable ADC DMA request*/ ADC1->CFGR1 &= ~ADC_CFGR1_DMAEN; /* Clear Transmission Complete Flag of DMA1 Channel1 */ LL_DMA_ClearFlag_TC1(DMA1); /* Clear EOC */ LL_ADC_ClearFlag_EOC( ADC1 ); /* The ADC is not triggered anymore by the PWM timer */ LL_ADC_REG_SetTriggerSource (ADC1, LL_ADC_REG_TRIG_SOFTWARE); /* We allow ADC usage for regular conversion on Systick*/ pHandle->ADCRegularLocked=false; /* Wait for a new PWM period to flush last HF task */ LL_TIM_ClearFlag_UPDATE(TIMx); while (LL_TIM_IsActiveFlag_UPDATE(TIMx) == RESET) {} LL_TIM_ClearFlag_UPDATE(TIMx); return; } /* * @brief Contains the TIMx Update event interrupt. * * @param pHandle: Handler of the current instance of the PWM component. */ void * R3_1_TIMx_UP_IRQHandler( PWMC_R3_1_Handle_t * pHandle ) { /* Set the trigger polarity as computed inside SetADCSampPointSectX*/ LL_ADC_REG_SetTriggerEdge (ADC1, pHandle->ADCTriggerEdge); /* set ADC trigger source */ LL_ADC_REG_SetTriggerSource(ADC1, LL_ADC_REG_TRIG_EXT_TIM1_CH4); /* Set scan direction according to the sector */ LL_ADC_REG_SetSequencerScanDirection(ADC1, pHandle->pParams_str->ADCScandir[pHandle->_Super.Sector]<<ADC_CFGR1_SCANDIR_Pos); /* Configure the ADC scheduler as selected inside SetADCSampPointSectX*/ ADC1->CHSELR = pHandle->pParams_str->ADCConfig[pHandle->_Super.Sector]; /* re-enable ADC trigger */ LL_TIM_CC_EnableChannel( TIM1, LL_TIM_CHANNEL_CH4 ); /* ADC needs to be restarted because DMA is configured as limited */ LL_ADC_REG_StartConversion( ADC1 ); /* Reset the ADC trigger edge for next conversion */ pHandle->ADCTriggerEdge = LL_ADC_REG_TRIG_EXT_RISING; return &pHandle->_Super.Motor; } /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
39,153
C
29.951779
143
0.606186
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/G0xx/Inc/g0xx_bemf_ADC_fdbk.h
/** ****************************************************************************** * @file g0xx_bemf_ADC_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * Sensorless Bemf acquisition with ADC component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup SpeednPosFdbk_Bemf */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef BEMFADCFDBK_H #define BEMFADCFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "speed_pos_fdbk.h" #include "speed_ctrl.h" #include "pwm_common_sixstep.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup SpeednPosFdbk * @{ */ /** @addtogroup SpeednPosFdbk_Bemf * @{ */ #define SPEED_BUFFER_LENGTH ((uint8_t) 18) /* Length of buffer used to store the timer period measurements */ /* * @brief Bemf_ADC parameters definition */ typedef struct { TIM_TypeDef * LfTim; /* Contains the pointer to the LF timer used for speed measurement. */ uint32_t LfTimerChannel; /* Channel of the LF timer used for speed measurement */ ADC_TypeDef * pAdc[3]; /* Pointer to the ADC */ uint32_t AdcChannel[3]; /* Array of ADC channels used for BEMF sensing */ bool gpio_divider_available; /* Availability of the GPIO port enabling the bemf resistor divider */ GPIO_TypeDef * bemf_divider_port; /* GPIO port enabling the bemf resistor divider */ uint16_t bemf_divider_pin; /* GPIO pin enabling the bemf resistor divider */ } Bemf_ADC_Params_t; /* * @brief This structure is used to handle the thresholds for bemf zero crossing detection * */ typedef struct { uint16_t AdcThresholdDown; /* BEMF voltage threshold for zero crossing detection when BEMF is decreasing */ uint16_t AdcThresholdUp; /* BEMF voltage threshold for zero crossing detection when BEMF is increasing */ uint16_t SamplingPoint; /* Pulse value of the timer channel used to trig the ADC when sensing occurs during PWM OFF time */ } Bemf_Sensing_Params; /* * @brief This structure is used to handle the demagnetization time before starting bemf acquisition * */ typedef struct { uint16_t DemagMinimumSpeedUnit; /* Speed threshold for minimum demagnetization time */ uint16_t RevUpDemagSpeedConv; /* Convertion factor between speed and demagnetization time */ uint16_t RunDemagSpeedConv; /* Open loop convertion factor between speed and demagnetization time during */ uint16_t DemagMinimumThreshold; /* Minimum demagnetization time */ } Bemf_Demag_Params; /* * @brief This structure is used to handle the data of an instance of the B-emf Feedback component * */ typedef struct { SpeednPosFdbk_Handle_t _Super; uint16_t BemfLastValues[3]; /* Bemf measurements of phase */ uint8_t ZcEvents; /* Number of bemf zero crossing events */ Bemf_Sensing_Params Pwm_ON; /* Parameters for zero crossing detection during ON time */ Bemf_Sensing_Params Pwm_OFF; /* Parameters for zero crossing detection during OFF time */ Bemf_Sensing_Params *pSensing_Params; uint16_t SamplingGuard; bool IsOnSensingEnabled; /* Value where 0 means BEMF is sensed during PWM OFF time and 1 or greater means BEMF is sensed during PWM ON time */ uint16_t OnSensingEnThres; /* Pulse value of HF timer above which the PWM ON sensing is enabled */ uint16_t OnSensingDisThres; /* Pulse value of HF timer below which the PWM ON sensing is disabled */ uint16_t Zc2CommDelay; /* Zero Crossing detection to commutation delay in 15/128 degrees */ Bemf_ADC_Params_t const *pParams_str; uint16_t SpeedSamplingFreqHz; /* Frequency (Hz) at which motor speed is to be computed. It must be equal to the frequency at which function SPD_CalcAvrgMecSpeedUnit is called.*/ uint8_t SpeedBufferSize; /* Size of the buffer used to calculate the average speed. It must be less than 18.*/ uint32_t TIMClockFreq; bool ADCRegularLocked; /* This flag is set when ADC is locked for bemf acquisition */ uint16_t ADC1_DMA_converted[1]; /* Buffer used for DMA data transfer after the ADC conversion */ int32_t ElPeriodSum; /* Period accumulator used to speed up the average speed computation*/ int16_t PrevRotorFreq; /* Used to store the last valid rotor electrical speed in dpp used when MAX_PSEUDO_SPEED is detected */ int8_t Direction; /* Instantaneous direction of rotor between two captures*/ int16_t AvrElSpeedDpp; /* Averaged rotor electrical speed express in s16degree per current control period.*/ int16_t VirtualElSpeedDpp; /* Averaged rotor electrical speed express in s16degree per current control period.*/ uint16_t MinStartUpValidSpeed; /* Absolute value of minimum mechanical speed required to validate the start-up. Expressed in the unit defined by #SPEED_UNIT. */ uint8_t StartUpConsistThreshold; /* Number of consecutive tests on speed consistency to be passed before validating the start-up */ bool IsSpeedReliable; /* Latest private speed reliability information, updated by SPD_CalcAvrgMecSpeedUnit, it is true if the speed measurement variance is lower then threshold corresponding to hVariancePercentage */ bool IsAlgorithmConverged; /* Boolean variable containing observer convergence information */ bool IsLoopClosed; /* Boolean variable containing speed loop status*/ bool ZcDetected; /* This flag is set when zero crossing is detected */ bool StepUpdate; /* This flag is set when step needs to be updated */ DrivingMode_t DriveMode; volatile uint8_t BufferFilled; /* Indicates the number of speed measuremt present in the buffer from the start. It will be max bSpeedBufferSize and it is used to validate the start of speed averaging. If bBufferFilled is below bSpeedBufferSize the instantaneous measured speed is returned as average speed.*/ int32_t SpeedBufferDpp[SPEED_BUFFER_LENGTH];/* Holding the last period captures */ uint32_t LowFreqTimerPsc; /* Prescaler value of the low frequency timer */ uint16_t SpeedFIFOIdx;/* Pointer of next element to be stored in the speed sensor buffer*/ int16_t DeltaAngle; /* Delta angle at the Hall sensor signal edge between current electrical rotor angle of synchronism. It is in s16degrees.*/ int16_t MeasuredElAngle; /* Electrical angle measured at each bemf zero crossing. It is considered the best measurement of electrical rotor angle.*/ int16_t CompSpeed; /* Speed compensation factor used to syncronize the current electrical angle with the target electrical angle. */ uint16_t SatSpeed; /* Returned value if the measured speed is above the maximum realistic.*/ uint32_t PseudoPeriodConv;/* Conversion factor between time interval Delta T between bemf zero crossing points, express in timer counts, and electrical rotor speed express in dpp. Ex. Rotor speed (dpp) = wPseudoFreqConv / Delta T It will be ((CKTIM / 6) / (SAMPLING_FREQ)) * 65536.*/ uint32_t MaxPeriod; /* Time delay between two bemf zero crossing points when the speed of the rotor is the minimum realistic in the application: this allows to discriminate too low freq for instance. This period shoud be expressed in timer counts and it will be: wMaxPeriod = ((10 * CKTIM) / 6) / MinElFreq(0.1Hz).*/ uint32_t MinPeriod; /* Time delay between two bemf zero crossing points when the speed of the rotor is the maximum realistic in the application: this allows discriminating glitches for instance. This period shoud be expressed in timer counts and it will be: wSpeedOverflow = ((10 * CKTIM) / 6) / MaxElFreq(0.1Hz).*/ uint16_t BemfTimeout; /* Max delay between two zero crossing signals to assert zero speed express in milliseconds.*/ uint16_t OvfFreq; /* Frequency of timer overflow (from 0 to 0x10000) it will be: hOvfFreq = CKTIM /65536.*/ uint16_t PWMNbrPSamplingFreq; /* Number of current control periods inside each speed control periods it will be: (hMeasurementFrequency / hSpeedSamplingFreqHz) - 1.*/ uint8_t PWMFreqScaling; /* Scaling factor to allow to store a PWMFrequency greater than 16 bits */ uint32_t Counter_Period; /* Low frequency timer period that allows speed calculation */ uint32_t ZC_Counter_Up; /* Low frequency timer counter value at zero crossing with increasing bemf */ uint32_t ZC_Counter_Down; /* Low frequency timer counter value at zero crossing with increasing bemf */ uint32_t ZC_Counter_Last; /* Last low frequency timer counter value at zero crossing */ uint32_t Last_Zc2Comm_Delay; /* Last delay between zero crossing and step change */ uint16_t DemagCounter; /* Demagnetization counter */ uint16_t DemagCounterThreshold; /* PWM cycles dedicated to windings demagnetization */ Bemf_Demag_Params DemagParams; /* Demagnetization parameters */ } Bemf_ADC_Handle_t; /* Exported functions --------------------------------------------------------*/ /* Initializes all the object variables. */ void BADC_Init( Bemf_ADC_Handle_t *pHandle ); /* Resets the ADC status and empties arrays. */ void BADC_Clear( Bemf_ADC_Handle_t *pHandle ); /* Gets ADC value and check for zero crossing detection.*/ bool BADC_IsZcDetected( Bemf_ADC_Handle_t *pHandle, PWMC_Handle_t *pHandlePWMC); /* Sets the trigger point of the ADC */ void BADC_SetSamplingPoint(Bemf_ADC_Handle_t *pHandle, PWMC_Handle_t *pHandlePWMC, SpeednTorqCtrl_Handle_t *pHandleSTC ); /* Computes the rotor average mechanical speed in the unit defined by #SPEED_UNIT and returns it in pMecSpeedUnit. */ bool BADC_CalcAvrgMecSpeedUnit( Bemf_ADC_Handle_t * pHandle, int16_t * pMecSpeedUnit ); /* Forces the rotation direction. */ void BADC_SetDirection( Bemf_ADC_Handle_t * pHandle, uint8_t direction ); /* Checks whether the state observer algorithm converged.*/ bool BADC_IsObserverConverged( Bemf_ADC_Handle_t * pHandle ); /* Starts the bemf acquisition.*/ void BADC_Start(Bemf_ADC_Handle_t *pHandle, uint8_t step); /* Stops the bemf acquisition.*/ void BADC_Stop(Bemf_ADC_Handle_t *pHandle); /* Selects the phase for the bemf acquisition.*/ void BADC_SelectAdcChannel(Bemf_ADC_Handle_t * pHandle, uint8_t Phase); /* Updates the estimated electrical angle.*/ int16_t BADC_CalcElAngle(Bemf_ADC_Handle_t * pHandle); /* Configures the sensorless parameters for the following step. */ void BADC_StepChangeEvent(Bemf_ADC_Handle_t * pHandle, int16_t hElSpeedDpp, PWMC_Handle_t *pHandlePWMC); /* Computes the demagnetization time during revup procedure. */ void BADC_CalcRevUpDemagTime(Bemf_ADC_Handle_t *pHandle); /* Computes the demagnetization time in closed loop operation.*/ void BADC_CalcRunDemagTime(Bemf_ADC_Handle_t *pHandle); /* Sets the flag when switch over phase ends.*/ void BADC_SetLoopClosed(Bemf_ADC_Handle_t *pHandle); /* Returns last converted Back-emf value.*/ uint16_t BADC_GetLastBemfValue(Bemf_ADC_Handle_t *pHandle, uint8_t phase); /* Returns the zero crossing detection flag. */ bool BADC_GetBemfZcrFlag(Bemf_ADC_Handle_t *pHandle); /* Enables low frequecy timer interrupt */ void BADC_SpeedMeasureOn(Bemf_ADC_Handle_t *pHandle); /* Disables low frequecy timer interrupt */ void BADC_SpeedMeasureOff(Bemf_ADC_Handle_t *pHandle); /* Clears StepUpdate flag */ bool BADC_ClearStepUpdate(Bemf_ADC_Handle_t *pHandle); /* Sets the parameters for bemf sensing during pwm off-time */ void BADC_SetBemfSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfAdcConfig, uint16_t *Zc2CommDelay, Bemf_Demag_Params *bemfAdcDemagConfig); /* Sets the parameters for bemf sensing during pwm on-time */ void BADC_SetBemfOnTimeSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfOnAdcConfig, uint16_t *OnSensingEnThres, uint16_t *OnSensingDisThres); /* Gets the parameters for bemf sensing during pwm off-time */ void BADC_GetBemfSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfAdcConfig, uint16_t *Zc2CommDelay, Bemf_Demag_Params *bemfAdcDemagConfig); /* Gets the parameters for bemf sensing during pwm on-time */ void BADC_GetBemfOnTimeSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfOnAdcConfig, uint16_t *OnSensingEnThres, uint16_t *OnSensingDisThres); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* BEMFADCFDBK_H */ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
15,212
C
50.222222
150
0.614844
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/G0xx/Inc/g0xx_bemf_ADC_OS_fdbk.h
/** ****************************************************************************** * @file g0xx_bemf_ADC_OS_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * multiple sensorless Bemf acquisition with ADC component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup SpeednPosFdbk_Bemf */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef BEMFADCFDBK_H #define BEMFADCFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "speed_pos_fdbk.h" #include "speed_ctrl.h" #include "pwm_common_sixstep.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup SpeednPosFdbk * @{ */ /** @addtogroup SpeednPosFdbk_Bemf * @{ */ #define SPEED_BUFFER_LENGTH ((uint8_t) 18) /* Length of buffer used to store the timer period measurements */ /* * @brief Bemf_ADC parameters definition */ typedef struct { TIM_TypeDef * LfTim; /* Contains the pointer to the LF timer used for speed measurement. */ uint32_t LfTimerChannel; /* Channel of the LF timer used for speed measurement */ ADC_TypeDef * pAdc[3]; /* Pointer to the ADC */ uint32_t AdcChannel[3]; /* Array of ADC channels used for BEMF sensing */ bool gpio_divider_available; /* Availability of the GPIO port enabling the bemf resistor divider */ GPIO_TypeDef * bemf_divider_port; /* GPIO port enabling the bemf resistor divider */ uint16_t bemf_divider_pin; /* GPIO pin enabling the bemf resistor divider */ uint32_t TIM_ADC_Trigger_Channel; TIM_TypeDef * TIM_Trigger; } Bemf_ADC_Params_t; /* * @brief This structure is used to handle the thresholds for bemf zero crossing detection * */ typedef struct { uint16_t AdcThresholdDown; /* BEMF voltage threshold for zero crossing detection when BEMF is decreasing */ uint16_t AdcThresholdUp; /* BEMF voltage threshold for zero crossing detection when BEMF is increasing */ uint16_t SamplingPoint; /* Pulse value of the timer channel used to trig the ADC when sensing occurs during PWM OFF time */ } Bemf_Sensing_Params; /* * @brief This structure is used to handle the demagnetization time before starting bemf acquisition * */ typedef struct { uint16_t DemagMinimumSpeedUnit; /* Speed threshold for minimum demagnetization time */ uint16_t RevUpDemagSpeedConv; /* Convertion factor between speed and demagnetization time */ uint16_t RunDemagSpeedConv; /* Open loop convertion factor between speed and demagnetization time during */ uint16_t DemagMinimumThreshold; /* Minimum demagnetization time */ } Bemf_Demag_Params; /* * @brief This structure is used to handle the data of an instance of the B-emf Feedback component * */ typedef struct { SpeednPosFdbk_Handle_t _Super; uint16_t BemfLastValues[3]; /* Bemf measurements of phase */ uint8_t ZcEvents; /* Number of bemf zero crossing events */ Bemf_Sensing_Params Pwm_ON; /* Parameters for zero crossing detection during ON time */ Bemf_Sensing_Params Pwm_OFF; /* Parameters for zero crossing detection during OFF time */ Bemf_Sensing_Params *pSensing_Params; uint16_t SamplingGuard; bool IsOnSensingEnabled; /* Value where 0 means BEMF is sensed during PWM OFF time and 1 or greater means BEMF is sensed during PWM ON time */ uint16_t OnSensingEnThres; /* Pulse value of HF timer above which the PWM ON sensing is enabled */ uint16_t OnSensingDisThres; /* Pulse value of HF timer below which the PWM ON sensing is disabled */ uint16_t Zc2CommDelay; /* Zero Crossing detection to commutation delay in 15/128 degrees */ Bemf_ADC_Params_t const *pParams_str; uint16_t SpeedSamplingFreqHz; /* Frequency (Hz) at which motor speed is to be computed. It must be equal to the frequency at which function SPD_CalcAvrgMecSpeedUnit is called.*/ uint8_t SpeedBufferSize; /* Size of the buffer used to calculate the average speed. It must be less than 18.*/ uint32_t TIMClockFreq; bool ADCRegularLocked; /* This flag is set when ADC is locked for bemf acquisition */ uint16_t ADC1_DMA_converted[5]; /* Buffer used for DMA data transfer after the ADC conversion */ uint16_t TIM1_pulses[5]; /* Buffer used for DMA data transfer after the ADC conversion */ int32_t ElPeriodSum; /* Period accumulator used to speed up the average speed computation*/ int16_t PrevRotorFreq; /* Used to store the last valid rotor electrical speed in dpp used when MAX_PSEUDO_SPEED is detected */ int8_t Direction; /* Instantaneous direction of rotor between two captures*/ int16_t AvrElSpeedDpp; /* Averaged rotor electrical speed express in s16degree per current control period.*/ int16_t VirtualElSpeedDpp; /* Averaged rotor electrical speed express in s16degree per current control period.*/ uint16_t MinStartUpValidSpeed; /* Absolute value of minimum mechanical speed required to validate the start-up. Expressed in the unit defined by #SPEED_UNIT. */ uint8_t StartUpConsistThreshold; /* Number of consecutive tests on speed consistency to be passed before validating the start-up */ uint8_t OverSamplingRate; bool IsSpeedReliable; /* Latest private speed reliability information, updated by SPD_CalcAvrgMecSpeedUnit, it is true if the speed measurement variance is lower then threshold corresponding to hVariancePercentage */ bool IsAlgorithmConverged; /* Boolean variable containing observer convergence information */ bool IsLoopClosed; /* Boolean variable containing speed loop status*/ bool ZcDetected; /* This flag is set when zero crossing is detected */ bool StepUpdate; /* This flag is set when step needs to be updated */ DrivingMode_t DriveMode; volatile uint8_t BufferFilled; /* Indicates the number of speed measuremt present in the buffer from the start. It will be max bSpeedBufferSize and it is used to validate the start of speed averaging. If bBufferFilled is below bSpeedBufferSize the instantaneous measured speed is returned as average speed.*/ int32_t SpeedBufferDpp[SPEED_BUFFER_LENGTH];/* Holding the last period captures */ uint32_t LowFreqTimerPsc; /* Prescaler value of the low frequency timer */ uint16_t SpeedFIFOIdx;/* Pointer of next element to be stored in the speed sensor buffer*/ int16_t DeltaAngle; /* Delta angle at the Hall sensor signal edge between current electrical rotor angle of synchronism. It is in s16degrees.*/ int16_t MeasuredElAngle; /* Electrical angle measured at each bemf zero crossing. It is considered the best measurement of electrical rotor angle.*/ int16_t CompSpeed; /* Speed compensation factor used to syncronize the current electrical angle with the target electrical angle. */ uint16_t SatSpeed; /* Returned value if the measured speed is above the maximum realistic.*/ uint32_t PseudoPeriodConv;/* Conversion factor between time interval Delta T between bemf zero crossing points, express in timer counts, and electrical rotor speed express in dpp. Ex. Rotor speed (dpp) = wPseudoFreqConv / Delta T It will be ((CKTIM / 6) / (SAMPLING_FREQ)) * 65536.*/ uint32_t MaxPeriod; /* Time delay between two bemf zero crossing points when the speed of the rotor is the minimum realistic in the application: this allows to discriminate too low freq for instance. This period shoud be expressed in timer counts and it will be: wMaxPeriod = ((10 * CKTIM) / 6) / MinElFreq(0.1Hz).*/ uint32_t MinPeriod; /* Time delay between two bemf zero crossing points when the speed of the rotor is the maximum realistic in the application: this allows discriminating glitches for instance. This period shoud be expressed in timer counts and it will be: wSpeedOverflow = ((10 * CKTIM) / 6) / MaxElFreq(0.1Hz).*/ uint16_t BemfTimeout; /* Max delay between two zero crossing signals to assert zero speed express in milliseconds.*/ uint16_t OvfFreq; /* Frequency of timer overflow (from 0 to 0x10000) it will be: hOvfFreq = CKTIM /65536.*/ uint16_t PWMNbrPSamplingFreq; /* Number of current control periods inside each speed control periods it will be: (hMeasurementFrequency / hSpeedSamplingFreqHz) - 1.*/ uint8_t PWMFreqScaling; /* Scaling factor to allow to store a PWMFrequency greater than 16 bits */ uint32_t Counter_Period; /* Low frequency timer period that allows speed calculation */ uint32_t ZC_Counter_Up; /* Low frequency timer counter value at zero crossing with increasing bemf */ uint32_t ZC_Counter_Down; /* Low frequency timer counter value at zero crossing with increasing bemf */ uint32_t ZC_Counter_Last; /* Last low frequency timer counter value at zero crossing */ uint32_t ZC_Counter_On_Last; /* Last low frequency timer counter value at zero crossing sensed with pwm on*/ uint32_t Last_Zc2Comm_Delay; /* Last delay between zero crossing and step change */ uint16_t DemagCounter; /* Demagnetization counter */ uint16_t DemagCounterThreshold; /* PWM cycles dedicated to windings demagnetization */ Bemf_Demag_Params DemagParams; /* Demagnetization parameters */ } Bemf_ADC_Handle_t; /* Exported functions --------------------------------------------------------*/ /* Initializes all the object variables. */ void BADC_Init( Bemf_ADC_Handle_t *pHandle ); /* Resets the ADC status and empties arrays. */ void BADC_Clear( Bemf_ADC_Handle_t *pHandle ); /* Gets ADC value and check for zero crossing detection.*/ bool BADC_IsZcDetected( Bemf_ADC_Handle_t *pHandle, PWMC_Handle_t *pHandlePWMC); /* Sets the trigger point of the ADC */ void BADC_SetSamplingPoint(Bemf_ADC_Handle_t *pHandle, PWMC_Handle_t *pHandlePWMC, SpeednTorqCtrl_Handle_t *pHandleSTC ); /* Computes the rotor average mechanical speed in the unit defined by #SPEED_UNIT and returns it in pMecSpeedUnit. */ bool BADC_CalcAvrgMecSpeedUnit( Bemf_ADC_Handle_t * pHandle, int16_t * pMecSpeedUnit ); /* Forces the rotation direction. */ void BADC_SetDirection( Bemf_ADC_Handle_t * pHandle, uint8_t direction ); /* Checks whether the state observer algorithm converged.*/ bool BADC_IsObserverConverged( Bemf_ADC_Handle_t * pHandle ); /* Starts the bemf acquisition.*/ void BADC_Start(Bemf_ADC_Handle_t *pHandle, uint8_t step); /* Stops the bemf acquisition.*/ void BADC_Stop(Bemf_ADC_Handle_t *pHandle); /* Selects the phase for the bemf acquisition.*/ void BADC_SelectAdcChannel(Bemf_ADC_Handle_t * pHandle, uint8_t Phase); /* Updates the estimated electrical angle.*/ int16_t BADC_CalcElAngle(Bemf_ADC_Handle_t * pHandle); /* Configures the sensorless parameters for the following step. */ void BADC_StepChangeEvent(Bemf_ADC_Handle_t * pHandle, int16_t hElSpeedDpp, PWMC_Handle_t *pHandlePWMC); /* Computes the demagnetization time during revup procedure. */ void BADC_CalcRevUpDemagTime(Bemf_ADC_Handle_t *pHandle); /* Computes the demagnetization time in closed loop operation.*/ void BADC_CalcRunDemagTime(Bemf_ADC_Handle_t *pHandle); /* Sets the flag when switch over phase ends.*/ void BADC_SetLoopClosed(Bemf_ADC_Handle_t *pHandle); /* Returns last converted Back-emf value.*/ uint16_t BADC_GetLastBemfValue(Bemf_ADC_Handle_t *pHandle, uint8_t phase); /* Returns the zero crossing detection flag. */ bool BADC_GetBemfZcrFlag(Bemf_ADC_Handle_t *pHandle); /* Enables low frequecy timer interrupt */ void BADC_SpeedMeasureOn(Bemf_ADC_Handle_t *pHandle); /* Disables low frequecy timer interrupt */ void BADC_SpeedMeasureOff(Bemf_ADC_Handle_t *pHandle); /* Clears StepUpdate flag */ bool BADC_ClearStepUpdate(Bemf_ADC_Handle_t *pHandle); /* Sets the parameters for bemf sensing during pwm off-time */ void BADC_SetBemfSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfAdcConfig, uint16_t *Zc2CommDelay, Bemf_Demag_Params *bemfAdcDemagConfig); /* Sets the parameters for bemf sensing during pwm on-time */ void BADC_SetBemfOnTimeSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfOnAdcConfig, uint16_t *OnSensingEnThres, uint16_t *OnSensingDisThres); /* Gets the parameters for bemf sensing during pwm off-time */ void BADC_GetBemfSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfAdcConfig, uint16_t *Zc2CommDelay, Bemf_Demag_Params *bemfAdcDemagConfig); /* Gets the parameters for bemf sensing during pwm on-time */ void BADC_GetBemfOnTimeSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfOnAdcConfig, uint16_t *OnSensingEnThres, uint16_t *OnSensingDisThres); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* BEMFADCFDBK_H */ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
15,524
C
50.237624
150
0.617302
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/G0xx/Inc/r3_g0xx_pwm_curr_fdbk.h
/** ****************************************************************************** * @file r3_g0xx_pwm_curr_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * R3_G0XX_pwm_curr_fdbk component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup R3_G0XX_pwm_curr_fdbk */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __R3_G0XX_PWMNCURRFDBK_H #define __R3_G0XX_PWMNCURRFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "pwm_curr_fdbk.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup R3_1_pwm_curr_fdbk * @{ */ /* Exported constants --------------------------------------------------------*/ /* Exported types ------------------------------------------------------------*/ /* * @brief R3_G0XX parameters definition */ typedef struct { TIM_TypeDef* TIMx; /* Timer used for PWM generation. */ uint32_t ADCConfig[6]; /* Stores ADC sequence for the 6 sectors. */ volatile uint16_t *ADCDataReg1[6]; /*!< Stores ADC read value's address for the 6 sectors. Specific to F0XX and G0XX. */ volatile uint16_t *ADCDataReg2[6]; /*!< Stores ADC read value's address for the 6 sectors. Specific to F0XX and G0XX. */ uint16_t hDeadTime; /*!< Dead time in number of TIM clock cycles. Specific to F0XX and G0XX. If CHxN are enabled, it must contain the dead time to be generated by the microcontroller, otherwise it expresses the maximum dead time generated by driving network. */ uint16_t hTafter; /* Sum of dead time plus max value between rise time and noise time express in number of TIM clocks.*/ uint16_t hTbefore; /* Sampling time express in number of TIM clocks.*/ uint16_t Tsampling; /* Sampling time express in number of TIM clocks.*/ uint16_t Tcase2; /* Sampling time express in number of TIM clocks.*/ uint16_t Tcase3; /* Sampling time express in number of TIM clocks.*/ uint8_t RepetitionCounter; /* Expresses the number of PWM periods to be elapsed before compare registers are updated again. In particular: RepetitionCounter= (2* #PWM periods)-1*/ uint8_t ADCScandir[6]; /*!< Stores ADC scan direction for the 6 sectors. Specific to F0XX and G0XX.*/ }R3_1_Params_t; /* * @brief Handle structure of the R1_G0XX_pwm_curr_fdbk Component. */ typedef struct { PWMC_Handle_t _Super; /* Base component handler. */ uint32_t PhaseAOffset; /* Offset of Phase A current sensing network. */ uint32_t PhaseBOffset; /* Offset of Phase B current sensing network. */ uint32_t PhaseCOffset; /* Offset of Phase C current sensing network. */ volatile uint32_t ADCTriggerEdge; /* External ADC trigger edge. */ uint16_t Half_PWMPeriod; /* Half PWM Period in timer clock counts. */ volatile uint16_t ADC1_DMA_converted[2]; /* Buffer used for DMA data transfer after the ADC conversion. */ volatile uint8_t PolarizationCounter; /* Number of conversions performed during the calibration phase. */ uint8_t CalibSector; /* Space vector sector number during calibration. */ bool ADCRegularLocked; /*!< This flag is set when regular conversions are locked. Specific to F0XX and G0XX. */ R3_1_Params_t const * pParams_str; }PWMC_R3_1_Handle_t; /* Exported functions ------------------------------------------------------- */ /* * Initializes TIM1, ADC1, GPIO, DMA1 and NVIC for three shunt current * reading configuration using STM32G0x. */ void R3_1_Init(PWMC_R3_1_Handle_t *pHandle); /* * Stores into the handler the voltage present on the * current feedback analog channel when no current is flowing into the * motor */ void R3_1_CurrentReadingCalibration(PWMC_Handle_t *pHdl); /* * Computes and stores in the handler the latest converted motor phase currents in ab_t format. */ void R3_1_GetPhaseCurrents(PWMC_Handle_t *pHdl, ab_t* pStator_Currents); /* * Computes and stores in the handler the latest converted motor phase currents in ab_t format. Specific to overmodulation. */ void R3_1_GetPhaseCurrents_OVM( PWMC_Handle_t * pHdl, ab_t * Iab ); /* * Configures the ADC for the current sampling related to sector X (X = [1..6] ). */ uint16_t R3_1_SetADCSampPointSectX(PWMC_Handle_t * pHdl ); /* * Configures the ADC for the current sampling related to sector X (X = [1..6] ) in case of overmodulation. */ uint16_t R3_1_SetADCSampPointSectX_OVM( PWMC_Handle_t * pHdl ); /* * Configures the ADC for the current sampling during calibration. */ uint16_t R3_1_SetADCSampPointCalibration(PWMC_Handle_t *pHdl); /* * Turns on low sides switches. */ void R3_1_TurnOnLowSides(PWMC_Handle_t *pHdl, uint32_t ticks); /* * Enables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_1_SwitchOnPWM(PWMC_Handle_t *pHdl); /* * Disables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_1_SwitchOffPWM(PWMC_Handle_t *pHdl); /* * Executes a regular conversion. */ uint16_t R3_1_ExecRegularConv(PWMC_Handle_t *pHdl, uint8_t bChannel); /* * Contains the TIMx Update event interrupt. */ void *R3_1_TIMx_UP_IRQHandler( PWMC_R3_1_Handle_t * pHandle ); /* * Sets the calibrated offset. */ void R3_1_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /* * Reads the calibrated offsets. */ void R3_1_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*__R3_G0XX_PWMNCURRFDBK_H*/ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
7,047
C
34.959183
124
0.570597
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/H5xx/Src/r3_1_h5xx_pwm_curr_fdbk.c
/** ****************************************************************************** * @file r3_1_h5xx_pwm_curr_fdbk.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement the features * of the three shunts current sensing topology. * * It is specifically designed for STM32H5XX microcontrollers and * implements the successive sampling of current using two ADCs. * + MCU peripheral and handle initialization function * + three shunt current sensing * + space vector modulation function * + ADC sampling function * ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup R3_1_H5XX_pwm_curr_fdbk */ /* Includes ------------------------------------------------------------------*/ #include "r3_1_h5xx_pwm_curr_fdbk.h" #include "pwm_common.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup R3_1_pwm_curr_fdbk * @{ */ /* Private defines -----------------------------------------------------------*/ #define TIMxCCER_MASK_CH123 ((uint16_t) (LL_TIM_CHANNEL_CH1|LL_TIM_CHANNEL_CH1N|\ LL_TIM_CHANNEL_CH2|LL_TIM_CHANNEL_CH2N|\ LL_TIM_CHANNEL_CH3|LL_TIM_CHANNEL_CH3N)) /* Private function prototypes -----------------------------------------------*/ static void R3_1_TIMxInit(TIM_TypeDef *TIMx, PWMC_Handle_t *pHdl); static void R3_1_ADCxInit(ADC_TypeDef *ADCx); __STATIC_INLINE uint16_t R3_1_WriteTIMRegisters( PWMC_Handle_t * pHdl, uint16_t hCCR4Reg ); static void R3_1_HFCurrentsPolarizationAB( PWMC_Handle_t * pHdl,ab_t * Iab ); static void R3_1_HFCurrentsPolarizationC( PWMC_Handle_t * pHdl, ab_t * Iab ); uint16_t R3_1_SetADCSampPointPolarization( PWMC_Handle_t * pHdl) ; static void R3_1_RLGetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * Iab ); static void R3_1_RLTurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ); static void R3_1_RLSwitchOnPWM( PWMC_Handle_t * pHdl ); /* * @brief Initializes TIMx, ADC, GPIO, DMA1 and NVIC for current reading * in three shunt topology one ADC. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void R3_1_Init( PWMC_R3_1_Handle_t * pHandle ) { TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; /*Checks that _Super is the first member of the structure PWMC_R3_1_Handle_t */ if ((uint32_t)pHandle == (uint32_t)&pHandle->_Super) //cstat !MISRAC2012-Rule-11.4 { /* Disables IT and flags in case of LL driver usage * workaround for unwanted interrupt enabling done by LL driver */ LL_ADC_DisableIT_EOC(ADCx); LL_ADC_ClearFlag_EOC(ADCx); LL_ADC_DisableIT_JEOC(ADCx); LL_ADC_ClearFlag_JEOC(ADCx); if (TIM1 == TIMx) { /* TIM1 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph(LL_DBGMCU_APB2_GRP1_TIM1_STOP); } #if defined(TIM8) else { /* TIM8 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph(LL_DBGMCU_APB2_GRP1_TIM8_STOP); } #endif if (0U == LL_ADC_IsEnabled(ADCx)) { R3_1_ADCxInit(ADCx); /* Only the Interrupt of the first ADC is enabled. * As Both ADCs are fired by HW at the same moment * It is safe to consider that both conversion are ready at the same time*/ LL_ADC_ClearFlag_JEOS(ADCx); LL_ADC_EnableIT_JEOS(ADCx); } else { /* Nothing to do ADCx already configured */ } R3_1_TIMxInit(TIMx, &pHandle->_Super); } else { /* Nothing to do */ } } /* * @brief Initializes @p ADCx peripheral for current sensing. * */ static void R3_1_ADCxInit(ADC_TypeDef *ADCx) { /* - Exit from deep-power-down mode */ LL_ADC_DisableDeepPowerDown(ADCx); if (0U == LL_ADC_IsInternalRegulatorEnabled(ADCx)) { /* Enable ADC internal voltage regulator */ LL_ADC_EnableInternalRegulator(ADCx); /* Wait for Regulator Startup time, once for both */ /* Note: Variable divided by 2 to compensate partially */ /* CPU processing cycles, scaling in us split to not */ /* exceed 32 bits register capacity and handle low frequency. */ volatile uint32_t wait_loop_index = ((LL_ADC_DELAY_INTERNAL_REGUL_STAB_US / 10UL) * (SystemCoreClock / (100000UL * 2UL))); while (wait_loop_index != 0UL) { wait_loop_index--; } } else { /* Nothing to do */ } LL_ADC_StartCalibration(ADCx, LL_ADC_SINGLE_ENDED); while (1U == LL_ADC_IsCalibrationOnGoing(ADCx)) { /* Nothing to do */ } /* ADC Enable (must be done after calibration) */ /* ADC5-140924: Enabling the ADC by setting ADEN bit soon after polling ADCAL=0 * following a calibration phase, could have no effect on ADC * within certain AHB/ADC clock ratio. */ while (0U == LL_ADC_IsActiveFlag_ADRDY(ADCx)) { LL_ADC_Enable(ADCx); } /* Clear JSQR from CubeMX setting to avoid not wanting conversion*/ LL_ADC_INJ_StartConversion(ADCx); LL_ADC_INJ_StopConversion(ADCx); /* TODO: check if not already done by MX */ LL_ADC_INJ_SetQueueMode(ADCx, LL_ADC_INJ_QUEUE_2CONTEXTS_END_EMPTY); } /* * @brief Initializes @p TIMx peripheral with @p pHdl handler for PWM generation. * */ static void R3_1_TIMxInit(TIM_TypeDef *TIMx, PWMC_Handle_t *pHdl) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 volatile uint32_t Brk2Timeout = 1000; /* disable main TIM counter to ensure * a synchronous start by TIM2 trigger */ LL_TIM_DisableCounter(TIMx); LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); /* Enables the TIMx Preload on CC1 Register */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH1); /* Enables the TIMx Preload on CC2 Register */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH2); /* Enables the TIMx Preload on CC3 Register */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH3); /* Enables the TIMx Preload on CC4 Register */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH4); /* Prepare timer for synchronization */ LL_TIM_GenerateEvent_UPDATE(TIMx); if (2U == pHandle->pParams_str->bFreqRatio) { if (HIGHER_FREQ == pHandle->pParams_str->bIsHigherFreqTim) { if (3U == pHandle->pParams_str->RepetitionCounter) { /* Set TIMx repetition counter to 1 */ LL_TIM_SetRepetitionCounter(TIMx, 1); LL_TIM_GenerateEvent_UPDATE(TIMx); /* Repetition counter will be set to 3 at next Update */ LL_TIM_SetRepetitionCounter(TIMx, 3); } else { /* Nothing to do */ } } else { /* Nothing to do */ } LL_TIM_SetCounter(TIMx, (uint32_t)(pHandle->Half_PWMPeriod) - 1U); } else /* bFreqRatio equal to 1 or 3 */ { if (M1 == pHandle->_Super.Motor) { if (1U == pHandle->pParams_str->RepetitionCounter) { LL_TIM_SetCounter(TIMx, (uint32_t)(pHandle->Half_PWMPeriod) - 1U); } else if (3U == pHandle->pParams_str->RepetitionCounter) { /* Set TIMx repetition counter to 1 */ LL_TIM_SetRepetitionCounter(TIMx, 1); LL_TIM_GenerateEvent_UPDATE(TIMx); /* Repetition counter will be set to 3 at next Update */ LL_TIM_SetRepetitionCounter(TIMx, 3); } else { /* Nothing to do */ } } else { /* Nothing to do */ } } LL_TIM_ClearFlag_BRK(TIMx); uint32_t result; result = LL_TIM_IsActiveFlag_BRK2(TIMx); while ((Brk2Timeout != 0u) && (1U == result)) { LL_TIM_ClearFlag_BRK2(TIMx); Brk2Timeout--; result = LL_TIM_IsActiveFlag_BRK2(TIMx); } LL_TIM_EnableIT_BRK(TIMx); /* Enable PWM channel */ LL_TIM_CC_EnableChannel(TIMx, TIMxCCER_MASK_CH123); } /* * @brief Stores in @p pHdl handler the calibrated @p offsets. * */ __weak void R3_1_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 pHandle->PhaseAOffset = offsets->phaseAOffset; pHandle->PhaseBOffset = offsets->phaseBOffset; pHandle->PhaseCOffset = offsets->phaseCOffset; pHdl->offsetCalibStatus = true; } /* * @brief Reads the calibrated @p offsets stored in @p pHdl handler. * */ __weak void R3_1_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 offsets->phaseAOffset = pHandle->PhaseAOffset; offsets->phaseBOffset = pHandle->PhaseBOffset; offsets->phaseCOffset = pHandle->PhaseCOffset; } /* * @brief Stores into the @p pHdl handler the voltage present on Ia and * Ib current feedback analog channels when no current is flowing into the * motor. * */ __weak void R3_1_CurrentReadingPolarization(PWMC_Handle_t *pHdl) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef *ADCx = pHandle->pParams_str->ADCx; volatile PWMC_GetPhaseCurr_Cb_t GetPhaseCurrCbSave; volatile PWMC_SetSampPointSectX_Cb_t SetSampPointSectXCbSave; if (true == pHandle->_Super.offsetCalibStatus) { LL_ADC_INJ_StartConversion(ADCx); pHandle->ADC_ExternalPolarityInjected = (uint16_t)LL_ADC_INJ_TRIG_EXT_RISING; } else { /* Save callback routines */ GetPhaseCurrCbSave = pHandle->_Super.pFctGetPhaseCurrents; SetSampPointSectXCbSave = pHandle->_Super.pFctSetADCSampPointSectX; pHandle->PhaseAOffset = 0U; pHandle->PhaseBOffset = 0U; pHandle->PhaseCOffset = 0U; pHandle->PolarizationCounter = 0U; /* It forces inactive level on TIMx CHy and CHyN */ LL_TIM_CC_DisableChannel(TIMx, TIMxCCER_MASK_CH123); /* Offset calibration for all phases */ /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R3_1_HFCurrentsPolarizationAB; pHandle->_Super.pFctSetADCSampPointSectX = &R3_1_SetADCSampPointPolarization; pHandle->ADC_ExternalPolarityInjected = (uint16_t)LL_ADC_INJ_TRIG_EXT_RISING; /* We want to polarize calibration Phase A and Phase B, so we select SECTOR_5 */ pHandle->PolarizationSector=SECTOR_5; /* Required to force first polarization conversion on SECTOR_5*/ pHandle->_Super.Sector = SECTOR_5; R3_1_SwitchOnPWM(&pHandle->_Super); /* IF CH4 is enabled, it means that JSQR is now configured to sample polarization current*/ /*while ( LL_TIM_CC_IsEnabledChannel(TIMx, LL_TIM_CHANNEL_CH4) == 0u ) */ while (((TIMx->CR2) & TIM_CR2_MMS_Msk) != LL_TIM_TRGO_OC4REF) { /* Nothing to do */ } /* It is the right time to start the ADC without unwanted conversion */ /* Start ADC to wait for external trigger. This is series dependant*/ LL_ADC_INJ_StartConversion(ADCx); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd(TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter); R3_1_SwitchOffPWM(&pHandle->_Super); /* Offset calibration for C phase */ pHandle->PolarizationCounter = 0U; /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R3_1_HFCurrentsPolarizationC; /* We want to polarize Phase C, so we select SECTOR_1 */ pHandle->PolarizationSector=SECTOR_1; /* Required to force first polarization conversion on SECTOR_1*/ pHandle->_Super.Sector = SECTOR_1; R3_1_SwitchOnPWM(&pHandle->_Super); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd(TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter); R3_1_SwitchOffPWM(&pHandle->_Super); pHandle->PhaseAOffset /= NB_CONVERSIONS; pHandle->PhaseBOffset /= NB_CONVERSIONS; pHandle->PhaseCOffset /= NB_CONVERSIONS; if (0U == pHandle->_Super.SWerror) { pHandle->_Super.offsetCalibStatus = true; } else { /* nothing to do */ } /* Change back function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = GetPhaseCurrCbSave; pHandle->_Super.pFctSetADCSampPointSectX = SetSampPointSectXCbSave; } /* It over write TIMx CCRy wrongly written by FOC during calibration so as to force 50% duty cycle on the three inverer legs */ /* Disable TIMx preload */ LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH1); LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH2); LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH3); LL_TIM_OC_SetCompareCH1 (TIMx, pHandle->Half_PWMPeriod); LL_TIM_OC_SetCompareCH2 (TIMx, pHandle->Half_PWMPeriod); LL_TIM_OC_SetCompareCH3 (TIMx, pHandle->Half_PWMPeriod); /* Enable TIMx preload */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH1); LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH2); LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH3); /* It re-enable drive of TIMx CHy and CHyN by TIMx CHyRef*/ LL_TIM_CC_EnableChannel(TIMx, TIMxCCER_MASK_CH123); /* At the end of calibration, all phases are at 50% we will sample A&B */ pHandle->_Super.Sector = SECTOR_5; pHandle->_Super.BrakeActionLock = false; } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /* * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p pStator_Currents ab_t format. * */ __weak void R3_1_GetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t* Iab ) { if (MC_NULL == Iab) { /* nothing to do */ } else { int32_t Aux; uint32_t ADCDataReg1; uint32_t ADCDataReg2; PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; uint8_t Sector; Sector = (uint8_t)pHandle->_Super.Sector; ADCDataReg1 = ADCx->JDR1; ADCDataReg2 = ADCx->JDR2; /* disable ADC trigger source */ /* LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4) */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); switch (Sector) { case SECTOR_4: case SECTOR_5: { /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = (int32_t)(pHandle->PhaseAOffset) - (int32_t)(ADCDataReg1); /* Saturation of Ia */ if (Aux < -INT16_MAX) { Iab->a = -INT16_MAX; } else if (Aux > INT16_MAX) { Iab->a = INT16_MAX; } else { Iab->a = (int16_t)Aux; } /* Ib = PhaseBOffset - ADC converted value) */ Aux = (int32_t)(pHandle->PhaseBOffset) - (int32_t)(ADCDataReg2); /* Saturation of Ib */ if (Aux < -INT16_MAX) { Iab->b = -INT16_MAX; } else if (Aux > INT16_MAX) { Iab->b = INT16_MAX; } else { Iab->b = (int16_t)Aux; } break; } case SECTOR_6: case SECTOR_1: { /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ Aux = (int32_t)(pHandle->PhaseBOffset) - (int32_t)(ADCDataReg1); /* Saturation of Ib */ if (Aux < -INT16_MAX) { Iab->b = -INT16_MAX; } else if (Aux > INT16_MAX) { Iab->b = INT16_MAX; } else { Iab->b = (int16_t)Aux; } /* Ia = -Ic -Ib */ Aux = (int32_t)(ADCDataReg2) - (int32_t)(pHandle->PhaseCOffset); /* -Ic */ Aux -= (int32_t)Iab->b; /* Ia */ /* Saturation of Ia */ if (Aux > INT16_MAX) { Iab->a = INT16_MAX; } else if (Aux < -INT16_MAX) { Iab->a = -INT16_MAX; } else { Iab->a = (int16_t)Aux; } break; } case SECTOR_2: case SECTOR_3: { /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = (int32_t)(pHandle->PhaseAOffset) - (int32_t)(ADCDataReg1); /* Saturation of Ia */ if (Aux < -INT16_MAX) { Iab->a = -INT16_MAX; } else if (Aux > INT16_MAX) { Iab->a = INT16_MAX; } else { Iab->a = (int16_t)Aux; } /* Ib = -Ic -Ia */ Aux = (int32_t)(ADCDataReg2) - (int32_t)(pHandle->PhaseCOffset); /* -Ic */ Aux -= (int32_t)Iab->a; /* Ib */ /* Saturation of Ib */ if (Aux > INT16_MAX) { Iab->b = INT16_MAX; } else if (Aux < -INT16_MAX) { Iab->b = -INT16_MAX; } else { Iab->b = (int16_t)Aux; } break; } default: break; } pHandle->_Super.Ia = Iab->a; pHandle->_Super.Ib = Iab->b; pHandle->_Super.Ic = -Iab->a - Iab->b; } } /* * @brief Implementation of PWMC_GetPhaseCurrents to be performed during polarization. * * It sums up injected conversion data into PhaseAOffset and * PhaseBOffset to compute the offset introduced in the current feedback * network. It is required to properly configure ADC inputs before in order to enable * the offset computation. * * @param pHdl: Handler of the current instance of the PWM component. * @param Iab: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ static void R3_1_HFCurrentsPolarizationAB( PWMC_Handle_t * pHdl, ab_t * Iab ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; uint32_t ADCDataReg1 = ADCx->JDR1; uint32_t ADCDataReg2 = ADCx->JDR2; /* disable ADC trigger source */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); if ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { pHandle-> PhaseAOffset += ADCDataReg1; pHandle-> PhaseBOffset += ADCDataReg2; pHandle->PolarizationCounter++; } /* during offset calibration no current is flowing in the phases */ Iab->a = 0; Iab->b = 0; } /* * @brief Implementation of PWMC_GetPhaseCurrents to be performed during polarization. * * It sums up injected conversion data into PhaseCOffset to compute the * offset introduced in the current feedback * network. It is required to proper configure ADC inputs before enabling * the offset computation. * * @param pHdl: Handler of the current instance of the PWM component. * @param Iab: Pointer to the structure that will receive motor current * of phase A and B in ElectricalValue format. */ static void R3_1_HFCurrentsPolarizationC( PWMC_Handle_t * pHdl, ab_t * Iab ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; uint32_t ADCDataReg2 = ADCx->JDR2; /* disable ADC trigger source */ //LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); if ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { /* Phase C is read from SECTOR_1, second value */ pHandle-> PhaseCOffset += ADCDataReg2; pHandle->PolarizationCounter++; } /* during offset calibration no current is flowing in the phases */ Iab->a = 0; Iab->b = 0; } /* * @brief Configures the ADC for the current sampling during calibration. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ uint16_t R3_1_SetADCSampPointPolarization( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ pHandle->_Super.Sector = pHandle->PolarizationSector; return R3_1_WriteTIMRegisters( &pHandle->_Super, ( pHandle->Half_PWMPeriod - (uint16_t) 1 ) ); } /* * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p Iab ab_t format. Specific to overmodulation. * */ __weak void R3_1_GetPhaseCurrents_OVM( PWMC_Handle_t * pHdl, ab_t * Iab ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; uint8_t Sector; int32_t Aux; uint32_t ADCDataReg1; uint32_t ADCDataReg2; Sector = ( uint8_t )pHandle->_Super.Sector; ADCDataReg1 = ADCx->JDR1; ADCDataReg2 = ADCx->JDR2; /* disable ADC trigger source */ /* LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4) */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); switch ( Sector ) { case SECTOR_4: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { // Ib not available, use estimated Ib Aux = ( int32_t )( pHandle->_Super.IbEst ); } else { /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg2 ); } /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_5: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { // Ia not available, use estimated Ia Aux = ( int32_t )( pHandle->_Super.IaEst ); } else { Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg2 ); /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_6: /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IcEst ; /* -Ic */ Aux -= ( int32_t )Iab->b; } else { /* Ia = -Ic -Ib */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->b; /* Ia */ } /* Saturation of Ia */ if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else { Iab->a = ( int16_t )Aux; } break; case SECTOR_1: /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IbEst; } else { Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } /* Ia = -Ic -Ib */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->b; /* Ia */ /* Saturation of Ia */ if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else { Iab->a = ( int16_t )Aux; } break; case SECTOR_2: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IaEst; } else { Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } /* Ib = -Ic -Ia */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ /* Saturation of Ib */ if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_3: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { /* Ib = -Ic -Ia */ Aux = ( int32_t ) pHandle->_Super.IcEst; /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ } else { /* Ib = -Ic -Ia */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ } /* Saturation of Ib */ if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; default: break; } pHandle->_Super.Ia = Iab->a; pHandle->_Super.Ib = Iab->b; pHandle->_Super.Ic = -Iab->a - Iab->b; } /* * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors of driving section. It has to be * called each motor start-up when using high voltage drivers. * * @param pHdl: Handler of the current instance of the PWM component * @param ticks: Timer ticks value to be applied * Min value: 0 (low sides ON) * Max value: PWM_PERIOD_CYCLES/2 (low sides OFF) */ __weak void R3_1_TurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ) { PWMC_R3_1_Handle_t * pHandle = (PWMC_R3_1_Handle_t *) pHdl; TIM_TypeDef* TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = true; /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE(TIMx); /*Turn on the three low side switches */ LL_TIM_OC_SetCompareCH1(TIMx,ticks); LL_TIM_OC_SetCompareCH2(TIMx,ticks); LL_TIM_OC_SetCompareCH3(TIMx,ticks); /* Wait until next update */ while (LL_TIM_IsActiveFlag_UPDATE(TIMx) == RESET) {} LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs(TIMx); if ( (pHandle->_Super.LowSideOutputs) == ES_GPIO ) { LL_GPIO_SetOutputPin (pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_SetOutputPin (pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_SetOutputPin (pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } return; } /* * @brief Enables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_1_SwitchOnPWM( PWMC_Handle_t * pHdl ) { PWMC_R3_1_Handle_t * pHandle = (PWMC_R3_1_Handle_t *) pHdl; TIM_TypeDef* TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = false; /* Set all duty to 50% */ LL_TIM_OC_SetCompareCH1(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH2(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH3(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH4(TIMx, (uint32_t)(pHandle->Half_PWMPeriod - 5u)); /* wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE(TIMx); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE(TIMx); /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE; LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { if ( LL_TIM_CC_IsEnabledChannel(TIMx,TIMxCCER_MASK_CH123) != 0u ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Enable Update IRQ */ LL_TIM_EnableIT_UPDATE(TIMx); return; } /* * @brief Disables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_1_SwitchOffPWM( PWMC_Handle_t * pHdl ) { PWMC_R3_1_Handle_t * pHandle = (PWMC_R3_1_Handle_t *) pHdl; TIM_TypeDef* TIMx = pHandle->pParams_str->TIMx; /* Disable UPDATE ISR */ LL_TIM_DisableIT_UPDATE( TIMx ); pHandle->_Super.TurnOnLowSidesAction = false; /* Main PWM Output Disable */ LL_TIM_DisableAllOutputs( TIMx ); if ( (pHandle->_Super.LowSideOutputs) == ES_GPIO ) { LL_GPIO_ResetOutputPin (pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_ResetOutputPin (pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_ResetOutputPin (pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } /* wait for a new PWM period to flush last HF task */ LL_TIM_ClearFlag_UPDATE(TIMx); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} LL_TIM_ClearFlag_UPDATE(TIMx); return; } /* * @brief Writes into peripheral registers the new duty cycles and sampling point. * * @param pHdl: Handler of the current instance of the PWM component. * @param hCCR4Reg: New capture/compare register value, written in timer clock counts. * @retval Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ __STATIC_INLINE uint16_t R3_1_WriteTIMRegisters( PWMC_Handle_t * pHdl, uint16_t hCCR4Reg ) { PWMC_R3_1_Handle_t * pHandle = (PWMC_R3_1_Handle_t *) pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint16_t hAux; LL_TIM_OC_SetCompareCH1( TIMx, pHandle->_Super.CntPhA ); LL_TIM_OC_SetCompareCH2( TIMx, pHandle->_Super.CntPhB ); LL_TIM_OC_SetCompareCH3( TIMx, pHandle->_Super.CntPhC ); LL_TIM_OC_SetCompareCH4( TIMx, hCCR4Reg ); /* Limit for update event */ /* Check the if TIMx CH4 is enabled. If it is set, an update event has occurred and thus the FOC rate is too high */ if (LL_TIM_CC_IsEnabledChannel(TIMx, LL_TIM_CHANNEL_CH4)) { hAux = MC_DURATION; } else { hAux = MC_NO_ERROR; } if ( pHandle->_Super.SWerror == 1u ) { hAux = MC_DURATION; pHandle->_Super.SWerror = 0u; } return hAux; } /* * @brief Configures the ADC for the current sampling related to sector X (X = [1..6] ). * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ __weak uint16_t R3_1_SetADCSampPointSectX( PWMC_Handle_t * pHdl ) { PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; uint16_t hCntSmp; uint16_t hDeltaDuty; register uint16_t lowDuty = pHdl->lowDuty; register uint16_t midDuty = pHdl->midDuty; /* Check if sampling AB in the middle of PWM is possible */ if ( ( uint16_t )( pHandle->Half_PWMPeriod - lowDuty ) > pHandle->pParams_str->hTafter ) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled wIch corresponds * to sector 4 */ pHandle->_Super.Sector = SECTOR_4; /* set sampling point trigger in the middle of PWM period */ hCntSmp = ( uint32_t )( pHandle->Half_PWMPeriod ) - 1u; } else { /* ADC Injected sequence configuration. The stator phase with minimum value of complementary duty cycle is set as first. In every sector there is always one phase with maximum complementary duty, one with minimum complementary duty and one with variable complementary duty. In this case, phases with variable complementary duty and with maximum duty are converted and the first will be always the phase with variable complementary duty cycle */ /* Crossing Point Searching */ hDeltaDuty = ( uint16_t )( lowDuty - midDuty ); /* Definition of crossing point */ if ( hDeltaDuty > ( uint16_t )( pHandle->Half_PWMPeriod - lowDuty ) * 2u ) { /* hTbefore = 2*Ts + Tc, where Ts = Sampling time of ADC, Tc = Conversion Time of ADC */ hCntSmp = lowDuty - pHandle->pParams_str->hTbefore; } else { /* hTafter = DT + max(Trise, Tnoise) */ hCntSmp = lowDuty + pHandle->pParams_str->hTafter; if ( hCntSmp >= pHandle->Half_PWMPeriod ) { /* It must be changed the trigger direction from positive to negative to sample after middle of PWM*/ pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_FALLING; hCntSmp = ( 2u * pHandle->Half_PWMPeriod ) - hCntSmp - 1u; } } } return R3_1_WriteTIMRegisters( &pHandle->_Super, hCntSmp ); } /* * @brief Configures the ADC for the current sampling related to sector X (X = [1..6] ) in case of overmodulation. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ uint16_t R3_1_SetADCSampPointSectX_OVM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ uint16_t SamplingPoint; uint16_t DeltaDuty; pHandle->_Super.useEstCurrent = false; DeltaDuty = ( uint16_t )( pHdl->lowDuty - pHdl->midDuty ); /* case 1 (cf user manual) */ if (( uint16_t )( pHandle->Half_PWMPeriod - pHdl->lowDuty ) > pHandle->pParams_str->hTafter) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled which corresponds * to sector 4 or 5 */ pHandle->_Super.Sector = SECTOR_5; /* set sampling point trigger in the middle of PWM period */ SamplingPoint = pHandle->Half_PWMPeriod - (uint16_t) 1; } else /* case 2 (cf user manual) */ { if (DeltaDuty >= pHandle->pParams_str->Tcase2) { SamplingPoint = pHdl->lowDuty - pHandle->pParams_str->hTbefore; } else { /* case 3 (cf user manual) */ if ((pHandle->Half_PWMPeriod - pHdl->lowDuty) > pHandle->pParams_str->Tcase3) { /* ADC trigger edge must be changed from positive to negative */ pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_FALLING; SamplingPoint = pHdl->lowDuty + pHandle->pParams_str->Tsampling; } else { SamplingPoint = pHandle->Half_PWMPeriod-1; pHandle->_Super.useEstCurrent = true; } } } return R3_1_WriteTIMRegisters( &pHandle->_Super, SamplingPoint ); } /* * @brief Contains the TIMx Update event interrupt. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void * R3_1_TIMx_UP_IRQHandler( PWMC_R3_1_Handle_t * pHandle) { void *tempPointer; if (MC_NULL == pHandle) { tempPointer = MC_NULL; } else { TIM_TypeDef* TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef* ADCx = pHandle->pParams_str->ADCx; ADCx->JSQR = pHandle->pParams_str->ADCConfig[pHandle->_Super.Sector] | (uint32_t) pHandle->ADC_ExternalPolarityInjected; /* enable ADC trigger source */ /* LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH4) */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_OC4REF); pHandle->ADC_ExternalPolarityInjected = (uint16_t)LL_ADC_INJ_TRIG_EXT_RISING; tempPointer = &(pHandle->_Super.Motor); } return (tempPointer); } /* * @brief Sets the PWM mode for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_1_RLDetectionModeEnable( PWMC_Handle_t * pHdl ) { PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; if ( pHandle->_Super.RLDetectionMode == false ) { /* Channel1 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH1, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH1N ); LL_TIM_OC_SetCompareCH1( TIMx, 0u ); /* Channel2 configuration */ if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_ACTIVE ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_INACTIVE ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else { } /* Channel3 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH3, LL_TIM_OCMODE_PWM2 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3N ); } pHandle->_Super.pFctGetPhaseCurrents = &R3_1_RLGetPhaseCurrents; pHandle->_Super.pFctTurnOnLowSides = &R3_1_RLTurnOnLowSides; pHandle->_Super.pFctSwitchOnPwm = &R3_1_RLSwitchOnPWM; pHandle->_Super.pFctSwitchOffPwm = &R3_1_SwitchOffPWM; pHandle->_Super.RLDetectionMode = true; } /* * @brief Disables the PWM mode for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_1_RLDetectionModeDisable( PWMC_Handle_t * pHdl ) { PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; if ( pHandle->_Super.RLDetectionMode == true ) { /* Channel1 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH1, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1 ); if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH1N ); } else { } LL_TIM_OC_SetCompareCH1( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) >> 1 ); /* Channel2 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2 ); if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else { } LL_TIM_OC_SetCompareCH2( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) >> 1 ); /* Channel3 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH3, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH3 ); if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH3N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3N ); } else { } LL_TIM_OC_SetCompareCH3( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) >> 1 ); pHandle->_Super.pFctGetPhaseCurrents = &R3_1_GetPhaseCurrents; pHandle->_Super.pFctTurnOnLowSides = &R3_1_TurnOnLowSides; pHandle->_Super.pFctSwitchOnPwm = &R3_1_SwitchOnPWM; pHandle->_Super.pFctSwitchOffPwm = &R3_1_SwitchOffPWM; pHandle->_Super.RLDetectionMode = false; } } /* * @brief Sets the PWM dutycycle for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. * @param hDuty: Duty cycle to apply, written in uint16_t. * @retval Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ uint16_t R3_1_RLDetectionModeSetDuty( PWMC_Handle_t * pHdl, uint16_t hDuty ) { PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint32_t val; uint16_t hAux; val = ( ( uint32_t )( pHandle->Half_PWMPeriod ) * ( uint32_t )( hDuty ) ) >> 16; pHandle->_Super.CntPhA = ( uint16_t )( val ); /* TIM1 Channel 1 Duty Cycle configuration. * In RL Detection mode only the Up-side device of Phase A are controlled*/ LL_TIM_OC_SetCompareCH1(TIMx, ( uint32_t )pHandle->_Super.CntPhA); /* set the sector that correspond to Phase A and B sampling */ pHdl->Sector = SECTOR_4; /* Limit for update event */ /* Check the status flag. If an update event has occurred before to set new values of regs the FOC rate is too high */ if (LL_TIM_CC_IsEnabledChannel(TIMx, LL_TIM_CHANNEL_CH4)) { hAux = MC_DURATION; } else { hAux = MC_NO_ERROR; } if ( pHandle->_Super.SWerror == 1u ) { hAux = MC_DURATION; pHandle->_Super.SWerror = 0u; } return hAux; } /* * @brief Computes and stores into @p pHandle latest converted motor phase currents * during RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ void R3_1_RLGetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; int32_t wAux; /* disable ADC trigger source */ LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); wAux = (int32_t)( pHandle->PhaseBOffset ) - (int32_t)ADCx->JDR2; /* Check saturation */ if ( wAux > -INT16_MAX ) { if ( wAux < INT16_MAX ) { } else { wAux = INT16_MAX; } } else { wAux = -INT16_MAX; } pStator_Currents->a = (int16_t)wAux; pStator_Currents->b = (int16_t)wAux; } /* * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors * of driving section. It has to be called at each motor start-up when * using high voltage drivers. * This function is specific for RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. * @param ticks: Duty cycle of the boot capacitors charge, specific to motor. */ static void R3_1_RLTurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ) { PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /*Turn on the phase A low side switch */ LL_TIM_OC_SetCompareCH1 ( TIMx, 0u ); /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Wait until next update */ while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } return; } /* * @brief Enables PWM generation on the proper Timer peripheral. * * This function is specific for RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. */ static void R3_1_RLSwitchOnPWM( PWMC_Handle_t * pHdl ) { PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); LL_TIM_OC_SetCompareCH1( TIMx, 1u ); LL_TIM_OC_SetCompareCH4( TIMx, ( pHandle->Half_PWMPeriod ) - 5u ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE ; LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { if ( ( TIMx->CCER & TIMxCCER_MASK_CH123 ) != 0u ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* enable TIMx update interrupt*/ LL_TIM_EnableIT_UPDATE( TIMx ); return; } /* * @brief Turns on low sides switches and start ADC triggering. * * This function is specific for MP phase. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_1_RLTurnOnLowSidesAndStart( PWMC_Handle_t * pHdl ) { PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); LL_TIM_OC_SetCompareCH1 ( TIMx, 0x0u ); LL_TIM_OC_SetCompareCH2 ( TIMx, 0x0u ); LL_TIM_OC_SetCompareCH3 ( TIMx, 0x0u ); LL_TIM_OC_SetCompareCH4( TIMx, ( pHandle->Half_PWMPeriod - 5u)); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE ; LL_TIM_EnableAllOutputs ( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } pHdl->Sector = SECTOR_4; LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH4); LL_TIM_EnableIT_UPDATE( TIMx ); return; } /** * @} */ /** * @} */ /** * @} */ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
52,048
C
29.617059
143
0.607036
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/H5xx/Src/r3_2_h5xx_pwm_curr_fdbk.c
/** ****************************************************************************** * @file r3_2_h5xx_pwm_curr_fdbk.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement the features * of the three shunts current sensing topology. * * It is specifically designed for STM32H5XX microcontrollers and * implements the successive sampling of current using two ADCs. * + MCU peripheral and handle initialization function * + three shunt current sensing * + space vector modulation function * + ADC sampling function * ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup R3_2_H5XX_pwm_curr_fdbk */ /* Includes ------------------------------------------------------------------*/ #include "r3_2_h5xx_pwm_curr_fdbk.h" #include "pwm_common.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup R3_2_pwm_curr_fdbk * @{ */ /* Private defines -----------------------------------------------------------*/ #define TIMxCCER_MASK_CH123 ((uint16_t) (LL_TIM_CHANNEL_CH1|LL_TIM_CHANNEL_CH1N|\ LL_TIM_CHANNEL_CH2|LL_TIM_CHANNEL_CH2N|\ LL_TIM_CHANNEL_CH3|LL_TIM_CHANNEL_CH3N)) /* Private function prototypes -----------------------------------------------*/ static void R3_2_TIMxInit(TIM_TypeDef *TIMx, PWMC_Handle_t *pHdl); static void R3_2_ADCxInit(ADC_TypeDef *ADCx); __STATIC_INLINE uint16_t R3_2_WriteTIMRegisters( PWMC_Handle_t * pHdl, uint16_t hCCR4Reg ); static void R3_2_HFCurrentsPolarizationAB( PWMC_Handle_t * pHdl,ab_t * Iab ); static void R3_2_HFCurrentsPolarizationC( PWMC_Handle_t * pHdl, ab_t * Iab ); uint16_t R3_2_SetADCSampPointPolarization( PWMC_Handle_t * pHdl) ; static void R3_2_RLGetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * Iab ); static void R3_2_RLTurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ); static void R3_2_RLSwitchOnPWM( PWMC_Handle_t * pHdl ); /* * @brief Initializes TIMx, ADC, GPIO, DMA1 and NVIC for current reading * in three shunt topology using STM32F30X and two ADCs. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void R3_2_Init( PWMC_R3_2_Handle_t * pHandle ) { TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx_1 = pHandle->pParams_str->ADCDataReg1[0]; ADC_TypeDef * ADCx_2 = pHandle->pParams_str->ADCDataReg2[0]; /*Checks that _Super is the first member of the structure PWMC_R3_2_Handle_t */ if ((uint32_t)pHandle == (uint32_t)&pHandle->_Super) //cstat !MISRAC2012-Rule-11.4 { /* Disables IT and flags in case of LL driver usage * workaround for unwanted interrupt enabling done by LL driver */ LL_ADC_DisableIT_EOC(ADCx_1); LL_ADC_ClearFlag_EOC(ADCx_1); LL_ADC_DisableIT_JEOC(ADCx_1); LL_ADC_ClearFlag_JEOC(ADCx_1); LL_ADC_DisableIT_EOC(ADCx_2); LL_ADC_ClearFlag_EOC(ADCx_2); LL_ADC_DisableIT_JEOC(ADCx_2); LL_ADC_ClearFlag_JEOC(ADCx_2); if (TIM1 == TIMx) { /* TIM1 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph(LL_DBGMCU_APB2_GRP1_TIM1_STOP); } else { /* TIM8 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph(LL_DBGMCU_APB2_GRP1_TIM8_STOP); } if (0U == LL_ADC_IsEnabled(ADCx_1)) { R3_2_ADCxInit(ADCx_1); /* Only the Interrupt of the first ADC is enabled. * As Both ADCs are fired by HW at the same moment * It is safe to consider that both conversion are ready at the same time*/ LL_ADC_ClearFlag_JEOS(ADCx_1); LL_ADC_EnableIT_JEOS(ADCx_1); } else { /* Nothing to do ADCx_1 already configured */ } if (0U == LL_ADC_IsEnabled(ADCx_2)) { R3_2_ADCxInit(ADCx_2); } else { /* Nothing to do ADCx_2 already configured */ } R3_2_TIMxInit(TIMx, &pHandle->_Super); } else { /* Nothing to do */ } } /* * @brief Initializes @p ADCx peripheral for current sensing. * */ static void R3_2_ADCxInit(ADC_TypeDef *ADCx) { /* - Exit from deep-power-down mode */ LL_ADC_DisableDeepPowerDown(ADCx); if (0U == LL_ADC_IsInternalRegulatorEnabled(ADCx)) { /* Enable ADC internal voltage regulator */ LL_ADC_EnableInternalRegulator(ADCx); /* Wait for Regulator Startup time, once for both */ /* Note: Variable divided by 2 to compensate partially */ /* CPU processing cycles, scaling in us split to not */ /* exceed 32 bits register capacity and handle low frequency. */ volatile uint32_t wait_loop_index = ((LL_ADC_DELAY_INTERNAL_REGUL_STAB_US / 10UL) * (SystemCoreClock / (100000UL * 2UL))); while (wait_loop_index != 0UL) { wait_loop_index--; } } else { /* Nothing to do */ } LL_ADC_StartCalibration(ADCx, LL_ADC_SINGLE_ENDED); while (1U == LL_ADC_IsCalibrationOnGoing(ADCx)) { /* Nothing to do */ } /* ADC Enable (must be done after calibration) */ /* ADC5-140924: Enabling the ADC by setting ADEN bit soon after polling ADCAL=0 * following a calibration phase, could have no effect on ADC * within certain AHB/ADC clock ratio. */ while (0U == LL_ADC_IsActiveFlag_ADRDY(ADCx)) { LL_ADC_Enable(ADCx); } /* Clear JSQR from CubeMX setting to avoid not wanting conversion*/ LL_ADC_INJ_StartConversion(ADCx); LL_ADC_INJ_StopConversion(ADCx); /* TODO: check if not already done by MX */ LL_ADC_INJ_SetQueueMode(ADCx, LL_ADC_INJ_QUEUE_2CONTEXTS_END_EMPTY); } /* * @brief Initializes @p TIMx peripheral with @p pHdl handler for PWM generation. * */ static void R3_2_TIMxInit(TIM_TypeDef *TIMx, PWMC_Handle_t *pHdl) { PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 volatile uint32_t Brk2Timeout = 1000; /* disable main TIM counter to ensure * a synchronous start by TIM2 trigger */ LL_TIM_DisableCounter(TIMx); LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); /* Enables the TIMx Preload on CC1 Register */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH1); /* Enables the TIMx Preload on CC2 Register */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH2); /* Enables the TIMx Preload on CC3 Register */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH3); /* Enables the TIMx Preload on CC4 Register */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH4); /* Prepare timer for synchronization */ LL_TIM_GenerateEvent_UPDATE(TIMx); if (2U == pHandle->pParams_str->bFreqRatio) { if (HIGHER_FREQ == pHandle->pParams_str->bIsHigherFreqTim) { if (3U == pHandle->pParams_str->RepetitionCounter) { /* Set TIMx repetition counter to 1 */ LL_TIM_SetRepetitionCounter(TIMx, 1); LL_TIM_GenerateEvent_UPDATE(TIMx); /* Repetition counter will be set to 3 at next Update */ LL_TIM_SetRepetitionCounter(TIMx, 3); } else { /* Nothing to do */ } } else { /* Nothing to do */ } LL_TIM_SetCounter(TIMx, (uint32_t)(pHandle->Half_PWMPeriod) - 1U); } else /* bFreqRatio equal to 1 or 3 */ { if (M1 == pHandle->_Super.Motor) { if (1U == pHandle->pParams_str->RepetitionCounter) { LL_TIM_SetCounter(TIMx, (uint32_t)(pHandle->Half_PWMPeriod) - 1U); } else if (3U == pHandle->pParams_str->RepetitionCounter) { /* Set TIMx repetition counter to 1 */ LL_TIM_SetRepetitionCounter(TIMx, 1); LL_TIM_GenerateEvent_UPDATE(TIMx); /* Repetition counter will be set to 3 at next Update */ LL_TIM_SetRepetitionCounter(TIMx, 3); } else { /* Nothing to do */ } } else { /* Nothing to do */ } } LL_TIM_ClearFlag_BRK(TIMx); uint32_t result; result = LL_TIM_IsActiveFlag_BRK2(TIMx); while ((Brk2Timeout != 0u) && (1U == result)) { LL_TIM_ClearFlag_BRK2(TIMx); Brk2Timeout--; result = LL_TIM_IsActiveFlag_BRK2(TIMx); } LL_TIM_EnableIT_BRK(TIMx); /* Enable PWM channel */ LL_TIM_CC_EnableChannel(TIMx, TIMxCCER_MASK_CH123); } /* * @brief Stores in @p pHdl handler the calibrated @p offsets. * */ __weak void R3_2_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 pHandle->PhaseAOffset = offsets->phaseAOffset; pHandle->PhaseBOffset = offsets->phaseBOffset; pHandle->PhaseCOffset = offsets->phaseCOffset; pHdl->offsetCalibStatus = true; } /* * @brief Reads the calibrated @p offsets stored in @p pHdl handler. * */ __weak void R3_2_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 offsets->phaseAOffset = pHandle->PhaseAOffset; offsets->phaseBOffset = pHandle->PhaseBOffset; offsets->phaseCOffset = pHandle->PhaseCOffset; } /* * @brief Stores into the @p pHdl handler the voltage present on Ia and * Ib current feedback analog channels when no current is flowing into the * motor. * */ __weak void R3_2_CurrentReadingPolarization(PWMC_Handle_t *pHdl) { PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef *ADCx_1 = pHandle->pParams_str->ADCDataReg1[0]; ADC_TypeDef *ADCx_2 = pHandle->pParams_str->ADCDataReg2[0]; volatile PWMC_GetPhaseCurr_Cb_t GetPhaseCurrCbSave; volatile PWMC_SetSampPointSectX_Cb_t SetSampPointSectXCbSave; if (true == pHandle->_Super.offsetCalibStatus) { LL_ADC_INJ_StartConversion(ADCx_1); LL_ADC_INJ_StartConversion(ADCx_2); pHandle->ADC_ExternalPolarityInjected = (uint16_t)LL_ADC_INJ_TRIG_EXT_RISING; } else { /* Save callback routines */ GetPhaseCurrCbSave = pHandle->_Super.pFctGetPhaseCurrents; SetSampPointSectXCbSave = pHandle->_Super.pFctSetADCSampPointSectX; pHandle->PhaseAOffset = 0U; pHandle->PhaseBOffset = 0U; pHandle->PhaseCOffset = 0U; pHandle->PolarizationCounter = 0U; /* It forces inactive level on TIMx CHy and CHyN */ LL_TIM_CC_DisableChannel(TIMx, TIMxCCER_MASK_CH123); /* Offset calibration for all phases */ /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R3_2_HFCurrentsPolarizationAB; pHandle->_Super.pFctSetADCSampPointSectX = &R3_2_SetADCSampPointPolarization; pHandle->ADC_ExternalPolarityInjected = (uint16_t)LL_ADC_INJ_TRIG_EXT_RISING; /* We want to polarize calibration Phase A and Phase B, so we select SECTOR_5 */ pHandle->PolarizationSector=SECTOR_5; /* Required to force first polarization conversion on SECTOR_5*/ pHandle->_Super.Sector = SECTOR_5; R3_2_SwitchOnPWM(&pHandle->_Super); /* IF CH4 is enabled, it means that JSQR is now configured to sample polarization current*/ /*while ( LL_TIM_CC_IsEnabledChannel(TIMx, LL_TIM_CHANNEL_CH4) == 0u ) */ while (((TIMx->CR2) & TIM_CR2_MMS_Msk) != LL_TIM_TRGO_OC4REF) { /* Nothing to do */ } /* It is the right time to start the ADC without unwanted conversion */ /* Start ADC to wait for external trigger. This is series dependant*/ LL_ADC_INJ_StartConversion(ADCx_1); LL_ADC_INJ_StartConversion(ADCx_2); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd(TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter); R3_2_SwitchOffPWM(&pHandle->_Super); /* Offset calibration for C phase */ pHandle->PolarizationCounter = 0U; /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R3_2_HFCurrentsPolarizationC; /* We want to polarize Phase C, so we select SECTOR_1 */ pHandle->PolarizationSector=SECTOR_1; /* Required to force first polarization conversion on SECTOR_1*/ pHandle->_Super.Sector = SECTOR_1; R3_2_SwitchOnPWM(&pHandle->_Super); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd(TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter); R3_2_SwitchOffPWM(&pHandle->_Super); pHandle->PhaseAOffset /= NB_CONVERSIONS; pHandle->PhaseBOffset /= NB_CONVERSIONS; pHandle->PhaseCOffset /= NB_CONVERSIONS; if (0U == pHandle->_Super.SWerror) { pHandle->_Super.offsetCalibStatus = true; } else { /* nothing to do */ } /* Change back function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = GetPhaseCurrCbSave; pHandle->_Super.pFctSetADCSampPointSectX = SetSampPointSectXCbSave; } /* It over write TIMx CCRy wrongly written by FOC during calibration so as to force 50% duty cycle on the three inverer legs */ /* Disable TIMx preload */ LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH1); LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH2); LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH3); LL_TIM_OC_SetCompareCH1 (TIMx, pHandle->Half_PWMPeriod); LL_TIM_OC_SetCompareCH2 (TIMx, pHandle->Half_PWMPeriod); LL_TIM_OC_SetCompareCH3 (TIMx, pHandle->Half_PWMPeriod); /* Enable TIMx preload */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH1); LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH2); LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH3); /* It re-enable drive of TIMx CHy and CHyN by TIMx CHyRef*/ LL_TIM_CC_EnableChannel(TIMx, TIMxCCER_MASK_CH123); /* At the end of calibration, all phases are at 50% we will sample A&B */ pHandle->_Super.Sector = SECTOR_5; pHandle->_Super.BrakeActionLock = false; } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /* * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p pStator_Currents ab_t format. * */ __weak void R3_2_GetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t* Iab ) { if (MC_NULL == Iab) { /* nothing to do */ } else { int32_t Aux; uint32_t ADCDataReg1; uint32_t ADCDataReg2; PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; uint8_t Sector; Sector = (uint8_t)pHandle->_Super.Sector; ADCDataReg1 = pHandle->pParams_str->ADCDataReg1[Sector]->JDR1; ADCDataReg2 = pHandle->pParams_str->ADCDataReg2[Sector]->JDR1; /* disable ADC trigger source */ /* LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4) */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); switch (Sector) { case SECTOR_4: case SECTOR_5: { /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = (int32_t)(pHandle->PhaseAOffset) - (int32_t)(ADCDataReg1); /* Saturation of Ia */ if (Aux < -INT16_MAX) { Iab->a = -INT16_MAX; } else if (Aux > INT16_MAX) { Iab->a = INT16_MAX; } else { Iab->a = (int16_t)Aux; } /* Ib = PhaseBOffset - ADC converted value) */ Aux = (int32_t)(pHandle->PhaseBOffset) - (int32_t)(ADCDataReg2); /* Saturation of Ib */ if (Aux < -INT16_MAX) { Iab->b = -INT16_MAX; } else if (Aux > INT16_MAX) { Iab->b = INT16_MAX; } else { Iab->b = (int16_t)Aux; } break; } case SECTOR_6: case SECTOR_1: { /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ Aux = (int32_t)(pHandle->PhaseBOffset) - (int32_t)(ADCDataReg1); /* Saturation of Ib */ if (Aux < -INT16_MAX) { Iab->b = -INT16_MAX; } else if (Aux > INT16_MAX) { Iab->b = INT16_MAX; } else { Iab->b = (int16_t)Aux; } /* Ia = -Ic -Ib */ Aux = (int32_t)(ADCDataReg2) - (int32_t)(pHandle->PhaseCOffset); /* -Ic */ Aux -= (int32_t)Iab->b; /* Ia */ /* Saturation of Ia */ if (Aux > INT16_MAX) { Iab->a = INT16_MAX; } else if (Aux < -INT16_MAX) { Iab->a = -INT16_MAX; } else { Iab->a = (int16_t)Aux; } break; } case SECTOR_2: case SECTOR_3: { /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = (int32_t)(pHandle->PhaseAOffset) - (int32_t)(ADCDataReg1); /* Saturation of Ia */ if (Aux < -INT16_MAX) { Iab->a = -INT16_MAX; } else if (Aux > INT16_MAX) { Iab->a = INT16_MAX; } else { Iab->a = (int16_t)Aux; } /* Ib = -Ic -Ia */ Aux = (int32_t)(ADCDataReg2) - (int32_t)(pHandle->PhaseCOffset); /* -Ic */ Aux -= (int32_t)Iab->a; /* Ib */ /* Saturation of Ib */ if (Aux > INT16_MAX) { Iab->b = INT16_MAX; } else if (Aux < -INT16_MAX) { Iab->b = -INT16_MAX; } else { Iab->b = (int16_t)Aux; } break; } default: break; } pHandle->_Super.Ia = Iab->a; pHandle->_Super.Ib = Iab->b; pHandle->_Super.Ic = -Iab->a - Iab->b; } } /* * @brief Implementation of PWMC_GetPhaseCurrents to be performed during polarization. * * It sums up injected conversion data into PhaseAOffset and * PhaseBOffset to compute the offset introduced in the current feedback * network. It is required to properly configure ADC inputs before in order to enable * the offset computation. * * @param pHdl: Handler of the current instance of the PWM component. * @param Iab: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ static void R3_2_HFCurrentsPolarizationAB( PWMC_Handle_t * pHdl, ab_t * Iab ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint32_t ADCDataReg1 = pHandle->pParams_str->ADCDataReg1[pHandle->PolarizationSector]->JDR1; uint32_t ADCDataReg2 = pHandle->pParams_str->ADCDataReg2[pHandle->PolarizationSector]->JDR1; /* disable ADC trigger source */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); if ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { pHandle-> PhaseAOffset += ADCDataReg1; pHandle-> PhaseBOffset += ADCDataReg2; pHandle->PolarizationCounter++; } /* during offset calibration no current is flowing in the phases */ Iab->a = 0; Iab->b = 0; } /* * @brief Implementation of PWMC_GetPhaseCurrents to be performed during polarization. * * It sums up injected conversion data into PhaseCOffset to compute the * offset introduced in the current feedback * network. It is required to proper configure ADC inputs before enabling * the offset computation. * * @param pHdl: Handler of the current instance of the PWM component. * @param Iab: Pointer to the structure that will receive motor current * of phase A and B in ElectricalValue format. */ static void R3_2_HFCurrentsPolarizationC( PWMC_Handle_t * pHdl, ab_t * Iab ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint32_t ADCDataReg2 = pHandle->pParams_str->ADCDataReg2[pHandle->PolarizationSector]->JDR1; /* disable ADC trigger source */ //LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); if ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { /* Phase C is read from SECTOR_1, second value */ pHandle-> PhaseCOffset += ADCDataReg2; pHandle->PolarizationCounter++; } /* during offset calibration no current is flowing in the phases */ Iab->a = 0; Iab->b = 0; } /* * @brief Configures the ADC for the current sampling during calibration. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ uint16_t R3_2_SetADCSampPointPolarization( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ pHandle->_Super.Sector = pHandle->PolarizationSector; return R3_2_WriteTIMRegisters( &pHandle->_Super, ( pHandle->Half_PWMPeriod - (uint16_t) 1 ) ); } /* * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p Iab ab_t format. Specific to overmodulation. * */ __weak void R3_2_GetPhaseCurrents_OVM( PWMC_Handle_t * pHdl, ab_t * Iab ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint8_t Sector; int32_t Aux; uint32_t ADCDataReg1; uint32_t ADCDataReg2; /* disable ADC trigger source */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); Sector = ( uint8_t )pHandle->_Super.Sector; ADCDataReg1 = pHandle->pParams_str->ADCDataReg1[Sector]->JDR1; ADCDataReg2 = pHandle->pParams_str->ADCDataReg2[Sector]->JDR1; switch ( Sector ) { case SECTOR_4: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { // Ib not available, use estimated Ib Aux = ( int32_t )( pHandle->_Super.IbEst ); } else { /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg2 ); } /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_5: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { // Ia not available, use estimated Ia Aux = ( int32_t )( pHandle->_Super.IaEst ); } else { Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg2 ); /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_6: /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IcEst ; /* -Ic */ Aux -= ( int32_t )Iab->b; } else { /* Ia = -Ic -Ib */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->b; /* Ia */ } /* Saturation of Ia */ if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else { Iab->a = ( int16_t )Aux; } break; case SECTOR_1: /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IbEst; } else { Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } /* Ia = -Ic -Ib */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->b; /* Ia */ /* Saturation of Ia */ if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else { Iab->a = ( int16_t )Aux; } break; case SECTOR_2: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IaEst; } else { Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } /* Ib = -Ic -Ia */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ /* Saturation of Ib */ if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_3: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { /* Ib = -Ic -Ia */ Aux = ( int32_t ) pHandle->_Super.IcEst; /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ } else { /* Ib = -Ic -Ia */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ } /* Saturation of Ib */ if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; default: break; } pHandle->_Super.Ia = Iab->a; pHandle->_Super.Ib = Iab->b; pHandle->_Super.Ic = -Iab->a - Iab->b; } /* * @brief Implementation of PWMC_GetPhaseCurrents to be performed during calibration. * * It sums up injected conversion data into PhaseCOffset to compute the offset * introduced in the current feedback network. It is required to properly configure * ADC inputs before in order to enable offset computation. * * @param pHdl: Pointer on the target component instance. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ __weak void R3_2_HFCurrentsCalibrationC( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { PWMC_R3_2_Handle_t * pHandle = (PWMC_R3_2_Handle_t *) pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* disable ADC trigger source */ LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); if ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { pHandle->PhaseCOffset += pHandle->pParams_str->ADCDataReg2[pHandle->CalibSector]->JDR1; pHandle->PolarizationCounter++; } /* during offset calibration no current is flowing in the phases */ pStator_Currents->a = 0; pStator_Currents->b = 0; } /* * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors of driving section. It has to be * called each motor start-up when using high voltage drivers. * * @param pHdl: Handler of the current instance of the PWM component * @param ticks: Timer ticks value to be applied * Min value: 0 (low sides ON) * Max value: PWM_PERIOD_CYCLES/2 (low sides OFF) */ __weak void R3_2_TurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ) { PWMC_R3_2_Handle_t * pHandle = (PWMC_R3_2_Handle_t *) pHdl; TIM_TypeDef* TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = true; /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE(TIMx); /*Turn on the three low side switches */ LL_TIM_OC_SetCompareCH1(TIMx,ticks); LL_TIM_OC_SetCompareCH2(TIMx,ticks); LL_TIM_OC_SetCompareCH3(TIMx,ticks); /* Wait until next update */ while (LL_TIM_IsActiveFlag_UPDATE(TIMx) == RESET) {} LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs(TIMx); if ( (pHandle->_Super.LowSideOutputs) == ES_GPIO ) { LL_GPIO_SetOutputPin (pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_SetOutputPin (pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_SetOutputPin (pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } return; } /* * @brief Enables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_2_SwitchOnPWM( PWMC_Handle_t * pHdl ) { PWMC_R3_2_Handle_t * pHandle = (PWMC_R3_2_Handle_t *) pHdl; TIM_TypeDef* TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = false; /* Set all duty to 50% */ LL_TIM_OC_SetCompareCH1(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH2(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH3(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH4(TIMx, (uint32_t)(pHandle->Half_PWMPeriod - 5u)); /* wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE(TIMx); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE(TIMx); /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE; LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { if ( LL_TIM_CC_IsEnabledChannel(TIMx,TIMxCCER_MASK_CH123) != 0u ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Enable Update IRQ */ LL_TIM_EnableIT_UPDATE(TIMx); return; } /* * @brief Disables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_2_SwitchOffPWM( PWMC_Handle_t * pHdl ) { PWMC_R3_2_Handle_t * pHandle = (PWMC_R3_2_Handle_t *) pHdl; TIM_TypeDef* TIMx = pHandle->pParams_str->TIMx; /* Disable UPDATE ISR */ LL_TIM_DisableIT_UPDATE( TIMx ); pHandle->_Super.TurnOnLowSidesAction = false; /* Main PWM Output Disable */ LL_TIM_DisableAllOutputs( TIMx ); if ( (pHandle->_Super.LowSideOutputs) == ES_GPIO ) { LL_GPIO_ResetOutputPin (pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_ResetOutputPin (pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_ResetOutputPin (pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } /* wait for a new PWM period to flush last HF task */ LL_TIM_ClearFlag_UPDATE(TIMx); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} LL_TIM_ClearFlag_UPDATE(TIMx); return; } /* * @brief Writes into peripheral registers the new duty cycles and sampling point. * * @param pHdl: Handler of the current instance of the PWM component. * @param hCCR4Reg: New capture/compare register value, written in timer clock counts. * @retval Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ __STATIC_INLINE uint16_t R3_2_WriteTIMRegisters( PWMC_Handle_t * pHdl, uint16_t hCCR4Reg ) { PWMC_R3_2_Handle_t * pHandle = (PWMC_R3_2_Handle_t *) pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint16_t hAux; LL_TIM_OC_SetCompareCH1( TIMx, pHandle->_Super.CntPhA ); LL_TIM_OC_SetCompareCH2( TIMx, pHandle->_Super.CntPhB ); LL_TIM_OC_SetCompareCH3( TIMx, pHandle->_Super.CntPhC ); LL_TIM_OC_SetCompareCH4( TIMx, hCCR4Reg ); /* Limit for update event */ /* Check the if TIMx CH4 is enabled. If it is set, an update event has occurred and thus the FOC rate is too high */ if (LL_TIM_CC_IsEnabledChannel(TIMx, LL_TIM_CHANNEL_CH4)) { hAux = MC_DURATION; } else { hAux = MC_NO_ERROR; } if ( pHandle->_Super.SWerror == 1u ) { hAux = MC_DURATION; pHandle->_Super.SWerror = 0u; } return hAux; } /* * @brief Configures the ADC for the current sampling during calibration. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ __weak uint16_t R3_2_SetADCSampPointCalibration( PWMC_Handle_t * pHdl) { PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; /* Set rising edge trigger (default) */ pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_RISING; pHandle->_Super.Sector = pHandle->CalibSector; return R3_2_WriteTIMRegisters( &pHandle->_Super, (uint32_t)(pHandle->Half_PWMPeriod - 1u) ); } /* * @brief Configures the ADC for the current sampling related to sector X (X = [1..6] ). * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ __weak uint16_t R3_2_SetADCSampPointSectX( PWMC_Handle_t * pHdl ) { PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; uint16_t hCntSmp; uint16_t hDeltaDuty; register uint16_t lowDuty = pHdl->lowDuty; register uint16_t midDuty = pHdl->midDuty; /* Check if sampling AB in the middle of PWM is possible */ if ( ( uint16_t )( pHandle->Half_PWMPeriod - lowDuty ) > pHandle->pParams_str->hTafter ) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled wIch corresponds * to sector 4 */ pHandle->_Super.Sector = SECTOR_4; /* set sampling point trigger in the middle of PWM period */ hCntSmp = ( uint32_t )( pHandle->Half_PWMPeriod ) - 1u; } else { /* ADC Injected sequence configuration. The stator phase with minimum value of complementary duty cycle is set as first. In every sector there is always one phase with maximum complementary duty, one with minimum complementary duty and one with variable complementary duty. In this case, phases with variable complementary duty and with maximum duty are converted and the first will be always the phase with variable complementary duty cycle */ /* Crossing Point Searching */ hDeltaDuty = ( uint16_t )( lowDuty - midDuty ); /* Definition of crossing point */ if ( hDeltaDuty > ( uint16_t )( pHandle->Half_PWMPeriod - lowDuty ) * 2u ) { /* hTbefore = 2*Ts + Tc, where Ts = Sampling time of ADC, Tc = Conversion Time of ADC */ hCntSmp = lowDuty - pHandle->pParams_str->hTbefore; } else { /* hTafter = DT + max(Trise, Tnoise) */ hCntSmp = lowDuty + pHandle->pParams_str->hTafter; if ( hCntSmp >= pHandle->Half_PWMPeriod ) { /* It must be changed the trigger direction from positive to negative to sample after middle of PWM*/ pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_FALLING; hCntSmp = ( 2u * pHandle->Half_PWMPeriod ) - hCntSmp - 1u; } } } return R3_2_WriteTIMRegisters( &pHandle->_Super, hCntSmp ); } /* * @brief Configures the ADC for the current sampling related to sector X (X = [1..6] ) in case of overmodulation. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ uint16_t R3_2_SetADCSampPointSectX_OVM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ uint16_t SamplingPoint; uint16_t DeltaDuty; pHandle->_Super.useEstCurrent = false; DeltaDuty = ( uint16_t )( pHdl->lowDuty - pHdl->midDuty ); /* case 1 (cf user manual) */ if (( uint16_t )( pHandle->Half_PWMPeriod - pHdl->lowDuty ) > pHandle->pParams_str->hTafter) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled which corresponds * to sector 4 or 5 */ pHandle->_Super.Sector = SECTOR_5; /* set sampling point trigger in the middle of PWM period */ SamplingPoint = pHandle->Half_PWMPeriod - (uint16_t) 1; } else /* case 2 (cf user manual) */ { if (DeltaDuty >= pHandle->pParams_str->Tcase2) { SamplingPoint = pHdl->lowDuty - pHandle->pParams_str->hTbefore; } else { /* case 3 (cf user manual) */ if ((pHandle->Half_PWMPeriod - pHdl->lowDuty) > pHandle->pParams_str->Tcase3) { /* ADC trigger edge must be changed from positive to negative */ pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_FALLING; SamplingPoint = pHdl->lowDuty + pHandle->pParams_str->Tsampling; } else { SamplingPoint = pHandle->Half_PWMPeriod-1; pHandle->_Super.useEstCurrent = true; } } } return R3_2_WriteTIMRegisters( &pHandle->_Super, SamplingPoint ); } /* * @brief Contains the TIMx Update event interrupt. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void * R3_2_TIMx_UP_IRQHandler( PWMC_R3_2_Handle_t * pHandle) { void *tempPointer; if (MC_NULL == pHandle) { tempPointer = MC_NULL; } else { TIM_TypeDef* TIMx = pHandle->pParams_str->TIMx; pHandle->pParams_str->ADCDataReg1[pHandle->_Super.Sector]->JSQR = pHandle->pParams_str->ADCConfig1[pHandle->_Super.Sector] | (uint32_t) pHandle->ADC_ExternalPolarityInjected; pHandle->pParams_str->ADCDataReg2[pHandle->_Super.Sector]->JSQR = pHandle->pParams_str->ADCConfig2[pHandle->_Super.Sector] | (uint32_t) pHandle->ADC_ExternalPolarityInjected; /* enable ADC trigger source */ /* LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH4) */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_OC4REF); pHandle->ADC_ExternalPolarityInjected = (uint16_t)LL_ADC_INJ_TRIG_EXT_RISING; tempPointer = &(pHandle->_Super.Motor); } return (tempPointer); } /* * @brief Sets the PWM mode for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_2_RLDetectionModeEnable( PWMC_Handle_t * pHdl ) { PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; if ( pHandle->_Super.RLDetectionMode == false ) { /* Channel1 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH1, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH1N ); LL_TIM_OC_SetCompareCH1( TIMx, 0u ); /* Channel2 configuration */ if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_ACTIVE ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_INACTIVE ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else { } /* Channel3 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH3, LL_TIM_OCMODE_PWM2 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3N ); } pHandle->_Super.pFctGetPhaseCurrents = &R3_2_RLGetPhaseCurrents; pHandle->_Super.pFctTurnOnLowSides = &R3_2_RLTurnOnLowSides; pHandle->_Super.pFctSwitchOnPwm = &R3_2_RLSwitchOnPWM; pHandle->_Super.pFctSwitchOffPwm = &R3_2_SwitchOffPWM; pHandle->_Super.RLDetectionMode = true; } /* * @brief Disables the PWM mode for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_2_RLDetectionModeDisable( PWMC_Handle_t * pHdl ) { PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; if ( pHandle->_Super.RLDetectionMode == true ) { /* Channel1 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH1, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1 ); if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH1N ); } else { } LL_TIM_OC_SetCompareCH1( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) >> 1 ); /* Channel2 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2 ); if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else { } LL_TIM_OC_SetCompareCH2( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) >> 1 ); /* Channel3 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH3, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH3 ); if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH3N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3N ); } else { } LL_TIM_OC_SetCompareCH3( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) >> 1 ); pHandle->_Super.pFctGetPhaseCurrents = &R3_2_GetPhaseCurrents; pHandle->_Super.pFctTurnOnLowSides = &R3_2_TurnOnLowSides; pHandle->_Super.pFctSwitchOnPwm = &R3_2_SwitchOnPWM; pHandle->_Super.pFctSwitchOffPwm = &R3_2_SwitchOffPWM; pHandle->_Super.RLDetectionMode = false; } } /* * @brief Sets the PWM dutycycle for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. * @param hDuty: Duty cycle to apply, written in uint16_t. * @retval Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ uint16_t R3_2_RLDetectionModeSetDuty( PWMC_Handle_t * pHdl, uint16_t hDuty ) { PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint32_t val; uint16_t hAux; val = ( ( uint32_t )( pHandle->Half_PWMPeriod ) * ( uint32_t )( hDuty ) ) >> 16; pHandle->_Super.CntPhA = ( uint16_t )( val ); /* TIM1 Channel 1 Duty Cycle configuration. * In RL Detection mode only the Up-side device of Phase A are controlled*/ LL_TIM_OC_SetCompareCH1(TIMx, ( uint32_t )pHandle->_Super.CntPhA); /* set the sector that correspond to Phase A and B sampling */ pHdl->Sector = SECTOR_4; /* Limit for update event */ /* Check the status flag. If an update event has occurred before to set new values of regs the FOC rate is too high */ if (LL_TIM_CC_IsEnabledChannel(TIMx, LL_TIM_CHANNEL_CH4)) { hAux = MC_DURATION; } else { hAux = MC_NO_ERROR; } if ( pHandle->_Super.SWerror == 1u ) { hAux = MC_DURATION; pHandle->_Super.SWerror = 0u; } return hAux; } /* * @brief Computes and stores into @p pHandle latest converted motor phase currents * during RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ void R3_2_RLGetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; int32_t wAux; /* disable ADC trigger source */ LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); wAux = (int32_t)( pHandle->PhaseBOffset ) - (int32_t)pHandle->pParams_str->ADCDataReg2[pHandle->_Super.Sector]->JDR1; /* Check saturation */ if ( wAux > -INT16_MAX ) { if ( wAux < INT16_MAX ) { } else { wAux = INT16_MAX; } } else { wAux = -INT16_MAX; } pStator_Currents->a = (int16_t)wAux; pStator_Currents->b = (int16_t)wAux; } /* * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors * of driving section. It has to be called at each motor start-up when * using high voltage drivers. * This function is specific for RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. * @param ticks: Duty cycle of the boot capacitors charge, specific to motor. */ static void R3_2_RLTurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ) { PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /*Turn on the phase A low side switch */ LL_TIM_OC_SetCompareCH1 ( TIMx, 0u ); /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Wait until next update */ while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } return; } /* * @brief Enables PWM generation on the proper Timer peripheral. * * This function is specific for RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. */ static void R3_2_RLSwitchOnPWM( PWMC_Handle_t * pHdl ) { PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); LL_TIM_OC_SetCompareCH1( TIMx, 1u ); LL_TIM_OC_SetCompareCH4( TIMx, ( pHandle->Half_PWMPeriod ) - 5u ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE ; LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { if ( ( TIMx->CCER & TIMxCCER_MASK_CH123 ) != 0u ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* enable TIMx update interrupt*/ LL_TIM_EnableIT_UPDATE( TIMx ); return; } /* * @brief Turns on low sides switches and start ADC triggering. * * This function is specific for MP phase. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_2_RLTurnOnLowSidesAndStart( PWMC_Handle_t * pHdl ) { PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); LL_TIM_OC_SetCompareCH1 ( TIMx, 0x0u ); LL_TIM_OC_SetCompareCH2 ( TIMx, 0x0u ); LL_TIM_OC_SetCompareCH3 ( TIMx, 0x0u ); LL_TIM_OC_SetCompareCH4( TIMx, ( pHandle->Half_PWMPeriod - 5u)); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE ; LL_TIM_EnableAllOutputs ( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } pHdl->Sector = SECTOR_4; LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH4); LL_TIM_EnableIT_UPDATE( TIMx ); return; } /* * @brief Sets ADC sampling points. * * This function is specific for MP phase. Specific to F4XX, F7XX, L4XX and H5XX. * * @param pHdl: Handler of the current instance of the PWM component. */ void RLSetADCSampPoint( PWMC_Handle_t * pHdl ) { /* dummy sector setting to get correct Ia value */ pHdl->Sector = SECTOR_4; return; } /** * @} */ /** * @} */ /** * @} */ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
55,093
C
30.073886
178
0.612673
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/H5xx/Inc/r3_2_h5xx_pwm_curr_fdbk.h
/** ****************************************************************************** * @file r3_2_h5xx_pwm_curr_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * R3_2_H5XX_pwm_curr_fdbk component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup R3_2_H5XX_pwm_curr_fdbk */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __R3_2_PWM_CURR_FDBK_H #define __R3_2_PWM_CURR_FDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "pwm_curr_fdbk.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup R3_2_pwm_curr_fdbk * @{ */ #define NONE ((uint8_t)(0x00)) #define EXT_MODE ((uint8_t)(0x01)) #define INT_MODE ((uint8_t)(0x02)) /* Exported types ------------------------------------------------------- */ /* * @brief R3_2_H5XX_pwm_curr_fdbk component parameters definition */ typedef const struct { TIM_TypeDef * TIMx; /* Contains the pointer to the timer used for PWM generation. It must equal to TIM1 if M1, to TIM8 otherwise */ ADC_TypeDef *ADCDataReg1[6]; ADC_TypeDef *ADCDataReg2[6]; uint32_t ADCConfig1[6]; /* Values of JSQR for first ADC for 6 sectors. */ uint32_t ADCConfig2[6]; /* Values of JSQR for second ADC for 6 sectors. */ /* PWM generation parameters --------------------------------------------------*/ uint16_t Tw; /*!< Used for switching the context in dual MC. It contains biggest delay (expressed in counter ticks) between the counter crest and ADC latest trigger. Specific to F4XX and F7XX. */ uint16_t hTafter; /*!< Sum of dead time plus max value between rise time and noise time express in number of TIM clocks. Specific to F4XX and F7XX.*/ uint16_t hTbefore; /* Sampling time expressed in number of TIM clocks.*/ uint16_t hDeadTime; /*!< Dead time in number of TIM clock cycles. If CHxN are enabled, it must contain the dead time to be generated by the microcontroller, otherwise it expresses the maximum dead time generated by driving network. Specific to F4XX and F7XX. */ uint16_t Tsampling; /* Sampling time expressed in number of TIM clocks.*/ uint16_t Tbefore; /* Sampling time expressed in number of TIM clocks.*/ uint16_t Tcase2; /* Sampling time expressed in number of TIM clocks.*/ uint16_t Tcase3; /* Sampling time expressed in number of TIM clocks.*/ /* Dual MC parameters --------------------------------------------------------*/ uint8_t bFreqRatio; /* Used in case of dual MC to synchronize TIM1 and TIM8. It has effect only on the second instanced object and must be equal to the ratio between the two PWM frequencies (higher/lower). Supported values are 1, 2 or 3 */ uint8_t bIsHigherFreqTim; /* When bFreqRatio is greater than 1 this param is used to indicate if this instance is the one with the highest frequency. Allowed values are: HIGHER_FREQ or LOWER_FREQ */ /* PWM Driving signals initialization ----------------------------------------*/ uint8_t RepetitionCounter; /* Expresses the number of PWM periods to be elapsed before compare registers are updated again. In particular: RepetitionCounter= (2* #PWM periods)-1*/ } R3_2_Params_t; /* * @brief Handles an instance of the R3_2_H5XX_pwm_curr_fdbk component. */ typedef struct { PWMC_Handle_t _Super; /* Base component handler */ uint32_t PhaseAOffset; /* Offset of Phase A current sensing network. */ uint32_t PhaseBOffset; /* Offset of Phase B current sensing network. */ uint32_t PhaseCOffset; /* Offset of Phase C current sensing network. */ uint16_t ADC_ExternalPolarityInjected; /* External trigger selection for ADC peripheral. */ uint32_t ADCTriggerEdge; /*!< Trigger edge selection. Specific to F4XX, F7XX and L4XX. */ uint16_t Half_PWMPeriod; /* Half PWM Period in timer clock counts. */ uint8_t CalibSector; /*!< Space vector sector number during calibration. Specific to F4XX, F7XX and L4XX. */ volatile uint8_t PolarizationCounter; uint8_t PolarizationSector; /* Sector selected during calibration phase. */ R3_2_Params_t const *pParams_str; } PWMC_R3_2_Handle_t; /* Exported functions ------------------------------------------------------- */ /* * Initializes TIMx, ADC, GPIO, DMA1 and NVIC for current reading * in three shunt topology using STM32F30X and two ADCs. */ void R3_2_Init( PWMC_R3_2_Handle_t * pHandle ); /* * Stores into the handler the voltage present on Ia and Ib current * feedback analog channels when no current is flowing into the motor. */ void R3_2_CurrentReadingCalibration( PWMC_Handle_t * pHandle ); /* * Stores into the handle the voltage present on Ia and * Ib current feedback analog channels when no current is flowing into the * motor. */ void R3_2_CurrentReadingPolarization(PWMC_Handle_t *pHdl); /* * Computes and stores in the handler the latest converted motor phase currents in ab_t format. */ void R3_2_GetPhaseCurrents( PWMC_Handle_t * pHandle,ab_t* Iab); /* * Computes and stores in the handler the latest converted motor phase currents in ab_t format. Specific to overmodulation. */ void R3_2_GetPhaseCurrents_OVM( PWMC_Handle_t * pHandle,ab_t* Iab); /* * Turns on low sides switches. */ void R3_2_TurnOnLowSides( PWMC_Handle_t * pHandle, uint32_t ticks ); /* * Enables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_2_SwitchOnPWM( PWMC_Handle_t * pHandle ); /* * Disables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_2_SwitchOffPWM( PWMC_Handle_t * pHandle ); /* * Configures the ADC for the current sampling during calibration. */ uint16_t R3_2_SetADCSampPointCalibration( PWMC_Handle_t * pHandle ); /* * Configures the ADC for the current sampling related to sector X (X = [1..6] ). */ uint16_t R3_2_SetADCSampPointSectX( PWMC_Handle_t * pHandle ); /* * Configures the ADC for the current sampling related to sector X (X = [1..6] ) in case of overmodulation. */ uint16_t R3_2_SetADCSampPointSectX_OVM( PWMC_Handle_t * pHandle ); /* * Contains the TIMx Update event interrupt. */ void *R3_2_TIMx_UP_IRQHandler( PWMC_R3_2_Handle_t * pHandle); /* * Sets the PWM mode for R/L detection. */ void R3_2_RLDetectionModeEnable( PWMC_Handle_t * pHandle ); /* * Disables the PWM mode for R/L detection. */ void R3_2_RLDetectionModeDisable( PWMC_Handle_t * pHandle ); /* * Sets the PWM dutycycle for R/L detection. */ uint16_t R3_2_RLDetectionModeSetDuty( PWMC_Handle_t * pHandle , uint16_t hDuty ); /* * Turns on low sides switches and start ADC triggering. */ void R3_2_RLTurnOnLowSidesAndStart( PWMC_Handle_t * pHandle ); /* * Sets ADC sampling points. */ void RLSetADCSampPoint( PWMC_Handle_t * pHdl ); /* * Stores in the handler the calibrated offsets. */ void R3_2_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /* * Reads the calibrated offsets stored in the handler. */ void R3_2_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*__R3_2_PWM_CURR_FDBK_H*/ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
9,492
C
36.374016
124
0.540771
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/H5xx/Inc/r3_1_h5xx_pwm_curr_fdbk.h
/** ****************************************************************************** * @file r3_1_h5xx_pwm_curr_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * r3_1_H5xx_pwm_curr_fdbk component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __R3_1_PWM_CURR_FDBK_H #define __R3_1_PWM_CURR_FDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "pwm_curr_fdbk.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup R3_1_pwm_curr_fdbk * @{ */ #define NONE ((uint8_t)(0x00)) #define EXT_MODE ((uint8_t)(0x01)) #define INT_MODE ((uint8_t)(0x02)) /* Exported constants --------------------------------------------------------*/ /* Exported types ------------------------------------------------------------*/ /* * @brief R3_1_H5XX_pwm_curr_fdbk component parameters definition */ typedef struct { ADC_TypeDef * ADCx; /* ADC peripheral to be used. */ TIM_TypeDef * TIMx; /* Timer used for PWM generation. */ uint32_t ADCConfig[6]; /*!< store ADC sequence for the 6 sectors */ uint16_t Tw; /*!< Used for switching the context in dual MC. It contains biggest delay (expressed in counter ticks) between the counter crest and ADC latest trigger. Specific to F4XX and F7XX. expresses the maximum dead time generated by driving network */ uint16_t hTafter; /*!< It is the sum of dead time plus max value between rise time and noise time express in number of TIM clocks.*/ uint16_t hTbefore; /*!< It is the sampling time express in number of TIM clocks.*/ uint16_t hDeadTime; /*!< Dead time in number of TIM clock cycles. If CHxN are enabled, it must contain the dead time to be generated by the microcontroller, otherwise it expresses the maximum dead time generated by driving network. Specific to F4XX and F7XX. */ uint16_t Tsampling; /* Sampling time expressed in number of TIM clocks.*/ uint16_t Tbefore; /* Sampling time expressed in number of TIM clocks.*/ uint16_t Tcase2; /* Sampling time expressed in number of TIM clocks.*/ uint16_t Tcase3; /* Sampling time expressed in number of TIM clocks.*/ /* Dual MC parameters --------------------------------------------------------*/ uint8_t bFreqRatio; /* Used in case of dual MC to synchronize TIM1 and TIM8. It has effect only on the second instanced object and must be equal to the ratio between the two PWM frequencies (higher/lower). Supported values are 1, 2 or 3 */ uint8_t bIsHigherFreqTim; /* When bFreqRatio is greater than 1 this param is used to indicate if this instance is the one with the highest frequency. Allowed values are: HIGHER_FREQ or LOWER_FREQ */ uint8_t RepetitionCounter; /*!< It expresses the number of PWM periods to be elapsed before compare registers are updated again. In particular: RepetitionCounter= (2* PWM periods)-1*/ }R3_1_Params_t; /* * @brief This structure is used to handle an instance of the * PWM and current feedback component. */ typedef struct { PWMC_Handle_t _Super; /*!< Offset of current sensing network */ uint32_t PhaseAOffset; /*!< Offset of Phase A current sensing network */ uint32_t PhaseBOffset; /*!< Offset of Phase B current sensing network */ uint32_t PhaseCOffset; /*!< Offset of Phase C current sensing network */ volatile uint32_t ADCTriggerEdge; /*!< edge trigger selection for ADC peripheral.*/ uint16_t Half_PWMPeriod; /*!< Half PWM Period in timer clock counts */ uint16_t ADC_ExternalTriggerInjected; /*!< External ADC trigger source. */ uint16_t ADC_ExternalPolarityInjected; volatile uint8_t PolarizationCounter; /*!< Number of conversions performed during the calibration phase*/ uint8_t PolarizationSector; /* Sector selected during calibration phase.*/ bool ADCRegularLocked; /*!< When it's true, we do not allow usage of ADC to do regular conversion on systick*/ R3_1_Params_t const * pParams_str; }PWMC_R3_1_Handle_t; /* Exported functions ------------------------------------------------------- */ /* * It initializes TIM1, ADC1, GPIO, DMA1 and NVIC for three shunt current * reading configuration using STM32H5x. */ void R3_1_Init(PWMC_R3_1_Handle_t *pHandle); /* * Stores into the handle the voltage present on Ia and * Ib current feedback analog channels when no current is flowing into the * motor. */ void R3_1_CurrentReadingPolarization( PWMC_Handle_t * pHdl ); /* * It computes and return latest converted motor phase currents */ void R3_1_GetPhaseCurrents(PWMC_Handle_t *pHdl, ab_t* pStator_Currents); /* * It computes and return latest converted motor phase currents motor * */ void R3_1_GetPhaseCurrents_OVM( PWMC_Handle_t * pHdl, ab_t * Iab ); /* * Configure the ADC for the current sampling related to sector 1. * It means set the sampling point via TIM1_Ch4 value and polarity * ADC sequence length and channels. */ uint16_t R3_1_SetADCSampPointSectX(PWMC_Handle_t * pHdl ); /* * Configure the ADC for the current sampling * It means set the sampling point via TIMx_Ch4 value and polarity * ADC sequence length and channels. * And call the WriteTIMRegisters method. */ uint16_t R3_1_SetADCSampPointSectX_OVM( PWMC_Handle_t * pHdl ); /* * Configure the ADC for the current sampling during calibration. * It means set the sampling point via TIMx_Ch4 value and polarity * ADC sequence length and channels. */ uint16_t R3_1_SetADCSampPointCalibration(PWMC_Handle_t *pHdl); /* * Turns on low sides switches. */ void R3_1_TurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks); /* * This function enables the PWM outputs */ void R3_1_SwitchOnPWM(PWMC_Handle_t *pHdl); /* * It disables PWM generation on the proper Timer peripheral acting on * MOE bit and reset the TIM status */ void R3_1_SwitchOffPWM(PWMC_Handle_t *pHdl); /* * It contains the TIMx Update event interrupt */ void * R3_1_TIMx_UP_IRQHandler( PWMC_R3_1_Handle_t * pHandle ); /* * Sets the calibrated offset. */ void R3_1_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /* * Reads the calibrated offsets. */ void R3_1_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /* * Sets the PWM mode for R/L detection. */ void R3_1_RLDetectionModeEnable( PWMC_Handle_t * pHdl ); /* * Disables the PWM mode for R/L detection. */ void R3_1_RLDetectionModeDisable( PWMC_Handle_t * pHdl ); /* * Sets the PWM dutycycle for R/L detection. */ uint16_t R3_1_RLDetectionModeSetDuty( PWMC_Handle_t * pHdl, uint16_t hDuty ); /* * This function is specific for MP phase. */ void R3_1_RLTurnOnLowSidesAndStart( PWMC_Handle_t * pHdl ); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*__R3_1_H5XX_PWMNCURRFDBK_H*/ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
9,283
C
36.136
119
0.533987
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/F4xx/Src/r3_2_f4xx_pwm_curr_fdbk.c
/** ****************************************************************************** * @file r3_2_f4xx_pwm_curr_fdbk.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement the features * of the three shunts current sensing topology. * * It is specifically designed for STM32F4XX microcontrollers and * implements the successive sampling of current using two ADCs. * + MCU peripheral and handle initialization function * + three shunt current sensing * + space vector modulation function * + ADC sampling function * ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup R3_2_F4XX_pwm_curr_fdbk */ /* Includes ------------------------------------------------------------------*/ #include "r3_2_f4xx_pwm_curr_fdbk.h" #include "pwm_common.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup R3_2_pwm_curr_fdbk * @{ */ /* Private defines -----------------------------------------------------------*/ #define TIMxCCER_MASK_CH123 ((uint16_t) (LL_TIM_CHANNEL_CH1|LL_TIM_CHANNEL_CH1N|\ LL_TIM_CHANNEL_CH2|LL_TIM_CHANNEL_CH2N|\ LL_TIM_CHANNEL_CH3|LL_TIM_CHANNEL_CH3N)) /* Private function prototypes -----------------------------------------------*/ __STATIC_INLINE uint16_t R3_2_WriteTIMRegisters( PWMC_Handle_t * pHdl, uint16_t hCCR4Reg ); void R3_2_HFCurrentsCalibrationAB( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ); void R3_2_HFCurrentsCalibrationC( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ); static void R3_2_RLGetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ); static void R3_2_RLTurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ); static void R3_2_RLSwitchOnPWM( PWMC_Handle_t * pHdl ); /* * @brief Initializes TIMx, ADC, GPIO, DMA1 and NVIC for current reading * in three shunt topology using two ADCs. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void R3_2_Init( PWMC_R3_2_Handle_t * pHandle ) { TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx_1 = pHandle->pParams_str->ADCDataReg1[0]; ADC_TypeDef * ADCx_2 = pHandle->pParams_str->ADCDataReg2[0]; LL_TIM_DisableCounter( TIMx ); LL_TIM_ClearFlag_BRK(TIMx); LL_TIM_EnableIT_BRK(TIMx); /* Prepare timer for synchronization */ LL_TIM_GenerateEvent_UPDATE(TIMx); if ( pHandle->pParams_str->bFreqRatio == 2u ) { if ( pHandle->pParams_str->bIsHigherFreqTim == HIGHER_FREQ ) { if ( pHandle->pParams_str->RepetitionCounter == 3u ) { /* Set TIMx repetition counter to 1 */ LL_TIM_SetRepetitionCounter( TIMx, 1u ); LL_TIM_GenerateEvent_UPDATE( TIMx ); /* Repetition counter will be set to 3 at next Update */ LL_TIM_SetRepetitionCounter( TIMx, 3 ); } } LL_TIM_SetCounter( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) - 1u ); } else /* FreqRatio equal to 1 or 3 */ { if ( pHandle->_Super.Motor == M1 ) { LL_TIM_SetCounter( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) - 1u ); } } /* Enable PWM channel */ LL_TIM_CC_EnableChannel( TIMx, TIMxCCER_MASK_CH123 ); if ( TIMx == TIM1 ) { /* TIM1 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph(LL_DBGMCU_APB2_GRP1_TIM1_STOP); pHandle->ADC_ExternalTriggerInjected = LL_ADC_INJ_TRIG_EXT_TIM1_CH4; } else { /* TIM8 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph(LL_DBGMCU_APB2_GRP1_TIM8_STOP); pHandle->ADC_ExternalTriggerInjected = LL_ADC_INJ_TRIG_EXT_TIM8_CH4; } /* ADCs registers configuration ---------------------------------*/ /* Enable ADCx_1 and ADCx_2 */ LL_ADC_Enable( ADCx_1 ); LL_ADC_Enable( ADCx_2 ); /* ADCx_1 Injected conversions end interrupt enabling */ LL_ADC_ClearFlag_JEOS(ADCx_1); LL_ADC_EnableIT_JEOS( ADCx_1 ); /* reset regular conversion sequencer length set by cubeMX */ LL_ADC_REG_SetSequencerLength( ADCx_1, LL_ADC_REG_SEQ_SCAN_DISABLE ); LL_ADC_INJ_SetSequencerLength( ADCx_1, LL_ADC_INJ_SEQ_SCAN_DISABLE ); LL_ADC_INJ_SetSequencerLength( ADCx_2, LL_ADC_INJ_SEQ_SCAN_DISABLE ); pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_RISING; pHandle->_Super.DTTest = 0u; } /* * @brief Stores in @p pHdl handler the calibrated @p offsets. * */ __weak void R3_2_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 pHandle->PhaseAOffset = offsets->phaseAOffset; pHandle->PhaseBOffset = offsets->phaseBOffset; pHandle->PhaseCOffset = offsets->phaseCOffset; pHdl->offsetCalibStatus = true; } /* * @brief Reads the calibrated @p offsets stored in @p pHdl handler. * */ __weak void R3_2_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 offsets->phaseAOffset = pHandle->PhaseAOffset; offsets->phaseBOffset = pHandle->PhaseBOffset; offsets->phaseCOffset = pHandle->PhaseCOffset; } /* * @brief Stores into the @p pHdl the voltage present on Ia and Ib current * feedback analog channels when no current is flowing into the motor. * */ __weak void R3_2_CurrentReadingCalibration( PWMC_Handle_t * pHdl ) { PWMC_R3_2_Handle_t * pHandle = (PWMC_R3_2_Handle_t *) pHdl; TIM_TypeDef* TIMx = pHandle->pParams_str->TIMx; if (false == pHandle->_Super.offsetCalibStatus) { volatile PWMC_GetPhaseCurr_Cb_t GetPhaseCurrCbSave; volatile PWMC_SetSampPointSectX_Cb_t SetSampPointSectXCbSave; /* Save callback routines */ GetPhaseCurrCbSave = pHandle->_Super.pFctGetPhaseCurrents; SetSampPointSectXCbSave = pHandle->_Super.pFctSetADCSampPointSectX; pHandle->PhaseAOffset = 0u; pHandle->PhaseBOffset = 0u; pHandle->PhaseCOffset = 0u; pHandle->PolarizationCounter = 0u; LL_TIM_CC_DisableChannel(TIMx, TIMxCCER_MASK_CH123); /* Offset calibration for A & B phases */ /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R3_2_HFCurrentsCalibrationAB; pHandle->_Super.pFctSetADCSampPointSectX = &R3_2_SetADCSampPointCalibration; pHandle->CalibSector = SECTOR_4; /* Required to force first polarization conversion on SECTOR_4*/ pHandle->_Super.Sector = SECTOR_4; R3_2_SwitchOnPWM( &pHandle->_Super ); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd( TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter ); R3_2_SwitchOffPWM( &pHandle->_Super ); /* Offset calibration for C phase */ /* Reset PolarizationCounter */ pHandle->PolarizationCounter = 0u; /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R3_2_HFCurrentsCalibrationC; pHandle->CalibSector = SECTOR_1; /* Required to force first polarization conversion on SECTOR_1*/ pHandle->_Super.Sector = SECTOR_1; R3_2_SwitchOnPWM( &pHandle->_Super ); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd( TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter ); R3_2_SwitchOffPWM( &pHandle->_Super ); pHandle->PhaseAOffset >>= 3; pHandle->PhaseBOffset >>= 3; pHandle->PhaseCOffset >>= 3; if (0U == pHandle->_Super.SWerror) { pHandle->_Super.offsetCalibStatus = true; } else { /* nothing to do */ } /* Change back function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = GetPhaseCurrCbSave; pHandle->_Super.pFctSetADCSampPointSectX = SetSampPointSectXCbSave; } /* It over write TIMx CCRy wrongly written by FOC during calibration so as to force 50% duty cycle on the three inverter legs */ /* Disable TIMx preload */ LL_TIM_OC_DisablePreload( TIMx, LL_TIM_CHANNEL_CH1 ); LL_TIM_OC_DisablePreload( TIMx, LL_TIM_CHANNEL_CH2 ); LL_TIM_OC_DisablePreload( TIMx, LL_TIM_CHANNEL_CH3 ); LL_TIM_OC_SetCompareCH1(TIMx,pHandle->Half_PWMPeriod); LL_TIM_OC_SetCompareCH2(TIMx,pHandle->Half_PWMPeriod); LL_TIM_OC_SetCompareCH3(TIMx,pHandle->Half_PWMPeriod); LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH1 ); LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH2 ); LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH3 ); /* It re-enable drive of TIMx CHy and CHyN by TIMx CHyRef*/ LL_TIM_CC_EnableChannel(TIMx, TIMxCCER_MASK_CH123); /* sector and phase sequence for the switch on phase */ pHandle->_Super.Sector = SECTOR_4; } /* * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p pStator_Currents ab_t format. * */ __weak void R3_2_GetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t* pStator_Currents ) { PWMC_R3_2_Handle_t * pHandle = (PWMC_R3_2_Handle_t *) pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; int32_t wAux; uint16_t hReg1; uint16_t hReg2; uint8_t bSector; /* disable ADC trigger source */ LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); bSector = pHandle->_Super.Sector; hReg1 = pHandle->pParams_str->ADCDataReg1[bSector]->JDR1 * 2; hReg2 = pHandle->pParams_str->ADCDataReg2[bSector]->JDR1 * 2; switch ( bSector ) { case SECTOR_4: case SECTOR_5: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ wAux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( hReg1 ); /* Saturation of Ia */ if ( wAux < -INT16_MAX ) { pStator_Currents->a = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->a = INT16_MAX; } else { pStator_Currents->a = ( int16_t )wAux; } /* Ib = PhaseBOffset - ADC converted value) */ wAux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( hReg2 ); /* Saturation of Ib */ if ( wAux < -INT16_MAX ) { pStator_Currents->b = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->b = INT16_MAX; } else { pStator_Currents->b = ( int16_t )wAux; } break; case SECTOR_6: case SECTOR_1: /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ wAux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( hReg1 ); /* Saturation of Ib */ if ( wAux < -INT16_MAX ) { pStator_Currents->b = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->b = INT16_MAX; } else { pStator_Currents->b = ( int16_t )wAux; } /* Ic = PhaseCOffset - ADC converted value) */ /* Ia = -Ic -Ib */ wAux = ( int32_t )( pHandle->PhaseCOffset ) - ( int32_t )( hReg2 ); wAux = -wAux - ( int32_t )pStator_Currents->b; /* Saturation of Ia */ if ( wAux > INT16_MAX ) { pStator_Currents->a = INT16_MAX; } else if ( wAux < -INT16_MAX ) { pStator_Currents->a = -INT16_MAX; } else { pStator_Currents->a = ( int16_t )wAux; } break; case SECTOR_2: case SECTOR_3: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ wAux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( hReg1 ); /* Saturation of Ia */ if ( wAux < -INT16_MAX ) { pStator_Currents->a = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->a = INT16_MAX; } else { pStator_Currents->a = ( int16_t )wAux; } /* Ic = PhaseCOffset - ADC converted value) */ /* Ib = -Ic -Ia */ wAux = ( int32_t )( pHandle->PhaseCOffset ) - ( int32_t )( hReg2 ); wAux = -wAux - ( int32_t )pStator_Currents->a; /* Saturation of Ib */ if ( wAux > INT16_MAX ) { pStator_Currents->b = INT16_MAX; } else if ( wAux < -INT16_MAX ) { pStator_Currents->b = -INT16_MAX; } else { pStator_Currents->b = ( int16_t )wAux; } break; default: break; } pHandle->_Super.Ia = pStator_Currents->a; pHandle->_Super.Ib = pStator_Currents->b; pHandle->_Super.Ic = -pStator_Currents->a - pStator_Currents->b; } /* * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p Iab ab_t format. Specific to overmodulation. * */ __weak void R3_2_GetPhaseCurrents_OVM( PWMC_Handle_t * pHdl, ab_t * Iab ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint8_t Sector; int32_t Aux; uint32_t ADCDataReg1; uint32_t ADCDataReg2; /* disable ADC trigger source */ LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); Sector = ( uint8_t )pHandle->_Super.Sector; ADCDataReg1 = pHandle->pParams_str->ADCDataReg1[Sector]->JDR1 * 2; ADCDataReg2 = pHandle->pParams_str->ADCDataReg2[Sector]->JDR1 * 2; switch ( Sector ) { case SECTOR_4: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { // Ib not available, use estimated Ib Aux = ( int32_t )( pHandle->_Super.IbEst ); } else { /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg2 ); } /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_5: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { // Ia not available, use estimated Ia Aux = ( int32_t )( pHandle->_Super.IaEst ); } else { Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg2 ); /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_6: /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IcEst ; /* -Ic */ Aux -= ( int32_t )Iab->b; } else { /* Ia = -Ic -Ib */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->b; /* Ia */ } /* Saturation of Ia */ if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else { Iab->a = ( int16_t )Aux; } break; case SECTOR_1: /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IbEst; } else { Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } /* Ia = -Ic -Ib */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->b; /* Ia */ /* Saturation of Ia */ if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else { Iab->a = ( int16_t )Aux; } break; case SECTOR_2: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IaEst; } else { Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } /* Ib = -Ic -Ia */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ /* Saturation of Ib */ if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_3: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { /* Ib = -Ic -Ia */ Aux = ( int32_t ) pHandle->_Super.IcEst; /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ } else { /* Ib = -Ic -Ia */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ } /* Saturation of Ib */ if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; default: break; } pHandle->_Super.Ia = Iab->a; pHandle->_Super.Ib = Iab->b; pHandle->_Super.Ic = -Iab->a - Iab->b; } /* * @brief Implementation of PWMC_GetPhaseCurrents to be performed during calibration. * * It sums up injected conversion data into PhaseAOffset and wPhaseBOffset * to compute the offset introduced in the current feedback network. It is required to * properly configure ADC inputs before in order to enable offset computation. * * @param pHdl: Pointer on the target component instance. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ __weak void R3_2_HFCurrentsCalibrationAB( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { PWMC_R3_2_Handle_t * pHandle = (PWMC_R3_2_Handle_t *) pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* disable ADC trigger source */ LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); if ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { pHandle->PhaseAOffset += pHandle->pParams_str->ADCDataReg1[pHandle->CalibSector]->JDR1; pHandle->PhaseBOffset += pHandle->pParams_str->ADCDataReg2[pHandle->CalibSector]->JDR1; pHandle->PolarizationCounter++; } /* during offset calibration no current is flowing in the phases */ pStator_Currents->a = 0; pStator_Currents->b = 0; } /* * @brief Implementation of PWMC_GetPhaseCurrents to be performed during calibration. * * It sums up injected conversion data into PhaseCOffset to compute the offset * introduced in the current feedback network. It is required to properly configure * ADC inputs before in order to enable offset computation. * * @param pHdl: Pointer on the target component instance. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ __weak void R3_2_HFCurrentsCalibrationC( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { PWMC_R3_2_Handle_t * pHandle = (PWMC_R3_2_Handle_t *) pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* disable ADC trigger source */ LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); if ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { pHandle->PhaseCOffset += pHandle->pParams_str->ADCDataReg2[pHandle->CalibSector]->JDR1; pHandle->PolarizationCounter++; } /* during offset calibration no current is flowing in the phases */ pStator_Currents->a = 0; pStator_Currents->b = 0; } /* * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors of driving section. It has to be * called each motor start-up when using high voltage drivers. * * @param pHdl: Handler of the current instance of the PWM component * @param ticks: Timer ticks value to be applied * Min value: 0 (low sides ON) * Max value: PWM_PERIOD_CYCLES/2 (low sides OFF) */ __weak void R3_2_TurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ) { PWMC_R3_2_Handle_t * pHandle = (PWMC_R3_2_Handle_t *) pHdl; TIM_TypeDef* TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = true; /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE(TIMx); /*Turn on the three low side switches */ LL_TIM_OC_SetCompareCH1(TIMx,ticks); LL_TIM_OC_SetCompareCH2(TIMx,ticks); LL_TIM_OC_SetCompareCH3(TIMx,ticks); /* Wait until next update */ while (LL_TIM_IsActiveFlag_UPDATE(TIMx) == RESET) {} LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs(TIMx); if ( (pHandle->_Super.LowSideOutputs) == ES_GPIO ) { LL_GPIO_SetOutputPin (pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_SetOutputPin (pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_SetOutputPin (pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } return; } /* * @brief Enables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_2_SwitchOnPWM( PWMC_Handle_t * pHdl ) { PWMC_R3_2_Handle_t * pHandle = (PWMC_R3_2_Handle_t *) pHdl; TIM_TypeDef* TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = false; /* Set all duty to 50% */ LL_TIM_OC_SetCompareCH1(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH2(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH3(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH4(TIMx, (uint32_t)(pHandle->Half_PWMPeriod - 5u)); /* wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE(TIMx); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE(TIMx); /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE; LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { if ( LL_TIM_CC_IsEnabledChannel(TIMx,TIMxCCER_MASK_CH123) != 0u ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Enable Update IRQ */ LL_TIM_EnableIT_UPDATE(TIMx); return; } /* * @brief Disables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_2_SwitchOffPWM( PWMC_Handle_t * pHdl ) { PWMC_R3_2_Handle_t * pHandle = (PWMC_R3_2_Handle_t *) pHdl; TIM_TypeDef* TIMx = pHandle->pParams_str->TIMx; /* Disable UPDATE ISR */ LL_TIM_DisableIT_UPDATE( TIMx ); pHandle->_Super.TurnOnLowSidesAction = false; /* Main PWM Output Disable */ LL_TIM_DisableAllOutputs( TIMx ); if ( (pHandle->_Super.LowSideOutputs) == ES_GPIO ) { LL_GPIO_ResetOutputPin (pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_ResetOutputPin (pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_ResetOutputPin (pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } /* wait for a new PWM period to flush last HF task */ LL_TIM_ClearFlag_UPDATE(TIMx); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} LL_TIM_ClearFlag_UPDATE(TIMx); return; } /* * @brief Writes into peripheral registers the new duty cycles and sampling point. * * @param pHdl: Handler of the current instance of the PWM component. * @param hCCR4Reg: New capture/compare register value, written in timer clock counts. * @retval Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ __STATIC_INLINE uint16_t R3_2_WriteTIMRegisters( PWMC_Handle_t * pHdl, uint16_t hCCR4Reg ) { PWMC_R3_2_Handle_t * pHandle = (PWMC_R3_2_Handle_t *) pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint16_t hAux; LL_TIM_OC_SetCompareCH1( TIMx, pHandle->_Super.CntPhA ); LL_TIM_OC_SetCompareCH2( TIMx, pHandle->_Super.CntPhB ); LL_TIM_OC_SetCompareCH3( TIMx, pHandle->_Super.CntPhC ); LL_TIM_OC_SetCompareCH4( TIMx, hCCR4Reg ); /* Limit for update event */ /* Check the if TIMx CH4 is enabled. If it is set, an update event has occurred and thus the FOC rate is too high */ if (LL_TIM_CC_IsEnabledChannel(TIMx, LL_TIM_CHANNEL_CH4)) { hAux = MC_DURATION; } else { hAux = MC_NO_ERROR; } if ( pHandle->_Super.SWerror == 1u ) { hAux = MC_DURATION; pHandle->_Super.SWerror = 0u; } return hAux; } /* * @brief Configures the ADC for the current sampling during calibration. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ __weak uint16_t R3_2_SetADCSampPointCalibration( PWMC_Handle_t * pHdl) { PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; /* Set rising edge trigger (default) */ pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_RISING; pHandle->_Super.Sector = pHandle->CalibSector; return R3_2_WriteTIMRegisters( &pHandle->_Super, (uint32_t)(pHandle->Half_PWMPeriod - 1u) ); } /* * @brief Configures the ADC for the current sampling related to sector X (X = [1..6] ). * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ __weak uint16_t R3_2_SetADCSampPointSectX( PWMC_Handle_t * pHdl ) { PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; uint16_t hCntSmp; uint16_t hDeltaDuty; register uint16_t lowDuty = pHdl->lowDuty; register uint16_t midDuty = pHdl->midDuty; /* Check if sampling AB in the middle of PWM is possible */ if ( ( uint16_t )( pHandle->Half_PWMPeriod - lowDuty ) > pHandle->pParams_str->hTafter ) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled wIch corresponds * to sector 4 */ pHandle->_Super.Sector = SECTOR_4; /* set sampling point trigger in the middle of PWM period */ hCntSmp = ( uint32_t )( pHandle->Half_PWMPeriod ) - 1u; } else { /* ADC Injected sequence configuration. The stator phase with minimum value of complementary duty cycle is set as first. In every sector there is always one phase with maximum complementary duty, one with minimum complementary duty and one with variable complementary duty. In this case, phases with variable complementary duty and with maximum duty are converted and the first will be always the phase with variable complementary duty cycle */ /* Crossing Point Searching */ hDeltaDuty = ( uint16_t )( lowDuty - midDuty ); /* Definition of crossing point */ if ( hDeltaDuty > ( uint16_t )( pHandle->Half_PWMPeriod - lowDuty ) * 2u ) { /* hTbefore = 2*Ts + Tc, where Ts = Sampling time of ADC, Tc = Conversion Time of ADC */ hCntSmp = lowDuty - pHandle->pParams_str->hTbefore; } else { /* hTafter = DT + max(Trise, Tnoise) */ hCntSmp = lowDuty + pHandle->pParams_str->hTafter; if ( hCntSmp >= pHandle->Half_PWMPeriod ) { /* It must be changed the trigger direction from positive to negative to sample after middle of PWM*/ pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_FALLING; hCntSmp = ( 2u * pHandle->Half_PWMPeriod ) - hCntSmp - 1u; } } } return R3_2_WriteTIMRegisters( &pHandle->_Super, hCntSmp ); } /* * @brief Configures the ADC for the current sampling related to sector X (X = [1..6] ) in case of overmodulation. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ uint16_t R3_2_SetADCSampPointSectX_OVM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ uint16_t SamplingPoint; uint16_t DeltaDuty; pHandle->_Super.useEstCurrent = false; DeltaDuty = ( uint16_t )( pHdl->lowDuty - pHdl->midDuty ); /* case 1 (cf user manual) */ if (( uint16_t )( pHandle->Half_PWMPeriod - pHdl->lowDuty ) > pHandle->pParams_str->hTafter) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled which corresponds * to sector 4 or 5 */ pHandle->_Super.Sector = SECTOR_5; /* set sampling point trigger in the middle of PWM period */ SamplingPoint = pHandle->Half_PWMPeriod - (uint16_t) 1; } else /* case 2 (cf user manual) */ { if (DeltaDuty >= pHandle->pParams_str->Tcase2) { SamplingPoint = pHdl->lowDuty - pHandle->pParams_str->hTbefore; } else { /* case 3 (cf user manual) */ if ((pHandle->Half_PWMPeriod - pHdl->lowDuty) > pHandle->pParams_str->Tcase3) { /* ADC trigger edge must be changed from positive to negative */ pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_FALLING; SamplingPoint = pHdl->lowDuty + pHandle->pParams_str->Tsampling; } else { SamplingPoint = pHandle->Half_PWMPeriod-1; pHandle->_Super.useEstCurrent = true; } } } return R3_2_WriteTIMRegisters( &pHandle->_Super, SamplingPoint ); } /* * @brief Contains the TIMx Update event interrupt. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void * R3_2_TIMx_UP_IRQHandler( PWMC_R3_2_Handle_t * pHandle) { TIM_TypeDef* TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx_1 = pHandle->pParams_str->ADCDataReg1[0]; ADC_TypeDef * ADCx_2 = pHandle->pParams_str->ADCDataReg2[0]; uint32_t ADCInjFlags; /* dual drive check */ ADCInjFlags = ADCx_1->SR & (LL_ADC_FLAG_JSTRT|LL_ADC_FLAG_JEOS); if ( ADCInjFlags == LL_ADC_FLAG_JSTRT ) { /* ADC conversion is on going on the second motor */ do { /* wait for end of conversion */ ADCInjFlags = ADCx_1->SR & (LL_ADC_FLAG_JSTRT|LL_ADC_FLAG_JEOS); } while ( ADCInjFlags != (LL_ADC_FLAG_JSTRT|LL_ADC_FLAG_JEOS) ); } else if ( ADCInjFlags == 0 ) { /* ADC conversion on the second motor is not yet started */ while ( ( TIMx->CNT ) < ( pHandle->pParams_str->Tw ) ) { /* wait for a maximum delay */ } ADCInjFlags = ADCx_1->SR & (LL_ADC_FLAG_JSTRT|LL_ADC_FLAG_JEOS); if ( ADCInjFlags == LL_ADC_FLAG_JSTRT ) { /* ADC conversion is on going on the second motor */ do { /* wait for end of conversion */ ADCInjFlags = ADCx_1->SR & (LL_ADC_FLAG_JSTRT|LL_ADC_FLAG_JEOS); } while ( ADCInjFlags != (LL_ADC_FLAG_JSTRT|LL_ADC_FLAG_JEOS) ); } } else { /* ADC conversion on the second motor is done */ } /* Disabling trigger to avoid unwanted conversion */ LL_ADC_INJ_StopConversionExtTrig(ADCx_1); LL_ADC_INJ_StopConversionExtTrig(ADCx_2); /* Set next current channel according to sector */ ADCx_1->JSQR = pHandle->pParams_str->ADCConfig1[pHandle->_Super.Sector]; ADCx_2->JSQR = pHandle->pParams_str->ADCConfig2[pHandle->_Super.Sector]; LL_ADC_INJ_SetTriggerSource(ADCx_1,pHandle->ADC_ExternalTriggerInjected); LL_ADC_INJ_SetTriggerSource(ADCx_2,pHandle->ADC_ExternalTriggerInjected); /* enable ADC trigger source */ LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH4); LL_ADC_INJ_StartConversionExtTrig(ADCx_1, pHandle->ADCTriggerEdge); LL_ADC_INJ_StartConversionExtTrig(ADCx_2, pHandle->ADCTriggerEdge); /* reset default edge detection trigger */ pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_RISING; return &( pHandle->_Super.Motor ); } /* * @brief Sets the PWM mode for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_2_RLDetectionModeEnable( PWMC_Handle_t * pHdl ) { PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; if ( pHandle->_Super.RLDetectionMode == false ) { /* Channel1 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH1, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH1N ); LL_TIM_OC_SetCompareCH1( TIMx, 0u ); /* Channel2 configuration */ if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_ACTIVE ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_INACTIVE ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else { } /* Channel3 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH3, LL_TIM_OCMODE_PWM2 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3N ); } pHandle->_Super.pFctGetPhaseCurrents = &R3_2_RLGetPhaseCurrents; pHandle->_Super.pFctTurnOnLowSides = &R3_2_RLTurnOnLowSides; pHandle->_Super.pFctSwitchOnPwm = &R3_2_RLSwitchOnPWM; pHandle->_Super.pFctSwitchOffPwm = &R3_2_SwitchOffPWM; pHandle->_Super.RLDetectionMode = true; } /* * @brief Disables the PWM mode for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_2_RLDetectionModeDisable( PWMC_Handle_t * pHdl ) { PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; if ( pHandle->_Super.RLDetectionMode == true ) { /* Channel1 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH1, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1 ); if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH1N ); } else { } LL_TIM_OC_SetCompareCH1( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) >> 1 ); /* Channel2 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2 ); if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else { } LL_TIM_OC_SetCompareCH2( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) >> 1 ); /* Channel3 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH3, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH3 ); if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH3N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3N ); } else { } LL_TIM_OC_SetCompareCH3( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) >> 1 ); pHandle->_Super.pFctGetPhaseCurrents = &R3_2_GetPhaseCurrents; pHandle->_Super.pFctTurnOnLowSides = &R3_2_TurnOnLowSides; pHandle->_Super.pFctSwitchOnPwm = &R3_2_SwitchOnPWM; pHandle->_Super.pFctSwitchOffPwm = &R3_2_SwitchOffPWM; pHandle->_Super.RLDetectionMode = false; } } /* * @brief Sets the PWM dutycycle for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. * @param hDuty: Duty cycle to apply, written in uint16_t. * @retval Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ uint16_t R3_2_RLDetectionModeSetDuty( PWMC_Handle_t * pHdl, uint16_t hDuty ) { PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint32_t val; uint16_t hAux; val = ( ( uint32_t )( pHandle->Half_PWMPeriod ) * ( uint32_t )( hDuty ) ) >> 16; pHandle->_Super.CntPhA = ( uint16_t )( val ); /* TIM1 Channel 1 Duty Cycle configuration. * In RL Detection mode only the Up-side device of Phase A are controlled*/ LL_TIM_OC_SetCompareCH1(TIMx, ( uint32_t )pHandle->_Super.CntPhA); /* set the sector that correspond to Phase A and B sampling */ pHdl->Sector = SECTOR_4; /* Limit for update event */ /* Check the status flag. If an update event has occurred before to set new values of regs the FOC rate is too high */ if (LL_TIM_CC_IsEnabledChannel(TIMx, LL_TIM_CHANNEL_CH4)) { hAux = MC_DURATION; } else { hAux = MC_NO_ERROR; } if ( pHandle->_Super.SWerror == 1u ) { hAux = MC_DURATION; pHandle->_Super.SWerror = 0u; } return hAux; } /* * @brief Computes and stores into @p pHandle latest converted motor phase currents * during RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ void R3_2_RLGetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; int32_t wAux; /* disable ADC trigger source */ LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); wAux = (int32_t)( pHandle->PhaseBOffset ) - (int32_t)pHandle->pParams_str->ADCDataReg2[pHandle->_Super.Sector]*2; /* Check saturation */ if ( wAux > -INT16_MAX ) { if ( wAux < INT16_MAX ) { } else { wAux = INT16_MAX; } } else { wAux = -INT16_MAX; } pStator_Currents->a = (int16_t)wAux; pStator_Currents->b = (int16_t)wAux; } /* * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors * of driving section. It has to be called at each motor start-up when * using high voltage drivers. * This function is specific for RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. * @param ticks: Duty cycle of the boot capacitors charge, specific to motor. */ static void R3_2_RLTurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ) { PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /*Turn on the phase A low side switch */ LL_TIM_OC_SetCompareCH1 ( TIMx, 0u ); /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Wait until next update */ while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } return; } /* * @brief Enables PWM generation on the proper Timer peripheral. * * This function is specific for RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. */ static void R3_2_RLSwitchOnPWM( PWMC_Handle_t * pHdl ) { PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); LL_TIM_OC_SetCompareCH1( TIMx, 1u ); LL_TIM_OC_SetCompareCH4( TIMx, ( pHandle->Half_PWMPeriod ) - 5u ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE ; LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { if ( ( TIMx->CCER & TIMxCCER_MASK_CH123 ) != 0u ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* enable TIMx update interrupt*/ LL_TIM_EnableIT_UPDATE( TIMx ); return; } /* * @brief Turns on low sides switches and start ADC triggering. * * This function is specific for MP phase. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_2_RLTurnOnLowSidesAndStart( PWMC_Handle_t * pHdl ) { PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx_1 = pHandle->pParams_str->ADCDataReg1[0]; ADC_TypeDef * ADCx_2 = pHandle->pParams_str->ADCDataReg2[0]; /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); LL_TIM_OC_SetCompareCH1 ( TIMx, 0x0u ); LL_TIM_OC_SetCompareCH2 ( TIMx, 0x0u ); LL_TIM_OC_SetCompareCH3 ( TIMx, 0x0u ); LL_TIM_OC_SetCompareCH4( TIMx, ( pHandle->Half_PWMPeriod - 5u)); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE ; LL_TIM_EnableAllOutputs ( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } pHdl->Sector = SECTOR_4; LL_ADC_INJ_SetTriggerSource( ADCx_1, pHandle->ADC_ExternalTriggerInjected); LL_ADC_INJ_SetTriggerSource( ADCx_2, pHandle->ADC_ExternalTriggerInjected); LL_ADC_INJ_StartConversionExtTrig(ADCx_1,LL_ADC_INJ_TRIG_EXT_RISING); LL_ADC_INJ_StartConversionExtTrig(ADCx_2,LL_ADC_INJ_TRIG_EXT_RISING); LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH4); LL_TIM_EnableIT_UPDATE( TIMx ); return; } /** * @brief Sets ADC sampling points. * * This function is specific for MP phase. Specific to F4XX, F7XX, L4XX and H5XX. * * @param pHdl: Handler of the current instance of the PWM component. */ void RLSetADCSampPoint( PWMC_Handle_t * pHdl ) { /* dummy sector setting to get correct Ia value */ pHdl->Sector = SECTOR_4; return; } /** * @} */ /** * @} */ /** * @} */ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
48,924
C
30.142584
143
0.613503
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/F4xx/Src/r3_1_f4xx_pwm_curr_fdbk.c
/** ****************************************************************************** * @file r3_1_f4xx_pwm_curr_fdbk.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement current sensor * class to be stantiated when the three shunts current sensing * topology is used. * * It is specifically designed for STM32F401x8 microcontrollers. * + MCU peripheral and handle initialization function * + three shunt current sensing * + space vector modulation function * + ADC sampling function * ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup R3_1_F4XX_pwm_curr_fdbk */ /* Includes ------------------------------------------------------------------*/ #include "r3_1_f4xx_pwm_curr_fdbk.h" #include "pwm_common.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup R3_1_pwm_curr_fdbk * @{ */ /* Private defines -----------------------------------------------------------*/ #define TIMxCCER_MASK_CH123 ((uint16_t) (LL_TIM_CHANNEL_CH1|LL_TIM_CHANNEL_CH1N|\ LL_TIM_CHANNEL_CH2|LL_TIM_CHANNEL_CH2N|\ LL_TIM_CHANNEL_CH3|LL_TIM_CHANNEL_CH3N)) /* DIR bits of TIM1 CR1 register identification for correct check of Counting direction detection*/ #define DIR_MASK 0x0010u /* binary value: 0000000000010000 */ /* Private typedef -----------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ void R3_1_HFCurrentsCalibrationAB(PWMC_Handle_t *pHdl,ab_t* pStator_Currents); void R3_1_HFCurrentsCalibrationC(PWMC_Handle_t *pHdl,ab_t* pStator_Currents); uint16_t R3_1_WriteTIMRegisters(PWMC_Handle_t *pHdl, uint16_t hCCR4Reg); /* Private functions ---------------------------------------------------------*/ /* Local redefinition of both LL_TIM_OC_EnablePreload & LL_TIM_OC_DisablePreload */ __STATIC_INLINE void __LL_TIM_OC_EnablePreload(TIM_TypeDef *TIMx, uint32_t Channel) { register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); register volatile uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); SET_BIT(*pReg, (TIM_CCMR1_OC1PE << SHIFT_TAB_OCxx[iChannel])); } __STATIC_INLINE void __LL_TIM_OC_DisablePreload(TIM_TypeDef *TIMx, uint32_t Channel) { register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); register volatile uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); CLEAR_BIT(*pReg, (TIM_CCMR1_OC1PE << SHIFT_TAB_OCxx[iChannel])); } /* * @brief Initializes TIMx, ADC, GPIO, DMA1 and NVIC for current reading * in three shunt topology using STM32F4XX and one ADC. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void R3_1_Init(PWMC_R3_1_Handle_t *pHandle) { TIM_TypeDef* TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef* ADCx = pHandle->pParams_str->ADCx; if ((uint32_t)pHandle == (uint32_t)&pHandle->_Super) { /* disable IT and flags in case of LL driver usage * workaround for unwanted interrupt enabling done by LL driver */ LL_ADC_DisableIT_EOCS(ADCx); LL_ADC_ClearFlag_EOCS(ADCx); LL_ADC_DisableIT_JEOS(ADCx); LL_ADC_ClearFlag_JEOS(ADCx); /* disable main TIM counter to ensure * a synchronous start by TIM2 trigger */ LL_TIM_DisableCounter(TIMx); if ( TIMx == TIM1 ) { /* TIM1 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph( LL_DBGMCU_APB2_GRP1_TIM1_STOP ); } #if defined(TIM8) else if ( TIMx == TIM8 ) { /* TIM8 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph( LL_DBGMCU_APB2_GRP1_TIM8_STOP ); } #endif LL_TIM_ClearFlag_BRK(TIMx); LL_TIM_EnableIT_BRK( TIMx ); /* Enable PWM channel */ LL_TIM_CC_EnableChannel( TIMx, TIMxCCER_MASK_CH123 ); /* ADC Enable (must be done after calibration) */ LL_ADC_Enable( ADCx ); /* reset regular conversion sequencer length set by cubeMX */ LL_ADC_REG_SetSequencerLength( ADCx, LL_ADC_REG_SEQ_SCAN_DISABLE ); /* ADCx Injected conversions end interrupt enabling */ LL_ADC_ClearFlag_JEOS( ADCx ); LL_ADC_EnableIT_JEOS( ADCx ); pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_RISING; /* reset injected conversion sequencer length set by cubeMX */ LL_ADC_INJ_SetSequencerLength( ADCx, LL_ADC_INJ_SEQ_SCAN_DISABLE ); /* Clear the flags */ pHandle->_Super.DTTest = 0u; } } /* * @brief Stores in @p pHdl handler the calibrated @p offsets. * */ __weak void R3_1_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 pHandle->PhaseAOffset = offsets->phaseAOffset; pHandle->PhaseBOffset = offsets->phaseBOffset; pHandle->PhaseCOffset = offsets->phaseCOffset; pHdl->offsetCalibStatus = true; } /* * @brief Reads the calibrated @p offsets stored in @p pHdl. * */ __weak void R3_1_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 offsets->phaseAOffset = pHandle->PhaseAOffset; offsets->phaseBOffset = pHandle->PhaseBOffset; offsets->phaseCOffset = pHandle->PhaseCOffset; } /* * @brief Stores into the @p pHdl the voltage present on Ia and Ib current * feedback analog channels when no current is flowing into the motor. * */ __weak void R3_1_CurrentReadingCalibration(PWMC_Handle_t *pHdl) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; TIM_TypeDef* TIMx = pHandle->pParams_str->TIMx; if (false == pHandle->_Super.offsetCalibStatus) { volatile PWMC_GetPhaseCurr_Cb_t GetPhaseCurrCbSave; volatile PWMC_SetSampPointSectX_Cb_t SetSampPointSectXCbSave; /* Save callback routines */ GetPhaseCurrCbSave = pHandle->_Super.pFctGetPhaseCurrents; SetSampPointSectXCbSave = pHandle->_Super.pFctSetADCSampPointSectX; pHandle->PhaseAOffset = 0u; pHandle->PhaseBOffset = 0u; pHandle->PhaseCOffset = 0u; pHandle->PolarizationCounter = 0u; /* It forces inactive level on TIMx CHy and CHyN */ LL_TIM_CC_DisableChannel(TIMx, TIMxCCER_MASK_CH123); /* Offset calibration for A & B phases */ /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R3_1_HFCurrentsCalibrationAB; pHandle->_Super.pFctSetADCSampPointSectX = &R3_1_SetADCSampPointCalibration; pHandle->CalibSector = SECTOR_5; /* Required to force first polarization conversion on SECTOR_5*/ pHandle->_Super.Sector = SECTOR_5; R3_1_SwitchOnPWM( &pHandle->_Super ); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd( TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter ); R3_1_SwitchOffPWM( &pHandle->_Super ); /* Offset calibration for C phase */ /* Reset PolarizationCounter */ pHandle->PolarizationCounter = 0u; /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R3_1_HFCurrentsCalibrationC; /* "Phase C current calibration to verify" */ pHandle->CalibSector = SECTOR_1; /* Required to force first polarization conversion on SECTOR_1*/ pHandle->_Super.Sector = SECTOR_1; R3_1_SwitchOnPWM( &pHandle->_Super ); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd( TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter ); R3_1_SwitchOffPWM( &pHandle->_Super ); /* Shift of N bits to divide for the NB_ CONVERSIONS = 16= 2^N with N = 4 */ pHandle->PhaseAOffset >>= 3; pHandle->PhaseBOffset >>= 3; pHandle->PhaseCOffset >>= 3; if (0U == pHandle->_Super.SWerror) { pHandle->_Super.offsetCalibStatus = true; } else { /* nothing to do */ } /* Change back function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = GetPhaseCurrCbSave; pHandle->_Super.pFctSetADCSampPointSectX = SetSampPointSectXCbSave; } /* It over write TIMx CCRy wrongly written by FOC during calibration so as to force 50% duty cycle on the three inverer legs */ /* Disable TIMx preload */ __LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH1); __LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH2); __LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH3); LL_TIM_OC_SetCompareCH1 (TIMx,pHandle->Half_PWMPeriod); LL_TIM_OC_SetCompareCH2 (TIMx,pHandle->Half_PWMPeriod); LL_TIM_OC_SetCompareCH3 (TIMx,pHandle->Half_PWMPeriod); /* Enable TIMx preload */ __LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH1); __LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH2); __LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH3); /* It re-enable drive of TIMx CHy and CHyN by TIMx CHyRef*/ LL_TIM_CC_EnableChannel(TIMx, TIMxCCER_MASK_CH123); /* sector and phase sequence for the switch on phase */ pHandle->_Super.Sector = SECTOR_5; pHandle->_Super.BrakeActionLock = false; } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section (".ccmram"))) #endif #endif /* * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p Iab ab_t format. * */ __weak void R3_1_GetPhaseCurrents(PWMC_Handle_t *pHdl, ab_t* pStator_Currents) { PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; int32_t wAux; uint16_t hReg1; uint16_t hReg2; uint8_t bSector; /* disable ADC trigger source */ LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); bSector = ( uint8_t )( pHandle->_Super.Sector ); hReg1 = (ADCx->JDR1)*2; hReg2 = (ADCx->JDR2)*2; switch ( bSector ) { case SECTOR_4: case SECTOR_5: { /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ wAux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( hReg1 ); /* Saturation of Ia */ if ( wAux < -INT16_MAX ) { pStator_Currents->a = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->a = INT16_MAX; } else { pStator_Currents->a = ( int16_t )wAux; } /* Ib = PhaseBOffset - ADC converted value) */ wAux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( hReg2 ); /* Saturation of Ib */ if ( wAux < -INT16_MAX ) { pStator_Currents->b = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->b = INT16_MAX; } else { pStator_Currents->b = ( int16_t )wAux; } } break; case SECTOR_6: case SECTOR_1: { /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ wAux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( hReg1 ); /* Saturation of Ib */ if ( wAux < -INT16_MAX ) { pStator_Currents->b = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->b = INT16_MAX; } else { pStator_Currents->b = ( int16_t )wAux; } /* Ic = PhaseCOffset - ADC converted value) */ /* Ia = -Ic -Ib */ wAux = ( int32_t )( pHandle->PhaseCOffset ) - ( int32_t )( hReg2 ); wAux = -wAux - ( int32_t )pStator_Currents->b; /* Saturation of Ia */ if ( wAux > INT16_MAX ) { pStator_Currents->a = INT16_MAX; } else if ( wAux < -INT16_MAX ) { pStator_Currents->a = -INT16_MAX; } else { pStator_Currents->a = ( int16_t )wAux; } } break; case SECTOR_2: case SECTOR_3: { /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ wAux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( hReg1 ); /* Saturation of Ia */ if ( wAux < -INT16_MAX ) { pStator_Currents->a = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->a = INT16_MAX; } else { pStator_Currents->a = ( int16_t )wAux; } /* Ic = PhaseCOffset - ADC converted value) */ /* Ib = -Ic -Ia */ wAux = ( int32_t )( pHandle->PhaseCOffset ) - ( int32_t )( hReg2 ); wAux = -wAux - ( int32_t )pStator_Currents->a; /* Saturation of Ib */ if ( wAux > INT16_MAX ) { pStator_Currents->b = INT16_MAX; } else if ( wAux < -INT16_MAX ) { pStator_Currents->b = -INT16_MAX; } else { pStator_Currents->b = ( int16_t )wAux; } } break; default: { } break; } pHandle->_Super.Ia = pStator_Currents->a; pHandle->_Super.Ib = pStator_Currents->b; pHandle->_Super.Ic = -pStator_Currents->a - pStator_Currents->b; } /* * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p Iab ab_t format. Specific to overmodulation. * */ __weak void R3_1_GetPhaseCurrents_OVM( PWMC_Handle_t * pHdl, ab_t * Iab ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; uint8_t Sector; int32_t Aux; uint32_t ADCDataReg1; uint32_t ADCDataReg2; /* disable ADC trigger source */ LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); Sector = ( uint8_t )pHandle->_Super.Sector; ADCDataReg1 = ADCx->JDR1 * 2; ADCDataReg2 = ADCx->JDR2 * 2; switch ( Sector ) { case SECTOR_4: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { // Ib not available, use estimated Ib Aux = ( int32_t )( pHandle->_Super.IbEst ); } else { /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg2 ); } /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_5: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { // Ia not available, use estimated Ia Aux = ( int32_t )( pHandle->_Super.IaEst ); } else { Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg2 ); /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_6: /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IcEst ; /* -Ic */ Aux -= ( int32_t )Iab->b; } else { /* Ia = -Ic -Ib */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->b; /* Ia */ } /* Saturation of Ia */ if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else { Iab->a = ( int16_t )Aux; } break; case SECTOR_1: /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IbEst; } else { Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } /* Ia = -Ic -Ib */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->b; /* Ia */ /* Saturation of Ia */ if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else { Iab->a = ( int16_t )Aux; } break; case SECTOR_2: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IaEst; } else { Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } /* Ib = -Ic -Ia */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ /* Saturation of Ib */ if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_3: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { /* Ib = -Ic -Ia */ Aux = ( int32_t ) pHandle->_Super.IcEst; /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ } else { /* Ib = -Ic -Ia */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ } /* Saturation of Ib */ if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; default: break; } pHandle->_Super.Ia = Iab->a; pHandle->_Super.Ib = Iab->b; pHandle->_Super.Ic = -Iab->a - Iab->b; } /* * @brief Implementation of PWMC_GetPhaseCurrents to be performed during calibration. * * It sums up injected conversion data into PhaseAOffset and wPhaseBOffset * to compute the offset introduced in the current feedback network. It is required to * properly configure ADC inputs before in order to enable offset computation. * * @param pHdl: Pointer on the target component instance. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ __weak void R3_1_HFCurrentsCalibrationAB( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { PWMC_R3_1_Handle_t * pHandle = (PWMC_R3_1_Handle_t *) pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; /* disable ADC trigger source */ LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); if ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { pHandle->PhaseAOffset += ADCx->JDR1; pHandle->PhaseBOffset += ADCx->JDR2; pHandle->PolarizationCounter++; } /* during offset calibration no current is flowing in the phases */ pStator_Currents->a = 0; pStator_Currents->b = 0; } /* * @brief Implementation of PWMC_GetPhaseCurrents to be performed during calibration. * * It sums up injected conversion data into PhaseCOffset to compute the offset * introduced in the current feedback network. It is required to properly configure * ADC inputs before in order to enable offset computation. * * @param pHdl: Pointer on the target component instance. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ __weak void R3_1_HFCurrentsCalibrationC(PWMC_Handle_t *pHdl, ab_t* pStator_Currents) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; /* disable ADC trigger source */ LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); if ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { pHandle->PhaseCOffset += ADCx->JDR2; pHandle->PolarizationCounter++; } /* during offset calibration no current is flowing in the phases */ pStator_Currents->a = 0; pStator_Currents->b = 0; } /* * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors of driving section. It has to be * called each motor start-up when using high voltage drivers. * * @param pHdl: Handler of the current instance of the PWM component * @param ticks: Timer ticks value to be applied * Min value: 0 (low sides ON) * Max value: PWM_PERIOD_CYCLES/2 (low sides OFF) */ __weak void R3_1_TurnOnLowSides(PWMC_Handle_t *pHdl, uint32_t ticks) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; TIM_TypeDef* TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = true; /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE(TIMx); /*Turn on the three low side switches */ LL_TIM_OC_SetCompareCH1( TIMx, 0 ); LL_TIM_OC_SetCompareCH2( TIMx, 0 ); LL_TIM_OC_SetCompareCH3( TIMx, 0 ); /* Wait until next update */ while (LL_TIM_IsActiveFlag_UPDATE(TIMx) == 0) {} LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs(TIMx); if ((pHandle->_Super.LowSideOutputs)== ES_GPIO) { /* Enable signals activation */ LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } return; } /* * @brief Enables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_1_SwitchOnPWM(PWMC_Handle_t *pHdl) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; TIM_TypeDef* TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = false; /* Set all duty to 50% */ LL_TIM_OC_SetCompareCH1(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH2(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH3(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH4(TIMx, (uint32_t)(pHandle->Half_PWMPeriod - 5u)); /* wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE(TIMx); while (LL_TIM_IsActiveFlag_UPDATE(TIMx) == 0) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE(TIMx); /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE; LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { if ((TIMx->CCER & TIMxCCER_MASK_CH123) != 0u) { LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } } /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Enable Update IRQ */ LL_TIM_EnableIT_UPDATE( TIMx ); return; } /* * @brief Disables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_1_SwitchOffPWM(PWMC_Handle_t *pHdl) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; TIM_TypeDef* TIMx = pHandle->pParams_str->TIMx; /* Disable UPDATE ISR */ LL_TIM_DisableIT_UPDATE( TIMx ); pHandle->_Super.TurnOnLowSidesAction = false; /* Main PWM Output Disable */ LL_TIM_DisableAllOutputs(TIMx); if (pHandle->_Super.BrakeActionLock == true) { } else { if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } } /* wait for a new PWM period to flush last HF task */ LL_TIM_ClearFlag_UPDATE(TIMx); while (LL_TIM_IsActiveFlag_UPDATE(TIMx) == 0) {} LL_TIM_ClearFlag_UPDATE(TIMx); return; } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section (".ccmram"))) #endif #endif /* * @brief Writes into peripheral registers the new duty cycles and sampling point. * * @param pHdl: Handler of the current instance of the PWM component. * @param hCCR4Reg: New capture/compare register value, written in timer clock counts. * @retval Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ __weak uint16_t R3_1_WriteTIMRegisters(PWMC_Handle_t *pHdl, uint16_t hCCR4Reg) { uint16_t hAux; PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; TIM_TypeDef* TIMx = pHandle->pParams_str->TIMx; LL_TIM_OC_SetCompareCH1 (TIMx,pHandle->_Super.CntPhA); LL_TIM_OC_SetCompareCH2 (TIMx,pHandle->_Super.CntPhB); LL_TIM_OC_SetCompareCH3 (TIMx,pHandle->_Super.CntPhC); LL_TIM_OC_SetCompareCH4 (TIMx,hCCR4Reg); /* Limit for update event */ /* Check the status flag. If an update event has occurred before to set new values of regs the FOC rate is too high */ if ( LL_TIM_CC_IsEnabledChannel(TIMx, LL_TIM_CHANNEL_CH4)) { hAux = MC_DURATION; } else { hAux = MC_NO_ERROR; } if ( pHandle->_Super.SWerror == 1u ) { hAux = MC_DURATION; pHandle->_Super.SWerror = 0u; } return hAux; } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section (".ccmram"))) #endif #endif /* * @brief Configures the ADC for the current sampling during calibration. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ __weak uint16_t R3_1_SetADCSampPointCalibration(PWMC_Handle_t *pHdl) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_RISING; pHandle->_Super.Sector = pHandle->CalibSector; return R3_1_WriteTIMRegisters(&pHandle->_Super, (uint16_t)(pHandle->Half_PWMPeriod) - 1u); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section (".ccmram"))) #endif #endif /* * @brief Configures the ADC for the current sampling related to sector X (X = [1..6] ). * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ __weak uint16_t R3_1_SetADCSampPointSectX( PWMC_Handle_t * pHdl ) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; uint16_t hCntSmp; uint16_t hDeltaDuty; register uint16_t lowDuty = pHdl->lowDuty; register uint16_t midDuty = pHdl->midDuty; /* Check if sampling AB in the middle of PWM is possible */ if ( ( uint16_t )( pHandle->Half_PWMPeriod - lowDuty ) > pHandle->pParams_str->hTafter ) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled which corresponds * to sector 5 */ pHandle->_Super.Sector = SECTOR_5; /* set sampling point trigger in the middle of PWM period */ hCntSmp = ( uint32_t )( pHandle->Half_PWMPeriod ) - 1u; } else { /* ADC Injected sequence configuration. The stator phase with minimum value of complementary duty cycle is set as first. In every sector there is always one phase with maximum complementary duty, one with minimum complementary duty and one with variable complementary duty. In this case, phases with variable complementary duty and with maximum duty are converted and the first will be always the phase with variable complementary duty cycle */ /* Crossing Point Searching */ hDeltaDuty = ( uint16_t )( lowDuty - midDuty ); /* Definition of crossing point */ if ( hDeltaDuty > ( uint16_t )( pHandle->Half_PWMPeriod - lowDuty ) * 2u ) { /* hTbefore = 2*Ts + Tc, where Ts = Sampling time of ADC, Tc = Conversion Time of ADC */ hCntSmp = lowDuty - pHandle->pParams_str->hTbefore; } else { /* hTafter = DT + max(Trise, Tnoise) */ hCntSmp = lowDuty + pHandle->pParams_str->hTafter; if ( hCntSmp >= pHandle->Half_PWMPeriod ) { /* It must be changed the trigger direction from positive to negative to sample after middle of PWM*/ pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_FALLING; hCntSmp = ( 2u * pHandle->Half_PWMPeriod ) - hCntSmp - 1u; } } } return R3_1_WriteTIMRegisters( &pHandle->_Super, hCntSmp); } /* * @brief Configures the ADC for the current sampling related to sector X (X = [1..6] ) in case of overmodulation. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ uint16_t R3_1_SetADCSampPointSectX_OVM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ uint16_t SamplingPoint; uint16_t DeltaDuty; pHandle->_Super.useEstCurrent = false; DeltaDuty = ( uint16_t )( pHdl->lowDuty - pHdl->midDuty ); /* case 1 (cf user manual) */ if (( uint16_t )( pHandle->Half_PWMPeriod - pHdl->lowDuty ) > pHandle->pParams_str->hTafter) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled which corresponds * to sector 4 or 5 */ pHandle->_Super.Sector = SECTOR_5; /* set sampling point trigger in the middle of PWM period */ SamplingPoint = pHandle->Half_PWMPeriod - (uint16_t) 1; } else /* case 2 (cf user manual) */ { if (DeltaDuty >= pHandle->pParams_str->Tcase2) { SamplingPoint = pHdl->lowDuty - pHandle->pParams_str->hTbefore; } else { /* case 3 (cf user manual) */ if ((pHandle->Half_PWMPeriod - pHdl->lowDuty) > pHandle->pParams_str->Tcase3) { /* ADC trigger edge must be changed from positive to negative */ pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_FALLING; SamplingPoint = pHdl->lowDuty + pHandle->pParams_str->Tsampling; } else { SamplingPoint = pHandle->Half_PWMPeriod-1; pHandle->_Super.useEstCurrent = true; } } } return R3_1_WriteTIMRegisters( &pHandle->_Super, SamplingPoint ); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section (".ccmram"))) #endif #endif /* * @brief Contains the TIMx Update event interrupt. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void *R3_1_TIMx_UP_IRQHandler(PWMC_R3_1_Handle_t *pHandle) { TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; /* reset ADC external trigger edge */ LL_ADC_INJ_StopConversionExtTrig(ADCx); ADCx->JSQR = pHandle->pParams_str->ADCConfig[pHandle->_Super.Sector]; /* enable ADC trigger source */ LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH4); /* set ADC external trigger edge */ LL_ADC_INJ_StartConversionExtTrig(ADCx, pHandle->ADCTriggerEdge); /* reset default edge detection trigger */ pHandle->ADCTriggerEdge = LL_ADC_INJ_TRIG_EXT_RISING; return &( pHandle->_Super.Motor ); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section (".ccmram"))) #endif #endif /* * @brief Sets the PWM mode for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_1_RLDetectionModeEnable(PWMC_Handle_t *pHdl) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; TIM_TypeDef* TIMx = pHandle->pParams_str->TIMx; if (pHandle->_Super.RLDetectionMode == false) { /* Channel1 configuration */ LL_TIM_OC_SetMode(TIMx, LL_TIM_CHANNEL_CH1, LL_TIM_OCMODE_PWM1); LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH1); LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH1N); LL_TIM_OC_SetCompareCH1(TIMx, 0u); /* Channel2 configuration */ if ((pHandle->_Super.LowSideOutputs)== LS_PWM_TIMER) { LL_TIM_OC_SetMode(TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_ACTIVE); LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH2); LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH2N); } else if ((pHandle->_Super.LowSideOutputs)== ES_GPIO) { LL_TIM_OC_SetMode(TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_INACTIVE); LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH2); LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH2N); } else { } /* Channel3 configuration */ LL_TIM_OC_SetMode(TIMx, LL_TIM_CHANNEL_CH3, LL_TIM_OCMODE_PWM2); LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH3); LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH3N); } pHandle->_Super.pFctGetPhaseCurrents = &R3_1_RLGetPhaseCurrents; pHandle->_Super.pFctTurnOnLowSides = &R3_1_RLTurnOnLowSides; pHandle->_Super.pFctSwitchOnPwm = &R3_1_RLSwitchOnPWM; pHandle->_Super.pFctSwitchOffPwm = &R3_1_SwitchOffPWM; pHandle->_Super.RLDetectionMode = true; } /* * @brief Disables the PWM mode for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_1_RLDetectionModeDisable(PWMC_Handle_t *pHdl) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; TIM_TypeDef* TIMx = pHandle->pParams_str->TIMx; if (pHandle->_Super.RLDetectionMode == true) { /* Repetition Counter of TIM1 User value reactivation BEGIN*/ /* The folowing while cycles ensure the identification of the positive counting mode of TIM1 * for correct reactivation of Repetition Counter value of TIM1.*/ /* Wait the change of Counter Direction of TIM1 from Up-Direction to Down-Direction*/ while ((TIMx->CR1 & DIR_MASK) == 0u) { } /* Wait the change of Counter Direction of TIM1 from Down-Direction to Up-Direction.*/ while ((TIMx->CR1 & DIR_MASK) == DIR_MASK) { } /* TIM1 Repetition Counter reactivation to the User Value */ TIMx->RCR = pHandle->pParams_str->RepetitionCounter; /* Repetition Counter of TIM1 User value reactivation END*/ /* Channel1 configuration */ LL_TIM_OC_SetMode(TIMx, LL_TIM_CHANNEL_CH1, LL_TIM_OCMODE_PWM1); LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH1); if ((pHandle->_Super.LowSideOutputs)== LS_PWM_TIMER) { LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH1N); } else if ((pHandle->_Super.LowSideOutputs)== ES_GPIO) { LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH1N); } else { } LL_TIM_OC_SetCompareCH1(TIMx, (uint32_t)(pHandle->Half_PWMPeriod) >> 1); /* Channel2 configuration */ LL_TIM_OC_SetMode(TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_PWM1); LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH2); if ((pHandle->_Super.LowSideOutputs)== LS_PWM_TIMER) { LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH2N); } else if ((pHandle->_Super.LowSideOutputs)== ES_GPIO) { LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH2N); } else { } LL_TIM_OC_SetCompareCH2(TIMx, (uint32_t)(pHandle->Half_PWMPeriod) >> 1); /* Channel3 configuration */ LL_TIM_OC_SetMode(TIMx, LL_TIM_CHANNEL_CH3, LL_TIM_OCMODE_PWM1); LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH3); if ((pHandle->_Super.LowSideOutputs)== LS_PWM_TIMER) { LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH3N); } else if ((pHandle->_Super.LowSideOutputs)== ES_GPIO) { LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH3N); } else { } LL_TIM_OC_SetCompareCH3(TIMx, (uint32_t)(pHandle->Half_PWMPeriod) >> 1); /* ADCx Injected discontinuous mode disable */ LL_ADC_INJ_SetSequencerDiscont(pHandle->pParams_str->ADCx, LL_ADC_INJ_SEQ_DISCONT_DISABLE); pHandle->_Super.pFctGetPhaseCurrents = &R3_1_GetPhaseCurrents; pHandle->_Super.pFctTurnOnLowSides = &R3_1_TurnOnLowSides; pHandle->_Super.pFctSwitchOnPwm = &R3_1_SwitchOnPWM; pHandle->_Super.pFctSwitchOffPwm = &R3_1_SwitchOffPWM; pHandle->_Super.RLDetectionMode = false; } } /* * @brief Sets the PWM dutycycle for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. * @param hDuty: Duty cycle to apply, written in uint16_t. * @retval Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ uint16_t R3_1_RLDetectionModeSetDuty(PWMC_Handle_t *pHdl, uint16_t hDuty) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint32_t val; uint16_t hAux; val = ( ( uint32_t )( pHandle->Half_PWMPeriod ) * ( uint32_t )( hDuty ) ) >> 16; pHandle->_Super.CntPhA = ( uint16_t )( val ); /* set sector in order to sample phase B */ pHandle->_Super.Sector = SECTOR_4; /* TIM1 Channel 1 Duty Cycle configuration. * In RL Detection mode only the Up-side device of Phase A are controlled*/ LL_TIM_OC_SetCompareCH1(TIMx, ( uint32_t )pHandle->_Super.CntPhA); /* Limit for update event */ /* Check the status flag. If an update event has occurred before to set new values of regs the FOC rate is too high */ if ( LL_TIM_CC_IsEnabledChannel(TIMx, LL_TIM_CHANNEL_CH4)) { hAux = MC_DURATION; } else { hAux = MC_NO_ERROR; } if (pHandle->_Super.SWerror == 1u) { hAux = MC_DURATION; pHandle->_Super.SWerror = 0u; } return hAux; } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section (".ccmram"))) #endif #endif /* * @brief Computes and stores into @p pHandle latest converted motor phase currents * during RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ void R3_1_RLGetPhaseCurrents(PWMC_Handle_t *pHdl,ab_t* pStator_Currents) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; int32_t wAux; /* disable ADC trigger source */ LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); wAux = (int32_t)( pHandle->PhaseBOffset ) - (int32_t)((ADCx->JDR2)*2u); /* Check saturation */ if (wAux > -INT16_MAX) { if (wAux < INT16_MAX) { } else { wAux = INT16_MAX; } } else { wAux = -INT16_MAX; } /* First value read of Phase B*/ pStator_Currents->a = ( int16_t )( wAux ); pStator_Currents->b = ( int16_t )( wAux ); } /* * @brief Turns on low sides switches. * * This function is used for charging boot capacitors * of driving section. It has to be called at each motor start-up when * using high voltage drivers. * This function is specific for RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. * @param ticks: Duty cycle of the boot capacitors charge, specific to motor. */ void R3_1_RLTurnOnLowSides(PWMC_Handle_t *pHdl, uint32_t ticks) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; TIM_TypeDef* TIMx = pHandle->pParams_str->TIMx; /*Turn on the phase A low side switch */ LL_TIM_OC_SetCompareCH1(TIMx, 0u); /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Wait until next update */ while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs(TIMx); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } return; } /* * @brief Enables PWM generation on the proper Timer peripheral. * * This function is specific for RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_1_RLSwitchOnPWM(PWMC_Handle_t *pHdl) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; TIM_TypeDef* TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; pHandle->_Super.TurnOnLowSidesAction = false; /* The following while cycles ensure the identification of the nergative counting mode of TIM1 * for correct modification of Repetition Counter value of TIM1.*/ /* Wait the change of Counter Direction of TIM1 from Down-Direction to Up-Direction*/ while ( ( TIMx->CR1 & DIR_MASK ) == DIR_MASK ) { } /* Wait the change of Counter Direction of TIM1 from Up-Direction to Down-Direction*/ while ( ( TIMx->CR1 & DIR_MASK ) == 0u ) { } /* Set channel 1 Compare/Capture register to 1 */ LL_TIM_OC_SetCompareCH1(TIMx, 1u); /* Set channel 4 Compare/Capture register to trig ADC in the middle of the PWM period */ LL_TIM_OC_SetCompareCH4(TIMx,(( uint32_t )( pHandle->Half_PWMPeriod ) - 5u)); LL_TIM_ClearFlag_UPDATE( TIMx ); /* Clear flag to wait next update */ while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE; LL_TIM_EnableAllOutputs(TIMx); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { if ((TIMx->CCER & TIMxCCER_MASK_CH123) != 0u) { LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } } /* Clear JEOC Flag */ LL_ADC_ClearFlag_JEOS(ADCx); /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* enable TIMx update interrupt*/ LL_TIM_EnableIT_UPDATE( TIMx ); return; } /* * @brief Turns on low sides switches and start ADC triggering. * * This function is specific for MP phase. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_1_RLTurnOnLowSidesAndStart( PWMC_Handle_t * pHdl ) { PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); LL_TIM_OC_SetCompareCH1 ( TIMx, 0x0u ); LL_TIM_OC_SetCompareCH2 ( TIMx, 0x0u ); LL_TIM_OC_SetCompareCH3 ( TIMx, 0x0u ); LL_TIM_OC_SetCompareCH4( TIMx, ( pHandle->Half_PWMPeriod - 5u)); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE ; LL_TIM_EnableAllOutputs ( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } // ADCx->JSQR = pHandle->wADC_JSQR_phAB; LL_ADC_INJ_StartConversionExtTrig(ADCx,LL_ADC_INJ_TRIG_EXT_RISING); return; } /** * @brief Sets ADC sampling points. * * This function is specific for MP phase. Specific to F4XX. * * @param pHdl: Handler of the current instance of the PWM component. */ void RLSetADCSampPoint( PWMC_Handle_t * pHdl ) { PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; /* dummy sector setting to get correct Ia value */ pHdl->Sector = SECTOR_5; // ADCx->JSQR = pHandle->wADC_JSQR_phAB; LL_ADC_INJ_StartConversionExtTrig(ADCx,LL_ADC_INJ_TRIG_EXT_RISING); return; } /** * @} */ /** * @} */ /** * @} */ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
50,313
C
29.437992
143
0.614016
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/F4xx/Src/ics_f4xx_pwm_curr_fdbk.c
/** ****************************************************************************** * @file ics_f4xx_pwm_curr_fdbk.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement the ICS * PWM current feedback component for F4xx of the Motor Control SDK. ******************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup ICS_F4XX_pwm_curr_fdbk */ /* Includes ------------------------------------------------------------------*/ #include "ics_f4xx_pwm_curr_fdbk.h" #include "pwm_common.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup ICS_pwm_curr_fdbk * @{ */ #define TIMxCCER_MASK_CH123 (LL_TIM_CHANNEL_CH1 | LL_TIM_CHANNEL_CH1N | LL_TIM_CHANNEL_CH2| LL_TIM_CHANNEL_CH2N |\ LL_TIM_CHANNEL_CH3 | LL_TIM_CHANNEL_CH3N) #define CONV_STARTED ((uint32_t) (0x8)) #define CONV_FINISHED ((uint32_t) (0xC)) #define FLAGS_CLEARED ((uint32_t) (0x0)) #define ADC_SR_MASK ((uint32_t) (0xC)) void ICS_HFCurrentsCalibration( PWMC_Handle_t * pHandle, ab_t * pStator_Currents ); /* * @brief Initializes TIMx, ADC, GPIO and NVIC for current reading * in ICS configuration using STM32F30X. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void ICS_Init( PWMC_ICS_Handle_t * pHandle ) { TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; if ( ( uint32_t )pHandle == ( uint32_t )&pHandle->_Super ) { /* disable main TIM counter to ensure * a synchronous start by TIM2 trigger */ LL_TIM_DisableCounter( TIMx ); LL_TIM_ClearFlag_BRK( TIMx ); LL_TIM_EnableIT_BRK( TIMx ); /* Prepare timer for synchronization */ LL_TIM_GenerateEvent_UPDATE( TIMx ); if ( pHandle->pParams_str->FreqRatio == 2u ) { if ( pHandle->pParams_str->IsHigherFreqTim == HIGHER_FREQ ) { if ( pHandle->pParams_str->RepetitionCounter == 3u ) { /* Set TIMx repetition counter to 1 */ LL_TIM_SetRepetitionCounter( TIMx, 1u ); LL_TIM_GenerateEvent_UPDATE( TIMx ); /* Repetition counter will be set to 3 at next Update */ LL_TIM_SetRepetitionCounter( TIMx, 3 ); } } LL_TIM_SetCounter( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) - 1u ); } else /* FreqRatio equal to 1 or 3 */ { if ( pHandle->pParams_str->InstanceNbr == 1u ) { LL_TIM_SetCounter( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) - 1u ); } } /* Enable PWM channel */ LL_TIM_CC_EnableChannel( TIMx, TIMxCCER_MASK_CH123 ); if ( pHandle->pParams_str->TIMx == TIM1 ) { /* TIM1 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph( LL_DBGMCU_APB2_GRP1_TIM1_STOP ); pHandle->ADCTriggerSet = LL_ADC_INJ_TRIG_EXT_TIM1_CH4; } else { /* TIM8 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph( LL_DBGMCU_APB2_GRP1_TIM8_STOP ); pHandle->ADCTriggerSet = LL_ADC_INJ_TRIG_EXT_TIM8_CH4; } /* ADC1 and ADC2 registers configuration ---------------------------------*/ /* Enable ADC1 and ADC2 */ LL_ADC_Enable( ADC1 ); LL_ADC_Enable( ADC2 ); /* reset regular conversion sequencer length set by cubeMX */ LL_ADC_REG_SetSequencerLength( ADC1, LL_ADC_REG_SEQ_SCAN_DISABLE ); /* ADC1 Injected conversions end interrupt enabling */ LL_ADC_ClearFlag_JEOS( ADC1 ); LL_ADC_EnableIT_JEOS( ADC1 ); pHandle->_Super.DTTest = 0u; } } /* * @brief Stores in @p pHdl handler the calibrated @p offsets. * */ __weak void ICS_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_ICS_Handle_t *pHandle = (PWMC_ICS_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 pHandle->PhaseAOffset = offsets->phaseAOffset; pHandle->PhaseBOffset = offsets->phaseBOffset; pHdl->offsetCalibStatus = true; } /* * @brief Reads the calibrated @p offsets stored in @p pHdl. * */ __weak void ICS_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_ICS_Handle_t *pHandle = (PWMC_ICS_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 offsets->phaseAOffset = pHandle->PhaseAOffset; offsets->phaseBOffset = pHandle->PhaseBOffset; } /* * @brief Stores into the @p pHdl handler the voltage present on Ia and * Ib current feedback analog channels when no current is flowing into the * motor. * */ __weak void ICS_CurrentReadingCalibration( PWMC_Handle_t * pHdl ) { PWMC_ICS_Handle_t * pHandle = ( PWMC_ICS_Handle_t * ) pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; if (false == pHandle->_Super.offsetCalibStatus) { pHandle->PhaseAOffset = 0u; pHandle->PhaseBOffset = 0u; pHandle->PolarizationCounter = 0u; /* Force inactive level on TIMx CHy and TIMx CHyN */ LL_TIM_CC_DisableChannel( TIMx, TIMxCCER_MASK_CH123 ); /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &ICS_HFCurrentsCalibration; ICS_SwitchOnPWM( &pHandle->_Super ); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd( TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter ); ICS_SwitchOffPWM( &pHandle->_Super ); pHandle->PhaseAOffset >>= 3; pHandle->PhaseBOffset >>= 3; if (0U == pHandle->_Super.SWerror) { pHandle->_Super.offsetCalibStatus = true; } else { /* nothing to do */ } /* Change back function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &ICS_GetPhaseCurrents; } /* It over write TIMx CCRy wrongly written by FOC during calibration so as to force 50% duty cycle on the three inverer legs */ /* Disable TIMx preload */ LL_TIM_OC_DisablePreload( TIMx, LL_TIM_CHANNEL_CH1 ); LL_TIM_OC_DisablePreload( TIMx, LL_TIM_CHANNEL_CH2 ); LL_TIM_OC_DisablePreload( TIMx, LL_TIM_CHANNEL_CH3 ); LL_TIM_OC_SetCompareCH1( TIMx, pHandle->Half_PWMPeriod ); LL_TIM_OC_SetCompareCH2( TIMx, pHandle->Half_PWMPeriod ); LL_TIM_OC_SetCompareCH3( TIMx, pHandle->Half_PWMPeriod ); LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH1 ); LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH2 ); LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH3 ); /* Set back TIMx CCER register */ LL_TIM_CC_EnableChannel( TIMx, TIMxCCER_MASK_CH123 ); } /* * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p pStator_Currents ab_t format. * */ __weak void ICS_GetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { int32_t aux; uint16_t reg; PWMC_ICS_Handle_t * pHandle = ( PWMC_ICS_Handle_t * ) pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* disable ADC trigger */ LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); /* Ia = (hPhaseAOffset)-(PHASE_A_ADC_CHANNEL vale) */ reg = ( uint16_t )( ( ADC1->JDR1 ) << 1 ); aux = ( int32_t )( reg ) - ( int32_t )( pHandle->PhaseAOffset ); /* Saturation of Ia */ if ( aux < -INT16_MAX ) { pStator_Currents->a = -INT16_MAX; } else if ( aux > INT16_MAX ) { pStator_Currents->a = INT16_MAX; } else { pStator_Currents->a = ( int16_t )aux; } /* Ib = (hPhaseBOffset)-(PHASE_B_ADC_CHANNEL value) */ reg = ( uint16_t )( ( ADC2->JDR1 ) << 1 ); aux = ( int32_t )( reg ) - ( int32_t )( pHandle->PhaseBOffset ); /* Saturation of Ib */ if ( aux < -INT16_MAX ) { pStator_Currents->b = -INT16_MAX; } else if ( aux > INT16_MAX ) { pStator_Currents->b = INT16_MAX; } else { pStator_Currents->b = ( int16_t )aux; } pHandle->_Super.Ia = pStator_Currents->a; pHandle->_Super.Ib = pStator_Currents->b; pHandle->_Super.Ic = -pStator_Currents->a - pStator_Currents->b; } /* * @brief Sums up injected conversion data into wPhaseXOffset. * * It is called only during current calibration. * * @param pHdl: Handler of the current instance of the PWM component. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ __weak void ICS_HFCurrentsCalibration( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { PWMC_ICS_Handle_t * pHandle = ( PWMC_ICS_Handle_t * ) pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* disable ADC trigger */ LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH4 ); if ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { pHandle->PhaseAOffset += ADC1->JDR1; pHandle->PhaseBOffset += ADC2->JDR1; pHandle->PolarizationCounter++; } /* during offset calibration no current is flowing in the phases */ pStator_Currents->a = 0; pStator_Currents->b = 0; } /* * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors of driving section. It has to be * called on each motor start-up when using high voltage drivers. * * @param pHdl: Handler of the current instance of the PWM component. * @param ticks: Timer ticks value to be applied * Min value: 0 (low sides ON) * Max value: PWM_PERIOD_CYCLES/2 (low sides OFF) */ __weak void ICS_TurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ) { PWMC_ICS_Handle_t * pHandle = ( PWMC_ICS_Handle_t * ) pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = true; /*Turn on the three low side switches */ LL_TIM_OC_SetCompareCH1( TIMx, 0 ); LL_TIM_OC_SetCompareCH2( TIMx, 0 ); LL_TIM_OC_SetCompareCH3( TIMx, 0 ); LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == RESET ) ; /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* * @brief Enables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void ICS_SwitchOnPWM( PWMC_Handle_t * pHdl ) { PWMC_ICS_Handle_t * pHandle = ( PWMC_ICS_Handle_t * ) pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = false; /* Set all duty to 50% */ LL_TIM_OC_SetCompareCH1(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH2(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH3(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH4(TIMx, (uint32_t)(pHandle->Half_PWMPeriod - 5u)); /* wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { if ( LL_TIM_CC_IsEnabledChannel(TIMx, TIMxCCER_MASK_CH123) != 0u ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Enable Update IRQ */ LL_TIM_EnableIT_UPDATE( TIMx ); } /* * @brief Disables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void ICS_SwitchOffPWM( PWMC_Handle_t * pHdl ) { PWMC_ICS_Handle_t * pHandle = ( PWMC_ICS_Handle_t * ) pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* Disable UPDATE ISR */ LL_TIM_DisableIT_UPDATE( TIMx ); pHandle->_Super.TurnOnLowSidesAction = false; /* Main PWM Output Disable */ LL_TIM_DisableAllOutputs(TIMx); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } /* wait for a new PWM period to flush last HF task */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); return; } /* * @brief Writes into peripheral registers the new duty cycle and sampling point. * * @param pHdl: Handler of the current instance of the PWM component. * @param SamplingPoint: Point at which the ADC will be triggered, written in timer clock counts. * @retval Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ __weak uint16_t ICS_WriteTIMRegisters( PWMC_Handle_t * pHdl ) { uint16_t aux; PWMC_ICS_Handle_t * pHandle = ( PWMC_ICS_Handle_t * ) pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; LL_TIM_OC_SetCompareCH1( TIMx, pHandle->_Super.CntPhA ); LL_TIM_OC_SetCompareCH2( TIMx, pHandle->_Super.CntPhB ); LL_TIM_OC_SetCompareCH3( TIMx, pHandle->_Super.CntPhC ); /* Limit for update event */ /* Check the status of SOFOC flag. If it is set, an update event has occurred and thus the FOC rate is too high */ if ( LL_TIM_CC_IsEnabledChannel(TIMx, LL_TIM_CHANNEL_CH4)) { aux = MC_DURATION; } else { aux = MC_NO_ERROR; } return aux; } /* * @brief Contains the TIMx Update event interrupt. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void * ICS_TIMx_UP_IRQHandler( PWMC_ICS_Handle_t * pHandle ) { uint32_t adcinjflags; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; adcinjflags = ( ADC1->SR ) & ADC_SR_MASK; if ( adcinjflags == CONV_STARTED ) { do { adcinjflags = ( ADC1-> SR ) & ADC_SR_MASK; } while ( adcinjflags != CONV_FINISHED ); } else if ( adcinjflags == FLAGS_CLEARED ) { while ( ( TIMx->CNT ) < ( pHandle->pParams_str->Tw ) ) {} adcinjflags = ( ADC1-> SR ) & ADC_SR_MASK; if ( adcinjflags == CONV_STARTED ) { do { adcinjflags = ( ADC1-> SR ) & ADC_SR_MASK; } while ( adcinjflags != CONV_FINISHED ); } } else {} /* Switch Context */ /* It re-initilize AD converter in run time when using dual MC */ LL_ADC_INJ_SetTriggerSource(ADC1, pHandle->ADCTriggerSet); LL_ADC_INJ_SetTriggerSource(ADC2, pHandle->ADCTriggerSet); /* Change channels keeping equal to 1 element the sequencer lenght */ ADC1->JSQR = ( uint32_t )( pHandle->pParams_str->IaChannel ) << 15; ADC2->JSQR = ( uint32_t )( pHandle->pParams_str->IbChannel ) << 15; LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH4 ); return &( pHandle->_Super.Motor ); } /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
16,429
C
30.354962
128
0.626818
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/F4xx/Inc/r3_2_f4xx_pwm_curr_fdbk.h
/** ****************************************************************************** * @file r3_2_f4xx_pwm_curr_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * R3_2_F4XX_pwm_curr_fdbk component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup R3_2_F4XX_pwm_curr_fdbk */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __R3_2_PWM_CURR_FDBK_H #define __R3_2_PWM_CURR_FDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "pwm_curr_fdbk.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup R3_2_pwm_curr_fdbk * @{ */ /* Exported types ------------------------------------------------------- */ /* * @brief R3_2_F4XX_pwm_curr_fdbk component parameters definition */ typedef const struct { TIM_TypeDef * TIMx; /* Contains the pointer to the timer used for PWM generation. It must equal to TIM1 if M1, to TIM8 otherwise */ ADC_TypeDef *ADCDataReg1[6]; ADC_TypeDef *ADCDataReg2[6]; uint32_t ADCConfig1[6]; /* Values of JSQR for first ADC for 6 sectors. */ uint32_t ADCConfig2[6]; /* Values of JSQR for second ADC for 6 sectors. */ /* PWM generation parameters --------------------------------------------------*/ uint16_t Tw; /*!< Used for switching the context in dual MC. It contains biggest delay (expressed in counter ticks) between the counter crest and ADC latest trigger. Specific to F4XX and F7XX. */ uint16_t hTafter; /*!< Sum of dead time plus max value between rise time and noise time express in number of TIM clocks. Specific to F4XX and F7XX.*/ uint16_t hTbefore; /* Sampling time expressed in number of TIM clocks.*/ uint16_t hDeadTime; /*!< Dead time in number of TIM clock cycles. If CHxN are enabled, it must contain the dead time to be generated by the microcontroller, otherwise it expresses the maximum dead time generated by driving network. Specific to F4XX and F7XX. */ uint16_t Tsampling; /* Sampling time expressed in number of TIM clocks.*/ uint16_t Tbefore; /* Sampling time expressed in number of TIM clocks.*/ uint16_t Tcase2; /* Sampling time expressed in number of TIM clocks.*/ uint16_t Tcase3; /* Sampling time expressed in number of TIM clocks.*/ /* Dual MC parameters --------------------------------------------------------*/ uint8_t bFreqRatio; /* Used in case of dual MC to synchronize TIM1 and TIM8. It has effect only on the second instanced object and must be equal to the ratio between the two PWM frequencies (higher/lower). Supported values are 1, 2 or 3 */ uint8_t bIsHigherFreqTim; /* When bFreqRatio is greater than 1 this param is used to indicate if this instance is the one with the highest frequency. Allowed values are: HIGHER_FREQ or LOWER_FREQ */ /* PWM Driving signals initialization ----------------------------------------*/ uint8_t RepetitionCounter; /* Expresses the number of PWM periods to be elapsed before compare registers are updated again. In particular: RepetitionCounter= (2* #PWM periods)-1*/ } R3_2_Params_t; /* * @brief Handles an instance of the R3_2_F4XX_pwm_curr_fdbk component. */ typedef struct { PWMC_Handle_t _Super; /* Base component handler */ uint32_t PhaseAOffset; /* Offset of Phase A current sensing network. */ uint32_t PhaseBOffset; /* Offset of Phase B current sensing network. */ uint32_t PhaseCOffset; /* Offset of Phase C current sensing network. */ uint32_t ADC_ExternalTriggerInjected; /*!< external ADC trigger source */ uint32_t ADCTriggerEdge; /*!< Trigger edge selection. Specific to F4XX, F7XX and L4XX. */ uint16_t Half_PWMPeriod; /* Half PWM Period in timer clock counts. */ uint8_t CalibSector; /*!< Space vector sector number during calibration. Specific to F4XX, F7XX and L4XX. */ volatile uint8_t PolarizationCounter; R3_2_Params_t const *pParams_str; } PWMC_R3_2_Handle_t; /* Exported functions ------------------------------------------------------- */ /* * Initializes TIMx, ADC, GPIO, DMA1 and NVIC for current reading * in three shunt topology using STM32F30X and two ADCs. */ void R3_2_Init( PWMC_R3_2_Handle_t * pHandle ); /* * Stores into the handler the voltage present on Ia and Ib current * feedback analog channels when no current is flowing into the motor. */ void R3_2_CurrentReadingCalibration( PWMC_Handle_t * pHandle ); /* * Computes and stores in the handler the latest converted motor phase currents in ab_t format. */ void R3_2_GetPhaseCurrents( PWMC_Handle_t * pHandle,ab_t* Iab); /* * Computes and stores in the handler the latest converted motor phase currents in ab_t format. Specific to overmodulation. */ void R3_2_GetPhaseCurrents_OVM( PWMC_Handle_t * pHandle,ab_t* Iab); /* * Turns on low sides switches. */ void R3_2_TurnOnLowSides( PWMC_Handle_t * pHandle, uint32_t ticks ); /* * Enables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_2_SwitchOnPWM( PWMC_Handle_t * pHandle ); /* * Disables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_2_SwitchOffPWM( PWMC_Handle_t * pHandle ); /* * Configures the ADC for the current sampling during calibration. */ uint16_t R3_2_SetADCSampPointCalibration( PWMC_Handle_t * pHandle ); /* * Configures the ADC for the current sampling related to sector X (X = [1..6] ). */ uint16_t R3_2_SetADCSampPointSectX( PWMC_Handle_t * pHandle ); /* * Configures the ADC for the current sampling related to sector X (X = [1..6] ) in case of overmodulation. */ uint16_t R3_2_SetADCSampPointSectX_OVM( PWMC_Handle_t * pHandle ); /* * Contains the TIMx Update event interrupt. */ void *R3_2_TIMx_UP_IRQHandler( PWMC_R3_2_Handle_t * pHandle); /* * Contains the TIMx Break event interrupt. */ void *R3_2_BRK_IRQHandler(PWMC_R3_2_Handle_t *pHdl); /* * Sets the PWM mode for R/L detection. */ void R3_2_RLDetectionModeEnable( PWMC_Handle_t * pHandle ); /* * Disables the PWM mode for R/L detection. */ void R3_2_RLDetectionModeDisable( PWMC_Handle_t * pHandle ); /* * Sets the PWM dutycycle for R/L detection. */ uint16_t R3_2_RLDetectionModeSetDuty( PWMC_Handle_t * pHandle , uint16_t hDuty ); /* * Turns on low sides switches and start ADC triggering. */ void R3_2_RLTurnOnLowSidesAndStart( PWMC_Handle_t * pHandle ); /* * Sets ADC sampling points. */ void RLSetADCSampPoint( PWMC_Handle_t * pHandle ); /* * Stores in the handler the calibrated offsets. */ void R3_2_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /* * Reads the calibrated offsets stored in the handler. */ void R3_2_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*__R3_2_PWM_CURR_FDBK_H*/ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
9,189
C
36.357723
124
0.534226
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/F4xx/Inc/r3_1_f4xx_pwm_curr_fdbk.h
/** ****************************************************************************** * @file r3_1_f4xx_pwm_curr_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * R3_1_F4XX_pwm_curr_fdbk component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup R3_1_F4XX_pwm_curr_fdbk */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __R3_1_PWMCURRFDBK_H #define __R3_1_PWMCURRFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "pwm_curr_fdbk.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup R3_1_pwm_curr_fdbk * @{ */ /* Exported types ------------------------------------------------------- */ /* * @brief R3_1_F4XX_pwm_curr_fdbk component parameters definition */ typedef const struct { /* Current reading A/D Conversions initialization -----------------------------*/ ADC_TypeDef * ADCx; /* ADC peripheral to be used. */ TIM_TypeDef * TIMx; /* Timer used for PWM generation. */ uint32_t ADCConfig [6] ; /* Stores ADC sequence for the 6 sectors. */ uint16_t hTafter; /* Sum of dead time plus max value between rise time and noise time express in number of TIM clocks.*/ uint16_t hTbefore; /* Sampling time expressed in number of TIM clocks.*/ uint16_t Tsampling; /* Sampling time expressed in number of TIM clocks.*/ uint16_t Tcase2; /* Sampling time expressed in number of TIM clocks.*/ uint16_t Tcase3; /* Sampling time expressed in number of TIM clocks.*/ uint8_t RepetitionCounter; /* Expresses the number of PWM periods to be elapsed before compare registers are updated again. In particular: RepetitionCounter= (2* #PWM periods)-1*/ } R3_1_Params_t; /* * @brief This structure is used to handle an instance of the * R3_1_F4XX_pwm_curr_fdbk component. */ typedef struct { PWMC_Handle_t _Super; /* Base component handler. */ uint32_t PhaseAOffset; /* Offset of Phase A current sensing network. */ uint32_t PhaseBOffset; /* Offset of Phase B current sensing network. */ uint32_t PhaseCOffset; /* Offset of Phase C current sensing network. */ uint32_t ADC_ExternalTriggerInjected; /* External ADC trigger source. */ uint32_t ADCTriggerEdge; /**< External ADC trigger edge. Specific to F0XX, F4XX, F7XX and G0XX. */ uint16_t Half_PWMPeriod; /* Half PWM Period in timer clock counts. */ uint8_t CalibSector; /* Space vector sector number during calibration. */ volatile uint8_t PolarizationCounter; /* Number of conversions performed during the calibration phase. */ R3_1_Params_t const *pParams_str; } PWMC_R3_1_Handle_t; /* Exported functions ------------------------------------------------------- */ /* Initializes peripherals for current reading and PWM generation * in three shunts configuration using STM32F401x8 *****/ void R3_1_Init(PWMC_R3_1_Handle_t *pHandle); /* Disables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_1_SwitchOffPWM(PWMC_Handle_t *pHdl); /* * Enables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_1_SwitchOnPWM(PWMC_Handle_t *pHdl); /* * Turns on low sides switches. */ void R3_1_TurnOnLowSides(PWMC_Handle_t *pHdl, uint32_t ticks); /* * Computes and returns latest converted motor phase currents motor. */ void R3_1_GetPhaseCurrents(PWMC_Handle_t *pHdl, ab_t* pStator_Currents); /* * Computes and returns latest converted motor phase currents motor. */ void R3_1_GetPhaseCurrents_OVM(PWMC_Handle_t *pHdl, ab_t* pStator_Currents); /* * Stores into the handler the voltage present on Ia and * Ib current feedback analog channels when no current is flowing into the motor. */ void R3_1_CurrentReadingCalibration(PWMC_Handle_t *pHdl); /* * Configures the ADC for the current sampling during calibration. */ uint16_t R3_1_SetADCSampPointCalibration(PWMC_Handle_t *pHdl); /* * Configures the ADC for the current sampling related to sector X (X = [1..6] ). */ uint16_t R3_1_SetADCSampPointSectX( PWMC_Handle_t * pHdl); /* * Configures the ADC for the current sampling related to sector X (X = [1..6] ). */ uint16_t R3_1_SetADCSampPointSectX_OVM( PWMC_Handle_t * pHdl); /* * Contains the TIMx Update event interrupt. */ void * R3_1_TIMx_UP_IRQHandler( PWMC_R3_1_Handle_t * pHdl ); /* * Contains the TIMx break2 event interrupt. */ void * R3_1_BRK_IRQHandler( PWMC_R3_1_Handle_t * pHdl ); /* * Enables the PWM mode during RL Detection Mode. */ void R3_1_RLDetectionModeEnable(PWMC_Handle_t *pHdl); /* * Disables the PWM mode during RL Detection Mode. */ void R3_1_RLDetectionModeDisable(PWMC_Handle_t *pHdl); /* * Sets the PWM dutycycle for R/L detection. */ uint16_t R3_1_RLDetectionModeSetDuty(PWMC_Handle_t *pHdl, uint16_t hDuty); /* * Computes and stores in the handler the latest converted motor phase currents in ab_t format. */ void R3_1_RLGetPhaseCurrents(PWMC_Handle_t *pHdl,ab_t* pStator_Currents); /* * Turns on low sides switches and start ADC triggering. */ void R3_1_RLTurnOnLowSides(PWMC_Handle_t *pHdl, uint32_t ticks); /* * Enables PWM generation on the proper Timer peripheral. */ void R3_1_RLSwitchOnPWM(PWMC_Handle_t *pHdl); /* * Disables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_1_RLSwitchOffPWM(PWMC_Handle_t *pHdl); /* * Turns on low sides switches and start ADC triggering. */ void R3_1_RLTurnOnLowSidesAndStart( PWMC_Handle_t * pHdl ); /* * Sets ADC sampling points. */ void RLSetADCSampPoint( PWMC_Handle_t * pHdl ); /* * Sets the calibrated offset. */ void R3_1_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /* * Reads the calibrated offsets. */ void R3_1_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*__R3_1_PWMNCURRFDBK_H*/ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
7,171
C
30.047619
114
0.603263
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/F4xx/Inc/ics_f4xx_pwm_curr_fdbk.h
/** ****************************************************************************** * @file ics_f4xx_pwm_curr_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * ICS PWM current feedback component for F4XX of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup ICS_F4XX_pwm_curr_fdbk */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __ICS_F4XX_PWMNCURRFDBK_H #define __ICS_F4XX_PWMNCURRFDBK_H #include "pwm_curr_fdbk.h" #include "ics_dd_pwmncurrfdbk.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup ICS_pwm_curr_fdbk * @{ */ #define SOFOC 0x0008u /* This flag is reset at the beginning of FOC and it is set in the TIM UP IRQ. If at the end of FOC this flag is set, it means that FOC rate is too high and thus an error is generated */ /* * PWM and Current Feedback ICS handle. */ typedef struct { PWMC_Handle_t _Super; /* Base component handler. */ uint32_t PhaseAOffset; /* Offset of Phase A current sensing network. */ uint32_t PhaseBOffset; /* Offset of Phase B current sensing network. */ uint16_t Half_PWMPeriod; /* Half PWM Period in timer clock counts. */ volatile uint8_t PolarizationCounter; /* Number of conversions performed during the calibration phase. */ uint32_t ADCTriggerSet; /**< Stores the value for ADC CR2 to properly configure current sampling during the context switching. Specific to F4XX.*/ ICS_Params_t const *pParams_str; } PWMC_ICS_Handle_t; /* Exported functions ------------------------------------------------------- */ /* * Initializes TIMx, ADC, GPIO and NVIC for current reading * in ICS configuration using STM32F4XX. */ void ICS_Init( PWMC_ICS_Handle_t * pHandle ); /* * Sums up injected conversion data into wPhaseXOffset. */ void ICS_CurrentReadingCalibration( PWMC_Handle_t * pHandle ); /* * Computes and stores in the handler the latest converted motor phase currents in ab_t format. */ void ICS_GetPhaseCurrents( PWMC_Handle_t * pHandle, ab_t * pStator_Currents ); /* * Turns on low sides switches. */ void ICS_TurnOnLowSides( PWMC_Handle_t * pHandle, uint32_t ticks ); /* * Enables PWM generation on the proper Timer peripheral acting on MOE bit. */ void ICS_SwitchOnPWM( PWMC_Handle_t * pHandle ); /* * Disables PWM generation on the proper Timer peripheral acting on MOE bit. */ void ICS_SwitchOffPWM( PWMC_Handle_t * pHandle ); /* * Writes into peripheral registers the new duty cycle and sampling point. */ uint16_t ICS_WriteTIMRegisters( PWMC_Handle_t * pHandle ); /* * Contains the TIMx Update event interrupt. */ void * ICS_TIMx_UP_IRQHandler( PWMC_ICS_Handle_t * pHandle ); /* * Contains the TIMx Break1 event interrupt. */ void * ICS_BRK_IRQHandler( PWMC_ICS_Handle_t * pHdl ); /* * Stores in the handler the calibrated offsets. */ void ICS_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /* * Reads the calibrated offsets stored in the handler. */ void ICS_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*__ICS_F4XX_PWMNCURRFDBK_H*/ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
4,091
C
27.816901
107
0.612564
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/C0xx/Src/r3_c0xx_pwm_curr_fdbk.c
/** ****************************************************************************** * @file r3_c0xx_pwm_curr_fdbk.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement current sensor * class to be stantiated when the three shunts current sensing * topology is used. It is specifically designed for STM32C0XX * microcontrollers and implements the successive sampling of two motor * current using only one ADC. * + MCU peripheral and handle initialization fucntion * + three shunt current sensing * + space vector modulation function * + ADC sampling function * ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "r3_c0xx_pwm_curr_fdbk.h" #include "pwm_common.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup R3_1_pwm_curr_fdbk * @{ */ /* Private defines -----------------------------------------------------------*/ #define TIMxCCER_MASK_CH123 (LL_TIM_CHANNEL_CH1 | LL_TIM_CHANNEL_CH1N | LL_TIM_CHANNEL_CH2|LL_TIM_CHANNEL_CH2N |\ LL_TIM_CHANNEL_CH3 | LL_TIM_CHANNEL_CH3N) /* Private function prototypes -----------------------------------------------*/ void R3_1_HFCurrentsCalibrationAB( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ); void R3_1_HFCurrentsCalibrationC( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ); uint16_t R3_1_WriteTIMRegisters( PWMC_Handle_t * pHdl, uint16_t hCCR4Reg ); /* Private functions ---------------------------------------------------------*/ /* Local redefinition of both LL_TIM_OC_EnablePreload & LL_TIM_OC_DisablePreload */ __STATIC_INLINE void __LL_TIM_OC_EnablePreload(TIM_TypeDef *TIMx, uint32_t Channel) { register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); register __IO uint32_t *pReg = (__IO uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); SET_BIT(*pReg, (TIM_CCMR1_OC1PE << SHIFT_TAB_OCxx[iChannel])); } __STATIC_INLINE void __LL_TIM_OC_DisablePreload(TIM_TypeDef *TIMx, uint32_t Channel) { register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(LL_TIM_CHANNEL_CH4); register __IO uint32_t *pReg = (__IO uint32_t *)((uint32_t)((uint32_t)(&TIM1->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); CLEAR_BIT(*pReg, (TIM_CCMR1_OC1PE << SHIFT_TAB_OCxx[iChannel])); } /* * @brief Initializes TIM1, ADC1, GPIO, DMA1 and NVIC for three shunt current * reading configuration using STM32C0XX. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void R3_1_Init( PWMC_R3_1_Handle_t * pHandle ) { if ( ( uint32_t )pHandle == ( uint32_t )&pHandle->_Super ) { /* disable IT and flags in case of LL driver usage * workaround for unwanted interrupt enabling done by LL driver */ LL_ADC_DisableIT_EOC( ADC1 ); LL_ADC_ClearFlag_EOC( ADC1 ); LL_ADC_DisableIT_EOS( ADC1 ); LL_ADC_ClearFlag_EOS( ADC1 ); /* Enable the CCS */ LL_RCC_HSE_EnableCSS(); /* Peripheral clocks enabling END ----------------------------------------*/ /* Clear TIMx break flag. */ LL_TIM_ClearFlag_BRK( TIM1 ); LL_TIM_EnableIT_BRK( TIM1 ); LL_TIM_SetCounter( TIM1, ( uint32_t )( pHandle->Half_PWMPeriod ) - 1u ); /* TIM1 Counter Clock stopped when the core is halted */ LL_APB1_GRP1_EnableClock (LL_APB1_GRP1_PERIPH_DBGMCU); LL_DBGMCU_APB2_GRP1_FreezePeriph( LL_DBGMCU_APB2_GRP1_TIM1_STOP ); /* ADC Calibration */ LL_ADC_StartCalibration( ADC1 ); while ((LL_ADC_IsCalibrationOnGoing(ADC1) == SET) || (LL_ADC_REG_IsConversionOngoing(ADC1) == SET) || (LL_ADC_REG_IsStopConversionOngoing(ADC1) == SET) || (LL_ADC_IsDisableOngoing(ADC1) == SET)) { /* wait */ } /* Enables the ADC peripheral */ LL_ADC_Enable( ADC1 ); /* Wait ADC Ready */ while ( LL_ADC_IsActiveFlag_ADRDY( ADC1 ) == RESET ) { /* wait */ } /* DMA1 Channel1 Config */ LL_DMA_SetMemoryAddress( DMA1, LL_DMA_CHANNEL_1, ( uint32_t )pHandle->ADC1_DMA_converted ); LL_DMA_SetPeriphAddress( DMA1, LL_DMA_CHANNEL_1, ( uint32_t )&ADC1->DR ); LL_DMA_SetDataLength(DMA1, LL_DMA_CHANNEL_1, 3); /* Enables the DMA1 Channel1 peripheral */ LL_DMA_EnableChannel( DMA1, LL_DMA_CHANNEL_1 ); /* disable ADC source trigger */ LL_TIM_SetTriggerOutput2(TIM1, LL_TIM_TRGO2_RESET); /* Enable PWM channel */ LL_TIM_CC_EnableChannel( TIM1, TIMxCCER_MASK_CH123 ); /* set default triggering edge */ pHandle->ADCTriggerEdge = LL_ADC_REG_TRIG_EXT_RISING; /* We allow ADC usage for regular conversion on Systick*/ pHandle->ADCRegularLocked=false; pHandle->_Super.DTTest = 0u; LL_TIM_EnableCounter( TIM1 ); } } /* * @brief Stores in @p pHdl handler the calibrated @p offsets. * */ __weak void R3_1_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 pHandle->PhaseAOffset = offsets->phaseAOffset; pHandle->PhaseBOffset = offsets->phaseBOffset; pHandle->PhaseCOffset = offsets->phaseCOffset; pHdl->offsetCalibStatus = true; } /* * @brief Reads the calibrated @p offsets stored in @p pHdl. * */ __weak void R3_1_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 offsets->phaseAOffset = pHandle->PhaseAOffset; offsets->phaseBOffset = pHandle->PhaseBOffset; offsets->phaseCOffset = pHandle->PhaseCOffset; } /* * @brief Stores into the @p pHdl handler the voltage present on Ia and * Ib current feedback analog channels when no current is flowing into the * motor. * */ __weak void R3_1_CurrentReadingCalibration( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = TIM1; volatile PWMC_GetPhaseCurr_Cb_t GetPhaseCurrCbSave; volatile PWMC_SetSampPointSectX_Cb_t SetSampPointSectXCbSave; if (false == pHandle->_Super.offsetCalibStatus) { /* Save callback routines */ GetPhaseCurrCbSave = pHandle->_Super.pFctGetPhaseCurrents; SetSampPointSectXCbSave = pHandle->_Super.pFctSetADCSampPointSectX; pHandle-> PhaseAOffset = 0u; pHandle-> PhaseBOffset = 0u; pHandle-> PhaseCOffset = 0u; pHandle->PolarizationCounter = 0u; /* It forces inactive level on TIMx CHy and CHyN */ LL_TIM_CC_DisableChannel( TIMx, TIMxCCER_MASK_CH123 ); /* Offset calibration for A B c phases */ /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R3_1_HFCurrentsCalibrationAB; pHandle->_Super.pFctSetADCSampPointSectX = &R3_1_SetADCSampPointCalibration; pHandle->CalibSector = SECTOR_5; /* Mandatory to force first polarization conversion on SECTOR_5*/ pHandle->_Super.Sector = SECTOR_5; R3_1_SwitchOnPWM( &pHandle->_Super ); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd( TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter ); R3_1_SwitchOffPWM( &pHandle->_Super ); pHandle->_Super.pFctGetPhaseCurrents = &R3_1_HFCurrentsCalibrationC; pHandle->CalibSector = SECTOR_1; /* Mandatory to force first polarization conversion on SECTOR_1*/ pHandle->_Super.Sector = SECTOR_1; pHandle->PolarizationCounter = 0; R3_1_SwitchOnPWM( &pHandle->_Super ); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd( TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter ); R3_1_SwitchOffPWM( &pHandle->_Super ); /* Mean Value of PhaseCurrents Offset calculation by 4bit shifting operation * instead division by NB_CONVERSIONS value fixed to 16. */ pHandle->PhaseAOffset = pHandle->PhaseAOffset / NB_CONVERSIONS; pHandle->PhaseBOffset = pHandle->PhaseBOffset / NB_CONVERSIONS; pHandle->PhaseCOffset = pHandle->PhaseCOffset / NB_CONVERSIONS; if (0U == pHandle->_Super.SWerror) { pHandle->_Super.offsetCalibStatus = true; } else { /* nothing to do */ } /* restore function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = GetPhaseCurrCbSave; pHandle->_Super.pFctSetADCSampPointSectX = SetSampPointSectXCbSave; } /* It over write TIMx CCRy wrongly written by FOC during calibration so as to force 50% duty cycle on the three inverer legs */ /* Disable TIMx preload */ __LL_TIM_OC_DisablePreload(TIMx,LL_TIM_CHANNEL_CH1); __LL_TIM_OC_DisablePreload(TIMx,LL_TIM_CHANNEL_CH2); __LL_TIM_OC_DisablePreload(TIMx,LL_TIM_CHANNEL_CH3); LL_TIM_OC_SetCompareCH1( TIMx, pHandle->Half_PWMPeriod ); LL_TIM_OC_SetCompareCH2( TIMx, pHandle->Half_PWMPeriod ); LL_TIM_OC_SetCompareCH3( TIMx, pHandle->Half_PWMPeriod ); /* Enable TIMx preload */ __LL_TIM_OC_EnablePreload(TIMx,LL_TIM_CHANNEL_CH1); __LL_TIM_OC_EnablePreload(TIMx,LL_TIM_CHANNEL_CH2); __LL_TIM_OC_EnablePreload(TIMx,LL_TIM_CHANNEL_CH3); /* It re-enable drive of TIMx CHy and CHyN by TIMx CHyRef*/ LL_TIM_CC_EnableChannel( TIMx, TIMxCCER_MASK_CH123 ); pHandle->_Super.Sector = SECTOR_5; pHandle->_Super.BrakeActionLock = false; } /* * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p pStator_Currents ab_t format. * */ __weak void R3_1_GetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif int32_t wAux; uint16_t hReg1; uint16_t hReg2; uint8_t bSector; /* disable ADC trigger source */ LL_TIM_SetTriggerOutput2(TIM1, LL_TIM_TRGO2_RESET); bSector = ( uint8_t ) pHandle->_Super.Sector; LL_ADC_REG_SetSequencerScanDirection(ADC1, LL_ADC_REG_SEQ_SCAN_DIR_FORWARD); hReg1 = *pHandle->pParams_str->ADCDataReg1[bSector]; hReg2 = *pHandle->pParams_str->ADCDataReg2[bSector]; switch ( bSector ) { case SECTOR_4: case SECTOR_5: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) ------------------------------*/ wAux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( hReg1 ); /* Saturation of Ia */ if ( wAux < -INT16_MAX ) { pStator_Currents->a = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->a = INT16_MAX; } else { pStator_Currents->a = ( int16_t )wAux; } /* Ib = PhaseBOffset - ADC converted value) ------------------------------*/ wAux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( hReg2 ); /* Saturation of Ib */ if ( wAux < -INT16_MAX ) { pStator_Currents->b = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->b = INT16_MAX; } else { pStator_Currents->b = ( int16_t )wAux; } break; case SECTOR_6: case SECTOR_1: /* Current on Phase A is not accessible */ /* Ib = (PhaseBOffset - ADC converted value) ------------------------------*/ wAux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( hReg1 ); /* Saturation of Ib */ if ( wAux < -INT16_MAX ) { pStator_Currents->b = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->b = INT16_MAX; } else { pStator_Currents->b = ( int16_t )wAux; } /* Ic = PhaseCOffset - ADC converted value) */ /* Ia = -Ic -Ib */ wAux = ( int32_t )( pHandle->PhaseCOffset ) - ( int32_t )( hReg2 ); wAux = -wAux - ( int32_t )pStator_Currents->b; /* Saturation of Ia */ if ( wAux > INT16_MAX ) { pStator_Currents->a = INT16_MAX; } else if ( wAux < -INT16_MAX ) { pStator_Currents->a = -INT16_MAX; } else { pStator_Currents->a = ( int16_t )wAux; } break; case SECTOR_2: case SECTOR_3: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) ------------------------------*/ wAux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( hReg1 ); /* Saturation of Ia */ if ( wAux < -INT16_MAX ) { pStator_Currents->a = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->a = INT16_MAX; } else { pStator_Currents->a = ( int16_t )wAux; } /* Ic = PhaseCOffset - ADC converted value) ------------------------------*/ wAux = ( int32_t )( pHandle->PhaseCOffset ) - ( int32_t )( hReg2 ); /* Ib = -Ic -Ia */ wAux = -wAux - ( int32_t )pStator_Currents->a; /* Ib */ /* Saturation of Ib */ if ( wAux > INT16_MAX ) { pStator_Currents->b = INT16_MAX; } else if ( wAux < -INT16_MAX ) { pStator_Currents->b = -INT16_MAX; } else { pStator_Currents->b = ( int16_t )wAux; } break; default: break; } pHandle->_Super.Ia = pStator_Currents->a; pHandle->_Super.Ib = pStator_Currents->b; pHandle->_Super.Ic = -pStator_Currents->a - pStator_Currents->b; } /* * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p Iab ab_t format. Specific to overmodulation. * */ __weak void R3_1_GetPhaseCurrents_OVM( PWMC_Handle_t * pHdl, ab_t * Iab ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ uint8_t Sector; int32_t Aux; uint32_t ADCDataReg1; uint32_t ADCDataReg2; /* disable ADC trigger source */ LL_TIM_SetTriggerOutput2(TIM1, LL_TIM_TRGO2_RESET); LL_ADC_REG_SetSequencerScanDirection(ADC1, LL_ADC_REG_SEQ_SCAN_DIR_FORWARD); Sector = ( uint8_t )pHandle->_Super.Sector; ADCDataReg1 = *pHandle->pParams_str->ADCDataReg1[Sector]; ADCDataReg2 = *pHandle->pParams_str->ADCDataReg2[Sector]; switch ( Sector ) { case SECTOR_4: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { // Ib not available, use estimated Ib Aux = ( int32_t )( pHandle->_Super.IbEst ); } else { /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg2 ); } /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_5: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { // Ia not available, use estimated Ia Aux = ( int32_t )( pHandle->_Super.IaEst ); } else { Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg2 ); /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_6: /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IcEst ; /* -Ic */ Aux -= ( int32_t )Iab->b; } else { /* Ia = -Ic -Ib */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->b; /* Ia */ } /* Saturation of Ia */ if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else { Iab->a = ( int16_t )Aux; } break; case SECTOR_1: /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IbEst; } else { Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } /* Ia = -Ic -Ib */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->b; /* Ia */ /* Saturation of Ia */ if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else { Iab->a = ( int16_t )Aux; } break; case SECTOR_2: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IaEst; } else { Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } /* Ib = -Ic -Ia */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ /* Saturation of Ib */ if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_3: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { /* Ib = -Ic -Ia */ Aux = ( int32_t ) pHandle->_Super.IcEst; /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ } else { /* Ib = -Ic -Ia */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ } /* Saturation of Ib */ if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; default: break; } pHandle->_Super.Ia = Iab->a; pHandle->_Super.Ib = Iab->b; pHandle->_Super.Ic = -Iab->a - Iab->b; } /* * @brief Configures the ADC for the current sampling during calibration. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ __weak uint16_t R3_1_SetADCSampPointCalibration( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif pHandle->ADCTriggerEdge = LL_ADC_REG_TRIG_EXT_RISING; pHandle->_Super.Sector = pHandle->CalibSector; return R3_1_WriteTIMRegisters( pHdl, ( uint16_t )( pHandle->Half_PWMPeriod ) - 1u); } /* * @brief Configures the ADC for the current sampling related to sector X (X = [1..6] ). * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ __weak uint16_t R3_1_SetADCSampPointSectX( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif uint16_t hCntSmp; uint16_t hDeltaDuty; register uint16_t lowDuty = pHdl->lowDuty; register uint16_t midDuty = pHdl->midDuty; /* Check if sampling AB in the middle of PWM is possible */ if ( ( uint16_t )( pHandle->Half_PWMPeriod - lowDuty ) > pHandle->pParams_str->hTafter ) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled which corresponds * to sector 4 (could be also sector 5) */ pHandle->_Super.Sector = SECTOR_5; /* set sampling point trigger in the middle of PWM period */ hCntSmp = ( uint32_t )( pHandle->Half_PWMPeriod ) - 1u; } else { /* In this case it is necessary to convert phases with Maximum and variable complementary duty cycle.*/ /* ADC Injected sequence configuration. The stator phase with minimum value of complementary duty cycle is set as first. In every sector there is always one phase with maximum complementary duty, one with minimum complementary duty and one with variable complementary duty. In this case, phases with variable complementary duty and with maximum duty are converted and the first will be always the phase with variable complementary duty cycle */ /* Crossing Point Searching */ hDeltaDuty = ( uint16_t )( lowDuty - midDuty ); /* Definition of crossing point */ if ( hDeltaDuty > ( uint16_t )( pHandle->Half_PWMPeriod - lowDuty ) * 2u ) { hCntSmp = lowDuty - pHandle->pParams_str->hTbefore; } else { hCntSmp = lowDuty + pHandle->pParams_str->hTafter; if ( hCntSmp >= pHandle->Half_PWMPeriod ) { pHandle->ADCTriggerEdge = LL_ADC_REG_TRIG_EXT_FALLING; hCntSmp = ( 2u * pHandle->Half_PWMPeriod ) - hCntSmp - 1u; } } } return R3_1_WriteTIMRegisters( &pHandle->_Super, hCntSmp ); } /* * @brief Configures the ADC for the current sampling related to sector X (X = [1..6] ) in case of overmodulation. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ uint16_t R3_1_SetADCSampPointSectX_OVM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ uint16_t SamplingPoint; uint16_t DeltaDuty; pHandle->_Super.useEstCurrent = false; DeltaDuty = ( uint16_t )( pHdl->lowDuty - pHdl->midDuty ); /* case 1 (cf user manual) */ if (( uint16_t )( pHandle->Half_PWMPeriod - pHdl->lowDuty ) > pHandle->pParams_str->hTafter) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled which corresponds * to sector 4 or 5 */ pHandle->_Super.Sector = SECTOR_5; /* set sampling point trigger in the middle of PWM period */ SamplingPoint = pHandle->Half_PWMPeriod - (uint16_t) 1; } else /* case 2 (cf user manual) */ { if (DeltaDuty >= pHandle->pParams_str->Tcase2) { SamplingPoint = pHdl->lowDuty - pHandle->pParams_str->hTbefore; } else { /* case 3 (cf user manual) */ if ((pHandle->Half_PWMPeriod - pHdl->lowDuty) > pHandle->pParams_str->Tcase3) { /* ADC trigger edge must be changed from positive to negative */ pHandle->ADCTriggerEdge = LL_ADC_REG_TRIG_EXT_FALLING; SamplingPoint = pHdl->lowDuty + pHandle->pParams_str->Tsampling; } else { SamplingPoint = pHandle->Half_PWMPeriod-1; pHandle->_Super.useEstCurrent = true; } } } return R3_1_WriteTIMRegisters( &pHandle->_Super, SamplingPoint ); } /* * @brief Writes into peripheral registers the new duty cycles and sampling point. * * @param pHdl: Handler of the current instance of the PWM component. * @param hCCR4Reg: New capture/compare register value, written in timer clock counts. * @retval Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ __weak uint16_t R3_1_WriteTIMRegisters( PWMC_Handle_t * pHdl, uint16_t hCCR4Reg) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint16_t hAux; LL_TIM_OC_SetCompareCH1 ( TIMx, (uint32_t)pHandle->_Super.CntPhA ); LL_TIM_OC_SetCompareCH2 ( TIMx, (uint32_t)pHandle->_Super.CntPhB ); LL_TIM_OC_SetCompareCH3 ( TIMx, (uint32_t)pHandle->_Super.CntPhC ); LL_TIM_OC_SetCompareCH4 ( TIMx, (uint32_t)hCCR4Reg ); /* Re-configuration of CCR4 must be done before the timer update to be taken into account at the next PWM cycle. Otherwise we are too late, we flag a FOC_DURATION error */ if (((TIMx->CR2) & TIM_CR2_MMS2_Msk) != LL_TIM_TRGO2_RESET) { hAux = MC_DURATION; } else { hAux = MC_NO_ERROR; } if ( pHandle->_Super.SWerror == 1u ) { hAux = MC_DURATION; pHandle->_Super.SWerror = 0u; } return hAux; } /* * @brief Implementation of PWMC_GetPhaseCurrents to be performed during calibration. * * It sums up injected conversion data into PhaseAOffset and wPhaseBOffset * to compute the offset introduced in the current feedback network. It is required to * properly configure ADC inputs before in order to enable offset computation. * * @param pHdl: Pointer on the target component instance. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ __weak void R3_1_HFCurrentsCalibrationAB( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = TIM1; uint8_t bSector = pHandle->CalibSector; /* disable ADC trigger source */ LL_TIM_SetTriggerOutput2(TIMx, LL_TIM_TRGO2_RESET); if ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { pHandle->PhaseAOffset += *pHandle->pParams_str->ADCDataReg1[bSector]; pHandle->PhaseBOffset += *pHandle->pParams_str->ADCDataReg2[bSector]; pHandle->PolarizationCounter++; } /* during offset calibration no current is flowing in the phases */ pStator_Currents->a = 0; pStator_Currents->b = 0; } /* * @brief Implementation of PWMC_GetPhaseCurrents to be performed during calibration. * * It sums up injected conversion data into PhaseCOffset to compute the offset * introduced in the current feedback network. It is required to properly configure * ADC inputs before in order to enable offset computation. * * @param pHdl: Pointer on the target component instance. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ __weak void R3_1_HFCurrentsCalibrationC( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = TIM1; uint8_t bSector = pHandle->CalibSector; /* disable ADC trigger source */ LL_TIM_SetTriggerOutput2(TIMx, LL_TIM_TRGO2_RESET); pHandle->_Super.Sector = SECTOR_1; if ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { pHandle->PhaseCOffset += *pHandle->pParams_str->ADCDataReg2[bSector]; pHandle->PolarizationCounter++; } /* during offset calibration no current is flowing in the phases */ pStator_Currents->a = 0; pStator_Currents->b = 0; } /* * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors of driving section. It has to be * called each motor start-up when using high voltage drivers. * * @param pHdl: Handler of the current instance of the PWM component * @param ticks: Timer ticks value to be applied * Min value: 0 (low sides ON) * Max value: PWM_PERIOD_CYCLES/2 (low sides OFF) */ __weak void R3_1_TurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = TIM1; pHandle->_Super.TurnOnLowSidesAction = true; /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /*Turn on the three low side switches */ LL_TIM_OC_SetCompareCH1(TIMx, ticks); LL_TIM_OC_SetCompareCH2(TIMx, ticks); LL_TIM_OC_SetCompareCH3(TIMx, ticks); /* Wait until next update */ while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == RESET ) {} /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs(TIMx); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { /* Enable signals activation */ LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } return; } /* * @brief Enables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_1_SwitchOnPWM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = TIM1; pHandle->_Super.TurnOnLowSidesAction = false; /* We forbid ADC usage for regular conversion on Systick*/ pHandle->ADCRegularLocked=true; /* Set all duty to 50% */ LL_TIM_OC_SetCompareCH1(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH2(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH3(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH4(TIMx, (uint32_t)(pHandle->Half_PWMPeriod - 5u)); /* Wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == RESET ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE; LL_TIM_EnableAllOutputs(TIMx); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { if ( LL_TIM_CC_IsEnabledChannel(TIMx, TIMxCCER_MASK_CH123) != 0u ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* Configuration of DMA and ADC to next conversions */ /* It's possible write the CHSELR resgister because the ADC conversion is stopped by the R3_1_SwitchOffPWM function */ LL_ADC_SetSamplingTimeCommonChannels ( ADC1, LL_ADC_SAMPLINGTIME_COMMON_2, pHandle->pParams_str->b_ISamplingTime ); /* Setting of the DMA Buffer Size.*/ /* NOTE. This register (CNDTRx) must not be written when the DMAy Channel x is ENABLED */ LL_DMA_DisableChannel( DMA1, LL_DMA_CHANNEL_1 ); /* Write the Buffer size on CNDTR register */ LL_DMA_SetDataLength( DMA1, LL_DMA_CHANNEL_1, 2u ); /* DMA Enabling */ LL_DMA_EnableChannel( DMA1, LL_DMA_CHANNEL_1 ); /* Clear EOC */ LL_ADC_ClearFlag_EOC( ADC1 ); /* Enable ADC DMA request*/ LL_ADC_REG_SetDMATransfer( ADC1, LL_ADC_REG_DMA_TRANSFER_LIMITED ); /* Clear Pending Interrupt Bits */ LL_DMA_ClearFlag_HT1( DMA1 ); // TBC: for TC1, GL1 (not cleared ...) /* DMA Interrupt Event configuration */ LL_DMA_EnableIT_TC( DMA1, LL_DMA_CHANNEL_1 ); /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Enable Update IRQ */ LL_TIM_EnableIT_UPDATE( TIMx ); return; } /* * @brief Disables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_1_SwitchOffPWM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = TIM1; /* Enable Update IRQ */ LL_TIM_DisableIT_UPDATE( TIMx ); pHandle->_Super.TurnOnLowSidesAction = false; /* Main PWM Output Disable */ LL_TIM_DisableAllOutputs(TIMx); if ( pHandle->_Super.BrakeActionLock == true ) { } else { if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* Disabling of DMA Interrupt Event configured */ LL_DMA_DisableIT_TC( DMA1, LL_DMA_CHANNEL_1 ); LL_ADC_REG_StopConversion( ADC1 ); /* Disable ADC DMA request*/ ADC1->CFGR1 &= ~ADC_CFGR1_DMAEN; /* Clear Transmission Complete Flag of DMA1 Channel1 */ LL_DMA_ClearFlag_TC1( DMA1 ); /* Clear EOC */ LL_ADC_ClearFlag_EOC( ADC1 ); /* The ADC is not triggered anymore by the PWM timer */ LL_ADC_REG_SetTriggerSource (ADC1, LL_ADC_REG_TRIG_SOFTWARE); /* We allow ADC usage for regular conversion on Systick*/ pHandle->ADCRegularLocked=false; /* Wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == RESET ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); return; } /* * @brief Contains the TIMx Update event interrupt. * * @param pHandle: Handler of the current instance of the PWM component. */ void * R3_1_TIMx_UP_IRQHandler( PWMC_R3_1_Handle_t * pHandle ) { /* Set the trigger polarity as computed inside SetADCSampPointSectX*/ LL_ADC_REG_SetTriggerEdge (ADC1, pHandle->ADCTriggerEdge); /* set ADC trigger source */ LL_ADC_REG_SetTriggerSource(ADC1, LL_ADC_REG_TRIG_EXT_TIM1_TRGO2); /* Set scan direction according to the sector */ LL_ADC_REG_SetSequencerScanDirection(ADC1, pHandle->pParams_str->ADCScandir[pHandle->_Super.Sector]<<ADC_CFGR1_SCANDIR_Pos); /* Configure the ADC scheduler as selected inside SetADCSampPointSectX*/ ADC1->CHSELR = pHandle->pParams_str->ADCConfig[pHandle->_Super.Sector]; /* ReConfigure sampling time, as deconfigured by reg_conv_manager */ LL_ADC_SetSamplingTimeCommonChannels ( ADC1, LL_ADC_SAMPLINGTIME_COMMON_2, pHandle->pParams_str->b_ISamplingTime ); /* disable ADC source trigger */ LL_TIM_SetTriggerOutput2(TIM1, LL_TIM_TRGO2_OC4); /* ADC needs to be restarted because DMA is configured as limited */ LL_ADC_REG_StartConversion( ADC1 ); /* Reset the ADC trigger edge for next conversion */ pHandle->ADCTriggerEdge = LL_ADC_REG_TRIG_EXT_RISING; return &pHandle->_Super.Motor; } /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
40,067
C
30.157076
143
0.608206
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/C0xx/Src/c0xx_bemf_ADC_OS_fdbk.c
/** ****************************************************************************** * @file c0xx_bemf_ADC_OS_fdbk.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement Bemf sensing * class to be stantiated when the six-step sensorless driving mode * topology is used. Differently from standard implementation, * this one performs multiple acquisition during a PWM cycle. * * It is specifically designed for STM32C0XX * microcontrollers and implements the sensing using one ADC with * DMA support. * + MCU peripheral and handle initialization fucntion * + ADC sampling function * ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup SpeednPosFdbk_Bemf */ /* Includes ------------------------------------------------------------------*/ #include "c0xx_bemf_ADC_OS_fdbk.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup SpeednPosFdbk * @{ */ /** @addtogroup SpeednPosFdbk_Bemf * @{ */ /* Private defines -----------------------------------------------------------*/ #define MAX_PSEUDO_SPEED ((int16_t)0x7FFF) #define PHASE_U 0u #define PHASE_V 1u #define PHASE_W 2u /* Private function prototypes -----------------------------------------------*/ void BADC_CalcAvrgElSpeedDpp( Bemf_ADC_Handle_t * pHandle ); /* Private functions ---------------------------------------------------------*/ /* * @brief Initializes ADC1, DMA and NVIC for three bemf voltages reading * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_Init( Bemf_ADC_Handle_t *pHandle) { uint8_t i; uint32_t tArray; if ( ( uint32_t )pHandle == ( uint32_t )&pHandle->_Super ) { /* disable IT and flags in case of LL driver usage * workaround for unwanted interrupt enabling done by LL driver */ LL_ADC_DisableIT_EOC( ADC1 ); LL_ADC_ClearFlag_EOC( ADC1 ); LL_ADC_DisableIT_EOS( ADC1 ); LL_ADC_ClearFlag_EOS( ADC1 ); /* ADC Calibration */ LL_ADC_StartCalibration( ADC1 ); while ((LL_ADC_IsCalibrationOnGoing(ADC1) == SET) || (LL_ADC_REG_IsConversionOngoing(ADC1) == SET) || (LL_ADC_REG_IsStopConversionOngoing(ADC1) == SET) || (LL_ADC_IsDisableOngoing(ADC1) == SET)) { /* wait */ } /* Enables the ADC peripheral */ LL_ADC_Enable( ADC1 ); LL_ADC_SetSamplingTimeCommonChannels(ADC1, LL_ADC_SAMPLINGTIME_COMMON_1, LL_ADC_SAMPLINGTIME_1CYCLE_5); /* Wait ADC Ready */ while ( LL_ADC_IsActiveFlag_ADRDY( ADC1 ) == RESET ) { /* wait */ } /* DMA1 Channel1 Config */ LL_DMA_SetMemoryAddress( DMA1, LL_DMA_CHANNEL_1, ( uint32_t )pHandle->ADC1_DMA_converted ); LL_DMA_SetPeriphAddress( DMA1, LL_DMA_CHANNEL_1, ( uint32_t )&ADC1->DR ); LL_DMA_SetDataLength(DMA1, LL_DMA_CHANNEL_1, pHandle->OverSamplingRate ); /* We allow ADC usage for regular conversion on Systick*/ pHandle->ADCRegularLocked=false; uint16_t hMinReliableElSpeedUnit = pHandle->_Super.hMinReliableMecSpeedUnit * pHandle->_Super.bElToMecRatio; uint16_t hMaxReliableElSpeedUnit = pHandle->_Super.hMaxReliableMecSpeedUnit * pHandle->_Super.bElToMecRatio; uint8_t bSpeedBufferSize; uint8_t bIndex; uint16_t MinBemfTime; /* Adjustment factor: minimum measurable speed is x time less than the minimum reliable speed */ hMinReliableElSpeedUnit /= 4U; /* Adjustment factor: maximum measurable speed is x time greater than the maximum reliable speed */ hMaxReliableElSpeedUnit *= 2U; pHandle->OvfFreq = (uint16_t)(pHandle->TIMClockFreq / 65536U); /* SW Init */ if (0U == hMinReliableElSpeedUnit) { /* Set fixed to 150 ms */ pHandle->BemfTimeout = 150U; } else { /* Set accordingly the min reliable speed */ /* 1000 comes from mS * 6 comes from the fact that sensors are toggling each 60 deg = 360/6 deg */ pHandle->BemfTimeout = (1000U * (uint16_t)SPEED_UNIT) / (6U * hMinReliableElSpeedUnit); } /* Align MaxPeriod and MinPeriod to a multiple of Overflow.*/ pHandle->MaxPeriod = (pHandle->BemfTimeout * pHandle->OvfFreq) / 1000U * 65536UL; MinBemfTime = ((1000U * (uint16_t)SPEED_UNIT) << 8) / (6U * hMaxReliableElSpeedUnit); pHandle->MinPeriod = ((MinBemfTime * pHandle->OvfFreq) >> 8) / 1000U * 65536UL; pHandle->SatSpeed = hMaxReliableElSpeedUnit; pHandle->PseudoPeriodConv = ((pHandle->TIMClockFreq / 6U) / pHandle->_Super.hMeasurementFrequency) * pHandle->_Super.DPPConvFactor; if (0U == hMaxReliableElSpeedUnit) { pHandle->MinPeriod = ((uint32_t)SPEED_UNIT * (pHandle->TIMClockFreq / 6UL)); } else { pHandle->MinPeriod = (((uint32_t)SPEED_UNIT * (pHandle->TIMClockFreq / 6UL)) / hMaxReliableElSpeedUnit); } pHandle->PWMNbrPSamplingFreq = ((pHandle->_Super.hMeasurementFrequency * pHandle->PWMFreqScaling) / pHandle->SpeedSamplingFreqHz) - 1U; pHandle->pSensing_Params = &(pHandle->Pwm_OFF); pHandle->IsOnSensingEnabled = false; pHandle->ElPeriodSum = 0; pHandle->ZcEvents = 0; pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold; /* Erase speed buffer */ bSpeedBufferSize = pHandle->SpeedBufferSize; for (bIndex = 0u; bIndex < bSpeedBufferSize; bIndex++) { pHandle->SpeedBufferDpp[bIndex] = (int32_t)pHandle->MaxPeriod; } LL_TIM_CC_EnableChannel( pHandle->pParams_str->TIM_Trigger, pHandle->pParams_str->TIM_ADC_Trigger_Channel ); LL_TIM_EnableCounter( pHandle->pParams_str->TIM_Trigger ); tArray = LL_TIM_GetAutoReload(pHandle->pParams_str->TIM_Trigger); LL_TIM_OC_SetCompareCH1( pHandle->pParams_str->TIM_Trigger, pHandle->pSensing_Params->SamplingPoint); for (i=0; i<pHandle->OverSamplingRate; i++) { pHandle->TIM1_pulses[i]= tArray * i + pHandle->Pwm_OFF.SamplingPoint; } LL_TIM_EnableCounter(pHandle->pParams_str->LfTim); } } /* * @brief Resets the ADC status * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_Clear( Bemf_ADC_Handle_t *pHandle ) { /* Disabling of DMA Interrupt Event configured */ LL_DMA_DisableIT_TC( DMA1, LL_DMA_CHANNEL_1 ); LL_ADC_REG_StopConversion( ADC1 ); /* Disable ADC DMA request*/ ADC1->CFGR1 &= ~ADC_CFGR1_DMAEN; /* Clear Transmission Complete Flag of DMA1 Channel1 */ LL_DMA_ClearFlag_TC1( DMA1 ); /* Clear EOC */ LL_ADC_ClearFlag_EOC( ADC1 ); /* We allow ADC usage for regular conversion on Systick*/ pHandle->ADCRegularLocked=false; pHandle->ZcEvents = 0; pHandle->ElPeriodSum = 0; /* Acceleration measurement not implemented.*/ pHandle->_Super.hMecAccelUnitP = 0; pHandle->BufferFilled = 0U; pHandle->CompSpeed = 0; /* Initialize speed buffer index */ pHandle->SpeedFIFOIdx = 0U; pHandle->_Super.hElAngle = 0; /* Clear speed error counter */ pHandle->_Super.bSpeedErrorNumber = 0; pHandle->IsLoopClosed=false; pHandle->IsAlgorithmConverged = false; } /* * @brief Starts bemf ADC conversion of the phase depending on current step * @param pHandle: handler of the current instance of the Bemf_ADC component * @param step: current step of the six-step sequence */ __weak void BADC_Start(Bemf_ADC_Handle_t *pHandle, uint8_t step) { pHandle->ADCRegularLocked=true; LL_ADC_REG_StopConversion( ADC1 ); /* Enable ADC DMA request*/ LL_ADC_REG_SetDMATransfer( ADC1, LL_ADC_REG_DMA_TRANSFER_UNLIMITED ); /* enable ADC source trigger */ LL_ADC_REG_SetTriggerSource (ADC1, LL_ADC_REG_TRIG_EXT_TIM2_TRGO); LL_ADC_REG_SetTriggerEdge (ADC1, LL_ADC_REG_TRIG_EXT_FALLING); LL_ADC_SetSamplingTimeCommonChannels (ADC1, LL_ADC_SAMPLINGTIME_COMMON_1, LL_ADC_SAMPLINGTIME_1CYCLE_5 ); switch (step) { case STEP_1: case STEP_4: BADC_SelectAdcChannel(pHandle, PHASE_W); break; case STEP_2: case STEP_5: BADC_SelectAdcChannel(pHandle, PHASE_V); break; case STEP_3: case STEP_6: BADC_SelectAdcChannel(pHandle, PHASE_U); break; default: break; } LL_DMA_DisableChannel(DMA1, LL_DMA_CHANNEL_1 ); LL_DMA_SetDataLength(DMA1, LL_DMA_CHANNEL_1, pHandle->OverSamplingRate ); LL_DMA_EnableChannel( DMA1, LL_DMA_CHANNEL_1 ); /* Clear Pending Interrupt Bits */ LL_DMA_ClearFlag_TC1( DMA1 ); /* DMA Interrupt Event configuration */ LL_DMA_EnableIT_TC( DMA1, LL_DMA_CHANNEL_1 ); LL_ADC_REG_StartConversion(ADC1); LL_TIM_GenerateEvent_UPDATE(TIM1); } /* * @brief Stops bemf ADC conversion * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_Stop(Bemf_ADC_Handle_t *pHandle) { LL_ADC_REG_StopConversion( ADC1 ); /* Clear Transmission Complete Flag of DMA1 Channel1 */ LL_DMA_ClearFlag_TC1( DMA1 ); /* Clear EOC */ LL_ADC_ClearFlag_EOC( ADC1 ); } /* * @brief Enables the speed loop (low frequency) timer * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_SpeedMeasureOn(Bemf_ADC_Handle_t *pHandle) { LL_TIM_ClearFlag_UPDATE(pHandle->pParams_str->LfTim); LL_TIM_EnableIT_UPDATE(pHandle->pParams_str->LfTim); } /* * @brief Disables the speed loop (low frequency) timer * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_SpeedMeasureOff(Bemf_ADC_Handle_t *pHandle) { LL_TIM_DisableIT_UPDATE(pHandle->pParams_str->LfTim); } /* * @brief Configures the ADC for the current sampling. * It sets the sampling point via TIM1_Ch4 value, the ADC sequence * and channels. * @param pHandle: handler of the current instance of the Bemf_ADC component * @param pHandlePWMC: handler of the current instance of the PWMC component * @param pHandleSTC: handler of the current instance of the Speed Control component */ __weak void BADC_SetSamplingPoint(Bemf_ADC_Handle_t *pHandle, PWMC_Handle_t *pHandlePWMC, SpeednTorqCtrl_Handle_t *pHandleSTC ) { if ((pHandleSTC->ModeDefault == MCM_SPEED_MODE) && (pHandle->DriveMode == VM)) { if (!(pHandle->IsOnSensingEnabled) && (pHandlePWMC->CntPh > pHandle->OnSensingEnThres)) { pHandle->IsOnSensingEnabled=true; pHandle->pSensing_Params = &(pHandle->Pwm_ON); } else if ((pHandle->IsOnSensingEnabled) && (pHandlePWMC->CntPh < pHandle->OnSensingDisThres)) { pHandle->IsOnSensingEnabled=false; pHandle->pSensing_Params = &(pHandle->Pwm_OFF); } else { } } else { pHandle->IsOnSensingEnabled=false; pHandle->pSensing_Params = &(pHandle->Pwm_OFF); } if (true == pHandle->pParams_str->gpio_divider_available) LL_GPIO_ResetOutputPin( pHandle->pParams_str->bemf_divider_port, pHandle->pParams_str->bemf_divider_pin ); LL_TIM_OC_SetCompareCH1( pHandle->pParams_str->TIM_Trigger, pHandle->pSensing_Params->SamplingPoint); } /* * @brief Gets last bemf value and checks for zero crossing detection. * It updates speed loop timer and electrical angle accordingly. * @param pHandle: handler of the current instance of the Bemf_ADC component * @param pHandlePWMC: handler of the current instance of the PWMC component */ __weak bool BADC_IsZcDetected( Bemf_ADC_Handle_t *pHandle, PWMC_Handle_t *pHandlePWMC) { uint8_t i; uint32_t DeltaCounter, tZC_Counter = pHandle->ZC_Counter_On_Last; bool ZcDetection = false; pHandle->DemagCounter++; if ( pHandle->DemagCounter >= pHandle->DemagCounterThreshold) { if (pHandle->ZcDetected == false) { for (i=0; i<pHandle->OverSamplingRate; i++) { if (((pHandle->TIM1_pulses[i] > (pHandlePWMC->CntPh + pHandle->SamplingGuard)) && (false == pHandle->IsOnSensingEnabled)) || ((pHandle->TIM1_pulses[i] < (pHandlePWMC->CntPh - pHandle->SamplingGuard)) && (true == pHandle->IsOnSensingEnabled))) { switch(pHandlePWMC->Step) { case STEP_1: pHandle->BemfLastValues[2] = pHandle->ADC1_DMA_converted[i]; if(pHandle->Direction == 1) { if (pHandle->ADC1_DMA_converted[i] < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_60_PHASE_SHIFT / 2; } } else { if (pHandle->ADC1_DMA_converted[i] > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = S16_120_PHASE_SHIFT + S16_60_PHASE_SHIFT / 2; } } break; case STEP_2: pHandle->BemfLastValues[1] = pHandle->ADC1_DMA_converted[i]; if(pHandle->Direction == 1) { if (pHandle->ADC1_DMA_converted[i] > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = S16_60_PHASE_SHIFT / 2; } } else { if (pHandle->ADC1_DMA_converted[i] < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_120_PHASE_SHIFT - S16_60_PHASE_SHIFT / 2; } } break; case STEP_3: pHandle->BemfLastValues[0] = pHandle->ADC1_DMA_converted[i]; if(pHandle->Direction == 1) { if (pHandle->ADC1_DMA_converted[i] < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = S16_60_PHASE_SHIFT + S16_60_PHASE_SHIFT / 2; } } else { if (pHandle->ADC1_DMA_converted[i] > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_60_PHASE_SHIFT - S16_60_PHASE_SHIFT / 2; } } break; case STEP_4: pHandle->BemfLastValues[2] = pHandle->ADC1_DMA_converted[i]; if(pHandle->Direction == 1) { if (pHandle->ADC1_DMA_converted[i] > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = S16_120_PHASE_SHIFT + S16_60_PHASE_SHIFT / 2; } } else { if (pHandle->ADC1_DMA_converted[i] < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_60_PHASE_SHIFT / 2; } } break; case STEP_5: pHandle->BemfLastValues[1] = pHandle->ADC1_DMA_converted[i]; if(pHandle->Direction == 1) { if (pHandle->ADC1_DMA_converted[i] < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_120_PHASE_SHIFT - S16_60_PHASE_SHIFT / 2; } } else { if (pHandle->ADC1_DMA_converted[i] > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = S16_60_PHASE_SHIFT / 2; } } break; case STEP_6: pHandle->BemfLastValues[0] = pHandle->ADC1_DMA_converted[i]; if(pHandle->Direction == 1) { if (pHandle->ADC1_DMA_converted[i] > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_60_PHASE_SHIFT - S16_60_PHASE_SHIFT / 2; } } else { if (pHandle->ADC1_DMA_converted[i] < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = S16_60_PHASE_SHIFT + S16_60_PHASE_SHIFT / 2; } } break; } if (ZcDetection == true) { DeltaCounter = pHandle->TIM1_pulses[pHandle->OverSamplingRate - 1] - pHandle->TIM1_pulses[i]; break; } } else if ((pHandle->TIM1_pulses[i] < (pHandlePWMC->CntPh - pHandle->SamplingGuard)) && (false == pHandle->IsOnSensingEnabled) && (pHandle->ZcDetected == false)) { tZC_Counter = pHandle->ADC1_DMA_converted[i]; } } } if (true == ZcDetection) { pHandle->ZC_Counter_On_Last = tZC_Counter; pHandle->MeasuredElAngle += (S16_60_PHASE_SHIFT/2) - (int16_t)((uint32_t)(pHandle->Zc2CommDelay * S16_60_PHASE_SHIFT)>>9); if (pHandle->ZcEvents > pHandle->StartUpConsistThreshold) { pHandle->IsAlgorithmConverged = true; } pHandle->ZcDetected = true; pHandle->ZcEvents++; switch(pHandlePWMC->Step) { case STEP_1: case STEP_3: case STEP_5: if(pHandle->Direction == 1) { pHandle->ZC_Counter_Down = LL_TIM_GetCounter(pHandle->pParams_str->LfTim) - DeltaCounter/(pHandle->LowFreqTimerPsc + 1); pHandle->ZC_Counter_Last = pHandle->ZC_Counter_Down; } else { pHandle->ZC_Counter_Up = LL_TIM_GetCounter(pHandle->pParams_str->LfTim) - DeltaCounter/(pHandle->LowFreqTimerPsc + 1); pHandle->ZC_Counter_Last = pHandle->ZC_Counter_Up; } break; case STEP_2: case STEP_4: case STEP_6: if(pHandle->Direction == 1) { pHandle->ZC_Counter_Up = LL_TIM_GetCounter(pHandle->pParams_str->LfTim) - DeltaCounter/(pHandle->LowFreqTimerPsc + 1); pHandle->ZC_Counter_Last = pHandle->ZC_Counter_Up; } else { pHandle->ZC_Counter_Down = LL_TIM_GetCounter(pHandle->pParams_str->LfTim) - DeltaCounter/(pHandle->LowFreqTimerPsc + 1); pHandle->ZC_Counter_Last = pHandle->ZC_Counter_Down; } break; } if (true == pHandle->IsAlgorithmConverged) { uint32_t tempReg = (uint32_t )(pHandle->PseudoPeriodConv / ((pHandle->LowFreqTimerPsc + 1) * (pHandle->AvrElSpeedDpp * pHandle->Direction))); LL_TIM_SetAutoReload(pHandle->pParams_str->LfTim,pHandle->ZC_Counter_Last + (((uint32_t)((pHandle->Zc2CommDelay) * tempReg)) >> 9) ); } } } return ZcDetection; } /* * @brief Must be called - at least - with the same periodicity * on which speed control is executed. It computes and returns - through * parameter hMecSpeedUnit - the rotor average mechanical speed, * expressed in Unit. Average is computed considering a FIFO depth * equal to SpeedBufferSizeUnit. Moreover it also computes and returns * the reliability state of the sensor. * @param pHandle: handler of the current instance of the Bemf_ADC component * @param pMecSpeedUnit pointer to int16_t, used to return the rotor average * mechanical speed (expressed in the unit defined by #SPEED_UNIT) * @retval bool speed sensor reliability, measured with reference to parameters * Reliability_hysteresys, VariancePercentage and SpeedBufferSize * true = sensor information is reliable * false = sensor information is not reliable */ __weak bool BADC_CalcAvrgMecSpeedUnit( Bemf_ADC_Handle_t * pHandle, int16_t * pMecSpeedUnit ) { bool bReliability; pHandle->_Super.hElSpeedDpp = pHandle->AvrElSpeedDpp; if (0 == pHandle->AvrElSpeedDpp) { /* Speed is too low */ *pMecSpeedUnit = 0; } else { /* Check if speed is not to fast */ if (pHandle->AvrElSpeedDpp != MAX_PSEUDO_SPEED) { pHandle->DeltaAngle = pHandle->MeasuredElAngle - pHandle->_Super.hElAngle; pHandle->CompSpeed = (int16_t)((int32_t)(pHandle->DeltaAngle) / (int32_t)(pHandle->PWMNbrPSamplingFreq)); /* Convert el_dpp to MecUnit */ *pMecSpeedUnit = (int16_t)((pHandle->AvrElSpeedDpp * (int32_t)pHandle->_Super.hMeasurementFrequency * (int32_t)SPEED_UNIT ) / ((int32_t)(pHandle->_Super.DPPConvFactor) * (int32_t)(pHandle->_Super.bElToMecRatio)) ); } else { *pMecSpeedUnit = (int16_t)pHandle->SatSpeed; } } bReliability = SPD_IsMecSpeedReliable(&pHandle->_Super, pMecSpeedUnit); pHandle->_Super.hAvrMecSpeedUnit = *pMecSpeedUnit; BADC_CalcAvrgElSpeedDpp (pHandle); return (bReliability); } /* * @brief Returns false if calculated speed is out of reliability ranges * @param pHandle: handler of the current instance of the Bemf_ADC component * @retval bool: reliability flag */ __weak bool BADC_IsSpeedReliable( Bemf_ADC_Handle_t *pHandle ) { bool SpeedError = false; if ( pHandle->_Super.hAvrMecSpeedUnit > pHandle->_Super.hMaxReliableMecSpeedUnit ) { SpeedError = true; } if ( pHandle->_Super.hAvrMecSpeedUnit < pHandle->_Super.hMinReliableMecSpeedUnit ) { SpeedError = true; } return ( SpeedError ); } /* * @brief Forces the rotation direction * @param direction: imposed direction */ __weak void BADC_SetDirection( Bemf_ADC_Handle_t * pHandle, uint8_t direction ) { if (MC_NULL == pHandle) { /* Nothing to do */ } else { pHandle->Direction = direction; } } /* * @brief Internally performs a checks necessary to state whether * the bemf algorithm converged. To be periodically called * during motor open-loop ramp-up (e.g. at the same frequency of * SPD_CalcElAngle), it returns true if the estimated angle and speed * can be considered reliable, false otherwise * @param pHandle: handler of the current instance of the Bemf_ADC component * @param hForcedMecSpeedUnit Mechanical speed in 0.1Hz unit as forced by VSS * @retval bool sensor reliability state */ __weak bool BADC_IsObserverConverged( Bemf_ADC_Handle_t * pHandle ) { return pHandle->IsAlgorithmConverged; } /* * @brief Configures the proper ADC channel according to the current * step corresponding to the floating phase. To be periodically called * at least at every step change. * @param pHandle: handler of the current instance of the Bemf_ADC component * @param Phase: Floating phase for bemf acquisition */ void BADC_SelectAdcChannel(Bemf_ADC_Handle_t * pHandle, uint8_t Phase) { while (LL_ADC_REG_IsConversionOngoing(ADC1)) { LL_ADC_REG_StopConversion(ADC1); while(LL_ADC_REG_IsStopConversionOngoing(ADC1)); } /* Sampling time configuration */ /* Regular sequence configuration */ LL_ADC_REG_SetSequencerChannels(ADC1, __LL_ADC_DECIMAL_NB_TO_CHANNEL(pHandle->pParams_str->AdcChannel[Phase])); LL_ADC_ClearFlag_EOC(ADC1); } /* * @brief Updates the estimated electrical angle. * @param pHandle: handler of the current instance of the Bemf_ADC component * @retval int16_t rotor electrical angle (s16Degrees) */ __weak int16_t BADC_CalcElAngle(Bemf_ADC_Handle_t * pHandle) { int16_t retValue; if (pHandle->_Super.hElSpeedDpp != MAX_PSEUDO_SPEED) { if (false == pHandle->IsLoopClosed) { pHandle->MeasuredElAngle += pHandle->_Super.hElSpeedDpp; pHandle->PrevRotorFreq = pHandle->_Super.hElSpeedDpp; pHandle->_Super.hElAngle += pHandle->_Super.hElSpeedDpp + pHandle->CompSpeed; } else { pHandle->_Super.hElAngle = pHandle->MeasuredElAngle; } } else { pHandle->_Super.hElAngle += pHandle->PrevRotorFreq; } retValue = pHandle->_Super.hElAngle; return (retValue); } /* * @brief Must be called - at least - with the same periodicity * on which speed control is executed. It computes and update component * variable hElSpeedDpp that is estimated average electrical speed * expressed in dpp used for instance in observer equations. * Average is computed considering a FIFO depth equal to * bSpeedBufferSizedpp. * @param pHandle: handler of the current instance of the Bemf_ADC component */ void BADC_CalcAvrgElSpeedDpp( Bemf_ADC_Handle_t * pHandle ) { uint32_t wCaptBuf; /* used to validate the average speed measurement */ if (pHandle->BufferFilled < pHandle->SpeedBufferSize) { pHandle->BufferFilled++; } else { /* Nothing to do */ } if (false == pHandle->IsLoopClosed) { if (pHandle->VirtualElSpeedDpp == 0) pHandle->Counter_Period = 0xFFFF; else pHandle->Counter_Period = ( uint32_t )(pHandle->PseudoPeriodConv / ((pHandle->LowFreqTimerPsc + 1) * pHandle->VirtualElSpeedDpp)); } else { pHandle->Counter_Period = pHandle->ZC_Counter_Last + pHandle->Last_Zc2Comm_Delay; } wCaptBuf = pHandle->Counter_Period * (pHandle->LowFreqTimerPsc + 1); /* Filtering to fast speed... could be a glitch ? */ /* the MAX_PSEUDO_SPEED is temporary in the buffer, and never included in average computation*/ if (wCaptBuf < pHandle->MinPeriod) { /* Nothing to do */ } else { pHandle->ElPeriodSum -= pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx]; /* value we gonna removed from the accumulator */ if (wCaptBuf >= pHandle->MaxPeriod) { pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx] = (int32_t)pHandle->MaxPeriod * pHandle->Direction; } else { pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx] = (int32_t)wCaptBuf ; pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx] *= pHandle->Direction; pHandle->ElPeriodSum += pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx]; } /* Update pointers to speed buffer */ pHandle->SpeedFIFOIdx++; if (pHandle->SpeedFIFOIdx == pHandle->SpeedBufferSize) { pHandle->SpeedFIFOIdx = 0U; } if (((pHandle->BufferFilled < pHandle->SpeedBufferSize) && (wCaptBuf != 0U)) || (false == pHandle->IsLoopClosed)) { uint32_t tempReg = (pHandle->PseudoPeriodConv / wCaptBuf) * (uint32_t)pHandle->Direction; pHandle->AvrElSpeedDpp = (int16_t)tempReg; } else { /* Average speed allow to smooth the mechanical sensors misalignement */ int32_t tElPeriodSum = 0; uint8_t i; for (i=0; i < pHandle->SpeedBufferSize; i++) { tElPeriodSum += pHandle->SpeedBufferDpp[i]; } pHandle->AvrElSpeedDpp = (int16_t)((int32_t)pHandle->PseudoPeriodConv / (tElPeriodSum / (int32_t)pHandle->SpeedBufferSize)); /* Average value */ } } } /* * @brief Used to calculate instant speed during revup, to * initialize parameters at step change and to select proper ADC channel * for next Bemf acquisitions * @param pHandle: handler of the current instance of the Bemf_ADC component * @param hElSpeedDpp: Mechanical speed imposed by virtual speed component * @param pHandlePWMC: handler of the current instance of the PWMC component */ void BADC_StepChangeEvent(Bemf_ADC_Handle_t * pHandle, int16_t hElSpeedDpp, PWMC_Handle_t *pHandlePWMC) { pHandle->DemagCounter = 0; while (LL_ADC_REG_IsConversionOngoing(ADC1)) { LL_ADC_REG_StopConversion(ADC1); while(LL_ADC_REG_IsStopConversionOngoing(ADC1)); } BADC_Stop(pHandle); pHandle->Last_Zc2Comm_Delay = LL_TIM_GetAutoReload(pHandle->pParams_str->LfTim) - pHandle->ZC_Counter_Last; if (false == pHandle->IsLoopClosed) { if (hElSpeedDpp < 0) { pHandle->VirtualElSpeedDpp = - hElSpeedDpp; } else { pHandle->VirtualElSpeedDpp = hElSpeedDpp; } pHandle->ZcDetected = false; } else { int16_t ElAngleUpdate; if(pHandle->Direction == -1) { ElAngleUpdate = -S16_60_PHASE_SHIFT ; } else { ElAngleUpdate = S16_60_PHASE_SHIFT ; } pHandle->MeasuredElAngle += ElAngleUpdate; if ( false == pHandle->ZcDetected) { LL_TIM_SetAutoReload(pHandle->pParams_str->LfTim,LL_TIM_GetAutoReload(pHandle->pParams_str->LfTim) * 120 / 100); } else { pHandle->ZcDetected = false; } } pHandle->StepUpdate = true; } /* * @brief Calculates and stores in the corresponding variable the demagnetization * time in open loop operation * @param pHandle: handler of the current instance of the Bemf_ADC component * @param pHandleSTC: handler of the current instance of the Speed Control component */ void BADC_CalcRevUpDemagTime(Bemf_ADC_Handle_t *pHandle) { int16_t hSpeed; hSpeed = (int16_t)((pHandle->VirtualElSpeedDpp * (int32_t)pHandle->_Super.hMeasurementFrequency * (int32_t)SPEED_UNIT ) / ((int32_t)(pHandle->_Super.DPPConvFactor) * (int32_t)(pHandle->_Super.bElToMecRatio)) );; if (hSpeed == 0) { pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold;; } else { pHandle->DemagCounterThreshold = (uint16_t) (pHandle->DemagParams.RevUpDemagSpeedConv / hSpeed); } if (pHandle->DemagCounterThreshold < pHandle->DemagParams.DemagMinimumThreshold) { pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold; } } /* * @brief Calculates and stores in the corresponding variable the demagnetization * time in closed loop operation * @param pHandle: handler of the current instance of the Bemf_ADC component * @param pHandleSTC: handler of the current instance of the Speed Control component */ void BADC_CalcRunDemagTime(Bemf_ADC_Handle_t *pHandle) { int16_t hSpeed; hSpeed = pHandle->_Super.hAvrMecSpeedUnit; if (hSpeed < 0) hSpeed = - hSpeed; if (hSpeed < pHandle->DemagParams.DemagMinimumSpeedUnit) { pHandle->DemagCounterThreshold = (uint16_t) (pHandle->DemagParams.RunDemagSpeedConv / hSpeed); if (pHandle->DemagCounterThreshold < pHandle->DemagParams.DemagMinimumThreshold) { pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold; } } else { pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold; } } /* * @brief This method must be called after switch-over procedure when * virtual speed sensor transition is ended. * @param pHandle: handler of the current instance of the STO component */ void BADC_SetLoopClosed(Bemf_ADC_Handle_t *pHandle) { pHandle->IsLoopClosed=true; } /* * @brief Returns the last acquired bemf value * @param pHandle: handler of the current instance of the Bemf_ADC component * @param phase: motor phase under investigation * @retval uint16_t: Bemf value */ uint16_t BADC_GetLastBemfValue(Bemf_ADC_Handle_t *pHandle, uint8_t phase) { return ((MC_NULL == pHandle) ? 0U : pHandle->BemfLastValues[phase]); } /* * @brief Returns the zero crossing detection flag * @param pHandle: handler of the current instance of the Bemf_ADC component * @retval bool: zero crossing detection flag */ bool BADC_GetBemfZcrFlag(Bemf_ADC_Handle_t *pHandle) { return ((MC_NULL == pHandle) ? 0U : pHandle->ZcDetected); } /* * @brief Returns true if the step needs to be updated * @param pHandle: handler of the current instance of the Bemf_ADC component * @retval bool: step update request */ bool BADC_ClearStepUpdate(Bemf_ADC_Handle_t *pHandle) { bool retValue = (((pHandle->IsLoopClosed == true) && (pHandle->StepUpdate == true)) || (pHandle->IsLoopClosed == false)); pHandle->StepUpdate = false; return retValue; } /* * @brief Configures the parameters for bemf sensing during pwm off-time * @param pHandle: handler of the current instance of the Bemf_ADC component * @param BemfAdcConfig: thresholds and sampling time parameters * @param Zc2CommDelay: delay between bemf zero crossing parameter and step commutation * @param bemfAdcDemagConfig: demagnetization parameters */ void BADC_SetBemfSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfAdcConfig, uint16_t *Zc2CommDelay, Bemf_Demag_Params *bemfAdcDemagConfig) { pHandle->Pwm_OFF.AdcThresholdUp = BemfAdcConfig->AdcThresholdUp; pHandle->Pwm_OFF.AdcThresholdDown = BemfAdcConfig->AdcThresholdDown; pHandle->Pwm_OFF.SamplingPoint = BemfAdcConfig->SamplingPoint; pHandle->Zc2CommDelay = *Zc2CommDelay; pHandle->DemagParams.DemagMinimumSpeedUnit = bemfAdcDemagConfig->DemagMinimumSpeedUnit; pHandle->DemagParams.DemagMinimumThreshold = bemfAdcDemagConfig->DemagMinimumThreshold; } /* * @brief Configures the parameters for bemf sensing during pwm on-time * @param pHandle: handler of the current instance of the Bemf_ADC component * @param BemfOnAdcConfig: thresholds and sampling time parameters * @param OnSensingEnThres: Minimum dudty cycle for on-sensing activation * @param OnSensingDisThres: Minimum duty cycle for on-sensing Deactivationg */ void BADC_SetBemfOnTimeSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfOnAdcConfig, uint16_t *OnSensingEnThres, uint16_t *OnSensingDisThres) { pHandle->Pwm_ON.AdcThresholdUp = BemfOnAdcConfig->AdcThresholdUp; pHandle->Pwm_ON.AdcThresholdDown = BemfOnAdcConfig->AdcThresholdDown; pHandle->Pwm_ON.SamplingPoint = BemfOnAdcConfig->SamplingPoint; pHandle->OnSensingEnThres = *OnSensingEnThres; pHandle->OnSensingDisThres = *OnSensingDisThres; } /* * @brief Gets the parameters for bemf sensing during pwm off-time * @param pHandle: handler of the current instance of the Bemf_ADC component * @param BemfAdcConfig: thresholds and sampling time parameters * @param Zc2CommDelay: delay between bemf zero crossing parameter and step commutation * @param bemfAdcDemagConfig: demagnetization parameters */ void BADC_GetBemfSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfAdcConfig, uint16_t *Zc2CommDelay, Bemf_Demag_Params *BemfAdcDemagConfig) { BemfAdcConfig->AdcThresholdUp = pHandle->Pwm_OFF.AdcThresholdUp; BemfAdcConfig->AdcThresholdDown = pHandle->Pwm_OFF.AdcThresholdDown; BemfAdcConfig->SamplingPoint = pHandle->Pwm_OFF.SamplingPoint; *Zc2CommDelay = pHandle->Zc2CommDelay; BemfAdcDemagConfig->DemagMinimumSpeedUnit = pHandle->DemagParams.DemagMinimumSpeedUnit; BemfAdcDemagConfig->DemagMinimumThreshold = pHandle->DemagParams.DemagMinimumThreshold; } /* * @brief Gets the parameters for bemf sensing during pwm on-time * @param pHandle: handler of the current instance of the Bemf_ADC component * @param BemfOnAdcConfig: thresholds and sampling time parameters * @param OnSensingEnThres: Minimum duty cycle for on-sensing activation * @param OnSensingDisThres: Minimum duty cycle for on-sensing Deactivationg */ void BADC_GetBemfOnTimeSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfOnAdcConfig, uint16_t *OnSensingEnThres, uint16_t *OnSensingDisThres) { BemfOnAdcConfig->AdcThresholdUp = pHandle->Pwm_ON.AdcThresholdUp; BemfOnAdcConfig->AdcThresholdDown = pHandle->Pwm_ON.AdcThresholdDown; BemfOnAdcConfig->SamplingPoint = pHandle->Pwm_ON.SamplingPoint; *OnSensingEnThres = pHandle->OnSensingEnThres; *OnSensingDisThres = pHandle->OnSensingDisThres; } /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
36,474
C
35.438561
167
0.638839
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/C0xx/Src/c0xx_bemf_ADC_fdbk.c
/** ****************************************************************************** * @file c0xx_bemf_ADC_fdbk.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement Bemf sensing * class to be stantiated when the six-step sensorless driving mode * topology is used. * * It is specifically designed for STM32C0XX * microcontrollers and implements the sensing using one ADC with * DMA support. * + MCU peripheral and handle initialization fucntion * + ADC sampling function * ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup SpeednPosFdbk_Bemf */ /* Includes ------------------------------------------------------------------*/ #include "c0xx_bemf_ADC_fdbk.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup SpeednPosFdbk * @{ */ /** @addtogroup SpeednPosFdbk_Bemf * @{ */ /* Private defines -----------------------------------------------------------*/ #define MAX_PSEUDO_SPEED ((int16_t)0x7FFF) #define PHASE_U 0u #define PHASE_V 1u #define PHASE_W 2u /* Private function prototypes -----------------------------------------------*/ void BADC_CalcAvrgElSpeedDpp( Bemf_ADC_Handle_t * pHandle ); /* Private functions ---------------------------------------------------------*/ /* * @brief Initializes ADC1, DMA and NVIC for three bemf voltages reading * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_Init( Bemf_ADC_Handle_t *pHandle) { if ( ( uint32_t )pHandle == ( uint32_t )&pHandle->_Super ) { /* disable IT and flags in case of LL driver usage * workaround for unwanted interrupt enabling done by LL driver */ LL_ADC_DisableIT_EOC( ADC1 ); LL_ADC_ClearFlag_EOC( ADC1 ); LL_ADC_DisableIT_EOS( ADC1 ); LL_ADC_ClearFlag_EOS( ADC1 ); /* ADC Calibration */ LL_ADC_StartCalibration( ADC1 ); while ((LL_ADC_IsCalibrationOnGoing(ADC1) == SET) || (LL_ADC_REG_IsConversionOngoing(ADC1) == SET) || (LL_ADC_REG_IsStopConversionOngoing(ADC1) == SET) || (LL_ADC_IsDisableOngoing(ADC1) == SET)) { /* wait */ } /* Enables the ADC peripheral */ LL_ADC_Enable( ADC1 ); LL_ADC_SetSamplingTimeCommonChannels(ADC1, LL_ADC_SAMPLINGTIME_COMMON_1, LL_ADC_SAMPLINGTIME_1CYCLE_5); /* Wait ADC Ready */ while ( LL_ADC_IsActiveFlag_ADRDY( ADC1 ) == RESET ) { /* wait */ } /* DMA1 Channel1 Config */ LL_DMA_SetMemoryAddress( DMA1, LL_DMA_CHANNEL_1, ( uint32_t )pHandle->ADC1_DMA_converted ); LL_DMA_SetPeriphAddress( DMA1, LL_DMA_CHANNEL_1, ( uint32_t )&ADC1->DR ); LL_DMA_SetDataLength(DMA1, LL_DMA_CHANNEL_1, 1 ); /* We allow ADC usage for regular conversion on Systick*/ pHandle->ADCRegularLocked=false; uint16_t hMinReliableElSpeedUnit = pHandle->_Super.hMinReliableMecSpeedUnit * pHandle->_Super.bElToMecRatio; uint16_t hMaxReliableElSpeedUnit = pHandle->_Super.hMaxReliableMecSpeedUnit * pHandle->_Super.bElToMecRatio; uint8_t bSpeedBufferSize; uint8_t bIndex; uint16_t MinBemfTime; /* Adjustment factor: minimum measurable speed is x time less than the minimum reliable speed */ hMinReliableElSpeedUnit /= 4U; /* Adjustment factor: maximum measurable speed is x time greater than the maximum reliable speed */ hMaxReliableElSpeedUnit *= 2U; pHandle->OvfFreq = (uint16_t)(pHandle->TIMClockFreq / 65536U); /* SW Init */ if (0U == hMinReliableElSpeedUnit) { /* Set fixed to 150 ms */ pHandle->BemfTimeout = 150U; } else { /* Set accordingly the min reliable speed */ /* 1000 comes from mS * 6 comes from the fact that sensors are toggling each 60 deg = 360/6 deg */ pHandle->BemfTimeout = (1000U * (uint16_t)SPEED_UNIT) / (6U * hMinReliableElSpeedUnit); } /* Align MaxPeriod and MinPeriod to a multiple of Overflow.*/ pHandle->MaxPeriod = (pHandle->BemfTimeout * pHandle->OvfFreq) / 1000U * 65536UL; MinBemfTime = ((1000U * (uint16_t)SPEED_UNIT) << 8) / (6U * hMaxReliableElSpeedUnit); pHandle->MinPeriod = ((MinBemfTime * pHandle->OvfFreq) >> 8) / 1000U * 65536UL; pHandle->SatSpeed = hMaxReliableElSpeedUnit; pHandle->PseudoPeriodConv = ((pHandle->TIMClockFreq / 6U) / pHandle->_Super.hMeasurementFrequency) * pHandle->_Super.DPPConvFactor; if (0U == hMaxReliableElSpeedUnit) { pHandle->MinPeriod = ((uint32_t)SPEED_UNIT * (pHandle->TIMClockFreq / 6UL)); } else { pHandle->MinPeriod = (((uint32_t)SPEED_UNIT * (pHandle->TIMClockFreq / 6UL)) / hMaxReliableElSpeedUnit); } pHandle->PWMNbrPSamplingFreq = ((pHandle->_Super.hMeasurementFrequency * pHandle->PWMFreqScaling) / pHandle->SpeedSamplingFreqHz) - 1U; pHandle->pSensing_Params = &(pHandle->Pwm_OFF); pHandle->IsOnSensingEnabled = false; pHandle->ElPeriodSum = 0; pHandle->ZcEvents = 0; pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold; /* Erase speed buffer */ bSpeedBufferSize = pHandle->SpeedBufferSize; for (bIndex = 0u; bIndex < bSpeedBufferSize; bIndex++) { pHandle->SpeedBufferDpp[bIndex] = (int32_t)pHandle->MaxPeriod; } LL_TIM_EnableCounter(pHandle->pParams_str->LfTim); } } /* * @brief Resets the ADC status * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_Clear( Bemf_ADC_Handle_t *pHandle ) { /* Disabling of DMA Interrupt Event configured */ LL_DMA_DisableIT_TC( DMA1, LL_DMA_CHANNEL_1 ); LL_ADC_REG_StopConversion( ADC1 ); /* Disable ADC DMA request*/ ADC1->CFGR1 &= ~ADC_CFGR1_DMAEN; /* Clear Transmission Complete Flag of DMA1 Channel1 */ LL_DMA_ClearFlag_TC1( DMA1 ); /* Clear EOC */ LL_ADC_ClearFlag_EOC( ADC1 ); /* We allow ADC usage for regular conversion on Systick*/ pHandle->ADCRegularLocked=false; pHandle->ZcEvents = 0; pHandle->ElPeriodSum = 0; /* Acceleration measurement not implemented.*/ pHandle->_Super.hMecAccelUnitP = 0; pHandle->BufferFilled = 0U; pHandle->CompSpeed = 0; /* Initialize speed buffer index */ pHandle->SpeedFIFOIdx = 0U; pHandle->_Super.hElAngle = 0; /* Clear speed error counter */ pHandle->_Super.bSpeedErrorNumber = 0; pHandle->IsLoopClosed=false; pHandle->IsAlgorithmConverged = false; } /* * @brief Starts bemf ADC conversion of the phase depending on current step * @param pHandle: handler of the current instance of the Bemf_ADC component * @param step: current step of the six-step sequence */ __weak void BADC_Start(Bemf_ADC_Handle_t *pHandle, uint8_t step) { pHandle->ADCRegularLocked=true; LL_ADC_REG_StopConversion( ADC1 ); /* Enable ADC DMA request*/ LL_ADC_REG_SetDMATransfer( ADC1, LL_ADC_REG_DMA_TRANSFER_UNLIMITED ); /* Enables the DMA1 Channel1 peripheral */ LL_DMA_EnableChannel( DMA1, LL_DMA_CHANNEL_1 ); /* Clear Pending Interrupt Bits */ LL_DMA_ClearFlag_TC1( DMA1 ); /* DMA Interrupt Event configuration */ LL_DMA_EnableIT_TC( DMA1, LL_DMA_CHANNEL_1 ); /* enable ADC source trigger */ LL_ADC_REG_SetTriggerSource (ADC1, LL_ADC_REG_TRIG_EXT_TIM1_TRGO2); LL_ADC_REG_SetTriggerEdge (ADC1, LL_ADC_REG_TRIG_EXT_FALLING); LL_ADC_SetSamplingTimeCommonChannels (ADC1, LL_ADC_SAMPLINGTIME_COMMON_1, LL_ADC_SAMPLINGTIME_1CYCLE_5 ); switch (step) { case STEP_1: case STEP_4: BADC_SelectAdcChannel(pHandle, PHASE_W); break; case STEP_2: case STEP_5: BADC_SelectAdcChannel(pHandle, PHASE_V); break; case STEP_3: case STEP_6: BADC_SelectAdcChannel(pHandle, PHASE_U); break; default: break; } LL_ADC_REG_StartConversion(ADC1); } /* * @brief Stops bemf ADC conversion * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_Stop(Bemf_ADC_Handle_t *pHandle) { LL_ADC_REG_StopConversion( ADC1 ); /* Clear Transmission Complete Flag of DMA1 Channel1 */ LL_DMA_ClearFlag_TC1( DMA1 ); /* Clear EOC */ LL_ADC_ClearFlag_EOC( ADC1 ); } /* * @brief Enables the speed loop (low frequency) timer * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_SpeedMeasureOn(Bemf_ADC_Handle_t *pHandle) { LL_TIM_ClearFlag_UPDATE(pHandle->pParams_str->LfTim); LL_TIM_EnableIT_UPDATE(pHandle->pParams_str->LfTim); } /* * @brief Disables the speed loop (low frequency) timer * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_SpeedMeasureOff(Bemf_ADC_Handle_t *pHandle) { LL_TIM_DisableIT_UPDATE(pHandle->pParams_str->LfTim); } /* * @brief Configures the ADC for the current sampling. * It sets the sampling point via TIM1_Ch4 value, the ADC sequence * and channels. * @param pHandle: handler of the current instance of the Bemf_ADC component * @param pHandlePWMC: handler of the current instance of the PWMC component * @param pHandleSTC: handler of the current instance of the Speed Control component */ __weak void BADC_SetSamplingPoint(Bemf_ADC_Handle_t *pHandle, PWMC_Handle_t *pHandlePWMC, SpeednTorqCtrl_Handle_t *pHandleSTC ) { if ((pHandleSTC->ModeDefault == MCM_SPEED_MODE) && (pHandle->DriveMode == VM)) { if (!(pHandle->IsOnSensingEnabled) && (pHandlePWMC->CntPh > pHandle->OnSensingEnThres)) { pHandle->IsOnSensingEnabled=true; pHandle->pSensing_Params = &(pHandle->Pwm_ON); } else if ((pHandle->IsOnSensingEnabled) && (pHandlePWMC->CntPh < pHandle->OnSensingDisThres)) { pHandle->IsOnSensingEnabled=false; pHandle->pSensing_Params = &(pHandle->Pwm_OFF); } else { } } else { pHandle->IsOnSensingEnabled=false; pHandle->pSensing_Params = &(pHandle->Pwm_OFF); } if (true == pHandle->pParams_str->gpio_divider_available) LL_GPIO_ResetOutputPin( pHandle->pParams_str->bemf_divider_port, pHandle->pParams_str->bemf_divider_pin ); PWMC_SetADCTriggerChannel( pHandlePWMC, pHandle->pSensing_Params->SamplingPoint); } /* * @brief Gets last bemf value and checks for zero crossing detection. * It updates speed loop timer and electrical angle accordingly. * @param pHandle: handler of the current instance of the Bemf_ADC component * @param pHandlePWMC: handler of the current instance of the PWMC component */ __weak bool BADC_IsZcDetected( Bemf_ADC_Handle_t *pHandle, PWMC_Handle_t *pHandlePWMC) { uint16_t AdcValue = pHandle->ADC1_DMA_converted[0]; bool ZcDetection = false; pHandle->DemagCounter++; if ( pHandle->DemagCounter > pHandle->DemagCounterThreshold) { if (pHandle->ZcDetected == false) { switch(pHandlePWMC->Step) { case STEP_1: pHandle->BemfLastValues[2] = AdcValue; if(pHandle->Direction == 1) { if (AdcValue < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_60_PHASE_SHIFT / 2; } } else { if (AdcValue > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = S16_120_PHASE_SHIFT + S16_60_PHASE_SHIFT / 2; } } break; case STEP_2: pHandle->BemfLastValues[1] = AdcValue; if(pHandle->Direction == 1) { if (AdcValue > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = S16_60_PHASE_SHIFT / 2; } } else { if (AdcValue < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_120_PHASE_SHIFT - S16_60_PHASE_SHIFT / 2; } } break; case STEP_3: pHandle->BemfLastValues[0] = AdcValue; if(pHandle->Direction == 1) { if (AdcValue < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = S16_60_PHASE_SHIFT + S16_60_PHASE_SHIFT / 2; } } else { if (AdcValue > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_60_PHASE_SHIFT - S16_60_PHASE_SHIFT / 2; } } break; case STEP_4: pHandle->BemfLastValues[2] = AdcValue; if(pHandle->Direction == 1) { if (AdcValue > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = S16_120_PHASE_SHIFT + S16_60_PHASE_SHIFT / 2; } } else { if (AdcValue < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_60_PHASE_SHIFT / 2; } } break; case STEP_5: pHandle->BemfLastValues[1] = AdcValue; if(pHandle->Direction == 1) { if (AdcValue < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_120_PHASE_SHIFT - S16_60_PHASE_SHIFT / 2; } } else { if (AdcValue > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = S16_60_PHASE_SHIFT / 2; } } break; case STEP_6: pHandle->BemfLastValues[0] = AdcValue; if(pHandle->Direction == 1) { if (AdcValue > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_60_PHASE_SHIFT - S16_60_PHASE_SHIFT / 2; } } else { if (AdcValue < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = S16_60_PHASE_SHIFT + S16_60_PHASE_SHIFT / 2; } } break; } if (true == ZcDetection) { pHandle->MeasuredElAngle += (S16_60_PHASE_SHIFT/2) - (int16_t)((uint32_t)(pHandle->Zc2CommDelay * S16_60_PHASE_SHIFT)>>9); if (pHandle->ZcEvents > pHandle->StartUpConsistThreshold) { pHandle->IsAlgorithmConverged = true; } pHandle->ZcDetected = true; pHandle->ZcEvents++; switch(pHandlePWMC->Step) { case STEP_1: case STEP_3: case STEP_5: if(pHandle->Direction == 1) { pHandle->ZC_Counter_Down = LL_TIM_GetCounter(pHandle->pParams_str->LfTim); pHandle->ZC_Counter_Last = pHandle->ZC_Counter_Down; } else { pHandle->ZC_Counter_Up = LL_TIM_GetCounter(pHandle->pParams_str->LfTim); pHandle->ZC_Counter_Last = pHandle->ZC_Counter_Up; } break; case STEP_2: case STEP_4: case STEP_6: if(pHandle->Direction == 1) { pHandle->ZC_Counter_Up = LL_TIM_GetCounter(pHandle->pParams_str->LfTim); pHandle->ZC_Counter_Last = pHandle->ZC_Counter_Up; } else { pHandle->ZC_Counter_Down = LL_TIM_GetCounter(pHandle->pParams_str->LfTim); pHandle->ZC_Counter_Last = pHandle->ZC_Counter_Down; } break; } if (true == pHandle->IsAlgorithmConverged) { uint32_t tempReg = (uint32_t )(pHandle->PseudoPeriodConv / ((pHandle->LowFreqTimerPsc + 1) * (pHandle->AvrElSpeedDpp * pHandle->Direction))); LL_TIM_SetAutoReload(pHandle->pParams_str->LfTim,pHandle->ZC_Counter_Last + (((uint32_t)((pHandle->Zc2CommDelay) * tempReg)) >> 9) ); } } } } return ZcDetection; } /* * @brief Must be called - at least - with the same periodicity * on which speed control is executed. It computes and returns - through * parameter hMecSpeedUnit - the rotor average mechanical speed, * expressed in Unit. Average is computed considering a FIFO depth * equal to SpeedBufferSizeUnit. Moreover it also computes and returns * the reliability state of the sensor. * @param pHandle: handler of the current instance of the Bemf_ADC component * @param pMecSpeedUnit pointer to int16_t, used to return the rotor average * mechanical speed (expressed in the unit defined by #SPEED_UNIT) * @retval bool speed sensor reliability, measured with reference to parameters * Reliability_hysteresys, VariancePercentage and SpeedBufferSize * true = sensor information is reliable * false = sensor information is not reliable */ __weak bool BADC_CalcAvrgMecSpeedUnit( Bemf_ADC_Handle_t * pHandle, int16_t * pMecSpeedUnit ) { bool bReliability; pHandle->_Super.hElSpeedDpp = pHandle->AvrElSpeedDpp; if (0 == pHandle->AvrElSpeedDpp) { /* Speed is too low */ *pMecSpeedUnit = 0; } else { /* Check if speed is not to fast */ if (pHandle->AvrElSpeedDpp != MAX_PSEUDO_SPEED) { pHandle->DeltaAngle = pHandle->MeasuredElAngle - pHandle->_Super.hElAngle; pHandle->CompSpeed = (int16_t)((int32_t)(pHandle->DeltaAngle) / (int32_t)(pHandle->PWMNbrPSamplingFreq)); /* Convert el_dpp to MecUnit */ *pMecSpeedUnit = (int16_t)((pHandle->AvrElSpeedDpp * (int32_t)pHandle->_Super.hMeasurementFrequency * (int32_t)SPEED_UNIT ) / ((int32_t)(pHandle->_Super.DPPConvFactor) * (int32_t)(pHandle->_Super.bElToMecRatio)) ); } else { *pMecSpeedUnit = (int16_t)pHandle->SatSpeed; } } bReliability = SPD_IsMecSpeedReliable(&pHandle->_Super, pMecSpeedUnit); pHandle->_Super.hAvrMecSpeedUnit = *pMecSpeedUnit; BADC_CalcAvrgElSpeedDpp (pHandle); return (bReliability); } /* * @brief Returns false if calculated speed is out of reliability ranges * @param pHandle: handler of the current instance of the Bemf_ADC component * @retval bool: reliability flag */ __weak bool BADC_IsSpeedReliable( Bemf_ADC_Handle_t *pHandle ) { bool SpeedError = false; if ( pHandle->_Super.hAvrMecSpeedUnit > pHandle->_Super.hMaxReliableMecSpeedUnit ) { SpeedError = true; } if ( pHandle->_Super.hAvrMecSpeedUnit < pHandle->_Super.hMinReliableMecSpeedUnit ) { SpeedError = true; } return ( SpeedError ); } /* * @brief Forces the rotation direction * @param direction: imposed direction */ __weak void BADC_SetDirection( Bemf_ADC_Handle_t * pHandle, uint8_t direction ) { if (MC_NULL == pHandle) { /* Nothing to do */ } else { pHandle->Direction = direction; } } /* * @brief Internally performs a checks necessary to state whether * the bemf algorithm converged. To be periodically called * during motor open-loop ramp-up (e.g. at the same frequency of * SPD_CalcElAngle), it returns true if the estimated angle and speed * can be considered reliable, false otherwise * @param pHandle: handler of the current instance of the Bemf_ADC component * @param hForcedMecSpeedUnit Mechanical speed in 0.1Hz unit as forced by VSS * @retval bool sensor reliability state */ __weak bool BADC_IsObserverConverged( Bemf_ADC_Handle_t * pHandle ) { return pHandle->IsAlgorithmConverged; } /* * @brief Configures the proper ADC channel according to the current * step corresponding to the floating phase. To be periodically called * at least at every step change. * @param pHandle: handler of the current instance of the Bemf_ADC component * @param Phase: Floating phase for bemf acquisition */ void BADC_SelectAdcChannel(Bemf_ADC_Handle_t * pHandle, uint8_t Phase) { while (LL_ADC_REG_IsConversionOngoing(ADC1)) { LL_ADC_REG_StopConversion(ADC1); while(LL_ADC_REG_IsStopConversionOngoing(ADC1)); } /* Sampling time configuration */ /* Regular sequence configuration */ LL_ADC_REG_SetSequencerChannels(ADC1, __LL_ADC_DECIMAL_NB_TO_CHANNEL(pHandle->pParams_str->AdcChannel[Phase])); LL_ADC_ClearFlag_EOC(ADC1); } /* * @brief Updates the estimated electrical angle. * @param pHandle: handler of the current instance of the Bemf_ADC component * @retval int16_t rotor electrical angle (s16Degrees) */ __weak int16_t BADC_CalcElAngle(Bemf_ADC_Handle_t * pHandle) { int16_t retValue; if (pHandle->_Super.hElSpeedDpp != MAX_PSEUDO_SPEED) { if (false == pHandle->IsLoopClosed) { pHandle->MeasuredElAngle += pHandle->_Super.hElSpeedDpp; pHandle->PrevRotorFreq = pHandle->_Super.hElSpeedDpp; pHandle->_Super.hElAngle += pHandle->_Super.hElSpeedDpp + pHandle->CompSpeed; } else { pHandle->_Super.hElAngle = pHandle->MeasuredElAngle; } } else { pHandle->_Super.hElAngle += pHandle->PrevRotorFreq; } retValue = pHandle->_Super.hElAngle; return (retValue); } /* * @brief Must be called - at least - with the same periodicity * on which speed control is executed. It computes and update component * variable hElSpeedDpp that is estimated average electrical speed * expressed in dpp used for instance in observer equations. * Average is computed considering a FIFO depth equal to * bSpeedBufferSizedpp. * @param pHandle: handler of the current instance of the Bemf_ADC component */ void BADC_CalcAvrgElSpeedDpp( Bemf_ADC_Handle_t * pHandle ) { uint32_t wCaptBuf; /* used to validate the average speed measurement */ if (pHandle->BufferFilled < pHandle->SpeedBufferSize) { pHandle->BufferFilled++; } else { /* Nothing to do */ } if (false == pHandle->IsLoopClosed) { if (pHandle->VirtualElSpeedDpp == 0) pHandle->Counter_Period = 0xFFFF; else pHandle->Counter_Period = ( uint32_t )(pHandle->PseudoPeriodConv / ((pHandle->LowFreqTimerPsc + 1) * pHandle->VirtualElSpeedDpp)); } else { pHandle->Counter_Period = pHandle->ZC_Counter_Last + pHandle->Last_Zc2Comm_Delay; } wCaptBuf = pHandle->Counter_Period * (pHandle->LowFreqTimerPsc + 1); /* Filtering to fast speed... could be a glitch ? */ /* the MAX_PSEUDO_SPEED is temporary in the buffer, and never included in average computation*/ if (wCaptBuf < pHandle->MinPeriod) { /* Nothing to do */ } else { pHandle->ElPeriodSum -= pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx]; /* value we gonna removed from the accumulator */ if (wCaptBuf >= pHandle->MaxPeriod) { pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx] = (int32_t)pHandle->MaxPeriod * pHandle->Direction; } else { pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx] = (int32_t)wCaptBuf ; pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx] *= pHandle->Direction; pHandle->ElPeriodSum += pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx]; } /* Update pointers to speed buffer */ pHandle->SpeedFIFOIdx++; if (pHandle->SpeedFIFOIdx == pHandle->SpeedBufferSize) { pHandle->SpeedFIFOIdx = 0U; } if (((pHandle->BufferFilled < pHandle->SpeedBufferSize) && (wCaptBuf != 0U)) || (false == pHandle->IsLoopClosed)) { uint32_t tempReg = (pHandle->PseudoPeriodConv / wCaptBuf) * (uint32_t)pHandle->Direction; pHandle->AvrElSpeedDpp = (int16_t)tempReg; } else { /* Average speed allow to smooth the mechanical sensors misalignement */ int32_t tElPeriodSum = 0; uint8_t i; for (i=0; i < pHandle->SpeedBufferSize; i++) { tElPeriodSum += pHandle->SpeedBufferDpp[i]; } pHandle->AvrElSpeedDpp = (int16_t)((int32_t)pHandle->PseudoPeriodConv / (tElPeriodSum / (int32_t)pHandle->SpeedBufferSize)); /* Average value */ } } } /* * @brief Used to calculate instant speed during revup, to * initialize parameters at step change and to select proper ADC channel * for next Bemf acquisitions * @param pHandle: handler of the current instance of the Bemf_ADC component * @param hElSpeedDpp: Mechanical speed imposed by virtual speed component * @param pHandlePWMC: handler of the current instance of the PWMC component */ void BADC_StepChangeEvent(Bemf_ADC_Handle_t * pHandle, int16_t hElSpeedDpp, PWMC_Handle_t *pHandlePWMC) { pHandle->DemagCounter = 0; while (LL_ADC_REG_IsConversionOngoing(ADC1)) { LL_ADC_REG_StopConversion(ADC1); while(LL_ADC_REG_IsStopConversionOngoing(ADC1)); } BADC_Stop(pHandle); pHandle->Last_Zc2Comm_Delay = LL_TIM_GetAutoReload(pHandle->pParams_str->LfTim) - pHandle->ZC_Counter_Last; if (false == pHandle->IsLoopClosed) { if (hElSpeedDpp < 0) { pHandle->VirtualElSpeedDpp = - hElSpeedDpp; } else { pHandle->VirtualElSpeedDpp = hElSpeedDpp; } pHandle->ZcDetected = false; } else { int16_t ElAngleUpdate; if(pHandle->Direction == -1) { ElAngleUpdate = -S16_60_PHASE_SHIFT ; } else { ElAngleUpdate = S16_60_PHASE_SHIFT ; } pHandle->MeasuredElAngle += ElAngleUpdate; if ( false == pHandle->ZcDetected) { LL_TIM_SetAutoReload(pHandle->pParams_str->LfTim,LL_TIM_GetAutoReload(pHandle->pParams_str->LfTim) * 120 / 100); } else { pHandle->ZcDetected = false; } } pHandle->StepUpdate = true; } /* * @brief Calculates and stores in the corresponding variable the demagnetization * time in open loop operation * @param pHandle: handler of the current instance of the Bemf_ADC component * @param pHandleSTC: handler of the current instance of the Speed Control component */ void BADC_CalcRevUpDemagTime(Bemf_ADC_Handle_t *pHandle) { int16_t hSpeed; hSpeed = (int16_t)((pHandle->VirtualElSpeedDpp * (int32_t)pHandle->_Super.hMeasurementFrequency * (int32_t)SPEED_UNIT ) / ((int32_t)(pHandle->_Super.DPPConvFactor) * (int32_t)(pHandle->_Super.bElToMecRatio)) );; if (hSpeed == 0) { pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold;; } else { pHandle->DemagCounterThreshold = (uint16_t) (pHandle->DemagParams.RevUpDemagSpeedConv / hSpeed); } if (pHandle->DemagCounterThreshold < pHandle->DemagParams.DemagMinimumThreshold) { pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold; } } /* * @brief Calculates and stores in the corresponding variable the demagnetization * time in closed loop operation * @param pHandle: handler of the current instance of the Bemf_ADC component * @param pHandleSTC: handler of the current instance of the Speed Control component */ void BADC_CalcRunDemagTime(Bemf_ADC_Handle_t *pHandle) { int16_t hSpeed; hSpeed = pHandle->_Super.hAvrMecSpeedUnit; if (hSpeed < 0) hSpeed = - hSpeed; if (hSpeed < pHandle->DemagParams.DemagMinimumSpeedUnit) { pHandle->DemagCounterThreshold = (uint16_t) (pHandle->DemagParams.RunDemagSpeedConv / hSpeed); if (pHandle->DemagCounterThreshold < pHandle->DemagParams.DemagMinimumThreshold) { pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold; } } else { pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold; } } /* * @brief This method must be called after switch-over procedure when * virtual speed sensor transition is ended. * @param pHandle: handler of the current instance of the STO component */ void BADC_SetLoopClosed(Bemf_ADC_Handle_t *pHandle) { pHandle->IsLoopClosed=true; } /* * @brief Returns the last acquired bemf value * @param pHandle: handler of the current instance of the Bemf_ADC component * @param phase: motor phase under investigation * @retval uint16_t: Bemf value */ uint16_t BADC_GetLastBemfValue(Bemf_ADC_Handle_t *pHandle, uint8_t phase) { return ((MC_NULL == pHandle) ? 0U : pHandle->BemfLastValues[phase]); } /* * @brief Returns the zero crossing detection flag * @param pHandle: handler of the current instance of the Bemf_ADC component * @retval bool: zero crossing detection flag */ bool BADC_GetBemfZcrFlag(Bemf_ADC_Handle_t *pHandle) { return ((MC_NULL == pHandle) ? 0U : pHandle->ZcDetected); } /* * @brief Returns true if the step needs to be updated * @param pHandle: handler of the current instance of the Bemf_ADC component * @retval bool: step update request */ bool BADC_ClearStepUpdate(Bemf_ADC_Handle_t *pHandle) { bool retValue = (((pHandle->IsLoopClosed == true) && (pHandle->StepUpdate == true)) || (pHandle->IsLoopClosed == false)); pHandle->StepUpdate = false; return retValue; } /* * @brief Configures the parameters for bemf sensing during pwm off-time * @param pHandle: handler of the current instance of the Bemf_ADC component * @param BemfAdcConfig: thresholds and sampling time parameters * @param Zc2CommDelay: delay between bemf zero crossing parameter and step commutation * @param bemfAdcDemagConfig: demagnetization parameters */ void BADC_SetBemfSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfAdcConfig, uint16_t *Zc2CommDelay, Bemf_Demag_Params *bemfAdcDemagConfig) { pHandle->Pwm_OFF.AdcThresholdUp = BemfAdcConfig->AdcThresholdUp; pHandle->Pwm_OFF.AdcThresholdDown = BemfAdcConfig->AdcThresholdDown; pHandle->Pwm_OFF.SamplingPoint = BemfAdcConfig->SamplingPoint; pHandle->Zc2CommDelay = *Zc2CommDelay; pHandle->DemagParams.DemagMinimumSpeedUnit = bemfAdcDemagConfig->DemagMinimumSpeedUnit; pHandle->DemagParams.DemagMinimumThreshold = bemfAdcDemagConfig->DemagMinimumThreshold; } /* * @brief Configures the parameters for bemf sensing during pwm on-time * @param pHandle: handler of the current instance of the Bemf_ADC component * @param BemfOnAdcConfig: thresholds and sampling time parameters * @param OnSensingEnThres: Minimum dudty cycle for on-sensing activation * @param OnSensingDisThres: Minimum duty cycle for on-sensing Deactivationg */ void BADC_SetBemfOnTimeSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfOnAdcConfig, uint16_t *OnSensingEnThres, uint16_t *OnSensingDisThres) { pHandle->Pwm_ON.AdcThresholdUp = BemfOnAdcConfig->AdcThresholdUp; pHandle->Pwm_ON.AdcThresholdDown = BemfOnAdcConfig->AdcThresholdDown; pHandle->Pwm_ON.SamplingPoint = BemfOnAdcConfig->SamplingPoint; pHandle->OnSensingEnThres = *OnSensingEnThres; pHandle->OnSensingDisThres = *OnSensingDisThres; } /* * @brief Gets the parameters for bemf sensing during pwm off-time * @param pHandle: handler of the current instance of the Bemf_ADC component * @param BemfAdcConfig: thresholds and sampling time parameters * @param Zc2CommDelay: delay between bemf zero crossing parameter and step commutation * @param bemfAdcDemagConfig: demagnetization parameters */ void BADC_GetBemfSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfAdcConfig, uint16_t *Zc2CommDelay, Bemf_Demag_Params *BemfAdcDemagConfig) { BemfAdcConfig->AdcThresholdUp = pHandle->Pwm_OFF.AdcThresholdUp; BemfAdcConfig->AdcThresholdDown = pHandle->Pwm_OFF.AdcThresholdDown; BemfAdcConfig->SamplingPoint = pHandle->Pwm_OFF.SamplingPoint; *Zc2CommDelay = pHandle->Zc2CommDelay; BemfAdcDemagConfig->DemagMinimumSpeedUnit = pHandle->DemagParams.DemagMinimumSpeedUnit; BemfAdcDemagConfig->DemagMinimumThreshold = pHandle->DemagParams.DemagMinimumThreshold; } /* * @brief Gets the parameters for bemf sensing during pwm on-time * @param pHandle: handler of the current instance of the Bemf_ADC component * @param BemfOnAdcConfig: thresholds and sampling time parameters * @param OnSensingEnThres: Minimum duty cycle for on-sensing activation * @param OnSensingDisThres: Minimum duty cycle for on-sensing Deactivationg */ void BADC_GetBemfOnTimeSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfOnAdcConfig, uint16_t *OnSensingEnThres, uint16_t *OnSensingDisThres) { BemfOnAdcConfig->AdcThresholdUp = pHandle->Pwm_ON.AdcThresholdUp; BemfOnAdcConfig->AdcThresholdDown = pHandle->Pwm_ON.AdcThresholdDown; BemfOnAdcConfig->SamplingPoint = pHandle->Pwm_ON.SamplingPoint; *OnSensingEnThres = pHandle->OnSensingEnThres; *OnSensingDisThres = pHandle->OnSensingDisThres; } /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
33,860
C
33.908247
167
0.644093
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/C0xx/Inc/c0xx_bemf_ADC_OS_fdbk.h
/** ****************************************************************************** * @file c0xx_bemf_ADC_OS_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * multiple sensorless Bemf acquisition with ADC component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup SpeednPosFdbk_Bemf */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef BEMFADCFDBK_H #define BEMFADCFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "speed_pos_fdbk.h" #include "speed_ctrl.h" #include "pwm_common_sixstep.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup SpeednPosFdbk * @{ */ /** @addtogroup SpeednPosFdbk_Bemf * @{ */ #define SPEED_BUFFER_LENGTH ((uint8_t) 18) /* Length of buffer used to store the timer period measurements */ /* * @brief Bemf_ADC parameters definition */ typedef struct { TIM_TypeDef * LfTim; /* Contains the pointer to the LF timer used for speed measurement. */ uint32_t LfTimerChannel; /* Channel of the LF timer used for speed measurement */ ADC_TypeDef * pAdc[3]; /* Pointer to the ADC */ uint32_t AdcChannel[3]; /* Array of ADC channels used for BEMF sensing */ bool gpio_divider_available; /* Availability of the GPIO port enabling the bemf resistor divider */ GPIO_TypeDef * bemf_divider_port; /* GPIO port enabling the bemf resistor divider */ uint16_t bemf_divider_pin; /* GPIO pin enabling the bemf resistor divider */ uint32_t TIM_ADC_Trigger_Channel; TIM_TypeDef * TIM_Trigger; } Bemf_ADC_Params_t; /* * @brief This structure is used to handle the thresholds for bemf zero crossing detection * */ typedef struct { uint16_t AdcThresholdDown; /* BEMF voltage threshold for zero crossing detection when BEMF is decreasing */ uint16_t AdcThresholdUp; /* BEMF voltage threshold for zero crossing detection when BEMF is increasing */ uint16_t SamplingPoint; /* Pulse value of the timer channel used to trig the ADC when sensing occurs during PWM OFF time */ } Bemf_Sensing_Params; /* * @brief This structure is used to handle the demagnetization time before starting bemf acquisition * */ typedef struct { uint16_t DemagMinimumSpeedUnit; /* Speed threshold for minimum demagnetization time */ uint16_t RevUpDemagSpeedConv; /* Convertion factor between speed and demagnetization time */ uint16_t RunDemagSpeedConv; /* Open loop convertion factor between speed and demagnetization time during */ uint16_t DemagMinimumThreshold; /* Minimum demagnetization time */ } Bemf_Demag_Params; /* * @brief This structure is used to handle the data of an instance of the B-emf Feedback component * */ typedef struct { SpeednPosFdbk_Handle_t _Super; uint16_t BemfLastValues[3]; /* Bemf measurements of phase */ uint8_t ZcEvents; /* Number of bemf zero crossing events */ Bemf_Sensing_Params Pwm_ON; /* Parameters for zero crossing detection during ON time */ Bemf_Sensing_Params Pwm_OFF; /* Parameters for zero crossing detection during OFF time */ Bemf_Sensing_Params *pSensing_Params; uint16_t SamplingGuard; bool IsOnSensingEnabled; /* Value where 0 means BEMF is sensed during PWM OFF time and 1 or greater means BEMF is sensed during PWM ON time */ uint16_t OnSensingEnThres; /* Pulse value of HF timer above which the PWM ON sensing is enabled */ uint16_t OnSensingDisThres; /* Pulse value of HF timer below which the PWM ON sensing is disabled */ uint16_t Zc2CommDelay; /* Zero Crossing detection to commutation delay in 15/128 degrees */ Bemf_ADC_Params_t const *pParams_str; uint16_t SpeedSamplingFreqHz; /* Frequency (Hz) at which motor speed is to be computed. It must be equal to the frequency at which function SPD_CalcAvrgMecSpeedUnit is called.*/ uint8_t SpeedBufferSize; /* Size of the buffer used to calculate the average speed. It must be less than 18.*/ uint32_t TIMClockFreq; bool ADCRegularLocked; /* This flag is set when ADC is locked for bemf acquisition */ uint16_t ADC1_DMA_converted[5]; /* Buffer used for DMA data transfer after the ADC conversion */ uint16_t TIM1_pulses[5]; /* Buffer used for DMA data transfer after the ADC conversion */ int32_t ElPeriodSum; /* Period accumulator used to speed up the average speed computation*/ int16_t PrevRotorFreq; /* Used to store the last valid rotor electrical speed in dpp used when MAX_PSEUDO_SPEED is detected */ int8_t Direction; /* Instantaneous direction of rotor between two captures*/ int16_t AvrElSpeedDpp; /* Averaged rotor electrical speed express in s16degree per current control period.*/ int16_t VirtualElSpeedDpp; /* Averaged rotor electrical speed express in s16degree per current control period.*/ uint16_t MinStartUpValidSpeed; /* Absolute value of minimum mechanical speed required to validate the start-up. Expressed in the unit defined by #SPEED_UNIT. */ uint8_t StartUpConsistThreshold; /* Number of consecutive tests on speed consistency to be passed before validating the start-up */ uint8_t OverSamplingRate; bool IsSpeedReliable; /* Latest private speed reliability information, updated by SPD_CalcAvrgMecSpeedUnit, it is true if the speed measurement variance is lower then threshold corresponding to hVariancePercentage */ bool IsAlgorithmConverged; /* Boolean variable containing observer convergence information */ bool IsLoopClosed; /* Boolean variable containing speed loop status*/ bool ZcDetected; /* This flag is set when zero crossing is detected */ bool StepUpdate; /* This flag is set when step needs to be updated */ DrivingMode_t DriveMode; volatile uint8_t BufferFilled; /* Indicates the number of speed measuremt present in the buffer from the start. It will be max bSpeedBufferSize and it is used to validate the start of speed averaging. If bBufferFilled is below bSpeedBufferSize the instantaneous measured speed is returned as average speed.*/ int32_t SpeedBufferDpp[SPEED_BUFFER_LENGTH];/* Holding the last period captures */ uint32_t LowFreqTimerPsc; /* Prescaler value of the low frequency timer */ uint16_t SpeedFIFOIdx;/* Pointer of next element to be stored in the speed sensor buffer*/ int16_t DeltaAngle; /* Delta angle at the Hall sensor signal edge between current electrical rotor angle of synchronism. It is in s16degrees.*/ int16_t MeasuredElAngle; /* Electrical angle measured at each bemf zero crossing. It is considered the best measurement of electrical rotor angle.*/ int16_t CompSpeed; /* Speed compensation factor used to syncronize the current electrical angle with the target electrical angle. */ uint16_t SatSpeed; /* Returned value if the measured speed is above the maximum realistic.*/ uint32_t PseudoPeriodConv;/* Conversion factor between time interval Delta T between bemf zero crossing points, express in timer counts, and electrical rotor speed express in dpp. Ex. Rotor speed (dpp) = wPseudoFreqConv / Delta T It will be ((CKTIM / 6) / (SAMPLING_FREQ)) * 65536.*/ uint32_t MaxPeriod; /* Time delay between two bemf zero crossing points when the speed of the rotor is the minimum realistic in the application: this allows to discriminate too low freq for instance. This period shoud be expressed in timer counts and it will be: wMaxPeriod = ((10 * CKTIM) / 6) / MinElFreq(0.1Hz).*/ uint32_t MinPeriod; /* Time delay between two bemf zero crossing points when the speed of the rotor is the maximum realistic in the application: this allows discriminating glitches for instance. This period shoud be expressed in timer counts and it will be: wSpeedOverflow = ((10 * CKTIM) / 6) / MaxElFreq(0.1Hz).*/ uint16_t BemfTimeout; /* Max delay between two zero crossing signals to assert zero speed express in milliseconds.*/ uint16_t OvfFreq; /* Frequency of timer overflow (from 0 to 0x10000) it will be: hOvfFreq = CKTIM /65536.*/ uint16_t PWMNbrPSamplingFreq; /* Number of current control periods inside each speed control periods it will be: (hMeasurementFrequency / hSpeedSamplingFreqHz) - 1.*/ uint8_t PWMFreqScaling; /* Scaling factor to allow to store a PWMFrequency greater than 16 bits */ uint32_t Counter_Period; /* Low frequency timer period that allows speed calculation */ uint32_t ZC_Counter_Up; /* Low frequency timer counter value at zero crossing with increasing bemf */ uint32_t ZC_Counter_Down; /* Low frequency timer counter value at zero crossing with increasing bemf */ uint32_t ZC_Counter_Last; /* Last low frequency timer counter value at zero crossing */ uint32_t ZC_Counter_On_Last; /* Last low frequency timer counter value at zero crossing sensed with pwm on*/ uint32_t Last_Zc2Comm_Delay; /* Last delay between zero crossing and step change */ uint16_t DemagCounter; /* Demagnetization counter */ uint16_t DemagCounterThreshold; /* PWM cycles dedicated to windings demagnetization */ Bemf_Demag_Params DemagParams; /* Demagnetization parameters */ } Bemf_ADC_Handle_t; /* Exported functions --------------------------------------------------------*/ /* Initializes all the object variables. */ void BADC_Init( Bemf_ADC_Handle_t *pHandle ); /* Resets the ADC status and empties arrays. */ void BADC_Clear( Bemf_ADC_Handle_t *pHandle ); /* Gets ADC value and check for zero crossing detection.*/ bool BADC_IsZcDetected( Bemf_ADC_Handle_t *pHandle, PWMC_Handle_t *pHandlePWMC); /* Sets the trigger point of the ADC */ void BADC_SetSamplingPoint(Bemf_ADC_Handle_t *pHandle, PWMC_Handle_t *pHandlePWMC, SpeednTorqCtrl_Handle_t *pHandleSTC ); /* Computes the rotor average mechanical speed in the unit defined by #SPEED_UNIT and returns it in pMecSpeedUnit. */ bool BADC_CalcAvrgMecSpeedUnit( Bemf_ADC_Handle_t * pHandle, int16_t * pMecSpeedUnit ); /* Forces the rotation direction. */ void BADC_SetDirection( Bemf_ADC_Handle_t * pHandle, uint8_t direction ); /* Checks whether the state observer algorithm converged.*/ bool BADC_IsObserverConverged( Bemf_ADC_Handle_t * pHandle ); /* Starts the bemf acquisition.*/ void BADC_Start(Bemf_ADC_Handle_t *pHandle, uint8_t step); /* Stops the bemf acquisition.*/ void BADC_Stop(Bemf_ADC_Handle_t *pHandle); /* Selects the phase for the bemf acquisition.*/ void BADC_SelectAdcChannel(Bemf_ADC_Handle_t * pHandle, uint8_t Phase); /* Updates the estimated electrical angle.*/ int16_t BADC_CalcElAngle(Bemf_ADC_Handle_t * pHandle); /* Configures the sensorless parameters for the following step. */ void BADC_StepChangeEvent(Bemf_ADC_Handle_t * pHandle, int16_t hElSpeedDpp, PWMC_Handle_t *pHandlePWMC); /* Computes the demagnetization time during revup procedure. */ void BADC_CalcRevUpDemagTime(Bemf_ADC_Handle_t *pHandle); /* Computes the demagnetization time in closed loop operation.*/ void BADC_CalcRunDemagTime(Bemf_ADC_Handle_t *pHandle); /* Sets the flag when switch over phase ends.*/ void BADC_SetLoopClosed(Bemf_ADC_Handle_t *pHandle); /* Returns last converted Back-emf value.*/ uint16_t BADC_GetLastBemfValue(Bemf_ADC_Handle_t *pHandle, uint8_t phase); /* Returns the zero crossing detection flag. */ bool BADC_GetBemfZcrFlag(Bemf_ADC_Handle_t *pHandle); /* Enables low frequecy timer interrupt */ void BADC_SpeedMeasureOn(Bemf_ADC_Handle_t *pHandle); /* Disables low frequecy timer interrupt */ void BADC_SpeedMeasureOff(Bemf_ADC_Handle_t *pHandle); /* Clears StepUpdate flag */ bool BADC_ClearStepUpdate(Bemf_ADC_Handle_t *pHandle); /* Sets the parameters for bemf sensing during pwm off-time */ void BADC_SetBemfSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfAdcConfig, uint16_t *Zc2CommDelay, Bemf_Demag_Params *bemfAdcDemagConfig); /* Sets the parameters for bemf sensing during pwm on-time */ void BADC_SetBemfOnTimeSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfOnAdcConfig, uint16_t *OnSensingEnThres, uint16_t *OnSensingDisThres); /* Gets the parameters for bemf sensing during pwm off-time */ void BADC_GetBemfSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfAdcConfig, uint16_t *Zc2CommDelay, Bemf_Demag_Params *bemfAdcDemagConfig); /* Gets the parameters for bemf sensing during pwm on-time */ void BADC_GetBemfOnTimeSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfOnAdcConfig, uint16_t *OnSensingEnThres, uint16_t *OnSensingDisThres); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* BEMFADCFDBK_H */ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
15,524
C
50.237624
150
0.617302
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/C0xx/Inc/r3_c0xx_pwm_curr_fdbk.h
/** ****************************************************************************** * @file r3_c0xx_pwm_curr_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * r3_c0xx_pwm_curr_fdbk component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup R3_C0XX_pwm_curr_fdbk */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __R3_C0XX_PWMNCURRFDBK_H #define __R3_C0XX_PWMNCURRFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "pwm_curr_fdbk.h" /** * @addtogroup MCSDK * @{ */ /** * @addtogroup pwm_curr_fdbk * @{ */ /** * @addtogroup R3_1_pwm_curr_fdbk * @{ */ /* Exported constants --------------------------------------------------------*/ /* Exported types ------------------------------------------------------------*/ /* * @brief R3_C0XX parameters definition */ typedef struct { TIM_TypeDef * TIMx; /* Timer used for PWM generation. */ uint32_t ADCConfig[6]; /* Stores ADC sequence for the 6 sectors. */ volatile uint16_t *ADCDataReg1[6]; /* Stores ADC read value's address for the 6 sectors. */ volatile uint16_t *ADCDataReg2[6]; /* Stores ADC read value's address for the 6 sectors. */ uint16_t hDeadTime; /* Dead time in number of TIM clock cycles. If CHxN are enabled, it must contain the dead time to be generated by the microcontroller, otherwise it expresses the maximum dead time generated by driving network. */ uint16_t hTafter; /* Sum of dead time plus max value between rise time and noise time express in number of TIM clocks.*/ uint16_t hTbefore; /* Sampling time expressed in number of TIM clocks.*/ uint16_t Tsampling; /* Sampling time expressed in number of TIM clocks.*/ uint16_t Tcase2; /* Sampling time expressed in number of TIM clocks.*/ uint16_t Tcase3; /* Sampling time expressed in number of TIM clocks.*/ uint8_t b_ISamplingTime; /* Sampling time used to convert hI[a|b|c]Channel. It must be equal to ADC_SampleTime_xCycles5 x= 1, 7, ...*/ uint8_t RepetitionCounter; /* Expresses the number of PWM periods to be elapsed before compare registers are updated again. In particular: RepetitionCounter= (2* #PWM periods)-1*/ uint8_t ADCScandir[6]; /* Stores ADC scan direction for the 6 sectors. */ } R3_1_Params_t; /* * @brief Handle structure of the R1_C0xx_pwm_curr_fdbk Component */ typedef struct { PWMC_Handle_t _Super; /* Base component handler. */ uint32_t PhaseAOffset; /* Offset of Phase A current sensing network. */ uint32_t PhaseBOffset; /* Offset of Phase B current sensing network. */ uint32_t PhaseCOffset; /* Offset of Phase C current sensing network. */ volatile uint32_t ADCTriggerEdge; /* External ADC trigger edge. */ uint16_t Half_PWMPeriod; /* Half PWM Period in timer clock counts. */ volatile uint16_t ADC1_DMA_converted[2]; /* Buffer used for DMA data transfer after the ADC conversion. */ volatile uint8_t PolarizationCounter; /* Number of conversions performed during the calibration phase. */ uint8_t CalibSector; /* Space vector sector number during calibration */ bool ADCRegularLocked; /* This flag is set when regular conversions are locked.*/ R3_1_Params_t const * pParams_str; } PWMC_R3_1_Handle_t; /* Exported functions ------------------------------------------------------- */ /* * Initializes TIM1, ADC1, GPIO, DMA1 and NVIC for three shunt current * reading configuration using STM32c0x. */ void R3_1_Init( PWMC_R3_1_Handle_t * pHandle ); /* * Stores into the handler the voltage present on the * current feedback analog channel when no current is flowin into the * motor */ void R3_1_CurrentReadingCalibration( PWMC_Handle_t * pHdl ); /* * Computes and return latest converted motor phase currents */ void R3_1_GetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ); /* * Computes and return latest converted motor phase currents motor * */ void R3_1_GetPhaseCurrents_OVM( PWMC_Handle_t * pHdl, ab_t * Iab ); /* * Configures the ADC for the current sampling related to sector X (X = [1..6] ). */ uint16_t R3_1_SetADCSampPointSectX(PWMC_Handle_t * pHdl ); /* * Configure the ADC for the current sampling related to sector X (X = [1..6] ) in case of overmodulation. */ uint16_t R3_1_SetADCSampPointSectX_OVM( PWMC_Handle_t * pHdl ); /* * Configures the ADC for the current sampling during calibration. */ uint16_t R3_1_SetADCSampPointCalibration( PWMC_Handle_t * pHdl ); /* * Turns on low sides switches. */ void R3_1_TurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ); /* * Enables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_1_SwitchOnPWM( PWMC_Handle_t * pHdl ); /* * Disables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_1_SwitchOffPWM( PWMC_Handle_t * pHdl ); /* * Contains the TIMx Update event interrupt. */ void * R3_1_TIMx_UP_IRQHandler( PWMC_R3_1_Handle_t * pHandle ); /* * Sets the calibrated offset. */ void R3_1_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /* * Reads the calibrated offsets. */ void R3_1_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /** * @} */ /** * @} */ /** @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*__R3_F0XX_PWMNCURRFDBK_H*/ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
6,977
C
34.784615
108
0.55425
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/C0xx/Inc/c0xx_bemf_ADC_fdbk.h
/** ****************************************************************************** * @file c0xx_bemf_ADC_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * Sensorless Bemf acquisition with ADC component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup SpeednPosFdbk_Bemf */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef BEMFADCFDBK_H #define BEMFADCFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "speed_pos_fdbk.h" #include "speed_ctrl.h" #include "pwm_common_sixstep.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup SpeednPosFdbk * @{ */ /** @addtogroup SpeednPosFdbk_Bemf * @{ */ #define SPEED_BUFFER_LENGTH ((uint8_t) 18) /* Length of buffer used to store the timer period measurements */ /* * @brief Bemf_ADC parameters definition */ typedef struct { TIM_TypeDef * LfTim; /* Contains the pointer to the LF timer used for speed measurement. */ uint32_t LfTimerChannel; /* Channel of the LF timer used for speed measurement */ ADC_TypeDef * pAdc[3]; /* Pointer to the ADC */ uint32_t AdcChannel[3]; /* Array of ADC channels used for BEMF sensing */ bool gpio_divider_available; /* Availability of the GPIO port enabling the bemf resistor divider */ GPIO_TypeDef * bemf_divider_port; /* GPIO port enabling the bemf resistor divider */ uint16_t bemf_divider_pin; /* GPIO pin enabling the bemf resistor divider */ } Bemf_ADC_Params_t; /* * @brief This structure is used to handle the thresholds for bemf zero crossing detection * */ typedef struct { uint16_t AdcThresholdDown; /* BEMF voltage threshold for zero crossing detection when BEMF is decreasing */ uint16_t AdcThresholdUp; /* BEMF voltage threshold for zero crossing detection when BEMF is increasing */ uint16_t SamplingPoint; /* Pulse value of the timer channel used to trig the ADC when sensing occurs during PWM OFF time */ } Bemf_Sensing_Params; /* * @brief This structure is used to handle the demagnetization time before starting bemf acquisition * */ typedef struct { uint16_t DemagMinimumSpeedUnit; /* Speed threshold for minimum demagnetization time */ uint16_t RevUpDemagSpeedConv; /* Convertion factor between speed and demagnetization time */ uint16_t RunDemagSpeedConv; /* Open loop convertion factor between speed and demagnetization time during */ uint16_t DemagMinimumThreshold; /* Minimum demagnetization time */ } Bemf_Demag_Params; /* * @brief This structure is used to handle the data of an instance of the B-emf Feedback component * */ typedef struct { SpeednPosFdbk_Handle_t _Super; uint16_t BemfLastValues[3]; /* Bemf measurements of phase */ uint8_t ZcEvents; /* Number of bemf zero crossing events */ Bemf_Sensing_Params Pwm_ON; /* Parameters for zero crossing detection during ON time */ Bemf_Sensing_Params Pwm_OFF; /* Parameters for zero crossing detection during OFF time */ Bemf_Sensing_Params *pSensing_Params; uint16_t SamplingGuard; bool IsOnSensingEnabled; /* Value where 0 means BEMF is sensed during PWM OFF time and 1 or greater means BEMF is sensed during PWM ON time */ uint16_t OnSensingEnThres; /* Pulse value of HF timer above which the PWM ON sensing is enabled */ uint16_t OnSensingDisThres; /* Pulse value of HF timer below which the PWM ON sensing is disabled */ uint16_t Zc2CommDelay; /* Zero Crossing detection to commutation delay in 15/128 degrees */ Bemf_ADC_Params_t const *pParams_str; uint16_t SpeedSamplingFreqHz; /* Frequency (Hz) at which motor speed is to be computed. It must be equal to the frequency at which function SPD_CalcAvrgMecSpeedUnit is called.*/ uint8_t SpeedBufferSize; /* Size of the buffer used to calculate the average speed. It must be less than 18.*/ uint32_t TIMClockFreq; bool ADCRegularLocked; /* This flag is set when ADC is locked for bemf acquisition */ uint16_t ADC1_DMA_converted[1]; /* Buffer used for DMA data transfer after the ADC conversion */ int32_t ElPeriodSum; /* Period accumulator used to speed up the average speed computation*/ int16_t PrevRotorFreq; /* Used to store the last valid rotor electrical speed in dpp used when MAX_PSEUDO_SPEED is detected */ int8_t Direction; /* Instantaneous direction of rotor between two captures*/ int16_t AvrElSpeedDpp; /* Averaged rotor electrical speed express in s16degree per current control period.*/ int16_t VirtualElSpeedDpp; /* Averaged rotor electrical speed express in s16degree per current control period.*/ uint16_t MinStartUpValidSpeed; /* Absolute value of minimum mechanical speed required to validate the start-up. Expressed in the unit defined by #SPEED_UNIT. */ uint8_t StartUpConsistThreshold; /* Number of consecutive tests on speed consistency to be passed before validating the start-up */ bool IsSpeedReliable; /* Latest private speed reliability information, updated by SPD_CalcAvrgMecSpeedUnit, it is true if the speed measurement variance is lower then threshold corresponding to hVariancePercentage */ bool IsAlgorithmConverged; /* Boolean variable containing observer convergence information */ bool IsLoopClosed; /* Boolean variable containing speed loop status*/ bool ZcDetected; /* This flag is set when zero crossing is detected */ bool StepUpdate; /* This flag is set when step needs to be updated */ DrivingMode_t DriveMode; volatile uint8_t BufferFilled; /* Indicates the number of speed measuremt present in the buffer from the start. It will be max bSpeedBufferSize and it is used to validate the start of speed averaging. If bBufferFilled is below bSpeedBufferSize the instantaneous measured speed is returned as average speed.*/ int32_t SpeedBufferDpp[SPEED_BUFFER_LENGTH];/* Holding the last period captures */ uint32_t LowFreqTimerPsc; /* Prescaler value of the low frequency timer */ uint16_t SpeedFIFOIdx;/* Pointer of next element to be stored in the speed sensor buffer*/ int16_t DeltaAngle; /* Delta angle at the Hall sensor signal edge between current electrical rotor angle of synchronism. It is in s16degrees.*/ int16_t MeasuredElAngle; /* Electrical angle measured at each bemf zero crossing. It is considered the best measurement of electrical rotor angle.*/ int16_t CompSpeed; /* Speed compensation factor used to syncronize the current electrical angle with the target electrical angle. */ uint16_t SatSpeed; /* Returned value if the measured speed is above the maximum realistic.*/ uint32_t PseudoPeriodConv;/* Conversion factor between time interval Delta T between bemf zero crossing points, express in timer counts, and electrical rotor speed express in dpp. Ex. Rotor speed (dpp) = wPseudoFreqConv / Delta T It will be ((CKTIM / 6) / (SAMPLING_FREQ)) * 65536.*/ uint32_t MaxPeriod; /* Time delay between two bemf zero crossing points when the speed of the rotor is the minimum realistic in the application: this allows to discriminate too low freq for instance. This period shoud be expressed in timer counts and it will be: wMaxPeriod = ((10 * CKTIM) / 6) / MinElFreq(0.1Hz).*/ uint32_t MinPeriod; /* Time delay between two bemf zero crossing points when the speed of the rotor is the maximum realistic in the application: this allows discriminating glitches for instance. This period shoud be expressed in timer counts and it will be: wSpeedOverflow = ((10 * CKTIM) / 6) / MaxElFreq(0.1Hz).*/ uint16_t BemfTimeout; /* Max delay between two zero crossing signals to assert zero speed express in milliseconds.*/ uint16_t OvfFreq; /* Frequency of timer overflow (from 0 to 0x10000) it will be: hOvfFreq = CKTIM /65536.*/ uint16_t PWMNbrPSamplingFreq; /* Number of current control periods inside each speed control periods it will be: (hMeasurementFrequency / hSpeedSamplingFreqHz) - 1.*/ uint8_t PWMFreqScaling; /* Scaling factor to allow to store a PWMFrequency greater than 16 bits */ uint32_t Counter_Period; /* Low frequency timer period that allows speed calculation */ uint32_t ZC_Counter_Up; /* Low frequency timer counter value at zero crossing with increasing bemf */ uint32_t ZC_Counter_Down; /* Low frequency timer counter value at zero crossing with increasing bemf */ uint32_t ZC_Counter_Last; /* Last low frequency timer counter value at zero crossing */ uint32_t Last_Zc2Comm_Delay; /* Last delay between zero crossing and step change */ uint16_t DemagCounter; /* Demagnetization counter */ uint16_t DemagCounterThreshold; /* PWM cycles dedicated to windings demagnetization */ Bemf_Demag_Params DemagParams; /* Demagnetization parameters */ } Bemf_ADC_Handle_t; /* Exported functions --------------------------------------------------------*/ /* Initializes all the object variables. */ void BADC_Init( Bemf_ADC_Handle_t *pHandle ); /* Resets the ADC status and empties arrays. */ void BADC_Clear( Bemf_ADC_Handle_t *pHandle ); /* Gets ADC value and check for zero crossing detection.*/ bool BADC_IsZcDetected( Bemf_ADC_Handle_t *pHandle, PWMC_Handle_t *pHandlePWMC); /* Sets the trigger point of the ADC */ void BADC_SetSamplingPoint(Bemf_ADC_Handle_t *pHandle, PWMC_Handle_t *pHandlePWMC, SpeednTorqCtrl_Handle_t *pHandleSTC ); /* Computes the rotor average mechanical speed in the unit defined by #SPEED_UNIT and returns it in pMecSpeedUnit. */ bool BADC_CalcAvrgMecSpeedUnit( Bemf_ADC_Handle_t * pHandle, int16_t * pMecSpeedUnit ); /* Forces the rotation direction. */ void BADC_SetDirection( Bemf_ADC_Handle_t * pHandle, uint8_t direction ); /* Checks whether the state observer algorithm converged.*/ bool BADC_IsObserverConverged( Bemf_ADC_Handle_t * pHandle ); /* Starts the bemf acquisition.*/ void BADC_Start(Bemf_ADC_Handle_t *pHandle, uint8_t step); /* Stops the bemf acquisition.*/ void BADC_Stop(Bemf_ADC_Handle_t *pHandle); /* Selects the phase for the bemf acquisition.*/ void BADC_SelectAdcChannel(Bemf_ADC_Handle_t * pHandle, uint8_t Phase); /* Updates the estimated electrical angle.*/ int16_t BADC_CalcElAngle(Bemf_ADC_Handle_t * pHandle); /* Configures the sensorless parameters for the following step. */ void BADC_StepChangeEvent(Bemf_ADC_Handle_t * pHandle, int16_t hElSpeedDpp, PWMC_Handle_t *pHandlePWMC); /* Computes the demagnetization time during revup procedure. */ void BADC_CalcRevUpDemagTime(Bemf_ADC_Handle_t *pHandle); /* Computes the demagnetization time in closed loop operation.*/ void BADC_CalcRunDemagTime(Bemf_ADC_Handle_t *pHandle); /* Sets the flag when switch over phase ends.*/ void BADC_SetLoopClosed(Bemf_ADC_Handle_t *pHandle); /* Returns last converted Back-emf value.*/ uint16_t BADC_GetLastBemfValue(Bemf_ADC_Handle_t *pHandle, uint8_t phase); /* Returns the zero crossing detection flag. */ bool BADC_GetBemfZcrFlag(Bemf_ADC_Handle_t *pHandle); /* Enables low frequecy timer interrupt */ void BADC_SpeedMeasureOn(Bemf_ADC_Handle_t *pHandle); /* Disables low frequecy timer interrupt */ void BADC_SpeedMeasureOff(Bemf_ADC_Handle_t *pHandle); /* Clears StepUpdate flag */ bool BADC_ClearStepUpdate(Bemf_ADC_Handle_t *pHandle); /* Sets the parameters for bemf sensing during pwm off-time */ void BADC_SetBemfSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfAdcConfig, uint16_t *Zc2CommDelay, Bemf_Demag_Params *bemfAdcDemagConfig); /* Sets the parameters for bemf sensing during pwm on-time */ void BADC_SetBemfOnTimeSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfOnAdcConfig, uint16_t *OnSensingEnThres, uint16_t *OnSensingDisThres); /* Gets the parameters for bemf sensing during pwm off-time */ void BADC_GetBemfSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfAdcConfig, uint16_t *Zc2CommDelay, Bemf_Demag_Params *bemfAdcDemagConfig); /* Gets the parameters for bemf sensing during pwm on-time */ void BADC_GetBemfOnTimeSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfOnAdcConfig, uint16_t *OnSensingEnThres, uint16_t *OnSensingDisThres); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* BEMFADCFDBK_H */ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
15,212
C
50.222222
150
0.614844
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/G4xx/Src/r1_g4xx_pwm_curr_fdbk.c
/** ****************************************************************************** * @file r1_g4xx_pwm_curr_fdbk.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement current sensor * class to be stantiated when the single shunt current sensing * topology is used. * * It is specifically designed for STM32G4XX microcontrollers and * implements the successive sampling of motor current using only one ADC. * + initializes MCU peripheral for 1 shunt topology and G4 family * + performs PWM duty cycle computation and generation * + performs current sensing * * ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup R1_G4XX_pwm_curr_fdbk */ /* Includes ------------------------------------------------------------------*/ #include "r1_g4xx_pwm_curr_fdbk.h" #include "pwm_common.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** * @defgroup R1_G4XX_pwm_curr_fdbk G4 R1 1 ADC PWM & Current Feedback * * @brief STM32G4, 1-Shunt, 1 ADC, PWM & Current Feedback implementation * * This component is used in applications based on an STM32G4 MCU * and using a single shunt resistor current sensing topology. * * @{ */ /* Constant values -----------------------------------------------------------*/ #define TIMxCCER_MASK_CH123 (TIM_CCER_CC1E | TIM_CCER_CC2E | TIM_CCER_CC3E |\ TIM_CCER_CC1NE | TIM_CCER_CC2NE | TIM_CCER_CC3NE) /* boundary zone definition */ #define REGULAR ((uint8_t)0u) #define BOUNDARY_1 ((uint8_t)1u) /* Two small, one big */ #define BOUNDARY_2 ((uint8_t)2u) /* Two big, one small */ #define BOUNDARY_3 ((uint8_t)3u) /* Three equal */ #define INVERT_NONE 0u #define INVERT_A 1u #define INVERT_B 2u #define INVERT_C 3u #define SAMP_NO 0u #define SAMP_IA 1u #define SAMP_IB 2u #define SAMP_IC 3u #define SAMP_NIA 4u #define SAMP_NIB 5u #define SAMP_NIC 6u #define SAMP_OLDA 7u #define SAMP_OLDB 8u #define SAMP_OLDC 9u static const uint8_t REGULAR_SAMP_CUR1[6] = {SAMP_NIC, SAMP_NIC, SAMP_NIA, SAMP_NIA, SAMP_NIB, SAMP_NIB}; static const uint8_t REGULAR_SAMP_CUR2[6] = {SAMP_IA, SAMP_IB, SAMP_IB, SAMP_IC, SAMP_IC, SAMP_IA}; static const uint8_t BOUNDR1_SAMP_CUR2[6] = {SAMP_IB, SAMP_IB, SAMP_IC, SAMP_IC, SAMP_IA, SAMP_IA}; static const uint8_t BOUNDR2_SAMP_CUR1[6] = {SAMP_IA, SAMP_IB, SAMP_IB, SAMP_IC, SAMP_IC, SAMP_IA}; static const uint8_t BOUNDR2_SAMP_CUR2[6] = {SAMP_IC, SAMP_IA, SAMP_IA, SAMP_IB, SAMP_IB, SAMP_IC}; /* Private typedef -----------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ void R1_HFCurrentsPolarization(PWMC_Handle_t *pHdl, ab_t *pStator_Currents); void R1_SetAOReferenceVoltage(uint32_t DAC_Channel, DAC_TypeDef *DACx, uint16_t hDACVref); void R1_1ShuntMotorVarsInit(PWMC_Handle_t *pHdl); void R1_TIMxInit(TIM_TypeDef *TIMx, PWMC_R1_Handle_t *pHdl); uint16_t R1_SetADCSampPointPolarization(PWMC_Handle_t *pHdl); /** * @brief Initializes TIMx, ADC, GPIO, DMA1 and NVIC for current reading * in three shunt topology using STM32F30X and shared ADC. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void R1_Init(PWMC_R1_Handle_t *pHandle) { OPAMP_TypeDef *OPAMPx = pHandle->pParams_str->OPAMP_Selection; COMP_TypeDef *COMP_OCPx = pHandle->pParams_str->CompOCPSelection; COMP_TypeDef *COMP_OVPx = pHandle->pParams_str->CompOVPSelection; DAC_TypeDef *DAC_OCPx = pHandle->pParams_str->DAC_OCP_Selection; DAC_TypeDef *DAC_OVP = pHandle->pParams_str->DAC_OVP_Selection; TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef *ADCx = pHandle->pParams_str->ADCx; R1_1ShuntMotorVarsInit(&pHandle->_Super); /* Disable IT and flags in case of LL driver usage * workaround for unwanted interrupt enabling done by LL driver */ LL_ADC_DisableIT_EOC(ADCx); LL_ADC_ClearFlag_EOC(ADCx); LL_ADC_DisableIT_JEOC(ADCx); LL_ADC_ClearFlag_JEOC(ADCx); /* Enable TIM1 - TIM8 clock */ if (TIM1 == TIMx) { /* DMA Event related to TIM1 Channel 4 */ /* DMA1 Channel4 configuration ----------------------------------------------*/ LL_DMA_SetMemoryAddress(DMA1, LL_DMA_CHANNEL_1, (uint32_t)pHandle->DmaBuff); LL_DMA_SetPeriphAddress(DMA1, LL_DMA_CHANNEL_1, (uint32_t) & (TIM1->CCR1)); LL_DMA_SetDataLength(DMA1, LL_DMA_CHANNEL_1, 2); /* Enable DMA1 Channel4 */ LL_DMA_EnableChannel(DMA1, LL_DMA_CHANNEL_1); pHandle->DistortionDMAy_Chx = DMA1_Channel1; } #if (defined(TIM8) && defined(DMA2)) else { /* DMA Event related to TIM8 Channel 4 */ /* DMA2 Channel2 configuration ----------------------------------------------*/ LL_DMA_SetMemoryAddress(DMA2, LL_DMA_CHANNEL_1, (uint32_t)pHandle->DmaBuff); LL_DMA_SetPeriphAddress(DMA2, LL_DMA_CHANNEL_1, (uint32_t)&TIMx->CCR1); LL_DMA_SetDataLength(DMA2, LL_DMA_CHANNEL_1, 2); /* Enable DMA2 Channel2 */ LL_DMA_EnableChannel(DMA2, LL_DMA_CHANNEL_1); pHandle->DistortionDMAy_Chx = DMA2_Channel1; } #else else { /* Nothing to do */ } #endif R1_TIMxInit(TIMx, pHandle); if (OPAMPx) { /* Enable OPAMP */ LL_OPAMP_Enable(OPAMPx); LL_OPAMP_Lock(OPAMPx); } else { /* Nothing to do */ } /* Over current protection */ if (COMP_OCPx) { /* Inverting input*/ if (pHandle->pParams_str->CompOCPInvInput_MODE != EXT_MODE) { R1_SetAOReferenceVoltage(pHandle->pParams_str->DAC_Channel_OCP, DAC_OCPx, (uint16_t)(pHandle->pParams_str->DAC_OCP_Threshold)); } else { /* Nothing to do */ } /* Enable comparator */ #if defined(COMP_CSR_COMPxHYST) LL_COMP_SetInputHysteresis(COMP_OCPx, LL_COMP_HYSTERESIS_LOW); #endif LL_COMP_Enable(COMP_OCPx); LL_COMP_Lock(COMP_OCPx); } else { /* Nothing to do */ } /* Over voltage protection */ if (COMP_OVPx) { /* Inverting input*/ if (pHandle->pParams_str->CompOCPInvInput_MODE != EXT_MODE) { R1_SetAOReferenceVoltage(pHandle->pParams_str->DAC_Channel_OVP, DAC_OVP, (uint16_t)(pHandle->pParams_str->DAC_OVP_Threshold)); } /* Enable comparator */ #if defined(COMP_CSR_COMPxHYST) LL_COMP_SetInputHysteresis(COMP_OCPx, LL_COMP_HYSTERESIS_LOW); #endif LL_COMP_Enable(COMP_OVPx); LL_COMP_Lock(COMP_OVPx); } else { /* Nothing to do */ } if (TIM1 == pHandle->pParams_str->TIMx) { /* TIM1 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph(LL_DBGMCU_APB2_GRP1_TIM1_STOP); } #if defined(TIM8) else { /* TIM8 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph(LL_DBGMCU_APB2_GRP1_TIM8_STOP); } #else else { /* Nothing to do */ } #endif /* - Exit from deep-power-down mode */ LL_ADC_DisableDeepPowerDown(ADCx); if (0U == LL_ADC_IsInternalRegulatorEnabled(ADCx)) { /* Enable ADC internal voltage regulator */ LL_ADC_EnableInternalRegulator(ADCx); /* Wait for Regulator Startup time, once for both */ /* Note: Variable divided by 2 to compensate partially */ /* CPU processing cycles, scaling in us split to not */ /* exceed 32 bits register capacity and handle low frequency */ volatile uint32_t wait_loop_index = ((LL_ADC_DELAY_INTERNAL_REGUL_STAB_US / 10UL) * (SystemCoreClock / (100000UL * 2UL))); while(wait_loop_index != 0UL) { wait_loop_index--; } } else { /* Nothing to do */ } LL_ADC_StartCalibration(ADCx, LL_ADC_SINGLE_ENDED); while (1U == LL_ADC_IsCalibrationOnGoing(ADCx)) { /* Nothing to do */ } /* ADC Enable (must be done after calibration) */ /* ADC5-140924: Enabling the ADC by setting ADEN bit soon after polling ADCAL=0 * following a calibration phase, could have no effect on ADC * within certain AHB/ADC clock ratio */ while (0U == LL_ADC_IsActiveFlag_ADRDY(ADCx)) { LL_ADC_Enable(ADCx); } /* Flushing JSQR queue of context by setting JADSTP = 1 (JQM)=1 */ LL_ADC_INJ_StopConversion(ADCx); if (TIM1 == pHandle->pParams_str->TIMx) { LL_ADC_INJ_ConfigQueueContext(ADCx, LL_ADC_INJ_TRIG_EXT_TIM1_TRGO2, LL_ADC_INJ_TRIG_EXT_RISING, LL_ADC_INJ_SEQ_SCAN_ENABLE_2RANKS, __LL_ADC_DECIMAL_NB_TO_CHANNEL(pHandle->pParams_str->IChannel), __LL_ADC_DECIMAL_NB_TO_CHANNEL(pHandle->pParams_str->IChannel), __LL_ADC_DECIMAL_NB_TO_CHANNEL(pHandle->pParams_str->IChannel), __LL_ADC_DECIMAL_NB_TO_CHANNEL(pHandle->pParams_str->IChannel)); } #if defined(TIM8) else { LL_ADC_INJ_ConfigQueueContext(ADCx, LL_ADC_INJ_TRIG_EXT_TIM8_TRGO2, LL_ADC_INJ_TRIG_EXT_RISING, LL_ADC_INJ_SEQ_SCAN_ENABLE_2RANKS, __LL_ADC_DECIMAL_NB_TO_CHANNEL(pHandle->pParams_str->IChannel), __LL_ADC_DECIMAL_NB_TO_CHANNEL(pHandle->pParams_str->IChannel), __LL_ADC_DECIMAL_NB_TO_CHANNEL(pHandle->pParams_str->IChannel), __LL_ADC_DECIMAL_NB_TO_CHANNEL(pHandle->pParams_str->IChannel)); } #else else { /* Nothing to do */ } #endif /* Store register value in the handle to be used later during SVPWM for re-init */ pHandle->ADCConfig = ADCx->JSQR; LL_ADC_INJ_StopConversion(ADCx); /* Enable injected end of sequence conversions interrupt */ LL_ADC_EnableIT_JEOS(ADCx); if (pHandle->pParams_str->RepetitionCounter > 1) { /* Enable DMA distortion window insertion interrupt */ if (TIM1 == TIMx) { LL_DMA_EnableIT_TC(DMA1, LL_DMA_CHANNEL_1); } else { LL_DMA_EnableIT_TC(DMA2, LL_DMA_CHANNEL_1); } } else { /* Nothing to do */ } LL_ADC_INJ_SetQueueMode(ADCx, LL_ADC_INJ_QUEUE_2CONTEXTS_END_EMPTY); LL_ADC_INJ_SetSequencerDiscont(ADCx, LL_ADC_INJ_SEQ_DISCONT_1RANK); /* Clear the flags */ pHandle->_Super.DTTest = 0u; } /** * @brief Initializes @p TIMx peripheral with @p pHandle handler for PWM generation. * */ __weak void R1_TIMxInit(TIM_TypeDef *TIMx, PWMC_R1_Handle_t *pHandle) { /* Disable main TIM counter to ensure * a synchronous start by TIM2 trigger */ LL_TIM_DisableCounter(TIMx); /* Enables the TIMx Preload on CC1 Register */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH1); /* Enables the TIMx Preload on CC2 Register */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH2); /* Enables the TIMx Preload on CC3 Register */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH3); /* Enables the TIMx Preload on CC4 Register */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH4); /* Enables the TIMx Preload on CC5 Register */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH5); /* Enables the TIMx Preload on CC6 Register */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH6); /* Always enable BKIN for safety feature */ LL_TIM_ClearFlag_BRK(TIMx); LL_TIM_ClearFlag_BRK2(TIMx); LL_TIM_EnableIT_BRK(TIMx); /* Prepare timer for synchronization */ LL_TIM_GenerateEvent_UPDATE(TIMx); if (2U == pHandle->pParams_str->FreqRatio) { if (HIGHER_FREQ == pHandle->pParams_str->IsHigherFreqTim) { if (3U == pHandle->pParams_str->RepetitionCounter) { /* Set TIMx repetition counter to 1 */ LL_TIM_SetRepetitionCounter(TIMx, 1); LL_TIM_GenerateEvent_UPDATE(TIMx); /* Repetition counter will be set to 3 at next Update */ LL_TIM_SetRepetitionCounter(TIMx, 3); } else { /* Nothing to do */ } } else { /* Nothing to do */ } LL_TIM_SetCounter(TIMx, (uint32_t)(pHandle->Half_PWMPeriod) - 1u); } else /* bFreqRatio equal to 1 or 3 */ { if (M1 == pHandle->_Super.Motor) { if (1U == pHandle->pParams_str->RepetitionCounter) { LL_TIM_SetCounter(TIMx, (uint32_t)(pHandle->Half_PWMPeriod) - 1u); } else if (3U == pHandle->pParams_str->RepetitionCounter) { /* Set TIMx repetition counter to 1 */ LL_TIM_SetRepetitionCounter(TIMx, 1); LL_TIM_GenerateEvent_UPDATE(TIMx); /* Repetition counter will be set to 3 at next Update */ LL_TIM_SetRepetitionCounter(TIMx, 3); } else { /* Nothing to do */ } } else { /* Nothing to do */ } } /* Enable PWM channel */ LL_TIM_CC_EnableChannel(TIMx, TIMxCCER_MASK_CH123); } /** * @brief First initialization of the @p pHdl handler. * */ __weak void R1_1ShuntMotorVarsInit(PWMC_Handle_t *pHdl) { PWMC_R1_Handle_t *pHandle = (PWMC_R1_Handle_t *)pHdl; /* Init motor vars */ pHandle->Inverted_pwm_new = INVERT_NONE; pHandle->Flags &= (~STBD3); /* STBD3 cleared */ /* After reset, value of DMA buffers for distortion */ pHandle->DmaBuff[0] = pHandle->Half_PWMPeriod + 1u; pHandle->DmaBuff[1] = pHandle->Half_PWMPeriod >> 1; /* Dummy */ /* Default value of sampling points */ pHandle->CntSmp1 = (pHandle->Half_PWMPeriod >> 1) + (pHandle->pParams_str->Tafter); pHandle->CntSmp2 = pHandle->Half_PWMPeriod - 1u; /* Set the default previous value of Phase A,B,C current */ pHandle->CurrAOld = 0; pHandle->CurrBOld = 0; pHandle->_Super.BrakeActionLock = false; } /** * @brief Stores into the @p pHdl the voltage present on Ia and * Ib current feedback analog channels when no current is flowing into the * motor. * */ __weak void R1_CurrentReadingPolarization(PWMC_Handle_t *pHdl) { PWMC_R1_Handle_t * pHandle = (PWMC_R1_Handle_t *)pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; pHandle->PhaseOffset = 0u; pHandle->PolarizationCounter = 0u; /* It forces inactive level on TIMx CHy and CHyN */ TIMx->CCER &= (~TIMxCCER_MASK_CH123); /* Offset Polarization */ /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R1_HFCurrentsPolarization; pHandle->_Super.pFctSetADCSampPointSectX = &R1_SetADCSampPointPolarization; R1_SwitchOnPWM(&pHandle->_Super); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd(TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter); R1_SwitchOffPWM(&pHandle->_Super); pHandle->PhaseOffset >>= 4; /* Change back function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R1_GetPhaseCurrents; pHandle->_Super.pFctSetADCSampPointSectX = &R1_CalcDutyCycles; /* It re-enable drive of TIMx CHy and CHyN by TIMx CHyRef */ TIMx->CCER |= TIMxCCER_MASK_CH123; R1_1ShuntMotorVarsInit(&pHandle->_Super); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section (".ccmram"))) #endif #endif /** * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p pStator_Currents ab_t format. * */ __weak void R1_GetPhaseCurrents(PWMC_Handle_t *pHdl, ab_t *pStator_Currents) { int32_t wAux; int16_t hCurrA = 0; int16_t hCurrB = 0; int16_t hCurrC = 0; uint8_t bCurrASamp = 0u; uint8_t bCurrBSamp = 0u; uint8_t bCurrCSamp = 0u; PWMC_R1_Handle_t *pHandle = (PWMC_R1_Handle_t *)pHdl; TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH1); LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH2); LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH3); /* Reset the buffered version of update flag to indicate the start of FOC algorithm */ pHandle->UpdateFlagBuffer = false; /* First sampling point */ wAux = (int32_t)(ADCx->JDR1); wAux -= (int32_t)(pHandle->PhaseOffset); /* Check saturation */ if (wAux > -INT16_MAX) { if (wAux < INT16_MAX) { /* Nothing to do */ } else { wAux = INT16_MAX; } } else { wAux = -INT16_MAX; } switch (pHandle->sampCur1) { case SAMP_IA: { hCurrA = (int16_t)(wAux); bCurrASamp = 1u; break; } case SAMP_IB: { hCurrB = (int16_t)(wAux); bCurrBSamp = 1u; break; } case SAMP_IC: { hCurrC = (int16_t)(wAux); bCurrCSamp = 1u; break; } case SAMP_NIA: { wAux = -wAux; hCurrA = (int16_t)(wAux); bCurrASamp = 1u; break; } case SAMP_NIB: { wAux = -wAux; hCurrB = (int16_t)(wAux); bCurrBSamp = 1u; break; } case SAMP_NIC: { wAux = -wAux; hCurrC = (int16_t)(wAux); bCurrCSamp = 1u; break; } case SAMP_OLDA: { hCurrA = pHandle->CurrAOld; bCurrASamp = 1u; break; } case SAMP_OLDB: { hCurrB = pHandle->CurrBOld; bCurrBSamp = 1u; break; } default: break; } /* Second sampling point */ wAux = (int32_t)(ADCx->JDR2); wAux -= (int32_t)(pHandle->PhaseOffset); /* Check saturation */ if (wAux > -INT16_MAX) { if (wAux < INT16_MAX) { /* Nothing to do */ } else { wAux = INT16_MAX; } } else { wAux = -INT16_MAX; } switch (pHandle->sampCur2) { case SAMP_IA: { hCurrA = (int16_t)(wAux); bCurrASamp = 1u; break; } case SAMP_IB: { hCurrB = (int16_t)(wAux); bCurrBSamp = 1u; break; } case SAMP_IC: { hCurrC = (int16_t)(wAux); bCurrCSamp = 1u; break; } case SAMP_NIA: { wAux = -wAux; hCurrA = (int16_t)(wAux); bCurrASamp = 1u; break; } case SAMP_NIB: { wAux = -wAux; hCurrB = (int16_t)(wAux); bCurrBSamp = 1u; break; } case SAMP_NIC: { wAux = -wAux; hCurrC = (int16_t)(wAux); bCurrCSamp = 1u; break; } default: break; } /* Computation of the third value */ if (0U == bCurrASamp) { wAux = -((int32_t)(hCurrB)) - ((int32_t)(hCurrC)); /* Check saturation */ if (wAux > -INT16_MAX) { if (wAux < INT16_MAX) { /* Nothing to do */ } else { wAux = INT16_MAX; } } else { wAux = -INT16_MAX; } hCurrA = (int16_t)wAux; } if (bCurrBSamp == 0u) { wAux = -((int32_t)(hCurrA)) - ((int32_t)(hCurrC)); /* Check saturation */ if (wAux > -INT16_MAX) { if (wAux < INT16_MAX) { /* Nothing to do */ } else { wAux = INT16_MAX; } } else { wAux = -INT16_MAX; } hCurrB = (int16_t)wAux; } if (bCurrCSamp == 0u) { wAux = -((int32_t)(hCurrA)) - ((int32_t)(hCurrB)); /* Check saturation */ if (wAux > -INT16_MAX) { if (wAux < INT16_MAX) { /* Nothing to do */ } else { wAux = INT16_MAX; } } else { wAux = -INT16_MAX; } hCurrC = (int16_t)wAux; } /* hCurrA, hCurrB, hCurrC values are the sampled values */ pHandle->CurrAOld = hCurrA; pHandle->CurrBOld = hCurrB; pStator_Currents->a = hCurrA; pStator_Currents->b = hCurrB; pHandle->_Super.Ia = hCurrA; pHandle->_Super.Ib = hCurrB; pHandle->_Super.Ic = -hCurrA - hCurrB; } /** * @brief Implementation of PWMC_GetPhaseCurrents to be performed during polarization. * * It sums up injected conversion data into PhaseOffset to compute the * offset introduced in the current feedback network. It is required * to properly configure ADC inputs before enabling the offset computation. * * @param pHdl: Handler of the current instance of the PWM component. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ __weak void R1_HFCurrentsPolarization(PWMC_Handle_t *pHdl, ab_t *pStator_Currents) { /* Derived class members container */ PWMC_R1_Handle_t *pHandle = (PWMC_R1_Handle_t *)pHdl; ADC_TypeDef *ADCx = pHandle->pParams_str->ADCx; /* Reset the buffered version of update flag to indicate the start of FOC algorithm */ pHandle->UpdateFlagBuffer = false; if (pHandle->PolarizationCounter < NB_CONVERSIONS) { pHandle->PhaseOffset += ADCx->JDR2; pHandle->PolarizationCounter++; } else { /* Nothing to do */ } /* During offset Polarization no current is flowing in the phases */ pStator_Currents->a = 0; pStator_Currents->b = 0; } /** * @brief Configures the ADC for the current sampling during calibration. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval uint16_t Return value of R3_1_WriteTIMRegisters. */ uint16_t R1_SetADCSampPointPolarization(PWMC_Handle_t * pHdl) { PWMC_R1_Handle_t *pHandle = (PWMC_R1_Handle_t *)pHdl; TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; uint16_t hAux; LL_TIM_OC_SetCompareCH5(TIMx, ((uint32_t)(pHandle->Half_PWMPeriod) >> 1) + (uint32_t)(pHandle->pParams_str->Tafter)); LL_TIM_OC_SetCompareCH6(TIMx, ((uint32_t)(pHandle->Half_PWMPeriod) - 1u)); if (LL_TIM_IsActiveFlag_UPDATE(TIMx)) { hAux = MC_DURATION; } else { hAux = MC_NO_ERROR; } return (hAux); } /** * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors of driving section. It has to be * called on each motor start-up when using high voltage drivers. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R1_TurnOnLowSides(PWMC_Handle_t *pHdl) { PWMC_R1_Handle_t *pHandle = (PWMC_R1_Handle_t *)pHdl; TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = true; /* Turn on the three low side switches */ LL_TIM_OC_SetCompareCH1(TIMx, 0); LL_TIM_OC_SetCompareCH2(TIMx, 0); LL_TIM_OC_SetCompareCH3(TIMx, 0); /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE(TIMx); /* Wait until next update */ while (RESET == LL_TIM_IsActiveFlag_UPDATE(TIMx)) { /* Nothing to do */ } /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs(TIMx); if ((pHandle->_Super.LowSideOutputs) == ES_GPIO) { LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } else { /* Nothing to do */ } } /** * @brief Enables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R1_SwitchOnPWM(PWMC_Handle_t *pHdl) { PWMC_R1_Handle_t *pHandle = (PWMC_R1_Handle_t *)pHdl; TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; /* We forbid ADC usage for regular conversion on Systick */ pHandle->ADCRegularLocked=true; /* Enables the TIMx Preload on CC1 Register */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH1); /* Enables the TIMx Preload on CC2 Register */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH2); /* Enables the TIMx Preload on CC3 Register */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH3); /* TIM output trigger 2 for ADC */ LL_TIM_SetTriggerOutput2(TIMx, LL_TIM_TRGO2_OC5_RISING_OC6_RISING); pHandle->_Super.TurnOnLowSidesAction = false; /* Set all duty to 50% */ /* Set ch5 ch6 for triggering */ /* Clear Update Flag */ /* TIM ch4 DMA request enable */ pHandle->DmaBuff[1] = pHandle->Half_PWMPeriod >> 1; LL_TIM_OC_SetCompareCH1(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH2(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH3(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH5(TIMx, (((uint32_t)(pHandle->Half_PWMPeriod >> 1)) + (uint32_t)pHandle->pParams_str->Tafter)); LL_TIM_OC_SetCompareCH6(TIMx, (uint32_t)(pHandle->Half_PWMPeriod - 1u)); /* Wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE(TIMx); while (RESET == LL_TIM_IsActiveFlag_UPDATE(TIMx)) { /* Nothing to do */ } LL_TIM_ClearFlag_UPDATE(TIMx); /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs(TIMx); if ((pHandle->_Super.LowSideOutputs) == ES_GPIO) { if ((TIMx->CCER & TIMxCCER_MASK_CH123) != 0u) { LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } else { /* It is executed during Polarization phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } } else { /* Nothing to do */ } /* Enable DMA request for distortion window insertion */ LL_TIM_EnableDMAReq_CC4(TIMx); /* Enable TIMx update IRQ */ LL_TIM_EnableIT_UPDATE(TIMx); } /** * @brief Disables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R1_SwitchOffPWM(PWMC_Handle_t *pHdl) { PWMC_R1_Handle_t *pHandle = (PWMC_R1_Handle_t *)pHdl; TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef *ADCx = pHandle->pParams_str->ADCx; /* Disable TIMx update IRQ */ LL_TIM_DisableIT_UPDATE(TIMx); /* Flushing JSQR queue of context by setting JADSTP = 1 (JQM)=1 */ LL_ADC_INJ_StopConversion(ADCx); pHandle->_Super.TurnOnLowSidesAction = false; /* Main PWM Output Disable */ LL_TIM_DisableAllOutputs(TIMx); if (pHandle->_Super.BrakeActionLock == true) { /* Nothing to do */ } else { if (ES_GPIO == (pHandle->_Super.LowSideOutputs)) { LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } else { /* Nothing to do */ } } /* Wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE(TIMx); while (RESET == LL_TIM_IsActiveFlag_UPDATE(TIMx)) { /* Nothing to do */ } LL_TIM_ClearFlag_UPDATE(TIMx); /* Clear injected end of sequence conversions flag */ LL_ADC_ClearFlag_JEOS(ADCx); /* Disable TIMx DMA requests enable */ LL_TIM_DisableDMAReq_CC4(TIMx); /* We allow ADC usage for regular conversion on Systick*/ pHandle->ADCRegularLocked = false; } /** * @brief Configures the analog output used for protection thresholds. * * @param DAC_Channel: the selected DAC channel. * This parameter can be: * @arg DAC_Channel_1: DAC Channel1 selected. * @arg DAC_Channel_2: DAC Channel2 selected. * @param DACx: DAC to be configured. * @param hDACVref: Value of DAC reference expressed as 16bit unsigned integer. \n * Ex. 0 = 0V ; 65536 = VDD_DAC. */ __weak void R1_SetAOReferenceVoltage(uint32_t DAC_Channel, DAC_TypeDef *DACx, uint16_t hDACVref) { LL_DAC_ConvertData12LeftAligned (DACx, DAC_Channel, hDACVref); /* Enable DAC Channel */ LL_DAC_TrigSWConversion (DACx, DAC_Channel); if (LL_DAC_IsEnabled (DACx, DAC_Channel) == 1u) { /* If DAC is already enable, we wait LL_DAC_DELAY_VOLTAGE_SETTLING_US */ uint32_t wait_loop_index = ((LL_DAC_DELAY_VOLTAGE_SETTLING_US) * (SystemCoreClock / (1000000UL * 2UL))); while(wait_loop_index != 0UL) { wait_loop_index--; } } else { /* If DAC is not enabled, we must wait LL_DAC_DELAY_STARTUP_VOLTAGE_SETTLING_US */ LL_DAC_Enable(DACx, DAC_Channel); uint32_t wait_loop_index = ((LL_DAC_DELAY_STARTUP_VOLTAGE_SETTLING_US) * (SystemCoreClock / (1000000UL * 2UL))); while(wait_loop_index != 0UL) { wait_loop_index--; } } } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section (".ccmram"))) #endif #endif /** * @brief Implementation of the single shunt algorithm to setup the * TIM1 register and DMA buffers values for the next PWM period. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ __weak uint16_t R1_CalcDutyCycles(PWMC_Handle_t *pHdl) { PWMC_R1_Handle_t *pHandle = (PWMC_R1_Handle_t *)pHdl; TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; int16_t hDeltaDuty_0; int16_t hDeltaDuty_1; uint16_t hAux; register uint16_t lowDuty = pHandle->_Super.lowDuty; register uint16_t midDuty = pHandle->_Super.midDuty; register uint16_t highDuty = pHandle->_Super.highDuty; uint8_t bSector; uint8_t bStatorFluxPos; bSector = (uint8_t)(pHandle->_Super.Sector); /* Compute delta duty */ hDeltaDuty_0 = (int16_t)(midDuty) - (int16_t)(highDuty); hDeltaDuty_1 = (int16_t)(lowDuty) - (int16_t)(midDuty); /* Check region */ if ((uint16_t)hDeltaDuty_0 <= pHandle->pParams_str->TMin) { if ((uint16_t)hDeltaDuty_1 <= pHandle->pParams_str->TMin) { bStatorFluxPos = BOUNDARY_3; } else { bStatorFluxPos = BOUNDARY_2; } } else { if ((uint16_t)hDeltaDuty_1 > pHandle->pParams_str->TMin) { bStatorFluxPos = REGULAR; } else { bStatorFluxPos = BOUNDARY_1; } } if (REGULAR == bStatorFluxPos) { pHandle->Inverted_pwm_new = INVERT_NONE; } else if (BOUNDARY_1 == bStatorFluxPos) /* Adjust the lower */ { switch (bSector) { case SECTOR_5: case SECTOR_6: { if ((pHandle->_Super.CntPhA - pHandle->pParams_str->CHTMin - highDuty) > pHandle->pParams_str->TMin) { pHandle->Inverted_pwm_new = INVERT_A; pHandle->_Super.CntPhA -= pHandle->pParams_str->CHTMin; if (pHandle->_Super.CntPhA < midDuty) { midDuty = pHandle->_Super.CntPhA; } else { /* Nothing to do */ } } else { bStatorFluxPos = BOUNDARY_3; if (0U == (pHandle->Flags & STBD3)) { pHandle->Inverted_pwm_new = INVERT_A; pHandle->_Super.CntPhA -= pHandle->pParams_str->CHTMin; pHandle->Flags |= STBD3; } else { pHandle->Inverted_pwm_new = INVERT_B; pHandle->_Super.CntPhB -= pHandle->pParams_str->CHTMin; pHandle->Flags &= (~STBD3); } } break; } case SECTOR_2: case SECTOR_1: { if ((pHandle->_Super.CntPhB - pHandle->pParams_str->CHTMin - highDuty) > pHandle->pParams_str->TMin) { pHandle->Inverted_pwm_new = INVERT_B; pHandle->_Super.CntPhB -= pHandle->pParams_str->CHTMin; if (pHandle->_Super.CntPhB < midDuty) { midDuty = pHandle->_Super.CntPhB; } else { /* Nothing to do */ } } else { bStatorFluxPos = BOUNDARY_3; if (0U == (pHandle->Flags & STBD3)) { pHandle->Inverted_pwm_new = INVERT_A; pHandle->_Super.CntPhA -= pHandle->pParams_str->CHTMin; pHandle->Flags |= STBD3; } else { pHandle->Inverted_pwm_new = INVERT_B; pHandle->_Super.CntPhB -= pHandle->pParams_str->CHTMin; pHandle->Flags &= (~STBD3); } } break; } case SECTOR_4: case SECTOR_3: { if ((pHandle->_Super.CntPhC - pHandle->pParams_str->CHTMin - highDuty) > pHandle->pParams_str->TMin) { pHandle->Inverted_pwm_new = INVERT_C; pHandle->_Super.CntPhC -= pHandle->pParams_str->CHTMin; if (pHandle->_Super.CntPhC < midDuty) { midDuty = pHandle->_Super.CntPhC; } else { /* Nothing to do */ } } else { bStatorFluxPos = BOUNDARY_3; if (0U == (pHandle->Flags & STBD3)) { pHandle->Inverted_pwm_new = INVERT_A; pHandle->_Super.CntPhA -= pHandle->pParams_str->CHTMin; pHandle->Flags |= STBD3; } else { pHandle->Inverted_pwm_new = INVERT_B; pHandle->_Super.CntPhB -= pHandle->pParams_str->CHTMin; pHandle->Flags &= (~STBD3); } } break; } default: break; } } else if (BOUNDARY_2 == bStatorFluxPos) /* Adjust the middler */ { switch (bSector) { case SECTOR_4: case SECTOR_5: /* Invert B */ { pHandle->Inverted_pwm_new = INVERT_B; pHandle->_Super.CntPhB -= pHandle->pParams_str->CHTMin; if (pHandle->_Super.CntPhB > 0xEFFFu) { pHandle->_Super.CntPhB = 0u; } else { /* Nothing to do */ } break; } case SECTOR_2: case SECTOR_3: /* Invert A */ { pHandle->Inverted_pwm_new = INVERT_A; pHandle->_Super.CntPhA -= pHandle->pParams_str->CHTMin; if (pHandle->_Super.CntPhA > 0xEFFFu) { pHandle->_Super.CntPhA = 0u; } else { /* Nothing to do */ } break; } case SECTOR_6: case SECTOR_1: /* Invert C */ { pHandle->Inverted_pwm_new = INVERT_C; pHandle->_Super.CntPhC -= pHandle->pParams_str->CHTMin; if (pHandle->_Super.CntPhC > 0xEFFFu) { pHandle->_Super.CntPhC = 0u; } else { /* Nothing to do */ } break; } default: break; } } else if (bStatorFluxPos == BOUNDARY_3) { if (0U == (pHandle->Flags & STBD3)) { pHandle->Inverted_pwm_new = INVERT_A; pHandle->_Super.CntPhA -= pHandle->pParams_str->CHTMin; pHandle->Flags |= STBD3; } else { pHandle->Inverted_pwm_new = INVERT_B; pHandle->_Super.CntPhB -= pHandle->pParams_str->CHTMin; pHandle->Flags &= (~STBD3); } } else { /* Nothing to do */ } if (REGULAR == bStatorFluxPos) /* Regular zone */ { /* First point */ pHandle->CntSmp1 = midDuty - pHandle->pParams_str->Tbefore; /* Second point */ pHandle->CntSmp2 = lowDuty - pHandle->pParams_str->Tbefore; } else { /* Nothing to do */ } if (BOUNDARY_1 == bStatorFluxPos) /* Two small, one big */ { /* First point */ pHandle->CntSmp1 = midDuty - pHandle->pParams_str->Tbefore; /* Second point */ pHandle->CntSmp2 = pHandle->Half_PWMPeriod - pHandle->pParams_str->HTMin + pHandle->pParams_str->TSample; } else { /* Nothing to do */ } if (BOUNDARY_2 == bStatorFluxPos) /* Two big, one small */ { /* First point */ pHandle->CntSmp1 = lowDuty - pHandle->pParams_str->Tbefore; /* Second point */ pHandle->CntSmp2 = pHandle->Half_PWMPeriod - pHandle->pParams_str->HTMin + pHandle->pParams_str->TSample; } else { /* Nothing to do */ } if (BOUNDARY_3 == bStatorFluxPos) { /* First point */ pHandle->CntSmp1 = highDuty - pHandle->pParams_str->Tbefore; /* Dummy trigger */ /* Second point */ pHandle->CntSmp2 = pHandle->Half_PWMPeriod - pHandle->pParams_str->HTMin + pHandle->pParams_str->TSample; } else { /* Nothing to do */ } LL_TIM_OC_SetCompareCH5(TIMx, pHandle->CntSmp1); LL_TIM_OC_SetCompareCH6(TIMx, pHandle->CntSmp2); if (REGULAR == bStatorFluxPos) { LL_TIM_SetTriggerOutput2(TIMx, LL_TIM_TRGO2_OC5_RISING_OC6_RISING); } else { LL_TIM_SetTriggerOutput2(TIMx, LL_TIM_TRGO2_OC5_RISING_OC6_FALLING); } /* Update Timer Ch 1,2,3 (These value are required before update event) */ LL_TIM_OC_SetCompareCH1(TIMx, pHandle->_Super.CntPhA); LL_TIM_OC_SetCompareCH2(TIMx, pHandle->_Super.CntPhB); LL_TIM_OC_SetCompareCH3(TIMx, pHandle->_Super.CntPhC); /* End of FOC */ /* Check software error */ if (true == pHandle->UpdateFlagBuffer) { hAux = MC_DURATION; } else { hAux = MC_NO_ERROR; } if (pHandle->_Super.SWerror == 1u) { hAux = MC_DURATION; pHandle->_Super.SWerror = 0u; } /* Set the current sampled */ if (REGULAR == bStatorFluxPos) /* Regual zone */ { pHandle->sampCur1 = REGULAR_SAMP_CUR1[bSector]; pHandle->sampCur2 = REGULAR_SAMP_CUR2[bSector]; } else { /* Nothing to do */ } if (BOUNDARY_1 == bStatorFluxPos) /* Two small, one big */ { pHandle->sampCur1 = REGULAR_SAMP_CUR1[bSector]; pHandle->sampCur2 = BOUNDR1_SAMP_CUR2[bSector]; } else { /* Nothing to do */ } if (BOUNDARY_2 == bStatorFluxPos) /* Two big, one small */ { pHandle->sampCur1 = BOUNDR2_SAMP_CUR1[bSector]; pHandle->sampCur2 = BOUNDR2_SAMP_CUR2[bSector]; } else { /* Nothing to do */ } if (BOUNDARY_3 == bStatorFluxPos) { if (pHandle->Inverted_pwm_new == INVERT_A) { pHandle->sampCur1 = SAMP_OLDB; pHandle->sampCur2 = SAMP_IA; } else { /* Nothing to do */ } if (pHandle->Inverted_pwm_new == INVERT_B) { pHandle->sampCur1 = SAMP_OLDA; pHandle->sampCur2 = SAMP_IB; } else { /* Nothing to do */ } } else { /* Nothing to do */ } return (hAux); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section (".ccmram"))) #endif #endif /** * @brief Contains the TIMx Update event interrupt. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void * R1_TIMx_UP_IRQHandler(PWMC_R1_Handle_t *pHandle) { TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef *ADCx = pHandle->pParams_str->ADCx; pHandle->UpdateFlagBuffer = true; switch (pHandle->Inverted_pwm_new) { case INVERT_A: { /* Active window insertion phase A: - Set duty cycle A value to be restored by DMA */ pHandle->DmaBuff[1] = pHandle->_Super.CntPhA; /* - Set DMA dest. address to phase A capture/compare register */ pHandle->DistortionDMAy_Chx->CPAR = (uint32_t) &TIMx->CCR1; /* - Disable phase preload register to take into account immediately the values written by DMA */ LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH1); LL_TIM_EnableDMAReq_CC4(TIMx); break; } case INVERT_B: { /* Active window insertion phase B: - Set duty cycle B value to be restored by DMA */ pHandle->DmaBuff[1] = pHandle->_Super.CntPhB; /* - Set DMA dest. address to phase B capture/compare register */ pHandle->DistortionDMAy_Chx->CPAR = (uint32_t) &TIMx->CCR2; /* - Disable phase preload register to take into account immediately the values written by DMA */ LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH2); LL_TIM_EnableDMAReq_CC4(TIMx); break; } case INVERT_C: { /* Active window insertion phase C: - Set duty cycle C value to be restored by DMA */ pHandle->DmaBuff[1] = pHandle->_Super.CntPhC; /* - Set DMA dest. address to phase C capture/compare register */ pHandle->DistortionDMAy_Chx->CPAR = (uint32_t) &TIMx->CCR3; /* - Disable phase preload register to take into account immediately the values written by DMA */ LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH3); LL_TIM_EnableDMAReq_CC4(TIMx); break; } default: { /* Disable DMA requests done by TIMx as no active window insertion needed on current PWM cycle */ LL_TIM_DisableDMAReq_CC4(TIMx); break; } /* Write ADC sequence */ pHandle->pParams_str->ADCx->JSQR = pHandle->ADCConfig; /* Start injected conversion */ LL_ADC_INJ_StartConversion(ADCx); return (&(pHandle->_Super.Motor)); } /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
42,406
C
26.735121
133
0.58961
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/G4xx/Src/r3_2_g4xx_pwm_curr_fdbk.c
/** ****************************************************************************** * @file r3_2_g4xx_pwm_curr_fdbk.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement current sensor * class to be stantiated when the three shunts current sensing * topology is used. * * It is specifically designed for STM32G4XX microcontrollers and * implements the successive sampling of motor current using two ADCs. * + MCU peripheral and handle initialization function * + three shunts current sensing * + space vector modulation function * + ADC sampling function * ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * * @ingroup R3_2_G4XX_pwm_curr_fdbk */ /* Includes ------------------------------------------------------------------*/ #include "r3_2_g4xx_pwm_curr_fdbk.h" #include "pwm_common.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup R3_2_pwm_curr_fdbk * @{ */ /* Private defines -----------------------------------------------------------*/ #define TIMxCCER_MASK_CH123 ((uint16_t)(LL_TIM_CHANNEL_CH1|LL_TIM_CHANNEL_CH1N|\ LL_TIM_CHANNEL_CH2|LL_TIM_CHANNEL_CH2N|\ LL_TIM_CHANNEL_CH3|LL_TIM_CHANNEL_CH3N)) /* Private typedef -----------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ static void R3_2_TIMxInit(TIM_TypeDef *TIMx, PWMC_Handle_t *pHdl); static void R3_2_ADCxInit(ADC_TypeDef *ADCx); __STATIC_INLINE uint16_t R3_2_WriteTIMRegisters(PWMC_Handle_t *pHdl, uint16_t hCCR4Reg); static void R3_2_HFCurrentsPolarizationAB(PWMC_Handle_t *pHdl, ab_t *Iab); static void R3_2_HFCurrentsPolarizationC(PWMC_Handle_t *pHdl, ab_t *Iab); static void R3_2_SetAOReferenceVoltage(uint32_t DAC_Channel, DAC_TypeDef *DACx, uint16_t hDACVref); uint16_t R3_2_SetADCSampPointPolarization(PWMC_Handle_t *pHdl) ; static void R3_2_RLGetPhaseCurrents(PWMC_Handle_t *pHdl, ab_t *pStator_Currents); static void R3_2_RLTurnOnLowSides(PWMC_Handle_t *pHdl, uint32_t ticks); static void R3_2_RLSwitchOnPWM(PWMC_Handle_t *pHdl); /* * @brief Initializes TIMx, ADC, GPIO, DMA1 and NVIC for current reading * in three shunt topology using STM32G4XX and shared ADC. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void R3_2_Init(PWMC_R3_2_Handle_t *pHandle) { #ifdef NULL_PTR_CHECK_R3_2_PWM_CURR_FDB if (MC_NULL == pHandle) { /* Nothing to do */ } else { #endif R3_3_OPAMPParams_t *OPAMPParams = pHandle->pParams_str->OPAMPParams; COMP_TypeDef *COMP_OCPAx = pHandle->pParams_str->CompOCPASelection; COMP_TypeDef *COMP_OCPBx = pHandle->pParams_str->CompOCPBSelection; COMP_TypeDef *COMP_OCPCx = pHandle->pParams_str->CompOCPCSelection; COMP_TypeDef *COMP_OVPx = pHandle->pParams_str->CompOVPSelection; DAC_TypeDef *DAC_OCPAx = pHandle->pParams_str->DAC_OCP_ASelection; DAC_TypeDef *DAC_OCPBx = pHandle->pParams_str->DAC_OCP_BSelection; DAC_TypeDef *DAC_OCPCx = pHandle->pParams_str->DAC_OCP_CSelection; DAC_TypeDef *DAC_OVPx = pHandle->pParams_str->DAC_OVP_Selection; TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef *ADCx_1 = pHandle->pParams_str->ADCDataReg1[0]; ADC_TypeDef *ADCx_2 = pHandle->pParams_str->ADCDataReg2[0]; /* Check that _Super is the first member of the structure PWMC_R3_2_Handle_t */ if ((uint32_t)pHandle == (uint32_t)&pHandle->_Super) //cstat !MISRAC2012-Rule-11.4 { /* Disable IT and flags in case of LL driver usage * workaround for unwanted interrupt enabling done by LL driver */ LL_ADC_DisableIT_EOC(ADCx_1); LL_ADC_ClearFlag_EOC(ADCx_1); LL_ADC_DisableIT_JEOC(ADCx_1); LL_ADC_ClearFlag_JEOC(ADCx_1); LL_ADC_DisableIT_EOC(ADCx_2); LL_ADC_ClearFlag_EOC(ADCx_2); LL_ADC_DisableIT_JEOC(ADCx_2); LL_ADC_ClearFlag_JEOC(ADCx_2); if (TIM1 == TIMx) { /* TIM1 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph(LL_DBGMCU_APB2_GRP1_TIM1_STOP); } else { /* TIM8 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph(LL_DBGMCU_APB2_GRP1_TIM8_STOP); } if (OPAMPParams != NULL) { /* Enable OpAmp defined in OPAMPSelect_X table */ LL_OPAMP_Enable(OPAMPParams->OPAMPSelect_1[0]); LL_OPAMP_Enable(OPAMPParams->OPAMPSelect_1[1]); LL_OPAMP_Enable(OPAMPParams->OPAMPSelect_2[0]); } else { /* Nothing to do */ } /* Over current protection phase A */ if (COMP_OCPAx != NULL) { /* Inverting input */ if ((pHandle->pParams_str->CompOCPAInvInput_MODE != EXT_MODE) && (DAC_OCPAx != MC_NULL)) { R3_2_SetAOReferenceVoltage(pHandle->pParams_str->DAC_Channel_OCPA, DAC_OCPAx, (uint16_t)(pHandle->pParams_str->DAC_OCP_Threshold)); } else { /* Nothing to do */ } /* Output */ LL_COMP_Enable(COMP_OCPAx); LL_COMP_Lock(COMP_OCPAx); } else { /* Nothing to do */ } /* Over current protection phase B */ if (COMP_OCPBx != NULL) { if ((pHandle->pParams_str->CompOCPBInvInput_MODE != EXT_MODE) && (DAC_OCPBx != MC_NULL)) { R3_2_SetAOReferenceVoltage(pHandle->pParams_str->DAC_Channel_OCPB, DAC_OCPBx, (uint16_t)(pHandle->pParams_str->DAC_OCP_Threshold)); } else { /* Nothing to do */ } LL_COMP_Enable(COMP_OCPBx); LL_COMP_Lock(COMP_OCPBx); } else { /* Nothing to do */ } /* Over current protection phase C */ if (COMP_OCPCx != NULL) { if ((pHandle->pParams_str->CompOCPCInvInput_MODE != EXT_MODE) && (DAC_OCPCx != MC_NULL)) { R3_2_SetAOReferenceVoltage(pHandle->pParams_str->DAC_Channel_OCPC, DAC_OCPCx, (uint16_t)(pHandle->pParams_str->DAC_OCP_Threshold)); } else { /* Nothing to do */ } LL_COMP_Enable(COMP_OCPCx); LL_COMP_Lock(COMP_OCPCx); } else { /* Nothing to do */ } /* Over voltage protection */ if (COMP_OVPx != NULL) { /* Inverting input */ if ((pHandle->pParams_str->CompOVPInvInput_MODE != EXT_MODE) && (DAC_OVPx != MC_NULL)) { R3_2_SetAOReferenceVoltage(pHandle->pParams_str->DAC_Channel_OVP, DAC_OVPx, (uint16_t)(pHandle->pParams_str->DAC_OVP_Threshold)); } else { /* Nothing to do */ } /* Output */ LL_COMP_Enable(COMP_OVPx); LL_COMP_Lock(COMP_OVPx); } else { /* Nothing to do */ } if (0U == LL_ADC_IsEnabled(ADCx_1)) { R3_2_ADCxInit(ADCx_1); /* Only the Interrupt of the first ADC is enabled. * As Both ADCs are fired by HW at the same moment * It is safe to consider that both conversion are ready at the same time */ LL_ADC_ClearFlag_JEOS(ADCx_1); LL_ADC_EnableIT_JEOS(ADCx_1); } else { /* Nothing to do ADCx_1 already configured */ } if (0U == LL_ADC_IsEnabled(ADCx_2)) { R3_2_ADCxInit(ADCx_2); } else { /* Nothing to do ADCx_2 already configured */ } R3_2_TIMxInit(TIMx, &pHandle->_Super); } else { /* Nothing to do */ } #ifdef NULL_PTR_CHECK_R3_2_PWM_CURR_FDB } #endif } /* * @brief Initializes @p ADCx peripheral for current sensing. * */ static void R3_2_ADCxInit(ADC_TypeDef *ADCx) { /* - Exit from deep-power-down mode */ LL_ADC_DisableDeepPowerDown(ADCx); if (0U == LL_ADC_IsInternalRegulatorEnabled(ADCx)) { /* Enable ADC internal voltage regulator */ LL_ADC_EnableInternalRegulator(ADCx); /* Wait for Regulator Startup time, once for both */ /* Note: Variable divided by 2 to compensate partially */ /* CPU processing cycles, scaling in us split to not */ /* exceed 32 bits register capacity and handle low frequency */ volatile uint32_t wait_loop_index = ((LL_ADC_DELAY_INTERNAL_REGUL_STAB_US / 10UL) * (SystemCoreClock / (100000UL * 2UL))); while (wait_loop_index != 0UL) { wait_loop_index--; } } else { /* Nothing to do */ } LL_ADC_StartCalibration(ADCx, LL_ADC_SINGLE_ENDED); while (1U == LL_ADC_IsCalibrationOnGoing(ADCx)) { /* Nothing to do */ } /* ADC Enable (must be done after calibration) */ /* ADC5-140924: Enabling the ADC by setting ADEN bit soon after polling ADCAL=0 * following a calibration phase, could have no effect on ADC * within certain AHB/ADC clock ratio */ while (0U == LL_ADC_IsActiveFlag_ADRDY(ADCx)) { LL_ADC_Enable(ADCx); } /* Clear JSQR from CubeMX setting to avoid not wanting conversion */ LL_ADC_INJ_StartConversion(ADCx); LL_ADC_INJ_StopConversion(ADCx); /* TODO: check if not already done by MX */ LL_ADC_INJ_SetQueueMode(ADCx, LL_ADC_INJ_QUEUE_2CONTEXTS_END_EMPTY); /* Dummy conversion (ES0431 doc chap. 2.5.8 ADC channel 0 converted instead of the required ADC channel) Note: Sequence length forced to zero in order to prevent ADC OverRun occurrence */ LL_ADC_REG_SetSequencerLength(ADCx, 0U); LL_ADC_REG_StartConversion(ADCx); } /* * @brief Initializes @p TIMx peripheral with @p pHdl handler for PWM generation. * */ static void R3_2_TIMxInit(TIM_TypeDef *TIMx, PWMC_Handle_t *pHdl) { PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 volatile uint32_t Brk2Timeout = 1000; /* Disable main TIM counter to ensure * a synchronous start by TIM2 trigger */ LL_TIM_DisableCounter(TIMx); LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); /* Enables the TIMx Preload on CC1 Register */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH1); /* Enables the TIMx Preload on CC2 Register */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH2); /* Enables the TIMx Preload on CC3 Register */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH3); /* Enables the TIMx Preload on CC4 Register */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH4); /* Prepare timer for synchronization */ LL_TIM_GenerateEvent_UPDATE(TIMx); if (2U == pHandle->pParams_str->FreqRatio) { if (HIGHER_FREQ == pHandle->pParams_str->IsHigherFreqTim) { if (3U == pHandle->pParams_str->RepetitionCounter) { /* Set TIMx repetition counter to 1 */ LL_TIM_SetRepetitionCounter(TIMx, 1); LL_TIM_GenerateEvent_UPDATE(TIMx); /* Repetition counter will be set to 3 at next Update */ LL_TIM_SetRepetitionCounter(TIMx, 3); } else { /* Nothing to do */ } } else { /* Nothing to do */ } LL_TIM_SetCounter(TIMx, (uint32_t)(pHandle->Half_PWMPeriod) - 1U); } else /* bFreqRatio equal to 1 or 3 */ { if (M1 == pHandle->_Super.Motor) { if (1U == pHandle->pParams_str->RepetitionCounter) { LL_TIM_SetCounter(TIMx, (uint32_t)(pHandle->Half_PWMPeriod) - 1U); } else if (3U == pHandle->pParams_str->RepetitionCounter) { /* Set TIMx repetition counter to 1 */ LL_TIM_SetRepetitionCounter(TIMx, 1); LL_TIM_GenerateEvent_UPDATE(TIMx); /* Repetition counter will be set to 3 at next Update */ LL_TIM_SetRepetitionCounter(TIMx, 3); } else { /* Nothing to do */ } } else { /* Nothing to do */ } } LL_TIM_ClearFlag_BRK(TIMx); uint32_t result; result = LL_TIM_IsActiveFlag_BRK2(TIMx); while ((Brk2Timeout != 0u) && (1U == result)) { LL_TIM_ClearFlag_BRK2(TIMx); Brk2Timeout--; result = LL_TIM_IsActiveFlag_BRK2(TIMx); } LL_TIM_EnableIT_BRK(TIMx); /* Enable PWM channel */ LL_TIM_CC_EnableChannel(TIMx, TIMxCCER_MASK_CH123); } /* * @brief Stores in the @p pHdl handler the calibrated @p offsets. * */ __weak void R3_2_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { #ifdef NULL_PTR_CHECK_R3_2_PWM_CURR_FDB if ((MC_NULL == offsets) || (MC_NULL == pHdl)) { /* Nothing to do */ } else { #endif PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 pHandle->PhaseAOffset = (uint32_t)offsets->phaseAOffset; pHandle->PhaseBOffset = (uint32_t)offsets->phaseBOffset; pHandle->PhaseCOffset = (uint32_t)offsets->phaseCOffset; pHdl->offsetCalibStatus = true; #ifdef NULL_PTR_CHECK_R3_2_PWM_CURR_FDB } #endif } /* * @brief Reads the calibrated @p offsets stored in @p pHdl handler. * */ __weak void R3_2_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { #ifdef NULL_PTR_CHECK_R3_2_PWM_CURR_FDB if (MC_NULL == offsets) { /* Nothing to do */ } else { #endif PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 offsets->phaseAOffset = (int32_t)pHandle->PhaseAOffset; offsets->phaseBOffset = (int32_t)pHandle->PhaseBOffset; offsets->phaseCOffset = (int32_t)pHandle->PhaseCOffset; #ifdef NULL_PTR_CHECK_R3_2_PWM_CURR_FDB } #endif } /* * @brief Stores into the @p pHdl handler the voltage present on Ia and * Ib current feedback analog channels when no current is flowing into the * motor. * */ __weak void R3_2_CurrentReadingPolarization(PWMC_Handle_t *pHdl) { PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef *ADCx_1 = pHandle->pParams_str->ADCDataReg1[0]; ADC_TypeDef *ADCx_2 = pHandle->pParams_str->ADCDataReg2[0]; volatile PWMC_GetPhaseCurr_Cb_t GetPhaseCurrCbSave; volatile PWMC_SetSampPointSectX_Cb_t SetSampPointSectXCbSave; if (true == pHandle->_Super.offsetCalibStatus) { LL_ADC_INJ_StartConversion(ADCx_1); LL_ADC_INJ_StartConversion(ADCx_2); pHandle->ADC_ExternalPolarityInjected = (uint16_t)LL_ADC_INJ_TRIG_EXT_RISING; } else { /* Save callback routines */ GetPhaseCurrCbSave = pHandle->_Super.pFctGetPhaseCurrents; SetSampPointSectXCbSave = pHandle->_Super.pFctSetADCSampPointSectX; pHandle->PhaseAOffset = 0U; pHandle->PhaseBOffset = 0U; pHandle->PhaseCOffset = 0U; pHandle->PolarizationCounter = 0U; /* It forces inactive level on TIMx CHy and CHyN */ LL_TIM_CC_DisableChannel(TIMx, TIMxCCER_MASK_CH123); /* Offset calibration for all phases */ /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R3_2_HFCurrentsPolarizationAB; pHandle->_Super.pFctSetADCSampPointSectX = &R3_2_SetADCSampPointPolarization; pHandle->ADC_ExternalPolarityInjected = (uint16_t)LL_ADC_INJ_TRIG_EXT_RISING; /* We want to polarize calibration Phase A and Phase B, so we select SECTOR_5 */ pHandle->PolarizationSector=SECTOR_5; /* Required to force first polarization conversion on SECTOR_5 */ pHandle->_Super.Sector = SECTOR_5; R3_2_SwitchOnPWM(&pHandle->_Super); /* IF CH4 is enabled, it means that JSQR is now configured to sample polarization current * while ( LL_TIM_CC_IsEnabledChannel(TIMx, LL_TIM_CHANNEL_CH4) == 0u ) */ while (((TIMx->CR2) & TIM_CR2_MMS_Msk) != LL_TIM_TRGO_OC4REF) { /* Nothing to do */ } /* It is the right time to start the ADC without unwanted conversion */ /* Start ADC to wait for external trigger. This is series dependant */ LL_ADC_INJ_StartConversion(ADCx_1); LL_ADC_INJ_StartConversion(ADCx_2); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd(TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter); R3_2_SwitchOffPWM(&pHandle->_Super); /* Offset calibration for C phase */ pHandle->PolarizationCounter = 0U; /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R3_2_HFCurrentsPolarizationC; /* We want to polarize Phase C, so we select SECTOR_1 */ pHandle->PolarizationSector=SECTOR_1; /* Required to force first polarization conversion on SECTOR_1 */ pHandle->_Super.Sector = SECTOR_1; R3_2_SwitchOnPWM(&pHandle->_Super); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd(TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter); R3_2_SwitchOffPWM(&pHandle->_Super); pHandle->PhaseAOffset /= NB_CONVERSIONS; pHandle->PhaseBOffset /= NB_CONVERSIONS; pHandle->PhaseCOffset /= NB_CONVERSIONS; pHandle->_Super.offsetCalibStatus = true; /* Change back function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = GetPhaseCurrCbSave; pHandle->_Super.pFctSetADCSampPointSectX = SetSampPointSectXCbSave; /* It over write TIMx CCRy wrongly written by FOC during calibration so as to force 50% duty cycle on the three inverer legs */ /* Disable TIMx preload */ LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH1); LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH2); LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH3); LL_TIM_OC_SetCompareCH1 (TIMx, pHandle->Half_PWMPeriod); LL_TIM_OC_SetCompareCH2 (TIMx, pHandle->Half_PWMPeriod); LL_TIM_OC_SetCompareCH3 (TIMx, pHandle->Half_PWMPeriod); /* Enable TIMx preload */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH1); LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH2); LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH3); /* It re-enable drive of TIMx CHy and CHyN by TIMx CHyRef */ LL_TIM_CC_EnableChannel(TIMx, TIMxCCER_MASK_CH123); } /* At the end of calibration, all phases are at 50% we will sample A&B */ pHandle->_Super.Sector = SECTOR_5; pHandle->_Super.BrakeActionLock = false; } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /* * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p Iab ab_t format. * */ __weak void R3_2_GetPhaseCurrents(PWMC_Handle_t *pHdl, ab_t *Iab) { #ifdef NULL_PTR_CHECK_R3_2_PWM_CURR_FDB if (MC_NULL == Iab) { /* Nothing to do */ } else { #endif int32_t Aux; uint32_t ADCDataReg1; uint32_t ADCDataReg2; PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; uint8_t Sector; Sector = (uint8_t)pHandle->_Super.Sector; ADCDataReg1 = pHandle->pParams_str->ADCDataReg1[Sector]->JDR1; ADCDataReg2 = pHandle->pParams_str->ADCDataReg2[Sector]->JDR1; /* Disable ADC trigger source */ /* LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4) */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); switch (Sector) { case SECTOR_4: case SECTOR_5: { /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = (int32_t)(pHandle->PhaseAOffset) - (int32_t)(ADCDataReg1); /* Saturation of Ia */ if (Aux < -INT16_MAX) { Iab->a = -INT16_MAX; } else if (Aux > INT16_MAX) { Iab->a = INT16_MAX; } else { Iab->a = (int16_t)Aux; } /* Ib = PhaseBOffset - ADC converted value) */ Aux = (int32_t)(pHandle->PhaseBOffset) - (int32_t)(ADCDataReg2); /* Saturation of Ib */ if (Aux < -INT16_MAX) { Iab->b = -INT16_MAX; } else if (Aux > INT16_MAX) { Iab->b = INT16_MAX; } else { Iab->b = (int16_t)Aux; } break; } case SECTOR_6: case SECTOR_1: { /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ Aux = (int32_t)(pHandle->PhaseBOffset) - (int32_t)(ADCDataReg1); /* Saturation of Ib */ if (Aux < -INT16_MAX) { Iab->b = -INT16_MAX; } else if (Aux > INT16_MAX) { Iab->b = INT16_MAX; } else { Iab->b = (int16_t)Aux; } /* Ia = -Ic -Ib */ Aux = (int32_t)(ADCDataReg2) - (int32_t)(pHandle->PhaseCOffset); /* -Ic */ Aux -= (int32_t)Iab->b; /* Ia */ /* Saturation of Ia */ if (Aux > INT16_MAX) { Iab->a = INT16_MAX; } else if (Aux < -INT16_MAX) { Iab->a = -INT16_MAX; } else { Iab->a = (int16_t)Aux; } break; } case SECTOR_2: case SECTOR_3: { /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = (int32_t)(pHandle->PhaseAOffset) - (int32_t)(ADCDataReg1); /* Saturation of Ia */ if (Aux < -INT16_MAX) { Iab->a = -INT16_MAX; } else if (Aux > INT16_MAX) { Iab->a = INT16_MAX; } else { Iab->a = (int16_t)Aux; } /* Ib = -Ic -Ia */ Aux = (int32_t)(ADCDataReg2) - (int32_t)(pHandle->PhaseCOffset); /* -Ic */ Aux -= (int32_t)Iab->a; /* Ib */ /* Saturation of Ib */ if (Aux > INT16_MAX) { Iab->b = INT16_MAX; } else if (Aux < -INT16_MAX) { Iab->b = -INT16_MAX; } else { Iab->b = (int16_t)Aux; } break; } default: break; } pHandle->_Super.Ia = Iab->a; pHandle->_Super.Ib = Iab->b; pHandle->_Super.Ic = -Iab->a - Iab->b; #ifdef NULL_PTR_CHECK_R3_2_PWM_CURR_FDB } #endif } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /* * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p Iab ab_t format. Specific to overmodulation. * */ __weak void R3_2_GetPhaseCurrents_OVM(PWMC_Handle_t *pHdl, ab_t *Iab) { #ifdef NULL_PTR_CHECK_R3_2_PWM_CURR_FDB if (MC_NULL == Iab) { /* Nothing to do */ } else { #endif PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; int32_t Aux; uint32_t ADCDataReg1; uint32_t ADCDataReg2; uint8_t Sector; /* Disable ADC trigger source */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); Sector = (uint8_t)pHandle->_Super.Sector; ADCDataReg1 = pHandle->pParams_str->ADCDataReg1[Sector]->JDR1; ADCDataReg2 = pHandle->pParams_str->ADCDataReg2[Sector]->JDR1; switch (Sector) { case SECTOR_4: { /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ((int32_t)pHandle->PhaseAOffset) - ((int32_t)ADCDataReg1); /* Saturation of Ia */ if (Aux < -INT16_MAX) { Iab->a = -INT16_MAX; } else if (Aux > INT16_MAX) { Iab->a = INT16_MAX; } else { Iab->a = (int16_t)Aux; } if (true == pHandle->_Super.useEstCurrent) { // Ib not available, use estimated Ib Aux = (int32_t)(pHandle->_Super.IbEst); } else { /* Ib = PhaseBOffset - ADC converted value) */ Aux = ((int32_t)pHandle->PhaseBOffset) - ((int32_t)ADCDataReg2); } /* Saturation of Ib */ if (Aux < -INT16_MAX) { Iab->b = -INT16_MAX; } else if (Aux > INT16_MAX) { Iab->b = INT16_MAX; } else { Iab->b = (int16_t)Aux; } break; } case SECTOR_5: { /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ if (true == pHandle->_Super.useEstCurrent) { /* Ia not available, use estimated Ia */ Aux = (int32_t)(pHandle->_Super.IaEst); } else { Aux = ((int32_t)pHandle->PhaseAOffset) - ((int32_t)ADCDataReg1); } /* Saturation of Ia */ if (Aux < -INT16_MAX) { Iab->a = -INT16_MAX; } else if (Aux > INT16_MAX) { Iab->a = INT16_MAX; } else { Iab->a = (int16_t)Aux; } /* Ib = PhaseBOffset - ADC converted value) */ Aux = ((int32_t)pHandle->PhaseBOffset) - ((int32_t)ADCDataReg2); /* Saturation of Ib */ if (Aux < -INT16_MAX) { Iab->b = -INT16_MAX; } else if (Aux > INT16_MAX) { Iab->b = INT16_MAX; } else { Iab->b = (int16_t)Aux; } break; } case SECTOR_6: { /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ Aux = ((int32_t)pHandle->PhaseBOffset) - ((int32_t)ADCDataReg1); /* Saturation of Ib */ if (Aux < -INT16_MAX) { Iab->b = -INT16_MAX; } else if (Aux > INT16_MAX) { Iab->b = INT16_MAX; } else { Iab->b = (int16_t)Aux; } if (pHandle->_Super.useEstCurrent == true) { Aux = (int32_t) pHandle->_Super.IcEst ; /* -Ic */ Aux -= (int32_t)Iab->b; } else { /* Ia = -Ic -Ib */ Aux = (int32_t)(ADCDataReg2) - (int32_t)(pHandle->PhaseCOffset); /* -Ic */ Aux -= (int32_t)Iab->b; /* Ia */ } /* Saturation of Ia */ if (Aux > INT16_MAX) { Iab->a = INT16_MAX; } else if (Aux < -INT16_MAX) { Iab->a = -INT16_MAX; } else { Iab->a = (int16_t)Aux; } break; } case SECTOR_1: { /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ if (true == pHandle->_Super.useEstCurrent) { Aux = (int32_t) pHandle->_Super.IbEst; } else { Aux = ((int32_t)pHandle->PhaseBOffset) - (int32_t)(ADCDataReg1); } /* Saturation of Ib */ if (Aux < -INT16_MAX) { Iab->b = -INT16_MAX; } else if (Aux > INT16_MAX) { Iab->b = INT16_MAX; } else { Iab->b = (int16_t)Aux; } /* Ia = -Ic -Ib */ Aux = ((int32_t)ADCDataReg2) - ((int32_t)pHandle->PhaseCOffset); /* -Ic */ Aux -= (int32_t)Iab->b; /* Ia */ /* Saturation of Ia */ if (Aux > INT16_MAX) { Iab->a = INT16_MAX; } else if (Aux < -INT16_MAX) { Iab->a = -INT16_MAX; } else { Iab->a = (int16_t)Aux; } break; } case SECTOR_2: { /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ if (true == pHandle->_Super.useEstCurrent) { Aux = (int32_t)pHandle->_Super.IaEst; } else { Aux = ((int32_t)pHandle->PhaseAOffset) - ((int32_t)ADCDataReg1); } /* Saturation of Ia */ if (Aux < -INT16_MAX) { Iab->a = -INT16_MAX; } else if (Aux > INT16_MAX) { Iab->a = INT16_MAX; } else { Iab->a = (int16_t)Aux; } /* Ib = -Ic -Ia */ Aux = ((int32_t)ADCDataReg2) - ((int32_t)pHandle->PhaseCOffset); /* -Ic */ Aux -= (int32_t)Iab->a; /* Ib */ /* Saturation of Ib */ if (Aux > INT16_MAX) { Iab->b = INT16_MAX; } else if (Aux < -INT16_MAX) { Iab->b = -INT16_MAX; } else { Iab->b = (int16_t)Aux; } break; } case SECTOR_3: { /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ((int32_t)pHandle->PhaseAOffset) - ((int32_t)ADCDataReg1); /* Saturation of Ia */ if (Aux < -INT16_MAX) { Iab->a = -INT16_MAX; } else if (Aux > INT16_MAX) { Iab->a = INT16_MAX; } else { Iab->a = (int16_t)Aux; } if (pHandle->_Super.useEstCurrent == true) { /* Ib = -Ic -Ia */ Aux = (int32_t)pHandle->_Super.IcEst; /* -Ic */ Aux -= (int32_t)Iab->a; /* Ib */ } else { /* Ib = -Ic -Ia */ Aux = ((int32_t)ADCDataReg2) - ((int32_t)pHandle->PhaseCOffset); /* -Ic */ Aux -= (int32_t)Iab->a; /* Ib */ } /* Saturation of Ib */ if (Aux > INT16_MAX) { Iab->b = INT16_MAX; } else if (Aux < -INT16_MAX) { Iab->b = -INT16_MAX; } else { Iab->b = (int16_t)Aux; } break; } default: break; } pHandle->_Super.Ia = Iab->a; pHandle->_Super.Ib = Iab->b; pHandle->_Super.Ic = -Iab->a - Iab->b; #ifdef NULL_PTR_CHECK_R3_2_PWM_CURR_FDB } #endif } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /* * @brief Configures the ADC for the current sampling during calibration. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ uint16_t R3_2_SetADCSampPointPolarization(PWMC_Handle_t *pHdl) { PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 pHandle->_Super.Sector = pHandle->PolarizationSector; return R3_2_WriteTIMRegisters(&pHandle->_Super, (pHandle->Half_PWMPeriod - (uint16_t)1)); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /* * @brief Configures the ADC for the current sampling related to sector X (X = [1..6] ). * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ uint16_t R3_2_SetADCSampPointSectX(PWMC_Handle_t *pHdl) { uint16_t returnValue; #ifdef NULL_PTR_CHECK_R3_2_PWM_CURR_FDB if (MC_NULL == pHdl) { returnValue = 0U; } else { #endif PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 uint16_t SamplingPoint; uint16_t DeltaDuty; /* Verify that sampling is possible in the middle of PWM by checking the smallest duty cycle */ if ((uint16_t)(pHandle->Half_PWMPeriod - pHdl->lowDuty) > pHandle->pParams_str->Tafter) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* Sector number needed by GetPhaseCurrent, phase A and B are sampled which corresponds to sector 4 or 5 */ pHandle->_Super.Sector = SECTOR_5; /* set sampling point trigger in the middle of PWM period */ SamplingPoint = pHandle->Half_PWMPeriod - (uint16_t)1; } else { /* In this case it is necessary to convert phases with Maximum and variable complementary duty cycle */ /* ADC Injected sequence configuration. The stator phase with minimum value of complementary duty cycle is set as first. In every sector there is always one phase with maximum complementary duty, one with minimum complementary duty and one with variable complementary duty. In this case, phases with variable complementary duty and with maximum duty are converted and the first will be always the phase with variable complementary duty cycle */ DeltaDuty = (uint16_t)(pHdl->lowDuty - pHdl->midDuty); /* Definition of crossing point */ if (DeltaDuty > ((uint16_t)(pHandle->Half_PWMPeriod - pHdl->lowDuty) * 2U)) { SamplingPoint = pHdl->lowDuty - pHandle->pParams_str->Tbefore; } else { SamplingPoint = pHdl->lowDuty + pHandle->pParams_str->Tafter; if (SamplingPoint >= pHandle->Half_PWMPeriod) { /* ADC trigger edge must be changed from positive to negative */ pHandle->ADC_ExternalPolarityInjected = (uint16_t)LL_ADC_INJ_TRIG_EXT_FALLING; SamplingPoint = (2U * pHandle->Half_PWMPeriod) - SamplingPoint - (uint16_t)1; } else { /* Nothing to do */ } } } returnValue = R3_2_WriteTIMRegisters(&pHandle->_Super, SamplingPoint); #ifdef NULL_PTR_CHECK_R3_2_PWM_CURR_FDB } #endif return (returnValue); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /* * @brief Configures the ADC for the current sampling related to sector X (X = [1..6] ) in case of overmodulation. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHandle: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ uint16_t R3_2_SetADCSampPointSectX_OVM(PWMC_Handle_t *pHdl) { uint16_t retVal; #ifdef NULL_PTR_CHECK_R3_2_PWM_CURR_FDB if (MC_NULL == pHdl) { retVal = 0U; } else { #endif PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 uint16_t SamplingPoint; uint16_t DeltaDuty; pHandle->_Super.useEstCurrent = false; DeltaDuty = (uint16_t)(pHdl->lowDuty - pHdl->midDuty); /* Case 1 (cf user manual) */ if ((uint16_t)(pHandle->Half_PWMPeriod - pHdl->lowDuty) > pHandle->pParams_str->Tafter) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* Sector number needed by GetPhaseCurrent, phase A and B are sampled which corresponds to sector 4 or 5 */ pHandle->_Super.Sector = SECTOR_5; /* Set sampling point trigger in the middle of PWM period */ SamplingPoint = pHandle->Half_PWMPeriod - (uint16_t) 1; } else /* Case 2 (cf user manual) */ { if (DeltaDuty >= pHandle->pParams_str->Tcase2) { SamplingPoint = pHdl->lowDuty - pHandle->pParams_str->Tbefore; } else { /* Case 3 (cf user manual) */ if ((pHandle->Half_PWMPeriod - pHdl->lowDuty) > pHandle->pParams_str->Tcase3) { /* ADC trigger edge must be changed from positive to negative */ pHandle->ADC_ExternalPolarityInjected = (uint16_t) LL_ADC_INJ_TRIG_EXT_FALLING; SamplingPoint = pHdl->lowDuty + pHandle->pParams_str->Tsampling; } else { SamplingPoint = pHandle->Half_PWMPeriod - 1U; pHandle->_Super.useEstCurrent = true; } } } retVal = R3_2_WriteTIMRegisters(&pHandle->_Super, SamplingPoint); #ifdef NULL_PTR_CHECK_R3_2_PWM_CURR_FDB } #endif return (retVal); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /* * @brief Writes into peripheral registers the new duty cycle and sampling point. * * @param pHandle: Handler of the current instance of the PWM component. * @param SamplingPoint: Point at which the ADC will be triggered, written in timer clock counts. * @retval Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ __STATIC_INLINE uint16_t R3_2_WriteTIMRegisters(PWMC_Handle_t *pHdl, uint16_t SamplingPoint) { PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; uint16_t Aux; LL_TIM_OC_SetCompareCH1(TIMx, (uint32_t) pHandle->_Super.CntPhA); LL_TIM_OC_SetCompareCH2(TIMx, (uint32_t) pHandle->_Super.CntPhB); LL_TIM_OC_SetCompareCH3(TIMx, (uint32_t) pHandle->_Super.CntPhC); LL_TIM_OC_SetCompareCH4(TIMx, (uint32_t) SamplingPoint); /* Limit for update event */ /* if ( LL_TIM_CC_IsEnabledChannel(TIMx, LL_TIM_CHANNEL_CH4) == 1u ) */ if (((TIMx->CR2) & TIM_CR2_MMS_Msk) != LL_TIM_TRGO_RESET) { Aux = MC_DURATION; } else { Aux = MC_NO_ERROR; } return Aux; } /* * @brief Implementation of PWMC_GetPhaseCurrents to be performed during polarization. * * It sums up injected conversion data into PhaseAOffset and * PhaseBOffset to compute the offset introduced in the current feedback * network. It is required to properly configure ADC inputs before in order to enable * the offset computation. * * @param pHdl: Handler of the current instance of the PWM component. * @param Iab: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ static void R3_2_HFCurrentsPolarizationAB(PWMC_Handle_t *pHdl, ab_t *Iab) { #ifdef NULL_PTR_CHECK_R3_2_PWM_CURR_FDB if (MC_NULL == Iab) { /* Nothing to do */ } else { #endif PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; uint32_t ADCDataReg1 = pHandle->pParams_str->ADCDataReg1[pHandle->PolarizationSector]->JDR1; uint32_t ADCDataReg2 = pHandle->pParams_str->ADCDataReg2[pHandle->PolarizationSector]->JDR1; /* Disable ADC trigger source */ /* LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4) */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); if (pHandle->PolarizationCounter < NB_CONVERSIONS) { pHandle-> PhaseAOffset += ADCDataReg1; pHandle-> PhaseBOffset += ADCDataReg2; pHandle->PolarizationCounter++; } else { /* Nothing to do */ } /* During offset calibration no current is flowing in the phases */ Iab->a = 0; Iab->b = 0; #ifdef NULL_PTR_CHECK_R3_2_PWM_CURR_FDB } #endif } /* * @brief Implementation of PWMC_GetPhaseCurrents to be performed during polarization. * * It sums up injected conversion data into PhaseCOffset to compute the * offset introduced in the current feedback * network. It is required to properly configure ADC inputs before enabling * the offset computation. * * @param pHdl: Handler of the current instance of the PWM component. * @param Iab: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ static void R3_2_HFCurrentsPolarizationC(PWMC_Handle_t *pHdl, ab_t *Iab) { #ifdef NULL_PTR_CHECK_R3_2_PWM_CURR_FDB if (MC_NULL == Iab) { /* Nothing to do */ } else { #endif PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; uint32_t ADCDataReg2 = pHandle->pParams_str->ADCDataReg2[pHandle->PolarizationSector]->JDR1; /* Disable ADC trigger source */ /* LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4) */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); if (pHandle->PolarizationCounter < NB_CONVERSIONS) { /* Phase C is read from SECTOR_1, second value */ pHandle-> PhaseCOffset += ADCDataReg2; pHandle->PolarizationCounter++; } else { /* Nothing to do */ } /* During offset calibration no current is flowing in the phases */ Iab->a = 0; Iab->b = 0; #ifdef NULL_PTR_CHECK_R3_2_PWM_CURR_FDB } #endif } /* * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors of driving section. It has to be * called on each motor start-up when using high voltage drivers. * * @param pHdl: Handler of the current instance of the PWM component. * @param ticks: Timer ticks value to be applied * Min value: 0 (low sides ON) * Max value: PWM_PERIOD_CYCLES/2 (low sides OFF) */ __weak void R3_2_TurnOnLowSides(PWMC_Handle_t *pHdl, uint32_t ticks) { PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = true; /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE(pHandle->pParams_str->TIMx); /* Turn on the three low side switches */ LL_TIM_OC_SetCompareCH1(TIMx, ticks); LL_TIM_OC_SetCompareCH2(TIMx, ticks); LL_TIM_OC_SetCompareCH3(TIMx, ticks); /* Wait until next update */ while (0U == LL_TIM_IsActiveFlag_UPDATE(TIMx)) { /* Nothing to do */ } /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs(TIMx); if ((ES_GPIO == pHandle->_Super.LowSideOutputs)) { LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } else { /* Nothing to do */ } } /* * @brief Enables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_2_SwitchOnPWM(PWMC_Handle_t *pHdl) { PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; /* We forbid ADC usage for regular conversion on Systick */ pHandle->ADCRegularLocked = true; pHandle->_Super.TurnOnLowSidesAction = false; /* Set all duty to 50% */ LL_TIM_OC_SetCompareCH1(TIMx, ((uint32_t)pHandle->Half_PWMPeriod / (uint32_t)2)); LL_TIM_OC_SetCompareCH2(TIMx, ((uint32_t)pHandle->Half_PWMPeriod / (uint32_t)2)); LL_TIM_OC_SetCompareCH3(TIMx, ((uint32_t)pHandle->Half_PWMPeriod / (uint32_t)2)); LL_TIM_OC_SetCompareCH4(TIMx, ((uint32_t)pHandle->Half_PWMPeriod - (uint32_t)5)); /* Wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE(TIMx); while (0U == LL_TIM_IsActiveFlag_UPDATE(TIMx)) { /* Nothing to do */ } LL_TIM_ClearFlag_UPDATE(TIMx); /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE; LL_TIM_EnableAllOutputs(TIMx); if ((ES_GPIO == pHandle->_Super.LowSideOutputs)) { if ((TIMx->CCER & TIMxCCER_MASK_CH123) != 0U) { LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } } else { /* Nothing to do */ } /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE(TIMx); /* Enable Update IRQ */ LL_TIM_EnableIT_UPDATE(TIMx); } /* * @brief Disables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_2_SwitchOffPWM(PWMC_Handle_t *pHdl) { PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; /* Disable UPDATE ISR */ LL_TIM_DisableIT_UPDATE(TIMx); pHandle->_Super.TurnOnLowSidesAction = false; /* Main PWM Output Disable */ LL_TIM_DisableAllOutputs(TIMx); if (true == pHandle->_Super.BrakeActionLock) { /* Nothing to do */ } else { if (ES_GPIO == pHandle->_Super.LowSideOutputs) { LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } else { /* Nothing to do */ } } /* Wait for a new PWM period to flush last HF task */ LL_TIM_ClearFlag_UPDATE(TIMx); while (0U == LL_TIM_IsActiveFlag_UPDATE(TIMx)) { /* Nothing to do */ } LL_TIM_ClearFlag_UPDATE(TIMx); /* We allow ADC usage for regular conversion on Systick */ pHandle->ADCRegularLocked = false; } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /* * @brief Contains the TIMx Update event interrupt. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void *R3_2_TIMx_UP_IRQHandler(PWMC_R3_2_Handle_t *pHandle) { void *tempPointer; //cstat !MISRAC2012-Rule-8.13 #ifdef NULL_PTR_CHECK_R3_2_PWM_CURR_FDB if (MC_NULL == pHandle) { tempPointer = MC_NULL; } else { #endif TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; R3_3_OPAMPParams_t *OPAMPParams = pHandle->pParams_str->OPAMPParams; OPAMP_TypeDef *operationAmp; uint32_t OpampConfig; if (OPAMPParams != NULL) { /* We can not change OPAMP source if ADC acquisition is ongoing (Dual motor with internal opamp use case) */ while (0x0u != pHandle->pParams_str->ADCDataReg1[pHandle->_Super.Sector]->JSQR) { /* Nothing to do */ } /* We need to manage the Operational amplifier internal output enable - Dedicated to G4 and the VPSEL selection */ OpampConfig = OPAMPParams->OPAMPConfig1[pHandle->_Super.Sector]; if (OpampConfig != OPAMP_UNCHANGED) { operationAmp = OPAMPParams->OPAMPSelect_1[pHandle->_Super.Sector]; MODIFY_REG(operationAmp->CSR, (OPAMP_CSR_OPAMPINTEN | OPAMP_CSR_VPSEL), OpampConfig); } else { /* Nothing to do */ } OpampConfig = OPAMPParams->OPAMPConfig2[pHandle->_Super.Sector]; if (OpampConfig != OPAMP_UNCHANGED) { operationAmp = OPAMPParams->OPAMPSelect_2[pHandle->_Super.Sector]; MODIFY_REG(operationAmp->CSR, (OPAMP_CSR_OPAMPINTEN | OPAMP_CSR_VPSEL), OpampConfig); } else { /* Nothing to do */ } } else { /* Nothing to do */ } pHandle->pParams_str->ADCDataReg1[pHandle->_Super.Sector]->JSQR = pHandle->pParams_str->ADCConfig1[pHandle->_Super.Sector] | (uint32_t) pHandle->ADC_ExternalPolarityInjected; pHandle->pParams_str->ADCDataReg2[pHandle->_Super.Sector]->JSQR = pHandle->pParams_str->ADCConfig2[pHandle->_Super.Sector] | (uint32_t) pHandle->ADC_ExternalPolarityInjected; /* Enable ADC trigger source */ /* LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH4) */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_OC4REF); pHandle->ADC_ExternalPolarityInjected = (uint16_t)LL_ADC_INJ_TRIG_EXT_RISING; tempPointer = &(pHandle->_Super.Motor); #ifdef NULL_PTR_CHECK_R3_2_PWM_CURR_FDB } #endif return (tempPointer); } /* * @brief Configures the analog output used for protection thresholds. * * @param DAC_Channel: the selected DAC channel. * This parameter can be: * @arg DAC_Channel_1: DAC Channel1 selected. * @arg DAC_Channel_2: DAC Channel2 selected. * @param DACx: DAC to be configured. * @param hDACVref: Value of DAC reference expressed as 16bit unsigned integer. * Ex. 0 = 0V 65536 = VDD_DAC. */ static void R3_2_SetAOReferenceVoltage(uint32_t DAC_Channel, DAC_TypeDef *DACx, uint16_t hDACVref) { LL_DAC_ConvertData12LeftAligned(DACx, DAC_Channel, hDACVref); /* Enable DAC Channel */ LL_DAC_TrigSWConversion(DACx, DAC_Channel); if (1U == LL_DAC_IsEnabled(DACx, DAC_Channel)) { /* If DAC is already enable, we wait LL_DAC_DELAY_VOLTAGE_SETTLING_US */ volatile uint32_t wait_loop_index = ((LL_DAC_DELAY_VOLTAGE_SETTLING_US) * (SystemCoreClock / (1000000UL * 2UL))); while (wait_loop_index != 0UL) { wait_loop_index--; } } else { /* If DAC is not enabled, we must wait LL_DAC_DELAY_STARTUP_VOLTAGE_SETTLING_US */ LL_DAC_Enable(DACx, DAC_Channel); volatile uint32_t wait_loop_index = ((LL_DAC_DELAY_STARTUP_VOLTAGE_SETTLING_US) * (SystemCoreClock / (1000000UL * 2UL))); while (wait_loop_index != 0UL) { wait_loop_index--; } } } /* * @brief Sets the PWM mode for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_2_RLDetectionModeEnable(PWMC_Handle_t *pHdl) { PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; if (false == pHandle->_Super.RLDetectionMode) { /* Channel1 configuration */ LL_TIM_OC_SetMode(TIMx, LL_TIM_CHANNEL_CH1, LL_TIM_OCMODE_PWM1); LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH1); LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH1N); LL_TIM_OC_SetCompareCH1(TIMx, 0U); /* Channel2 configuration */ if (LS_PWM_TIMER == pHandle->_Super.LowSideOutputs) { LL_TIM_OC_SetMode(TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_ACTIVE); LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH2); LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH2N); } else if (ES_GPIO == pHandle->_Super.LowSideOutputs) { LL_TIM_OC_SetMode(TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_INACTIVE); LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH2); LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH2N); } else { /* Nothing to do */ } /* Channel3 configuration */ LL_TIM_OC_SetMode(TIMx, LL_TIM_CHANNEL_CH3, LL_TIM_OCMODE_PWM2); LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH3); LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH3N); pHandle->PhaseAOffset = pHandle->PhaseBOffset; /* Use only the offset of phB */ } else { /* Nothing to do */ } pHandle->_Super.pFctGetPhaseCurrents = &R3_2_RLGetPhaseCurrents; pHandle->_Super.pFctTurnOnLowSides = &R3_2_RLTurnOnLowSides; pHandle->_Super.pFctSwitchOnPwm = &R3_2_RLSwitchOnPWM; pHandle->_Super.pFctSwitchOffPwm = &R3_2_SwitchOffPWM; pHandle->_Super.RLDetectionMode = true; } /* * @brief Disables the PWM mode for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_2_RLDetectionModeDisable(PWMC_Handle_t *pHdl) { PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; if (true == pHandle->_Super.RLDetectionMode) { /* Channel1 configuration */ LL_TIM_OC_SetMode(TIMx, LL_TIM_CHANNEL_CH1, LL_TIM_OCMODE_PWM1); LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH1); if (LS_PWM_TIMER == pHandle->_Super.LowSideOutputs) { LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH1N); } else if (ES_GPIO == pHandle->_Super.LowSideOutputs) { LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH1N); } else { /* Nothing to do */ } LL_TIM_OC_SetCompareCH1(TIMx, ((uint32_t)pHandle->Half_PWMPeriod) >> 1); /* Channel2 configuration */ LL_TIM_OC_SetMode(TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_PWM1); LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH2); if (LS_PWM_TIMER == pHandle->_Super.LowSideOutputs) { LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH2N); } else if (ES_GPIO == pHandle->_Super.LowSideOutputs) { LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH2N); } else { /* Nothing to do */ } LL_TIM_OC_SetCompareCH2(TIMx, ((uint32_t)pHandle->Half_PWMPeriod) >> 1); /* Channel3 configuration */ LL_TIM_OC_SetMode(TIMx, LL_TIM_CHANNEL_CH3, LL_TIM_OCMODE_PWM1); LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH3); if (LS_PWM_TIMER == pHandle->_Super.LowSideOutputs) { LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH3N); } else if (ES_GPIO == pHandle->_Super.LowSideOutputs) { LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH3N); } else { /* Nothing to do */ } LL_TIM_OC_SetCompareCH3(TIMx, ((uint32_t)pHandle->Half_PWMPeriod) >> 1); pHandle->_Super.pFctGetPhaseCurrents = &R3_2_GetPhaseCurrents; pHandle->_Super.pFctTurnOnLowSides = &R3_2_TurnOnLowSides; pHandle->_Super.pFctSwitchOnPwm = &R3_2_SwitchOnPWM; pHandle->_Super.pFctSwitchOffPwm = &R3_2_SwitchOffPWM; pHandle->_Super.RLDetectionMode = false; } else { /* Nothing to do */ } } /* * @brief Sets the PWM dutycycle for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. * @param hDuty: Duty cycle to apply, written in uint16_t. * @retval Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ uint16_t R3_2_RLDetectionModeSetDuty(PWMC_Handle_t *pHdl, uint16_t hDuty) { uint16_t tempValue; #ifdef NULL_PTR_CHECK_R3_2_PWM_CURR_FDB if (MC_NULL == pHdl) { tempValue = 0U; } else { #endif PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; uint32_t val; uint16_t hAux; pHandle->ADCRegularLocked = true; val = (((uint32_t)pHandle->Half_PWMPeriod) * ((uint32_t)hDuty)) >> 16; pHandle->_Super.CntPhA = (uint16_t)val; /* Set CC4 as PWM mode 2 (default) */ LL_TIM_OC_SetMode(TIMx, LL_TIM_CHANNEL_CH4, LL_TIM_OCMODE_PWM2); LL_TIM_OC_SetCompareCH4(TIMx, (((uint32_t)pHandle->Half_PWMPeriod) - ((uint32_t)pHandle->_Super.Ton))); LL_TIM_OC_SetCompareCH3(TIMx, (uint32_t)pHandle->_Super.Toff); LL_TIM_OC_SetCompareCH1(TIMx, (uint32_t)pHandle->_Super.CntPhA); /* Enabling next Trigger */ /* LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH4) */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_OC4REF); /* Set the sector that correspond to Phase A and B sampling */ pHdl->Sector = SECTOR_4; /* Limit for update event */ /* Check the status flag. If an update event has occurred before to set new values of regs the FOC rate is too high */ if (((TIMx->CR2) & TIM_CR2_MMS_Msk) != LL_TIM_TRGO_RESET) { hAux = MC_DURATION; } else { hAux = MC_NO_ERROR; } if (1U == pHandle->_Super.SWerror) { hAux = MC_DURATION; pHandle->_Super.SWerror = 0U; } else { /* Nothing to do */ } tempValue = hAux; #ifdef NULL_PTR_CHECK_R3_2_PWM_CURR_FDB } #endif return (tempValue); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /* * @brief Computes and stores into @p pHandle latest converted motor phase currents * during RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ static void R3_2_RLGetPhaseCurrents(PWMC_Handle_t *pHdl, ab_t *pStator_Currents) { #ifdef NULL_PTR_CHECK_R3_2_PWM_CURR_FDB if (MC_NULL == pStator_Currents) { /* Nothing to do */ } else { #endif PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; int32_t wAux; /* Disable ADC trigger source */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); wAux = ((int32_t)pHandle->PhaseBOffset) - ((int32_t)(pHandle->pParams_str->ADCDataReg2[pHandle->_Super.Sector]->JDR1)); /* Check saturation */ if (wAux > -INT16_MAX) { if (wAux < INT16_MAX) { /* Nothing to do */ } else { wAux = INT16_MAX; } } else { wAux = -INT16_MAX; } pStator_Currents->a = (int16_t)wAux; pStator_Currents->b = (int16_t)wAux; #ifdef NULL_PTR_CHECK_R3_2_PWM_CURR_FDB } #endif } /* * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors * of driving section. It has to be called at each motor start-up when * using high voltage drivers. * This function is specific for RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. * @param ticks: Duty cycle of the boot capacitors charge, specific to motor. */ static void R3_2_RLTurnOnLowSides(PWMC_Handle_t *pHdl, uint32_t ticks) { PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; pHandle->ADCRegularLocked = true; /* Turn on the phase A low side switch */ LL_TIM_OC_SetCompareCH1(TIMx, 0u); /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE(TIMx); /* Wait until next update */ while (0U == LL_TIM_IsActiveFlag_UPDATE(TIMx)) { /* Nothing to do */ } /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs(TIMx); if (ES_GPIO == pHandle->_Super.LowSideOutputs) { LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } else { /* Nothing to do */ } } /* * @brief Enables PWM generation on the proper Timer peripheral. * * This function is specific for RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. */ static void R3_2_RLSwitchOnPWM( PWMC_Handle_t *pHdl) { #ifdef NULL_PTR_CHECK_R3_2_PWM_CURR_FDB if (MC_NULL == pHdl) { /* Nothing to do */ } else { #endif PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef *ADCx_1 = pHandle->pParams_str->ADCDataReg1[0]; ADC_TypeDef *ADCx_2 = pHandle->pParams_str->ADCDataReg2[0]; pHandle->ADCRegularLocked=true; /* Wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE(TIMx); while (0U == LL_TIM_IsActiveFlag_UPDATE(TIMx)) { /* Nothing to do */ } /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE(TIMx); LL_TIM_OC_SetCompareCH1(TIMx, 1U); LL_TIM_OC_SetCompareCH4(TIMx, ((uint32_t )pHandle->Half_PWMPeriod) - 5U); while (0U == LL_TIM_IsActiveFlag_UPDATE(TIMx)) { /* Nothing to do */ } /* Enable TIMx update interrupt */ LL_TIM_EnableIT_UPDATE(TIMx); /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE ; LL_TIM_EnableAllOutputs(TIMx); if (ES_GPIO == pHandle->_Super.LowSideOutputs) { if ((TIMx->CCER & TIMxCCER_MASK_CH123 ) != 0U) { LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } } else { /* Nothing to do */ } /* Set the sector that correspond to Phase B and C sampling * B will be sampled by ADCx_1 */ pHdl->Sector = SECTOR_4; LL_ADC_INJ_StartConversion(ADCx_1); LL_ADC_INJ_StartConversion(ADCx_2); #ifdef NULL_PTR_CHECK_R3_2_PWM_CURR_FDB } #endif } /* * @brief Turns on low sides switches and start ADC triggering. * * This function is specific for MP phase. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_2_RLTurnOnLowSidesAndStart(PWMC_Handle_t *pHdl) { #ifdef NULL_PTR_CHECK_R3_2_PWM_CURR_FDB if (MC_NULL == pHdl) { /* Nothing to do */ } else { #endif PWMC_R3_2_Handle_t *pHandle = (PWMC_R3_2_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; pHandle->ADCRegularLocked=true; LL_TIM_ClearFlag_UPDATE(TIMx); while (0U == LL_TIM_IsActiveFlag_UPDATE(TIMx)) { /* Nothing to do */ } /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE(TIMx); LL_TIM_OC_SetCompareCH1(TIMx, 0x0U); LL_TIM_OC_SetCompareCH2(TIMx, 0x0U); LL_TIM_OC_SetCompareCH3(TIMx, 0x0U); LL_TIM_OC_SetCompareCH4(TIMx, ((uint32_t )pHandle->Half_PWMPeriod) - 5U); while (0U == LL_TIM_IsActiveFlag_UPDATE(TIMx)) { /* Nothing to do */ } /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE ; LL_TIM_EnableAllOutputs (TIMx); if (ES_GPIO == pHandle->_Super.LowSideOutputs ) { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } else { /* Nothing to do */ } pHdl->Sector = SECTOR_4; LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH4); LL_TIM_EnableIT_UPDATE(TIMx); #ifdef NULL_PTR_CHECK_R3_2_PWM_CURR_FDB } #endif } /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
64,669
C
29.404325
178
0.60154
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/G4xx/Src/r3_1_g4xx_pwm_curr_fdbk.c
/** ****************************************************************************** * @file r3_1_g4xx_pwm_curr_fdbk.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement current sensor * class to be stantiated when the three shunts current sensing * topology is used. It is specifically designed for STM32G4XX * microcontrollers and implements the successive sampling of two motor * current using shared ADC. * + MCU peripheral and handle initialization function * + three shunts current sensing * + space vector modulation function * + ADC sampling function * ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "r3_1_g4xx_pwm_curr_fdbk.h" #include "pwm_common.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup R3_1_pwm_curr_fdbk * @{ */ /* Private defines -----------------------------------------------------------*/ #define TIMxCCER_MASK_CH123 ((uint16_t)(LL_TIM_CHANNEL_CH1|LL_TIM_CHANNEL_CH1N|\ LL_TIM_CHANNEL_CH2|LL_TIM_CHANNEL_CH2N|\ LL_TIM_CHANNEL_CH3|LL_TIM_CHANNEL_CH3N)) /* Private typedef -----------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ static void R3_1_TIMxInit(TIM_TypeDef *TIMx, PWMC_Handle_t *pHdl); static void R3_1_ADCxInit(ADC_TypeDef *ADCx); __STATIC_INLINE uint16_t R3_1_WriteTIMRegisters(PWMC_Handle_t *pHdl, uint16_t hCCR4Reg); static void R3_1_HFCurrentsPolarizationAB(PWMC_Handle_t *pHdl, ab_t *Iab); static void R3_1_HFCurrentsPolarizationC(PWMC_Handle_t *pHdl, ab_t *Iab); static void R3_1_SetAOReferenceVoltage(uint32_t DAC_Channel, DAC_TypeDef *DACx, uint16_t hDACVref); uint16_t R3_1_SetADCSampPointPolarization(PWMC_Handle_t *pHdl) ; /* * @brief Initializes TIMx, ADC, GPIO, DMA1 and NVIC for current reading * in three shunt topology using STM32G4XX and shared ADC. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void R3_1_Init(PWMC_R3_1_Handle_t *pHandle) { if (MC_NULL == pHandle) { /* Nothing to do */ } else { R3_3_OPAMPParams_t *OPAMPParams = pHandle->pParams_str->OPAMPParams; COMP_TypeDef *COMP_OCPAx = pHandle->pParams_str->CompOCPASelection; COMP_TypeDef *COMP_OCPBx = pHandle->pParams_str->CompOCPBSelection; COMP_TypeDef *COMP_OCPCx = pHandle->pParams_str->CompOCPCSelection; COMP_TypeDef *COMP_OVPx = pHandle->pParams_str->CompOVPSelection; DAC_TypeDef *DAC_OCPAx = pHandle->pParams_str->DAC_OCP_ASelection; DAC_TypeDef *DAC_OCPBx = pHandle->pParams_str->DAC_OCP_BSelection; DAC_TypeDef *DAC_OCPCx = pHandle->pParams_str->DAC_OCP_CSelection; DAC_TypeDef *DAC_OVPx = pHandle->pParams_str->DAC_OVP_Selection; TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef *ADCx = pHandle->pParams_str->ADCx; /*Check that _Super is the first member of the structure PWMC_R3_1_Handle_t */ if ((uint32_t)pHandle == (uint32_t)&pHandle->_Super) //cstat !MISRAC2012-Rule-11.4 { /* disable IT and flags in case of LL driver usage * workaround for unwanted interrupt enabling done by LL driver */ LL_ADC_DisableIT_EOC(ADCx); LL_ADC_ClearFlag_EOC(ADCx); LL_ADC_DisableIT_JEOC(ADCx); LL_ADC_ClearFlag_JEOC(ADCx); if (TIM1 == TIMx) { /* TIM1 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph(LL_DBGMCU_APB2_GRP1_TIM1_STOP); } else { /* TIM8 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph(LL_DBGMCU_APB2_GRP1_TIM8_STOP); } if (OPAMPParams != NULL) { /* Enable OpAmp defined in OPAMPSelect_X table */ LL_OPAMP_Enable(OPAMPParams->OPAMPSelect_1[0]); LL_OPAMP_Enable(OPAMPParams->OPAMPSelect_1[1]); LL_OPAMP_Enable(OPAMPParams->OPAMPSelect_2[0]); } else { /* Nothing to do */ } /* Over current protection phase A */ if (COMP_OCPAx != NULL) { /* Inverting input*/ if ((pHandle->pParams_str->CompOCPAInvInput_MODE != EXT_MODE) && (DAC_OCPAx != MC_NULL)) { R3_1_SetAOReferenceVoltage(pHandle->pParams_str->DAC_Channel_OCPA, DAC_OCPAx, (uint16_t)(pHandle->pParams_str->DAC_OCP_Threshold)); } /* Output */ LL_COMP_Enable(COMP_OCPAx); LL_COMP_Lock(COMP_OCPAx); } else { /* Nothing to do */ } /* Over current protection phase B */ if (COMP_OCPBx != NULL) { if ((pHandle->pParams_str->CompOCPBInvInput_MODE != EXT_MODE) && (DAC_OCPBx != MC_NULL)) { R3_1_SetAOReferenceVoltage(pHandle->pParams_str->DAC_Channel_OCPB, DAC_OCPBx, (uint16_t)(pHandle->pParams_str->DAC_OCP_Threshold)); } LL_COMP_Enable(COMP_OCPBx); LL_COMP_Lock(COMP_OCPBx); } else { /* Nothing to do */ } /* Over current protection phase C */ if (COMP_OCPCx != NULL) { if ((pHandle->pParams_str->CompOCPCInvInput_MODE != EXT_MODE) && (DAC_OCPCx != MC_NULL)) { R3_1_SetAOReferenceVoltage(pHandle->pParams_str->DAC_Channel_OCPC, DAC_OCPCx, (uint16_t)(pHandle->pParams_str->DAC_OCP_Threshold)); } LL_COMP_Enable(COMP_OCPCx); LL_COMP_Lock(COMP_OCPCx); } else { /* Nothing to do */ } /* Over voltage protection */ if (COMP_OVPx != NULL) { /* Inverting input*/ if ((pHandle->pParams_str->CompOVPInvInput_MODE != EXT_MODE) && (DAC_OVPx != MC_NULL)) { R3_1_SetAOReferenceVoltage(pHandle->pParams_str->DAC_Channel_OVP, DAC_OVPx, (uint16_t)(pHandle->pParams_str->DAC_OVP_Threshold)); } /* Output */ LL_COMP_Enable(COMP_OVPx); LL_COMP_Lock(COMP_OVPx); } else { /* Nothing to do */ } if (0U == LL_ADC_IsEnabled(ADCx)) { R3_1_ADCxInit(ADCx); /* Only the Interrupt of the first ADC is enabled. * As Both ADCs are fired by HW at the same moment * It is safe to consider that both conversion are ready at the same time*/ LL_ADC_ClearFlag_JEOS(ADCx); LL_ADC_EnableIT_JEOS(ADCx); } else { /* Nothing to do ADCx already configured */ } R3_1_TIMxInit(TIMx, &pHandle->_Super); } else { /* Nothing to do */ } } } /* * @brief Initializes @p ADCx peripheral for current sensing. * */ static void R3_1_ADCxInit(ADC_TypeDef *ADCx) { /* - Exit from deep-power-down mode */ LL_ADC_DisableDeepPowerDown(ADCx); if (0U == LL_ADC_IsInternalRegulatorEnabled(ADCx)) { /* Enable ADC internal voltage regulator */ LL_ADC_EnableInternalRegulator(ADCx); /* Wait for Regulator Startup time, once for both */ /* Note: Variable divided by 2 to compensate partially */ /* CPU processing cycles, scaling in us split to not */ /* exceed 32 bits register capacity and handle low frequency. */ volatile uint32_t wait_loop_index = ((LL_ADC_DELAY_INTERNAL_REGUL_STAB_US / 10UL) * (SystemCoreClock / (100000UL * 2UL))); while (wait_loop_index != 0UL) { wait_loop_index--; } } else { /* Nothing to do */ } LL_ADC_StartCalibration(ADCx, LL_ADC_SINGLE_ENDED); while (1U == LL_ADC_IsCalibrationOnGoing(ADCx)) { /* Nothing to do */ } /* ADC Enable (must be done after calibration) */ /* ADC5-140924: Enabling the ADC by setting ADEN bit soon after polling ADCAL=0 * following a calibration phase, could have no effect on ADC * within certain AHB/ADC clock ratio. */ while (0U == LL_ADC_IsActiveFlag_ADRDY(ADCx)) { LL_ADC_Enable(ADCx); } /* Clear JSQR from CubeMX setting to avoid not wanting conversion*/ LL_ADC_INJ_StartConversion(ADCx); LL_ADC_INJ_StopConversion(ADCx); /* TODO: check if not already done by MX */ LL_ADC_INJ_SetQueueMode(ADCx, LL_ADC_INJ_QUEUE_2CONTEXTS_END_EMPTY); /* Dummy conversion (ES0431 doc chap. 2.5.8 ADC channel 0 converted instead of the required ADC channel) Note: Sequence length forced to zero in order to prevent ADC OverRun occurrence */ LL_ADC_REG_SetSequencerLength(ADCx, 0U); LL_ADC_REG_StartConversion(ADCx); } /* * @brief It initializes TIMx peripheral for PWM generation. * * @param TIMx: Timer to be initialized. * @param pHdl: Handler of the current instance of the PWM component. */ static void R3_1_TIMxInit(TIM_TypeDef *TIMx, PWMC_Handle_t *pHdl) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ volatile uint32_t Brk2Timeout = 1000; /* disable main TIM counter to ensure * a synchronous start by TIM2 trigger */ LL_TIM_DisableCounter(TIMx); LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); /* Enables the TIMx Preload on CC1 Register */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH1); /* Enables the TIMx Preload on CC2 Register */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH2); /* Enables the TIMx Preload on CC3 Register */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH3); /* Enables the TIMx Preload on CC4 Register */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH4); /* Prepare timer for synchronization */ LL_TIM_GenerateEvent_UPDATE(TIMx); if (2U == pHandle->pParams_str->FreqRatio) { if (HIGHER_FREQ == pHandle->pParams_str->IsHigherFreqTim) { if (3U == pHandle->pParams_str->RepetitionCounter) { /* Set TIMx repetition counter to 1 */ LL_TIM_SetRepetitionCounter(TIMx, 1); LL_TIM_GenerateEvent_UPDATE(TIMx); /* Repetition counter will be set to 3 at next Update */ LL_TIM_SetRepetitionCounter(TIMx, 3); } else { /* Nothing to do */ } } else { /* Nothing to do */ } LL_TIM_SetCounter(TIMx, (uint32_t)(pHandle->Half_PWMPeriod) - 1U); } else /* bFreqRatio equal to 1 or 3 */ { if (M1 == pHandle->_Super.Motor) { if (1U == pHandle->pParams_str->RepetitionCounter) { LL_TIM_SetCounter(TIMx, (uint32_t)(pHandle->Half_PWMPeriod) - 1U); } else if (3U == pHandle->pParams_str->RepetitionCounter) { /* Set TIMx repetition counter to 1 */ LL_TIM_SetRepetitionCounter(TIMx, 1); LL_TIM_GenerateEvent_UPDATE(TIMx); /* Repetition counter will be set to 3 at next Update */ LL_TIM_SetRepetitionCounter(TIMx, 3); } else { /* Nothing to do */ } } else { /* Nothing to do */ } } LL_TIM_ClearFlag_BRK(TIMx); uint32_t result; result = LL_TIM_IsActiveFlag_BRK2(TIMx); while ((Brk2Timeout != 0u) && (1U == result)) { LL_TIM_ClearFlag_BRK2(TIMx); Brk2Timeout--; result = LL_TIM_IsActiveFlag_BRK2(TIMx); } LL_TIM_EnableIT_BRK(TIMx); /* Enable PWM channel */ LL_TIM_CC_EnableChannel(TIMx, TIMxCCER_MASK_CH123); } /* * @brief Stores in the handler the calibrated offsets. * */ __weak void R3_1_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 pHandle->PhaseAOffset = offsets->phaseAOffset; pHandle->PhaseBOffset = offsets->phaseBOffset; pHandle->PhaseCOffset = offsets->phaseCOffset; pHdl->offsetCalibStatus = true; } /* * @brief Reads the calibrated offsets stored in the handler. * */ __weak void R3_1_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 offsets->phaseAOffset = pHandle->PhaseAOffset; offsets->phaseBOffset = pHandle->PhaseBOffset; offsets->phaseCOffset = pHandle->PhaseCOffset; } /* * @brief Stores into the @p pHdl the voltage present on Ia and Ib current * feedback analog channels when no current is flowing into the motor. * */ __weak void R3_1_CurrentReadingPolarization(PWMC_Handle_t *pHdl) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef *ADCx = pHandle->pParams_str->ADCx; volatile PWMC_GetPhaseCurr_Cb_t GetPhaseCurrCbSave; volatile PWMC_SetSampPointSectX_Cb_t SetSampPointSectXCbSave; if (true == pHandle->_Super.offsetCalibStatus) { LL_ADC_INJ_StartConversion(ADCx); pHandle->ADC_ExternalPolarityInjected = (uint16_t)LL_ADC_INJ_TRIG_EXT_RISING; } else { /* Save callback routines */ GetPhaseCurrCbSave = pHandle->_Super.pFctGetPhaseCurrents; SetSampPointSectXCbSave = pHandle->_Super.pFctSetADCSampPointSectX; pHandle->PhaseAOffset = 0U; pHandle->PhaseBOffset = 0U; pHandle->PhaseCOffset = 0U; pHandle->PolarizationCounter = 0U; /* It forces inactive level on TIMx CHy and CHyN */ LL_TIM_CC_DisableChannel(TIMx, TIMxCCER_MASK_CH123); /* Offset calibration for all phases */ /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R3_1_HFCurrentsPolarizationAB; pHandle->_Super.pFctSetADCSampPointSectX = &R3_1_SetADCSampPointPolarization; pHandle->ADC_ExternalPolarityInjected = (uint16_t)LL_ADC_INJ_TRIG_EXT_RISING; /* We want to polarize calibration Phase A and Phase B, so we select SECTOR_5 */ pHandle->PolarizationSector=SECTOR_5; /* Required to force first polarization conversion on SECTOR_5*/ pHandle->_Super.Sector = SECTOR_5; R3_1_SwitchOnPWM(&pHandle->_Super); /* IF CH4 is enabled, it means that JSQR is now configured to sample polarization current*/ /*while ( LL_TIM_CC_IsEnabledChannel(TIMx, LL_TIM_CHANNEL_CH4) == 0u ) */ while (((TIMx->CR2) & TIM_CR2_MMS_Msk) != LL_TIM_TRGO_OC4REF) { /* Nothing to do */ } /* It is the right time to start the ADC without unwanted conversion */ /* Start ADC to wait for external trigger. This is series dependant*/ LL_ADC_INJ_StartConversion(ADCx); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd(TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter); R3_1_SwitchOffPWM(&pHandle->_Super); /* Offset calibration for C phase */ pHandle->PolarizationCounter = 0U; /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R3_1_HFCurrentsPolarizationC; /* We want to polarize Phase C, so we select SECTOR_1 */ pHandle->PolarizationSector=SECTOR_1; /* Required to force first polarization conversion on SECTOR_1*/ pHandle->_Super.Sector = SECTOR_1; R3_1_SwitchOnPWM(&pHandle->_Super); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd(TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter); R3_1_SwitchOffPWM(&pHandle->_Super); pHandle->PhaseAOffset /= NB_CONVERSIONS; pHandle->PhaseBOffset /= NB_CONVERSIONS; pHandle->PhaseCOffset /= NB_CONVERSIONS; if (0U == pHandle->_Super.SWerror) { pHandle->_Super.offsetCalibStatus = true; } else { /* nothing to do */ } /* Change back function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = GetPhaseCurrCbSave; pHandle->_Super.pFctSetADCSampPointSectX = SetSampPointSectXCbSave; /* It over write TIMx CCRy wrongly written by FOC during calibration so as to force 50% duty cycle on the three inverer legs */ /* Disable TIMx preload */ LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH1); LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH2); LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH3); LL_TIM_OC_SetCompareCH1 (TIMx, pHandle->Half_PWMPeriod); LL_TIM_OC_SetCompareCH2 (TIMx, pHandle->Half_PWMPeriod); LL_TIM_OC_SetCompareCH3 (TIMx, pHandle->Half_PWMPeriod); /* Enable TIMx preload */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH1); LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH2); LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH3); /* It re-enable drive of TIMx CHy and CHyN by TIMx CHyRef*/ LL_TIM_CC_EnableChannel(TIMx, TIMxCCER_MASK_CH123); } /* At the end of calibration, all phases are at 50% we will sample A&B */ pHandle->_Super.Sector = SECTOR_5; pHandle->_Super.BrakeActionLock = false; } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /* * @brief Computes and stores in the handler the latest converted motor phase currents in ab_t format. * */ __weak void R3_1_GetPhaseCurrents(PWMC_Handle_t *pHdl, ab_t *Iab) { if (MC_NULL == Iab) { /* nothing to do */ } else { int32_t Aux; uint32_t ADCDataReg1; uint32_t ADCDataReg2; #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; uint8_t Sector; Sector = (uint8_t)pHandle->_Super.Sector; ADCDataReg1 = ADCx->JDR1; ADCDataReg2 = ADCx->JDR2; /* disable ADC trigger source */ /* LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4) */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); switch (Sector) { case SECTOR_4: case SECTOR_5: { /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = (int32_t)(pHandle->PhaseAOffset) - (int32_t)(ADCDataReg1); /* Saturation of Ia */ if (Aux < -INT16_MAX) { Iab->a = -INT16_MAX; } else if (Aux > INT16_MAX) { Iab->a = INT16_MAX; } else { Iab->a = (int16_t)Aux; } /* Ib = PhaseBOffset - ADC converted value) */ Aux = (int32_t)(pHandle->PhaseBOffset) - (int32_t)(ADCDataReg2); /* Saturation of Ib */ if (Aux < -INT16_MAX) { Iab->b = -INT16_MAX; } else if (Aux > INT16_MAX) { Iab->b = INT16_MAX; } else { Iab->b = (int16_t)Aux; } break; } case SECTOR_6: case SECTOR_1: { /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ Aux = (int32_t)(pHandle->PhaseBOffset) - (int32_t)(ADCDataReg1); /* Saturation of Ib */ if (Aux < -INT16_MAX) { Iab->b = -INT16_MAX; } else if (Aux > INT16_MAX) { Iab->b = INT16_MAX; } else { Iab->b = (int16_t)Aux; } /* Ia = -Ic -Ib */ Aux = (int32_t)(ADCDataReg2) - (int32_t)(pHandle->PhaseCOffset); /* -Ic */ Aux -= (int32_t)Iab->b; /* Ia */ /* Saturation of Ia */ if (Aux > INT16_MAX) { Iab->a = INT16_MAX; } else if (Aux < -INT16_MAX) { Iab->a = -INT16_MAX; } else { Iab->a = (int16_t)Aux; } break; } case SECTOR_2: case SECTOR_3: { /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = (int32_t)(pHandle->PhaseAOffset) - (int32_t)(ADCDataReg1); /* Saturation of Ia */ if (Aux < -INT16_MAX) { Iab->a = -INT16_MAX; } else if (Aux > INT16_MAX) { Iab->a = INT16_MAX; } else { Iab->a = (int16_t)Aux; } /* Ib = -Ic -Ia */ Aux = (int32_t)(ADCDataReg2) - (int32_t)(pHandle->PhaseCOffset); /* -Ic */ Aux -= (int32_t)Iab->a; /* Ib */ /* Saturation of Ib */ if (Aux > INT16_MAX) { Iab->b = INT16_MAX; } else if (Aux < -INT16_MAX) { Iab->b = -INT16_MAX; } else { Iab->b = (int16_t)Aux; } break; } default: break; } pHandle->_Super.Ia = Iab->a; pHandle->_Super.Ib = Iab->b; pHandle->_Super.Ic = -Iab->a - Iab->b; } } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /* * @brief Computes and stores in the handler the latest converted motor phase currents in ab_t format. Specific to overmodulation. * */ __weak void R3_1_GetPhaseCurrents_OVM(PWMC_Handle_t *pHdl, ab_t *Iab) { if (MC_NULL == Iab) { /* Nothing to do */ } else { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; int32_t Aux; uint32_t ADCDataReg1; uint32_t ADCDataReg2; uint8_t Sector; /* disable ADC trigger source */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); Sector = (uint8_t)pHandle->_Super.Sector; ADCDataReg1 = ADCx->JDR1; ADCDataReg2 = ADCx->JDR2; switch (Sector) { case SECTOR_4: { /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ((int32_t)pHandle->PhaseAOffset) - ((int32_t)ADCDataReg1); /* Saturation of Ia */ if (Aux < -INT16_MAX) { Iab->a = -INT16_MAX; } else if (Aux > INT16_MAX) { Iab->a = INT16_MAX; } else { Iab->a = (int16_t)Aux; } if (true == pHandle->_Super.useEstCurrent) { // Ib not available, use estimated Ib Aux = (int32_t)(pHandle->_Super.IbEst); } else { /* Ib = PhaseBOffset - ADC converted value) */ Aux = ((int32_t)pHandle->PhaseBOffset) - ((int32_t)ADCDataReg2); } /* Saturation of Ib */ if (Aux < -INT16_MAX) { Iab->b = -INT16_MAX; } else if (Aux > INT16_MAX) { Iab->b = INT16_MAX; } else { Iab->b = (int16_t)Aux; } break; } case SECTOR_5: { /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ if (true == pHandle->_Super.useEstCurrent) { // Ia not available, use estimated Ia Aux = (int32_t)(pHandle->_Super.IaEst); } else { Aux = ((int32_t)pHandle->PhaseAOffset) - ((int32_t)ADCDataReg1); } /* Saturation of Ia */ if (Aux < -INT16_MAX) { Iab->a = -INT16_MAX; } else if (Aux > INT16_MAX) { Iab->a = INT16_MAX; } else { Iab->a = (int16_t)Aux; } /* Ib = PhaseBOffset - ADC converted value) */ Aux = ((int32_t)pHandle->PhaseBOffset) - ((int32_t)ADCDataReg2); /* Saturation of Ib */ if (Aux < -INT16_MAX) { Iab->b = -INT16_MAX; } else if (Aux > INT16_MAX) { Iab->b = INT16_MAX; } else { Iab->b = (int16_t)Aux; } break; } case SECTOR_6: { /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ Aux = ((int32_t)pHandle->PhaseBOffset) - ((int32_t)ADCDataReg1); /* Saturation of Ib */ if (Aux < -INT16_MAX) { Iab->b = -INT16_MAX; } else if (Aux > INT16_MAX) { Iab->b = INT16_MAX; } else { Iab->b = (int16_t)Aux; } if (pHandle->_Super.useEstCurrent == true) { Aux = (int32_t) pHandle->_Super.IcEst ; /* -Ic */ Aux -= (int32_t)Iab->b; } else { /* Ia = -Ic -Ib */ Aux = (int32_t)(ADCDataReg2) - (int32_t)(pHandle->PhaseCOffset); /* -Ic */ Aux -= (int32_t)Iab->b; /* Ia */ } /* Saturation of Ia */ if (Aux > INT16_MAX) { Iab->a = INT16_MAX; } else if (Aux < -INT16_MAX) { Iab->a = -INT16_MAX; } else { Iab->a = (int16_t)Aux; } break; } case SECTOR_1: { /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ if (true == pHandle->_Super.useEstCurrent) { Aux = (int32_t) pHandle->_Super.IbEst; } else { Aux = ((int32_t)pHandle->PhaseBOffset) - (int32_t)(ADCDataReg1); } /* Saturation of Ib */ if (Aux < -INT16_MAX) { Iab->b = -INT16_MAX; } else if (Aux > INT16_MAX) { Iab->b = INT16_MAX; } else { Iab->b = (int16_t)Aux; } /* Ia = -Ic -Ib */ Aux = ((int32_t)ADCDataReg2) - ((int32_t)pHandle->PhaseCOffset); /* -Ic */ Aux -= (int32_t)Iab->b; /* Ia */ /* Saturation of Ia */ if (Aux > INT16_MAX) { Iab->a = INT16_MAX; } else if (Aux < -INT16_MAX) { Iab->a = -INT16_MAX; } else { Iab->a = (int16_t)Aux; } break; } case SECTOR_2: { /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ if (true == pHandle->_Super.useEstCurrent) { Aux = (int32_t)pHandle->_Super.IaEst; } else { Aux = ((int32_t)pHandle->PhaseAOffset) - ((int32_t)ADCDataReg1); } /* Saturation of Ia */ if (Aux < -INT16_MAX) { Iab->a = -INT16_MAX; } else if (Aux > INT16_MAX) { Iab->a = INT16_MAX; } else { Iab->a = (int16_t)Aux; } /* Ib = -Ic -Ia */ Aux = ((int32_t)ADCDataReg2) - ((int32_t)pHandle->PhaseCOffset); /* -Ic */ Aux -= (int32_t)Iab->a; /* Ib */ /* Saturation of Ib */ if (Aux > INT16_MAX) { Iab->b = INT16_MAX; } else if (Aux < -INT16_MAX) { Iab->b = -INT16_MAX; } else { Iab->b = (int16_t)Aux; } break; } case SECTOR_3: { /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ((int32_t)pHandle->PhaseAOffset) - ((int32_t)ADCDataReg1); /* Saturation of Ia */ if (Aux < -INT16_MAX) { Iab->a = -INT16_MAX; } else if (Aux > INT16_MAX) { Iab->a = INT16_MAX; } else { Iab->a = (int16_t)Aux; } if (pHandle->_Super.useEstCurrent == true) { /* Ib = -Ic -Ia */ Aux = (int32_t)pHandle->_Super.IcEst; /* -Ic */ Aux -= (int32_t)Iab->a; /* Ib */ } else { /* Ib = -Ic -Ia */ Aux = ((int32_t)ADCDataReg2) - ((int32_t)pHandle->PhaseCOffset); /* -Ic */ Aux -= (int32_t)Iab->a; /* Ib */ } /* Saturation of Ib */ if (Aux > INT16_MAX) { Iab->b = INT16_MAX; } else if (Aux < -INT16_MAX) { Iab->b = -INT16_MAX; } else { Iab->b = (int16_t)Aux; } break; } default: break; } pHandle->_Super.Ia = Iab->a; pHandle->_Super.Ib = Iab->b; pHandle->_Super.Ic = -Iab->a - Iab->b; } } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /* * @brief Configures the ADC for the current sampling during calibration. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. Called R3_1_SetADCSampPointCalibration in every other MCU. * * @param pHdl: Handler of the current instance of the PWM component. * @retval uint16_t Returns the return value of R3_1_WriteTIMRegisters. */ uint16_t R3_1_SetADCSampPointPolarization(PWMC_Handle_t *pHdl) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 pHandle->_Super.Sector = pHandle->PolarizationSector; return R3_1_WriteTIMRegisters(&pHandle->_Super, (pHandle->Half_PWMPeriod - (uint16_t)1)); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /* * @brief Configures the ADC for the current sampling related to sector X (X = [1..6] ). * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval uint16_t Returns the return value of R3_1_WriteTIMRegisters. */ uint16_t R3_1_SetADCSampPointSectX(PWMC_Handle_t *pHdl) { uint16_t returnValue; if (MC_NULL == pHdl) { returnValue = 0U; } else { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ uint16_t SamplingPoint; uint16_t DeltaDuty; /* Verify that sampling is possible in the middle of PWM by checking the smallest duty cycle */ if ((uint16_t)(pHandle->Half_PWMPeriod - pHdl->lowDuty) > pHandle->pParams_str->Tafter) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled which corresponds * to sector 4 or 5 */ pHandle->_Super.Sector = SECTOR_5; /* set sampling point trigger in the middle of PWM period */ SamplingPoint = pHandle->Half_PWMPeriod - (uint16_t)1; } else { /* In this case it is necessary to convert phases with Maximum and variable complementary duty cycle.*/ /* ADC Injected sequence configuration. The stator phase with minimum value of complementary duty cycle is set as first. In every sector there is always one phase with maximum complementary duty, one with minimum complementary duty and one with variable complementary duty. In this case, phases with variable complementary duty and with maximum duty are converted and the first will be always the phase with variable complementary duty cycle */ DeltaDuty = (uint16_t)(pHdl->lowDuty - pHdl->midDuty); /* Definition of crossing point */ if (DeltaDuty > ((uint16_t)(pHandle->Half_PWMPeriod - pHdl->lowDuty) * 2U)) { SamplingPoint = pHdl->lowDuty - pHandle->pParams_str->Tbefore; } else { SamplingPoint = pHdl->lowDuty + pHandle->pParams_str->Tafter; if (SamplingPoint >= pHandle->Half_PWMPeriod) { /* ADC trigger edge must be changed from positive to negative */ pHandle->ADC_ExternalPolarityInjected = (uint16_t)LL_ADC_INJ_TRIG_EXT_FALLING; SamplingPoint = (2U * pHandle->Half_PWMPeriod) - SamplingPoint - (uint16_t)1; } } } returnValue = R3_1_WriteTIMRegisters(&pHandle->_Super, SamplingPoint); } return (returnValue); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /* * @brief Configures the ADC for the current sampling related to sector X (X = [1..6] ) in case of overmodulation. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval uint16_t Returns the return value of R3_1_WriteTIMRegisters. */ uint16_t R3_1_SetADCSampPointSectX_OVM(PWMC_Handle_t *pHdl) { uint16_t retVal; if (MC_NULL == pHdl) { retVal = 0U; } else { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ uint16_t SamplingPoint; uint16_t DeltaDuty; pHandle->_Super.useEstCurrent = false; DeltaDuty = (uint16_t)(pHdl->lowDuty - pHdl->midDuty); /* case 1 (cf user manual) */ if ((uint16_t)(pHandle->Half_PWMPeriod - pHdl->lowDuty) > pHandle->pParams_str->Tafter) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled which corresponds * to sector 4 or 5 */ pHandle->_Super.Sector = SECTOR_5; /* set sampling point trigger in the middle of PWM period */ SamplingPoint = pHandle->Half_PWMPeriod - (uint16_t) 1; } else /* case 2 (cf user manual) */ { if (DeltaDuty >= pHandle->pParams_str->Tcase2) { SamplingPoint = pHdl->lowDuty - pHandle->pParams_str->Tbefore; } else { /* case 3 (cf user manual) */ if ((pHandle->Half_PWMPeriod - pHdl->lowDuty) > pHandle->pParams_str->Tcase3) { /* ADC trigger edge must be changed from positive to negative */ pHandle->ADC_ExternalPolarityInjected = (uint16_t) LL_ADC_INJ_TRIG_EXT_FALLING; SamplingPoint = pHdl->lowDuty + pHandle->pParams_str->Tsampling; } else { SamplingPoint = pHandle->Half_PWMPeriod - 1U; pHandle->_Super.useEstCurrent = true; } } } retVal = R3_1_WriteTIMRegisters(&pHandle->_Super, SamplingPoint); } return (retVal); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /* * @brief Writes into peripheral registers the new duty cycle and sampling point. * * @param pHdl: Handler of the current instance of the PWM component. * @param SamplingPoint: Point at which the ADC will be triggered, written in timer clock counts. * @retval uint16_t Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ __STATIC_INLINE uint16_t R3_1_WriteTIMRegisters(PWMC_Handle_t *pHdl, uint16_t SamplingPoint) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; uint16_t Aux; LL_TIM_OC_SetCompareCH1(TIMx, (uint32_t) pHandle->_Super.CntPhA); LL_TIM_OC_SetCompareCH2(TIMx, (uint32_t) pHandle->_Super.CntPhB); LL_TIM_OC_SetCompareCH3(TIMx, (uint32_t) pHandle->_Super.CntPhC); LL_TIM_OC_SetCompareCH4(TIMx, (uint32_t) SamplingPoint); /* Limit for update event */ // if ( LL_TIM_CC_IsEnabledChannel(TIMx, LL_TIM_CHANNEL_CH4) == 1u ) if (((TIMx->CR2) & TIM_CR2_MMS_Msk) != LL_TIM_TRGO_RESET) { Aux = MC_DURATION; } else { Aux = MC_NO_ERROR; } return Aux; } /* * @brief Implementation of PWMC_GetPhaseCurrents to be performed during polarization. * * It sums up injected conversion data into PhaseAOffset and * PhaseBOffset to compute the offset introduced in the current feedback * network. It is required to properly configure ADC inputs before in order to enable * the offset computation. Called R3_1_HFCurrentsCalibrationAB in every other MCU except for F30X. * * @param pHdl: Handler of the current instance of the PWM component. * @param Iab: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ static void R3_1_HFCurrentsPolarizationAB(PWMC_Handle_t *pHdl, ab_t *Iab) { if (MC_NULL == Iab) { /* Nothing to do */ } else { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; uint32_t ADCDataReg1 = ADCx->JDR1; uint32_t ADCDataReg2 = ADCx->JDR2; /* disable ADC trigger source */ /* LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4) */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); if (pHandle->PolarizationCounter < NB_CONVERSIONS) { pHandle-> PhaseAOffset += ADCDataReg1; pHandle-> PhaseBOffset += ADCDataReg2; pHandle->PolarizationCounter++; } else { /* Nothing to do */ } /* during offset calibration no current is flowing in the phases */ Iab->a = 0; Iab->b = 0; } } /* * @brief Implementation of PWMC_GetPhaseCurrents to be performed during polarization. * * It sums up injected conversion data into PhaseCOffset to compute the offset * introduced in the current feedback network. It is required to properly configure * ADC inputs before in order to enable offset computation. Called R3_1_HFCurrentsCalibrationC in every other MCU. * * @param pHdl: Handler of the current instance of the PWM component. * @param ticks: Timer ticks value to be applied * Min value: 0 (low sides ON) * Max value: PWM_PERIOD_CYCLES/2 (low sides OFF) */ static void R3_1_HFCurrentsPolarizationC(PWMC_Handle_t *pHdl, ab_t *Iab) { if (MC_NULL == Iab) { /* Nothing to do */ } else { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; uint32_t ADCDataReg2 = ADCx->JDR2; /* disable ADC trigger source */ /* LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4) */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); if (pHandle->PolarizationCounter < NB_CONVERSIONS) { /* Phase C is read from SECTOR_1, second value */ pHandle-> PhaseCOffset += ADCDataReg2; pHandle->PolarizationCounter++; } else { /* Nothing to do */ } /* during offset calibration no current is flowing in the phases */ Iab->a = 0; Iab->b = 0; } } /* * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors of driving section. It has to be * called on each motor start-up when using high voltage drivers. * * @param pHdl: Handler of the current instance of the PWM component. * @param ticks: Timer ticks value to be applied * Min value: 0 (low sides ON) * Max value: PWM_PERIOD_CYCLES/2 (low sides OFF) */ __weak void R3_1_TurnOnLowSides(PWMC_Handle_t *pHdl, uint32_t ticks) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = true; /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE(pHandle->pParams_str->TIMx); /*Turn on the three low side switches */ LL_TIM_OC_SetCompareCH1(TIMx, ticks); LL_TIM_OC_SetCompareCH2(TIMx, ticks); LL_TIM_OC_SetCompareCH3(TIMx, ticks); /* Wait until next update */ while (0U == LL_TIM_IsActiveFlag_UPDATE(TIMx)) { /* Nothing to do */ } /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs(TIMx); if ((ES_GPIO == pHandle->_Super.LowSideOutputs)) { LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } else { /* Nothing to do */ } return; } /* * @brief Enables PWM generation on the proper Timer peripheral. * * This function is specific for RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_1_SwitchOnPWM(PWMC_Handle_t *pHdl) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; /* We forbid ADC usage for regular conversion on Systick*/ pHandle->ADCRegularLocked = true; pHandle->_Super.TurnOnLowSidesAction = false; /* Set all duty to 50% */ LL_TIM_OC_SetCompareCH1(TIMx, ((uint32_t)pHandle->Half_PWMPeriod / (uint32_t)2)); LL_TIM_OC_SetCompareCH2(TIMx, ((uint32_t)pHandle->Half_PWMPeriod / (uint32_t)2)); LL_TIM_OC_SetCompareCH3(TIMx, ((uint32_t)pHandle->Half_PWMPeriod / (uint32_t)2)); LL_TIM_OC_SetCompareCH4(TIMx, ((uint32_t)pHandle->Half_PWMPeriod - (uint32_t)5)); /* wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE(TIMx); while (0U == LL_TIM_IsActiveFlag_UPDATE(TIMx)) { /* Nothing to do */ } LL_TIM_ClearFlag_UPDATE(TIMx); /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE; LL_TIM_EnableAllOutputs(TIMx); if ((ES_GPIO == pHandle->_Super.LowSideOutputs)) { if ((TIMx->CCER & TIMxCCER_MASK_CH123) != 0U) { LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } } else { /* Nothing to do */ } /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE(TIMx); /* Enable Update IRQ */ LL_TIM_EnableIT_UPDATE(TIMx); } /* * @brief Disables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_1_SwitchOffPWM(PWMC_Handle_t *pHdl) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; /* Disable UPDATE ISR */ LL_TIM_DisableIT_UPDATE(TIMx); pHandle->_Super.TurnOnLowSidesAction = false; /* Main PWM Output Disable */ LL_TIM_DisableAllOutputs(TIMx); if (true == pHandle->_Super.BrakeActionLock) { /* Nothing to do */ } else { if (ES_GPIO == pHandle->_Super.LowSideOutputs) { LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } else { /* Nothing to do */ } } /* wait for a new PWM period to flush last HF task */ LL_TIM_ClearFlag_UPDATE(TIMx); while (0U == LL_TIM_IsActiveFlag_UPDATE(TIMx)) { /* Nothing to do */ } LL_TIM_ClearFlag_UPDATE(TIMx); /* We allow ADC usage for regular conversion on Systick*/ pHandle->ADCRegularLocked = false; } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /* * @brief Contains the TIMx Update event interrupt. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void *R3_1_TIMx_UP_IRQHandler(PWMC_R3_1_Handle_t *pHandle) { void *tempPointer; if (MC_NULL == pHandle) { tempPointer = MC_NULL; } else { TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef *ADCx = pHandle->pParams_str->ADCx; R3_3_OPAMPParams_t *OPAMPParams = pHandle->pParams_str->OPAMPParams; OPAMP_TypeDef *operationAmp; uint32_t OpampConfig; if (OPAMPParams != NULL) { /* We can not change OPAMP source if ADC acquisition is ongoing (Dual motor with internal opamp use case)*/ while (ADCx->JSQR != 0x0u) { /* Nothing to do */ } /* We need to manage the Operational amplifier internal output enable - Dedicated to G4 and the VPSEL selection */ operationAmp = OPAMPParams->OPAMPSelect_1[pHandle->_Super.Sector]; if (operationAmp != NULL) { OpampConfig = OPAMPParams->OPAMPConfig1[pHandle->_Super.Sector]; MODIFY_REG(operationAmp->CSR, (OPAMP_CSR_OPAMPINTEN | OPAMP_CSR_VPSEL), OpampConfig); } else { /* Nothing to do */ } operationAmp = OPAMPParams->OPAMPSelect_2[pHandle->_Super.Sector]; if (operationAmp != NULL) { OpampConfig = OPAMPParams->OPAMPConfig2[pHandle->_Super.Sector]; MODIFY_REG(operationAmp->CSR, (OPAMP_CSR_OPAMPINTEN | OPAMP_CSR_VPSEL), OpampConfig); } else { /* Nothing to do */ } } ADCx->JSQR = pHandle->pParams_str->ADCConfig[pHandle->_Super.Sector] | (uint32_t) pHandle->ADC_ExternalPolarityInjected; /* enable ADC trigger source */ /* LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH4) */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_OC4REF); pHandle->ADC_ExternalPolarityInjected = (uint16_t)LL_ADC_INJ_TRIG_EXT_RISING; tempPointer = &(pHandle->_Super.Motor); } return (tempPointer); } /* * @brief Configures the analog output used for protection thresholds. * * @param DAC_Channel: the selected DAC channel. * This parameter can be: * @arg DAC_Channel_1: DAC Channel1 selected. * @arg DAC_Channel_2: DAC Channel2 selected. * @param DACx: DAC to be configured. * @param hDACVref: Value of DAC reference expressed as 16bit unsigned integer. * Ex. 0 = 0V 65536 = VDD_DAC. */ static void R3_1_SetAOReferenceVoltage(uint32_t DAC_Channel, DAC_TypeDef *DACx, uint16_t hDACVref) { LL_DAC_ConvertData12LeftAligned(DACx, DAC_Channel, hDACVref); /* Enable DAC Channel */ LL_DAC_TrigSWConversion(DACx, DAC_Channel); if (1U == LL_DAC_IsEnabled(DACx, DAC_Channel)) { /* If DAC is already enable, we wait LL_DAC_DELAY_VOLTAGE_SETTLING_US*/ volatile uint32_t wait_loop_index = ((LL_DAC_DELAY_VOLTAGE_SETTLING_US) * (SystemCoreClock / (1000000UL * 2UL))); while (wait_loop_index != 0UL) { wait_loop_index--; } } else { /* If DAC is not enabled, we must wait LL_DAC_DELAY_STARTUP_VOLTAGE_SETTLING_US*/ LL_DAC_Enable(DACx, DAC_Channel); volatile uint32_t wait_loop_index = ((LL_DAC_DELAY_STARTUP_VOLTAGE_SETTLING_US) * (SystemCoreClock / (1000000UL * 2UL))); while (wait_loop_index != 0UL) { wait_loop_index--; } } } /* * @brief Sets the PWM mode for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_1_RLDetectionModeEnable(PWMC_Handle_t *pHdl) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; if (false == pHandle->_Super.RLDetectionMode) { /* Channel1 configuration */ LL_TIM_OC_SetMode(TIMx, LL_TIM_CHANNEL_CH1, LL_TIM_OCMODE_PWM1); LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH1); LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH1N); LL_TIM_OC_SetCompareCH1(TIMx, 0U); /* Channel2 configuration */ if (LS_PWM_TIMER == pHandle->_Super.LowSideOutputs) { LL_TIM_OC_SetMode(TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_ACTIVE); LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH2); LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH2N); } else if (ES_GPIO == pHandle->_Super.LowSideOutputs) { LL_TIM_OC_SetMode(TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_INACTIVE); LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH2); LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH2N); } else { /* Nothing to do */ } /* Channel3 configuration */ LL_TIM_OC_SetMode(TIMx, LL_TIM_CHANNEL_CH3, LL_TIM_OCMODE_PWM2); LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH3); LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH3N); pHandle->PhaseAOffset = pHandle->PhaseBOffset; /* Use only the offset of phB */ } else { /* Nothing to do */ } pHandle->_Super.pFctGetPhaseCurrents = &R3_1_RLGetPhaseCurrents; pHandle->_Super.pFctTurnOnLowSides = &R3_1_RLTurnOnLowSides; pHandle->_Super.pFctSwitchOnPwm = &R3_1_RLSwitchOnPWM; pHandle->_Super.pFctSwitchOffPwm = &R3_1_SwitchOffPWM; pHandle->_Super.RLDetectionMode = true; } /* * @brief Disables the PWM mode for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_1_RLDetectionModeDisable(PWMC_Handle_t *pHdl) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; if (true == pHandle->_Super.RLDetectionMode) { /* Channel1 configuration */ LL_TIM_OC_SetMode(TIMx, LL_TIM_CHANNEL_CH1, LL_TIM_OCMODE_PWM1); LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH1); if (LS_PWM_TIMER == pHandle->_Super.LowSideOutputs) { LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH1N); } else if (ES_GPIO == pHandle->_Super.LowSideOutputs) { LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH1N); } else { /* Nothing to do */ } LL_TIM_OC_SetCompareCH1(TIMx, ((uint32_t)pHandle->Half_PWMPeriod) >> 1); /* Channel2 configuration */ LL_TIM_OC_SetMode(TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_PWM1); LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH2); if (LS_PWM_TIMER == pHandle->_Super.LowSideOutputs) { LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH2N); } else if (ES_GPIO == pHandle->_Super.LowSideOutputs) { LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH2N); } else { /* Nothing to do */ } LL_TIM_OC_SetCompareCH2(TIMx, ((uint32_t)pHandle->Half_PWMPeriod) >> 1); /* Channel3 configuration */ LL_TIM_OC_SetMode(TIMx, LL_TIM_CHANNEL_CH3, LL_TIM_OCMODE_PWM1); LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH3); if (LS_PWM_TIMER == pHandle->_Super.LowSideOutputs) { LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH3N); } else if (ES_GPIO == pHandle->_Super.LowSideOutputs) { LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH3N); } else { /* Nothing to do */ } LL_TIM_OC_SetCompareCH3(TIMx, ((uint32_t)pHandle->Half_PWMPeriod) >> 1); pHandle->_Super.pFctGetPhaseCurrents = &R3_1_GetPhaseCurrents; pHandle->_Super.pFctTurnOnLowSides = &R3_1_TurnOnLowSides; pHandle->_Super.pFctSwitchOnPwm = &R3_1_SwitchOnPWM; pHandle->_Super.pFctSwitchOffPwm = &R3_1_SwitchOffPWM; pHandle->_Super.RLDetectionMode = false; } else { /* Nothing to do */ } } /* * @brief Sets the PWM dutycycle for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. * @param hDuty: Duty cycle to apply, written in uint16_t. * @retval Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ uint16_t R3_1_RLDetectionModeSetDuty(PWMC_Handle_t *pHdl, uint16_t hDuty) { uint16_t tempValue; #ifdef NULL_PTR_CHECK_R3_1_PWM_CURR_FDB if (MC_NULL == pHdl) { tempValue = 0U; } else { #endif PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; uint32_t val; uint16_t hAux; pHandle->ADCRegularLocked = true; val = (((uint32_t)pHandle->Half_PWMPeriod) * ((uint32_t)hDuty)) >> 16; pHandle->_Super.CntPhA = (uint16_t)val; /* Set CC4 as PWM mode 2 (default) */ LL_TIM_OC_SetMode(TIMx, LL_TIM_CHANNEL_CH4, LL_TIM_OCMODE_PWM2); LL_TIM_OC_SetCompareCH4(TIMx, (((uint32_t)pHandle->Half_PWMPeriod) - ((uint32_t)pHandle->_Super.Ton))); LL_TIM_OC_SetCompareCH3(TIMx, (uint32_t)pHandle->_Super.Toff); LL_TIM_OC_SetCompareCH1(TIMx, (uint32_t)pHandle->_Super.CntPhA); /* Enabling next Trigger */ /* LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH4) */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_OC4REF); /* Set the sector that correspond to Phase A and B sampling */ pHdl->Sector = SECTOR_4; /* Limit for update event */ /* Check the status flag. If an update event has occurred before to set new values of regs the FOC rate is too high */ if (((TIMx->CR2) & TIM_CR2_MMS_Msk) != LL_TIM_TRGO_RESET) { hAux = MC_DURATION; } else { hAux = MC_NO_ERROR; } if (1U == pHandle->_Super.SWerror) { hAux = MC_DURATION; pHandle->_Super.SWerror = 0U; } else { /* Nothing to do */ } tempValue = hAux; #ifdef NULL_PTR_CHECK_R3_1_PWM_CURR_FDB } #endif return (tempValue); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /* * @brief Computes and stores into @p pHandle latest converted motor phase currents * during RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ static void R3_1_RLGetPhaseCurrents(PWMC_Handle_t *pHdl, ab_t *pStator_Currents) { #ifdef NULL_PTR_CHECK_R3_1_PWM_CURR_FDB if (MC_NULL == pStator_Currents) { /* Nothing to do */ } else { #endif PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef *ADCx = pHandle->pParams_str->ADCx; int32_t wAux; /* Disable ADC trigger source */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); wAux = ((int32_t)pHandle->PhaseBOffset) - (int32_t)ADCx->JDR2; /* Check saturation */ if (wAux > -INT16_MAX) { if (wAux < INT16_MAX) { /* Nothing to do */ } else { wAux = INT16_MAX; } } else { wAux = -INT16_MAX; } pStator_Currents->a = (int16_t)wAux; pStator_Currents->b = (int16_t)wAux; #ifdef NULL_PTR_CHECK_R3_1_PWM_CURR_FDB } #endif } /* * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors * of driving section. It has to be called at each motor start-up when * using high voltage drivers. * This function is specific for RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. * @param ticks: Duty cycle of the boot capacitors charge, specific to motor. */ static void R3_1_RLTurnOnLowSides(PWMC_Handle_t *pHdl, uint32_t ticks) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; pHandle->ADCRegularLocked = true; /* Turn on the phase A low side switch */ LL_TIM_OC_SetCompareCH1(TIMx, 0u); /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE(TIMx); /* Wait until next update */ while (0U == LL_TIM_IsActiveFlag_UPDATE(TIMx)) { /* Nothing to do */ } /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs(TIMx); if (ES_GPIO == pHandle->_Super.LowSideOutputs) { LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } else { /* Nothing to do */ } } /* * @brief Enables PWM generation on the proper Timer peripheral. * * This function is specific for RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. */ static void R3_1_RLSwitchOnPWM( PWMC_Handle_t *pHdl) { #ifdef NULL_PTR_CHECK_R3_1_PWM_CURR_FDB if (MC_NULL == pHdl) { /* Nothing to do */ } else { #endif PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef *ADCx = pHandle->pParams_str->ADCx; pHandle->ADCRegularLocked=true; /* Wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE(TIMx); while (0U == LL_TIM_IsActiveFlag_UPDATE(TIMx)) { /* Nothing to do */ } /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE(TIMx); LL_TIM_OC_SetCompareCH1(TIMx, 1U); LL_TIM_OC_SetCompareCH4(TIMx, ((uint32_t )pHandle->Half_PWMPeriod) - 5U); while (0U == LL_TIM_IsActiveFlag_UPDATE(TIMx)) { /* Nothing to do */ } /* Enable TIMx update interrupt */ LL_TIM_EnableIT_UPDATE(TIMx); /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE ; LL_TIM_EnableAllOutputs(TIMx); if (ES_GPIO == pHandle->_Super.LowSideOutputs) { if ((TIMx->CCER & TIMxCCER_MASK_CH123 ) != 0U) { LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } } else { /* Nothing to do */ } /* Set the sector that correspond to Phase B and C sampling * B will be sampled by ADCx */ pHdl->Sector = SECTOR_4; LL_ADC_INJ_StartConversion(ADCx); #ifdef NULL_PTR_CHECK_R3_1_PWM_CURR_FDB } #endif } /* * @brief Turns on low sides switches and start ADC triggering. * * This function is specific for MP phase. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_1_RLTurnOnLowSidesAndStart(PWMC_Handle_t *pHdl) { #ifdef NULL_PTR_CHECK_R3_1_PWM_CURR_FDB if (MC_NULL == pHdl) { /* Nothing to do */ } else { #endif PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; pHandle->ADCRegularLocked=true; LL_TIM_ClearFlag_UPDATE(TIMx); while (0U == LL_TIM_IsActiveFlag_UPDATE(TIMx)) { /* Nothing to do */ } /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE(TIMx); LL_TIM_OC_SetCompareCH1(TIMx, 0x0U); LL_TIM_OC_SetCompareCH2(TIMx, 0x0U); LL_TIM_OC_SetCompareCH3(TIMx, 0x0U); LL_TIM_OC_SetCompareCH4(TIMx, ((uint32_t )pHandle->Half_PWMPeriod) - 5U); while (0U == LL_TIM_IsActiveFlag_UPDATE(TIMx)) { /* Nothing to do */ } /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE ; LL_TIM_EnableAllOutputs (TIMx); if (ES_GPIO == pHandle->_Super.LowSideOutputs ) { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } else { /* Nothing to do */ } pHdl->Sector = SECTOR_4; LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH4); LL_TIM_EnableIT_UPDATE(TIMx); #ifdef NULL_PTR_CHECK_R3_1_PWM_CURR_FDB } #endif } /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
64,729
C
29.418233
132
0.600921
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/G4xx/Src/ics_g4xx_pwm_curr_fdbk.c
/** ****************************************************************************** * @file ics_g4xx_pwm_curr_fdbk.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement current sensor * class to be stantiated when the three shunts current sensing * topology is used. * * It is specifically designed for STM32G4X microcontrollers and * implements the successive sampling of motor current using two ADCs. * + MCU peripheral and handle initialization function * + three shunt current sensing * + space vector modulation function * + ADC sampling function * ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup ICS_G4XX_pwm_curr_fdbk */ /* Includes ------------------------------------------------------------------*/ #include "ics_g4xx_pwm_curr_fdbk.h" #include "pwm_common.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup ICS_pwm_curr_fdbk * @{ */ /* Private defines -----------------------------------------------------------*/ #define TIMxCCER_MASK_CH123 ((uint16_t)(LL_TIM_CHANNEL_CH1|LL_TIM_CHANNEL_CH1N|\ LL_TIM_CHANNEL_CH2|LL_TIM_CHANNEL_CH2N|\ LL_TIM_CHANNEL_CH3|LL_TIM_CHANNEL_CH3N)) /* Private typedef -----------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ static void ICS_TIMxInit(TIM_TypeDef *TIMx, PWMC_Handle_t *pHdl); static void ICS_ADCxInit(ADC_TypeDef *ADCx); static void ICS_HFCurrentsPolarization(PWMC_Handle_t *pHdl, ab_t *Iab); /* * @brief Initializes TIMx, ADC, GPIO and NVIC for current reading * in ICS configuration using STM32G4XX. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void ICS_Init(PWMC_ICS_Handle_t *pHandle) { TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef *ADCx_1 = pHandle->pParams_str->ADCx_1; ADC_TypeDef *ADCx_2 = pHandle->pParams_str->ADCx_2; /*Check that _Super is the first member of the structure PWMC_ICS_Handle_t */ if ((uint32_t)pHandle == (uint32_t)&pHandle->_Super) { /* disable IT and flags in case of LL driver usage * workaround for unwanted interrupt enabling done by LL driver */ LL_ADC_DisableIT_EOC(ADCx_1); LL_ADC_ClearFlag_EOC(ADCx_1); LL_ADC_DisableIT_JEOC(ADCx_1); LL_ADC_ClearFlag_JEOC(ADCx_1); LL_ADC_DisableIT_EOC(ADCx_2); LL_ADC_ClearFlag_EOC(ADCx_2); LL_ADC_DisableIT_JEOC(ADCx_2); LL_ADC_ClearFlag_JEOC(ADCx_2); if (TIMx == TIM1) { /* TIM1 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph(LL_DBGMCU_APB2_GRP1_TIM1_STOP); } else { /* TIM8 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph(LL_DBGMCU_APB2_GRP1_TIM8_STOP); } if (0U == LL_ADC_IsEnabled(ADCx_1)) { ICS_ADCxInit(ADCx_1); /* Only the Interrupt of the first ADC is enabled. * As Both ADCs are fired by HW at the same moment * It is safe to consider that both conversion are ready at the same time*/ LL_ADC_ClearFlag_JEOS(ADCx_1); LL_ADC_EnableIT_JEOS(ADCx_1); } else { /* Nothing to do ADCx_1 already configured */ } if (0U == LL_ADC_IsEnabled(ADCx_2)) { ICS_ADCxInit(ADCx_2); } else { /* Nothing to do ADCx_2 already configured */ } ICS_TIMxInit(TIMx, &pHandle->_Super); } } /** * @brief Initializes @p ADCx peripheral for current sensing. * * Specific to G4XX. * */ static void ICS_ADCxInit(ADC_TypeDef *ADCx) { /* - Exit from deep-power-down mode */ LL_ADC_DisableDeepPowerDown(ADCx); if (LL_ADC_IsInternalRegulatorEnabled(ADCx) == 0u) { /* Enable ADC internal voltage regulator */ LL_ADC_EnableInternalRegulator(ADCx); /* Wait for Regulator Startup time, once for both */ /* Note: Variable divided by 2 to compensate partially */ /* CPU processing cycles, scaling in us split to not */ /* exceed 32 bits register capacity and handle low frequency. */ volatile uint32_t wait_loop_index = ((LL_ADC_DELAY_INTERNAL_REGUL_STAB_US / 10UL) * (SystemCoreClock / (100000UL * 2UL))); while (wait_loop_index != 0UL) { wait_loop_index--; } } else { /* Nothing to do */ } LL_ADC_StartCalibration(ADCx, LL_ADC_SINGLE_ENDED); while (LL_ADC_IsCalibrationOnGoing(ADCx) == 1u) {} /* ADC Enable (must be done after calibration) */ /* ADC5-140924: Enabling the ADC by setting ADEN bit soon after polling ADCAL=0 * following a calibration phase, could have no effect on ADC * within certain AHB/ADC clock ratio. */ while (LL_ADC_IsActiveFlag_ADRDY(ADCx) == 0u) { LL_ADC_Enable(ADCx); } /* Clear JSQR from CubeMX setting to avoid not wanting conversion*/ LL_ADC_INJ_StartConversion(ADCx); LL_ADC_INJ_StopConversion(ADCx); /* TODO: check if not already done by MX */ LL_ADC_INJ_SetQueueMode(ADCx, LL_ADC_INJ_QUEUE_2CONTEXTS_END_EMPTY); /* Dummy conversion (ES0431 doc chap. 2.5.8 ADC channel 0 converted instead of the required ADC channel) Note: Sequence length forced to zero in order to prevent ADC OverRun occurrence */ LL_ADC_REG_SetSequencerLength(ADCx, 0U); LL_ADC_REG_StartConversion(ADCx); } /** * @brief Initializes @p TIMx peripheral with @p pHdl handler for PWM generation. * * Specific to G4XX. * */ static void ICS_TIMxInit(TIM_TypeDef *TIMx, PWMC_Handle_t *pHdl) { PWMC_ICS_Handle_t *pHandle = (PWMC_ICS_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 uint32_t Brk2Timeout = 1000; /* disable main TIM counter to ensure * a synchronous start by TIM2 trigger */ LL_TIM_DisableCounter(TIMx); LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); /* Enables the TIMx Preload on CC1 Register */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH1); /* Enables the TIMx Preload on CC2 Register */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH2); /* Enables the TIMx Preload on CC3 Register */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH3); /* Enables the TIMx Preload on CC4 Register */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH4); /* Prepare timer for synchronization */ LL_TIM_GenerateEvent_UPDATE(TIMx); if (pHandle->pParams_str->FreqRatio == 2u) { if (pHandle->pParams_str->IsHigherFreqTim == HIGHER_FREQ) { if (pHandle->pParams_str->RepetitionCounter == 3u) { /* Set TIMx repetition counter to 1 */ LL_TIM_SetRepetitionCounter(TIMx, 1); LL_TIM_GenerateEvent_UPDATE(TIMx); /* Repetition counter will be set to 3 at next Update */ LL_TIM_SetRepetitionCounter(TIMx, 3); } else { /* Nothing to do */ } } else { /* Nothing to do */ } LL_TIM_SetCounter(TIMx, (uint32_t)(pHandle->Half_PWMPeriod) - 1u); } else /* bFreqRatio equal to 1 or 3 */ { if (pHandle->_Super.Motor == M1) { if (pHandle->pParams_str->RepetitionCounter == 1u) { LL_TIM_SetCounter(TIMx, (uint32_t)(pHandle->Half_PWMPeriod) - 1u); } else if (pHandle->pParams_str->RepetitionCounter == 3u) { /* Set TIMx repetition counter to 1 */ LL_TIM_SetRepetitionCounter(TIMx, 1); LL_TIM_GenerateEvent_UPDATE(TIMx); /* Repetition counter will be set to 3 at next Update */ LL_TIM_SetRepetitionCounter(TIMx, 3); } else { /* Nothing to do */ } } else { /* Nothing to do */ } } LL_TIM_ClearFlag_BRK(TIMx); while ((LL_TIM_IsActiveFlag_BRK2(TIMx) == 1u) && (Brk2Timeout != 0u)) { LL_TIM_ClearFlag_BRK2(TIMx); Brk2Timeout--; } LL_TIM_EnableIT_BRK(TIMx); /* Enable PWM channel */ LL_TIM_CC_EnableChannel(TIMx, TIMxCCER_MASK_CH123); } /* * @brief Stores in @p pHdl handler the calibrated @p offsets. * */ __weak void ICS_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_ICS_Handle_t *pHandle = (PWMC_ICS_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 pHandle->PhaseAOffset = offsets->phaseAOffset; pHandle->PhaseBOffset = offsets->phaseBOffset; pHdl->offsetCalibStatus = true; } /* * @brief Reads the calibrated @p offsets stored in @p pHdl. * */ __weak void ICS_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_ICS_Handle_t *pHandle = (PWMC_ICS_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 offsets->phaseAOffset = pHandle->PhaseAOffset; offsets->phaseBOffset = pHandle->PhaseBOffset; } /* * @brief Stores into the @p pHdl handler the voltage present on Ia and * Ib current feedback analog channels when no current is flowing into the * motor. * */ __weak void ICS_CurrentReadingPolarization(PWMC_Handle_t *pHdl) { PWMC_ICS_Handle_t *pHandle = (PWMC_ICS_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef *ADCx_1 = pHandle->pParams_str->ADCx_1; ADC_TypeDef *ADCx_2 = pHandle->pParams_str->ADCx_2; if (true == pHandle->_Super.offsetCalibStatus) { LL_ADC_INJ_StartConversion(ADCx_1); LL_ADC_INJ_StartConversion(ADCx_2); } else { /* reset offset and counter */ pHandle->PhaseAOffset = 0u; pHandle->PhaseBOffset = 0u; pHandle->PolarizationCounter = 0u; /* It forces inactive level on TIMx CHy and CHyN */ LL_TIM_CC_DisableChannel(TIMx, TIMxCCER_MASK_CH123); /* Offset calibration for all phases */ /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &ICS_HFCurrentsPolarization; ICS_SwitchOnPWM(&pHandle->_Super); /* IF CH4 is enabled, it means that JSQR is now configured to sample polarization current*/ while (((TIMx->CR2) & TIM_CR2_MMS_Msk) != LL_TIM_TRGO_OC4REF) { } /* It is the right time to start the ADC without unwanted conversion */ /* Start ADC to wait for external trigger. This is series dependent*/ LL_ADC_INJ_StartConversion( ADCx_1 ); LL_ADC_INJ_StartConversion( ADCx_2 ); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd(TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter); ICS_SwitchOffPWM( &pHandle->_Super ); pHandle->PhaseAOffset /= NB_CONVERSIONS; pHandle->PhaseBOffset /= NB_CONVERSIONS; if (0U == pHandle->_Super.SWerror) { pHandle->_Super.offsetCalibStatus = true; } else { /* nothing to do */ } /* Change back function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &ICS_GetPhaseCurrents; pHandle->_Super.pFctSetADCSampPointSectX = &ICS_WriteTIMRegisters; } /* It over write TIMx CCRy wrongly written by FOC during calibration so as to force 50% duty cycle on the three inverer legs */ /* Disable TIMx preload */ LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH1); LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH2); LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH3); LL_TIM_OC_SetCompareCH1(TIMx, pHandle->Half_PWMPeriod); LL_TIM_OC_SetCompareCH2(TIMx, pHandle->Half_PWMPeriod); LL_TIM_OC_SetCompareCH3(TIMx, pHandle->Half_PWMPeriod); /* Enable TIMx preload */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH1); LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH2); LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH3); /* It re-enable drive of TIMx CHy and CHyN by TIMx CHyRef*/ LL_TIM_CC_EnableChannel(TIMx, TIMxCCER_MASK_CH123); pHandle->_Super.BrakeActionLock = false; } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /* * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p Iab ab_t format. * */ __weak void ICS_GetPhaseCurrents(PWMC_Handle_t *pHdl, ab_t *Iab) { PWMC_ICS_Handle_t *pHandle = (PWMC_ICS_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef *ADCx_1 = pHandle->pParams_str->ADCx_1; ADC_TypeDef *ADCx_2 = pHandle->pParams_str->ADCx_2; int32_t aux; uint16_t reg; /* disable ADC trigger source */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); /* Ia = (hPhaseAOffset)-(PHASE_A_ADC_CHANNEL value) */ reg = (uint16_t)(ADCx_1->JDR1); aux = (int32_t)(reg) - (int32_t)(pHandle->PhaseAOffset); /* Saturation of Ia */ if (aux < -INT16_MAX) { Iab->a = -INT16_MAX; } else if (aux > INT16_MAX) { Iab->a = INT16_MAX; } else { Iab->a = (int16_t)aux; } /* Ib = (hPhaseBOffset)-(PHASE_B_ADC_CHANNEL value) */ reg = (uint16_t)(ADCx_2->JDR1); aux = (int32_t)(reg) - (int32_t)(pHandle->PhaseBOffset); /* Saturation of Ib */ if (aux < -INT16_MAX) { Iab->b = -INT16_MAX; } else if (aux > INT16_MAX) { Iab->b = INT16_MAX; } else { Iab->b = (int16_t)aux; } pHandle->_Super.Ia = Iab->a; pHandle->_Super.Ib = Iab->b; pHandle->_Super.Ic = -Iab->a - Iab->b; } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /* * @brief Writes into peripheral registers the new duty cycle and sampling point. * * @param pHdl: Handler of the current instance of the PWM component. * @param SamplingPoint: Point at which the ADC will be triggered, written in timer clock counts. * @retval Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ __weak uint16_t ICS_WriteTIMRegisters(PWMC_Handle_t *pHdl) { PWMC_ICS_Handle_t *pHandle = (PWMC_ICS_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; uint16_t Aux; LL_TIM_OC_SetCompareCH1(TIMx, (uint32_t) pHandle->_Super.CntPhA); LL_TIM_OC_SetCompareCH2(TIMx, (uint32_t) pHandle->_Super.CntPhB); LL_TIM_OC_SetCompareCH3(TIMx, (uint32_t) pHandle->_Super.CntPhC); /* Limit for update event */ if (((TIMx->CR2) & TIM_CR2_MMS_Msk) != LL_TIM_TRGO_RESET) { Aux = MC_DURATION; } else { Aux = MC_NO_ERROR; } return (Aux); } /* * @brief Implementation of PWMC_GetPhaseCurrents to be performed during polarization. * * It sums up injected conversion data into PhaseAOffset and * PhaseBOffset to compute the offset introduced in the current feedback * network. It is required to properly configure ADC inputs before in order to enable * the offset computation. * * @param pHdl: Handler of the current instance of the PWM component. * @param Iab: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ static void ICS_HFCurrentsPolarization(PWMC_Handle_t *pHdl, ab_t *Iab) { PWMC_ICS_Handle_t *pHandle = (PWMC_ICS_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef *ADCx_1 = pHandle->pParams_str->ADCx_1; ADC_TypeDef *ADCx_2 = pHandle->pParams_str->ADCx_2; /* disable ADC trigger source */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); if (pHandle->PolarizationCounter < NB_CONVERSIONS) { pHandle-> PhaseAOffset += ADCx_1->JDR1; pHandle-> PhaseBOffset += ADCx_2->JDR1; pHandle->PolarizationCounter++; } else { /* Nothing to do */ } /* during offset calibration no current is flowing in the phases */ Iab->a = 0; Iab->b = 0; } /* * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors of driving section. It has to be * called on each motor start-up when using high voltage drivers. * * @param pHdl: Handler of the current instance of the PWM component. * @param ticks: Timer ticks value to be applied * Min value: 0 (low sides ON) * Max value: PWM_PERIOD_CYCLES/2 (low sides OFF) */ __weak void ICS_TurnOnLowSides(PWMC_Handle_t *pHdl, uint32_t ticks) { PWMC_ICS_Handle_t *pHandle = (PWMC_ICS_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = true; /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE(pHandle->pParams_str->TIMx); /*Turn on the three low side switches */ LL_TIM_OC_SetCompareCH1(TIMx, ticks); LL_TIM_OC_SetCompareCH2(TIMx, ticks); LL_TIM_OC_SetCompareCH3(TIMx, ticks); /* Wait until next update */ while (0U == LL_TIM_IsActiveFlag_UPDATE(TIMx)) { /* Nothing to do */ } /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs(TIMx); if ((pHandle->_Super.LowSideOutputs) == ES_GPIO) { LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } else { /* Nothing to do */ } } /* * @brief Enables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void ICS_SwitchOnPWM(PWMC_Handle_t *pHdl) { PWMC_ICS_Handle_t *pHandle = (PWMC_ICS_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; /* We forbid ADC usage for regular conversion on Systick cut 2.2 patch*/ pHandle->ADCRegularLocked = true; pHandle->_Super.TurnOnLowSidesAction = false; /* Set all duty to 50% */ LL_TIM_OC_SetCompareCH1(TIMx, ((uint32_t) pHandle->Half_PWMPeriod / (uint32_t) 2)); LL_TIM_OC_SetCompareCH2(TIMx, ((uint32_t) pHandle->Half_PWMPeriod / (uint32_t) 2)); LL_TIM_OC_SetCompareCH3(TIMx, ((uint32_t) pHandle->Half_PWMPeriod / (uint32_t) 2)); LL_TIM_OC_SetCompareCH4(TIMx, ((uint32_t) pHandle->Half_PWMPeriod - (uint32_t) 5)); /* wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE(TIMx); while (0U == LL_TIM_IsActiveFlag_UPDATE(TIMx)) { /* Nothing to do */ } LL_TIM_ClearFlag_UPDATE(TIMx); /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE; LL_TIM_EnableAllOutputs(TIMx); if ((pHandle->_Super.LowSideOutputs) == ES_GPIO) { if ((TIMx->CCER & TIMxCCER_MASK_CH123) != 0u) { LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } } else { /* Nothing to do */ } /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE(TIMx); /* Enable Update IRQ */ LL_TIM_EnableIT_UPDATE(TIMx); } /* * @brief Disables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void ICS_SwitchOffPWM(PWMC_Handle_t *pHdl) { PWMC_ICS_Handle_t *pHandle = (PWMC_ICS_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; /* Disable UPDATE ISR */ LL_TIM_DisableIT_UPDATE(TIMx); pHandle->_Super.TurnOnLowSidesAction = false; /* Main PWM Output Disable */ if (pHandle->_Super.BrakeActionLock == true) { /* Nothing to do */ } else { TIMx->BDTR &= ~((uint32_t)(LL_TIM_OSSI_ENABLE)); LL_TIM_DisableAllOutputs(TIMx); if ((pHandle->_Super.LowSideOutputs) == ES_GPIO) { LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } else { /* Nothing to do */ } } /* wait for a new PWM period to flush last HF task */ LL_TIM_ClearFlag_UPDATE(TIMx); while (0U == LL_TIM_IsActiveFlag_UPDATE(TIMx)) { /* Nothing to do */ } LL_TIM_ClearFlag_UPDATE(TIMx); /* We allow ADC usage for regular conversion on Systick, cut 2.2 patch */ pHandle->ADCRegularLocked = false; } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /* * @brief Contains the TIMx Update event interrupt. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void *ICS_TIMx_UP_IRQHandler(PWMC_ICS_Handle_t *pHandle) { TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef *ADCx_1 = pHandle->pParams_str->ADCx_1; ADC_TypeDef *ADCx_2 = pHandle->pParams_str->ADCx_2; ADCx_1->JSQR = (uint32_t) pHandle->pParams_str->ADCConfig1; ADCx_2->JSQR = (uint32_t) pHandle->pParams_str->ADCConfig2; /* enable ADC trigger source */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_OC4REF); return (&(pHandle->_Super.Motor)); } /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
22,398
C
30.15299
126
0.636396
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/G4xx/Src/g4xx_bemf_ADC_fdbk.c
/** ****************************************************************************** * @file g4xx_bemf_ADC_fdbk.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement Bemf sensing * class to be stantiated when the six-step sensorless driving mode * topology is used. * * It is specifically designed for STM32G4XX microcontrollers and * implements the sensing using one, two or three independent * ADCs with injected channels. * + MCU peripheral and handle initialization fucntion * + ADC sampling function * ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup SpeednPosFdbk_Bemf */ /* Includes ------------------------------------------------------------------*/ #include "g4xx_bemf_ADC_fdbk.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup SpeednPosFdbk * @{ */ /** @addtogroup SpeednPosFdbk_Bemf * @{ */ /* Private defines -----------------------------------------------------------*/ #define MAX_PSEUDO_SPEED ((int16_t)0x7FFF) #define PHASE_U 0u #define PHASE_V 1u #define PHASE_W 2u /* Private function prototypes -----------------------------------------------*/ void BADC_CalcAvrgElSpeedDpp( Bemf_ADC_Handle_t * pHandle ); /* Private functions ---------------------------------------------------------*/ /** * @brief Initializes ADC and NVIC for three bemf voltages reading * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_Init( Bemf_ADC_Handle_t *pHandle) { ADC_TypeDef * ADCx_u = pHandle->pParams_str->pAdc[0]; ADC_TypeDef * ADCx_v = pHandle->pParams_str->pAdc[1]; ADC_TypeDef * ADCx_w = pHandle->pParams_str->pAdc[2]; if ( ( uint32_t )pHandle == ( uint32_t )&pHandle->_Super ) { /* disable IT and flags in case of LL driver usage * workaround for unwanted interrupt enabling done by LL driver */ LL_ADC_DisableIT_EOC( ADCx_u ); LL_ADC_DisableIT_EOC( ADCx_v ); LL_ADC_DisableIT_EOC( ADCx_w ); LL_ADC_ClearFlag_EOC( ADCx_u ); LL_ADC_ClearFlag_EOC( ADCx_v ); LL_ADC_ClearFlag_EOC( ADCx_w ); LL_ADC_DisableIT_JEOC( ADCx_u ); LL_ADC_DisableIT_JEOC( ADCx_v ); LL_ADC_DisableIT_JEOC( ADCx_w ); LL_ADC_ClearFlag_JEOC( ADCx_u ); LL_ADC_ClearFlag_JEOC( ADCx_v ); LL_ADC_ClearFlag_JEOC( ADCx_w ); /* - Exit from deep-power-down mode */ LL_ADC_DisableDeepPowerDown(ADCx_u); LL_ADC_DisableDeepPowerDown(ADCx_v); LL_ADC_DisableDeepPowerDown(ADCx_w); LL_ADC_EnableInternalRegulator( ADCx_u ); LL_ADC_EnableInternalRegulator( ADCx_v ); LL_ADC_EnableInternalRegulator( ADCx_w ); volatile uint32_t wait_loop_index = ((LL_ADC_DELAY_INTERNAL_REGUL_STAB_US / 10UL) * (SystemCoreClock / (100000UL * 2UL))); while(wait_loop_index != 0UL) { wait_loop_index--; } LL_ADC_StartCalibration( ADCx_u, LL_ADC_SINGLE_ENDED ); while ( LL_ADC_IsCalibrationOnGoing( ADCx_u ) ) { } if (ADCx_u != ADCx_v) { LL_ADC_StartCalibration( ADCx_v, LL_ADC_SINGLE_ENDED ); while ( LL_ADC_IsCalibrationOnGoing( ADCx_v ) ) { } } if ((ADCx_w != ADCx_u) && (ADCx_w != ADCx_v)) { LL_ADC_StartCalibration( ADCx_w, LL_ADC_SINGLE_ENDED ); while ( LL_ADC_IsCalibrationOnGoing( ADCx_w ) ) { } } /* ADC Enable (must be done after calibration) */ /* ADC5-140924: Enabling the ADC by setting ADEN bit soon after polling ADCAL=0 * following a calibration phase, could have no effect on ADC * within certain AHB/ADC clock ratio. */ LL_ADC_SetChannelSamplingTime (ADCx_u, pHandle->pParams_str->AdcChannel[0], LL_ADC_SAMPLINGTIME_2CYCLES_5 ); LL_ADC_SetChannelSamplingTime (ADCx_v, pHandle->pParams_str->AdcChannel[1], LL_ADC_SAMPLINGTIME_2CYCLES_5 ); LL_ADC_SetChannelSamplingTime (ADCx_w, pHandle->pParams_str->AdcChannel[2], LL_ADC_SAMPLINGTIME_2CYCLES_5 ); while ( LL_ADC_IsActiveFlag_ADRDY( ADCx_u ) == 0u) { LL_ADC_Enable( ADCx_u ); } while ( LL_ADC_IsActiveFlag_ADRDY( ADCx_v ) == 0u) { LL_ADC_Enable( ADCx_v ); } while ( LL_ADC_IsActiveFlag_ADRDY( ADCx_w ) == 0u) { LL_ADC_Enable( ADCx_w ); } pHandle->ADCRegularLocked=false; uint16_t hMinReliableElSpeedUnit = pHandle->_Super.hMinReliableMecSpeedUnit * pHandle->_Super.bElToMecRatio; uint16_t hMaxReliableElSpeedUnit = pHandle->_Super.hMaxReliableMecSpeedUnit * pHandle->_Super.bElToMecRatio; uint8_t bSpeedBufferSize; uint8_t bIndex; uint16_t MinBemfTime; /* Adjustment factor: minimum measurable speed is x time less than the minimum reliable speed */ hMinReliableElSpeedUnit /= 4U; /* Adjustment factor: maximum measurable speed is x time greater than the maximum reliable speed */ hMaxReliableElSpeedUnit *= 2U; pHandle->OvfFreq = (uint16_t)(pHandle->TIMClockFreq / 65536U); /* SW Init */ if (0U == hMinReliableElSpeedUnit) { /* Set fixed to 150 ms */ pHandle->BemfTimeout = 150U; } else { /* Set accordingly the min reliable speed */ /* 1000 comes from mS * 6 comes from the fact that sensors are toggling each 60 deg = 360/6 deg */ pHandle->BemfTimeout = (1000U * (uint16_t)SPEED_UNIT) / (6U * hMinReliableElSpeedUnit); } /* Align MaxPeriod and MinPeriod to a multiple of Overflow.*/ pHandle->MaxPeriod = (pHandle->BemfTimeout * pHandle->OvfFreq) / 1000U * 65536UL; MinBemfTime = ((1000U * (uint16_t)SPEED_UNIT) << 8) / (6U * hMaxReliableElSpeedUnit); pHandle->MinPeriod = ((MinBemfTime * pHandle->OvfFreq) >> 8) / 1000U * 65536UL; pHandle->SatSpeed = hMaxReliableElSpeedUnit; pHandle->PseudoPeriodConv = ((pHandle->TIMClockFreq / 6U) / pHandle->_Super.hMeasurementFrequency) * pHandle->_Super.DPPConvFactor; if (0U == hMaxReliableElSpeedUnit) { pHandle->MinPeriod = ((uint32_t)SPEED_UNIT * (pHandle->TIMClockFreq / 6UL)); } else { pHandle->MinPeriod = (((uint32_t)SPEED_UNIT * (pHandle->TIMClockFreq / 6UL)) / hMaxReliableElSpeedUnit); } pHandle->PWMNbrPSamplingFreq = ((pHandle->_Super.hMeasurementFrequency * pHandle->PWMFreqScaling) / pHandle->SpeedSamplingFreqHz) - 1U; pHandle->pSensing_Params = &(pHandle->Pwm_OFF); pHandle->IsOnSensingEnabled = false; pHandle->ElPeriodSum = 0; pHandle->ZcEvents = 0; pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold; /* Erase speed buffer */ bSpeedBufferSize = pHandle->SpeedBufferSize; for (bIndex = 0u; bIndex < bSpeedBufferSize; bIndex++) { pHandle->SpeedBufferDpp[bIndex] = (int32_t)pHandle->MaxPeriod; } LL_TIM_EnableCounter(pHandle->pParams_str->LfTim); } } /** * @brief Resets the parameter values of the component * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_Clear( Bemf_ADC_Handle_t *pHandle ) { pHandle->ZcEvents = 0; pHandle->ElPeriodSum = 0; /* Acceleration measurement not implemented.*/ pHandle->_Super.hMecAccelUnitP = 0; pHandle->BufferFilled = 0U; pHandle->CompSpeed = 0; /* Initialize speed buffer index */ pHandle->SpeedFIFOIdx = 0U; pHandle->_Super.hElAngle = 0; /* Clear speed error counter */ pHandle->_Super.bSpeedErrorNumber = 0; pHandle->IsLoopClosed=false; pHandle->IsAlgorithmConverged = false; } /** * @brief Starts bemf ADC conversion of the phase depending on current step * @param pHandle: handler of the current instance of the Bemf_ADC component * @param step: current step of the six-step sequence */ __weak void BADC_Start(Bemf_ADC_Handle_t *pHandle, uint8_t step) { ADC_TypeDef * ADCx_u = pHandle->pParams_str->pAdc[0]; ADC_TypeDef * ADCx_v = pHandle->pParams_str->pAdc[1]; ADC_TypeDef * ADCx_w = pHandle->pParams_str->pAdc[2]; if (true == pHandle->ADCRegularLocked) { LL_ADC_DisableIT_JEOC( ADCx_u ); LL_ADC_DisableIT_JEOC( ADCx_v ); LL_ADC_DisableIT_JEOC( ADCx_w ); } else { pHandle->ADCRegularLocked = true; } switch (step) { case STEP_1: case STEP_4: BADC_SelectAdcChannel(pHandle, PHASE_W); /*start injected conversion */ LL_ADC_EnableIT_JEOC( ADCx_w ); LL_ADC_INJ_StartConversion( ADCx_w ); break; case STEP_2: case STEP_5: BADC_SelectAdcChannel(pHandle, PHASE_V); /*start injected conversion */ LL_ADC_EnableIT_JEOC( ADCx_v ); LL_ADC_INJ_StartConversion( ADCx_v ); break; case STEP_3: case STEP_6: BADC_SelectAdcChannel(pHandle, PHASE_U); /*start injected conversion */ LL_ADC_EnableIT_JEOC( ADCx_u ); LL_ADC_INJ_StartConversion( ADCx_u ); break; default: break; } } /** * @brief Stops bemf ADC conversion * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_Stop(Bemf_ADC_Handle_t *pHandle) { ADC_TypeDef * ADCx_u = pHandle->pParams_str->pAdc[0]; ADC_TypeDef * ADCx_v = pHandle->pParams_str->pAdc[1]; ADC_TypeDef * ADCx_w = pHandle->pParams_str->pAdc[2]; /* Disable JEOC */ LL_ADC_DisableIT_JEOC( ADCx_u ); LL_ADC_DisableIT_JEOC( ADCx_v ); LL_ADC_DisableIT_JEOC( ADCx_w ); /* Clear JEOC */ LL_ADC_ClearFlag_JEOC( ADCx_u ); LL_ADC_ClearFlag_JEOC( ADCx_v ); LL_ADC_ClearFlag_JEOC( ADCx_w ); if (true == pHandle->ADCRegularLocked) { /* Stop ADC injected conversion */ LL_ADC_INJ_StopConversion( ADCx_u ); LL_ADC_INJ_StopConversion( ADCx_v ); LL_ADC_INJ_StopConversion( ADCx_w ); pHandle->ADCRegularLocked=false; } else { /* Nothing to do */ } } /** * @brief Enables the speed loop (low frequency) timer * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_SpeedMeasureOn(Bemf_ADC_Handle_t *pHandle) { LL_TIM_ClearFlag_UPDATE(pHandle->pParams_str->LfTim); LL_TIM_EnableIT_UPDATE(pHandle->pParams_str->LfTim); } /** * @brief Disables the speed loop (low frequency) timer * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_SpeedMeasureOff(Bemf_ADC_Handle_t *pHandle) { LL_TIM_DisableIT_UPDATE(pHandle->pParams_str->LfTim); } /** * @brief Configures the ADC for the current sampling. * It sets the sampling point via TIM1_Ch4 value, the ADC sequence * and channels. * @param pHandle: handler of the current instance of the Bemf_ADC component * @param pHandlePWMC: handler of the current instance of the PWMC component * @param pHandleSTC: handler of the current instance of the Speed Control component */ __weak void BADC_SetSamplingPoint(Bemf_ADC_Handle_t *pHandle, PWMC_Handle_t *pHandlePWMC, SpeednTorqCtrl_Handle_t *pHandleSTC ) { if ((pHandleSTC->ModeDefault == MCM_SPEED_MODE) && (pHandle->DriveMode == VM)) { if (!(pHandle->IsOnSensingEnabled) && (pHandlePWMC->CntPh > pHandle->OnSensingEnThres)) { pHandle->IsOnSensingEnabled=true; pHandle->pSensing_Params = &(pHandle->Pwm_ON); } else if ((pHandle->IsOnSensingEnabled) && (pHandlePWMC->CntPh < pHandle->OnSensingDisThres)) { pHandle->IsOnSensingEnabled=false; pHandle->pSensing_Params = &(pHandle->Pwm_OFF); } else { } } else { pHandle->IsOnSensingEnabled=false; pHandle->pSensing_Params = &(pHandle->Pwm_OFF); } if (true == pHandle->pParams_str->gpio_divider_available) LL_GPIO_ResetOutputPin( pHandle->pParams_str->bemf_divider_port, pHandle->pParams_str->bemf_divider_pin ); PWMC_SetADCTriggerChannel( pHandlePWMC, pHandle->pSensing_Params->SamplingPoint); } /** * @brief Gets last bemf value and checks for zero crossing detection. * It updates speed loop timer and electrical angle accordingly. * @param pHandle: handler of the current instance of the Bemf_ADC component * @param pHandlePWMC: handler of the current instance of the PWMC component * @retval True if zero has been crossed, false otherwise */ __weak bool BADC_IsZcDetected( Bemf_ADC_Handle_t *pHandle, PWMC_Handle_t *pHandlePWMC) { ADC_TypeDef * ADCx_u = pHandle->pParams_str->pAdc[0]; ADC_TypeDef * ADCx_v = pHandle->pParams_str->pAdc[1]; ADC_TypeDef * ADCx_w = pHandle->pParams_str->pAdc[2]; uint16_t AdcValue; bool ZcDetection = false; pHandle->DemagCounter++; if ( pHandle->DemagCounter > pHandle->DemagCounterThreshold) { if (pHandle->ZcDetected == false) { switch(pHandlePWMC->Step) { case STEP_1: AdcValue = ADCx_w->JDR1; pHandle->BemfLastValues[2] = AdcValue; if(pHandle->Direction == 1) { if (AdcValue < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_60_PHASE_SHIFT / 2; } } else { if (AdcValue > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = S16_120_PHASE_SHIFT + S16_60_PHASE_SHIFT / 2; } } break; case STEP_2: AdcValue = ADCx_v->JDR1; pHandle->BemfLastValues[1] = AdcValue; if(pHandle->Direction == 1) { if (AdcValue > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = S16_60_PHASE_SHIFT / 2; } } else { if (AdcValue < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_120_PHASE_SHIFT - S16_60_PHASE_SHIFT / 2; } } break; case STEP_3: AdcValue = ADCx_u->JDR1; pHandle->BemfLastValues[0] = AdcValue; if(pHandle->Direction == 1) { if (AdcValue < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = S16_60_PHASE_SHIFT + S16_60_PHASE_SHIFT / 2; } } else { if (AdcValue > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_60_PHASE_SHIFT - S16_60_PHASE_SHIFT / 2; } } break; case STEP_4: AdcValue = ADCx_w->JDR1; pHandle->BemfLastValues[2] = AdcValue; if(pHandle->Direction == 1) { if (AdcValue > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = S16_120_PHASE_SHIFT + S16_60_PHASE_SHIFT / 2; } } else { if (AdcValue < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_60_PHASE_SHIFT / 2; } } break; case STEP_5: AdcValue = ADCx_v->JDR1; pHandle->BemfLastValues[1] = AdcValue; if(pHandle->Direction == 1) { if (AdcValue < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_120_PHASE_SHIFT - S16_60_PHASE_SHIFT / 2; } } else { if (AdcValue > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = S16_60_PHASE_SHIFT / 2; } } break; case STEP_6: AdcValue = ADCx_u->JDR1; pHandle->BemfLastValues[0] = AdcValue; if(pHandle->Direction == 1) { if (AdcValue > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_60_PHASE_SHIFT - S16_60_PHASE_SHIFT / 2; } } else { if (AdcValue < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = S16_60_PHASE_SHIFT + S16_60_PHASE_SHIFT / 2; } } break; } if (true == ZcDetection) { pHandle->MeasuredElAngle += (S16_60_PHASE_SHIFT/2) - (int16_t)((uint32_t)(pHandle->Zc2CommDelay * S16_60_PHASE_SHIFT)>>9); if (pHandle->ZcEvents > pHandle->StartUpConsistThreshold) { pHandle->IsAlgorithmConverged = true; } pHandle->ZcDetected = true; pHandle->ZcEvents++; switch(pHandlePWMC->Step) { case STEP_1: case STEP_3: case STEP_5: if(pHandle->Direction == 1) { pHandle->ZC_Counter_Down = LL_TIM_GetCounter(pHandle->pParams_str->LfTim); pHandle->ZC_Counter_Last = pHandle->ZC_Counter_Down; } else { pHandle->ZC_Counter_Up = LL_TIM_GetCounter(pHandle->pParams_str->LfTim); pHandle->ZC_Counter_Last = pHandle->ZC_Counter_Up; } break; case STEP_2: case STEP_4: case STEP_6: if(pHandle->Direction == 1) { pHandle->ZC_Counter_Up = LL_TIM_GetCounter(pHandle->pParams_str->LfTim); pHandle->ZC_Counter_Last = pHandle->ZC_Counter_Up; } else { pHandle->ZC_Counter_Down = LL_TIM_GetCounter(pHandle->pParams_str->LfTim); pHandle->ZC_Counter_Last = pHandle->ZC_Counter_Down; } break; } if (true == pHandle->IsAlgorithmConverged) { uint32_t tempReg = (uint32_t )(pHandle->PseudoPeriodConv / ((pHandle->LowFreqTimerPsc + 1) * (pHandle->AvrElSpeedDpp * pHandle->Direction))); LL_TIM_SetAutoReload(pHandle->pParams_str->LfTim,pHandle->ZC_Counter_Last + (((uint32_t)((pHandle->Zc2CommDelay) * tempReg)) >> 9) ); } } } } return ZcDetection; } /** * @brief This method must be called - at least - with the same periodicity * on which speed control is executed. It computes and returns - through * parameter hMecSpeedUnit - the rotor average mechanical speed, * expressed in Unit. Average is computed considering a FIFO depth * equal to SpeedBufferSizeUnit. Moreover it also computes and returns * the reliability state of the sensor. * @param pHandle: handler of the current instance of the Bemf_ADC component * @param pMecSpeedUnit pointer to int16_t, used to return the rotor average * mechanical speed (expressed in the unit defined by SPEED_UNIT) * @retval bool speed sensor reliability, measured with reference to parameters * Reliability_hysteresys, VariancePercentage and SpeedBufferSize * true = sensor information is reliable * false = sensor information is not reliable */ __weak bool BADC_CalcAvrgMecSpeedUnit( Bemf_ADC_Handle_t * pHandle, int16_t * pMecSpeedUnit ) { bool bReliability; pHandle->_Super.hElSpeedDpp = pHandle->AvrElSpeedDpp; if (0 == pHandle->AvrElSpeedDpp) { /* Speed is too low */ *pMecSpeedUnit = 0; } else { /* Check if speed is not to fast */ if (pHandle->AvrElSpeedDpp != MAX_PSEUDO_SPEED) { pHandle->DeltaAngle = pHandle->MeasuredElAngle - pHandle->_Super.hElAngle; pHandle->CompSpeed = (int16_t)((int32_t)(pHandle->DeltaAngle) / (int32_t)(pHandle->PWMNbrPSamplingFreq)); /* Convert el_dpp to MecUnit */ *pMecSpeedUnit = (int16_t)((pHandle->AvrElSpeedDpp * (int32_t)pHandle->_Super.hMeasurementFrequency * (int32_t)SPEED_UNIT ) / ((int32_t)(pHandle->_Super.DPPConvFactor) * (int32_t)(pHandle->_Super.bElToMecRatio)) ); } else { *pMecSpeedUnit = (int16_t)pHandle->SatSpeed; } } bReliability = SPD_IsMecSpeedReliable(&pHandle->_Super, pMecSpeedUnit); pHandle->_Super.hAvrMecSpeedUnit = *pMecSpeedUnit; BADC_CalcAvrgElSpeedDpp (pHandle); return (bReliability); } /** * @brief Returns false if calculated speed is out of reliability ranges * @param pHandle: handler of the current instance of the Bemf_ADC component * @retval bool: reliability flag */ __weak bool BADC_IsSpeedReliable( Bemf_ADC_Handle_t *pHandle ) { bool SpeedError = false; if ( pHandle->_Super.hAvrMecSpeedUnit > pHandle->_Super.hMaxReliableMecSpeedUnit ) { SpeedError = true; } if ( pHandle->_Super.hAvrMecSpeedUnit < pHandle->_Super.hMinReliableMecSpeedUnit ) { SpeedError = true; } return ( SpeedError ); } /** * @brief Forces the rotation direction * @param pHandle: handler of the current instance of the Bemf_ADC component * @param direction: imposed direction */ __weak void BADC_SetDirection( Bemf_ADC_Handle_t * pHandle, uint8_t direction ) { if (MC_NULL == pHandle) { /* Nothing to do */ } else { pHandle->Direction = direction; } } /** * @brief Internally performs a checks necessary to state whether * the bemf algorithm converged. To be periodically called * during motor open-loop ramp-up (e.g. at the same frequency of * SPD_CalcElAngle), it returns true if the estimated angle and speed * can be considered reliable, false otherwise * @param pHandle: handler of the current instance of the Bemf_ADC component * * @retval bool sensor reliability state */ __weak bool BADC_IsObserverConverged( Bemf_ADC_Handle_t * pHandle ) { return pHandle->IsAlgorithmConverged; } /** * @brief Configures the proper ADC channel according to the current * step corresponding to the floating phase. To be periodically called * at least at every step change. * @param pHandle: handler of the current instance of the Bemf_ADC component * @param Phase: Floating phase for bemf acquisition */ void BADC_SelectAdcChannel(Bemf_ADC_Handle_t * pHandle, uint8_t Phase) { LL_ADC_INJ_SetSequencerRanks(pHandle->pParams_str->pAdc[Phase], LL_ADC_INJ_RANK_1, __LL_ADC_DECIMAL_NB_TO_CHANNEL(pHandle->pParams_str->AdcChannel[Phase])); } /** * @brief Updates the estimated electrical angle. * @param pHandle: handler of the current instance of the Bemf_ADC component * @retval int16_t rotor electrical angle (s16Degrees) */ __weak int16_t BADC_CalcElAngle(Bemf_ADC_Handle_t * pHandle) { int16_t retValue; if (pHandle->_Super.hElSpeedDpp != MAX_PSEUDO_SPEED) { if (false == pHandle->IsLoopClosed) { pHandle->MeasuredElAngle += pHandle->_Super.hElSpeedDpp; pHandle->PrevRotorFreq = pHandle->_Super.hElSpeedDpp; pHandle->_Super.hElAngle += pHandle->_Super.hElSpeedDpp + pHandle->CompSpeed; } else { pHandle->_Super.hElAngle = pHandle->MeasuredElAngle; } } else { pHandle->_Super.hElAngle += pHandle->PrevRotorFreq; } retValue = pHandle->_Super.hElAngle; return (retValue); } /** * @brief Must be called - at least - with the same periodicity * on which speed control is executed. It computes and update component * variable hElSpeedDpp that is estimated average electrical speed * expressed in dpp used for instance in observer equations. * Average is computed considering a FIFO depth equal to * bSpeedBufferSizedpp. * @param pHandle: handler of the current instance of the Bemf_ADC component */ void BADC_CalcAvrgElSpeedDpp( Bemf_ADC_Handle_t * pHandle ) { uint32_t wCaptBuf; /* used to validate the average speed measurement */ if (pHandle->BufferFilled < pHandle->SpeedBufferSize) { pHandle->BufferFilled++; } else { /* Nothing to do */ } if (false == pHandle->IsLoopClosed) { if (pHandle->VirtualElSpeedDpp == 0) pHandle->Counter_Period = 0xFFFF; else pHandle->Counter_Period = ( uint32_t )(pHandle->PseudoPeriodConv / ((pHandle->LowFreqTimerPsc + 1) * pHandle->VirtualElSpeedDpp)); } else { pHandle->Counter_Period = pHandle->ZC_Counter_Last + pHandle->Last_Zc2Comm_Delay; } wCaptBuf = pHandle->Counter_Period * (pHandle->LowFreqTimerPsc + 1); /* Filtering to fast speed... could be a glitch ? */ /* the MAX_PSEUDO_SPEED is temporary in the buffer, and never included in average computation*/ if (wCaptBuf < pHandle->MinPeriod) { /* Nothing to do */ } else { pHandle->ElPeriodSum -= pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx]; /* value we gonna removed from the accumulator */ if (wCaptBuf >= pHandle->MaxPeriod) { pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx] = (int32_t)pHandle->MaxPeriod * pHandle->Direction; } else { pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx] = (int32_t)wCaptBuf ; pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx] *= pHandle->Direction; pHandle->ElPeriodSum += pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx]; } /* Update pointers to speed buffer */ pHandle->SpeedFIFOIdx++; if (pHandle->SpeedFIFOIdx == pHandle->SpeedBufferSize) { pHandle->SpeedFIFOIdx = 0U; } if (((pHandle->BufferFilled < pHandle->SpeedBufferSize) && (wCaptBuf != 0U)) || (false == pHandle->IsLoopClosed)) { uint32_t tempReg = (pHandle->PseudoPeriodConv / wCaptBuf) * (uint32_t)pHandle->Direction; pHandle->AvrElSpeedDpp = (int16_t)tempReg; } else { /* Average speed allow to smooth the mechanical sensors misalignement */ int32_t tElPeriodSum = 0; uint8_t i; for (i=0; i < pHandle->SpeedBufferSize; i++) { tElPeriodSum += pHandle->SpeedBufferDpp[i]; } pHandle->AvrElSpeedDpp = (int16_t)((int32_t)pHandle->PseudoPeriodConv / (tElPeriodSum / (int32_t)pHandle->SpeedBufferSize)); /* Average value */ } } } /** * @brief Used to calculate instant speed during revup, to * initialize parameters at step change and to select proper ADC channel * for next Bemf acquisitions * @param pHandle: handler of the current instance of the Bemf_ADC component * @param hElSpeedDpp: Mechanical speed imposed by virtual speed component * @param pHandlePWMC: handler of the current instance of the PWMC component */ void BADC_StepChangeEvent(Bemf_ADC_Handle_t * pHandle, int16_t hElSpeedDpp, PWMC_Handle_t *pHandlePWMC) { pHandle->DemagCounter = 0; pHandle->Last_Zc2Comm_Delay = LL_TIM_GetAutoReload(pHandle->pParams_str->LfTim) - pHandle->ZC_Counter_Last; if (false == pHandle->IsLoopClosed) { if (hElSpeedDpp < 0) { pHandle->VirtualElSpeedDpp = - hElSpeedDpp; } else { pHandle->VirtualElSpeedDpp = hElSpeedDpp; } pHandle->ZcDetected = false; } else { int16_t ElAngleUpdate; if(pHandle->Direction == -1) { ElAngleUpdate = -S16_60_PHASE_SHIFT ; } else { ElAngleUpdate = S16_60_PHASE_SHIFT ; } pHandle->MeasuredElAngle += ElAngleUpdate; if ( false == pHandle->ZcDetected) { LL_TIM_SetAutoReload(pHandle->pParams_str->LfTim,LL_TIM_GetAutoReload(pHandle->pParams_str->LfTim) * 150 / 100); } else { pHandle->ZcDetected = false; } } pHandle->StepUpdate = true; } /** * @brief Calculates and stores in the corresponding variable the demagnetization * time in open loop operation * @param pHandle: handler of the current instance of the Bemf_ADC component */ void BADC_CalcRevUpDemagTime(Bemf_ADC_Handle_t *pHandle) { int16_t hSpeed; hSpeed = (int16_t)((pHandle->VirtualElSpeedDpp * (int32_t)pHandle->_Super.hMeasurementFrequency * (int32_t)SPEED_UNIT ) / ((int32_t)(pHandle->_Super.DPPConvFactor) * (int32_t)(pHandle->_Super.bElToMecRatio)) );; if (hSpeed == 0) { pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold;; } else { pHandle->DemagCounterThreshold = (uint16_t) (pHandle->DemagParams.RevUpDemagSpeedConv / hSpeed); } if (pHandle->DemagCounterThreshold < pHandle->DemagParams.DemagMinimumThreshold) { pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold; } } /** * @brief Calculates and stores in the corresponding variable the demagnetization * time in closed loop operation * @param pHandle: handler of the current instance of the Bemf_ADC component */ void BADC_CalcRunDemagTime(Bemf_ADC_Handle_t *pHandle) { int16_t hSpeed; hSpeed = pHandle->_Super.hAvrMecSpeedUnit; if (hSpeed < 0) hSpeed = - hSpeed; if (hSpeed < pHandle->DemagParams.DemagMinimumSpeedUnit) { pHandle->DemagCounterThreshold = (uint16_t) (pHandle->DemagParams.RunDemagSpeedConv / hSpeed); if (pHandle->DemagCounterThreshold < pHandle->DemagParams.DemagMinimumThreshold) { pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold; } } else { pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold; } } /** * @brief Must be called after switch-over procedure when * virtual speed sensor transition is ended. * @param pHandle: handler of the current instance of the STO component */ void BADC_SetLoopClosed(Bemf_ADC_Handle_t *pHandle) { pHandle->IsLoopClosed=true; } /** * @brief Returns the last acquired bemf value * @param pHandle: handler of the current instance of the Bemf_ADC component * @param phase: motor phase under investigation * @retval uint16_t: Bemf value */ uint16_t BADC_GetLastBemfValue(Bemf_ADC_Handle_t *pHandle, uint8_t phase) { return ((MC_NULL == pHandle) ? 0U : pHandle->BemfLastValues[phase]); } /** * @brief Returns the zero crossing detection flag * @param pHandle: handler of the current instance of the Bemf_ADC component * @retval bool: zero crossing detection flag */ bool BADC_GetBemfZcrFlag(Bemf_ADC_Handle_t *pHandle) { return ((MC_NULL == pHandle) ? 0U : pHandle->ZcDetected); } /** * @brief Returns true if the step needs to be updated * @param pHandle: handler of the current instance of the Bemf_ADC component * @retval bool: step update request */ bool BADC_ClearStepUpdate(Bemf_ADC_Handle_t *pHandle) { bool retValue = (((pHandle->IsLoopClosed == true) && (pHandle->StepUpdate == true)) || (pHandle->IsLoopClosed == false)); pHandle->StepUpdate = false; return retValue; } /** * @brief Configures the parameters for bemf sensing during pwm off-time * @param pHandle: handler of the current instance of the Bemf_ADC component * @param BemfAdcConfig: thresholds and sampling time parameters * @param Zc2CommDelay: delay between bemf zero crossing parameter and step commutation * @param bemfAdcDemagConfig: demagnetization parameters */ void BADC_SetBemfSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfAdcConfig, uint16_t *Zc2CommDelay, Bemf_Demag_Params *bemfAdcDemagConfig) { pHandle->Pwm_OFF.AdcThresholdUp = BemfAdcConfig->AdcThresholdUp; pHandle->Pwm_OFF.AdcThresholdDown = BemfAdcConfig->AdcThresholdDown; pHandle->Pwm_OFF.SamplingPoint = BemfAdcConfig->SamplingPoint; pHandle->Zc2CommDelay = *Zc2CommDelay; pHandle->DemagParams.DemagMinimumSpeedUnit = bemfAdcDemagConfig->DemagMinimumSpeedUnit; pHandle->DemagParams.DemagMinimumThreshold = bemfAdcDemagConfig->DemagMinimumThreshold; } /** * @brief Configures the parameters for bemf sensing during pwm on-time * @param pHandle: handler of the current instance of the Bemf_ADC component * @param BemfOnAdcConfig: thresholds and sampling time parameters * @param OnSensingEnThres: Minimum dudty cycle for on-sensing activation * @param OnSensingDisThres: Minimum duty cycle for on-sensing Deactivationg */ void BADC_SetBemfOnTimeSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfOnAdcConfig, uint16_t *OnSensingEnThres, uint16_t *OnSensingDisThres) { pHandle->Pwm_ON.AdcThresholdUp = BemfOnAdcConfig->AdcThresholdUp; pHandle->Pwm_ON.AdcThresholdDown = BemfOnAdcConfig->AdcThresholdDown; pHandle->Pwm_ON.SamplingPoint = BemfOnAdcConfig->SamplingPoint; pHandle->OnSensingEnThres = *OnSensingEnThres; pHandle->OnSensingDisThres = *OnSensingDisThres; } /** * @brief Gets the parameters for bemf sensing during pwm off-time * @param pHandle: handler of the current instance of the Bemf_ADC component * @param BemfAdcConfig: thresholds and sampling time parameters * @param Zc2CommDelay: delay between bemf zero crossing parameter and step commutation * @param BemfAdcDemagConfig: demagnetization parameters */ void BADC_GetBemfSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfAdcConfig, uint16_t *Zc2CommDelay, Bemf_Demag_Params *BemfAdcDemagConfig) { BemfAdcConfig->AdcThresholdUp = pHandle->Pwm_OFF.AdcThresholdUp; BemfAdcConfig->AdcThresholdDown = pHandle->Pwm_OFF.AdcThresholdDown; BemfAdcConfig->SamplingPoint = pHandle->Pwm_OFF.SamplingPoint; *Zc2CommDelay = pHandle->Zc2CommDelay; BemfAdcDemagConfig->DemagMinimumSpeedUnit = pHandle->DemagParams.DemagMinimumSpeedUnit; BemfAdcDemagConfig->DemagMinimumThreshold = pHandle->DemagParams.DemagMinimumThreshold; } /** * @brief Gets the parameters for bemf sensing during pwm on-time * @param pHandle: handler of the current instance of the Bemf_ADC component * @param BemfOnAdcConfig: thresholds and sampling time parameters * @param OnSensingEnThres: Minimum duty cycle for on-sensing activation * @param OnSensingDisThres: Minimum duty cycle for on-sensing Deactivationg */ void BADC_GetBemfOnTimeSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfOnAdcConfig, uint16_t *OnSensingEnThres, uint16_t *OnSensingDisThres) { BemfOnAdcConfig->AdcThresholdUp = pHandle->Pwm_ON.AdcThresholdUp; BemfOnAdcConfig->AdcThresholdDown = pHandle->Pwm_ON.AdcThresholdDown; BemfOnAdcConfig->SamplingPoint = pHandle->Pwm_ON.SamplingPoint; *OnSensingEnThres = pHandle->OnSensingEnThres; *OnSensingDisThres = pHandle->OnSensingDisThres; } /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
35,285
C
34.005952
167
0.638713
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/G4xx/Src/r3_3_g4xx_pwm_curr_fdbk.c
/** ****************************************************************************** * @file r3_3_g4xx_pwm_curr_fdbk.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement current sensor * class to be stantiated when the three shunts current sensing * topology is used. * * It is specifically designed for STM32G4XX microcontrollers and * implements the successive sampling of motor current using three ADCs. * + MCU peripheral and handle initialization function * + three shunts current sensing * + space vector modulation function * + ADC sampling function * ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics International N.V. * All rights reserved.</center></h2> * * Redistribution and use in source and binary forms, with or without * modification, are permitted, provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of other * contributors to this software may be used to endorse or promote products * derived from this software without specific written permission. * 4. This software, including modifications and/or derivative works of this * software, must execute solely and exclusively on microcontroller or * microprocessor devices manufactured by or for STMicroelectronics. * 5. Redistribution and use of this software other than as permitted under * this license is void and will automatically terminate your rights under * this license. * * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT * SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** * @ingroup R3_3_G4XX_pwm_curr_fdbk */ /* Includes ------------------------------------------------------------------*/ #include "r3_3_g4xx_pwm_curr_fdbk.h" #include "pwm_common.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /* Private defines -----------------------------------------------------------*/ #define TIMxCCER_MASK_CH123 (LL_TIM_CHANNEL_CH1 | LL_TIM_CHANNEL_CH1N | LL_TIM_CHANNEL_CH2|LL_TIM_CHANNEL_CH2N |\ LL_TIM_CHANNEL_CH3 | LL_TIM_CHANNEL_CH3N) /* Private typedef -----------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* These function overloads the TIM_BDTRConfig and TIM_BDTRStructInit of the standard library */ void R3_3_G4XX_TIMxInit(TIM_TypeDef *TIMx, PWMC_Handle_t *pHdl); uint16_t R3_3_G4XX_WriteTIMRegisters(PWMC_Handle_t *pHdl, uint16_t hCCR4Reg); void R3_3_G4XX_HFCurrentsCalibrationABC(PWMC_Handle_t *pHdl, Curr_Components *pStator_Currents); void R3_3_G4XX_SetAOReferenceVoltage(uint32_t DAC_Channel, uint16_t hDACVref); /* Private functions ---------------------------------------------------------*/ /* Local redefinition of both LL_TIM_OC_EnablePreload & LL_TIM_OC_DisablePreload */ __STATIC_INLINE void __LL_TIM_OC_EnablePreload(TIM_TypeDef *TIMx, uint32_t Channel) { register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); register volatile uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); SET_BIT(*pReg, (TIM_CCMR1_OC1PE << SHIFT_TAB_OCxx[iChannel])); } __STATIC_INLINE void __LL_TIM_OC_DisablePreload(TIM_TypeDef *TIMx, uint32_t Channel) { register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); register volatile uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); CLEAR_BIT(*pReg, (TIM_CCMR1_OC1PE << SHIFT_TAB_OCxx[iChannel])); } /** * @defgroup R3_3_G4XX_pwm_curr_fdbk R3 3 ADCs PWM & Current Feedback * * @brief 3-Shunt, 3 ADCs, PWM & Current Feedback implementation for G4XX MCU * * This component is used in applications based on an STM32G4 MCU, using a three * shunt resistors current sensing topology and 3 ADC peripherals to acquire the current * values. * * @{ */ /** * @brief Initializes TIMx, ADC, GPIO, DMA1 and NVIC for current reading * in three shunt topology using STM32G4XX and shared ADC. * * @param pHandle: handler of the current instance of the PWM component. */ __weak void R3_3_G4XX_Init(PWMC_R3_3_G4_Handle_t *pHandle) { pR3_3_G4XXOPAMPParams_t pDOPAMPParams_str = pHandle->pParams_str->pOPAMPParams; COMP_TypeDef *COMP_OCPAx = pHandle->pParams_str->wCompOCPASelection; COMP_TypeDef *COMP_OCPBx = pHandle->pParams_str->wCompOCPBSelection; COMP_TypeDef *COMP_OCPCx = pHandle->pParams_str->wCompOCPCSelection; COMP_TypeDef *COMP_OVPx = pHandle->pParams_str->wCompOVPSelection; TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; if ((uint32_t)pHandle == (uint32_t)&pHandle->_Super) { /* disable IT and flags in case of LL driver usage * workaround for unwanted interrupt enabling done by LL driver */ LL_ADC_DisableIT_EOC(pHandle->pParams_str->ADCx_A); LL_ADC_ClearFlag_EOC(pHandle->pParams_str->ADCx_A); LL_ADC_DisableIT_JEOC(pHandle->pParams_str->ADCx_A); LL_ADC_ClearFlag_JEOC(pHandle->pParams_str->ADCx_A); LL_ADC_DisableIT_EOC(pHandle->pParams_str->ADCx_B); LL_ADC_ClearFlag_EOC(pHandle->pParams_str->ADCx_B); LL_ADC_DisableIT_JEOC(pHandle->pParams_str->ADCx_B); LL_ADC_ClearFlag_JEOC(pHandle->pParams_str->ADCx_B); LL_ADC_DisableIT_EOC(pHandle->pParams_str->ADCx_C); LL_ADC_ClearFlag_EOC(pHandle->pParams_str->ADCx_C); LL_ADC_DisableIT_JEOC(pHandle->pParams_str->ADCx_C); LL_ADC_ClearFlag_JEOC(pHandle->pParams_str->ADCx_C); R3_3_G4XX_TIMxInit(TIMx, &pHandle->_Super); if (TIMx == TIM1) { /* TIM1 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph(LL_DBGMCU_APB2_GRP1_TIM1_STOP); } else { /* TIM8 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph(LL_DBGMCU_APB2_GRP1_TIM8_STOP); } if (pDOPAMPParams_str) { LL_OPAMP_Enable(pDOPAMPParams_str->OPAMP_PHA); LL_OPAMP_Enable(pDOPAMPParams_str->OPAMP_PHB); LL_OPAMP_Enable(pDOPAMPParams_str->OPAMP_PHC); } /* Over current protection phase A */ if (COMP_OCPAx) { /* Inverting input*/ if (pHandle->pParams_str->bCompOCPAInvInput_MODE != EXT_MODE) { if (LL_COMP_GetInputMinus(COMP_OCPAx) == LL_COMP_INPUT_MINUS_DAC1_CH1) { R3_3_G4XX_SetAOReferenceVoltage(LL_DAC_CHANNEL_1, (uint16_t)(pHandle->pParams_str->hDAC_OCP_Threshold)); } #if defined(DAC_CHANNEL2_SUPPORT) else if (LL_COMP_GetInputMinus(COMP_OCPAx) == LL_COMP_INPUT_MINUS_DAC1_CH2) { R3_3_G4XX_SetAOReferenceVoltage(LL_DAC_CHANNEL_2, (uint16_t)(pHandle->pParams_str->hDAC_OCP_Threshold)); } #endif else { /* Nothing to do */ } } else { /* Nothing to do */ } /* Wait to stabilize DAC voltage */ volatile uint16_t waittime = 0u; for (waittime = 0u; waittime < 1000u; waittime++) {} /* Output */ LL_COMP_Enable(COMP_OCPAx); LL_COMP_Lock(COMP_OCPAx); } /* Over current protection phase B */ if (COMP_OCPBx) { LL_COMP_Enable(COMP_OCPBx); LL_COMP_Lock(COMP_OCPBx); } else { /* Nothing to do */ } /* Over current protection phase C */ if (COMP_OCPCx) { LL_COMP_Enable(COMP_OCPCx); LL_COMP_Lock(COMP_OCPCx); } else { /* Nothing to do */ } /* Over voltage protection */ if (COMP_OVPx) { /* Inverting input*/ if (pHandle->pParams_str->bCompOVPInvInput_MODE != EXT_MODE) { if (LL_COMP_GetInputMinus(COMP_OVPx) == LL_COMP_INPUT_MINUS_DAC1_CH1) { R3_3_G4XX_SetAOReferenceVoltage(LL_DAC_CHANNEL_1, (uint16_t)(pHandle->pParams_str->hDAC_OVP_Threshold)); } #if defined(DAC_CHANNEL2_SUPPORT) else if (LL_COMP_GetInputMinus(COMP_OVPx) == LL_COMP_INPUT_MINUS_DAC1_CH2) { R3_3_G4XX_SetAOReferenceVoltage(LL_DAC_CHANNEL_2, (uint16_t)(pHandle->pParams_str->hDAC_OVP_Threshold)); } #endif else { /* Nothing to do */ } } /* Wait to stabilize DAC voltage */ volatile uint16_t waittime = 0u; for (waittime = 0u; waittime < 1000u; waittime++) {} /* Output */ LL_COMP_Enable(COMP_OVPx); LL_COMP_Lock(COMP_OVPx); } if (pHandle->_Super.bMotor == M1) { /* - Exit from deep-power-down mode */ LL_ADC_DisableDeepPowerDown(pHandle->pParams_str->ADCx_A); LL_ADC_DisableDeepPowerDown(pHandle->pParams_str->ADCx_B); LL_ADC_DisableDeepPowerDown(pHandle->pParams_str->ADCx_C); if (LL_ADC_IsInternalRegulatorEnabled(pHandle->pParams_str->ADCx_A) == 0) { /* Enable ADC internal voltage regulator */ LL_ADC_EnableInternalRegulator(pHandle->pParams_str->ADCx_A); LL_ADC_EnableInternalRegulator(pHandle->pParams_str->ADCx_B); LL_ADC_EnableInternalRegulator(pHandle->pParams_str->ADCx_C); /* Wait for Regulator Startup time */ /* Note: Variable divided by 2 to compensate partially */ /* CPU processing cycles, scaling in us split to not */ /* exceed 32 bits register capacity and handle low frequency. */ uint32_t wait_loop_index = ((LL_ADC_DELAY_INTERNAL_REGUL_STAB_US / 10UL) * (SystemCoreClock / (100000UL * 2UL))); while (wait_loop_index != 0UL) { wait_loop_index--; } } else { /* Nothing to do */ } LL_ADC_StartCalibration(pHandle->pParams_str->ADCx_A, LL_ADC_SINGLE_ENDED); while (LL_ADC_IsCalibrationOnGoing(pHandle->pParams_str->ADCx_A)) {} LL_ADC_StartCalibration(pHandle->pParams_str->ADCx_B, LL_ADC_SINGLE_ENDED); while (LL_ADC_IsCalibrationOnGoing(pHandle->pParams_str->ADCx_B)) {} LL_ADC_StartCalibration(pHandle->pParams_str->ADCx_C, LL_ADC_SINGLE_ENDED); while (LL_ADC_IsCalibrationOnGoing(pHandle->pParams_str->ADCx_C)) {} if ((pHandle->pParams_str->regconvADCx != pHandle->pParams_str->ADCx_A) && (pHandle->pParams_str->regconvADCx != pHandle->pParams_str->ADCx_B) && (pHandle->pParams_str->regconvADCx != pHandle->pParams_str->ADCx_C)) { LL_ADC_EnableInternalRegulator(pHandle->pParams_str->regconvADCx); /* Wait for Regulator Startup time, once for both */ uint16_t waittime = 0u; for (waittime = 0u; waittime < 65000u; waittime++) {} LL_ADC_StartCalibration(pHandle->pParams_str->regconvADCx, LL_ADC_SINGLE_ENDED); while (LL_ADC_IsCalibrationOnGoing(pHandle->pParams_str->regconvADCx)) {} } else { /* Nothing to do */ } /* Enable ADCx_A, ADCx_B and ADCx_C*/ LL_ADC_Enable(pHandle->pParams_str->ADCx_A); LL_ADC_Enable(pHandle->pParams_str->ADCx_B); LL_ADC_Enable(pHandle->pParams_str->ADCx_C); } else { /* already done by the first motor */ } if ((pHandle->pParams_str->regconvADCx != pHandle->pParams_str->ADCx_A) && (pHandle->pParams_str->regconvADCx != pHandle->pParams_str->ADCx_B) && (pHandle->pParams_str->regconvADCx != pHandle->pParams_str->ADCx_C)) { LL_ADC_Enable(pHandle->pParams_str->regconvADCx); } /* reset regular conversion sequencer length set by cubeMX */ LL_ADC_REG_SetSequencerLength(pHandle->pParams_str->regconvADCx, LL_ADC_REG_SEQ_SCAN_DISABLE); pHandle->wADC_JSQR_phA = pHandle->pParams_str->ADCx_A->JSQR; pHandle->wADC_JSQR_phB = pHandle->pParams_str->ADCx_B->JSQR; pHandle->wADC_JSQR_phC = pHandle->pParams_str->ADCx_C->JSQR; CLEAR_BIT(pHandle->wADC_JSQR_phA, ADC_JSQR_JEXTEN); CLEAR_BIT(pHandle->wADC_JSQR_phB, ADC_JSQR_JEXTEN); CLEAR_BIT(pHandle->wADC_JSQR_phC, ADC_JSQR_JEXTEN); LL_ADC_INJ_SetQueueMode(pHandle->pParams_str->ADCx_A, LL_ADC_INJ_QUEUE_2CONTEXTS_END_EMPTY); LL_ADC_INJ_SetQueueMode(pHandle->pParams_str->ADCx_B, LL_ADC_INJ_QUEUE_2CONTEXTS_END_EMPTY); LL_ADC_INJ_SetQueueMode(pHandle->pParams_str->ADCx_C, LL_ADC_INJ_QUEUE_2CONTEXTS_END_EMPTY); #if NOT_IMPLEMENTED pHandle->pParams_str->ADCx_A->JSQR = pHandle->wADC_JSQR_phA + LL_ADC_INJ_TRIG_EXT_RISING; pHandle->pParams_str->ADCx_B->JSQR = pHandle->wADC_JSQR_phB + LL_ADC_INJ_TRIG_EXT_RISING; pHandle->pParams_str->ADCx_C->JSQR = pHandle->wADC_JSQR_phC + LL_ADC_INJ_TRIG_EXT_RISING; #endif LL_ADC_INJ_StartConversion(pHandle->pParams_str->ADCx_A); LL_ADC_INJ_StartConversion(pHandle->pParams_str->ADCx_B); LL_ADC_INJ_StartConversion(pHandle->pParams_str->ADCx_C); #if NOT_IMPLEMENTED LL_TIM_OC_DisablePreload( TIMx, LL_TIM_CHANNEL_CH4 ); LL_TIM_OC_SetCompareCH4( TIMx, 0xFFFFu ); LL_TIM_OC_SetCompareCH4( TIMx, 0x0u ); LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH4 ); while ( LL_ADC_IsActiveFlag_JEOS( pHandle->pParams_str->ADCx_A ) == RESET ) {} while ( LL_ADC_IsActiveFlag_JEOS( pHandle->pParams_str->ADCx_B ) == RESET ) {} while ( LL_ADC_IsActiveFlag_JEOS( pHandle->pParams_str->ADCx_C ) == RESET ) {} /* ADCx_ Injected conversions end interrupt enabling */ LL_ADC_ClearFlag_JEOS( pHandle->pParams_str->ADCx_A ); LL_ADC_ClearFlag_JEOS( pHandle->pParams_str->ADCx_B ); LL_ADC_ClearFlag_JEOS( pHandle->pParams_str->ADCx_C ); #endif /* TODO: check this It pending */ NVIC_ClearPendingIRQ(ADC3_IRQn); LL_ADC_EnableIT_JEOS(pHandle->pParams_str->ADCx_C); /* Clear the flags */ pHandle->_Super.DTTest = 0u; pHandle->_Super.DTCompCnt = pHandle->_Super.hDTCompCnt; } } /** * @brief Initializes @p TIMx peripheral with @p pHdl handler for PWM generation. * */ __weak void R3_3_G4XX_TIMxInit(TIM_TypeDef *TIMx, PWMC_Handle_t *pHdl) { PWMC_R3_3_G4_Handle_t *pHandle = (PWMC_R3_3_G4_Handle_t *)pHdl; /* disable main TIM counter to ensure * a synchronous start by TIM2 trigger */ LL_TIM_DisableCounter(TIMx); /* Enables the TIMx Preload on CC1 Register */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH1); /* Enables the TIMx Preload on CC2 Register */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH2); /* Enables the TIMx Preload on CC3 Register */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH3); /* Enables the TIMx Preload on CC4 Register */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH4); LL_TIM_ClearFlag_BRK(TIMx); LL_TIM_ClearFlag_BRK2(TIMx); LL_TIM_EnableIT_BRK(TIMx); /* Prepare timer for synchronization */ LL_TIM_GenerateEvent_UPDATE(TIMx); if (pHandle->pParams_str->bFreqRatio == 2u) { if (pHandle->pParams_str->bIsHigherFreqTim == HIGHER_FREQ) { if (pHandle->pParams_str->RepetitionCounter == 3u) { /* Set TIMx repetition counter to 1 */ LL_TIM_SetRepetitionCounter(TIMx, 1); LL_TIM_GenerateEvent_UPDATE(TIMx); /* Repetition counter will be set to 3 at next Update */ LL_TIM_SetRepetitionCounter(TIMx, 3); } else { /* Nothing to do */ } } else { /* Nothing to do */ } LL_TIM_SetCounter(TIMx, (uint32_t)(pHandle->Half_PWMPeriod) - 1u); } else /* bFreqRatio equal to 1 or 3 */ { if (pHandle->_Super.bMotor == M1) { if (pHandle->pParams_str->RepetitionCounter == 1u) { LL_TIM_SetCounter(TIMx, (uint32_t)(pHandle->Half_PWMPeriod) - 1u); } else if (pHandle->pParams_str->RepetitionCounter == 3u) { /* Set TIMx repetition counter to 1 */ LL_TIM_SetRepetitionCounter(TIMx, 1); LL_TIM_GenerateEvent_UPDATE(TIMx); /* Repetition counter will be set to 3 at next Update */ LL_TIM_SetRepetitionCounter(TIMx, 3); } else { /* Nothing to do */ } } else { /* Nothing to do */ } } /* Enable PWM channel */ LL_TIM_CC_EnableChannel(TIMx, TIMxCCER_MASK_CH123); } /** * @brief Sets the calibrated offsets. * * @param pHdl: Handler of the current instance of the PWM component. * @param offsets: Pointer to the structure that contains the offsets for each phase. */ __weak void R3_3_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_R3_3_Handle_t *pHandle = (PWMC_R3_3_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 pHandle->PhaseAOffset = offsets->phaseAOffset; pHandle->PhaseBOffset = offsets->phaseBOffset; pHandle->PhaseCOffset = offsets->phaseCOffset; pHdl->offsetCalibStatus = true; } /** * @brief Reads the calibrated @p offsets stored in @p pHdl. * */ __weak void R3_3_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_R3_3_Handle_t *pHandle = (PWMC_R3_3_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 offsets->phaseAOffset = pHandle->PhaseAOffset; offsets->phaseBOffset = pHandle->PhaseBOffset; offsets->phaseCOffset = pHandle->PhaseCOffset; } /** * @brief Stores into the @p pHdl handler the voltage present on Ia and * Ib current feedback analog channels when no current is flowing into the * motor. * */ __weak void R3_3_G4XX_CurrentReadingCalibration(PWMC_Handle_t *pHdl) { PWMC_R3_3_G4_Handle_t *pHandle = (PWMC_R3_3_G4_Handle_t *)pHdl; TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; if (false == pHandle->_Super.offsetCalibStatus) { pHandle-> wPhaseAOffset = 0u; pHandle-> wPhaseBOffset = 0u; pHandle-> wPhaseCOffset = 0u; pHandle->bIndex = 0u; /* It forces inactive level on TIMx CHy and CHyN */ LL_TIM_CC_DisableChannel(TIMx, TIMxCCER_MASK_CH123); /* Offset calibration for all phases */ /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R3_3_G4XX_HFCurrentsCalibrationABC; R3_3_G4XX_SwitchOnPWM( &pHandle->_Super ); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd(TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->bIndex); R3_3_G4XX_SwitchOffPWM( &pHandle->_Super ); pHandle->wPhaseAOffset >>= 4; pHandle->wPhaseBOffset >>= 4; pHandle->wPhaseCOffset >>= 4; if (0U == pHandle->_Super.SWerror) { pHandle->_Super.offsetCalibStatus = true; } else { /* nothing to do */ } /* Change back function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R3_3_G4XX_GetPhaseCurrents; } else { /* Nothing to do */ } /* It over write TIMx CCRy wrongly written by FOC during calibration so as to force 50% duty cycle on the three inverer legs */ /* Disable TIMx preload */ LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH1); LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH2); LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH3); LL_TIM_OC_SetCompareCH1(TIMx, pHandle->Half_PWMPeriod); LL_TIM_OC_SetCompareCH2(TIMx, pHandle->Half_PWMPeriod); LL_TIM_OC_SetCompareCH3(TIMx, pHandle->Half_PWMPeriod); /* Enable TIMx preload */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH1); LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH2); LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH3); /* It re-enable drive of TIMx CHy and CHyN by TIMx CHyRef*/ LL_TIM_CC_EnableChannel(TIMx, TIMxCCER_MASK_CH123); pHandle->_Super.BrakeActionLock = false; } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /** * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p pStator_Currents Curr_Components format. * */ __weak void R3_3_G4XX_GetPhaseCurrents(PWMC_Handle_t *pHdl, Curr_Components *pStator_Currents) { int32_t wAux; uint16_t phaseA; uint16_t phaseB; uint16_t phaseC; uint8_t bSector; static uint16_t i; PWMC_R3_3_G4_Handle_t *pHandle = (PWMC_R3_3_G4_Handle_t *)pHdl; /* Reset the SOFOC flag to indicate the start of FOC algorithm*/ pHandle->bSoFOC = 0u; phaseA = (uint16_t)(pHandle->pParams_str->ADCx_A->JDR1); phaseB = (uint16_t)(pHandle->pParams_str->ADCx_B->JDR1); phaseC = (uint16_t)(pHandle->pParams_str->ADCx_C->JDR1); bSector = (uint8_t)pHandle->_Super.hSector; switch (bSector) { case SECTOR_4: case SECTOR_5: { /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ wAux = (int32_t)(pHandle->wPhaseAOffset) - (int32_t)(phaseA); /* Saturation of Ia */ if (wAux < -INT16_MAX) { pStator_Currents->qI_Component1 = -INT16_MAX; } else if (wAux > INT16_MAX) { pStator_Currents->qI_Component1 = INT16_MAX; } else { pStator_Currents->qI_Component1 = (int16_t)wAux; } /* Ib = PhaseBOffset - ADC converted value) */ wAux = (int32_t)(pHandle->wPhaseBOffset) - (int32_t)(phaseB); /* Saturation of Ib */ if (wAux < -INT16_MAX) { pStator_Currents->qI_Component2 = -INT16_MAX; } else if (wAux > INT16_MAX) { pStator_Currents->qI_Component2 = INT16_MAX; } else { pStator_Currents->qI_Component2 = (int16_t)wAux; } break; } case SECTOR_6: case SECTOR_1: { /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ wAux = (int32_t)(pHandle->wPhaseBOffset) - (int32_t)(phaseB); /* Saturation of Ib */ if (wAux < -INT16_MAX) { pStator_Currents->qI_Component2 = -INT16_MAX; } else if (wAux > INT16_MAX) { pStator_Currents->qI_Component2 = INT16_MAX; } else { pStator_Currents->qI_Component2 = (int16_t)wAux; } /* Ia = -Ic -Ib */ wAux = (int32_t)(phaseC) - (int32_t)(pHandle->wPhaseCOffset); /* -Ic */ wAux -= (int32_t)pStator_Currents->qI_Component2; /* Ia */ /* Saturation of Ia */ if (wAux > INT16_MAX) { pStator_Currents->qI_Component1 = INT16_MAX; } else if (wAux < -INT16_MAX) { pStator_Currents->qI_Component1 = -INT16_MAX; } else { pStator_Currents->qI_Component1 = (int16_t)wAux; } break; } case SECTOR_2: case SECTOR_3: { /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ wAux = (int32_t)(pHandle->wPhaseAOffset) - (int32_t)(phaseA); /* Saturation of Ia */ if (wAux < -INT16_MAX) { pStator_Currents->qI_Component1 = -INT16_MAX; } else if (wAux > INT16_MAX) { pStator_Currents->qI_Component1 = INT16_MAX; } else { pStator_Currents->qI_Component1 = (int16_t)wAux; } /* Ib = -Ic -Ia */ wAux = (int32_t)(phaseC) - (int32_t)(pHandle->wPhaseCOffset); /* -Ic */ wAux -= (int32_t)pStator_Currents->qI_Component1; /* Ib */ /* Saturation of Ib */ if (wAux > INT16_MAX) { pStator_Currents->qI_Component2 = INT16_MAX; } else if (wAux < -INT16_MAX) { pStator_Currents->qI_Component2 = -INT16_MAX; } else { pStator_Currents->qI_Component2 = (int16_t)wAux; } break; } default: break; } pHandle->_Super.hIa = pStator_Currents->qI_Component1; pHandle->_Super.hIb = pStator_Currents->qI_Component2; pHandle->_Super.hIc = -pStator_Currents->qI_Component1 - pStator_Currents->qI_Component2; } /** * @brief Implementation of PWMC_GetPhaseCurrents to be performed during calibration. * * It sums up injected conversion data into PhaseAOffset, wPhaseBOffset and wPhaseCOffset * to compute the offset introduced in the current feedback network. It is required to * properly configure ADC inputs before in order to enable offset computation. * * @param pHdl: Pointer on the target component instance. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ __weak void R3_3_G4XX_HFCurrentsCalibrationABC(PWMC_Handle_t *pHdl, Curr_Components *pStator_Currents) { PWMC_R3_3_G4_Handle_t *pHandle = (PWMC_R3_3_G4_Handle_t *)pHdl; /* Reset the SOFOC flag to indicate the start of FOC algorithm*/ pHandle->bSoFOC = 0u; if (pHandle->bIndex < NB_CONVERSIONS) { pHandle-> wPhaseAOffset += pHandle->pParams_str->ADCx_A->JDR1; pHandle-> wPhaseBOffset += pHandle->pParams_str->ADCx_B->JDR1; pHandle-> wPhaseCOffset += pHandle->pParams_str->ADCx_C->JDR1; pHandle->bIndex++; } else { /* Nothing to do */ } /* during offset calibration no current is flowing in the phases */ pStator_Currents->qI_Component1 = 0; pStator_Currents->qI_Component2 = 0; } /** * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors of driving section. It has to be * called each motor start-up when using high voltage drivers. * * @param pHdl: Handler of the current instance of the PWM component * @param ticks: Timer ticks value to be applied * Min value: 0 (low sides ON) * Max value: PWM_PERIOD_CYCLES/2 (low sides OFF) */ __weak void R3_3_G4XX_TurnOnLowSides(PWMC_Handle_t *pHdl, uint32_t ticks) { PWMC_R3_3_G4_Handle_t *pHandle = (PWMC_R3_3_G4_Handle_t *)pHdl; TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.bTurnOnLowSidesAction = true; /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE(pHandle->pParams_str->TIMx); /*Turn on the three low side switches */ LL_TIM_OC_SetCompareCH1(TIMx, ticks); LL_TIM_OC_SetCompareCH2(TIMx, ticks); LL_TIM_OC_SetCompareCH3(TIMx, ticks); /* Wait until next update */ while (0U == LL_TIM_IsActiveFlag_UPDATE(TIMx)) { /* Nothing to do */ } /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs(TIMx); if ((pHandle->_Super.LowSideOutputs) == ES_GPIO) { LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } } /** * @brief Enables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_3_G4XX_SwitchOnPWM(PWMC_Handle_t *pHdl) { PWMC_R3_3_G4_Handle_t *pHandle = (PWMC_R3_3_G4_Handle_t *)pHdl; TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.bTurnOnLowSidesAction = false; /* Set all duty to 50% */ /* Set ch4 for triggering */ /* Clear Update Flag */ LL_TIM_OC_SetCompareCH1(TIMx, (uint32_t)(pHandle->Half_PWMPeriod) >> 1); LL_TIM_OC_SetCompareCH2(TIMx, (uint32_t)(pHandle->Half_PWMPeriod) >> 1); LL_TIM_OC_SetCompareCH3(TIMx, (uint32_t)(pHandle->Half_PWMPeriod) >> 1); LL_TIM_OC_SetCompareCH4(TIMx, (uint32_t)(pHandle->Half_PWMPeriod) - 5u); /* wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE(TIMx); while (0U == LL_TIM_IsActiveFlag_UPDATE(TIMx)) { /* Nothing to do */ } LL_TIM_ClearFlag_UPDATE(TIMx); /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE; LL_TIM_EnableAllOutputs(TIMx); if ((pHandle->_Super.LowSideOutputs) == ES_GPIO) { if ((TIMx->CCER & TIMxCCER_MASK_CH123) != 0u) { LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_SetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } } else { /* Nothing to do */ } pHandle->pParams_str->ADCx_A->JSQR = pHandle->wADC_JSQR_phA + LL_ADC_INJ_TRIG_EXT_RISING; pHandle->pParams_str->ADCx_B->JSQR = pHandle->wADC_JSQR_phB + LL_ADC_INJ_TRIG_EXT_RISING; pHandle->pParams_str->ADCx_C->JSQR = pHandle->wADC_JSQR_phC + LL_ADC_INJ_TRIG_EXT_RISING; /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE(TIMx); /* Enable Update IRQ */ LL_TIM_EnableIT_UPDATE(TIMx); } /** * @brief Disables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_3_G4XX_SwitchOffPWM(PWMC_Handle_t *pHdl) { PWMC_R3_3_G4_Handle_t *pHandle = (PWMC_R3_3_G4_Handle_t *)pHdl; TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; /* Disable UPDATE ISR */ LL_TIM_DisableIT_UPDATE(TIMx); pHandle->_Super.bTurnOnLowSidesAction = false; /* Main PWM Output Disable */ LL_TIM_DisableAllOutputs(TIMx); if (pHandle->_Super.BrakeActionLock == true) { /* Nothing to do */ } else { if ((pHandle->_Super.LowSideOutputs) == ES_GPIO) { LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin); LL_GPIO_ResetOutputPin(pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin); } else { /* nothing to do */ } } /* Clear the JSAQR register queue */ LL_ADC_INJ_StopConversion(pHandle->pParams_str->ADCx_A); LL_ADC_INJ_StopConversion(pHandle->pParams_str->ADCx_B); LL_ADC_INJ_StopConversion(pHandle->pParams_str->ADCx_C); LL_ADC_INJ_StartConversion(pHandle->pParams_str->ADCx_A); LL_ADC_INJ_StartConversion(pHandle->pParams_str->ADCx_B); LL_ADC_INJ_StartConversion(pHandle->pParams_str->ADCx_C); /* wait for a new PWM period to flush last HF task */ LL_TIM_ClearFlag_UPDATE(TIMx); while (0U == LL_TIM_IsActiveFlag_UPDATE(TIMx)) { /* Nothing to do */ } LL_TIM_ClearFlag_UPDATE(TIMx); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /** * @brief Writes into peripheral registers the new duty cycles and sampling point. * * @param pHdl: Handler of the current instance of the PWM component. * @param hCCR4Reg: New capture/compare register value, written in timer clock counts. * @retval uint16_t Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ __weak uint16_t R3_3_G4XX_WriteTIMRegisters(PWMC_Handle_t *pHdl, uint16_t hCCR4Reg) { uint16_t hAux; PWMC_R3_3_G4_Handle_t *pHandle = (PWMC_R3_3_G4_Handle_t *)pHdl; TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; LL_TIM_OC_SetCompareCH1(TIMx, pHandle->_Super.hCntPhA); LL_TIM_OC_SetCompareCH2(TIMx, pHandle->_Super.hCntPhB); LL_TIM_OC_SetCompareCH3(TIMx, pHandle->_Super.hCntPhC); __LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH4); LL_TIM_OC_SetCompareCH4(TIMx, 0xFFFFu); __LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH4); LL_TIM_OC_SetCompareCH4(TIMx, hCCR4Reg); pHandle->pParams_str->ADCx_A->JSQR = pHandle->wADC_JSQR_phA + pHandle->ADC_ExternalPolarityInjected; pHandle->pParams_str->ADCx_B->JSQR = pHandle->wADC_JSQR_phB + pHandle->ADC_ExternalPolarityInjected; pHandle->pParams_str->ADCx_C->JSQR = pHandle->wADC_JSQR_phC + pHandle->ADC_ExternalPolarityInjected; /* Limit for update event */ /* Check the status of SOFOC flag. If it is set, an update event has occurred and thus the FOC rate is too high */ if (pHandle->bSoFOC != 0u) { hAux = MC_DURATION; } else { hAux = MC_NO_ERROR; } if (pHandle->_Super.SWerror == 1u) { hAux = MC_DURATION; pHandle->_Super.SWerror = 0u; } else { /* Nothing to do */ } return (hAux); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /** * @brief Configures the ADC for the current sampling related to sector 1. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval uint16_t Return value of R3_1_WriteTIMRegisters. */ __weak uint16_t R3_3_G4XX_SetADCSampPointSect1(PWMC_Handle_t *pHdl) { uint16_t hCntSmp; uint16_t hDeltaDuty; PWMC_R3_3_G4_Handle_t *pHandle = (PWMC_R3_3_G4_Handle_t *)pHdl; TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; pHandle->ADC_ExternalPolarityInjected = LL_ADC_INJ_TRIG_EXT_RISING; /* Verify that sampling is possible in the middle of PWM by checking the smallest duty cycle * in the sector 1 (i.e phase A duty cycle) */ if ((uint16_t)(pHandle->Half_PWMPeriod - pHandle->_Super.hCntPhA) > pHandle->pParams_str->hTafter) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled which corresponds * to sector 4 */ pHandle->_Super.hSector = SECTOR_4; /* set sampling point trigger in the middle of PWM period */ hCntSmp = (uint32_t)(pHandle->Half_PWMPeriod) - 1u; } else { /* In this case it is necessary to convert phases with Maximum and variable complementary duty cycle.*/ /* ADC Injected sequence configuration. The stator phase with minimum value of complementary duty cycle is set as first. In every sector there is always one phase with maximum complementary duty, one with minimum complementary duty and one with variable complementary duty. In this case, phases with variable complementary duty and with maximum duty are converted and the first will be always the phase with variable complementary duty cycle */ hDeltaDuty = (uint16_t)(pHandle->_Super.hCntPhA - pHandle->_Super.hCntPhB); /* Definition of crossing point */ if (hDeltaDuty > ((uint16_t)(pHandle->Half_PWMPeriod - pHandle->_Super.hCntPhA) * 2u)) { hCntSmp = pHandle->_Super.hCntPhA - pHandle->pParams_str->hTbefore; } else { hCntSmp = pHandle->_Super.hCntPhA + pHandle->pParams_str->hTafter; if (hCntSmp >= pHandle->Half_PWMPeriod) { /* Set CC4 as PWM mode 1 */ pHandle->ADC_ExternalPolarityInjected = LL_ADC_INJ_TRIG_EXT_FALLING; hCntSmp = (2u * pHandle->Half_PWMPeriod) - hCntSmp - 1u; } else { /* Nothing to do */ } } } return (R3_3_G4XX_WriteTIMRegisters(&pHandle->_Super, hCntSmp)); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /** * @brief Configures the ADC for the current sampling related to sector 2. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHandle: Handler of the current instance of the PWM component. * @retval uint16_t Return value of R3_1_WriteTIMRegisters. */ __weak uint16_t R3_3_G4XX_SetADCSampPointSect2(PWMC_Handle_t *pHdl) { uint16_t hCntSmp; uint16_t hDeltaDuty; PWMC_R3_3_G4_Handle_t *pHandle = (PWMC_R3_3_G4_Handle_t *)pHdl; TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; pHandle->ADC_ExternalPolarityInjected = LL_ADC_INJ_TRIG_EXT_RISING; /* Verify that sampling is possible in the middle of PWM by checking the smallest duty cycle * in the sector 2 (i.e phase B duty cycle) */ if ((uint16_t)(pHandle->Half_PWMPeriod - pHandle->_Super.hCntPhB) > pHandle->pParams_str->hTafter) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled which corresponds * to sector 4 */ pHandle->_Super.hSector = SECTOR_4; /* set sampling point trigger in the middle of PWM period */ hCntSmp = (uint32_t)(pHandle->Half_PWMPeriod) - 1u; } else { /* In this case it is necessary to convert phases with Maximum and variable complementary duty cycle.*/ /* ADC Injected sequence configuration. The stator phase with minimum value of complementary duty cycle is set as first. In every sector there is always one phase with maximum complementary duty, one with minimum complementary duty and one with variable complementary duty. In this case, phases with variable complementary duty and with maximum duty are converted and the first will be always the phase with variable complementary duty cycle */ hDeltaDuty = (uint16_t)(pHandle->_Super.hCntPhB - pHandle->_Super.hCntPhA); /* Definition of crossing point */ if (hDeltaDuty > ((uint16_t)(pHandle->Half_PWMPeriod - pHandle->_Super.hCntPhB) * 2u)) { hCntSmp = pHandle->_Super.hCntPhB - pHandle->pParams_str->hTbefore; } else { hCntSmp = pHandle->_Super.hCntPhB + pHandle->pParams_str->hTafter; if (hCntSmp >= pHandle->Half_PWMPeriod) { /* Set CC4 as PWM mode 1 */ pHandle->ADC_ExternalPolarityInjected = LL_ADC_INJ_TRIG_EXT_FALLING; hCntSmp = (2u * pHandle->Half_PWMPeriod) - hCntSmp - 1u; } else { /* Nothing to do */ } } } return (R3_3_G4XX_WriteTIMRegisters(&pHandle->_Super, hCntSmp)); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /** * @brief Configures the ADC for the current sampling related to sector 3. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHandle: Handler of the current instance of the PWM component. * @retval uint16_t Return value of R3_1_WriteTIMRegisters. */ __weak uint16_t R3_3_G4XX_SetADCSampPointSect3(PWMC_Handle_t *pHdl) { uint16_t hCntSmp; uint16_t hDeltaDuty; PWMC_R3_3_G4_Handle_t *pHandle = (PWMC_R3_3_G4_Handle_t *)pHdl; TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; pHandle->ADC_ExternalPolarityInjected = LL_ADC_INJ_TRIG_EXT_RISING; /* Verify that sampling is possible in the middle of PWM by checking the smallest duty cycle * in the sector 3 (i.e phase B duty cycle) */ if ((uint16_t)(pHandle->Half_PWMPeriod - pHandle->_Super.hCntPhB) > pHandle->pParams_str->hTafter) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled which corresponds * to sector 4 */ pHandle->_Super.hSector = SECTOR_4; /* set sampling point trigger in the middle of PWM period */ hCntSmp = (uint32_t)(pHandle->Half_PWMPeriod) - 1u; } else { /* In this case it is necessary to convert phases with Maximum and variable complementary duty cycle.*/ /* ADC Injected sequence configuration. The stator phase with minimum value of complementary duty cycle is set as first. In every sector there is always one phase with maximum complementary duty, one with minimum complementary duty and one with variable complementary duty. In this case, phases with variable complementary duty and with maximum duty are converted and the first will be always the phase with variable complementary duty cycle */ hDeltaDuty = (uint16_t)(pHandle->_Super.hCntPhB - pHandle->_Super.hCntPhC); /* Definition of crossing point */ if (hDeltaDuty > ((uint16_t)(pHandle->Half_PWMPeriod - pHandle->_Super.hCntPhB) * 2u)) { hCntSmp = pHandle->_Super.hCntPhB - pHandle->pParams_str->hTbefore; } else { hCntSmp = pHandle->_Super.hCntPhB + pHandle->pParams_str->hTafter; if (hCntSmp >= pHandle->Half_PWMPeriod) { /* Set CC4 as PWM mode 1 */ pHandle->ADC_ExternalPolarityInjected = LL_ADC_INJ_TRIG_EXT_FALLING; hCntSmp = (2u * pHandle->Half_PWMPeriod) - hCntSmp - 1u; } else { /* Nothing to do */ } } } return (R3_3_G4XX_WriteTIMRegisters(&pHandle->_Super, hCntSmp)); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /** * @brief Configures the ADC for the current sampling related to sector 4. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHandle: Handler of the current instance of the PWM component. * @retval uint16_t Return value of R3_1_WriteTIMRegisters. */ __weak uint16_t R3_3_G4XX_SetADCSampPointSect4(PWMC_Handle_t *pHdl) { uint16_t hCntSmp; uint16_t hDeltaDuty; PWMC_R3_3_G4_Handle_t *pHandle = (PWMC_R3_3_G4_Handle_t *)pHdl; TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; pHandle->ADC_ExternalPolarityInjected = LL_ADC_INJ_TRIG_EXT_RISING; /* Verify that sampling is possible in the middle of PWM by checking the smallest duty cycle * in the sector 4 (i.e phase C duty cycle) */ if ((uint16_t)(pHandle->Half_PWMPeriod - pHandle->_Super.hCntPhC) > pHandle->pParams_str->hTafter) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled which corresponds * to sector 4 */ pHandle->_Super.hSector = SECTOR_4; /* set sampling point trigger in the middle of PWM period */ hCntSmp = (uint32_t)(pHandle->Half_PWMPeriod) - 1u; } else { /* In this case it is necessary to convert phases with Maximum and variable complementary duty cycle.*/ /* ADC Injected sequence configuration. The stator phase with minimum value of complementary duty cycle is set as first. In every sector there is always one phase with maximum complementary duty, one with minimum complementary duty and one with variable complementary duty. In this case, phases with variable complementary duty and with maximum duty are converted and the first will be always the phase with variable complementary duty cycle */ hDeltaDuty = (uint16_t)(pHandle->_Super.hCntPhC - pHandle->_Super.hCntPhB); /* Definition of crossing point */ if (hDeltaDuty > ((uint16_t)(pHandle->Half_PWMPeriod - pHandle->_Super.hCntPhC) * 2u)) { hCntSmp = pHandle->_Super.hCntPhC - pHandle->pParams_str->hTbefore; } else { hCntSmp = pHandle->_Super.hCntPhC + pHandle->pParams_str->hTafter; if (hCntSmp >= pHandle->Half_PWMPeriod) { /* Set CC4 as PWM mode 1 */ pHandle->ADC_ExternalPolarityInjected = LL_ADC_INJ_TRIG_EXT_FALLING; hCntSmp = (2u * pHandle->Half_PWMPeriod) - hCntSmp - 1u; } else { /* Nothing to do */ } } } return (R3_3_G4XX_WriteTIMRegisters(&pHandle->_Super, hCntSmp)); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /** * @brief Configures the ADC for the current sampling related to sector 5. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHandle: Handler of the current instance of the PWM component. * @retval uint16_t Return value of R3_1_WriteTIMRegisters. */ __weak uint16_t R3_3_G4XX_SetADCSampPointSect5(PWMC_Handle_t *pHdl) { uint16_t hCntSmp; uint16_t hDeltaDuty; PWMC_R3_3_G4_Handle_t *pHandle = (PWMC_R3_3_G4_Handle_t *)pHdl; TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; pHandle->ADC_ExternalPolarityInjected = LL_ADC_INJ_TRIG_EXT_RISING; /* Verify that sampling is possible in the middle of PWM by checking the smallest duty cycle * in the sector 5 (i.e phase C duty cycle) */ if ((uint16_t)(pHandle->Half_PWMPeriod - pHandle->_Super.hCntPhC) > pHandle->pParams_str->hTafter) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB, AC or BC) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled which corresponds * to sector 4 */ pHandle->_Super.hSector = SECTOR_4; /* set sampling point trigger in the middle of PWM period */ hCntSmp = (uint32_t)(pHandle->Half_PWMPeriod) - 1u; } else { /* In this case it is necessary to convert phases with Maximum and variable complementary duty cycle.*/ /* ADC Injected sequence configuration. The stator phase with minimum value of complementary duty cycle is set as first. In every sector there is always one phase with maximum complementary duty, one with minimum complementary duty and one with variable complementary duty. In this case, phases with variable complementary duty and with maximum duty are converted and the first will be always the phase with variable complementary duty cycle */ hDeltaDuty = (uint16_t)(pHandle->_Super.hCntPhC - pHandle->_Super.hCntPhA); /* Definition of crossing point */ if (hDeltaDuty > ((uint16_t)(pHandle->Half_PWMPeriod - pHandle->_Super.hCntPhC) * 2u)) { hCntSmp = pHandle->_Super.hCntPhC - pHandle->pParams_str->hTbefore; } else { hCntSmp = pHandle->_Super.hCntPhC + pHandle->pParams_str->hTafter; if (hCntSmp >= pHandle->Half_PWMPeriod) { /* Set CC4 as PWM mode 1 */ pHandle->ADC_ExternalPolarityInjected = LL_ADC_INJ_TRIG_EXT_FALLING; hCntSmp = (2u * pHandle->Half_PWMPeriod) - hCntSmp - 1u; } else { /* nothing to do */ } } } return (R3_3_G4XX_WriteTIMRegisters(&pHandle->_Super, hCntSmp)); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /** * @brief Configures the ADC for the current sampling related to sector 6. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHandle: Handler of the current instance of the PWM component. * @retval uint16_t Return value of R3_1_WriteTIMRegisters. */ __weak uint16_t R3_3_G4XX_SetADCSampPointSect6(PWMC_Handle_t *pHdl) { uint16_t hCntSmp; uint16_t hDeltaDuty; PWMC_R3_3_G4_Handle_t *pHandle = (PWMC_R3_3_G4_Handle_t *)pHdl; TIM_TypeDef *TIMx = pHandle->pParams_str->TIMx; pHandle->ADC_ExternalPolarityInjected = LL_ADC_INJ_TRIG_EXT_RISING; /* Verify that sampling is possible in the middle of PWM by checking the smallest duty cycle * in the sector 6 (i.e phase A duty cycle) */ if ((uint16_t)(pHandle->Half_PWMPeriod - pHandle->_Super.hCntPhA) > pHandle->pParams_str->hTafter) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled which corresponds * to sector 4 */ pHandle->_Super.hSector = SECTOR_4; /* set sampling point trigger in the middle of PWM period */ hCntSmp = (uint32_t)(pHandle->Half_PWMPeriod) - 1u; } else { /* In this case it is necessary to convert phases with Maximum and variable complementary duty cycle.*/ /* ADC Injected sequence configuration. The stator phase with minimum value of complementary duty cycle is set as first. In every sector there is always one phase with maximum complementary duty, one with minimum complementary duty and one with variable complementary duty. In this case, phases with variable complementary duty and with maximum duty are converted and the first will be always the phase with variable complementary duty cycle */ hDeltaDuty = (uint16_t)(pHandle->_Super.hCntPhA - pHandle->_Super.hCntPhC); /* Definition of crossing point */ if (hDeltaDuty > ((uint16_t)(pHandle->Half_PWMPeriod - pHandle->_Super.hCntPhA) * 2u)) { hCntSmp = pHandle->_Super.hCntPhA - pHandle->pParams_str->hTbefore; } else { hCntSmp = pHandle->_Super.hCntPhA + pHandle->pParams_str->hTafter; if (hCntSmp >= pHandle->Half_PWMPeriod) { /* Set CC4 as PWM mode 1 */ pHandle->ADC_ExternalPolarityInjected = LL_ADC_INJ_TRIG_EXT_FALLING; hCntSmp = (2u * pHandle->Half_PWMPeriod) - hCntSmp - 1u; } else { /* Nothing to do */ } } } return (R3_3_G4XX_WriteTIMRegisters(&pHandle->_Super, hCntSmp)); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /** * @brief Contains the TIMx Update event interrupt. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void *R3_3_G4XX_TIMx_UP_IRQHandler(PWMC_R3_3_G4_Handle_t *pHandle) { /* Set the SOFOC flag to indicate the execution of Update IRQ*/ pHandle->bSoFOC = 1u; return (&(pHandle->_Super.bMotor)); } /** * @brief Configures the analog output used for protection thresholds. * * @param DAC_Channel: Selected DAC channel. * This parameter can be: * @arg DAC_Channel_1: DAC Channel1 selected. * @arg DAC_Channel_2: DAC Channel2 selected. * @param hDACVref: Value of DAC reference expressed as 16bit unsigned integer. \n * Ex. 0 = 0V ; 65536 = VDD_DAC. */ __weak void R3_3_G4XX_SetAOReferenceVoltage(uint32_t DAC_Channel, uint16_t hDACVref) { if (DAC_Channel == LL_DAC_CHANNEL_2) { LL_DAC_ConvertData12LeftAligned(DAC1, LL_DAC_CHANNEL_2, hDACVref); } else { LL_DAC_ConvertData12LeftAligned(DAC1, LL_DAC_CHANNEL_1, hDACVref); } /* Enable DAC Channel */ LL_DAC_TrigSWConversion(DAC1, DAC_Channel); LL_DAC_Enable(DAC1, DAC_Channel); } /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
53,248
C
34.334439
139
0.652719
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/G4xx/Src/stspin32g4.c
/** ****************************************************************************** * @file stspin32g4.c * @author P. Lombardi, IPC Application Team * @brief Implementation of STSPIN32G4 driver library ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** **/ #if defined(USE_FULL_LL_DRIVER) #include <stm32g4xx_ll_i2c.h> #include <stm32g4xx_ll_gpio.h> #include <stm32g4xx_ll_bus.h> #include <stm32g4xx_ll_cortex.h> #include <stm32g4xx_ll_rcc.h> #include <stm32g4xx_ll_utils.h> #else #include <stm32g4xx_hal.h> #include <stm32g4xx_hal_def.h> #include <stm32g4xx_hal_i2c.h> #endif #include <stdint.h> #include <stdbool.h> #include <stspin32g4.h> #define STSPIN32G4_I2C_TIMEOUT (100u) #define STSPIN32G4_I2C_LOCKCODE (0xDu) #if defined(USE_FULL_LL_DRIVER) #define GD_READY_GPIO_Port GPIOE #define GD_READY_Pin LL_GPIO_PIN_14 #define GD_NFAULT_GPIO_Port GPIOE #define GD_NFAULT_Pin LL_GPIO_PIN_15 #define GD_WAKE_GPIO_Port GPIOE #define GD_WAKE_Pin LL_GPIO_PIN_7 #else #define GD_READY_GPIO_Port GPIOE #define GD_READY_Pin GPIO_PIN_14 #define GD_NFAULT_GPIO_Port GPIOE #define GD_NFAULT_Pin GPIO_PIN_15 #define GD_WAKE_GPIO_Port GPIOE #define GD_WAKE_Pin GPIO_PIN_7 #endif static uint8_t STSPIN32G4_bkupREADY; #if !defined(USE_FULL_LL_DRIVER) extern I2C_HandleTypeDef hi2c3; #endif void SystemClock_Config(void); STSPIN32G4_StatusTypeDef STSPIN32G4_init(STSPIN32G4_HandleTypeDef *hdl) { STSPIN32G4_StatusTypeDef status = STSPIN32G4_OK; if (hdl == NULL) { return STSPIN32G4_ERROR; } #if defined(USE_FULL_LL_DRIVER) LL_GPIO_InitTypeDef GPIO_InitStruct = {0}; hdl->i2cHdl = I2C3; LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_GPIOE); LL_GPIO_SetOutputPin(GD_WAKE_GPIO_Port, GD_WAKE_Pin); GPIO_InitStruct.Pin = GD_WAKE_Pin; GPIO_InitStruct.Mode = LL_GPIO_MODE_OUTPUT; GPIO_InitStruct.OutputType = LL_GPIO_OUTPUT_PUSHPULL; GPIO_InitStruct.Pull = LL_GPIO_PULL_NO; GPIO_InitStruct.Speed = LL_GPIO_SPEED_LOW; LL_GPIO_Init(GD_WAKE_GPIO_Port, &GPIO_InitStruct); GPIO_InitStruct.Pin = GD_NFAULT_Pin; GPIO_InitStruct.Mode = LL_GPIO_MODE_INPUT; GPIO_InitStruct.Pull = LL_GPIO_PULL_UP; LL_GPIO_Init(GD_NFAULT_GPIO_Port, &GPIO_InitStruct); GPIO_InitStruct.Pin = GD_READY_Pin; GPIO_InitStruct.Mode = LL_GPIO_MODE_INPUT; GPIO_InitStruct.Pull = LL_GPIO_PULL_UP; LL_GPIO_Init(GD_READY_GPIO_Port, &GPIO_InitStruct); #else GPIO_InitTypeDef GPIO_InitStruct = {0}; hdl->i2cHdl = &hi2c3; __HAL_RCC_GPIOE_CLK_ENABLE(); HAL_GPIO_WritePin(GD_WAKE_GPIO_Port, GD_WAKE_Pin, GPIO_PIN_SET); GPIO_InitStruct.Pin = GD_WAKE_Pin; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; HAL_GPIO_Init(GD_WAKE_GPIO_Port, &GPIO_InitStruct); GPIO_InitStruct.Pin = GD_NFAULT_Pin; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_PULLUP; HAL_GPIO_Init(GD_NFAULT_GPIO_Port, &GPIO_InitStruct); GPIO_InitStruct.Pin = GD_READY_Pin; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_PULLUP; HAL_GPIO_Init(GD_READY_GPIO_Port, &GPIO_InitStruct); #endif if (status != STSPIN32G4_OK) { return status; } return status; } STSPIN32G4_StatusTypeDef STSPIN32G4_deInit(STSPIN32G4_HandleTypeDef *hdl) { STSPIN32G4_StatusTypeDef status = STSPIN32G4_OK; #if defined(USE_FULL_LL_DRIVER) LL_GPIO_InitTypeDef GPIO_InitStruct = {0}; status = (STSPIN32G4_StatusTypeDef) LL_I2C_DeInit(hdl->i2cHdl); GPIO_InitStruct.Mode = LL_GPIO_MODE_ANALOG; GPIO_InitStruct.Pull = LL_GPIO_PULL_NO; GPIO_InitStruct.Pin = GD_WAKE_Pin; LL_GPIO_Init(GD_WAKE_GPIO_Port, &GPIO_InitStruct); GPIO_InitStruct.Pin = GD_NFAULT_Pin; LL_GPIO_Init(GD_NFAULT_GPIO_Port, &GPIO_InitStruct); GPIO_InitStruct.Pin = GD_READY_Pin; LL_GPIO_Init(GD_READY_GPIO_Port, &GPIO_InitStruct); #else status = (STSPIN32G4_StatusTypeDef) HAL_I2C_DeInit(hdl->i2cHdl); HAL_GPIO_DeInit(GD_WAKE_GPIO_Port, GD_WAKE_Pin); HAL_GPIO_DeInit(GD_NFAULT_GPIO_Port, GD_NFAULT_Pin); HAL_GPIO_DeInit(GD_READY_GPIO_Port, GD_READY_Pin); #endif hdl->i2cHdl = NULL; return status; } STSPIN32G4_StatusTypeDef STSPIN32G4_lockReg(STSPIN32G4_HandleTypeDef *hdl) { STSPIN32G4_StatusTypeDef status; STSPIN32G4_statusRegTypeDef statusReg; uint8_t i2cReg = 0; if (hdl == NULL) { return STSPIN32G4_ERROR; } i2cReg = ((STSPIN32G4_I2C_LOCKCODE << 4) & 0xf0) | (STSPIN32G4_I2C_LOCKCODE & 0x0f); status = STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_LOCK, i2cReg); #ifdef STSPIN32G4_I2C_LOCKUSEPARANOID if (status == STSPIN32G4_OK) { status = STSPIN32G4_getStatus(hdl, &statusReg); } if (status == STSPIN32G4_OK) { if (statusReg.lock != 1) { status = STSPIN32G4_ERROR; } } #endif return status; } STSPIN32G4_StatusTypeDef STSPIN32G4_unlockReg(STSPIN32G4_HandleTypeDef *hdl) { STSPIN32G4_StatusTypeDef status; STSPIN32G4_statusRegTypeDef statusReg; uint8_t i2cReg = 0; if (hdl == NULL) { return STSPIN32G4_ERROR; } i2cReg = (((~STSPIN32G4_I2C_LOCKCODE) << 4) & 0xf0) | (STSPIN32G4_I2C_LOCKCODE & 0x0f); status = STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_LOCK, i2cReg); #ifdef STSPIN32G4_I2C_LOCKUSEPARANOID if (status == STSPIN32G4_OK) { status = STSPIN32G4_getStatus(hdl, &statusReg); } if (status == STSPIN32G4_OK) { if (statusReg.lock == 1) { status = STSPIN32G4_ERROR; } } #endif return status; } STSPIN32G4_StatusTypeDef STSPIN32G4_readReg(STSPIN32G4_HandleTypeDef *hdl, uint8_t regAddr, uint8_t *value) { STSPIN32G4_StatusTypeDef status = STSPIN32G4_OK; if (hdl == NULL) { status = STSPIN32G4_ERROR; return status; } if (hdl->i2cHdl == NULL) { status = STSPIN32G4_ERROR; return status; } if (value == NULL) { status = STSPIN32G4_ERROR; return status; } #if defined(USE_FULL_LL_DRIVER) LL_RCC_ClocksTypeDef RCC_Clocks; LL_RCC_GetSystemClocksFreq(&RCC_Clocks); uint32_t tickFreq = RCC_Clocks.HCLK_Frequency / (SysTick->LOAD + 1); if (LL_SYSTICK_GetClkSource() == LL_SYSTICK_CLKSOURCE_HCLK_DIV8) { tickFreq /= 8; } uint8_t stat = 0; uint32_t ticks = (STSPIN32G4_I2C_TIMEOUT * tickFreq) / 1000 + 1; while (true) { switch (stat) { case 0: stat += !LL_I2C_IsActiveFlag_BUSY(hdl->i2cHdl); break; case 1: LL_I2C_HandleTransfer(hdl->i2cHdl, STSPIN32G4_I2C_ADDR, LL_I2C_ADDRSLAVE_7BIT, 1, LL_I2C_MODE_SOFTEND, LL_I2C_GENERATE_START_WRITE); stat++; break; case 2: stat += LL_I2C_IsActiveFlag_TXIS(hdl->i2cHdl); break; case 3: LL_I2C_TransmitData8(hdl->i2cHdl, regAddr); stat++; break; case 4: stat += LL_I2C_IsActiveFlag_TC(hdl->i2cHdl); break; case 5: LL_I2C_HandleTransfer(hdl->i2cHdl, STSPIN32G4_I2C_ADDR, LL_I2C_ADDRSLAVE_7BIT, 1, I2C_CR2_AUTOEND, LL_I2C_GENERATE_START_READ); stat++; break; case 6: stat += LL_I2C_IsActiveFlag_RXNE(hdl->i2cHdl); break; case 7: *value = LL_I2C_ReceiveData8(hdl->i2cHdl); stat++; break; case 8: stat += LL_I2C_IsActiveFlag_STOP(hdl->i2cHdl); break; case 9: LL_I2C_ClearFlag_STOP(hdl->i2cHdl); status = STSPIN32G4_OK; return status; default: status = STSPIN32G4_ERROR; return status; } if (LL_SYSTICK_IsActiveCounterFlag()) { ticks--; } if(ticks == 0) { status = STSPIN32G4_TIMEOUT; return status; } } #else uint32_t ticks = (STSPIN32G4_I2C_TIMEOUT * HAL_GetTickFreq()) / 1000 + 1; status = (STSPIN32G4_StatusTypeDef) HAL_I2C_Mem_Read(hdl->i2cHdl, STSPIN32G4_I2C_ADDR, (uint16_t) regAddr, 1, value, 1, ticks); return status; #endif } STSPIN32G4_StatusTypeDef STSPIN32G4_writeReg(STSPIN32G4_HandleTypeDef *hdl, uint8_t regAddr, uint8_t value) { STSPIN32G4_StatusTypeDef status = STSPIN32G4_OK; if (hdl == NULL) { status = STSPIN32G4_ERROR; return status; } if (hdl->i2cHdl == NULL) { status = STSPIN32G4_ERROR; return status; } #if defined(USE_FULL_LL_DRIVER) LL_RCC_ClocksTypeDef RCC_Clocks; LL_RCC_GetSystemClocksFreq(&RCC_Clocks); uint32_t tickFreq = RCC_Clocks.HCLK_Frequency / (SysTick->LOAD + 1); if (LL_SYSTICK_GetClkSource() == LL_SYSTICK_CLKSOURCE_HCLK_DIV8) { tickFreq /= 8; } uint8_t stat = 0; uint32_t ticks = (STSPIN32G4_I2C_TIMEOUT * tickFreq) / 1000 + 1; while (true) { switch (stat) { case 0: stat += !LL_I2C_IsActiveFlag_BUSY(hdl->i2cHdl); break; case 1: LL_I2C_HandleTransfer(hdl->i2cHdl, STSPIN32G4_I2C_ADDR, LL_I2C_ADDRSLAVE_7BIT, 1, I2C_CR2_RELOAD, LL_I2C_GENERATE_START_WRITE); stat++; break; case 2: stat += LL_I2C_IsActiveFlag_TXIS(hdl->i2cHdl); break; case 3: LL_I2C_TransmitData8(hdl->i2cHdl, regAddr); stat++; break; case 4: stat += LL_I2C_IsActiveFlag_TCR(hdl->i2cHdl); break; case 5: LL_I2C_HandleTransfer(hdl->i2cHdl, STSPIN32G4_I2C_ADDR, LL_I2C_ADDRSLAVE_7BIT, 1, I2C_CR2_AUTOEND, LL_I2C_GENERATE_NOSTARTSTOP); stat++; break; case 6: stat += LL_I2C_IsActiveFlag_TXIS(hdl->i2cHdl); break; case 7: LL_I2C_TransmitData8(hdl->i2cHdl, value); stat++; break; case 8: stat += LL_I2C_IsActiveFlag_STOP(hdl->i2cHdl); break; case 9: LL_I2C_ClearFlag_STOP(hdl->i2cHdl); status = STSPIN32G4_OK; return status; default: status = STSPIN32G4_ERROR; return status; } if (LL_SYSTICK_IsActiveCounterFlag()) { ticks--; } if(ticks == 0) { status = STSPIN32G4_TIMEOUT; return status; } } #else uint32_t ticks = (STSPIN32G4_I2C_TIMEOUT * HAL_GetTickFreq()) / 1000 + 1; status = (STSPIN32G4_StatusTypeDef) HAL_I2C_Mem_Write(hdl->i2cHdl, STSPIN32G4_I2C_ADDR, (uint16_t) regAddr, 1, &value, 1, ticks); return status; #endif } STSPIN32G4_StatusTypeDef STSPIN32G4_writeVerifyReg(STSPIN32G4_HandleTypeDef *hdl, uint8_t regAddr, uint8_t value) { STSPIN32G4_StatusTypeDef status; uint8_t i2cReg = 0; status = STSPIN32G4_writeReg(hdl, regAddr, value); if (status == STSPIN32G4_OK) { status = STSPIN32G4_readReg(hdl, regAddr, &i2cReg); } if (status == STSPIN32G4_OK) { if (value != i2cReg) { status = STSPIN32G4_ERROR; } } return status; } STSPIN32G4_StatusTypeDef STSPIN32G4_set3V3(STSPIN32G4_HandleTypeDef *hdl, bool enabled) { STSPIN32G4_StatusTypeDef status; uint8_t i2cReg = 0; if (hdl == NULL) { return STSPIN32G4_ERROR; } status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_POWMNG, &i2cReg); if (status == STSPIN32G4_OK) { status = STSPIN32G4_unlockReg(hdl); } if (status == STSPIN32G4_OK) { if (enabled) { i2cReg &= ~STSPIN32G4_I2C_REG3V3_DIS; } else { i2cReg |= STSPIN32G4_I2C_REG3V3_DIS; } status = STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_POWMNG, i2cReg); } if (status == STSPIN32G4_OK) { STSPIN32G4_lockReg(hdl); return status; } else { return STSPIN32G4_lockReg(hdl); } } STSPIN32G4_StatusTypeDef STSPIN32G4_get3V3(STSPIN32G4_HandleTypeDef *hdl, bool *enabled) { STSPIN32G4_StatusTypeDef status; uint8_t i2cReg = 0; if (hdl == NULL) { return STSPIN32G4_ERROR; } if (enabled == NULL) { return STSPIN32G4_ERROR; } status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_POWMNG, &i2cReg); *enabled = (i2cReg & STSPIN32G4_I2C_REG3V3_DIS) ? false : true; return status; } STSPIN32G4_StatusTypeDef STSPIN32G4_setVCC(STSPIN32G4_HandleTypeDef *hdl, STSPIN32G4_confVCC vcc) { STSPIN32G4_StatusTypeDef status; uint8_t i2cReg = 0; if (hdl == NULL) { return STSPIN32G4_ERROR; } status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_POWMNG, &i2cReg); if (status == STSPIN32G4_OK) { status = STSPIN32G4_unlockReg(hdl); } if (status == STSPIN32G4_OK) { switch (vcc.voltage) { case _EXT: i2cReg |= STSPIN32G4_I2C_VCC_DIS; break; case _8V: i2cReg &= ~(STSPIN32G4_I2C_VCC_DIS | STSPIN32G4_I2C_VCC_VAL_3); i2cReg |= STSPIN32G4_I2C_VCC_VAL_0; break; case _10V: i2cReg &= ~(STSPIN32G4_I2C_VCC_DIS | STSPIN32G4_I2C_VCC_VAL_3); i2cReg |= STSPIN32G4_I2C_VCC_VAL_1; break; case _12V: i2cReg &= ~(STSPIN32G4_I2C_VCC_DIS | STSPIN32G4_I2C_VCC_VAL_3); i2cReg |= STSPIN32G4_I2C_VCC_VAL_2; break; case _15V: i2cReg &= ~STSPIN32G4_I2C_VCC_DIS; i2cReg |= STSPIN32G4_I2C_VCC_VAL_3; break; default: status = STSPIN32G4_ERROR; break; } } if (status == STSPIN32G4_OK) { status = STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_POWMNG, i2cReg); } if (status == STSPIN32G4_OK) { status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_NFAULT, &i2cReg); } if (status == STSPIN32G4_OK) // configuration of nFAULT pin { if (vcc.useNFAULT) { i2cReg |= STSPIN32G4_I2C_VCC_UVLO_FLT; } else { i2cReg &= ~STSPIN32G4_I2C_VCC_UVLO_FLT; } status = STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_NFAULT, i2cReg); } if (status == STSPIN32G4_OK) { status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_READY, &i2cReg); } if (status == STSPIN32G4_OK) // configuration of READY pin { if (vcc.useREADY) { i2cReg |= STSPIN32G4_I2C_VCC_UVLO_RDY; } else { i2cReg &= ~STSPIN32G4_I2C_VCC_UVLO_RDY; } status = STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_READY, i2cReg); } if (status == STSPIN32G4_OK) { STSPIN32G4_lockReg(hdl); return status; } else { return STSPIN32G4_lockReg(hdl); } } STSPIN32G4_StatusTypeDef STSPIN32G4_getVCC(STSPIN32G4_HandleTypeDef *hdl, STSPIN32G4_confVCC *vcc) { STSPIN32G4_StatusTypeDef status; uint8_t i2cReg = 0; if (hdl == NULL) { return STSPIN32G4_ERROR; } if (vcc == NULL) { return STSPIN32G4_ERROR; } status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_POWMNG, &i2cReg); if (status == STSPIN32G4_OK) { if (i2cReg & STSPIN32G4_I2C_VCC_DIS) { vcc->voltage = _EXT; } else { switch (i2cReg & STSPIN32G4_I2C_VCC_VAL_3) { case STSPIN32G4_I2C_VCC_VAL_0: vcc->voltage = _8V; break; case STSPIN32G4_I2C_VCC_VAL_1: vcc->voltage = _10V; break; case STSPIN32G4_I2C_VCC_VAL_2: vcc->voltage = _12V; break; case STSPIN32G4_I2C_VCC_VAL_3: vcc->voltage = _15V; break; default: status = STSPIN32G4_ERROR; break; } } } if (status == STSPIN32G4_OK) { status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_NFAULT, &i2cReg); vcc->useNFAULT = (i2cReg & STSPIN32G4_I2C_VCC_UVLO_FLT) ? true : false; } if (status == STSPIN32G4_OK) { status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_READY, &i2cReg); vcc->useREADY = (i2cReg & STSPIN32G4_I2C_VCC_UVLO_RDY) ? true : false; } return status; } STSPIN32G4_StatusTypeDef STSPIN32G4_setInterlocking(STSPIN32G4_HandleTypeDef *hdl, bool enabled) { STSPIN32G4_StatusTypeDef status; uint8_t i2cReg = 0; if (hdl == NULL) { return STSPIN32G4_ERROR; } status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_LOGIC, &i2cReg); if (status == STSPIN32G4_OK) { status = STSPIN32G4_unlockReg(hdl); } if (status == STSPIN32G4_OK) { if (enabled) { i2cReg |= STSPIN32G4_I2C_ILOCK; } else { i2cReg &= ~STSPIN32G4_I2C_ILOCK; } status = STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_LOGIC, i2cReg); } if (status == STSPIN32G4_OK) { STSPIN32G4_lockReg(hdl); return status; } else { return STSPIN32G4_lockReg(hdl); } } STSPIN32G4_StatusTypeDef STSPIN32G4_getInterlocking(STSPIN32G4_HandleTypeDef *hdl, bool *enabled) { STSPIN32G4_StatusTypeDef status; uint8_t i2cReg = 0; if (hdl == NULL) { return STSPIN32G4_ERROR; } if (enabled == NULL) { return STSPIN32G4_ERROR; } status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_LOGIC, &i2cReg); *enabled = (i2cReg & STSPIN32G4_I2C_ILOCK) ? true : false; return status; } STSPIN32G4_StatusTypeDef STSPIN32G4_setMinimumDeadTime(STSPIN32G4_HandleTypeDef *hdl, bool enabled) { STSPIN32G4_StatusTypeDef status; uint8_t i2cReg = 0; if (hdl == NULL) { return STSPIN32G4_ERROR; } status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_LOGIC, &i2cReg); if (status == STSPIN32G4_OK) { status = STSPIN32G4_unlockReg(hdl); } if (status == STSPIN32G4_OK) { if (enabled) { i2cReg |= STSPIN32G4_I2C_DTMIN; } else { i2cReg &= ~STSPIN32G4_I2C_DTMIN; } status = STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_LOGIC, i2cReg); } if (status == STSPIN32G4_OK) { STSPIN32G4_lockReg(hdl); return status; } else { return STSPIN32G4_lockReg(hdl); } } STSPIN32G4_StatusTypeDef STSPIN32G4_getMinimumDeadTime(STSPIN32G4_HandleTypeDef *hdl, bool *enabled) { STSPIN32G4_StatusTypeDef status; uint8_t i2cReg = 0; if (hdl == NULL) { return STSPIN32G4_ERROR; } if (enabled == NULL) { return STSPIN32G4_ERROR; } status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_LOGIC, &i2cReg); *enabled = (i2cReg & STSPIN32G4_I2C_DTMIN) ? true : false; return status; } STSPIN32G4_StatusTypeDef STSPIN32G4_setVDSP(STSPIN32G4_HandleTypeDef *hdl, STSPIN32G4_confVDSP vdsp) { STSPIN32G4_StatusTypeDef status; uint8_t i2cReg = 0; if (hdl == NULL) { return STSPIN32G4_ERROR; } status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_LOGIC, &i2cReg); if (status == STSPIN32G4_OK) { status = STSPIN32G4_unlockReg(hdl); } if (status == STSPIN32G4_OK) { i2cReg &= ~STSPIN32G4_I2C_VDS_P_DEG_3; switch (vdsp.deglitchTime) { case _6us: i2cReg |= STSPIN32G4_I2C_VDS_P_DEG_0; break; case _4us: i2cReg |= STSPIN32G4_I2C_VDS_P_DEG_1; break; case _3us: i2cReg |= STSPIN32G4_I2C_VDS_P_DEG_2; break; case _2us: i2cReg |= STSPIN32G4_I2C_VDS_P_DEG_3; break; default: status = STSPIN32G4_ERROR; break; } } if (status == STSPIN32G4_OK) { status = STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_LOGIC, i2cReg); } if (status == STSPIN32G4_OK) { status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_NFAULT, &i2cReg); } if (status == STSPIN32G4_OK) // configure nFault signaling { if (vdsp.useNFAULT) { i2cReg |= STSPIN32G4_I2C_VDS_P_FLT; } else { i2cReg &= ~STSPIN32G4_I2C_VDS_P_FLT; } status = STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_NFAULT, i2cReg); } if (status == STSPIN32G4_OK) { STSPIN32G4_lockReg(hdl); return status; } else { return STSPIN32G4_lockReg(hdl); } } STSPIN32G4_StatusTypeDef STSPIN32G4_getVDSP(STSPIN32G4_HandleTypeDef *hdl, STSPIN32G4_confVDSP *vdsp) { STSPIN32G4_StatusTypeDef status; uint8_t i2cReg = 0; if (hdl == NULL) { return STSPIN32G4_ERROR; } if (vdsp == NULL) { return STSPIN32G4_ERROR; } status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_LOGIC, &i2cReg); if (status == STSPIN32G4_OK) { switch (i2cReg & STSPIN32G4_I2C_VDS_P_DEG_3) { case STSPIN32G4_I2C_VDS_P_DEG_0: vdsp->deglitchTime = _6us; break; case STSPIN32G4_I2C_VDS_P_DEG_1: vdsp->deglitchTime = _4us; break; case STSPIN32G4_I2C_VDS_P_DEG_2: vdsp->deglitchTime = _3us; break; case STSPIN32G4_I2C_VDS_P_DEG_3: vdsp->deglitchTime = _2us; break; default: status = STSPIN32G4_ERROR; break; } } if (status == STSPIN32G4_OK) { status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_NFAULT, &i2cReg); vdsp->useNFAULT = (i2cReg & STSPIN32G4_I2C_VDS_P_FLT) ? true : false; } return status; } STSPIN32G4_StatusTypeDef STSPIN32G4_setTHSD(STSPIN32G4_HandleTypeDef *hdl, STSPIN32G4_confTHSD thsd) { STSPIN32G4_StatusTypeDef status; uint8_t i2cReg = 0; if (hdl == NULL) { return STSPIN32G4_ERROR; } status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_NFAULT, &i2cReg); if (status == STSPIN32G4_OK) { status = STSPIN32G4_unlockReg(hdl); } if (status == STSPIN32G4_OK) { if (thsd.useNFAULT) { i2cReg |= STSPIN32G4_I2C_THSD_FLT; } else { i2cReg &= ~STSPIN32G4_I2C_THSD_FLT; } status = STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_NFAULT, i2cReg); } if (status == STSPIN32G4_OK) { status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_READY, &i2cReg); } if (status == STSPIN32G4_OK) { if (thsd.useREADY) { i2cReg |= STSPIN32G4_I2C_THSD_RDY; } else { i2cReg &= ~STSPIN32G4_I2C_THSD_RDY; } status = STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_READY, i2cReg); } if (status == STSPIN32G4_OK) { STSPIN32G4_lockReg(hdl); return status; } else { return STSPIN32G4_lockReg(hdl); } } STSPIN32G4_StatusTypeDef STSPIN32G4_getTHSD(STSPIN32G4_HandleTypeDef *hdl, STSPIN32G4_confTHSD *thsd) { STSPIN32G4_StatusTypeDef status; uint8_t i2cReg = 0; if (hdl == NULL) { return STSPIN32G4_ERROR; } if (thsd == NULL) { return STSPIN32G4_ERROR; } status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_NFAULT, &i2cReg); thsd->useNFAULT = (i2cReg & STSPIN32G4_I2C_THSD_FLT) ? true : false; if (status == STSPIN32G4_OK) { status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_READY, &i2cReg); thsd->useREADY = (i2cReg & STSPIN32G4_I2C_THSD_RDY) ? true : false; } return status; } STSPIN32G4_StatusTypeDef STSPIN32G4_clearFaults(STSPIN32G4_HandleTypeDef *hdl) { uint8_t i2cReg = 0xff; if (hdl == NULL) { return STSPIN32G4_ERROR; } return STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_CLEAR, i2cReg); } STSPIN32G4_StatusTypeDef STSPIN32G4_reset(STSPIN32G4_HandleTypeDef *hdl) { STSPIN32G4_StatusTypeDef status; uint8_t i2cReg = 0xff; if (hdl == NULL) { return STSPIN32G4_ERROR; } status = STSPIN32G4_unlockReg(hdl); if (status == STSPIN32G4_OK) { status = STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_RESET, i2cReg); } return status; } STSPIN32G4_StatusTypeDef STSPIN32G4_standby(STSPIN32G4_HandleTypeDef *hdl, bool enableStbyReg) { STSPIN32G4_StatusTypeDef status; uint8_t i2cReg = 0; uint32_t tickFreq; uint32_t ticks; #if defined(USE_FULL_LL_DRIVER) LL_RCC_ClocksTypeDef RCC_Clocks; LL_RCC_GetSystemClocksFreq(&RCC_Clocks); tickFreq = RCC_Clocks.HCLK_Frequency / (SysTick->LOAD + 1); if (LL_SYSTICK_GetClkSource() == LL_SYSTICK_CLKSOURCE_HCLK_DIV8) { tickFreq /= 8; } #else uint32_t tickStart; tickFreq = HAL_GetTickFreq() / 1000; // in kHz to have ms base #endif if (hdl == NULL) { return STSPIN32G4_ERROR; } status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_POWMNG, &i2cReg); if (status == STSPIN32G4_OK) { status = STSPIN32G4_unlockReg(hdl); } if (status == STSPIN32G4_OK) // configure the Standby regulator { if (enableStbyReg) { i2cReg |= STSPIN32G4_I2C_STBY_REG_EN; } else { i2cReg &= ~STSPIN32G4_I2C_STBY_REG_EN; } status = STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_POWMNG, i2cReg); } if (status == STSPIN32G4_OK) // create backup of the READY register { status = STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_READY, &STSPIN32G4_bkupREADY); } if (status == STSPIN32G4_OK) // set only STBY_RDY to signal the exit from standby { i2cReg = STSPIN32G4_I2C_STBY_RDY; status = STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_READY, i2cReg); } if (status == STSPIN32G4_OK) // WAKE line low { #if defined(USE_FULL_LL_DRIVER) LL_GPIO_ResetOutputPin(GD_WAKE_GPIO_Port, GD_WAKE_Pin); #else HAL_GPIO_WritePin(GD_WAKE_GPIO_Port, GD_WAKE_Pin, GPIO_PIN_RESET); #endif } #ifdef STSPIN32G4_HSI16 if (status == STSPIN32G4_OK) { if (enableStbyReg) { // Set HSI16 clock to reduce current consumption #if defined(USE_FULL_LL_DRIVER) status = (STSPIN32G4_StatusTypeDef) LL_RCC_DeInit(); #else status = (STSPIN32G4_StatusTypeDef) HAL_RCC_DeInit(); #endif } } #endif // request to enter standby if (status == STSPIN32G4_OK) { i2cReg = 0x01; status = STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_STBY, i2cReg); } ticks = (1 * tickFreq) / 1000 + 1; #if defined(USE_FULL_LL_DRIVER) if (LL_GPIO_IsInputPinSet(GD_READY_GPIO_Port, GD_READY_Pin)) { LL_GPIO_SetOutputPin(GD_WAKE_GPIO_Port, GD_WAKE_Pin); status = STSPIN32G4_ERROR; } else { LL_SYSTICK_IsActiveCounterFlag(); while (!LL_GPIO_IsInputPinSet(GD_READY_GPIO_Port, GD_READY_Pin)) { if (LL_SYSTICK_IsActiveCounterFlag()) { ticks--; } if (ticks == 0) { status = STSPIN32G4_TIMEOUT; break; } } } #else if (HAL_GPIO_ReadPin(GD_READY_GPIO_Port, GD_READY_Pin) == GPIO_PIN_SET) { HAL_GPIO_WritePin(GD_WAKE_GPIO_Port, GD_WAKE_Pin, GPIO_PIN_SET); status = STSPIN32G4_ERROR; } else { tickStart = HAL_GetTick(); while (HAL_GPIO_ReadPin(GD_READY_GPIO_Port, GD_READY_Pin) == GPIO_PIN_RESET) { if ((HAL_GetTick() - tickStart) > ticks) // expected time is 100us { status = STSPIN32G4_TIMEOUT; break; } } } #endif // wait 1ms and check possible exit from standby #if defined(USE_FULL_LL_DRIVER) LL_mDelay(ticks); if (!LL_GPIO_IsInputPinSet(GD_READY_GPIO_Port, GD_READY_Pin) || !LL_GPIO_IsInputPinSet(GD_NFAULT_GPIO_Port, GD_NFAULT_Pin)) { status = STSPIN32G4_ERROR; } #else HAL_Delay(ticks); if ((HAL_GPIO_ReadPin(GD_READY_GPIO_Port, GD_READY_Pin) != GPIO_PIN_SET) || (HAL_GPIO_ReadPin(GD_NFAULT_GPIO_Port, GD_NFAULT_Pin) != GPIO_PIN_SET)) { status = STSPIN32G4_ERROR; } #endif #ifdef STSPIN32G4_HSI16 // if the driver failed to enter standby clock is reconfigured if (status != STSPIN32G4_OK) { SystemClock_Config(); // restore clock configuration } #endif return status; } STSPIN32G4_StatusTypeDef STSPIN32G4_wakeup(STSPIN32G4_HandleTypeDef *hdl, uint8_t timeout_ms) { STSPIN32G4_StatusTypeDef status; STSPIN32G4_statusRegTypeDef statReg; uint32_t tickFreq; uint32_t ticks; #if defined(USE_FULL_LL_DRIVER) LL_RCC_ClocksTypeDef RCC_Clocks; LL_RCC_GetSystemClocksFreq(&RCC_Clocks); tickFreq = RCC_Clocks.HCLK_Frequency / (SysTick->LOAD + 1); if (LL_SYSTICK_GetClkSource() == LL_SYSTICK_CLKSOURCE_HCLK_DIV8) { tickFreq /= 8; } #else uint32_t tickStart; tickFreq = HAL_GetTickFreq() / 1000; // in kHz to have ms base #endif if (hdl == NULL) { return STSPIN32G4_ERROR; } #if defined(USE_FULL_LL_DRIVER) LL_GPIO_SetOutputPin(GD_WAKE_GPIO_Port, GD_WAKE_Pin); #else HAL_GPIO_WritePin(GD_WAKE_GPIO_Port, GD_WAKE_Pin, GPIO_PIN_SET); #endif if (timeout_ms < 4) { timeout_ms = 4; // The soft start is expected to take 4ms } ticks = (timeout_ms * tickFreq) / 1000 + 1; #if defined(USE_FULL_LL_DRIVER) LL_SYSTICK_IsActiveCounterFlag(); while (!LL_GPIO_IsInputPinSet(GD_READY_GPIO_Port, GD_READY_Pin)) { if (LL_SYSTICK_IsActiveCounterFlag()) { ticks--; } if (ticks == 0) { status = STSPIN32G4_TIMEOUT; break; } } #else tickStart = HAL_GetTick(); while (HAL_GPIO_ReadPin(GD_READY_GPIO_Port, GD_READY_Pin) == GPIO_PIN_RESET) { if ((HAL_GetTick() - tickStart) > ticks) { status = STSPIN32G4_TIMEOUT; break; } } #endif #ifdef STSPIN32G4_HSI16 if (status == STSPIN32G4_OK) { SystemClock_Config(); } #endif // Restore READY register if (status == STSPIN32G4_OK) { status = STSPIN32G4_writeReg(hdl, STSPIN32G4_I2C_READY, STSPIN32G4_bkupREADY); } if (status == STSPIN32G4_OK) { status = STSPIN32G4_lockReg(hdl); } if (status == STSPIN32G4_OK) { status = STSPIN32G4_getStatus(hdl, &statReg); } if (status == STSPIN32G4_OK) { if (statReg.reset == 1) { status = STSPIN32G4_ERROR; } } return status; } STSPIN32G4_StatusTypeDef STSPIN32G4_getStatus(STSPIN32G4_HandleTypeDef *hdl, STSPIN32G4_statusRegTypeDef *status) { if (hdl == NULL) { return STSPIN32G4_ERROR; } if (status == NULL) { return STSPIN32G4_ERROR; } return STSPIN32G4_readReg(hdl, STSPIN32G4_I2C_STATUS, (uint8_t *)status); }
29,260
C
19.62086
138
0.636569
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/G4xx/Inc/r3_2_g4xx_pwm_curr_fdbk.h
/** ****************************************************************************** * @file r3_2_g4xx_pwm_curr_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * R3_2_G4XX_pwm_curr_fdbk component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup R3_2_G4XX_pwm_curr_fdbk */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef R3_2_G4XX_PWMNCURRFDBK_H #define R3_2_G4XX_PWMNCURRFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "pwm_curr_fdbk.h" /* Exported defines --------------------------------------------------------*/ #define GPIO_NoRemap_TIM1 ((uint32_t)(0)) #define SHIFTED_TIMs ((uint8_t) 1) #define NO_SHIFTED_TIMs ((uint8_t) 0) #define NONE ((uint8_t)(0x00)) #define EXT_MODE ((uint8_t)(0x01)) #define INT_MODE ((uint8_t)(0x02)) /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup R3_2_pwm_curr_fdbk * @{ */ /* Exported types ------------------------------------------------------- */ #ifndef R3_3_OPAMP #define R3_3_OPAMP /** * @brief Current feedback component 3-OPAMP parameters structure definition. Specific to G4XX. */ typedef const struct { /* First OPAMP settings ------------------------------------------------------*/ OPAMP_TypeDef *OPAMPSelect_1 [6] ; /*!< Define for each sector first conversion which OPAMP is involved - Null otherwise */ OPAMP_TypeDef *OPAMPSelect_2 [6] ; /*!< Define for each sector second conversion which OPAMP is involved - Null otherwise */ uint32_t OPAMPConfig1 [6]; /*!< Define the OPAMP_CSR_OPAMPINTEN and the OPAMP_CSR_VPSEL config for each ADC conversions*/ uint32_t OPAMPConfig2 [6]; /*!< Define the OPAMP_CSR_OPAMPINTEN and the OPAMP_CSR_VPSEL config for each ADC conversions*/ } R3_3_OPAMPParams_t; #endif /* * @brief R3_2_G4XX_pwm_curr_fdbk component parameters structure definition. */ typedef const struct { /* HW IP involved -----------------------------*/ TIM_TypeDef *TIMx; /* timer used for PWM generation.*/ R3_3_OPAMPParams_t *OPAMPParams; /*!< Pointer to the 3-OPAMP params struct. It must be #MC_NULL if internal OPAMP are not used. Specific to G4XX.*/ COMP_TypeDef *CompOCPASelection; /* Internal comparator used for Phase A protection.*/ COMP_TypeDef *CompOCPBSelection; /* Internal comparator used for Phase B protection.*/ COMP_TypeDef *CompOCPCSelection; /* Internal comparator used for Phase C protection.*/ COMP_TypeDef *CompOVPSelection; /* Internal comparator used for Over Voltage protection.*/ DAC_TypeDef *DAC_OCP_ASelection; /*!< DAC used for Phase A protection. Specific to G4XX.*/ DAC_TypeDef *DAC_OCP_BSelection; /*!< DAC used for Phase B protection. Specific to G4XX.*/ DAC_TypeDef *DAC_OCP_CSelection; /*!< DAC used for Phase C protection. Specific to G4XX.*/ DAC_TypeDef *DAC_OVP_Selection; /*!< DAC used for Over Voltage protection. Specific to G4XX.*/ uint32_t DAC_Channel_OCPA; /*!< DAC channel used for Phase A current protection.*/ uint32_t DAC_Channel_OCPB; /*!< DAC channel used for Phase B current protection.*/ uint32_t DAC_Channel_OCPC; /*!< DAC channel used for Phase C current protection.*/ uint32_t DAC_Channel_OVP; /*!< DAC channel used for Over Voltage protection.*/ ADC_TypeDef *ADCDataReg1[6]; ADC_TypeDef *ADCDataReg2[6]; uint32_t ADCConfig1 [6] ; /* Values of JSQR for first ADC for 6 sectors */ uint32_t ADCConfig2 [6] ; /* Values of JSQR for Second ADC for 6 sectors */ /* PWM generation parameters --------------------------------------------------*/ uint16_t Tafter; /* Sum of dead time plus max value between rise time and noise time expressed in number of TIM clocks.*/ uint16_t Tsampling; /* Sampling time expressed in number of TIM clocks.*/ uint16_t Tbefore; /* Sampling time expressed in number of TIM clocks.*/ uint16_t Tcase2; /* Sampling time expressed in number of TIM clocks.*/ uint16_t Tcase3; /* Sampling time expressed in number of TIM clocks.*/ /* DAC settings --------------------------------------------------------------*/ uint16_t DAC_OCP_Threshold; /* Value of analog reference expressed as 16bit unsigned integer. Ex. 0 = 0V ; 65536 = VDD_DAC.*/ uint16_t DAC_OVP_Threshold; /* Value of analog reference expressed as 16bit unsigned integer. Ex. 0 = 0V ; 65536 = VDD_DAC.*/ /* PWM Driving signals initialization ----------------------------------------*/ uint8_t RepetitionCounter; /* Expresses the number of PWM periods to be elapsed before compare registers are updated again. In particular: RepetitionCounter= (2* #PWM periods)-1*/ /* Internal COMP settings ----------------------------------------------------*/ uint8_t CompOCPAInvInput_MODE; /* COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. */ uint8_t CompOCPBInvInput_MODE; /* COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. */ uint8_t CompOCPCInvInput_MODE; /* COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. */ uint8_t CompOVPInvInput_MODE; /* COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. */ /* Dual MC parameters --------------------------------------------------------*/ uint8_t FreqRatio; /* Used in case of dual MC to synchronize TIM1 and TIM8. It has effect only on the second instanced object and must be equal to the ratio between the two PWM frequencies (higher/lower). Supported values are 1, 2 or 3 */ uint8_t IsHigherFreqTim; /* When bFreqRatio is greather than 1 this param is used to indicate if this instance is the one with the highest frequency. Allowed value are: HIGHER_FREQ or LOWER_FREQ */ } R3_2_Params_t, *pR3_2_Params_t; /* * @brief Handles an instance of the R3_2_G4XX_pwm_curr_fdbk component. */ typedef struct { PWMC_Handle_t _Super; /* */ uint32_t PhaseAOffset; /* Offset of Phase A current sensing network. */ uint32_t PhaseBOffset; /* Offset of Phase B current sensing network. */ uint32_t PhaseCOffset; /* Offset of Phase C current sensing network. */ uint16_t Half_PWMPeriod; /* Half PWM Period in timer clock counts. */ uint16_t ADC_ExternalPolarityInjected; /* External trigger selection for ADC peripheral. */ volatile uint8_t PolarizationCounter; uint8_t PolarizationSector; /* Sector selected during calibration phase. */ pR3_2_Params_t pParams_str; bool ADCRegularLocked; /*!< This flag is set when regular conversions are locked. Specific to G4XX. */ /* Cut 2.2 patch*/ } PWMC_R3_2_Handle_t; /* Exported functions ------------------------------------------------------- */ /* * Initializes TIMx, ADC, GPIO, DMA1 and NVIC for current reading * in three shunt topology using STM32F30X and shared ADC. */ void R3_2_Init(PWMC_R3_2_Handle_t *pHandle); /* * Stores into the handle the voltage present on Ia and * Ib current feedback analog channels when no current is flowing into the * motor. */ void R3_2_CurrentReadingPolarization(PWMC_Handle_t *pHdl); /* * Computes and returns latest converted motor phase currents. */ void R3_2_GetPhaseCurrents(PWMC_Handle_t *pHdl, ab_t *Iab); /* * Computes and return latest converted motor phase currents. */ void R3_2_GetPhaseCurrents_OVM(PWMC_Handle_t *pHdl, ab_t *Iab); /* * Turns on low sides switches. */ void R3_2_TurnOnLowSides(PWMC_Handle_t *pHdl, uint32_t ticks); /* * Enables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_2_SwitchOnPWM(PWMC_Handle_t *pHdl); /* * Disables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_2_SwitchOffPWM(PWMC_Handle_t *pHdl); /* * Configures the ADC for the current sampling related to sector 1. */ uint16_t R3_2_SetADCSampPointSectX(PWMC_Handle_t *pHdl); /* * Configures the ADC for the current sampling related to sector X (X = [1..6] ). */ uint16_t R3_2_SetADCSampPointSectX_OVM(PWMC_Handle_t *pHdl); /* * Contains the TIMx Update event interrupt. */ void *R3_2_TIMx_UP_IRQHandler(PWMC_R3_2_Handle_t *pHandle); /* * Sets the PWM mode for R/L detection. */ void R3_2_RLDetectionModeEnable(PWMC_Handle_t *pHdl); /* * Disables the PWM mode for R/L detection. */ void R3_2_RLDetectionModeDisable(PWMC_Handle_t *pHdl); /* * Sets the PWM dutycycle for R/L detection. */ uint16_t R3_2_RLDetectionModeSetDuty(PWMC_Handle_t *pHdl, uint16_t hDuty); /* * Turns on low sides switches and start ADC triggering. * This function is specific for MP phase. */ void R3_2_RLTurnOnLowSidesAndStart(PWMC_Handle_t *pHdl); /* * Sets the calibrated offset. */ void R3_2_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /* * Reads the calibrated offsets. */ void R3_2_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*R3_2_G4XX_PWMNCURRFDBK_H*/ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
11,237
C
40.014598
130
0.554418
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/G4xx/Inc/ics_g4xx_pwm_curr_fdbk.h
/** ****************************************************************************** * @file ics_g4xx_pwm_curr_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * ICS_G4XX_pwm_curr_fdbk component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup ICS_G4XX_pwm_curr_fdbk */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef ICS_G4XX_PWMNCURRFDBK_H #define ICS_G4XX_PWMNCURRFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "pwm_curr_fdbk.h" /* Exported defines --------------------------------------------------------*/ #define NONE ((uint8_t)(0x00)) #define EXT_MODE ((uint8_t)(0x01)) #define INT_MODE ((uint8_t)(0x02)) /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup ICS_pwm_curr_fdbk * @{ */ /* Exported types ------------------------------------------------------- */ /* * @brief ICS_G4XX_pwm_curr_fdbk component parameters definition. */ typedef const struct { /* HW IP involved -----------------------------*/ ADC_TypeDef *ADCx_1; /* First ADC peripheral to be used.*/ ADC_TypeDef *ADCx_2; /* Second ADC peripheral to be used.*/ TIM_TypeDef *TIMx; /* Timer used for PWM generation.*/ uint32_t ADCConfig1; /*!< Value for ADC CR2 to properly configure current sampling during the context switching. Either defined in PWMC_ICS_Handle_t or in ICS_Params_t. Absent in F4XX. */ uint32_t ADCConfig2; /*!< Value for ADC CR2 to properly configure current sampling during the context switching. Either defined in PWMC_ICS_Handle_t or in ICS_Params_t. Absent in F4XX. */ uint8_t RepetitionCounter; /* Expresses the number of PWM periods to be elapsed before compare registers are updated again. In particular: RepetitionCounter= (2* #PWM periods)-1*/ /* Dual MC parameters --------------------------------------------------------*/ uint8_t FreqRatio; /* Used in case of dual MC to synchronize TIM1 and TIM8. It has effect only on the second instanced object and must be equal to the ratio between the two PWM frequencies (higher/lower). Supported values are 1, 2 or 3 */ uint8_t IsHigherFreqTim; /* When FreqRatio is greater than 1 this param is used to indicate if this instance is the one with the highest frequency. Allowed values are: HIGHER_FREQ or LOWER_FREQ */ } ICS_Params_t, *pICS_Params_t; /* * This structure is used to handle an instance of the ICS_G4XX_pwm_curr_fdbk component. */ typedef struct { PWMC_Handle_t _Super; /* Base component handler. */ uint32_t PhaseAOffset; /* Offset of Phase A current sensing network. */ uint32_t PhaseBOffset; /* Offset of Phase B current sensing network. */ uint16_t Half_PWMPeriod; /* Half PWM Period in timer clock counts. */ volatile uint8_t PolarizationCounter; /* Number of conversions performed during the calibration phase. */ bool ADCRegularLocked; /*!< This flag is set when regular conversions are locked. Specific to G4XX. */ /* Cut 2.2 patch*/ pICS_Params_t pParams_str; } PWMC_ICS_Handle_t; /* Exported functions ------------------------------------------------------- */ /* * Initializes TIMx, ADC, GPIO and NVIC for current reading * in ICS configuration using STM32G4XX. */ void ICS_Init(PWMC_ICS_Handle_t *pHandle); /* * Stores into the handler the voltage present on Ia and Ib current * feedback analog channels when no current is flowing into the motor. */ void ICS_CurrentReadingPolarization(PWMC_Handle_t *pHdl); /* * Computes and stores in the handler the latest converted motor phase currents in ab_t format. */ void ICS_GetPhaseCurrents(PWMC_Handle_t *pHdl, ab_t *Iab); /* * Turns on low sides switches. */ void ICS_TurnOnLowSides(PWMC_Handle_t *pHdl, uint32_t ticks); /* * Enables PWM generation on the proper Timer peripheral acting on MOE bit. */ void ICS_SwitchOnPWM(PWMC_Handle_t *pHdl); /* * Disables PWM generation on the proper Timer peripheral acting on MOE bit. */ void ICS_SwitchOffPWM(PWMC_Handle_t *pHdl); /* * Writes into peripheral registers the new duty cycle and sampling point. */ uint16_t ICS_WriteTIMRegisters(PWMC_Handle_t *pHdl); /* * Contains the TIMx Update event interrupt. */ void *ICS_TIMx_UP_IRQHandler(PWMC_ICS_Handle_t *pHdl); /* * Contains the TIMx Break2 event interrupt. */ void *ICS_BRK2_IRQHandler(PWMC_ICS_Handle_t *pHdl); /* * Contains the TIMx Break1 event interrupt. */ void *ICS_BRK_IRQHandler(PWMC_ICS_Handle_t *pHdl); /* * Stores in the handler the calibrated offsets. */ void ICS_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /* * Reads the calibrated offsets stored in the handler. */ void ICS_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*ICS_G4XX_PWMNCURRFDBK_H*/ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
6,573
C
33.239583
127
0.538871
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/G4xx/Inc/stspin32g4.h
/** ****************************************************************************** * @file stspin32g4.h * @author IPC Application Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * ICSSTSPIN32G4 driver library. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup stspin32g4_STSPIN32G4_DriverLib */ /** * * @defgroup stspin32g4_STSPIN32G4_DriverLib STSPIN32G4 Driver Library * @{ * * <h2>Operation</h2> * The STSPIN32G4 is a system in package integrating a triple high-performance * STSPIN32G4f-bridge gate driver with a rich set of programmable features * and one mixed signal STM32G431 microcontroller. * This library provides functions to configure STSPIN32G4 gate driver * but does not include functions to generate PWM signals for MOSFETs driving * * @pre This library requires at least HAL drivers 1.3.0 or Low-layer (LL) drivers 1.5.0 * * The library should be included in an application as follows: * @code * #include <stspin32g4.h> * @endcode * * <h3>Opening the driver</h3> * @code * STSPIN32G4_HandleTypeDef hdlG4; * * STSPIN32G4_StatusTypeDef res = STSPIN32G4_init(&hdlG4); * * if(res != STSPIN32G4_OK) * STSPIN32G4_deInit(&hdlG4); * @endcode * * <h3>Example</h3> * The following code shows a minimal device configuration to operate the gate driver * @code * // Purge registers to default values * STSPIN32G4_reset(&hdlG4); * * // Configure the Buck regulator at 12V and map VCC UVLO on NFAULT pin * STSPIN32G4_confVCC vcc = {.voltage = _12V, .useNFAULT=true, .useREADY=false}; * STSPIN32G4_setVCC(&hdlG4, vcc); * * // Configure VDSP protection with 4us deglitch time and map triggering on NFAULT pin * STSPIN32G4_confVDSP vdsp = {.deglitchTime=_4us, .useNFAULT=true}; * STSPIN32G4_setVDSP(&hdlG4, vdsp); * * // After reset a clearing of fault is needed to enable GHSx/GLSx outputs * STSPIN32G4_clearFaults(&hdlG4); * @endcode * <h3>Closing the driver</h3> * @code * // Reset the device to put GHSx/GLSx outputs in safe state * STSPIN32G4_reset(&hdlG4); * * // Close the driver * STSPIN32G4_deInit(&hdlG4); * @endcode * * <h3>Standby</h3> * * @code * // Enter Standby enabling low quiescent regulator * if(STSPIN32G4_OK == STSPIN32G4_standby(&hdlG4, true)) * { * // Stay 1s in standby * HAL_Delay(1000); // or LL_mDelay(1000); * * // Wakeup the driver waiting 4ms for completion of VCC soft-start * STSPIN32G4_wakeup(&hdlG4, 4); * } * else * { * // Consumption from 3.3V supply is likely too high * } * @endcode */ /** * @defgroup stspin32g4_Basic Basic * @brief Basic function and definitions to work with STSPIN32G4 * @{ * @} */ /** * @defgroup stspin32g4_PowerManagement Power Management * @brief Function and definitions to manage regulators embedded in STSPIN32G4 and standby * @{ * @} */ /** * @defgroup stspin32g4_Protections Protections * @brief Function and definitions to configure protection features of STSPIN32G4 * @{ * @} */ /** @defgroup stspin32g4_I2c Driver Registers @brief Function and definitions to directly access I2C registers of STSPIN32G4 @{ @} */ /** @} */ #ifndef STSPIN32G4 #define STSPIN32G4 #if defined(USE_FULL_LL_DRIVER) #include <stm32g4xx_ll_i2c.h> #include <stm32g4xx_ll_gpio.h> #include <stm32g4xx_ll_bus.h> #include <stm32g4xx_ll_cortex.h> #include <stm32g4xx_ll_rcc.h> #include <stm32g4xx_ll_utils.h> #else #include <stm32g4xx_hal.h> #include <stm32g4xx_hal_def.h> #include <stm32g4xx_hal_i2c.h> #endif #include <stdint.h> #include <stdbool.h> /** @ingroup stspin32g4_I2c @{ */ #define STSPIN32G4_I2C_LOCKUSEPARANOID /**< Flag to check status register lock bit in functions STSPIN32G4_lockReg() and STSPIN32G4_unlockReg() */ #define STSPIN32G4_I2C_ADDR (0x8E) /**< I2C address of STSPIN32G4 */ #define STSPIN32G4_I2C_POWMNG (0x01) /**< Address of register POWMNG */ #define STSPIN32G4_I2C_REG3V3_DIS (1<<6) /**< Bit REG3V3_DIS */ #define STSPIN32G4_I2C_VCC_DIS (1<<5) /**< Bit VCC_DIS */ #define STSPIN32G4_I2C_STBY_REG_EN (1<<4) /**< Bit STBY_REG_EN */ #define STSPIN32G4_I2C_VCC_VAL_0 (0) /**< Bits VCC_VAL as 00, (VCC=8V) */ #define STSPIN32G4_I2C_VCC_VAL_1 (1) /**< Bits VCC_VAL as 01, (VCC=10V) */ #define STSPIN32G4_I2C_VCC_VAL_2 (2) /**< Bits VCC_VAL as 10, (VCC=12V) */ #define STSPIN32G4_I2C_VCC_VAL_3 (3) /**< Bits VCC_VAL as 11, (VCC=15V) */ #define STSPIN32G4_I2C_LOGIC (0x02) /**< Address of register LOGIC */ #define STSPIN32G4_I2C_VDS_P_DEG_0 (0<<2) /**< Bits VDS_P_DEG as 00, (6us deglitch) */ #define STSPIN32G4_I2C_VDS_P_DEG_1 (1<<2) /**< Bits VDS_P_DEG as 01, (4us deglitch) */ #define STSPIN32G4_I2C_VDS_P_DEG_2 (2<<2) /**< Bits VDS_P_DEG as 10, (3us deglitch) */ #define STSPIN32G4_I2C_VDS_P_DEG_3 (3<<2) /**< Bits VDS_P_DEG as 11, (2us deglitch) */ #define STSPIN32G4_I2C_DTMIN (1<<1) /**< Bit DTMIN */ #define STSPIN32G4_I2C_ILOCK (1<<0) /**< Bit ILOCK */ #define STSPIN32G4_I2C_READY (0x07) /**< Address of register READY */ #define STSPIN32G4_I2C_STBY_RDY (1<<3) /**< Bit STBY_RDY */ #define STSPIN32G4_I2C_THSD_RDY (1<<1) /**< Bit THSD_RDY */ #define STSPIN32G4_I2C_VCC_UVLO_RDY (1<<0) /**< Bit VCC_UVLO_RDY */ #define STSPIN32G4_I2C_NFAULT (0x08) /**< Address of register NFAULT */ #define STSPIN32G4_I2C_RESET_FLT (1<<3) /**< Bit RESET_FLT */ #define STSPIN32G4_I2C_VDS_P_FLT (1<<2) /**< Bit VDS_P_FLT */ #define STSPIN32G4_I2C_THSD_FLT (1<<1) /**< Bit THSD_FLT */ #define STSPIN32G4_I2C_VCC_UVLO_FLT (1<<0) /**< Bit VCC_UVLO_FLT */ #define STSPIN32G4_I2C_CLEAR (0x09) /**< Address of register CLEAR */ #define STSPIN32G4_I2C_STBY (0x0A) /**< Address of register STBY */ #define STSPIN32G4_I2C_LOCK (0x0B) /**< Address of register LOCK */ #define STSPIN32G4_I2C_RESET (0x0C) /**< Address of register RESET */ #define STSPIN32G4_I2C_STATUS (0x80) /**< Address of register STATUS */ /** @} */ /** @ingroup stspin32g4_PowerManagement @{ */ #define STSPIN32G4_HSI16 /**< Flag to automatically reduce system clock frequency before entering standby in function STSPIN32G4_standby() */ /** @brief Possible results of library functions. */ typedef enum { STSPIN32G4_OK = 0, /**< Operation successfully completed. */ STSPIN32G4_ERROR = 1, /**< Operation failed. */ STSPIN32G4_BUSY = 2, /**< The operation cannot be performed since a needed resource is not ready or available. */ STSPIN32G4_TIMEOUT = 3 /**< A timeout occurred before operation ended. */ } STSPIN32G4_StatusTypeDef; /** @brief Configuration for VCC voltage to be used with functions STSPIN32G4_setVCC() and STSPIN32G4_getVCC(). @details The STSPIN32G4 embeds a Buck converter to generate the supply voltage for the gate drivers, VCC, starting from the motor supply voltage. \n Four different VCC output values can be selected. \n The Under Voltage Lock Out (UVLO) condition of VCC can be signaled via pins nFAULT and READY. */ typedef struct { /** @brief VCC voltage selection. @details When VCC set point is changed the Buck converter performs a soft-start ramp. */ enum valVCC { _EXT = 0, /**< Buck converter is disabled and VCC should be supplied externally. */ _8V, /**< VCC = 8V generetad by Buck converter. Deafult value. */ _10V, /**< VCC = 10V generetad by Buck converter. */ _12V, /**< VCC = 12V generetad by Buck converter. */ _15V /**< VCC = 15V generetad by Buck converter. */ } voltage; /**< Value assigned to VCC voltage */ bool useNFAULT; /**< If true the nNFAULT pin goes low when device is in VCC UVLO condition. */ bool useREADY; /**< If true the READY pin goes low when device is in VCC UVLO condition. */ } STSPIN32G4_confVCC; /** @} */ /** @brief Configuration for VDS monitoring protection to be used with functions STSPIN32G4_setVDSP() and STSPIN32G4_getVDSP(). @details The STSPIN32G4 embeds a circuitry which measures the voltage between the drain and the source of each MOSFET (VDS) and compares it with a specified threshold set by voltage of SCREF pin. In case an overvoltage of one MOSFET is detected, all gate driver outputs GHSx and GLSx go low whatever the driver inputs INHx and INLx. \n The protection provides a deglitch filtering with configurable value. \n Triggering of the protection can be signaled via nFAULT pin. \n Function STSPIN32G4_clearFaults() can be used to clear the fault condition and make the device operative again. @ingroup stspin32g4_Protections */ typedef struct { /** @brief Deglitch filtering time for VDS protection. @ingroup stspin32g4_Protections */ enum degVDSP { _6us = 0, /**< 6 micro seconds. Deafult value. */ _4us, /**< 4 micro seconds */ _3us, /**< 3 micro seconds */ _2us /**< 2 micro seconds */ } deglitchTime; /**< Value assigned to deglitch filtering time of VDS protection */ bool useNFAULT; /**< If true the nNFAULT pin goes low in case of VDS protection triggering. */ } STSPIN32G4_confVDSP; /** @brief Configuration for Thermal Shutdown signaling to be used with functions STSPIN32G4_setTHSD() and STSPIN32G4_getTHSD(). @details The STSPIN32G4 embeds one Buck converter and one LDO linear regulator. Both voltage regulators are protected in case of overheating by thermal shutdown. \n The protection is always active and its triggering can be signaled via nFAULT and READY pins. @ingroup stspin32g4_Protections */ typedef struct { bool useNFAULT; /**< If true the nFAULT pin goes low in case of Thermal Shutdown. */ bool useREADY; /**< If true the READY pin goes low in case of Thermal Shutdown. */ } STSPIN32G4_confTHSD; /** @brief Status register fileds to be used with function STSPIN32G4_getStatus() @ingroup stspin32g4_Basic */ typedef struct { uint8_t vccUvlo:1; /**< If 1 the device is in VCC UVLO condition. While in VCC UVLO condition the device cannot drive MOSFETs*/ uint8_t thsd:1; /**< If 1 one voltage regulator is in Thermal Shutdown. While in Thermal Shutdown the device cannot drive MOSFETs*/ uint8_t vdsp:1; /**< If 1 the VDS protection triggered. Use STSPIN32G4_clearFaults() to make the device operative again. */ uint8_t reset:1; /**< If 1 the device performed a reset or power up. Use STSPIN32G4_clearFaults() to make the device operative. */ uint8_t r1:1; /**< Reserved. */ uint8_t r2:1; /**< Reserved. */ uint8_t r3:1; /**< Reserved. */ uint8_t lock:1; /**< If 1 the protected registers are locked and cannot be modified. */ } STSPIN32G4_statusRegTypeDef; /** @brief Handler of STSPIN32G4 driver to be used with all driver functions @see STSPIN32G4_init() for example code @ingroup stspin32g4_Basic */ typedef struct { #if defined(USE_FULL_LL_DRIVER) I2C_TypeDef *i2cHdl; /**< Handler to i2c3 */ #else I2C_HandleTypeDef *i2cHdl; /**< Handler to i2c3 */ #endif } STSPIN32G4_HandleTypeDef; /** @brief Initialize the STSPIN32G4 driver @pre The STSPIN32G4_HandleTypeDef structure must exist and be persistent before this function can be called. \n This function must also be called before any other driver APIs. \n The driver uses I2C3 interface which must be already initialized. \n Initialization example: @code STSPIN32G4_HandleTypeDef hdlG4; STSPIN32G4_StatusTypeDef ret = STSPIN32G4_init(&hdlG4); @endcode @param [out] hdl Driver handler @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_Basic */ STSPIN32G4_StatusTypeDef STSPIN32G4_init(STSPIN32G4_HandleTypeDef *hdl); /** @brief De-initialize the STSPIN32G4 driver @param [in] hdl Driver handler @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_Basic */ STSPIN32G4_StatusTypeDef STSPIN32G4_deInit(STSPIN32G4_HandleTypeDef *hdl); /** @brief Perform a reset. All registers will be set to their default values. @param [in] hdl Driver handler @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_Basic */ STSPIN32G4_StatusTypeDef STSPIN32G4_reset(STSPIN32G4_HandleTypeDef *hdl); /** @brief Get the status register @see STSPIN32G4_statusRegTypeDef @param [in] hdl Driver handler @param [out] status Current value of the status register @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_Basic */ STSPIN32G4_StatusTypeDef STSPIN32G4_getStatus(STSPIN32G4_HandleTypeDef *hdl, STSPIN32G4_statusRegTypeDef *status); /** @brief Enable or Disable the LDO linear regulator @param [in] hdl Driver handler @param [in] enabled If 1 the 3.3V supply is internally generated via the LDO linear regulator. \n If 0 the LDO regulator is disabled and the 3.3V supply have to be provided externally. @warning The device will perform a reset if the LDO is disabled without providing externally the 3.3V supply. @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_PowerManagement */ STSPIN32G4_StatusTypeDef STSPIN32G4_set3V3(STSPIN32G4_HandleTypeDef *hdl, bool enabled); /** @brief Get current configuration of LDO linear regulator @param [in] hdl Driver handler @param [out] enabled Set to 1 if the internal LDO is active, 0 otherwise. @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_PowerManagement */ STSPIN32G4_StatusTypeDef STSPIN32G4_get3V3(STSPIN32G4_HandleTypeDef *hdl, bool *enabled); /** @brief Configures the Buck converter and VCC UVLO signaling @see STSPIN32G4_confVCC @param [in] hdl Driver handler @param [in] vcc VCC configuration to be applied \n Example to set VCC at 12V and enable VCC UVLO singaling on NFAULT pin: @code STSPIN32G4_confVCC vcc = {.voltage = _12V, .useNFAULT=true, .useREADY=false}; STSPIN32G4_StatusTypeDef ret = STSPIN32G4_setVCC(&hdlG4, vcc); @endcode @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_PowerManagement **/ STSPIN32G4_StatusTypeDef STSPIN32G4_setVCC(STSPIN32G4_HandleTypeDef *hdl, STSPIN32G4_confVCC vcc); /** @brief Get current configuration of Buck converter and VCC UVLO signaling @see STSPIN32G4_confVCC @param [in] hdl Driver handler @param [out] vcc Current VCC configuration @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_PowerManagement */ STSPIN32G4_StatusTypeDef STSPIN32G4_getVCC(STSPIN32G4_HandleTypeDef *hdl, STSPIN32G4_confVCC *vcc); /** @brief Configures the Thermal Shutdown signaling @see STSPIN32G4_confTHSD @param [in] hdl Driver handler @param [in] thsd Configuration of Thermal Shutdown signaling to be applied @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_Protections */ STSPIN32G4_StatusTypeDef STSPIN32G4_setTHSD(STSPIN32G4_HandleTypeDef *hdl, STSPIN32G4_confTHSD thsd); /** @brief Get current configuration of the Thermal Shutdown signaling @see STSPIN32G4_confTHSD @param [in] hdl Driver handler @param [out] thsd Current configuration of Thermal Shutdown signaling @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_Protections */ STSPIN32G4_StatusTypeDef STSPIN32G4_getTHSD(STSPIN32G4_HandleTypeDef *hdl, STSPIN32G4_confTHSD *thsd); /** @brief Requests the device to enter standby mode @details In standby mode the device turns off most of its internal circuitry with inclusion of Buck converter, LDO linear regulator and gate drivers. \n In standby the overall current consumption is reduced to ~15uA and the MCU can be supplied via dedicated low quiescent linear regulator from main supply voltage. @param [in] hdl Driver handler @param [in] enableStbyReg If 1 the internal low quiescent linear regulator will be activated when entering standby mode @warning Overall consumption from 3.3V supply should be reduced as much as possible before entering standby. \n In case the consumption exceeds 5mA the device will automatically exit from standby performing a reset. \n Disable all MCU peripherals and reduce system clock frequency before calling function STSPIN32G4_standby(). \n If flag STSPIN32G4_HSI16 is used, the driver will automatically reduce system clock frequency. @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_PowerManagement */ STSPIN32G4_StatusTypeDef STSPIN32G4_standby(STSPIN32G4_HandleTypeDef *hdl, bool enableStbyReg); /** @brief Wake up from standby @param [in] hdl Driver handler @param [in] timeout_ms Timeout in milliseconds allowed for device wake up. The minimum value is 4. @return STSPIN32G4_ERROR in case of failure \n STSPIN32G4_TIMEOUT in case the timeout time elapsed before device returned operative \n STSPIN32G4_OK in case of proper wake up @ingroup stspin32g4_PowerManagement */ STSPIN32G4_StatusTypeDef STSPIN32G4_wakeup(STSPIN32G4_HandleTypeDef *hdl, uint8_t timeout_ms); /** @brief Configures the interlocking @details The device integrates interlocking features that prevents the power stage from accidental cross conduction. \n HS and LS MOSFET of same channel cannot be turned on simultaneously when interlocking is active. @param [in] hdl Driver handler @param [in] enabled If 1 the interlocking is enabled. \n If 0 the interlocking is disabled. @warning Disable the interlocking is potentially desruptive for power stage. @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_Protections */ STSPIN32G4_StatusTypeDef STSPIN32G4_setInterlocking(STSPIN32G4_HandleTypeDef *hdl, bool enabled); /** @brief Get current configuration of the interlocking @param [in] hdl Driver handler @param [out] enabled If 1 the interlocking is enabled. \n If 0 the interlocking is disabled. @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_Protections */ STSPIN32G4_StatusTypeDef STSPIN32G4_getInterlocking(STSPIN32G4_HandleTypeDef *hdl, bool *enabled); /** @brief Configures the minimum deadtime @details The device integrates a minimum deadtime features. When enabled a minimum delay is imposed between the turn-off of one MOSFET and the turn-on of the complementary one. @param [in] hdl Driver handler @param [in] enabled If 1 the minimum deadtime is enabled \n If 0 the the minimum deadtime is disabled. \n The minimum deadtime is not added to the one imposed by the MCU @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_Protections */ STSPIN32G4_StatusTypeDef STSPIN32G4_setMinimumDeadTime(STSPIN32G4_HandleTypeDef *hdl, bool enabled); /** @brief Get current configuration of the minimum deadtime @param [in] hdl Driver handler @param [out] enabled If 1 the minimum deadtime is enabled \n If 0 the the minimum deadtime is disabled. @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_Protections */ STSPIN32G4_StatusTypeDef STSPIN32G4_getMinimumDeadTime(STSPIN32G4_HandleTypeDef *hdl, bool *enabled); /** @brief Configures the VDS monitoring protection @see STSPIN32G4_confVDSP @param [in] hdl Driver handler. @param [in] vdsp Settings of the VDS protection. @note Example to set deglitch time to 4 microsenconds and enable signaling on NFAULT pin: @code STSPIN32G4_confVDSP vdsp = {.deglitchTime=_4us, .useNFAULT=true}; STSPIN32G4_StatusTypeDef ret = STSPIN32G4_setVDSP(&hdlG4, vdsp); @endcode @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_Protections */ STSPIN32G4_StatusTypeDef STSPIN32G4_setVDSP(STSPIN32G4_HandleTypeDef *hdl, STSPIN32G4_confVDSP vdsp); /** @brief Get current configuration for the VDS monitoring protection @see STSPIN32G4_confVDSP @param [in] hdl Driver handler. @param [out] vdsp Current configuration for the VDS protection. @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_Protections */ STSPIN32G4_StatusTypeDef STSPIN32G4_getVDSP(STSPIN32G4_HandleTypeDef *hdl, STSPIN32G4_confVDSP *vdsp); /** @brief Clear a fault condition @param [in] hdl Driver handler. @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_Basic */ STSPIN32G4_StatusTypeDef STSPIN32G4_clearFaults(STSPIN32G4_HandleTypeDef *hdl); /** @brief Lock protected registers @param [in] hdl Driver handler. @note With flag STSPIN32G4_I2C_LOCKUSEPARANOID the lock bit of status register will be tested to 1 at the end of locking. @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_I2c */ STSPIN32G4_StatusTypeDef STSPIN32G4_lockReg(STSPIN32G4_HandleTypeDef *hdl); /** @brief Un-Lock protected registers @param [in] hdl Driver handler. @note With flag STSPIN32G4_I2C_LOCKUSEPARANOID the lock bit of status register will be tested to 0 at the end of unlocking. @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_I2c */ STSPIN32G4_StatusTypeDef STSPIN32G4_unlockReg(STSPIN32G4_HandleTypeDef *hdl); /** @brief Read register at address @p regAddr @param [in] hdl Driver handler. @param [in] regAddr Address of the register to read. @param [out] value Contains the register value. @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_I2c */ STSPIN32G4_StatusTypeDef STSPIN32G4_readReg(STSPIN32G4_HandleTypeDef *hdl, uint8_t regAddr, uint8_t *value); /** @brief Write register at address @p regAddr @param [in] hdl Driver handler. @param [in] regAddr Address of the register to write. @param [in] value Content to write in the register. @warning Before writing a protected register use function STSPIN32G4_unlockReg() @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_I2c */ STSPIN32G4_StatusTypeDef STSPIN32G4_writeReg(STSPIN32G4_HandleTypeDef *hdl, uint8_t regAddr, uint8_t value); /** @brief Write register at address @p regAddr then read back register and verify value matching @param [in] hdl Driver handler. @param [in] regAddr Address of the register to write. @param [in] value Content to write in the register. @warning Before writing a protected register use function STSPIN32G4_unlockReg() @return STSPIN32G4_ERROR in case of failure otherwise STSPIN32G4_OK. @ingroup stspin32g4_I2c */ STSPIN32G4_StatusTypeDef STSPIN32G4_writeVerifyReg(STSPIN32G4_HandleTypeDef *hdl, uint8_t regAddr, uint8_t value); #endif //#define STSPIN32G4
23,205
C
38.736301
147
0.727559
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/G4xx/Inc/g4xx_bemf_ADC_fdbk.h
/** ****************************************************************************** * @file g4xx_bemf_ADC_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * Sensorless Bemf acquisition with ADC component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup SpeednPosFdbk_Bemf */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef BEMFADCFDBK_H #define BEMFADCFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "speed_pos_fdbk.h" #include "speed_ctrl.h" #include "pwm_common_sixstep.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup SpeednPosFdbk * @{ */ /** @addtogroup SpeednPosFdbk_Bemf * @{ */ #define SPEED_BUFFER_LENGTH ((uint8_t) 18) /*!< Length of buffer used to store the timer period measurements */ /** * @brief Bemf_ADC parameters definition */ typedef struct { TIM_TypeDef * LfTim; /*!< Contains the pointer to the LF timer used for speed measurement. */ uint32_t LfTimerChannel; /*!< Channel of the LF timer used for speed measurement */ ADC_TypeDef * pAdc[3]; /*!< Pointer to the ADC */ uint32_t AdcChannel[3]; /*!< Array of ADC channels used for BEMF sensing */ bool gpio_divider_available; /*!< Availability of the GPIO port enabling the bemf resistor divider */ GPIO_TypeDef * bemf_divider_port; /*!< GPIO port enabling the bemf resistor divider */ uint16_t bemf_divider_pin; /*!< GPIO pin enabling the bemf resistor divider */ } Bemf_ADC_Params_t; /** * @brief This structure is used to handle the thresholds for bemf zero crossing detection * */ typedef struct { uint16_t AdcThresholdDown; /*!< BEMF voltage threshold for zero crossing detection when BEMF is decreasing */ uint16_t AdcThresholdUp; /*!< BEMF voltage threshold for zero crossing detection when BEMF is increasing */ uint16_t SamplingPoint; /*!< Pulse value of the timer channel used to trig the ADC */ } Bemf_Sensing_Params; /** * @brief This structure is used to handle the demagnetization time before starting bemf acquisition * */ typedef struct { uint16_t DemagMinimumSpeedUnit; /*!< Speed threshold for minimum demagnetization time */ uint16_t RevUpDemagSpeedConv; /*!< Convertion factor between speed and demagnetization time */ uint16_t RunDemagSpeedConv; /*!< Open loop convertion factor between speed and demagnetization time during */ uint16_t DemagMinimumThreshold; /*!< Minimum demagnetization time */ } Bemf_Demag_Params; /** * @brief This structure is used to handle the data of an instance of the B-emf Feedback component * */ typedef struct { SpeednPosFdbk_Handle_t _Super; uint16_t BemfLastValues[3]; /**< Bemf measurements of phase */ uint8_t ZcEvents; /**< Number of bemf zero crossing events */ Bemf_Sensing_Params Pwm_ON; /**< Parameters for zero crossing detection during ON time */ Bemf_Sensing_Params Pwm_OFF; /**< Parameters for zero crossing detection during OFF time */ Bemf_Sensing_Params *pSensing_Params; uint16_t SamplingGuard; bool IsOnSensingEnabled; /*!< Value where 0 means BEMF is sensed during PWM OFF time and 1 or greater means BEMF is sensed during PWM ON time */ uint16_t OnSensingEnThres; /*!< Pulse value of HF timer above which the PWM ON sensing is enabled */ uint16_t OnSensingDisThres; /*!< Pulse value of HF timer below which the PWM ON sensing is disabled */ uint16_t Zc2CommDelay; /*!< Zero Crossing detection to commutation delay in 15/128 degrees */ Bemf_ADC_Params_t const *pParams_str; uint16_t SpeedSamplingFreqHz; /*!< Frequency (Hz) at which motor speed is to be computed. It must be equal to the frequency at which function SPD_CalcAvrgMecSpeedUnit is called.*/ uint8_t SpeedBufferSize; /*!< Size of the buffer used to calculate the average speed. It must be less than 18.*/ uint32_t TIMClockFreq; bool ADCRegularLocked; /*!< This flag is set when ADC is locked for bemf acquisition */ int32_t ElPeriodSum; /*!< Period accumulator used to speed up the average speed computation*/ int16_t PrevRotorFreq; /*!< Used to store the last valid rotor electrical speed in dpp used when MAX_PSEUDO_SPEED is detected */ int8_t Direction; /*!< Instantaneous direction of rotor between two captures*/ int16_t AvrElSpeedDpp; /*!< Averaged rotor electrical speed express in s16degree per current control period.*/ int16_t VirtualElSpeedDpp; /*!< Averaged rotor electrical speed express in s16degree per current control period.*/ uint16_t MinStartUpValidSpeed; /*!< Absolute value of minimum mechanical speed required to validate the start-up. Expressed in the unit defined by #SPEED_UNIT. */ uint8_t StartUpConsistThreshold; /*!< Number of consecutive tests on speed consistency to be passed before validating the start-up */ uint8_t OverSamplingRate; bool IsSpeedReliable; /*!< Latest private speed reliability information, updated by SPD_CalcAvrgMecSpeedUnit, it is true if the speed measurement variance is lower then threshold corresponding to hVariancePercentage */ bool IsAlgorithmConverged; /*!< Boolean variable containing observer convergence information */ bool IsLoopClosed; /*!< Boolean variable containing speed loop status*/ bool ZcDetected; /*!< This flag is set when zero crossing is detected */ bool StepUpdate; /*!< This flag is set when step needs to be updated */ DrivingMode_t DriveMode; volatile uint8_t BufferFilled; /*!< Indicates the number of speed measuremt present in the buffer from the start. It will be max bSpeedBufferSize and it is used to validate the start of speed averaging. If bBufferFilled is below bSpeedBufferSize the instantaneous measured speed is returned as average speed.*/ int32_t SpeedBufferDpp[SPEED_BUFFER_LENGTH];/*!< Holding the last period captures */ uint32_t LowFreqTimerPsc; /*!< Prescaler value of the low frequency timer */ uint16_t SpeedFIFOIdx;/*!< Pointer of next element to be stored in the speed sensor buffer*/ int16_t DeltaAngle; /*!< Delta angle at the Hall sensor signal edge between current electrical rotor angle of synchronism. It is in s16degrees.*/ int16_t MeasuredElAngle;/*!< Electrical angle measured at each bemf zero crossing. It is considered the best measurement of electrical rotor angle.*/ int16_t CompSpeed; /*!< Speed compensation factor used to syncronize the current electrical angle with the target electrical angle. */ uint16_t SatSpeed; /*!< Returned value if the measured speed is above the maximum realistic.*/ uint32_t PseudoPeriodConv;/*!< Conversion factor between time interval Delta T between bemf zero crossing points, express in timer counts, and electrical rotor speed express in dpp. Ex. Rotor speed (dpp) = wPseudoFreqConv / Delta T It will be ((CKTIM / 6) / (SAMPLING_FREQ)) * 65536.*/ uint32_t MaxPeriod; /*!< Time delay between two bemf zero crossing points when the speed of the rotor is the minimum realistic in the application: this allows to discriminate too low freq for instance. This period shoud be expressed in timer counts and it will be: wMaxPeriod = ((10 * CKTIM) / 6) / MinElFreq(0.1Hz).*/ uint32_t MinPeriod; /*!< Time delay between two bemf zero crossing points when the speed of the rotor is the maximum realistic in the application: this allows discriminating glitches for instance. This period shoud be expressed in timer counts and it will be: wSpeedOverflow = ((10 * CKTIM) / 6) / MaxElFreq(0.1Hz).*/ uint16_t BemfTimeout;/*!< Max delay between two zero crossing signals to assert zero speed express in milliseconds.*/ uint16_t OvfFreq; /*!< Frequency of timer overflow (from 0 to 0x10000) it will be: hOvfFreq = CKTIM /65536.*/ uint16_t PWMNbrPSamplingFreq; /*!< Number of current control periods inside each speed control periods it will be: (hMeasurementFrequency / hSpeedSamplingFreqHz) - 1.*/ uint8_t PWMFreqScaling; /*!< Scaling factor to allow to store a PWMFrequency greater than 16 bits */ uint32_t Counter_Period; /*!< Low frequency timer period that allows speed calculation */ uint32_t ZC_Counter_Up; /*!< Low frequency timer counter value at zero crossing with increasing bemf */ uint32_t ZC_Counter_Down; /*!< Low frequency timer counter value at zero crossing with increasing bemf */ uint32_t ZC_Counter_Last; /*!< Last low frequency timer counter value at zero crossing sensed with pwm off*/ uint32_t ZC_Counter_On_Last; /*!< Last low frequency timer counter value at zero crossing sensed with pwm on. Specific to G4XX.*/ uint32_t Last_Zc2Comm_Delay; /*!< Last delay between zero crossing and step change */ uint16_t DemagCounter; /*!< Demagnetization counter */ uint16_t DemagCounterThreshold; /*!< PWM cycles dedicated to windings demagnetization */ Bemf_Demag_Params DemagParams; /*!< Demagnetization parameters */ } Bemf_ADC_Handle_t; /* Exported functions --------------------------------------------------------*/ /* Initializes all the object variables. */ void BADC_Init( Bemf_ADC_Handle_t *pHandle ); /* Resets the ADC status and empties arrays. */ void BADC_Clear( Bemf_ADC_Handle_t *pHandle ); /* Gets ADC value and check for zero crossing detection.*/ bool BADC_IsZcDetected( Bemf_ADC_Handle_t *pHandle, PWMC_Handle_t *pHandlePWMC); /* Sets the trigger point of the ADC */ void BADC_SetSamplingPoint(Bemf_ADC_Handle_t *pHandle, PWMC_Handle_t *pHandlePWMC, SpeednTorqCtrl_Handle_t *pHandleSTC ); /* Computes the rotor average mechanical speed in the unit defined by #SPEED_UNIT and returns it in pMecSpeedUnit. */ bool BADC_CalcAvrgMecSpeedUnit( Bemf_ADC_Handle_t * pHandle, int16_t * pMecSpeedUnit ); /* Forces the rotation direction. */ void BADC_SetDirection( Bemf_ADC_Handle_t * pHandle, uint8_t direction ); /* Checks whether the state observer algorithm converged.*/ bool BADC_IsObserverConverged( Bemf_ADC_Handle_t * pHandle ); /* Starts the bemf acquisition.*/ void BADC_Start(Bemf_ADC_Handle_t *pHandle, uint8_t step); /* Stops the bemf acquisition.*/ void BADC_Stop(Bemf_ADC_Handle_t *pHandle); /* Selects the phase for the bemf acquisition.*/ void BADC_SelectAdcChannel(Bemf_ADC_Handle_t * pHandle, uint8_t Phase); /* Updates the estimated electrical angle.*/ int16_t BADC_CalcElAngle(Bemf_ADC_Handle_t * pHandle); /* Configures the sensorless parameters for the following step. */ void BADC_StepChangeEvent(Bemf_ADC_Handle_t * pHandle, int16_t hElSpeedDpp, PWMC_Handle_t *pHandlePWMC); /* Computes the demagnetization time during revup procedure. */ void BADC_CalcRevUpDemagTime(Bemf_ADC_Handle_t *pHandle); /* Computes the demagnetization time in closed loop operation.*/ void BADC_CalcRunDemagTime(Bemf_ADC_Handle_t *pHandle); /* Sets the flag when switch over phase ends.*/ void BADC_SetLoopClosed(Bemf_ADC_Handle_t *pHandle); /* Returns last converted Back-emf value.*/ uint16_t BADC_GetLastBemfValue(Bemf_ADC_Handle_t *pHandle, uint8_t phase); /* Returns the zero crossing detection flag. */ bool BADC_GetBemfZcrFlag(Bemf_ADC_Handle_t *pHandle); /* Enables low frequecy timer interrupt */ void BADC_SpeedMeasureOn(Bemf_ADC_Handle_t *pHandle); /* Disables low frequecy timer interrupt */ void BADC_SpeedMeasureOff(Bemf_ADC_Handle_t *pHandle); /* Clears StepUpdate flag */ bool BADC_ClearStepUpdate(Bemf_ADC_Handle_t *pHandle); /* Sets the parameters for bemf sensing during pwm off-time */ void BADC_SetBemfSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfAdcConfig, uint16_t *Zc2CommDelay, Bemf_Demag_Params *bemfAdcDemagConfig); /* Sets the parameters for bemf sensing during pwm on-time */ void BADC_SetBemfOnTimeSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfOnAdcConfig, uint16_t *OnSensingEnThres, uint16_t *OnSensingDisThres); /* Gets the parameters for bemf sensing during pwm off-time */ void BADC_GetBemfSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfAdcConfig, uint16_t *Zc2CommDelay, Bemf_Demag_Params *bemfAdcDemagConfig); /* Gets the parameters for bemf sensing during pwm on-time */ void BADC_GetBemfOnTimeSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfOnAdcConfig, uint16_t *OnSensingEnThres, uint16_t *OnSensingDisThres); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* BEMFADCFDBK_H */ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
15,318
C
50.40604
152
0.612547
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/G4xx/Inc/r3_3_g4xx_pwm_curr_fdbk.h
/** ****************************************************************************** * @file r3_3_g4xx_pwm_curr_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * R3_3_G4XX_pwm_curr_fdbk component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics International N.V. * All rights reserved.</center></h2> * * Redistribution and use in source and binary forms, with or without * modification, are permitted, provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of other * contributors to this software may be used to endorse or promote products * derived from this software without specific written permission. * 4. This software, including modifications and/or derivative works of this * software, must execute solely and exclusively on microcontroller or * microprocessor devices manufactured by or for STMicroelectronics. * 5. Redistribution and use of this software other than as permitted under * this license is void and will automatically terminate your rights under * this license. * * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT * SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** * @ingroup R3_3_G4XX_pwm_curr_fdbk */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __R3_3_G4XX_PWMNCURRFDBK_H #define __R3_3_G4XX_PWMNCURRFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "pwm_curr_fdbk.h" /* Exported defines --------------------------------------------------------*/ #define GPIO_NoRemap_TIM1 ((uint32_t)(0)) #define SHIFTED_TIMs ((uint8_t) 1) #define NO_SHIFTED_TIMs ((uint8_t) 0) #define NONE ((uint8_t)(0x00)) #define EXT_MODE ((uint8_t)(0x01)) #define INT_MODE ((uint8_t)(0x02)) /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup R3_3_G4XX_pwm_curr_fdbk * @{ */ /* Exported types ------------------------------------------------------- */ /** * @brief R3_3_G4XX_pwm_curr_fdbk component OPAMP parameters definition */ typedef const struct { /* First OPAMP settings ------------------------------------------------------*/ OPAMP_TypeDef *OPAMP_PHA; /* OPAMP dedicated to phase A */ OPAMP_TypeDef *OPAMP_PHB; /* OPAMP dedicated to phase B */ OPAMP_TypeDef *OPAMP_PHC; /* OPAMP dedicated to phase C */ uint32_t wOPAMP_InvertingInput; /*!< First OPAMP inverting input pin. It must be one of the following: OPAMP1_InvertingInput_PC5 or OPAMP1_InvertingInput_PA3 if the bOPAMP_InvertingInput_MODE is EXT_MODE or OPAMP1_InvertingInput_PGA or OPAMP1_InvertingInput_FOLLOWER if the bOPAMP_InvertingInput_MODE is INT_MODE.*/ uint32_t wOPAMP_NonInvertingInput_PHA; uint32_t wOPAMP_NonInvertingInput_PHB; uint32_t wOPAMP_NonInvertingInput_PHC; } R3_3_G4XXOPAMPParams_t, *pR3_3_G4XXOPAMPParams_t; /** * @brief R3_3_G4XX_pwm_curr_fdbk component parameters definition */ typedef const struct { /* Dual MC parameters --------------------------------------------------------*/ uint8_t bFreqRatio; /*!< It is used in case of dual MC to synchronize TIM1 and TIM8. It has effect only on the second instanced object and must be equal to the ratio between the two PWM frequencies (higher/lower). Supported values are 1, 2 or 3 */ uint8_t bIsHigherFreqTim; /*!< When bFreqRatio is greather than 1 this param is used to indicate if this instance is the one with the highest frequency. Allowed value are: HIGHER_FREQ or LOWER_FREQ */ /* Current reading A/D Conversions initialization -----------------------------*/ ADC_TypeDef *ADCx_A; /*!< First ADC peripheral to be used.*/ ADC_TypeDef *ADCx_B; /*!< Second ADC peripheral to be used.*/ ADC_TypeDef *ADCx_C; /*!< Third ADC peripheral to be used.*/ /* PWM generation parameters --------------------------------------------------*/ uint8_t RepetitionCounter; /*!< It expresses the number of PWM periods to be elapsed before compare registers are updated again. In particular: @f$ RepetitionCounter\ =\ (2\times PWM\ Periods)\ -\ 1 @f$ */ uint16_t hTafter; /*!< It is the sum of dead time plus max value between rise time and noise time express in number of TIM clocks.*/ uint16_t hTbefore; /*!< It is the sampling time express in number of TIM clocks.*/ TIM_TypeDef *TIMx; /*!< It contains the pointer to the timer used for PWM generation. It must equal to TIM1 if bInstanceNbr is equal to 1, to TIM8 otherwise */ /* PWM Driving signals initialization ----------------------------------------*/ LowSideOutputsFunction_t LowSideOutputs; /*!< Low side or enabling signals generation method are defined here.*/ GPIO_TypeDef *pwm_en_u_port; /*!< Channel 1N (low side) GPIO output port (if used, after re-mapping). It must be GPIOx x= A, B, ...*/ uint16_t pwm_en_u_pin; /*!< Channel 1N (low side) GPIO output pin (if used, after re-mapping). It must be GPIO_Pin_x x= 0, 1, ...*/ GPIO_TypeDef *pwm_en_v_port; /*!< Channel 2N (low side) GPIO output port (if used, after re-mapping). It must be GPIOx x= A, B, ...*/ uint16_t pwm_en_v_pin; /*!< Channel 2N (low side) GPIO output pin (if used, after re-mapping). It must be GPIO_Pin_x x= 0, 1, ...*/ GPIO_TypeDef *pwm_en_w_port; /*!< Channel 3N (low side) GPIO output port (if used, after re-mapping). It must be GPIOx x= A, B, ...*/ uint16_t pwm_en_w_pin; /*!< Channel 3N (low side) GPIO output pin (if used, after re-mapping). It must be GPIO_Pin_x x= 0, 1, ...*/ /* Internal OPAMP common settings --------------------------------------------*/ pR3_3_G4XXOPAMPParams_t pOPAMPParams; /*!< Pointer to the OPAMP params struct. It must be #MC_NULL if internal OPAMP are not used.*/ /* Internal COMP settings ----------------------------------------------------*/ COMP_TypeDef *wCompOCPASelection; /*!< Internal comparator used for protection. It must be COMP_Selection_COMPx x = 1,2,3,4,5,6,7.*/ uint8_t bCompOCPAInvInput_MODE; /*!< COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. */ COMP_TypeDef *wCompOCPBSelection; /*!< Internal comparator used for protection. It must be COMP_Selection_COMPx x = 1,2,3,4,5,6,7.*/ uint8_t bCompOCPBInvInput_MODE; /*!< COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. */ COMP_TypeDef *wCompOCPCSelection; /*!< Internal comparator used for protection. It must be COMP_Selection_COMPx x = 1,2,3,4,5,6,7.*/ uint8_t bCompOCPCInvInput_MODE; /*!< COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. */ COMP_TypeDef *wCompOVPSelection; /*!< Internal comparator used for protection. It must be COMP_Selection_COMPx x = 1,2,3,4,5,6,7.*/ uint8_t bCompOVPInvInput_MODE; /*!< COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. */ /* DAC settings --------------------------------------------------------------*/ uint16_t hDAC_OCP_Threshold; /*!< Value of analog reference expressed as 16bit unsigned integer. Ex. 0 = 0V ; 65536 = VDD_DAC.*/ uint16_t hDAC_OVP_Threshold; /*!< Value of analog reference expressed as 16bit unsigned integer. Ex. 0 = 0V ; 65536 = VDD_DAC.*/ /* Regular conversion --------------------------------------------------------*/ ADC_TypeDef *regconvADCx; /*!< ADC peripheral used for regular conversion.*/ } R3_3_G4XXParams_t, *pR3_3_G4XXParams_t; /** * @brief Handles an instance of the R3_3_G4XX_pwm_curr_fdbk component parameters structure definition. */ typedef struct { PWMC_Handle_t _Super; /*!< Base component handler. */ uint32_t wPhaseAOffset; /*!< Offset of Phase A current sensing network. */ uint32_t wPhaseBOffset; /*!< Offset of Phase B current sensing network. */ uint32_t wPhaseCOffset; /*!< Offset of Phase C current sensing network. */ uint32_t wADC_JSQR_phA; /*!< Injected sequence register for the ADC sampling phase A. */ uint32_t wADC_JSQR_phB; /*!< Injected sequence register for the ADC sampling phase B. */ uint32_t wADC_JSQR_phC; /*!< Injected sequence register for the ADC sampling phase C. */ uint32_t wOAMP1CR; /*!< OAMP1 control register to select channel current sampling. */ uint32_t wOAMP2CR; /*!< OAMP2 control register to select channel current sampling. */ uint16_t Half_PWMPeriod; /*!< Half PWM Period in timer clock counts. */ uint16_t hRegConv; /*!< Variable used to store regular conversions result. */ volatile uint8_t bSoFOC; /*!< This flag is reset at the beginning of FOC and it is set in the TIM UP IRQ. If at the end of FOC this flag is set, it means that FOC rate is too high and thus an error is generated. */ uint8_t bIndex; /*!< Counter for the number of conversions in one cycle. */ uint16_t ADC_ExternalTriggerInjected; /*!< External trigger selection for ADC peripheral. */ uint16_t ADC_ExternalPolarityInjected; pR3_3_G4XXParams_t pParams_str; } PWMC_R3_3_G4_Handle_t; /* Exported functions ------------------------------------------------------- */ /* * Initializes TIMx, ADC, GPIO, DMA1 and NVIC for current reading * in three shunt topology using STM32F30X and shared ADC. */ void R3_3_G4XX_Init(PWMC_R3_3_G4_Handle_t *pHandle); /* * Stores into the handle the voltage present on Ia and * Ib current feedback analog channels when no current is flowing into the * motor. */ void R3_3_G4XX_CurrentReadingCalibration(PWMC_Handle_t *pHdl); /* * Computes and returns latest converted motor phase currents. */ void R3_3_G4XX_GetPhaseCurrents(PWMC_Handle_t *pHdl, Curr_Components *pStator_Currents); /* * Turns on low sides switches. */ void R3_3_G4XX_TurnOnLowSides(PWMC_Handle_t *pHdl, uint32_t ticks); /* * Enables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_3_G4XX_SwitchOnPWM(PWMC_Handle_t *pHdl); /* * Disables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_3_G4XX_SwitchOffPWM(PWMC_Handle_t *pHdl); /* * Configures the ADC for the current sampling related to sector 1. */ uint16_t R3_3_G4XX_SetADCSampPointSect1(PWMC_Handle_t *pHdl); /* * Configures the ADC for the current sampling related to sector 2. */ uint16_t R3_3_G4XX_SetADCSampPointSect2(PWMC_Handle_t *pHdl); /* * Configures the ADC for the current sampling related to sector 3. */ uint16_t R3_3_G4XX_SetADCSampPointSect3(PWMC_Handle_t *pHdl); /* * Configure the ADC for the current sampling related to sector 4. */ uint16_t R3_3_G4XX_SetADCSampPointSect4(PWMC_Handle_t *pHdl); /* * Configures the ADC for the current sampling related to sector 5. */ uint16_t R3_3_G4XX_SetADCSampPointSect5(PWMC_Handle_t *pHdl); /* * Configure the ADC for the current sampling related to sector 6. */ uint16_t R3_3_G4XX_SetADCSampPointSect6(PWMC_Handle_t *pHdl); /* * Contains the TIMx Update event interrupt. */ void *R3_3_G4XX_TIMx_UP_IRQHandler(PWMC_R3_3_G4_Handle_t *pHdl); /* * Contains the TIMx Break2 event interrupt. */ void *R3_3_G4XX_BRK2_IRQHandler(PWMC_R3_3_G4_Handle_t *pHdl); /* * Contains the TIMx Break1 event interrupt. */ void *R3_3_G4XX_BRK_IRQHandler(PWMC_R3_3_G4_Handle_t *pHdl); /* * Sets the calibrated offset. */ void R3_3_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /* * Reads the calibrated offsets. */ void R3_3_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*__R3_3_G4XX_PWMNCURRFDBK_H*/ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
16,204
C
45.83526
105
0.534066
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/G4xx/Inc/r3_1_g4xx_pwm_curr_fdbk.h
/** ****************************************************************************** * @file r3_1_g4xx_pwm_curr_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * R3_1_G4XX_pwm_curr_fdbk component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup R3_1_G4XX_pwm_curr_fdbk */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef R3_1_G4XX_PWMNCURRFDBK_H #define R3_1_G4XX_PWMNCURRFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "pwm_curr_fdbk.h" /* Exported defines --------------------------------------------------------*/ #define GPIO_NoRemap_TIM1 ((uint32_t)(0)) #define SHIFTED_TIMs ((uint8_t) 1) #define NO_SHIFTED_TIMs ((uint8_t) 0) #define NONE ((uint8_t)(0x00)) #define EXT_MODE ((uint8_t)(0x01)) #define INT_MODE ((uint8_t)(0x02)) /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup R3_1_pwm_curr_fdbk * @{ */ /* Exported types ------------------------------------------------------- */ #ifndef R3_3_OPAMP #define R3_3_OPAMP /** * @brief Current feedback component 3-OPAMP parameters structure definition. Specific to G4XX. */ typedef const struct { /* First OPAMP settings ------------------------------------------------------*/ OPAMP_TypeDef *OPAMPSelect_1 [6] ; /*!< Define for each sector first conversion which OPAMP is involved - Null otherwise */ OPAMP_TypeDef *OPAMPSelect_2 [6] ; /*!< Define for each sector second conversion which OPAMP is involved - Null otherwise */ uint32_t OPAMPConfig1 [6]; /*!< Define the OPAMP_CSR_OPAMPINTEN and the OPAMP_CSR_VPSEL config for each ADC conversions*/ uint32_t OPAMPConfig2 [6]; /*!< Define the OPAMP_CSR_OPAMPINTEN and the OPAMP_CSR_VPSEL config for each ADC conversions*/ } R3_3_OPAMPParams_t; #endif /* * @brief R3_1_G4XX_pwm_curr_fdbk component parameters definition */ typedef const struct { /* HW IP involved -----------------------------*/ ADC_TypeDef *ADCx; /* ADC peripheral to be used.*/ TIM_TypeDef *TIMx; /* timer used for PWM generation.*/ R3_3_OPAMPParams_t *OPAMPParams; /*!< Pointer to the OPAMP params struct. It must be #MC_NULL if internal OPAMP are not used. Specific to G4XX.*/ COMP_TypeDef *CompOCPASelection; /* Internal comparator used for Phase A protection.*/ COMP_TypeDef *CompOCPBSelection; /* Internal comparator used for Phase B protection.*/ COMP_TypeDef *CompOCPCSelection; /* Internal comparator used for Phase C protection.*/ COMP_TypeDef *CompOVPSelection; /* Internal comparator used for Over Voltage protection.*/ DAC_TypeDef *DAC_OCP_ASelection; /*!< DAC used for Phase A protection. Specific to G4XX.*/ DAC_TypeDef *DAC_OCP_BSelection; /*!< DAC used for Phase B protection. Specific to G4XX.*/ DAC_TypeDef *DAC_OCP_CSelection; /*!< DAC used for Phase C protection. Specific to G4XX.*/ DAC_TypeDef *DAC_OVP_Selection; /*!< DAC used for Over Voltage protection. Specific to G4XX.*/ uint32_t DAC_Channel_OCPA; /*!< DAC channel used for Phase A current protection. Specific to G4XX.*/ uint32_t DAC_Channel_OCPB; /*!< DAC channel used for Phase B current protection. Specific to G4XX.*/ uint32_t DAC_Channel_OCPC; /*!< DAC channel used for Phase C current protection. Specific to G4XX.*/ uint32_t DAC_Channel_OVP; /*!< DAC channel used for Over Voltage protection. Specific to G4XX.*/ uint32_t ADCConfig [6] ; /* Stores ADC sequence for the 6 sectors. */ /* PWM generation parameters --------------------------------------------------*/ uint16_t Tafter; /* Sum of dead time plus max value between rise time and noise time expressed in number of TIM clocks. */ uint16_t Tsampling; /* Sampling time expressed in number of TIM clocks. */ uint16_t Tbefore; /* Sampling time expressed in number of TIM clocks. */ uint16_t Tcase2; /* Sampling time expressed in number of TIM clocks. */ uint16_t Tcase3; /* Sampling time expressed in number of TIM clocks. */ /* DAC settings --------------------------------------------------------------*/ uint16_t DAC_OCP_Threshold; /* Value of analog reference expressed as 16bit unsigned integer. Ex. 0 = 0V ; 65536 = VDD_DAC.*/ uint16_t DAC_OVP_Threshold; /* Value of analog reference expressed as 16bit unsigned integer. Ex. 0 = 0V ; 65536 = VDD_DAC. */ /* PWM Driving signals initialization ----------------------------------------*/ uint8_t RepetitionCounter; /* Expresses the number of PWM periods to be elapsed before compare registers are updated again. In particular: RepetitionCounter= (2* #PWM periods)-1*/ /* Internal COMP settings ----------------------------------------------------*/ uint8_t CompOCPAInvInput_MODE; /* COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. */ uint8_t CompOCPBInvInput_MODE; /* COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. */ uint8_t CompOCPCInvInput_MODE; /* COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. */ uint8_t CompOVPInvInput_MODE; /* COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. */ /* Dual MC parameters --------------------------------------------------------*/ uint8_t FreqRatio; /* Used in case of dual MC to synchronize TIM1 and TIM8. It has effect only on the second instanced object and must be equal to the ratio between the two PWM frequencies (higher/lower). Supported values are 1, 2 or 3 */ uint8_t IsHigherFreqTim; /* When bFreqRatio is greater than 1 this param is used to indicate if this instance is the one with the highest frequency. Allowed value are: HIGHER_FREQ or LOWER_FREQ */ } R3_1_Params_t, *pR3_1_Params_t; /* * @brief This structure is used to handle an instance of the * PWM and current feedback component. */ typedef struct { PWMC_Handle_t _Super; /* Base component handler. */ uint32_t PhaseAOffset; /* Offset of Phase A current sensing network. */ uint32_t PhaseBOffset; /* Offset of Phase B current sensing network. */ uint32_t PhaseCOffset; /* Offset of Phase C current sensing network. */ uint16_t Half_PWMPeriod; /* Half PWM Period in timer clock counts. */ uint16_t ADC_ExternalPolarityInjected; volatile uint8_t PolarizationCounter; /* Number of conversions performed during the calibration phase. */ uint8_t PolarizationSector; /* Sector selected during calibration phase. */ pR3_1_Params_t pParams_str; bool ADCRegularLocked; /* Cut 2.2 patch, specific to G4XX. */ } PWMC_R3_1_Handle_t; /* Exported functions ------------------------------------------------------- */ /* * Initializes TIMx, ADC, GPIO, DMA1 and NVIC for current reading * in three shunt topology using STM32F30X and ADC. */ void R3_1_Init(PWMC_R3_1_Handle_t *pHandle); /* * Stores into the handle the voltage present on Ia and * Ib current feedback analog channels when no current is flowing into the * motor. */ void R3_1_CurrentReadingPolarization(PWMC_Handle_t *pHdl); /* * Computes and return latest converted motor phase currents motor. */ void R3_1_GetPhaseCurrents(PWMC_Handle_t *pHdl, ab_t *Iab); /* * Computes and return latest converted motor phase currents motor. */ void R3_1_GetPhaseCurrents_OVM(PWMC_Handle_t *pHdl, ab_t *Iab); /* * Turns on low sides switches. */ void R3_1_TurnOnLowSides(PWMC_Handle_t *pHdl, uint32_t ticks); /* * Enables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_1_SwitchOnPWM(PWMC_Handle_t *pHdl); /* * Disables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_1_SwitchOffPWM(PWMC_Handle_t *pHdl); /* * Configures the ADC for the current sampling . */ uint16_t R3_1_SetADCSampPointSectX(PWMC_Handle_t *pHdl); /* * Configures the ADC for the current sampling. Specific to overmodulation. */ uint16_t R3_1_SetADCSampPointSectX_OVM(PWMC_Handle_t *pHdl); /* * Contains the TIMx Update event interrupt. */ void *R3_1_TIMx_UP_IRQHandler(PWMC_R3_1_Handle_t *pHandle); /* * Sets the calibrated offsets. */ void R3_1_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /* * Reads the calibrated offsets. */ void R3_1_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /* * @brief Sets the PWM mode for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_1_RLDetectionModeEnable(PWMC_Handle_t *pHdl); /* * @brief Disables the PWM mode for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_1_RLDetectionModeDisable(PWMC_Handle_t *pHdl); /* * @brief Sets the PWM dutycycle for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. * @param hDuty: Duty cycle to apply, written in uint16_t. * @retval Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ uint16_t R3_1_RLDetectionModeSetDuty(PWMC_Handle_t *pHdl, uint16_t hDuty); /* * @brief Computes and stores into @p pHandle latest converted motor phase currents * during RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ static void R3_1_RLGetPhaseCurrents(PWMC_Handle_t *pHdl, ab_t *pStator_Currents); /* * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors * of driving section. It has to be called at each motor start-up when * using high voltage drivers. * This function is specific for RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. * @param ticks: Duty cycle of the boot capacitors charge, specific to motor. */ static void R3_1_RLTurnOnLowSides(PWMC_Handle_t *pHdl, uint32_t ticks); /* * @brief Enables PWM generation on the proper Timer peripheral. * * This function is specific for RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. */ static void R3_1_RLSwitchOnPWM( PWMC_Handle_t *pHdl); /* * @brief Turns on low sides switches and start ADC triggering. * * This function is specific for MP phase. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_1_RLTurnOnLowSidesAndStart(PWMC_Handle_t *pHdl); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*R3_1_G4XX_PWMNCURRFDBK_H*/ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
12,818
C
39.566456
127
0.581994
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/G4xx/Inc/r1_g4xx_pwm_curr_fdbk.h
/** ****************************************************************************** * @file r1_g4xx_pwm_curr_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * R1_G4XX_pwm_curr_fdbk component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup R1_G4XX_pwm_curr_fdbk */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef R1_G4XX_PWMNCURRFDBK_H #define R1_G4XX_PWMNCURRFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "pwm_curr_fdbk.h" /* Exported defines --------------------------------------------------------*/ #define NONE ((uint8_t)(0x00)) #define EXT_MODE ((uint8_t)(0x01)) #define INT_MODE ((uint8_t)(0x02)) #define STBD3 0x02u /*!< Flag to indicate which phase has been distorted in boudary 3 zone (A or B).*/ #define DSTEN 0x04u /*!< Flag to indicate if the distortion must be performed or not (in case of charge of bootstrap capacitor phase is not required).*/ /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /* Exported types ------------------------------------------------------- */ /** * @brief Current feedback component parameters structure definition for 1 Shunt configurations. Common to G0XX and G4XX MCUs. */ typedef const struct { /* HW IP involved -----------------------------*/ ADC_TypeDef *ADCx; /*!< ADC peripheral to be used. */ TIM_TypeDef *TIMx; /*!< Timer used for PWM generation. */ OPAMP_TypeDef *OPAMP_Selection; /*!< Selected Opamp for 1 shunt configuration. */ COMP_TypeDef *CompOCPSelection; /*!< Internal comparator used for Phases protection. */ COMP_TypeDef *CompOVPSelection; /*!< Internal comparator used for Over Voltage protection. */ GPIO_TypeDef *pwm_en_u_port; /*!< Channel 1N (low side) GPIO output. */ GPIO_TypeDef *pwm_en_v_port; /*!< Channel 2N (low side) GPIO output. */ GPIO_TypeDef *pwm_en_w_port; /*!< Channel 3N (low side) GPIO output. */ DAC_TypeDef *DAC_OCP_Selection; /*!< DAC used for Over Current protection. */ DAC_TypeDef *DAC_OVP_Selection; /*!< DAC used for Over Voltage protection. */ uint32_t DAC_Channel_OCP; /*!< DAC channel used for Phase A current protection. */ uint32_t DAC_Channel_OVP; /*!< DAC channel used for over voltage protection. */ /* PWM generation parameters --------------------------------------------------*/ uint16_t TMin; /* */ uint16_t HTMin; /* */ uint16_t CHTMin; /* */ uint16_t Tbefore; /*!< Sampling time expressed in number of TIM clocks. */ uint16_t Tafter; /*!< Sum of dead time plus max value between rise time and noise time expressed in number of TIM clocks. */ uint16_t TSample; /*!< Sampling time expressed in number of TIM clocks. */ /* DAC settings --------------------------------------------------------------*/ uint16_t DAC_OCP_Threshold; /*!< Value of analog reference expressed as 16bit unsigned integer. Ex. 0 = 0V 65536 = VDD_DAC. */ uint16_t DAC_OVP_Threshold; /*!< Value of analog reference expressed as 16bit unsigned integer. Ex. 0 = 0V 65536 = VDD_DAC. */ /* PWM Driving signals initialization ----------------------------------------*/ uint8_t IChannel; uint8_t RepetitionCounter; /*!< It expresses the number of PWM periods to be elapsed before compare registers are updated again. In particular: RepetitionCounter= (2* #PWM periods)-1*/ /* Internal COMP settings ----------------------------------------------------*/ uint8_t CompOCPInvInput_MODE; /*!< COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. */ uint8_t CompOVPInvInput_MODE; /*!< COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. */ /* Dual MC parameters --------------------------------------------------------*/ uint8_t FreqRatio; /*!< It is used in case of dual MC to effect only on the second instanced object and must be equal to the ratio between the two PWM frequencies (higher/lower). Supported values are 1, 2 or 3. */ uint8_t IsHigherFreqTim; /*!< When bFreqRatio is greather than 1 this instance is the one with the highest frequency. Allowed value are: HIGHER_FREQ or LOWER_FREQ */ } R1_Params_t; /** * @brief This structure is used to handle an instance of the * Current feedback component for 1 Shunt configurations. Common to G0XX and G4XX MCUs. */ typedef struct { PWMC_Handle_t _Super; /*!< Base component handler. */ DMA_Channel_TypeDef * DistortionDMAy_Chx; /*!< DMA resource used for doing the distortion. */ uint32_t ADCConfig; /*!< Values of JSQR register for ADC. */ uint32_t PhaseOffset; /*!< Offset of Phase A current sensing network. */ uint16_t Half_PWMPeriod; /*!< Half PWM Period in timer clock counts. */ uint16_t DmaBuff[2]; uint16_t CntSmp1; uint16_t CntSmp2; uint16_t CurrAOld; uint16_t CurrBOld; uint8_t bIChannel; /*!< ADC channel used for current conversion. */ uint8_t PolarizationCounter; /*!< Number of conversions performed during the calibration phase. */ uint8_t sampCur1; uint8_t sampCur2; uint8_t Inverted_pwm_new; /* */ uint8_t Flags; /* */ bool UpdateFlagBuffer; /*!< Buffered version of Timer update IT flag. */ /* Trigger selection for ADC peripheral.*/ bool ADCRegularLocked; /*!< This flag is set when regular conversions are locked. */ R1_Params_t * pParams_str; } PWMC_R1_Handle_t; /** @addtogroup R1_G4XX_pwm_curr_fdbk * @{ */ /* * Initializes TIMx, ADC, GPIO, DMA1 and NVIC for current reading * in single shunt configuration using STM3G4XX */ void R1_Init(PWMC_R1_Handle_t *pHandle); /* * Stores into the handle the voltage present on Ia and * Ib current feedback analog channels when no current is flowin into the * motor */ void R1_CurrentReadingPolarization(PWMC_Handle_t *pHdl); /* * Computes and return latest converted motor phase currents. */ void R1_GetPhaseCurrents(PWMC_Handle_t *pHdl, ab_t *Iab); /* * Turns on low sides switches */ void R1_TurnOnLowSides(PWMC_Handle_t *pHdl); /* * Enables PWM generation on the proper Timer peripheral acting on MOE bit */ void R1_SwitchOnPWM(PWMC_Handle_t *pHdl); /* * Disables PWM generation on the proper Timer peripheral acting on MOE bit */ void R1_SwitchOffPWM(PWMC_Handle_t *pHdl); /* * Configures the ADC for the current sampling */ uint16_t R1_CalcDutyCycles(PWMC_Handle_t *pHdl); /* * Contains the TIMx Update event interrupt */ void *R1_TIMx_UP_IRQHandler(PWMC_R1_Handle_t *pHdl); /* * Contains the TIMx Break2 event interrupt */ void *R1_BRK2_IRQHandler(PWMC_R1_Handle_t *pHdl); /* * Contains the TIMx Break1 event interrupt */ void *R1_BRK_IRQHandler(PWMC_R1_Handle_t *pHdl); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*R1_G4XX_PWMNCURRFDBK_H*/ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
8,878
C
38.995495
127
0.528272
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/F0xx/Src/f0xx_bemf_ADC_fdbk.c
/** ****************************************************************************** * @file f0xx_bemf_ADC_fdbk.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement Bemf sensing * class to be stantiated when the six-step sensorless driving mode * topology is used. * * It is specifically designed for STM32F0XX * microcontrollers and implements the sensing using one ADC with * DMA support. * + MCU peripheral and handle initialization fucntion * + ADC sampling function * ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup SpeednPosFdbk_Bemf */ /* Includes ------------------------------------------------------------------*/ #include "f0xx_bemf_ADC_fdbk.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup SpeednPosFdbk * @{ */ /** @addtogroup SpeednPosFdbk_Bemf * @{ */ /* Private defines -----------------------------------------------------------*/ #define MAX_PSEUDO_SPEED ((int16_t)0x7FFF) #define PHASE_U 0u #define PHASE_V 1u #define PHASE_W 2u /* Private function prototypes -----------------------------------------------*/ void BADC_CalcAvrgElSpeedDpp( Bemf_ADC_Handle_t * pHandle ); /* Private functions ---------------------------------------------------------*/ /* * @brief Initializes ADC1, DMA and NVIC for three bemf voltages reading * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_Init( Bemf_ADC_Handle_t *pHandle) { if ( ( uint32_t )pHandle == ( uint32_t )&pHandle->_Super ) { /* disable IT and flags in case of LL driver usage * workaround for unwanted interrupt enabling done by LL driver */ LL_ADC_DisableIT_EOC( ADC1 ); LL_ADC_ClearFlag_EOC( ADC1 ); LL_ADC_DisableIT_EOS( ADC1 ); LL_ADC_ClearFlag_EOS( ADC1 ); /* ADC Calibration */ LL_ADC_StartCalibration( ADC1 ); while ((LL_ADC_IsCalibrationOnGoing(ADC1) == SET) || (LL_ADC_REG_IsConversionOngoing(ADC1) == SET) || (LL_ADC_REG_IsStopConversionOngoing(ADC1) == SET) || (LL_ADC_IsDisableOngoing(ADC1) == SET)) { /* wait */ } /* Enables the ADC peripheral */ LL_ADC_Enable( ADC1 ); LL_ADC_SetSamplingTimeCommonChannels(ADC1, LL_ADC_SAMPLINGTIME_1CYCLE_5); /* Wait ADC Ready */ while ( LL_ADC_IsActiveFlag_ADRDY( ADC1 ) == RESET ) { /* wait */ } /* DMA1 Channel1 Config */ LL_DMA_SetMemoryAddress( DMA1, LL_DMA_CHANNEL_1, ( uint32_t )pHandle->ADC1_DMA_converted ); LL_DMA_SetPeriphAddress( DMA1, LL_DMA_CHANNEL_1, ( uint32_t )&ADC1->DR ); LL_DMA_SetDataLength(DMA1, LL_DMA_CHANNEL_1, 1 ); /* We allow ADC usage for regular conversion on Systick*/ pHandle->ADCRegularLocked=false; uint16_t hMinReliableElSpeedUnit = pHandle->_Super.hMinReliableMecSpeedUnit * pHandle->_Super.bElToMecRatio; uint16_t hMaxReliableElSpeedUnit = pHandle->_Super.hMaxReliableMecSpeedUnit * pHandle->_Super.bElToMecRatio; uint8_t bSpeedBufferSize; uint8_t bIndex; uint16_t MinBemfTime; /* Adjustment factor: minimum measurable speed is x time less than the minimum reliable speed */ hMinReliableElSpeedUnit /= 4U; /* Adjustment factor: maximum measurable speed is x time greater than the maximum reliable speed */ hMaxReliableElSpeedUnit *= 2U; pHandle->OvfFreq = (uint16_t)(pHandle->TIMClockFreq / 65536U); /* SW Init */ if (0U == hMinReliableElSpeedUnit) { /* Set fixed to 150 ms */ pHandle->BemfTimeout = 150U; } else { /* Set accordingly the min reliable speed */ /* 1000 comes from mS * 6 comes from the fact that sensors are toggling each 60 deg = 360/6 deg */ pHandle->BemfTimeout = (1000U * (uint16_t)SPEED_UNIT) / (6U * hMinReliableElSpeedUnit); } /* Align MaxPeriod and MinPeriod to a multiple of Overflow.*/ pHandle->MaxPeriod = (pHandle->BemfTimeout * pHandle->OvfFreq) / 1000U * 65536UL; MinBemfTime = ((1000U * (uint16_t)SPEED_UNIT) << 8) / (6U * hMaxReliableElSpeedUnit); pHandle->MinPeriod = ((MinBemfTime * pHandle->OvfFreq) >> 8) / 1000U * 65536UL; pHandle->SatSpeed = hMaxReliableElSpeedUnit; pHandle->PseudoPeriodConv = ((pHandle->TIMClockFreq / 6U) / pHandle->_Super.hMeasurementFrequency) * pHandle->_Super.DPPConvFactor; if (0U == hMaxReliableElSpeedUnit) { pHandle->MinPeriod = ((uint32_t)SPEED_UNIT * (pHandle->TIMClockFreq / 6UL)); } else { pHandle->MinPeriod = (((uint32_t)SPEED_UNIT * (pHandle->TIMClockFreq / 6UL)) / hMaxReliableElSpeedUnit); } pHandle->PWMNbrPSamplingFreq = ((pHandle->_Super.hMeasurementFrequency * pHandle->PWMFreqScaling) / pHandle->SpeedSamplingFreqHz) - 1U; pHandle->pSensing_Params = &(pHandle->Pwm_OFF); pHandle->IsOnSensingEnabled = false; pHandle->ElPeriodSum = 0; pHandle->ZcEvents = 0; pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold; /* Erase speed buffer */ bSpeedBufferSize = pHandle->SpeedBufferSize; for (bIndex = 0u; bIndex < bSpeedBufferSize; bIndex++) { pHandle->SpeedBufferDpp[bIndex] = (int32_t)pHandle->MaxPeriod; } LL_TIM_EnableCounter(pHandle->pParams_str->LfTim); } } /* * @brief Resets the ADC status * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_Clear( Bemf_ADC_Handle_t *pHandle ) { /* Disabling of DMA Interrupt Event configured */ LL_DMA_DisableIT_TC( DMA1, LL_DMA_CHANNEL_1 ); LL_ADC_REG_StopConversion( ADC1 ); /* Disable ADC DMA request*/ ADC1->CFGR1 &= ~ADC_CFGR1_DMAEN; /* Clear Transmission Complete Flag of DMA1 Channel1 */ LL_DMA_ClearFlag_TC1( DMA1 ); /* Clear EOC */ LL_ADC_ClearFlag_EOC( ADC1 ); /* We allow ADC usage for regular conversion on Systick*/ pHandle->ADCRegularLocked=false; pHandle->ZcEvents = 0; pHandle->ElPeriodSum = 0; /* Acceleration measurement not implemented.*/ pHandle->_Super.hMecAccelUnitP = 0; pHandle->BufferFilled = 0U; pHandle->CompSpeed = 0; /* Initialize speed buffer index */ pHandle->SpeedFIFOIdx = 0U; pHandle->_Super.hElAngle = 0; /* Clear speed error counter */ pHandle->_Super.bSpeedErrorNumber = 0; pHandle->IsLoopClosed=false; pHandle->IsAlgorithmConverged = false; } /* * @brief Starts bemf ADC conversion of the phase depending on current step * @param pHandle: handler of the current instance of the Bemf_ADC component * @param step: current step of the six-step sequence */ __weak void BADC_Start(Bemf_ADC_Handle_t *pHandle, uint8_t step) { pHandle->ADCRegularLocked=true; LL_ADC_REG_StopConversion( ADC1 ); /* Enable ADC DMA request*/ LL_ADC_REG_SetDMATransfer( ADC1, LL_ADC_REG_DMA_TRANSFER_UNLIMITED ); /* Enables the DMA1 Channel1 peripheral */ LL_DMA_EnableChannel( DMA1, LL_DMA_CHANNEL_1 ); /* Clear Pending Interrupt Bits */ LL_DMA_ClearFlag_TC1( DMA1 ); /* DMA Interrupt Event configuration */ LL_DMA_EnableIT_TC( DMA1, LL_DMA_CHANNEL_1 ); /* enable ADC source trigger */ LL_ADC_REG_SetTriggerSource (ADC1, LL_ADC_REG_TRIG_EXT_TIM1_TRGO); LL_ADC_REG_SetTriggerEdge (ADC1, LL_ADC_REG_TRIG_EXT_FALLING); LL_ADC_SetSamplingTimeCommonChannels (ADC1, LL_ADC_SAMPLINGTIME_1CYCLE_5 ); switch (step) { case STEP_1: case STEP_4: BADC_SelectAdcChannel(pHandle, PHASE_W); break; case STEP_2: case STEP_5: BADC_SelectAdcChannel(pHandle, PHASE_V); break; case STEP_3: case STEP_6: BADC_SelectAdcChannel(pHandle, PHASE_U); break; default: break; } LL_ADC_REG_StartConversion(ADC1); } /* * @brief Stops bemf ADC conversion * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_Stop(Bemf_ADC_Handle_t *pHandle) { LL_ADC_REG_StopConversion( ADC1 ); /* Clear Transmission Complete Flag of DMA1 Channel1 */ LL_DMA_ClearFlag_TC1( DMA1 ); /* Clear EOC */ LL_ADC_ClearFlag_EOC( ADC1 ); } /* * @brief Enables the speed loop (low frequency) timer * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_SpeedMeasureOn(Bemf_ADC_Handle_t *pHandle) { LL_TIM_ClearFlag_UPDATE(pHandle->pParams_str->LfTim); LL_TIM_EnableIT_UPDATE(pHandle->pParams_str->LfTim); } /* * @brief Disables the speed loop (low frequency) timer * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_SpeedMeasureOff(Bemf_ADC_Handle_t *pHandle) { LL_TIM_DisableIT_UPDATE(pHandle->pParams_str->LfTim); } /* * @brief Configures the ADC for the current sampling. * It sets the sampling point via TIM1_Ch4 value, the ADC sequence * and channels. * @param pHandle: handler of the current instance of the Bemf_ADC component * @param pHandlePWMC: handler of the current instance of the PWMC component * @param pHandleSTC: handler of the current instance of the Speed Control component */ __weak void BADC_SetSamplingPoint(Bemf_ADC_Handle_t *pHandle, PWMC_Handle_t *pHandlePWMC, SpeednTorqCtrl_Handle_t *pHandleSTC ) { if ((pHandleSTC->ModeDefault == MCM_SPEED_MODE) && (pHandle->DriveMode == VM)) { if (!(pHandle->IsOnSensingEnabled) && (pHandlePWMC->CntPh > pHandle->OnSensingEnThres)) { pHandle->IsOnSensingEnabled=true; pHandle->pSensing_Params = &(pHandle->Pwm_ON); } else if ((pHandle->IsOnSensingEnabled) && (pHandlePWMC->CntPh < pHandle->OnSensingDisThres)) { pHandle->IsOnSensingEnabled=false; pHandle->pSensing_Params = &(pHandle->Pwm_OFF); } else { } } else { pHandle->IsOnSensingEnabled=false; pHandle->pSensing_Params = &(pHandle->Pwm_OFF); } if (true == pHandle->pParams_str->gpio_divider_available) LL_GPIO_ResetOutputPin( pHandle->pParams_str->bemf_divider_port, pHandle->pParams_str->bemf_divider_pin ); PWMC_SetADCTriggerChannel( pHandlePWMC, pHandle->pSensing_Params->SamplingPoint); } /* * @brief Gets last bemf value and checks for zero crossing detection. * Updates speed loop timer and electrical angle accordingly. * @param pHandle: handler of the current instance of the Bemf_ADC component * @param pHandlePWMC: handler of the current instance of the PWMC component * @retval none */ __weak bool BADC_IsZcDetected( Bemf_ADC_Handle_t *pHandle, PWMC_Handle_t *pHandlePWMC) { uint16_t AdcValue = pHandle->ADC1_DMA_converted[0]; bool ZcDetection = false; pHandle->DemagCounter++; if ( pHandle->DemagCounter > pHandle->DemagCounterThreshold) { if (pHandle->ZcDetected == false) { switch(pHandlePWMC->Step) { case STEP_1: pHandle->BemfLastValues[2] = AdcValue; if(pHandle->Direction == 1) { if (AdcValue < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_60_PHASE_SHIFT / 2; } } else { if (AdcValue > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = S16_120_PHASE_SHIFT + S16_60_PHASE_SHIFT / 2; } } break; case STEP_2: pHandle->BemfLastValues[1] = AdcValue; if(pHandle->Direction == 1) { if (AdcValue > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = S16_60_PHASE_SHIFT / 2; } } else { if (AdcValue < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_120_PHASE_SHIFT - S16_60_PHASE_SHIFT / 2; } } break; case STEP_3: pHandle->BemfLastValues[0] = AdcValue; if(pHandle->Direction == 1) { if (AdcValue < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = S16_60_PHASE_SHIFT + S16_60_PHASE_SHIFT / 2; } } else { if (AdcValue > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_60_PHASE_SHIFT - S16_60_PHASE_SHIFT / 2; } } break; case STEP_4: pHandle->BemfLastValues[2] = AdcValue; if(pHandle->Direction == 1) { if (AdcValue > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = S16_120_PHASE_SHIFT + S16_60_PHASE_SHIFT / 2; } } else { if (AdcValue < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_60_PHASE_SHIFT / 2; } } break; case STEP_5: pHandle->BemfLastValues[1] = AdcValue; if(pHandle->Direction == 1) { if (AdcValue < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_120_PHASE_SHIFT - S16_60_PHASE_SHIFT / 2; } } else { if (AdcValue > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = S16_60_PHASE_SHIFT / 2; } } break; case STEP_6: pHandle->BemfLastValues[0] = AdcValue; if(pHandle->Direction == 1) { if (AdcValue > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_60_PHASE_SHIFT - S16_60_PHASE_SHIFT / 2; } } else { if (AdcValue < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = S16_60_PHASE_SHIFT + S16_60_PHASE_SHIFT / 2; } } break; } if (true == ZcDetection) { pHandle->MeasuredElAngle += (S16_60_PHASE_SHIFT/2) - (int16_t)((uint32_t)(pHandle->Zc2CommDelay * S16_60_PHASE_SHIFT)>>9); if (pHandle->ZcEvents > pHandle->StartUpConsistThreshold) { pHandle->IsAlgorithmConverged = true; } pHandle->ZcDetected = true; pHandle->ZcEvents++; switch(pHandlePWMC->Step) { case STEP_1: case STEP_3: case STEP_5: if(pHandle->Direction == 1) { pHandle->ZC_Counter_Down = LL_TIM_GetCounter(pHandle->pParams_str->LfTim); pHandle->ZC_Counter_Last = pHandle->ZC_Counter_Down; } else { pHandle->ZC_Counter_Up = LL_TIM_GetCounter(pHandle->pParams_str->LfTim); pHandle->ZC_Counter_Last = pHandle->ZC_Counter_Up; } break; case STEP_2: case STEP_4: case STEP_6: if(pHandle->Direction == 1) { pHandle->ZC_Counter_Up = LL_TIM_GetCounter(pHandle->pParams_str->LfTim); pHandle->ZC_Counter_Last = pHandle->ZC_Counter_Up; } else { pHandle->ZC_Counter_Down = LL_TIM_GetCounter(pHandle->pParams_str->LfTim); pHandle->ZC_Counter_Last = pHandle->ZC_Counter_Down; } break; } if (true == pHandle->IsAlgorithmConverged) { uint32_t tempReg = (uint32_t )(pHandle->PseudoPeriodConv / ((pHandle->LowFreqTimerPsc + 1) * (pHandle->AvrElSpeedDpp * pHandle->Direction))); LL_TIM_SetAutoReload(pHandle->pParams_str->LfTim,pHandle->ZC_Counter_Last + (((uint32_t)((pHandle->Zc2CommDelay) * tempReg)) >> 9) ); } } } } return ZcDetection; } /* * @brief This method must be called - at least - with the same periodicity * on which speed control is executed. It computes and returns - through * parameter hMecSpeedUnit - the rotor average mechanical speed, * expressed in Unit. Average is computed considering a FIFO depth * equal to SpeedBufferSizeUnit. Moreover it also computes and returns * the reliability state of the sensor. * @param pHandle: handler of the current instance of the Bemf_ADC component * @param pMecSpeedUnit pointer to int16_t, used to return the rotor average * mechanical speed (expressed in the unit defined by #SPEED_UNIT) * @retval bool speed sensor reliability, measured with reference to parameters * Reliability_hysteresys, VariancePercentage and SpeedBufferSize * true = sensor information is reliable * false = sensor information is not reliable */ __weak bool BADC_CalcAvrgMecSpeedUnit( Bemf_ADC_Handle_t * pHandle, int16_t * pMecSpeedUnit ) { bool bReliability; pHandle->_Super.hElSpeedDpp = pHandle->AvrElSpeedDpp; if (0 == pHandle->AvrElSpeedDpp) { /* Speed is too low */ *pMecSpeedUnit = 0; } else { /* Check if speed is not to fast */ if (pHandle->AvrElSpeedDpp != MAX_PSEUDO_SPEED) { pHandle->DeltaAngle = pHandle->MeasuredElAngle - pHandle->_Super.hElAngle; pHandle->CompSpeed = (int16_t)((int32_t)(pHandle->DeltaAngle) / (int32_t)(pHandle->PWMNbrPSamplingFreq)); /* Convert el_dpp to MecUnit */ *pMecSpeedUnit = (int16_t)((pHandle->AvrElSpeedDpp * (int32_t)pHandle->_Super.hMeasurementFrequency * (int32_t)SPEED_UNIT ) / ((int32_t)(pHandle->_Super.DPPConvFactor) * (int32_t)(pHandle->_Super.bElToMecRatio)) ); } else { *pMecSpeedUnit = (int16_t)pHandle->SatSpeed; } } bReliability = SPD_IsMecSpeedReliable(&pHandle->_Super, pMecSpeedUnit); pHandle->_Super.hAvrMecSpeedUnit = *pMecSpeedUnit; BADC_CalcAvrgElSpeedDpp (pHandle); return (bReliability); } /* * @brief Returns false if calculated speed is out of reliability ranges * @param pHandle: handler of the current instance of the Bemf_ADC component * @retval bool: reliability flag */ __weak bool BADC_IsSpeedReliable( Bemf_ADC_Handle_t *pHandle ) { bool SpeedError = false; if ( pHandle->_Super.hAvrMecSpeedUnit > pHandle->_Super.hMaxReliableMecSpeedUnit ) { SpeedError = true; } if ( pHandle->_Super.hAvrMecSpeedUnit < pHandle->_Super.hMinReliableMecSpeedUnit ) { SpeedError = true; } return ( SpeedError ); } /* * @brief Forces the rotation direction * @param pHandle: handler of the current instance of the Bemf_ADC component * @param direction: imposed direction */ __weak void BADC_SetDirection( Bemf_ADC_Handle_t * pHandle, uint8_t direction ) { if (MC_NULL == pHandle) { /* Nothing to do */ } else { pHandle->Direction = direction; } } /* * @brief Internally performs a checks necessary to state whether * the bemf algorithm converged. To be periodically called * during motor open-loop ramp-up (e.g. at the same frequency of * SPD_CalcElAngle), it returns true if the estimated angle and speed * can be considered reliable, false otherwise * @param pHandle: handler of the current instance of the Bemf_ADC component * * @retval bool sensor reliability state */ __weak bool BADC_IsObserverConverged( Bemf_ADC_Handle_t * pHandle ) { return pHandle->IsAlgorithmConverged; } /* * @brief Configures the proper ADC channel according to the current * step corresponding to the floating phase. To be periodically called * at least at every step change. * @param pHandle: handler of the current instance of the Bemf_ADC component * @param Phase: Floating phase for bemf acquisition */ void BADC_SelectAdcChannel(Bemf_ADC_Handle_t * pHandle, uint8_t Phase) { while (LL_ADC_REG_IsConversionOngoing(ADC1)) { LL_ADC_REG_StopConversion(ADC1); while(LL_ADC_REG_IsStopConversionOngoing(ADC1)); } /* Sampling time configuration */ /* Regular sequence configuration */ LL_ADC_REG_SetSequencerChannels(ADC1, __LL_ADC_DECIMAL_NB_TO_CHANNEL(pHandle->pParams_str->AdcChannel[Phase])); LL_ADC_ClearFlag_EOC(ADC1); } /* * @brief Updates the estimated electrical angle. * @param pHandle: handler of the current instance of the Bemf_ADC component * @retval int16_t rotor electrical angle (s16Degrees) */ __weak int16_t BADC_CalcElAngle(Bemf_ADC_Handle_t * pHandle) { int16_t retValue; if (pHandle->_Super.hElSpeedDpp != MAX_PSEUDO_SPEED) { if (false == pHandle->IsLoopClosed) { pHandle->MeasuredElAngle += pHandle->_Super.hElSpeedDpp; pHandle->PrevRotorFreq = pHandle->_Super.hElSpeedDpp; pHandle->_Super.hElAngle += pHandle->_Super.hElSpeedDpp + pHandle->CompSpeed; } else { pHandle->_Super.hElAngle = pHandle->MeasuredElAngle; } } else { pHandle->_Super.hElAngle += pHandle->PrevRotorFreq; } retValue = pHandle->_Super.hElAngle; return (retValue); } /* * @brief Must be called - at least - with the same periodicity * on which speed control is executed. It computes and update component * variable hElSpeedDpp that is estimated average electrical speed * expressed in dpp used for instance in observer equations. * Average is computed considering a FIFO depth equal to * bSpeedBufferSizedpp. * @param pHandle: handler of the current instance of the Bemf_ADC component */ void BADC_CalcAvrgElSpeedDpp( Bemf_ADC_Handle_t * pHandle ) { uint32_t wCaptBuf; /* used to validate the average speed measurement */ if (pHandle->BufferFilled < pHandle->SpeedBufferSize) { pHandle->BufferFilled++; } else { /* Nothing to do */ } if (false == pHandle->IsLoopClosed) { if (pHandle->VirtualElSpeedDpp == 0) pHandle->Counter_Period = 0xFFFF; else pHandle->Counter_Period = ( uint32_t )(pHandle->PseudoPeriodConv / ((pHandle->LowFreqTimerPsc + 1) * pHandle->VirtualElSpeedDpp)); } else { pHandle->Counter_Period = pHandle->ZC_Counter_Last + pHandle->Last_Zc2Comm_Delay; } wCaptBuf = pHandle->Counter_Period * (pHandle->LowFreqTimerPsc + 1); /* Filtering to fast speed... could be a glitch ? */ /* the MAX_PSEUDO_SPEED is temporary in the buffer, and never included in average computation*/ if (wCaptBuf < pHandle->MinPeriod) { /* Nothing to do */ } else { pHandle->ElPeriodSum -= pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx]; /* value we gonna removed from the accumulator */ if (wCaptBuf >= pHandle->MaxPeriod) { pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx] = (int32_t)pHandle->MaxPeriod * pHandle->Direction; } else { pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx] = (int32_t)wCaptBuf ; pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx] *= pHandle->Direction; pHandle->ElPeriodSum += pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx]; } /* Update pointers to speed buffer */ pHandle->SpeedFIFOIdx++; if (pHandle->SpeedFIFOIdx == pHandle->SpeedBufferSize) { pHandle->SpeedFIFOIdx = 0U; } if (((pHandle->BufferFilled < pHandle->SpeedBufferSize) && (wCaptBuf != 0U)) || (false == pHandle->IsLoopClosed)) { uint32_t tempReg = (pHandle->PseudoPeriodConv / wCaptBuf) * (uint32_t)pHandle->Direction; pHandle->AvrElSpeedDpp = (int16_t)tempReg; } else { /* Average speed allow to smooth the mechanical sensors misalignement */ int32_t tElPeriodSum = 0; uint8_t i; for (i=0; i < pHandle->SpeedBufferSize; i++) { tElPeriodSum += pHandle->SpeedBufferDpp[i]; } pHandle->AvrElSpeedDpp = (int16_t)((int32_t)pHandle->PseudoPeriodConv / (tElPeriodSum / (int32_t)pHandle->SpeedBufferSize)); /* Average value */ } } } /* * @brief Used to calculate instant speed during revup, to * initialize parameters at step change and to select proper ADC channel * for next Bemf acquisitions * @param pHandle: handler of the current instance of the Bemf_ADC component * @param hElSpeedDpp: Mechanical speed imposed by virtual speed component * @param pHandlePWMC: handler of the current instance of the PWMC component */ void BADC_StepChangeEvent(Bemf_ADC_Handle_t * pHandle, int16_t hElSpeedDpp, PWMC_Handle_t *pHandlePWMC) { pHandle->DemagCounter = 0; while (LL_ADC_REG_IsConversionOngoing(ADC1)) { LL_ADC_REG_StopConversion(ADC1); while(LL_ADC_REG_IsStopConversionOngoing(ADC1)); } BADC_Stop(pHandle); pHandle->Last_Zc2Comm_Delay = LL_TIM_GetAutoReload(pHandle->pParams_str->LfTim) - pHandle->ZC_Counter_Last; if (false == pHandle->IsLoopClosed) { if (hElSpeedDpp < 0) { pHandle->VirtualElSpeedDpp = - hElSpeedDpp; } else { pHandle->VirtualElSpeedDpp = hElSpeedDpp; } pHandle->ZcDetected = false; } else { int16_t ElAngleUpdate; if(pHandle->Direction == -1) { ElAngleUpdate = -S16_60_PHASE_SHIFT ; } else { ElAngleUpdate = S16_60_PHASE_SHIFT ; } pHandle->MeasuredElAngle += ElAngleUpdate; if ( false == pHandle->ZcDetected) { LL_TIM_SetAutoReload(pHandle->pParams_str->LfTim,LL_TIM_GetAutoReload(pHandle->pParams_str->LfTim) * 120 / 100); } else { pHandle->ZcDetected = false; } } pHandle->StepUpdate = true; } /* * @brief Calculates and stores in the corresponding variable the demagnetization * time in open loop operation * @param pHandle: handler of the current instance of the Bemf_ADC component */ void BADC_CalcRevUpDemagTime(Bemf_ADC_Handle_t *pHandle) { int16_t hSpeed; hSpeed = (int16_t)((pHandle->VirtualElSpeedDpp * (int32_t)pHandle->_Super.hMeasurementFrequency * (int32_t)SPEED_UNIT ) / ((int32_t)(pHandle->_Super.DPPConvFactor) * (int32_t)(pHandle->_Super.bElToMecRatio)) );; if (hSpeed == 0) { pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold;; } else { pHandle->DemagCounterThreshold = (uint16_t) (pHandle->DemagParams.RevUpDemagSpeedConv / hSpeed); } if (pHandle->DemagCounterThreshold < pHandle->DemagParams.DemagMinimumThreshold) { pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold; } } /* * @brief Calculates and stores in the corresponding variable the demagnetization * time in closed loop operation * @param pHandle: handler of the current instance of the Bemf_ADC component */ void BADC_CalcRunDemagTime(Bemf_ADC_Handle_t *pHandle) { int16_t hSpeed; hSpeed = pHandle->_Super.hAvrMecSpeedUnit; if (hSpeed < 0) hSpeed = - hSpeed; if (hSpeed < pHandle->DemagParams.DemagMinimumSpeedUnit) { pHandle->DemagCounterThreshold = (uint16_t) (pHandle->DemagParams.RunDemagSpeedConv / hSpeed); if (pHandle->DemagCounterThreshold < pHandle->DemagParams.DemagMinimumThreshold) { pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold; } } else { pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold; } } /* * @brief Must be called after switch-over procedure when * virtual speed sensor transition is ended. * @param pHandle: handler of the current instance of the STO component */ void BADC_SetLoopClosed(Bemf_ADC_Handle_t *pHandle) { pHandle->IsLoopClosed=true; } /* * @brief Returns the last acquired bemf value * @param pHandle: handler of the current instance of the Bemf_ADC component * @param phase: motor phase under investigation * @retval uint16_t: Bemf value */ uint16_t BADC_GetLastBemfValue(Bemf_ADC_Handle_t *pHandle, uint8_t phase) { return ((MC_NULL == pHandle) ? 0U : pHandle->BemfLastValues[phase]); } /* * @brief Returns the zero crossing detection flag * @param pHandle: handler of the current instance of the Bemf_ADC component * @retval bool: zero crossing detection flag */ bool BADC_GetBemfZcrFlag(Bemf_ADC_Handle_t *pHandle) { return ((MC_NULL == pHandle) ? 0U : pHandle->ZcDetected); } /* * @brief Returns true if the step needs to be updated * @param pHandle: handler of the current instance of the Bemf_ADC component * @retval bool: step update request */ bool BADC_ClearStepUpdate(Bemf_ADC_Handle_t *pHandle) { bool retValue = (((pHandle->IsLoopClosed == true) && (pHandle->StepUpdate == true)) || (pHandle->IsLoopClosed == false)); pHandle->StepUpdate = false; return retValue; } /* * @brief Configures the parameters for bemf sensing during pwm off-time * @param pHandle: handler of the current instance of the Bemf_ADC component * @param BemfAdcConfig: thresholds and sampling time parameters * @param Zc2CommDelay: delay between bemf zero crossing parameter and step commutation * @param bemfAdcDemagConfig: demagnetization parameters */ void BADC_SetBemfSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfAdcConfig, uint16_t *Zc2CommDelay, Bemf_Demag_Params *bemfAdcDemagConfig) { pHandle->Pwm_OFF.AdcThresholdUp = BemfAdcConfig->AdcThresholdUp; pHandle->Pwm_OFF.AdcThresholdDown = BemfAdcConfig->AdcThresholdDown; pHandle->Pwm_OFF.SamplingPoint = BemfAdcConfig->SamplingPoint; pHandle->Zc2CommDelay = *Zc2CommDelay; pHandle->DemagParams.DemagMinimumSpeedUnit = bemfAdcDemagConfig->DemagMinimumSpeedUnit; pHandle->DemagParams.DemagMinimumThreshold = bemfAdcDemagConfig->DemagMinimumThreshold; } /* * @brief Configures the parameters for bemf sensing during pwm on-time * @param pHandle: handler of the current instance of the Bemf_ADC component * @param BemfOnAdcConfig: thresholds and sampling time parameters * @param OnSensingEnThres: Minimum dudty cycle for on-sensing activation * @param OnSensingDisThres: Minimum duty cycle for on-sensing Deactivationg */ void BADC_SetBemfOnTimeSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfOnAdcConfig, uint16_t *OnSensingEnThres, uint16_t *OnSensingDisThres) { pHandle->Pwm_ON.AdcThresholdUp = BemfOnAdcConfig->AdcThresholdUp; pHandle->Pwm_ON.AdcThresholdDown = BemfOnAdcConfig->AdcThresholdDown; pHandle->Pwm_ON.SamplingPoint = BemfOnAdcConfig->SamplingPoint; pHandle->OnSensingEnThres = *OnSensingEnThres; pHandle->OnSensingDisThres = *OnSensingDisThres; } /* * @brief Gets the parameters for bemf sensing during pwm off-time * @param pHandle: handler of the current instance of the Bemf_ADC component * @param BemfAdcConfig: thresholds and sampling time parameters * @param Zc2CommDelay: delay between bemf zero crossing parameter and step commutation * @param BemfAdcDemagConfig: demagnetization parameters */ void BADC_GetBemfSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfAdcConfig, uint16_t *Zc2CommDelay, Bemf_Demag_Params *BemfAdcDemagConfig) { BemfAdcConfig->AdcThresholdUp = pHandle->Pwm_OFF.AdcThresholdUp; BemfAdcConfig->AdcThresholdDown = pHandle->Pwm_OFF.AdcThresholdDown; BemfAdcConfig->SamplingPoint = pHandle->Pwm_OFF.SamplingPoint; *Zc2CommDelay = pHandle->Zc2CommDelay; BemfAdcDemagConfig->DemagMinimumSpeedUnit = pHandle->DemagParams.DemagMinimumSpeedUnit; BemfAdcDemagConfig->DemagMinimumThreshold = pHandle->DemagParams.DemagMinimumThreshold; } /* * @brief Gets the parameters for bemf sensing during pwm on-time * @param pHandle: handler of the current instance of the Bemf_ADC component * @param BemfOnAdcConfig: thresholds and sampling time parameters * @param OnSensingEnThres: Minimum duty cycle for on-sensing activation * @param OnSensingDisThres: Minimum duty cycle for on-sensing Deactivationg */ void BADC_GetBemfOnTimeSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfOnAdcConfig, uint16_t *OnSensingEnThres, uint16_t *OnSensingDisThres) { BemfOnAdcConfig->AdcThresholdUp = pHandle->Pwm_ON.AdcThresholdUp; BemfOnAdcConfig->AdcThresholdDown = pHandle->Pwm_ON.AdcThresholdDown; BemfOnAdcConfig->SamplingPoint = pHandle->Pwm_ON.SamplingPoint; *OnSensingEnThres = pHandle->OnSensingEnThres; *OnSensingDisThres = pHandle->OnSensingDisThres; } /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
33,643
C
33.648816
167
0.642927
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/F0xx/Src/f0xx_bemf_ADC_OS_fdbk.c
/** ****************************************************************************** * @file f0xx_bemf_ADC_OS_fdbk.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement Bemf sensing * class to be stantiated when the six-step sensorless driving mode * topology is used. Differently from standard implementation, * this one performs multiple acquisition during a PWM cycle. * * It is specifically designed for STM32F0XX * microcontrollers and implements the sensing using one ADC with * DMA support. * + MCU peripheral and handle initialization fucntion * + ADC sampling function * ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup SpeednPosFdbk_Bemf */ /* Includes ------------------------------------------------------------------*/ #include "f0xx_bemf_ADC_OS_fdbk.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup SpeednPosFdbk * @{ */ /** @addtogroup SpeednPosFdbk_Bemf * @{ */ /* Private defines -----------------------------------------------------------*/ #define MAX_PSEUDO_SPEED ((int16_t)0x7FFF) #define PHASE_U 0u #define PHASE_V 1u #define PHASE_W 2u /* Private function prototypes -----------------------------------------------*/ void BADC_CalcAvrgElSpeedDpp( Bemf_ADC_Handle_t * pHandle ); /* Private functions ---------------------------------------------------------*/ /* * @brief Initializes ADC1, DMA and NVIC for three bemf voltages reading * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_Init( Bemf_ADC_Handle_t *pHandle) { uint8_t i; uint32_t tArray; if ( ( uint32_t )pHandle == ( uint32_t )&pHandle->_Super ) { /* disable IT and flags in case of LL driver usage * workaround for unwanted interrupt enabling done by LL driver */ LL_ADC_DisableIT_EOC( ADC1 ); LL_ADC_ClearFlag_EOC( ADC1 ); LL_ADC_DisableIT_EOS( ADC1 ); LL_ADC_ClearFlag_EOS( ADC1 ); /* ADC Calibration */ LL_ADC_StartCalibration( ADC1 ); while ((LL_ADC_IsCalibrationOnGoing(ADC1) == SET) || (LL_ADC_REG_IsConversionOngoing(ADC1) == SET) || (LL_ADC_REG_IsStopConversionOngoing(ADC1) == SET) || (LL_ADC_IsDisableOngoing(ADC1) == SET)) { /* wait */ } /* Enables the ADC peripheral */ LL_ADC_Enable( ADC1 ); LL_ADC_SetSamplingTimeCommonChannels(ADC1, LL_ADC_SAMPLINGTIME_1CYCLE_5); /* Wait ADC Ready */ while ( LL_ADC_IsActiveFlag_ADRDY( ADC1 ) == RESET ) { /* wait */ } /* DMA1 Channel1 Config */ LL_DMA_SetMemoryAddress( DMA1, LL_DMA_CHANNEL_1, ( uint32_t )pHandle->ADC1_DMA_converted ); LL_DMA_SetPeriphAddress( DMA1, LL_DMA_CHANNEL_1, ( uint32_t )&ADC1->DR ); LL_DMA_SetDataLength(DMA1, LL_DMA_CHANNEL_1, pHandle->OverSamplingRate ); /* We allow ADC usage for regular conversion on Systick*/ pHandle->ADCRegularLocked=false; uint16_t hMinReliableElSpeedUnit = pHandle->_Super.hMinReliableMecSpeedUnit * pHandle->_Super.bElToMecRatio; uint16_t hMaxReliableElSpeedUnit = pHandle->_Super.hMaxReliableMecSpeedUnit * pHandle->_Super.bElToMecRatio; uint8_t bSpeedBufferSize; uint8_t bIndex; uint16_t MinBemfTime; /* Adjustment factor: minimum measurable speed is x time less than the minimum reliable speed */ hMinReliableElSpeedUnit /= 4U; /* Adjustment factor: maximum measurable speed is x time greater than the maximum reliable speed */ hMaxReliableElSpeedUnit *= 2U; pHandle->OvfFreq = (uint16_t)(pHandle->TIMClockFreq / 65536U); /* SW Init */ if (0U == hMinReliableElSpeedUnit) { /* Set fixed to 150 ms */ pHandle->BemfTimeout = 150U; } else { /* Set accordingly the min reliable speed */ /* 1000 comes from mS * 6 comes from the fact that sensors are toggling each 60 deg = 360/6 deg */ pHandle->BemfTimeout = (1000U * (uint16_t)SPEED_UNIT) / (6U * hMinReliableElSpeedUnit); } /* Align MaxPeriod and MinPeriod to a multiple of Overflow.*/ pHandle->MaxPeriod = (pHandle->BemfTimeout * pHandle->OvfFreq) / 1000U * 65536UL; MinBemfTime = ((1000U * (uint16_t)SPEED_UNIT) << 8) / (6U * hMaxReliableElSpeedUnit); pHandle->MinPeriod = ((MinBemfTime * pHandle->OvfFreq) >> 8) / 1000U * 65536UL; pHandle->SatSpeed = hMaxReliableElSpeedUnit; pHandle->PseudoPeriodConv = ((pHandle->TIMClockFreq / 6U) / pHandle->_Super.hMeasurementFrequency) * pHandle->_Super.DPPConvFactor; if (0U == hMaxReliableElSpeedUnit) { pHandle->MinPeriod = ((uint32_t)SPEED_UNIT * (pHandle->TIMClockFreq / 6UL)); } else { pHandle->MinPeriod = (((uint32_t)SPEED_UNIT * (pHandle->TIMClockFreq / 6UL)) / hMaxReliableElSpeedUnit); } pHandle->PWMNbrPSamplingFreq = ((pHandle->_Super.hMeasurementFrequency * pHandle->PWMFreqScaling) / pHandle->SpeedSamplingFreqHz) - 1U; pHandle->pSensing_Params = &(pHandle->Pwm_OFF); pHandle->IsOnSensingEnabled = false; pHandle->ElPeriodSum = 0; pHandle->ZcEvents = 0; pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold; /* Erase speed buffer */ bSpeedBufferSize = pHandle->SpeedBufferSize; for (bIndex = 0u; bIndex < bSpeedBufferSize; bIndex++) { pHandle->SpeedBufferDpp[bIndex] = (int32_t)pHandle->MaxPeriod; } LL_TIM_CC_EnableChannel( pHandle->pParams_str->TIM_Trigger, pHandle->pParams_str->TIM_ADC_Trigger_Channel ); LL_TIM_EnableCounter( pHandle->pParams_str->TIM_Trigger ); tArray = LL_TIM_GetAutoReload(pHandle->pParams_str->TIM_Trigger); LL_TIM_OC_SetCompareCH1( pHandle->pParams_str->TIM_Trigger, pHandle->pSensing_Params->SamplingPoint); for (i=0; i<pHandle->OverSamplingRate; i++) { pHandle->TIM1_pulses[i]= tArray * i + pHandle->Pwm_OFF.SamplingPoint; } LL_TIM_EnableCounter(pHandle->pParams_str->LfTim); } } /* * @brief Resets the ADC status * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_Clear( Bemf_ADC_Handle_t *pHandle ) { /* Disabling of DMA Interrupt Event configured */ LL_DMA_DisableIT_TC( DMA1, LL_DMA_CHANNEL_1 ); LL_ADC_REG_StopConversion( ADC1 ); /* Disable ADC DMA request*/ ADC1->CFGR1 &= ~ADC_CFGR1_DMAEN; /* Clear Transmission Complete Flag of DMA1 Channel1 */ LL_DMA_ClearFlag_TC1( DMA1 ); /* Clear EOC */ LL_ADC_ClearFlag_EOC( ADC1 ); /* We allow ADC usage for regular conversion on Systick*/ pHandle->ADCRegularLocked=false; pHandle->ZcEvents = 0; pHandle->ElPeriodSum = 0; /* Acceleration measurement not implemented.*/ pHandle->_Super.hMecAccelUnitP = 0; pHandle->BufferFilled = 0U; pHandle->CompSpeed = 0; /* Initialize speed buffer index */ pHandle->SpeedFIFOIdx = 0U; pHandle->_Super.hElAngle = 0; /* Clear speed error counter */ pHandle->_Super.bSpeedErrorNumber = 0; pHandle->IsLoopClosed=false; pHandle->IsAlgorithmConverged = false; } /* * @brief Starts bemf ADC conversion of the phase depending on current step * @param pHandle: handler of the current instance of the Bemf_ADC component * @param step: current step of the six-step sequence */ __weak void BADC_Start(Bemf_ADC_Handle_t *pHandle, uint8_t step) { pHandle->ADCRegularLocked=true; LL_ADC_REG_StopConversion( ADC1 ); /* Enable ADC DMA request*/ LL_ADC_REG_SetDMATransfer( ADC1, LL_ADC_REG_DMA_TRANSFER_UNLIMITED ); /* enable ADC source trigger */ LL_ADC_REG_SetTriggerSource (ADC1, LL_ADC_REG_TRIG_EXT_TIM2_TRGO); LL_ADC_REG_SetTriggerEdge (ADC1, LL_ADC_REG_TRIG_EXT_FALLING); LL_ADC_SetSamplingTimeCommonChannels (ADC1, LL_ADC_SAMPLINGTIME_1CYCLE_5 ); switch (step) { case STEP_1: case STEP_4: BADC_SelectAdcChannel(pHandle, PHASE_W); break; case STEP_2: case STEP_5: BADC_SelectAdcChannel(pHandle, PHASE_V); break; case STEP_3: case STEP_6: BADC_SelectAdcChannel(pHandle, PHASE_U); break; default: break; } LL_DMA_DisableChannel(DMA1, LL_DMA_CHANNEL_1 ); LL_DMA_SetDataLength(DMA1, LL_DMA_CHANNEL_1, pHandle->OverSamplingRate ); LL_DMA_EnableChannel( DMA1, LL_DMA_CHANNEL_1 ); /* Clear Pending Interrupt Bits */ LL_DMA_ClearFlag_TC1( DMA1 ); /* DMA Interrupt Event configuration */ LL_DMA_EnableIT_TC( DMA1, LL_DMA_CHANNEL_1 ); LL_ADC_REG_StartConversion(ADC1); LL_TIM_GenerateEvent_UPDATE(TIM1); } /* * @brief Stops bemf ADC conversion * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_Stop(Bemf_ADC_Handle_t *pHandle) { LL_ADC_REG_StopConversion( ADC1 ); /* Clear Transmission Complete Flag of DMA1 Channel1 */ LL_DMA_ClearFlag_TC1( DMA1 ); /* Clear EOC */ LL_ADC_ClearFlag_EOC( ADC1 ); } /* * @brief Enables the speed loop (low frequency) timer * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_SpeedMeasureOn(Bemf_ADC_Handle_t *pHandle) { LL_TIM_ClearFlag_UPDATE(pHandle->pParams_str->LfTim); LL_TIM_EnableIT_UPDATE(pHandle->pParams_str->LfTim); } /* * @brief Disables the speed loop (low frequency) timer * @param pHandle: handler of the current instance of the Bemf_ADC component */ __weak void BADC_SpeedMeasureOff(Bemf_ADC_Handle_t *pHandle) { LL_TIM_DisableIT_UPDATE(pHandle->pParams_str->LfTim); } /* * @brief Configures the ADC for the current sampling. * It sets the sampling point via TIM1_Ch4 value, the ADC sequence * and channels. * @param pHandle: handler of the current instance of the Bemf_ADC component * @param pHandlePWMC: handler of the current instance of the PWMC component * @param pHandleSTC: handler of the current instance of the Speed Control component */ __weak void BADC_SetSamplingPoint(Bemf_ADC_Handle_t *pHandle, PWMC_Handle_t *pHandlePWMC, SpeednTorqCtrl_Handle_t *pHandleSTC ) { if ((pHandleSTC->ModeDefault == MCM_SPEED_MODE) && (pHandle->DriveMode == VM)) { if (!(pHandle->IsOnSensingEnabled) && (pHandlePWMC->CntPh > pHandle->OnSensingEnThres)) { pHandle->IsOnSensingEnabled=true; pHandle->pSensing_Params = &(pHandle->Pwm_ON); } else if ((pHandle->IsOnSensingEnabled) && (pHandlePWMC->CntPh < pHandle->OnSensingDisThres)) { pHandle->IsOnSensingEnabled=false; pHandle->pSensing_Params = &(pHandle->Pwm_OFF); } else { } } else { pHandle->IsOnSensingEnabled=false; pHandle->pSensing_Params = &(pHandle->Pwm_OFF); } if (true == pHandle->pParams_str->gpio_divider_available) LL_GPIO_ResetOutputPin( pHandle->pParams_str->bemf_divider_port, pHandle->pParams_str->bemf_divider_pin ); LL_TIM_OC_SetCompareCH1( pHandle->pParams_str->TIM_Trigger, pHandle->pSensing_Params->SamplingPoint); } /* * @brief Gets last bemf value and checks for zero crossing detection. * Updates speed loop timer and electrical angle accordingly. * @param pHandle: handler of the current instance of the Bemf_ADC component * @param pHandlePWMC: handler of the current instance of the PWMC component * @retval none */ __weak bool BADC_IsZcDetected( Bemf_ADC_Handle_t *pHandle, PWMC_Handle_t *pHandlePWMC) { uint8_t i; uint32_t DeltaCounter, tZC_Counter = pHandle->ZC_Counter_On_Last; bool ZcDetection = false; pHandle->DemagCounter++; if ( pHandle->DemagCounter >= pHandle->DemagCounterThreshold) { if (pHandle->ZcDetected == false) { for (i=0; i<pHandle->OverSamplingRate; i++) { if (((pHandle->TIM1_pulses[i] > (pHandlePWMC->CntPh + pHandle->SamplingGuard)) && (false == pHandle->IsOnSensingEnabled)) || ((pHandle->TIM1_pulses[i] < (pHandlePWMC->CntPh - pHandle->SamplingGuard)) && (true == pHandle->IsOnSensingEnabled))) { switch(pHandlePWMC->Step) { case STEP_1: pHandle->BemfLastValues[2] = pHandle->ADC1_DMA_converted[i]; if(pHandle->Direction == 1) { if (pHandle->ADC1_DMA_converted[i] < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_60_PHASE_SHIFT / 2; } } else { if (pHandle->ADC1_DMA_converted[i] > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = S16_120_PHASE_SHIFT + S16_60_PHASE_SHIFT / 2; } } break; case STEP_2: pHandle->BemfLastValues[1] = pHandle->ADC1_DMA_converted[i]; if(pHandle->Direction == 1) { if (pHandle->ADC1_DMA_converted[i] > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = S16_60_PHASE_SHIFT / 2; } } else { if (pHandle->ADC1_DMA_converted[i] < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_120_PHASE_SHIFT - S16_60_PHASE_SHIFT / 2; } } break; case STEP_3: pHandle->BemfLastValues[0] = pHandle->ADC1_DMA_converted[i]; if(pHandle->Direction == 1) { if (pHandle->ADC1_DMA_converted[i] < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = S16_60_PHASE_SHIFT + S16_60_PHASE_SHIFT / 2; } } else { if (pHandle->ADC1_DMA_converted[i] > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_60_PHASE_SHIFT - S16_60_PHASE_SHIFT / 2; } } break; case STEP_4: pHandle->BemfLastValues[2] = pHandle->ADC1_DMA_converted[i]; if(pHandle->Direction == 1) { if (pHandle->ADC1_DMA_converted[i] > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = S16_120_PHASE_SHIFT + S16_60_PHASE_SHIFT / 2; } } else { if (pHandle->ADC1_DMA_converted[i] < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_60_PHASE_SHIFT / 2; } } break; case STEP_5: pHandle->BemfLastValues[1] = pHandle->ADC1_DMA_converted[i]; if(pHandle->Direction == 1) { if (pHandle->ADC1_DMA_converted[i] < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_120_PHASE_SHIFT - S16_60_PHASE_SHIFT / 2; } } else { if (pHandle->ADC1_DMA_converted[i] > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = S16_60_PHASE_SHIFT / 2; } } break; case STEP_6: pHandle->BemfLastValues[0] = pHandle->ADC1_DMA_converted[i]; if(pHandle->Direction == 1) { if (pHandle->ADC1_DMA_converted[i] > pHandle->pSensing_Params->AdcThresholdUp) { ZcDetection = true; pHandle->MeasuredElAngle = - S16_60_PHASE_SHIFT - S16_60_PHASE_SHIFT / 2; } } else { if (pHandle->ADC1_DMA_converted[i] < pHandle->pSensing_Params->AdcThresholdDown) { ZcDetection = true; pHandle->MeasuredElAngle = S16_60_PHASE_SHIFT + S16_60_PHASE_SHIFT / 2; } } break; } if (ZcDetection == true) { DeltaCounter = pHandle->TIM1_pulses[pHandle->OverSamplingRate - 1] - pHandle->TIM1_pulses[i]; break; } } else if ((pHandle->TIM1_pulses[i] < (pHandlePWMC->CntPh - pHandle->SamplingGuard)) && (false == pHandle->IsOnSensingEnabled) && (pHandle->ZcDetected == false)) { tZC_Counter = pHandle->ADC1_DMA_converted[i]; } } } if (true == ZcDetection) { pHandle->ZC_Counter_On_Last = tZC_Counter; pHandle->MeasuredElAngle += (S16_60_PHASE_SHIFT/2) - (int16_t)((uint32_t)(pHandle->Zc2CommDelay * S16_60_PHASE_SHIFT)>>9); if (pHandle->ZcEvents > pHandle->StartUpConsistThreshold) { pHandle->IsAlgorithmConverged = true; } pHandle->ZcDetected = true; pHandle->ZcEvents++; switch(pHandlePWMC->Step) { case STEP_1: case STEP_3: case STEP_5: if(pHandle->Direction == 1) { pHandle->ZC_Counter_Down = LL_TIM_GetCounter(pHandle->pParams_str->LfTim) - DeltaCounter/(pHandle->LowFreqTimerPsc + 1); pHandle->ZC_Counter_Last = pHandle->ZC_Counter_Down; } else { pHandle->ZC_Counter_Up = LL_TIM_GetCounter(pHandle->pParams_str->LfTim) - DeltaCounter/(pHandle->LowFreqTimerPsc + 1); pHandle->ZC_Counter_Last = pHandle->ZC_Counter_Up; } break; case STEP_2: case STEP_4: case STEP_6: if(pHandle->Direction == 1) { pHandle->ZC_Counter_Up = LL_TIM_GetCounter(pHandle->pParams_str->LfTim) - DeltaCounter/(pHandle->LowFreqTimerPsc + 1); pHandle->ZC_Counter_Last = pHandle->ZC_Counter_Up; } else { pHandle->ZC_Counter_Down = LL_TIM_GetCounter(pHandle->pParams_str->LfTim) - DeltaCounter/(pHandle->LowFreqTimerPsc + 1); pHandle->ZC_Counter_Last = pHandle->ZC_Counter_Down; } break; } if (true == pHandle->IsAlgorithmConverged) { uint32_t tempReg = (uint32_t )(pHandle->PseudoPeriodConv / ((pHandle->LowFreqTimerPsc + 1) * (pHandle->AvrElSpeedDpp * pHandle->Direction))); LL_TIM_SetAutoReload(pHandle->pParams_str->LfTim,pHandle->ZC_Counter_Last + (((uint32_t)((pHandle->Zc2CommDelay) * tempReg)) >> 9) ); } } } return ZcDetection; } /* * @brief This method must be called - at least - with the same periodicity * on which speed control is executed. It computes and returns - through * parameter hMecSpeedUnit - the rotor average mechanical speed, * expressed in Unit. Average is computed considering a FIFO depth * equal to SpeedBufferSizeUnit. Moreover it also computes and returns * the reliability state of the sensor. * @param pHandle: handler of the current instance of the Bemf_ADC component * @param pMecSpeedUnit pointer to int16_t, used to return the rotor average * mechanical speed (expressed in the unit defined by SPEED_UNIT) * @retval bool speed sensor reliability, measured with reference to parameters * Reliability_hysteresys, VariancePercentage and SpeedBufferSize * true = sensor information is reliable * false = sensor information is not reliable */ __weak bool BADC_CalcAvrgMecSpeedUnit( Bemf_ADC_Handle_t * pHandle, int16_t * pMecSpeedUnit ) { bool bReliability; pHandle->_Super.hElSpeedDpp = pHandle->AvrElSpeedDpp; if (0 == pHandle->AvrElSpeedDpp) { /* Speed is too low */ *pMecSpeedUnit = 0; } else { /* Check if speed is not to fast */ if (pHandle->AvrElSpeedDpp != MAX_PSEUDO_SPEED) { pHandle->DeltaAngle = pHandle->MeasuredElAngle - pHandle->_Super.hElAngle; pHandle->CompSpeed = (int16_t)((int32_t)(pHandle->DeltaAngle) / (int32_t)(pHandle->PWMNbrPSamplingFreq)); /* Convert el_dpp to MecUnit */ *pMecSpeedUnit = (int16_t)((pHandle->AvrElSpeedDpp * (int32_t)pHandle->_Super.hMeasurementFrequency * (int32_t)SPEED_UNIT ) / ((int32_t)(pHandle->_Super.DPPConvFactor) * (int32_t)(pHandle->_Super.bElToMecRatio)) ); } else { *pMecSpeedUnit = (int16_t)pHandle->SatSpeed; } } bReliability = SPD_IsMecSpeedReliable(&pHandle->_Super, pMecSpeedUnit); pHandle->_Super.hAvrMecSpeedUnit = *pMecSpeedUnit; BADC_CalcAvrgElSpeedDpp (pHandle); return (bReliability); } /* * @brief Returns false if calculated speed is out of reliability ranges * @param pHandle: handler of the current instance of the Bemf_ADC component * @retval bool: reliability flag */ __weak bool BADC_IsSpeedReliable( Bemf_ADC_Handle_t *pHandle ) { bool SpeedError = false; if ( pHandle->_Super.hAvrMecSpeedUnit > pHandle->_Super.hMaxReliableMecSpeedUnit ) { SpeedError = true; } if ( pHandle->_Super.hAvrMecSpeedUnit < pHandle->_Super.hMinReliableMecSpeedUnit ) { SpeedError = true; } return ( SpeedError ); } /* * @brief Forces the rotation direction * @param pHandle: handler of the current instance of the Bemf_ADC component * @param direction: imposed direction */ __weak void BADC_SetDirection( Bemf_ADC_Handle_t * pHandle, uint8_t direction ) { if (MC_NULL == pHandle) { /* Nothing to do */ } else { pHandle->Direction = direction; } } /* * @brief Internally performs a checks necessary to state whether * the bemf algorithm converged. To be periodically called * during motor open-loop ramp-up (e.g. at the same frequency of * SPD_CalcElAngle), it returns true if the estimated angle and speed * can be considered reliable, false otherwise * @param pHandle: handler of the current instance of the Bemf_ADC component * * @retval bool sensor reliability state */ __weak bool BADC_IsObserverConverged( Bemf_ADC_Handle_t * pHandle ) { return pHandle->IsAlgorithmConverged; } /* * @brief Configures the proper ADC channel according to the current * step corresponding to the floating phase. To be periodically called * at least at every step change. * @param pHandle: handler of the current instance of the Bemf_ADC component * @param Phase: Floating phase for bemf acquisition */ void BADC_SelectAdcChannel(Bemf_ADC_Handle_t * pHandle, uint8_t Phase) { while (LL_ADC_REG_IsConversionOngoing(ADC1)) { LL_ADC_REG_StopConversion(ADC1); while(LL_ADC_REG_IsStopConversionOngoing(ADC1)); } /* Sampling time configuration */ /* Regular sequence configuration */ LL_ADC_REG_SetSequencerChannels(ADC1, __LL_ADC_DECIMAL_NB_TO_CHANNEL(pHandle->pParams_str->AdcChannel[Phase])); LL_ADC_ClearFlag_EOC(ADC1); } /* * @brief Updates the estimated electrical angle. * @param pHandle: handler of the current instance of the Bemf_ADC component * @retval int16_t rotor electrical angle (s16Degrees) */ __weak int16_t BADC_CalcElAngle(Bemf_ADC_Handle_t * pHandle) { int16_t retValue; if (pHandle->_Super.hElSpeedDpp != MAX_PSEUDO_SPEED) { if (false == pHandle->IsLoopClosed) { pHandle->MeasuredElAngle += pHandle->_Super.hElSpeedDpp; pHandle->PrevRotorFreq = pHandle->_Super.hElSpeedDpp; pHandle->_Super.hElAngle += pHandle->_Super.hElSpeedDpp + pHandle->CompSpeed; } else { pHandle->_Super.hElAngle = pHandle->MeasuredElAngle; } } else { pHandle->_Super.hElAngle += pHandle->PrevRotorFreq; } retValue = pHandle->_Super.hElAngle; return (retValue); } /* * @brief Must be called - at least - with the same periodicity * on which speed control is executed. It computes and update component * variable hElSpeedDpp that is estimated average electrical speed * expressed in dpp used for instance in observer equations. * Average is computed considering a FIFO depth equal to * bSpeedBufferSizedpp. * @param pHandle: handler of the current instance of the Bemf_ADC component */ void BADC_CalcAvrgElSpeedDpp( Bemf_ADC_Handle_t * pHandle ) { uint32_t wCaptBuf; /* used to validate the average speed measurement */ if (pHandle->BufferFilled < pHandle->SpeedBufferSize) { pHandle->BufferFilled++; } else { /* Nothing to do */ } if (false == pHandle->IsLoopClosed) { if (pHandle->VirtualElSpeedDpp == 0) pHandle->Counter_Period = 0xFFFF; else pHandle->Counter_Period = ( uint32_t )(pHandle->PseudoPeriodConv / ((pHandle->LowFreqTimerPsc + 1) * pHandle->VirtualElSpeedDpp)); } else { pHandle->Counter_Period = pHandle->ZC_Counter_Last + pHandle->Last_Zc2Comm_Delay; } wCaptBuf = pHandle->Counter_Period * (pHandle->LowFreqTimerPsc + 1); /* Filtering to fast speed... could be a glitch ? */ /* the MAX_PSEUDO_SPEED is temporary in the buffer, and never included in average computation*/ if (wCaptBuf < pHandle->MinPeriod) { /* Nothing to do */ } else { pHandle->ElPeriodSum -= pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx]; /* value we gonna removed from the accumulator */ if (wCaptBuf >= pHandle->MaxPeriod) { pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx] = (int32_t)pHandle->MaxPeriod * pHandle->Direction; } else { pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx] = (int32_t)wCaptBuf ; pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx] *= pHandle->Direction; pHandle->ElPeriodSum += pHandle->SpeedBufferDpp[pHandle->SpeedFIFOIdx]; } /* Update pointers to speed buffer */ pHandle->SpeedFIFOIdx++; if (pHandle->SpeedFIFOIdx == pHandle->SpeedBufferSize) { pHandle->SpeedFIFOIdx = 0U; } if (((pHandle->BufferFilled < pHandle->SpeedBufferSize) && (wCaptBuf != 0U)) || (false == pHandle->IsLoopClosed)) { uint32_t tempReg = (pHandle->PseudoPeriodConv / wCaptBuf) * (uint32_t)pHandle->Direction; pHandle->AvrElSpeedDpp = (int16_t)tempReg; } else { /* Average speed allow to smooth the mechanical sensors misalignement */ int32_t tElPeriodSum = 0; uint8_t i; for (i=0; i < pHandle->SpeedBufferSize; i++) { tElPeriodSum += pHandle->SpeedBufferDpp[i]; } pHandle->AvrElSpeedDpp = (int16_t)((int32_t)pHandle->PseudoPeriodConv / (tElPeriodSum / (int32_t)pHandle->SpeedBufferSize)); /* Average value */ } } } /* * @brief Used to calculate instant speed during revup, to * initialize parameters at step change and to select proper ADC channel * for next Bemf acquisitions * @param pHandle: handler of the current instance of the Bemf_ADC component * @param hElSpeedDpp: Mechanical speed imposed by virtual speed component * @param pHandlePWMC: handler of the current instance of the PWMC component */ void BADC_StepChangeEvent(Bemf_ADC_Handle_t * pHandle, int16_t hElSpeedDpp, PWMC_Handle_t *pHandlePWMC) { pHandle->DemagCounter = 0; while (LL_ADC_REG_IsConversionOngoing(ADC1)) { LL_ADC_REG_StopConversion(ADC1); while(LL_ADC_REG_IsStopConversionOngoing(ADC1)); } BADC_Stop(pHandle); pHandle->Last_Zc2Comm_Delay = LL_TIM_GetAutoReload(pHandle->pParams_str->LfTim) - pHandle->ZC_Counter_Last; if (false == pHandle->IsLoopClosed) { if (hElSpeedDpp < 0) { pHandle->VirtualElSpeedDpp = - hElSpeedDpp; } else { pHandle->VirtualElSpeedDpp = hElSpeedDpp; } pHandle->ZcDetected = false; } else { int16_t ElAngleUpdate; if(pHandle->Direction == -1) { ElAngleUpdate = -S16_60_PHASE_SHIFT ; } else { ElAngleUpdate = S16_60_PHASE_SHIFT ; } pHandle->MeasuredElAngle += ElAngleUpdate; if ( false == pHandle->ZcDetected) { LL_TIM_SetAutoReload(pHandle->pParams_str->LfTim,LL_TIM_GetAutoReload(pHandle->pParams_str->LfTim) * 120 / 100); } else { pHandle->ZcDetected = false; } } pHandle->StepUpdate = true; } /* * @brief Calculates and stores in the corresponding variable the demagnetization * time in open loop operation * @param pHandle: handler of the current instance of the Bemf_ADC component */ void BADC_CalcRevUpDemagTime(Bemf_ADC_Handle_t *pHandle) { int16_t hSpeed; hSpeed = (int16_t)((pHandle->VirtualElSpeedDpp * (int32_t)pHandle->_Super.hMeasurementFrequency * (int32_t)SPEED_UNIT ) / ((int32_t)(pHandle->_Super.DPPConvFactor) * (int32_t)(pHandle->_Super.bElToMecRatio)) );; if (hSpeed == 0) { pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold;; } else { pHandle->DemagCounterThreshold = (uint16_t) (pHandle->DemagParams.RevUpDemagSpeedConv / hSpeed); } if (pHandle->DemagCounterThreshold < pHandle->DemagParams.DemagMinimumThreshold) { pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold; } } /* * @brief Calculates and stores in the corresponding variable the demagnetization * time in closed loop operation * @param pHandle: handler of the current instance of the Bemf_ADC component */ void BADC_CalcRunDemagTime(Bemf_ADC_Handle_t *pHandle) { int16_t hSpeed; hSpeed = pHandle->_Super.hAvrMecSpeedUnit; if (hSpeed < 0) hSpeed = - hSpeed; if (hSpeed < pHandle->DemagParams.DemagMinimumSpeedUnit) { pHandle->DemagCounterThreshold = (uint16_t) (pHandle->DemagParams.RunDemagSpeedConv / hSpeed); if (pHandle->DemagCounterThreshold < pHandle->DemagParams.DemagMinimumThreshold) { pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold; } } else { pHandle->DemagCounterThreshold = pHandle->DemagParams.DemagMinimumThreshold; } } /* * @brief Must be called after switch-over procedure when * virtual speed sensor transition is ended. * @param pHandle: handler of the current instance of the STO component */ void BADC_SetLoopClosed(Bemf_ADC_Handle_t *pHandle) { pHandle->IsLoopClosed=true; } /* * @brief Returns the last acquired bemf value * @param pHandle: handler of the current instance of the Bemf_ADC component * @param phase: motor phase under investigation * @retval uint16_t: Bemf value */ uint16_t BADC_GetLastBemfValue(Bemf_ADC_Handle_t *pHandle, uint8_t phase) { return ((MC_NULL == pHandle) ? 0U : pHandle->BemfLastValues[phase]); } /* * @brief Returns the zero crossing detection flag * @param pHandle: handler of the current instance of the Bemf_ADC component * @retval bool: zero crossing detection flag */ bool BADC_GetBemfZcrFlag(Bemf_ADC_Handle_t *pHandle) { return ((MC_NULL == pHandle) ? 0U : pHandle->ZcDetected); } /* * @brief Returns true if the step needs to be updated * @param pHandle: handler of the current instance of the Bemf_ADC component * @retval bool: step update request */ bool BADC_ClearStepUpdate(Bemf_ADC_Handle_t *pHandle) { bool retValue = (((pHandle->IsLoopClosed == true) && (pHandle->StepUpdate == true)) || (pHandle->IsLoopClosed == false)); pHandle->StepUpdate = false; return retValue; } /* * @brief Configures the parameters for bemf sensing during pwm off-time * @param pHandle: handler of the current instance of the Bemf_ADC component * @param BemfAdcConfig: thresholds and sampling time parameters * @param Zc2CommDelay: delay between bemf zero crossing parameter and step commutation * @param bemfAdcDemagConfig: demagnetization parameters */ void BADC_SetBemfSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfAdcConfig, uint16_t *Zc2CommDelay, Bemf_Demag_Params *bemfAdcDemagConfig) { pHandle->Pwm_OFF.AdcThresholdUp = BemfAdcConfig->AdcThresholdUp; pHandle->Pwm_OFF.AdcThresholdDown = BemfAdcConfig->AdcThresholdDown; pHandle->Pwm_OFF.SamplingPoint = BemfAdcConfig->SamplingPoint; pHandle->Zc2CommDelay = *Zc2CommDelay; pHandle->DemagParams.DemagMinimumSpeedUnit = bemfAdcDemagConfig->DemagMinimumSpeedUnit; pHandle->DemagParams.DemagMinimumThreshold = bemfAdcDemagConfig->DemagMinimumThreshold; } /* * @brief Configures the parameters for bemf sensing during pwm on-time * @param pHandle: handler of the current instance of the Bemf_ADC component * @param BemfOnAdcConfig: thresholds and sampling time parameters * @param OnSensingEnThres: Minimum dudty cycle for on-sensing activation * @param OnSensingDisThres: Minimum duty cycle for on-sensing Deactivationg */ void BADC_SetBemfOnTimeSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfOnAdcConfig, uint16_t *OnSensingEnThres, uint16_t *OnSensingDisThres) { pHandle->Pwm_ON.AdcThresholdUp = BemfOnAdcConfig->AdcThresholdUp; pHandle->Pwm_ON.AdcThresholdDown = BemfOnAdcConfig->AdcThresholdDown; pHandle->Pwm_ON.SamplingPoint = BemfOnAdcConfig->SamplingPoint; pHandle->OnSensingEnThres = *OnSensingEnThres; pHandle->OnSensingDisThres = *OnSensingDisThres; } /* * @brief Gets the parameters for bemf sensing during pwm off-time * @param pHandle: handler of the current instance of the Bemf_ADC component * @param BemfAdcConfig: thresholds and sampling time parameters * @param Zc2CommDelay: delay between bemf zero crossing parameter and step commutation * @param BemfAdcDemagConfig: demagnetization parameters */ void BADC_GetBemfSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfAdcConfig, uint16_t *Zc2CommDelay, Bemf_Demag_Params *BemfAdcDemagConfig) { BemfAdcConfig->AdcThresholdUp = pHandle->Pwm_OFF.AdcThresholdUp; BemfAdcConfig->AdcThresholdDown = pHandle->Pwm_OFF.AdcThresholdDown; BemfAdcConfig->SamplingPoint = pHandle->Pwm_OFF.SamplingPoint; *Zc2CommDelay = pHandle->Zc2CommDelay; BemfAdcDemagConfig->DemagMinimumSpeedUnit = pHandle->DemagParams.DemagMinimumSpeedUnit; BemfAdcDemagConfig->DemagMinimumThreshold = pHandle->DemagParams.DemagMinimumThreshold; } /* * @brief Gets the parameters for bemf sensing during pwm on-time * @param pHandle: handler of the current instance of the Bemf_ADC component * @param BemfOnAdcConfig: thresholds and sampling time parameters * @param OnSensingEnThres: Minimum duty cycle for on-sensing activation * @param OnSensingDisThres: Minimum duty cycle for on-sensing Deactivationg */ void BADC_GetBemfOnTimeSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfOnAdcConfig, uint16_t *OnSensingEnThres, uint16_t *OnSensingDisThres) { BemfOnAdcConfig->AdcThresholdUp = pHandle->Pwm_ON.AdcThresholdUp; BemfOnAdcConfig->AdcThresholdDown = pHandle->Pwm_ON.AdcThresholdDown; BemfOnAdcConfig->SamplingPoint = pHandle->Pwm_ON.SamplingPoint; *OnSensingEnThres = pHandle->OnSensingEnThres; *OnSensingDisThres = pHandle->OnSensingDisThres; } /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
36,252
C
35.144566
167
0.637841
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/F0xx/Src/r3_f0xx_pwm_curr_fdbk.c
/** ****************************************************************************** * @file r3_f0xx_pwm_curr_fdbk.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement current sensor * class to be stantiated when the three shunts current sensing * topology is used. * * It is specifically designed for STM32F0XX * microcontrollers and implements the successive sampling of two motor * current using only one ADC. * + MCU peripheral and handle initialization fucntion * + three shunt current sensing * + space vector modulation function * + ADC sampling function * ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup R3_F0XX_pwm_curr_fdbk */ /* Includes ------------------------------------------------------------------*/ #include "r3_f0xx_pwm_curr_fdbk.h" #include "pwm_common.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup R3_1_pwm_curr_fdbk * @{ */ /* Private defines -----------------------------------------------------------*/ #define TIMxCCER_MASK_CH123 (LL_TIM_CHANNEL_CH1 | LL_TIM_CHANNEL_CH1N | LL_TIM_CHANNEL_CH2|LL_TIM_CHANNEL_CH2N |\ LL_TIM_CHANNEL_CH3 | LL_TIM_CHANNEL_CH3N) /* Private function prototypes -----------------------------------------------*/ void R3_1_HFCurrentsCalibrationAB( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ); void R3_1_HFCurrentsCalibrationC( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ); uint16_t R3_1_WriteTIMRegisters( PWMC_Handle_t * pHdl, uint16_t hCCR4Reg ); /* Private functions ---------------------------------------------------------*/ /* Local redefinition of both LL_TIM_OC_EnablePreload & LL_TIM_OC_DisablePreload */ __STATIC_INLINE void __LL_TIM_OC_EnablePreload(TIM_TypeDef *TIMx, uint32_t Channel) { register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); register __IO uint32_t *pReg = (__IO uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); SET_BIT(*pReg, (TIM_CCMR1_OC1PE << SHIFT_TAB_OCxx[iChannel])); } __STATIC_INLINE void __LL_TIM_OC_DisablePreload(TIM_TypeDef *TIMx, uint32_t Channel) { register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(LL_TIM_CHANNEL_CH4); register __IO uint32_t *pReg = (__IO uint32_t *)((uint32_t)((uint32_t)(&TIM1->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); CLEAR_BIT(*pReg, (TIM_CCMR1_OC1PE << SHIFT_TAB_OCxx[iChannel])); } /* * @brief Initializes TIM1, ADC1, GPIO, DMA1 and NVIC for three shunt current * reading configuration using STM32F0X. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void R3_1_Init( PWMC_R3_1_Handle_t * pHandle ) { if ( ( uint32_t )pHandle == ( uint32_t )&pHandle->_Super ) { /* disable IT and flags in case of LL driver usage * workaround for unwanted interrupt enabling done by LL driver */ LL_ADC_DisableIT_EOC( ADC1 ); LL_ADC_ClearFlag_EOC( ADC1 ); LL_ADC_DisableIT_EOS( ADC1 ); LL_ADC_ClearFlag_EOS( ADC1 ); /* Enable the CCS */ LL_RCC_HSE_EnableCSS(); /* Peripheral clocks enabling END ----------------------------------------*/ /* Clear TIMx break flag. */ LL_TIM_ClearFlag_BRK( TIM1 ); LL_TIM_EnableIT_BRK( TIM1 ); LL_TIM_SetCounter( TIM1, ( uint32_t )( pHandle->Half_PWMPeriod ) - 1u ); /* TIM1 Counter Clock stopped when the core is halted */ LL_APB1_GRP2_EnableClock (LL_APB1_GRP2_PERIPH_DBGMCU); LL_DBGMCU_APB1_GRP2_FreezePeriph( LL_DBGMCU_APB1_GRP2_TIM1_STOP ); /* ADC Calibration */ LL_ADC_StartCalibration( ADC1 ); while ((LL_ADC_IsCalibrationOnGoing(ADC1) == SET) || (LL_ADC_REG_IsConversionOngoing(ADC1) == SET) || (LL_ADC_REG_IsStopConversionOngoing(ADC1) == SET) || (LL_ADC_IsDisableOngoing(ADC1) == SET)) { /* wait */ } /* Enables the ADC peripheral */ LL_ADC_Enable( ADC1 ); /* Wait ADC Ready */ while ( LL_ADC_IsActiveFlag_ADRDY( ADC1 ) == RESET ) { /* wait */ } /* DMA1 Channel1 Config */ LL_DMA_SetMemoryAddress( DMA1, LL_DMA_CHANNEL_1, ( uint32_t )pHandle->ADC1_DMA_converted ); LL_DMA_SetPeriphAddress( DMA1, LL_DMA_CHANNEL_1, ( uint32_t )&ADC1->DR ); LL_DMA_SetDataLength(DMA1, LL_DMA_CHANNEL_1, 3); /* Enables the DMA1 Channel1 peripheral */ LL_DMA_EnableChannel( DMA1, LL_DMA_CHANNEL_1 ); /* disable ADC source trigger */ LL_TIM_SetTriggerOutput(TIM1, LL_TIM_TRGO_RESET); /* Enable PWM channel */ LL_TIM_CC_EnableChannel( TIM1, TIMxCCER_MASK_CH123 ); /* set default triggering edge */ pHandle->ADCTriggerEdge = LL_ADC_REG_TRIG_EXT_RISING; /* We allow ADC usage for regular conversion on Systick*/ pHandle->ADCRegularLocked=false; pHandle->_Super.DTTest = 0u; LL_TIM_EnableCounter( TIM1 ); } } /* * @brief Stores in @p pHdl handler the calibrated @p offsets. * */ __weak void R3_1_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 pHandle->PhaseAOffset = offsets->phaseAOffset; pHandle->PhaseBOffset = offsets->phaseBOffset; pHandle->PhaseCOffset = offsets->phaseCOffset; pHdl->offsetCalibStatus = true; } /* * @brief Reads the calibrated @p offsets stored in @p pHdl. * */ __weak void R3_1_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets) { PWMC_R3_1_Handle_t *pHandle = (PWMC_R3_1_Handle_t *)pHdl; //cstat !MISRAC2012-Rule-11.3 offsets->phaseAOffset = pHandle->PhaseAOffset; offsets->phaseBOffset = pHandle->PhaseBOffset; offsets->phaseCOffset = pHandle->PhaseCOffset; } /* * @brief Stores into the @p pHdl handler the voltage present on Ia and * Ib current feedback analog channels when no current is flowing into the * motor. * */ __weak void R3_1_CurrentReadingCalibration( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = TIM1; volatile PWMC_GetPhaseCurr_Cb_t GetPhaseCurrCbSave; volatile PWMC_SetSampPointSectX_Cb_t SetSampPointSectXCbSave; if (false == pHandle->_Super.offsetCalibStatus) { /* Save callback routines */ GetPhaseCurrCbSave = pHandle->_Super.pFctGetPhaseCurrents; SetSampPointSectXCbSave = pHandle->_Super.pFctSetADCSampPointSectX; pHandle->PhaseAOffset = 0u; pHandle->PhaseBOffset = 0u; pHandle->PhaseCOffset = 0u; pHandle->PolarizationCounter = 0u; /* It forces inactive level on TIMx CHy and CHyN */ LL_TIM_CC_DisableChannel( TIMx, TIMxCCER_MASK_CH123 ); /* Offset calibration for A B c phases */ /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R3_1_HFCurrentsCalibrationAB; pHandle->_Super.pFctSetADCSampPointSectX = &R3_1_SetADCSampPointCalibration; pHandle->CalibSector = SECTOR_5; /* Mandatory to force first polarization conversion on SECTOR_5*/ pHandle->_Super.Sector = SECTOR_5; R3_1_SwitchOnPWM( &pHandle->_Super ); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd( TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter ); R3_1_SwitchOffPWM( &pHandle->_Super ); pHandle->_Super.pFctGetPhaseCurrents = &R3_1_HFCurrentsCalibrationC; pHandle->CalibSector = SECTOR_1; /* Mandatory to force first polarization conversion on SECTOR_1*/ pHandle->_Super.Sector = SECTOR_1; pHandle->PolarizationCounter = 0; R3_1_SwitchOnPWM( &pHandle->_Super ); /* Wait for NB_CONVERSIONS to be executed */ waitForPolarizationEnd( TIMx, &pHandle->_Super.SWerror, pHandle->pParams_str->RepetitionCounter, &pHandle->PolarizationCounter ); R3_1_SwitchOffPWM( &pHandle->_Super ); /* Mean Value of PhaseCurrents Offset calculation by 4bit shifting operation * instead division by NB_CONVERSIONS value fixed to 16. */ pHandle->PhaseAOffset = pHandle->PhaseAOffset / NB_CONVERSIONS; pHandle->PhaseBOffset = pHandle->PhaseBOffset / NB_CONVERSIONS; pHandle->PhaseCOffset = pHandle->PhaseCOffset / NB_CONVERSIONS; if (0U == pHandle->_Super.SWerror) { pHandle->_Super.offsetCalibStatus = true; } else { /* nothing to do */ } /* restore function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = GetPhaseCurrCbSave; pHandle->_Super.pFctSetADCSampPointSectX = SetSampPointSectXCbSave; } /* It over write TIMx CCRy wrongly written by FOC during calibration so as to force 50% duty cycle on the three inverer legs */ /* Disable TIMx preload */ __LL_TIM_OC_DisablePreload(TIMx,LL_TIM_CHANNEL_CH1); __LL_TIM_OC_DisablePreload(TIMx,LL_TIM_CHANNEL_CH2); __LL_TIM_OC_DisablePreload(TIMx,LL_TIM_CHANNEL_CH3); LL_TIM_OC_SetCompareCH1( TIMx, pHandle->Half_PWMPeriod ); LL_TIM_OC_SetCompareCH2( TIMx, pHandle->Half_PWMPeriod ); LL_TIM_OC_SetCompareCH3( TIMx, pHandle->Half_PWMPeriod ); /* Enable TIMx preload */ __LL_TIM_OC_EnablePreload(TIMx,LL_TIM_CHANNEL_CH1); __LL_TIM_OC_EnablePreload(TIMx,LL_TIM_CHANNEL_CH2); __LL_TIM_OC_EnablePreload(TIMx,LL_TIM_CHANNEL_CH3); /* It re-enable drive of TIMx CHy and CHyN by TIMx CHyRef*/ LL_TIM_CC_EnableChannel( TIMx, TIMxCCER_MASK_CH123 ); pHandle->_Super.Sector = SECTOR_5; pHandle->_Super.BrakeActionLock = false; } /* * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p pStator_Currents ab_t format. * */ __weak void R3_1_GetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif int32_t wAux; uint16_t hReg1; uint16_t hReg2; uint8_t bSector; /* disable ADC trigger source */ LL_TIM_SetTriggerOutput(TIM1, LL_TIM_TRGO_RESET); bSector = ( uint8_t ) pHandle->_Super.Sector; LL_ADC_REG_SetSequencerScanDirection(ADC1, LL_ADC_REG_SEQ_SCAN_DIR_FORWARD); hReg1 = *pHandle->pParams_str->ADCDataReg1[bSector]; hReg2 = *pHandle->pParams_str->ADCDataReg2[bSector]; switch ( bSector ) { case SECTOR_4: case SECTOR_5: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) ------------------------------*/ wAux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( hReg1 ); /* Saturation of Ia */ if ( wAux < -INT16_MAX ) { pStator_Currents->a = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->a = INT16_MAX; } else { pStator_Currents->a = ( int16_t )wAux; } /* Ib = PhaseBOffset - ADC converted value) ------------------------------*/ wAux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( hReg2 ); /* Saturation of Ib */ if ( wAux < -INT16_MAX ) { pStator_Currents->b = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->b = INT16_MAX; } else { pStator_Currents->b = ( int16_t )wAux; } break; case SECTOR_6: case SECTOR_1: /* Current on Phase A is not accessible */ /* Ib = (PhaseBOffset - ADC converted value) ------------------------------*/ wAux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( hReg1 ); /* Saturation of Ib */ if ( wAux < -INT16_MAX ) { pStator_Currents->b = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->b = INT16_MAX; } else { pStator_Currents->b = ( int16_t )wAux; } /* Ic = PhaseCOffset - ADC converted value) */ /* Ia = -Ic -Ib */ wAux = ( int32_t )( pHandle->PhaseCOffset ) - ( int32_t )( hReg2 ); wAux = -wAux - ( int32_t )pStator_Currents->b; /* Saturation of Ia */ if ( wAux > INT16_MAX ) { pStator_Currents->a = INT16_MAX; } else if ( wAux < -INT16_MAX ) { pStator_Currents->a = -INT16_MAX; } else { pStator_Currents->a = ( int16_t )wAux; } break; case SECTOR_2: case SECTOR_3: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) ------------------------------*/ wAux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( hReg1 ); /* Saturation of Ia */ if ( wAux < -INT16_MAX ) { pStator_Currents->a = -INT16_MAX; } else if ( wAux > INT16_MAX ) { pStator_Currents->a = INT16_MAX; } else { pStator_Currents->a = ( int16_t )wAux; } /* Ic = PhaseCOffset - ADC converted value) ------------------------------*/ wAux = ( int32_t )( pHandle->PhaseCOffset ) - ( int32_t )( hReg2 ); /* Ib = -Ic -Ia */ wAux = -wAux - ( int32_t )pStator_Currents->a; /* Ib */ /* Saturation of Ib */ if ( wAux > INT16_MAX ) { pStator_Currents->b = INT16_MAX; } else if ( wAux < -INT16_MAX ) { pStator_Currents->b = -INT16_MAX; } else { pStator_Currents->b = ( int16_t )wAux; } break; default: break; } pHandle->_Super.Ia = pStator_Currents->a; pHandle->_Super.Ib = pStator_Currents->b; pHandle->_Super.Ic = -pStator_Currents->a - pStator_Currents->b; } /* * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p Iab ab_t format. Specific to overmodulation. * */ __weak void R3_1_GetPhaseCurrents_OVM( PWMC_Handle_t * pHdl, ab_t * Iab ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ uint8_t Sector; int32_t Aux; uint32_t ADCDataReg1; uint32_t ADCDataReg2; /* disable ADC trigger source */ LL_TIM_SetTriggerOutput(TIM1, LL_TIM_TRGO_RESET); LL_ADC_REG_SetSequencerScanDirection(ADC1, LL_ADC_REG_SEQ_SCAN_DIR_FORWARD); Sector = ( uint8_t )pHandle->_Super.Sector; ADCDataReg1 = *pHandle->pParams_str->ADCDataReg1[Sector]; ADCDataReg2 = *pHandle->pParams_str->ADCDataReg2[Sector]; switch ( Sector ) { case SECTOR_4: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { // Ib not available, use estimated Ib Aux = ( int32_t )( pHandle->_Super.IbEst ); } else { /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg2 ); } /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_5: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { // Ia not available, use estimated Ia Aux = ( int32_t )( pHandle->_Super.IaEst ); } else { Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg2 ); /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_6: /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IcEst ; /* -Ic */ Aux -= ( int32_t )Iab->b; } else { /* Ia = -Ic -Ib */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->b; /* Ia */ } /* Saturation of Ia */ if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else { Iab->a = ( int16_t )Aux; } break; case SECTOR_1: /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IbEst; } else { Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } /* Ia = -Ic -Ib */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->b; /* Ia */ /* Saturation of Ia */ if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else { Iab->a = ( int16_t )Aux; } break; case SECTOR_2: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ if (pHandle->_Super.useEstCurrent == true) { Aux = ( int32_t ) pHandle->_Super.IaEst; } else { Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); } /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } /* Ib = -Ic -Ia */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ /* Saturation of Ib */ if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_3: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } if (pHandle->_Super.useEstCurrent == true) { /* Ib = -Ic -Ia */ Aux = ( int32_t ) pHandle->_Super.IcEst; /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ } else { /* Ib = -Ic -Ia */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ } /* Saturation of Ib */ if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; default: break; } pHandle->_Super.Ia = Iab->a; pHandle->_Super.Ib = Iab->b; pHandle->_Super.Ic = -Iab->a - Iab->b; } /* * @brief Configures the ADC for the current sampling during calibration. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ __weak uint16_t R3_1_SetADCSampPointCalibration( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif pHandle->ADCTriggerEdge = LL_ADC_REG_TRIG_EXT_RISING; pHandle->_Super.Sector = pHandle->CalibSector; return R3_1_WriteTIMRegisters( pHdl, ( uint16_t )( pHandle->Half_PWMPeriod ) - 1u); } /* * @brief Configures the ADC for the current sampling related to sector X (X = [1..6] ). * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ __weak uint16_t R3_1_SetADCSampPointSectX( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif uint16_t hCntSmp; uint16_t hDeltaDuty; register uint16_t lowDuty = pHdl->lowDuty; register uint16_t midDuty = pHdl->midDuty; /* Check if sampling AB in the middle of PWM is possible */ if ( ( uint16_t )( pHandle->Half_PWMPeriod - lowDuty ) > pHandle->pParams_str->hTafter ) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled which corresponds * to sector 4 (could be also sector 5) */ pHandle->_Super.Sector = SECTOR_5; /* set sampling point trigger in the middle of PWM period */ hCntSmp = ( uint32_t )( pHandle->Half_PWMPeriod ) - 1u; } else { /* In this case it is necessary to convert phases with Maximum and variable complementary duty cycle.*/ /* ADC Injected sequence configuration. The stator phase with minimum value of complementary duty cycle is set as first. In every sector there is always one phase with maximum complementary duty, one with minimum complementary duty and one with variable complementary duty. In this case, phases with variable complementary duty and with maximum duty are converted and the first will be always the phase with variable complementary duty cycle */ /* Crossing Point Searching */ hDeltaDuty = ( uint16_t )( lowDuty - midDuty ); /* Definition of crossing point */ if ( hDeltaDuty > ( uint16_t )( pHandle->Half_PWMPeriod - lowDuty ) * 2u ) { hCntSmp = lowDuty - pHandle->pParams_str->hTbefore; } else { hCntSmp = lowDuty + pHandle->pParams_str->hTafter; if ( hCntSmp >= pHandle->Half_PWMPeriod ) { pHandle->ADCTriggerEdge = LL_ADC_REG_TRIG_EXT_FALLING; hCntSmp = ( 2u * pHandle->Half_PWMPeriod ) - hCntSmp - 1u; } } } return R3_1_WriteTIMRegisters( &pHandle->_Super, hCntSmp ); } /* * @brief Configures the ADC for the current sampling related to sector X (X = [1..6] ) in case of overmodulation. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ uint16_t R3_1_SetADCSampPointSectX_OVM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ uint16_t SamplingPoint; uint16_t DeltaDuty; pHandle->_Super.useEstCurrent = false; DeltaDuty = ( uint16_t )( pHdl->lowDuty - pHdl->midDuty ); /* case 1 (cf user manual) */ if (( uint16_t )( pHandle->Half_PWMPeriod - pHdl->lowDuty ) > pHandle->pParams_str->hTafter) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled which corresponds * to sector 4 or 5 */ pHandle->_Super.Sector = SECTOR_5; /* set sampling point trigger in the middle of PWM period */ SamplingPoint = pHandle->Half_PWMPeriod - (uint16_t) 1; } else /* case 2 (cf user manual) */ { if (DeltaDuty >= pHandle->pParams_str->Tcase2) { SamplingPoint = pHdl->lowDuty - pHandle->pParams_str->hTbefore; } else { /* case 3 (cf user manual) */ if ((pHandle->Half_PWMPeriod - pHdl->lowDuty) > pHandle->pParams_str->Tcase3) { /* ADC trigger edge must be changed from positive to negative */ pHandle->ADCTriggerEdge = LL_ADC_REG_TRIG_EXT_FALLING; SamplingPoint = pHdl->lowDuty + pHandle->pParams_str->Tsampling; } else { SamplingPoint = pHandle->Half_PWMPeriod-1; pHandle->_Super.useEstCurrent = true; } } } return R3_1_WriteTIMRegisters( &pHandle->_Super, SamplingPoint ); } /* * @brief Writes into peripheral registers the new duty cycles and sampling point. * * @param pHdl: Handler of the current instance of the PWM component. * @param hCCR4Reg: New capture/compare register value, written in timer clock counts. * @retval Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ __weak uint16_t R3_1_WriteTIMRegisters( PWMC_Handle_t * pHdl, uint16_t hCCR4Reg) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint16_t hAux; LL_TIM_OC_SetCompareCH1 ( TIMx, (uint32_t)pHandle->_Super.CntPhA ); LL_TIM_OC_SetCompareCH2 ( TIMx, (uint32_t)pHandle->_Super.CntPhB ); LL_TIM_OC_SetCompareCH3 ( TIMx, (uint32_t)pHandle->_Super.CntPhC ); LL_TIM_OC_SetCompareCH4 ( TIMx, (uint32_t)hCCR4Reg ); /* Re-configuration of CCR4 must be done before the timer update to be taken into account at the next PWM cycle. Otherwise we are too late, we flag a FOC_DURATION error */ if (((TIMx->CR2) & TIM_CR2_MMS_Msk) != LL_TIM_TRGO_RESET ) { hAux = MC_DURATION; } else { hAux = MC_NO_ERROR; } if ( pHandle->_Super.SWerror == 1u ) { hAux = MC_DURATION; pHandle->_Super.SWerror = 0u; } return hAux; } /* * @brief Implementation of PWMC_GetPhaseCurrents to be performed during calibration. * * It sums up injected conversion data into PhaseAOffset and wPhaseBOffset * to compute the offset introduced in the current feedback network. It is required to * properly configure ADC inputs before in order to enable offset computation. * * @param pHdl: Pointer on the target component instance. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ __weak void R3_1_HFCurrentsCalibrationAB( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = TIM1; uint8_t bSector = pHandle->CalibSector; /* disable ADC trigger source */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); if ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { pHandle->PhaseAOffset += *pHandle->pParams_str->ADCDataReg1[bSector]; pHandle->PhaseBOffset += *pHandle->pParams_str->ADCDataReg2[bSector]; pHandle->PolarizationCounter++; } /* during offset calibration no current is flowing in the phases */ pStator_Currents->a = 0; pStator_Currents->b = 0; } /* * @brief Implementation of PWMC_GetPhaseCurrents to be performed during calibration. * * It sums up injected conversion data into PhaseCOffset to compute the offset * introduced in the current feedback network. It is required to properly configure * ADC inputs before in order to enable offset computation. * * @param pHdl: Pointer on the target component instance. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ __weak void R3_1_HFCurrentsCalibrationC( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = TIM1; uint8_t bSector = pHandle->CalibSector; /* disable ADC trigger source */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); pHandle->_Super.Sector = SECTOR_1; if ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { pHandle->PhaseCOffset += *pHandle->pParams_str->ADCDataReg2[bSector]; pHandle->PolarizationCounter++; } /* during offset calibration no current is flowing in the phases */ pStator_Currents->a = 0; pStator_Currents->b = 0; } /* * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors of driving section. It has to be * called each motor start-up when using high voltage drivers. * * @param pHdl: Handler of the current instance of the PWM component * @param ticks: Timer ticks value to be applied * Min value: 0 (low sides ON) * Max value: PWM_PERIOD_CYCLES/2 (low sides OFF) */ __weak void R3_1_TurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = TIM1; pHandle->_Super.TurnOnLowSidesAction = true; /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /*Turn on the three low side switches */ LL_TIM_OC_SetCompareCH1(TIMx, ticks); LL_TIM_OC_SetCompareCH2(TIMx, ticks); LL_TIM_OC_SetCompareCH3(TIMx, ticks); /* Wait until next update */ while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == RESET ) {} /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs(TIMx); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { /* Enable signals activation */ LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } return; } /* * @brief Enables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_1_SwitchOnPWM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = TIM1; pHandle->_Super.TurnOnLowSidesAction = false; /* We forbid ADC usage for regular conversion on Systick*/ pHandle->ADCRegularLocked=true; /* Set all duty to 50% */ LL_TIM_OC_SetCompareCH1(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH2(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH3(TIMx, (uint32_t)(pHandle->Half_PWMPeriod >> 1)); LL_TIM_OC_SetCompareCH4(TIMx, (uint32_t)(pHandle->Half_PWMPeriod - 5u)); /* Wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == RESET ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE; LL_TIM_EnableAllOutputs(TIMx); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { if ( LL_TIM_CC_IsEnabledChannel(TIMx, TIMxCCER_MASK_CH123) != 0u ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* Configuration of DMA and ADC to next conversions */ /* It's possible write the CHSELR resgister because the ADC conversion is stopped by the R3_1_SwitchOffPWM function */ LL_ADC_SetSamplingTimeCommonChannels ( ADC1, pHandle->pParams_str->b_ISamplingTime ); /* Setting of the DMA Buffer Size.*/ /* NOTE. This register (CNDTRx) must not be written when the DMAy Channel x is ENABLED */ LL_DMA_DisableChannel( DMA1, LL_DMA_CHANNEL_1 ); /* Write the Buffer size on CNDTR register */ LL_DMA_SetDataLength( DMA1, LL_DMA_CHANNEL_1, 2u ); /* DMA Enabling */ LL_DMA_EnableChannel( DMA1, LL_DMA_CHANNEL_1 ); /* Clear EOC */ LL_ADC_ClearFlag_EOC( ADC1 ); /* Enable ADC DMA request*/ LL_ADC_REG_SetDMATransfer( ADC1, LL_ADC_REG_DMA_TRANSFER_LIMITED ); /* Clear Pending Interrupt Bits */ LL_DMA_ClearFlag_HT1( DMA1 ); // TBC: for TC1, GL1 (not cleared ...) /* DMA Interrupt Event configuration */ LL_DMA_EnableIT_TC( DMA1, LL_DMA_CHANNEL_1 ); /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Enable Update IRQ */ LL_TIM_EnableIT_UPDATE( TIMx ); return; } /* * @brief Contains the TIMx Update event interrupt. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void R3_1_SwitchOffPWM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_R3_1_Handle_t * pHandle = ( PWMC_R3_1_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = TIM1; /* Enable Update IRQ */ LL_TIM_DisableIT_UPDATE( TIMx ); pHandle->_Super.TurnOnLowSidesAction = false; /* Main PWM Output Disable */ LL_TIM_DisableAllOutputs(TIMx); if ( pHandle->_Super.BrakeActionLock == true ) { } else { if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* Disabling of DMA Interrupt Event configured */ LL_DMA_DisableIT_TC( DMA1, LL_DMA_CHANNEL_1 ); LL_ADC_REG_StopConversion( ADC1 ); /* Disable ADC DMA request*/ ADC1->CFGR1 &= ~ADC_CFGR1_DMAEN; /* Clear Transmission Complete Flag of DMA1 Channel1 */ LL_DMA_ClearFlag_TC1( DMA1 ); /* Clear EOC */ LL_ADC_ClearFlag_EOC( ADC1 ); /* The ADC is not triggered anymore by the PWM timer */ LL_ADC_REG_SetTriggerSource (ADC1, LL_ADC_REG_TRIG_SOFTWARE); /* We allow ADC usage for regular conversion on Systick*/ pHandle->ADCRegularLocked=false; /* Wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == RESET ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); return; } /* * @brief Contains the TIMx Update event interrupt. * * @param pHandle: Handler of the current instance of the PWM component. */ void * R3_1_TIMx_UP_IRQHandler( PWMC_R3_1_Handle_t * pHandle ) { /* Set the trigger polarity as computed inside SetADCSampPointSectX*/ LL_ADC_REG_SetTriggerEdge (ADC1, pHandle->ADCTriggerEdge); /* set ADC trigger source */ LL_ADC_REG_SetTriggerSource(ADC1, LL_ADC_REG_TRIG_EXT_TIM1_TRGO); /* Set scan direction according to the sector */ LL_ADC_REG_SetSequencerScanDirection(ADC1, pHandle->pParams_str->ADCScandir[pHandle->_Super.Sector]<<ADC_CFGR1_SCANDIR_Pos); /* Configure the ADC scheduler as selected inside SetADCSampPointSectX*/ ADC1->CHSELR = pHandle->pParams_str->ADCConfig[pHandle->_Super.Sector]; /* ReConfigure sampling time, as deconfigured by reg_conv_manager */ LL_ADC_SetSamplingTimeCommonChannels ( ADC1, pHandle->pParams_str->b_ISamplingTime ); /* disable ADC source trigger */ LL_TIM_SetTriggerOutput(TIM1, LL_TIM_TRGO_OC4REF); /* ADC needs to be restarted because DMA is configured as limited */ LL_ADC_REG_StartConversion( ADC1 ); /* Reset the ADC trigger edge for next conversion */ pHandle->ADCTriggerEdge = LL_ADC_REG_TRIG_EXT_RISING; return &pHandle->_Super.Motor; } /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
40,168
C
30.090557
143
0.605183
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/F0xx/Inc/r3_f0xx_pwm_curr_fdbk.h
/** ****************************************************************************** * @file r3_f0xx_pwm_curr_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * R3_f0XX_pwm_curr_fdbk component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup R3_F0XX_pwm_curr_fdbk */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __R3_F0XX_PWMNCURRFDBK_H #define __R3_F0XX_PWMNCURRFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "pwm_curr_fdbk.h" /** * @addtogroup MCSDK * @{ */ /** * @addtogroup pwm_curr_fdbk * @{ */ /** * @addtogroup R3_1_pwm_curr_fdbk * @{ */ /* Exported constants --------------------------------------------------------*/ /* Exported types ------------------------------------------------------------*/ /* * @brief R3_F0XX parameters definition */ typedef struct { TIM_TypeDef * TIMx; /* Timer used for PWM generation. */ uint32_t ADCConfig[6]; /* Stores ADC sequence for the 6 sectors. */ volatile uint16_t *ADCDataReg1[6]; /* Stores ADC read value's address for the 6 sectors. */ volatile uint16_t *ADCDataReg2[6]; /* Stores ADC read value's address for the 6 sectors. */ uint16_t hDeadTime; /* Dead time in number of TIM clock cycles. If CHxN are enabled, it must contain the dead time to be generated by the microcontroller, otherwise it expresses the maximum dead time generated by driving network. */ uint16_t hTafter; /* Sum of dead time plus max value between rise time and noise time express in number of TIM clocks.*/ uint16_t hTbefore; /* Sampling time express in number of TIM clocks.*/ uint16_t Tsampling; /* Sampling time express in number of TIM clocks.*/ uint16_t Tcase2; /* Sampling time express in number of TIM clocks.*/ uint16_t Tcase3; /* Sampling time express in number of TIM clocks.*/ uint8_t b_ISamplingTime; /*!< Sampling time used to convert hI[a|b|c]Channel. It must be equal to ADC_SampleTime_xCycles5 x= 1, 7, ... Specific to F0XX. */ uint8_t RepetitionCounter; /* Expresses the number of PWM periods to be elapsed before compare registers are updated again. In particular: RepetitionCounter= (2* #PWM periods)-1*/ uint8_t ADCScandir[6]; /* Stores ADC scan direction for the 6 sectors. */ } R3_1_Params_t; /* * Handle structure of the r1_f0xx_pwm_curr_fdbk Component */ typedef struct { PWMC_Handle_t _Super; /* Offset of current sensing network. */ uint32_t PhaseAOffset; /* Offset of Phase A current sensing network. */ uint32_t PhaseBOffset; /* Offset of Phase B current sensing network. */ uint32_t PhaseCOffset; /* Offset of Phase C current sensing network. */ volatile uint32_t ADCTriggerEdge; /* External ADC trigger edge. */ uint16_t Half_PWMPeriod; /* Half PWM Period in timer clock counts. */ volatile uint16_t ADC1_DMA_converted[2]; /*!< Buffer used for DMA data transfer after the ADC conversion. */ volatile uint8_t PolarizationCounter; /* Number of conversions performed during the calibration phase. */ uint8_t CalibSector; /*!< Sector selected during calibration phase. Replaced by PolarizationSector in F30X.*/ bool ADCRegularLocked; /* This flag is set when regular conversions are locked. */ R3_1_Params_t const * pParams_str; } PWMC_R3_1_Handle_t; /* Exported functions ------------------------------------------------------- */ /* * Initializes TIM1, ADC1, GPIO, DMA1 and NVIC for three shunt current * reading configuration using STM32F0x. */ void R3_1_Init( PWMC_R3_1_Handle_t * pHandle ); /* * Stores into the handler the voltage present on the * current feedback analog channel when no current is flowing into the * motor. */ void R3_1_CurrentReadingCalibration( PWMC_Handle_t * pHdl ); /* * Computes and returns latest converted motor phase currents. */ void R3_1_GetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ); /* * Computes and returns latest converted motor phase currents. */ void R3_1_GetPhaseCurrents_OVM( PWMC_Handle_t * pHdl, ab_t * Iab ); /* * Configures the ADC for the current sampling related to sector X. */ uint16_t R3_1_SetADCSampPointSectX(PWMC_Handle_t * pHdl ); /* * Configures the ADC for the current sampling. */ uint16_t R3_1_SetADCSampPointSectX_OVM( PWMC_Handle_t * pHdl ); /* * Configures the ADC for the current sampling during calibration. */ uint16_t R3_1_SetADCSampPointCalibration( PWMC_Handle_t * pHdl ); /* * Turns on low sides switches. */ void R3_1_TurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks); /* * Enables the PWM outputs. */ void R3_1_SwitchOnPWM( PWMC_Handle_t * pHdl ); /* * Disables PWM generation on the proper Timer peripheral acting on * MOE bit and reset the TIM status. */ void R3_1_SwitchOffPWM( PWMC_Handle_t * pHdl ); /* * Contains the TIMx Update event interrupt. */ void * R3_1_TIMx_UP_IRQHandler( PWMC_R3_1_Handle_t * pHandle ); /* * Contains the Break event interrupt. */ void * F0XX_BRK_IRQHandler( PWMC_R3_1_Handle_t * pHdl ); /* * Sets the calibrated offset. */ void R3_1_SetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /* * Reads the calibrated offsets. */ void R3_1_GetOffsetCalib(PWMC_Handle_t *pHdl, PolarizationOffsets_t *offsets); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*__R3_F0XX_PWMNCURRFDBK_H*/ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
7,184
C
33.052133
120
0.544404
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/F0xx/Inc/f0xx_bemf_ADC_OS_fdbk.h
/** ****************************************************************************** * @file f0xx_bemf_ADC_OS_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * multiple Sensorless Bemf acquisition with ADC component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup SpeednPosFdbk_Bemf */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef BEMFADCFDBK_H #define BEMFADCFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "speed_pos_fdbk.h" #include "speed_ctrl.h" #include "pwm_common_sixstep.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup SpeednPosFdbk * @{ */ /** @addtogroup SpeednPosFdbk_Bemf * @{ */ #define SPEED_BUFFER_LENGTH ((uint8_t) 18) /* Length of buffer used to store the timer period measurements */ /* * @brief Bemf_ADC parameters definition */ typedef struct { TIM_TypeDef * LfTim; /* Contains the pointer to the LF timer used for speed measurement. */ uint32_t LfTimerChannel; /* Channel of the LF timer used for speed measurement */ ADC_TypeDef * pAdc[3]; /* Pointer to the ADC */ uint32_t AdcChannel[3]; /* Array of ADC channels used for BEMF sensing */ bool gpio_divider_available; /* Availability of the GPIO port enabling the bemf resistor divider */ GPIO_TypeDef * bemf_divider_port; /* GPIO port enabling the bemf resistor divider */ uint16_t bemf_divider_pin; /* GPIO pin enabling the bemf resistor divider */ uint32_t TIM_ADC_Trigger_Channel; TIM_TypeDef * TIM_Trigger; } Bemf_ADC_Params_t; /* * @brief This structure is used to handle the thresholds for bemf zero crossing detection * */ typedef struct { uint16_t AdcThresholdDown; /* BEMF voltage threshold for zero crossing detection when BEMF is decreasing */ uint16_t AdcThresholdUp; /* BEMF voltage threshold for zero crossing detection when BEMF is increasing */ uint16_t SamplingPoint; /* Pulse value of the timer channel used to trig the ADC when sensing occurs during PWM OFF time */ } Bemf_Sensing_Params; /* * @brief This structure is used to handle the demagnetization time before starting bemf acquisition * */ typedef struct { uint16_t DemagMinimumSpeedUnit; /* Speed threshold for minimum demagnetization time */ uint16_t RevUpDemagSpeedConv; /* Convertion factor between speed and demagnetization time */ uint16_t RunDemagSpeedConv; /* Open loop convertion factor between speed and demagnetization time during */ uint16_t DemagMinimumThreshold; /* Minimum demagnetization time */ } Bemf_Demag_Params; /* * @brief This structure is used to handle the data of an instance of the B-emf Feedback component * */ typedef struct { SpeednPosFdbk_Handle_t _Super; uint16_t BemfLastValues[3]; /* Bemf measurements of phase */ uint8_t ZcEvents; /* Number of bemf zero crossing events */ Bemf_Sensing_Params Pwm_ON; /* Parameters for zero crossing detection during ON time */ Bemf_Sensing_Params Pwm_OFF; /* Parameters for zero crossing detection during OFF time */ Bemf_Sensing_Params *pSensing_Params; uint16_t SamplingGuard; bool IsOnSensingEnabled; /* Value where 0 means BEMF is sensed during PWM OFF time and 1 or greater means BEMF is sensed during PWM ON time */ uint16_t OnSensingEnThres; /* Pulse value of HF timer above which the PWM ON sensing is enabled */ uint16_t OnSensingDisThres; /* Pulse value of HF timer below which the PWM ON sensing is disabled */ uint16_t Zc2CommDelay; /* Zero Crossing detection to commutation delay in 15/128 degrees */ Bemf_ADC_Params_t const *pParams_str; uint16_t SpeedSamplingFreqHz; /* Frequency (Hz) at which motor speed is to be computed. It must be equal to the frequency at which function SPD_CalcAvrgMecSpeedUnit is called.*/ uint8_t SpeedBufferSize; /* Size of the buffer used to calculate the average speed. It must be less than 18.*/ uint32_t TIMClockFreq; bool ADCRegularLocked; /* This flag is set when ADC is locked for bemf acquisition */ uint16_t ADC1_DMA_converted[5]; /* Buffer used for DMA data transfer after the ADC conversion */ uint16_t TIM1_pulses[5]; /* Buffer used for DMA data transfer after the ADC conversion */ int32_t ElPeriodSum; /* Period accumulator used to speed up the average speed computation*/ int16_t PrevRotorFreq; /* Used to store the last valid rotor electrical speed in dpp used when MAX_PSEUDO_SPEED is detected */ int8_t Direction; /* Instantaneous direction of rotor between two captures*/ int16_t AvrElSpeedDpp; /* Averaged rotor electrical speed express in s16degree per current control period.*/ int16_t VirtualElSpeedDpp; /* Averaged rotor electrical speed express in s16degree per current control period.*/ uint16_t MinStartUpValidSpeed; /* Absolute value of minimum mechanical speed required to validate the start-up. Expressed in the unit defined by #SPEED_UNIT. */ uint8_t StartUpConsistThreshold; /* Number of consecutive tests on speed consistency to be passed before validating the start-up */ uint8_t OverSamplingRate; bool IsSpeedReliable; /* Latest private speed reliability information, updated by SPD_CalcAvrgMecSpeedUnit, it is true if the speed measurement variance is lower then threshold corresponding to hVariancePercentage */ bool IsAlgorithmConverged; /* Boolean variable containing observer convergence information */ bool IsLoopClosed; /* Boolean variable containing speed loop status*/ bool ZcDetected; /* This flag is set when zero crossing is detected */ bool StepUpdate; /* This flag is set when step needs to be updated */ DrivingMode_t DriveMode; volatile uint8_t BufferFilled; /* Indicates the number of speed measuremt present in the buffer from the start. It will be max bSpeedBufferSize and it is used to validate the start of speed averaging. If bBufferFilled is below bSpeedBufferSize the instantaneous measured speed is returned as average speed.*/ int32_t SpeedBufferDpp[SPEED_BUFFER_LENGTH];/* Holding the last period captures */ uint32_t LowFreqTimerPsc; /* Prescaler value of the low frequency timer */ uint16_t SpeedFIFOIdx;/* Pointer of next element to be stored in the speed sensor buffer*/ int16_t DeltaAngle; /* Delta angle at the Hall sensor signal edge between current electrical rotor angle of synchronism. It is in s16degrees.*/ int16_t MeasuredElAngle; /* Electrical angle measured at each bemf zero crossing. It is considered the best measurement of electrical rotor angle.*/ int16_t CompSpeed; /* Speed compensation factor used to syncronize the current electrical angle with the target electrical angle. */ uint16_t SatSpeed; /* Returned value if the measured speed is above the maximum realistic.*/ uint32_t PseudoPeriodConv;/* Conversion factor between time interval Delta T between bemf zero crossing points, express in timer counts, and electrical rotor speed express in dpp. Ex. Rotor speed (dpp) = wPseudoFreqConv / Delta T It will be ((CKTIM / 6) / (SAMPLING_FREQ)) * 65536.*/ uint32_t MaxPeriod; /* Time delay between two bemf zero crossing points when the speed of the rotor is the minimum realistic in the application: this allows to discriminate too low freq for instance. This period shoud be expressed in timer counts and it will be: wMaxPeriod = ((10 * CKTIM) / 6) / MinElFreq(0.1Hz).*/ uint32_t MinPeriod; /* Time delay between two bemf zero crossing points when the speed of the rotor is the maximum realistic in the application: this allows discriminating glitches for instance. This period shoud be expressed in timer counts and it will be: wSpeedOverflow = ((10 * CKTIM) / 6) / MaxElFreq(0.1Hz).*/ uint16_t BemfTimeout; /* Max delay between two zero crossing signals to assert zero speed express in milliseconds.*/ uint16_t OvfFreq; /* Frequency of timer overflow (from 0 to 0x10000) it will be: hOvfFreq = CKTIM /65536.*/ uint16_t PWMNbrPSamplingFreq; /* Number of current control periods inside each speed control periods it will be: (hMeasurementFrequency / hSpeedSamplingFreqHz) - 1.*/ uint8_t PWMFreqScaling; /* Scaling factor to allow to store a PWMFrequency greater than 16 bits */ uint32_t Counter_Period; /* Low frequency timer period that allows speed calculation */ uint32_t ZC_Counter_Up; /* Low frequency timer counter value at zero crossing with increasing bemf */ uint32_t ZC_Counter_Down; /* Low frequency timer counter value at zero crossing with increasing bemf */ uint32_t ZC_Counter_Last; /* Last low frequency timer counter value at zero crossing */ uint32_t ZC_Counter_On_Last; /* Last low frequency timer counter value at zero crossing sensed with pwm on*/ uint32_t Last_Zc2Comm_Delay; /* Last delay between zero crossing and step change */ uint16_t DemagCounter; /* Demagnetization counter */ uint16_t DemagCounterThreshold; /* PWM cycles dedicated to windings demagnetization */ Bemf_Demag_Params DemagParams; /* Demagnetization parameters */ } Bemf_ADC_Handle_t; /* Exported functions --------------------------------------------------------*/ /* Initializes all the object variables. */ void BADC_Init( Bemf_ADC_Handle_t *pHandle ); /* Resets the ADC status and empties arrays. */ void BADC_Clear( Bemf_ADC_Handle_t *pHandle ); /* Gets ADC value and check for zero crossing detection.*/ bool BADC_IsZcDetected( Bemf_ADC_Handle_t *pHandle, PWMC_Handle_t *pHandlePWMC); /* Sets the trigger point of the ADC */ void BADC_SetSamplingPoint(Bemf_ADC_Handle_t *pHandle, PWMC_Handle_t *pHandlePWMC, SpeednTorqCtrl_Handle_t *pHandleSTC ); /* Computes the rotor average mechanical speed in the unit defined by #SPEED_UNIT and returns it in pMecSpeedUnit. */ bool BADC_CalcAvrgMecSpeedUnit( Bemf_ADC_Handle_t * pHandle, int16_t * pMecSpeedUnit ); /* Forces the rotation direction. */ void BADC_SetDirection( Bemf_ADC_Handle_t * pHandle, uint8_t direction ); /* Checks whether the state observer algorithm converged.*/ bool BADC_IsObserverConverged( Bemf_ADC_Handle_t * pHandle ); /* Starts the bemf acquisition.*/ void BADC_Start(Bemf_ADC_Handle_t *pHandle, uint8_t step); /* Stops the bemf acquisition.*/ void BADC_Stop(Bemf_ADC_Handle_t *pHandle); /* Selects the phase for the bemf acquisition.*/ void BADC_SelectAdcChannel(Bemf_ADC_Handle_t * pHandle, uint8_t Phase); /* Updates the estimated electrical angle.*/ int16_t BADC_CalcElAngle(Bemf_ADC_Handle_t * pHandle); /* Configures the sensorless parameters for the following step. */ void BADC_StepChangeEvent(Bemf_ADC_Handle_t * pHandle, int16_t hElSpeedDpp, PWMC_Handle_t *pHandlePWMC); /* Computes the demagnetization time during revup procedure. */ void BADC_CalcRevUpDemagTime(Bemf_ADC_Handle_t *pHandle); /* Computes the demagnetization time in closed loop operation.*/ void BADC_CalcRunDemagTime(Bemf_ADC_Handle_t *pHandle); /* Sets the flag when switch over phase ends.*/ void BADC_SetLoopClosed(Bemf_ADC_Handle_t *pHandle); /* Returns last converted Back-emf value.*/ uint16_t BADC_GetLastBemfValue(Bemf_ADC_Handle_t *pHandle, uint8_t phase); /* Returns the zero crossing detection flag. */ bool BADC_GetBemfZcrFlag(Bemf_ADC_Handle_t *pHandle); /* Enables low frequecy timer interrupt */ void BADC_SpeedMeasureOn(Bemf_ADC_Handle_t *pHandle); /* Disables low frequecy timer interrupt */ void BADC_SpeedMeasureOff(Bemf_ADC_Handle_t *pHandle); /* Clears StepUpdate flag */ bool BADC_ClearStepUpdate(Bemf_ADC_Handle_t *pHandle); /* Sets the parameters for bemf sensing during pwm off-time */ void BADC_SetBemfSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfAdcConfig, uint16_t *Zc2CommDelay, Bemf_Demag_Params *bemfAdcDemagConfig); /* Sets the parameters for bemf sensing during pwm on-time */ void BADC_SetBemfOnTimeSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfOnAdcConfig, uint16_t *OnSensingEnThres, uint16_t *OnSensingDisThres); /* Gets the parameters for bemf sensing during pwm off-time */ void BADC_GetBemfSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfAdcConfig, uint16_t *Zc2CommDelay, Bemf_Demag_Params *bemfAdcDemagConfig); /* Gets the parameters for bemf sensing during pwm on-time */ void BADC_GetBemfOnTimeSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfOnAdcConfig, uint16_t *OnSensingEnThres, uint16_t *OnSensingDisThres); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* BEMFADCFDBK_H */ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
15,524
C
50.237624
150
0.617302
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/F0xx/Inc/f0xx_bemf_ADC_fdbk.h
/** ****************************************************************************** * @file f0xx_bemf_ADC_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * Sensorless Bemf acquisition with ADC component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup SpeednPosFdbk_Bemf */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef BEMFADCFDBK_H #define BEMFADCFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "speed_pos_fdbk.h" #include "speed_ctrl.h" #include "pwm_common_sixstep.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup SpeednPosFdbk * @{ */ /** @addtogroup SpeednPosFdbk_Bemf * @{ */ #define SPEED_BUFFER_LENGTH ((uint8_t) 18) /* Length of buffer used to store the timer period measurements */ /* * @brief Bemf_ADC parameters definition */ typedef struct { TIM_TypeDef * LfTim; /* Contains the pointer to the LF timer used for speed measurement. */ uint32_t LfTimerChannel; /* Channel of the LF timer used for speed measurement */ ADC_TypeDef * pAdc[3]; /* Pointer to the ADC */ uint32_t AdcChannel[3]; /* Array of ADC channels used for BEMF sensing */ bool gpio_divider_available; /* Availability of the GPIO port enabling the bemf resistor divider */ GPIO_TypeDef * bemf_divider_port; /* GPIO port enabling the bemf resistor divider */ uint16_t bemf_divider_pin; /* GPIO pin enabling the bemf resistor divider */ } Bemf_ADC_Params_t; /* * @brief This structure is used to handle the thresholds for bemf zero crossing detection * */ typedef struct { uint16_t AdcThresholdDown; /* BEMF voltage threshold for zero crossing detection when BEMF is decreasing */ uint16_t AdcThresholdUp; /* BEMF voltage threshold for zero crossing detection when BEMF is increasing */ uint16_t SamplingPoint; /* Pulse value of the timer channel used to trig the ADC when sensing occurs during PWM OFF time */ } Bemf_Sensing_Params; /* * @brief This structure is used to handle the demagnetization time before starting bemf acquisition * */ typedef struct { uint16_t DemagMinimumSpeedUnit; /* Speed threshold for minimum demagnetization time */ uint16_t RevUpDemagSpeedConv; /* Convertion factor between speed and demagnetization time */ uint16_t RunDemagSpeedConv; /* Open loop convertion factor between speed and demagnetization time during */ uint16_t DemagMinimumThreshold; /* Minimum demagnetization time */ } Bemf_Demag_Params; /* * @brief This structure is used to handle the data of an instance of the B-emf Feedback component * */ typedef struct { SpeednPosFdbk_Handle_t _Super; uint16_t BemfLastValues[3]; /* Bemf measurements of phase */ uint8_t ZcEvents; /* Number of bemf zero crossing events */ Bemf_Sensing_Params Pwm_ON; /* Parameters for zero crossing detection during ON time */ Bemf_Sensing_Params Pwm_OFF; /* Parameters for zero crossing detection during OFF time */ Bemf_Sensing_Params *pSensing_Params; uint16_t SamplingGuard; bool IsOnSensingEnabled; /* Value where 0 means BEMF is sensed during PWM OFF time and 1 or greater means BEMF is sensed during PWM ON time */ uint16_t OnSensingEnThres; /* Pulse value of HF timer above which the PWM ON sensing is enabled */ uint16_t OnSensingDisThres; /* Pulse value of HF timer below which the PWM ON sensing is disabled */ uint16_t Zc2CommDelay; /* Zero Crossing detection to commutation delay in 15/128 degrees */ Bemf_ADC_Params_t const *pParams_str; uint16_t SpeedSamplingFreqHz; /* Frequency (Hz) at which motor speed is to be computed. It must be equal to the frequency at which function SPD_CalcAvrgMecSpeedUnit is called.*/ uint8_t SpeedBufferSize; /* Size of the buffer used to calculate the average speed. It must be less than 18.*/ uint32_t TIMClockFreq; bool ADCRegularLocked; /* This flag is set when ADC is locked for bemf acquisition */ uint16_t ADC1_DMA_converted[1]; /* Buffer used for DMA data transfer after the ADC conversion */ int32_t ElPeriodSum; /* Period accumulator used to speed up the average speed computation*/ int16_t PrevRotorFreq; /* Used to store the last valid rotor electrical speed in dpp used when MAX_PSEUDO_SPEED is detected */ int8_t Direction; /* Instantaneous direction of rotor between two captures*/ int16_t AvrElSpeedDpp; /* Averaged rotor electrical speed express in s16degree per current control period.*/ int16_t VirtualElSpeedDpp; /* Averaged rotor electrical speed express in s16degree per current control period.*/ uint16_t MinStartUpValidSpeed; /* Absolute value of minimum mechanical speed required to validate the start-up. Expressed in the unit defined by #SPEED_UNIT. */ uint8_t StartUpConsistThreshold; /* Number of consecutive tests on speed consistency to be passed before validating the start-up */ bool IsSpeedReliable; /* Latest private speed reliability information, updated by SPD_CalcAvrgMecSpeedUnit, it is true if the speed measurement variance is lower then threshold corresponding to hVariancePercentage */ bool IsAlgorithmConverged; /* Boolean variable containing observer convergence information */ bool IsLoopClosed; /* Boolean variable containing speed loop status*/ bool ZcDetected; /* This flag is set when zero crossing is detected */ bool StepUpdate; /* This flag is set when step needs to be updated */ DrivingMode_t DriveMode; volatile uint8_t BufferFilled; /* Indicates the number of speed measuremt present in the buffer from the start. It will be max bSpeedBufferSize and it is used to validate the start of speed averaging. If bBufferFilled is below bSpeedBufferSize the instantaneous measured speed is returned as average speed.*/ int32_t SpeedBufferDpp[SPEED_BUFFER_LENGTH];/* Holding the last period captures */ uint32_t LowFreqTimerPsc; /* Prescaler value of the low frequency timer */ uint16_t SpeedFIFOIdx;/* Pointer of next element to be stored in the speed sensor buffer*/ int16_t DeltaAngle; /* Delta angle at the Hall sensor signal edge between current electrical rotor angle of synchronism. It is in s16degrees.*/ int16_t MeasuredElAngle; /* Electrical angle measured at each bemf zero crossing. It is considered the best measurement of electrical rotor angle.*/ int16_t CompSpeed; /* Speed compensation factor used to syncronize the current electrical angle with the target electrical angle. */ uint16_t SatSpeed; /* Returned value if the measured speed is above the maximum realistic.*/ uint32_t PseudoPeriodConv;/* Conversion factor between time interval Delta T between bemf zero crossing points, express in timer counts, and electrical rotor speed express in dpp. Ex. Rotor speed (dpp) = wPseudoFreqConv / Delta T It will be ((CKTIM / 6) / (SAMPLING_FREQ)) * 65536.*/ uint32_t MaxPeriod; /* Time delay between two bemf zero crossing points when the speed of the rotor is the minimum realistic in the application: this allows to discriminate too low freq for instance. This period shoud be expressed in timer counts and it will be: wMaxPeriod = ((10 * CKTIM) / 6) / MinElFreq(0.1Hz).*/ uint32_t MinPeriod; /* Time delay between two bemf zero crossing points when the speed of the rotor is the maximum realistic in the application: this allows discriminating glitches for instance. This period shoud be expressed in timer counts and it will be: wSpeedOverflow = ((10 * CKTIM) / 6) / MaxElFreq(0.1Hz).*/ uint16_t BemfTimeout; /* Max delay between two zero crossing signals to assert zero speed express in milliseconds.*/ uint16_t OvfFreq; /* Frequency of timer overflow (from 0 to 0x10000) it will be: hOvfFreq = CKTIM /65536.*/ uint16_t PWMNbrPSamplingFreq; /* Number of current control periods inside each speed control periods it will be: (hMeasurementFrequency / hSpeedSamplingFreqHz) - 1.*/ uint8_t PWMFreqScaling; /* Scaling factor to allow to store a PWMFrequency greater than 16 bits */ uint32_t Counter_Period; /* Low frequency timer period that allows speed calculation */ uint32_t ZC_Counter_Up; /* Low frequency timer counter value at zero crossing with increasing bemf */ uint32_t ZC_Counter_Down; /* Low frequency timer counter value at zero crossing with increasing bemf */ uint32_t ZC_Counter_Last; /* Last low frequency timer counter value at zero crossing */ uint32_t Last_Zc2Comm_Delay; /* Last delay between zero crossing and step change */ uint16_t DemagCounter; /* Demagnetization counter */ uint16_t DemagCounterThreshold; /* PWM cycles dedicated to windings demagnetization */ Bemf_Demag_Params DemagParams; /* Demagnetization parameters */ } Bemf_ADC_Handle_t; /* Exported functions --------------------------------------------------------*/ /* Initializes all the object variables. */ void BADC_Init( Bemf_ADC_Handle_t *pHandle ); /* Resets the ADC status and empties arrays. */ void BADC_Clear( Bemf_ADC_Handle_t *pHandle ); /* Gets ADC value and check for zero crossing detection.*/ bool BADC_IsZcDetected( Bemf_ADC_Handle_t *pHandle, PWMC_Handle_t *pHandlePWMC); /* Sets the trigger point of the ADC */ void BADC_SetSamplingPoint(Bemf_ADC_Handle_t *pHandle, PWMC_Handle_t *pHandlePWMC, SpeednTorqCtrl_Handle_t *pHandleSTC ); /* Computes the rotor average mechanical speed in the unit defined by #SPEED_UNIT and returns it in pMecSpeedUnit. */ bool BADC_CalcAvrgMecSpeedUnit( Bemf_ADC_Handle_t * pHandle, int16_t * pMecSpeedUnit ); /* Forces the rotation direction. */ void BADC_SetDirection( Bemf_ADC_Handle_t * pHandle, uint8_t direction ); /* Checks whether the state observer algorithm converged.*/ bool BADC_IsObserverConverged( Bemf_ADC_Handle_t * pHandle ); /* Starts the bemf acquisition.*/ void BADC_Start(Bemf_ADC_Handle_t *pHandle, uint8_t step); /* Stops the bemf acquisition.*/ void BADC_Stop(Bemf_ADC_Handle_t *pHandle); /* Selects the phase for the bemf acquisition.*/ void BADC_SelectAdcChannel(Bemf_ADC_Handle_t * pHandle, uint8_t Phase); /* Updates the estimated electrical angle.*/ int16_t BADC_CalcElAngle(Bemf_ADC_Handle_t * pHandle); /* Configures the sensorless parameters for the following step. */ void BADC_StepChangeEvent(Bemf_ADC_Handle_t * pHandle, int16_t hElSpeedDpp, PWMC_Handle_t *pHandlePWMC); /* Computes the demagnetization time during revup procedure. */ void BADC_CalcRevUpDemagTime(Bemf_ADC_Handle_t *pHandle); /* Computes the demagnetization time in closed loop operation.*/ void BADC_CalcRunDemagTime(Bemf_ADC_Handle_t *pHandle); /* Sets the flag when switch over phase ends.*/ void BADC_SetLoopClosed(Bemf_ADC_Handle_t *pHandle); /* Returns last converted Back-emf value.*/ uint16_t BADC_GetLastBemfValue(Bemf_ADC_Handle_t *pHandle, uint8_t phase); /* Returns the zero crossing detection flag. */ bool BADC_GetBemfZcrFlag(Bemf_ADC_Handle_t *pHandle); /* Enables low frequecy timer interrupt */ void BADC_SpeedMeasureOn(Bemf_ADC_Handle_t *pHandle); /* Disables low frequecy timer interrupt */ void BADC_SpeedMeasureOff(Bemf_ADC_Handle_t *pHandle); /* Clears StepUpdate flag */ bool BADC_ClearStepUpdate(Bemf_ADC_Handle_t *pHandle); /* Sets the parameters for bemf sensing during pwm off-time */ void BADC_SetBemfSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfAdcConfig, uint16_t *Zc2CommDelay, Bemf_Demag_Params *bemfAdcDemagConfig); /* Sets the parameters for bemf sensing during pwm on-time */ void BADC_SetBemfOnTimeSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfOnAdcConfig, uint16_t *OnSensingEnThres, uint16_t *OnSensingDisThres); /* Gets the parameters for bemf sensing during pwm off-time */ void BADC_GetBemfSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfAdcConfig, uint16_t *Zc2CommDelay, Bemf_Demag_Params *bemfAdcDemagConfig); /* Gets the parameters for bemf sensing during pwm on-time */ void BADC_GetBemfOnTimeSensorlessParam(Bemf_ADC_Handle_t *pHandle, Bemf_Sensing_Params *BemfOnAdcConfig, uint16_t *OnSensingEnThres, uint16_t *OnSensingDisThres); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* BEMFADCFDBK_H */ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
15,215
C
50.060403
150
0.614722
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/H7xx/Src/r1_h7xx_pwm_curr_fdbk.c
/** ****************************************************************************** * @file r1_h7xx_pwm_curr_fdbk.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement current sensor * class to be stantiated when the single shunt current sensing * topology is used. * * It is specifically designed for STM32H7XX microcontrollers and * implements the successive sampling of motor current using only one ADC. * + initializes MCU peripheral for 1 shunt topology and H7 family * + performs PWM duty cycle computation and generation * + performs current sensing * ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup R1_H7XX_pwm_curr_fdbk */ /* Includes ------------------------------------------------------------------*/ #include "r1_f30x_pwm_curr_fdbk.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** * @defgroup R1_H7XX_pwm_curr_fdbk H7 R1 1 ADC PWM & Current Feedback * * @brief STM32H7, 1-Shunt, 1 ADC, PWM & Current Feedback implementation * * This component is used in applications based on an STM32H7 MCU * and using a single shunt resistor current sensing topology. * * @{ */ /* Constant values -----------------------------------------------------------*/ #define TIMxCCER_MASK_CH123 (TIM_CCER_CC1E|TIM_CCER_CC2E|TIM_CCER_CC3E|\ TIM_CCER_CC1NE|TIM_CCER_CC2NE|TIM_CCER_CC3NE) #define CC12_PRELOAD_ENABLE_MASK (TIM_CCMR1_OC1PE|TIM_CCMR1_OC2PE) #define CC3_PRELOAD_ENABLE_MASK TIM_CCMR2_OC3PE #define CC1_PRELOAD_DISABLE_MASK ~TIM_CCMR1_OC1PE #define CC2_PRELOAD_DISABLE_MASK ~TIM_CCMR1_OC2PE #define CC3_PRELOAD_DISABLE_MASK ~TIM_CCMR2_OC3PE #define TIMxCCR56_PRELOAD_DISABLE_MASK ~(TIM_CCMR3_OC5PE|TIM_CCMR3_OC6PE) #define TIMxCCR56_PRELOAD_ENABLE_MASK (TIM_CCMR3_OC5PE|TIM_CCMR3_OC6PE) #define NB_CONVERSIONS 16u /* boundary zone definition */ #define REGULAR ((uint8_t)0u) #define BOUNDARY_1 ((uint8_t)1u) /* Two small, one big */ #define BOUNDARY_2 ((uint8_t)2u) /* Two big, one small */ #define BOUNDARY_3 ((uint8_t)3u) /* Three equal */ #define INVERT_NONE 0u #define INVERT_A 1u #define INVERT_B 2u #define INVERT_C 3u #define SAMP_NO 0u #define SAMP_IA 1u #define SAMP_IB 2u #define SAMP_IC 3u #define SAMP_NIA 4u #define SAMP_NIB 5u #define SAMP_NIC 6u #define SAMP_OLDA 7u #define SAMP_OLDB 8u #define SAMP_OLDC 9u static const uint8_t REGULAR_SAMP_CUR1[6] = {SAMP_NIC, SAMP_NIC, SAMP_NIA, SAMP_NIA, SAMP_NIB, SAMP_NIB}; static const uint8_t REGULAR_SAMP_CUR2[6] = {SAMP_IA, SAMP_IB, SAMP_IB, SAMP_IC, SAMP_IC, SAMP_IA}; static const uint8_t BOUNDR1_SAMP_CUR2[6] = {SAMP_IB, SAMP_IB, SAMP_IC, SAMP_IC, SAMP_IA, SAMP_IA}; static const uint8_t BOUNDR2_SAMP_CUR1[6] = {SAMP_IA, SAMP_IB, SAMP_IB, SAMP_IC, SAMP_IC, SAMP_IA}; static const uint8_t BOUNDR2_SAMP_CUR2[6] = {SAMP_IC, SAMP_IA, SAMP_IA, SAMP_IB, SAMP_IB, SAMP_IC}; /* Private typedef -----------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ static void R1F30X_HFCurrentsCalibration( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ); static void R1F30X_SetAOReferenceVoltage( uint32_t DAC_Channel, uint16_t hDACVref ); static void R1F30X_1ShuntMotorVarsInit( PWMC_Handle_t * pHdl ); static void R1F30X_1ShuntMotorVarsRestart( PWMC_Handle_t * pHdl ); static void R1F30X_TIMxInit( TIM_TypeDef * TIMx, PWMC_R1_F3_Handle_t * pHdl ); /** * @brief It initializes TIMx, ADC, GPIO, DMA1 and NVIC for current reading * in ICS configuration using STM32H7x High Density * @param pHandle: handler of the current instance of the PWM component * */ void R1F30X_Init( PWMC_R1_F3_Handle_t * pHandle ) { OPAMP_TypeDef * OPAMPx = pHandle->pParams_str->OPAMP_Selection; COMP_TypeDef * COMP_OCPx = pHandle->pParams_str->CompOCPSelection; COMP_TypeDef * COMP_OVPx = pHandle->pParams_str->CompOVPSelection; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; R1F30X_1ShuntMotorVarsInit( &pHandle->_Super ); /* disable IT and flags in case of LL driver usage * workaround for unwanted interrupt enabling done by LL driver */ LL_ADC_DisableIT_EOC( ADCx ); LL_ADC_ClearFlag_EOC( ADCx ); LL_ADC_DisableIT_JEOC( ADCx ); LL_ADC_ClearFlag_JEOC( ADCx ); /* Enable TIM1 - TIM8 clock */ if ( TIMx == TIM1 ) { /* DMA Event related to TIM1 Channel 4 */ /* DMA1 Channel4 configuration ----------------------------------------------*/ LL_DMA_SetMemoryAddress( DMA1, LL_DMA_CHANNEL_4, ( uint32_t )pHandle->DmaBuff ); LL_DMA_SetPeriphAddress( DMA1, LL_DMA_CHANNEL_4, ( uint32_t ) & ( TIM1->CCR1 ) ); LL_DMA_SetDataLength( DMA1, LL_DMA_CHANNEL_4, 2 ); /* ensable DMA1 Channel4 */ LL_DMA_EnableChannel( DMA1, LL_DMA_CHANNEL_4 ); pHandle->DistortionDMAy_Chx = DMA1_Channel4; /* DMA Event related to TIM1 update */ /* DMA1 Channel5 configuration ----------------------------------------------*/ LL_DMA_SetMemoryAddress( DMA1, LL_DMA_CHANNEL_5, ( uint32_t ) & ( pHandle->PreloadDisableActing ) ); LL_DMA_SetPeriphAddress( DMA1, LL_DMA_CHANNEL_5, ( uint32_t )&TIM1->CCMR1 ); LL_DMA_SetDataLength( DMA1, LL_DMA_CHANNEL_5, 1 ); /* enable DMA1 Channel5 */ LL_DMA_EnableChannel( DMA1, LL_DMA_CHANNEL_5 ); pHandle->PreloadDMAy_Chx = DMA1_Channel5; } #if (defined(TIM8) && defined(DMA2)) else { /* DMA Event related to TIM8 Channel 4 */ /* DMA2 Channel2 configuration ----------------------------------------------*/ LL_DMA_SetMemoryAddress( DMA2, LL_DMA_CHANNEL_2, ( uint32_t )pHandle->DmaBuff ); LL_DMA_SetPeriphAddress( DMA2, LL_DMA_CHANNEL_2, ( uint32_t )&TIMx->CCR1 ); LL_DMA_SetDataLength( DMA2, LL_DMA_CHANNEL_2, 2 ); /* enable DMA2 Channel2 */ LL_DMA_EnableChannel( DMA2, LL_DMA_CHANNEL_2 ); pHandle->DistortionDMAy_Chx = DMA2_Channel2; /* DMA Event related to TIM8 update */ /* DMA2 Channel1 configuration ----------------------------------------------*/ LL_DMA_SetMemoryAddress( DMA2, LL_DMA_CHANNEL_1, ( uint32_t )&pHandle->PreloadDisableActing ); LL_DMA_SetPeriphAddress( DMA2, LL_DMA_CHANNEL_1, ( uint32_t )&TIMx->CCMR1 ); LL_DMA_SetDataLength( DMA2, LL_DMA_CHANNEL_1, 1 ); /* enable DMA2 Channel2 */ LL_DMA_EnableChannel( DMA2, LL_DMA_CHANNEL_1 ); pHandle->PreloadDMAy_Chx = DMA2_Channel1; } #endif R1F30X_TIMxInit( TIMx, pHandle ); if ( OPAMPx ) { /* enable OPAMP */ LL_OPAMP_Enable( OPAMPx ); LL_OPAMP_Lock( OPAMPx ); } /* Over current protection */ if ( COMP_OCPx ) { /* Inverting input*/ if ( pHandle->pParams_str->CompOCPInvInput_MODE != EXT_MODE ) { if ( LL_COMP_GetInputMinus( COMP_OCPx ) == LL_COMP_INPUT_MINUS_DAC1_CH1 ) { R1F30X_SetAOReferenceVoltage( LL_DAC_CHANNEL_1, ( uint16_t )( pHandle->pParams_str->DAC_OCP_Threshold ) ); } #if defined(DAC_CHANNEL2_SUPPORT) else if ( LL_COMP_GetInputMinus( COMP_OCPx ) == LL_COMP_INPUT_MINUS_DAC1_CH2 ) { R1F30X_SetAOReferenceVoltage( LL_DAC_CHANNEL_2, ( uint16_t )( pHandle->pParams_str->DAC_OCP_Threshold ) ); } #endif else {} } /* Wait to stabilize DAC voltage */ volatile uint16_t waittime = 0u; for ( waittime = 0u; waittime < 1000u; waittime++ ) {} /* enable comparator */ #if defined(COMP_CSR_COMPxHYST) LL_COMP_SetInputHysteresis( COMP_OCPx, LL_COMP_HYSTERESIS_LOW ); #endif LL_COMP_Enable( COMP_OCPx ); LL_COMP_Lock( COMP_OCPx ); } /* Over voltage protection */ if ( COMP_OVPx ) { /* Inverting input*/ if ( pHandle->pParams_str->CompOCPInvInput_MODE != EXT_MODE ) { if ( LL_COMP_GetInputMinus( COMP_OVPx ) == LL_COMP_INPUT_MINUS_DAC1_CH1 ) { R1F30X_SetAOReferenceVoltage( LL_DAC_CHANNEL_1, ( uint16_t )( pHandle->pParams_str->DAC_OVP_Threshold ) ); } #if defined(DAC_CHANNEL2_SUPPORT) else if ( LL_COMP_GetInputMinus( COMP_OVPx ) == LL_COMP_INPUT_MINUS_DAC1_CH2 ) { R1F30X_SetAOReferenceVoltage( LL_DAC_CHANNEL_2, ( uint16_t )( pHandle->pParams_str->DAC_OVP_Threshold ) ); } #endif else {} } /* Wait to stabilize DAC voltage */ volatile uint16_t waittime = 0u; for ( waittime = 0u; waittime < 1000u; waittime++ ) {} /* enable comparator */ #if defined(COMP_CSR_COMPxHYST) LL_COMP_SetInputHysteresis( COMP_OCPx, LL_COMP_HYSTERESIS_LOW ); #endif LL_COMP_Enable( COMP_OVPx ); LL_COMP_Lock( COMP_OVPx ); } if ( pHandle->pParams_str->TIMx == TIM1 ) { /* TIM1 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph( LL_DBGMCU_APB2_GRP1_TIM1_STOP ); } #if defined(TIM8) else { /* TIM8 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph( LL_DBGMCU_APB2_GRP1_TIM8_STOP ); } #endif LL_ADC_EnableInternalRegulator( ADCx ); volatile uint32_t wait_loop_index = ((LL_ADC_DELAY_INTERNAL_REGUL_STAB_US / 10UL) * (SystemCoreClock / (100000UL * 2UL))); while(wait_loop_index != 0UL) { wait_loop_index--; } LL_ADC_StartCalibration( ADCx, LL_ADC_SINGLE_ENDED ); while ( LL_ADC_IsCalibrationOnGoing( ADCx ) ) { } /* ADC registers configuration ---------------------------------*/ /* Enable ADC*/ LL_ADC_Enable( ADCx ); /* Flushing JSQR queue of context by setting JADSTP = 1 (JQM)=1 */ LL_ADC_INJ_StopConversion( ADCx ); if ( pHandle->pParams_str->TIMx == TIM1 ) { LL_ADC_INJ_ConfigQueueContext( ADCx, LL_ADC_INJ_TRIG_EXT_TIM1_TRGO2, LL_ADC_INJ_TRIG_EXT_RISING, LL_ADC_INJ_SEQ_SCAN_ENABLE_2RANKS, __LL_ADC_DECIMAL_NB_TO_CHANNEL(pHandle->pParams_str->IChannel), __LL_ADC_DECIMAL_NB_TO_CHANNEL(pHandle->pParams_str->IChannel), __LL_ADC_DECIMAL_NB_TO_CHANNEL(pHandle->pParams_str->IChannel), __LL_ADC_DECIMAL_NB_TO_CHANNEL(pHandle->pParams_str->IChannel)); } #if defined(TIM8) else { LL_ADC_INJ_ConfigQueueContext( ADCx, LL_ADC_INJ_TRIG_EXT_TIM8_TRGO2, LL_ADC_INJ_TRIG_EXT_RISING, LL_ADC_INJ_SEQ_SCAN_ENABLE_2RANKS, __LL_ADC_DECIMAL_NB_TO_CHANNEL(pHandle->pParams_str->IChannel), __LL_ADC_DECIMAL_NB_TO_CHANNEL(pHandle->pParams_str->IChannel), __LL_ADC_DECIMAL_NB_TO_CHANNEL(pHandle->pParams_str->IChannel), __LL_ADC_DECIMAL_NB_TO_CHANNEL(pHandle->pParams_str->IChannel)); } #endif /* store register value in the handle to be used later during SVPWM for re-init */ pHandle->ADC_JSQR = ADCx->JSQR; /* Flushing JSQR queue of context by setting JADSTP = 1 (JQM)=1 */ LL_ADC_INJ_StartConversion( ADCx ); LL_ADC_INJ_StopConversion( ADCx ); /* store register value in the handle to be used later during SVPWM for re-init */ LL_ADC_INJ_SetQueueMode( ADCx, LL_ADC_INJ_QUEUE_2CONTEXTS_END_EMPTY ); LL_ADC_INJ_SetSequencerDiscont( ADCx, LL_ADC_INJ_SEQ_DISCONT_1RANK ); /* Clear the flags */ pHandle->_Super.DTTest = 0u; } /** * @brief Initializes @p TIMx peripheral with @p pHdl handler for PWM generation. * */ void R1F30X_TIMxInit( TIM_TypeDef * TIMx, PWMC_R1_F3_Handle_t * pHandle ) { /* disable main TIM counter to ensure * a synchronous start by TIM2 trigger */ LL_TIM_DisableCounter( TIMx ); /* Enables the TIMx Preload on CC1 Register */ LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH1 ); /* Enables the TIMx Preload on CC2 Register */ LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH2 ); /* Enables the TIMx Preload on CC3 Register */ LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH3 ); /* Enables the TIMx Preload on CC4 Register */ LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH4 ); /* Enables the TIMx Preload on CC5 Register */ LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH5 ); /* Enables the TIMx Preload on CC6 Register */ LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH6 ); /* Always enable BKIN for safety feature */ LL_TIM_ClearFlag_BRK( TIMx ); LL_TIM_ClearFlag_BRK2( TIMx ); LL_TIM_EnableIT_BRK( TIMx ); /* Prepare timer for synchronization */ LL_TIM_GenerateEvent_UPDATE( TIMx ); if ( pHandle->pParams_str->FreqRatio == 2u ) { if ( pHandle->pParams_str->IsHigherFreqTim == HIGHER_FREQ ) { if ( pHandle->pParams_str->RepetitionCounter == 3u ) { /* Set TIMx repetition counter to 1 */ LL_TIM_SetRepetitionCounter( TIMx, 1 ); LL_TIM_GenerateEvent_UPDATE( TIMx ); /* Repetition counter will be set to 3 at next Update */ LL_TIM_SetRepetitionCounter( TIMx, 3 ); } } LL_TIM_SetCounter( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) - 1u ); } else /* bFreqRatio equal to 1 or 3 */ { if ( pHandle->_Super.Motor == M1 ) { if ( pHandle->pParams_str->RepetitionCounter == 3u ) { /* Set TIMx repetition counter to 1 */ LL_TIM_SetRepetitionCounter( TIMx, 1 ); LL_TIM_GenerateEvent_UPDATE( TIMx ); /* Repetition counter will be set to 3 at next Update */ LL_TIM_SetRepetitionCounter( TIMx, 3 ); } LL_TIM_SetCounter( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) - 1u ); } } /* Enable PWM channel */ LL_TIM_CC_EnableChannel( TIMx, TIMxCCER_MASK_CH123 ); pHandle->PreloadDisableCC1 = TIMx->CCMR1 & CC1_PRELOAD_DISABLE_MASK; pHandle->PreloadDisableCC2 = TIMx->CCMR1 & CC2_PRELOAD_DISABLE_MASK; pHandle->PreloadDisableCC3 = TIMx->CCMR2 & CC3_PRELOAD_DISABLE_MASK; } /** * @brief First initialization of the handler * @param pHdl: handler of the current instance of the PWM component * */ void R1F30X_1ShuntMotorVarsInit( PWMC_Handle_t * pHdl ) { PWMC_R1_F3_Handle_t * pHandle = ( PWMC_R1_F3_Handle_t * )pHdl; /* Init motor vars */ pHandle->Inverted_pwm_new = INVERT_NONE; pHandle->Flags &= ( ~STBD3 ); /*STBD3 cleared*/ pHandle->Flags &= ( ~DSTEN ); /*DSTEN cleared*/ pHandle->Half_PWMPeriod = ( ( pHandle->_Super.PWMperiod ) / 2u ); /* After reset, value of DMA buffers for distortion*/ pHandle->DmaBuff[0] = pHandle->Half_PWMPeriod + 1u; pHandle->DmaBuff[1] = pHandle->Half_PWMPeriod >> 1; /*dummy*/ /* Default value of sampling points */ pHandle->CntSmp1 = ( pHandle->Half_PWMPeriod >> 1 ) + ( pHandle->pParams_str->Tafter ); pHandle->CntSmp2 = pHandle->Half_PWMPeriod - 1u; } /** * @brief Re-initialization of of the handler after each motor start * @param pHdl: handler of the current instance of the PWM component * */ void R1F30X_1ShuntMotorVarsRestart( PWMC_Handle_t * pHdl ) { PWMC_R1_F3_Handle_t * pHandle = ( PWMC_R1_F3_Handle_t * )pHdl; /* Default value of sampling points */ pHandle->CntSmp1 = ( pHandle->Half_PWMPeriod >> 1 ) + ( pHandle->pParams_str->Tafter ); pHandle->CntSmp2 = pHandle->Half_PWMPeriod - 1u; pHandle->Inverted_pwm_new = INVERT_NONE; pHandle->Flags &= ( ~STBD3 ); /*STBD3 cleared*/ /* Set the default previous value of Phase A,B,C current */ pHandle->CurrAOld = 0; pHandle->CurrBOld = 0; pHandle->DmaBuff[0] = pHandle->Half_PWMPeriod + 1u; pHandle->DmaBuff[1] = pHandle->Half_PWMPeriod >> 1; /*dummy*/ pHandle->_Super.BrakeActionLock = false; } /** * @brief It stores into pHandle the offset voltage read onchannels when no * current is flowing into the motor * @param pHdl: handler of the current instance of the PWM component * */ __weak void R1F30X_CurrentReadingCalibration( PWMC_Handle_t * pHdl ) { uint16_t hCalibrationPeriodCounter; uint16_t hMaxPeriodsNumber; PWMC_R1_F3_Handle_t * pHandle = ( PWMC_R1_F3_Handle_t * )pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; pHandle->PhaseOffset = 0u; pHandle->Index = 0u; /* Disable distortion*/ pHandle->Flags &= ( ~DSTEN ); /*DSTEN cleared*/ /* It forces inactive level on TIMx CHy and CHyN */ TIMx->CCER &= ( ~TIMxCCER_MASK_CH123 ); /* Offset calibration */ /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R1F30X_HFCurrentsCalibration; R1F30X_SwitchOnPWM( &pHandle->_Super ); /* Wait for NB_CONVERSIONS to be executed */ hMaxPeriodsNumber = ( NB_CONVERSIONS + 1u ) * ( ( uint16_t )( pHandle->pParams_str->RepetitionCounter ) + 1u ); LL_TIM_ClearFlag_CC1( TIMx ); hCalibrationPeriodCounter = 0u; while ( pHandle->Index < NB_CONVERSIONS ) { if ( LL_TIM_IsActiveFlag_CC1( TIMx ) ) { LL_TIM_ClearFlag_CC1( TIMx ); hCalibrationPeriodCounter++; if ( hCalibrationPeriodCounter >= hMaxPeriodsNumber ) { if ( pHandle->Index < NB_CONVERSIONS ) { pHandle->_Super.SWerror = 1u; break; } } } } R1F30X_SwitchOffPWM( &pHandle->_Super ); pHandle->PhaseOffset >>= 4; /* Change back function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R1F30X_GetPhaseCurrents; /* It re-enable drive of TIMx CHy and CHyN by TIMx CHyRef*/ TIMx->CCER |= TIMxCCER_MASK_CH123; /* Enable distortion*/ pHandle->Flags |= DSTEN; /*DSTEN set*/ R1F30X_1ShuntMotorVarsRestart( &pHandle->_Super ); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__( ( section ( ".ccmram" ) ) ) #endif #endif /** * @brief It computes and return latest converted motor phase currents motor * @param pHdl: handler of the current instance of the PWM component * @retval Ia and Ib current in Curr_Components format */ __weak void R1F30X_GetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { int32_t wAux; int16_t hCurrA = 0; int16_t hCurrB = 0; int16_t hCurrC = 0; uint8_t bCurrASamp = 0u; uint8_t bCurrBSamp = 0u; uint8_t bCurrCSamp = 0u; PWMC_R1_F3_Handle_t * pHandle = ( PWMC_R1_F3_Handle_t * )pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; TIMx->CCMR1 |= CC12_PRELOAD_ENABLE_MASK; TIMx->CCMR2 |= CC3_PRELOAD_ENABLE_MASK; /* Reset the update flag to indicate the start of FOC algorithm*/ pHandle->UpdateFlagBuffer = false; /* First sampling point */ wAux = ( int32_t )( ADCx->JDR1 ); wAux -= ( int32_t )( pHandle->PhaseOffset ); /* Check saturation */ if ( wAux > -INT16_MAX ) { if ( wAux < INT16_MAX ) { } else { wAux = INT16_MAX; } } else { wAux = -INT16_MAX; } switch ( pHandle->sampCur1 ) { case SAMP_IA: hCurrA = ( int16_t )( wAux ); bCurrASamp = 1u; break; case SAMP_IB: hCurrB = ( int16_t )( wAux ); bCurrBSamp = 1u; break; case SAMP_IC: hCurrC = ( int16_t )( wAux ); bCurrCSamp = 1u; break; case SAMP_NIA: wAux = -wAux; hCurrA = ( int16_t )( wAux ); bCurrASamp = 1u; break; case SAMP_NIB: wAux = -wAux; hCurrB = ( int16_t )( wAux ); bCurrBSamp = 1u; break; case SAMP_NIC: wAux = -wAux; hCurrC = ( int16_t )( wAux ); bCurrCSamp = 1u; break; case SAMP_OLDA: hCurrA = pHandle->CurrAOld; bCurrASamp = 1u; break; case SAMP_OLDB: hCurrB = pHandle->CurrBOld; bCurrBSamp = 1u; break; default: break; } /* Second sampling point */ wAux = ( int32_t )( ADCx->JDR2 ); wAux -= ( int32_t )( pHandle->PhaseOffset ); /* Check saturation */ if ( wAux > -INT16_MAX ) { if ( wAux < INT16_MAX ) { } else { wAux = INT16_MAX; } } else { wAux = -INT16_MAX; } switch ( pHandle->sampCur2 ) { case SAMP_IA: hCurrA = ( int16_t )( wAux ); bCurrASamp = 1u; break; case SAMP_IB: hCurrB = ( int16_t )( wAux ); bCurrBSamp = 1u; break; case SAMP_IC: hCurrC = ( int16_t )( wAux ); bCurrCSamp = 1u; break; case SAMP_NIA: wAux = -wAux; hCurrA = ( int16_t )( wAux ); bCurrASamp = 1u; break; case SAMP_NIB: wAux = -wAux; hCurrB = ( int16_t )( wAux ); bCurrBSamp = 1u; break; case SAMP_NIC: wAux = -wAux; hCurrC = ( int16_t )( wAux ); bCurrCSamp = 1u; break; default: break; } /* Computation of the third value */ if ( bCurrASamp == 0u ) { wAux = -( ( int32_t )( hCurrB ) ) - ( ( int32_t )( hCurrC ) ); /* Check saturation */ if ( wAux > -INT16_MAX ) { if ( wAux < INT16_MAX ) { } else { wAux = INT16_MAX; } } else { wAux = -INT16_MAX; } hCurrA = ( int16_t )wAux; } if ( bCurrBSamp == 0u ) { wAux = -( ( int32_t )( hCurrA ) ) - ( ( int32_t )( hCurrC ) ); /* Check saturation */ if ( wAux > -INT16_MAX ) { if ( wAux < INT16_MAX ) { } else { wAux = INT16_MAX; } } else { wAux = -INT16_MAX; } hCurrB = ( int16_t )wAux; } if ( bCurrCSamp == 0u ) { wAux = -( ( int32_t )( hCurrA ) ) - ( ( int32_t )( hCurrB ) ); /* Check saturation */ if ( wAux > -INT16_MAX ) { if ( wAux < INT16_MAX ) { } else { wAux = INT16_MAX; } } else { wAux = -INT16_MAX; } hCurrC = ( int16_t )wAux; } /* hCurrA, hCurrB, hCurrC values are the sampled values */ pHandle->CurrAOld = hCurrA; pHandle->CurrBOld = hCurrB; pStator_Currents->a = hCurrA; pStator_Currents->b = hCurrB; pHandle->_Super.Ia = hCurrA; pHandle->_Super.Ib = hCurrB; pHandle->_Super.Ic = -hCurrA - hCurrB; } /** * @brief Implementaion of PWMC_GetPhaseCurrents to be performed during * calibration. It sum up injected conversion data into wPhaseCOffset * to compute the offset introduced in the current feedback * network. It is requied to proper configure ADC input before to enable * the offset computation. * @param pHdl: handler of the current instance of the PWM component * @retval It always returns {0,0} in Curr_Components format */ static void R1F30X_HFCurrentsCalibration( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { /* Derived class members container */ PWMC_R1_F3_Handle_t * pHandle = ( PWMC_R1_F3_Handle_t * )pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; /* Reset the update flag to indicate the start of FOC algorithm*/ pHandle->UpdateFlagBuffer = false; if ( pHandle->Index < NB_CONVERSIONS ) { pHandle->PhaseOffset += ADCx->JDR2; pHandle->Index++; /* fill the queue*/ /* Preload Disable */ TIMx->CCMR3 &= TIMxCCR56_PRELOAD_DISABLE_MASK; LL_TIM_OC_SetCompareCH5( TIMx, 0 ); LL_TIM_OC_SetCompareCH6( TIMx, 0 ); /* Preload enable */ TIMx->CCMR3 |= TIMxCCR56_PRELOAD_ENABLE_MASK; LL_TIM_OC_SetCompareCH5( TIMx, ( ( uint32_t )( pHandle->Half_PWMPeriod ) >> 1 ) + ( uint32_t )( pHandle->pParams_str->Tafter ) ); LL_TIM_OC_SetCompareCH6( TIMx, ( ( uint32_t )( pHandle->Half_PWMPeriod ) - 1u ) ); } /* during offset calibration no current is flowing in the phases */ pStator_Currents->a = 0; pStator_Currents->b = 0; } /** * @brief It turns on low sides switches. This function is intended to be * used for charging boot capacitors of driving section. It has to be * called each motor start-up when using high voltage drivers * @param pHdl: handler of the current instance of the PWM component * @retval none */ __weak void R1F30X_TurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ) { PWMC_R1_F3_Handle_t * pHandle = ( PWMC_R1_F3_Handle_t * )pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = true; /*Turn on the three low side switches */ LL_TIM_OC_SetCompareCH1( TIMx, ticks ); LL_TIM_OC_SetCompareCH2( TIMx, ticks ); LL_TIM_OC_SetCompareCH3( TIMx, ticks ); /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Wait until next update */ while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == RESET ) {} /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } return; } /** * @brief It enables PWM generation on the proper Timer peripheral acting on MOE * bit * @param pHdl: handler of the current instance of the PWM component * @retval none */ __weak void R1F30X_SwitchOnPWM( PWMC_Handle_t * pHdl ) { PWMC_R1_F3_Handle_t * pHandle = ( PWMC_R1_F3_Handle_t * )pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; pHandle->_Super.TurnOnLowSidesAction = false; LL_TIM_DisableDMAReq_CC4( TIMx ); LL_TIM_DisableDMAReq_UPDATE( TIMx ); pHandle->PreloadDMAy_Chx->CCR &= ( uint16_t )( ~DMA_CCR_EN ); pHandle->DistortionDMAy_Chx->CCR &= ( uint16_t )( ~DMA_CCR_EN ); pHandle->DistortionDMAy_Chx->CNDTR = 2u; /* Enables the TIMx Preload on CC1 Register */ LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH1 ); /* Enables the TIMx Preload on CC2 Register */ LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH2 ); /* Enables the TIMx Preload on CC3 Register */ LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH3 ); /* TIM output trigger 2 for ADC */ LL_TIM_SetTriggerOutput2( TIMx, LL_TIM_TRGO2_OC5_RISING_OC6_RISING ); /* wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == RESET ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); /* Set all duty to 50% */ /* Set ch5 ch6 for triggering */ /* Clear Update Flag */ /* TIM ch4 DMA request enable */ pHandle->DmaBuff[1] = pHandle->Half_PWMPeriod >> 1; LL_TIM_OC_SetCompareCH1( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod >> 1 ) ); LL_TIM_OC_SetCompareCH2( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod >> 1 ) ); LL_TIM_OC_SetCompareCH3( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod >> 1 ) ); /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { if ( ( TIMx->CCER & TIMxCCER_MASK_CH123 ) != 0u ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* wait for new PWM cycle */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == RESET ) {} LL_TIM_EnableIT_UPDATE(TIMx); LL_TIM_ClearFlag_UPDATE( TIMx ); /* Re-enable ADC triggering ( wADC_JSQRvalue has been computed stored * during the init routine ) */ ADCx->JSQR = pHandle->ADC_JSQR; /*start injected conversion */ LL_ADC_INJ_StartConversion( ADCx ); /* clear injected end of sequence conversions flag*/ LL_ADC_ClearFlag_JEOS( ADCx ); /* enable injected end of sequence conversions interrupt */ LL_ADC_EnableIT_JEOS( ADCx ); /* ADC trigger setting (CH5+CH6 => TRGO2) */ LL_TIM_OC_DisablePreload( TIMx, LL_TIM_CHANNEL_CH5 ); LL_TIM_OC_DisablePreload( TIMx, LL_TIM_CHANNEL_CH6 ); LL_TIM_OC_SetCompareCH5( TIMx, ( ( ( uint32_t )( pHandle->Half_PWMPeriod >> 1 ) ) + ( uint32_t )pHandle->pParams_str->Tafter ) ); LL_TIM_OC_SetCompareCH6( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod - 1u ) ); LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH5 ); LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH6 ); /* enable DMA transfer */ LL_TIM_EnableDMAReq_CC4( TIMx ); pHandle->DistortionDMAy_Chx->CCR |= DMA_CCR_EN; } /** * @brief It disables PWM generation on the proper Timer peripheral acting on * MOE bit * @param pHdl: handler of the current instance of the PWM component * @retval none */ __weak void R1F30X_SwitchOffPWM( PWMC_Handle_t * pHdl ) { PWMC_R1_F3_Handle_t * pHandle = ( PWMC_R1_F3_Handle_t * )pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx = pHandle->pParams_str->ADCx; LL_TIM_DisableIT_UPDATE(TIMx); pHandle->_Super.TurnOnLowSidesAction = false; /* Main PWM Output Disable */ if ( pHandle->_Super.BrakeActionLock == true ) { } else { TIMx->BDTR &= ~( ( uint32_t )( LL_TIM_OSSI_ENABLE ) ); // todo } LL_TIM_DisableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } /* wait for new PWM cycle to flush last HF task */ while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == RESET ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); /* Flushing JSQR queue of context by setting JADSTP = 1 (JQM)=1 */ LL_ADC_INJ_StopConversion( ADCx ); /* disable injected end of sequence conversions interrupt */ LL_ADC_DisableIT_JEOS( ADCx ); /* clear injected end of sequence conversions flag*/ LL_ADC_ClearFlag_JEOS( ADCx ); /* Flushing JSQR queue of context by setting JADSTP = 1 (JQM)=1 */ LL_ADC_INJ_StopConversion( ADCx ); /* disable injected end of sequence conversions interrupt */ LL_ADC_DisableIT_JEOS( ADCx ); /* Disable ADC trigger (CH5+CH6 => TRGO2) */ LL_TIM_OC_DisablePreload( TIMx, LL_TIM_CHANNEL_CH5 ); LL_TIM_OC_DisablePreload( TIMx, LL_TIM_CHANNEL_CH6 ); LL_TIM_OC_SetCompareCH5( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod + 1u ) ); LL_TIM_OC_SetCompareCH6( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod + 1u ) ); LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH5 ); LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH6 ); /* Disable TIMx DMA requests enable */ LL_TIM_DisableDMAReq_CC4( TIMx ); LL_TIM_DisableDMAReq_UPDATE( TIMx ); /* Disable DMA channels*/ pHandle->PreloadDMAy_Chx->CCR &= ( uint16_t )( ~DMA_CCR_EN ); /* wait for a new PWM period to flush last HF task */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0u ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); return; } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__( ( section ( ".ccmram" ) ) ) #endif #endif /** * @brief It contains the TIMx Update event interrupt * @param pHdl: handler of the current instance of the PWM component * @retval none */ __weak void * R1F30X_TIMx_UP_IRQHandler( PWMC_R1_F3_Handle_t * pHandle ) { pHandle->UpdateFlagBuffer = true; return &( pHandle->_Super.Motor ); } /** * @brief It is used to configure the analog output used for protection * thresholds. * @param DAC_Channel: the selected DAC channel. * This parameter can be: * @arg DAC_Channel_1: DAC Channel1 selected * @arg DAC_Channel_2: DAC Channel2 selected * @param hDACVref Value of DAC reference expressed as 16bit unsigned integer. \n * Ex. 0 = 0V ; 65536 = VDD_DAC. * @retval none */ void R1F30X_SetAOReferenceVoltage( uint32_t DAC_Channel, uint16_t hDACVref ) { LL_DAC_ConvertData12LeftAligned( DAC1, DAC_Channel, hDACVref ); LL_DAC_TrigSWConversion( DAC1, DAC_Channel ); /* Enable DAC Channel */ LL_DAC_Enable( DAC1, DAC_Channel ); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__( ( section ( ".ccmram" ) ) ) #endif #endif /** * @brief Implementation of the single shunt algorithm to setup the * TIM1 register and DMA buffers values for the next PWM period. * @param pHandle related object of class CPWMC * @retval uint16_t It returns #MC_DURATION if the TIMx update occurs * before the end of FOC algorithm else returns #MC_NO_ERROR */ __weak uint16_t R1F30X_CalcDutyCycles( PWMC_Handle_t * pHdl ) { PWMC_R1_F3_Handle_t * pHandle = ( PWMC_R1_F3_Handle_t * )pHdl; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; int16_t hDeltaDuty_0; int16_t hDeltaDuty_1; register uint16_t lowDuty = pHandle->_Super.lowDuty; register uint16_t midDuty = pHandle->_Super.midDuty; register uint16_t highDuty = pHandle->_Super.highDuty; uint8_t bSector; uint8_t bStatorFluxPos; uint16_t hAux; bSector = ( uint8_t )( pHandle->_Super.Sector ); if ( ( pHandle->Flags & DSTEN ) != 0u ) { /* Compute delta duty */ hDeltaDuty_0 = ( int16_t )( midDuty ) - ( int16_t )( highDuty ); hDeltaDuty_1 = ( int16_t )( lowDuty ) - ( int16_t )( midDuty ); /* Check region */ if ( ( uint16_t )hDeltaDuty_0 <= pHandle->pParams_str->TMin ) { if ( ( uint16_t )hDeltaDuty_1 <= pHandle->pParams_str->TMin ) { bStatorFluxPos = BOUNDARY_3; } else { bStatorFluxPos = BOUNDARY_2; } } else { if ( ( uint16_t )hDeltaDuty_1 > pHandle->pParams_str->TMin ) { bStatorFluxPos = REGULAR; } else { bStatorFluxPos = BOUNDARY_1; } } if ( bStatorFluxPos == BOUNDARY_1 ) /* Adjust the lower */ { switch ( bSector ) { case SECTOR_5: case SECTOR_6: if ( pHandle->_Super.CntPhA - pHandle->pParams_str->CHTMin - highDuty > pHandle->pParams_str->TMin ) { pHandle->Inverted_pwm_new = INVERT_A; pHandle->_Super.CntPhA -= pHandle->pParams_str->CHTMin; if ( pHandle->_Super.CntPhA < midDuty ) { midDuty = pHandle->_Super.CntPhA; } } else { bStatorFluxPos = BOUNDARY_3; if ( ( pHandle->Flags & STBD3 ) == 0u ) { pHandle->Inverted_pwm_new = INVERT_A; pHandle->_Super.CntPhA -= pHandle->pParams_str->CHTMin; pHandle->Flags |= STBD3; } else { pHandle->Inverted_pwm_new = INVERT_B; pHandle->_Super.CntPhB -= pHandle->pParams_str->CHTMin; pHandle->Flags &= ( ~STBD3 ); } } break; case SECTOR_2: case SECTOR_1: if ( pHandle->_Super.CntPhB - pHandle->pParams_str->CHTMin - highDuty > pHandle->pParams_str->TMin ) { pHandle->Inverted_pwm_new = INVERT_B; pHandle->_Super.CntPhB -= pHandle->pParams_str->CHTMin; if ( pHandle->_Super.CntPhB < midDuty ) { midDuty = pHandle->_Super.CntPhB; } } else { bStatorFluxPos = BOUNDARY_3; if ( ( pHandle->Flags & STBD3 ) == 0u ) { pHandle->Inverted_pwm_new = INVERT_A; pHandle->_Super.CntPhA -= pHandle->pParams_str->CHTMin; pHandle->Flags |= STBD3; } else { pHandle->Inverted_pwm_new = INVERT_B; pHandle->_Super.CntPhB -= pHandle->pParams_str->CHTMin; pHandle->Flags &= ( ~STBD3 ); } } break; case SECTOR_4: case SECTOR_3: if ( pHandle->_Super.CntPhC - pHandle->pParams_str->CHTMin - highDuty > pHandle->pParams_str->TMin ) { pHandle->Inverted_pwm_new = INVERT_C; pHandle->_Super.CntPhC -= pHandle->pParams_str->CHTMin; if ( pHandle->_Super.CntPhC < midDuty ) { midDuty = pHandle->_Super.CntPhC; } } else { bStatorFluxPos = BOUNDARY_3; if ( ( pHandle->Flags & STBD3 ) == 0u ) { pHandle->Inverted_pwm_new = INVERT_A; pHandle->_Super.CntPhA -= pHandle->pParams_str->CHTMin; pHandle->Flags |= STBD3; } else { pHandle->Inverted_pwm_new = INVERT_B; pHandle->_Super.CntPhB -= pHandle->pParams_str->CHTMin; pHandle->Flags &= ( ~STBD3 ); } } break; default: break; } } else if ( bStatorFluxPos == BOUNDARY_2 ) /* Adjust the middler */ { switch ( bSector ) { case SECTOR_4: case SECTOR_5: /* Invert B */ pHandle->Inverted_pwm_new = INVERT_B; pHandle->_Super.CntPhB -= pHandle->pParams_str->CHTMin; if ( pHandle->_Super.CntPhB > 0xEFFFu ) { pHandle->_Super.CntPhB = 0u; } break; case SECTOR_2: case SECTOR_3: /* Invert A */ pHandle->Inverted_pwm_new = INVERT_A; pHandle->_Super.CntPhA -= pHandle->pParams_str->CHTMin; if ( pHandle->_Super.CntPhA > 0xEFFFu ) { pHandle->_Super.CntPhA = 0u; } break; case SECTOR_6: case SECTOR_1: /* Invert C */ pHandle->Inverted_pwm_new = INVERT_C; pHandle->_Super.CntPhC -= pHandle->pParams_str->CHTMin; if ( pHandle->_Super.CntPhC > 0xEFFFu ) { pHandle->_Super.CntPhC = 0u; } break; default: break; } } else if ( bStatorFluxPos == BOUNDARY_3 ) { if ( ( pHandle->Flags & STBD3 ) == 0u ) { pHandle->Inverted_pwm_new = INVERT_A; pHandle->_Super.CntPhA -= pHandle->pParams_str->CHTMin; pHandle->Flags |= STBD3; } else { pHandle->Inverted_pwm_new = INVERT_B; pHandle->_Super.CntPhB -= pHandle->pParams_str->CHTMin; pHandle->Flags &= ( ~STBD3 ); } } else { } if ( bStatorFluxPos == REGULAR ) /* Regular zone */ { /* First point */ pHandle->CntSmp1 = midDuty - pHandle->pParams_str->Tbefore; /* Second point */ pHandle->CntSmp2 = lowDuty - pHandle->pParams_str->Tbefore; } if ( bStatorFluxPos == BOUNDARY_1 ) /* Two small, one big */ { /* First point */ pHandle->CntSmp1 = midDuty - pHandle->pParams_str->Tbefore; /* Second point */ pHandle->CntSmp2 = pHandle->Half_PWMPeriod - pHandle->pParams_str->HTMin + pHandle->pParams_str->TSample; } if ( bStatorFluxPos == BOUNDARY_2 ) /* Two big, one small */ { /* First point */ pHandle->CntSmp1 = lowDuty - pHandle->pParams_str->Tbefore; /* Second point */ pHandle->CntSmp2 = pHandle->Half_PWMPeriod - pHandle->pParams_str->HTMin + pHandle->pParams_str->TSample; } if ( bStatorFluxPos == BOUNDARY_3 ) { /* First point */ pHandle->CntSmp1 = highDuty - pHandle->pParams_str->Tbefore; /* Dummy trigger */ /* Second point */ pHandle->CntSmp2 = pHandle->Half_PWMPeriod - pHandle->pParams_str->HTMin + pHandle->pParams_str->TSample; } } else { pHandle->Inverted_pwm_new = INVERT_NONE; bStatorFluxPos = REGULAR; } /* Update Timer Ch4 for active vector*/ /* Update Timer Ch 5,6 for ADC triggering and books the queue*/ TIMx->CCMR3 &= TIMxCCR56_PRELOAD_DISABLE_MASK; TIMx->CCR5 = 0x0u; TIMx->CCR6 = 0xFFFFu; TIMx->CCMR3 |= TIMxCCR56_PRELOAD_ENABLE_MASK; LL_TIM_OC_SetCompareCH5(TIMx, pHandle->CntSmp1); LL_TIM_OC_SetCompareCH6(TIMx, pHandle->CntSmp2); if ( bStatorFluxPos == REGULAR ) { /*LL_TIM_SetTriggerOutput2(TIMx, LL_TIM_TRGO2_OC5_RISING_OC6_RISING); */ TIMx->CR2 &= ( ( uint32_t )0xFFEFFFFFu ); switch ( pHandle->Inverted_pwm_new ) { case INVERT_A: pHandle->DmaBuff[1] = pHandle->_Super.CntPhA; break; case INVERT_B: pHandle->DmaBuff[1] = pHandle->_Super.CntPhB; break; case INVERT_C: pHandle->DmaBuff[1] = pHandle->_Super.CntPhC; break; default: break; } } else { /* disable DMA request update interrupt */ LL_TIM_DisableDMAReq_UPDATE( TIMx ); /* Set the DMA destinations */ switch ( pHandle->Inverted_pwm_new ) { case INVERT_A: pHandle->DistortionDMAy_Chx->CPAR = ( uint32_t )( &( TIMx->CCR1 ) ); pHandle->PreloadDMAy_Chx->CPAR = ( uint32_t )( &( TIMx->CCMR1 ) ); pHandle->DmaBuff[1] = pHandle->_Super.CntPhA; pHandle->PreloadDisableActing = pHandle->PreloadDisableCC1; break; case INVERT_B: pHandle->DistortionDMAy_Chx->CPAR = ( uint32_t )( &( TIMx->CCR2 ) ); pHandle->PreloadDMAy_Chx->CPAR = ( uint32_t )( &( TIMx->CCMR1 ) ); pHandle->DmaBuff[1] = pHandle->_Super.CntPhB; pHandle->PreloadDisableActing = pHandle->PreloadDisableCC2; break; case INVERT_C: pHandle->DistortionDMAy_Chx->CPAR = ( uint32_t )( &( TIMx->CCR3 ) ); pHandle->PreloadDMAy_Chx->CPAR = ( uint32_t )( &( TIMx->CCMR2 ) ); pHandle->DmaBuff[1] = pHandle->_Super.CntPhC; pHandle->PreloadDisableActing = pHandle->PreloadDisableCC3; break; default: break; } /*TIM_SelectOutputTrigger2(TIMx, TIM_TRGO2Source_OC5RefRising_OC6RefFalling); */ TIMx->CR2 |= ( ( uint32_t )0x100000u ); /*active vector*/ pHandle->PreloadDMAy_Chx->CCR &= ( uint16_t )( ~DMA_CCR_EN ); pHandle->PreloadDMAy_Chx->CNDTR = 1u; pHandle->PreloadDMAy_Chx->CCR |= DMA_CCR_EN; /* enable DMA request update interrupt */ LL_TIM_EnableDMAReq_UPDATE( TIMx ); } pHandle->pParams_str->ADCx->JSQR = pHandle->ADC_JSQR; /* Update Timer Ch 1,2,3 (These value are required before update event) */ LL_TIM_OC_SetCompareCH1(TIMx, pHandle->_Super.CntPhA); LL_TIM_OC_SetCompareCH2(TIMx, pHandle->_Super.CntPhB); LL_TIM_OC_SetCompareCH3(TIMx, pHandle->_Super.CntPhC); /*End of FOC*/ /*check software error*/ if ( pHandle->UpdateFlagBuffer == true ) { hAux = MC_DURATION; } else { hAux = MC_NO_ERROR; } if ( pHandle->_Super.SWerror == 1u ) { hAux = MC_DURATION; pHandle->_Super.SWerror = 0u; } /* Set the current sampled */ if ( bStatorFluxPos == REGULAR ) /* Regual zone */ { pHandle->sampCur1 = REGULAR_SAMP_CUR1[bSector]; pHandle->sampCur2 = REGULAR_SAMP_CUR2[bSector]; } if ( bStatorFluxPos == BOUNDARY_1 ) /* Two small, one big */ { pHandle->sampCur1 = REGULAR_SAMP_CUR1[bSector]; pHandle->sampCur2 = BOUNDR1_SAMP_CUR2[bSector]; } if ( bStatorFluxPos == BOUNDARY_2 ) /* Two big, one small */ { pHandle->sampCur1 = BOUNDR2_SAMP_CUR1[bSector]; pHandle->sampCur2 = BOUNDR2_SAMP_CUR2[bSector]; } if ( bStatorFluxPos == BOUNDARY_3 ) { if ( pHandle->Inverted_pwm_new == INVERT_A ) { pHandle->sampCur1 = SAMP_OLDB; pHandle->sampCur2 = SAMP_IA; } if ( pHandle->Inverted_pwm_new == INVERT_B ) { pHandle->sampCur1 = SAMP_OLDA; pHandle->sampCur2 = SAMP_IB; } } /* Limit for the Get Phase current (Second EOC Handler) */ return ( hAux ); } /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
44,883
C
30.169444
130
0.599136
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/H7xx/Src/r3_2_h7xx_pwm_curr_fdbk.c
/** ****************************************************************************** * @file r3_2_h7xx_pwm_curr_fdbk.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement current sensor * class to be stantiated when the three shunts current sensing * topology is used. * * It is specifically designed for STM32H7XX microcontrollers and * implements the successive sampling of motor current using two ADCs. * + MCU peripheral and handle initialization function * + three shunt current sensing * + space vector modulation function * + ADC sampling function * ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * * @ingroup R3_2_H7XX_pwm_curr_fdbk */ /* Includes ------------------------------------------------------------------*/ #include "r3_2_h7xx_pwm_curr_fdbk.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup R3_2_pwm_curr_fdbk * @{ */ /* Private defines -----------------------------------------------------------*/ #define TIMxCCER_MASK_CH123 ((uint16_t) (LL_TIM_CHANNEL_CH1|LL_TIM_CHANNEL_CH1N|\ LL_TIM_CHANNEL_CH2|LL_TIM_CHANNEL_CH2N|\ LL_TIM_CHANNEL_CH3|LL_TIM_CHANNEL_CH3N)) #define NB_CONVERSIONS 16u #define CCMR2_CH4_DISABLE 0x8FFFu // /* Private typedef -----------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ static void R3_2_TIMxInit( TIM_TypeDef * TIMx, PWMC_Handle_t * pHdl ); static void R3_2_ADCxInit( ADC_TypeDef * ADCx ); __STATIC_INLINE uint16_t R3_2_WriteTIMRegisters( PWMC_Handle_t * pHdl, uint16_t hCCR4Reg ); static void R3_2_HFCurrentsPolarizationAB( PWMC_Handle_t * pHdl,ab_t * Iab ); static void R3_2_HFCurrentsPolarizationC( PWMC_Handle_t * pHdl, ab_t * Iab ); static void R3_2_SetAOReferenceVoltage( uint32_t DAC_Channel, uint16_t hDACVref ); uint16_t R3_2_SetADCSampPointPolarization( PWMC_Handle_t * pHdl) ; static void R3_2_RLGetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ); static void R3_2_RLTurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ); static void R3_2_RLSwitchOnPWM( PWMC_Handle_t * pHdl ); /* * @brief Initializes TIMx, ADC, GPIO, DMA1 and NVIC for current reading * in three shunt topology using STM32H7XX and two ADCs. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void R3_2_Init( PWMC_R3_2_Handle_t * pHandle ) { R3_2_OPAMPParams_t * OPAMPParams = pHandle->pParams_str->OPAMPParams; COMP_TypeDef * COMP_OCPAx = pHandle->pParams_str->CompOCPASelection; COMP_TypeDef * COMP_OCPBx = pHandle->pParams_str->CompOCPBSelection; COMP_TypeDef * COMP_OCPCx = pHandle->pParams_str->CompOCPCSelection; COMP_TypeDef * COMP_OVPx = pHandle->pParams_str->CompOVPSelection; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx_1 = pHandle->pParams_str->ADCDataReg1[0]; ADC_TypeDef * ADCx_2 = pHandle->pParams_str->ADCDataReg2[0]; /*Check that _Super is the first member of the structure PWMC_R3_2_Handle_t */ if ( ( uint32_t )pHandle == ( uint32_t )&pHandle->_Super ) { /* disable IT and flags in case of LL driver usage * workaround for unwanted interrupt enabling done by LL driver */ LL_ADC_DisableIT_EOC( ADCx_1 ); LL_ADC_ClearFlag_EOC( ADCx_1 ); LL_ADC_DisableIT_JEOC( ADCx_1 ); LL_ADC_ClearFlag_JEOC( ADCx_1 ); LL_ADC_DisableIT_EOC( ADCx_2 ); LL_ADC_ClearFlag_EOC( ADCx_2 ); LL_ADC_DisableIT_JEOC( ADCx_2 ); LL_ADC_ClearFlag_JEOC( ADCx_2 ); if ( TIMx == TIM1 ) { /* TIM1 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph( LL_DBGMCU_APB2_GRP1_TIM1_STOP ); } else { /* TIM8 Counter Clock stopped when the core is halted */ LL_DBGMCU_APB2_GRP1_FreezePeriph( LL_DBGMCU_APB2_GRP1_TIM8_STOP ); } if ( OPAMPParams != NULL ) { LL_OPAMP_Enable(OPAMPParams->OPAMPSelect_1[0]); LL_OPAMP_Enable(OPAMPParams->OPAMPSelect_2[0]); } /* Over current protection phase A */ if ( COMP_OCPAx != NULL ) { /* Inverting input*/ if ( pHandle->pParams_str->CompOCPAInvInput_MODE != EXT_MODE ) { if ( LL_COMP_GetInputMinus( COMP_OCPAx ) == LL_COMP_INPUT_MINUS_DAC1_CH1 ) { R3_2_SetAOReferenceVoltage( LL_DAC_CHANNEL_1, ( uint16_t )( pHandle->pParams_str->DAC_OCP_Threshold ) ); } #if defined(DAC_CHANNEL2_SUPPORT) else if ( LL_COMP_GetInputMinus( COMP_OCPAx ) == LL_COMP_INPUT_MINUS_DAC1_CH2 ) { R3_2_SetAOReferenceVoltage( LL_DAC_CHANNEL_2, ( uint16_t )( pHandle->pParams_str->DAC_OCP_Threshold ) ); } #endif else { } } /* Output */ LL_COMP_Enable ( COMP_OCPAx ); LL_COMP_Lock( COMP_OCPAx ); } /* Over current protection phase B */ if ( COMP_OCPBx != NULL ) { LL_COMP_Enable ( COMP_OCPBx ); LL_COMP_Lock( COMP_OCPBx ); } /* Over current protection phase C */ if ( COMP_OCPCx != NULL ) { LL_COMP_Enable ( COMP_OCPCx ); LL_COMP_Lock( COMP_OCPCx ); } /* Over voltage protection */ if ( COMP_OVPx != NULL ) { /* Inverting input*/ if ( pHandle->pParams_str->CompOVPInvInput_MODE != EXT_MODE ) { if ( LL_COMP_GetInputMinus( COMP_OVPx ) == LL_COMP_INPUT_MINUS_DAC1_CH1 ) { R3_2_SetAOReferenceVoltage( LL_DAC_CHANNEL_1, ( uint16_t )( pHandle->pParams_str->DAC_OVP_Threshold ) ); } #if defined(DAC_CHANNEL2_SUPPORT) else if ( LL_COMP_GetInputMinus( COMP_OVPx ) == LL_COMP_INPUT_MINUS_DAC1_CH2 ) { R3_2_SetAOReferenceVoltage( LL_DAC_CHANNEL_2, ( uint16_t )( pHandle->pParams_str->DAC_OVP_Threshold ) ); } #endif else { } } /* Output */ LL_COMP_Enable ( COMP_OVPx ); LL_COMP_Lock( COMP_OVPx ); } if (LL_ADC_IsEnabled (ADCx_1) == 0) { R3_2_ADCxInit (ADCx_1); /* Only the Interrupt of the first ADC is enabled. * As Both ADCs are fired by HW at the same moment * It is safe to consider that both conversion are ready at the same time*/ LL_ADC_ClearFlag_JEOS( ADCx_1 ); LL_ADC_EnableIT_JEOS( ADCx_1 ); } else { /* Nothing to do ADCx_1 already configured */ } if (LL_ADC_IsEnabled (ADCx_2) == 0) { R3_2_ADCxInit (ADCx_2); } else { /* Nothing to do ADCx_2 already configured */ } R3_2_TIMxInit( TIMx, &pHandle->_Super ); } } /* * @brief Initializes @p ADCx peripheral for current sensing. * */ static void R3_2_ADCxInit( ADC_TypeDef * ADCx ) { /* - Exit from deep-power-down mode */ LL_ADC_DisableDeepPowerDown(ADCx); if ( LL_ADC_IsInternalRegulatorEnabled(ADCx) == 0u) { /* Enable ADC internal voltage regulator */ LL_ADC_EnableInternalRegulator(ADCx); /* Wait for Regulator Startup time, once for both */ /* Note: Variable divided by 2 to compensate partially */ /* CPU processing cycles, scaling in us split to not */ /* exceed 32 bits register capacity and handle low frequency. */ volatile uint32_t wait_loop_index = ((LL_ADC_DELAY_INTERNAL_REGUL_STAB_US / 10UL) * (SystemCoreClock / (100000UL * 2UL))); while(wait_loop_index != 0UL) { wait_loop_index--; } } LL_ADC_StartCalibration( ADCx, LL_ADC_CALIB_OFFSET_LINEARITY, LL_ADC_SINGLE_ENDED ); while ( LL_ADC_IsCalibrationOnGoing( ADCx) == 1u) {} /* ADC Enable (must be done after calibration) */ /* ADC5-140924: Enabling the ADC by setting ADEN bit soon after polling ADCAL=0 * following a calibration phase, could have no effect on ADC * within certain AHB/ADC clock ratio. */ while ( LL_ADC_IsActiveFlag_ADRDY( ADCx ) == 0u) { LL_ADC_Enable( ADCx ); } /* Clear JSQR from CubeMX setting to avoid not wanting conversion*/ LL_ADC_INJ_StartConversion( ADCx ); LL_ADC_INJ_StopConversion(ADCx); /* TODO: check if not already done by MX */ LL_ADC_INJ_SetQueueMode( ADCx, LL_ADC_INJ_QUEUE_2CONTEXTS_END_EMPTY ); } /* * @brief Initializes @p TIMx peripheral with @p pHdl handler for PWM generation. * */ static void R3_2_TIMxInit( TIM_TypeDef * TIMx, PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ uint32_t Brk2Timeout = 1000; /* disable main TIM counter to ensure * a synchronous start by TIM2 trigger */ LL_TIM_DisableCounter( TIMx ); LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); /* Enables the TIMx Preload on CC1 Register */ LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH1 ); /* Enables the TIMx Preload on CC2 Register */ LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH2 ); /* Enables the TIMx Preload on CC3 Register */ LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH3 ); /* Enables the TIMx Preload on CC4 Register */ LL_TIM_OC_EnablePreload( TIMx, LL_TIM_CHANNEL_CH4 ); /* Prepare timer for synchronization */ LL_TIM_GenerateEvent_UPDATE( TIMx ); if ( pHandle->pParams_str->FreqRatio == 2u ) { if ( pHandle->pParams_str->IsHigherFreqTim == HIGHER_FREQ ) { if ( pHandle->pParams_str->RepetitionCounter == 3u ) { /* Set TIMx repetition counter to 1 */ LL_TIM_SetRepetitionCounter( TIMx, 1 ); LL_TIM_GenerateEvent_UPDATE( TIMx ); /* Repetition counter will be set to 3 at next Update */ LL_TIM_SetRepetitionCounter( TIMx, 3 ); } } LL_TIM_SetCounter( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) - 1u ); } else /* bFreqRatio equal to 1 or 3 */ { if ( pHandle->_Super.Motor == M1 ) { if ( pHandle->pParams_str->RepetitionCounter == 3u ) { /* Set TIMx repetition counter to 1 */ LL_TIM_SetRepetitionCounter( TIMx, 1 ); LL_TIM_GenerateEvent_UPDATE( TIMx ); /* Repetition counter will be set to 3 at next Update */ LL_TIM_SetRepetitionCounter( TIMx, 3 ); } LL_TIM_SetCounter( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) - 1u ); } else { } } LL_TIM_ClearFlag_BRK( TIMx ); while ((LL_TIM_IsActiveFlag_BRK2 (TIMx) == 1u) && (Brk2Timeout != 0u) ) { LL_TIM_ClearFlag_BRK2( TIMx ); Brk2Timeout--; } LL_TIM_EnableIT_BRK( TIMx ); /* Enable PWM channel */ LL_TIM_CC_EnableChannel( TIMx, TIMxCCER_MASK_CH123 ); } /* * @brief Stores into the @p pHdl the voltage present on Ia and Ib current * feedback analog channels when no current is flowing into the motor. * */ __weak void R3_2_CurrentReadingPolarization( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx_1 = pHandle->pParams_str->ADCDataReg1[0]; ADC_TypeDef * ADCx_2 = pHandle->pParams_str->ADCDataReg2[0]; pHandle->PhaseAOffset = 0u; pHandle->PhaseBOffset = 0u; pHandle->PhaseCOffset = 0u; pHandle->PolarizationCounter = 0u; /* It forces inactive level on TIMx CHy and CHyN */ LL_TIM_CC_DisableChannel(TIMx, TIMxCCER_MASK_CH123); /* Offset calibration for all phases */ /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R3_2_HFCurrentsPolarizationAB; pHandle->_Super.pFctSetADCSampPointSectX = &R3_2_SetADCSampPointPolarization; pHandle->ADC_ExternalPolarityInjected = (uint16_t) LL_ADC_INJ_TRIG_EXT_RISING; /* We want to polarize calibration Phase A and Phase B, so we select SECTOR_5 */ pHandle->PolarizationSector=SECTOR_5; /* Required to force first polarization conversion on SECTOR_5*/ pHandle->_Super.Sector = SECTOR_5; R3_2_SwitchOnPWM( &pHandle->_Super ); /* IF CH4 is enabled, it means that JSQR is now configured to sample polarization current*/ //while ( LL_TIM_CC_IsEnabledChannel(TIMx, LL_TIM_CHANNEL_CH4) == 0u ) //{ //} while ( ((TIMx->CR2) & TIM_CR2_MMS_Msk) != LL_TIM_TRGO_OC4REF ) { } /* It is the right time to start the ADC without unwanted conversion */ /* Start ADC to wait for external trigger. This is series dependant*/ LL_ADC_INJ_StartConversion( ADCx_1 ); LL_ADC_INJ_StartConversion( ADCx_2 ); /* Wait for NB_CONVERSIONS to be executed */ while ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { } R3_2_SwitchOffPWM( &pHandle->_Super ); /* Offset calibration for C phase */ pHandle->PolarizationCounter = 0u; /* Change function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R3_2_HFCurrentsPolarizationC; /* We want to polarize Phase C, so we select SECTOR_1 */ pHandle->PolarizationSector=SECTOR_1; /* Required to force first polarization conversion on SECTOR_1*/ pHandle->_Super.Sector = SECTOR_1; R3_2_SwitchOnPWM( &pHandle->_Super ); /* Wait for NB_CONVERSIONS to be executed */ while ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { } R3_2_SwitchOffPWM( &pHandle->_Super ); pHandle->PhaseAOffset /= NB_CONVERSIONS; pHandle->PhaseBOffset /= NB_CONVERSIONS; pHandle->PhaseCOffset /= NB_CONVERSIONS; /* Change back function to be executed in ADCx_ISR */ pHandle->_Super.pFctGetPhaseCurrents = &R3_2_GetPhaseCurrents; pHandle->_Super.pFctSetADCSampPointSectX = &R3_2_SetADCSampPointSectX; /* It over write TIMx CCRy wrongly written by FOC during calibration so as to force 50% duty cycle on the three inverer legs */ /* Disable TIMx preload */ LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH1); LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH2); LL_TIM_OC_DisablePreload(TIMx, LL_TIM_CHANNEL_CH3); LL_TIM_OC_SetCompareCH1 (TIMx, pHandle->Half_PWMPeriod); LL_TIM_OC_SetCompareCH2 (TIMx, pHandle->Half_PWMPeriod); LL_TIM_OC_SetCompareCH3 (TIMx, pHandle->Half_PWMPeriod); /* Enable TIMx preload */ LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH1); LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH2); LL_TIM_OC_EnablePreload(TIMx, LL_TIM_CHANNEL_CH3); /* It re-enable drive of TIMx CHy and CHyN by TIMx CHyRef*/ LL_TIM_CC_EnableChannel(TIMx, TIMxCCER_MASK_CH123); /* At the end of calibration, all phases are at 50% we will sample A&B */ pHandle->_Super.Sector=SECTOR_5; pHandle->_Super.BrakeActionLock = false; } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__( ( section ( ".ccmram" ) ) ) #endif #endif /* * @brief Computes and stores in @p pHdl handler the latest converted motor phase currents in @p Iab ab_t format. * */ __weak void R3_2_GetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * Iab ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint8_t Sector; int32_t Aux; uint32_t ADCDataReg1; uint32_t ADCDataReg2; Sector = ( uint8_t )pHandle->_Super.Sector; ADCDataReg1 = pHandle->pParams_str->ADCDataReg1[Sector]->JDR1; ADCDataReg2 = pHandle->pParams_str->ADCDataReg2[Sector]->JDR1; /* disable ADC trigger source */ //LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); switch ( Sector ) { case SECTOR_4: case SECTOR_5: /* Current on Phase C is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg2 ); /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; case SECTOR_6: case SECTOR_1: /* Current on Phase A is not accessible */ /* Ib = PhaseBOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseBOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ib */ if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else { Iab->b = ( int16_t )Aux; } /* Ia = -Ic -Ib */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->b; /* Ia */ /* Saturation of Ia */ if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else { Iab->a = ( int16_t )Aux; } break; case SECTOR_2: case SECTOR_3: /* Current on Phase B is not accessible */ /* Ia = PhaseAOffset - ADC converted value) */ Aux = ( int32_t )( pHandle->PhaseAOffset ) - ( int32_t )( ADCDataReg1 ); /* Saturation of Ia */ if ( Aux < -INT16_MAX ) { Iab->a = -INT16_MAX; } else if ( Aux > INT16_MAX ) { Iab->a = INT16_MAX; } else { Iab->a = ( int16_t )Aux; } /* Ib = -Ic -Ia */ Aux = ( int32_t )( ADCDataReg2 ) - ( int32_t )( pHandle->PhaseCOffset ); /* -Ic */ Aux -= ( int32_t )Iab->a; /* Ib */ /* Saturation of Ib */ if ( Aux > INT16_MAX ) { Iab->b = INT16_MAX; } else if ( Aux < -INT16_MAX ) { Iab->b = -INT16_MAX; } else { Iab->b = ( int16_t )Aux; } break; default: break; } pHandle->_Super.Ia = Iab->a; pHandle->_Super.Ib = Iab->b; pHandle->_Super.Ic = -Iab->a - Iab->b; } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__( ( section ( ".ccmram" ) ) ) #endif #endif /* * @brief Configures the ADC for the current sampling during calibration. * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ uint16_t R3_2_SetADCSampPointPolarization( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ pHandle->_Super.Sector = pHandle->PolarizationSector; return R3_2_WriteTIMRegisters( &pHandle->_Super, ( pHandle->Half_PWMPeriod - (uint16_t) 1 ) ); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__( ( section ( ".ccmram" ) ) ) #endif #endif /* * @brief Configures the ADC for the current sampling related to sector X (X = [1..6] ). * * It sets the ADC sequence length and channels, and the sampling point via TIMx_Ch4 value and polarity. * It then calls the WriteTIMRegisters method. * * @param pHdl: Handler of the current instance of the PWM component. * @retval Return value of R3_1_WriteTIMRegisters. */ uint16_t R3_2_SetADCSampPointSectX( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ uint16_t SamplingPoint; uint16_t DeltaDuty; /* Verify that sampling is possible in the middle of PWM by checking the smallest duty cycle */ if ( ( uint16_t )( pHandle->Half_PWMPeriod - pHdl->lowDuty ) > pHandle->pParams_str->Tafter ) { /* When it is possible to sample in the middle of the PWM period, always sample the same phases * (AB are chosen) for all sectors in order to not induce current discontinuities when there are differences * between offsets */ /* sector number needed by GetPhaseCurrent, phase A and B are sampled which corresponds * to sector 4 or 5 */ pHandle->_Super.Sector = SECTOR_5; /* set sampling point trigger in the middle of PWM period */ SamplingPoint = pHandle->Half_PWMPeriod - (uint16_t) 1; } else { /* In this case it is necessary to convert phases with Maximum and variable complementary duty cycle.*/ /* ADC Injected sequence configuration. The stator phase with minimum value of complementary duty cycle is set as first. In every sector there is always one phase with maximum complementary duty, one with minimum complementary duty and one with variable complementary duty. In this case, phases with variable complementary duty and with maximum duty are converted and the first will be always the phase with variable complementary duty cycle */ DeltaDuty = ( uint16_t )( pHdl->lowDuty - pHdl->midDuty ); /* Definition of crossing point */ if ( DeltaDuty > ( uint16_t )( pHandle->Half_PWMPeriod - pHdl->lowDuty ) * 2u ) { SamplingPoint = pHdl->lowDuty - pHandle->pParams_str->Tbefore; } else { SamplingPoint = pHdl->lowDuty + pHandle->pParams_str->Tafter; if ( SamplingPoint >= pHandle->Half_PWMPeriod ) { /* ADC trigger edge must be changed from positive to negative */ pHandle->ADC_ExternalPolarityInjected = (uint16_t) LL_ADC_INJ_TRIG_EXT_FALLING; SamplingPoint = ( 2u * pHandle->Half_PWMPeriod ) - SamplingPoint - (uint16_t) 1; } } } return R3_2_WriteTIMRegisters( &pHandle->_Super, SamplingPoint ); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__( ( section ( ".ccmram" ) ) ) #endif #endif /* * @brief Writes into peripheral registers the new duty cycle and sampling point. * * @param pHdl: Handler of the current instance of the PWM component. * @param SamplingPoint: Point at which the ADC will be triggered, written in timer clock counts. * @retval Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ __STATIC_INLINE uint16_t R3_2_WriteTIMRegisters( PWMC_Handle_t * pHdl, uint16_t SamplingPoint ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint16_t Aux; LL_TIM_OC_SetCompareCH1 ( TIMx, (uint32_t) pHandle->_Super.CntPhA ); LL_TIM_OC_SetCompareCH2 ( TIMx, (uint32_t) pHandle->_Super.CntPhB ); LL_TIM_OC_SetCompareCH3 ( TIMx, (uint32_t) pHandle->_Super.CntPhC ); LL_TIM_OC_SetCompareCH4( TIMx, (uint32_t) SamplingPoint ); /* Limit for update event */ // if ( LL_TIM_CC_IsEnabledChannel(TIMx, LL_TIM_CHANNEL_CH4) == 1u ) if (((TIMx->CR2) & TIM_CR2_MMS_Msk) != LL_TIM_TRGO_RESET ) { Aux = MC_DURATION; } else { Aux = MC_NO_ERROR; } return Aux; } /* * @brief Implementation of PWMC_GetPhaseCurrents to be performed during polarization. * * It sums up injected conversion data into PhaseAOffset and * PhaseBOffset to compute the offset introduced in the current feedback * network. It is required to properly configure ADC inputs before in order to enable * the offset computation. * * @param pHdl: Handler of the current instance of the PWM component. * @param Iab: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ static void R3_2_HFCurrentsPolarizationAB( PWMC_Handle_t * pHdl, ab_t * Iab ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint32_t ADCDataReg1 = pHandle->pParams_str->ADCDataReg1[pHandle->PolarizationSector]->JDR1; uint32_t ADCDataReg2 = pHandle->pParams_str->ADCDataReg2[pHandle->PolarizationSector]->JDR1; /* disable ADC trigger source */ //LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); if ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { pHandle-> PhaseAOffset += ADCDataReg1; pHandle-> PhaseBOffset += ADCDataReg2; pHandle->PolarizationCounter++; } /* during offset calibration no current is flowing in the phases */ Iab->a = 0; Iab->b = 0; } /* * @brief Implementation of PWMC_GetPhaseCurrents to be performed during polarization. * * It sums up injected conversion data into PhaseCOffset to compute the * offset introduced in the current feedback * network. It is required to proper configure ADC inputs before enabling * the offset computation. * * @param pHdl: Handler of the current instance of the PWM component. * @param Iab: Pointer to the structure that will receive motor current * of phase A and B in ElectricalValue format. */ static void R3_2_HFCurrentsPolarizationC( PWMC_Handle_t * pHdl, ab_t * Iab ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint32_t ADCDataReg2 = pHandle->pParams_str->ADCDataReg2[pHandle->PolarizationSector]->JDR1; /* disable ADC trigger source */ //LL_TIM_CC_DisableChannel(TIMx, LL_TIM_CHANNEL_CH4); LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); if ( pHandle->PolarizationCounter < NB_CONVERSIONS ) { /* Phase C is read from SECTOR_1, second value */ pHandle-> PhaseCOffset += ADCDataReg2; pHandle->PolarizationCounter++; } /* during offset calibration no current is flowing in the phases */ Iab->a = 0; Iab->b = 0; } /* * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors of driving section. It has to be * called on each motor start-up when using high voltage drivers. * * @param pHdl: Handler of the current instance of the PWM component. * @param ticks: Timer ticks value to be applied * Min value: 0 (low sides ON) * Max value: PWM_PERIOD_CYCLES/2 (low sides OFF) */ __weak void R3_2_TurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = true; /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( pHandle->pParams_str->TIMx ); /*Turn on the three low side switches */ LL_TIM_OC_SetCompareCH1( TIMx, ticks ); LL_TIM_OC_SetCompareCH2( TIMx, ticks ); LL_TIM_OC_SetCompareCH3( TIMx, ticks ); /* Wait until next update */ while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0u ) {} /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } return; } /* * @brief Enables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_2_SwitchOnPWM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.TurnOnLowSidesAction = false; /* Set all duty to 50% */ LL_TIM_OC_SetCompareCH1(TIMx, ((uint32_t) pHandle->Half_PWMPeriod / (uint32_t) 2)); LL_TIM_OC_SetCompareCH2(TIMx, ((uint32_t) pHandle->Half_PWMPeriod / (uint32_t) 2)); LL_TIM_OC_SetCompareCH3(TIMx, ((uint32_t) pHandle->Half_PWMPeriod / (uint32_t) 2)); LL_TIM_OC_SetCompareCH4(TIMx, ((uint32_t) pHandle->Half_PWMPeriod - (uint32_t) 5)); /* wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0u ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE; LL_TIM_EnableAllOutputs ( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { if ( ( TIMx->CCER & TIMxCCER_MASK_CH123 ) != 0u ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Enable Update IRQ */ LL_TIM_EnableIT_UPDATE( TIMx ); } /* * @brief Disables PWM generation on the proper Timer peripheral acting on MOE bit. * * @param pHdl: Handler of the current instance of the PWM component. */ __weak void R3_2_SwitchOffPWM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /* Disable UPDATE ISR */ LL_TIM_DisableIT_UPDATE( TIMx ); pHandle->_Super.TurnOnLowSidesAction = false; /* Main PWM Output Disable */ if ( pHandle->_Super.BrakeActionLock == true ) { } else { TIMx->BDTR &= ~( ( uint32_t )( LL_TIM_OSSI_ENABLE ) ); LL_TIM_DisableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* wait for a new PWM period to flush last HF task */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0u ) {} LL_TIM_ClearFlag_UPDATE( TIMx ); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__( ( section ( ".ccmram" ) ) ) #endif #endif /* * @brief Contains the TIMx Update event interrupt. * * @param pHandle: Handler of the current instance of the PWM component. */ __weak void * R3_2_TIMx_UP_IRQHandler( PWMC_R3_2_Handle_t * pHandle ) { TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx_1 = pHandle->pParams_str->ADCDataReg1[0]; R3_2_OPAMPParams_t * OPAMPParams = pHandle->pParams_str->OPAMPParams; uint32_t OpampConfig; OPAMP_TypeDef *operationAmp; if ( OPAMPParams != NULL ) { /* We can not change OPAMP source if ADC acquisition is ongoing (Dual motor with internal opamp use case)*/ while (ADCx_1->JSQR != 0x0u ) {} OpampConfig = OPAMPParams->OPAMPConfig1[pHandle->_Super.Sector]; operationAmp = OPAMPParams->OPAMPSelect_1[pHandle->_Super.Sector]; MODIFY_REG(operationAmp->CSR, OPAMP_CSR_VPSEL, OpampConfig); OpampConfig = OPAMPParams->OPAMPConfig2[pHandle->_Super.Sector]; operationAmp = OPAMPParams->OPAMPSelect_2[pHandle->_Super.Sector]; MODIFY_REG(operationAmp->CSR, OPAMP_CSR_VPSEL, OpampConfig); } pHandle->pParams_str->ADCDataReg1[pHandle->_Super.Sector]->JSQR = pHandle->pParams_str->ADCConfig1[pHandle->_Super.Sector] | (uint32_t) pHandle->ADC_ExternalPolarityInjected; pHandle->pParams_str->ADCDataReg2[pHandle->_Super.Sector]->JSQR = pHandle->pParams_str->ADCConfig2[pHandle->_Super.Sector] | (uint32_t) pHandle->ADC_ExternalPolarityInjected; /* enable ADC trigger source */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_OC4REF); pHandle->ADC_ExternalPolarityInjected = (uint16_t)LL_ADC_INJ_TRIG_EXT_RISING; return &( pHandle->_Super.Motor ); } /* * @brief Configures the analog output used for protection thresholds. * * @param DAC_Channel: the selected DAC channel. * This parameter can be: * @arg DAC_Channel_1: DAC Channel1 selected. * @arg DAC_Channel_2: DAC Channel2 selected. * @param hDACVref: Value of DAC reference expressed as 16bit unsigned integer. \n * Ex. 0 = 0V ; 65536 = VDD_DAC. */ static void R3_2_SetAOReferenceVoltage( uint32_t DAC_Channel, uint16_t hDACVref ) { LL_DAC_ConvertData12LeftAligned ( DAC1, DAC_Channel, hDACVref ); /* Enable DAC Channel */ LL_DAC_TrigSWConversion ( DAC1, DAC_Channel ); if (LL_DAC_IsEnabled ( DAC1, DAC_Channel ) == 1u ) { /* If DAC is already enable, we wait LL_DAC_DELAY_VOLTAGE_SETTLING_US*/ uint32_t wait_loop_index = ((LL_DAC_DELAY_VOLTAGE_SETTLING_US) * (SystemCoreClock / (1000000UL * 2UL))); while(wait_loop_index != 0UL) { wait_loop_index--; } } else { /* If DAC is not enabled, we must wait LL_DAC_DELAY_STARTUP_VOLTAGE_SETTLING_US*/ LL_DAC_Enable ( DAC1, DAC_Channel ); uint32_t wait_loop_index = ((LL_DAC_DELAY_STARTUP_VOLTAGE_SETTLING_US) * (SystemCoreClock / (1000000UL * 2UL))); while(wait_loop_index != 0UL) { wait_loop_index--; } } } /* * @brief Sets the PWM mode for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_2_RLDetectionModeEnable( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; if ( pHandle->_Super.RLDetectionMode == false ) { /* Channel1 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH1, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH1N ); LL_TIM_OC_SetCompareCH1( TIMx, 0u ); /* Channel2 configuration */ if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_ACTIVE ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_INACTIVE ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else { } /* Channel3 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH3, LL_TIM_OCMODE_PWM2 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3 ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3N ); } pHandle->_Super.pFctGetPhaseCurrents = &R3_2_RLGetPhaseCurrents; pHandle->_Super.pFctTurnOnLowSides = &R3_2_RLTurnOnLowSides; pHandle->_Super.pFctSwitchOnPwm = &R3_2_RLSwitchOnPWM; pHandle->_Super.pFctSwitchOffPwm = &R3_2_SwitchOffPWM; pHandle->_Super.RLDetectionMode = true; } /* * @brief Disables the PWM mode for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_2_RLDetectionModeDisable( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; if ( pHandle->_Super.RLDetectionMode == true ) { /* Channel1 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH1, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1 ); if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH1N ); } else { } LL_TIM_OC_SetCompareCH1( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) >> 1 ); /* Channel2 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2 ); if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2N ); } else { } LL_TIM_OC_SetCompareCH2( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) >> 1 ); /* Channel3 configuration */ LL_TIM_OC_SetMode ( TIMx, LL_TIM_CHANNEL_CH3, LL_TIM_OCMODE_PWM1 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH3 ); if ( ( pHandle->_Super.LowSideOutputs ) == LS_PWM_TIMER ) { LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH3N ); } else if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3N ); } else { } LL_TIM_OC_SetCompareCH3( TIMx, ( uint32_t )( pHandle->Half_PWMPeriod ) >> 1 ); pHandle->_Super.pFctGetPhaseCurrents = &R3_2_GetPhaseCurrents; pHandle->_Super.pFctTurnOnLowSides = &R3_2_TurnOnLowSides; pHandle->_Super.pFctSwitchOnPwm = &R3_2_SwitchOnPWM; pHandle->_Super.pFctSwitchOffPwm = &R3_2_SwitchOffPWM; pHandle->_Super.RLDetectionMode = false; } } /* * @brief Sets the PWM dutycycle for R/L detection. * * @param pHdl: Handler of the current instance of the PWM component. * @param hDuty: Duty cycle to apply, written in uint16_t. * @retval Returns #MC_NO_ERROR if no error occurred or #MC_DURATION if the duty cycles were * set too late for being taken into account in the next PWM cycle. */ uint16_t R3_2_RLDetectionModeSetDuty( PWMC_Handle_t * pHdl, uint16_t hDuty ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; uint32_t val; uint16_t hAux; val = ( ( uint32_t )( pHandle->Half_PWMPeriod ) * ( uint32_t )( hDuty ) ) >> 16; pHandle->_Super.CntPhA = ( uint16_t )( val ); LL_TIM_OC_SetCompareCH1(TIMx, ( uint32_t )pHandle->_Super.CntPhA); /* set the sector that correspond to Phase A and B sampling */ pHdl->Sector = SECTOR_4; /* Limit for update event */ /* Check the status flag. If an update event has occurred before to set new values of regs the FOC rate is too high */ if (((TIMx->CR2) & TIM_CR2_MMS_Msk) != LL_TIM_TRGO_RESET ) { hAux = MC_DURATION; } else { hAux = MC_NO_ERROR; } if ( pHandle->_Super.SWerror == 1u ) { hAux = MC_DURATION; pHandle->_Super.SWerror = 0u; } return hAux; } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__( ( section ( ".ccmram" ) ) ) #endif #endif /* * @brief Computes and stores into @p pHandle latest converted motor phase currents * during RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. * @param pStator_Currents: Pointer to the structure that will receive motor current * of phase A and B in ab_t format. */ static void R3_2_RLGetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; int32_t wAux; /* disable ADC trigger source */ LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET); wAux = (int32_t)( pHandle->PhaseBOffset ) - (int32_t)(pHandle->pParams_str->ADCDataReg2[pHandle->_Super.Sector]->JDR1); /* Check saturation */ if ( wAux > -INT16_MAX ) { if ( wAux < INT16_MAX ) { } else { wAux = INT16_MAX; } } else { wAux = -INT16_MAX; } pStator_Currents->a = (int16_t)wAux; pStator_Currents->b = (int16_t)wAux; } /* * @brief Turns on low sides switches. * * This function is intended to be used for charging boot capacitors * of driving section. It has to be called at each motor start-up when * using high voltage drivers. * This function is specific for RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. * @param ticks: Duty cycle of the boot capacitors charge, specific to motor. */ static void R3_2_RLTurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; /*Turn on the phase A low side switch */ LL_TIM_OC_SetCompareCH1 ( TIMx, 0u ); /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); /* Wait until next update */ while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } return; } /* * @brief Enables PWM generation on the proper Timer peripheral. * * This function is specific for RL detection phase. * * @param pHdl: Handler of the current instance of the PWM component. */ static void R3_2_RLSwitchOnPWM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; ADC_TypeDef * ADCx_1 = pHandle->pParams_str->ADCDataReg1[0]; ADC_TypeDef * ADCx_2 = pHandle->pParams_str->ADCDataReg2[0]; /* wait for a new PWM period */ LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); LL_TIM_OC_SetCompareCH1( TIMx, 1u ); LL_TIM_OC_SetCompareCH4( TIMx, ( pHandle->Half_PWMPeriod ) - 5u ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* enable TIMx update interrupt*/ LL_TIM_EnableIT_UPDATE( TIMx ); /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE ; LL_TIM_EnableAllOutputs( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { if ( ( TIMx->CCER & TIMxCCER_MASK_CH123 ) != 0u ) { LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } else { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } } /* set the sector that correspond to Phase B and C sampling * B will be sampled by ADCx_1 */ pHdl->Sector = SECTOR_4; LL_ADC_INJ_StartConversion( ADCx_1 ); LL_ADC_INJ_StartConversion( ADCx_2 ); return; } /* * @brief Turns on low sides switches and start ADC triggering. * * This function is specific for MP phase. * * @param pHdl: Handler of the current instance of the PWM component. */ void R3_2_RLTurnOnLowSidesAndStart( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ PWMC_R3_2_Handle_t * pHandle = ( PWMC_R3_2_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif /* __ICCARM__ */ TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; LL_TIM_ClearFlag_UPDATE( TIMx ); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Clear Update Flag */ LL_TIM_ClearFlag_UPDATE( TIMx ); LL_TIM_OC_SetCompareCH1( TIMx, 0x0u ); LL_TIM_OC_SetCompareCH2( TIMx, 0x0u ); LL_TIM_OC_SetCompareCH3( TIMx, 0x0u ); LL_TIM_OC_SetCompareCH4( TIMx, ( pHandle->Half_PWMPeriod - 5u)); while ( LL_TIM_IsActiveFlag_UPDATE( TIMx ) == 0 ) {} /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE ; LL_TIM_EnableAllOutputs ( TIMx ); if ( ( pHandle->_Super.LowSideOutputs ) == ES_GPIO ) { /* It is executed during calibration phase the EN signal shall stay off */ LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_u_port, pHandle->_Super.pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_v_port, pHandle->_Super.pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->_Super.pwm_en_w_port, pHandle->_Super.pwm_en_w_pin ); } pHdl->Sector = SECTOR_4; LL_TIM_CC_EnableChannel(TIMx, LL_TIM_CHANNEL_CH4); LL_TIM_EnableIT_UPDATE( TIMx ); return; } /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
49,143
C
32.227857
177
0.632908
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/H7xx/Inc/r1_h7xx_pwm_curr_fdbk.h
/** ****************************************************************************** * @file r1_h7xx_pwm_curr_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * R1_H7XX_pwm_curr_fdbk component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup R1_H7XX_pwm_curr_fdbk */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef R1_F30X_PWMCURRFDBK_H #define R1_F30X_PWMCURRFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "pwm_curr_fdbk.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /* Exported constants --------------------------------------------------------*/ #define GPIO_NoRemap_TIM1 ((uint32_t)(0)) #define SHIFTED_TIMs ((uint8_t) 1) #define NO_SHIFTED_TIMs ((uint8_t) 0) #define NONE ((uint8_t)(0x00)) #define EXT_MODE ((uint8_t)(0x01)) #define INT_MODE ((uint8_t)(0x02)) #define STBD3 0x0002u /*!< Flag to indicate which phase has been distorted in boudary 3 zone (A or B)*/ #define DSTEN 0x0004u /*!< Flag to indicate if the distortion must be performed or not (in case of charge of bootstrap capacitor phase is not required)*/ /* Exported types ------------------------------------------------------------*/ /* * @brief parameters structure of the R1_H7XX_pwm_curr_fdbk Component. * */ typedef struct { /* HW IP involved -----------------------------*/ ADC_TypeDef * ADCx; /* First ADC peripheral to be used.*/ TIM_TypeDef * TIMx; /* timer used for PWM generation.*/ OPAMP_TypeDef * OPAMP_Selection; /* Selected Opamp for 1 shunt configuration */ COMP_TypeDef * CompOCPSelection; /* Internal comparator used for Phases protection.*/ COMP_TypeDef * CompOVPSelection; /* Internal comparator used for Over Voltage protection.*/ GPIO_TypeDef * pwm_en_u_port; /* Channel 1N (low side) GPIO output */ GPIO_TypeDef * pwm_en_v_port; /* Channel 2N (low side) GPIO output*/ GPIO_TypeDef * pwm_en_w_port; /* Channel 3N (low side) GPIO output */ uint16_t pwm_en_u_pin; /*!< Channel 1N (low side) GPIO output pin */ uint16_t pwm_en_v_pin; /*!< Channel 2N (low side) GPIO output pin */ uint16_t pwm_en_w_pin; /*!< Channel 3N (low side) GPIO output pin */ /* PWM generation parameters --------------------------------------------------*/ uint16_t TMin; /* */ uint16_t HTMin; /* */ uint16_t CHTMin; /* */ uint16_t Tbefore; /* It is the sampling time express in number of TIM clocks.*/ uint16_t Tafter; /* It is the sum of dead time plus max value between rise time and noise time express in number of TIM clocks.*/ uint16_t TSample; /* It is the sampling time express in number of TIM clocks.*/ /* DAC settings --------------------------------------------------------------*/ uint16_t DAC_OCP_Threshold; /* Value of analog reference expressed as 16bit unsigned integer. Ex. 0 = 0V ; 65536 = VDD_DAC.*/ uint16_t DAC_OVP_Threshold; /* Value of analog reference expressed as 16bit unsigned integer. Ex. 0 = 0V ; 65536 = VDD_DAC.*/ /* PWM Driving signals initialization ----------------------------------------*/ LowSideOutputsFunction_t LowSideOutputs; /* Low side or enabling signals generation method are defined here.*/ uint8_t IChannel; uint8_t RepetitionCounter; /* It expresses the number of PWM periods to be elapsed before compare registers are updated again. In particular: RepetitionCounter= (2* #PWM periods)-1*/ /* Internal COMP settings ----------------------------------------------------*/ uint8_t CompOCPInvInput_MODE; /*!< COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. */ uint8_t CompOVPInvInput_MODE; /*!< COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. */ /* Dual MC parameters --------------------------------------------------------*/ uint8_t FreqRatio; /* It is used in case of dual MC to synchronize TIM1 and TIM8. It has effect only on the second instanced object and must be equal to the ratio between the two PWM frequencies (higher/lower). Supported values are 1, 2 or 3 */ uint8_t IsHigherFreqTim; /* When bFreqRatio is greather than 1 this param is used to indicate if this instance is the one with the highest frequency. Allowed value are: HIGHER_FREQ or LOWER_FREQ */ } R1_F30XParams_t; /** * @brief Handle structure of the r1_f30x_pwm_curr_fdbk Component */ typedef struct { PWMC_Handle_t _Super; /*!< Offset of current sensing network */ uint16_t DmaBuff[2]; /*!< Buffer used for PWM distortion points*/ uint16_t CntSmp1; /*!< First sampling point express in timer counts*/ uint16_t CntSmp2; /*!< Second sampling point express in timer counts*/ uint8_t sampCur1; /*!< Current sampled in the first sampling point*/ uint8_t sampCur2; /*!< Current sampled in the second sampling point*/ int16_t CurrAOld; /*!< Previous measured value of phase A current*/ int16_t CurrBOld; /*!< Previous measured value of phase B current*/ uint8_t Inverted_pwm_new; /*!< This value indicates the type of the current PWM period (Regular, Distort PHA, PHB or PHC)*/ uint16_t Flags; /*!< Flags STBD3: Flag to indicate which phase has been distorted in boudary 3 zone (A or B) DSTEN: Flag to indicate if the distortion must be performed or not (charge of bootstrap capacitor phase) */ uint16_t RegConv; /*!< Temporary variables used to store regular conversions*/ uint32_t PhaseOffset; /*!< Offset of Phase current sensing network */ volatile uint8_t Index; /*!< Number of conversions performed during the calibration phase*/ uint16_t Half_PWMPeriod; /* Half PWM Period in timer clock counts */ uint32_t ADC_JSQR; /*!< Stores the value for JSQR register to select phase A motor current.*/ uint32_t PreloadDisableActing; /*!< Preload disable to be applied.*/ uint32_t PreloadDisableCC1; /*!< CCMR1 that disables the preload register of the channel to be distorted.*/ uint32_t PreloadDisableCC2; /*!< CCMR1 that disables the preload register of the channel to be distorted.*/ uint32_t PreloadDisableCC3; /*!< CCMR2 that disables the preload register of the channel to be distorted.*/ DMA_Channel_TypeDef * PreloadDMAy_Chx; /*!< DMA resource used for disabling the preload register*/ DMA_Channel_TypeDef * DistortionDMAy_Chx; /*!< DMA resource used for doing the distortion*/ bool UpdateFlagBuffer; /*!< buffered version of Timer update IT flag */ R1_F30XParams_t const * pParams_str; } PWMC_R1_F3_Handle_t; /** @addtogroup R1_H7XX_pwm_curr_fdbk * @{ */ /** * It performs the initialization of the MCU peripherals required for * the PWM generation and current sensing. this initialization is dedicated * to one shunt topology and F3 family */ void R1F30X_Init( PWMC_R1_F3_Handle_t * pHandle ); /** * It disables PWM generation on the proper Timer peripheral acting on * MOE bit */ void R1F30X_SwitchOffPWM( PWMC_Handle_t * pHdl ); /** * It enables PWM generation on the proper Timer peripheral acting on MOE * bit */ void R1F30X_SwitchOnPWM( PWMC_Handle_t * pHdl ); /** * It turns on low sides switches. This function is intended to be * used for charging boot capacitors of driving section. It has to be * called each motor start-up when using high voltage drivers */ void R1F30X_TurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ); /** * It computes and return latest converted motor phase currents motor */ void R1F30X_GetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * pStator_Currents ); /** * It contains the TIMx Update event interrupt */ void * R1F30X_TIMx_UP_IRQHandler( PWMC_R1_F3_Handle_t * pHdl ); /** * It contains the TIMx Break2 event interrupt */ void * R1F30X_BRK2_IRQHandler( PWMC_R1_F3_Handle_t * pHdl ); /** * It contains the TIMx Break1 event interrupt */ void * R1F30X_BRK_IRQHandler( PWMC_R1_F3_Handle_t * pHdl ); /** * It stores into pHandle the offset voltage read onchannels when no * current is flowing into the motor */ void R1F30X_CurrentReadingCalibration( PWMC_Handle_t * pHdl ); /** * Implementation of the single shunt algorithm to setup the * TIM1 register and DMA buffers values for the next PWM period. */ uint16_t R1F30X_CalcDutyCycles( PWMC_Handle_t * pHdl ); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*__R1_F30X_PWMCURRFDBK_H*/ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
11,010
C
41.844358
115
0.531971
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/H7xx/Inc/r3_2_h7xx_pwm_curr_fdbk.h
/** ****************************************************************************** * @file r3_2_h7xx_pwm_curr_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * r3_2_h7xx_pwm_curr_fdbk component of the Motor Control SDK. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** * @ingroup R3_2_H7XX_pwm_curr_fdbk */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef R3_2_H7XX_PWMNCURRFDBK_H #define R3_2_H7XX_PWMNCURRFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "pwm_curr_fdbk.h" /* Exported defines --------------------------------------------------------*/ #define NONE ((uint8_t)(0x00)) #define EXT_MODE ((uint8_t)(0x01)) #define INT_MODE ((uint8_t)(0x02)) /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup R3_2_pwm_curr_fdbk * @{ */ /* Exported types ------------------------------------------------------- */ /* * @brief R3_2_H7XX_pwm_curr_fdbk component OPAMP parameters structure definition. */ typedef struct { /* First OPAMP settings ------------------------------------------------------*/ OPAMP_TypeDef *OPAMPSelect_1 [6] ; /*!< Define for each sector first conversion which OPAMP is involved - Null otherwise */ OPAMP_TypeDef *OPAMPSelect_2 [6] ; /*!< Define for each sector second conversion which OPAMP is involved - Null otherwise */ uint32_t OPAMPConfig1 [6]; /* Defines the OPAMP_CSR_VPSEL config for each ADC conversions*/ uint32_t OPAMPConfig2 [6]; /* Defines the OPAMP_CSR_VPSEL config for each ADC conversions*/ } R3_2_OPAMPParams_t; /* * @brief R3_4_h7XX_pwm_curr_fdbk component parameters structure definition. */ typedef struct { /* HW IP involved -----------------------------*/ TIM_TypeDef * TIMx; /* Timer used for PWM generation.*/ R3_2_OPAMPParams_t * OPAMPParams; /* Pointer to the OPAMP params struct. It must be #MC_NULL if internal OPAMP are not used.*/ COMP_TypeDef * CompOCPASelection; /* Internal comparator used for Phase A protection.*/ COMP_TypeDef * CompOCPBSelection; /* Internal comparator used for Phase B protection.*/ COMP_TypeDef * CompOCPCSelection; /* Internal comparator used for Phase C protection.*/ COMP_TypeDef * CompOVPSelection; /* Internal comparator used for Over Voltage protection.*/ ADC_TypeDef * ADCDataReg1[6]; /* Contains the Address of ADC read value for one phase and all the 6 sectors. */ ADC_TypeDef * ADCDataReg2[6]; /* Contains the Address of ADC read value for one phase and all the 6 sectors. */ uint32_t ADCConfig1 [6] ; /* Values of JSQR for first ADC for 6 sectors. */ uint32_t ADCConfig2 [6] ; /* Values of JSQR for second ADC for 6 sectors. */ /* PWM generation parameters --------------------------------------------------*/ uint16_t Tafter; /* Sum of dead time plus max value between rise time and noise time expressed in number of TIM clocks.*/ uint16_t Tbefore; /* Sampling time expressed in number of TIM clocks.*/ /* DAC settings --------------------------------------------------------------*/ uint16_t DAC_OCP_Threshold; /* Value of analog reference expressed as 16bit unsigned integer. Ex. 0 = 0V ; 65536 = VDD_DAC.*/ uint16_t DAC_OVP_Threshold; /* Value of analog reference expressed as 16bit unsigned integer. Ex. 0 = 0V ; 65536 = VDD_DAC.*/ /* PWM Driving signals initialization ----------------------------------------*/ uint8_t RepetitionCounter; /*!< Expresses the number of PWM periods to be elapsed before compare registers are updated again. In particular: @f$ RepetitionCounter\ =\ (2\times PWM\ Periods)\ -\ 1 @f$ */ /* Internal COMP settings ----------------------------------------------------*/ uint8_t CompOCPAInvInput_MODE; /* COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. */ uint8_t CompOCPBInvInput_MODE; /* COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. */ uint8_t CompOCPCInvInput_MODE; /* COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. */ uint8_t CompOVPInvInput_MODE; /* COMPx inverting input mode. It must be either equal to EXT_MODE or INT_MODE. */ /* Dual MC parameters --------------------------------------------------------*/ uint8_t FreqRatio; /* Used in case of dual MC to synchronize TIM1 and TIM8. It has effect only on the second instanced object and must be equal to the ratio between the two PWM frequencies (higher/lower). Supported values are 1, 2 or 3 */ uint8_t IsHigherFreqTim; /* When bFreqRatio is greater than 1 this param is used to indicate if this instance is the one with the highest frequency. Allowed values are: HIGHER_FREQ or LOWER_FREQ */ } R3_2_Params_t; /* * @brief Handles an instance of the R3_2_H7XX_pwm_curr_fdbk component. */ typedef struct { PWMC_Handle_t _Super; /* Base component handler. */ uint32_t PhaseAOffset; /* Offset of Phase A current sensing network. */ uint32_t PhaseBOffset; /* Offset of Phase B current sensing network. */ uint32_t PhaseCOffset; /* Offset of Phase C current sensing network. */ uint16_t Half_PWMPeriod; /* Half PWM Period in timer clock counts. */ uint16_t ADC_ExternalTriggerInjected; /* External trigger selection for ADC peripheral.*/ uint16_t ADC_ExternalPolarityInjected; volatile uint8_t PolarizationCounter; /* Number of conversions performed during the calibration phase. */ uint8_t PolarizationSector; /* Sector selected during calibration phase. */ R3_2_Params_t const * pParams_str; } PWMC_R3_2_Handle_t; /* Exported functions ------------------------------------------------------- */ /* * Initializes TIMx, ADC, GPIO, DMA1 and NVIC for current reading * in three shunt topology using STM32H7XX and two ADCs. */ void R3_2_Init( PWMC_R3_2_Handle_t * pHandle ); /* * Stores into the handler the voltage present on Ia and Ib current * feedback analog channels when no current is flowing into the motor. */ void R3_2_CurrentReadingPolarization( PWMC_Handle_t * pHdl ); /* * Computes and stores in the handler the latest converted motor phase currents in ab_t format. */ void R3_2_GetPhaseCurrents( PWMC_Handle_t * pHdl, ab_t * Iab ); /* * Turns on low sides switches. */ void R3_2_TurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks ); /* * Enables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_2_SwitchOnPWM( PWMC_Handle_t * pHdl ); /* * Disables PWM generation on the proper Timer peripheral acting on MOE bit. */ void R3_2_SwitchOffPWM( PWMC_Handle_t * pHdl ); /* * Configures the ADC for the current sampling related to sector X (X = [1..6] ). */ uint16_t R3_2_SetADCSampPointSectX( PWMC_Handle_t * pHdl ); /* * Contains the TIMx Update event interrupt. */ void * R3_2_TIMx_UP_IRQHandler( PWMC_R3_2_Handle_t * pHdl ); /* * Sets the PWM mode for R/L detection. */ void R3_2_RLDetectionModeEnable( PWMC_Handle_t * pHdl ); /* * Disables the PWM mode for R/L detection. */ void R3_2_RLDetectionModeDisable( PWMC_Handle_t * pHdl ); /* * Sets the PWM dutycycle for R/L detection. */ uint16_t R3_2_RLDetectionModeSetDuty( PWMC_Handle_t * pHdl, uint16_t hDuty ); /* * Turns on low sides switches and start ADC triggering. */ void R3_2_RLTurnOnLowSidesAndStart( PWMC_Handle_t * pHdl ); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*R3_2_H7XX_PWMNCURRFDBK_H*/ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
9,890
C
40.911017
127
0.517594
Tbarkin121/GuardDog/stm32/MotorDrive/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLibACIM/Any/Src/acim_lso_foc.c
/** ****************************************************************************** * @file acim_lso_foc.c * @author STMicroelectronics - System Lab - MC Team * @brief This file provides firmware functions that implement the features * of the Rotor Flux Position Feedback component of the Motor Control SDK. * - estimates the rotor flux electrical angle and mechanical rotor speed ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2023 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "acim_lso_foc.h" #include "math.h" /* Variables ---------------------------------------------------------*/ /* Function prototypes -----------------------------------------------*/ bool ACIM_LSO_IsNotValidNumber(float fVar); /* * @brief It initializes the handle * @param pHandle: handler of the * @param * @retval none. */ void ACIM_LSO_Init(ACIM_LSO_Handle_t *pHandle, BusVoltageSensor_Handle_t *pBVS) { pHandle->pBVS = pBVS; PI_Float_HandleInit(pHandle->fPI); } #if (defined (CCMRAM) || defined(CCMRAM_ENABLED)) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) __attribute__((section ("ccmram"))) #elif defined (__GNUC__) __attribute__((section ("ccmram"))) #endif #endif /** * @brief * * @param * @param * * @retval */ void ACIM_LSO_CalcAngle(ACIM_LSO_Handle_t *pHandle) { float fSlipFreq_rads = 0.0f; float fRotorFluxFreq_rads = 0.0f; float fRotorElSpeed_obs_rads = 0.0f; Signal_Components fIqds_obs_A; Signal_Components fFlux_qdr_obs; Signal_Components fVqds_meas_V; float fSpeedEstError = 0.0f; /*Local variables */ float k = pHandle->k; float k1; float k2; float k3; float k4; /* Motor params */ float fsigma = pHandle->pACIM_MotorParams->fsigma; float ftaur = pHandle->pACIM_MotorParams->ftaur; float ftaus = pHandle->pACIM_MotorParams->ftaus; float fLs = pHandle->pACIM_MotorParams->fLs; float fPP = pHandle->pACIM_MotorParams->bPP; /* Previous values for estimated quantities */ fRotorFluxFreq_rads = pHandle->fRotorFluxFreq_rads; fRotorElSpeed_obs_rads = pHandle->fRotorElSpeed_obs_rads; fIqds_obs_A = pHandle->fIqds_obs_A; fFlux_qdr_obs = pHandle->fFlux_qdr_obs; fVqds_meas_V = Convert_s16_to_V(pHandle->pBVS, pHandle->pFOCVars->Vqd); Signal_Components Iqdmeas_A = Convert_s16_to_A(pHandle->pFOCVars[M1].Iqd); float ids_obs_A = fIqds_obs_A.fS_Component2; float divftaur = 1/ftaur; float divftaus = 1/ftaus; float divfsigma = 1/fsigma; float fsigmadiff = 1-fsigma; /* Online computation of Observer parameters */ k1 = -((k-1)/fsigma)*(divftaur + divftaus); k2 = (k-1)*fRotorElSpeed_obs_rads; k3 = ((k-1)/(1-fsigma))*(divftaur - k*divftaus); k4 = ((k-1)*fRotorElSpeed_obs_rads*fsigma)/(1-fsigma); /* STEP 1 - Computing of prediction errors --------------------------------------------------------- */ /* Iq error(k) */ pHandle->fIqds_error_A.fS_Component1 = Iqdmeas_A.fS_Component1 - fIqds_obs_A.fS_Component1; /* Id error(k) */ pHandle->fIqds_error_A.fS_Component2 = Iqdmeas_A.fS_Component2 - fIqds_obs_A.fS_Component2; /* STEP 2 - Computing of mech. rotor speed estimation --------------------------------------------- */ /* SpeedEstError = -(Iq_error * Flux_dr) */ fSpeedEstError = -(pHandle->fIqds_error_A.fS_Component1 * pHandle->fFlux_qdr_obs.fS_Component2); pHandle->fRotorElSpeed_obs_rads = PI_Float_Calc(pHandle->fPI, fSpeedEstError); pHandle->_SpeedEstimator.hAvrMecSpeedUnit = (int16_t)((pHandle->fRotorElSpeed_obs_rads*10.0f)/(2.0f*(float)PI* fPP)); pHandle->fRotorSpeed_RPM = (float)pHandle->_SpeedEstimator.hAvrMecSpeedUnit*6.0f; /* STEP 3 - Computing of rotor frequency */ float fFlux_dr_tmp = pHandle->fFlux_qdr_obs.fS_Component2; if(fFlux_dr_tmp==0.0f) { fFlux_dr_tmp = pHandle->pACIM_MotorParams->fImagn_A; } if(ids_obs_A==0.0f) { ids_obs_A = pHandle->pACIM_MotorParams->fImagn_A; } /* Slip frequency estimation */ fSlipFreq_rads = fIqds_obs_A.fS_Component1/(fFlux_dr_tmp * ftaur); /* Rotor Flux frequency computation */ fRotorFluxFreq_rads = fSlipFreq_rads + pHandle->fRotorElSpeed_obs_rads; pHandle->fRotorFluxFreq_rads = fRotorFluxFreq_rads; /* STEP 4 - Computing and output of field angle */ pHandle->fRotorFlux_Angle_rad += fRotorFluxFreq_rads*pHandle->fCalcAngleExecTime_s; /* Observed Rotor Flux angle between 0 and 2pi */ pHandle->fRotorFlux_Angle_rad = (float) fmod((double)pHandle->fRotorFlux_Angle_rad , (double) (2.0f*(float)PI)); /* STEP 5 and 6 - Prediction of currents and flux */ fIqds_obs_A.fS_Component1 += ((-fRotorFluxFreq_rads* pHandle->fIqds_obs_A.fS_Component2) + (((-divfsigma)*(divftaus +(fsigmadiff)*divftaur))*pHandle->fIqds_obs_A.fS_Component1) -((fsigmadiff)*divfsigma*fRotorElSpeed_obs_rads)*pHandle->fFlux_qdr_obs.fS_Component2 +fVqds_meas_V.fS_Component1/(fsigma* fLs) +k2*((pHandle->fIqds_error_A.fS_Component2)) + k1*((pHandle->fIqds_error_A.fS_Component1)))*pHandle->fCalcAngleExecTime_s; fIqds_obs_A.fS_Component2 += ((-divfsigma*(divftaus +(fsigmadiff*divftaur))*(pHandle->fIqds_obs_A.fS_Component2))+ fRotorFluxFreq_rads*pHandle->fIqds_obs_A.fS_Component1 +((fsigmadiff)/(fsigma*ftaur))*(pHandle->fFlux_qdr_obs.fS_Component2) +fVqds_meas_V.fS_Component2/(fsigma* fLs) +k1*(pHandle->fIqds_error_A.fS_Component2) - k2*(pHandle->fIqds_error_A.fS_Component1))*pHandle->fCalcAngleExecTime_s; fFlux_qdr_obs.fS_Component2 += ((ids_obs_A*divftaur) -(pHandle->fFlux_qdr_obs.fS_Component2*divftaur) +k3*pHandle->fIqds_error_A.fS_Component2 - k4*pHandle->fIqds_error_A.fS_Component1)*pHandle->fCalcAngleExecTime_s; pHandle->fIqds_obs_A = fIqds_obs_A; pHandle->fFlux_qdr_obs.fS_Component2 = fFlux_qdr_obs.fS_Component2; pHandle->hElAngle = Convert_Rad_to16bit(pHandle->fRotorFlux_Angle_rad); } #if (defined (CCMRAM) || defined(CCMRAM_ENABLED)) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) __attribute__((section ("ccmram"))) #elif defined (__GNUC__) __attribute__((section ("ccmram"))) #endif #endif int16_t ACIM_LSO_GetElAngle(ACIM_LSO_Handle_t *pHandle) { return pHandle->hElAngle; } void ACIM_LSO_Clear(ACIM_LSO_Handle_t *pHandle) { Signal_Components fnull = {0.0f,0.0f}; pHandle->fFlux_qdr_obs = fnull; pHandle->fIqds_error_A = fnull; pHandle->fIqds_obs_A = fnull; PI_Float_HandleInit(pHandle->fPI); pHandle->fRotorElSpeed_obs_rads = 0.0f; pHandle->fRotorFluxFreq_rads = 0.0f; pHandle->fRotorFlux_Angle_rad = 0.0f; pHandle->hElAngle = 0.0f; pHandle->fRotorSpeed_RPM = 0.0f; pHandle->_SpeedEstimator.hAvrMecSpeedUnit = 0; pHandle->fdbg_Vampl = 0.0f; pHandle->fdbg_ElAngle_rad = 0.0f; pHandle->fdbg_Frequency_rads = 0.0f; pHandle->hdbg_ElAngle = 0.0f; } #if (defined (CCMRAM) || defined(CCMRAM_ENABLED)) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) __attribute__((section ("ccmram"))) #elif defined (__GNUC__) __attribute__((section ("ccmram"))) #endif #endif /* It returns true if LSO variables are valid numerical values It return false as soon as one of the LSO variables becomes Nan or INF */ bool ACIM_LSO_CheckIntegrity(ACIM_LSO_Handle_t *pHandle) { bool bRetVal = true; if( ACIM_LSO_IsNotValidNumber(pHandle->fFlux_qdr_obs.fS_Component1)|| ACIM_LSO_IsNotValidNumber(pHandle->fFlux_qdr_obs.fS_Component2)|| ACIM_LSO_IsNotValidNumber(pHandle->fIqds_obs_A.fS_Component1)|| ACIM_LSO_IsNotValidNumber(pHandle->fIqds_obs_A.fS_Component2)|| ACIM_LSO_IsNotValidNumber(pHandle->fRotorElSpeed_obs_rads)|| ACIM_LSO_IsNotValidNumber(pHandle->fRotorFluxFreq_rads)|| ACIM_LSO_IsNotValidNumber(pHandle->fRotorFlux_Angle_rad)|| ACIM_LSO_IsNotValidNumber(pHandle->fRotorSpeed_RPM)|| (pHandle->fRotorElSpeed_obs_rads >= pHandle->fMaxObsRotorSpeed_RPM)|| (pHandle->fRotorElSpeed_obs_rads <= -pHandle->fMaxObsRotorSpeed_RPM) ) { bRetVal = false; } return bRetVal; } bool ACIM_LSO_IsNotValidNumber(float fVar) { bool bRetVar = false; if(isnan(fVar)||isnan(fVar)) { bRetVar = true; } return bRetVar; } #if (defined (CCMRAM) || defined(CCMRAM_ENABLED)) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) __attribute__((section ("ccmram"))) #elif defined (__GNUC__) __attribute__((section ("ccmram"))) #endif #endif void ACIM_DBG_LSO_CalcAngle(ACIM_LSO_Handle_t *pHandle, float fFrequency_Hz) { pHandle->fdbg_Frequency_rads = fFrequency_Hz*2.0f*PI; /* Discrete Integration */ pHandle->fdbg_ElAngle_rad += (pHandle->fdbg_Frequency_rads * pHandle->fCalcAngleExecTime_s); pHandle->fdbg_ElAngle_rad = (float) fmod((double)pHandle->fdbg_ElAngle_rad , (double) (2.0f*(float)PI)); pHandle->hdbg_ElAngle = Convert_Rad_to16bit(pHandle->fdbg_ElAngle_rad); } #if (defined (CCMRAM) || defined(CCMRAM_ENABLED)) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) __attribute__((section ("ccmram"))) #elif defined (__GNUC__) __attribute__((section ("ccmram"))) #endif #endif int16_t ACIM_DBG_LSO_GetdbgElAngle(ACIM_LSO_Handle_t *pHandle) { return (pHandle->hdbg_ElAngle); } #if (defined (CCMRAM) || defined(CCMRAM_ENABLED)) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) __attribute__((section ("ccmram"))) #elif defined (__GNUC__) __attribute__((section ("ccmram"))) #endif #endif qd_t ACIM_DBG_LSO_CalcVoltage(ACIM_LSO_Handle_t *pHandle) { qd_t Vqd = {0,0}; float fFreq_rads_abs=0; fFreq_rads_abs = pHandle->fdbg_Frequency_rads; if(fFreq_rads_abs <0.0f) { fFreq_rads_abs = -fFreq_rads_abs; } if(fFreq_rads_abs < pHandle->fdbg_MinFreqTH_rads) { pHandle->fdbg_Vampl = pHandle->fdbg_VoltageOffset_V; } else { pHandle->fdbg_Vampl = (fFreq_rads_abs * pHandle->fdbg_Flux_K); } Signal_Components fVqd_V = {pHandle->fdbg_Vampl, 0.0f}; Vqd = Convert_V_to_s16(pHandle->pBVS, fVqd_V); return Vqd; } /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
11,120
C
29.385246
208
0.621223